From 5ea22a325c069fe497b2dc8a73d4de69fd8cc27b Mon Sep 17 00:00:00 2001 From: Sebastian Date: Fri, 14 Apr 2023 14:07:15 -0300 Subject: using new localStorage api, pageState => settings, notifcation using observer api --- packages/demobank-ui/src/hooks/notification.ts | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 packages/demobank-ui/src/hooks/notification.ts (limited to 'packages/demobank-ui/src/hooks/notification.ts') diff --git a/packages/demobank-ui/src/hooks/notification.ts b/packages/demobank-ui/src/hooks/notification.ts new file mode 100644 index 000000000..7cdece515 --- /dev/null +++ b/packages/demobank-ui/src/hooks/notification.ts @@ -0,0 +1,54 @@ +import { TranslatedString } from "@gnu-taler/taler-util"; +import { memoryMap } from "@gnu-taler/web-util/lib/index.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]; +} -- cgit v1.2.3