aboutsummaryrefslogtreecommitdiff
path: root/src/stores/stateBin.ts
blob: 06d34bef1c0e47c425c2612f5d69f76e1fd0ddb7 (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
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>({});

if (browser) {
	localforage.getItem<StateBin>(STORAGE_KEY).then((value) => {
		if (value && typeof value === "object") baseStore.set(value);
	});

	baseStore.subscribe((value) => {
		localforage.setItem(STORAGE_KEY, value);
	});
}

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;