blob: ca61ed774a137d2470addd5e6ebe935026d4b79f (
plain) (
blame)
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
|
import { browser } from "$app/environment";
import { writable, get, type Writable } from "svelte/store";
import localforage from "localforage";
interface StateBin {
dueAnimeListOpen?: boolean;
upcomingAnimeListOpen?: boolean;
dueMangaListOpen?: boolean;
completedAnimeListOpen?: boolean;
completedMangaListOpen?: boolean;
[key: string]: boolean | string | undefined;
}
const STORAGE_KEY = "stateBin";
const baseStore = writable<StateBin>({});
let hydrated = !browser;
let state: StateBin = {};
let changedBeforeHydration = false;
let initialEmission = true;
let applyingStoredValue = false;
if (browser) {
localforage.getItem<StateBin>(STORAGE_KEY).then((value) => {
if (value && typeof value === "object" && !changedBeforeHydration) {
applyingStoredValue = true;
baseStore.set(value);
applyingStoredValue = false;
}
hydrated = true;
localforage.setItem(STORAGE_KEY, state);
});
baseStore.subscribe((value) => {
state = value;
if (browser && !hydrated && !initialEmission && !applyingStoredValue)
changedBeforeHydration = true;
if (hydrated) localforage.setItem(STORAGE_KEY, value);
initialEmission = false;
});
}
const createProxyStore = (store: Writable<StateBin>) => {
return new Proxy(store, {
get(target, prop: string) {
if (prop in target)
return (target as unknown as Record<string, unknown>)[prop];
const derivedKey = writable(get(store)[prop]);
derivedKey.subscribe((value) => {
const state = get(store);
const updatedState = { ...state };
if (value === null || value === undefined) delete updatedState[prop];
else updatedState[prop] = value;
store.set(updatedState);
});
return derivedKey;
},
set(_, prop: string, value) {
const state = get(store);
const updatedState = { ...state };
if (value === null || value === undefined) delete updatedState[prop];
else updatedState[prop] = value;
store.set(updatedState);
return true;
},
});
};
const stateBin = createProxyStore(baseStore);
export default stateBin;
|