@dr.pogodin/react-global-state 0.19.4 → 0.20.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.
@@ -1,7 +1,7 @@
1
1
  // Hook for updates of global state.
2
2
 
3
3
  import { isFunction } from 'lodash';
4
- import { useEffect, useRef, useSyncExternalStore } from 'react';
4
+ import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
5
5
  import { Emitter } from '@dr.pogodin/js-utils';
6
6
  import { getGlobalState } from "./GlobalStateProvider";
7
7
  import { cloneDeepForLog, isDebugMode } from "./utils";
@@ -71,74 +71,74 @@ initialValue
71
71
  // TODO: Revise it later!
72
72
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
73
  ) {
74
+ var _ref$current;
74
75
  const globalState = getGlobalState();
75
- const ref = useRef(undefined);
76
-
77
- // TODO: Revise how this `rc` variable is used, perhaps we can simplify stuff
78
- // here.
79
- let rc = ref.current;
80
- if (!ref.current) {
76
+ const ref = useRef(null);
77
+ const [stable] = useState(() => {
81
78
  const emitter = new Emitter();
82
- ref.current = {
83
- emitter,
84
- globalState,
85
- path,
86
- setter: value => {
87
- const newState = isFunction(value) ? value(rc.globalState.get(rc.path)) : value;
88
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
89
- var _path, _path2;
90
- /* eslint-disable no-console */
91
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${(_path = rc.path) !== null && _path !== void 0 ? _path : ''}`);
92
- console.log('New value:', cloneDeepForLog(newState, (_path2 = rc.path) !== null && _path2 !== void 0 ? _path2 : ''));
93
- console.groupEnd();
94
- /* eslint-enable no-console */
95
- }
96
- rc.globalState.set(rc.path, newState);
97
-
98
- // NOTE: The regular global state's update notifications, automatically
99
- // triggered by the rc.globalState.set() call above, are batched, and
100
- // scheduled to fire asynchronosuly at a later time, which is problematic
101
- // for managed text inputs - if they have their value update delayed to
102
- // future render cycles, it will result in reset of their cursor position
103
- // to the value end. Calling the rc.emitter.emit() below causes a sooner
104
- // state update for the current component, thus working around the issue.
105
- // For additional details see the original issue:
106
- // https://github.com/birdofpreyru/react-global-state/issues/22
107
- if (newState !== rc.state) rc.emitter.emit();
108
- },
109
- state: isFunction(initialValue) ? initialValue() : initialValue,
110
- subscribe: emitter.addListener.bind(emitter),
111
- watcher: () => {
112
- // TODO: Revise it later.
113
- // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
114
- const state = rc.globalState.get(rc.path);
115
- if (state !== rc.state) rc.emitter.emit();
79
+ const setter = value => {
80
+ const rc = ref.current;
81
+ if (!rc) throw Error('Internal error');
82
+ const newState = isFunction(value) ? value(rc.globalState.get(rc.path)) : value;
83
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
84
+ var _rc$path, _rc$path2;
85
+ /* eslint-disable no-console */
86
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${(_rc$path = rc.path) !== null && _rc$path !== void 0 ? _rc$path : ''}`);
87
+ console.log('New value:', cloneDeepForLog(newState, (_rc$path2 = rc.path) !== null && _rc$path2 !== void 0 ? _rc$path2 : ''));
88
+ console.groupEnd();
89
+ /* eslint-enable no-console */
116
90
  }
91
+ rc.globalState.set(rc.path, newState);
92
+
93
+ // NOTE: The regular global state's update notifications, automatically
94
+ // triggered by the rc.globalState.set() call above, are batched, and
95
+ // scheduled to fire asynchronosuly at a later time, which is problematic
96
+ // for managed text inputs - if they have their value update delayed to
97
+ // future render cycles, it will result in reset of their cursor position
98
+ // to the value end. Calling the rc.emitter.emit() below causes a sooner
99
+ // state update for the current component, thus working around the issue.
100
+ // For additional details see the original issue:
101
+ // https://github.com/birdofpreyru/react-global-state/issues/22
102
+ if (newState !== rc.prevValue) emitter.emit();
103
+ };
104
+ const subscribe = emitter.addListener.bind(emitter);
105
+ return {
106
+ emitter,
107
+ setter,
108
+ subscribe
117
109
  };
118
- }
119
- rc = ref.current;
120
- rc.globalState = globalState;
121
- rc.path = path;
122
- rc.state = useSyncExternalStore(rc.subscribe, () => rc.globalState.get(rc.path, {
110
+ });
111
+ const value = useSyncExternalStore(stable.subscribe, () => globalState.get(path, {
123
112
  initialValue
124
- }), () => rc.globalState.get(rc.path, {
113
+ }), () => globalState.get(path, {
125
114
  initialState: true,
126
115
  initialValue
127
116
  }));
117
+ (_ref$current = ref.current) !== null && _ref$current !== void 0 ? _ref$current : ref.current = {
118
+ globalState,
119
+ path,
120
+ prevValue: value
121
+ };
128
122
  useEffect(() => {
129
- const {
130
- watcher
131
- } = ref.current;
123
+ ref.current = {
124
+ globalState,
125
+ path,
126
+ prevValue: ref.current.prevValue
127
+ };
128
+ const watcher = () => {
129
+ const nextValue = globalState.get(path);
130
+ if (ref.current.prevValue !== nextValue) {
131
+ ref.current.prevValue = nextValue;
132
+ stable.emitter.emit();
133
+ }
134
+ };
132
135
  globalState.watch(watcher);
133
136
  watcher();
134
137
  return () => {
135
138
  globalState.unWatch(watcher);
136
139
  };
137
- }, [globalState]);
138
- useEffect(() => {
139
- ref.current.watcher();
140
- }, [path]);
141
- return [rc.state, rc.setter];
140
+ }, [globalState, stable.emitter, path]);
141
+ return [value, stable.setter];
142
142
  }
