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

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 (55) hide show
  1. package/README.md +3 -328
  2. package/build/GlobalState.d.ts +75 -0
  3. package/build/GlobalState.js +193 -0
  4. package/build/GlobalStateProvider.d.ts +55 -0
  5. package/build/GlobalStateProvider.js +103 -0
  6. package/build/SsrContext.d.ts +6 -0
  7. package/build/SsrContext.js +10 -0
  8. package/build/index.d.ts +8 -0
  9. package/build/index.js +23 -0
  10. package/build/{module/useAsyncCollection.js → useAsyncCollection.d.ts} +16 -23
  11. package/build/useAsyncCollection.js +14 -0
  12. package/build/useAsyncData.d.ts +76 -0
  13. package/build/useAsyncData.js +150 -0
  14. package/build/{module/useGlobalState.js → useGlobalState.d.ts} +11 -62
  15. package/build/useGlobalState.js +49 -0
  16. package/build/utils.d.ts +31 -0
  17. package/build/{node/utils.js → utils.js} +11 -17
  18. package/build/withGlobalStateType.d.ts +39 -0
  19. package/build/withGlobalStateType.js +55 -0
  20. package/package.json +48 -27
  21. package/src/GlobalState.ts +279 -0
  22. package/src/GlobalStateProvider.tsx +116 -0
  23. package/src/SsrContext.ts +11 -0
  24. package/src/index.ts +33 -0
  25. package/{build/node/useAsyncCollection.js → src/useAsyncCollection.ts} +58 -25
  26. package/src/useAsyncData.ts +287 -0
  27. package/src/useGlobalState.ts +158 -0
  28. package/src/utils.ts +59 -0
  29. package/src/withGlobalStateType.ts +118 -0
  30. package/tsconfig.json +9 -0
  31. package/build/module/GlobalState.js +0 -191
  32. package/build/module/GlobalState.js.map +0 -1
  33. package/build/module/GlobalStateProvider.js +0 -81
  34. package/build/module/GlobalStateProvider.js.map +0 -1
  35. package/build/module/index.js +0 -12
  36. package/build/module/index.js.map +0 -1
  37. package/build/module/useAsyncCollection.js.map +0 -1
  38. package/build/module/useAsyncData.js +0 -206
  39. package/build/module/useAsyncData.js.map +0 -1
  40. package/build/module/useGlobalState.js.map +0 -1
  41. package/build/module/utils.js +0 -23
  42. package/build/module/utils.js.map +0 -1
  43. package/build/node/GlobalState.js +0 -174
  44. package/build/node/GlobalState.js.map +0 -1
  45. package/build/node/GlobalStateProvider.js +0 -88
  46. package/build/node/GlobalStateProvider.js.map +0 -1
  47. package/build/node/index.js +0 -56
  48. package/build/node/index.js.map +0 -1
  49. package/build/node/useAsyncCollection.js.map +0 -1
  50. package/build/node/useAsyncData.js +0 -211
  51. package/build/node/useAsyncData.js.map +0 -1
  52. package/build/node/useGlobalState.js +0 -114
  53. package/build/node/useGlobalState.js.map +0 -1
  54. package/build/node/utils.js.map +0 -1
  55. package/index.d.ts +0 -70
@@ -1,12 +1,6 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- exports.isDebugMode = isDebugMode;
8
- // Auxiliary stuff.
9
-
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isDebugMode = void 0;
10
4
  /**
11
5
  * Returns 'true' if debug logging should be performed; 'false' otherwise.
12
6
  *
@@ -16,16 +10,16 @@ exports.isDebugMode = isDebugMode;
16
10
  * }
17
11
  * to ensure that debug code is stripped out by Webpack in production mode.
18
12
  *
19
- * @returns {boolean}
13
+ * @returns
20
14
  * @ignore
21
15
  */
22
16
  function isDebugMode() {
23
- try {
24
- return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
25
- } catch (error) {
26
- return false;
27
- }
17
+ try {
18
+ return process.env.NODE_ENV !== 'production'
19
+ && !!process.env.REACT_GLOBAL_STATE_DEBUG;
20
+ }
21
+ catch (error) {
22
+ return false;
23
+ }
28
24
  }
