react-shared-states 1.0.8 → 1.0.12
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 +155 -91
- package/dist/{SharedData.d.ts → SharedValuesManager.d.ts} +28 -17
- package/dist/hooks/index.d.ts +2 -2
- package/dist/hooks/use-shared-function.d.ts +37 -12
- package/dist/hooks/use-shared-state.d.ts +22 -3
- package/dist/hooks/use-shared-subscription.d.ts +44 -16
- package/dist/main.esm.js +480 -395
- package/dist/main.min.js +5 -5
- package/dist/types.d.ts +2 -1
- package/package.json +9 -2
- package/tests/index.test.tsx +309 -5
- package/pnpm-workspace.yaml +0 -2
package/dist/main.min.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* react-shared-states v1.0.
|
|
2
|
+
* react-shared-states v1.0.12
|
|
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(
|
|
8
|
+
(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={};/**
|
|
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 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={};/**
|
|
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 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:
|
|
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} />`,p,v,y,v),ne[v+p]=!0)}if(v=null,b!==void 0&&(r(b),v=""+b),o(i)&&(r(i.key),v=""+i.key),"key"in i){b={};for(var G in i)G!=="key"&&(b[G]=i[G])}else b=i;return v&&A(b,typeof n=="function"?n.displayName||n.name||"Unknown":n),O(n,v,w,j,s(),b,W,U)}function u(n){typeof n=="object"&&n!==null&&n.$$typeof===S&&n._store&&(n._store.validated=1)}var m=g,S=Symbol.for("react.transitional.element"),d=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),Re=Symbol.for("react.profiler"),Te=Symbol.for("react.consumer"),Ae=Symbol.for("react.context"),we=Symbol.for("react.forward_ref"),Pe=Symbol.for("react.suspense"),Oe=Symbol.for("react.suspense_list"),je=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),Le=Symbol.for("react.activity"),ye=Symbol.for("react.client.reference"),D=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q=Object.prototype.hasOwnProperty,Ve=Array.isArray,I=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(n){return n()}};var $,ee={},te=m.react_stack_bottom_frame.bind(m,f)(),re=I(t(f)),ne={};C.Fragment=c,C.jsx=function(n,i,b,p,j){var w=1e4>D.recentlyCreatedOwnerStacks++;return P(n,i,b,!1,p,j,w?Error("react-stack-top-frame"):te,w?I(t(n)):re)},C.jsxs=function(n,i,b,p,j){var w=1e4>D.recentlyCreatedOwnerStacks++;return P(n,i,b,!0,p,j,w?Error("react-stack-top-frame"):te,w?I(t(n)):re)}}()),C}var X;function oe(){return X||(X=1,process.env.NODE_ENV==="production"?M.exports=se():M.exports=ae()),M.exports}var ie=oe();h.isDevMode=!1;const ce=a=>{h.isDevMode=a},N=(...a)=>{h.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...a)},T=a=>{if(!a)throw new Error("Value is empty");return a},F=()=>Math.random().toString(36).substring(2,15),B=g.createContext(void 0),le=({children:a,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=g.useMemo(()=>F(),[])),ie.jsx(B.Provider,{value:{scopeName:e},children:a})},ue=()=>g.useContext(B);class l{data=new Map;defaultValue(){return{}}addListener(e,r,t){this.data.has(l.prefix(e,r))||this.data.set(l.prefix(e,r),{...this.defaultValue,listeners:[]}),this.data.get(l.prefix(e,r)).listeners.push(t)}removeListener(e,r,t){this.data.has(l.prefix(e,r))&&(this.data.get(l.prefix(e,r)).listeners=this.data.get(l.prefix(e,r)).listeners.filter(s=>s!==t))}callListeners(e,r){this.data.has(l.prefix(e,r))&&this.data.get(l.prefix(e,r)).listeners.forEach(t=>t())}init(e,r,t){this.data.has(l.prefix(e,r))||this.data.set(l.prefix(e,r),{...t,listeners:[]})}clearAll(e=!1){e||this.data.forEach(r=>{r.listeners.forEach(t=>t())}),this.data.clear()}clear(e,r,t=!1){t||this.callListeners(e,r),this.data.delete(l.prefix(e,r))}get(e,r){let t=this.has(e,r);if(t)return this.data.get(t)}setValue(e,r,t){this.data.has(l.prefix(e,r))&&this.data.set(l.prefix(e,r),{...this.data.get(l.prefix(e,r)),...t})}has(e,r){return this.data.has(l.prefix(e,r))?l.prefix(e,r):this.data.has(l.prefix(e,"_global"))?l.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){g.useEffect(()=>()=>{t?.(),N(`[${l.prefix(e,r)}]`,"unmount effect"),this.data.get(l.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class Y{constructor(e){this.sharedData=e}get(e,r){e=T(e);const t=r||"_global";return this.sharedData.get(e,t)}set(e,r,t){e=T(e);const s=t||"_global";this.sharedData.setValue(e,s,r)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,s)=>{const[f]=l.extractPrefix(s);if(f===r){this.sharedData.clear(s,f);return}})}resolve(e){const{key:r,prefix:t}=e;return this.get(r,t)}clear(e,r){let t,s;typeof e=="string"?(t=e,s=r||"_global"):(t=e.key,s=e.prefix),this.sharedData.clear(t,s)}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[s,f]=l.extractPrefix(t);e[s]=e[s]||{},e[s][f]=r}),e}}const k=a=>{const e=ue();return{prefix:a??e?.scopeName??"_global"}};class fe extends l{defaultValue(){return{value:void 0}}init(e,r,t){super.init(e,r,{value:t})}setValue(e,r,t){super.setValue(e,r,{value:t})}removeListener(e,r,t){super.removeListener(e,r,t)}}class H extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return R.get(e,t)?.value}set(e,r,t="_global"){e=T(e);const s=t||"_global";R.setValue(e,s,{value:r})}}const R=new fe,de=new H(R),he=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,initialValue:a}};function be(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:u,initialValue:m,prefix:S}=a;t=u,s=m,f=S}else t=T(a),s=e;const{prefix:o}=k(f);R.init(t,o,s);const A=g.useMemo(()=>u=>(R.init(t,o,e),R.addListener(t,o,u),()=>{R.removeListener(t,o,u)}),[]),L=g.useMemo(()=>()=>R.get(t,o)?.value,[]),O=g.useSyncExternalStore(A,L),P=u=>{const m=typeof u=="function"?u(R.get(t,o)?.value):u;m!==O&&(R.setValue(t,o,m),R.callListeners(t,o))};return R.useEffect(t,o),[O,P]}class Se extends l{defaultValue(){return{fnState:{results:void 0,isLoading:!1,error:void 0}}}init(e,r){super.init(e,r,this.defaultValue())}setValue(e,r,t){super.setValue(e,r,t)}}class Z extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return x.get(e,t)?.fnState}set(e,r,t="_global"){e=T(e);const s=t||"_global";x.setValue(e,s,r)}}const x=new Se,ge=new Z(x),pe=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,fn:a}};function ve(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:u,fn:m,prefix:S}=a;t=u,s=m,f=S}else t=T(a),s=e;const{prefix:o}=k(f);x.init(t,o);const A=g.useMemo(()=>u=>(x.init(t,o),x.addListener(t,o,u),()=>{x.removeListener(t,o,u)}),[]),L=g.useMemo(()=>()=>x.get(t,o).fnState,[]),O=g.useSyncExternalStore(A,L),P=async(u,...m)=>{const S=x.get(t,o);if(!u&&(S.fnState.isLoading||S.fnState.results!==void 0))return S.fnState;S.fnState={...S.fnState,isLoading:!0,error:void 0},S.listeners.forEach(d=>d());try{const d=await s(...m);S.fnState={results:d,isLoading:!1,error:void 0}}catch(d){S.fnState={...S.fnState,isLoading:!1,error:d}}S.listeners.forEach(d=>d())};return x.useEffect(t,o),{state:O,trigger:(...u)=>{P(!1,...u)},forceTrigger:(...u)=>{P(!0,...u)},clear:()=>{const u=x.get(t,o);u&&(u.fnState=x.defaultValue().fnState,x.callListeners(t,o))}}}class Ee extends l{defaultValue(){return{fnState:{data:void 0,isLoading:!1,error:void 0,subscribed:!1}}}init(e,r){super.init(e,r,this.defaultValue())}setValue(e,r,t){super.setValue(e,r,t)}useEffect(e,r){g.useEffect(()=>()=>{N(`[${l.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 Q extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return E.get(e,t)?.fnState}set(e,r,t="_global"){e=T(e);const s=t||"_global";E.setValue(e,s,r)}}const E=new Ee,me=new Q(E),xe=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,subscriber:a}};function _e(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:d,subscriber:c,prefix:_}=a;t=d,s=c,f=_}else t=T(a),s=e;const{prefix:o}=k(f);E.init(t,o);const A=g.useMemo(()=>d=>(E.init(t,o),E.addListener(t,o,d),()=>{E.removeListener(t,o,d)}),[]),L=g.useMemo(()=>()=>E.get(t,o).fnState,[]),O=g.useSyncExternalStore(A,L),P=d=>{const c=E.get(t,o);c.fnState={...c.fnState,data:d},c.listeners.forEach(_=>_())},u=d=>{const c=E.get(t,o);c.fnState={...c.fnState,isLoading:!1,data:void 0,error:d},c.listeners.forEach(_=>_())},m=()=>{const d=E.get(t,o);d.fnState={...d.fnState,isLoading:!1},d.listeners.forEach(c=>c())},S=async d=>{const c=E.get(t,o);if(d&&(await E.unsubscribe(t,o),c.fnState={...c.fnState,isLoading:!1,data:void 0,error:void 0,subscribed:!1}),c.fnState.subscribed)return c.fnState;N("triggered !!"),c.fnState={...c.fnState,isLoading:!0,error:void 0},c.listeners.forEach(_=>_());try{c.unsubscribe=await s(P,u,m),c.fnState.subscribed=!0}catch(_){c.fnState={...c.fnState,isLoading:!1,error:_}}c.listeners.forEach(_=>_())};return E.useEffect(t,o),{state:O,trigger:()=>{S(!1)},forceTrigger:()=>{S(!0)},unsubscribe:()=>{E.unsubscribe(t,o)}}}h.SharedFunctionsApi=Z,h.SharedStatesApi=H,h.SharedStatesProvider=le,h.SharedSubscriptionsApi=Q,h.createSharedFunction=pe,h.createSharedState=he,h.createSharedSubscription=xe,h.setDevMode=ce,h.sharedFunctionsApi=ge,h.sharedStatesApi=de,h.sharedSubscriptionsApi=me,h.useSharedFunction=ve,h.useSharedState=be,h.useSharedSubscription=_e,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
|
|
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"})});
|
package/dist/types.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export type PotentialPromise<T> = T | Promise<T>;
|
|
2
2
|
export type AFunction<R = unknown, Args extends unknown[] = unknown[]> = (...args: Args) => PotentialPromise<R>;
|
|
3
3
|
export type Prefix = "_global" | ({} & string);
|
|
4
|
-
export interface
|
|
4
|
+
export interface SharedValue {
|
|
5
5
|
listeners: AFunction[];
|
|
6
|
+
isStatic?: true;
|
|
6
7
|
}
|
|
7
8
|
export interface SharedCreated {
|
|
8
9
|
key: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-shared-states",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Global state made as simple as useState, with zero config, built-in async caching, and automatic scoping.",
|
|
6
6
|
"keywords": [
|
|
@@ -24,6 +24,10 @@
|
|
|
24
24
|
"bugs": {
|
|
25
25
|
"url": "https://github.com/HichemTab-tech/react-shared-states/issues"
|
|
26
26
|
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"react": "^19.1.11",
|
|
29
|
+
"react-dom": "^19.1.11"
|
|
30
|
+
},
|
|
27
31
|
"homepage": "https://github.com/HichemTab-tech/react-shared-states#readme",
|
|
28
32
|
"devDependencies": {
|
|
29
33
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -36,11 +40,14 @@
|
|
|
36
40
|
"react": "^19.1.1",
|
|
37
41
|
"react-dom": "^19.1.1",
|
|
38
42
|
"typescript": "^5.9.2",
|
|
39
|
-
"vite": "
|
|
43
|
+
"vite": "7.1.5",
|
|
40
44
|
"vite-plugin-banner": "^0.8.1",
|
|
41
45
|
"vite-plugin-dts": "^4.5.4",
|
|
42
46
|
"vitest": "^3.2.4"
|
|
43
47
|
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"react-fast-compare": "^3.2.2"
|
|
50
|
+
},
|
|
44
51
|
"scripts": {
|
|
45
52
|
"tsc": "tsc",
|
|
46
53
|
"bump": "node scripts/bumper.js",
|
package/tests/index.test.tsx
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import React from 'react'
|
|
3
|
-
import {
|
|
1
|
+
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
|
|
2
|
+
import React, {useEffect} from 'react'
|
|
3
|
+
import {act, cleanup, fireEvent, render, screen} from '@testing-library/react'
|
|
4
4
|
import {
|
|
5
5
|
createSharedFunction,
|
|
6
|
-
createSharedState,
|
|
6
|
+
createSharedState,
|
|
7
|
+
createSharedSubscription,
|
|
8
|
+
sharedFunctionsApi,
|
|
9
|
+
sharedStatesApi,
|
|
7
10
|
SharedStatesProvider,
|
|
11
|
+
sharedSubscriptionsApi,
|
|
8
12
|
useSharedFunction,
|
|
9
13
|
useSharedState,
|
|
14
|
+
useSharedStateSelector,
|
|
10
15
|
useSharedSubscription
|
|
11
16
|
} from "../src";
|
|
12
|
-
import type {SubscriberEvents} from "../src/hooks/use-shared-subscription";
|
|
17
|
+
import type {Subscriber, SubscriberEvents} from "../src/hooks/use-shared-subscription";
|
|
13
18
|
|
|
14
19
|
// Mocking random to have predictable keys for created states/functions/subscriptions
|
|
15
20
|
vi.mock('../src/lib/utils', async (importActual) => {
|
|
@@ -139,6 +144,29 @@ describe('useSharedState', () => {
|
|
|
139
144
|
|
|
140
145
|
expect(screen.getByTestId('value1').textContent).toBe('15');
|
|
141
146
|
});
|
|
147
|
+
|
|
148
|
+
it('should allow direct api manipulation with createSharedState objects', () => {
|
|
149
|
+
const sharedCounter = createSharedState(100);
|
|
150
|
+
|
|
151
|
+
// Get initial value
|
|
152
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
|
|
153
|
+
|
|
154
|
+
// Set a new value
|
|
155
|
+
act(() => {
|
|
156
|
+
sharedStatesApi.set(sharedCounter, 200);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Get updated value
|
|
160
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(200);
|
|
161
|
+
|
|
162
|
+
// Clear the value
|
|
163
|
+
act(() => {
|
|
164
|
+
sharedStatesApi.clear(sharedCounter);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Get value after clear (should be initial value because createSharedState re-initializes it)
|
|
168
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
|
|
169
|
+
});
|
|
142
170
|
});
|
|
143
171
|
|
|
144
172
|
describe('useSharedFunction', () => {
|
|
@@ -255,6 +283,108 @@ describe('useSharedFunction', () => {
|
|
|
255
283
|
expect(mockApiCall).toHaveBeenCalledTimes(1);
|
|
256
284
|
expect(screen.getByTestId('result').textContent).toBe('result: arg1');
|
|
257
285
|
});
|
|
286
|
+
|
|
287
|
+
it('should allow direct api manipulation with createSharedFunction objects', () => {
|
|
288
|
+
const sharedFunction = createSharedFunction(async (arg: string) => `result: ${arg}`);
|
|
289
|
+
|
|
290
|
+
// Get initial state
|
|
291
|
+
const initialState = sharedFunctionsApi.get(sharedFunction);
|
|
292
|
+
expect(initialState.results).toBeUndefined();
|
|
293
|
+
expect(initialState.isLoading).toBe(false);
|
|
294
|
+
expect(initialState.error).toBeUndefined();
|
|
295
|
+
|
|
296
|
+
// Set a new state
|
|
297
|
+
act(() => {
|
|
298
|
+
sharedFunctionsApi.set(sharedFunction, {
|
|
299
|
+
fnState: {
|
|
300
|
+
results: 'test data',
|
|
301
|
+
isLoading: true,
|
|
302
|
+
error: 'test error',
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// Get updated state
|
|
308
|
+
const updatedState = sharedFunctionsApi.get(sharedFunction);
|
|
309
|
+
expect(updatedState.results).toBe('test data');
|
|
310
|
+
expect(updatedState.isLoading).toBe(true);
|
|
311
|
+
expect(updatedState.error).toBe('test error');
|
|
312
|
+
|
|
313
|
+
// Clear the value
|
|
314
|
+
act(() => {
|
|
315
|
+
sharedFunctionsApi.clear(sharedFunction);
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// Get value after clear (should be initial value)
|
|
319
|
+
const clearedState = sharedFunctionsApi.get(sharedFunction);
|
|
320
|
+
expect(clearedState.results).toBeUndefined();
|
|
321
|
+
expect(clearedState.isLoading).toBe(false);
|
|
322
|
+
expect(clearedState.error).toBeUndefined();
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
describe('useSharedSubscription', () => {
|
|
327
|
+
it('should handle subscription lifecycle', () => {
|
|
328
|
+
const mockSubscriber = vi.fn<Subscriber<string>>((set) => {
|
|
329
|
+
set('initial data');
|
|
330
|
+
return () => {
|
|
331
|
+
};
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
const TestComponent = () => {
|
|
335
|
+
const {state: {data}, trigger} = useSharedSubscription('test-sub', mockSubscriber);
|
|
336
|
+
|
|
337
|
+
useEffect(() => {
|
|
338
|
+
trigger();
|
|
339
|
+
}, []);
|
|
340
|
+
|
|
341
|
+
return <span data-testid="data">{data}</span>;
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
render(<TestComponent/>);
|
|
345
|
+
|
|
346
|
+
expect(mockSubscriber).toHaveBeenCalledTimes(1);
|
|
347
|
+
expect(screen.getByTestId('data').textContent).toBe('initial data');
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it('should allow direct api manipulation with createSharedSubscription objects', () => {
|
|
351
|
+
const mockSubscriber = vi.fn();
|
|
352
|
+
const sharedSubscription = createSharedSubscription(mockSubscriber);
|
|
353
|
+
|
|
354
|
+
// Get initial state
|
|
355
|
+
const initialState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
356
|
+
expect(initialState.data).toBeUndefined();
|
|
357
|
+
expect(initialState.isLoading).toBe(false);
|
|
358
|
+
expect(initialState.error).toBeUndefined();
|
|
359
|
+
|
|
360
|
+
// Set a new state
|
|
361
|
+
act(() => {
|
|
362
|
+
sharedSubscriptionsApi.set(sharedSubscription, {
|
|
363
|
+
fnState: {
|
|
364
|
+
data: 'test data',
|
|
365
|
+
isLoading: true,
|
|
366
|
+
error: 'test error',
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
// Get updated state
|
|
372
|
+
const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
373
|
+
expect(updatedState.data).toBe('test data');
|
|
374
|
+
expect(updatedState.isLoading).toBe(true);
|
|
375
|
+
expect(updatedState.error).toBe('test error');
|
|
376
|
+
|
|
377
|
+
// Clear the value
|
|
378
|
+
act(() => {
|
|
379
|
+
sharedSubscriptionsApi.clear(sharedSubscription);
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// Get value after clear (should be initial value)
|
|
383
|
+
const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
384
|
+
expect(clearedState.data).toBeUndefined();
|
|
385
|
+
expect(clearedState.isLoading).toBe(false);
|
|
386
|
+
expect(clearedState.error).toBeUndefined();
|
|
387
|
+
});
|
|
258
388
|
});
|
|
259
389
|
|
|
260
390
|
describe('useSharedSubscription', () => {
|
|
@@ -355,4 +485,178 @@ describe('useSharedSubscription', () => {
|
|
|
355
485
|
expect(mockSubscriber).toHaveBeenCalledTimes(1);
|
|
356
486
|
expect(screen.getByTestId('data').textContent).toBe('initial data');
|
|
357
487
|
});
|
|
488
|
+
|
|
489
|
+
it('should allow direct api manipulation with createSharedSubscription objects', () => {
|
|
490
|
+
const mockSubscriber = vi.fn();
|
|
491
|
+
const sharedSubscription = createSharedSubscription(mockSubscriber);
|
|
492
|
+
|
|
493
|
+
// Get initial state
|
|
494
|
+
const initialState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
495
|
+
expect(initialState.data).toBeUndefined();
|
|
496
|
+
expect(initialState.isLoading).toBe(false);
|
|
497
|
+
expect(initialState.error).toBeUndefined();
|
|
498
|
+
|
|
499
|
+
// Set a new state
|
|
500
|
+
act(() => {
|
|
501
|
+
sharedSubscriptionsApi.set(sharedSubscription, {
|
|
502
|
+
fnState: {
|
|
503
|
+
data: 'test data',
|
|
504
|
+
isLoading: true,
|
|
505
|
+
error: 'test error',
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
// Get updated state
|
|
511
|
+
const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
512
|
+
expect(updatedState.data).toBe('test data');
|
|
513
|
+
expect(updatedState.isLoading).toBe(true);
|
|
514
|
+
expect(updatedState.error).toBe('test error');
|
|
515
|
+
|
|
516
|
+
// Clear the value
|
|
517
|
+
act(() => {
|
|
518
|
+
sharedSubscriptionsApi.clear(sharedSubscription);
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
// Get value after clear (should be initial value)
|
|
522
|
+
const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
523
|
+
expect(clearedState.data).toBeUndefined();
|
|
524
|
+
expect(clearedState.isLoading).toBe(false);
|
|
525
|
+
expect(clearedState.error).toBeUndefined();
|
|
526
|
+
});
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
describe('useSharedStateSelector', () => {
|
|
530
|
+
const initialState = {a: 1, b: 2, nested: {c: 'hello'}};
|
|
531
|
+
const sharedObjectState = createSharedState(initialState);
|
|
532
|
+
|
|
533
|
+
it('should select a slice of state and only re-render when that slice changes', () => {
|
|
534
|
+
const renderSpyA = vi.fn();
|
|
535
|
+
const renderSpyB = vi.fn();
|
|
536
|
+
|
|
537
|
+
const ComponentA = () => {
|
|
538
|
+
const a = useSharedStateSelector(sharedObjectState, state => state.a);
|
|
539
|
+
renderSpyA();
|
|
540
|
+
return <span data-testid="a-value">{a}</span>;
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
const ComponentB = () => {
|
|
544
|
+
const b = useSharedStateSelector(sharedObjectState, state => state.b);
|
|
545
|
+
renderSpyB();
|
|
546
|
+
return <span data-testid="b-value">{b}</span>;
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
const Controller = () => {
|
|
550
|
+
const [state, setState] = useSharedState(sharedObjectState);
|
|
551
|
+
return (
|
|
552
|
+
<div>
|
|
553
|
+
<button onClick={() => setState(s => ({...s, a: s.a + 1}))}>inc a</button>
|
|
554
|
+
<button onClick={() => setState(s => ({...s, b: s.b + 1}))}>inc b</button>
|
|
555
|
+
<span data-testid="full-state">{JSON.stringify(state)}</span>
|
|
556
|
+
</div>
|
|
557
|
+
);
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
render(
|
|
561
|
+
<>
|
|
562
|
+
<ComponentA/>
|
|
563
|
+
<ComponentB/>
|
|
564
|
+
<Controller/>
|
|
565
|
+
</>
|
|
566
|
+
);
|
|
567
|
+
|
|
568
|
+
// Initial render
|
|
569
|
+
expect(screen.getByTestId('a-value').textContent).toBe('1');
|
|
570
|
+
expect(screen.getByTestId('b-value').textContent).toBe('2');
|
|
571
|
+
expect(renderSpyA).toHaveBeenCalledTimes(1);
|
|
572
|
+
expect(renderSpyB).toHaveBeenCalledTimes(1);
|
|
573
|
+
|
|
574
|
+
// Update 'b', only ComponentB should re-render
|
|
575
|
+
act(() => {
|
|
576
|
+
fireEvent.click(screen.getByText('inc b'));
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
expect(screen.getByTestId('a-value').textContent).toBe('1');
|
|
580
|
+
expect(screen.getByTestId('b-value').textContent).toBe('3');
|
|
581
|
+
expect(renderSpyA).toHaveBeenCalledTimes(1); // Should not re-render
|
|
582
|
+
expect(renderSpyB).toHaveBeenCalledTimes(2); // Should re-render
|
|
583
|
+
|
|
584
|
+
// Update 'a', only ComponentA should re-render
|
|
585
|
+
act(() => {
|
|
586
|
+
fireEvent.click(screen.getByText('inc a'));
|
|
587
|
+
});
|
|
588
|
+
|
|
589
|
+
expect(screen.getByTestId('a-value').textContent).toBe('2');
|
|
590
|
+
expect(screen.getByTestId('b-value').textContent).toBe('3');
|
|
591
|
+
expect(renderSpyA).toHaveBeenCalledTimes(2); // Should re-render
|
|
592
|
+
expect(renderSpyB).toHaveBeenCalledTimes(2); // Should not re-render
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
it('should work with string keys', () => {
|
|
596
|
+
const renderSpy = vi.fn();
|
|
597
|
+
const key = 'string-key-state';
|
|
598
|
+
sharedStatesApi.set(key, {val: 100});
|
|
599
|
+
|
|
600
|
+
const SelectorComponent = () => {
|
|
601
|
+
const val = useSharedStateSelector<{ val: number }, typeof key, number>(key, state => state.val);
|
|
602
|
+
renderSpy();
|
|
603
|
+
return <span data-testid="val">{val}</span>;
|
|
604
|
+
};
|
|
605
|
+
|
|
606
|
+
render(<SelectorComponent/>);
|
|
607
|
+
expect(screen.getByTestId('val').textContent).toBe('100');
|
|
608
|
+
expect(renderSpy).toHaveBeenCalledTimes(1);
|
|
609
|
+
|
|
610
|
+
// Update state
|
|
611
|
+
act(() => {
|
|
612
|
+
sharedStatesApi.set(key, {val: 200});
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
expect(screen.getByTestId('val').textContent).toBe('200');
|
|
616
|
+
expect(renderSpy).toHaveBeenCalledTimes(2);
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
it('should perform deep comparison correctly', () => {
|
|
620
|
+
const renderSpy = vi.fn();
|
|
621
|
+
const nestedState = createSharedState({ a: 1, nested: { c: 'initial' } });
|
|
622
|
+
|
|
623
|
+
const NestedSelector = () => {
|
|
624
|
+
const nested = useSharedStateSelector(nestedState, state => state.nested);
|
|
625
|
+
renderSpy();
|
|
626
|
+
return <span data-testid="nested-c">{nested.c}</span>;
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
const Controller = () => {
|
|
630
|
+
const [, setState] = useSharedState(nestedState);
|
|
631
|
+
return (
|
|
632
|
+
<div>
|
|
633
|
+
<button onClick={() => setState(s => ({ ...s, a: s.a + 1 }))}>update outer</button>
|
|
634
|
+
<button onClick={() => setState(s => ({ ...s, nested: { c: 'updated' } }))}>update inner</button>
|
|
635
|
+
</div>
|
|
636
|
+
);
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
render(
|
|
640
|
+
<>
|
|
641
|
+
<NestedSelector />
|
|
642
|
+
<Controller />
|
|
643
|
+
</>
|
|
644
|
+
);
|
|
645
|
+
|
|
646
|
+
expect(screen.getByTestId('nested-c').textContent).toBe('initial');
|
|
647
|
+
expect(renderSpy).toHaveBeenCalledTimes(1);
|
|
648
|
+
|
|
649
|
+
// Update outer property, should not re-render because the selected object is deep-equal
|
|
650
|
+
act(() => {
|
|
651
|
+
fireEvent.click(screen.getByText('update outer'));
|
|
652
|
+
});
|
|
653
|
+
expect(renderSpy).toHaveBeenCalledTimes(1);
|
|
654
|
+
|
|
655
|
+
// Update inner property, should re-render
|
|
656
|
+
act(() => {
|
|
657
|
+
fireEvent.click(screen.getByText('update inner'));
|
|
658
|
+
});
|
|
659
|
+
expect(screen.getByTestId('nested-c').textContent).toBe('updated');
|
|
660
|
+
expect(renderSpy).toHaveBeenCalledTimes(2);
|
|
661
|
+
});
|
|
358
662
|
});
|
package/pnpm-workspace.yaml
DELETED