@dr.pogodin/react-global-state 0.12.0 → 0.14.0
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.
- package/build/common/GlobalState.js.map +1 -1
- package/build/common/GlobalStateProvider.js.map +1 -1
- package/build/common/SsrContext.js.map +1 -1
- package/build/common/index.js +1 -1
- package/build/common/index.js.map +1 -1
- package/build/common/useAsyncCollection.js.map +1 -1
- package/build/common/useAsyncData.js +15 -6
- package/build/common/useAsyncData.js.map +1 -1
- package/build/common/useGlobalState.js +38 -33
- package/build/common/useGlobalState.js.map +1 -1
- package/build/common/utils.js.map +1 -1
- package/build/module/GlobalState.js +29 -43
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/GlobalStateProvider.js.map +1 -1
- package/build/module/SsrContext.js.map +1 -1
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js +15 -5
- package/build/module/useAsyncData.js.map +1 -1
- package/build/module/useGlobalState.js +38 -33
- package/build/module/useGlobalState.js.map +1 -1
- package/build/module/utils.js.map +1 -1
- package/build/types/useAsyncData.d.ts +4 -1
- package/package.json +26 -27
- package/src/useAsyncData.ts +10 -5
- package/src/useGlobalState.ts +56 -40
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","emit","watcher","get","cb","addListener","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\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<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n const rc: GlobalStateRef = ref.current || {\n emitter: new Emitter(),\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value) ? value(rc.state) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // 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.state) rc.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n watcher: () => {\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) rc.emitter.emit();\n },\n };\n ref.current = rc;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => rc.emitter.addListener(cb),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue }),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | 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":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAOEC,WAAW;;AAgBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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ACM,KAAK,EAAEN,EAAE,CAACE,OAAO,CAACa,IAAI,CAAC,CAAC;IAC3C;EACF,CAAC;EACDhB,GAAG,CAACE,OAAO,GAAGD,EAAE;EAEhBA,EAAE,CAACF,WAAW,GAAGA,WAAW;EAC5BE,EAAE,CAACJ,IAAI,GAAGA,IAAI;EAEdI,EAAE,CAACM,KAAK,GAAGf,oBAAoB,CAC5B2B,EAAE,IAAKlB,EAAE,CAACE,OAAO,CAACiB,WAAW,CAACD,EAAE,CAAC,EAClC,MAAMlB,EAAE,CAACF,WAAW,CAACmB,GAAG,CAAkBjB,EAAE,CAACJ,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EACpE,MAAMG,EAAE,CAACF,WAAW,CAACmB,GAAG,CAAkBjB,EAAE,CAACJ,IAAI,EAAE;IAAEC,YAAY;IAAEuB,YAAY,EAAE;EAAK,CAAC,CACzF,CAAC;EAED/B,SAAS,CAAC,MAAM;IACd,MAAM;MAAE2B;IAAQ,CAAC,GAAGjB,GAAG,CAACE,OAAQ;IAChCH,WAAW,CAACuB,KAAK,CAACL,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAMlB,WAAW,CAACwB,OAAO,CAACN,OAAO,CAAC;EAC3C,CAAC,EAAE,CAAClB,WAAW,CAAC,CAAC;EAEjBT,SAAS,CAAC,MAAM;IACdU,GAAG,CAACE,OAAO,CAAEe,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACpB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACI,EAAE,CAACM,KAAK,EAAEN,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc"}
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\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<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\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:', cloneDeep(newState));\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!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | 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":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QA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T,OAAO,MAAMtB,WAAW,CAACyB,OAAO,CAACH,OAAO,CAAC;EAC3C,CAAC,EAAE,CAACtB,WAAW,CAAC,CAAC;EAEjBT,SAAS,CAAC,MAAM;IACdU,GAAG,CAACE,OAAO,CAAEmB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACxB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACI,EAAE,CAACe,KAAK,EAAEf,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare 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 LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n"],"mappings":"AAIA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare 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 LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n"],"mappings":"AAIA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF","ignoreList":[]}
|
|
@@ -9,7 +9,10 @@ export type AsyncDataEnvelopeT<DataT> = {
|
|
|
9
9
|
operationId: string;
|
|
10
10
|
timestamp: number;
|
|
11
11
|
};
|
|
12
|
-
export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null
|
|
12
|
+
export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null, { numRefs, timestamp }?: {
|
|
13
|
+
numRefs?: number | undefined;
|
|
14
|
+
timestamp?: number | undefined;
|
|
15
|
+
}): AsyncDataEnvelopeT<DataT>;
|
|
13
16
|
export type UseAsyncDataOptionsT = {
|
|
14
17
|
deps?: unknown[];
|
|
15
18
|
garbageCollectAge?: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
5
|
"main": "./build/common/index.js",
|
|
6
6
|
"react-native": "src/index.ts",
|
|
@@ -43,41 +43,40 @@
|
|
|
43
43
|
"node": ">=18"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@babel/runtime": "^7.
|
|
47
|
-
"@dr.pogodin/js-utils": "^0.0.
|
|
48
|
-
"@types/lodash": "^4.
|
|
46
|
+
"@babel/runtime": "^7.24.1",
|
|
47
|
+
"@dr.pogodin/js-utils": "^0.0.9",
|
|
48
|
+
"@types/lodash": "^4.17.0",
|
|
49
49
|
"lodash": "^4.17.21",
|
|
50
50
|
"uuid": "^9.0.1"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@babel/cli": "^7.
|
|
54
|
-
"@babel/core": "^7.
|
|
55
|
-
"@babel/eslint-parser": "^7.
|
|
53
|
+
"@babel/cli": "^7.24.1",
|
|
54
|
+
"@babel/core": "^7.24.3",
|
|
55
|
+
"@babel/eslint-parser": "^7.24.1",
|
|
56
56
|
"@babel/eslint-plugin": "^7.23.5",
|
|
57
|
-
"@babel/node": "^7.
|
|
58
|
-
"@babel/plugin-transform-runtime": "^7.
|
|
59
|
-
"@babel/preset-env": "^7.
|
|
60
|
-
"@babel/preset-react": "^7.
|
|
61
|
-
"@babel/preset-typescript": "^7.
|
|
62
|
-
"@tsconfig/recommended": "^1.0.
|
|
63
|
-
"@tsd/typescript": "^5.
|
|
64
|
-
"@types/jest": "^29.5.
|
|
57
|
+
"@babel/node": "^7.23.9",
|
|
58
|
+
"@babel/plugin-transform-runtime": "^7.24.3",
|
|
59
|
+
"@babel/preset-env": "^7.24.3",
|
|
60
|
+
"@babel/preset-react": "^7.24.1",
|
|
61
|
+
"@babel/preset-typescript": "^7.24.1",
|
|
62
|
+
"@tsconfig/recommended": "^1.0.5",
|
|
63
|
+
"@tsd/typescript": "^5.4.3",
|
|
64
|
+
"@types/jest": "^29.5.12",
|
|
65
65
|
"@types/pretty": "^2.0.3",
|
|
66
|
-
"@types/react": "^18.2.
|
|
67
|
-
"@types/react-dom": "^18.2.
|
|
68
|
-
"@types/uuid": "^9.0.
|
|
69
|
-
"
|
|
70
|
-
"@typescript-eslint/parser": "^6.13.2",
|
|
66
|
+
"@types/react": "^18.2.73",
|
|
67
|
+
"@types/react-dom": "^18.2.23",
|
|
68
|
+
"@types/uuid": "^9.0.8",
|
|
69
|
+
"typescript-eslint": "^7.4.0",
|
|
71
70
|
"babel-jest": "^29.7.0",
|
|
72
71
|
"babel-plugin-module-resolver": "^5.0.0",
|
|
73
|
-
"eslint": "^8.
|
|
72
|
+
"eslint": "^8.57.0",
|
|
74
73
|
"eslint-config-airbnb": "^19.0.4",
|
|
75
|
-
"eslint-config-airbnb-typescript": "^
|
|
74
|
+
"eslint-config-airbnb-typescript": "^18.0.0",
|
|
76
75
|
"eslint-import-resolver-babel-module": "^5.3.2",
|
|
77
|
-
"eslint-plugin-import": "^2.29.
|
|
78
|
-
"eslint-plugin-jest": "^27.
|
|
76
|
+
"eslint-plugin-import": "^2.29.1",
|
|
77
|
+
"eslint-plugin-jest": "^27.9.0",
|
|
79
78
|
"eslint-plugin-jsx-a11y": "^6.8.0",
|
|
80
|
-
"eslint-plugin-react": "^7.
|
|
79
|
+
"eslint-plugin-react": "^7.34.1",
|
|
81
80
|
"eslint-plugin-react-hooks": "^4.6.0",
|
|
82
81
|
"jest": "^29.7.0",
|
|
83
82
|
"jest-environment-jsdom": "^29.7.0",
|
|
@@ -85,8 +84,8 @@
|
|
|
85
84
|
"mockdate": "^3.0.5",
|
|
86
85
|
"pretty": "^2.0.0",
|
|
87
86
|
"rimraf": "^5.0.1",
|
|
88
|
-
"tsd-lite": "^0.
|
|
89
|
-
"typescript": "^5.
|
|
87
|
+
"tsd-lite": "^0.9.0",
|
|
88
|
+
"typescript": "^5.4.3"
|
|
90
89
|
},
|
|
91
90
|
"peerDependencies": {
|
|
92
91
|
"react": "^18.2.0",
|
package/src/useAsyncData.ts
CHANGED
|
@@ -36,12 +36,13 @@ export type AsyncDataEnvelopeT<DataT> = {
|
|
|
36
36
|
|
|
37
37
|
export function newAsyncDataEnvelope<DataT>(
|
|
38
38
|
initialData: DataT | null = null,
|
|
39
|
+
{ numRefs = 0, timestamp = 0 } = {},
|
|
39
40
|
): AsyncDataEnvelopeT<DataT> {
|
|
40
41
|
return {
|
|
41
42
|
data: initialData,
|
|
42
|
-
numRefs
|
|
43
|
+
numRefs,
|
|
43
44
|
operationId: '',
|
|
44
|
-
timestamp
|
|
45
|
+
timestamp,
|
|
45
46
|
};
|
|
46
47
|
}
|
|
47
48
|
|
|
@@ -280,12 +281,16 @@ function useAsyncData<DataT>(
|
|
|
280
281
|
}
|
|
281
282
|
});
|
|
282
283
|
|
|
283
|
-
const deps = options.deps || [];
|
|
284
284
|
useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
|
|
285
|
-
|
|
285
|
+
const { deps } = options;
|
|
286
|
+
if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
|
|
286
287
|
load(path, loader, globalState, null);
|
|
287
288
|
}
|
|
288
|
-
|
|
289
|
+
|
|
290
|
+
// Here we need to default to empty array, so that this hook is re-evaluated
|
|
291
|
+
// only when dependencies specified in options change, and it should not be
|
|
292
|
+
// re-evaluated at all if no `deps` option is used.
|
|
293
|
+
}, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
|
|
289
294
|
}
|
|
290
295
|
|
|
291
296
|
const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(
|
package/src/useGlobalState.ts
CHANGED
|
@@ -20,11 +20,14 @@ import {
|
|
|
20
20
|
|
|
21
21
|
export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
|
|
22
22
|
|
|
23
|
+
type ListenerT = () => void;
|
|
24
|
+
|
|
23
25
|
type GlobalStateRef = {
|
|
24
26
|
emitter: Emitter<[]>;
|
|
25
27
|
globalState: GlobalState<unknown>;
|
|
26
28
|
path: null | string | undefined;
|
|
27
29
|
setter: SetterT<unknown>;
|
|
30
|
+
subscribe: (listener: ListenerT) => () => void;
|
|
28
31
|
state: unknown;
|
|
29
32
|
watcher: CallbackT;
|
|
30
33
|
};
|
|
@@ -110,51 +113,64 @@ function useGlobalState(
|
|
|
110
113
|
const globalState = getGlobalState();
|
|
111
114
|
|
|
112
115
|
const ref = useRef<GlobalStateRef>();
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
116
|
+
|
|
117
|
+
let rc: GlobalStateRef;
|
|
118
|
+
if (!ref.current) {
|
|
119
|
+
const emitter = new Emitter();
|
|
120
|
+
ref.current = {
|
|
121
|
+
emitter,
|
|
122
|
+
globalState,
|
|
123
|
+
path,
|
|
124
|
+
setter: (value) => {
|
|
125
|
+
const newState = isFunction(value)
|
|
126
|
+
? value(rc!.globalState.get(rc!.path))
|
|
127
|
+
: value;
|
|
128
|
+
|
|
129
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
130
|
+
/* eslint-disable no-console */
|
|
131
|
+
console.groupCollapsed(
|
|
132
|
+
`ReactGlobalState - useGlobalState setter triggered for path ${
|
|
133
|
+
rc!.path || ''
|
|
134
|
+
}`,
|
|
135
|
+
);
|
|
136
|
+
console.log('New value:', cloneDeep(newState));
|
|
137
|
+
console.groupEnd();
|
|
138
|
+
/* eslint-enable no-console */
|
|
139
|
+
}
|
|
140
|
+
rc!.globalState.set<ForceT, unknown>(rc!.path, newState);
|
|
141
|
+
|
|
142
|
+
// NOTE: The regular global state's update notifications, automatically
|
|
143
|
+
// triggered by the rc.globalState.set() call above, are batched, and
|
|
144
|
+
// scheduled to fire asynchronosuly at a later time, which is problematic
|
|
145
|
+
// for managed text inputs - if they have their value update delayed to
|
|
146
|
+
// future render cycles, it will result in reset of their cursor position
|
|
147
|
+
// to the value end. Calling the rc.emitter.emit() below causes a sooner
|
|
148
|
+
// state update for the current component, thus working around the issue.
|
|
149
|
+
// For additional details see the original issue:
|
|
150
|
+
// https://github.com/birdofpreyru/react-global-state/issues/22
|
|
151
|
+
if (newState !== rc!.state) rc!.emitter.emit();
|
|
152
|
+
},
|
|
153
|
+
state: isFunction(initialValue) ? initialValue() : initialValue,
|
|
154
|
+
subscribe: emitter.addListener.bind(emitter),
|
|
155
|
+
watcher: () => {
|
|
156
|
+
const state = rc!.globalState.get(rc!.path);
|
|
157
|
+
if (state !== rc!.state) rc!.emitter.emit();
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
rc = ref.current!;
|
|
150
162
|
|
|
151
163
|
rc.globalState = globalState;
|
|
152
164
|
rc.path = path;
|
|
153
165
|
|
|
154
166
|
rc.state = useSyncExternalStore(
|
|
155
|
-
|
|
156
|
-
() => rc
|
|
157
|
-
|
|
167
|
+
rc.subscribe,
|
|
168
|
+
() => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),
|
|
169
|
+
|
|
170
|
+
() => rc!.globalState.get<ForceT, unknown>(
|
|
171
|
+
rc!.path,
|
|
172
|
+
{ initialValue, initialState: true },
|
|
173
|
+
),
|
|
158
174
|
);
|
|
159
175
|
|
|
160
176
|
useEffect(() => {
|