@dxos/react-hooks 0.6.10 → 0.6.11-staging.32b42e4

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.
@@ -12,11 +12,36 @@ var useAsyncCallback = (cb) => {
12
12
  return value;
13
13
  };
14
14
 
15
+ // packages/ui/primitives/react-hooks/src/useAsyncEffect.ts
16
+ import { useEffect as useEffect2 } from "react";
17
+ import { log } from "@dxos/log";
18
+ var useAsyncEffect = (callback, destructor, deps) => {
19
+ const [effectDestructor, effectDeps] = typeof destructor === "function" ? [
20
+ destructor,
21
+ deps
22
+ ] : [
23
+ void 0,
24
+ destructor
25
+ ];
26
+ useEffect2(() => {
27
+ let mounted = true;
28
+ let value;
29
+ const asyncResult = callback(() => mounted);
30
+ void Promise.resolve(asyncResult).then((result) => {
31
+ value = result;
32
+ }).catch(log.catch);
33
+ return () => {
34
+ mounted = false;
35
+ effectDestructor?.(value);
36
+ };
37
+ }, effectDeps);
38
+ };
39
+
15
40
  // packages/ui/primitives/react-hooks/src/useControlledValue.ts
16
- import { useEffect as useEffect2, useState as useState2 } from "react";
41
+ import { useEffect as useEffect3, useState as useState2 } from "react";
17
42
  var useControlledValue = (controlledValue) => {
18
43
  const [value, setValue] = useState2(controlledValue);
19
- useEffect2(() => {
44
+ useEffect3(() => {
20
45
  if (controlledValue !== void 0) {
21
46
  setValue(controlledValue);
22
47
  }
@@ -29,12 +54,34 @@ var useControlledValue = (controlledValue) => {
29
54
  ];
30
55
  };
31
56
 
57
+ // packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts
58
+ import { useEffect as useEffect4, useRef } from "react";
59
+ var useDebugReactDeps = (deps = []) => {
60
+ const lastDeps = useRef([]);
61
+ useEffect4(() => {
62
+ console.group("deps changed", {
63
+ old: lastDeps.current.length,
64
+ new: deps.length
65
+ });
66
+ for (let i = 0; i < Math.max(lastDeps.current.length ?? 0, deps.length ?? 0); i++) {
67
+ console.log(i, lastDeps.current[i] === deps[i] ? "SAME" : "CHANGED", {
68
+ previous: lastDeps.current[i],
69
+ current: deps[i]
70
+ });
71
+ }
72
+ console.groupEnd();
73
+ lastDeps.current = deps;
74
+ }, deps);
75
+ };
76
+
32
77
  // packages/ui/primitives/react-hooks/src/useDefaultValue.ts
33
- import { useEffect as useEffect3, useState as useState3, useMemo } from "react";
78
+ import { useEffect as useEffect5, useState as useState3, useMemo } from "react";
34
79
  var useDefaultValue = (reactiveValue, defaultValue) => {
35
80
  const stableDefaultValue = useMemo(() => defaultValue, []);
36
81
  const [value, setValue] = useState3(reactiveValue ?? stableDefaultValue);
37
- useEffect3(() => setValue(reactiveValue ?? stableDefaultValue), [
82
+ useEffect5(() => {
83
+ setValue(reactiveValue ?? stableDefaultValue);
84
+ }, [
38
85
  reactiveValue,
39
86
  stableDefaultValue
40
87
  ]);
@@ -42,10 +89,10 @@ var useDefaultValue = (reactiveValue, defaultValue) => {
42
89
  };
43
90
 
44
91
  // packages/ui/primitives/react-hooks/src/useDynamicRef.ts
45
- import { useEffect as useEffect4, useRef } from "react";
92
+ import { useEffect as useEffect6, useRef as useRef2 } from "react";
46
93
  var useDynamicRef = (value) => {
47
- const ref = useRef(value);
48
- useEffect4(() => {
94
+ const ref = useRef2(value);
95
+ useEffect6(() => {
49
96
  ref.current = value;
50
97
  }, [
51
98
  value
@@ -67,10 +114,10 @@ var useFileDownload = () => {
67
114
  };
68
115
 
69
116
  // packages/ui/primitives/react-hooks/src/useForwardedRef.ts
70
- import { useRef as useRef2, useEffect as useEffect5 } from "react";
117
+ import { useRef as useRef3, useEffect as useEffect7 } from "react";
71
118
  var useForwardedRef = (ref) => {
72
- const innerRef = useRef2(null);
73
- useEffect5(() => {
119
+ const innerRef = useRef3(null);
120
+ useEffect7(() => {
74
121
  if (!ref) {
75
122
  return;
76
123
  }
@@ -94,12 +141,12 @@ var useId = (namespace, propsId, opts) => useMemo3(() => propsId ?? `${namespace
94
141
  ]);
95
142
 
96
143
  // packages/ui/primitives/react-hooks/src/useIsFocused.ts
97
- import { useEffect as useEffect6, useRef as useRef3, useState as useState4 } from "react";
144
+ import { useEffect as useEffect8, useRef as useRef4, useState as useState4 } from "react";
98
145
  var useIsFocused = (inputRef) => {
99
146
  const [isFocused, setIsFocused] = useState4(void 0);
100
- const isFocusedRef = useRef3(isFocused);
147
+ const isFocusedRef = useRef4(isFocused);
101
148
  isFocusedRef.current = isFocused;
102
- useEffect6(() => {
149
+ useEffect8(() => {
103
150
  const input = inputRef.current;
104
151
  if (!input) {
105
152
  return;
@@ -123,7 +170,7 @@ var useIsFocused = (inputRef) => {
123
170
  };
124
171
 
125
172
  // packages/ui/primitives/react-hooks/src/useMediaQuery.ts
126
- import { useEffect as useEffect7, useState as useState5 } from "react";
173
+ import { useEffect as useEffect9, useState as useState5 } from "react";
127
174
  var breakpointMediaQueries = {
128
175
  sm: "(min-width: 640px)",
129
176
  md: "(min-width: 768px)",
@@ -146,7 +193,7 @@ var useMediaQuery = (query, options = {}) => {
146
193
  matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query2).matches
147
194
  }));
148
195
  });
149
- useEffect7(() => {
196
+ useEffect9(() => {
150
197
  setValue(queries.map((query2) => ({
151
198
  media: query2,
152
199
  matches: document.defaultView?.matchMedia(query2).matches
@@ -187,6 +234,18 @@ var useMediaQuery = (query, options = {}) => {
187
234
  return value.map((item) => !!item.matches);
188
235
  };
189
236
 
237
+ // packages/ui/primitives/react-hooks/src/useMulticastObservable.ts
238
+ import { useMemo as useMemo4, useSyncExternalStore } from "react";
239
+ var useMulticastObservable = (observable) => {
240
+ const subscribeFn = useMemo4(() => (listener) => {
241
+ const subscription = observable.subscribe(listener);
242
+ return () => subscription.unsubscribe();
243
+ }, [
244
+ observable
245
+ ]);
246
+ return useSyncExternalStore(subscribeFn, () => observable.get());
247
+ };
248
+
190
249
  // packages/ui/primitives/react-hooks/src/useRefCallback.ts
191
250
  import { useState as useState6 } from "react";
192
251
  var useRefCallback = () => {
@@ -198,14 +257,14 @@ var useRefCallback = () => {
198
257
  };
199
258
 
200
259
  // packages/ui/primitives/react-hooks/src/useTransitions.ts
201
- import { useRef as useRef4, useEffect as useEffect8, useState as useState7 } from "react";
260
+ import { useRef as useRef5, useEffect as useEffect10, useState as useState7 } from "react";
202
261
  var isFunction = (functionToCheck) => {
203
262
  return functionToCheck instanceof Function;
204
263
  };
205
264
  var useDidTransition = (currentValue, fromValue, toValue) => {
206
265
  const [hasTransitioned, setHasTransitioned] = useState7(false);
207
- const previousValue = useRef4(currentValue);
208
- useEffect8(() => {
266
+ const previousValue = useRef5(currentValue);
267
+ useEffect10(() => {
209
268
  const toValueValid = isFunction(toValue) ? toValue(currentValue) : toValue === currentValue;
210
269
  const fromValueValid = isFunction(fromValue) ? fromValue(previousValue.current) : fromValue === previousValue.current;
211
270
  const transitioned = fromValueValid && toValueValid;
@@ -225,15 +284,15 @@ var useDidTransition = (currentValue, fromValue, toValue) => {
225
284
  return hasTransitioned;
226
285
  };
227
286
  var useOnTransition = (currentValue, fromValue, toValue, callback) => {
228
- const dirty = useRef4(false);
287
+ const dirty = useRef5(false);
229
288
  const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);
230
- useEffect8(() => {
289
+ useEffect10(() => {
231
290
  dirty.current = false;
232
291
  }, [
233
292
  currentValue,
234
293
  dirty
235
294
  ]);
236
- useEffect8(() => {
295
+ useEffect10(() => {
237
296
  if (hasTransitioned && !dirty.current) {
238
297
  callback();
239
298
  dirty.current = true;
@@ -247,7 +306,9 @@ var useOnTransition = (currentValue, fromValue, toValue, callback) => {
247
306
  export {
248
307
  randomString,
249
308
  useAsyncCallback,
309
+ useAsyncEffect,
250
310
  useControlledValue,
311
+ useDebugReactDeps,
251
312
  useDefaultValue,
252
313
  useDidTransition,
253
314
  useDynamicRef,
@@ -256,6 +317,7 @@ export {
256
317
  useId,
257
318
  useIsFocused,
258
319
  useMediaQuery,
320
+ useMulticastObservable,
259
321
  useOnTransition,
260
322
  useRefCallback
261
323
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/useAsyncCallback.ts", "../../../src/useControlledValue.ts", "../../../src/useDefaultValue.ts", "../../../src/useDynamicRef.ts", "../../../src/useFileDownload.ts", "../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts", "../../../src/useRefCallback.ts", "../../../src/useTransitions.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState } from 'react';\n\nexport const useAsyncCallback = <T>(cb: () => Promise<T>): T | undefined => {\n const [value, setValue] = useState<T | undefined>();\n useEffect(() => {\n const t = setTimeout(async () => {\n const data = await cb();\n setValue(data);\n });\n\n return () => clearTimeout(t);\n }, []);\n\n return value;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from 'react';\n\n/**\n * A stateful hook with a controlled value.\n */\nexport const useControlledValue = <TValue>(controlledValue: TValue): [TValue, Dispatch<SetStateAction<TValue>>] => {\n const [value, setValue] = useState<TValue>(controlledValue);\n useEffect(() => {\n if (controlledValue !== undefined) {\n setValue(controlledValue);\n }\n }, [controlledValue]);\n\n return [value, setValue];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState, useMemo } from 'react';\n\n/**\n * A custom React hook that provides a stable default value for a potentially undefined reactive value.\n * The defaultValue is memoized upon component mount and remains unchanged until the component unmounts,\n * ensuring stability across all re-renders, even if the defaultValue prop changes.\n *\n * Note: The defaultValue is not reactive. It retains the same value from the component's mount to unmount.\n *\n * @param reactiveValue - The value that may change over time.\n * @param defaultValue - The initial value used when the reactiveValue is undefined. This value is not reactive.\n * @returns - The reactiveValue if it's defined, otherwise the defaultValue.\n */\nexport const useDefaultValue = <T>(reactiveValue: T | undefined | null, defaultValue: T): T => {\n // Memoize defaultValue with an empty dependency array.\n // This ensures that the defaultValue instance remains stable across all re-renders,\n // regardless of whether the defaultValue changes.\n const stableDefaultValue = useMemo(() => defaultValue, []);\n const [value, setValue] = useState(reactiveValue ?? stableDefaultValue);\n\n useEffect(() => setValue(reactiveValue ?? stableDefaultValue), [reactiveValue, stableDefaultValue]);\n\n return value;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useRef } from 'react';\n\nexport const useDynamicRef = <T>(value: T) => {\n const ref = useRef<T>(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\n/**\n * File download anchor.\n *\n * ```\n * const download = useDownload();\n * const handleDownload = (data: string) => {\n * download(new Blob([data], { type: 'text/plain' }), 'test.txt');\n * };\n * ```\n */\nexport const useFileDownload = (): ((data: Blob | string, filename: string) => void) => {\n return useMemo(\n () => (data: Blob | string, filename: string) => {\n const url = typeof data === 'string' ? data : URL.createObjectURL(data);\n const element = document.createElement('a');\n element.setAttribute('href', url);\n element.setAttribute('download', filename);\n element.setAttribute('target', 'download');\n element.click();\n },\n [],\n );\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type ForwardedRef, useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\n// TODO(burdon): Replace with PublicKey.random().\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, type RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type RefCallback, useState } from 'react';\n\n/**\n * Custom React Hook that creates a ref callback and a state variable.\n * The ref callback sets the state variable when the ref changes.\n *\n * @returns An object containing the ref callback and the current value of the ref.\n */\nexport const useRefCallback = <T = any>(): { refCallback: RefCallback<T>; value: T | null } => {\n const [value, setValue] = useState<T | null>(null);\n return { refCallback: (value: T) => setValue(value), value };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useRef, useEffect, useState } from 'react';\n\nconst isFunction = <T>(functionToCheck: any): functionToCheck is (value: T) => boolean => {\n return functionToCheck instanceof Function;\n};\n\n/**\n * This is an internal custom hook that checks if a value has transitioned from a specified 'from' value to a 'to' value.\n *\n * @param currentValue - The value that is being monitored for transitions.\n * @param fromValue - The *from* value or a predicate function that determines the start of the transition.\n * @param toValue - The *to* value or a predicate function that determines the end of the transition.\n * @returns A boolean indicating whether the transition from *fromValue* to *toValue* has occurred.\n *\n * @internal Consider using `useOnTransition` for handling transitions instead of this hook.\n */\nexport const useDidTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: T | ((value: T) => boolean),\n) => {\n const [hasTransitioned, setHasTransitioned] = useState(false);\n const previousValue = useRef<T>(currentValue);\n\n useEffect(() => {\n const toValueValid = isFunction<T>(toValue) ? toValue(currentValue) : toValue === currentValue;\n\n const fromValueValid = isFunction<T>(fromValue)\n ? fromValue(previousValue.current)\n : fromValue === previousValue.current;\n\n const transitioned = fromValueValid && toValueValid;\n\n if (transitioned) {\n setHasTransitioned(true);\n } else {\n setHasTransitioned(false);\n }\n\n previousValue.current = currentValue;\n }, [currentValue, fromValue, toValue, setHasTransitioned, previousValue]);\n\n return hasTransitioned;\n};\n\n/**\n * Executes a callback function when a specified transition occurs in a value.\n *\n * This function utilizes the `useDidTransition` hook to monitor changes in `currentValue`.\n * When `currentValue` transitions from `fromValue` to `toValue`, the provided `callback` function is executed. */\nexport const useOnTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: ((value: T) => boolean) | T,\n callback: () => void,\n) => {\n const dirty = useRef(false);\n const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);\n\n useEffect(() => {\n dirty.current = false;\n }, [currentValue, dirty]);\n\n useEffect(() => {\n if (hasTransitioned && !dirty.current) {\n callback();\n dirty.current = true;\n }\n }, [hasTransitioned, dirty, callback]);\n};\n"],
5
- "mappings": ";AAIA,SAASA,WAAWC,gBAAgB;AAE7B,IAAMC,mBAAmB,CAAIC,OAAAA;AAClC,QAAM,CAACC,OAAOC,QAAAA,IAAYC,SAAAA;AAC1BC,YAAU,MAAA;AACR,UAAMC,IAAIC,WAAW,YAAA;AACnB,YAAMC,OAAO,MAAMP,GAAAA;AACnBE,eAASK,IAAAA;IACX,CAAA;AAEA,WAAO,MAAMC,aAAaH,CAAAA;EAC5B,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IG,cAAc;AAChBR,yBAAmB,IAAA;IACrB,OAAO;AACLA,yBAAmB,KAAA;IACrB;AAEAE,kBAAcK,UAAUX;EAC1B,GAAG;IAACA;IAAcC;IAAWC;IAASE;IAAoBE;GAAc;AAExE,SAAOH;AACT;AAOO,IAAMU,kBAAkB,CAC7Bb,cACAC,WACAC,SACAY,aAAAA;AAEA,QAAMC,QAAQR,QAAO,KAAA;AACrB,QAAMJ,kBAAkBJ,iBAAiBC,cAAcC,WAAWC,OAAAA;AAElEM,EAAAA,WAAU,MAAA;AACRO,UAAMJ,UAAU;EAClB,GAAG;IAACX;IAAce;GAAM;AAExBP,EAAAA,WAAU,MAAA;AACR,QAAIL,mBAAmB,CAACY,MAAMJ,SAAS;AACrCG,eAAAA;AACAC,YAAMJ,UAAU;IAClB;EACF,GAAG;IAACR;IAAiBY;IAAOD;GAAS;AACvC;",
6
- "names": ["useEffect", "useState", "useAsyncCallback", "cb", "value", "setValue", "useState", "useEffect", "t", "setTimeout", "data", "clearTimeout", "useEffect", "useState", "useControlledValue", "controlledValue", "value", "setValue", "useState", "useEffect", "undefined", "useEffect", "useState", "useMemo", "useDefaultValue", "reactiveValue", "defaultValue", "stableDefaultValue", "useMemo", "value", "setValue", "useState", "useEffect", "useEffect", "useRef", "useDynamicRef", "value", "ref", "useRef", "useEffect", "current", "useMemo", "useFileDownload", "useMemo", "data", "filename", "url", "URL", "createObjectURL", "element", "document", "createElement", "setAttribute", "click", "useRef", "useEffect", "useForwardedRef", "ref", "innerRef", "useRef", "useEffect", "current", "alea", "useMemo", "Alea", "alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useMemo", "useEffect", "useRef", "useState", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "useState", "undefined", "isFocusedRef", "useRef", "current", "useEffect", "input", "onFocus", "onBlur", "addEventListener", "document", "activeElement", "removeEventListener", "useEffect", "useState", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "value", "setValue", "useState", "index", "media", "matches", "document", "defaultView", "matchMedia", "useEffect", "mql", "handler", "evt", "prev", "slice", "item", "forEach", "addListener", "addEventListener", "removeListener", "removeEventListener", "useState", "useRefCallback", "value", "setValue", "useState", "refCallback", "useRef", "useEffect", "useState", "isFunction", "functionToCheck", "Function", "useDidTransition", "currentValue", "fromValue", "toValue", "hasTransitioned", "setHasTransitioned", "useState", "previousValue", "useRef", "useEffect", "toValueValid", "fromValueValid", "current", "transitioned", "useOnTransition", "callback", "dirty"]
3
+ "sources": ["../../../src/useAsyncCallback.ts", "../../../src/useAsyncEffect.ts", "../../../src/useControlledValue.ts", "../../../src/useDebugReactDeps.ts", "../../../src/useDefaultValue.ts", "../../../src/useDynamicRef.ts", "../../../src/useFileDownload.ts", "../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts", "../../../src/useMulticastObservable.ts", "../../../src/useRefCallback.ts", "../../../src/useTransitions.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState } from 'react';\n\n/**\n * NOTE: Use with care and when necessary to be able to cancel an async operation when unmounting.\n */\nexport const useAsyncCallback = <T>(cb: () => Promise<T>): T | undefined => {\n const [value, setValue] = useState<T | undefined>();\n useEffect(() => {\n const t = setTimeout(async () => {\n const data = await cb();\n setValue(data);\n });\n\n return () => clearTimeout(t);\n }, []);\n\n return value;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { useEffect } from 'react';\n\nimport { log } from '@dxos/log';\n\n/**\n * Process async event with optional non-async destructor.\n * Inspired by: https://github.com/rauldeheer/use-async-effect/blob/master/index.js\n *\n * ```tsx\n * useAsyncEffect(async () => {\n * await test();\n * }, []);\n * ```\n *\n * The callback may check of the component is still mounted before doing state updates.\n *\n * ```tsx\n * const [value, setValue] = useState<string>();\n * useAsyncEffect<string>(async (isMounted) => {\n * const value = await test();\n * if (!isMounted()) {\n * setValue(value);\n * }\n * }, () => console.log('Unmounted'), []);\n * ```\n *\n * @param callback Receives a getter function that determines if the component is still mounted.\n * @param destructor Receives the value returned from the callback.\n * @param deps\n *\n * NOTE: This effect does not cancel the async operation if the component is unmounted.\n */\nexport const useAsyncEffect = <T>(\n callback: (isMounted: () => boolean) => Promise<T> | undefined,\n destructor?: ((value?: T) => void) | any[],\n deps?: any[],\n) => {\n const [effectDestructor, effectDeps] =\n typeof destructor === 'function' ? [destructor, deps] : [undefined, destructor];\n\n useEffect(() => {\n let mounted = true;\n let value: T | undefined;\n const asyncResult = callback(() => mounted);\n\n void Promise.resolve(asyncResult)\n .then((result) => {\n value = result;\n })\n .catch(log.catch);\n\n return () => {\n mounted = false;\n effectDestructor?.(value);\n };\n }, effectDeps);\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from 'react';\n\n/**\n * A stateful hook with a controlled value.\n */\nexport const useControlledValue = <TValue>(controlledValue: TValue): [TValue, Dispatch<SetStateAction<TValue>>] => {\n const [value, setValue] = useState<TValue>(controlledValue);\n useEffect(() => {\n if (controlledValue !== undefined) {\n setValue(controlledValue);\n }\n }, [controlledValue]);\n\n return [value, setValue];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/* eslint-disable no-console */\n\nimport { type DependencyList, useEffect, useRef } from 'react';\n\n/**\n * Util to log deps that have changed.\n */\n// TODO(burdon): Move to react-hooks.\nexport const useDebugReactDeps = (deps: DependencyList = []) => {\n const lastDeps = useRef<DependencyList>([]);\n useEffect(() => {\n console.group('deps changed', { old: lastDeps.current.length, new: deps.length });\n for (let i = 0; i < Math.max(lastDeps.current.length ?? 0, deps.length ?? 0); i++) {\n console.log(i, lastDeps.current[i] === deps[i] ? 'SAME' : 'CHANGED', {\n previous: lastDeps.current[i],\n current: deps[i],\n });\n }\n\n console.groupEnd();\n lastDeps.current = deps;\n }, deps);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState, useMemo } from 'react';\n\n/**\n * A custom React hook that provides a stable default value for a potentially undefined reactive value.\n * The defaultValue is memoized upon component mount and remains unchanged until the component unmounts,\n * ensuring stability across all re-renders, even if the defaultValue prop changes.\n *\n * Note: The defaultValue is not reactive. It retains the same value from the component's mount to unmount.\n *\n * @param reactiveValue - The value that may change over time.\n * @param defaultValue - The initial value used when the reactiveValue is undefined. This value is not reactive.\n * @returns - The reactiveValue if it's defined, otherwise the defaultValue.\n */\nexport const useDefaultValue = <T>(reactiveValue: T | undefined | null, defaultValue: T): T => {\n // Memoize defaultValue with an empty dependency array.\n // This ensures that the defaultValue instance remains stable across all re-renders,\n // regardless of whether the defaultValue changes.\n const stableDefaultValue = useMemo(() => defaultValue, []);\n const [value, setValue] = useState(reactiveValue ?? stableDefaultValue);\n\n useEffect(() => {\n setValue(reactiveValue ?? stableDefaultValue);\n }, [reactiveValue, stableDefaultValue]);\n\n return value;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useRef } from 'react';\n\nexport const useDynamicRef = <T>(value: T) => {\n const ref = useRef<T>(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\n/**\n * File download anchor.\n *\n * ```\n * const download = useDownload();\n * const handleDownload = (data: string) => {\n * download(new Blob([data], { type: 'text/plain' }), 'test.txt');\n * };\n * ```\n */\nexport const useFileDownload = (): ((data: Blob | string, filename: string) => void) => {\n return useMemo(\n () => (data: Blob | string, filename: string) => {\n const url = typeof data === 'string' ? data : URL.createObjectURL(data);\n const element = document.createElement('a');\n element.setAttribute('href', url);\n element.setAttribute('download', filename);\n element.setAttribute('target', 'download');\n element.click();\n },\n [],\n );\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type ForwardedRef, useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\n// TODO(burdon): Replace with PublicKey.random().\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, type RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { type MulticastObservable } from '@dxos/async';\n\n/**\n * Subscribe to a MulticastObservable and return the latest value.\n * @param observable the observable to subscribe to. Will resubscribe if the observable changes.\n */\n// TODO(burdon): Move to react-hooks.\nexport const useMulticastObservable = <T>(observable: MulticastObservable<T>): T => {\n // Make sure useSyncExternalStore is stable in respect to the observable.\n const subscribeFn = useMemo(\n () => (listener: () => void) => {\n const subscription = observable.subscribe(listener);\n return () => subscription.unsubscribe();\n },\n [observable],\n );\n\n // useSyncExternalStore will resubscribe to the observable and update the value if the subscribeFn changes.\n return useSyncExternalStore(subscribeFn, () => observable.get());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type RefCallback, useState } from 'react';\n\n/**\n * Custom React Hook that creates a ref callback and a state variable.\n * The ref callback sets the state variable when the ref changes.\n *\n * @returns An object containing the ref callback and the current value of the ref.\n */\nexport const useRefCallback = <T = any>(): { refCallback: RefCallback<T>; value: T | null } => {\n const [value, setValue] = useState<T | null>(null);\n return { refCallback: (value: T) => setValue(value), value };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useRef, useEffect, useState } from 'react';\n\nconst isFunction = <T>(functionToCheck: any): functionToCheck is (value: T) => boolean => {\n return functionToCheck instanceof Function;\n};\n\n/**\n * This is an internal custom hook that checks if a value has transitioned from a specified 'from' value to a 'to' value.\n *\n * @param currentValue - The value that is being monitored for transitions.\n * @param fromValue - The *from* value or a predicate function that determines the start of the transition.\n * @param toValue - The *to* value or a predicate function that determines the end of the transition.\n * @returns A boolean indicating whether the transition from *fromValue* to *toValue* has occurred.\n *\n * @internal Consider using `useOnTransition` for handling transitions instead of this hook.\n */\nexport const useDidTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: T | ((value: T) => boolean),\n) => {\n const [hasTransitioned, setHasTransitioned] = useState(false);\n const previousValue = useRef<T>(currentValue);\n\n useEffect(() => {\n const toValueValid = isFunction<T>(toValue) ? toValue(currentValue) : toValue === currentValue;\n\n const fromValueValid = isFunction<T>(fromValue)\n ? fromValue(previousValue.current)\n : fromValue === previousValue.current;\n\n const transitioned = fromValueValid && toValueValid;\n\n if (transitioned) {\n setHasTransitioned(true);\n } else {\n setHasTransitioned(false);\n }\n\n previousValue.current = currentValue;\n }, [currentValue, fromValue, toValue, setHasTransitioned, previousValue]);\n\n return hasTransitioned;\n};\n\n/**\n * Executes a callback function when a specified transition occurs in a value.\n *\n * This function utilizes the `useDidTransition` hook to monitor changes in `currentValue`.\n * When `currentValue` transitions from `fromValue` to `toValue`, the provided `callback` function is executed. */\nexport const useOnTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: ((value: T) => boolean) | T,\n callback: () => void,\n) => {\n const dirty = useRef(false);\n const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);\n\n useEffect(() => {\n dirty.current = false;\n }, [currentValue, dirty]);\n\n useEffect(() => {\n if (hasTransitioned && !dirty.current) {\n callback();\n dirty.current = true;\n }\n }, [hasTransitioned, dirty, callback]);\n};\n"],
5
+ "mappings": ";AAIA,SAASA,WAAWC,gBAAgB;AAK7B,IAAMC,mBAAmB,CAAIC,OAAAA;AAClC,QAAM,CAACC,OAAOC,QAAAA,IAAYC,SAAAA;AAC1BC,YAAU,MAAA;AACR,UAAMC,IAAIC,WAAW,YAAA;AACnB,YAAMC,OAAO,MAAMP,GAAAA;AACnBE,eAASK,IAAAA;IACX,CAAA;AAEA,WAAO,MAAMC,aAAaH,CAAAA;EAC5B,GAAG,CAAA,CAAE;AAEL,SAAOJ;AACT;;;ACjBA,SAASQ,aAAAA,kBAAiB;AAE1B,SAASC,WAAW;AA8Bb,IAAMC,iBAAiB,CAC5BC,UACAC,YACAC,SAAAA;AAEA,QAAM,CAACC,kBAAkBC,UAAAA,IACvB,OAAOH,eAAe,aAAa;IAACA;IAAYC;MAAQ;IAACG;IAAWJ;;AAEtEK,EAAAA,WAAU,MAAA;AACR,QAAIC,UAAU;AACd,QAAIC;AACJ,UAAMC,cAAcT,SAAS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;AAOO,IAAMU,kBAAkB,CAC7Bb,cACAC,WACAC,SACAY,aAAAA;AAEA,QAAMC,QAAQR,QAAO,KAAA;AACrB,QAAMJ,kBAAkBJ,iBAAiBC,cAAcC,WAAWC,OAAAA;AAElEM,EAAAA,YAAU,MAAA;AACRO,UAAMJ,UAAU;EAClB,GAAG;IAACX;IAAce;GAAM;AAExBP,EAAAA,YAAU,MAAA;AACR,QAAIL,mBAAmB,CAACY,MAAMJ,SAAS;AACrCG,eAAAA;AACAC,YAAMJ,UAAU;IAClB;EACF,GAAG;IAACR;IAAiBY;IAAOD;GAAS;AACvC;",
6
+ "names": ["useEffect", "useState", "useAsyncCallback", "cb", "value", "setValue", "useState", "useEffect", "t", "setTimeout", "data", "clearTimeout", "useEffect", "log", "useAsyncEffect", "callback", "destructor", "deps", "effectDestructor", "effectDeps", "undefined", "useEffect", "mounted", "value", "asyncResult", "Promise", "resolve", "then", "result", "catch", "log", "useEffect", "useState", "useControlledValue", "controlledValue", "value", "setValue", "useState", "useEffect", "undefined", "useEffect", "useRef", "useDebugReactDeps", "deps", "lastDeps", "useRef", "useEffect", "console", "group", "old", "current", "length", "new", "i", "Math", "max", "log", "previous", "groupEnd", "useEffect", "useState", "useMemo", "useDefaultValue", "reactiveValue", "defaultValue", "stableDefaultValue", "useMemo", "value", "setValue", "useState", "useEffect", "useEffect", "useRef", "useDynamicRef", "value", "ref", "useRef", "useEffect", "current", "useMemo", "useFileDownload", "useMemo", "data", "filename", "url", "URL", "createObjectURL", "element", "document", "createElement", "setAttribute", "click", "useRef", "useEffect", "useForwardedRef", "ref", "innerRef", "useRef", "useEffect", "current", "alea", "useMemo", "Alea", "alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useMemo", "useEffect", "useRef", "useState", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "useState", "undefined", "isFocusedRef", "useRef", "current", "useEffect", "input", "onFocus", "onBlur", "addEventListener", "document", "activeElement", "removeEventListener", "useEffect", "useState", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "value", "setValue", "useState", "index", "media", "matches", "document", "defaultView", "matchMedia", "useEffect", "mql", "handler", "evt", "prev", "slice", "item", "forEach", "addListener", "addEventListener", "removeListener", "removeEventListener", "useMemo", "useSyncExternalStore", "useMulticastObservable", "observable", "subscribeFn", "useMemo", "listener", "subscription", "subscribe", "unsubscribe", "useSyncExternalStore", "get", "useState", "useRefCallback", "value", "setValue", "useState", "refCallback", "useRef", "useEffect", "useState", "isFunction", "functionToCheck", "Function", "useDidTransition", "currentValue", "fromValue", "toValue", "hasTransitioned", "setHasTransitioned", "useState", "previousValue", "useRef", "useEffect", "toValueValid", "fromValueValid", "current", "transitioned", "useOnTransition", "callback", "dirty"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytes":1751,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytes":1974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytes":4059,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytes":1247,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytes":2740,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1783,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":2163,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3990,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9390,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytes":1879,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytes":7797,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":1572,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts","kind":"import-statement","original":"./useAsyncCallback"},{"path":"packages/ui/primitives/react-hooks/src/useControlledValue.ts","kind":"import-statement","original":"./useControlledValue"},{"path":"packages/ui/primitives/react-hooks/src/useDefaultValue.ts","kind":"import-statement","original":"./useDefaultValue"},{"path":"packages/ui/primitives/react-hooks/src/useDynamicRef.ts","kind":"import-statement","original":"./useDynamicRef"},{"path":"packages/ui/primitives/react-hooks/src/useFileDownload.ts","kind":"import-statement","original":"./useFileDownload"},{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"},{"path":"packages/ui/primitives/react-hooks/src/useRefCallback.ts","kind":"import-statement","original":"./useRefCallback"},{"path":"packages/ui/primitives/react-hooks/src/useTransitions.ts","kind":"import-statement","original":"./useTransitions"}],"format":"esm"}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":18788},"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs":{"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["randomString","useAsyncCallback","useControlledValue","useDefaultValue","useDidTransition","useDynamicRef","useFileDownload","useForwardedRef","useId","useIsFocused","useMediaQuery","useOnTransition","useRefCallback"],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytesInOutput":301},"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":0},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytesInOutput":350},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytesInOutput":411},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytesInOutput":205},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytesInOutput":416},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":343},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":326},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":833},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":1940},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytesInOutput":197},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytesInOutput":1384}},"bytes":7649}}}
1
+ {"inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytes":2022,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts":{"bytes":5018,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytes":1974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts":{"bytes":3192,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytes":4104,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytes":1251,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytes":2740,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1783,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":2163,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3990,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9390,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts":{"bytes":3033,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytes":1879,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytes":7797,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":1913,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts","kind":"import-statement","original":"./useAsyncCallback"},{"path":"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts","kind":"import-statement","original":"./useAsyncEffect"},{"path":"packages/ui/primitives/react-hooks/src/useControlledValue.ts","kind":"import-statement","original":"./useControlledValue"},{"path":"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts","kind":"import-statement","original":"./useDebugReactDeps"},{"path":"packages/ui/primitives/react-hooks/src/useDefaultValue.ts","kind":"import-statement","original":"./useDefaultValue"},{"path":"packages/ui/primitives/react-hooks/src/useDynamicRef.ts","kind":"import-statement","original":"./useDynamicRef"},{"path":"packages/ui/primitives/react-hooks/src/useFileDownload.ts","kind":"import-statement","original":"./useFileDownload"},{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"},{"path":"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts","kind":"import-statement","original":"./useMulticastObservable"},{"path":"packages/ui/primitives/react-hooks/src/useRefCallback.ts","kind":"import-statement","original":"./useRefCallback"},{"path":"packages/ui/primitives/react-hooks/src/useTransitions.ts","kind":"import-statement","original":"./useTransitions"}],"format":"esm"}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":24207},"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs":{"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["randomString","useAsyncCallback","useAsyncEffect","useControlledValue","useDebugReactDeps","useDefaultValue","useDidTransition","useDynamicRef","useFileDownload","useForwardedRef","useId","useIsFocused","useMediaQuery","useMulticastObservable","useOnTransition","useRefCallback"],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytesInOutput":301},"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":0},"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts":{"bytesInOutput":596},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytesInOutput":350},"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts":{"bytesInOutput":567},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytesInOutput":422},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytesInOutput":217},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytesInOutput":416},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":343},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":326},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":833},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":1940},"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts":{"bytesInOutput":368},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytesInOutput":197},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytesInOutput":1388}},"bytes":9466}}}
@@ -30,7 +30,9 @@ var node_exports = {};
30
30
  __export(node_exports, {
31
31
  randomString: () => randomString,
32
32
  useAsyncCallback: () => useAsyncCallback,
33
+ useAsyncEffect: () => useAsyncEffect,
33
34
  useControlledValue: () => useControlledValue,
35
+ useDebugReactDeps: () => useDebugReactDeps,
34
36
  useDefaultValue: () => useDefaultValue,
35
37
  useDidTransition: () => useDidTransition,
36
38
  useDynamicRef: () => useDynamicRef,
@@ -39,22 +41,27 @@ __export(node_exports, {
39
41
  useId: () => useId,
40
42
  useIsFocused: () => useIsFocused,
41
43
  useMediaQuery: () => useMediaQuery,
44
+ useMulticastObservable: () => useMulticastObservable,
42
45
  useOnTransition: () => useOnTransition,
43
46
  useRefCallback: () => useRefCallback
44
47
  });
45
48
  module.exports = __toCommonJS(node_exports);
46
49
  var import_react = require("react");
47
50
  var import_react2 = require("react");
51
+ var import_log = require("@dxos/log");
48
52
  var import_react3 = require("react");
49
53
  var import_react4 = require("react");
50
54
  var import_react5 = require("react");
51
55
  var import_react6 = require("react");
52
- var import_alea = __toESM(require("alea"));
53
56
  var import_react7 = require("react");
54
57
  var import_react8 = require("react");
58
+ var import_alea = __toESM(require("alea"));
55
59
  var import_react9 = require("react");
56
60
  var import_react10 = require("react");
57
61
  var import_react11 = require("react");
62
+ var import_react12 = require("react");
63
+ var import_react13 = require("react");
64
+ var import_react14 = require("react");
58
65
  var useAsyncCallback = (cb) => {
59
66
  const [value, setValue] = (0, import_react.useState)();
60
67
  (0, import_react.useEffect)(() => {
@@ -66,9 +73,30 @@ var useAsyncCallback = (cb) => {
66
73
  }, []);
67
74
  return value;
68
75
  };
69
- var useControlledValue = (controlledValue) => {
70
- const [value, setValue] = (0, import_react2.useState)(controlledValue);
76
+ var useAsyncEffect = (callback, destructor, deps) => {
77
+ const [effectDestructor, effectDeps] = typeof destructor === "function" ? [
78
+ destructor,
79
+ deps
80
+ ] : [
81
+ void 0,
82
+ destructor
83
+ ];
71
84
  (0, import_react2.useEffect)(() => {
85
+ let mounted = true;
86
+ let value;
87
+ const asyncResult = callback(() => mounted);
88
+ void Promise.resolve(asyncResult).then((result) => {
89
+ value = result;
90
+ }).catch(import_log.log.catch);
91
+ return () => {
92
+ mounted = false;
93
+ effectDestructor?.(value);
94
+ };
95
+ }, effectDeps);
96
+ };
97
+ var useControlledValue = (controlledValue) => {
98
+ const [value, setValue] = (0, import_react3.useState)(controlledValue);
99
+ (0, import_react3.useEffect)(() => {
72
100
  if (controlledValue !== void 0) {
73
101
  setValue(controlledValue);
74
102
  }
@@ -80,18 +108,37 @@ var useControlledValue = (controlledValue) => {
80
108
  setValue
81
109
  ];
82
110
  };
111
+ var useDebugReactDeps = (deps = []) => {
112
+ const lastDeps = (0, import_react4.useRef)([]);
113
+ (0, import_react4.useEffect)(() => {
114
+ console.group("deps changed", {
115
+ old: lastDeps.current.length,
116
+ new: deps.length
117
+ });
118
+ for (let i = 0; i < Math.max(lastDeps.current.length ?? 0, deps.length ?? 0); i++) {
119
+ console.log(i, lastDeps.current[i] === deps[i] ? "SAME" : "CHANGED", {
120
+ previous: lastDeps.current[i],
121
+ current: deps[i]
122
+ });
123
+ }
124
+ console.groupEnd();
125
+ lastDeps.current = deps;
126
+ }, deps);
127
+ };
83
128
  var useDefaultValue = (reactiveValue, defaultValue) => {
84
- const stableDefaultValue = (0, import_react3.useMemo)(() => defaultValue, []);
85
- const [value, setValue] = (0, import_react3.useState)(reactiveValue ?? stableDefaultValue);
86
- (0, import_react3.useEffect)(() => setValue(reactiveValue ?? stableDefaultValue), [
129
+ const stableDefaultValue = (0, import_react5.useMemo)(() => defaultValue, []);
130
+ const [value, setValue] = (0, import_react5.useState)(reactiveValue ?? stableDefaultValue);
131
+ (0, import_react5.useEffect)(() => {
132
+ setValue(reactiveValue ?? stableDefaultValue);
133
+ }, [
87
134
  reactiveValue,
88
135
  stableDefaultValue
89
136
  ]);
90
137
  return value;
91
138
  };
92
139
  var useDynamicRef = (value) => {
93
- const ref = (0, import_react4.useRef)(value);
94
- (0, import_react4.useEffect)(() => {
140
+ const ref = (0, import_react6.useRef)(value);
141
+ (0, import_react6.useEffect)(() => {
95
142
  ref.current = value;
96
143
  }, [
97
144
  value
@@ -99,7 +146,7 @@ var useDynamicRef = (value) => {
99
146
  return ref;
100
147
  };
101
148
  var useFileDownload = () => {
102
- return (0, import_react5.useMemo)(() => (data, filename) => {
149
+ return (0, import_react7.useMemo)(() => (data, filename) => {
103
150
  const url = typeof data === "string" ? data : URL.createObjectURL(data);
104
151
  const element = document.createElement("a");
105
152
  element.setAttribute("href", url);
@@ -109,8 +156,8 @@ var useFileDownload = () => {
109
156
  }, []);
110
157
  };
111
158
  var useForwardedRef = (ref) => {
112
- const innerRef = (0, import_react6.useRef)(null);
113
- (0, import_react6.useEffect)(() => {
159
+ const innerRef = (0, import_react8.useRef)(null);
160
+ (0, import_react8.useEffect)(() => {
114
161
  if (!ref) {
115
162
  return;
116
163
  }
@@ -125,14 +172,14 @@ var useForwardedRef = (ref) => {
125
172
  var Alea = import_alea.default;
126
173
  var prng = new Alea("@dxos/react-hooks");
127
174
  var randomString = (n = 4) => prng().toString(16).slice(2, n + 2);
128
- var useId = (namespace, propsId, opts) => (0, import_react7.useMemo)(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [
175
+ var useId = (namespace, propsId, opts) => (0, import_react9.useMemo)(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [
129
176
  propsId
130
177
  ]);
131
178
  var useIsFocused = (inputRef) => {
132
- const [isFocused, setIsFocused] = (0, import_react8.useState)(void 0);
133
- const isFocusedRef = (0, import_react8.useRef)(isFocused);
179
+ const [isFocused, setIsFocused] = (0, import_react10.useState)(void 0);
180
+ const isFocusedRef = (0, import_react10.useRef)(isFocused);
134
181
  isFocusedRef.current = isFocused;
135
- (0, import_react8.useEffect)(() => {
182
+ (0, import_react10.useEffect)(() => {
136
183
  const input = inputRef.current;
137
184
  if (!input) {
138
185
  return;
@@ -170,13 +217,13 @@ var useMediaQuery = (query, options = {}) => {
170
217
  fallback
171
218
  ];
172
219
  fallbackValues = fallbackValues.filter((v) => v != null);
173
- const [value, setValue] = (0, import_react9.useState)(() => {
220
+ const [value, setValue] = (0, import_react11.useState)(() => {
174
221
  return queries.map((query2, index) => ({
175
222
  media: query2,
176
223
  matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query2).matches
177
224
  }));
178
225
  });
179
- (0, import_react9.useEffect)(() => {
226
+ (0, import_react11.useEffect)(() => {
180
227
  setValue(queries.map((query2) => ({
181
228
  media: query2,
182
229
  matches: document.defaultView?.matchMedia(query2).matches
@@ -216,8 +263,17 @@ var useMediaQuery = (query, options = {}) => {
216
263
  ]);
217
264
  return value.map((item) => !!item.matches);
218
265
  };
266
+ var useMulticastObservable = (observable) => {
267
+ const subscribeFn = (0, import_react12.useMemo)(() => (listener) => {
268
+ const subscription = observable.subscribe(listener);
269
+ return () => subscription.unsubscribe();
270
+ }, [
271
+ observable
272
+ ]);
273
+ return (0, import_react12.useSyncExternalStore)(subscribeFn, () => observable.get());
274
+ };
219
275
  var useRefCallback = () => {
220
- const [value, setValue] = (0, import_react10.useState)(null);
276
+ const [value, setValue] = (0, import_react13.useState)(null);
221
277
  return {
222
278
  refCallback: (value2) => setValue(value2),
223
279
  value
@@ -227,9 +283,9 @@ var isFunction = (functionToCheck) => {
227
283
  return functionToCheck instanceof Function;
228
284
  };
229
285
  var useDidTransition = (currentValue, fromValue, toValue) => {
230
- const [hasTransitioned, setHasTransitioned] = (0, import_react11.useState)(false);
231
- const previousValue = (0, import_react11.useRef)(currentValue);
232
- (0, import_react11.useEffect)(() => {
286
+ const [hasTransitioned, setHasTransitioned] = (0, import_react14.useState)(false);
287
+ const previousValue = (0, import_react14.useRef)(currentValue);
288
+ (0, import_react14.useEffect)(() => {
233
289
  const toValueValid = isFunction(toValue) ? toValue(currentValue) : toValue === currentValue;
234
290
  const fromValueValid = isFunction(fromValue) ? fromValue(previousValue.current) : fromValue === previousValue.current;
235
291
  const transitioned = fromValueValid && toValueValid;
@@ -249,15 +305,15 @@ var useDidTransition = (currentValue, fromValue, toValue) => {
249
305
  return hasTransitioned;
250
306
  };
251
307
  var useOnTransition = (currentValue, fromValue, toValue, callback) => {
252
- const dirty = (0, import_react11.useRef)(false);
308
+ const dirty = (0, import_react14.useRef)(false);
253
309
  const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);
254
- (0, import_react11.useEffect)(() => {
310
+ (0, import_react14.useEffect)(() => {
255
311
  dirty.current = false;
256
312
  }, [
257
313
  currentValue,
258
314
  dirty
259
315
  ]);
260
- (0, import_react11.useEffect)(() => {
316
+ (0, import_react14.useEffect)(() => {
261
317
  if (hasTransitioned && !dirty.current) {
262
318
  callback();
263
319
  dirty.current = true;
@@ -272,7 +328,9 @@ var useOnTransition = (currentValue, fromValue, toValue, callback) => {
272
328
  0 && (module.exports = {
273
329
  randomString,
274
330
  useAsyncCallback,
331
+ useAsyncEffect,
275
332
  useControlledValue,
333
+ useDebugReactDeps,
276
334
  useDefaultValue,
277
335
  useDidTransition,
278
336
  useDynamicRef,
@@ -281,6 +339,7 @@ var useOnTransition = (currentValue, fromValue, toValue, callback) => {
281
339
  useId,
282
340
  useIsFocused,
283
341
  useMediaQuery,
342
+ useMulticastObservable,
284
343
  useOnTransition,
285
344
  useRefCallback
286
345
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/useAsyncCallback.ts", "../../../src/useControlledValue.ts", "../../../src/useDefaultValue.ts", "../../../src/useDynamicRef.ts", "../../../src/useFileDownload.ts", "../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts", "../../../src/useRefCallback.ts", "../../../src/useTransitions.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState } from 'react';\n\nexport const useAsyncCallback = <T>(cb: () => Promise<T>): T | undefined => {\n const [value, setValue] = useState<T | undefined>();\n useEffect(() => {\n const t = setTimeout(async () => {\n const data = await cb();\n setValue(data);\n });\n\n return () => clearTimeout(t);\n }, []);\n\n return value;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from 'react';\n\n/**\n * A stateful hook with a controlled value.\n */\nexport const useControlledValue = <TValue>(controlledValue: TValue): [TValue, Dispatch<SetStateAction<TValue>>] => {\n const [value, setValue] = useState<TValue>(controlledValue);\n useEffect(() => {\n if (controlledValue !== undefined) {\n setValue(controlledValue);\n }\n }, [controlledValue]);\n\n return [value, setValue];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState, useMemo } from 'react';\n\n/**\n * A custom React hook that provides a stable default value for a potentially undefined reactive value.\n * The defaultValue is memoized upon component mount and remains unchanged until the component unmounts,\n * ensuring stability across all re-renders, even if the defaultValue prop changes.\n *\n * Note: The defaultValue is not reactive. It retains the same value from the component's mount to unmount.\n *\n * @param reactiveValue - The value that may change over time.\n * @param defaultValue - The initial value used when the reactiveValue is undefined. This value is not reactive.\n * @returns - The reactiveValue if it's defined, otherwise the defaultValue.\n */\nexport const useDefaultValue = <T>(reactiveValue: T | undefined | null, defaultValue: T): T => {\n // Memoize defaultValue with an empty dependency array.\n // This ensures that the defaultValue instance remains stable across all re-renders,\n // regardless of whether the defaultValue changes.\n const stableDefaultValue = useMemo(() => defaultValue, []);\n const [value, setValue] = useState(reactiveValue ?? stableDefaultValue);\n\n useEffect(() => setValue(reactiveValue ?? stableDefaultValue), [reactiveValue, stableDefaultValue]);\n\n return value;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useRef } from 'react';\n\nexport const useDynamicRef = <T>(value: T) => {\n const ref = useRef<T>(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\n/**\n * File download anchor.\n *\n * ```\n * const download = useDownload();\n * const handleDownload = (data: string) => {\n * download(new Blob([data], { type: 'text/plain' }), 'test.txt');\n * };\n * ```\n */\nexport const useFileDownload = (): ((data: Blob | string, filename: string) => void) => {\n return useMemo(\n () => (data: Blob | string, filename: string) => {\n const url = typeof data === 'string' ? data : URL.createObjectURL(data);\n const element = document.createElement('a');\n element.setAttribute('href', url);\n element.setAttribute('download', filename);\n element.setAttribute('target', 'download');\n element.click();\n },\n [],\n );\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type ForwardedRef, useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\n// TODO(burdon): Replace with PublicKey.random().\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, type RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type RefCallback, useState } from 'react';\n\n/**\n * Custom React Hook that creates a ref callback and a state variable.\n * The ref callback sets the state variable when the ref changes.\n *\n * @returns An object containing the ref callback and the current value of the ref.\n */\nexport const useRefCallback = <T = any>(): { refCallback: RefCallback<T>; value: T | null } => {\n const [value, setValue] = useState<T | null>(null);\n return { refCallback: (value: T) => setValue(value), value };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useRef, useEffect, useState } from 'react';\n\nconst isFunction = <T>(functionToCheck: any): functionToCheck is (value: T) => boolean => {\n return functionToCheck instanceof Function;\n};\n\n/**\n * This is an internal custom hook that checks if a value has transitioned from a specified 'from' value to a 'to' value.\n *\n * @param currentValue - The value that is being monitored for transitions.\n * @param fromValue - The *from* value or a predicate function that determines the start of the transition.\n * @param toValue - The *to* value or a predicate function that determines the end of the transition.\n * @returns A boolean indicating whether the transition from *fromValue* to *toValue* has occurred.\n *\n * @internal Consider using `useOnTransition` for handling transitions instead of this hook.\n */\nexport const useDidTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: T | ((value: T) => boolean),\n) => {\n const [hasTransitioned, setHasTransitioned] = useState(false);\n const previousValue = useRef<T>(currentValue);\n\n useEffect(() => {\n const toValueValid = isFunction<T>(toValue) ? toValue(currentValue) : toValue === currentValue;\n\n const fromValueValid = isFunction<T>(fromValue)\n ? fromValue(previousValue.current)\n : fromValue === previousValue.current;\n\n const transitioned = fromValueValid && toValueValid;\n\n if (transitioned) {\n setHasTransitioned(true);\n } else {\n setHasTransitioned(false);\n }\n\n previousValue.current = currentValue;\n }, [currentValue, fromValue, toValue, setHasTransitioned, previousValue]);\n\n return hasTransitioned;\n};\n\n/**\n * Executes a callback function when a specified transition occurs in a value.\n *\n * This function utilizes the `useDidTransition` hook to monitor changes in `currentValue`.\n * When `currentValue` transitions from `fromValue` to `toValue`, the provided `callback` function is executed. */\nexport const useOnTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: ((value: T) => boolean) | T,\n callback: () => void,\n) => {\n const dirty = useRef(false);\n const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);\n\n useEffect(() => {\n dirty.current = false;\n }, [currentValue, dirty]);\n\n useEffect(() => {\n if (hasTransitioned && !dirty.current) {\n callback();\n dirty.current = true;\n }\n }, [hasTransitioned, dirty, callback]);\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAoC;ACApC,IAAAA,gBAAwE;ACAxE,IAAAA,gBAA6C;ACA7C,IAAAA,gBAAkC;ACAlC,IAAAA,gBAAwB;ACAxB,IAAAA,gBAAqD;ACArD,kBAAiB;AACjB,IAAAA,gBAAwB;ACExB,IAAAA,gBAA4D;ACD5D,IAAAA,gBAAoC;ACFpC,IAAAA,iBAA2C;ACA3C,IAAAA,iBAA4C;AVErC,IAAMC,mBAAmB,CAAIC,OAAAA;AAClC,QAAM,CAACC,OAAOC,QAAAA,QAAYC,uBAAAA;AAC1BC,8BAAU,MAAA;AACR,UAAMC,IAAIC,WAAW,YAAA;AACnB,YAAMC,OAAO,MAAMP,GAAAA;AACnBE,eAASK,IAAAA;IACX,CAAA;AAEA,WAAO,MAAMC,aAAaH,CAAAA;EAC5B,GAAG,CAAA,CAAE;AAEL,SAAOJ;AACT;ACTO,IAAMQ,qBAAqB,CAASC,oBAAAA;AACzC,QAAM,CAACT,OAAOC,QAAAA,QAAYC,cAAAA,UAAiBO,eAAAA;AAC3CN,oBAAAA,WAAU,MAAA;AACR,QAAIM,oBAAoBC,QAAW;AACjCT,eAASQ,eAAAA;IACX;EACF,GAAG;IAACA;GAAgB;AAEpB,SAAO;IAACT;IA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_react", "useAsyncCallback", "cb", "value", "setValue", "useState", "useEffect", "t", "setTimeout", "data", "clearTimeout", "useControlledValue", "controlledValue", "undefined", "useDefaultValue", "reactiveValue", "defaultValue", "stableDefaultValue", "useMemo", "useDynamicRef", "ref", "useRef", "current", "useFileDownload", "filename", "url", "URL", "createObjectURL", "element", "document", "createElement", "setAttribute", "click", "useForwardedRef", "innerRef", "Alea", "alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "isFocusedRef", "input", "onFocus", "onBlur", "addEventListener", "activeElement", "removeEventListener", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "index", "media", "matches", "defaultView", "matchMedia", "mql", "handler", "evt", "prev", "item", "forEach", "addListener", "removeListener", "useRefCallback", "refCallback", "isFunction", "functionToCheck", "Function", "useDidTransition", "currentValue", "fromValue", "toValue", "hasTransitioned", "setHasTransitioned", "previousValue", "toValueValid", "fromValueValid", "transitioned", "useOnTransition", "callback", "dirty"]
3
+ "sources": ["../../../src/useAsyncCallback.ts", "../../../src/useAsyncEffect.ts", "../../../src/useControlledValue.ts", "../../../src/useDebugReactDeps.ts", "../../../src/useDefaultValue.ts", "../../../src/useDynamicRef.ts", "../../../src/useFileDownload.ts", "../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts", "../../../src/useMulticastObservable.ts", "../../../src/useRefCallback.ts", "../../../src/useTransitions.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState } from 'react';\n\n/**\n * NOTE: Use with care and when necessary to be able to cancel an async operation when unmounting.\n */\nexport const useAsyncCallback = <T>(cb: () => Promise<T>): T | undefined => {\n const [value, setValue] = useState<T | undefined>();\n useEffect(() => {\n const t = setTimeout(async () => {\n const data = await cb();\n setValue(data);\n });\n\n return () => clearTimeout(t);\n }, []);\n\n return value;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { useEffect } from 'react';\n\nimport { log } from '@dxos/log';\n\n/**\n * Process async event with optional non-async destructor.\n * Inspired by: https://github.com/rauldeheer/use-async-effect/blob/master/index.js\n *\n * ```tsx\n * useAsyncEffect(async () => {\n * await test();\n * }, []);\n * ```\n *\n * The callback may check of the component is still mounted before doing state updates.\n *\n * ```tsx\n * const [value, setValue] = useState<string>();\n * useAsyncEffect<string>(async (isMounted) => {\n * const value = await test();\n * if (!isMounted()) {\n * setValue(value);\n * }\n * }, () => console.log('Unmounted'), []);\n * ```\n *\n * @param callback Receives a getter function that determines if the component is still mounted.\n * @param destructor Receives the value returned from the callback.\n * @param deps\n *\n * NOTE: This effect does not cancel the async operation if the component is unmounted.\n */\nexport const useAsyncEffect = <T>(\n callback: (isMounted: () => boolean) => Promise<T> | undefined,\n destructor?: ((value?: T) => void) | any[],\n deps?: any[],\n) => {\n const [effectDestructor, effectDeps] =\n typeof destructor === 'function' ? [destructor, deps] : [undefined, destructor];\n\n useEffect(() => {\n let mounted = true;\n let value: T | undefined;\n const asyncResult = callback(() => mounted);\n\n void Promise.resolve(asyncResult)\n .then((result) => {\n value = result;\n })\n .catch(log.catch);\n\n return () => {\n mounted = false;\n effectDestructor?.(value);\n };\n }, effectDeps);\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from 'react';\n\n/**\n * A stateful hook with a controlled value.\n */\nexport const useControlledValue = <TValue>(controlledValue: TValue): [TValue, Dispatch<SetStateAction<TValue>>] => {\n const [value, setValue] = useState<TValue>(controlledValue);\n useEffect(() => {\n if (controlledValue !== undefined) {\n setValue(controlledValue);\n }\n }, [controlledValue]);\n\n return [value, setValue];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/* eslint-disable no-console */\n\nimport { type DependencyList, useEffect, useRef } from 'react';\n\n/**\n * Util to log deps that have changed.\n */\n// TODO(burdon): Move to react-hooks.\nexport const useDebugReactDeps = (deps: DependencyList = []) => {\n const lastDeps = useRef<DependencyList>([]);\n useEffect(() => {\n console.group('deps changed', { old: lastDeps.current.length, new: deps.length });\n for (let i = 0; i < Math.max(lastDeps.current.length ?? 0, deps.length ?? 0); i++) {\n console.log(i, lastDeps.current[i] === deps[i] ? 'SAME' : 'CHANGED', {\n previous: lastDeps.current[i],\n current: deps[i],\n });\n }\n\n console.groupEnd();\n lastDeps.current = deps;\n }, deps);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useState, useMemo } from 'react';\n\n/**\n * A custom React hook that provides a stable default value for a potentially undefined reactive value.\n * The defaultValue is memoized upon component mount and remains unchanged until the component unmounts,\n * ensuring stability across all re-renders, even if the defaultValue prop changes.\n *\n * Note: The defaultValue is not reactive. It retains the same value from the component's mount to unmount.\n *\n * @param reactiveValue - The value that may change over time.\n * @param defaultValue - The initial value used when the reactiveValue is undefined. This value is not reactive.\n * @returns - The reactiveValue if it's defined, otherwise the defaultValue.\n */\nexport const useDefaultValue = <T>(reactiveValue: T | undefined | null, defaultValue: T): T => {\n // Memoize defaultValue with an empty dependency array.\n // This ensures that the defaultValue instance remains stable across all re-renders,\n // regardless of whether the defaultValue changes.\n const stableDefaultValue = useMemo(() => defaultValue, []);\n const [value, setValue] = useState(reactiveValue ?? stableDefaultValue);\n\n useEffect(() => {\n setValue(reactiveValue ?? stableDefaultValue);\n }, [reactiveValue, stableDefaultValue]);\n\n return value;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useEffect, useRef } from 'react';\n\nexport const useDynamicRef = <T>(value: T) => {\n const ref = useRef<T>(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\n/**\n * File download anchor.\n *\n * ```\n * const download = useDownload();\n * const handleDownload = (data: string) => {\n * download(new Blob([data], { type: 'text/plain' }), 'test.txt');\n * };\n * ```\n */\nexport const useFileDownload = (): ((data: Blob | string, filename: string) => void) => {\n return useMemo(\n () => (data: Blob | string, filename: string) => {\n const url = typeof data === 'string' ? data : URL.createObjectURL(data);\n const element = document.createElement('a');\n element.setAttribute('href', url);\n element.setAttribute('download', filename);\n element.setAttribute('target', 'download');\n element.click();\n },\n [],\n );\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type ForwardedRef, useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\n// TODO(burdon): Replace with PublicKey.random().\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, type RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { type MulticastObservable } from '@dxos/async';\n\n/**\n * Subscribe to a MulticastObservable and return the latest value.\n * @param observable the observable to subscribe to. Will resubscribe if the observable changes.\n */\n// TODO(burdon): Move to react-hooks.\nexport const useMulticastObservable = <T>(observable: MulticastObservable<T>): T => {\n // Make sure useSyncExternalStore is stable in respect to the observable.\n const subscribeFn = useMemo(\n () => (listener: () => void) => {\n const subscription = observable.subscribe(listener);\n return () => subscription.unsubscribe();\n },\n [observable],\n );\n\n // useSyncExternalStore will resubscribe to the observable and update the value if the subscribeFn changes.\n return useSyncExternalStore(subscribeFn, () => observable.get());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type RefCallback, useState } from 'react';\n\n/**\n * Custom React Hook that creates a ref callback and a state variable.\n * The ref callback sets the state variable when the ref changes.\n *\n * @returns An object containing the ref callback and the current value of the ref.\n */\nexport const useRefCallback = <T = any>(): { refCallback: RefCallback<T>; value: T | null } => {\n const [value, setValue] = useState<T | null>(null);\n return { refCallback: (value: T) => setValue(value), value };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { useRef, useEffect, useState } from 'react';\n\nconst isFunction = <T>(functionToCheck: any): functionToCheck is (value: T) => boolean => {\n return functionToCheck instanceof Function;\n};\n\n/**\n * This is an internal custom hook that checks if a value has transitioned from a specified 'from' value to a 'to' value.\n *\n * @param currentValue - The value that is being monitored for transitions.\n * @param fromValue - The *from* value or a predicate function that determines the start of the transition.\n * @param toValue - The *to* value or a predicate function that determines the end of the transition.\n * @returns A boolean indicating whether the transition from *fromValue* to *toValue* has occurred.\n *\n * @internal Consider using `useOnTransition` for handling transitions instead of this hook.\n */\nexport const useDidTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: T | ((value: T) => boolean),\n) => {\n const [hasTransitioned, setHasTransitioned] = useState(false);\n const previousValue = useRef<T>(currentValue);\n\n useEffect(() => {\n const toValueValid = isFunction<T>(toValue) ? toValue(currentValue) : toValue === currentValue;\n\n const fromValueValid = isFunction<T>(fromValue)\n ? fromValue(previousValue.current)\n : fromValue === previousValue.current;\n\n const transitioned = fromValueValid && toValueValid;\n\n if (transitioned) {\n setHasTransitioned(true);\n } else {\n setHasTransitioned(false);\n }\n\n previousValue.current = currentValue;\n }, [currentValue, fromValue, toValue, setHasTransitioned, previousValue]);\n\n return hasTransitioned;\n};\n\n/**\n * Executes a callback function when a specified transition occurs in a value.\n *\n * This function utilizes the `useDidTransition` hook to monitor changes in `currentValue`.\n * When `currentValue` transitions from `fromValue` to `toValue`, the provided `callback` function is executed. */\nexport const useOnTransition = <T>(\n currentValue: T,\n fromValue: T | ((value: T) => boolean),\n toValue: ((value: T) => boolean) | T,\n callback: () => void,\n) => {\n const dirty = useRef(false);\n const hasTransitioned = useDidTransition(currentValue, fromValue, toValue);\n\n useEffect(() => {\n dirty.current = false;\n }, [currentValue, dirty]);\n\n useEffect(() => {\n if (hasTransitioned && !dirty.current) {\n callback();\n dirty.current = true;\n }\n }, [hasTransitioned, dirty, callback]);\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAoC;ACApC,IAAAA,gBAA0B;AAE1B,iBAAoB;ACFpB,IAAAA,gBAAwE;ACExE,IAAAA,gBAAuD;ACFvD,IAAAA,gBAA6C;ACA7C,IAAAA,gBAAkC;ACAlC,IAAAA,gBAAwB;ACAxB,IAAAA,gBAAqD;ACArD,kBAAi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AAYF;AAElF,UAAMO,iBAAiBX,WAAcK,SAAAA,IACjCA,UAAUI,cAAcnG,OAAO,IAC/B+F,cAAcI,cAAcnG;AAEhC,UAAMsG,eAAeD,kBAAkBD;AAEvC,QAAIE,cAAc;AAChBJ,yBAAmB,IAAA;IACrB,OAAO;AACLA,yBAAmB,KAAA;IACrB;AAEAC,kBAAcnG,UAAU8F;EAC1B,GAAG;IAACA;IAAcC;IAAWC;IAASE;IAAoBC;GAAc;AAExE,SAAOF;AACT;AAOO,IAAMM,kBAAkB,CAC7BT,cACAC,WACAC,SACAtH,aAAAA;AAEA,QAAM8H,YAAQ5G,eAAAA,QAAO,KAAA;AACrB,QAAMqG,kBAAkBJ,iBAAiBC,cAAcC,WAAWC,OAAAA;AAElE5H,qBAAAA,WAAU,MAAA;AACRoI,UAAMxG,UAAU;EAClB,GAAG;IAAC8F;IAAcU;GAAM;AAExBpI,qBAAAA,WAAU,MAAA;AACR,QAAI6H,mBAAmB,CAACO,MAAMxG,SAAS;AACrCtB,eAAAA;AACA8H,YAAMxG,UAAU;IAClB;EACF,GAAG;IAACiG;IAAiBO;IAAO9H;GAAS;AACvC;",
6
+ "names": ["import_react", "useAsyncCallback", "cb", "value", "setValue", "useState", "useEffect", "t", "setTimeout", "data", "clearTimeout", "useAsyncEffect", "callback", "destructor", "deps", "effectDestructor", "effectDeps", "undefined", "mounted", "asyncResult", "Promise", "resolve", "then", "result", "catch", "log", "useControlledValue", "controlledValue", "useDebugReactDeps", "lastDeps", "useRef", "console", "group", "old", "current", "length", "new", "i", "Math", "max", "previous", "groupEnd", "useDefaultValue", "reactiveValue", "defaultValue", "stableDefaultValue", "useMemo", "useDynamicRef", "ref", "useFileDownload", "filename", "url", "URL", "createObjectURL", "element", "document", "createElement", "setAttribute", "click", "useForwardedRef", "innerRef", "Alea", "alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "isFocusedRef", "input", "onFocus", "onBlur", "addEventListener", "activeElement", "removeEventListener", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "index", "media", "matches", "defaultView", "matchMedia", "mql", "handler", "evt", "prev", "item", "forEach", "addListener", "removeListener", "useMulticastObservable", "observable", "subscribeFn", "listener", "subscription", "subscribe", "unsubscribe", "useSyncExternalStore", "get", "useRefCallback", "refCallback", "isFunction", "functionToCheck", "Function", "useDidTransition", "currentValue", "fromValue", "toValue", "hasTransitioned", "setHasTransitioned", "previousValue", "toValueValid", "fromValueValid", "transitioned", "useOnTransition", "dirty"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytes":1751,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytes":1974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytes":4059,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytes":1247,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytes":2740,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1783,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":2163,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3990,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9390,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytes":1879,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytes":7797,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":1572,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts","kind":"import-statement","original":"./useAsyncCallback"},{"path":"packages/ui/primitives/react-hooks/src/useControlledValue.ts","kind":"import-statement","original":"./useControlledValue"},{"path":"packages/ui/primitives/react-hooks/src/useDefaultValue.ts","kind":"import-statement","original":"./useDefaultValue"},{"path":"packages/ui/primitives/react-hooks/src/useDynamicRef.ts","kind":"import-statement","original":"./useDynamicRef"},{"path":"packages/ui/primitives/react-hooks/src/useFileDownload.ts","kind":"import-statement","original":"./useFileDownload"},{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"},{"path":"packages/ui/primitives/react-hooks/src/useRefCallback.ts","kind":"import-statement","original":"./useRefCallback"},{"path":"packages/ui/primitives/react-hooks/src/useTransitions.ts","kind":"import-statement","original":"./useTransitions"}],"format":"esm"}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":18788},"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs":{"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["randomString","useAsyncCallback","useControlledValue","useDefaultValue","useDidTransition","useDynamicRef","useFileDownload","useForwardedRef","useId","useIsFocused","useMediaQuery","useOnTransition","useRefCallback"],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytesInOutput":301},"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":0},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytesInOutput":350},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytesInOutput":411},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytesInOutput":205},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytesInOutput":416},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":343},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":326},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":833},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":1940},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytesInOutput":197},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytesInOutput":1384}},"bytes":7649}}}
1
+ {"inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytes":2022,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts":{"bytes":5018,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytes":1974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts":{"bytes":3192,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytes":4104,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytes":1251,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytes":2740,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1783,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":2163,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3990,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9390,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts":{"bytes":3033,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytes":1879,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytes":7797,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":1913,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts","kind":"import-statement","original":"./useAsyncCallback"},{"path":"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts","kind":"import-statement","original":"./useAsyncEffect"},{"path":"packages/ui/primitives/react-hooks/src/useControlledValue.ts","kind":"import-statement","original":"./useControlledValue"},{"path":"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts","kind":"import-statement","original":"./useDebugReactDeps"},{"path":"packages/ui/primitives/react-hooks/src/useDefaultValue.ts","kind":"import-statement","original":"./useDefaultValue"},{"path":"packages/ui/primitives/react-hooks/src/useDynamicRef.ts","kind":"import-statement","original":"./useDynamicRef"},{"path":"packages/ui/primitives/react-hooks/src/useFileDownload.ts","kind":"import-statement","original":"./useFileDownload"},{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"},{"path":"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts","kind":"import-statement","original":"./useMulticastObservable"},{"path":"packages/ui/primitives/react-hooks/src/useRefCallback.ts","kind":"import-statement","original":"./useRefCallback"},{"path":"packages/ui/primitives/react-hooks/src/useTransitions.ts","kind":"import-statement","original":"./useTransitions"}],"format":"esm"}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":24207},"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs":{"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["randomString","useAsyncCallback","useAsyncEffect","useControlledValue","useDebugReactDeps","useDefaultValue","useDidTransition","useDynamicRef","useFileDownload","useForwardedRef","useId","useIsFocused","useMediaQuery","useMulticastObservable","useOnTransition","useRefCallback"],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/useAsyncCallback.ts":{"bytesInOutput":301},"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":0},"packages/ui/primitives/react-hooks/src/useAsyncEffect.ts":{"bytesInOutput":596},"packages/ui/primitives/react-hooks/src/useControlledValue.ts":{"bytesInOutput":350},"packages/ui/primitives/react-hooks/src/useDebugReactDeps.ts":{"bytesInOutput":567},"packages/ui/primitives/react-hooks/src/useDefaultValue.ts":{"bytesInOutput":422},"packages/ui/primitives/react-hooks/src/useDynamicRef.ts":{"bytesInOutput":217},"packages/ui/primitives/react-hooks/src/useFileDownload.ts":{"bytesInOutput":416},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":343},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":326},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":833},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":1940},"packages/ui/primitives/react-hooks/src/useMulticastObservable.ts":{"bytesInOutput":368},"packages/ui/primitives/react-hooks/src/useRefCallback.ts":{"bytesInOutput":197},"packages/ui/primitives/react-hooks/src/useTransitions.ts":{"bytesInOutput":1388}},"bytes":9466}}}
@@ -1,5 +1,7 @@
1
1
  export * from './useAsyncCallback';
2
+ export * from './useAsyncEffect';
2
3
  export * from './useControlledValue';
4
+ export * from './useDebugReactDeps';
3
5
  export * from './useDefaultValue';
4
6
  export * from './useDynamicRef';
5
7
  export * from './useFileDownload';
@@ -7,6 +9,7 @@ export * from './useForwardedRef';
7
9
  export * from './useId';
8
10
  export * from './useIsFocused';
9
11
  export * from './useMediaQuery';
12
+ export * from './useMulticastObservable';
10
13
  export * from './useRefCallback';
11
14
  export * from './useTransitions';
12
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,oBAAoB,CAAC;AACnC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC"}
@@ -1,2 +1,5 @@
1
+ /**
2
+ * NOTE: Use with care and when necessary to be able to cancel an async operation when unmounting.
3
+ */
1
4
  export declare const useAsyncCallback: <T>(cb: () => Promise<T>) => T | undefined;
2
5
  //# sourceMappingURL=useAsyncCallback.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCallback.d.ts","sourceRoot":"","sources":["../../../src/useAsyncCallback.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,GAAI,CAAC,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,KAAG,CAAC,GAAG,SAY9D,CAAC"}
1
+ {"version":3,"file":"useAsyncCallback.d.ts","sourceRoot":"","sources":["../../../src/useAsyncCallback.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAAI,CAAC,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,KAAG,CAAC,GAAG,SAY9D,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Process async event with optional non-async destructor.
3
+ * Inspired by: https://github.com/rauldeheer/use-async-effect/blob/master/index.js
4
+ *
5
+ * ```tsx
6
+ * useAsyncEffect(async () => {
7
+ * await test();
8
+ * }, []);
9
+ * ```
10
+ *
11
+ * The callback may check of the component is still mounted before doing state updates.
12
+ *
13
+ * ```tsx
14
+ * const [value, setValue] = useState<string>();
15
+ * useAsyncEffect<string>(async (isMounted) => {
16
+ * const value = await test();
17
+ * if (!isMounted()) {
18
+ * setValue(value);
19
+ * }
20
+ * }, () => console.log('Unmounted'), []);
21
+ * ```
22
+ *
23
+ * @param callback Receives a getter function that determines if the component is still mounted.
24
+ * @param destructor Receives the value returned from the callback.
25
+ * @param deps
26
+ *
27
+ * NOTE: This effect does not cancel the async operation if the component is unmounted.
28
+ */
29
+ export declare const useAsyncEffect: <T>(callback: (isMounted: () => boolean) => Promise<T> | undefined, destructor?: ((value?: T) => void) | any[], deps?: any[]) => void;
30
+ //# sourceMappingURL=useAsyncEffect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncEffect.d.ts","sourceRoot":"","sources":["../../../src/useAsyncEffect.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,cAAc,GAAI,CAAC,YACpB,CAAC,SAAS,EAAE,MAAM,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,eACjD,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,IAAI,CAAC,GAAG,GAAG,EAAE,SACnC,GAAG,EAAE,SAqBb,CAAC"}
@@ -0,0 +1,2 @@
1
+ import 'raf/polyfill';
2
+ //# sourceMappingURL=useAsyncEffect.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncEffect.test.d.ts","sourceRoot":"","sources":["../../../src/useAsyncEffect.test.tsx"],"names":[],"mappings":"AAKA,OAAO,cAAc,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { type DependencyList } from 'react';
2
+ /**
3
+ * Util to log deps that have changed.
4
+ */
5
+ export declare const useDebugReactDeps: (deps?: DependencyList) => void;
6
+ //# sourceMappingURL=useDebugReactDeps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDebugReactDeps.d.ts","sourceRoot":"","sources":["../../../src/useDebugReactDeps.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,cAAc,EAAqB,MAAM,OAAO,CAAC;AAE/D;;GAEG;AAEH,eAAO,MAAM,iBAAiB,UAAU,cAAc,SAcrD,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useDefaultValue.d.ts","sourceRoot":"","sources":["../../../src/useDefaultValue.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,iBAAiB,CAAC,GAAG,SAAS,GAAG,IAAI,gBAAgB,CAAC,KAAG,CAUzF,CAAC"}
1
+ {"version":3,"file":"useDefaultValue.d.ts","sourceRoot":"","sources":["../../../src/useDefaultValue.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,iBAAiB,CAAC,GAAG,SAAS,GAAG,IAAI,gBAAgB,CAAC,KAAG,CAYzF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useDynamicRef.d.ts","sourceRoot":"","sources":["../../../src/useDynamicRef.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,CAAC,wCAMxC,CAAC"}
1
+ {"version":3,"file":"useDynamicRef.d.ts","sourceRoot":"","sources":["../../../src/useDynamicRef.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,CAAC,wCAOxC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { type MulticastObservable } from '@dxos/async';
2
+ /**
3
+ * Subscribe to a MulticastObservable and return the latest value.
4
+ * @param observable the observable to subscribe to. Will resubscribe if the observable changes.
5
+ */
6
+ export declare const useMulticastObservable: <T>(observable: MulticastObservable<T>) => T;
7
+ //# sourceMappingURL=useMulticastObservable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useMulticastObservable.d.ts","sourceRoot":"","sources":["../../../src/useMulticastObservable.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD;;;GAGG;AAEH,eAAO,MAAM,sBAAsB,GAAI,CAAC,cAAc,mBAAmB,CAAC,CAAC,CAAC,KAAG,CAY9E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/react-hooks",
3
- "version": "0.6.10",
3
+ "version": "0.6.11-staging.32b42e4",
4
4
  "description": "React hooks supporting DXOS React primitives.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -24,7 +24,9 @@
24
24
  "src"
25
25
  ],
26
26
  "dependencies": {
27
- "alea": "^1.0.1"
27
+ "alea": "^1.0.1",
28
+ "@dxos/async": "0.6.11-staging.32b42e4",
29
+ "@dxos/log": "0.6.11-staging.32b42e4"
28
30
  },
29
31
  "devDependencies": {
30
32
  "@types/react": "~18.2.0",
package/src/index.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  //
4
4
 
5
5
  export * from './useAsyncCallback';
6
+ export * from './useAsyncEffect';
6
7
  export * from './useControlledValue';
8
+ export * from './useDebugReactDeps';
7
9
  export * from './useDefaultValue';
8
10
  export * from './useDynamicRef';
9
11
  export * from './useFileDownload';
@@ -11,5 +13,6 @@ export * from './useForwardedRef';
11
13
  export * from './useId';
12
14
  export * from './useIsFocused';
13
15
  export * from './useMediaQuery';
16
+ export * from './useMulticastObservable';
14
17
  export * from './useRefCallback';
15
18
  export * from './useTransitions';
@@ -4,6 +4,9 @@
4
4
 
5
5
  import { useEffect, useState } from 'react';
6
6
 
7
+ /**
8
+ * NOTE: Use with care and when necessary to be able to cancel an async operation when unmounting.
9
+ */
7
10
  export const useAsyncCallback = <T>(cb: () => Promise<T>): T | undefined => {
8
11
  const [value, setValue] = useState<T | undefined>();
9
12
  useEffect(() => {
@@ -0,0 +1,57 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ import expect from 'expect';
6
+ import 'raf/polyfill';
7
+ import React, { useState } from 'react';
8
+ import { createRoot } from 'react-dom/client';
9
+ import { act } from 'react-dom/test-utils';
10
+ import waitForExpect from 'wait-for-expect';
11
+
12
+ import { afterEach, beforeEach, describe, test } from '@dxos/test';
13
+
14
+ import { useAsyncEffect } from './useAsyncEffect';
15
+
16
+ const doAsync = async <T,>(value: T) =>
17
+ await new Promise<T>((resolve) => {
18
+ resolve(value);
19
+ });
20
+
21
+ const Test = () => {
22
+ const [value, setValue] = useState<string>();
23
+ useAsyncEffect(async (isMounted) => {
24
+ const value = await doAsync('DXOS');
25
+ if (isMounted()) {
26
+ void act(() => {
27
+ setValue(value);
28
+ });
29
+ }
30
+ }, []);
31
+
32
+ return <h1>{value}</h1>;
33
+ };
34
+
35
+ let rootContainer: HTMLElement;
36
+
37
+ describe('useAsyncEffect', () => {
38
+ beforeEach(() => {
39
+ rootContainer = document.createElement('div');
40
+ document.body.appendChild(rootContainer);
41
+ });
42
+
43
+ afterEach(() => {
44
+ document.body.removeChild(rootContainer!);
45
+ });
46
+
47
+ test('gets async value.', async () => {
48
+ void act(() => {
49
+ createRoot(rootContainer).render(<Test />);
50
+ });
51
+
52
+ const h1 = rootContainer.querySelector('h1');
53
+ await waitForExpect(() => {
54
+ expect(h1?.textContent).toEqual('DXOS');
55
+ });
56
+ });
57
+ });
@@ -0,0 +1,61 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ import { useEffect } from 'react';
6
+
7
+ import { log } from '@dxos/log';
8
+
9
+ /**
10
+ * Process async event with optional non-async destructor.
11
+ * Inspired by: https://github.com/rauldeheer/use-async-effect/blob/master/index.js
12
+ *
13
+ * ```tsx
14
+ * useAsyncEffect(async () => {
15
+ * await test();
16
+ * }, []);
17
+ * ```
18
+ *
19
+ * The callback may check of the component is still mounted before doing state updates.
20
+ *
21
+ * ```tsx
22
+ * const [value, setValue] = useState<string>();
23
+ * useAsyncEffect<string>(async (isMounted) => {
24
+ * const value = await test();
25
+ * if (!isMounted()) {
26
+ * setValue(value);
27
+ * }
28
+ * }, () => console.log('Unmounted'), []);
29
+ * ```
30
+ *
31
+ * @param callback Receives a getter function that determines if the component is still mounted.
32
+ * @param destructor Receives the value returned from the callback.
33
+ * @param deps
34
+ *
35
+ * NOTE: This effect does not cancel the async operation if the component is unmounted.
36
+ */
37
+ export const useAsyncEffect = <T>(
38
+ callback: (isMounted: () => boolean) => Promise<T> | undefined,
39
+ destructor?: ((value?: T) => void) | any[],
40
+ deps?: any[],
41
+ ) => {
42
+ const [effectDestructor, effectDeps] =
43
+ typeof destructor === 'function' ? [destructor, deps] : [undefined, destructor];
44
+
45
+ useEffect(() => {
46
+ let mounted = true;
47
+ let value: T | undefined;
48
+ const asyncResult = callback(() => mounted);
49
+
50
+ void Promise.resolve(asyncResult)
51
+ .then((result) => {
52
+ value = result;
53
+ })
54
+ .catch(log.catch);
55
+
56
+ return () => {
57
+ mounted = false;
58
+ effectDestructor?.(value);
59
+ };
60
+ }, effectDeps);
61
+ };
@@ -0,0 +1,27 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ /* eslint-disable no-console */
6
+
7
+ import { type DependencyList, useEffect, useRef } from 'react';
8
+
9
+ /**
10
+ * Util to log deps that have changed.
11
+ */
12
+ // TODO(burdon): Move to react-hooks.
13
+ export const useDebugReactDeps = (deps: DependencyList = []) => {
14
+ const lastDeps = useRef<DependencyList>([]);
15
+ useEffect(() => {
16
+ console.group('deps changed', { old: lastDeps.current.length, new: deps.length });
17
+ for (let i = 0; i < Math.max(lastDeps.current.length ?? 0, deps.length ?? 0); i++) {
18
+ console.log(i, lastDeps.current[i] === deps[i] ? 'SAME' : 'CHANGED', {
19
+ previous: lastDeps.current[i],
20
+ current: deps[i],
21
+ });
22
+ }
23
+
24
+ console.groupEnd();
25
+ lastDeps.current = deps;
26
+ }, deps);
27
+ };
@@ -22,7 +22,9 @@ export const useDefaultValue = <T>(reactiveValue: T | undefined | null, defaultV
22
22
  const stableDefaultValue = useMemo(() => defaultValue, []);
23
23
  const [value, setValue] = useState(reactiveValue ?? stableDefaultValue);
24
24
 
25
- useEffect(() => setValue(reactiveValue ?? stableDefaultValue), [reactiveValue, stableDefaultValue]);
25
+ useEffect(() => {
26
+ setValue(reactiveValue ?? stableDefaultValue);
27
+ }, [reactiveValue, stableDefaultValue]);
26
28
 
27
29
  return value;
28
30
  };
@@ -9,5 +9,6 @@ export const useDynamicRef = <T>(value: T) => {
9
9
  useEffect(() => {
10
10
  ref.current = value;
11
11
  }, [value]);
12
+
12
13
  return ref;
13
14
  };
@@ -0,0 +1,26 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { useMemo, useSyncExternalStore } from 'react';
6
+
7
+ import { type MulticastObservable } from '@dxos/async';
8
+
9
+ /**
10
+ * Subscribe to a MulticastObservable and return the latest value.
11
+ * @param observable the observable to subscribe to. Will resubscribe if the observable changes.
12
+ */
13
+ // TODO(burdon): Move to react-hooks.
14
+ export const useMulticastObservable = <T>(observable: MulticastObservable<T>): T => {
15
+ // Make sure useSyncExternalStore is stable in respect to the observable.
16
+ const subscribeFn = useMemo(
17
+ () => (listener: () => void) => {
18
+ const subscription = observable.subscribe(listener);
19
+ return () => subscription.unsubscribe();
20
+ },
21
+ [observable],
22
+ );
23
+
24
+ // useSyncExternalStore will resubscribe to the observable and update the value if the subscribeFn changes.
25
+ return useSyncExternalStore(subscribeFn, () => observable.get());
26
+ };