summaryrefslogtreecommitdiff
path: root/packages/web-util/src/hooks/useNotifications.ts
blob: ca67c5b9ba2e5a5883401ef2f525d6266dace18d (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { TalerError, TalerErrorCode, TranslatedString } from "@gnu-taler/taler-util";
import { useEffect, useState } from "preact/hooks";
import { memoryMap, useTranslationContext } from "../index.browser.js";

export type NotificationMessage = ErrorNotification | InfoNotification;

export interface ErrorNotification {
  type: "error";
  title: TranslatedString;
  description?: TranslatedString;
  debug?: any;
}
export interface InfoNotification {
  type: "info";
  title: TranslatedString;
}

const storage = memoryMap<Map<string, NotificationMessage>>();
const NOTIFICATION_KEY = "notification";

export function notify(notif: NotificationMessage): void {
  const currentState: Map<string, NotificationMessage> =
    storage.get(NOTIFICATION_KEY) ?? new Map();
  const newState = currentState.set(hash(notif), notif);
  storage.set(NOTIFICATION_KEY, newState);
}
export function notifyError(
  title: TranslatedString,
  description: TranslatedString | undefined,
  debug?: any,
) {
  notify({
    type: "error" as const,
    title,
    description,
    debug,
  });
}
export function notifyException(
  title: TranslatedString,
  ex: Error,
) {
  notify({
    type: "error" as const,
    title,
    description: ex.message as TranslatedString,
    debug: ex.stack,
  });
}
export function notifyInfo(title: TranslatedString) {
  notify({
    type: "info" as const,
    title,
  });
}

export type Notification = {
  message: NotificationMessage;
  remove: () => void;
};

export function useNotifications(): Notification[] {
  const [value, setter] = useState<Map<string, NotificationMessage>>(new Map());
  useEffect(() => {
    return storage.onUpdate(NOTIFICATION_KEY, () => {
      const mem = storage.get(NOTIFICATION_KEY) ?? new Map();
      setter(structuredClone(mem));
    });
  });

  return Array.from(value.values()).map((message, idx) => {
    return {
      message,
      remove: () => {
        const mem = storage.get(NOTIFICATION_KEY) ?? new Map();
        const newState = new Map(mem);
        newState.delete(hash(message));
        storage.set(NOTIFICATION_KEY, newState);
      },
    };
  });
}

function hashCode(str: string): string {
  if (str.length === 0) return "0";
  let hash = 0;
  let chr;
  for (let i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash.toString(16);
}

function hash(msg: NotificationMessage): string {
  let str = (msg.type + ":" + msg.title) as string;
  if (msg.type === "error") {
    if (msg.description) {
      str += ":" + msg.description;
    }
    if (msg.debug) {
      str += ":" + msg.debug;
    }
  }
  return hashCode(str);
}

export function useLocalNotification(): [Notification | undefined, (n: NotificationMessage) => void, (cb: () => Promise<void>) => Promise<void>] {
  const {i18n} = useTranslationContext();

  const [value, setter] = useState<NotificationMessage>();
  const notif = !value ? undefined : {
    message: value,
    remove: () => {
      setter(undefined);
    },
  }

  async function errorHandling(cb: () => Promise<void>) {
    try {
      return await cb()
    } catch (error: unknown) {
      if (error instanceof TalerError) {
        notify(buildRequestErrorMessage(i18n, error))
      } else {
        notifyError(
          i18n.str`Operation failed, please report`,
          (error instanceof Error
            ? error.message
            : JSON.stringify(error)) as TranslatedString
        )
      }

    }
  }
  return [notif, setter, errorHandling]
}

type Translator = ReturnType<typeof useTranslationContext>["i18n"]

function buildRequestErrorMessage( i18n: Translator, cause: TalerError): ErrorNotification {
  let result: ErrorNotification;
  switch (cause.errorDetail.code) {
    case TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT: {
      result = {
        type: "error",
        title: i18n.str`Request timeout`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
    case TalerErrorCode.WALLET_HTTP_REQUEST_THROTTLED: {
      result = {
        type: "error",
        title: i18n.str`Request throttled`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
    case TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE: {
      result = {
        type: "error",
        title: i18n.str`Malformed response`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
    case TalerErrorCode.WALLET_NETWORK_ERROR: {
      result = {
        type: "error",
        title: i18n.str`Network error`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
    case TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR: {
      result = {
        type: "error",
        title: i18n.str`Unexpected request error`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
    default: {
      result = {
        type: "error",
        title: i18n.str`Unexpected error`,
        description: cause.message as TranslatedString,
        debug: JSON.stringify(cause.errorDetail, undefined, 2),
      };
      break;
    }
  }
  return result;
}