29
- var _default = null;
30
- exports.default = _default;
31
- //# sourceMappingURL=utils.js.map
25
+ exports.isDebugMode = isDebugMode;
@@ -0,0 +1,39 @@
1
+ /// <reference types="react" />
2
+ import { type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
3
+ import SsrContext from './SsrContext';
4
+ import { type UseGlobalStateResT } from './useGlobalState';
5
+ import { type AsyncCollectionLoaderT } from './useAsyncCollection';
6
+ import { type AsyncDataLoaderT, type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
7
+ export default function withGlobalStateType<StateT>(): {
8
+ getGlobalState: () => import("./GlobalState").default<StateT>;
9
+ getSsrContext: (throwWithoutSsrContext?: boolean) => SsrContext<StateT> | undefined;
10
+ GlobalStateProvider: {
11
+ ({ children, ...rest }: {
12
+ children?: import("react").ReactNode;
13
+ } & ({
14
+ initialState: ValueOrInitializerT<StateT>;
15
+ ssrContext?: SsrContext<StateT> | undefined;
16
+ } | {
17
+ stateProxy: true | import("./GlobalState").default<StateT>;
18
+ })): import("react/jsx-runtime").JSX.Element;
19
+ defaultProps: {
20
+ children: undefined;
21
+ };
22
+ };
23
+ SsrContext: {
24
+ new (state?: StateT | undefined): SsrContext<StateT>;
25
+ };
26
+ useAsyncCollection: {
27
+ <PathT extends string | null | undefined>(id: string, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
28
+ <Unlocked extends 0 | 1 = 0, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Unlocked, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
29
+ };
30
+ useAsyncData: {
31
+ <PathT_1 extends string | null | undefined>(path: PathT_1, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT_1>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT_1>>;
32
+ <Unlocked_1 extends 0 | 1 = 0, DataT_1 = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Unlocked_1, void, DataT_1>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Unlocked_1, never, DataT_1>>;
33
+ };
34
+ useGlobalState: {
35
+ (): UseGlobalStateResT<StateT>;
36
+ <PathT_2 extends string | null | undefined>(path: PathT_2, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT_2, never>> | undefined): UseGlobalStateResT<ValueAtPathT<StateT, PathT_2, void>>;
37
+ <Unlocked_2 extends 0 | 1 = 0, ValueT = void>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Unlocked_2, never, ValueT>> | undefined): UseGlobalStateResT<TypeLock<Unlocked_2, void, ValueT>>;
38
+ };
39
+ };
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const GlobalStateProvider_1 = __importStar(require("./GlobalStateProvider"));
30
+ const SsrContext_1 = __importDefault(require("./SsrContext"));
31
+ const useGlobalState_1 = __importDefault(require("./useGlobalState"));
32
+ const useAsyncCollection_1 = __importDefault(require("./useAsyncCollection"));
33
+ const useAsyncData_1 = __importDefault(require("./useAsyncData"));
34
+ function withGlobalStateType() {
35
+ // These wrap useGlobalState() with locked-in StateT type.
36
+ function useGlobalStateWrap(path, initialValue) {
37
+ return (0, useGlobalState_1.default)(path, initialValue);
38
+ }
39
+ function useAsyncDataWrap(path, loader, options = {}) {
40
+ return (0, useAsyncData_1.default)(path, loader, options);
41
+ }
42
+ function useAsyncCollectionWrap(id, path, loader, options = {}) {
43
+ return (0, useAsyncCollection_1.default)(id, path, loader, options);
44
+ }
45
+ return {
46
+ getGlobalState: (GlobalStateProvider_1.getGlobalState),
47
+ getSsrContext: (GlobalStateProvider_1.getSsrContext),
48
+ GlobalStateProvider: (GlobalStateProvider_1.default),
49
+ SsrContext: (SsrContext_1.default),
50
+ useAsyncCollection: useAsyncCollectionWrap,
51
+ useAsyncData: useAsyncDataWrap,
52
+ useGlobalState: useGlobalStateWrap,
53
+ };
54
+ }
55
+ exports.default = withGlobalStateType;
package/package.json CHANGED
@@ -1,21 +1,22 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.9.3",
3
+ "version": "0.10.0-alpha.2",
4
4
  "description": "Hook-based global state for React",
5
- "main": "./build/node/index.js",
5
+ "main": "./build/index.js",
6
+ "react-native": "src/index.ts",
7
+ "source": "src/index.ts",
6
8
  "exports": {
7
- "module": "./build/module/index.js",
8
- "node": "./build/node/index.js",
9
9
  "types": "./index.d.ts",
10
- "default": "./build/node/index.js"
10
+ "default": "./build/index.js"
11
11
  },
12
12
  "scripts": {
13
- "build": "rimraf build && npm run build:module && npm run build:node",
14
- "build:module": "rimraf build/web && babel src --out-dir build/module --source-maps --config-file ./babel.module.config.js",
15
- "build:node": "rimraf build/node && babel src --out-dir build/node --source-maps",
16
- "jest": "jest --config jest/config.json",
17
- "lint": "eslint --ext .js,.jsx .",
18
- "test": "npm run lint && npm run jest"
13
+ "build": "rimraf build && tsc",
14
+ "jest": "npm run jest:types && npm run jest:logic",
15
+ "jest:types": "jest --config jest/config-types.json",
16
+ "jest:logic": "jest --config jest/config.json -w 1",
17
+ "lint": "eslint --ext .js,.jsx,.ts,.tsx .",
18
+ "test": "npm run lint && npm run typecheck && npm run jest",
19
+ "typecheck": "tsc --noEmit && tsc --project __tests__/tsconfig.typecheck.json"
19
20
  },
20
21
  "repository": "github:birdofpreyru/react-global-state",
21
22
  "keywords": [
@@ -24,7 +25,8 @@
24
25
  "state",
25
26
  "hooks",
26
27
  "hook",
27
- "global"
28
+ "global",
29
+ "typescript"
28
30
  ],
29
31
  "author": "Dr. Sergey Pogodin <doc@pogodin.studio> (https://dr.pogodin.studio)",
30
32
  "license": "MIT",
@@ -32,35 +34,54 @@
32
34
  "url": "https://github.com/birdofpreyru/react-global-state.git/issues"
33
35
  },
34
36
  "homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
37
+ "engines": {
38
+ "node": ">=16"
39
+ },
35
40
  "dependencies": {
36
- "@babel/runtime": "^7.21.0",
41
+ "@babel/runtime": "^7.22.6",
42
+ "@dr.pogodin/js-utils": "^0.0.6",
37
43
  "lodash": "^4.17.21",
38
44
  "uuid": "^9.0.0"
39
45
  },
40
46
  "devDependencies": {
41
- "@babel/cli": "^7.21.0",
42
- "@babel/core": "^7.21.4",
43
- "@babel/eslint-parser": "^7.21.3",
44
- "@babel/eslint-plugin": "^7.19.1",
45
- "@babel/node": "^7.20.7",
46
- "@babel/plugin-transform-runtime": "^7.21.4",
47
- "@babel/preset-env": "^7.21.4",
48
- "@babel/preset-react": "^7.18.6",
49
- "babel-jest": "^29.5.0",
47
+ "@babel/cli": "^7.22.6",
48
+ "@babel/core": "^7.22.8",
49
+ "@babel/eslint-parser": "^7.22.7",
50
+ "@babel/eslint-plugin": "^7.22.5",
51
+ "@babel/node": "^7.22.6",
52
+ "@babel/plugin-transform-runtime": "^7.22.7",
53
+ "@babel/preset-env": "^7.22.7",
54
+ "@babel/preset-react": "^7.22.5",
55
+ "@babel/preset-typescript": "^7.22.5",
56
+ "@tsconfig/recommended": "^1.0.2",
57
+ "@tsd/typescript": "^5.1.6",
58
+ "@types/jest": "^29.5.3",
59
+ "@types/lodash": "^4.14.195",
60
+ "@types/pretty": "^2.0.1",
61
+ "@types/react": "^18.2.14",
62
+ "@types/react-dom": "^18.2.6",
63
+ "@types/uuid": "^9.0.2",
64
+ "@typescript-eslint/eslint-plugin": "^5.61.0",
65
+ "@typescript-eslint/parser": "^5.61.0",
66
+ "babel-jest": "^29.6.1",
50
67
  "babel-plugin-module-resolver": "^5.0.0",
51
- "eslint": "^8.37.0",
68
+ "eslint": "^8.44.0",
52
69
  "eslint-config-airbnb": "^19.0.4",
70
+ "eslint-config-airbnb-typescript": "^17.0.0",
53
71
  "eslint-import-resolver-babel-module": "^5.3.2",
54
72
  "eslint-plugin-import": "^2.27.5",
55
- "eslint-plugin-jest": "^27.2.1",
73
+ "eslint-plugin-jest": "^27.2.2",
56
74
  "eslint-plugin-jsx-a11y": "^6.7.1",
57
75
  "eslint-plugin-react": "^7.32.2",
58
76
  "eslint-plugin-react-hooks": "^4.6.0",
59
- "jest": "^29.5.0",
60
- "jest-environment-jsdom": "^29.5.0",
77
+ "jest": "^29.6.1",
78
+ "jest-environment-jsdom": "^29.6.1",
79
+ "jest-runner-tsd": "^6.0.0",
61
80
  "mockdate": "^3.0.5",
62
81
  "pretty": "^2.0.0",
63
- "rimraf": "^4.4.1"
82
+ "rimraf": "^5.0.1",
83
+ "tsd-lite": "^0.8.0",
84
+ "typescript": "^5.1.6"
64
85
  },
65
86
  "peerDependencies": {
66
87
  "react": "^18.2.0",
@@ -0,0 +1,279 @@
1
+ import {
2
+ cloneDeep,
3
+ get,
4
+ isFunction,
5
+ isObject,
6
+ isNil,
7
+ set,
8
+ toPath,
9
+ } from 'lodash';
10
+
11
+ import SsrContext from './SsrContext';
12
+
13
+ import {
14
+ type CallbackT,
15
+ type TypeLock,
16
+ type ValueAtPathT,
17
+ type ValueOrInitializerT,
18
+ isDebugMode,
19
+ } from './utils';
20
+
21
+ const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
22
+
23
+ type GetOptsT<T> = {
24
+ initialState?: boolean;
25
+ initialValue?: ValueOrInitializerT<T>;
26
+ };
27
+
28
+ export default class GlobalState<StateT> {
29
+ readonly ssrContext?: SsrContext<StateT>;
30
+
31
+ #initialState: StateT;
32
+
33
+ // TODO: It is tempting to replace watchers here by
34
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
35
+ // current watchers for emitting later, and this is not something
36
+ // Emitter supports right now.
37
+ #watchers: CallbackT[] = [];
38
+
39
+ #nextNotifierId?: NodeJS.Timeout;
40
+
41
+ #currentState: StateT;
42
+
43
+ /**
44
+ * Creates a new global state object.
45
+ * @param initialState Intial global state content.
46
+ * @param ssrContext Server-side rendering context.
47
+ */
48
+ constructor(
49
+ initialState: StateT,
50
+ ssrContext?: SsrContext<StateT>,
51
+ ) {
52
+ this.#currentState = initialState;
53
+ this.#initialState = initialState;
54
+
55
+ if (ssrContext) {
56
+ /* eslint-disable no-param-reassign */
57
+ ssrContext.dirty = false;
58
+ ssrContext.pending = [];
59
+ ssrContext.state = this.#currentState;
60
+ /* eslint-enable no-param-reassign */
61
+
62
+ this.ssrContext = ssrContext;
63
+ }
64
+
65
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
66
+ /* eslint-disable no-console */
67
+ let msg = 'New ReactGlobalState created';
68
+ if (ssrContext) msg += ' (SSR mode)';
69
+ console.groupCollapsed(msg);
70
+ console.log('Initial state:', cloneDeep(initialState));
71
+ console.groupEnd();
72
+ /* eslint-enable no-console */
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Gets entire state, the same way as .get(null, opts) would do.
78
+ * @param opts.initialState
79
+ * @param opts.initialValue
80
+ */
81
+ getEntireState(opts?: GetOptsT<StateT>): StateT {
82
+ let state = opts?.initialState ? this.#initialState : this.#currentState;
83
+ if (state !== undefined || opts?.initialValue === undefined) return state;
84
+
85
+ const iv = opts.initialValue;
86
+ state = isFunction(iv) ? iv() : iv;
87
+ if (this.#currentState === undefined) this.setEntireState(state);
88
+ return state;
89
+ }
90
+
91
+ /**
92
+ * Notifies all connected state watchers that a state update has happened.
93
+ */
94
+ private notifyStateUpdate(path: null | string | undefined, value: unknown) {
95
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
96
+ /* eslint-disable no-console */
97
+ const p = typeof path === 'string'
98
+ ? `"${path}"` : 'none (entire state update)';
99
+ console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
100
+ console.log('New value:', cloneDeep(value));
101
+ console.log('New state:', cloneDeep(this.#currentState));
102
+ console.groupEnd();
103
+ /* eslint-enable no-console */
104
+ }
105
+
106
+ if (this.ssrContext) {
107
+ this.ssrContext.dirty = true;
108
+ this.ssrContext.state = this.#currentState;
109
+ } else if (!this.#nextNotifierId) {
110
+ this.#nextNotifierId = setTimeout(() => {
111
+ this.#nextNotifierId = undefined;
112
+ const watchers = [...this.#watchers];
113
+ for (let i = 0; i < watchers.length; ++i) {
114
+ watchers[i]();
115
+ }
116
+ });
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Sets entire state, the same way as .set(null, value) would do.
122
+ * @param value
123
+ */
124
+ setEntireState(value: StateT): StateT {
125
+ if (this.#currentState !== value) {
126
+ this.#currentState = value;
127
+ this.notifyStateUpdate(null, value);
128
+ }
129
+ return value;
130
+ }
131
+
132
+ /**
133
+ * Gets current or initial value at the specified "path" of the global state.
134
+ * @param path Dot-delimitered state path.
135
+ * @param options Additional options.
136
+ * @param options.initialState If "true" the value will be read
137
+ * from the initial state instead of the current one.
138
+ * @param options.initialValue If the value read from the "path" is
139
+ * "undefined", this "initialValue" will be returned instead. In such case
140
+ * "initialValue" will also be written to the "path" of the current global
141
+ * state (no matter "initialState" flag), if "undefined" is stored there.
142
+ * @return Retrieved value.
143
+ */
144
+
145
+ // .get() without arguments just falls back to .getEntireState().
146
+ get(): StateT;
147
+
148
+ // This variant attempts to automatically resolve and check the type of value
149
+ // at the given path, as precise as the actual state and path types permit.
150
+ // If the automatic path resolution is not possible, the ValueT fallsback
151
+ // to `never` (or to `undefined` in some cases), effectively forbidding
152
+ // to use this .get() variant.
153
+ get<
154
+ PathT extends null | string | undefined,
155
+ ValueArgT extends ValueAtPathT<StateT, PathT, never>,
156
+ ValueResT extends ValueAtPathT<StateT, PathT, void>,
157
+ >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
158
+
159
+ // This variant is not callable by default (without generic arguments),
160
+ // otherwise it allows to set the correct ValueT directly.
161
+ get<Unlocked extends 0 | 1 = 0, ValueT = void>(
162
+ path?: null | string,
163
+ opts?: GetOptsT<TypeLock<Unlocked, never, ValueT>>,
164
+ ): TypeLock<Unlocked, void, ValueT>;
165
+
166
+ get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {
167
+ if (isNil(path)) {
168
+ const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);
169
+ return (res as unknown) as ValueT;
170
+ }
171
+
172
+ const state = opts?.initialState ? this.#initialState : this.#currentState;
173
+
174
+ let res = get(state, path);
175
+ if (res !== undefined || opts?.initialValue === undefined) return res;
176
+
177
+ const iv = opts.initialValue;
178
+ res = isFunction(iv) ? iv() : iv;
179
+
180
+ if (!opts?.initialState || this.get(path) === undefined) {
181
+ this.set<1, unknown>(path, res);
182
+ }
183
+
184
+ return res;
185
+ }
186
+
187
+ /**
188
+ * Writes the `value` to given global state `path`.
189
+ * @param path Dot-delimitered state path. If not given, entire
190
+ * global state content is replaced by the `value`.
191
+ * @param value The value.
192
+ * @return Given `value` itself.
193
+ */
194
+
195
+ // This variant attempts automatic value type resolution & checking.
196
+ set<
197
+ PathT extends null | string | undefined,
198
+ ValueArgT extends ValueAtPathT<StateT, PathT, never>,
199
+ ValueResT extends ValueAtPathT<StateT, PathT, void>,
200
+ >(path: PathT, value: ValueArgT): ValueResT;
201
+
202
+ // This variant is disabled by default, otherwise allows to give
203
+ // expected value type explicitly.
204
+ set<Unlocked extends 0 | 1 = 0, ValueT = never>(
205
+ path: null | string | undefined,
206
+ value: TypeLock<Unlocked, never, ValueT>,
207
+ ): TypeLock<Unlocked, void, ValueT>;
208
+
209
+ set(path: null | string | undefined, value: unknown): unknown {
210
+ if (isNil(path)) return this.setEntireState(value as StateT);
211
+
212
+ if (value !== this.get(path)) {
213
+ const root = { state: this.#currentState };
214
+ let segIdx = 0;
215
+ let pos: any = root;
216
+ const pathSegments = toPath(`state.${path}`);
217
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
218
+ const seg = pathSegments[segIdx];
219
+ const next = pos[seg];
220
+ if (Array.isArray(next)) pos[seg] = [...next];
221
+ else if (isObject(next)) pos[seg] = { ...next };
222
+ else {
223
+ // We arrived to a state sub-segment, where the remaining part of
224
+ // the update path does not exist yet. We rely on lodash's set()
225
+ // function to create the remaining path, and set the value.
226
+ set(pos, pathSegments.slice(segIdx), value);
227
+ break;
228
+ }
229
+ pos = pos[seg];
230
+ }
231
+
232
+ if (segIdx === pathSegments.length - 1) {
233
+ pos[pathSegments[segIdx]] = value;
234
+ }
235
+
236
+ this.#currentState = root.state;
237
+
238
+ this.notifyStateUpdate(path, value);
239
+ }
240
+ return value;
241
+ }
242
+
243
+ /**
244
+ * Unsubscribes `callback` from watching state updates; no operation if
245
+ * `callback` is not subscribed to the state updates.
246
+ * @param callback
247
+ * @throws if {@link SsrContext} is attached to the state instance: the state
248
+ * watching functionality is intended for client-side (non-SSR) only.
249
+ */
250
+ unWatch(callback: CallbackT) {
251
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
252
+
253
+ const watchers = this.#watchers;
254
+ const pos = watchers.indexOf(callback);
255
+ if (pos >= 0) {
256
+ watchers[pos] = watchers[watchers.length - 1];
257
+ watchers.pop();
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Subscribes `callback` to watch state updates; no operation if
263
+ * `callback` is already subscribed to this state instance.
264
+ * @param callback It will be called without any arguments every
265
+ * time the state content changes (note, howhever, separate state updates can
266
+ * be applied to the state at once, and watching callbacks will be called once
267
+ * after such bulk update).
268
+ * @throws if {@link SsrContext} is attached to the state instance: the state
269
+ * watching functionality is intended for client-side (non-SSR) only.
270
+ */
271
+ watch(callback: CallbackT) {
272
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
273
+
274
+ const watchers = this.#watchers;
275
+ if (watchers.indexOf(callback) < 0) {
276
+ watchers.push(callback);
277
+ }
278
+ }
279
+ }
@@ -0,0 +1,116 @@
1
+ /* eslint-disable react/prop-types */
2
+
3
+ import { isFunction } from 'lodash';
4
+
5
+ import {
6
+ type ReactNode,
7
+ createContext,
8
+ useContext,
9
+ useRef,
10
+ } from 'react';
11
+
12
+ import GlobalState from './GlobalState';
13
+ import SsrContext from './SsrContext';
14
+
15
+ import { type ValueOrInitializerT } from './utils';
16
+
17
+ const context = createContext<GlobalState<unknown> | null>(null);
18
+
19
+ /**
20
+ * Gets {@link GlobalState} instance from the context. In most cases
21
+ * you should use {@link useGlobalState}, and other hooks to interact with
22
+ * the global state, instead of accessing it directly.
23
+ * @return
24
+ */
25
+ export function getGlobalState<StateT>(): GlobalState<StateT> {
26
+ // Here Rules of Hooks are violated because "getGlobalState()" does not follow
27
+ // convention that hook names should start with use... This is intentional in
28
+ // our case, as getGlobalState() hook is intended for advance scenarious,
29
+ // while the normal interaction with the global state should happen via
30
+ // another hook, useGlobalState().
31
+ /* eslint-disable react-hooks/rules-of-hooks */
32
+ const globalState = useContext(context);
33
+ /* eslint-enable react-hooks/rules-of-hooks */
34
+ if (!globalState) throw new Error('Missing GlobalStateProvider');
35
+ return globalState as GlobalState<StateT>;
36
+ }
37
+
38
+ /**
39
+ * @category Hooks
40
+ * @desc Gets SSR context.
41
+ * @param throwWithoutSsrContext If `true` (default),
42
+ * this hook will throw if no SSR context is attached to the global state;
43
+ * set `false` to not throw in such case. In either case the hook will throw
44
+ * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
45
+ * @returns SSR context.
46
+ * @throws
47
+ * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
48
+ * in the rendered React tree.
49
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
50
+ * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
51
+ */
52
+ export function getSsrContext<StateT>(
53
+ throwWithoutSsrContext = true,
54
+ ): SsrContext<StateT> | undefined {
55
+ const { ssrContext } = getGlobalState<StateT>();
56
+ if (!ssrContext && throwWithoutSsrContext) {
57
+ throw new Error('No SSR context found');
58
+ }
59
+ return ssrContext;
60
+ }
61
+
62
+ type NewStateProps<StateT> = {
63
+ initialState: ValueOrInitializerT<StateT>,
64
+ ssrContext?: SsrContext<StateT>;
65
+ };
66
+
67
+ type GlobalStateProviderProps<StateT> = {
68
+ children?: ReactNode;
69
+ } & (NewStateProps<StateT> | {
70
+ stateProxy: true | GlobalState<StateT>;
71
+ });
72
+
73
+ /**
74
+ * Provides global state to its children.
75
+ * @param prop.children Component children, which will be provided with
76
+ * the global state, and rendered in place of the provider.
77
+ * @param prop.initialState Initial content of the global state.
78
+ * @param prop.ssrContext Server-side rendering (SSR) context.
79
+ * @param prop.stateProxy This option is useful for code
80
+ * splitting and SSR implementation:
81
+ * - If `true`, this provider instance will fetch and reuse the global state
82
+ * from a parent provider.
83
+ * - If `GlobalState` instance, it will be used by this provider.
84
+ * - If not given, a new `GlobalState` instance will be created and used.
85
+ */
86
+ export default function GlobalStateProvider<StateT>(
87
+ { children, ...rest }: GlobalStateProviderProps<StateT>,
88
+ ) {
89
+ const state = useRef<GlobalState<StateT>>();
90
+ if (!state.current) {
91
+ // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
92
+ // graceful compatibility with JavaScript - if "undefined" stateProxy value
93
+ // is given, we want to follow the second branch, which creates a new
94
+ // GlobalState with whatever intiialState given.
95
+ if ('stateProxy' in rest && rest.stateProxy) {
96
+ if (rest.stateProxy === true) state.current = getGlobalState();
97
+ else state.current = rest.stateProxy;
98
+ } else {
99
+ const { initialState, ssrContext } = rest as NewStateProps<StateT>;
100
+
101
+ state.current = new GlobalState<StateT>(
102
+ isFunction(initialState) ? initialState() : initialState,
103
+ ssrContext,
104
+ );
105
+ }
106
+ }
107
+ return (
108
+ <context.Provider value={state.current}>
109
+ {children}
110
+ </context.Provider>
111
+ );
112
+ }
113
+
114
+ GlobalStateProvider.defaultProps = {
115
+ children: undefined,
116
+ };
@@ -0,0 +1,11 @@
1
+ export default class SsrContext<StateT> {
2
+ dirty: boolean = false;
3
+
4
+ pending: Promise<void>[] = [];
5
+
6
+ state?: StateT;
7
+
8
+ constructor(state?: StateT) {
9
+ this.state = state;
10
+ }
11
+ }