summaryrefslogtreecommitdiff
path: root/packages/web-util/src/utils/observable.ts
blob: 16a33ae7264be1ca2c65be34176d443e8b6fdde0 (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import { isArrayBufferView } from "util/types";

export type ObservableMap<K, V> = Map<K, V> & {
  onAnyUpdate: (callback: () => void) => () => void;
  onUpdate: (key: string, callback: () => void) => () => void;
};

//FIXME: allow different type for different properties
export function memoryMap<T>(
  backend: Map<string, T> = new Map<string, T>(),
): ObservableMap<string, T> {
  const obs = new EventTarget();
  const theMemoryMap: ObservableMap<string, T> = {
    onAnyUpdate: (handler) => {
      obs.addEventListener(`update`, handler);
      obs.addEventListener(`clear`, handler);
      return () => {
        obs.removeEventListener(`update`, handler);
        obs.removeEventListener(`clear`, handler);
      };
    },
    onUpdate: (key, handler) => {
      obs.addEventListener(`update-${key}`, handler);
      obs.addEventListener(`clear`, handler);
      return () => {
        obs.removeEventListener(`update-${key}`, handler);
        obs.removeEventListener(`clear`, handler);
      };
    },
    delete: (key: string) => {
      const result = backend.delete(key);
      //@ts-ignore
      theMemoryMap.size = backend.length;
      obs.dispatchEvent(new Event(`update-${key}`));
      obs.dispatchEvent(new Event(`update`));
      return result;
    },
    set: (key: string, value: T) => {
      backend.set(key, value);
      //@ts-ignore
      theMemoryMap.size = backend.length;
      obs.dispatchEvent(new Event(`update-${key}`));
      obs.dispatchEvent(new Event(`update`));
      return theMemoryMap;
    },
    clear: () => {
      backend.clear();
      obs.dispatchEvent(new Event(`clear`));
    },
    entries: backend.entries.bind(backend),
    forEach: backend.forEach.bind(backend),
    get: backend.get.bind(backend),
    has: backend.has.bind(backend),
    keys: backend.keys.bind(backend),
    size: backend.size,
    values: backend.values.bind(backend),
    [Symbol.iterator]: backend[Symbol.iterator],
    [Symbol.toStringTag]: "theMemoryMap",
  };
  return theMemoryMap;
}

//FIXME: change this implementation to match the
// browser storage. instead of creating a sync implementation
// of observable map it should reuse the memoryMap and
// sync the state with local storage
export function localStorageMap(): ObservableMap<string, string> {
  const obs = new EventTarget();
  const theLocalStorageMap: ObservableMap<string, string> = {
    onAnyUpdate: (handler) => {
      obs.addEventListener(`update`, handler);
      obs.addEventListener(`clear`, handler);
      window.addEventListener("storage", handler);
      return () => {
        window.removeEventListener("storage", handler);
        obs.removeEventListener(`update`, handler);
        obs.removeEventListener(`clear`, handler);
      };
    },
    onUpdate: (key, handler) => {
      obs.addEventListener(`update-${key}`, handler);
      obs.addEventListener(`clear`, handler);
      function handleStorageEvent(ev: StorageEvent) {
        if (ev.key === null || ev.key === key) {
          handler();
        }
      }
      window.addEventListener("storage", handleStorageEvent);
      return () => {
        window.removeEventListener("storage", handleStorageEvent);
        obs.removeEventListener(`update-${key}`, handler);
        obs.removeEventListener(`clear`, handler);
      };
    },
    delete: (key: string) => {
      const exists = localStorage.getItem(key) !== null;
      localStorage.removeItem(key);
      //@ts-ignore
      theLocalStorageMap.size = localStorage.length;
      obs.dispatchEvent(new Event(`update-${key}`));
      obs.dispatchEvent(new Event(`update`));
      return exists;
    },
    set: (key: string, v: string) => {
      localStorage.setItem(key, v);
      //@ts-ignore
      theLocalStorageMap.size = localStorage.length;
      obs.dispatchEvent(new Event(`update-${key}`));
      obs.dispatchEvent(new Event(`update`));
      return theLocalStorageMap;
    },
    clear: () => {
      localStorage.clear();
      obs.dispatchEvent(new Event(`clear`));
    },
    entries: (): IterableIterator<[string, string]> => {
      let index = 0;
      const total = localStorage.length;
      return {
        next() {
          if (index === total) return { done: true, value: undefined };
          const key = localStorage.key(index);
          if (key === null) {
            //we are going from 0 until last, this should not happen
            throw Error("key cant be null");
          }
          const item = localStorage.getItem(key);
          if (item === null) {
            //the key exist, this should not happen
            throw Error("value cant be null");
          }
          index = index + 1;
          return { done: false, value: [key, item] };
        },
        [Symbol.iterator]() {
          return this;
        },
      };
    },
    forEach: (cb) => {
      for (let index = 0; index < localStorage.length; index++) {
        const key = localStorage.key(index);
        if (key === null) {
          //we are going from 0 until last, this should not happen
          throw Error("key cant be null");
        }
        const item = localStorage.getItem(key);
        if (item === null) {
          //the key exist, this should not happen
          throw Error("value cant be null");
        }
        cb(key, item, theLocalStorageMap);
      }
    },
    get: (key: string) => {
      const item = localStorage.getItem(key);
      if (item === null) return undefined;
      return item;
    },
    has: (key: string) => {
      return localStorage.getItem(key) === null;
    },
    keys: () => {
      let index = 0;
      const total = localStorage.length;
      return {
        next() {
          if (index === total) return { done: true, value: undefined };
          const key = localStorage.key(index);
          if (key === null) {
            //we are going from 0 until last, this should not happen
            throw Error("key cant be null");
          }
          index = index + 1;
          return { done: false, value: key };
        },
        [Symbol.iterator]() {
          return this;
        },
      };
    },
    size: localStorage.length,
    values: () => {
      let index = 0;
      const total = localStorage.length;
      return {
        next() {
          if (index === total) return { done: true, value: undefined };
          const key = localStorage.key(index);
          if (key === null) {
            //we are going from 0 until last, this should not happen
            throw Error("key cant be null");
          }
          const item = localStorage.getItem(key);
          if (item === null) {
            //the key exist, this should not happen
            throw Error("value cant be null");
          }
          index = index + 1;
          return { done: false, value: item };
        },
        [Symbol.iterator]() {
          return this;
        },
      };
    },
    [Symbol.iterator]: function (): IterableIterator<[string, string]> {
      return theLocalStorageMap.entries();
    },
    [Symbol.toStringTag]: "theLocalStorageMap",
  };
  return theLocalStorageMap;
}

const isFirefox =
  typeof (window as any) !== "undefined" &&
  typeof (window as any)["InstallTrigger"] !== "undefined";

async function getAllContent() {
  //Firefox and Chrome has different storage api
  if (isFirefox) {
    // @ts-ignore
    return browser.storage.local.get();
  } else {
    return chrome.storage.local.get();
  }
}

async function updateContent(obj: Record<string, any>) {
  if (isFirefox) {
    // @ts-ignore
    return browser.storage.local.set(obj);
  } else {
    return chrome.storage.local.set(obj);
  }
}
type Changes = { [key: string]: { oldValue?: any; newValue?: any } };
function onBrowserStorageUpdate(cb: (changes: Changes) => void): void {
  if (isFirefox) {
    // @ts-ignore
    browser.storage.local.onChanged.addListener(cb);
  } else {
    chrome.storage.local.onChanged.addListener(cb);
  }
}

export function browserStorageMap(
  backend: ObservableMap<string, string>,
): ObservableMap<string, string> {
  getAllContent().then(content => {
    Object.entries(content ?? {}).forEach(([k, v]) => {
      backend.set(k, v as string);
    });
  })

  backend.onAnyUpdate(async () => {
    const result: Record<string, string> = {};
    for (const [key, value] of backend.entries()) {
      result[key] = value;
    }
    await updateContent(result);
  });

  onBrowserStorageUpdate((changes) => {
    //another chrome instance made the change
    const changedItems = Object.keys(changes);
    if (changedItems.length === 0) {
      backend.clear();
    } else {
      for (const key of changedItems) {
        if (!changes[key].newValue) {
          backend.delete(key);
        } else {
          if (changes[key].newValue !== changes[key].oldValue) {
            backend.set(key, changes[key].newValue);
          }
        }
      }
    }
  });

  return backend;
}