|
| 1 | +import { browser } from '$app/environment'; |
| 2 | + |
| 3 | +export type StorageType = 'local' | 'session'; |
| 4 | + |
| 5 | +export interface LocalStorageStateOptions { |
| 6 | + /** Which Web Storage area to persist to. Defaults to `'local'`. */ |
| 7 | + storage?: StorageType; |
| 8 | +} |
| 9 | + |
| 10 | +const mockStorage: Storage = { |
| 11 | + length: 0, |
| 12 | + clear: () => {}, |
| 13 | + getItem: () => null, |
| 14 | + key: () => null, |
| 15 | + removeItem: () => {}, |
| 16 | + setItem: () => {}, |
| 17 | +}; |
| 18 | + |
| 19 | +export class PersistedState<T> { |
| 20 | + readonly #key: string; |
| 21 | + readonly defaultValue: T; |
| 22 | + readonly #storage: Storage; |
| 23 | + #value: T; |
| 24 | + |
| 25 | + constructor(key: string, defaultValue: T, options: LocalStorageStateOptions = {}) { |
| 26 | + this.#key = key; |
| 27 | + this.defaultValue = defaultValue; |
| 28 | + this.#storage = browser |
| 29 | + ? options.storage === 'session' |
| 30 | + ? sessionStorage |
| 31 | + : localStorage |
| 32 | + : mockStorage; |
| 33 | + |
| 34 | + this.#value = $state<T>(this.deserialize(this.#storage.getItem(key))); |
| 35 | + |
| 36 | + // Only localStorage fires storage events across tabs; sessionStorage is tab-scoped. |
| 37 | + if (browser && options.storage !== 'session') { |
| 38 | + window.addEventListener('storage', this.#onStorage); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + #onStorage = (event: StorageEvent) => { |
| 43 | + if (event.storageArea !== this.#storage) return; |
| 44 | + if (event.key !== this.#key) return; |
| 45 | + this.#update(this.deserialize(event.newValue)); |
| 46 | + }; |
| 47 | + |
| 48 | + #update(value: T) { |
| 49 | + this.#value = value; |
| 50 | + this.onChange(value); |
| 51 | + } |
| 52 | + |
| 53 | + get value() { |
| 54 | + return this.#value; |
| 55 | + } |
| 56 | + set value(value: T) { |
| 57 | + this.#update(value); |
| 58 | + this.#storage.setItem(this.#key, this.serialize(value)); |
| 59 | + } |
| 60 | + |
| 61 | + reset() { |
| 62 | + this.#update(this.defaultValue); |
| 63 | + this.#storage.removeItem(this.#key); |
| 64 | + } |
| 65 | + |
| 66 | + /** Hook called whenever the value changes, regardless of source (setter, reset, or storage event). */ |
| 67 | + protected onChange(_value: T): void {} |
| 68 | + |
| 69 | + protected serialize(value: T): string { |
| 70 | + return JSON.stringify(value); |
| 71 | + } |
| 72 | + |
| 73 | + protected deserialize(raw: string | null): T { |
| 74 | + if (raw === null) return this.defaultValue; |
| 75 | + return JSON.parse(raw) as T; |
| 76 | + } |
| 77 | +} |
0 commit comments