UNPKG

atomaric

Version:

Manage your project state

60 lines (59 loc) 2.4 kB
const u = {}; window.addEventListener("storage", (e) => { e.key === null || u[e.key] === void 0 || u[e.key](e); }); class g { constructor(s, i) { if (this._defaultValue = s, this.subscribers = /* @__PURE__ */ new Set(), this.save = () => { }, this.invokeSubscriber = (t) => t(this.value), this.get = () => this.value, this.toggle = () => this.set(!this.value), this.inkrement = (t) => this.set(this.value + t), this.subscribe = (t) => (this.subscribers.add(t), () => { this.subscribers.delete(t); }), this.set = (t, c) => { const n = typeof t == "function" ? t(this.value) : t; n === this.value || n === void 0 || typeof n == "number" && isNaN(n) || (this.value = n, this.subscribers.forEach(this.invokeSubscriber, this), c !== !0 && this.save(n)); }, this.value = s, typeof s != "boolean" && (this.toggle = () => { }), typeof s != "number" && (this.inkrement = () => { }), this.reset = () => { this.set(s, !0), this.subscribers.forEach(this.invokeSubscriber, this); }, i == null) return; let o = null, l = !0, h = !0; if (typeof i == "string" ? o = i : i.storeKey !== void 0 && (l = i.warnOnDuplicateStoreKey ?? !0, h = i.listenStorageChanges ?? !0, o = i.storeKey), o === null) return; const r = `atom/${o}`; this.value = r in localStorage ? JSON.parse(localStorage[r]) : s, this.save = (t) => { if (t === s) { this.reset(); return; } localStorage[r] = JSON.stringify(t); }, this.reset = () => { delete localStorage[r], this.set(s, !0); }, l && u[r] !== void 0 && console.warn("Duplicate Atom key", i), h && (u[r] = (t) => { if (t.newValue === null) { this.reset(); return; } try { this.set(JSON.parse(t.newValue)); } catch { console.warn("Invalid json value", t.newValue); } }); } get defaultValue() { return this._defaultValue; } } let a = () => { throw "call configureAtomaric() before all!"; }; const S = (e) => a = e.useSyncExternalStore, b = (e) => a(e.subscribe, e.get), f = (e) => e.set, m = (e) => e.get, v = (e) => e.toggle, k = (e) => e.inkrement, w = (e) => [b(e), f(e)], y = (e, s) => new g(e, s); export { g as Atom, y as atom, S as configureAtomaric, w as useAtom, m as useAtomGet, k as useAtomInkrement, f as useAtomSet, v as useAtomToggle, b as useAtomValue };