@dr.pogodin/react-global-state 0.20.1 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","setState","path","gs","prevState","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","load","loader","globalState","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } 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 LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\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 reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: string | null | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\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\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\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 */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): void | Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n set?: (data: DataT | null) => void;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\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 ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n heap.set ??= (data: DataT | null) => {\n if (!heap.globalState) throw Error('Internal error');\n setState(data, heap.path, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\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 if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\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.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, 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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\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 reload: heap.reload,\n set: heap.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<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 | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBO,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAA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
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 _isFunction = _interopRequireDefault(require("lodash/isFunction.js"));
9
- var _react = require("react");
10
- var _jsUtils = require("@dr.pogodin/js-utils");
11
- var _GlobalStateProvider = require("./GlobalStateProvider");
12
- var _utils = require("./utils");
13
- // Hook for updates of global state.
14
-
15
- /**
16
- * The primary hook for interacting with the global state, modeled after
17
- * the standard React's
18
- * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
19
- * It subscribes a component to a given `path` of global state, and provides
20
- * a function to update it. Each time the value at `path` changes, the hook
21
- * triggers re-render of its host component.
22
- *
23
- * **Note:**
24
- * - For performance, the library does not copy objects written to / read from
25
- * global state paths. You MUST NOT manually mutate returned state values,
26
- * or change objects already written into the global state, without explicitly
27
- * clonning them first yourself.
28
- * - State update notifications are asynchronous. When your code does multiple
29
- * global state updates in the same React rendering cycle, all state update
30
- * notifications are queued and dispatched together, after the current
31
- * rendering cycle. In other words, in any given rendering cycle the global
32
- * state values are "fixed", and all changes becomes visible at once in the
33
- * next triggered rendering pass.
34
- *
35
- * @param path Dot-delimitered state path. It can be undefined to
36
- * subscribe for entire state.
37
- *
38
- * Under-the-hood state values are read and written using `lodash`
39
- * [_.get()](https://lodash.com/docs/4.17.15#get) and
40
- * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
41
- * to access state paths which have not been created before.
42
- * @param initialValue Initial value to set at the `path`, or its
43
- * factory:
44
- * - If a function is given, it will act similar to
45
- * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
46
- * only if the value at `path` is `undefined`, the function will be executed,
47
- * and the value it returns will be written to the `path`.
48
- * - Otherwise, the given value itself will be written to the `path`,
49
- * if the current value at `path` is `undefined`.
50
- * @return It returs an array with two elements: `[value, setValue]`:
51
- *
52
- * - The `value` is the current value at given `path`.
53
- *
54
- * - The `setValue()` is setter function to write a new value to the `path`.
55
- *
56
- * Similar to the standard React's `useState()`, it supports
57
- * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
58
- * if `setValue()` is called with a function as argument, that function will
59
- * be called and its return value will be written to `path`. Otherwise,
60
- * the argument of `setValue()` itself is written to `path`.
61
- *
62
- * Also, similar to the standard React's state setters, `setValue()` is
63
- * stable function: it does not change between component re-renders.
64
- */
65
-
66
- // "Enforced type overload"
67
-
68
- // "Entire state overload"
69
-
70
- // "State evaluation overload"
71
-
72
- function useGlobalState(path,
73
- // TODO: Revise it later!
74
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
- initialValue
76
-
77
- // TODO: Revise it later!
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- ) {
80
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
81
- const ref = (0, _react.useRef)(null);
82
- const [stable] = (0, _react.useState)(() => {
83
- const emitter = new _jsUtils.Emitter();
84
- const setter = value => {
85
- const rc = ref.current;
86
- if (!rc) throw Error('Internal error');
87
- const newState = (0, _isFunction.default)(value) ? value(rc.globalState.get(rc.path)) : value;
88
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
89
- /* eslint-disable no-console */
90
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path ?? ''}`);
91
- console.log('New value:', (0, _utils.cloneDeepForLog)(newState, rc.path ?? ''));
92
- console.groupEnd();
93
- /* eslint-enable no-console */
94
- }
95
- rc.globalState.set(rc.path, newState);
96
-
97
- // NOTE: The regular global state's update notifications, automatically
98
- // triggered by the rc.globalState.set() call above, are batched, and
99
- // scheduled to fire asynchronosuly at a later time, which is problematic
100
- // for managed text inputs - if they have their value update delayed to
101
- // future render cycles, it will result in reset of their cursor position
102
- // to the value end. Calling the rc.emitter.emit() below causes a sooner
103
- // state update for the current component, thus working around the issue.
104
- // For additional details see the original issue:
105
- // https://github.com/birdofpreyru/react-global-state/issues/22
106
- if (newState !== rc.prevValue) emitter.emit();
107
- };
108
- const subscribe = emitter.addListener.bind(emitter);
109
- return {
110
- emitter,
111
- setter,
112
- subscribe
113
- };
114
- });
115
- const value = (0, _react.useSyncExternalStore)(stable.subscribe, () => globalState.get(path, {
116
- initialValue
117
- }), () => globalState.get(path, {
118
- initialState: true,
119
- initialValue
120
- }));
121
- ref.current ??= {
122
- globalState,
123
- path,
124
- prevValue: value
125
- };
126
- (0, _react.useEffect)(() => {
127
- ref.current = {
128
- globalState,
129
- path,
130
- prevValue: ref.current.prevValue
131
- };
132
- const watcher = () => {
133
- const nextValue = globalState.get(path);
134
- if (ref.current.prevValue !== nextValue) {
135
- ref.current.prevValue = nextValue;
136
- stable.emitter.emit();
137
- }
138
- };
139
- globalState.watch(watcher);
140
- watcher();
141
- return () => {
142
- globalState.unWatch(watcher);
143
- };
144
- }, [globalState, stable.emitter, path]);
145
- return [value, stable.setter];
146
- }
147
- var _default = exports.default = useGlobalState; // TODO: Revise.
148
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
149
- //# sourceMappingURL=useGlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["_isFunction","_interopRequireDefault","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","stable","useState","emitter","Emitter","setter","value","rc","current","Error","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","prevValue","emit","subscribe","addListener","bind","useSyncExternalStore","initialState","useEffect","watcher","nextValue","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport isFunction from 'lodash/isFunction.js';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\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\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>,\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\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 // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = isFunction(value)\n ? value(rc.globalState.get(rc.path)) as unknown\n : value;\n\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:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\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 | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;;AAEA,IAAAA,WAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AASA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAlBA;;AA8CA;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;;AAEA;;AASA;;AAGA;;AAkBA,SAASK,cAAcA,CACrBC,IAAoB;AACpB;AACA;AACAC;;AAEA;AACA;AAAA,EACyB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAW,IAAI,CAAC;EAElC,MAAM,CAACC,MAAM,CAAC,GAAG,IAAAC,eAAQ,EAAU,MAAM;IACvC,MAAMC,OAAO,GAAG,IAAIC,gBAAO,CAAC,CAAC;IAC7B,MAAMC,MAAM,GAAIC,KAAc,IAAK;MACjC,MAAMC,EAAE,GAAGR,GAAG,CAACS,OAAO;MACtB,IAAI,CAACD,EAAE,EAAE,MAAME,KAAK,CAAC,gBAAgB,CAAC;MAEtC,MAAMC,QAAQ,GAAG,IAAAC,mBAAU,EAACL,KAAK,CAAC,GAC9BA,KAAK,C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,GAAG;MACZX,WAAW;MACXF,IAAI;MACJ4B,SAAS,EAAExB,GAAG,CAACS,OAAO,CAAEe;IAC1B,CAAC;IAED,MAAMQ,OAAO,GAAGA,CAAA,KAAM;MACpB,MAAMC,SAAS,GAAGnC,WAAW,CAACe,GAAG,CAAkBjB,IAAI,CAAC;MACxD,IAAII,GAAG,CAACS,OAAO,CAAEe,SAAS,KAAKS,SAAS,EAAE;QACxCjC,GAAG,CAACS,OAAO,CAAEe,SAAS,GAAGS,SAAS;QAClC/B,MAAM,CAACE,OAAO,CAACqB,IAAI,CAAC,CAAC;MACvB;IACF,CAAC;IAED3B,WAAW,CAACoC,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IAET,OAAO,MAAM;MACXlC,WAAW,CAACqC,OAAO,CAACH,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAClC,WAAW,EAAEI,MAAM,CAACE,OAAO,EAAER,IAAI,CAAC,CAAC;EAEvC,OAAO,CAACW,KAAK,EAAEL,MAAM,CAACI,MAAM,CAAC;AAC/B;AAAC,IAAA8B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc3C,cAAc,EAE7B;AACA","ignoreList":[]}
@@ -1,92 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.cloneDeepForLog = cloneDeepForLog;
8
- exports.escape = escape;
9
- exports.hash = hash;
10
- exports.isDebugMode = isDebugMode;
11
- var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep.js"));
12
- // TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
13
- // lib.
14
-
15
- /**
16
- * Given the type of state, `StateT`, and the type of state path, `PathT`,
17
- * it evaluates the type of value at that path of the state, if it can be
18
- * evaluated from the path type (it is possible when `PathT` is a string
19
- * literal type, and `StateT` elements along this path have appropriate
20
- * types); otherwise it falls back to the specified `UnknownT` type,
21
- * which should be set either `never` (for input arguments), or `void`
22
- * (for return types) - `never` and `void` in those places forbid assignments,
23
- * and are not auto-inferred to more permissible types.
24
- *
25
- * BEWARE: When StateT is any the construct resolves to any for any string
26
- * paths.
27
- */
28
-
29
- /**
30
- * Returns 'true' if debug logging should be performed; 'false' otherwise.
31
- *
32
- * BEWARE: The actual safeguards for the debug logging still should read
33
- * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
34
- * // Some debug logging
35
- * }
36
- * to ensure that debug code is stripped out by Webpack in production mode.
37
- *
38
- * @returns
39
- * @ignore
40
- */
41
- function isDebugMode() {
42
- try {
43
- return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
44
- } catch {
45
- return false;
46
- }
47
- }
48
- const cloneDeepBailKeys = new Set();
49
-
50
- /**
51
- * Deep-clones given value for logging purposes, or returns the value itself
52
- * if the previous clone attempt, with the same key, took more than 300ms
53
- * (to avoid situations when large payload in the global state slows down
54
- * development versions of the app due to the logging overhead).
55
- */
56
- function cloneDeepForLog(value, key = '') {
57
- if (cloneDeepBailKeys.has(key)) {
58
- // eslint-disable-next-line no-console
59
- console.warn(`The logged value won't be clonned (key "${key}").`);
60
- return value;
61
- }
62
- const start = Date.now();
63
- const res = (0, _cloneDeep.default)(value);
64
- const time = Date.now() - start;
65
- if (time > 300) {
66
- // eslint-disable-next-line no-console
67
- console.warn(`${time}ms spent to clone the logged value (key "${key}").`);
68
- cloneDeepBailKeys.add(key);
69
- }
70
- return res;
71
- }
72
-
73
- /**
74
- * Converts given value to an escaped string. For now, we are good with the most
75
- * trivial escape logic:
76
- * - '%' characters are replaced by '%0' code pair;
77
- * - '/' characters are replaced by '%1' code pair.
78
- */
79
- function escape(x) {
80
- return typeof x === 'string' ? x.replace(/%/g, '%0').replace(/\//g, '%1') : x.toString();
81
- }
82
-
83
- /**
84
- * Hashes given string array. For our current needs we are fine to go with
85
- * the most trivial implementation, which probably should not be called "hash"
86
- * in the strict sense: we just escape each given string to not include '/'
87
- * characters, and then we join all those strings using '/' as the separator.
88
- */
89
- function hash(items) {
90
- return items.map(escape).join('/');
91
- }
92
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["_cloneDeep","_interopRequireDefault","require","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","cloneDeep","time","add","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\nimport cloneDeep from 'lodash/cloneDeep.js';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\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\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\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 {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');\n}\n"],"mappings":";;;;;;;;;;AACA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,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