react-hooks-global-states 15.0.8 → 15.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/GlobalStore.d.ts +10 -2
- package/GlobalStore.js +1 -1
- package/README.md +8 -9
- package/createContext.d.ts +3 -3
- package/createContext.js +1 -1
- package/createGlobalState.d.ts +1 -1
- package/createGlobalState.js +1 -1
- package/index.d.ts +4 -4
- package/isRecord.js +1 -1
- package/package.json +2 -10
- package/shallowCompare.js +1 -1
- package/throwWrongKeyOnActionCollectionConfig.js +1 -1
- package/types.d.ts +13 -6
- package/uniqueId.d.ts +1 -1
- package/uniqueId.js +1 -1
- package/webpack.config.js +1 -16
package/GlobalStore.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import type { ActionCollectionConfig, GlobalStoreCallbacks, ActionCollectionResult, MetadataSetter, SubscriberParameters, StateHook, BaseMetadata, StateChanges, StoreTools, ObservableFragment, AnyFunction, ReadonlyHook, ReadonlyStateApi, SubscribeToState } from './types';
|
|
1
|
+
import type { ActionCollectionConfig, GlobalStoreCallbacks, ActionCollectionResult, MetadataSetter, SubscriberParameters, StateHook, BaseMetadata, StateChanges, StoreTools, ObservableFragment, AnyFunction, ReadonlyHook, ReadonlyStateApi, SubscribeToState, CleanupFunction } from './types';
|
|
2
2
|
/**
|
|
3
3
|
* The GlobalStore class is the main class of the library and it is used to create a GlobalStore instances
|
|
4
4
|
* */
|
|
5
5
|
export declare class GlobalStore<State, Metadata extends BaseMetadata, ActionsConfig extends ActionCollectionConfig<State, Metadata> | undefined | unknown, PublicStateMutator = keyof ActionsConfig extends never | undefined ? React.Dispatch<React.SetStateAction<State>> : ActionCollectionResult<State, Metadata, NonNullable<ActionsConfig>>> {
|
|
6
|
+
protected cleanupFunctions: CleanupFunction[];
|
|
6
7
|
protected _name: string;
|
|
7
8
|
actionsConfig: ActionsConfig | null;
|
|
8
9
|
callbacks: GlobalStoreCallbacks<State, PublicStateMutator, Metadata> | null;
|
|
@@ -33,7 +34,7 @@ export declare class GlobalStore<State, Metadata extends BaseMetadata, ActionsCo
|
|
|
33
34
|
/**
|
|
34
35
|
* This method is meant to be overridden by the extended classes
|
|
35
36
|
*/
|
|
36
|
-
protected onInit?: () => void;
|
|
37
|
+
protected onInit?: () => void | CleanupFunction;
|
|
37
38
|
/**
|
|
38
39
|
* This method is meant to be overridden by the extended classes
|
|
39
40
|
*/
|
|
@@ -124,7 +125,14 @@ export declare class GlobalStore<State, Metadata extends BaseMetadata, ActionsCo
|
|
|
124
125
|
storeTools: StoreTools<State, PublicStateMutator, Metadata>;
|
|
125
126
|
};
|
|
126
127
|
protected removeSubscriptions: () => void;
|
|
128
|
+
protected executeCleanupTasks: () => void;
|
|
127
129
|
dispose: () => void;
|
|
130
|
+
/**
|
|
131
|
+
* @description Resets the store to a new initial state and re-runs initialization.
|
|
132
|
+
*
|
|
133
|
+
* This method is reserved for advanced use cases and testing scenarios, use with caution.
|
|
134
|
+
*/
|
|
135
|
+
reset: (state: State, metadata: Metadata) => void;
|
|
128
136
|
__devtools_getLifeCycleStoreToolsWrapper?: (logsPrefix: string) => StoreTools<State, PublicStateMutator, Metadata>;
|
|
129
137
|
__devtools_initialize_getStoreActionsMapWrapped?: () => {
|
|
130
138
|
actions: PublicStateMutator extends AnyFunction ? null : PublicStateMutator;
|
package/GlobalStore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t,e;t=this,e=(t,e,r,n,o,i)=>(()=>{"use strict";var a={78:e=>{e.exports=t},155:t=>{t.exports=e},361:t=>{t.exports=r},487:t=>{t.exports=n},506:t=>{t.exports=o},673:t=>{t.exports=i},811:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});var r=globalThis;r.isDevToolsPresent=Boolean(r.REACT_GLOBAL_STATE_HOOK_DEBUG),e.default=r}},s={};function u(t){var e=s[t];if(void 0!==e)return e.exports;var r=s[t]={exports:{}};return a[t](r,r.exports,u),r.exports}var c={};return(()=>{var t=c;function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function r(t,e){if(t){if("string"==typeof t)return n(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(t,e):void 0}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function o(){o=function(){return r};var t,r={},n=Object.prototype,i=n.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},s="function"==typeof Symbol?Symbol:{},u=s.iterator||"@@iterator",c=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function d(t,e,r,n){var o=e&&e.prototype instanceof m?e:m,i=Object.create(o.prototype),s=new P(n||[]);return a(i,"_invoke",{value:C(t,r,s)}),i}function h(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}r.wrap=d;var v="suspendedStart",p="suspendedYield",b="executing",y="completed",g={};function m(){}function S(){}function w(){}var j={};f(j,u,(function(){return this}));var O=Object.getPrototypeOf,x=O&&O(O(q([])));x&&x!==n&&i.call(x,u)&&(j=x);var E=w.prototype=m.prototype=Object.create(j);function _(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,r){function n(o,a,s,u){var c=h(t[o],t,a);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==e(f)&&i.call(f,"__await")?r.resolve(f.__await).then((function(t){n("next",t,s,u)}),(function(t){n("throw",t,s,u)})):r.resolve(f).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,u)}))}u(c.arg)}var o;a(this,"_invoke",{value:function(t,e){function i(){return new r((function(r,o){n(t,e,r,o)}))}return o=o?o.then(i,i):i()}})}function C(e,r,n){var o=v;return function(i,a){if(o===b)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=L(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===v)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=b;var c=h(e,r,n);if("normal"===c.type){if(o=n.done?y:p,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function L(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,L(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=h(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function A(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(A,this),this.reset(!0)}function q(r){if(r||""===r){var n=r[u];if(n)return n.call(r);if("function"==typeof r.next)return r;if(!isNaN(r.length)){var o=-1,a=function e(){for(;++o<r.length;)if(i.call(r,o))return e.value=r[o],e.done=!1,e;return e.value=t,e.done=!0,e};return a.next=a}}throw new TypeError(e(r)+" is not iterable")}return S.prototype=w,a(E,"constructor",{value:w,configurable:!0}),a(w,"constructor",{value:S,configurable:!0}),S.displayName=f(w,l,"GeneratorFunction"),r.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===S||"GeneratorFunction"===(e.displayName||e.name))},r.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,f(t,l,"GeneratorFunction")),t.prototype=Object.create(E),t},r.awrap=function(t){return{__await:t}},_(k.prototype),f(k.prototype,c,(function(){return this})),r.AsyncIterator=k,r.async=function(t,e,n,o,i){void 0===i&&(i=Promise);var a=new k(d(t,e,n,o),i);return r.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),f(E,l,"Generator"),f(E,u,(function(){return this})),f(E,"toString",(function(){return"[object Generator]"})),r.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},r.values=q,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&i.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,o){return s.type="throw",s.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var u=i.call(a,"catchLoc"),c=i.call(a,"finallyLoc");if(u&&c){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:q(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},r}function i(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,s(n.key),n)}}function a(t,e,r){return e&&i(t.prototype,e),r&&i(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(t){var r=function(t){if("object"!=e(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=e(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==e(r)?r:r+""}var l,f=Object.create?function(t,e,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]},d=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e},h=(l=function(t){return l=Object.getOwnPropertyNames||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[e.length]=r);return e},l(t)},function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r=l(t),n=0;n<r.length;n++)"default"!==r[n]&&f(e,t,r[n]);return d(e,t),e}),v=function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalStore=void 0,t.createObservable=O,t.createSelectorHook=x;var p=u(155),b=v(u(506)),y=v(u(487)),g=h(u(673)),m=v(u(361)),S=v(u(78)),w=v(u(811)),j=a((function t(e){var n,i,a=this,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{metadata:{}};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.actionsConfig=null,this.callbacks=null,this.actions=null,this.subscribers=new Set,this.initialize=function(){return t=a,e=void 0,r=o().mark((function t(){var e,r,n,i,a,s,u,c,l,f,d,h;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=null!==(r=null===(e=this.__devtools_initialize_getStoreActionsMapWrapped)||void 0===e?void 0:e.call(this))&&void 0!==r?r:this.getStoreActionsMap(),c=u.actions,l=u.storeTools,this.actions=c,this.storeTools=l,this.use=this.getMainHook(),null===(n=this.onInit)||void 0===n||n.call(this),f=null!==(i=this.callbacks)&&void 0!==i?i:{},d=f.onInit){t.next=9;break}return t.abrupt("return");case 9:h=null!==(s=null===(a=this.__devtools_getLifeCycleStoreToolsWrapper)||void 0===a?void 0:a.call(this,"config/onInit/"))&&void 0!==s?s:l,null==d||d(h);case 11:case"end":return t.stop()}}),t,this)})),new(e||(e=Promise))((function(n,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?n(t.value):(r=t.value,r instanceof e?r:new e((function(t){t(r)}))).then(i,a)}s((r=r.apply(t,[])).next())}));var t,e,r},this.executeSetStateForSubscriber=function(t,e){var r=t.selector,n=t.onStoreChange,o=t.currentState,i=t.isEqualRoot,s=void 0===i?function(t,e){return t===e}:i,u=t.isEqual,c=void 0===u?function(t,e){return t===e}:u;if(!e.forceUpdate&&s(e.currentState,e.newState))return{didUpdate:!1};var l=r?r(e.newState):e.newState;return!e.forceUpdate&&c(o,l)?{didUpdate:!1}:(a.partialUpdateSubscription(t,{currentState:l}),n({state:l},{identifier:e.identifier}),{didUpdate:!0})},this.setActualStateWithoutValidations=function(t,e){var n=e.forceUpdate,o=e.identifier,i=a.state;if(n||i!==t){a.state=t;var s,u={forceUpdate:n,newState:t,currentState:i,identifier:o},c=function(t){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=r(t))){e&&(t=e);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==e.return||e.return()}finally{if(s)throw i}}}}(a.subscribers.values());try{for(c.s();!(s=c.n()).done;){var l=s.value;a.executeSetStateForSubscriber(l,u)}}catch(t){c.e(t)}finally{c.f()}}},this.setMetadata=function(t){var e=(0,b.default)(t)?t(a.metadata):t;a.metadata=e},this.getMetadata=function(){return a.metadata},this.getState=function(){return a.state},this.subscribe=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];var n,o=e[0],i=e[1],s=e[2],u=(0,b.default)(i),c=u?o:void 0,l=u?i:o,f=null!==(n=u?s:i)&&void 0!==n?n:void 0,d=c?c(a.state):a.state;(null==f?void 0:f.skipFirst)||l(d);var h=Object.assign({selector:c,currentState:d,onStoreChange:function(t){var e=t.state;return l(e)}},f);return a.subscribeCallback(h),function(){a.subscribers.delete(h)}},this.subscribeCallback=function(t){var e,r;return null===(r=null===(e=a.callbacks)||void 0===e?void 0:e.onSubscribed)||void 0===r||r.call(e,a.storeTools,t),a.subscribers.add(t),function(){a.subscribers.delete(t)}},this.partialUpdateSubscription=function(t,e){Object.assign(t,e)},this.getMainHook=function(){var t="globalHook:".concat(a._name),e=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];(0,p.useDebugValue)(t);var n=(0,g.isArray)(r)?{dependencies:r}:null!=r?r:{},o=(0,p.useRef)(null),i=function(t){return(0,b.default)(e)?e(t):t};o.current=o.current?o.current:Object.assign({selector:i,currentState:i(a.state),onStoreChange:function(){throw new Error("Callback not set")}},n);var s=o.current.dependencies,u=null==n?void 0:n.dependencies,c=Object.assign(Object.assign({},n),{selector:i,dependencies:u});a.partialUpdateSubscription(o.current,c);var l=(0,p.useMemo)((function(){var t=function(){return o.current.currentState};return{subscribe:function(t){return o.current.onStoreChange=t,a.subscribeCallback(o.current)},getSnapshot:t,getServerSnapshot:t}}),[]),f=l.subscribe,d=l.getSnapshot,h=l.getServerSnapshot;return a.reselectIfDependenciesChanged({subscription:o.current,newDependencies:u,currentDependencies:s}),[(0,p.useSyncExternalStore)(f,d,h),a.getStateOrchestrator(),a.metadata]},r=a.setMetadata,n=a.getMetadata,o=a.actions,i=a.actions?null:a.setState.bind(a),s=a,u={actions:o,createObservable:a.createObservable.bind(s),createSelectorHook:a.createSelectorHook.bind(s),dispose:a.dispose.bind(a),getMetadata:n,getState:a.getState.bind(a),setMetadata:r,setState:i,subscribe:a.subscribe.bind(a),subscribers:a.subscribers,use:e,select:function(){return e.apply(void 0,arguments)[0]}};return Object.assign(e,u),e},this.reselectIfDependenciesChanged=function(t){var e=t.subscription,r=t.newDependencies,n=t.currentDependencies;e.selector&&n!==r&&((null==n?void 0:n.length)===(null==r?void 0:r.length)&&(0,g.default)(n,r)||a.partialUpdateSubscription(e,{currentState:e.selector(a.state)}))},this.createSelectorHook=x,this.createObservable=O,this.getStateOrchestrator=function(){return a.actions?a.actions:a.setState},this.setState=function(t){var e,r,n,o,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=i.forceUpdate,u=i.identifier,c=a.state,l=(0,b.default)(t)?t(c):t;if(s||a.state!==l){var f=a.setActualStateWithoutValidations,d={previousState:c,state:l,identifier:u},h=Object.assign(Object.assign(Object.assign({},a.storeTools),d),{setState:f});if((null===(e=a.callbacks)||void 0===e?void 0:e.computePreventStateChange)&&(null===(n=null===(r=a.callbacks)||void 0===r?void 0:r.computePreventStateChange)||void 0===n?void 0:n.call(r,h)))return;a.setActualStateWithoutValidations(l,{forceUpdate:s,identifier:u});var v=a.onStateChanged,p=null===(o=a.callbacks)||void 0===o?void 0:o.onStateChanged;null==v||v(h),null==p||p(h)}},this.getStoreActionsMap=function(){var t=a.actionsConfig,e=a.getMetadata,r=a.getState,n={setMetadata:a.setMetadata,getMetadata:e,getState:r,setState:a.setState,subscribe:a.subscribe,actions:null};if(!(0,y.default)(t))return{actions:null,storeTools:n};var o={};n.actions=o;for(var i=Object.keys(t),u=function(){var e,r,i,a=l[c];Object.assign(o,(e={},i=function(){for(var e=t[a],r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var u=e.apply(o,i);return"function"!=typeof u&&(0,m.default)(a),u.call(o,n)},(r=s(r=a))in e?Object.defineProperty(e,r,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[r]=i,e))},c=0,l=i;c<l.length;c++)u();return{actions:o,storeTools:n}},this.removeSubscriptions=function(){a.subscribers.clear()},this.dispose=function(){a.removeSubscriptions()};var c=u.metadata,l=u.callbacks,f=u.actions,d=u.name;if(this.state=e,this._name=null!=d?d:(0,S.default)("gs:"),this.metadata=null!=c?c:{},this.callbacks=null!=l?l:null,this.actionsConfig=null!=f?f:null,w.default.isDevToolsPresent){var h=null!==(n=(new Error).stack)&&void 0!==n?n:"";null===(i=w.default.REACT_GLOBAL_STATE_HOOK_DEBUG)||void 0===i||i.call(w.default,this,u,h)}this.constructor!==t||this.initialize()}));function O(t,e){var r=null==e?void 0:e.name,n=null==e?void 0:e.isEqualRoot,o=null==e?void 0:e.isEqual,i=this.getState(),a=(null!=t?t:function(t){return t})(i),s=new j(a,{name:null!=r?r:(0,S.default)("sh:")}),u=this.subscribe((function(e){if(!(null!=n?n:Object.is)(i,e)){i=e;var r=t(e);(null!=o?o:Object.is)(a,r)||(a=r,s.setState(r))}}),{skipFirst:!0}),c=s.subscribe.bind(s),l={getState:s.getState.bind(s),subscribe:s.subscribe.bind(s),createSelectorHook:x.bind(c),createObservable:O.bind(c),dispose:function(){u(),s.dispose()},subscribers:s.subscribers};return Object.assign(c,l),c}function x(t,e){var n=null==e?void 0:e.name,o=null==e?void 0:e.isEqualRoot,i=null==e?void 0:e.isEqual,a=this.getState(),s=(null!=t?t:function(t){return t})(a),u=new j(s,{name:null!=n?n:(0,S.default)("sh:")}),c=this.subscribe((function(e){if(!(null!=o?o:Object.is)(a,e)){a=e;var r=t(e);(null!=i?i:Object.is)(s,r)||(s=r,u.setState(r))}}),{skipFirst:!0}),l=function(){return(t=u.use.apply(u,arguments),function(t){if(Array.isArray(t))return t}(t)||function(t){var e=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=e){var r,n,o,i,a=[],s=!0,u=!1;try{for(o=(e=e.call(t)).next;!(s=(r=o.call(e)).done)&&(a.push(r.value),1!==a.length);s=!0);}catch(t){u=!0,n=t}finally{try{if(!s&&null!=e.return&&(i=e.return(),Object(i)!==i))return}finally{if(u)throw n}}return a}}(t)||r(t,1)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];var t},f={getState:function(){return u.getState()},subscribe:u.subscribe.bind(u),createSelectorHook:x.bind(l),createObservable:O.bind(l),dispose:function(){c(),u.dispose()},subscribers:u.subscribers};return Object.assign(l,f),l}t.GlobalStore=j,t.default=j})(),c})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js")):"function"==typeof define&&define.amd?define(["./uniqueId.js","react","./throwWrongKeyOnActionCollectionConfig.js","./isRecord.js","json-storage-formatter/isFunction","./shallowCompare.js"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js")):t["react-hooks-global-states"]=e(t["./uniqueId.js"],t.react,t["./throwWrongKeyOnActionCollectionConfig.js"],t["./isRecord.js"],t["json-storage-formatter/isFunction"],t["./shallowCompare.js"]);
|
|
1
|
+
var t,e;t=this,e=(t,e,s,i,n,o)=>(()=>{"use strict";var r={78:e=>{e.exports=t},132:function(t,e,s){var i,n=this&&this.__createBinding||(Object.create?function(t,e,s,i){void 0===i&&(i=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,i,n)}:function(t,e,s,i){void 0===i&&(i=s),t[i]=e[s]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),r=this&&this.__importStar||(i=function(t){return i=Object.getOwnPropertyNames||function(t){var e=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[e.length]=s);return e},i(t)},function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var s=i(t),r=0;r<s.length;r++)"default"!==s[r]&&n(e,t,s[r]);return o(e,t),e}),a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.GlobalStore=void 0,e.createObservable=g,e.createSelectorHook=v;const l=s(155),c=a(s(506)),u=a(s(487)),d=r(s(673)),h=a(s(361)),b=a(s(78)),p=a(s(627));class f{constructor(t,e={metadata:{}}){var s,i;this.cleanupFunctions=[],this.actionsConfig=null,this.callbacks=null,this.actions=null,this.subscribers=new Set,this.initialize=async()=>{var t,e,s,i,n,o;const r=null!==(e=null===(t=this.__devtools_initialize_getStoreActionsMapWrapped)||void 0===t?void 0:t.call(this))&&void 0!==e?e:this.getStoreActionsMap(),{actions:a,storeTools:l}=r;this.actions=a,this.storeTools=l,this.use=this.getMainHook(),null===(s=this.onInit)||void 0===s||s.call(this);const{onInit:c}=null!==(i=this.callbacks)&&void 0!==i?i:{};if(!c)return;const u=null!==(o=null===(n=this.__devtools_getLifeCycleStoreToolsWrapper)||void 0===n?void 0:n.call(this,"config/onInit/"))&&void 0!==o?o:l;null==c||c(u)},this.executeSetStateForSubscriber=(t,e)=>{const{selector:s,onStoreChange:i,currentState:n,isEqualRoot:o=(t,e)=>t===e,isEqual:r=(t,e)=>t===e}=t;if(!e.forceUpdate&&o(e.currentState,e.newState))return{didUpdate:!1};const a=s?s(e.newState):e.newState;return!e.forceUpdate&&r(n,a)?{didUpdate:!1}:(this.partialUpdateSubscription(t,{currentState:a}),i({state:a},{identifier:e.identifier}),{didUpdate:!0})},this.setActualStateWithoutValidations=(t,{forceUpdate:e,identifier:s})=>{const i=this.state;if(!e&&i===t)return;this.state=t;const n=this.subscribers.values(),o={forceUpdate:e,newState:t,currentState:i,identifier:s};for(const t of n)this.executeSetStateForSubscriber(t,o)},this.setMetadata=t=>{const e=(0,c.default)(t)?t(this.metadata):t;this.metadata=e},this.getMetadata=()=>this.metadata,this.getState=()=>this.state,this.subscribe=(...[t,e,s])=>{var i;const n=(0,c.default)(e),o=n?t:void 0,r=n?e:t,a=null!==(i=n?s:e)&&void 0!==i?i:void 0,l=o?o(this.state):this.state;(null==a?void 0:a.skipFirst)||r(l);const u=Object.assign({selector:o,currentState:l,onStoreChange:({state:t})=>r(t)},a);return this.subscribeCallback(u),()=>{this.subscribers.delete(u)}},this.subscribeCallback=t=>{var e,s;return null===(s=null===(e=this.callbacks)||void 0===e?void 0:e.onSubscribed)||void 0===s||s.call(e,this.storeTools,t),this.subscribers.add(t),()=>{this.subscribers.delete(t)}},this.partialUpdateSubscription=(t,e)=>{Object.assign(t,e)},this.getMainHook=()=>{const t=`globalHook:${this._name}`,e=(e,s=[])=>{(0,l.useDebugValue)(t);const i=(0,d.isArray)(s)?{dependencies:s}:null!=s?s:{},n=(0,l.useRef)(null),o=t=>(0,c.default)(e)?e(t):t;n.current=(()=>n.current?n.current:Object.assign({selector:o,currentState:o(this.state),onStoreChange:()=>{throw new Error("Callback not set")}},i))();const r=n.current.dependencies,a=null==i?void 0:i.dependencies,u=Object.assign(Object.assign({},i),{selector:o,dependencies:a});this.partialUpdateSubscription(n.current,u);const{subscribe:h,getSnapshot:b,getServerSnapshot:p}=(0,l.useMemo)((()=>{const t=()=>n.current.currentState;return{subscribe:t=>(n.current.onStoreChange=t,this.subscribeCallback(n.current)),getSnapshot:t,getServerSnapshot:t}}),[]);return this.reselectIfDependenciesChanged({subscription:n.current,newDependencies:a,currentDependencies:r}),[(0,l.useSyncExternalStore)(h,b,p),this.getStateOrchestrator(),this.metadata]},{setMetadata:s,getMetadata:i,actions:n}=this,o={actions:n,createObservable:this.createObservable.bind(this),createSelectorHook:this.createSelectorHook.bind(this),dispose:this.dispose.bind(this),getMetadata:i,getState:this.getState.bind(this),reset:this.reset.bind(this),setMetadata:s,setState:this.setState.bind(this),subscribe:this.subscribe.bind(this),subscribers:this.subscribers,use:e,select:(...t)=>e(...t)[0]};return Object.assign(e,o),e},this.reselectIfDependenciesChanged=({subscription:t,newDependencies:e,currentDependencies:s})=>{t.selector&&s!==e&&((null==s?void 0:s.length)===(null==e?void 0:e.length)&&(0,d.default)(s,e)||this.partialUpdateSubscription(t,{currentState:t.selector(this.state)}))},this.createSelectorHook=v,this.createObservable=g,this.getStateOrchestrator=()=>(()=>this.actions?this.actions:this.setState)(),this.setState=(t,{forceUpdate:e,identifier:s}={})=>{var i,n,o,r;const a=this.state,l=(0,c.default)(t)?t(a):t;if(!e&&this.state===l)return;const u=this.setActualStateWithoutValidations,d={previousState:a,state:l,identifier:s},h=Object.assign(Object.assign(Object.assign({},this.storeTools),d),{setState:u});if((null===(i=this.callbacks)||void 0===i?void 0:i.computePreventStateChange)&&(null===(o=null===(n=this.callbacks)||void 0===n?void 0:n.computePreventStateChange)||void 0===o?void 0:o.call(n,h)))return;this.setActualStateWithoutValidations(l,{forceUpdate:e,identifier:s});const{onStateChanged:b}=this,p=null===(r=this.callbacks)||void 0===r?void 0:r.onStateChanged;null==b||b(h),null==p||p(h)},this.getStoreActionsMap=()=>{const{actionsConfig:t,getMetadata:e,getState:s,setMetadata:i,setState:n,subscribe:o}=this,r={setMetadata:i,getMetadata:e,getState:s,setState:n,subscribe:o,actions:null};if(!(0,u.default)(t))return{actions:null,storeTools:r};const a={};r.actions=a;const l=Object.keys(t);for(const e of l)Object.assign(a,{[e](...s){const i=t[e].apply(a,s);return"function"!=typeof i&&(0,h.default)(e),i.call(a,r)}});return{actions:a,storeTools:r}},this.removeSubscriptions=()=>{this.subscribers.clear()},this.executeCleanupTasks=()=>{this.cleanupFunctions.forEach((t=>{null==t||t()})),this.cleanupFunctions.length=0},this.dispose=()=>{this.removeSubscriptions(),this.executeCleanupTasks()},this.reset=(t,e)=>{var s,i,n,o,r,a;this.executeCleanupTasks(),this.setActualStateWithoutValidations(t,{forceUpdate:!0}),this.metadata=e;const l=null!==(i=null===(s=this.onInit)||void 0===s?void 0:s.call(this))&&void 0!==i?i:null;(0,c.default)(l)&&this.cleanupFunctions.push(l);const{onInit:u}=null!==(n=this.callbacks)&&void 0!==n?n:{};if(!u)return;const d=null!==(r=null===(o=this.__devtools_getLifeCycleStoreToolsWrapper)||void 0===o?void 0:o.call(this,"config/onInit/"))&&void 0!==r?r:this.storeTools,h=null!==(a=null==u?void 0:u(d))&&void 0!==a?a:null;(0,c.default)(h)&&this.cleanupFunctions.push(h)};const{metadata:n,callbacks:o,actions:r,name:a}=e;if(this.state=t,this._name=null!=a?a:(0,b.default)("gs:"),this.metadata=null!=n?n:{},this.callbacks=null!=o?o:null,this.actionsConfig=null!=r?r:null,p.default.isDevToolsPresent){const t=null!==(s=(new Error).stack)&&void 0!==s?s:"";null===(i=p.default.REACT_GLOBAL_STATE_HOOK_DEBUG)||void 0===i||i.call(p.default,this,e,t)}this.constructor!==f||this.initialize()}}function g(t,e){const s=null==e?void 0:e.name,i=null==e?void 0:e.isEqualRoot,n=null==e?void 0:e.isEqual;let o=this.getState(),r=(null!=t?t:t=>t)(o);const a=new f(r,{name:null!=s?s:(0,b.default)("sh:")}),l=this.subscribe((e=>{if((null!=i?i:Object.is)(o,e))return;o=e;const s=t(e);(null!=n?n:Object.is)(r,s)||(r=s,a.setState(s))}),{skipFirst:!0}),c=a.subscribe.bind(a),u={getState:a.getState.bind(a),subscribe:a.subscribe.bind(a),createSelectorHook:v.bind(c),createObservable:g.bind(c),dispose:()=>{l(),a.dispose()},subscribers:a.subscribers};return Object.assign(c,u),c}function v(t,e){const s=null==e?void 0:e.name,i=null==e?void 0:e.isEqualRoot,n=null==e?void 0:e.isEqual;let o=this.getState(),r=(null!=t?t:t=>t)(o);const a=new f(r,{name:null!=s?s:(0,b.default)("sh:")}),l=this.subscribe((e=>{if((null!=i?i:Object.is)(o,e))return;o=e;const s=t(e);(null!=n?n:Object.is)(r,s)||(r=s,a.setState(s))}),{skipFirst:!0}),c=(...t)=>{const[e]=a.use(...t);return e},u={getState:()=>a.getState(),subscribe:a.subscribe.bind(a),createSelectorHook:v.bind(c),createObservable:g.bind(c),dispose:()=>{l(),a.dispose()},subscribers:a.subscribers};return Object.assign(c,u),c}e.GlobalStore=f,e.default=f},155:t=>{t.exports=e},361:t=>{t.exports=s},487:t=>{t.exports=i},506:t=>{t.exports=n},627:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});const s=globalThis;s.isDevToolsPresent=Boolean(s.REACT_GLOBAL_STATE_HOOK_DEBUG),e.default=s},673:t=>{t.exports=o}},a={};return function t(e){var s=a[e];if(void 0!==s)return s.exports;var i=a[e]={exports:{}};return r[e].call(i.exports,i,i.exports,t),i.exports}(132)})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js")):"function"==typeof define&&define.amd?define(["./uniqueId.js","react","./throwWrongKeyOnActionCollectionConfig.js","./isRecord.js","json-storage-formatter/isFunction","./shallowCompare.js"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("./uniqueId.js"),require("react"),require("./throwWrongKeyOnActionCollectionConfig.js"),require("./isRecord.js"),require("json-storage-formatter/isFunction"),require("./shallowCompare.js")):t["react-hooks-global-states"]=e(t["./uniqueId.js"],t.react,t["./throwWrongKeyOnActionCollectionConfig.js"],t["./isRecord.js"],t["json-storage-formatter/isFunction"],t["./shallowCompare.js"]);
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|