143
143
  export default useGlobalState;
144
144
 
@@ -1 +1 @@
1
- {"version":3,"file":"useGlobalState.js","names":["isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","cloneDeepForLog","isDebugMode","useGlobalState","path","initialValue","globalState","ref","undefined","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","_path","_path2","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 { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\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 CallbackT,\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 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<\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<GlobalStateRef>(undefined);\n\n // TODO: Revise how this `rc` variable is used, perhaps we can simplify stuff\n // here.\n let rc: GlobalStateRef | undefined = ref.current;\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)) 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!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n // TODO: Revise it later.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const state = rc!.globalState.get(rc!.path) as unknown;\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 { initialState: true, initialValue },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.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":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAGEC,SAAS,EACTC,MAAM,EACNC,oBAAoB,QACf,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAOEC,eAAe,EACfC,WAAW;;AAmBb;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,SAASC,cAAcA,CACrBC,IAAoB;AACpB;AACA;AACAC;;AAEA;AACA;AAAA,EACyB;EACzB,MAAMC,WAAW,GAAGN,cAAc,CAAC,CAAC;EAEpC,MAAMO,GAAG,GAAGV,MAAM,CAAiBW,SAAS,CAAC;;EAE7C;EACA;EACA,IAAIC,EAA8B,GAAGF,GAAG,CAACG,OAAO;EAChD,IAAI,CAACH,GAAG,CAACG,OAAO,EAAE;IAChB,MAAMC,OAAO,GAAG,IAAIZ,OAAO,CAAC,CAAC;IAC7BQ,GAAG,CAACG,OAAO,GAAG;MACZC,OAAO;MACPL,WAAW;MACXF,IAAI;MACJQ,MAAM,EAAGC,KAAK,IAAK;QACjB,M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AC,CAAC;MAC7C;IACF,CAAC;EACH;EACAlB,EAAE,GAAGF,GAAG,CAACG,OAAQ;EAEjBD,EAAE,CAACH,WAAW,GAAGA,WAAW;EAC5BG,EAAE,CAACL,IAAI,GAAGA,IAAI;EAEdK,EAAE,CAACiB,KAAK,GAAG5B,oBAAoB,CAC7BW,EAAE,CAACmB,SAAS,EACZ,MAAMnB,EAAE,CAACH,WAAW,CAACS,GAAG,CAAkBN,EAAE,CAACL,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEpE,MAAMI,EAAE,CAACH,WAAW,CAACS,GAAG,CACtBN,EAAE,CAACL,IAAI,EACP;IAAE4B,YAAY,EAAE,IAAI;IAAE3B;EAAa,CACrC,CACF,CAAC;EAEDT,SAAS,CAAC,MAAM;IACd,MAAM;MAAEmC;IAAQ,CAAC,GAAGxB,GAAG,CAACG,OAAQ;IAChCJ,WAAW,CAAC2B,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM;MACXzB,WAAW,CAAC4B,OAAO,CAACH,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAACzB,WAAW,CAAC,CAAC;EAEjBV,SAAS,CAAC,MAAM;IACdW,GAAG,CAACG,OAAO,CAAEqB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC3B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACK,EAAE,CAACiB,KAAK,EAAEjB,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeT,cAAc;;AAE7B;AACA","ignoreList":[]}
1
+ {"version":3,"file":"useGlobalState.js","names":["isFunction","useEffect","useRef","useState","useSyncExternalStore","Emitter","getGlobalState","cloneDeepForLog","isDebugMode","useGlobalState","path","initialValue","_ref$current","globalState","ref","stable","emitter","setter","value","rc","current","Error","newState","get","process","env","NODE_ENV","_rc$path","_rc$path2","console","groupCollapsed","log","groupEnd","set","prevValue","emit","subscribe","addListener","bind","initialState","watcher","nextValue","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\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":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAGEC,SAAS,EACTC,MAAM,EACNC,QAAQ,EACRC,oBAAoB,QACf,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAMEC,eAAe,EACfC,WAAW;;AAqBb;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,SAASC,cAAcA,CACrBC,IAAoB;AACpB;AACA;AACAC;;AAEA;AACA;AAAA,EACyB;EAAA,IAAAC,YAAA;EACzB,MAAMC,WAAW,GAAGP,cAAc,CAAC,CAAC;EAEpC,MAAMQ,GAAG,GAAGZ,MAAM,CAAW,IAAI,CAAC;EAElC,MAAM,CAACa,MAAM,CAAC,GAAGZ,QAAQ,CAAU,MAAM;IACvC,MAAMa,OAAO,GAAG,IAAIX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WAAW,CAACU,GAAG,CAAkBb,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAE9D,MAAME,WAAW,CAACU,GAAG,CACnBb,IAAI,EACJ;IAAE6B,YAAY,EAAE,IAAI;IAAE5B;EAAa,CACrC,CACF,CAAC;EAED,CAAAC,YAAA,GAAAE,GAAG,CAACM,OAAO,cAAAR,YAAA,cAAAA,YAAA,GAAXE,GAAG,CAACM,OAAO,GAAK;IACdP,WAAW;IACXH,IAAI;IACJwB,SAAS,EAAEhB;EACb,CAAC;EAEDjB,SAAS,CAAC,MAAM;IACda,GAAG,CAACM,OAAO,GAAG;MACZP,WAAW;MACXH,IAAI;MACJwB,SAAS,EAAEpB,GAAG,CAACM,OAAO,CAAEc;IAC1B,CAAC;IAED,MAAMM,OAAO,GAAGA,CAAA,KAAM;MACpB,MAAMC,SAAS,GAAG5B,WAAW,CAACU,GAAG,CAAkBb,IAAI,CAAC;MACxD,IAAII,GAAG,CAACM,OAAO,CAAEc,SAAS,KAAKO,SAAS,EAAE;QACxC3B,GAAG,CAACM,OAAO,CAAEc,SAAS,GAAGO,SAAS;QAClC1B,MAAM,CAACC,OAAO,CAACmB,IAAI,CAAC,CAAC;MACvB;IACF,CAAC;IAEDtB,WAAW,CAAC6B,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IAET,OAAO,MAAM;MACX3B,WAAW,CAAC8B,OAAO,CAACH,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAC3B,WAAW,EAAEE,MAAM,CAACC,OAAO,EAAEN,IAAI,CAAC,CAAC;EAEvC,OAAO,CAACQ,KAAK,EAAEH,MAAM,CAACE,MAAM,CAAC;AAC/B;AAEA,eAAeR,cAAc;;AAE7B;AACA","ignoreList":[]}
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.19.4",
3
+ "version": "0.20.0",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/code/index.js",
6
6
  "types": "./build/types/index.d.ts",
7
7
  "exports": {
8
8
  "require": "./build/cjs/index.js",
9
+ "types": "./build/types/index.d.ts",
9
10
  "default": "./build/code/index.js"
10
11
  },
11
12
  "scripts": {
@@ -37,42 +38,42 @@
37
38
  },
38
39
  "homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
39
40
  "engines": {
40
- "node": ">=18"
41
+ "node": ">=20"
41
42
  },
42
43
  "dependencies": {
43
- "@babel/runtime": "^7.28.2",
44
+ "@babel/runtime": "^7.28.4",
44
45
  "@dr.pogodin/js-utils": "^0.1.3",
45
46
  "@types/lodash": "^4.17.20",
46
47
  "lodash": "^4.17.21",
47
- "uuid": "^11.1.0"
48
+ "uuid": "^13.0.0"
48
49
  },
49
50
  "devDependencies": {
50
- "@babel/cli": "^7.28.0",
51
- "@babel/core": "^7.28.0",
51
+ "@babel/cli": "^7.28.3",
52
+ "@babel/core": "^7.28.4",
52
53
  "@babel/node": "^7.28.0",
53
- "@babel/plugin-transform-runtime": "^7.28.0",
54
- "@babel/preset-env": "^7.28.0",
54
+ "@babel/plugin-transform-runtime": "^7.28.3",
55
+ "@babel/preset-env": "^7.28.3",
55
56
  "@babel/preset-react": "^7.27.1",
56
57
  "@babel/preset-typescript": "^7.27.1",
57
- "@dr.pogodin/eslint-configs": "^0.0.11",
58
+ "@dr.pogodin/eslint-configs": "^0.1.0",
58
59
  "@testing-library/dom": "^10.4.1",
59
60
  "@testing-library/react": "^16.3.0",
60
61
  "@tsconfig/recommended": "^1.0.10",
61
62
  "@types/jest": "^30.0.0",
62
63
  "@types/pretty": "^2.0.3",
63
- "@types/react": "^19.1.9",
64
- "@types/react-dom": "^19.1.7",
65
- "babel-jest": "^30.0.5",
64
+ "@types/react": "^19.2.2",
65
+ "@types/react-dom": "^19.2.1",
66
+ "babel-jest": "^30.2.0",
66
67
  "babel-plugin-module-resolver": "^5.0.2",
67
- "jest": "^30.0.5",
68
- "jest-environment-jsdom": "^30.0.5",
68
+ "jest": "^30.2.0",
69
+ "jest-environment-jsdom": "^30.2.0",
69
70
  "mockdate": "^3.0.5",
70
71
  "rimraf": "^6.0.1",
71
72
  "tstyche": "^4.3.0",
72
- "typescript": "^5.9.2"
73
+ "typescript": "^5.9.3"
73
74
  },
74
75
  "peerDependencies": {
75
- "react": "^19.1.1",
76
- "react-dom": "^19.1.1"
76
+ "react": "^19.2.0",
77
+ "react-dom": "^19.2.0"
77
78
  }
78
79
  }