@pixelation/state
Version:
Composable, reactive state management.
2 lines (1 loc) • 1.24 kB
JavaScript
;var d=Object.defineProperty;var c=(o,t,n)=>t in o?d(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n;var s=(o,t,n)=>c(o,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class u{constructor(){s(this,"id",0);s(this,"queue",[]);s(this,"atom",(t,n)=>{const e={id:this.id++,children:new Set,parents: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});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 u,h=r.atom,l=r.get,p=r.set,f=r.update;exports.ROOT_STORE=r;exports.Store=u;exports.atom=h;exports.get=l;exports.set=p;exports.update=f;