From 35cc13e229ddc4953a1e68b6b7ea18c54eb9a70b Mon Sep 17 00:00:00 2001 From: Sebastian Date: Fri, 19 May 2023 13:24:30 -0300 Subject: imported useNotifications, new memory storage hook and fixed but in localstorage --- packages/web-util/src/hooks/useNotifications.ts | 67 +++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 packages/web-util/src/hooks/useNotifications.ts (limited to 'packages/web-util/src/hooks/useNotifications.ts') 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(); +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); + }, + }; + }); +} -- cgit v1.2.3