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

type StateBin = Record<string, unknown>;

const STORAGE_KEY = 'stateBin';
const defaultState: StateBin = {};

function createStateBin() {
  const initialState: StateBin = browser
    ? JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}')
    : defaultState;
  const store: Writable<StateBin> = writable(initialState);

  const writeToStorage = (val: StateBin) => {
    if (browser)
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(val));
      } catch (error) {
        console.error('Failed to write stateBin:', error);
      }
  };

  return {
    subscribe: store.subscribe,

    set: (value) => {
      writeToStorage(value);
      store.set(value);
    },

    update: (updateFunction) => {
      const updatedStore = updateFunction(get(store));

      writeToStorage(updatedStore);
      store.set(updatedStore);
    },

    reset: () => {
      writeToStorage(defaultState);
      store.set(defaultState);
    },

    get: () => get(store),

    setKey: (key: string, value: unknown) => {
      const currentStore = get(store);
      const updatedStore = { ...currentStore, [key]: value };

      writeToStorage(updatedStore);
      store.set(updatedStore);
    },

    removeKey: (key: string) => {
      const currentStore = get(store);
      const { [key]: _, ...rest } = currentStore;

      writeToStorage(rest);
      store.set(rest);
    }
  };
}

const stateBin = createStateBin();

export default stateBin;