@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
package/README.md CHANGED
@@ -10,6 +10,8 @@ State of the art approach to the global state and asynchronous data management
10
10
  in React applications, powered by hooks and Context API. Simple, efficient, with
11
11
  full server-side rendering (SSR) support.
12
12
 
13
+ TypeScript support since v0.10.0.
14
+
13
15
  [⇒ Documentation ⇐](https://dr.pogodin.studio/docs/react-global-state/index.html)
14
16
 
15
17
  [![Sponsor](https://raw.githubusercontent.com/birdofpreyru/react-global-state/master/.README/sponsor.svg)](https://github.com/sponsors/birdofpreyru)
@@ -0,0 +1,219 @@
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
+
13
+ // TODO: It is tempting to replace watchers here by
14
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
15
+ // current watchers for emitting later, and this is not something
16
+ // Emitter supports right now.
17
+ #watchers = [];
18
+ #nextNotifierId;
19
+ #currentState;
20
+
21
+ /**
22
+ * Creates a new global state object.
23
+ * @param initialState Intial global state content.
24
+ * @param ssrContext Server-side rendering context.
25
+ */
26
+ constructor(initialState, ssrContext) {
27
+ this.#currentState = initialState;
28
+ this.#initialState = initialState;
29
+ if (ssrContext) {
30
+ /* eslint-disable no-param-reassign */
31
+ ssrContext.dirty = false;
32
+ ssrContext.pending = [];
33
+ ssrContext.state = this.#currentState;
34
+ /* eslint-enable no-param-reassign */
35
+
36
+ this.ssrContext = ssrContext;
37
+ }
38
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
39
+ /* eslint-disable no-console */
40
+ let msg = 'New ReactGlobalState created';
41
+ if (ssrContext) msg += ' (SSR mode)';
42
+ console.groupCollapsed(msg);
43
+ console.log('Initial state:', (0, _lodash.cloneDeep)(initialState));
44
+ console.groupEnd();
45
+ /* eslint-enable no-console */
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Gets entire state, the same way as .get(null, opts) would do.
51
+ * @param opts.initialState
52
+ * @param opts.initialValue
53
+ */
54
+ getEntireState(opts) {
55
+ let state = opts?.initialState ? this.#initialState : this.#currentState;
56
+ if (state !== undefined || opts?.initialValue === undefined) return state;
57
+ const iv = opts.initialValue;
58
+ state = (0, _lodash.isFunction)(iv) ? iv() : iv;
59
+ if (this.#currentState === undefined) this.setEntireState(state);
60
+ return state;
61
+ }
62
+
63
+ /**
64
+ * Notifies all connected state watchers that a state update has happened.
65
+ */
66
+ notifyStateUpdate(path, value) {
67
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
68
+ /* eslint-disable no-console */
69
+ const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
70
+ console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
71
+ console.log('New value:', (0, _lodash.cloneDeep)(value));
72
+ console.log('New state:', (0, _lodash.cloneDeep)(this.#currentState));
73
+ console.groupEnd();
74
+ /* eslint-enable no-console */
75
+ }
76
+
77
+ if (this.ssrContext) {
78
+ this.ssrContext.dirty = true;
79
+ this.ssrContext.state = this.#currentState;
80
+ } else if (!this.#nextNotifierId) {
81
+ this.#nextNotifierId = setTimeout(() => {
82
+ this.#nextNotifierId = undefined;
83
+ const watchers = [...this.#watchers];
84
+ for (let i = 0; i < watchers.length; ++i) {
85
+ watchers[i]();
86
+ }
87
+ });
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Sets entire state, the same way as .set(null, value) would do.
93
+ * @param value
94
+ */
95
+ setEntireState(value) {
96
+ if (this.#currentState !== value) {
97
+ this.#currentState = value;
98
+ this.notifyStateUpdate(null, value);
99
+ }
100
+ return value;
101
+ }
102
+
103
+ /**
104
+ * Gets current or initial value at the specified "path" of the global state.
105
+ * @param path Dot-delimitered state path.
106
+ * @param options Additional options.
107
+ * @param options.initialState If "true" the value will be read
108
+ * from the initial state instead of the current one.
109
+ * @param options.initialValue If the value read from the "path" is
110
+ * "undefined", this "initialValue" will be returned instead. In such case
111
+ * "initialValue" will also be written to the "path" of the current global
112
+ * state (no matter "initialState" flag), if "undefined" is stored there.
113
+ * @return Retrieved value.
114
+ */
115
+
116
+ // .get() without arguments just falls back to .getEntireState().
117
+ // This variant attempts to automatically resolve and check the type of value
118
+ // at the given path, as precise as the actual state and path types permit.
119
+ // If the automatic path resolution is not possible, the ValueT fallsback
120
+ // to `never` (or to `undefined` in some cases), effectively forbidding
121
+ // to use this .get() variant.
122
+ // This variant is not callable by default (without generic arguments),
123
+ // otherwise it allows to set the correct ValueT directly.
124
+ get(path, opts) {
125
+ if ((0, _lodash.isNil)(path)) {
126
+ const res = this.getEntireState(opts);
127
+ return res;
128
+ }
129
+ const state = opts?.initialState ? this.#initialState : this.#currentState;
130
+ let res = (0, _lodash.get)(state, path);
131
+ if (res !== undefined || opts?.initialValue === undefined) return res;
132
+ const iv = opts.initialValue;
133
+ res = (0, _lodash.isFunction)(iv) ? iv() : iv;
134
+ if (!opts?.initialState || this.get(path) === undefined) {
135
+ this.set(path, res);
136
+ }
137
+ return res;
138
+ }
139
+
140
+ /**
141
+ * Writes the `value` to given global state `path`.
142
+ * @param path Dot-delimitered state path. If not given, entire
143
+ * global state content is replaced by the `value`.
144
+ * @param value The value.
145
+ * @return Given `value` itself.
146
+ */
147
+
148
+ // This variant attempts automatic value type resolution & checking.
149
+ // This variant is disabled by default, otherwise allows to give
150
+ // expected value type explicitly.
151
+ set(path, value) {
152
+ if ((0, _lodash.isNil)(path)) return this.setEntireState(value);
153
+ if (value !== this.get(path)) {
154
+ const root = {
155
+ state: this.#currentState
156
+ };
157
+ let segIdx = 0;
158
+ let pos = root;
159
+ const pathSegments = (0, _lodash.toPath)(`state.${path}`);
160
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
161
+ const seg = pathSegments[segIdx];
162
+ const next = pos[seg];
163
+ if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
164
+ ...next
165
+ };else {
166
+ // We arrived to a state sub-segment, where the remaining part of
167
+ // the update path does not exist yet. We rely on lodash's set()
168
+ // function to create the remaining path, and set the value.
169
+ (0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
170
+ break;
171
+ }
172
+ pos = pos[seg];
173
+ }
174
+ if (segIdx === pathSegments.length - 1) {
175
+ pos[pathSegments[segIdx]] = value;
176
+ }
177
+ this.#currentState = root.state;
178
+ this.notifyStateUpdate(path, value);
179
+ }
180
+ return value;
181
+ }
182
+
183
+ /**
184
+ * Unsubscribes `callback` from watching state updates; no operation if
185
+ * `callback` is not subscribed to the state updates.
186
+ * @param callback
187
+ * @throws if {@link SsrContext} is attached to the state instance: the state
188
+ * watching functionality is intended for client-side (non-SSR) only.
189
+ */
190
+ unWatch(callback) {
191
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
192
+ const watchers = this.#watchers;
193
+ const pos = watchers.indexOf(callback);
194
+ if (pos >= 0) {
195
+ watchers[pos] = watchers[watchers.length - 1];
196
+ watchers.pop();
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Subscribes `callback` to watch state updates; no operation if
202
+ * `callback` is already subscribed to this state instance.
203
+ * @param callback It will be called without any arguments every
204
+ * time the state content changes (note, howhever, separate state updates can
205
+ * be applied to the state at once, and watching callbacks will be called once
206
+ * after such bulk update).
207
+ * @throws if {@link SsrContext} is attached to the state instance: the state
208
+ * watching functionality is intended for client-side (non-SSR) only.
209
+ */
210
+ watch(callback) {
211
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
212
+ const watchers = this.#watchers;
213
+ if (watchers.indexOf(callback) < 0) {
214
+ watchers.push(callback);
215
+ }
216
+ }
217
+ }
218
+ exports.default = GlobalState;
219
+ //# sourceMappingURL=GlobalState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalState.js","names":["_lodash","require","_utils","ERR_NO_SSR_WATCH","GlobalState","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeep","groupEnd","getEntireState","opts","undefined","initialValue","iv","isFunction","setEntireState","notifyStateUpdate","path","value","p","setTimeout","i","length","get","isNil","res","set","root","segIdx","pos","pathSegments","toPath","seg","next","Array","isArray","isObject","slice","unWatch","callback","Error","indexOf","pop","watch","push","exports","default"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\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 entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeep(value));\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\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 = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param 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 Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | false = false, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | false = false, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = 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 this.notifyStateUpdate(path, value);\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 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: CallbackT) {\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 /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param 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: CallbackT) {\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,IAAAA,OAAA,GAAAC,OAAA;AAYA,IAAAC,MAAA,GAAAD,OAAA;AASA,MAAME,gBAAgB,GAAG,gDAAgD;AAO1D,MAAMC,WAAW,CAG9B;EAGA,CAACC,YAAY;;EAEb;EACA;EACA;EACA;EACA,CAACC,QAAQ,GAAgB,EAAE;EAE3B,CAACC,cAAc;EAEf,CAACC,YAAY;;EAEb;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTJ,YAAoB,EACpBK,UAAwB,EACxB;IACA,IAAI,CAAC,CAACF,YAAY,GAAGH,YAAY;IACjC,IAAI,CAAC,CAACA,YAAY,GAAGA,YAAY;IAEjC,IAAIK,UAAU,EAAE;MACd;MACAA,UAAU,CAACC,KAAK,GAAG,KAAK;MACxBD,UAAU,C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GAAG,IAAI,CAAC,EAAE;MACZtC,QAAQ,CAACsC,GAAG,CAAC,GAAGtC,QAAQ,CAACA,QAAQ,CAAC+B,MAAM,GAAG,CAAC,CAAC;MAC7C/B,QAAQ,CAACmD,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC5C,UAAU,EAAE,MAAM,IAAI6C,KAAK,CAACpD,gBAAgB,CAAC;IAEtD,MAAMG,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,IAAIA,QAAQ,CAACkD,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClChD,QAAQ,CAACqD,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF;AAACM,OAAA,CAAAC,OAAA,GAAAzD,WAAA"}
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = GlobalStateProvider;
8
+ exports.getGlobalState = getGlobalState;
9
+ exports.getSsrContext = getSsrContext;
10
+ var _lodash = require("lodash");
11
+ var _react = require("react");
12
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
13
+ var _jsxRuntime = require("react/jsx-runtime");
14
+ /* eslint-disable react/prop-types */
15
+
16
+ const context = /*#__PURE__*/(0, _react.createContext)(null);
17
+
18
+ /**
19
+ * Gets {@link GlobalState} instance from the context. In most cases
20
+ * you should use {@link useGlobalState}, and other hooks to interact with
21
+ * the global state, instead of accessing it directly.
22
+ * @return
23
+ */
24
+ function getGlobalState() {
25
+ // Here Rules of Hooks are violated because "getGlobalState()" does not follow
26
+ // convention that hook names should start with use... This is intentional in
27
+ // our case, as getGlobalState() hook is intended for advance scenarious,
28
+ // while the normal interaction with the global state should happen via
29
+ // another hook, useGlobalState().
30
+ /* eslint-disable react-hooks/rules-of-hooks */
31
+ const globalState = (0, _react.useContext)(context);
32
+ /* eslint-enable react-hooks/rules-of-hooks */
33
+ if (!globalState) throw new Error('Missing GlobalStateProvider');
34
+ return globalState;
35
+ }
36
+
37
+ /**
38
+ * @category Hooks
39
+ * @desc Gets SSR context.
40
+ * @param throwWithoutSsrContext If `true` (default),
41
+ * this hook will throw if no SSR context is attached to the global state;
42
+ * set `false` to not throw in such case. In either case the hook will throw
43
+ * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
44
+ * @returns SSR context.
45
+ * @throws
46
+ * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
47
+ * in the rendered React tree.
48
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
49
+ * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
50
+ */
51
+ function getSsrContext(throwWithoutSsrContext = true) {
52
+ const {
53
+ ssrContext
54
+ } = getGlobalState();
55
+ if (!ssrContext && throwWithoutSsrContext) {
56
+ throw new Error('No SSR context found');
57
+ }
58
+ return ssrContext;
59
+ }
60
+ /**
61
+ * Provides global state to its children.
62
+ * @param prop.children Component children, which will be provided with
63
+ * the global state, and rendered in place of the provider.
64
+ * @param prop.initialState Initial content of the global state.
65
+ * @param prop.ssrContext Server-side rendering (SSR) context.
66
+ * @param prop.stateProxy This option is useful for code
67
+ * splitting and SSR implementation:
68
+ * - If `true`, this provider instance will fetch and reuse the global state
69
+ * from a parent provider.
70
+ * - If `GlobalState` instance, it will be used by this provider.
71
+ * - If not given, a new `GlobalState` instance will be created and used.
72
+ */
73
+ function GlobalStateProvider({
74
+ children,
75
+ ...rest
76
+ }) {
77
+ const state = (0, _react.useRef)();
78
+ if (!state.current) {
79
+ // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
80
+ // graceful compatibility with JavaScript - if "undefined" stateProxy value
81
+ // is given, we want to follow the second branch, which creates a new
82
+ // GlobalState with whatever intiialState given.
83
+ if ('stateProxy' in rest && rest.stateProxy) {
84
+ if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
85
+ } else {
86
+ const {
87
+ initialState,
88
+ ssrContext
89
+ } = rest;
90
+ state.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
91
+ }
92
+ }
93
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
94
+ value: state.current,
95
+ children: children
96
+ });
97
+ }
98
+ GlobalStateProvider.defaultProps = {
99
+ children: undefined
100
+ };
101
+ //# sourceMappingURL=GlobalStateProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","context","createContext","getGlobalState","globalState","useContext","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","state","useRef","current","stateProxy","initialState","GlobalState","isFunction","jsx","Provider","value","defaultProps","undefined"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n\nGlobalStateProvider.defaultProps = {\n children: undefined,\n};\n"],"mappings":";;;;;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAXxC;;AAgBA,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,iBAAU,EAACJ,OAAO,CAAC;EACvC;EACA,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACM,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,mBAAmBA,CAIzC;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,EACpE;EACA,MAAMC,KAAK,GAAG,IAAAC,aAAM,EAAmC,CAAC;EACxD,IAAI,CAACD,KAAK,CAACE,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIH,IAAI,IAAIA,IAAI,CAACI,UAAU,EAAE;MAC3C,IAAIJ,IAAI,CAACI,UAAU,KAAK,IAAI,EAAEH,KAAK,CAACE,OAAO,GAAGZ,cAAc,CAAC,CAAC,CAAC,KAC1DU,KAAK,CAACE,OAAO,GAAGH,IAAI,CAACI,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGG,IAA0C;MAE/EC,KAAK,CAACE,OAAO,GAAG,IAAIG,oBAAW,CAC7B,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACE,IAAAT,WAAA,CAAAoB,GAAA,EAACnB,OAAO,CAACoB,QAAQ;IAACC,KAAK,EAAET,KAAK,CAACE,OAAQ;IAAAJ,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAD,mBAAmB,CAACa,YAAY,GAAG;EACjCZ,QAAQ,EAAEa;AACZ,CAAC"}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ class SsrContext {
8
+ dirty = false;
9
+ pending = [];
10
+ constructor(state) {
11
+ this.state = state;
12
+ }
13
+ }
14
+ exports.default = SsrContext;
15
+ //# sourceMappingURL=SsrContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SsrContext.js","names":["SsrContext","dirty","pending","constructor","state","exports","default"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";;;;;;AAAe,MAAMA,UAAU,CAAS;EACtCC,KAAK,GAAY,KAAK;EAEtBC,OAAO,GAAoB,EAAE;EAI7BC,WAAWA,CAACC,KAAc,EAAE;IAC1B,IAAI,CAACA,KAAK,GAAGA,KAAK;EACpB;AACF;AAACC,OAAA,CAAAC,OAAA,GAAAN,UAAA"}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ Object.defineProperty(exports, "GlobalState", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _GlobalState.default;
11
+ }
12
+ });
13
+ Object.defineProperty(exports, "GlobalStateProvider", {
14
+ enumerable: true,
15
+ get: function () {
16
+ return _GlobalStateProvider.default;
17
+ }
18
+ });
19
+ Object.defineProperty(exports, "SsrContext", {
20
+ enumerable: true,
21
+ get: function () {
22
+ return _SsrContext.default;
23
+ }
24
+ });
25
+ Object.defineProperty(exports, "getGlobalState", {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _GlobalStateProvider.getGlobalState;
29
+ }
30
+ });
31
+ Object.defineProperty(exports, "getSsrContext", {
32
+ enumerable: true,
33
+ get: function () {
34
+ return _GlobalStateProvider.getSsrContext;
35
+ }
36
+ });
37
+ Object.defineProperty(exports, "newAsyncDataEnvelope", {
38
+ enumerable: true,
39
+ get: function () {
40
+ return _useAsyncData.newAsyncDataEnvelope;
41
+ }
42
+ });
43
+ Object.defineProperty(exports, "useAsyncCollection", {
44
+ enumerable: true,
45
+ get: function () {
46
+ return _useAsyncCollection.default;
47
+ }
48
+ });
49
+ Object.defineProperty(exports, "useAsyncData", {
50
+ enumerable: true,
51
+ get: function () {
52
+ return _useAsyncData.default;
53
+ }
54
+ });
55
+ Object.defineProperty(exports, "useGlobalState", {
56
+ enumerable: true,
57
+ get: function () {
58
+ return _useGlobalState.default;
59
+ }
60
+ });
61
+ Object.defineProperty(exports, "withGlobalStateType", {
62
+ enumerable: true,
63
+ get: function () {
64
+ return _withGlobalStateType.default;
65
+ }
66
+ });
67
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
68
+ var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
69
+ var _SsrContext = _interopRequireDefault(require("./SsrContext"));
70
+ var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
71
+ var _useAsyncData = _interopRequireWildcard(require("./useAsyncData"));
72
+ var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
73
+ var _withGlobalStateType = _interopRequireDefault(require("./withGlobalStateType"));
74
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
75
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
76
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_withGlobalStateType","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set"],"sources":["../../src/index.ts"],"sourcesContent":["export { default as GlobalState } from './GlobalState';\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as SsrContext } from './SsrContext';\n\nexport {\n type AsyncCollectionLoaderT,\n default as useAsyncCollection,\n} from './useAsyncCollection';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n default as useAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nexport {\n type SetterT,\n type UseGlobalStateResT,\n default as useGlobalState,\n} from './useGlobalState';\n\nexport { type ForceT, type ValueOrInitializerT } from './utils';\n\nexport { default as withGlobalStateType } from './withGlobalStateType';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAMA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAH,uBAAA,CAAAF,OAAA;AASA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAQA,IAAAO,oBAAA,GAAAR,sBAAA,CAAAC,OAAA;AAAuE,SAAAQ,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAP,wBAAAO,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAjB,CAAA,EAAAc,CAAA,SAAAI,CAAA,GAAAR,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAI,CAAA,KAAAA,CAAA,CAAAX,GAAA,IAAAW,CAAA,CAAAC,GAAA,IAAAR,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAI,CAAA,IAAAV,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAgB,GAAA,CAAAnB,CAAA,EAAAQ,CAAA,GAAAA,CAAA"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
9
+ /**
10
+ * Loads and uses an item in an async collection.
11
+ */
12
+
13
+ /**
14
+ * Resolves and stores at the given `path` of global state elements of
15
+ * an asynchronous data collection. In other words, it is an auxiliar wrapper
16
+ * around {@link useAsyncData}, which uses a loader which resolves to different
17
+ * data, based on ID argument passed in, and stores data fetched for different
18
+ * IDs in the state.
19
+ * @param id ID of the collection item to load & use.
20
+ * @param path The global state path where entire collection should be
21
+ * stored.
22
+ * @param loader A loader function, which takes an
23
+ * ID of data to load, and resolves to the corresponding data.
24
+ * @param options Additional options.
25
+ * @param options.deps An array of dependencies, which trigger
26
+ * data reload when changed. Given dependency changes are watched shallowly
27
+ * (similarly to the standard React's
28
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
29
+ * @param options.noSSR If `true`, this hook won't load data during
30
+ * server-side rendering.
31
+ * @param options.garbageCollectAge The maximum age of data
32
+ * (in milliseconds), after which they are dropped from the state when the last
33
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
34
+ * `maxage` option value.
35
+ * @param options.maxage The maximum age of
36
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
37
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
38
+ * @param options.refreshAge The maximum age of data
39
+ * (in milliseconds), after which their refreshment will be triggered when
40
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
41
+ * Defaults to `maxage` value.
42
+ * @return Returns an object with three fields: `data` holds the actual result of
43
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
44
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
45
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
46
+ * is Unix timestamp of related data currently loaded into the global state.
47
+ *
48
+ * Note that loaded data, if any, are stored at the given `path` of global state
49
+ * along with related meta-information, using slightly different state segment
50
+ * structure (see {@link AsyncDataEnvelope}). That segment of the global state
51
+ * can be accessed, and even modified using other hooks,
52
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
53
+ * `useAsyncData()` hooks logic.
54
+ */
55
+
56
+ function useAsyncCollection(id, path, loader, options = {}) {
57
+ const itemPath = path ? `${path}.${id}` : id;
58
+ return (0, _useAsyncData.default)(itemPath, oldData => loader(id, oldData), options);
59
+ }
60
+ var _default = exports.default = useAsyncCollection;
61
+ //# sourceMappingURL=useAsyncCollection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","_interopRequireDefault","require","useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\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 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 */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>\n >,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | false = false,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n"],"mappings":";;;;;;;AAIA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AAJA;AACA;AACA;;AAaA;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;;AAyBA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;EACzB,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EACjBD,QAAQ,EACPE,OAAqB,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAC9CH,OACF,CAAC;AACH;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,kBAAkB"}