@dr.pogodin/react-global-state 0.10.0-alpha.2 → 0.10.0-alpha.3

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.
Files changed (67) hide show
  1. package/README.md +2 -0
  2. package/build/common/GlobalState.js +219 -0
  3. package/build/common/GlobalState.js.map +1 -0
  4. package/build/common/GlobalStateProvider.js +101 -0
  5. package/build/common/GlobalStateProvider.js.map +1 -0
  6. package/build/common/SsrContext.js +15 -0
  7. package/build/common/SsrContext.js.map +1 -0
  8. package/build/common/index.js +76 -0
  9. package/build/common/index.js.map +1 -0
  10. package/build/common/useAsyncCollection.js +61 -0
  11. package/build/common/useAsyncCollection.js.map +1 -0
  12. package/build/common/useAsyncData.js +204 -0
  13. package/build/common/useAsyncData.js.map +1 -0
  14. package/build/common/useGlobalState.js +113 -0
  15. package/build/common/useGlobalState.js.map +1 -0
  16. package/build/common/utils.js +44 -0
  17. package/build/common/utils.js.map +1 -0
  18. package/build/common/withGlobalStateType.js +42 -0
  19. package/build/common/withGlobalStateType.js.map +1 -0
  20. package/build/module/GlobalState.js +230 -0
  21. package/build/module/GlobalState.js.map +1 -0
  22. package/build/module/GlobalStateProvider.js +94 -0
  23. package/build/module/GlobalStateProvider.js.map +1 -0
  24. package/build/module/SsrContext.js +9 -0
  25. package/build/module/SsrContext.js.map +1 -0
  26. package/build/module/index.js +8 -0
  27. package/build/module/index.js.map +1 -0
  28. package/build/module/useAsyncCollection.js +56 -0
  29. package/build/module/useAsyncCollection.js.map +1 -0
  30. package/build/module/useAsyncData.js +199 -0
  31. package/build/module/useAsyncData.js.map +1 -0
  32. package/build/module/useGlobalState.js +108 -0
  33. package/build/module/useGlobalState.js.map +1 -0
  34. package/build/module/utils.js +35 -0
  35. package/build/module/utils.js.map +1 -0
  36. package/build/module/withGlobalStateType.js +35 -0
  37. package/build/module/withGlobalStateType.js.map +1 -0
  38. package/build/{GlobalState.d.ts → types/GlobalState.d.ts} +6 -6
  39. package/build/{GlobalStateProvider.d.ts → types/GlobalStateProvider.d.ts} +8 -8
  40. package/build/{index.d.ts → types/index.d.ts} +1 -1
  41. package/build/{useAsyncCollection.d.ts → types/useAsyncCollection.d.ts} +2 -2
  42. package/build/{useAsyncData.d.ts → types/useAsyncData.d.ts} +2 -3
  43. package/build/{useGlobalState.d.ts → types/useGlobalState.d.ts} +2 -2
  44. package/build/{utils.d.ts → types/utils.d.ts} +4 -1
  45. package/build/types/withGlobalStateType.d.ts +29 -0
  46. package/package.json +43 -38
  47. package/src/GlobalState.ts +14 -10
  48. package/src/GlobalStateProvider.tsx +26 -15
  49. package/src/index.ts +1 -1
  50. package/src/useAsyncCollection.ts +5 -5
  51. package/src/useAsyncData.ts +27 -19
  52. package/src/useGlobalState.ts +9 -11
  53. package/src/utils.ts +8 -3
  54. package/src/withGlobalStateType.ts +77 -25
  55. package/tsconfig.json +9 -3
  56. package/tsconfig.types.json +14 -0
  57. package/build/GlobalState.js +0 -193
  58. package/build/GlobalStateProvider.js +0 -103
  59. package/build/SsrContext.js +0 -10
  60. package/build/index.js +0 -23
  61. package/build/useAsyncCollection.js +0 -14
  62. package/build/useAsyncData.js +0 -150
  63. package/build/useGlobalState.js +0 -49
  64. package/build/utils.js +0 -25
  65. package/build/withGlobalStateType.d.ts +0 -39
  66. package/build/withGlobalStateType.js +0 -55
  67. /package/build/{SsrContext.d.ts → types/SsrContext.d.ts} +0 -0
