@uxf/core-react 13.0.0 → 14.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +80 -53
  2. package/clickable/_use-simulated-button.js +9 -5
  3. package/hooks/use-debounce.js +4 -2
  4. package/hooks/use-debounce.test.d.ts +1 -0
  5. package/hooks/use-debounce.test.js +63 -0
  6. package/hooks/use-focus-return.js +3 -2
  7. package/hooks/use-focus-trap.js +3 -4
  8. package/hooks/use-is-hydrated.d.ts +10 -0
  9. package/hooks/use-is-hydrated.js +18 -0
  10. package/hooks/use-is-hydrated.test.d.ts +1 -0
  11. package/hooks/use-is-hydrated.test.js +33 -0
  12. package/hooks/use-is-mounted.d.ts +5 -0
  13. package/hooks/use-is-mounted.js +5 -0
  14. package/hooks/use-isomorphic-layout-effect.d.ts +4 -0
  15. package/hooks/use-isomorphic-layout-effect.js +4 -0
  16. package/hooks/use-key.js +12 -11
  17. package/hooks/use-key.test.d.ts +1 -0
  18. package/hooks/use-key.test.js +65 -0
  19. package/hooks/use-latest.d.ts +5 -0
  20. package/hooks/use-latest.js +5 -0
  21. package/hooks/use-media-query.d.ts +10 -1
  22. package/hooks/use-media-query.js +16 -17
  23. package/hooks/use-media-query.test.d.ts +1 -0
  24. package/hooks/use-media-query.test.js +55 -0
  25. package/hooks/use-min-window-width.js +3 -2
  26. package/hooks/use-on-unmount.d.ts +1 -0
  27. package/hooks/use-on-unmount.js +4 -7
  28. package/hooks/use-on-unmount.test.d.ts +1 -0
  29. package/hooks/use-on-unmount.test.js +16 -0
  30. package/hooks/use-on-update.d.ts +8 -0
  31. package/hooks/use-on-update.js +15 -3
  32. package/hooks/use-on-update.test.d.ts +1 -0
  33. package/hooks/use-on-update.test.js +75 -0
  34. package/hooks/use-previous.d.ts +5 -0
  35. package/hooks/use-previous.js +5 -0
  36. package/hooks/use-window-scroll.js +3 -5
  37. package/hooks/use-window-scroll.test.js +3 -1
  38. package/hooks/use-window-size.js +3 -2
  39. package/hooks/use-window-size.test.js +3 -1
  40. package/package.json +9 -3
  41. package/swipeable/use-swipeable.js +47 -32
  42. package/swipeable/use-swipeable.test.d.ts +1 -0
  43. package/swipeable/use-swipeable.test.js +59 -0
  44. package/translations/replace-variables.js +4 -1
  45. package/translations/replace-variables.test.d.ts +1 -0
  46. package/translations/replace-variables.test.js +13 -0
  47. package/components/viewport-height-polyfill.d.ts +0 -2
  48. package/components/viewport-height-polyfill.js +0 -58
package/README.md CHANGED
@@ -24,30 +24,6 @@ import { Show } from "@uxf/core-react/components/show";
24
24
  <Show when={SOME_CONDITION}>...some content</Show>;
25
25
  ```
26
26
 
27
- ### ViewportHeightPolyfill
28
-
29
- Polyfill for custom css variable `--viewport-height` to mimic functionality of browser's [dynamic viewport height](https://web.dev/blog/viewport-units).
30
-
31
- Add component to react app root (eg. `_app.tsx`).
32
-
33
- ```tsx
34
- import { ViewportHeightPolyfill } from "@uxf/core-react/components/viewport-height-polyfill";
35
-
36
- <ViewportHeightPolyfill />;
37
- ```
38
-
39
- Add css variable declaration with fallback to app global styles (eg. `base.css`) if already not there.
40
-
41
- ```css
42
- :root {
43
- --viewport-height: 100vh;
44
-
45
- @supports (height: 100dvh) {
46
- --viewport-height: 100dvh;
47
- }
48
- }
49
- ```
50
-
51
27
  ## Hooks
52
28
 
53
29
  ---
@@ -76,7 +52,7 @@ useBodyScrollLock<HTMLDivElement>(innerRef, isOpen, {
76
52
 
77
53
  ---
78
54
 
79
- ### isMounted
55
+ ### useIsMounted
80
56
 
81
57
  Check if component is mounted.
82
58
 
@@ -86,11 +62,34 @@ import { useIsMounted } from "@uxf/core-react/hooks/use-is-mounted";
86
62
  const isMounted = useIsMounted();
87
63
  ```
