UNPKG

@pixelation/state

Version:

Composable, reactive state management.

65 lines (64 loc) 1.77 kB
var u = Object.defineProperty; var h = (o, t, n) => t in o ? u(o, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : o[t] = n; var s = (o, t, n) => h(o, typeof t != "symbol" ? t + "" : t, n); class d { constructor() { s(this, "id", 0); s(this, "queue", []); // @ts-expect-error s(this, "atom", (t, n) => { const e = { id: this.id++, children: /* @__PURE__ */ new Set(), parents: /* @__PURE__ */ new Set() }; if (typeof t == "function") { const a = (i) => (e.children.add(i), i.parents.add(e), this.get(i)); e.read = t, e.value = t(a); } else e.value = t; return n !== void 0 && (e.write = n), e; }); // @ts-expect-error s(this, "get", (t) => t.value); s(this, "set", (t, ...n) => { let e; if (t.hasOwnProperty("write")) e = t.write( this.get, this.set, ...n ); else { if (t.hasOwnProperty("read")) throw new Error("Cannot set a dynamic read atom"); t.value = n[0]; } for (const a of t.parents) this.queue.push(a); return this.update(), e; }); s(this, "update", () => { for (; this.queue.length > 0; ) { const t = this.queue.shift(), n = t.value; if (!t.hasOwnProperty("read")) throw new Error("Cannot dynamically update non-dynamic atom"); const e = t.read(this.get); if (n !== e) { t.value = e; for (const a of t.parents) this.queue.unshift(a); } } }); } } const r = new d(), p = r.atom, l = r.get, f = r.set, w = r.update; export { r as ROOT_STORE, d as Store, p as atom, l as get, f as set, w as update };