react-native-global-state-hooks 2.1.22 → 3.0.0

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.
@@ -189,4 +189,3 @@ export declare class GlobalStore<TState, TMetadata = null, TStateSetter extends
189
189
  invokerSetState?: React.Dispatch<React.SetStateAction<TState>>;
190
190
  }) => ActionCollectionResult<TState, TMetadata, TStateSetter>;
191
191
  }
192
- //# sourceMappingURL=GlobalStore.d.ts.map
@@ -106,4 +106,3 @@ export type GlobalStoreConfig<TState, TMetadata, TStateSetter extends ActionColl
106
106
  onSubscribed?: (parameters: StateConfigCallbackParam<TState, TMetadata, TStateSetter>) => void;
107
107
  computePreventStateChange?: (parameters: StateChangesParam<TState, TMetadata, TStateSetter>) => boolean;
108
108
  } | null;
109
- //# sourceMappingURL=GlobalStore.types.d.ts.map
package/lib/bundle.js ADDED
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports["react-native-global-state-hooks"]=e(require("react")):t["react-native-global-state-hooks"]=e(t.react)}(this,(t=>(()=>{"use strict";var e={774:(t,e,r)=>{function n(t){return n="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},n(t)}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function a(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,i(n.key),n)}}function i(t){var e=function(t,e){if("object"!==n(t)||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var o=r.call(t,"string");if("object"!==n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===n(e)?e:String(e)}Object.defineProperty(e,"__esModule",{value:!0}),e.GlobalStore=e.formatToStore=e.formatFromStore=void 0;var s=r(789);Object.defineProperty(e,"formatFromStore",{enumerable:!0,get:function(){return s.formatFromStore}}),Object.defineProperty(e,"formatToStore",{enumerable:!0,get:function(){return s.formatToStore}});var u=r(789),l=r(156),c=function(){function t(e){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.state=e,this.setterConfig=a,this.subscribers=new Set,this.config={metadata:null},this.onInit=null,this.onStateChanged=null,this.onSubscribed=null,this.computePreventStateChange=null,this.onInitializeStore=function(){var t=r.onInit,e=r.config.onInit;if(t||e){var n=r.getConfigCallbackParam({});null==t||t(n),null==e||e(n)}},this.getStateClone=function(){return(0,u.clone)(r.state)},this.getMetadataClone=function(){var t,e;return(0,u.clone)(null!==(e=null===(t=r.config)||void 0===t?void 0:t.metadata)&&void 0!==e?e:null)},this.setState=function(t){var e=t.invokerSetState,n=t.state;r.state=n,null==e||e(n),r.subscribers.forEach((function(t){t!==e&&t(n)}))},this.setMetadata=function(t){var e,n="function"==typeof t?t(r.getMetadataClone()):t;r.config=Object.assign(Object.assign({},null!==(e=r.config)&&void 0!==e?e:{}),{metadata:n})},this.getConfigCallbackParam=function(t){var e=t.invokerSetState;return{setMetadata:r.setMetadata,getMetadata:r.getMetadataClone,getState:r.getStateClone,setState:r.getSetStateWrapper({invokerSetState:e}),actions:r.getStoreActionsMap({})}},this.getHook=function(){return function(){var t,e,n=(t=(0,l.useState)((function(){return r.state})),e=2,function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,a,i,s=[],u=!0,l=!1;try{if(a=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(s.push(n.value),s.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(l)throw o}}return s}}(t,e)||function(t,e){if(t){if("string"==typeof t)return o(t,e);var r=Object.prototype.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)?o(t,e):void 0}}(t,e)||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.")}()),a=n[0],i=n[1];return(0,l.useEffect)((function(){r.subscribers.add(i);var t=r.onSubscribed,e=r.config.onSubscribed;if(t||e){var n=r.getConfigCallbackParam({invokerSetState:i});null==t||t(n),null==e||e(n)}return function(){r.subscribers.delete(i)}}),[]),[a,r.getStateOrchestrator(i),r.getMetadataClone()]}},this.getHookDecoupled=function(){var t=r.getStateClone,e=r.getMetadataClone;return[t,r.getStateOrchestrator(),e]},this.getSetStateWrapper=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).invokerSetState;return function(e){r.computeSetState({invokerSetState:t,setter:e})}},this.hasStateCallbacks=function(){var t=r.computePreventStateChange,e=r.onStateChanged,n=r.config,o=n.computePreventStateChange,a=n.onStateChanged;return!!(t||o||e||a)},this.computeSetState=function(t){var e=t.setter,n=t.invokerSetState,o="function"==typeof e,a=r.getStateClone(),i=o?e(a):e,s=r.hasStateCallbacks(),u=s&&r.getStoreActionsMap({}),l=s&&r.getSetStateWrapper({invokerSetState:n}),c={setMetadata:r.setMetadata,getMetadata:r.getMetadataClone,setState:l,getState:r.getStateClone,actions:u,previousState:a,state:i},f=r.computePreventStateChange,S=r.config.computePreventStateChange;if(!f&&!S||!(null==f?void 0:f(c))&&!(null==S?void 0:S(c))){r.setState({invokerSetState:n,state:i});var g=r.onStateChanged,v=r.config.onStateChanged;(g||v)&&(null==g||g(c),null==v||v(c))}},this.getStoreActionsMap=function(t){var e=t.invokerSetState;if(!r.setterConfig)return null;var n=r.setterConfig,o=r.setMetadata,a=n,s=Object.keys(a),u=r.getSetStateWrapper({invokerSetState:e}),l=r.getStateClone,c=r.getMetadataClone,f=s.reduce((function(t,e){return Object.assign(Object.assign({},t),(r={},s=function(){for(var t=a[e],r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];var s=t.apply(f,n);return"function"!=typeof s&&function(t){throw new Error("[WRONG CONFIGURATION!]: Every key inside the storeActionsConfig must be a higher order function that returns a function \n[".concat(t,"]: key is not a valid function, try something like this: \n{\n\n ").concat(t,": (param) => ({ setState, getState, setMetadata, getMetadata }) => {\n\n setState((state) => ({ ...state, ...param }))\n\n }\n\n}\n"))}(e),s.call(f,{setState:u,getState:l,setMetadata:o,getMetadata:c})},(n=i(n=e))in r?Object.defineProperty(r,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):r[n]=s,r));var r,n,s}),{});return f},this.config=Object.assign({metadata:null},null!=n?n:{}),this.onInitializeStore()}var e,r;return e=t,(r=[{key:"getStateOrchestrator",value:function(t){return this.setterConfig?this.getStoreActionsMap({invokerSetState:t}):this.getSetStateWrapper({invokerSetState:t})}}])&&a(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.GlobalStore=c},530:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},991:(t,e,r)=>{var n=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]},o=function(t,e){for(var r in t)"default"===r||Object.prototype.hasOwnProperty.call(e,r)||n(e,t,r)};Object.defineProperty(e,"__esModule",{value:!0}),o(r(530),e),o(r(774),e)},789:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatToStore=e.formatFromStore=e.isPrimitive=e.isRegex=e.isDate=e.isString=e.isBoolean=e.isNumber=e.isNil=e.clone=void 0,e.clone=t=>{if((0,e.isPrimitive)(t)||(0,e.isDate)(t))return t;if(Array.isArray(t))return t.map((t=>(0,e.clone)(t)));if(t instanceof Map){const r=Array.from(t.entries());return new Map(r.map((t=>(0,e.clone)(t))))}if(t instanceof Set){const r=Array.from(t.values());return new Set(r.map((t=>(0,e.clone)(t))))}return t instanceof RegExp?new RegExp(t.toString()):t instanceof Error?new Error(t.message):Object.keys(t).reduce(((r,n)=>{const o=t[n];return Object.assign(Object.assign({},r),{[n]:(0,e.clone)(o)})}),{})},e.isNil=t=>null==t,e.isNumber=t=>"number"==typeof t,e.isBoolean=t=>"boolean"==typeof t,e.isString=t=>"string"==typeof t,e.isDate=t=>t instanceof Date,e.isRegex=t=>t instanceof RegExp,e.isPrimitive=t=>(0,e.isNil)(t)||(0,e.isNumber)(t)||(0,e.isBoolean)(t)||(0,e.isString)(t)||"symbol"==typeof t,e.formatFromStore=t=>(t=>{var r,n;if((0,e.isPrimitive)(t))return t;if("date"===(null==t?void 0:t.$t))return new Date(t.$v);if("map"===(null==t?void 0:t.$t)){const n=(null!==(r=t.$v)&&void 0!==r?r:[]).map((([t,r])=>[t,(0,e.formatFromStore)(r)]));return new Map(n)}if("set"===(null==t?void 0:t.$t)){const r=null!==(n=t.$v)&&void 0!==n?n:[].map((t=>(0,e.formatFromStore)(t)));return new Set(r)}return"regex"===(null==t?void 0:t.$t)?new RegExp(t.$v):"error"===(null==t?void 0:t.$t)?new Error(t.$v):Array.isArray(t)?t.map((t=>(0,e.formatFromStore)(t))):Object.keys(t).reduce(((r,n)=>{const o=t[n];return Object.assign(Object.assign({},r),{[n]:(0,e.formatFromStore)(o)})}),{})})((0,e.clone)(t)),e.formatToStore=(t,{stringify:r}={stringify:!1})=>{const n=(o=(0,e.clone)(t),(0,e.isPrimitive)(o)?o:Array.isArray(o)?o.map((t=>(0,e.formatToStore)(t))):o instanceof Map?{$t:"map",$v:Array.from(o.entries()).map((t=>(0,e.formatToStore)(t)))}:o instanceof Set?{$t:"set",$v:Array.from(o.values()).map((t=>(0,e.formatToStore)(t)))}:(0,e.isDate)(o)?{$t:"date",$v:o.toISOString()}:(0,e.isRegex)(o)?{$t:"regex",$v:o.toString()}:o instanceof Error?{$t:"error",$v:o.message}:Object.keys(o).reduce(((t,r)=>{const n=o[r];return Object.assign(Object.assign({},t),{[r]:(0,e.formatToStore)(n)})}),{}));var o;return r?JSON.stringify(n):n}},156:e=>{e.exports=t}},r={};return function t(n){var o=r[n];if(void 0!==o)return o.exports;var a=r[n]={exports:{}};return e[n](a,a.exports,t),a.exports}(991)})()));
package/lib/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from './GlobalStore.types';
2
2
  export * from './GlobalStore';
