react-liberate
Version:
simple and elegant React Global State Manager.
2 lines (1 loc) • 2.44 kB
JavaScript
import{reactive as P,toRefs as W,markRaw as H,computed as B,watch as J,activeEffect as N}from"@maoism/runtime-core";import{isFunction as U}from"savage-types";import T from"react";import{isRef as F,isReactive as G,ReactiveEffect as M,activeEffect as C}from"@maoism/runtime-core";import{isObject as Y,isArray as Z,isUndefined as ee}from"savage-types";import{copyDeep as ne}from"savage-utils";function f(){return{}}function _(e){return e&&typeof e=="object"&&Object.prototype.toString.call(e)==="[object Object]"&&typeof e.toJSON!="function"}function b(e,t){e instanceof Map&&t instanceof Map&&t.forEach((r,o)=>e.set(o,r)),e instanceof Set&&t instanceof Set&&t.forEach(e.add,e);for(let r in t){if(!t.hasOwnProperty(r))continue;let o=t[r],u=e[r];_(u)&&_(o)&&e.hasOwnProperty(r)&&!F(o)&&!G(o)?e[r]=b(u,o):e[r]=o}return e}function I(){let[,e]=T.useState({});return T.useCallback(()=>e({}),[])}var E=new WeakMap;function h(){let e=I(),t=E.get(e);t||(t=new M(f,f,()=>{e(),t!=null&&t.dirty&&t.run()}),t.run(),E.set(e,t)),C.value=t}import{useState as $}from"react";var y="component";function g(e){y=e}function K(){try{g("pending"),$(),g("component")}catch(e){g("js")}return y}function v(e,t=f){K()==="component"?e():t()}function V(e){try{e()}catch(t){}}V(()=>{let e=globalThis.console.error;globalThis.console.error=function(...t){y!=="pending"&&e(...t)}});var i;function j(){return{_store:new Map,_state:new Map,_plugins:new Set,use(e){return this._plugins.add(e),this}}}function w(e){i=e}w(j());var x=new Set;function O(e,t=f){return x.add(e),()=>{x.delete(e),t()}}function k(e){x.forEach(t=>t(e))}var S=!1;function q(e,t){let r=!1;function o(){let{state:p,actions:l,getters:d}=t,s=P(p?p():{}),L=p?p():{},R={$id:e,$state:s,$patch(n){r=!1,U(n)?n(s):b(s,n),r=!0,k(s)},$reset(){this.$patch(n=>{Object.assign(n,L)})},$subscribe(n){let c=O(n,()=>m()),m=J(s,D=>{r&&n(D)},{deep:!0,flush:"sync"});return c}};i._state.set(e,s);let a=P(Object.assign(R,W(s),Object.keys(l!=null?l:[]).reduce((n,c)=>Object.assign(n,{[c]:function(...m){return l[c].call(a,...m)}}),{}),Object.keys(d||{}).reduce((n,c)=>(n[c]=H(B(()=>d==null?void 0:d[c].call(a,a))),n),{}))),A=S;S=!0,i._plugins.forEach(n=>{Object.assign(a,n({store:a,options:t})||{})}),S=A,i._store.set(e,a)}function u(){return S||v(()=>N.value=void 0),i._store.has(e)||o(),S||v(()=>h()),r=!0,i._store.get(e)}return u.$id=e,u}export{j as createLiberate,q as defineStore,i as liberate,w as setActiveLiberate};