react-shared-states 1.0.8 → 1.0.11
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 +424 -29
- package/dist/{SharedData.d.ts → SharedValuesManager.d.ts} +28 -17
- package/dist/hooks/use-shared-function.d.ts +37 -12
- package/dist/hooks/use-shared-state.d.ts +19 -3
- package/dist/hooks/use-shared-subscription.d.ts +44 -16
- package/dist/main.esm.js +372 -369
- package/dist/main.min.js +5 -5
- package/dist/types.d.ts +2 -1
- package/package.json +1 -1
- package/tests/index.test.tsx +173 -5
package/dist/main.min.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* react-shared-states v1.0.
|
|
2
|
+
* react-shared-states v1.0.11
|
|
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(f,p){typeof exports=="object"&&typeof module<"u"?p(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.ReactSharedStates={},f.React))})(this,function(f,p){"use strict";var N={exports:{}},D={};/**
|
|
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 J;function
|
|
16
|
+
*/var J;function ie(){if(J)return D;J=1;var i=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(t,s,c){var a=null;if(c!==void 0&&(a=""+c),s.key!==void 0&&(a=""+s.key),"key"in s){c={};for(var b in s)b!=="key"&&(c[b]=s[b])}else c=s;return s=c.ref,{$$typeof:i,type:t,key:a,ref:s!==void 0?s:null,props:c}}return D.Fragment=e,D.jsx=r,D.jsxs=r,D}var C={};/**
|
|
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 z;function
|
|
24
|
+
*/var z;function oe(){return z||(z=1,process.env.NODE_ENV!=="production"&&function(){function i(n){if(n==null)return null;if(typeof n=="function")return n.$$typeof===De?null:n.displayName||n.name||null;if(typeof n=="string")return n;switch(n){case v:return"Fragment";case O:return"Profiler";case L:return"StrictMode";case Pe:return"Suspense";case Le:return"SuspenseList";case je:return"Activity"}if(typeof n=="object")switch(typeof n.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),n.$$typeof){case h:return"Portal";case we:return(n.displayName||"Context")+".Provider";case Ae:return(n._context.displayName||"Context")+".Consumer";case ye:var o=n.render;return n=n.displayName,n||(n=o.displayName||o.name||"",n=n!==""?"ForwardRef("+n+")":"ForwardRef"),n;case Oe:return o=n.displayName||null,o!==null?o:i(n.type)||"Memo";case $:o=n._payload,n=n._init;try{return i(n(o))}catch{}}return null}function e(n){return""+n}function r(n){try{e(n);var o=!1}catch{o=!0}if(o){o=console;var d=o.error,m=typeof Symbol=="function"&&Symbol.toStringTag&&n[Symbol.toStringTag]||n.constructor.name||"Object";return d.call(o,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",m),e(n)}}function t(n){if(n===v)return"<>";if(typeof n=="object"&&n!==null&&n.$$typeof===$)return"<...>";try{var o=i(n);return o?"<"+o+">":"<...>"}catch{return"<...>"}}function s(){var n=V.A;return n===null?null:n.getOwner()}function c(){return Error("react-stack-top-frame")}function a(n){if(ee.call(n,"key")){var o=Object.getOwnPropertyDescriptor(n,"key").get;if(o&&o.isReactWarning)return!1}return n.key!==void 0}function b(n,o){function d(){te||(te=!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)",o))}d.isReactWarning=!0,Object.defineProperty(n,"key",{get:d,configurable:!0})}function _(){var n=i(this.type);return re[n]||(re[n]=!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.")),n=this.props.ref,n!==void 0?n:null}function y(n,o,d,m,P,A,M,U){return d=A.ref,n={$$typeof:g,type:n,key:o,props:A,_owner:P},(d!==void 0?d:null)!==null?Object.defineProperty(n,"ref",{enumerable:!1,get:_}):Object.defineProperty(n,"ref",{enumerable:!1,value:null}),n._store={},Object.defineProperty(n._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(n,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(n,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(n,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(n.props),Object.freeze(n)),n}function w(n,o,d,m,P,A,M,U){var E=o.children;if(E!==void 0)if(m)if(Ce(E)){for(m=0;m<E.length;m++)l(E[m]);Object.freeze&&Object.freeze(E)}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(E);if(ee.call(o,"key")){E=i(n);var j=Object.keys(o).filter(function(ke){return ke!=="key"});m=0<j.length?"{key: someKey, "+j.join(": ..., ")+": ...}":"{key: someKey}",ae[E+m]||(j=0<j.length?"{"+j.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} />`,
|
|
29
|
+
<%s key={someKey} {...props} />`,m,E,j,E),ae[E+m]=!0)}if(E=null,d!==void 0&&(r(d),E=""+d),a(o)&&(r(o.key),E=""+o.key),"key"in o){d={};for(var G in o)G!=="key"&&(d[G]=o[G])}else d=o;return E&&b(d,typeof n=="function"?n.displayName||n.name||"Unknown":n),y(n,E,A,P,s(),d,M,U)}function l(n){typeof n=="object"&&n!==null&&n.$$typeof===g&&n._store&&(n._store.validated=1)}var x=p,g=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),O=Symbol.for("react.profiler"),Ae=Symbol.for("react.consumer"),we=Symbol.for("react.context"),ye=Symbol.for("react.forward_ref"),Pe=Symbol.for("react.suspense"),Le=Symbol.for("react.suspense_list"),Oe=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),je=Symbol.for("react.activity"),De=Symbol.for("react.client.reference"),V=x.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=Object.prototype.hasOwnProperty,Ce=Array.isArray,W=console.createTask?console.createTask:function(){return null};x={react_stack_bottom_frame:function(n){return n()}};var te,re={},ne=x.react_stack_bottom_frame.bind(x,c)(),se=W(t(c)),ae={};C.Fragment=v,C.jsx=function(n,o,d,m,P){var A=1e4>V.recentlyCreatedOwnerStacks++;return w(n,o,d,!1,m,P,A?Error("react-stack-top-frame"):ne,A?W(t(n)):se)},C.jsxs=function(n,o,d,m,P){var A=1e4>V.recentlyCreatedOwnerStacks++;return w(n,o,d,!0,m,P,A?Error("react-stack-top-frame"):ne,A?W(t(n)):se)}}()),C}var X;function ce(){return X||(X=1,process.env.NODE_ENV==="production"?N.exports=ie():N.exports=oe()),N.exports}var ue=ce();f.isDevMode=!1;const le=i=>{f.isDevMode=i},F=(...i)=>{f.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...i)},k=i=>{if(!i)throw new Error("Value is empty");return i},B=()=>Math.random().toString(36).substring(2,15),H=p.createContext(void 0),fe=({children:i,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=p.useMemo(()=>B(),[])),ue.jsx(H.Provider,{value:{scopeName:e},children:i})},de=()=>p.useContext(H),Z=[];class u{data=new Map;defaultValue(){return{}}addListener(e,r,t){this.data.has(u.prefix(e,r))||this.data.set(u.prefix(e,r),{...this.defaultValue(),listeners:[]}),this.data.get(u.prefix(e,r)).listeners.push(t)}removeListener(e,r,t){this.data.has(u.prefix(e,r))&&(this.data.get(u.prefix(e,r)).listeners=this.data.get(u.prefix(e,r)).listeners.filter(s=>s!==t))}callListeners(e,r){this.data.has(u.prefix(e,r))&&this.data.get(u.prefix(e,r)).listeners.forEach(t=>t())}init(e,r,t,s=!1){this.data.has(u.prefix(e,r))||this.data.set(u.prefix(e,r),{...t,isStatic:s,listeners:[]})}createStatic(e,r){const t=r??r??"_global",s={key:B(),prefix:t,...e};return Z.push(s),this.initStatic(s),s}initStatic(e){const{key:r,prefix:t}=e;this.init(r,t,this.defaultValue(),!0)}clearAll(e=!1,r=!1){this.data.forEach((t,s)=>{const[c,a]=u.extractPrefix(s);this.clear(a,c,e,r)})}clear(e,r,t=!1,s=!1){t||this.callListeners(e,r);const c=this.data.get(u.prefix(e,r));if(!c)return;const a={...c};if(this.data.delete(u.prefix(e,r)),a.isStatic&&!s){const b=Z.find(_=>_.key===e&&_.prefix===r);b&&this.initStatic(b)}}get(e,r){let t=this.has(e,r);if(t)return this.data.get(t)}setValue(e,r,t){this.data.has(u.prefix(e,r))&&this.data.set(u.prefix(e,r),{...this.data.get(u.prefix(e,r)),...t})}has(e,r){return this.data.has(u.prefix(e,r))?u.prefix(e,r):this.data.has(u.prefix(e,"_global"))?u.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){p.useEffect(()=>()=>{t?.(),F(`[${u.prefix(e,r)}]`,"unmount effect"),this.data.get(u.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class Y{constructor(e){this.sharedData=e}get(e,r){let t,s=r;if(typeof e!="string"){const{key:b,prefix:_}=e;t=b,s=_}else t=k(e);const c=s||"_global";return this.sharedData.get(t,c)}set(e,r,t){let s,c=t;if(typeof e!="string"){const{key:b,prefix:_}=e;s=b,c=_}else s=k(e);const a=c||"_global";this.sharedData.setValue(s,a,r)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,s)=>{const[c,a]=u.extractPrefix(s);if(c===r){this.sharedData.clear(a,c);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,c]=u.extractPrefix(t);e[s]=e[s]||{},e[s][c]=r}),e}}const I=i=>{const e=de();return{prefix:i??e?.scopeName??"_global"}};class Se extends u{defaultValue(){return{value:void 0}}initValue(e,r,t,s=!1){super.init(e,r,{value:t},s)}initStatic(e){const{key:r,prefix:t,initialValue:s}=e;this.initValue(r,t,s,!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 T=new Se,pe=new Q(T),he=(i,e)=>T.createStatic({initialValue:i},e);function be(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:l,initialValue:x,prefix:g}=i;t=l,s=x,c=g}else t=k(i),s=e;const{prefix:a}=I(c);T.initValue(t,a,s);const b=p.useMemo(()=>l=>(T.initValue(t,a,e),T.addListener(t,a,l),()=>{T.removeListener(t,a,l)}),[]),_=p.useMemo(()=>()=>T.get(t,a)?.value,[]),y=p.useSyncExternalStore(b,_),w=l=>{const x=typeof l=="function"?l(T.get(t,a)?.value):l;x!==y&&(T.setValue(t,a,{value:x}),T.callListeners(t,a))};return T.useEffect(t,a),[y,w]}class ge extends u{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 K 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 R=new ge,ve=new K(R),me=(i,e)=>R.createStatic({fn:i},e);function Ee(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:l,fn:x,prefix:g}=i;t=l,s=x,c=g}else t=k(i),s=e;const{prefix:a}=I(c);R.initValue(t,a);const b=p.useMemo(()=>l=>(R.initValue(t,a),R.addListener(t,a,l),()=>{R.removeListener(t,a,l)}),[]),_=p.useMemo(()=>()=>R.get(t,a).fnState,[]),y=p.useSyncExternalStore(b,_),w=async(l,...x)=>{const g=R.get(t,a);if(!l&&(g.fnState.isLoading||g.fnState.results!==void 0))return g.fnState;g.fnState={...g.fnState,isLoading:!0,error:void 0},R.callListeners(t,a);try{const h=await s(...x);g.fnState={results:h,isLoading:!1,error:void 0}}catch(h){g.fnState={...g.fnState,isLoading:!1,error:h}}R.callListeners(t,a)};return R.useEffect(t,a),{state:y,trigger:(...l)=>{w(!1,...l)},forceTrigger:(...l)=>{w(!0,...l)},clear:()=>{const l=R.get(t,a);l&&(l.fnState=R.defaultValue().fnState,R.callListeners(t,a))}}}class xe extends u{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){p.useEffect(()=>()=>{F(`[${u.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{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 S=new xe,Re=new q(S),_e=(i,e)=>S.createStatic({subscriber:i},e);function Te(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:h,subscriber:v,prefix:L}=i;t=h,s=v,c=L}else t=k(i),s=e;const{prefix:a}=I(c);S.initValue(t,a);const b=p.useMemo(()=>h=>(S.initValue(t,a),S.addListener(t,a,h),()=>{S.removeListener(t,a,h)}),[]),_=p.useMemo(()=>()=>S.get(t,a).fnState,[]),y=p.useSyncExternalStore(b,_),w=h=>{const v=S.get(t,a);v.fnState={...v.fnState,data:h},S.callListeners(t,a)},l=h=>{const v=S.get(t,a);v.fnState={...v.fnState,isLoading:!1,data:void 0,error:h},S.callListeners(t,a)},x=()=>{const h=S.get(t,a);h.fnState={...h.fnState,isLoading:!1},S.callListeners(t,a)},g=async h=>{const v=S.get(t,a);if(h&&(await S.unsubscribe(t,a),v.fnState={...v.fnState,isLoading:!1,data:void 0,error:void 0,subscribed:!1}),v.fnState.subscribed)return v.fnState;F("triggered !!"),v.fnState={...v.fnState,isLoading:!0,error:void 0},S.callListeners(t,a);try{const L=await s(w,l,x),O=S.get(t,a);O.unsubscribe=L,O.fnState.subscribed=!0}catch(L){const O=S.get(t,a);O.fnState={...O.fnState,isLoading:!1,error:L}}S.callListeners(t,a)};return S.useEffect(t,a),{state:y,trigger:()=>{g(!1)},forceTrigger:()=>{g(!0)},unsubscribe:()=>{S.unsubscribe(t,a)}}}f.SharedFunctionsApi=K,f.SharedStatesApi=Q,f.SharedStatesProvider=fe,f.SharedSubscriptionsApi=q,f.createSharedFunction=me,f.createSharedState=he,f.createSharedSubscription=_e,f.setDevMode=le,f.sharedFunctionsApi=ve,f.sharedStatesApi=pe,f.sharedSubscriptionsApi=Re,f.useSharedFunction=Ee,f.useSharedState=be,f.useSharedSubscription=Te,Object.defineProperty(f,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
package/tests/index.test.tsx
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
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,
|
|
10
14
|
useSharedSubscription
|
|
11
15
|
} from "../src";
|
|
12
|
-
import type {SubscriberEvents} from "../src/hooks/use-shared-subscription";
|
|
16
|
+
import type {Subscriber, SubscriberEvents} from "../src/hooks/use-shared-subscription";
|
|
13
17
|
|
|
14
18
|
// Mocking random to have predictable keys for created states/functions/subscriptions
|
|
15
19
|
vi.mock('../src/lib/utils', async (importActual) => {
|
|
@@ -139,6 +143,29 @@ describe('useSharedState', () => {
|
|
|
139
143
|
|
|
140
144
|
expect(screen.getByTestId('value1').textContent).toBe('15');
|
|
141
145
|
});
|
|
146
|
+
|
|
147
|
+
it('should allow direct api manipulation with createSharedState objects', () => {
|
|
148
|
+
const sharedCounter = createSharedState(100);
|
|
149
|
+
|
|
150
|
+
// Get initial value
|
|
151
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
|
|
152
|
+
|
|
153
|
+
// Set a new value
|
|
154
|
+
act(() => {
|
|
155
|
+
sharedStatesApi.set(sharedCounter, 200);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// Get updated value
|
|
159
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(200);
|
|
160
|
+
|
|
161
|
+
// Clear the value
|
|
162
|
+
act(() => {
|
|
163
|
+
sharedStatesApi.clear(sharedCounter);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// Get value after clear (should be initial value because createSharedState re-initializes it)
|
|
167
|
+
expect(sharedStatesApi.get(sharedCounter)).toBe(100);
|
|
168
|
+
});
|
|
142
169
|
});
|
|
143
170
|
|
|
144
171
|
describe('useSharedFunction', () => {
|
|
@@ -255,6 +282,108 @@ describe('useSharedFunction', () => {
|
|
|
255
282
|
expect(mockApiCall).toHaveBeenCalledTimes(1);
|
|
256
283
|
expect(screen.getByTestId('result').textContent).toBe('result: arg1');
|
|
257
284
|
});
|
|
285
|
+
|
|
286
|
+
it('should allow direct api manipulation with createSharedFunction objects', () => {
|
|
287
|
+
const sharedFunction = createSharedFunction(async (arg: string) => `result: ${arg}`);
|
|
288
|
+
|
|
289
|
+
// Get initial state
|
|
290
|
+
const initialState = sharedFunctionsApi.get(sharedFunction);
|
|
291
|
+
expect(initialState.results).toBeUndefined();
|
|
292
|
+
expect(initialState.isLoading).toBe(false);
|
|
293
|
+
expect(initialState.error).toBeUndefined();
|
|
294
|
+
|
|
295
|
+
// Set a new state
|
|
296
|
+
act(() => {
|
|
297
|
+
sharedFunctionsApi.set(sharedFunction, {
|
|
298
|
+
fnState: {
|
|
299
|
+
results: 'test data',
|
|
300
|
+
isLoading: true,
|
|
301
|
+
error: 'test error',
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
// Get updated state
|
|
307
|
+
const updatedState = sharedFunctionsApi.get(sharedFunction);
|
|
308
|
+
expect(updatedState.results).toBe('test data');
|
|
309
|
+
expect(updatedState.isLoading).toBe(true);
|
|
310
|
+
expect(updatedState.error).toBe('test error');
|
|
311
|
+
|
|
312
|
+
// Clear the value
|
|
313
|
+
act(() => {
|
|
314
|
+
sharedFunctionsApi.clear(sharedFunction);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// Get value after clear (should be initial value)
|
|
318
|
+
const clearedState = sharedFunctionsApi.get(sharedFunction);
|
|
319
|
+
expect(clearedState.results).toBeUndefined();
|
|
320
|
+
expect(clearedState.isLoading).toBe(false);
|
|
321
|
+
expect(clearedState.error).toBeUndefined();
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
describe('useSharedSubscription', () => {
|
|
326
|
+
it('should handle subscription lifecycle', () => {
|
|
327
|
+
const mockSubscriber = vi.fn<Subscriber<string>>((set) => {
|
|
328
|
+
set('initial data');
|
|
329
|
+
return () => {
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
const TestComponent = () => {
|
|
334
|
+
const {state: {data}, trigger} = useSharedSubscription('test-sub', mockSubscriber);
|
|
335
|
+
|
|
336
|
+
useEffect(() => {
|
|
337
|
+
trigger();
|
|
338
|
+
}, []);
|
|
339
|
+
|
|
340
|
+
return <span data-testid="data">{data}</span>;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
render(<TestComponent/>);
|
|
344
|
+
|
|
345
|
+
expect(mockSubscriber).toHaveBeenCalledTimes(1);
|
|
346
|
+
expect(screen.getByTestId('data').textContent).toBe('initial data');
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('should allow direct api manipulation with createSharedSubscription objects', () => {
|
|
350
|
+
const mockSubscriber = vi.fn();
|
|
351
|
+
const sharedSubscription = createSharedSubscription(mockSubscriber);
|
|
352
|
+
|
|
353
|
+
// Get initial state
|
|
354
|
+
const initialState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
355
|
+
expect(initialState.data).toBeUndefined();
|
|
356
|
+
expect(initialState.isLoading).toBe(false);
|
|
357
|
+
expect(initialState.error).toBeUndefined();
|
|
358
|
+
|
|
359
|
+
// Set a new state
|
|
360
|
+
act(() => {
|
|
361
|
+
sharedSubscriptionsApi.set(sharedSubscription, {
|
|
362
|
+
fnState: {
|
|
363
|
+
data: 'test data',
|
|
364
|
+
isLoading: true,
|
|
365
|
+
error: 'test error',
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
// Get updated state
|
|
371
|
+
const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
372
|
+
expect(updatedState.data).toBe('test data');
|
|
373
|
+
expect(updatedState.isLoading).toBe(true);
|
|
374
|
+
expect(updatedState.error).toBe('test error');
|
|
375
|
+
|
|
376
|
+
// Clear the value
|
|
377
|
+
act(() => {
|
|
378
|
+
sharedSubscriptionsApi.clear(sharedSubscription);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
// Get value after clear (should be initial value)
|
|
382
|
+
const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
383
|
+
expect(clearedState.data).toBeUndefined();
|
|
384
|
+
expect(clearedState.isLoading).toBe(false);
|
|
385
|
+
expect(clearedState.error).toBeUndefined();
|
|
386
|
+
});
|
|
258
387
|
});
|
|
259
388
|
|
|
260
389
|
describe('useSharedSubscription', () => {
|
|
@@ -355,4 +484,43 @@ describe('useSharedSubscription', () => {
|
|
|
355
484
|
expect(mockSubscriber).toHaveBeenCalledTimes(1);
|
|
356
485
|
expect(screen.getByTestId('data').textContent).toBe('initial data');
|
|
357
486
|
});
|
|
487
|
+
|
|
488
|
+
it('should allow direct api manipulation with createSharedSubscription objects', () => {
|
|
489
|
+
const mockSubscriber = vi.fn();
|
|
490
|
+
const sharedSubscription = createSharedSubscription(mockSubscriber);
|
|
491
|
+
|
|
492
|
+
// Get initial state
|
|
493
|
+
const initialState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
494
|
+
expect(initialState.data).toBeUndefined();
|
|
495
|
+
expect(initialState.isLoading).toBe(false);
|
|
496
|
+
expect(initialState.error).toBeUndefined();
|
|
497
|
+
|
|
498
|
+
// Set a new state
|
|
499
|
+
act(() => {
|
|
500
|
+
sharedSubscriptionsApi.set(sharedSubscription, {
|
|
501
|
+
fnState: {
|
|
502
|
+
data: 'test data',
|
|
503
|
+
isLoading: true,
|
|
504
|
+
error: 'test error',
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
// Get updated state
|
|
510
|
+
const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
511
|
+
expect(updatedState.data).toBe('test data');
|
|
512
|
+
expect(updatedState.isLoading).toBe(true);
|
|
513
|
+
expect(updatedState.error).toBe('test error');
|
|
514
|
+
|
|
515
|
+
// Clear the value
|
|
516
|
+
act(() => {
|
|
517
|
+
sharedSubscriptionsApi.clear(sharedSubscription);
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// Get value after clear (should be initial value)
|
|
521
|
+
const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
|
|
522
|
+
expect(clearedState.data).toBeUndefined();
|
|
523
|
+
expect(clearedState.isLoading).toBe(false);
|
|
524
|
+
expect(clearedState.error).toBeUndefined();
|
|
525
|
+
});
|
|
358
526
|
});
|