88
64
 
65
+ Deprecated in favour of `useIsHydrated` for rendering something only in the browser. Keep it only where the code
66
+ needs effects to have run (refs attached).
67
+
68
+ ---
69
+
70
+ ### useIsHydrated
71
+
72
+ False on the server and during hydration, true in every other render, including the first render of a component
73
+ that mounts later on the client. Use it to render something only in the browser (`window`, a portal into
74
+ `document.body`, an editor) without the extra commit and the flash of fallback that `useIsMounted` costs on every
75
+ client-side mount. It does not mean effects have run: refs are not attached yet in the render where it turns true.
76
+
77
+ ```tsx
78
+ import { useIsHydrated } from "@uxf/core-react/hooks/use-is-hydrated";
79
+
80
+ const isHydrated = useIsHydrated();
81
+
82
+ return isHydrated ? <Editor /> : <Loader />;
83
+ ```
84
+
89
85
  ---
90
86
 
91
87
  ### useIsomorphicLayoutEffect
92
88
 
93
- Returns `useEffect` on client and `useLayoutEffect` on server.
89
+ **Deprecated – use `useLayoutEffect`.** It only silenced React's server warning about `useLayoutEffect`, which
90
+ React 19 removed; on the server `useLayoutEffect` simply does not run.
91
+
92
+ Returns `useLayoutEffect` in the browser and `useEffect` on the server.
94
93
 
95
94
  ```tsx
96
95
  import { useIsomorphicLayoutEffect } from "@uxf/core-react/hooks/use-isomorphic-layout-effect";
@@ -107,7 +106,8 @@ useIsomorphicLayoutEffect(
107
106
 
108
107
  ### useKey
109
108
 
110
- Trigger callback on given key.
109
+ Trigger callback on given key. The callback and the key filter are always the latest ones, also when passed inline.
110
+ The listener follows `targetRef`: a target that mounts later or is replaced gets it after the next commit.
111
111
 
112
112
  ```tsx
113
113
  import { useKey } from "@uxf/core-react/hooks/use-key";
@@ -173,21 +173,34 @@ const [state, setState] = useRafState<boolean>(false);
173
173
 
174
174
  ### useOnMount
175
175
 
176
- Calls the callback on component mount.
176
+ Calls the callback on component mount; a returned function runs on unmount.
177
177
 
178
178
  ```tsx
179
- import { useOnUnmount } from "@uxf/core-react/hooks/use-on-unmount";
179
+ import { useOnMount } from "@uxf/core-react/hooks/use-on-mount";
180
+
181
+ useOnMount(() => console.log("mounted"));
182
+ ```
183
+
184
+ ---
185
+
186
+ ### useOnUnmount
180
187
 
181
- const exampleCallback = () => {};
188
+ Calls the callback on component unmount, in its version from the latest render.
182
189
 
183
- useOnUnmount(exampleCallback());
190
+ ```tsx
191
+ import { useOnUnmount } from "@uxf/core-react/hooks/use-on-unmount";
192
+
193
+ useOnUnmount(() => clearTimeout(timer.current));
184
194
  ```
185
195
 
186
196
  ---
187
197
 
188
198
  ### useOnUpdate
189
199
 
