UNPKG

react-shared-states

Version:

Global state made as simple as useState, with zero config, built-in async caching, and automatic scoping.

30 lines (28 loc) 16.8 kB
/*! * react-shared-states v1.0.12 * (c) Hichem Taboukouyout * Released under the MIT License. * Github: github.com/HichemTab-tech/react-shared-states */ (function(p,S){typeof exports=="object"&&typeof module<"u"?S(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],S):(p=typeof globalThis<"u"?globalThis:p||self,S(p.ReactSharedStates={},p.React))})(this,function(p,S){"use strict";function ce(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var N={exports:{}},C={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var B;function ue(){if(B)return C;B=1;var i=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(t,o,a){var n=null;if(a!==void 0&&(n=""+a),o.key!==void 0&&(n=""+o.key),"key"in o){a={};for(var f in o)f!=="key"&&(a[f]=o[f])}else a=o;return o=a.ref,{$$typeof:i,type:t,key:n,ref:o!==void 0?o:null,props:a}}return C.Fragment=e,C.jsx=r,C.jsxs=r,C}var F={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var J;function fe(){return J||(J=1,process.env.NODE_ENV!=="production"&&function(){function i(s){if(s==null)return null;if(typeof s=="function")return s.$$typeof===Me?null:s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case x:return"Fragment";case j:return"Profiler";case P:return"StrictMode";case Ne:return"Suspense";case ke:return"SuspenseList";case Ye:return"Activity"}if(typeof s=="object")switch(typeof s.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),s.$$typeof){case m:return"Portal";case Ce:return(s.displayName||"Context")+".Provider";case De:return(s._context.displayName||"Context")+".Consumer";case Fe:var u=s.render;return s=s.displayName,s||(s=u.displayName||u.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case Ve:return u=s.displayName||null,u!==null?u:i(s.type)||"Memo";case te:u=s._payload,s=s._init;try{return i(s(u))}catch{}}return null}function e(s){return""+s}function r(s){try{e(s);var u=!1}catch{u=!0}if(u){u=console;var g=u.error,R=typeof Symbol=="function"&&Symbol.toStringTag&&s[Symbol.toStringTag]||s.constructor.name||"Object";return g.call(u,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",R),e(s)}}function t(s){if(s===x)return"<>";if(typeof s=="object"&&s!==null&&s.$$typeof===te)return"<...>";try{var u=i(s);return u?"<"+u+">":"<...>"}catch{return"<...>"}}function o(){var s=I.A;return s===null?null:s.getOwner()}function a(){return Error("react-stack-top-frame")}function n(s){if(re.call(s,"key")){var u=Object.getOwnPropertyDescriptor(s,"key").get;if(u&&u.isReactWarning)return!1}return s.key!==void 0}function f(s,u){function g(){ne||(ne=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",u))}g.isReactWarning=!0,Object.defineProperty(s,"key",{get:g,configurable:!0})}function c(){var s=i(this.type);return se[s]||(se[s]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),s=this.props.ref,s!==void 0?s:null}function b(s,u,g,R,O,w,z,G){return g=w.ref,s={$$typeof:E,type:s,key:u,props:w,_owner:O},(g!==void 0?g:null)!==null?Object.defineProperty(s,"ref",{enumerable:!1,get:c}):Object.defineProperty(s,"ref",{enumerable:!1,value:null}),s._store={},Object.defineProperty(s._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(s,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(s,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:z}),Object.defineProperty(s,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:G}),Object.freeze&&(Object.freeze(s.props),Object.freeze(s)),s}function h(s,u,g,R,O,w,z,G){var y=u.children;if(y!==void 0)if(R)if(Ie(y)){for(R=0;R<y.length;R++)l(y[R]);Object.freeze&&Object.freeze(y)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else l(y);if(re.call(u,"key")){y=i(s);var D=Object.keys(u).filter(function(We){return We!=="key"});R=0<D.length?"{key: someKey, "+D.join(": ..., ")+": ...}":"{key: someKey}",ie[y+R]||(D=0<D.length?"{"+D.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,R,y,D,y),ie[y+R]=!0)}if(y=null,g!==void 0&&(r(g),y=""+g),n(u)&&(r(u.key),y=""+u.key),"key"in u){g={};for(var U in u)U!=="key"&&(g[U]=u[U])}else g=u;return y&&f(g,typeof s=="function"?s.displayName||s.name||"Unknown":s),b(s,y,w,O,o(),g,z,G)}function l(s){typeof s=="object"&&s!==null&&s.$$typeof===E&&s._store&&(s._store.validated=1)}var A=S,E=Symbol.for("react.transitional.element"),m=Symbol.for("react.portal"),x=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),De=Symbol.for("react.consumer"),Ce=Symbol.for("react.context"),Fe=Symbol.for("react.forward_ref"),Ne=Symbol.for("react.suspense"),ke=Symbol.for("react.suspense_list"),Ve=Symbol.for("react.memo"),te=Symbol.for("react.lazy"),Ye=Symbol.for("react.activity"),Me=Symbol.for("react.client.reference"),I=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,re=Object.prototype.hasOwnProperty,Ie=Array.isArray,W=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(s){return s()}};var ne,se={},ae=A.react_stack_bottom_frame.bind(A,a)(),oe=W(t(a)),ie={};F.Fragment=x,F.jsx=function(s,u,g,R,O){var w=1e4>I.recentlyCreatedOwnerStacks++;return h(s,u,g,!1,R,O,w?Error("react-stack-top-frame"):ae,w?W(t(s)):oe)},F.jsxs=function(s,u,g,R,O){var w=1e4>I.recentlyCreatedOwnerStacks++;return h(s,u,g,!0,R,O,w?Error("react-stack-top-frame"):ae,w?W(t(s)):oe)}}()),F}var X;function le(){return X||(X=1,process.env.NODE_ENV==="production"?N.exports=ue():N.exports=fe()),N.exports}var de=le();p.isDevMode=!1;const pe=i=>{p.isDevMode=i},V=(...i)=>{p.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...i)},L=i=>{if(!i)throw new Error("Value is empty");return i},H=()=>Math.random().toString(36).substring(2,15),Z=S.createContext(void 0),Se=({children:i,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=S.useMemo(()=>H(),[])),de.jsx(Z.Provider,{value:{scopeName:e},children:i})},he=()=>S.useContext(Z),Q=[];class d{data=new Map;defaultValue(){return{}}addListener(e,r,t){this.data.has(d.prefix(e,r))||this.data.set(d.prefix(e,r),{...this.defaultValue(),listeners:[]}),this.data.get(d.prefix(e,r)).listeners.push(t)}removeListener(e,r,t){this.data.has(d.prefix(e,r))&&(this.data.get(d.prefix(e,r)).listeners=this.data.get(d.prefix(e,r)).listeners.filter(o=>o!==t))}callListeners(e,r){this.data.has(d.prefix(e,r))&&this.data.get(d.prefix(e,r)).listeners.forEach(t=>t())}init(e,r,t,o=!1){this.data.has(d.prefix(e,r))||this.data.set(d.prefix(e,r),{...t,isStatic:o,listeners:[]})}createStatic(e,r){const t=r??r??"_global",o={key:H(),prefix:t,...e};return Q.push(o),this.initStatic(o),o}initStatic(e){const{key:r,prefix:t}=e;this.init(r,t,this.defaultValue(),!0)}clearAll(e=!1,r=!1){this.data.forEach((t,o)=>{const[a,n]=d.extractPrefix(o);this.clear(n,a,e,r)})}clear(e,r,t=!1,o=!1){t||this.callListeners(e,r);const a=this.data.get(d.prefix(e,r));if(!a)return;const n={...a};if(this.data.delete(d.prefix(e,r)),n.isStatic&&!o){const f=Q.find(c=>c.key===e&&c.prefix===r);f&&this.initStatic(f)}}get(e,r){let t=this.has(e,r);if(t)return this.data.get(t)}setValue(e,r,t){this.data.has(d.prefix(e,r))&&this.data.set(d.prefix(e,r),{...this.data.get(d.prefix(e,r)),...t})}has(e,r){return this.data.has(d.prefix(e,r))?d.prefix(e,r):this.data.has(d.prefix(e,"_global"))?d.prefix(e,"_global"):void 0}static prefix(e,r){if(e.includes("//"))throw new Error("key cannot contain '//'");return`${r}//${e}`}static extractPrefix(e){return e.split("//")}useEffect(e,r,t=null){S.useEffect(()=>()=>{t?.(),V(`[${d.prefix(e,r)}]`,"unmount effect"),this.data.get(d.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class Y{constructor(e){this.sharedData=e}get(e,r){let t,o=r;if(typeof e!="string"){const{key:f,prefix:c}=e;t=f,o=c}else t=L(e);const a=o||"_global";return this.sharedData.get(t,a)}set(e,r,t){let o,a=t;if(typeof e!="string"){const{key:f,prefix:c}=e;o=f,a=c}else o=L(e);const n=a||"_global";this.sharedData.init(o,n,r),this.sharedData.setValue(o,n,r),this.sharedData.callListeners(o,n)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,o)=>{const[a,n]=d.extractPrefix(o);if(a===r){this.sharedData.clear(n,a),this.sharedData.callListeners(n,a);return}})}resolve(e){const{key:r,prefix:t}=e;return this.get(r,t)}clear(e,r){let t,o;typeof e=="string"?(t=e,o=r||"_global"):(t=e.key,o=e.prefix),this.sharedData.clear(t,o)}has(e,r="_global"){const t=r||"_global";return!!this.sharedData.has(e,t)}getAll(){const e={};return this.sharedData.data.forEach((r,t)=>{const[o,a]=d.extractPrefix(t);e[o]=e[o]||{},e[o][a]=r}),e}}const k=i=>{const e=he();return{prefix:i??e?.scopeName??"_global"}};var M,K;function ge(){if(K)return M;K=1;var i=typeof Element<"u",e=typeof Map=="function",r=typeof Set=="function",t=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function o(a,n){if(a===n)return!0;if(a&&n&&typeof a=="object"&&typeof n=="object"){if(a.constructor!==n.constructor)return!1;var f,c,b;if(Array.isArray(a)){if(f=a.length,f!=n.length)return!1;for(c=f;c--!==0;)if(!o(a[c],n[c]))return!1;return!0}var h;if(e&&a instanceof Map&&n instanceof Map){if(a.size!==n.size)return!1;for(h=a.entries();!(c=h.next()).done;)if(!n.has(c.value[0]))return!1;for(h=a.entries();!(c=h.next()).done;)if(!o(c.value[1],n.get(c.value[0])))return!1;return!0}if(r&&a instanceof Set&&n instanceof Set){if(a.size!==n.size)return!1;for(h=a.entries();!(c=h.next()).done;)if(!n.has(c.value[0]))return!1;return!0}if(t&&ArrayBuffer.isView(a)&&ArrayBuffer.isView(n)){if(f=a.length,f!=n.length)return!1;for(c=f;c--!==0;)if(a[c]!==n[c])return!1;return!0}if(a.constructor===RegExp)return a.source===n.source&&a.flags===n.flags;if(a.valueOf!==Object.prototype.valueOf&&typeof a.valueOf=="function"&&typeof n.valueOf=="function")return a.valueOf()===n.valueOf();if(a.toString!==Object.prototype.toString&&typeof a.toString=="function"&&typeof n.toString=="function")return a.toString()===n.toString();if(b=Object.keys(a),f=b.length,f!==Object.keys(n).length)return!1;for(c=f;c--!==0;)if(!Object.prototype.hasOwnProperty.call(n,b[c]))return!1;if(i&&a instanceof Element)return!1;for(c=f;c--!==0;)if(!((b[c]==="_owner"||b[c]==="__v"||b[c]==="__o")&&a.$$typeof)&&!o(a[b[c]],n[b[c]]))return!1;return!0}return a!==a&&n!==n}return M=function(n,f){try{return o(n,f)}catch(c){if((c.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw c}},M}var ve=ge();const be=ce(ve);class me extends d{defaultValue(){return{value:void 0}}initValue(e,r,t,o=!1){super.init(e,r,{value:t},o)}initStatic(e){const{key:r,prefix:t,initialValue:o}=e;this.initValue(r,t,o,!0)}}class q extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.value:super.get(e,r)?.value}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,{value:r});return}super.set(e,{value:r},t)}}const _=new me,Ee=new q(_),xe=(i,e)=>_.createStatic({initialValue:i},e);function Re(i,e,r){let t,o,a=r;if(typeof i!="string"){const{key:l,initialValue:A,prefix:E}=i;t=l,o=A,a=E}else t=L(i),o=e;const{prefix:n}=k(a);_.initValue(t,n,o);const f=S.useMemo(()=>l=>(_.initValue(t,n,e),_.addListener(t,n,l),()=>{_.removeListener(t,n,l)}),[]),c=S.useMemo(()=>()=>_.get(t,n)?.value,[]),b=S.useSyncExternalStore(f,c),h=l=>{const A=typeof l=="function"?l(_.get(t,n)?.value):l;A!==b&&(_.setValue(t,n,{value:A}),_.callListeners(t,n))};return _.useEffect(t,n),[b,h]}function ye(i,e,r){let t,o=r;if(typeof i!="string"){const{key:h,prefix:l}=i;t=h,o=l}else t=L(i);const{prefix:a}=k(o),n=S.useRef(void 0),f=S.useMemo(()=>h=>(_.addListener(t,a,h),()=>{_.removeListener(t,a,h)}),[]),c=S.useMemo(()=>()=>{const h=_.get(t,a)?.value,l=e(h);return be(n.current,l)?n.current:l},[]),b=S.useSyncExternalStore(f,c);return _.useEffect(t,a),b}class _e extends d{defaultValue(){return{fnState:{results:void 0,isLoading:!1,error:void 0}}}initValue(e,r,t=!1){super.init(e,r,this.defaultValue(),t)}setValue(e,r,t){super.setValue(e,r,t)}}class $ extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.fnState:super.get(e,r)?.fnState}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,r);return}super.set(e,r,t)}}const T=new _e,Ae=new $(T),Te=(i,e)=>T.createStatic({fn:i},e);function we(i,e,r){let t,o,a=r;if(typeof i!="string"){const{key:l,fn:A,prefix:E}=i;t=l,o=A,a=E}else t=L(i),o=e;const{prefix:n}=k(a);T.initValue(t,n);const f=S.useMemo(()=>l=>(T.initValue(t,n),T.addListener(t,n,l),()=>{T.removeListener(t,n,l)}),[]),c=S.useMemo(()=>()=>T.get(t,n).fnState,[]),b=S.useSyncExternalStore(f,c),h=async(l,...A)=>{const E=T.get(t,n);if(!l&&(E.fnState.isLoading||E.fnState.results!==void 0))return E.fnState;E.fnState={...E.fnState,isLoading:!0,error:void 0},T.callListeners(t,n);try{const m=await o(...A);E.fnState={results:m,isLoading:!1,error:void 0}}catch(m){E.fnState={...E.fnState,isLoading:!1,error:m}}T.callListeners(t,n)};return T.useEffect(t,n),{state:b,trigger:(...l)=>{h(!1,...l)},forceTrigger:(...l)=>{h(!0,...l)},clear:()=>{const l=T.get(t,n);l&&(l.fnState=T.defaultValue().fnState,T.callListeners(t,n))}}}class Oe extends d{defaultValue(){return{fnState:{data:void 0,isLoading:!1,error:void 0,subscribed:!1}}}initValue(e,r,t=!1){super.init(e,r,this.defaultValue(),t)}setValue(e,r,t){super.setValue(e,r,t)}useEffect(e,r){S.useEffect(()=>()=>{V(`[${d.prefix(e,r)}]`,"unmount effect2"),this.get(e,r)?.listeners.length===0&&this.unsubscribe(e,r)},[]),super.useEffect(e,r)}async unsubscribe(e,r){const t=this.get(e,r);t&&(t.unsubscribe&&(t.unsubscribe(),t.unsubscribe=void 0),t.fnState={...t.fnState,subscribed:!1},this.callListeners(e,r))}}class ee extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.fnState:super.get(e,r)?.fnState}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,r);return}super.set(e,r,t)}}const v=new Oe,Pe=new ee(v),je=(i,e)=>v.createStatic({subscriber:i},e);function Le(i,e,r){let t,o,a=r;if(typeof i!="string"){const{key:m,subscriber:x,prefix:P}=i;t=m,o=x,a=P}else t=L(i),o=e;const{prefix:n}=k(a);v.initValue(t,n);const f=S.useMemo(()=>m=>(v.initValue(t,n),v.addListener(t,n,m),()=>{v.removeListener(t,n,m)}),[]),c=S.useMemo(()=>()=>v.get(t,n).fnState,[]),b=S.useSyncExternalStore(f,c),h=m=>{const x=v.get(t,n);x.fnState={...x.fnState,data:m},v.callListeners(t,n)},l=m=>{const x=v.get(t,n);x.fnState={...x.fnState,isLoading:!1,data:void 0,error:m},v.callListeners(t,n)},A=()=>{const m=v.get(t,n);m.fnState={...m.fnState,isLoading:!1},v.callListeners(t,n)},E=async m=>{const x=v.get(t,n);if(m&&(await v.unsubscribe(t,n),x.fnState={...x.fnState,isLoading:!1,data:void 0,error:void 0,subscribed:!1}),x.fnState.subscribed)return x.fnState;V("triggered !!"),x.fnState={...x.fnState,isLoading:!0,error:void 0},v.callListeners(t,n);try{const P=await o(h,l,A),j=v.get(t,n);j.unsubscribe=P,j.fnState.subscribed=!0}catch(P){const j=v.get(t,n);j.fnState={...j.fnState,isLoading:!1,error:P}}v.callListeners(t,n)};return v.useEffect(t,n),{state:b,trigger:()=>{E(!1)},forceTrigger:()=>{E(!0)},unsubscribe:()=>{v.unsubscribe(t,n)}}}p.SharedFunctionsApi=$,p.SharedStatesApi=q,p.SharedStatesProvider=Se,p.SharedSubscriptionsApi=ee,p.createSharedFunction=Te,p.createSharedState=xe,p.createSharedSubscription=je,p.setDevMode=pe,p.sharedFunctionsApi=Ae,p.sharedStatesApi=Ee,p.sharedSubscriptionsApi=Pe,p.useSharedFunction=we,p.useSharedState=Re,p.useSharedStateSelector=ye,p.useSharedSubscription=Le,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});