diff options
Diffstat (limited to 'src/stores')
| -rw-r--r-- | src/stores/stateBin.ts | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/stores/stateBin.ts b/src/stores/stateBin.ts new file mode 100644 index 00000000..6c664f71 --- /dev/null +++ b/src/stores/stateBin.ts @@ -0,0 +1,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; |