190
- Calls the callback only on component update, except initial mount.
200
+ Calls the callback when the deps change, not on mount. It compares the deps with those of its previous run, so
201
+ StrictMode's second mount run is skipped too, and so is a reconnect with the same deps (an `<Activity>` shown again),
202
+ whose cleanup has already run. Work that has to survive a reconnect, like a pending timer, belongs in a plain
203
+ `useEffect`.
191
204
 
192
205
  ```tsx
193
206
  import { useOnUpdate } from "@uxf/core-react/hooks/use-on-update";
@@ -267,6 +280,12 @@ useFocusReturn(active);
267
280
 
268
281
  Returns props for anchor element.
269
282
 
283
+ `type: "submit"` works like a native submit button, through `form.requestSubmit()` on the form the element sits in
284
+ (or, outside any form, the form that has focus). The browser validates first (`required`, `type="email"`, …) unless
285
+ the form has `noValidate`, which `@uxf/form`'s `Form` sets. A form whose `submit` handler does not call
286
+ `preventDefault()` is then submitted natively, so the page navigates. Earlier versions dispatched a bare `submit`
287
+ event instead: no validation and no native submission.
288
+
270
289
  ```tsx
271
290
  import { useAnchorProps } from "@uxf/core-react/clickable/use-anchor-props";
272
291
  import { AnchorHTMLAttributes } from "react";
