react-shared-states 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/SharedValuesManager.d.ts +9 -0
- package/dist/hooks/use-shared-function.d.ts +6 -0
- package/dist/hooks/use-shared-state.d.ts +2 -0
- package/dist/hooks/use-shared-subscription.d.ts +6 -0
- package/dist/main.esm.js +351 -321
- package/dist/main.min.js +5 -5
- package/package.json +1 -1
- package/tests/index.test.tsx +70 -0
package/dist/main.min.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* react-shared-states v1.0.
|
|
2
|
+
* react-shared-states v1.0.15
|
|
3
3
|
* (c) Hichem Taboukouyout
|
|
4
4
|
* Released under the MIT License.
|
|
5
5
|
* Github: github.com/HichemTab-tech/react-shared-states
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
(function(p,
|
|
8
|
+
(function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.ReactSharedStates={},p.React))})(this,(function(p,h){"use strict";function ce(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var V={exports:{}},C={};/**
|
|
9
9
|
* @license React
|
|
10
10
|
* react-jsx-runtime.production.js
|
|
11
11
|
*
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the MIT license found in the
|
|
15
15
|
* LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/var
|
|
16
|
+
*/var J;function ue(){if(J)return C;J=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(t,i,s){var n=null;if(s!==void 0&&(n=""+s),i.key!==void 0&&(n=""+i.key),"key"in i){s={};for(var f in i)f!=="key"&&(s[f]=i[f])}else s=i;return i=s.ref,{$$typeof:o,type:t,key:n,ref:i!==void 0?i:null,props:s}}return C.Fragment=e,C.jsx=r,C.jsxs=r,C}var F={};/**
|
|
17
17
|
* @license React
|
|
18
18
|
* react-jsx-runtime.development.js
|
|
19
19
|
*
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
*
|
|
22
22
|
* This source code is licensed under the MIT license found in the
|
|
23
23
|
* LICENSE file in the root directory of this source tree.
|
|
24
|
-
*/var
|
|
24
|
+
*/var X;function fe(){return X||(X=1,process.env.NODE_ENV!=="production"&&(function(){function o(a){if(a==null)return null;if(typeof a=="function")return a.$$typeof===Ie?null:a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case x:return"Fragment";case L:return"Profiler";case P:return"StrictMode";case Ve:return"Suspense";case Ne:return"SuspenseList";case Me:return"Activity"}if(typeof a=="object")switch(typeof a.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),a.$$typeof){case m:return"Portal";case Ce:return(a.displayName||"Context")+".Provider";case De:return(a._context.displayName||"Context")+".Consumer";case Fe:var u=a.render;return a=a.displayName,a||(a=u.displayName||u.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case Ye:return u=a.displayName||null,u!==null?u:o(a.type)||"Memo";case te:u=a._payload,a=a._init;try{return o(a(u))}catch{}}return null}function e(a){return""+a}function r(a){try{e(a);var u=!1}catch{u=!0}if(u){u=console;var g=u.error,_=typeof Symbol=="function"&&Symbol.toStringTag&&a[Symbol.toStringTag]||a.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.",_),e(a)}}function t(a){if(a===x)return"<>";if(typeof a=="object"&&a!==null&&a.$$typeof===te)return"<...>";try{var u=o(a);return u?"<"+u+">":"<...>"}catch{return"<...>"}}function i(){var a=W.A;return a===null?null:a.getOwner()}function s(){return Error("react-stack-top-frame")}function n(a){if(re.call(a,"key")){var u=Object.getOwnPropertyDescriptor(a,"key").get;if(u&&u.isReactWarning)return!1}return a.key!==void 0}function f(a,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(a,"key",{get:g,configurable:!0})}function c(){var a=o(this.type);return se[a]||(se[a]=!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.")),a=this.props.ref,a!==void 0?a:null}function b(a,u,g,_,O,y,G,U){return g=y.ref,a={$$typeof:E,type:a,key:u,props:y,_owner:O},(g!==void 0?g:null)!==null?Object.defineProperty(a,"ref",{enumerable:!1,get:c}):Object.defineProperty(a,"ref",{enumerable:!1,value:null}),a._store={},Object.defineProperty(a._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(a,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(a,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:G}),Object.defineProperty(a,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(a.props),Object.freeze(a)),a}function S(a,u,g,_,O,y,G,U){var R=u.children;if(R!==void 0)if(_)if(We(R)){for(_=0;_<R.length;_++)l(R[_]);Object.freeze&&Object.freeze(R)}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(R);if(re.call(u,"key")){R=o(a);var D=Object.keys(u).filter(function(ze){return ze!=="key"});_=0<D.length?"{key: someKey, "+D.join(": ..., ")+": ...}":"{key: someKey}",oe[R+_]||(D=0<D.length?"{"+D.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
25
25
|
let props = %s;
|
|
26
26
|
<%s {...props} />
|
|
27
27
|
React keys must be passed directly to JSX without using spread:
|
|
28
28
|
let props = %s;
|
|
29
|
-
<%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"})}));
|
|
29
|
+
<%s key={someKey} {...props} />`,_,R,D,R),oe[R+_]=!0)}if(R=null,g!==void 0&&(r(g),R=""+g),n(u)&&(r(u.key),R=""+u.key),"key"in u){g={};for(var B in u)B!=="key"&&(g[B]=u[B])}else g=u;return R&&f(g,typeof a=="function"?a.displayName||a.name||"Unknown":a),b(a,R,y,O,i(),g,G,U)}function l(a){typeof a=="object"&&a!==null&&a.$$typeof===E&&a._store&&(a._store.validated=1)}var A=h,E=Symbol.for("react.transitional.element"),m=Symbol.for("react.portal"),x=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),L=Symbol.for("react.profiler"),De=Symbol.for("react.consumer"),Ce=Symbol.for("react.context"),Fe=Symbol.for("react.forward_ref"),Ve=Symbol.for("react.suspense"),Ne=Symbol.for("react.suspense_list"),Ye=Symbol.for("react.memo"),te=Symbol.for("react.lazy"),Me=Symbol.for("react.activity"),Ie=Symbol.for("react.client.reference"),W=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,re=Object.prototype.hasOwnProperty,We=Array.isArray,z=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(a){return a()}};var ne,se={},ae=A.react_stack_bottom_frame.bind(A,s)(),ie=z(t(s)),oe={};F.Fragment=x,F.jsx=function(a,u,g,_,O){var y=1e4>W.recentlyCreatedOwnerStacks++;return S(a,u,g,!1,_,O,y?Error("react-stack-top-frame"):ae,y?z(t(a)):ie)},F.jsxs=function(a,u,g,_,O){var y=1e4>W.recentlyCreatedOwnerStacks++;return S(a,u,g,!0,_,O,y?Error("react-stack-top-frame"):ae,y?z(t(a)):ie)}})()),F}var H;function le(){return H||(H=1,process.env.NODE_ENV==="production"?V.exports=ue():V.exports=fe()),V.exports}var de=le();p.isDevMode=!1;const pe=o=>{p.isDevMode=o},Y=(...o)=>{p.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...o)},j=o=>{if(!o)throw new Error("Value is empty");return o},Z=()=>Math.random().toString(36).substring(2,15),k=h.createContext(void 0),he=({children:o,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=h.useMemo(()=>Z(),[])),de.jsx(k.Provider,{value:{scopeName:e},children:o})},Se=()=>h.useContext(k),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(i=>i!==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,i=!1){this.data.has(d.prefix(e,r))||this.data.set(d.prefix(e,r),{...t,isStatic:i,listeners:[]})}createStatic(e,r){const t=r??r??"_global",i={key:Z(),prefix:t,...e};return Q.push(i),this.initStatic(i),i}initStatic(e){const{key:r,prefix:t}=e;this.init(r,t,this.defaultValue(),!0)}clearAll(e=!1,r=!1){this.data.forEach((t,i)=>{const[s,n]=d.extractPrefix(i);this.clear(n,s,e,r)})}clear(e,r,t=!1,i=!1){t||this.callListeners(e,r);const s=this.data.get(d.prefix(e,r));if(!s)return;const n={...s};if(this.data.delete(d.prefix(e,r)),n.isStatic&&!i){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){h.useEffect(()=>()=>{t?.(),Y(`[${d.prefix(e,r)}]`,"unmount effect"),this.data.get(d.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class M{constructor(e){this.sharedData=e}get(e,r){let t,i=r;if(typeof e!="string"){const{key:f,prefix:c}=e;t=f,i=c}else t=j(e);const s=i||"_global";return this.sharedData.get(t,s)}set(e,r,t){let i,s=t;if(typeof e!="string"){const{key:f,prefix:c}=e;i=f,s=c}else i=j(e);const n=s||"_global";this.sharedData.init(i,n,r),this.sharedData.setValue(i,n,r),this.sharedData.callListeners(i,n)}update(e,r,t){let i;typeof e=="string"?i=this.get(e,t):i=this.get(e);const s=r(i);typeof e=="string"?this.set(e,s,t):this.set(e,s)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,i)=>{const[s,n]=d.extractPrefix(i);if(s===r){this.sharedData.clear(n,s),this.sharedData.callListeners(n,s);return}})}resolve(e){const{key:r,prefix:t}=e;return this.get(r,t)}clear(e,r){let t,i;typeof e=="string"?(t=e,i=r||"_global"):(t=e.key,i=e.prefix),this.sharedData.clear(t,i)}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[i,s]=d.extractPrefix(t);e[i]=e[i]||{},e[i][s]=r}),e}subscribe(e,r,t){let i,s;return typeof e=="string"?(i=e,s=t||"_global"):(i=e.key,s=e.prefix),this.sharedData.addListener(i,s,r),()=>{this.sharedData.removeListener(i,s,r)}}}const N=o=>{const e=Se();return{prefix:o??e?.scopeName??"_global"}};var I,K;function ge(){if(K)return I;K=1;var o=typeof Element<"u",e=typeof Map=="function",r=typeof Set=="function",t=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function i(s,n){if(s===n)return!0;if(s&&n&&typeof s=="object"&&typeof n=="object"){if(s.constructor!==n.constructor)return!1;var f,c,b;if(Array.isArray(s)){if(f=s.length,f!=n.length)return!1;for(c=f;c--!==0;)if(!i(s[c],n[c]))return!1;return!0}var S;if(e&&s instanceof Map&&n instanceof Map){if(s.size!==n.size)return!1;for(S=s.entries();!(c=S.next()).done;)if(!n.has(c.value[0]))return!1;for(S=s.entries();!(c=S.next()).done;)if(!i(c.value[1],n.get(c.value[0])))return!1;return!0}if(r&&s instanceof Set&&n instanceof Set){if(s.size!==n.size)return!1;for(S=s.entries();!(c=S.next()).done;)if(!n.has(c.value[0]))return!1;return!0}if(t&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(n)){if(f=s.length,f!=n.length)return!1;for(c=f;c--!==0;)if(s[c]!==n[c])return!1;return!0}if(s.constructor===RegExp)return s.source===n.source&&s.flags===n.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof n.valueOf=="function")return s.valueOf()===n.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof n.toString=="function")return s.toString()===n.toString();if(b=Object.keys(s),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(o&&s instanceof Element)return!1;for(c=f;c--!==0;)if(!((b[c]==="_owner"||b[c]==="__v"||b[c]==="__o")&&s.$$typeof)&&!i(s[b[c]],n[b[c]]))return!1;return!0}return s!==s&&n!==n}return I=function(n,f){try{return i(n,f)}catch(c){if((c.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw c}},I}var ve=ge();const be=ce(ve);class me extends d{defaultValue(){return{value:void 0}}initValue(e,r,t,i=!1){super.init(e,r,{value:t},i)}initStatic(e){const{key:r,prefix:t,initialValue:i}=e;this.initValue(r,t,i,!0)}}class q extends M{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)}update(e,r,t="_global"){let i;typeof e=="string"?i=this.get(e,t):i=this.get(e);const s=r(i);typeof e=="string"?this.set(e,s,t):this.set(e,s)}}const w=new me,Ee=new q(w),xe=(o,e)=>w.createStatic({initialValue:o},e);function _e(o,e,r){let t,i,s=r;if(typeof o!="string"){const{key:l,initialValue:A,prefix:E}=o;t=l,i=A,s=E}else t=j(o),i=e;const{prefix:n}=N(s);w.initValue(t,n,i);const f=h.useMemo(()=>l=>(w.initValue(t,n,e),w.addListener(t,n,l),()=>{w.removeListener(t,n,l)}),[]),c=h.useMemo(()=>()=>w.get(t,n)?.value,[]),b=h.useSyncExternalStore(f,c),S=l=>{const A=typeof l=="function"?l(w.get(t,n)?.value):l;A!==b&&(w.setValue(t,n,{value:A}),w.callListeners(t,n))};return w.useEffect(t,n),[b,S]}function Re(o,e,r){let t,i=r;if(typeof o!="string"){const{key:S,prefix:l}=o;t=S,i=l}else t=j(o);const{prefix:s}=N(i),n=h.useRef(void 0),f=h.useMemo(()=>S=>(w.addListener(t,s,S),()=>{w.removeListener(t,s,S)}),[]),c=h.useMemo(()=>()=>{const S=w.get(t,s)?.value,l=e(S);return be(n.current,l)?n.current:l},[]),b=h.useSyncExternalStore(f,c);return w.useEffect(t,s),b}class we 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 M{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)}update(e,r,t="_global"){let i;typeof e=="string"?i=this.get(e,t):i=this.get(e);const s=r(i);typeof e=="string"?this.set(e,s,t):this.set(e,s)}}const T=new we,Ae=new $(T),Te=(o,e)=>T.createStatic({fn:o},e);function ye(o,e,r){let t,i,s=r;if(typeof o!="string"){const{key:l,fn:A,prefix:E}=o;t=l,i=A,s=E}else t=j(o),i=e;const{prefix:n}=N(s);T.initValue(t,n);const f=h.useMemo(()=>l=>(T.initValue(t,n),T.addListener(t,n,l),()=>{T.removeListener(t,n,l)}),[]),c=h.useMemo(()=>()=>T.get(t,n).fnState,[]),b=h.useSyncExternalStore(f,c),S=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 i(...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)=>{S(!1,...l)},forceTrigger:(...l)=>{S(!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){h.useEffect(()=>()=>{Y(`[${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 M{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)}update(e,r,t="_global"){let i;typeof e=="string"?i=this.get(e,t):i=this.get(e);const s=r(i);typeof e=="string"?this.set(e,s,t):this.set(e,s)}}const v=new Oe,Pe=new ee(v),Le=(o,e)=>v.createStatic({subscriber:o},e);function je(o,e,r){let t,i,s=r;if(typeof o!="string"){const{key:m,subscriber:x,prefix:P}=o;t=m,i=x,s=P}else t=j(o),i=e;const{prefix:n}=N(s);v.initValue(t,n);const f=h.useMemo(()=>m=>(v.initValue(t,n),v.addListener(t,n,m),()=>{v.removeListener(t,n,m)}),[]),c=h.useMemo(()=>()=>v.get(t,n).fnState,[]),b=h.useSyncExternalStore(f,c),S=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;Y("triggered !!"),x.fnState={...x.fnState,isLoading:!0,error:void 0},v.callListeners(t,n);try{const P=await i(S,l,A),L=v.get(t,n);L.unsubscribe=P,L.fnState.subscribed=!0}catch(P){const L=v.get(t,n);L.fnState={...L.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=he,p.SharedSubscriptionsApi=ee,p.createSharedFunction=Te,p.createSharedState=xe,p.createSharedSubscription=Le,p.setDevMode=pe,p.sharedFunctionsApi=Ae,p.sharedStatesApi=Ee,p.sharedSubscriptionsApi=Pe,p.useSharedFunction=ye,p.useSharedState=_e,p.useSharedStateSelector=Re,p.useSharedSubscription=je,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
|
package/package.json
CHANGED
package/tests/index.test.tsx
CHANGED
|
@@ -159,6 +159,14 @@ describe('useSharedState', () => {
|
|
|
159
159
|
// Get updated value
|
|
160
160
|
expect(sharedStatesApi.get(sharedCounter)).toBe(200);
|
|
161
161
|
|
|
162
|
+
// Update the value
|
|
163
|
+
act(() => {
|
|
164
|
+
sharedStatesApi.update(sharedCounter, (prev) => prev + 50);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Get updated value after update
|
|
168
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(250);
|
|
169
|
+
|
|
162
170
|
// Clear the value
|
|
163
171
|
act(() => {
|
|
164
172
|
sharedStatesApi.clear(sharedCounter);
|
|
@@ -167,6 +175,26 @@ describe('useSharedState', () => {
|
|
|
167
175
|
// Get value after clear (should be initial value because createSharedState re-initializes it)
|
|
168
176
|
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
|
|
169
177
|
});
|
|
178
|
+
|
|
179
|
+
it('should be able to subscribe to state changes from api', () => {
|
|
180
|
+
const sharedCounter = createSharedState(100);
|
|
181
|
+
|
|
182
|
+
const subscribeCallback = vi.fn();
|
|
183
|
+
|
|
184
|
+
act(() => {
|
|
185
|
+
sharedStatesApi.subscribe(sharedCounter, () => {
|
|
186
|
+
subscribeCallback();
|
|
187
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(200);
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// Update the value
|
|
192
|
+
act(() => {
|
|
193
|
+
sharedStatesApi.set(sharedCounter,200);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
expect(subscribeCallback).toHaveBeenCalledTimes(1);
|
|
197
|
+
});
|
|
170
198
|
});
|
|
171
199
|
|
|
172
200
|
describe('useSharedFunction', () => {
|
|
@@ -310,6 +338,20 @@ describe('useSharedFunction', () => {
|
|
|
310
338
|
expect(updatedState.isLoading).toBe(true);
|
|
311
339
|
expect(updatedState.error).toBe('test error');
|
|
312
340
|
|
|
341
|
+
// Update the state
|
|
342
|
+
act(() => {
|
|
343
|
+
sharedFunctionsApi.update(sharedFunction, (prev) => ({
|
|
344
|
+
fnState: {
|
|
345
|
+
...prev,
|
|
346
|
+
results: 'updated data',
|
|
347
|
+
}
|
|
348
|
+
}));
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
// Get updated state after update
|
|
352
|
+
const updatedState2 = sharedFunctionsApi.get(sharedFunction);
|
|
353
|
+
expect(updatedState2.results).toBe('updated data');
|
|
354
|
+
|
|
313
355
|
// Clear the value
|
|
314
356
|
act(() => {
|
|
315
357
|
sharedFunctionsApi.clear(sharedFunction);
|
|
@@ -374,6 +416,20 @@ describe('useSharedSubscription', () => {
|
|
|
374
416
|
expect(updatedState.isLoading).toBe(true);
|
|
375
417
|
expect(updatedState.error).toBe('test error');
|
|
376
418
|
|
|
419
|
+
// Update the state
|
|
420
|
+
act(() => {
|
|
421
|
+
sharedSubscriptionsApi.update(sharedSubscription, (prev) => ({
|
|
422
|
+
fnState: {
|
|
423
|
+
...prev,
|
|
424
|
+
data: 'updated data',
|
|
425
|
+
}
|
|
426
|
+
}));
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
// Get updated state after update
|
|
430
|
+
const updatedState2 = sharedSubscriptionsApi.get(sharedSubscription);
|
|
431
|
+
expect(updatedState2.data).toBe('updated data');
|
|
432
|
+
|
|
377
433
|
// Clear the value
|
|
378
434
|
act(() => {
|
|
379
435
|
sharedSubscriptionsApi.clear(sharedSubscription);
|
|
@@ -513,6 +569,20 @@ describe('useSharedSubscription', () => {
|
|
|
513
569
|
expect(updatedState.isLoading).toBe(true);
|
|
514
570
|
expect(updatedState.error).toBe('test error');
|
|
515
571
|
|
|
572
|
+
// Update the state
|
|
573
|
+
act(() => {
|
|
574
|
+
sharedSubscriptionsApi.update(sharedSubscription, (prev) => ({
|
|
575
|
+
fnState: {
|
|
576
|
+
...prev,
|
|
577
|
+
data: 'updated data',
|
|
578
|
+
}
|
|
579
|
+
}));
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
// Get updated state after update
|
|
583
|
+
const updatedState2 = sharedSubscriptionsApi.get(sharedSubscription);
|
|
584
|
+
expect(updatedState2.data).toBe('updated data');
|
|
585
|
+
|
|
516
586
|
// Clear the value
|
|
517
587
|
act(() => {
|
|
518
588
|
sharedSubscriptionsApi.clear(sharedSubscription);
|