-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstorage.svelte.ts
97 lines (76 loc) · 1.87 KB
/
storage.svelte.ts
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
import { tick } from 'svelte';
export class LocalStorage<T> {
#key: string;
#version = $state(0);
#listeners = 0;
#value: T | undefined;
#handler = (e: StorageEvent) => {
if (e.storageArea !== localStorage) return;
if (e.key !== this.#key) return;
this.#version += 1;
};
constructor(key: string, initial?: T) {
this.#key = key;
this.#value = initial;
if (typeof localStorage !== 'undefined') {
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, JSON.stringify(initial));
}
}
}
get current() {
this.#version;
const root =
typeof localStorage !== 'undefined'
? JSON.parse(localStorage.getItem(this.#key) as any)
: this.#value;
const proxies = new WeakMap();
const proxy = (value: unknown) => {
if (typeof value !== 'object' || value === null) {
return value;
}
let p = proxies.get(value);
if (!p) {
p = new Proxy(value, {
get: (target, property) => {
this.#version;
return proxy(Reflect.get(target, property));
},
set: (target, property, value) => {
this.#version += 1;
Reflect.set(target, property, value);
if (typeof localStorage !== 'undefined') {
localStorage.setItem(this.#key, JSON.stringify(root));
}
return true;
}
});
proxies.set(value, p);
}
return p;
};
if ($effect.tracking()) {
$effect(() => {
if (this.#listeners === 0) {
window.addEventListener('storage', this.#handler);
}
this.#listeners += 1;
return () => {
tick().then(() => {
this.#listeners -= 1;
if (this.#listeners === 0) {
window.removeEventListener('storage', this.#handler);
}
});
};
});
}
return proxy(root);
}
set current(value) {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(this.#key, JSON.stringify(value));
}
this.#version += 1;
}
}