import { TranslatedString } from "@gnu-taler/taler-util"; import { StateUpdater, useEffect, useState } from "preact/hooks"; import { memoryMap } from "../index.browser.js"; export type NotificationMessage = ErrorNotification | InfoNotification; interface ErrorNotification { type: "error"; title: TranslatedString; description?: TranslatedString; debug?: string; } interface InfoNotification { type: "info"; title: TranslatedString; } const storage = memoryMap(); const NOTIFICATION_KEY = "notification"; export function notifyError( title: TranslatedString, description: TranslatedString | undefined, debug?: any, ) { const currentState: NotificationMessage[] = storage.get(NOTIFICATION_KEY) ?? []; const newState = currentState.concat({ type: "error", title, description, debug, }); storage.set(NOTIFICATION_KEY, newState); } export function notifyInfo(title: TranslatedString) { const currentState: NotificationMessage[] = storage.get(NOTIFICATION_KEY) ?? []; const newState = currentState.concat({ type: "info", title }); storage.set(NOTIFICATION_KEY, newState); } type Notification = { message: NotificationMessage; remove: () => void; }; export function useNotifications(): Notification[] { const [value, setter] = useState([]); useEffect(() => { return storage.onUpdate(NOTIFICATION_KEY, () => { const mem = storage.get(NOTIFICATION_KEY) ?? []; setter(mem); }); }); return value.map((message, idx) => { return { message, remove: () => { const mem = storage.get(NOTIFICATION_KEY) ?? []; const newState = Array.from(mem); newState.splice(idx, 1); storage.set(NOTIFICATION_KEY, newState); }, }; }); }