3
- //# sourceMappingURL=index.d.ts.map
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "react-native-global-state-hooks",
3
- "version": "2.1.22",
3
+ "version": "3.0.0",
4
4
  "description": "This is a package to easily handling global-state across your react-native-components No-redux",
5
- "main": "lib/index.js",
5
+ "main": "lib/bundle.js",
6
6
  "types": "lib/index.d.ts",
7
7
  "files": [
8
8
  "lib"
@@ -11,7 +11,7 @@
11
11
  "test:debug": "node --inspect-brk node_modules/.bin/jest --watch --runInBand",
12
12
  "test:quick": "jest --maxWorkers=4 -c --no-watchman -u",
13
13
  "test:coverage": "jest --maxWorkers=4 -c --colors --no-watchman --verbose --coverage",
14
- "build": "tsc",
14
+ "build": "webpack --config webpack.config.js",
15
15
  "prepare": "npm run build",
16
16
  "version": "npm run format && git add -A src",
17
17
  "postversion": "git push && git push --tags",
@@ -41,6 +41,11 @@
41
41
  },
42
42
  "homepage": "https://github.com/johnny-quesada-developer/react-native-global-state-hooks#readme",
43
43
  "devDependencies": {
44
+ "@babel/core": "^7.21.3",
45
+ "@babel/plugin-transform-modules-commonjs": "^7.21.2",
46
+ "@babel/preset-env": "^7.20.2",
47
+ "@babel/preset-react": "^7.18.6",
48
+ "@babel/preset-typescript": "^7.21.0",
44
49
  "@types/jest": "^26.0.17",
45
50
  "@types/lodash": "^4.14.165",
46
51
  "@types/react": "^17.0.0",
@@ -48,6 +53,7 @@
48
53
  "@types/react-test-renderer": "^17.0.0",
49
54
  "@typescript-eslint/eslint-plugin": "^4.9.1",
50
55
  "@typescript-eslint/parser": "^4.9.1",
56
+ "babel-loader": "^9.1.2",
51
57
  "cancelable-promise-jq": "^1.0.4",
52
58
  "eslint": "^7.15.0",
53
59
  "eslint-config-airbnb": "^18.2.1",
@@ -60,12 +66,16 @@
60
66
  "react": ">=17.0.0",
61
67
  "react-test-renderer": "^17.0.1",
62
68
  "ts-jest": "^26.4.4",
69
+ "ts-loader": "^9.4.2",
63
70
  "tslib": "^2.5.0",
64
- "typescript": "^4.9.5"
71
+ "typescript": "^4.9.5",
72
+ "webpack": "^5.76.3",
73
+ "webpack-cli": "^5.0.1"
65
74
  },
