summaryrefslogtreecommitdiff
path: root/packages/web-util/src/utils/observable.ts
blob: dfa434635891c8b6bf19a915e82e964218555921 (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
export type ObservableMap<K, V> = Map<K, V> & {
  onUpdate: (key: string, callback: () => void) => () => void;
};

const UPDATE_EVENT_NAME = "update";

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

export function localStorageMap(): ObservableMap<string, string> {
  const obs = new EventTarget();
  const theLocalStorageMap: ObservableMap<string, string> = {
    onUpdate: (key, handler) => {
      //@ts-ignore
      theLocalStorageMap.size = localStorage.length;
      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);
      obs.dispatchEvent(new Event(`update-${key}`));
      return exists;
    },
    set: (key: string, v: string) => {
      localStorage.setItem(key, v);
      obs.dispatchEvent(new Event(`update-${key}`));
      return theLocalStorageMap;
    },
    clear: () => {
      localStorage.clear();
      obs.dispatchEvent(new Event(`clear`));
    },
    entries: (): IterableIterator<[string, string]> => {
      let index = 0;
      const total = localStorage.length;
      return {
        next() {
          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");
          }
          if (index == total) return { done: true, value: [key, item] };
          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() {
          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");
          }
          if (index == total) return { done: true, value: key };
          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() {
          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");
          }
          if (index == total) return { done: true, value: item };
          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;
}