storebound/apps/desktop/src/card/card-api.ts

25 lines
1.4 KiB
TypeScript

// The tray card's host calls (the card page's counterpart of src/api.ts, kept apart so the card bundle stays small).
// Main window: card_snapshot + the `card-request` event. Card window: card_get, card_action and its two events.
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type { CardSnapshot } from './model';
export type CardAction = 'hide' | 'open' | 'route' | 'refresh' | 'mute' | 'quit' | 'external' | 'ready' | 'size';
export const inTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
function sub<T>(ev: string, fn: (p: T) => void): () => void {
const un = listen<T>(ev, e => fn(e.payload));
return () => { un.then(f => f()).catch(() => {}); };
}
export const cardApi = {
/** Main window: hands the host the card's snapshot (the host forwards it as `card-snapshot`). */
push: (snapshot: CardSnapshot) => invoke<void>('card_snapshot', { snapshot }),
/** Main window: the card opened; refresh what is kept per app. */
onRequest: (fn: () => void) => sub<null>('card-request', () => fn()),
get: () => invoke<CardSnapshot | null>('card_get'),
onSnapshot: (fn: (s: CardSnapshot) => void) => sub<CardSnapshot>('card-snapshot', fn),
onShown: (fn: () => void) => sub<null>('card-shown', () => fn()),
action: (action: CardAction, arg?: string) => { invoke('card_action', { action, arg: arg ?? null }).catch(() => {}); },
};