aboutsummaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/hooks/notification.ts
blob: 9bf621b41f75dae8d6afcb7cdf43300506ffad1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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<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];
}