aboutsummaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/hooks/notification.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/demobank-ui/src/hooks/notification.ts')
-rw-r--r--packages/demobank-ui/src/hooks/notification.ts54
1 files changed, 54 insertions, 0 deletions
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<NotificationMessage>();
+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<NotificationMessage | undefined>,
+] {
+ const [value, setter] = useState<NotificationMessage | undefined>();
+ useEffect(() => {
+ return storage.onUpdate(NOTIFICATION_KEY, () => {
+ setter(storage.get(NOTIFICATION_KEY));
+ });
+ });
+ return [value, setter];
+}