@@ -342,7 +361,8 @@ const buttonProps = useButtonProps<Props>({
342
361
 
343
362
  ### useClickableProps
344
363
 
345
- Returns props for clickable element.
364
+ Returns props for clickable element. `type: "submit"` submits the element's form through `requestSubmit()`, as
365
+ described under `useAnchorProps`.
346
366
 
347
367
  ```tsx
348
368
  import { useClickableProps } from "@uxf/core-react/clickable/use-clickable-props";
@@ -418,7 +438,11 @@ const input = useInputFocus(focusRef, onBlur, onFocus);
418
438
 
419
439
  ### useLatest
420
440
 
421
- Allways returns latest value of given variable.
441
+ **Deprecated.** It writes `ref.current` during render, which React 19 asks not to do. To read the latest props or
442
+ state from an effect or a listener it registers, use `useEffectEvent`; for a value read during render, use the value
443
+ itself.
444
+
445
+ Always returns the latest value of the given variable.
422
446
 
423
447
  ```tsx
424
448
  import { useLatest } from "@uxf/core-react/hooks/use-latest";
@@ -455,7 +479,11 @@ callback on every call, so use it only outside a component.
455
479
 
456
480
  ### usePrevious
457
481
 
458
- Returns previous value of given variable.
482
+ **Deprecated.** Its ref is only useful when read during render, which React 19 asks not to do. To react to a change,
483
+ keep the previous value in state and compare during render
484
+ ([React docs](https://react.dev/reference/react/useState#storing-information-from-previous-renders)).
485
+
486
+ Returns the previous value of the given variable.
459
487
 
460
488
  ```tsx
461
489
  import { usePrevious } from "@uxf/core-react/hooks/use-previous";
@@ -507,28 +535,19 @@ import { useDebounce } from "@uxf/core-react/hooks/use-debounce";
507
535
  const debouncedValue = useDebounce<string>("some value", 300);
508
536
  ```
509
537
 
510
- ## String helpers
511
-
512
- ```tsx
513
- import { nl2br } from "@uxf/core-react/string/nl2br";
514
-
515
- <div>{nl2br("Hello\nWorld")}</div>;
516
- ```
517
-
518
- ---
519
-
520
538
  ### useMediaQuery
521
539
 
522
540
  Returns whether the given media query is currently matched. Optionally accepts a callback that is called on every change.
523
541
 
524
- Uses `window.matchMedia` with a `change` event listener (via `AbortController`) for efficient updates.
542
+ Reads `window.matchMedia` through `useSyncExternalStore`: `false` on the server and during hydration (no mismatch),
543
+ the real value from the first render of a component mounted on the client, and updated on every `change`.
525
544
 
526
545
  ```tsx
527
546
  import { useMediaQuery } from "@uxf/core-react/hooks/use-media-query";
528
547
  import type { UseMediaQueryCallback } from "@uxf/core-react/hooks/use-media-query";
529
548
  import { twScreens } from "@generated/tw-tokens/tw-screens";
530
549
 
531
- // Basic usage – reactive boolean (SSR-safe, initializes as false)
550
+ // Basic usage – reactive boolean, SSR-safe
532
551
  const isDesktop = useMediaQuery(`(min-width: ${twScreens.sm})`);
533
552
 
534
553
  // With optional callback – fired on every match change
@@ -537,17 +556,25 @@ const callback: UseMediaQueryCallback = (isMatching, mediaQueryString) => {
537
556
  };
538
557
 
539
558
  const isDesktopWithCallback = useMediaQuery(`(min-width: ${twScreens.sm})`, callback);
540
-
541
- // Client-only usage – initializes immediately from window.matchMedia (no SSR hydration)
542
- // Pass isSSR=false only when the component is guaranteed to render client-side only
543
- const isDesktopClientOnly = useMediaQuery(`(min-width: ${twScreens.sm})`, undefined, false);
544
559
  ```
545
560
 
546
561
  **Parameters:**
547
562
 
548
563
  - `mediaQueryString` – CSS media query string
549
- - `callback` _(optional)_ – called with `(isMatching, mediaQueryString)` on every match change
550
- - `isSSR` _(optional, default: `true`)_ – when `true`, initial state is `false` to avoid SSR/hydration mismatch; when `false`, initial state is read directly from `window.matchMedia` (use only in client-only components)
564
+ - `callback` _(optional)_ – called with `(isMatching, mediaQueryString)` once after mount and on every match change; always the latest callback, without resubscribing
565
+ - `isSSR` – deprecated and ignored; a client-only component gets the real value in its first render anyway
566
+
567
+ ---
568
+
569
+ ## String helpers
570
+
571
+ ```tsx
572
+ import { nl2br } from "@uxf/core-react/string/nl2br";
573
+
574
+ <div>{nl2br("Hello\nWorld")}</div>;
575
+ ```
576
+
577
+ ---
551
578
 
552
579
  ## Drag and Drop
553
580
 
@@ -7,16 +7,20 @@ function _useSimulatedButton({ analyticsCallback, isClickable, isHyperlink, onCl
7
7
  const [isBusy, setIsBusy] = (0, react_1.useState)(false);
8
8
  // eslint-disable-next-line react-hooks/rules-of-hooks
9
9
  const _onClick = (0, react_1.useCallback)((e) => {
10
- var _a;
10
+ var _a, _b;
11
11
  if ((isClickable || isHyperlink) && analyticsCallback) {
12
12
  analyticsCallback();
13
13
  }
14
14
  if (isClickable) {
15
15
  if (isSubmitType) {
16
- const closestForm = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.closest("form");
17
- if (closestForm) {
18
- closestForm.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
19
- }
16
+ // The element's own form first: a mouse click in Safari does not focus it, so focus can be on
17
+ // <body> or in another form. The focused element's form is the fallback for a button rendered
18
+ // outside any form, e.g. clicked programmatically from a field's Enter handler.
19
+ const form = (_a = e.currentTarget.closest("form")) !== null && _a !== void 0 ? _a : (_b = document.activeElement) === null || _b === void 0 ? void 0 : _b.closest("form");
20
+ // `requestSubmit`, not a dispatched `Event("submit")`: it validates, fires a real `SubmitEvent`
21
+ // and submits natively unless a handler prevents it. This element is no submit button, so it
22
+ // cannot be passed as the submitter.
23
+ form === null || form === void 0 ? void 0 : form.requestSubmit();
20
24
  }
21
25
  // TODO @vejvis - jaktože tady je onclick který vrací void a ne Promise<void> ?
22
26
  const clickResult = onClick === null || onClick === void 0 ? void 0 : onClick(e);
@@ -2,10 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useDebounce = useDebounce;
4
4
  const react_1 = require("react");
5
- const use_on_update_1 = require("./use-on-update");
6
5
  function useDebounce(value, delay) {
7
6
  const [debouncedValue, setDebouncedValue] = (0, react_1.useState)(value);
8
- (0, use_on_update_1.useOnUpdate)(() => {
7
+ // A plain effect, not useOnUpdate: after a reconnect (an <Activity> revealed again) a pending value must still
8
+ // arrive. On mount the timer sets the value the state already holds, so nothing re-renders, except that under
9
+ // StrictMode a value built during render (an inline object) is a new one.
10
+ (0, react_1.useEffect)(() => {
9
11
  const timer = setTimeout(() => setDebouncedValue(value), delay !== null && delay !== void 0 ? delay : 500);
10
12
  return () => {
11
13
  clearTimeout(timer);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const react_1 = require("@testing-library/react");
37
+ const react_2 = __importStar(require("react"));
38
+ const use_debounce_1 = require("./use-debounce");
39
+ function Probe(props) {
40
+ const debounced = (0, use_debounce_1.useDebounce)(props.value, 100);
41
+ return react_2.default.createElement("span", { "data-testid": "debounced" }, debounced);
42
+ }
43
+ function Host(props) {
44
+ return (react_2.default.createElement(react_2.Activity, { mode: props.isVisible ? "visible" : "hidden" },
45
+ react_2.default.createElement(Probe, { value: props.value })));
46
+ }
47
+ beforeEach(() => jest.useFakeTimers());
48
+ afterEach(() => jest.useRealTimers());
49
+ test("delivers the value after the delay", () => {
50
+ const { getByTestId, rerender } = (0, react_1.render)(react_2.default.createElement(Host, { isVisible: true, value: "a" }));
51
+ rerender(react_2.default.createElement(Host, { isVisible: true, value: "b" }));
52
+ expect(getByTestId("debounced").textContent).toBe("a");
53
+ (0, react_1.act)(() => jest.advanceTimersByTime(100));
54
+ expect(getByTestId("debounced").textContent).toBe("b");
55
+ });
56
+ test("delivers a value still pending when an Activity hid it, once it is shown again", () => {
57
+ const { getByTestId, rerender } = (0, react_1.render)(react_2.default.createElement(Host, { isVisible: true, value: "a" }));
58
+ rerender(react_2.default.createElement(Host, { isVisible: true, value: "b" }));
59
+ rerender(react_2.default.createElement(Host, { isVisible: false, value: "b" }));
60
+ rerender(react_2.default.createElement(Host, { isVisible: true, value: "b" }));
61
+ (0, react_1.act)(() => jest.advanceTimersByTime(100));
62
+ expect(getByTestId("debounced").textContent).toBe("b");
63
+ });
@@ -18,7 +18,8 @@ function useFocusReturn(opened, transitionDuration = 0, shouldReturnFocus = true
18
18
  clearTimeout(timeout);
19
19
  }
20
20
  };
21
- document.addEventListener("keydown", clearFocusTimeout);
21
+ const controller = new AbortController();
22
+ document.addEventListener("keydown", clearFocusTimeout, { signal: controller.signal });
22
23
  if (opened) {
23
24
  lastActiveElement.current = document.activeElement;
24
25
  }
@@ -27,7 +28,7 @@ function useFocusReturn(opened, transitionDuration = 0, shouldReturnFocus = true
27
28
  }
28
29
  return () => {
29
30
  clearTimeout(timeout);
30
- document.removeEventListener("keydown", clearFocusTimeout);
31
+ controller.abort();
31
32
  };
32
33
  }, [opened, shouldReturnFocus, transitionDuration]);
33
34
  return returnFocus;
@@ -135,10 +135,9 @@ function useFocusTrap(active = true) {
135
135
  scopeTab(node, e);
136
136
  }
137
137
  };
138
- document.addEventListener("keydown", handler);
139
- return () => {
140
- document.removeEventListener("keydown", handler);
141
- };
138
+ const controller = new AbortController();
139
+ document.addEventListener("keydown", handler, { signal: controller.signal });
140
+ return () => controller.abort();
142
141
  }, [active]);
143
142
  (0, use_on_unmount_1.useOnUnmount)(() => clearTimeout(timer.current));
144
143
  return setRef;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * False on the server and during hydration, true in every other render, including the first render of a component
3
+ * that mounts later on the client. For rendering something only in the browser (it touches `window`, a portal
4
+ * into `document.body`, an editor), without the extra commit and the flash of fallback `useIsMounted` costs on
5
+ * every client-side mount.
6
+ *
7
+ * Unlike `useIsMounted`, it does not mean effects have run: refs are not attached yet in a render where it turns
8
+ * true. Code that reads refs or measures the DOM after mount still needs an effect.
9
+ */
10
+ export declare function useIsHydrated(): boolean;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useIsHydrated = useIsHydrated;
4
+ const noop_1 = require("@uxf/core/utils/noop");
5
+ const react_1 = require("react");
6
+ const subscribeToNothing = () => noop_1.noop;
7
+ /**
8
+ * False on the server and during hydration, true in every other render, including the first render of a component
9
+ * that mounts later on the client. For rendering something only in the browser (it touches `window`, a portal
10
+ * into `document.body`, an editor), without the extra commit and the flash of fallback `useIsMounted` costs on
11
+ * every client-side mount.
12
+ *
13
+ * Unlike `useIsMounted`, it does not mean effects have run: refs are not attached yet in a render where it turns
14
+ * true. Code that reads refs or measures the DOM after mount still needs an effect.
15
+ */
16
+ function useIsHydrated() {
17
+ return (0, react_1.useSyncExternalStore)(subscribeToNothing, () => true, () => false);
18
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = require("@testing-library/react");
7
+ const react_2 = __importDefault(require("react"));
8
+ const client_1 = require("react-dom/client");
9
+ const server_1 = require("react-dom/server");
10
+ const use_is_hydrated_1 = require("./use-is-hydrated");
11
+ function Probe(props) {
12
+ const isHydrated = (0, use_is_hydrated_1.useIsHydrated)();
13
+ props.onRender(isHydrated);
14
+ return react_2.default.createElement("span", null, isHydrated ? "client" : "server");
15
+ }
16
+ test("is false while rendering on the server", () => {
17
+ expect((0, server_1.renderToString)(react_2.default.createElement(Probe, { onRender: jest.fn() }))).toContain("server");
18
+ });
19
+ test("is false while hydrating, then true", async () => {
20
+ const container = document.createElement("div");
21
+ container.innerHTML = (0, server_1.renderToString)(react_2.default.createElement(Probe, { onRender: jest.fn() }));
22
+ const onRender = jest.fn();
23
+ await (0, react_1.act)(async () => {
24
+ (0, client_1.hydrateRoot)(container, react_2.default.createElement(Probe, { onRender: onRender }));
25
+ });
26
+ expect(onRender.mock.calls.map(([isHydrated]) => isHydrated)).toEqual([false, true]);
27
+ expect(container.textContent).toBe("client");
28
+ });
29
+ test("is true from the first render of a component mounted on the client", () => {
30
+ const onRender = jest.fn();
31
+ (0, react_1.render)(react_2.default.createElement(Probe, { onRender: onRender }));
32
+ expect(onRender.mock.calls.map(([isHydrated]) => isHydrated)).toEqual([true]);
33
+ });
@@ -1 +1,6 @@
1
+ /**
2
+ * @deprecated Use `useIsHydrated` (`@uxf/core-react/hooks/use-is-hydrated`) to render something only in the browser:
3
+ * it is true from the first render of a component mounted on the client, where this costs an extra commit and a
4
+ * flash of the fallback. Keep this only where the code needs effects to have run, i.e. refs attached.
5
+ */
1
6
  export declare function useIsMounted(): boolean;
@@ -2,6 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useIsMounted = useIsMounted;
4
4
  const react_1 = require("react");
5
+ /**
6
+ * @deprecated Use `useIsHydrated` (`@uxf/core-react/hooks/use-is-hydrated`) to render something only in the browser:
7
+ * it is true from the first render of a component mounted on the client, where this costs an extra commit and a
8
+ * flash of the fallback. Keep this only where the code needs effects to have run, i.e. refs attached.
9
+ */
5
10
  function useIsMounted() {
6
11
  const [isMounted, setIsMounted] = (0, react_1.useState)(false);
7
12
  (0, react_1.useEffect)(() => setIsMounted(true), []);
@@ -1,2 +1,6 @@
1
1
  import { useEffect } from "react";
2
+ /**
3
+ * @deprecated Use `useLayoutEffect`. This existed only to silence React's server warning "useLayoutEffect does
4
+ * nothing on the server", which React 19 removed; on the server `useLayoutEffect` now simply does not run.
5
+ */
2
6
  export declare const useIsomorphicLayoutEffect: typeof useEffect;
@@ -3,4 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useIsomorphicLayoutEffect = void 0;
4
4
  const is_browser_1 = require("@uxf/core/utils/is-browser");
5
5
  const react_1 = require("react");
6
+ /**
7
+ * @deprecated Use `useLayoutEffect`. This existed only to silence React's server warning "useLayoutEffect does
8
+ * nothing on the server", which React 19 removed; on the server `useLayoutEffect` now simply does not run.
9
+ */
6
10
  exports.useIsomorphicLayoutEffect = is_browser_1.isBrowser ? react_1.useLayoutEffect : react_1.useEffect;
package/hooks/use-key.js CHANGED
@@ -8,20 +8,21 @@ const createKeyPredicate = (keyFilter) => typeof keyFilter === "function"
8
8
  ? (e) => e.key === keyFilter
9
9
  : () => false;
10
10
  function useKey(keyFilter, callback, { disabled, targetRef, type = "keydown" } = {}) {
11
+ // An effect event, so an inline `callback` or `keyFilter` does not re-attach the listener on every render.
12
+ const onKey = (0, react_1.useEffectEvent)((e) => {
13
+ if (createKeyPredicate(keyFilter)(e)) {
14
+ callback(e);
15
+ }
16
+ });
17
+ // No dependency array: the target can mount, unmount or be replaced after the hook mounted, and
18
+ // `targetRef.current` is only readable after a commit. Re-attaching is cheap, the callback is an effect event.
11
19
  (0, react_1.useEffect)(() => {
12
20
  if (disabled) {
13
21
  return;
14
22
  }
15
23
  const thisNode = (targetRef ? targetRef.current : document);
16
- const predicate = createKeyPredicate(keyFilter);
17
- const handler = (e) => {
18
- if (predicate(e)) {
19
- callback(e);
20
- }
21
- };
22
- thisNode === null || thisNode === void 0 ? void 0 : thisNode.addEventListener(type, handler);
23
- return () => {
24
- thisNode === null || thisNode === void 0 ? void 0 : thisNode.removeEventListener(type, handler);
25
- };
26
- }, [callback, disabled, keyFilter, targetRef, type]);
24
+ const controller = new AbortController();
25
+ thisNode === null || thisNode === void 0 ? void 0 : thisNode.addEventListener(type, (e) => onKey(e), { signal: controller.signal });
26
+ return () => controller.abort();
27
+ });
27
28
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const react_1 = require("@testing-library/react");
37
+ const react_2 = __importStar(require("react"));
38
+ const use_key_1 = require("./use-key");
39
+ function Probe(props) {
40
+ const ref = (0, react_2.useRef)(null);
41
+ const [isOpen, setIsOpen] = (0, react_2.useState)(false);
42
+ (0, use_key_1.useKey)("Escape", () => props.onKey(), { targetRef: ref });
43
+ return (react_2.default.createElement(react_2.default.Fragment, null,
44
+ react_2.default.createElement("button", { onClick: () => setIsOpen(true) }, "open"),
45
+ isOpen && react_2.default.createElement("div", { "data-testid": "t", ref: ref, tabIndex: -1 })));
46
+ }
47
+ test("listens on a target that appears after mount", () => {
48
+ const onKey = jest.fn();
49
+ const { getByText, getByTestId } = (0, react_1.render)(react_2.default.createElement(Probe, { onKey: onKey }));
50
+ (0, react_1.act)(() => getByText("open").click());
51
+ react_1.fireEvent.keyDown(getByTestId("t"), { key: "Escape" });
52
+ expect(onKey).toHaveBeenCalledTimes(1);
53
+ });
54
+ function Toggle(props) {
55
+ const ref = (0, react_2.useRef)(null);
56
+ (0, use_key_1.useKey)("Escape", () => props.onKey(), { targetRef: ref });
57
+ return props.isA ? react_2.default.createElement("div", { "data-testid": "a", ref: ref }) : react_2.default.createElement("span", { "data-testid": "b", ref: ref });
58
+ }
59
+ test("follows the target when the element is replaced", () => {
60
+ const onKey = jest.fn();
61
+ const { rerender, getByTestId } = (0, react_1.render)(react_2.default.createElement(Toggle, { isA: true, onKey: onKey }));
62
+ rerender(react_2.default.createElement(Toggle, { isA: false, onKey: onKey }));
63
+ react_1.fireEvent.keyDown(getByTestId("b"), { key: "Escape" });
64
+ expect(onKey).toHaveBeenCalledTimes(1);
65
+ });
@@ -1 +1,6 @@
1
+ /**
2
+ * @deprecated Writes `ref.current` during render, which React 19 asks not to do: a render that never commits
3
+ * leaves its value behind. To read the latest props or state from an effect or a listener it registers, use
4
+ * `useEffectEvent`; for a value read during render, use the value itself.
5
+ */
1
6
  export declare function useLatest<T>(current: T): import("react").RefObject<T>;
@@ -2,6 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useLatest = useLatest;
4
4
  const react_1 = require("react");
5
+ /**
6
+ * @deprecated Writes `ref.current` during render, which React 19 asks not to do: a render that never commits
7
+ * leaves its value behind. To read the latest props or state from an effect or a listener it registers, use
8
+ * `useEffectEvent`; for a value read during render, use the value itself.
9
+ */
5
10
  function useLatest(current) {
6
11
  const storedValue = (0, react_1.useRef)(current);
7
12
  storedValue.current = current;
@@ -1,2 +1,11 @@
1
1
  export type UseMediaQueryCallback = (isMatching: boolean, mediaQueryString: string) => void;
2
- export declare function useMediaQuery(mediaQueryString: string, callback?: UseMediaQueryCallback, isSSR?: boolean): boolean;
2
+ /**
3
+ * Whether `mediaQueryString` matches, read through `useSyncExternalStore`: false on the server and during hydration,
4
+ * the real value from the first render of a component mounted on the client, and updated on every change.
5
+ */
6
+ export declare function useMediaQuery(mediaQueryString: string, callback?: UseMediaQueryCallback): boolean;
7
+ /**
8
+ * @deprecated `isSSR` is ignored. It opted client-only components out of the hydration-safe `false`; the hook now
9
+ * reads the real value whenever it is not hydrating. Drop the argument.
10
+ */
11
+ export declare function useMediaQuery(mediaQueryString: string, callback: UseMediaQueryCallback | undefined, isSSR: boolean | undefined): boolean;