@dr.pogodin/react-global-state 0.9.2 → 0.10.0-alpha.1

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.
@@ -1,88 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = GlobalStateProvider;
8
- exports.getGlobalState = getGlobalState;
9
- exports.getSsrContext = getSsrContext;
10
- var _react = require("react");
11
- var _GlobalState = _interopRequireDefault(require("./GlobalState"));
12
- var _jsxRuntime = require("react/jsx-runtime");
13
- /* eslint-disable react/prop-types */
14
-
15
- const context = /*#__PURE__*/(0, _react.createContext)();
16
-
17
- /**
18
- * Gets {@link GlobalState} instance from the context. In most cases
19
- * you should use {@link useGlobalState}, and other hooks to interact with
20
- * the global state, instead of accessing it directly.
21
- * @return {GlobalState}
22
- */
23
- function getGlobalState() {
24
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
25
- // convention that hook names should start with use... This is intentional in
26
- // our case, as getGlobalState() hook is intended for advance scenarious,
27
- // while the normal interaction with the global state should happen via
28
- // another hook, useGlobalState().
29
- /* eslint-disable react-hooks/rules-of-hooks */
30
- const globalState = (0, _react.useContext)(context);
31
- /* eslint-enable react-hooks/rules-of-hooks */
32
- if (!globalState) throw new Error('Missing GlobalStateProvider');
33
- return globalState;
34
- }
35
-
36
- /**
37
- * @category Hooks
38
- * @desc Gets SSR context.
39
- * @param {boolean} [throwWithoutSsrContext=true] If `true` (default),
40
- * this hook will throw if no SSR context is attached to the global state;
41
- * set `false` to not throw in such case. In either case the hook will throw
42
- * if the {@link <GlobalStateProvider>} (hence the state) is missing.
43
- * @returns {SsrContext} SSR context.
44
- * @throws
45
- * - If current component has no parent {@link <GlobalStateProvider>}
46
- * in the rendered React tree.
47
- * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
48
- * to the global state provided by {@link <GlobalStateProvider>}.
49
- */
50
- function getSsrContext(throwWithoutSsrContext = true) {
51
- const {
52
- ssrContext
53
- } = getGlobalState();
54
- if (!ssrContext && throwWithoutSsrContext) {
55
- throw new Error('No SSR context found');
56
- }
57
- return ssrContext;
58
- }
59
-
60
- /**
61
- * Provides global state to its children.
62
- * @prop {ReactNode} [children] Component children, which will be provided with
63
- * the global state, and rendered in place of the provider.
64
- * @prop {any} [initialState] Initial content of the global state.
65
- * @prop {SsrContext} [ssrContext] Server-side rendering (SSR) context.
66
- * @prop {boolean|GlobalState} [stateProxy] This option is useful for code
67
- * splitting and SSR implementation:
68
- * - If `true`, this provider instance will fetch and reuse the global state
69
- * from a parent provider.
70
- * - If `GlobalState` instance, it will be used by this provider.
71
- * - If not given, a new `GlobalState` instance will be created and used.
72
- */
73
- function GlobalStateProvider({
74
- children,
75
- initialState,
76
- ssrContext,
77
- stateProxy
78
- }) {
79
- const state = (0, _react.useRef)();
80
- if (!state.current) {
81
- if (stateProxy instanceof _GlobalState.default) state.current = stateProxy;else if (stateProxy) state.current = getGlobalState();else state.current = new _GlobalState.default(initialState, ssrContext);
82
- }
83
- return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
84
- value: state.current,
85
- children: children
86
- });
87
- }
88
- //# sourceMappingURL=GlobalStateProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["context","createContext","getGlobalState","globalState","useContext","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","initialState","stateProxy","state","useRef","current","GlobalState"],"sources":["../../src/GlobalStateProvider.jsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { createContext, useContext, useRef } from 'react';\n\nimport GlobalState from './GlobalState';\n\nconst context = createContext();\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return {GlobalState}\n */\nexport function getGlobalState() {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param {boolean} [throwWithoutSsrContext=true] If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns {SsrContext} SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext(throwWithoutSsrContext = true) {\n const { ssrContext } = getGlobalState();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\n/**\n * Provides global state to its children.\n * @prop {ReactNode} [children] Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @prop {any} [initialState] Initial content of the global state.\n * @prop {SsrContext} [ssrContext] Server-side rendering (SSR) context.\n * @prop {boolean|GlobalState} [stateProxy] This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider({\n children,\n initialState,\n ssrContext,\n stateProxy,\n}) {\n const state = useRef();\n if (!state.current) {\n if (stateProxy instanceof GlobalState) state.current = stateProxy;\n else if (stateProxy) state.current = getGlobalState();\n else state.current = new GlobalState(initialState, ssrContext);\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n"],"mappings":";;;;;;;;;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_interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- Object.defineProperty(exports, "GlobalStateProvider", {
8
- enumerable: true,
9
- get: function () {
10
- return _GlobalStateProvider.default;
11
- }
12
- });
13
- Object.defineProperty(exports, "getGlobalState", {
14
- enumerable: true,
15
- get: function () {
16
- return _GlobalStateProvider.getGlobalState;
17
- }
18
- });
19
- Object.defineProperty(exports, "getSsrContext", {
20
- enumerable: true,
21
- get: function () {
22
- return _GlobalStateProvider.getSsrContext;
23
- }
24
- });
25
- Object.defineProperty(exports, "useAsyncCollection", {
26
- enumerable: true,
27
- get: function () {
28
- return _useAsyncCollection.default;
29
- }
30
- });
31
- Object.defineProperty(exports, "useAsyncData", {
32
- enumerable: true,
33
- get: function () {
34
- return _useAsyncData.default;
35
- }
36
- });
37
- Object.defineProperty(exports, "useGlobalState", {
38
- enumerable: true,
39
- get: function () {
40
- return _useGlobalState.default;
41
- }
42
- });
43
- var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
44
- var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
45
- var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
46
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
47
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
48
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
49
- // TODO: This is a temporary polyfill for `Promise.allSettled(..)` method,
50
- // which is supported natively by NodeJS >= v12.9.0. As earlier NodeJS version
51
- // are still in a wide use, this polyfill is added here, and it is to be dropped
52
- // some time later.
53
- if (!Promise.allSettled) {
54
- Promise.allSettled = promises => Promise.all(promises.map(p => p instanceof Promise ? p.finally(() => null) : p));
55
- }
56
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["Promise","allSettled","promises","all","map","p","finally"],"sources":["../../src/index.js"],"sourcesContent":["// TODO: This is a temporary polyfill for `Promise.allSettled(..)` method,\n// which is supported natively by NodeJS >= v12.9.0. As earlier NodeJS version\n// are still in a wide use, this polyfill is added here, and it is to be dropped\n// some time later.\nif (!Promise.allSettled) {\n Promise.allSettled = (promises) => Promise.all(\n promises.map((p) => (p instanceof Promise ? p.finally(() => null) : p)),\n );\n}\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as useAsyncCollection } from './useAsyncCollection';\nexport { default as useAsyncData } from './useAsyncData';\nexport { default as useGlobalState } from './useGlobalState';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAMA;AACA;AACA;AAA6D;AAAA;AAlB7D;AACA;AACA;AACA;AACA,IAAI,CAACA,OAAO,CAACC,UAAU,EAAE;EACvBD,OAAO,CAACC,UAAU,GAAIC,QAAQ,IAAKF,OAAO,CAACG,GAAG,CAC5CD,QAAQ,CAACE,GAAG,CAAEC,CAAC,IAAMA,CAAC,YAAYL,OAAO,GAAGK,CAAC,CAACC,OAAO,CAAC,MAAM,IAAI,CAAC,GAAGD,CAAE,CAAC,CACxE;AACH"}
@@ -1,63 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = useAsyncCollection;
8
- var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
9
- /**
10
- * Loads and uses an item in an async collection.
11
- */
12
-
13
- /**
14
- * Resolves and stores at the given `path` of global state elements of
15
- * an asynchronous data collection. In other words, it is an auxiliar wrapper
16
- * around {@link useAsyncData}, which uses a loader which resolves to different
17
- * data, based on ID argument passed in, and stores data fetched for different
18
- * IDs in the state.
19
- * @param {string} id ID of the collection item to load & use.
20
- * @param {string} path The global state path where entire collection should be
21
- * stored.
22
- * @param {AsyncCollectionLoader} loader A loader function, which takes an
23
- * ID of data to load, and resolves to the corresponding data.
24
- * @param {object} [options] Additional options.
25
- * @param {any[]} [options.deps=[]] An array of dependencies, which trigger
26
- * data reload when changed. Given dependency changes are watched shallowly
27
- * (similarly to the standard React's
28
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
29
- * @param {boolean} [options.noSSR] If `true`, this hook won't load data during
30
- * server-side rendering.
31
- * @param {number} [options.garbageCollectAge=maxage] The maximum age of data
32
- * (in milliseconds), after which they are dropped from the state when the last
33
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
34
- * `maxage` option value.
35
- * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of
36
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
37
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
38
- * @param {number} [options.refreshAge=maxage] The maximum age of data
39
- * (in milliseconds), after which their refreshment will be triggered when
40
- * any component referencing them via `useAsyncData()` hook (re-)renders.
41
- * Defaults to `maxage` value.
42
- * @return {{
43
- * data: any,
44
- * loading: boolean,
45
- * timestamp: number
46
- * }} Returns an object with three fields: `data` holds the actual result of
47
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
48
- * is a boolean flag, which is `true` if data are being loaded (the hook is
49
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
50
- * is Unix timestamp of related data currently loaded into the global state.
51
- *
52
- * Note that loaded data, if any, are stored at the given `path` of global state
53
- * along with related meta-information, using slightly different state segment
54
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
55
- * can be accessed, and even modified using other hooks,
56
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
57
- * `useAsyncData()` hooks logic.
58
- */
59
- function useAsyncCollection(id, path, loader, options = {}) {
60
- const itemPath = path ? `${path}.${id}` : id;
61
- return (0, _useAsyncData.default)(itemPath, oldData => loader(id, oldData), options);
62
- }
63
- //# sourceMappingURL=useAsyncCollection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData"],"sources":["../../src/useAsyncCollection.js"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData from './useAsyncData';\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param {string} id ID of the collection item to load & use.\n * @param {string} path The global state path where entire collection should be\n * stored.\n * @param {AsyncCollectionLoader} loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncCollection(\n id,\n path,\n loader,\n options = {},\n) {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData(itemPath, (oldData) => loader(id, oldData), options);\n}\n"],"mappings":";;;;;;;AAIA;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,kBAAkB,CACxCC,EAAE,EACFC,IAAI,EACJC,MAAM,EACNC,OAAO,GAAG,CAAC,CAAC,EACZ;EACA,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EAACD,QAAQ,EAAGE,OAAO,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAAEH,OAAO,CAAC;AAC1E"}
@@ -1,211 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = useAsyncData;
8
- var _lodash = require("lodash");
9
- var _react = require("react");
10
- var _uuid = require("uuid");
11
- var _GlobalStateProvider = require("./GlobalStateProvider");
12
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
13
- var _utils = require("./utils");
14
- /**
15
- * Loads and uses async data into the GlobalState path.
16
- */
17
-
18
- const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
19
-
20
- /**
21
- * Executes the data loading operation.
22
- * @param {string} path Data segment path inside the global state.
23
- * @param {function} loader Data loader.
24
- * @param {GlobalState} globalState The global state instance.
25
- * @param {any} [oldData] Optional. Previously fetched data, currently stored in
26
- * the state, if already fetched by the caller; otherwise, they will be fetched
27
- * by the load() function itself.
28
- * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be
29
- * 'C' at the client-side (default), or 'S' at the server-side (within SSR
30
- * context).
31
- * @return {Promise} Resolves once the operation is done.
32
- * @ignore
33
- */
34
- async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
35
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
36
- /* eslint-disable no-console */
37
- console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
38
- /* eslint-enable no-console */
39
- }
40
-
41
- const operationId = opIdPrefix + (0, _uuid.v4)();
42
- const operationIdPath = path ? `${path}.operationId` : 'operationId';
43
- globalState.set(operationIdPath, operationId);
44
- const data = await loader(oldData || globalState.get(path).data);
45
- const state = globalState.get(path);
46
- if (operationId === state.operationId) {
47
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
- /* eslint-disable no-console */
49
- console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
50
- console.log('Data:', (0, _lodash.cloneDeep)(data));
51
- /* eslint-enable no-console */
52
- }
53
-
54
- globalState.set(path, {
55
- ...state,
56
- data,
57
- operationId: '',
58
- timestamp: Date.now()
59
- });
60
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
61
- /* eslint-disable no-console */
62
- console.groupEnd();
63
- /* eslint-enable no-console */
64
- }
65
- }
66
- }
67
-
68
- /**
69
- * Resolves asynchronous data, and stores them at given `path` of global
70
- * state. When multiple components rely on asynchronous data at the same `path`,
71
- * the data are resolved once, and reused until their age is within specified
72
- * bounds. Once the data are stale, the hook allows to refresh them. It also
73
- * garbage-collects stale data from the global state when the last component
74
- * relying on them is unmounted.
75
- * @param {string} path Dot-delimitered state path, where data envelop is
76
- * stored.
77
- * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)
78
- * data, which should be stored at the global state `path`. When multiple
79
- * components
80
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
81
- * hook instances are called with the same `loader` (_i.e._ whichever of these
82
- * loaders is used to resolve async data, the result is acceptable to be reused
83
- * in all related components).
84
- * @param {object} [options] Additional options.
85
- * @param {any[]} [options.deps=[]] An array of dependencies, which trigger
86
- * data reload when changed. Given dependency changes are watched shallowly
87
- * (similarly to the standard React's
88
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
89
- * @param {boolean} [options.noSSR] If `true`, this hook won't load data during
90
- * server-side rendering.
91
- * @param {number} [options.garbageCollectAge=maxage] The maximum age of data
92
- * (in milliseconds), after which they are dropped from the state when the last
93
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
94
- * `maxage` option value.
95
- * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of
96
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
97
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
98
- * @param {number} [options.refreshAge=maxage] The maximum age of data
99
- * (in milliseconds), after which their refreshment will be triggered when
100
- * any component referencing them via `useAsyncData()` hook (re-)renders.
101
- * Defaults to `maxage` value.
102
- * @return {{
103
- * data: any,
104
- * loading: boolean,
105
- * timestamp: number
106
- * }} Returns an object with three fields: `data` holds the actual result of
107
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
108
- * is a boolean flag, which is `true` if data are being loaded (the hook is
109
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
110
- * is Unix timestamp of related data currently loaded into the global state.
111
- *
112
- * Note that loaded data, if any, are stored at the given `path` of global state
113
- * along with related meta-information, using slightly different state segment
114
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
115
- * can be accessed, and even modified using other hooks,
116
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
117
- * `useAsyncData()` hooks logic.
118
- */
119
- function useAsyncData(path, loader, options = {}) {
120
- let {
121
- garbageCollectAge,
122
- maxage,
123
- refreshAge
124
- } = options;
125
- if (maxage === undefined) maxage = DEFAULT_MAXAGE;
126
- if (refreshAge === undefined) refreshAge = maxage;
127
- if (garbageCollectAge === undefined) garbageCollectAge = maxage;
128
-
129
- // Note: here we can't depend on useGlobalState() to init the initial value,
130
- // because that way we'll have issues with SSR (see details below).
131
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
132
- const state = globalState.get(path, {
133
- initialValue: {
134
- data: null,
135
- numRefs: 0,
136
- operationId: '',
137
- timestamp: 0
138
- }
139
- });
140
- if (globalState.ssrContext && !options.noSSR) {
141
- if (!state.timestamp && !state.operationId) {
142
- globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
143
- }
144
- } else {
145
- // This takes care about the client-side reference counting, and garbage
146
- // collection.
147
- //
148
- // Note: the Rules of Hook below are violated by conditional call to a hook,
149
- // but as the condition is actually server-side or client-side environment,
150
- // it is effectively non-conditional at the runtime.
151
- //
152
- // TODO: Though, maybe there is a way to refactor it into a cleaner code.
153
- // The same applies to other useEffect() hooks below.
154
- (0, _react.useEffect)(() => {
155
- // eslint-disable-line react-hooks/rules-of-hooks
156
- const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
157
- const numRefs = globalState.get(numRefsPath);
158
- globalState.set(numRefsPath, numRefs + 1);
159
- return () => {
160
- const state2 = globalState.get(path);
161
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
162
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
163
- /* eslint-disable no-console */
164
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
165
- /* eslint-enable no-console */
166
- }
167
-
168
- globalState.set(path, {
169
- ...state2,
170
- data: null,
171
- numRefs: 0,
172
- timestamp: 0
173
- });
174
- } else globalState.set(numRefsPath, state2.numRefs - 1);
175
- };
176
- }, [garbageCollectAge, globalState, path]);
177
-
178
- // Note: a bunch of Rules of Hooks ignored belows because in our very
179
- // special case the otherwise wrong behavior is actually what we need.
180
-
181
- // Data loading and refreshing.
182
- let loadTriggered = false;
183
- (0, _react.useEffect)(() => {
184
- // eslint-disable-line react-hooks/rules-of-hooks
185
- const state2 = globalState.get(path);
186
- if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
187
- load(path, loader, globalState, state2.data);
188
- loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
189
- }
190
- });
191
-
192
- const deps = options.deps || [];
193
- (0, _react.useEffect)(() => {
194
- // eslint-disable-line react-hooks/rules-of-hooks
195
- if (!loadTriggered && deps.length) load(path, loader, globalState);
196
- }, deps); // eslint-disable-line react-hooks/exhaustive-deps
197
- }
198
-
199
- const [localState] = (0, _useGlobalState.default)(path, {
200
- data: null,
201
- numRefs: 0,
202
- operationId: '',
203
- timestamp: 0
204
- });
205
- return {
206
- data: maxage < Date.now() - localState.timestamp ? null : localState.data,
207
- loading: Boolean(localState.operationId),
208
- timestamp: localState.timestamp
209
- };
210
- }
211
- //# sourceMappingURL=useAsyncData.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncData.js","names":["DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","operationId","uuid","operationIdPath","set","data","get","state","groupCollapsed","cloneDeep","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","getGlobalState","initialValue","numRefs","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.js"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [oldData] Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param {object} [options] Additional options.\n * @param {any[]} [options.deps=[]] An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param {number} [options.refreshAge=maxage] The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) garbageCollectAge = maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get(path, {\n initialValue: {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n },\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState(path, {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n });\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n"],"mappings":";;;;;;;AAIA;AACA;AACA;AAEA;AACA;AACA;AAVA;AACA;AACA;;AAUA,MAAMA,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,UAAU,GAAG,GAAG,EAAE;EACxE,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,GAAE,EAAE;IAC1D;IACAC,OAAO,CAACC,GAAG,CACR,4DAA2DV,IAAI,IAAI,EAAG,GAAE,CAC1E;IACD;EACF;;EACA,MAAMW,WAAW,GAAGP,UAAU,GAAG,IAAAQ,QAAI,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AAI,CAACC,MAAM,EAAE5C,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,CAAC;IACpE,CAAC,EAAEwC,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EAAC7C,IAAI,EAAE;IACxCe,IAAI,EAAE,IAAI;IACViB,OAAO,EAAE,CAAC;IACVrB,WAAW,EAAE,EAAE;IACfS,SAAS,EAAE;EACb,CAAC,CAAC;EAEF,OAAO;IACLL,IAAI,EAAEY,MAAM,GAAGN,IAAI,CAACC,GAAG,EAAE,GAAGsB,UAAU,CAACxB,SAAS,GAAG,IAAI,GAAGwB,UAAU,CAAC7B,IAAI;IACzE+B,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACjC,WAAW,CAAC;IACxCS,SAAS,EAAEwB,UAAU,CAACxB;EACxB,CAAC;AACH"}
@@ -1,114 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = useGlobalState;
7
- var _lodash = require("lodash");
8
- var _react = require("react");
9
- var _GlobalStateProvider = require("./GlobalStateProvider");
10
- var _utils = require("./utils");
11
- // Hook for updates of global state.
12
-
13
- /**
14
- * The primary hook for interacting with the global state, modeled after
15
- * the standard React's
16
- * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
17
- * It subscribes a component to a given `path` of global state, and provides
18
- * a function to update it. Each time the value at `path` changes, the hook
19
- * triggers re-render of its host component.
20
- *
21
- * **Note:**
22
- * - For performance, the library does not copy objects written to / read from
23
- * global state paths. You MUST NOT manually mutate returned state values,
24
- * or change objects already written into the global state, without explicitly
25
- * clonning them first yourself.
26
- * - State update notifications are asynchronous. When your code does multiple
27
- * global state updates in the same React rendering cycle, all state update
28
- * notifications are queued and dispatched together, after the current
29
- * rendering cycle. In other words, in any given rendering cycle the global
30
- * state values are "fixed", and all changes becomes visible at once in the
31
- * next triggered rendering pass.
32
- *
33
- * @param {string} [path] Dot-delimitered state path. It can be undefined to
34
- * subscribe for entire state.
35
- *
36
- * Under-the-hood state values are read and written using `lodash`
37
- * [_.get()](https://lodash.com/docs/4.17.15#get) and
38
- * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
39
- * to access state paths which have not been created before.
40
- * @param {any} [initialValue] Initial value to set at the `path`, or its
41
- * factory:
42
- * - If a function is given, it will act similar to
43
- * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
44
- * only if the value at `path` is `undefined`, the function will be executed,
45
- * and the value it returns will be written to the `path`.
46
- * - Otherwise, the given value itself will be written to the `path`,
47
- * if the current value at `path` is `undefined`.
48
- * @return {Array} It returs an array with two elements: `[value, setValue]`:
49
- *
50
- * - The `value` is the current value at given `path`.
51
- *
52
- * - The `setValue()` is setter function to write a new value to the `path`.
53
- *
54
- * Similar to the standard React's `useState()`, it supports
55
- * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
56
- * if `setValue()` is called with a function as argument, that function will
57
- * be called and its return value will be written to `path`. Otherwise,
58
- * the argument of `setValue()` itself is written to `path`.
59
- *
60
- * Also, similar to the standard React's state setters, `setValue()` is
61
- * stable function: it does not change between component re-renders.
62
- */
63
- function useGlobalState(path, initialValue) {
64
- const ref = (0, _react.useRef)();
65
- if (!ref.current) {
66
- ref.current = {
67
- callbacks: [],
68
- setter: value => {
69
- const rc = ref.current;
70
- const newState = (0, _lodash.isFunction)(value) ? value(rc.state) : value;
71
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
72
- /* eslint-disable no-console */
73
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
74
- console.log('New value:', (0, _lodash.cloneDeep)(newState));
75
- console.groupEnd();
76
- /* eslint-enable no-console */
77
- }
78
-
79
- rc.globalState.set(rc.path, newState);
80
- },
81
- watcher: () => {
82
- const rc = ref.current;
83
- const state = rc.globalState.get(rc.path);
84
- if (state !== rc.state) {
85
- for (let i = 0; i < rc.callbacks.length; ++i) {
86
- rc.callbacks[i]();
87
- }
88
- }
89
- }
90
- };
91
- }
92
- const rc = ref.current;
93
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
94
- rc.globalState = globalState;
95
- rc.path = path;
96
- rc.state = (0, _react.useSyncExternalStore)(cb => {
97
- rc.callbacks.push(cb);
98
- }, () => rc.globalState.get(rc.path, {
99
- initialValue
100
- }), () => rc.globalState.get(rc.path, {
101
- initialValue,
102
- initialState: true
103
- }));
104
- (0, _react.useEffect)(() => {
105
- globalState.watch(rc.watcher);
106
- rc.watcher();
107
- return () => globalState.unWatch(rc.watcher);
108
- }, [globalState, rc]);
109
- (0, _react.useEffect)(() => {
110
- rc.watcher();
111
- }, [path, rc]);
112
- return [rc.state, rc.setter];
113
- }
114
- //# sourceMappingURL=useGlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["useGlobalState","path","initialValue","ref","useRef","current","callbacks","setter","value","rc","newState","isFunction","state","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","globalState","set","watcher","get","i","length","getGlobalState","useSyncExternalStore","cb","push","initialState","useEffect","watch","unWatch"],"sources":["../../src/useGlobalState.js"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param {string} [path] Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param {any} [initialValue] Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return {Array} It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\nexport default function useGlobalState(path, initialValue) {\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n callbacks: [],\n setter: (value) => {\n const rc = ref.current;\n const newState = isFunction(value) ? value(rc.state) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set(rc.path, newState);\n },\n watcher: () => {\n const rc = ref.current;\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) {\n for (let i = 0; i < rc.callbacks.length; ++i) {\n rc.callbacks[i]();\n }\n }\n },\n };\n }\n\n const rc = ref.current;\n const globalState = getGlobalState();\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => { rc.callbacks.push(cb); },\n () => rc.globalState.get(rc.path, { initialValue }),\n () => rc.globalState.get(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n globalState.watch(rc.watcher);\n rc.watcher();\n return () => globalState.unWatch(rc.watcher);\n }, [globalState, rc]);\n\n useEffect(() => {\n rc.watcher();\n }, [path, rc]);\n\n return [rc.state, rc.setter];\n}\n"],"mappings":";;;;;;AAEA;AACA;AAEA;AACA;AANA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,cAAc,CAACC,IAAI,EAAEC,YAAY,EAAE;EACzD,MAAMC,GAAG,GAAG,IAAAC,aAAM,GAAE;EACpB,IAAI,CAACD,GAAG,CAACE,OAAO,EAAE;IAChBF,GAAG,CAACE,OAAO,GAAG;MACZC,SAAS,EAAE,EAAE;MACbC,MAAM,EAAGC,KAAK,IAAK;QACjB,MAAMC,EAAE,GAAGN,GAAG,CAACE,OAAO;QACtB,MAAMK,QAAQ,GAAG,IAAAC,kBAAU,EAACH,KAAK,CAAC,GAAGA,KAAK,CAACC,EAAE,CAACG,KAAK,CAAC,GAAGJ,KAAK;QAC5D,IAAIK,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,GAAE,EAAE;UAC1D;UACAC,OAAO,CAACC,cAAc,CACnB,+DACCT,EAAE,CAACR,IAAI,IAAI,EACZ,EAAC,CACH;UACDgB,OA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ACe,OAAO,CAAC;IAC7Bf,EAAE,CAACe,OAAO,EAAE;IACZ,OAAO,MAAMF,WAAW,CAACa,OAAO,CAAC1B,EAAE,CAACe,OAAO,CAAC;EAC9C,CAAC,EAAE,CAACF,WAAW,EAAEb,EAAE,CAAC,CAAC;EAErB,IAAAwB,gBAAS,EAAC,MAAM;IACdxB,EAAE,CAACe,OAAO,EAAE;EACd,CAAC,EAAE,CAACvB,IAAI,EAAEQ,EAAE,CAAC,CAAC;EAEd,OAAO,CAACA,EAAE,CAACG,KAAK,EAAEH,EAAE,CAACF,MAAM,CAAC;AAC9B"}
@@ -1,31 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- exports.isDebugMode = isDebugMode;
8
- // Auxiliary stuff.
9
-
10
- /**
11
- * Returns 'true' if debug logging should be performed; 'false' otherwise.
12
- *
13
- * BEWARE: The actual safeguards for the debug logging still should read
14
- * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
15
- * // Some debug logging
16
- * }
17
- * to ensure that debug code is stripped out by Webpack in production mode.
18
- *
19
- * @returns {boolean}
20
- * @ignore
21
- */
22
- function isDebugMode() {
23
- try {
24
- return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
25
- } catch (error) {
26
- return false;
27
- }
28
- }
29
- var _default = null;
30
- exports.default = _default;
31
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.js"],"sourcesContent":["// Auxiliary stuff.\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns {boolean}\n * @ignore\n */\nexport function isDebugMode() {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n\nexport default null;\n"],"mappings":";;;;;;;AAAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,WAAW,GAAG;EAC5B,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF;AAAC,eAEc,IAAI;AAAA"}