UNPKG

@pixelation/state

Version:

Composable, reactive state management.

2 lines (1 loc) 1.42 kB
(function(t,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(t=typeof globalThis<"u"?globalThis:t||self,n(t.PixelationState={}))})(this,function(t){"use strict";var l=Object.defineProperty;var p=(t,n,o)=>n in t?l(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o;var u=(t,n,o)=>p(t,typeof n!="symbol"?n+"":n,o);class n{constructor(){u(this,"id",0);u(this,"queue",[]);u(this,"atom",(e,s)=>{const i={id:this.id++,children:new Set,parents:new Set};if(typeof e=="function"){const a=r=>(i.children.add(r),r.parents.add(i),this.get(r));i.read=e,i.value=e(a)}else i.value=e;return s!==void 0&&(i.write=s),i});u(this,"get",e=>e.value);u(this,"set",(e,...s)=>{let i;if(e.hasOwnProperty("write"))i=e.write(this.get,this.set,...s);else{if(e.hasOwnProperty("read"))throw new Error("Cannot set a dynamic read atom");e.value=s[0]}for(const a of e.parents)this.queue.push(a);return this.update(),i});u(this,"update",()=>{for(;this.queue.length>0;){const e=this.queue.shift(),s=e.value;if(!e.hasOwnProperty("read"))throw new Error("Cannot dynamically update non-dynamic atom");const i=e.read(this.get);if(s!==i){e.value=i;for(const a of e.parents)this.queue.unshift(a)}}})}}const o=new n,d=o.atom,f=o.get,h=o.set,c=o.update;t.ROOT_STORE=o,t.Store=n,t.atom=d,t.get=f,t.set=h,t.update=c,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});