UNPKG

unistore-hooks

Version:

2 lines (1 loc) 1.27 kB
import{createContext as t}from"preact";import{useContext as n,useMemo as r,useReducer as e,useCallback as i}from"preact/hooks";function o(t,n,r,e,i){for(n=n.split?n.split("."):n,e=0;e<n.length;e++)t=t?t[n[e]]:i;return t===i?r:t}const f=t(),u=f.Provider;function c(t,n){let r=!1;for(let e in n)t[e]!==n[e]&&(!1===r&&(r=!0,t=Object.assign({},t)),t[e]=n[e]);return t}function s(){return n(f)}function p(t){const i=n(f),u=r(()=>function(t){let n=typeof t;return"function"==n?t:("string"==n&&(t=t.split(/\s*,\s*/)),Array.isArray(t)&&(t=t.reduce((t,n)=>(t[n]=n,t),{})),n=>{let r={};if(n)for(let e in t)r[e]=e in n?n[e]:o(n,t[e]);return r})}(t),[]),[s,p]=e(c,i?u(i.getState()):{});return useEffect(()=>i.subscribe(t=>p(u(t))),[i]),s}function a(t,e,o){"function"==typeof o&&([o,e]=[e,o]);const u=n(f),c=r(()=>function(t,n){const r=n.bindings||(n.bindings=new("function"==typeof WeakMap?WeakMap:Map));let e=r.get(t);if(!e){r.set(t,e={}),"function"==typeof t&&(t=t(n));for(let r in t)e[r]=n.action(t[r])}return e}(t,u),[t,u]);return e=i(e,o||[]),r(()=>{let t=e,n={};if(!t)return c;"function"==typeof t&&(t=t(c));for(let r in t){let e=t[r];Array.isArray(e)&&(e=e[0].bind.apply(e[0],e)),n[r]=e}return n},[c,e])}export{u as Provider,a as useActions,s as useStore,p as useStoreState};