@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,206 +0,0 @@
1
- /**
2
- * Loads and uses async data into the GlobalState path.
3
- */
4
-
5
- import { cloneDeep } from 'lodash';
6
- import { useEffect } from 'react';
7
- import { v4 as uuid } from 'uuid';
8
- import { getGlobalState } from "./GlobalStateProvider";
9
- import useGlobalState from "./useGlobalState";
10
- import { isDebugMode } from "./utils";
11
- const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
12
-
13
- /**
14
- * Executes the data loading operation.
15
- * @param {string} path Data segment path inside the global state.
16
- * @param {function} loader Data loader.
17
- * @param {GlobalState} globalState The global state instance.
18
- * @param {any} [oldData] Optional. Previously fetched data, currently stored in
19
- * the state, if already fetched by the caller; otherwise, they will be fetched
20
- * by the load() function itself.
21
- * @param {string} [opIdPrefix='C'] operationId prefix to use, which should be
22
- * 'C' at the client-side (default), or 'S' at the server-side (within SSR
23
- * context).
24
- * @return {Promise} Resolves once the operation is done.
25
- * @ignore
26
- */
27
- async function load(path, loader, globalState, oldData) {
28
- let opIdPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'C';
29
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
30
- /* eslint-disable no-console */
31
- console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
32
- /* eslint-enable no-console */
33
- }
34
-
35
- const operationId = opIdPrefix + uuid();
36
- const operationIdPath = path ? `${path}.operationId` : 'operationId';
37
- globalState.set(operationIdPath, operationId);
38
- const data = await loader(oldData || globalState.get(path).data);
39
- const state = globalState.get(path);
40
- if (operationId === state.operationId) {
41
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
42
- /* eslint-disable no-console */
43
- console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
44
- console.log('Data:', cloneDeep(data));
45
- /* eslint-enable no-console */
46
- }
47
-
48
- globalState.set(path, {
49
- ...state,
50
- data,
51
- operationId: '',
52
- timestamp: Date.now()
53
- });
54
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
55
- /* eslint-disable no-console */
56
- console.groupEnd();
57
- /* eslint-enable no-console */
58
- }
59
- }
60
- }
61
-
62
- /**
63
- * Resolves asynchronous data, and stores them at given `path` of global
64
- * state. When multiple components rely on asynchronous data at the same `path`,
65
- * the data are resolved once, and reused until their age is within specified
66
- * bounds. Once the data are stale, the hook allows to refresh them. It also
67
- * garbage-collects stale data from the global state when the last component
68
- * relying on them is unmounted.
69
- * @param {string} path Dot-delimitered state path, where data envelop is
70
- * stored.
71
- * @param {AsyncDataLoader} loader Asynchronous function which resolves (loads)
72
- * data, which should be stored at the global state `path`. When multiple
73
- * components
74
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
75
- * hook instances are called with the same `loader` (_i.e._ whichever of these
76
- * loaders is used to resolve async data, the result is acceptable to be reused
77
- * in all related components).
78
- * @param {object} [options] Additional options.
79
- * @param {any[]} [options.deps=[]] An array of dependencies, which trigger
80
- * data reload when changed. Given dependency changes are watched shallowly
81
- * (similarly to the standard React's
82
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
83
- * @param {boolean} [options.noSSR] If `true`, this hook won't load data during
84
- * server-side rendering.
85
- * @param {number} [options.garbageCollectAge=maxage] The maximum age of data
86
- * (in milliseconds), after which they are dropped from the state when the last
87
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
88
- * `maxage` option value.
89
- * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of
90
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
91
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
92
- * @param {number} [options.refreshAge=maxage] The maximum age of data
93
- * (in milliseconds), after which their refreshment will be triggered when
94
- * any component referencing them via `useAsyncData()` hook (re-)renders.
95
- * Defaults to `maxage` value.
96
- * @return {{
97
- * data: any,
98
- * loading: boolean,
99
- * timestamp: number
100
- * }} Returns an object with three fields: `data` holds the actual result of
101
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
102
- * is a boolean flag, which is `true` if data are being loaded (the hook is
103
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
104
- * is Unix timestamp of related data currently loaded into the global state.
105
- *
106
- * Note that loaded data, if any, are stored at the given `path` of global state
107
- * along with related meta-information, using slightly different state segment
108
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
109
- * can be accessed, and even modified using other hooks,
110
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
111
- * `useAsyncData()` hooks logic.
112
- */
113
- export default function useAsyncData(path, loader) {
114
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
115
- let {
116
- garbageCollectAge,
117
- maxage,
118
- refreshAge
119
- } = options;
120
- if (maxage === undefined) maxage = DEFAULT_MAXAGE;
121
- if (refreshAge === undefined) refreshAge = maxage;
122
- if (garbageCollectAge === undefined) garbageCollectAge = maxage;
123
-
124
- // Note: here we can't depend on useGlobalState() to init the initial value,
125
- // because that way we'll have issues with SSR (see details below).
126
- const globalState = getGlobalState();
127
- const state = globalState.get(path, {
128
- initialValue: {
129
- data: null,
130
- numRefs: 0,
131
- operationId: '',
132
- timestamp: 0
133
- }
134
- });
135
- if (globalState.ssrContext && !options.noSSR) {
136
- if (!state.timestamp && !state.operationId) {
137
- globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
138
- }
139
- } else {
140
- // This takes care about the client-side reference counting, and garbage
141
- // collection.
142
- //
143
- // Note: the Rules of Hook below are violated by conditional call to a hook,
144
- // but as the condition is actually server-side or client-side environment,
145
- // it is effectively non-conditional at the runtime.
146
- //
147
- // TODO: Though, maybe there is a way to refactor it into a cleaner code.
148
- // The same applies to other useEffect() hooks below.
149
- useEffect(() => {
150
- // eslint-disable-line react-hooks/rules-of-hooks
151
- const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
152
- const numRefs = globalState.get(numRefsPath);
153
- globalState.set(numRefsPath, numRefs + 1);
154
- return () => {
155
- const state2 = globalState.get(path);
156
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
157
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
158
- /* eslint-disable no-console */
159
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
160
- /* eslint-enable no-console */
161
- }
162
-
163
- globalState.set(path, {
164
- ...state2,
165
- data: null,
166
- numRefs: 0,
167
- timestamp: 0
168
- });
169
- } else globalState.set(numRefsPath, state2.numRefs - 1);
170
- };
171
- }, [garbageCollectAge, globalState, path]);
172
-
173
- // Note: a bunch of Rules of Hooks ignored belows because in our very
174
- // special case the otherwise wrong behavior is actually what we need.
175
-
176
- // Data loading and refreshing.
177
- let loadTriggered = false;
178
- useEffect(() => {
179
- // eslint-disable-line react-hooks/rules-of-hooks
180
- const state2 = globalState.get(path);
181
- if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
182
- load(path, loader, globalState, state2.data);
183
- loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
184
- }
185
- });
186
-
187
- const deps = options.deps || [];
188
- useEffect(() => {
189
- // eslint-disable-line react-hooks/rules-of-hooks
190
- if (!loadTriggered && deps.length) load(path, loader, globalState);
191
- }, deps); // eslint-disable-line react-hooks/exhaustive-deps
192
- }
193
-
194
- const [localState] = useGlobalState(path, {
195
- data: null,
196
- numRefs: 0,
197
- operationId: '',
198
- timestamp: 0
199
- });
200
- return {
201
- data: maxage < Date.now() - localState.timestamp ? null : localState.data,
202
- loading: Boolean(localState.operationId),
203
- timestamp: localState.timestamp
204
- };
205
- }
206
- //# sourceMappingURL=useAsyncData.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","data","get","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","initialValue","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,cAAc;AACvB,OAAOC,cAAc;AACrB,SAASC,WAAW;AAEpB,MAAMC,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,EAAoB;EAAA,IAAlBC,UAAU,uEAAG,GAAG;EACtE,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAIV,WAAW,EAAE,EAAE;IAC1D;IACAW,OAAO,CAACC,GAAG,CACR,4DAA2DT,IAAI,IAAI,EAAG,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C,aAAa,IAAIE,IAAI,CAACC,MAAM,EAAEvC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,CAAC;IACpE,CAAC,EAAEmC,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG3C,cAAc,CAACI,IAAI,EAAE;IACxCa,IAAI,EAAE,IAAI;IACVe,OAAO,EAAE,CAAC;IACVlB,WAAW,EAAE,EAAE;IACfO,SAAS,EAAE;EACb,CAAC,CAAC;EAEF,OAAO;IACLJ,IAAI,EAAEW,MAAM,GAAGN,IAAI,CAACC,GAAG,EAAE,GAAGoB,UAAU,CAACtB,SAAS,GAAG,IAAI,GAAGsB,UAAU,CAAC1B,IAAI;IACzE2B,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC7B,WAAW,CAAC;IACxCO,SAAS,EAAEsB,UAAU,CAACtB;EACxB,CAAC;AACH"}
@@ -1,109 +0,0 @@
1
- // Hook for updates of global state.
2
-
3
- import { cloneDeep, isFunction } from 'lodash';
4
- import { useEffect, useRef, useSyncExternalStore } from 'react';
5
- import { getGlobalState } from "./GlobalStateProvider";
6
- import { isDebugMode } from "./utils";
7
-
8
- /**
9
- * The primary hook for interacting with the global state, modeled after
10
- * the standard React's
11
- * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
12
- * It subscribes a component to a given `path` of global state, and provides
13
- * a function to update it. Each time the value at `path` changes, the hook
14
- * triggers re-render of its host component.
15
- *
16
- * **Note:**
17
- * - For performance, the library does not copy objects written to / read from
18
- * global state paths. You MUST NOT manually mutate returned state values,
19
- * or change objects already written into the global state, without explicitly
20
- * clonning them first yourself.
21
- * - State update notifications are asynchronous. When your code does multiple
22
- * global state updates in the same React rendering cycle, all state update
23
- * notifications are queued and dispatched together, after the current
24
- * rendering cycle. In other words, in any given rendering cycle the global
25
- * state values are "fixed", and all changes becomes visible at once in the
26
- * next triggered rendering pass.
27
- *
28
- * @param {string} [path] Dot-delimitered state path. It can be undefined to
29
- * subscribe for entire state.
30
- *
31
- * Under-the-hood state values are read and written using `lodash`
32
- * [_.get()](https://lodash.com/docs/4.17.15#get) and
33
- * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
34
- * to access state paths which have not been created before.
35
- * @param {any} [initialValue] Initial value to set at the `path`, or its
36
- * factory:
37
- * - If a function is given, it will act similar to
38
- * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
39
- * only if the value at `path` is `undefined`, the function will be executed,
40
- * and the value it returns will be written to the `path`.
41
- * - Otherwise, the given value itself will be written to the `path`,
42
- * if the current value at `path` is `undefined`.
43
- * @return {Array} It returs an array with two elements: `[value, setValue]`:
44
- *
45
- * - The `value` is the current value at given `path`.
46
- *
47
- * - The `setValue()` is setter function to write a new value to the `path`.
48
- *
49
- * Similar to the standard React's `useState()`, it supports
50
- * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
51
- * if `setValue()` is called with a function as argument, that function will
52
- * be called and its return value will be written to `path`. Otherwise,
53
- * the argument of `setValue()` itself is written to `path`.
54
- *
55
- * Also, similar to the standard React's state setters, `setValue()` is
56
- * stable function: it does not change between component re-renders.
57
- */
58
- export default function useGlobalState(path, initialValue) {
59
- const ref = useRef();
60
- if (!ref.current) {
61
- ref.current = {
62
- callbacks: [],
63
- setter: value => {
64
- const rc = ref.current;
65
- const newState = isFunction(value) ? value(rc.state) : value;
66
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
67
- /* eslint-disable no-console */
68
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
69
- console.log('New value:', cloneDeep(newState));
70
- console.groupEnd();
71
- /* eslint-enable no-console */
72
- }
73
-
74
- rc.globalState.set(rc.path, newState);
75
- },
76
- watcher: () => {
77
- const rc = ref.current;
78
- const state = rc.globalState.get(rc.path);
79
- if (state !== rc.state) {
80
- for (let i = 0; i < rc.callbacks.length; ++i) {
81
- rc.callbacks[i]();
82
- }
83
- }
84
- }
85
- };
86
- }
87
- const rc = ref.current;
88
- const globalState = getGlobalState();
89
- rc.globalState = globalState;
90
- rc.path = path;
91
- rc.state = useSyncExternalStore(cb => {
92
- rc.callbacks.push(cb);
93
- }, () => rc.globalState.get(rc.path, {
94
- initialValue
95
- }), () => rc.globalState.get(rc.path, {
96
- initialValue,
97
- initialState: true
98
- }));
99
- useEffect(() => {
100
- globalState.watch(rc.watcher);
101
- rc.watcher();
102
- return () => globalState.unWatch(rc.watcher);
103
- }, [globalState, rc]);
104
- useEffect(() => {
105
- rc.watcher();
106
- }, [path, rc]);
107
- return [rc.state, rc.setter];
108
- }
109
- //# sourceMappingURL=useGlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","getGlobalState","isDebugMode","useGlobalState","path","initialValue","ref","current","callbacks","setter","value","rc","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","globalState","set","watcher","get","i","length","cb","push","initialState","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":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,cAAc;AACvB,SAASC,WAAW;;AAEpB;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;AACA,eAAe,SAASC,cAAc,CAACC,IAAI,EAAEC,YAAY,EAAE;EACzD,MAAMC,GAAG,GAAGP,MAAM,EAAE;EACpB,IAAI,CAACO,GAAG,CAACC,OAAO,EAAE;IAChBD,GAAG,CAACC,OAAO,GAAG;MACZC,SAAS,EAAE,EAAE;MACbC,MAAM,EAAGC,KAAK,IAAK;QACjB,MAAMC,EAAE,GAAGL,GAAG,CAACC,OAAO;QACtB,MAAMK,QAAQ,GAAGf,UAAU,CAACa,KAAK,CAAC,GAAGA,KAAK,CAACC,EAAE,CAACE,KAAK,CAAC,GAAGH,KAAK;QAC5D,IAAII,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAId,WAAW,EAAE,EAAE;UAC1D;UACAe,OAAO,CAACC,cAAc,CACnB,+DACCP,EAAE,CAACP,IAAI,IAAI,EACZ,EAAC,CACH;UACDa,OAAO,CAAC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OAAO,EAAE;IACZ,OAAO,MAAMF,WAAW,CAACU,OAAO,CAACpB,EAAE,CAACY,OAAO,CAAC;EAC9C,CAAC,EAAE,CAACF,WAAW,EAAEV,EAAE,CAAC,CAAC;EAErBb,SAAS,CAAC,MAAM;IACda,EAAE,CAACY,OAAO,EAAE;EACd,CAAC,EAAE,CAACnB,IAAI,EAAEO,EAAE,CAAC,CAAC;EAEd,OAAO,CAACA,EAAE,CAACE,KAAK,EAAEF,EAAE,CAACF,MAAM,CAAC;AAC9B"}
@@ -1,23 +0,0 @@
1
- // Auxiliary stuff.
2
-
3
- /**
4
- * Returns 'true' if debug logging should be performed; 'false' otherwise.
5
- *
6
- * BEWARE: The actual safeguards for the debug logging still should read
7
- * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
8
- * // Some debug logging
9
- * }
10
- * to ensure that debug code is stripped out by Webpack in production mode.
11
- *
12
- * @returns {boolean}
13
- * @ignore
14
- */
15
- export function isDebugMode() {
16
- try {
17
- return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
18
- } catch (error) {
19
- return false;
20
- }
21
- }
22
- export default null;
23
- //# 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;AACA,OAAO,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;AAEA,eAAe,IAAI"}
@@ -1,174 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _lodash = require("lodash");
8
- var _utils = require("./utils");
9
- const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
10
- class GlobalState {
11
- #initialState;
12
- #nextNotifierId = null;
13
- #ssrContext;
14
- #currentState;
15
- #watchers = [];
16
-
17
- /**
18
- * Creates a new global state object.
19
- * @param {any} [initialState] Intial global state content.
20
- * @param {SsrContext} [ssrContext] Server-side rendering context.
21
- */
22
- constructor(initialState, ssrContext) {
23
- this.#currentState = initialState;
24
- this.#initialState = initialState;
25
- if (ssrContext) {
26
- /* eslint-disable no-param-reassign */
27
- ssrContext.dirty = false;
28
- ssrContext.pending = [];
29
- ssrContext.state = this.#currentState;
30
- /* eslint-enable no-param-reassign */
31
-
32
- this.#ssrContext = ssrContext;
33
- }
34
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
35
- /* eslint-disable no-console */
36
- let msg = 'New ReactGlobalState created';
37
- if (ssrContext) msg += ' (SSR mode)';
38
- console.groupCollapsed(msg);
39
- console.log('Initial state:', (0, _lodash.cloneDeep)(initialState));
40
- console.groupEnd();
41
- /* eslint-enable no-console */
42
- }
43
- }
44
-
45
- /**
46
- * Gets current or initial value at the specified "path" of the global state.
47
- * Allows to get the entire global state, and automatically set default value
48
- * at the "path".
49
- * @param {string} [path] Dot-delimitered state path. Pass it "null",
50
- * or "undefined" to refer the entire global state.
51
- * @param {object} [options={}] Additional options.
52
- * @param {boolean} [options.initialState] If "true" the value will be read
53
- * from the initial state instead of the current one.
54
- * @param {any} [options.initialValue] If the value read from the "path" is
55
- * "undefined", this "initialValue" will be returned instead. In such case
56
- * "initialValue" will also be written to the "path" of the current global
57
- * state (no matter "initialState" flag), if "undefined" is stored there.
58
- * @return {any} Retrieved value.
59
- */
60
- get(path, {
61
- initialState,
62
- initialValue
63
- } = {}) {
64
- const state = initialState ? this.#initialState : this.#currentState;
65
- let value = (0, _lodash.isNil)(path) ? state : (0, _lodash.get)(state, path);
66
- if (value === undefined && initialValue !== undefined) {
67
- value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
68
- if (!initialState || this.get(path) === undefined) this.set(path, value);
69
- }
70
- return value;
71
- }
72
-
73
- /**
74
- * Writes the `value` to given global state `path`.
75
- * @param {string} [path] Dot-delimitered state path. If not given, entire
76
- * global state content is replaced by the `value`.
77
- * @param {any} value The value.
78
- * @return {any} Given `value` itself.
79
- */
80
- set(path, value) {
81
- if (value !== this.get(path)) {
82
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
83
- /* eslint-disable no-console */
84
- console.groupCollapsed(`ReactGlobalState update. Path: "${path || ''}"`);
85
- console.log('New value:', (0, _lodash.cloneDeep)(value));
86
- /* eslint-enable no-console */
87
- }
88
-
89
- if ((0, _lodash.isNil)(path)) this.#currentState = value;else {
90
- const root = {
91
- state: this.#currentState
92
- };
93
- let segIdx = 0;
94
- let pos = root;
95
- const pathSegments = (0, _lodash.toPath)(`state.${path}`);
96
- for (; segIdx < pathSegments.length - 1; segIdx += 1) {
97
- const seg = pathSegments[segIdx];
98
- const next = pos[seg];
99
- if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
100
- ...next
101
- };else {
102
- // We arrived to a state sub-segment, where the remaining part of
103
- // the update path does not exist yet. We rely on lodash's set()
104
- // function to create the remaining path, and set the value.
105
- (0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
106
- break;
107
- }
108
- pos = pos[seg];
109
- }
110
- if (segIdx === pathSegments.length - 1) {
111
- pos[pathSegments[segIdx]] = value;
112
- }
113
- this.#currentState = root.state;
114
- }
115
- if (this.#ssrContext) {
116
- this.#ssrContext.dirty = true;
117
- this.#ssrContext.state = this.#currentState;
118
- } else if (!this.#nextNotifierId) {
119
- this.#nextNotifierId = setTimeout(() => {
120
- this.#nextNotifierId = null;
121
- [...this.#watchers].forEach(w => w());
122
- });
123
- }
124
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
125
- /* eslint-disable no-console */
126
- console.log('New state:', (0, _lodash.cloneDeep)(this.#currentState));
127
- console.groupEnd();
128
- /* eslint-enable no-console */
129
- }
130
- }
131
-
132
- return value;
133
- }
134
-
135
- /**
136
- * Unsubscribes `callback` from watching state updates; no operation if
137
- * `callback` is not subscribed to the state updates.
138
- * @param {function} callback
139
- * @throws if {@link SsrContext} is attached to the state instance: the state
140
- * watching functionality is intended for client-side (non-SSR) only.
141
- */
142
- unWatch(callback) {
143
- if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
144
- const watchers = this.#watchers;
145
- const pos = watchers.indexOf(callback);
146
- if (pos >= 0) {
147
- watchers[pos] = watchers[watchers.length - 1];
148
- watchers.pop();
149
- }
150
- }
151
- get ssrContext() {
152
- return this.#ssrContext;
153
- }
154
-
155
- /**
156
- * Subscribes `callback` to watch state updates; no operation if
157
- * `callback` is already subscribed to this state instance.
158
- * @param {function} callback It will be called without any arguments every
159
- * time the state content changes (note, howhever, separate state updates can
160
- * be applied to the state at once, and watching callbacks will be called once
161
- * after such bulk update).
162
- * @throws if {@link SsrContext} is attached to the state instance: the state
163
- * watching functionality is intended for client-side (non-SSR) only.
164
- */
165
- watch(callback) {
166
- if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
167
- const watchers = this.#watchers;
168
- if (watchers.indexOf(callback) < 0) {
169
- watchers.push(callback);
170
- }
171
- }
172
- }
173
- exports.default = GlobalState;
174
- //# sourceMappingURL=GlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalState.js","names":["ERR_NO_SSR_WATCH","GlobalState","initialState","nextNotifierId","ssrContext","currentState","watchers","constructor","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeep","groupEnd","get","path","initialValue","value","isNil","undefined","isFunction","set","root","segIdx","pos","pathSegments","toPath","length","seg","next","Array","isArray","isObject","slice","setTimeout","forEach","w","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.js"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport { isDebugMode } from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\nexport default class GlobalState {\n #initialState;\n\n #nextNotifierId = null;\n\n #ssrContext;\n\n #currentState;\n\n #watchers = [];\n\n /**\n * Creates a new global state object.\n * @param {any} [initialState] Intial global state content.\n * @param {SsrContext} [ssrContext] Server-side rendering context.\n */\n constructor(initialState, ssrContext) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.#ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * Allows to get the entire global state, and automatically set default value\n * at the \"path\".\n * @param {string} [path] Dot-delimitered state path. Pass it \"null\",\n * or \"undefined\" to refer the entire global state.\n * @param {object} [options={}] Additional options.\n * @param {boolean} [options.initialState] If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param {any} [options.initialValue] If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return {any} Retrieved value.\n */\n get(path, { initialState, initialValue } = {}) {\n const state = initialState ? this.#initialState : this.#currentState;\n let value = isNil(path) ? state : get(state, path);\n if (value === undefined && initialValue !== undefined) {\n value = isFunction(initialValue) ? initialValue() : initialValue;\n if (!initialState || this.get(path) === undefined) this.set(path, value);\n }\n return value;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param {string} [path] Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param {any} value The value.\n * @return {any} Given `value` itself.\n */\n set(path, value) {\n if (value !== this.get(path)) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState update. Path: \"${path || ''}\"`,\n );\n console.log('New value:', cloneDeep(value));\n /* eslint-enable no-console */\n }\n\n if (isNil(path)) this.#currentState = value;\n else {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n }\n\n if (this.#ssrContext) {\n this.#ssrContext.dirty = true;\n this.#ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = null;\n [...this.#watchers].forEach((w) => w());\n });\n }\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param {function} callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback) {\n if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n get ssrContext() { return this.#ssrContext; }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param {function} callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback) {\n if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;;AAAA;AAUA;AAEA,MAAMA,gBAAgB,GAAG,gDAAgD;AAE1D,MAAMC,WAAW,CAAC;EAC/B,CAACC,YAAY;EAEb,CAACC,cAAc,GAAG,IAAI;EAEtB,CAACC,UAAU;EAEX,CAACC,YAAY;EAEb,CAACC,QAAQ,GAAG,EAAE;;EAEd;AACF;AACA;AACA;AACA;EACEC,WAAW,CAACL,YAAY,EAAEE,UAAU,EAAE;IACpC,IAAI,CAAC,CAACC,YAAY,GAAGH,YAAY;IACjC,IAAI,CAAC,CAACA,YAAY,GAAGA,YAAY;IAEjC,IAAIE,UAAU,EAAE;MACd;MACAA,UAAU,CAACI,KAAK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