@dependable/state
Version:
Observables and computeds for reactive state management
2 lines (1 loc) • 2.15 kB
JavaScript
const o=globalThis.o||{},t=globalThis;t.o||(t.o=o,o.a=new Set,o.b=new Map,o.c=new Set,o.t=new Map);const n=t=>{o.c.add(t)},e=t=>{o.c.delete(t)},s=()=>{const t=new Set;for(const n of o.b.values()){const o=n.deref();o&&t.add(o)}return t},c=t=>{o.t.set(t.id,t)},f=t=>{t.id&&o.b.set(t.id,new WeakRef(t)),w(new Set([t]))},r=()=>(t.cancelAnimationFrame||clearTimeout)(l),w=t=>{for(const n of o.c)n(t)},l=()=>{const t=o.a,n=new Map,e=new Set;S(t,e);const s=new Set;for(const o of e){if(o.e){let t=!1;for(const n of o.e)if(n.l){t=!0;break}t&&o.d()}if(o.l){s.add(o);for(const[t,e]of o.i.entries())n.set(t,e)}}o.a.clear();const c=Array.from(n.entries()).sort(((o,t)=>o[1]-t[1])).map((([o])=>o));for(const o of c)o();w(s),r(),o.a.size>0&&l()},i=n=>{o.a.add(n),(()=>{r();const o=t.requestAnimationFrame;o?o(l):setTimeout(l,0)})()},a=(t,n={})=>{const{id:e}=n;if(e&&o.t.has(e)){const t=o.t.get(e);return o.t.delete(e),t}let s=t;const c=(...t)=>{if(0===t.length)return o.e&&o.e.add(c),s;s=t[0],c.l=!0,i(c)};return c.id=e,c.kind="observable",c.f=new Set,c.i=new Map,c.l=!1,c.g=o=>{c.f.add(o)},c.h=o=>{c.f.delete(o)},c.subscribe=(o,t=0)=>{c.i.set(o,t)},c.unsubscribe=o=>{c.i.delete(o)},f(c),c},S=(o,t)=>{const n=new Set;for(const e of o){t.delete(e),t.add(e);for(const o of e.f)n.add(o)}n.size>0&&S(n,t)},u=t=>{const n=o.e,e=new Set;return o.e=e,t(),o.e=n,e},p=(t,n={})=>{const{id:e,isEqual:s=Object.is}=n;let c=null,r=null,w=!1;const l=()=>(o.e&&o.e.add(l),w?c:o.e?(l.d(),c):(r=c,c=t(),c));l.id=e,l.kind="computed",l.f=new Set,l.e=new Set,l.i=new Map,l.l=!1,l.d=()=>{r=c;const o=u((()=>{c=t()})),n=l.e;l.e=o,w||(r=c),l.l=!s(c,r);const e=new Set;for(const t of n)o.has(t)||e.add(t);for(const o of l.e)o.g(l);for(const o of e)o.h(l)};const i=()=>{if(w){if(0===l.f.size&&0===l.i.size){for(const o of l.e)o.h(l);l.e=new Set,w=!1}}else l.f.size>0?w=!0:l.i.size>0&&(l.d(),w=!0)};return l.g=o=>{l.f.add(o),i()},l.h=o=>{l.f.delete(o),i()},l.subscribe=(o,t=0)=>{l.i.set(o,t),i()},l.unsubscribe=o=>{l.i.delete(o),i()},f(l),l};export{n as addStateListener,p as computed,l as flush,a as observable,c as registerInitial,e as removeStateListener,s as subscribables,u as track};