aboutsummaryrefslogtreecommitdiff
path: root/src/stores/stateBin.ts
blob: 74ea510fb75de4b316572a86625961117cb39692 (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
import { browser } from '$app/environment';
import { writable, get, type Writable } from 'svelte/store';

type StateBin = Record<string, unknown>;

const STORAGE_KEY = 'stateBin';
const initialState = browser ? JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') : {};
const baseStore = writable<StateBin>(initialState);

if (browser)
  baseStore.subscribe((val) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(val));
  });

const createProxyStore = (store: Writable<StateBin>) => {
  return new Proxy(store, {
    get(target, prop: string) {
      if (prop in target) return (target as any)[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;