66
75
  "peerDependencies": {
67
- "json-storage-formatter": ">=1.0.5",
68
76
  "react": ">=17.0.0"
69
77
  },
70
- "dependencies": {}
78
+ "dependencies": {
79
+ "json-storage-formatter": ">=1.0.5"
80
+ }
71
81
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalStore.d.ts","sourceRoot":"","sources":["../src/GlobalStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAExE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAuB,MAAM,OAAO,CAAC;AAEtE,OAAO,EACL,sBAAsB,EACtB,WAAW,EACX,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EAEzB,MAAM,qBAAqB,CAAC;AAU7B;;;;;KAKK;AACL,qBAAa,WAAW,CACtB,MAAM,EACN,SAAS,GAAG,IAAI,EAChB,YAAY,SACR,sBAAsB,CAAC,MAAM,EAAE,SAAS,CAAC,GACzC,W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SAAS,CAAC,aAAa,QAAO,MAAM,CAAsB;IAE1D;;;SAGK;IACL,SAAS,CAAC,gBAAgB,QAAO,SAAS,CACU;IAEpD;;;;SAIK;IACL,SAAS,CAAC,QAAQ;eAIT,MAAM;0BACK,cAAc,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;eAc9D;IAEF;;;SAGK;IACL,SAAS,CAAC,WAAW,EAAE,WAAW,CAAC,SAAS,CAAC,CAW3C;IAEF;;;;;;SAMK;IACL,SAAS,CAAC,sBAAsB;0BAGZ,cAAc,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;UAC5D,yBAAyB,MAAM,EAAE,SAAS,EAAE,YAAY,CAAC,CAsB3D;IAEF;;;SAGK;IACE,OAAO,4JA8BZ;IAEF;;;SAGK;IACE,gBAAgB,eAMb,MAAM,kIAIN,SAAS,EAEjB;IAEF;;;;SAIK;IACL,SAAS,CAAC,kBAAkB;0BAGR,cAAc,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;UACvD,YAAY,MAAM,CAAC,CAM1B;IAEF;;;;SAIK;IACL,SAAS,CAAC,oBAAoB,CAC5B,eAAe,CAAC,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;IAWhE;;;SAGK;IACL,SAAS,CAAC,iBAAiB,QAAO,OAAO,CAgBvC;IAEF;;;;;;OAMG;IACH,SAAS,CAAC,eAAe;gBAIf,YAAY,MAAM,CAAC;0BACT,cAAc,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;eAwD9D;IAEF;;;;SAIK;IACL,SAAS,CAAC,kBAAkB;0BAGR,cAAc,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;UAC5D,uBAAuB,MAAM,EAAE,SAAS,EAAE,YAAY,CAAC,CAgDzD;CACH"}
@@ -1,318 +0,0 @@
1
- export { formatFromStore, formatToStore } from 'json-storage-formatter';
2
- import { clone } from 'json-storage-formatter';
3
- import { useEffect, useState } from 'react';
4
- const throwWrongKeyOnActionCollectionConfig = (action_key) => {
5
- throw new Error(`[WRONG CONFIGURATION!]: Every key inside the storeActionsConfig must be a higher order function that returns a function \n[${action_key}]: key is not a valid function, try something like this: \n{\n
6
- ${action_key}: (param) => ({ setState, getState, setMetadata, getMetadata }) => {\n
7
- setState((state) => ({ ...state, ...param }))\n
8
- }\n
9
- }\n`);
10
- };
11
- /**
12
- * The GlobalStore class is the main class of the library and it is used to create a GlobalStore instances
13
- * @template {TState} TState - The type of the state object
14
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
15
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
16
- * */
17
- export class GlobalStore {
18
- /**
19
- * Create a new instance of the GlobalStore
20
- * @param {TState} state - The initial state
21
- * @param {GlobalStoreConfig<TState, TMetadata>} config - The configuration object (optional) (default: { metadata: null })
22
- * @param {GlobalStoreConfig<TState, TMetadata>} config.metadata - The metadata object (optional) (default: null) if not null the metadata object will be reactive
23
- * @param {GlobalStoreConfig<TState, TMetadata>} config.onInit - The callback to execute when the store is initialized (optional) (default: null)
24
- * @param {GlobalStoreConfig<TState, TMetadata>} config.onStateChanged - The callback to execute when the state is changed (optional) (default: null)
25
- * @param {GlobalStoreConfig<TState, TMetadata>} config.onSubscribed - The callback to execute when a new component gets subscribed to the store (optional) (default: null)
26
- * @param {GlobalStoreConfig<TState, TMetadata>} config.computePreventStateChange - The callback to execute everytime a state change is triggered and before the state is updated, it allows to prevent the state change by returning true (optional) (default: null) * @param {TStateSetter} setterConfig - The actions configuration object (optional) (default: null) if not null the store manipulation will be done through the actions
27
- * */
28
- constructor(state, config = {}, setterConfig = null) {
29
- this.state = state;
30
- this.setterConfig = setterConfig;
31
- /**
32
- * list of all the subscribers setState functions
33
- * @template {TState} TState - The type of the state object
34
- * */
35
- this.subscribers = new Set();
36
- /**
37
- * additional configuration for the store
38
- * @template {TState} TState - The type of the state object
39
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
40
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
41
- * @property {GlobalStoreConfig<TState, TMetadata, TStateSetter>} config.metadata - The metadata to pass to the callbacks (optional) (default: null)
42
- * @property {GlobalStoreConfig<TState, TMetadata, TStateSetter>} config.onInit - The callback to execute when the store is initialized (optional) (default: null)
43
- * @property {GlobalStoreConfig<TState, TMetadata, TStateSetter>} config.onStateChanged - The callback to execute when the state is changed (optional) (default: null)
44
- * @property {GlobalStoreConfig<TState, TMetadata, TStateSetter>} config.onSubscribed - The callback to execute when a component is subscribed to the store (optional) (default: null)
45
- * @property {GlobalStoreConfig<TState, TMetadata, TStateSetter>} config.computePreventStateChange - The callback to execute when the state is changed to compute if the state change should be prevented (optional) (default: null)
46
- */
47
- this.config = {
48
- metadata: null,
49
- };
50
- /**
51
- * execute once the store is created
52
- * @template {TState} TState - The type of the state object
53
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
54
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
55
- * @param {StateConfigCallbackParam<TState, TMetadata, TStateSetter>} parameters - The parameters object brings the following properties: setState, getState, setMetadata, getMetadata
56
- * @param {Dispatch<SetStateAction<TState>>} parameters.setState - The setState function to update the state
57
- * @param {() => TState} parameters.getState - The getState function to get the state
58
- * @param {Dispatch<SetStateAction<TMetadata>>} parameters.setMetadata - The setMetadata function to update the metadata
59
- * @param {() => TMetadata} parameters.getMetadata - The getMetadata function to get the metadata
60
- * */
61
- this.onInit = null;
62
- /**
63
- * execute every time the state is changed
64
- * @template {TState} TState - The type of the state object
65
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
66
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
67
- * @param {StateConfigCallbackParam<TState, TMetadata, TStateSetter>} parameters - The parameters object brings the following properties: setState, getState, setMetadata, getMetadata
68
- * @param {Dispatch<SetStateAction<TState>>} parameters.setState - The setState function to update the state
69
- * @param {() => TState} parameters.getState - The getState function to get the state
70
- * @param {Dispatch<SetStateAction<TMetadata>>} parameters.setMetadata - The setMetadata function to update the metadata
71
- * @param {() => TMetadata} parameters.getMetadata - The getMetadata function to get the metadata
72
- * */
73
- this.onStateChanged = null;
74
- /**
75
- * Execute each time a new component gets subscribed to the store
76
- * @template {TState} TState - The type of the state object
77
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
78
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
79
- * @param {StateConfigCallbackParam<TState, TMetadata, TStateSetter>} parameters - The parameters object brings the following properties: setState, getState, setMetadata, getMetadata
80
- * @param {Dispatch<SetStateAction<TState>>} parameters.setState - The setState function to update the state
81
- * @param {() => TState} parameters.getState - The getState function to get the state
82
- * @param {Dispatch<SetStateAction<TMetadata>>} parameters.setMetadata - The setMetadata function to update the metadata
83
- * @param {() => TMetadata} parameters.getMetadata - The getMetadata function to get the metadata
84
- * */
85
- this.onSubscribed = null;
86
- /**
87
- * Execute everytime a state change is triggered and before the state is updated, it allows to prevent the state change by returning true
88
- * @template {TState} TState - The type of the state object
89
- * @template {TMetadata} TMetadata - The type of the metadata object (optional) (default: null) no reactive information set to share with the subscribers
90
- * @template {TStateSetter} TStateSetter - The type of the setterConfig object (optional) (default: null) if a configuration is passed, the hook will return an object with the actions then all the store manipulation will be done through the actions
91
- * @param {StateConfigCallbackParam<TState, TMetadata, TStateSetter>} parameters - The parameters object brings the following properties: setState, getState, setMetadata, getMetadata
92
- * @param {Dispatch<SetStateAction<TState>>} parameters.setState - The setState function to update the state
93
- * @param {() => TState} parameters.getState - The getState function to get the state
94
- * @param {Dispatch<SetStateAction<TMetadata>>} parameters.setMetadata - The setMetadata function to update the metadata
95
- * @param {() => TMetadata} parameters.getMetadata - The getMetadata function to get the metadata
96
- * @returns {boolean} - true to prevent the state change, false to allow the state change
97
- * */
98
- this.computePreventStateChange = null;
99
- this.onInitializeStore = () => {
100
- const { onInit } = this;
101
- const { onInit: onInitFromConfig } = this.config;
102
- if (!onInit && !onInitFromConfig)
103
- return;
104
- const parameters = this.getConfigCallbackParam({});
105
- onInit === null || onInit === void 0 ? void 0 : onInit(parameters);
106
- onInitFromConfig === null || onInitFromConfig === void 0 ? void 0 : onInitFromConfig(parameters);
107
- };
108
- /**
109
- * gets a clone of the state
110
- * @returns {TState} - The state clone
111
- * */
112
- this.getStateClone = () => clone(this.state);
113
- /**
114
- * gets a clone of the metadata
115
- * @returns {TMetadata} - The metadata clone
116
- * */
117
- this.getMetadataClone = () => { var _a, _b; return clone((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.metadata) !== null && _b !== void 0 ? _b : null); };
118
- /**
119
- * set the state and update all the subscribers
120
- * @param {StateSetter<TState>} setter - The setter function or the value to set
121
- * @param {React.Dispatch<React.SetStateAction<TState>>} invokerSetState - The setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
122
- * */
123
- this.setState = ({ invokerSetState, state, }) => {
124
- // update the state
125
- this.state = state;
126
- // execute first the callback of the component that invoked the state change
127
- invokerSetState === null || invokerSetState === void 0 ? void 0 : invokerSetState(state);
128
- // update all the subscribers
129
- this.subscribers.forEach((setState) => {
130
- if (setState === invokerSetState)
131
- return;
132
- setState(state);
133
- });
134
- };
135
- /**
136
- * Set the value of the metadata property, this is no reactive and will not trigger a re-render
137
- * @param {StateSetter<TMetadata>} setter - The setter function or the value to set
138
- * */
139
- this.setMetadata = (setter) => {
140
- var _a;
141
- const isSetterFunction = typeof setter === 'function';
142
- const metadata = isSetterFunction
143
- ? setter(this.getMetadataClone())
144
- : setter;
145
- this.config = Object.assign(Object.assign({}, ((_a = this.config) !== null && _a !== void 0 ? _a : {})), { metadata });
146
- };
147
- /**
148
- * get the parameters object to pass to the callback functions (onInit, onStateChanged, onSubscribed, computePreventStateChange)
149
- * this parameters object brings the following properties: setState, getState, setMetadata, getMetadata
150
- * this parameter object allows to update the state, get the state, update the metadata, get the metadata
151
- * @param {{ invokerSetState?: React.Dispatch<React.SetStateAction<TState>> }} parameters - The setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
152
- * @returns {StateConfigCallbackParam<TState, TMetadata>} - The parameters object
153
- * */
154
- this.getConfigCallbackParam = ({ invokerSetState, }) => {
155
- const { setMetadata, getMetadataClone: getMetadata, getStateClone: getState, } = this;
156
- const setState = this.getSetStateWrapper({ invokerSetState });
157
- const actions = this.getStoreActionsMap({});
158
- return {
159
- setMetadata,
160
- getMetadata,
161
- getState,
162
- setState,
163
- actions,
164
- };
165
- };
166
- /**
167
- * Returns a custom hook that allows to handle a global state
168
- * @returns {[TState, TStateSetter, TMetadata]} - The state, the state setter or the actions map, the metadata
169
- * */
170
- this.getHook = () => () => {
171
- const [value, invokerSetState] = useState(() => this.state);
172
- useEffect(() => {
173
- this.subscribers.add(invokerSetState);
174
- const { onSubscribed } = this;
175
- const { onSubscribed: onSubscribedFromConfig } = this.config;
176
- if (onSubscribed || onSubscribedFromConfig) {
177
- const parameters = this.getConfigCallbackParam({ invokerSetState });
178
- onSubscribed === null || onSubscribed === void 0 ? void 0 : onSubscribed(parameters);
179
- onSubscribedFromConfig === null || onSubscribedFromConfig === void 0 ? void 0 : onSubscribedFromConfig(parameters);
180
- }
181
- return () => {
182
- this.subscribers.delete(invokerSetState);
183
- };
184
- }, []);
185
- const stateOrchestrator = this.getStateOrchestrator(invokerSetState);
186
- return [value, stateOrchestrator, this.getMetadataClone()];
187
- };
188
- /**
189
- * Returns an array with the a function to get the state, the state setter or the actions map, and a function to get the metadata
190
- * @returns {[() => TState, TStateSetter, () => TMetadata]} - The state getter, the state setter or the actions map, the metadata getter
191
- * */
192
- this.getHookDecoupled = () => {
193
- const { getStateClone: getState, getMetadataClone: getMetadata } = this;
194
- const stateOrchestrator = this.getStateOrchestrator();
195
- return [getState, stateOrchestrator, getMetadata];
196
- };
197
- /**
198
- * returns a wrapper for the setState function that will update the state and all the subscribers
199
- * @param {{ invokerSetState?: React.Dispatch<React.SetStateAction<TState>> }} parameters - The setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
200
- * @returns {StateSetter<TState>} - The state setter
201
- * */
202
- this.getSetStateWrapper = ({ invokerSetState, } = {}) => {
203
- const setState = (setter) => {
204
- this.computeSetState({ invokerSetState, setter });
205
- };
206
- return setState;
207
- };
208
- /**
209
- * Calculate whenever or not we should compute the callback parameters on the state change
210
- * @returns {boolean} - True if we should compute the callback parameters on the state change
211
- * */
212
- this.hasStateCallbacks = () => {
213
- const { computePreventStateChange, onStateChanged } = this;
214
- const { computePreventStateChange: computePreventStateChangeFromConfig, onStateChanged: onStateChangedFromConfig, } = this.config;
215
- const preventStateChangesCalls = computePreventStateChange || computePreventStateChangeFromConfig;
216
- const stateChangeCalls = onStateChanged || onStateChangedFromConfig;
217
- const shouldComputeParameter = preventStateChangesCalls || stateChangeCalls;
218
- return !!shouldComputeParameter;
219
- };
220
- /**
221
- * This is responsible for defining whenever or not the state change should be allowed or prevented
222
- * the function also execute the functions:
223
- * - onStateChanged (if defined) - this function is executed after the state change
224
- * - computePreventStateChange (if defined) - this function is executed before the state change and it should return a boolean value that will be used to determine if the state change should be prevented or not
225
- * @param {{ setter: StateSetter<TState>; invokerSetState?: React.Dispatch<React.SetStateAction<TState>> }} parameters - The state setter and the setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
226
- */
227
- this.computeSetState = ({ setter, invokerSetState, }) => {
228
- const isSetterFunction = typeof setter === 'function';
229
- const previousState = this.getStateClone();
230
- const newState = isSetterFunction
231
- ? setter(previousState)
232
- : setter;
233
- const itHasStateCallbacks = this.hasStateCallbacks();
234
- const actions = itHasStateCallbacks && this.getStoreActionsMap({});
235
- const setState = itHasStateCallbacks && this.getSetStateWrapper({ invokerSetState });
236
- const { setMetadata, getMetadataClone: getMetadata, getStateClone: getState, } = this;
237
- const callbackParameter = {
238
- setMetadata,
239
- getMetadata,
240
- setState,
241
- getState,
242
- actions,
243
- previousState,
244
- state: newState,
245
- };
246
- const { computePreventStateChange } = this;
247
- const { computePreventStateChange: computePreventStateChangeFromConfig } = this.config;
248
- // check if the state change should be prevented
249
- if (computePreventStateChange || computePreventStateChangeFromConfig) {
250
- const preventStateChange = (computePreventStateChange === null || computePreventStateChange === void 0 ? void 0 : computePreventStateChange(callbackParameter)) ||
251
- (computePreventStateChangeFromConfig === null || computePreventStateChangeFromConfig === void 0 ? void 0 : computePreventStateChangeFromConfig(callbackParameter));
252
- if (preventStateChange)
253
- return;
254
- }
255
- this.setState({
256
- invokerSetState,
257
- state: newState,
258
- });
259
- const { onStateChanged } = this;
260
- const { onStateChanged: onStateChangedFromConfig } = this.config;
261
- if (!onStateChanged && !onStateChangedFromConfig)
262
- return;
263
- onStateChanged === null || onStateChanged === void 0 ? void 0 : onStateChanged(callbackParameter);
264
- onStateChangedFromConfig === null || onStateChangedFromConfig === void 0 ? void 0 : onStateChangedFromConfig(callbackParameter);
265
- };
266
- /**
267
- * This creates a map of actions that can be used to modify or interact with the state
268
- * @param {{ invokerSetState?: React.Dispatch<React.SetStateAction<TState>> }} parameters - The setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
269
- * @returns {ActionCollectionResult<TState, TMetadata, TStateSetter>} - The actions map result of the configuration object passed to the constructor
270
- * */
271
- this.getStoreActionsMap = ({ invokerSetState, }) => {
272
- if (!this.setterConfig)
273
- return null;
274
- const { setterConfig, setMetadata } = this;
275
- const actionsConfig = setterConfig;
276
- const actionsKeys = Object.keys(actionsConfig);
277
- const setState = this.getSetStateWrapper({
278
- invokerSetState,
279
- });
280
- // we expose a copy of the state and metadata to the actions to prevent them from modifying the state directly
281
- const { getStateClone: getState, getMetadataClone: getMetadata } = this;
282
- // we bind the functions to the actions object to allow reusing actions in the same api config by using the -this- keyword
283
- const actions = actionsKeys.reduce((accumulator, action_key) => (Object.assign(Object.assign({}, accumulator), { [action_key](...parameres) {
284
- const actionConfig = actionsConfig[action_key];
285
- const action = actionConfig.apply(actions, parameres);
286
- const actionIsNotAFunction = typeof action !== 'function';
287
- // we throw an error if the action is not a function, this is mandatory for the correct execution of the actions
288
- if (actionIsNotAFunction) {
289
- throwWrongKeyOnActionCollectionConfig(action_key);
290
- }
291
- // executes the actions bringing access to the state setter and a copy of the state
292
- const result = action.call(actions, {
293
- setState,
294
- getState,
295
- setMetadata,
296
- getMetadata,
297
- });
298
- // we return the result of the actions to the invoker
299
- return result;
300
- } })), {});
301
- return actions;
302
- };
303
- this.config = Object.assign({ metadata: null }, (config !== null && config !== void 0 ? config : {}));
304
- this.onInitializeStore();
305
- }
306
- /**
307
- * Returns the state setter or the actions map
308
- * @param {{ invokerSetState?: React.Dispatch<React.SetStateAction<TState>> }} parameters - The setState function of the component that invoked the state change (optional) (default: null) this is used to updated first the component that invoked the state change
309
- * @returns {TStateSetter} - The state setter or the actions map
310
- * */
311
- getStateOrchestrator(invokerSetState) {
312
- const stateHasCustomActions = this.setterConfig;
313
- if (stateHasCustomActions) {
314
- return this.getStoreActionsMap({ invokerSetState });
315
- }
316
- return this.getSetStateWrapper({ invokerSetState });
317
- }
318
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalStore.types.d.ts","sourceRoot":"","sources":["../src/GlobalStore.types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,WAAW,CAAC,MAAM,IAAI,CAChC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,KACzC,IAAI,CAAC;AAEV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1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC"}
package/lib/index.js DELETED
@@ -1,2 +0,0 @@
1
- export * from './GlobalStore.types';
2
- export * from './GlobalStore';