@@ -0,0 +1,199 @@
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 { MIN_MS } from '@dr.pogodin/js-utils';
9
+ import { getGlobalState } from "./GlobalStateProvider";
10
+ import useGlobalState from "./useGlobalState";
11
+ import { isDebugMode } from "./utils";
12
+ const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
13
+
14
+ export function newAsyncDataEnvelope() {
15
+ let initialData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
16
+ return {
17
+ data: initialData,
18
+ numRefs: 0,
19
+ operationId: '',
20
+ timestamp: 0
21
+ };
22
+ }
23
+ /**
24
+ * Executes the data loading operation.
25
+ * @param path Data segment path inside the global state.
26
+ * @param loader Data loader.
27
+ * @param globalState The global state instance.
28
+ * @param oldData Optional. Previously fetched data, currently stored in
29
+ * the state, if already fetched by the caller; otherwise, they will be fetched
30
+ * by the load() function itself.
31
+ * @param opIdPrefix operationId prefix to use, which should be
32
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
33
+ * context).
34
+ * @return Resolves once the operation is done.
35
+ * @ignore
36
+ */
37
+ async function load(path, loader, globalState, oldData) {
38
+ let opIdPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'C';
39
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
40
+ /* eslint-disable no-console */
41
+ console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
42
+ /* eslint-enable no-console */
43
+ }
44
+
45
+ const operationId = opIdPrefix + uuid();
46
+ const operationIdPath = path ? `${path}.operationId` : 'operationId';
47
+ globalState.set(operationIdPath, operationId);
48
+ const data = await loader(oldData || globalState.get(path).data);
49
+ const state = globalState.get(path);
50
+ if (operationId === state.operationId) {
51
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
52
+ /* eslint-disable no-console */
53
+ console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
54
+ console.log('Data:', cloneDeep(data));
55
+ /* eslint-enable no-console */
56
+ }
57
+
58
+ globalState.set(path, {
59
+ ...state,
60
+ data,
61
+ operationId: '',
62
+ timestamp: Date.now()
63
+ });
64
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
65
+ /* eslint-disable no-console */
66
+ console.groupEnd();
67
+ /* eslint-enable no-console */
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Resolves asynchronous data, and stores them at given `path` of global
74
+ * state. When multiple components rely on asynchronous data at the same `path`,
75
+ * the data are resolved once, and reused until their age is within specified
76
+ * bounds. Once the data are stale, the hook allows to refresh them. It also
77
+ * garbage-collects stale data from the global state when the last component
78
+ * relying on them is unmounted.
79
+ * @param path Dot-delimitered state path, where data envelop is
80
+ * stored.
81
+ * @param loader Asynchronous function which resolves (loads)
82
+ * data, which should be stored at the global state `path`. When multiple
83
+ * components
84
+ * use `useAsyncData()` hook for the same `path`, the library assumes that all
85
+ * hook instances are called with the same `loader` (_i.e._ whichever of these
86
+ * loaders is used to resolve async data, the result is acceptable to be reused
87
+ * in all related components).
88
+ * @param options Additional options.
89
+ * @param options.deps An array of dependencies, which trigger
90
+ * data reload when changed. Given dependency changes are watched shallowly
91
+ * (similarly to the standard React's
92
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
93
+ * @param options.noSSR If `true`, this hook won't load data during
94
+ * server-side rendering.
95
+ * @param options.garbageCollectAge The maximum age of data
96
+ * (in milliseconds), after which they are dropped from the state when the last
97
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
98
+ * `maxage` option value.
99
+ * @param options.maxage The maximum age of
100
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
101
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
102
+ * @param options.refreshAge The maximum age of data
103
+ * (in milliseconds), after which their refreshment will be triggered when
104
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
105
+ * Defaults to `maxage` value.
106
+ * @return 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 AsyncDataEnvelopeT}). 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
+
120
+ function useAsyncData(path, loader) {
121
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
122
+ const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
123
+ const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
124
+ const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
125
+
126
+ // Note: here we can't depend on useGlobalState() to init the initial value,
127
+ // because that way we'll have issues with SSR (see details below).
128
+ const globalState = getGlobalState();
129
+ const state = globalState.get(path, {
130
+ initialValue: newAsyncDataEnvelope()
131
+ });
132
+ if (globalState.ssrContext && !options.noSSR) {
133
+ if (!state.timestamp && !state.operationId) {
134
+ globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
135
+ }
136
+ } else {
137
+ // This takes care about the client-side reference counting, and garbage
138
+ // collection.
139
+ //
140
+ // Note: the Rules of Hook below are violated by conditional call to a hook,
141
+ // but as the condition is actually server-side or client-side environment,
142
+ // it is effectively non-conditional at the runtime.
143
+ //
144
+ // TODO: Though, maybe there is a way to refactor it into a cleaner code.
145
+ // The same applies to other useEffect() hooks below.
146
+ useEffect(() => {
147
+ // eslint-disable-line react-hooks/rules-of-hooks
148
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
149
+ const numRefs = globalState.get(numRefsPath);
150
+ globalState.set(numRefsPath, numRefs + 1);
151
+ return () => {
152
+ const state2 = globalState.get(path);
153
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
154
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
155
+ /* eslint-disable no-console */
156
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
157
+ /* eslint-enable no-console */
158
+ }
159
+
160
+ globalState.set(path, {
161
+ ...state2,
162
+ data: null,
163
+ numRefs: 0,
164
+ timestamp: 0
165
+ });
166
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
167
+ };
168
+ }, [garbageCollectAge, globalState, path]);
169
+
170
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
171
+ // special case the otherwise wrong behavior is actually what we need.
172
+
173
+ // Data loading and refreshing.
174
+ let loadTriggered = false;
175
+ useEffect(() => {
176
+ // eslint-disable-line react-hooks/rules-of-hooks
177
+ const state2 = globalState.get(path);
178
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
179
+ load(path, loader, globalState, state2.data);
180
+ loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
181
+ }
182
+ });
183
+
184
+ const deps = options.deps || [];
185
+ useEffect(() => {
186
+ // eslint-disable-line react-hooks/rules-of-hooks
187
+ if (!loadTriggered && deps.length) load(path, loader, globalState, null);
188
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
189
+ }
190
+
191
+ const [localState] = useGlobalState(path, newAsyncDataEnvelope());
192
+ return {
193
+ data: maxage < Date.now() - localState.timestamp ? null : localState.data,
194
+ loading: Boolean(localState.operationId),
195
+ timestamp: localState.timestamp
196
+ };
197
+ }
198
+ export default useAsyncData;
199
+ //# sourceMappingURL=useAsyncData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"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 { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param 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 opIdPrefix 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 Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\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<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(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<ForceT, AsyncDataEnvelopeT<DataT>>(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 path Dot-delimitered state path, where data envelop is\n * stored.\n * @param 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 options Additional options.\n * @param 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 options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge 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 options.maxage 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 options.refreshAge 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 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 AsyncDataEnvelopeT}). 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 */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | false = false,\n DataT = unknown,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\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<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\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<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(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: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === '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, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\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\nexport default useAsyncData;\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAIEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAEP;EAAA,IAD3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAEhC,OAAO;IACLG,IAAI,EAAEJ,WAAW;IACjBK,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAIA,CACjBC,IAA+B,EA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AIqB,UAAU,GAAGN,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGa,MAAM,CAAC/B,SAAS,KAC1C,CAAC+B,MAAM,CAAChC,WAAW,IAAIgC,MAAM,CAAChC,WAAW,CAACkC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,EAAE;QAChEhC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE2B,MAAM,CAAClC,IAAI,CAAC;QAC5CmC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;;IAEF,MAAME,IAAI,GAAGb,OAAO,CAACa,IAAI,IAAI,EAAE;IAC/BlD,SAAS,CAAC,MAAM;MAAE;MAChB,IAAI,CAACgD,aAAa,IAAIE,IAAI,CAACvC,MAAM,EAAEM,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;IAC1E,CAAC,EAAE8B,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACC,UAAU,CAAC,GAAG9C,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLK,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGiB,UAAU,CAACnC,SAAS,GAAG,IAAI,GAAGmC,UAAU,CAACtC,IAAI;IACzEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpC,WAAW,CAAC;IACxCC,SAAS,EAAEmC,UAAU,CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
@@ -0,0 +1,108 @@
1
+ // Hook for updates of global state.
2
+
3
+ import { cloneDeep, isFunction } from 'lodash';
4
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
5
+ import { Emitter } from '@dr.pogodin/js-utils';
6
+ import { getGlobalState } from "./GlobalStateProvider";
7
+ import { isDebugMode } from "./utils";
8
+
9
+ /**
10
+ * The primary hook for interacting with the global state, modeled after
11
+ * the standard React's
12
+ * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
13
+ * It subscribes a component to a given `path` of global state, and provides
14
+ * a function to update it. Each time the value at `path` changes, the hook
15
+ * triggers re-render of its host component.
16
+ *
17
+ * **Note:**
18
+ * - For performance, the library does not copy objects written to / read from
19
+ * global state paths. You MUST NOT manually mutate returned state values,
20
+ * or change objects already written into the global state, without explicitly
21
+ * clonning them first yourself.
22
+ * - State update notifications are asynchronous. When your code does multiple
23
+ * global state updates in the same React rendering cycle, all state update
24
+ * notifications are queued and dispatched together, after the current
25
+ * rendering cycle. In other words, in any given rendering cycle the global
26
+ * state values are "fixed", and all changes becomes visible at once in the
27
+ * next triggered rendering pass.
28
+ *
29
+ * @param path Dot-delimitered state path. It can be undefined to
30
+ * subscribe for entire state.
31
+ *
32
+ * Under-the-hood state values are read and written using `lodash`
33
+ * [_.get()](https://lodash.com/docs/4.17.15#get) and
34
+ * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
35
+ * to access state paths which have not been created before.
36
+ * @param initialValue Initial value to set at the `path`, or its
37
+ * factory:
38
+ * - If a function is given, it will act similar to
39
+ * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
40
+ * only if the value at `path` is `undefined`, the function will be executed,
41
+ * and the value it returns will be written to the `path`.
42
+ * - Otherwise, the given value itself will be written to the `path`,
43
+ * if the current value at `path` is `undefined`.
44
+ * @return It returs an array with two elements: `[value, setValue]`:
45
+ *
46
+ * - The `value` is the current value at given `path`.
47
+ *
48
+ * - The `setValue()` is setter function to write a new value to the `path`.
49
+ *
50
+ * Similar to the standard React's `useState()`, it supports
51
+ * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
52
+ * if `setValue()` is called with a function as argument, that function will
53
+ * be called and its return value will be written to `path`. Otherwise,
54
+ * the argument of `setValue()` itself is written to `path`.
55
+ *
56
+ * Also, similar to the standard React's state setters, `setValue()` is
57
+ * stable function: it does not change between component re-renders.
58
+ */
59
+
60
+ function useGlobalState(path, initialValue) {
61
+ const globalState = getGlobalState();
62
+ const ref = useRef();
63
+ const rc = ref.current || {
64
+ emitter: new Emitter(),
65
+ globalState,
66
+ path,
67
+ setter: value => {
68
+ const newState = isFunction(value) ? value(rc.state) : value;
69
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
70
+ /* eslint-disable no-console */
71
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
72
+ console.log('New value:', cloneDeep(newState));
73
+ console.groupEnd();
74
+ /* eslint-enable no-console */
75
+ }
76
+
77
+ rc.globalState.set(rc.path, newState);
78
+ },
79
+ state: isFunction(initialValue) ? initialValue() : initialValue,
80
+ watcher: () => {
81
+ const state = rc.globalState.get(rc.path);
82
+ if (state !== rc.state) rc.emitter.emit();
83
+ }
84
+ };
85
+ ref.current = rc;
86
+ rc.globalState = globalState;
87
+ rc.path = path;
88
+ rc.state = useSyncExternalStore(cb => rc.emitter.addListener(cb), () => rc.globalState.get(rc.path, {
89
+ initialValue
90
+ }), () => rc.globalState.get(rc.path, {
91
+ initialValue,
92
+ initialState: true
93
+ }));
94
+ useEffect(() => {
95
+ const {
96
+ watcher
97
+ } = ref.current;
98
+ globalState.watch(watcher);
99
+ watcher();
100
+ return () => globalState.unWatch(watcher);
101
+ }, [globalState]);
102
+ useEffect(() => {
103
+ ref.current.watcher();
104
+ }, [path]);
105
+ return [rc.state, rc.setter];
106
+ }
107
+ export default useGlobalState;
108
+ //# sourceMappingURL=useGlobalState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","watcher","get","emit","cb","addListener","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\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 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 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 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 */\n\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\nfunction useGlobalState<Forced extends ForceT | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n const rc: GlobalStateRef = ref.current || {\n emitter: new Emitter(),\n globalState,\n path,\n setter: (value) => {\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<ForceT, unknown>(rc.path, newState);\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n watcher: () => {\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) rc.emitter.emit();\n },\n };\n ref.current = rc;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => rc.emitter.addListener(cb),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue }),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n"],"mappings":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAMEC,WAAW;;AAgBb;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;;AAiBA,SAASC,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAGL,cAAc,CAAC,CAAC;EAEpC,MAAMM,GAAG,GAAGT,MAAM,CAAiB,CAAC;EACpC,MAAMU,EAAkB,GAAGD,GAAG,CAACE,OAAO,IAAI;IACxCC,OAAO,EAAE,IAAIV,OAAO,CAAC,CAAC;IACtBM,WAAW;IACXF,IAAI;IACJO,MAAM,EAAGC,KAAK,IAAK;MACjB,MAAMC,QAAQ,GAAGjB,UAAU,CAACgB,KAAK,CAAC,GAAGA,KAAK,CAACJ,EAAE,CAACM,KAAK,CAAC,GAAGF,KAAK;MAC5D,IAAIG,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAIf,WAA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,KAAK,CAACN,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAMjB,WAAW,CAACwB,OAAO,CAACP,OAAO,CAAC;EAC3C,CAAC,EAAE,CAACjB,WAAW,CAAC,CAAC;EAEjBT,SAAS,CAAC,MAAM;IACdU,GAAG,CAACE,OAAO,CAAEc,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACnB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACI,EAAE,CAACM,KAAK,EAAEN,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc"}
@@ -0,0 +1,35 @@
1
+ // TODO: This (ForceT & TypeLock) probably should be moved to JS Utils lib.
2
+ // This type is used to "unlocked" special generic overrides around the library.
3
+ /**
4
+ * Given the type of state, `StateT`, and the type of state path, `PathT`,
5
+ * it evaluates the type of value at that path of the state, if it can be
6
+ * evaluated from the path type (it is possible when `PathT` is a string
7
+ * literal type, and `StateT` elements along this path have appropriate
8
+ * types); otherwise it falls back to the specified `UnknownT` type,
9
+ * which should be set either `never` (for input arguments), or `void`
10
+ * (for return types) - `never` and `void` in those places forbid assignments,
11
+ * and are not auto-inferred to more permissible types.
12
+ *
13
+ * BEWARE: When StateT is any the construct resolves to any for any string
14
+ * paths.
15
+ */
16
+ /**
17
+ * Returns 'true' if debug logging should be performed; 'false' otherwise.
18
+ *
19
+ * BEWARE: The actual safeguards for the debug logging still should read
20
+ * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
21
+ * // Some debug logging
22
+ * }
23
+ * to ensure that debug code is stripped out by Webpack in production mode.
24
+ *
25
+ * @returns
26
+ * @ignore
27
+ */
28
+ export function isDebugMode() {
29
+ try {
30
+ return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
31
+ } catch (error) {
32
+ return false;
33
+ }
34
+ }
35
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT & TypeLock) probably should be moved to JS Utils lib.\n\n// This type is used to \"unlocked\" special generic overrides around the library.\ndeclare const force: unique symbol;\nexport type ForceT = typeof force;\n\nexport type TypeLock<\n Unlocked extends ForceT | false,\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\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\n * @ignore\n */\nexport function isDebugMode(): boolean {\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"],"mappings":"AAIA;AAEA;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAWA,CAAA,EAAY;EACrC,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"}
@@ -0,0 +1,35 @@
1
+ import GlobalStateProvider, { getGlobalState, getSsrContext } from "./GlobalStateProvider";
2
+ import useGlobalState from "./useGlobalState";
3
+ import useAsyncCollection from "./useAsyncCollection";
4
+ import useAsyncData from "./useAsyncData";
5
+ export default function withGlobalStateType() {
6
+ // These wrap useGlobalState() with locked-in StateT type.
7
+
8
+ function useGlobalStateWrap(path, initialValue) {
9
+ return useGlobalState(path, initialValue);
10
+ }
11
+
12
+ // These overloads & implementation wrap useAsyncData() hook to lock-in its
13
+ // underlying StateT.
14
+ function useAsyncDataWrap(path, loader) {
15
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
16
+ return useAsyncData(path, loader, options);
17
+ }
18
+
19
+ // These overloads & implementation wrap useAsyncCollection() hook to lock-in
20
+ // its underlying StateT.
21
+ function useAsyncCollectionWrap(id, path, loader) {
22
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
23
+ return useAsyncCollection(id, path, loader, options);
24
+ }
25
+ return {
26
+ getGlobalState: getGlobalState,
27
+ getSsrContext: getSsrContext,
28
+ GlobalStateProvider: GlobalStateProvider,
29
+ // SsrContext, /* CustomSsrContext || SsrContext, */
30
+ useAsyncCollection: useAsyncCollectionWrap,
31
+ useAsyncData: useAsyncDataWrap,
32
+ useGlobalState: useGlobalStateWrap
33
+ };
34
+ }
35
+ //# sourceMappingURL=withGlobalStateType.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withGlobalStateType.js","names":["GlobalStateProvider","getGlobalState","getSsrContext","useGlobalState","useAsyncCollection","useAsyncData","withGlobalStateType","useGlobalStateWrap","path","initialValue","useAsyncDataWrap","loader","options","arguments","length","undefined","useAsyncCollectionWrap","id"],"sources":["../../src/withGlobalStateType.ts"],"sourcesContent":["import {\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n} from './utils';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useGlobalState, {\n type UseGlobalStateResT,\n} from './useGlobalState';\n\nimport useAsyncCollection, {\n type AsyncCollectionLoaderT,\n} from './useAsyncCollection';\n\nimport useAsyncData, {\n type AsyncDataLoaderT,\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\ninterface NarrowedUseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n\ninterface NarrowedUseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | false = false, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, never, DataT>>;\n}\n\ninterface NarrowedUseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined>(\n id: string,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | false = false, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataT>;\n}\n\ntype WithGlobalStateTypeResT<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> = {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>,\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n // SsrContext: SsrContext<StateT>,\n useAsyncCollection: NarrowedUseAsyncCollectionI<StateT>,\n useAsyncData: NarrowedUseAsyncDataI<StateT>,\n useGlobalState: NarrowedUseGlobalStateI<StateT>,\n};\n\nexport default function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): WithGlobalStateTypeResT<StateT, SsrContextT> {\n // These wrap useGlobalState() with locked-in StateT type.\n\n function useGlobalStateWrap(): UseGlobalStateResT<StateT>;\n\n function useGlobalStateWrap<PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n function useGlobalStateWrap<Forced extends ForceT | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n function useGlobalStateWrap(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n ): UseGlobalStateResT<any> {\n return useGlobalState<ForceT, unknown>(path, initialValue);\n }\n\n // These overloads & implementation wrap useAsyncData() hook to lock-in its\n // underlying StateT.\n\n function useAsyncDataWrap<PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n function useAsyncDataWrap<Forced extends ForceT | false = false, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, never, DataT>>;\n\n function useAsyncDataWrap<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n ): UseAsyncDataResT<DataT> {\n return useAsyncData<ForceT, DataT>(path, loader, options);\n }\n\n // These overloads & implementation wrap useAsyncCollection() hook to lock-in\n // its underlying StateT.\n\n function useAsyncCollectionWrap<PathT extends null | string | undefined>(\n id: string,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n function useAsyncCollectionWrap<Forced extends ForceT | false = false, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataT>;\n\n function useAsyncCollectionWrap<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n ): UseAsyncDataResT<DataT> {\n return useAsyncCollection<ForceT, DataT>(id, path, loader, options);\n }\n\n return {\n getGlobalState: getGlobalState<StateT, SsrContextT>,\n getSsrContext: getSsrContext<SsrContextT>,\n GlobalStateProvider: GlobalStateProvider<StateT, SsrContextT>,\n // SsrContext, /* CustomSsrContext || SsrContext, */\n useAsyncCollection: useAsyncCollectionWrap,\n useAsyncData: useAsyncDataWrap,\n useGlobalState: useGlobalStateWrap,\n };\n}\n"],"mappings":"AAOA,OAAOA,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAKf,OAAOC,cAAc;AAIrB,OAAOC,kBAAkB;AAIzB,OAAOC,YAAY;AAgEnB,eAAe,SAASC,mBAAmBA,CAAA,EAGO;EAChD;;EAcA,SAASC,kBAAkBA,CACzBC,IAAoB,EACpBC,YAA2C,EAClB;IACzB,OAAON,cAAc,CAAkBK,IAAI,EAAEC,YAAY,CAAC;EAC5D;;EAEA;EACA;EAcA,SAASC,gBAAgBA,CACvBF,IAA+B,EAC/BG,MAA+B,EAEN;IAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IAElC,OAAOR,YAAY,CAAgBG,IAAI,EAAEG,MAAM,EAAEC,OAAO,CAAC;EAC3D;;EAEA;EACA;EAgBA,SAASI,sBAAsBA,CAC7BC,EAAU,EACVT,IAA+B,EAC/BG,MAAqC,EAEZ;IAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IAElC,OAAOT,kBAAkB,CAAgBa,EAAE,EAAET,IAAI,EAAEG,MAAM,EAAEC,OAAO,CAAC;EACrE;EAEA,OAAO;IACLX,cAAc,EAAEA,cAAmC;IACnDC,aAAa,EAAEA,aAA0B;IACzCF,mBAAmB,EAAEA,mBAAwC;IAC7D;IACAI,kBAAkB,EAAEY,sBAAsB;IAC1CX,YAAY,EAAEK,gBAAgB;IAC9BP,cAAc,EAAEI;EAClB,CAAC;AACH"}
@@ -1,18 +1,18 @@
1
1
  import SsrContext from './SsrContext';
