Debian Codegraph @

frontend/src/lib/store.ts

raw
1 import type { Readable, Writable } from "svelte/store";
2 import { derived, writable } from "svelte/store";
3
4 import type { StrictEquality } from "./equals";
5 import { shallow_equal } from "./equals";
6 import { parseJSON } from "./json";
7 import type { Validator } from "./validation";
8
9 /**
10 * Create a derived store that does a shallow array equality check.
11 * @param store - The store to derive the value from.
12 * @param getter - A getter that obtains the array that should be contained in the store.
13 */
14 export function derived_array<S, T extends StrictEquality>(
15 store: Readable<S>,
16 getter: (values: S) => readonly T[],
17 ): Readable<readonly T[]> {
18 let val: readonly T[] = [];
19 return derived(
20 store,
21 (store_val, set) => {
22 const newVal = getter(store_val);
23 if (!shallow_equal(val, newVal)) {
24 set(newVal);
25 val = newVal;
26 }
27 },
28 val,
29 );
30 }
31
32 /** A store that has its value synced to localStorage. */
33 export type LocalStoreSyncedStore<T> = Writable<T> & {
34 /** List all the values that this store can take. */
35 values: () => [T, string][];
36 };
37
38 /**
39 * Create a store that syncs its value to localStorage.
40 * @param key - The key to save this with in localStorage.
41 * @param validator - A Validator to check the loaded value.
42 * @param init - A default to initialise the store with if localStorage is empty.
43 * @param values - An optional enumerator of all possible values and descriptions.
44 */
45 export function localStorageSyncedStore<T>(
46 key: string,
47 validator: Validator<T>,
48 init: () => T,
49 values: () => [T, string][] = () => [],
50 ): LocalStoreSyncedStore<T> {
51 const fullKey = `fava-${key}`;
52
53 // Create a store which is empty first but reads the value from
54 // localStorage on the first subscription.
55 const store = writable<T>(undefined, (set) => {
56 const stored_val = localStorage.getItem(fullKey);
57 let initial: T | null = null;
58 if (stored_val != null) {
59 const val = parseJSON(stored_val).and_then(validator).unwrap_or(null);
60 if (val !== null) {
61 initial = val;
62 }
63 }
64 set(initial ?? init());
65
66 store.subscribe((val) => {
67 localStorage.setItem(fullKey, JSON.stringify(val));
68 });
69 });
70
71 return { ...store, values };
72 }