import type { AtomEffect, ViewOf } from "atom.io" export type StringInterface = { stringify: (t: ViewOf) => string parse: (s: string) => T } export const storageSync = ( storage: Storage | undefined, { stringify, parse }: StringInterface, key: string, ): AtomEffect => function storageSyncInit({ setSelf, onSet }) { if (!storage) { return } const savedValue = storage.getItem(key) if (savedValue != null) setSelf(parse(savedValue)) onSet(function storageSyncOnSet({ newValue }) { if (newValue == null) { storage.removeItem(key) return } storage.setItem(key, stringify(newValue)) }) }