2
- import { type CallbackT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
2
+ import { type CallbackT, type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
3
3
  type GetOptsT<T> = {
4
4
  initialState?: boolean;
5
5
  initialValue?: ValueOrInitializerT<T>;
6
6
  };
7
- export default class GlobalState<StateT> {
7
+ export default class GlobalState<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
8
8
  #private;
9
- readonly ssrContext?: SsrContext<StateT>;
9
+ readonly ssrContext?: SsrContextT;
10
10
  /**
11
11
  * Creates a new global state object.
12
12
  * @param initialState Intial global state content.
13
13
  * @param ssrContext Server-side rendering context.
14
14
  */
15
- constructor(initialState: StateT, ssrContext?: SsrContext<StateT>);
15
+ constructor(initialState: StateT, ssrContext?: SsrContextT);
16
16
  /**
17
17
  * Gets entire state, the same way as .get(null, opts) would do.
18
18
  * @param opts.initialState
@@ -42,7 +42,7 @@ export default class GlobalState<StateT> {
42
42
  */
43
43
  get(): StateT;
44
44
  get<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
45
- get<Unlocked extends 0 | 1 = 0, ValueT = void>(path?: null | string, opts?: GetOptsT<TypeLock<Unlocked, never, ValueT>>): TypeLock<Unlocked, void, ValueT>;
45
+ get<Forced extends ForceT | false = false, ValueT = void>(path?: null | string, opts?: GetOptsT<TypeLock<Forced, never, ValueT>>): TypeLock<Forced, void, ValueT>;
46
46
  /**
47
47
  * Writes the `value` to given global state `path`.
48
48
  * @param path Dot-delimitered state path. If not given, entire
@@ -51,7 +51,7 @@ export default class GlobalState<StateT> {
51
51
  * @return Given `value` itself.
52
52
  */
53
53
  set<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, value: ValueArgT): ValueResT;
54
- set<Unlocked extends 0 | 1 = 0, ValueT = never>(path: null | string | undefined, value: TypeLock<Unlocked, never, ValueT>): TypeLock<Unlocked, void, ValueT>;
54
+ set<Forced extends ForceT | false = false, ValueT = never>(path: null | string | undefined, value: TypeLock<Forced, never, ValueT>): TypeLock<Forced, void, ValueT>;
55
55
  /**
56
56
  * Unsubscribes `callback` from watching state updates; no operation if
57
57
  * `callback` is not subscribed to the state updates.
@@ -8,7 +8,7 @@ import { type ValueOrInitializerT } from './utils';
8
8
  * the global state, instead of accessing it directly.
9
9
  * @return
10
10
  */
11
- export declare function getGlobalState<StateT>(): GlobalState<StateT>;
11
+ export declare function getGlobalState<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>>(): GlobalState<StateT, SsrContextT>;
12
12
  /**
13
13
  * @category Hooks
14
14
  * @desc Gets SSR context.
@@ -23,15 +23,15 @@ export declare function getGlobalState<StateT>(): GlobalState<StateT>;
23
23
  * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
24
24
  * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
25
25
  */
26
- export declare function getSsrContext<StateT>(throwWithoutSsrContext?: boolean): SsrContext<StateT> | undefined;
27
- type NewStateProps<StateT> = {
26
+ export declare function getSsrContext<SsrContextT extends SsrContext<unknown>>(throwWithoutSsrContext?: boolean): SsrContextT | undefined;
27
+ type NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {
28
28
  initialState: ValueOrInitializerT<StateT>;
29
- ssrContext?: SsrContext<StateT>;
29
+ ssrContext?: SsrContextT;
30
30
  };
31
- type GlobalStateProviderProps<StateT> = {
31
+ type GlobalStateProviderProps<StateT, SsrContextT extends SsrContext<StateT>> = {
32
32
  children?: ReactNode;
33
- } & (NewStateProps<StateT> | {
34
- stateProxy: true | GlobalState<StateT>;
33
+ } & (NewStateProps<StateT, SsrContextT> | {
34
+ stateProxy: true | GlobalState<StateT, SsrContextT>;
35
35
  });
36
36
  /**
37
37
  * Provides global state to its children.
@@ -46,7 +46,7 @@ type GlobalStateProviderProps<StateT> = {
46
46
  * - If `GlobalState` instance, it will be used by this provider.
47
47
  * - If not given, a new `GlobalState` instance will be created and used.
48
48
  */
49
- declare function GlobalStateProvider<StateT>({ children, ...rest }: GlobalStateProviderProps<StateT>): import("react/jsx-runtime").JSX.Element;
49
+ declare function GlobalStateProvider<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>): import("react/jsx-runtime").JSX.Element;
50
50
  declare namespace GlobalStateProvider {
51
51
  var defaultProps: {
52
52
  children: undefined;
@@ -4,5 +4,5 @@ export { default as SsrContext } from './SsrContext';
4
4
  export { type AsyncCollectionLoaderT, default as useAsyncCollection, } from './useAsyncCollection';
5
5
  export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type UseAsyncDataOptionsT, type UseAsyncDataResT, default as useAsyncData, newAsyncDataEnvelope, } from './useAsyncData';
6
6
  export { type SetterT, type UseGlobalStateResT, default as useGlobalState, } from './useGlobalState';
7
- export { type ValueOrInitializerT } from './utils';
7
+ export { type ForceT, type ValueOrInitializerT } from './utils';
8
8
  export { default as withGlobalStateType } from './withGlobalStateType';
@@ -2,7 +2,7 @@
2
2
  * Loads and uses an item in an async collection.
3
3
  */
4
4
  import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
5
- import { TypeLock } from './utils';
5
+ import { type ForceT, type TypeLock } from './utils';
6
6
  export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
7
7
  /**
8
8
  * Resolves and stores at the given `path` of global state elements of
@@ -47,5 +47,5 @@ export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT)
47
47
  * `useAsyncData()` hooks logic.
48
48
  */
49
49
  declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
50
- declare function useAsyncCollection<Unlocked extends 0 | 1 = 0, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Unlocked, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
50
+ declare function useAsyncCollection<Forced extends ForceT | false = false, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
51
51
  export default useAsyncCollection;
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * Loads and uses async data into the GlobalState path.
3
3
  */
4
- import { TypeLock } from './utils';
5
- import { type ValueAtPathT } from './utils';
4
+ import { type ForceT, type TypeLock, type ValueAtPathT } from './utils';
6
5
  export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
7
6
  export type AsyncDataEnvelopeT<DataT> = {
8
7
  data: null | DataT;
@@ -72,5 +71,5 @@ export type UseAsyncDataResT<DataT> = {
72
71
  */
73
72
  export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
74
73
  declare function useAsyncData<StateT, PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
75
- declare function useAsyncData<Unlocked extends 0 | 1 = 0, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Unlocked, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
74
+ declare function useAsyncData<Forced extends ForceT | false = false, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
76
75
  export default useAsyncData;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="react" />
2
- import { type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
2
+ import { type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
3
3
  export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
4
4
  export type UseGlobalStateResT<T> = [T, SetterT<T>];
5
5
  /**
@@ -53,6 +53,6 @@ export type UseGlobalStateResT<T> = [T, SetterT<T>];
53
53
  * stable function: it does not change between component re-renders.
54
54
  */
55
55
  declare function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
56
+ declare function useGlobalState<Forced extends ForceT | false = false, ValueT = unknown>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
56
57
  declare function useGlobalState<StateT, PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
57
- declare function useGlobalState<Unlocked extends 0 | 1 = 0, ValueT = void>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Unlocked, never, ValueT>>): UseGlobalStateResT<TypeLock<Unlocked, void, ValueT>>;
58
58
  export default useGlobalState;
@@ -1,6 +1,8 @@
1
1
  import { type GetFieldType } from 'lodash';
2
2
  export type CallbackT = () => void;
3
- export type TypeLock<Unlocked extends 0 | 1, LockedT extends never | void, UnlockedT> = Unlocked extends 0 ? LockedT : UnlockedT;
3
+ declare const force: unique symbol;
4
+ export type ForceT = typeof force;
5
+ export type TypeLock<Unlocked extends ForceT | false, LockedT extends never | void, UnlockedT> = Unlocked extends ForceT ? UnlockedT : LockedT;
4
6
  /**
5
7
  * Given the type of state, `StateT`, and the type of state path, `PathT`,
6
8
  * it evaluates the type of value at that path of the state, if it can be
@@ -29,3 +31,4 @@ export type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);
29
31
  * @ignore
30
32
  */
31
33
  export declare function isDebugMode(): boolean;
34
+ export {};