diff options
Diffstat (limited to 'packages/web-util/src/hooks/useNotifications.ts')
-rw-r--r-- | packages/web-util/src/hooks/useNotifications.ts | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/packages/web-util/src/hooks/useNotifications.ts b/packages/web-util/src/hooks/useNotifications.ts new file mode 100644 index 000000000..deaa7a7c1 --- /dev/null +++ b/packages/web-util/src/hooks/useNotifications.ts @@ -0,0 +1,67 @@ +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<NotificationMessage[]>(); +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<NotificationMessage[]>([]); + 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); + }, + }; + }); +} |