import { TranslatedString } from "@gnu-taler/taler-util"; import { memoryMap } from "@gnu-taler/web-util/browser"; import { StateUpdater, useEffect, useState } from "preact/hooks"; export type NotificationMessage = ErrorNotification | InfoNotification; //FIXME: this should not be exported since every notification // goes throw notify function export interface ErrorMessage { description?: string; title: TranslatedString; debug?: string; } interface ErrorNotification { type: "error"; error: ErrorMessage; } interface InfoNotification { type: "info"; info: TranslatedString; } const storage = memoryMap(); const NOTIFICATION_KEY = "notification"; export function onNotificationUpdate( handler: (newValue: NotificationMessage | undefined) => void, ) { return storage.onUpdate(NOTIFICATION_KEY, () => { const newValue = storage.get(NOTIFICATION_KEY); handler(newValue); }); } export function notifyError(error: ErrorMessage) { storage.set(NOTIFICATION_KEY, { type: "error", error }); } export function notifyInfo(info: TranslatedString) { storage.set(NOTIFICATION_KEY, { type: "info", info }); } export function useNotifications(): [ NotificationMessage | undefined, StateUpdater, ] { const [value, setter] = useState(); useEffect(() => { return storage.onUpdate(NOTIFICATION_KEY, () => { setter(storage.get(NOTIFICATION_KEY)); }); }); return [value, setter]; }