|
|
4
4
|
|
|
5
|
-
Effortless **global state management** for `React
|
|
5
|
+
Effortless **global state management** for `React`, `React Native`, and `Preact`! 🚀 Define **global state in just one line of code** and enjoy **lightweight, flexible, and scalable** state management. Try it now on **[CodePen](https://codepen.io/johnnynabetes/pen/WNmeGwb?editors=0010)** and see it in action! ✨
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -18,7 +18,7 @@ Effortless **global state management** for `React` & `React Native` & `Preact`!
|
|
|
18
18
|
|
|
19
19
|
## 🚀 React Hooks Global States - DevTools Extension
|
|
20
20
|
|
|
21
|
-
React Hooks Global States includes a dedicated
|
|
21
|
+
React Hooks Global States includes a dedicated `DevTools extension` to streamline your development workflow! Easily visualize, inspect, debug, and modify your application's global state in real-time within your browser.
|
|
22
22
|
|
|
23
23
|
### 🔗 [Install the DevTools Extension for Chrome](https://chromewebstore.google.com/detail/bafojplmkpejhglhjpibpdhoblickpee/preview?hl=en&authuser=0)
|
|
24
24
|
|
|
@@ -99,7 +99,7 @@ const [contacts] = useContacts((state) => state.entities.filter((item) => item.n
|
|
|
99
99
|
});
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
Unlike Redux, where only **root state changes trigger re-selection**, this approach ensures
|
|
102
|
+
Unlike Redux, where only **root state changes trigger re-selection**, this approach ensures **derived values recompute when dependencies change** while maintaining performance.
|
|
103
103
|
|
|
104
104
|
---
|
|
105
105
|
|
|
@@ -132,7 +132,7 @@ const [filteredContacts] = useContactsArray(
|
|
|
132
132
|
|
|
133
133
|
#### ✅ Selector hooks share the same state mutator
|
|
134
134
|
|
|
135
|
-
The **state
|
|
135
|
+
The **state API is stable across renders**, meaning actions and setState functions stay consistent.
|
|
136
136
|
|
|
137
137
|
```tsx
|
|
138
138
|
const [, setState1] = useContactsArray();
|
|
@@ -178,8 +178,7 @@ const [filter, { setFilter }] = useContacts();
|
|
|
178
178
|
|
|
179
179
|
## 🌍 Accessing Global State Outside Components
|
|
180
180
|
|
|
181
|
-
You can access and manipulate global without hooks, useful for non-component code like services or utilities.
|
|
182
|
-
Or for non reactive components.
|
|
181
|
+
You can access and manipulate global state without hooks, useful for non-component code like services or utilities, or for non-reactive components.
|
|
183
182
|
|
|
184
183
|
```tsx
|
|
185
184
|
console.log(useContacts.getState()); // Retrieves the current state
|
|
@@ -193,7 +192,7 @@ const unsubscribe = useContacts.subscribe((state) => {
|
|
|
193
192
|
});
|
|
194
193
|
```
|
|
195
194
|
|
|
196
|
-
#### ✅
|
|
195
|
+
#### ✅ Use subscriptions when one state depends on another
|
|
197
196
|
|
|
198
197
|
```tsx
|
|
199
198
|
const useSelectedContact = createGlobalState(null, {
|
|
@@ -239,7 +238,7 @@ export const Component = () => {
|
|
|
239
238
|
};
|
|
240
239
|
|
|
241
240
|
export const Component2 = () => {
|
|
242
|
-
const [count, setCount] = counter.use.api(); // non
|
|
241
|
+
const [count, setCount] = counter.use.api(); // non-reactive access to the context API
|
|
243
242
|
|
|
244
243
|
return <Button onClick={() => setCount((c) => c + 1)}>{count}</Button>;
|
|
245
244
|
};
|
|
@@ -337,7 +336,7 @@ Use **`onInit`** for setup, **`onStateChanged`** to listen to updates, and **`co
|
|
|
337
336
|
|
|
338
337
|
## Metadata
|
|
339
338
|
|
|
340
|
-
|
|
339
|
+
You can add non-reactive information to the global state:
|
|
341
340
|
|
|
342
341
|
```tsx
|
|
343
342
|
const useCount = createGlobalState(0, { metadata: { renders: 0 } });
|
package/createContext.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import React, { type PropsWithChildren, Context as ReactContext } from 'react';
|
|
|
2
2
|
import { GlobalStore } from './GlobalStore';
|
|
3
3
|
import type { BaseMetadata, GlobalStoreCallbacks as GlobalStoreCallbacksBase, UseHookOptions, AnyFunction, StoreTools, ReadonlyStateApi, SelectHook, ObservableFragment, StateApi, UnsubscribeCallback } from './types';
|
|
4
4
|
import { AnyActions } from 'createGlobalState';
|
|
5
|
-
type GlobalStoreContextCallbacks<State, StateMutator, Metadata extends BaseMetadata> = {
|
|
5
|
+
export type GlobalStoreContextCallbacks<State, StateMutator, Metadata extends BaseMetadata> = {
|
|
6
6
|
/**
|
|
7
7
|
* @description Optional callback invoked after the context is created,
|
|
8
8
|
*/
|
|
@@ -146,7 +146,7 @@ export type ContextProvider<State, StateMutator, Metadata extends BaseMetadata>
|
|
|
146
146
|
/**
|
|
147
147
|
* @description Represents a hook that returns a readonly state.
|
|
148
148
|
*/
|
|
149
|
-
interface ReadonlyContextHook<State, StateMutator, Metadata extends BaseMetadata> extends ReadonlyContextPublicApi<State, StateMutator, Metadata> {
|
|
149
|
+
export interface ReadonlyContextHook<State, StateMutator, Metadata extends BaseMetadata> extends ReadonlyContextPublicApi<State, StateMutator, Metadata> {
|
|
150
150
|
/**
|
|
151
151
|
* @description Returns the full state.
|
|
152
152
|
*/
|
|
@@ -317,7 +317,7 @@ export type ReadonlyContextPublicApi<State, StateMutator, Metadata extends BaseM
|
|
|
317
317
|
*/
|
|
318
318
|
api: () => ReadonlyStateApi<State, StateMutator, Metadata>;
|
|
319
319
|
};
|
|
320
|
-
interface CreateContext {
|
|
320
|
+
export interface CreateContext {
|
|
321
321
|
/**
|
|
322
322
|
* @description Creates a highly granular React context with its associated provider and state hook.
|
|
323
323
|
* @param value Initial state value or initializer function.
|
package/createContext.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t;e=this,t=(e,t,r,o,
|
|
1
|
+
var e,t;e=this,t=(e,t,r,o,a)=>(()=>{"use strict";var s={78:t=>{t.exports=e},155:e=>{e.exports=t},506:e=>{e.exports=r},695:function(e,t,r){var o=this&&this.__rest||function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(o=Object.getOwnPropertySymbols(e);a<o.length;a++)t.indexOf(o[a])<0&&Object.prototype.propertyIsEnumerable.call(e,o[a])&&(r[o[a]]=e[o[a]])}return r},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createContext=void 0;const s=r(155),n=r(778),l=a(r(506)),u=a(r(773)),i=a(r(78));function c(e,t){var r;const o=null!==(r=null==t?void 0:t.name)&&void 0!==r?r:(0,i.default)("sh:"),a=(...r)=>{const a=this.api();return(0,s.useDebugValue)(`${this.displayName}:selector`),(0,s.useDebugValue)(`${o}:use`),(0,s.useMemo)((()=>a.createSelectorHook(e,t)),[a])(...r)},l={displayName:this.displayName,createSelectorHook:c.bind(a),api:()=>{(0,s.useDebugValue)(`${this.displayName}:selector`),(0,s.useDebugValue)(`${o}:api`);const r=this.api();return(0,s.useMemo)((()=>{const o=r.createObservable(e,t);return Object.assign(Object.assign({},r),{getState:()=>o.getState(),subscribe:o.subscribe.bind(o),createSelectorHook:n.createSelectorHook.bind(o),createObservable:n.createObservable.bind(o)})}),[r])}};return Object.assign(a,l),a}t.createContext=(e,t={})=>{var r;const a=(0,s.createContext)(null),d=null!==(r=t.name)&&void 0!==r?r:(0,i.default)("ctx:"),v=r=>{const i=(r=>{var{value:a}=r,i=o(r,["value"]);(0,s.useDebugValue)(`${d}:Provider`);const c=(0,s.useMemo)((()=>{var r,o,s,c;const d=()=>(0,l.default)(e)?e():e,v=(0,u.default)(a)?d():(0,l.default)(a)?a(d()):a,b=new n.GlobalStore(v,Object.assign(Object.assign({},t),{metadata:null!==(r=(0,l.default)(t.metadata)?t.metadata():t.metadata)&&void 0!==r?r:{}})),f={use:p};return Object.assign(b.storeTools,f),null===(s=null===(o=t.callbacks)||void 0===o?void 0:o.onCreated)||void 0===s||s.call(o,b.storeTools,b),null===(c=i.onCreated)||void 0===c||c.call(i,b.storeTools,b),b}),[]);return(0,s.useEffect)((()=>{var e,r,o;const a=[null===(r=null===(e=t.callbacks)||void 0===e?void 0:e.onMounted)||void 0===r?void 0:r.call(e,c.storeTools,c),null===(o=i.onMounted)||void 0===o?void 0:o.call(i,c.storeTools,c)].filter(Boolean);return()=>{var e,t,r,o;null===(t=null===(e=c.callbacks)||void 0===e?void 0:e.onUnMount)||void 0===t||t.call(e,c),a.forEach((e=>null==e?void 0:e())),null===(o=(r=c).__onUnMountContext)||void 0===o||o.call(r,c)}}),[c]),c})(r);return(0,s.createElement)(a.Provider,{value:i.use},r.children)};v.displayName=`${d}:Provider`,a.displayName=`${d}`;const b={makeProviderWrapper:e=>{const t={current:void 0,instance:void 0};return{wrapper:r=>{var{children:a}=r,n=o(r,["children"]);return(0,s.createElement)(v,Object.assign(Object.assign(Object.assign({},e),n),{onCreated:(r,o)=>{var a;t.current=r,t.instance=o,null===(a=null==e?void 0:e.onCreated)||void 0===a||a.call(e,r,o)}}),a)},context:t}}},p=(...e)=>{(0,s.useDebugValue)(`${d}:use`);const t=(0,s.useContext)(a);if(!t)throw new Error("use hook must be used within a ContextProvider");return t(...e)},f=()=>{(0,s.useDebugValue)(`${d}:api`);const e=(0,s.useContext)(a);if(!e)throw new Error("api hook must be used within a ContextProvider");return e},m={displayName:a.displayName,createSelectorHook:c.bind(p),api:f,select:(...e)=>p(...e)[0],observable:(...e)=>{(0,s.useDebugValue)(`${d}:observable`);const t=f(),r=(0,s.useRef)(e);return r.current=e,(0,s.useMemo)((()=>{var e,o,a;return t.createObservable((e=>(0,r.current[0])(e)),{isEqualRoot:(null===(e=r.current[1])||void 0===e?void 0:e.isEqualRoot)?(e,t)=>{const o=r.current[1].isEqualRoot;return Boolean(o(e,t))}:void 0,isEqual:(null===(o=r.current[1])||void 0===o?void 0:o.isEqual)?(e,t)=>{const o=r.current[1].isEqual;return Boolean(o(e,t))}:void 0,name:null===(a=r.current[1])||void 0===a?void 0:a.name})}),[t])},actions:()=>f().actions};return Object.assign(v,b),Object.assign(p,m),{use:p,Provider:v,Context:a}},t.default=t.createContext},773:e=>{e.exports=o},778:e=>{e.exports=a}},n={};return function e(t){var r=n[t];if(void 0!==r)return r.exports;var o=n[t]={exports:{}};return s[t].call(o.exports,o,o.exports,e),o.exports}(695)})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("./uniqueId.js"),require("react"),require("json-storage-formatter/isFunction"),require("json-storage-formatter/isNil"),require("./GlobalStore.js")):"function"==typeof define&&define.amd?define(["./uniqueId.js","react","json-storage-formatter/isFunction","json-storage-formatter/isNil","./GlobalStore.js"],t):"object"==typeof exports?exports["react-hooks-global-states"]=t(require("./uniqueId.js"),require("react"),require("json-storage-formatter/isFunction"),require("json-storage-formatter/isNil"),require("./GlobalStore.js")):e["react-hooks-global-states"]=t(e["./uniqueId.js"],e.react,e["json-storage-formatter/isFunction"],e["json-storage-formatter/isNil"],e["./GlobalStore.js"]);
|
package/createGlobalState.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ import type { ActionCollectionConfig, ActionCollectionResult, StateHook, BaseMet
|
|
|
23
23
|
* ```
|
|
24
24
|
*/
|
|
25
25
|
export type AnyActions = Record<string, (...args: any[]) => any>;
|
|
26
|
-
interface CreateGlobalState {
|
|
26
|
+
export interface CreateGlobalState {
|
|
27
27
|
/**
|
|
28
28
|
* Creates a global state hook.
|
|
29
29
|
* @param state initial state value
|
package/createGlobalState.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e;e=e=>(()=>{"use strict";var t={778:t=>{t.exports=e},
|
|
1
|
+
var e;e=e=>(()=>{"use strict";var t={778:t=>{t.exports=e},904:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createGlobalState=void 0;const r=o(778);t.createGlobalState=(...[e,t])=>new r.GlobalStore(e,t).use,t.default=t.createGlobalState}},o={};return function e(r){var a=o[r];if(void 0!==a)return a.exports;var s=o[r]={exports:{}};return t[r](s,s.exports,e),s.exports}(904)})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("./GlobalStore.js")):"function"==typeof define&&define.amd?define(["./GlobalStore.js"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("./GlobalStore.js")):this["react-hooks-global-states"]=e(this["./GlobalStore.js"]);
|
package/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export type { StateApi, ObservableFragment, MetadataSetter, StateChanges, StoreTools, ActionCollectionResult, GlobalStoreCallbacks, UseHookOptions, UnsubscribeCallback, SubscribeCallbackConfig, SubscribeCallback, BaseMetadata, MetadataGetter, SelectorCallback, SubscriberParameters, SubscriptionCallback,
|
|
1
|
+
export type { AnyFunction, ReadonlyHook, SelectHook, StateApi, ReadonlyStateApi, ObservableFragment, StateHook, MetadataSetter, StateChanges, StoreTools, ActionCollectionConfig, ActionCollectionResult, GlobalStoreCallbacks, UseHookOptions, UnsubscribeCallback, SubscribeCallbackConfig, SubscribeCallback, SubscribeToState, BaseMetadata, MetadataGetter, SelectorCallback, SubscriberParameters, SubscriptionCallback, } from './types';
|
|
2
2
|
export { GlobalStore } from './GlobalStore';
|
|
3
|
-
export { createGlobalState, type InferActionsType, type InferStateApi, AnyActions, } from './createGlobalState';
|
|
3
|
+
export { createGlobalState, type CreateGlobalState, type InferActionsType, type InferStateApi, type AnyActions, } from './createGlobalState';
|
|
4
4
|
export { shallowCompare } from './shallowCompare';
|
|
5
|
-
export { uniqueId, type BrandedId } from './uniqueId';
|
|
5
|
+
export { uniqueId, type BrandedId, type UniqueId } from './uniqueId';
|
|
6
6
|
export { throwWrongKeyOnActionCollectionConfig } from './throwWrongKeyOnActionCollectionConfig';
|
|
7
7
|
export { isRecord } from './isRecord';
|
|
8
|
-
export { type
|
|
8
|
+
export { createContext, type CreateContext, type ContextHook, type ReadonlyContextHook, type ContextProvider, type ContextProviderExtensions, type ContextStoreTools, type ContextStoreToolsExtensions, type ContextPublicApi, type ReadonlyContextPublicApi, type ContextActionCollectionConfig, type ContextActionCollectionResult, type GlobalStoreContextCallbacks, type InferContextApi, } from './createContext';
|
package/isRecord.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e;e=e=>(()=>{"use strict";var
|
|
1
|
+
var e;e=e=>(()=>{"use strict";var t={773:t=>{t.exports=e},867:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRecord=void 0;const s=r(o(773));t.isRecord=e=>!(0,s.default)(e)&&"object"==typeof e,t.default=t.isRecord}},o={};return function e(r){var s=o[r];if(void 0!==s)return s.exports;var i=o[r]={exports:{}};return t[r].call(i.exports,i,i.exports,e),i.exports}(867)})(),"object"==typeof exports&&"object"==typeof module?module.exports=e(require("json-storage-formatter/isNil")):"function"==typeof define&&define.amd?define(["json-storage-formatter/isNil"],e):"object"==typeof exports?exports["react-hooks-global-states"]=e(require("json-storage-formatter/isNil")):this["react-hooks-global-states"]=e(this["json-storage-formatter/isNil"]);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-hooks-global-states",
|
|
3
|
-
"version": "15.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "15.0.11",
|
|
4
|
+
"description": "A package to easily handle global state across your React components using hooks.",
|
|
5
5
|
"main": "./bundle.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -100,13 +100,6 @@
|
|
|
100
100
|
},
|
|
101
101
|
"homepage": "https://github.com/johnny-quesada-developer/react-hooks-global-states#readme",
|
|
102
102
|
"devDependencies": {
|
|
103
|
-
"@babel/core": "^7.21.3",
|
|
104
|
-
"@babel/plugin-proposal-class-properties": "^7.18.6",
|
|
105
|
-
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
|
|
106
|
-
"@babel/plugin-transform-modules-commonjs": "^7.21.2",
|
|
107
|
-
"@babel/preset-env": "^7.20.2",
|
|
108
|
-
"@babel/preset-react": "^7.18.6",
|
|
109
|
-
"@babel/preset-typescript": "^7.21.0",
|
|
110
103
|
"@eslint/js": "^9.39.1",
|
|
111
104
|
"@testing-library/dom": "^10.4.0",
|
|
112
105
|
"@testing-library/react": "^16.3.0",
|
|
@@ -115,7 +108,6 @@
|
|
|
115
108
|
"@types/react-dom": "^18.2.18",
|
|
116
109
|
"@typescript-eslint/eslint-plugin": "^4.9.1",
|
|
117
110
|
"@typescript-eslint/parser": "^4.9.1",
|
|
118
|
-
"babel-loader": "^9.1.2",
|
|
119
111
|
"clean-webpack-plugin": "^4.0.0",
|
|
120
112
|
"easy-cancelable-promise": "^1.0.1",
|
|
121
113
|
"eslint": "^9.39.1",
|
package/shallowCompare.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var e,t;e=this,t=(e,t,r,s)=>(()=>{"use strict";var i={38:t=>{t.exports=e},154:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEqualObject=t.isEqualSet=t.isEqualMap=t.isEqualArray=t.canCheckSimpleEquality=t.isSet=t.isMap=t.isArray=t.shallowCompare=void 0;const i=s(r(955)),o=s(r(38)),a=s(r(773)),n=s(r(487));t.shallowCompare=(e,r)=>!(e!==r)||((0,t.canCheckSimpleEquality)(e,r)?e===r:(0,t.isArray)(e)&&(0,t.isArray)(r)?(0,t.isEqualArray)(e,r):(0,t.isMap)(e)&&(0,t.isMap)(r)?(0,t.isEqualMap)(e,r):(0,t.isSet)(e)&&(0,t.isSet)(r)?(0,t.isEqualSet)(e,r):(0,n.default)(e)&&(0,n.default)(r)?(0,t.isEqualObject)(e,r):e===r),t.isArray=e=>Array.isArray(e),t.isMap=e=>e instanceof Map,t.isSet=e=>e instanceof Set,t.canCheckSimpleEquality=(e,t)=>{const r=typeof e,s=typeof t;return r!==s||(0,a.default)(e)||(0,a.default)(t)||(0,i.default)(e)&&(0,i.default)(t)||(0,o.default)(e)&&(0,o.default)(t)||"function"===r&&"function"===s},t.isEqualArray=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0},t.isEqualMap=(e,t)=>{if(e.size!==t.size)return!1;for(const[r,s]of e)if(s!==t.get(r))return!1;return!0},t.isEqualSet=(e,t)=>{if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0},t.isEqualObject=(e,t)=>{const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(const s of r)if(e[s]!==t[s])return!1;return!0},t.default=t.shallowCompare},487:e=>{e.exports=t},773:e=>{e.exports=r},955:e=>{e.exports=s}},o={};return function e(t){var r=o[t];if(void 0!==r)return r.exports;var s=o[t]={exports:{}};return i[t].call(s.exports,s,s.exports,e),s.exports}(154)})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("json-storage-formatter/isDate"),require("./isRecord.js"),require("json-storage-formatter/isNil"),require("json-storage-formatter/isPrimitive")):"function"==typeof define&&define.amd?define(["json-storage-formatter/isDate","./isRecord.js","json-storage-formatter/isNil","json-storage-formatter/isPrimitive"],t):"object"==typeof exports?exports["react-hooks-global-states"]=t(require("json-storage-formatter/isDate"),require("./isRecord.js"),require("json-storage-formatter/isNil"),require("json-storage-formatter/isPrimitive")):e["react-hooks-global-states"]=t(e["json-storage-formatter/isDate"],e["./isRecord.js"],e["json-storage-formatter/isNil"],e["json-storage-formatter/isPrimitive"]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var t;t=()=>(()=>{"use strict";var t={};return((t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.throwWrongKeyOnActionCollectionConfig=void 0,e.throwWrongKeyOnActionCollectionConfig=
|
|
1
|
+
var t;t=()=>(()=>{"use strict";var t={};return((t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.throwWrongKeyOnActionCollectionConfig=void 0,e.throwWrongKeyOnActionCollectionConfig=t=>{throw new Error(`[WRONG CONFIGURATION!]: Every key inside the storeActionsConfig must be a higher order function that returns a function \n[${t}]: key is not a valid function, try something like this: \n{\n\n ${t}: (param) => ({ setState, getState, setMetadata, getMetadata, actions }) => {\n\n setState((state) => ({ ...state, ...param }))\n\n }\n\n}\n`)},e.default=e.throwWrongKeyOnActionCollectionConfig})(0,t),t})(),"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["react-hooks-global-states"]=t():this["react-hooks-global-states"]=t();
|
package/types.d.ts
CHANGED
|
@@ -53,16 +53,15 @@ export type StateApi<State, StateMutator, Metadata extends BaseMetadata> = {
|
|
|
53
53
|
setMetadata: MetadataSetter<Metadata>;
|
|
54
54
|
/**
|
|
55
55
|
* @description Contains the generated action functions if custom actions are defined.
|
|
56
|
-
* When actions exist, direct state mutation via `setState` is disabled and setState will be `null`.
|
|
57
56
|
* If no actions are provided, this property is `null`.
|
|
58
57
|
*/
|
|
59
58
|
actions: StateMutator extends AnyFunction ? null : StateMutator;
|
|
60
59
|
/**
|
|
61
|
-
* @description Provides direct access to the state updater
|
|
62
|
-
*
|
|
63
|
-
*
|
|
60
|
+
* @description Provides direct access to the state updater.
|
|
61
|
+
* Always available for testing purposes, even when actions are defined.
|
|
62
|
+
* In production, prefer using actions when they are defined.
|
|
64
63
|
*/
|
|
65
|
-
setState:
|
|
64
|
+
setState: React.Dispatch<React.SetStateAction<State>>;
|
|
66
65
|
/**
|
|
67
66
|
* @description Get the current state value
|
|
68
67
|
*/
|
|
@@ -133,6 +132,13 @@ export type StateApi<State, StateMutator, Metadata extends BaseMetadata> = {
|
|
|
133
132
|
* @description Disposes the global state instance, cleaning up all resources and subscriptions.
|
|
134
133
|
*/
|
|
135
134
|
dispose: () => void;
|
|
135
|
+
/**
|
|
136
|
+
* @description Resets the store to a new initial state and re-runs initialization (including onInit callbacks).
|
|
137
|
+
* Existing subscribers are maintained and notified of the new state.
|
|
138
|
+
* Useful for testing scenarios where you need to reinitialize the store.
|
|
139
|
+
* @param newState - The new initial state to reset to
|
|
140
|
+
*/
|
|
141
|
+
reset: (newState: State, metadata: Metadata) => void;
|
|
136
142
|
/**
|
|
137
143
|
* @deprecated
|
|
138
144
|
* @description Useful for debugging purposes, exposes the current subscribers of the store
|
|
@@ -241,6 +247,7 @@ export type ActionCollectionResult<State, Metadata extends BaseMetadata, Actions
|
|
|
241
247
|
(...params: Parameters<ActionsConfig[key]>): ReturnType<ReturnType<ActionsConfig[key]>>;
|
|
242
248
|
};
|
|
243
249
|
};
|
|
250
|
+
export type CleanupFunction = () => void;
|
|
244
251
|
/**
|
|
245
252
|
* Callbacks for the global store lifecycle events
|
|
246
253
|
*/
|
|
@@ -248,7 +255,7 @@ export type GlobalStoreCallbacks<State, StateMutator, Metadata extends BaseMetad
|
|
|
248
255
|
/**
|
|
249
256
|
* @description Called when the store is initialized
|
|
250
257
|
*/
|
|
251
|
-
onInit?: (args: StoreTools<State, StateMutator, Metadata>) => void;
|
|
258
|
+
onInit?: (args: StoreTools<State, StateMutator, Metadata>) => void | Promise<void> | CleanupFunction;
|
|
252
259
|
/**
|
|
253
260
|
* @description Called when the state has changed
|
|
254
261
|
*/
|
package/uniqueId.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export declare const __brand: unique symbol;
|
|
|
5
5
|
export type BrandedId<T extends string | undefined> = `${T extends string ? T : ''}${string}` & {
|
|
6
6
|
[__brand]: T;
|
|
7
7
|
};
|
|
8
|
-
interface UniqueId {
|
|
8
|
+
export interface UniqueId {
|
|
9
9
|
/**
|
|
10
10
|
* Generates a unique identifier string, optionally prefixed.
|
|
11
11
|
*
|
package/uniqueId.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t;t=()=>(()=>{"use strict";var t={};return((t,e)=>{
|
|
1
|
+
var t;t=()=>(()=>{"use strict";var t={};return((t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.uniqueId=void 0,e.uniqueId=(()=>{let t=0;const e=()=>(t===Number.MAX_SAFE_INTEGER&&(t=0),t++),o=(t,e)=>(null!=t?t:"")+Date.now().toString(36)+e.toString(36),r=t=>o(t,e());return r.for=t=>{const r=()=>o(t,e());return r.is=e=>"string"==typeof e&&e.startsWith(t),r.assert=function(e){if(!r.is(e))throw new Error(`The value "${String(e)}" does not match the expected prefix "${String(t)}"`)},r.strict=()=>r,r},r.of=()=>r.for(""),r.strict=()=>r,r})(),e.default=e.uniqueId})(0,t),t})(),"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["react-hooks-global-states"]=t():this["react-hooks-global-states"]=t();
|
package/webpack.config.js
CHANGED
|
@@ -61,22 +61,7 @@ module.exports = {
|
|
|
61
61
|
rules: [
|
|
62
62
|
{
|
|
63
63
|
test: /\.ts$/,
|
|
64
|
-
use:
|
|
65
|
-
{
|
|
66
|
-
loader: 'babel-loader',
|
|
67
|
-
options: {
|
|
68
|
-
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
|
|
69
|
-
plugins: [
|
|
70
|
-
'@babel/plugin-transform-modules-commonjs',
|
|
71
|
-
'@babel/plugin-proposal-class-properties',
|
|
72
|
-
'@babel/plugin-proposal-export-namespace-from',
|
|
73
|
-
],
|
|
74
|
-
},
|
|
75
|
-
},
|
|
76
|
-
{
|
|
77
|
-
loader: 'ts-loader',
|
|
78
|
-
},
|
|
79
|
-
],
|
|
64
|
+
use: 'ts-loader',
|
|
80
65
|
exclude: /node_modules/,
|
|
81
66
|
},
|
|
82
67
|
],
|