Skip to content

Commit

Permalink
Wire up Tauri error listener in root layout
Browse files Browse the repository at this point in the history
  • Loading branch information
maiertech committed Aug 20, 2024
1 parent e86c94e commit c38a7ed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
24 changes: 6 additions & 18 deletions unime/src/lib/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,6 @@ import { writable } from 'svelte/store';

// TODO: run some copy task instead of importing across root to make the frontend independent
import type { AppState } from '@bindings/AppState';
import { listen } from '@tauri-apps/api/event';
import { error as err } from '@tauri-apps/plugin-log';

interface ErrorEvent {
event: string;
payload: string;
id: number;
}

interface OnboardingState {
name?: string;
Expand Down Expand Up @@ -48,22 +40,18 @@ const empty_state: AppState = {
};

/**
* A store that listens for updates to the application state emitted by the Rust backend.
* If the frontend intends to change the state, it must dispatch an action to the backend.
* This store contains the frontend state.
* It may be altered only by the `state-changed` Tauri listener.
* The frontend must dispatch an action to the backend to change state.
*/
// TODO: make read-only
export const state = writable<AppState>(empty_state);

/**
* A store that listens for errors emitted by the Rust backend.
* This store contains errors to be displayed by an error toast.
* It may be altered only by the `error` Tauri listener.
*/
export const error = writable<string | undefined>(undefined, (set) => {
listen('error', (event: ErrorEvent) => {
err(`Error: ${event.payload}`);
set(event.payload);
});
// TODO: unsubscribe from listener!
});
export const error = writable<string | undefined>(undefined);

/**
* This store is only used by the frontend for storing state during onboarding.
Expand Down
7 changes: 7 additions & 0 deletions unime/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,19 @@
import '../app.css';
let detachConsole: UnlistenFn;
let unlistenError: UnlistenFn;
let unlistenStateChanged: UnlistenFn;
onMount(async () => {
detachConsole = await attachConsole();
loadAllLocales(); //TODO: performance: only load locale on user request
unlistenError = await listen('error', (event) => {
error(`Error: ${event.payload}`);
errorState.set(event.payload as string);
});
unlistenStateChanged = await listen('state-changed', (event) => {
// Set frontend state to state received from backend.
appState.set(event.payload as AppState);
Expand Down Expand Up @@ -73,6 +79,7 @@
onDestroy(() => {
// Destroy in reverse order.
unlistenStateChanged();
unlistenError();
detachConsole();
});
Expand Down

0 comments on commit c38a7ed

Please sign in to comment.