@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
@@ -3,25 +3,24 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.useMediaQuery = useMediaQuery;
5
5
  const react_1 = require("react");
6
- const use_latest_1 = require("@uxf/core-react/hooks/use-latest");
7
- function useMediaQuery(mediaQueryString, callback, isSSR = true) {
8
- const [isMatching, setIsMatching] = (0, react_1.useState)(isSSR ? false : window.matchMedia(mediaQueryString).matches);
9
- const latestCallback = (0, use_latest_1.useLatest)(callback);
10
- (0, react_1.useEffect)(() => {
6
+ function useMediaQuery(mediaQueryString, callback) {
7
+ const subscribe = (0, react_1.useCallback)((onStoreChange) => {
11
8
  const controller = new AbortController();
12
- const mqList = window.matchMedia(mediaQueryString);
13
- function handler(matches, media) {
14
- var _a;
15
- setIsMatching(matches);
16
- (_a = latestCallback.current) === null || _a === void 0 ? void 0 : _a.call(latestCallback, matches, media);
17
- }
18
- handler(mqList.matches, mqList.media);
19
- mqList.addEventListener("change", (e) => handler(e.matches, e.media), {
9
+ window.matchMedia(mediaQueryString).addEventListener("change", onStoreChange, {
20
10
  signal: controller.signal,
21
11
  });
22
- return () => {
23
- controller.abort();
24
- };
25
- }, [latestCallback, mediaQueryString]);
12
+ return () => controller.abort();
13
+ }, [mediaQueryString]);
14
+ const isMatching = (0, react_1.useSyncExternalStore)(subscribe, () => window.matchMedia(mediaQueryString).matches, () => false);
15
+ // The callback keeps its own subscription, so it hears the real value on mount and every change after, and
16
+ // not the `false` a hydrating render reports.
17
+ const onChange = (0, react_1.useEffectEvent)((matches, media) => callback === null || callback === void 0 ? void 0 : callback(matches, media));
18
+ (0, react_1.useEffect)(() => {
19
+ const controller = new AbortController();
20
+ const mqList = window.matchMedia(mediaQueryString);
21
+ onChange(mqList.matches, mqList.media);
22
+ mqList.addEventListener("change", (e) => onChange(e.matches, e.media), { signal: controller.signal });
23
+ return () => controller.abort();
24
+ }, [mediaQueryString]);
26
25
  return isMatching;
27
26
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
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 server_1 = require("react-dom/server");
9
+ const use_media_query_1 = require("./use-media-query");
10
+ const originalMatchMedia = window.matchMedia;
11
+ function mockMatchMedia(initiallyMatches) {
12
+ let matches = initiallyMatches;
13
+ const listeners = new Set();
14
+ window.matchMedia = ((query) => ({
15
+ get matches() {
16
+ return matches;
17
+ },
18
+ media: query,
19
+ addEventListener: (_type, listener) => listeners.add(listener),
20
+ removeEventListener: (_type, listener) => listeners.delete(listener),
21
+ }));
22
+ return {
23
+ change(next) {
24
+ matches = next;
25
+ listeners.forEach((listener) => listener({ matches: next, media: "(min-width: 640px)" }));
26
+ },
27
+ };
28
+ }
29
+ afterEach(() => {
30
+ window.matchMedia = originalMatchMedia;
31
+ });
32
+ test("a component mounted on the client gets the real value in its first render", () => {
33
+ mockMatchMedia(true);
34
+ const values = [];
35
+ (0, react_1.renderHook)(() => values.push((0, use_media_query_1.useMediaQuery)("(min-width: 640px)")));
36
+ expect(values.at(0)).toBe(true);
37
+ });
38
+ test("renders false on the server", () => {
39
+ function Probe() {
40
+ return react_2.default.createElement("span", null, String((0, use_media_query_1.useMediaQuery)("(min-width: 640px)")));
41
+ }
42
+ expect((0, server_1.renderToString)(react_2.default.createElement(Probe, null))).toContain("false");
43
+ });
44
+ test("follows changes and reports them, and the initial value, to the latest callback", () => {
45
+ const media = mockMatchMedia(false);
46
+ const first = jest.fn();
47
+ const latest = jest.fn();
48
+ const { result, rerender } = (0, react_1.renderHook)((props) => (0, use_media_query_1.useMediaQuery)("(min-width: 640px)", props.callback), { initialProps: { callback: first } });
49
+ rerender({ callback: latest });
50
+ (0, react_1.act)(() => media.change(true));
51
+ expect(result.current).toBe(true);
52
+ expect(first).toHaveBeenCalledWith(false, "(min-width: 640px)");
53
+ expect(latest).toHaveBeenCalledWith(true, "(min-width: 640px)");
54
+ expect(first).toHaveBeenCalledTimes(1);
55
+ });
@@ -21,9 +21,10 @@ function useMinWindowWidth(minWidth, debounce = 0) {
21
21
  }
22
22
  };
23
23
  stateHandler();
24
- window.addEventListener("resize", handler);
24
+ const controller = new AbortController();
25
+ window.addEventListener("resize", handler, { signal: controller.signal });
25
26
  return () => {
26
- window.removeEventListener("resize", handler);
27
+ controller.abort();
27
28
  window.clearTimeout(timer);
28
29
  };
29
30
  }, [debounce, minWidth, setState]);
@@ -1,2 +1,3 @@
1
1
  import { EffectCallback } from "react";
2
+ /** Runs `effect` when the component unmounts, in the version from the latest render. */
2
3
  export declare function useOnUnmount(effect: EffectCallback): void;
@@ -2,13 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useOnUnmount = useOnUnmount;
4
4
  const react_1 = require("react");
5
+ /** Runs `effect` when the component unmounts, in the version from the latest render. */
5
6
  function useOnUnmount(effect) {
6
- const effectRef = (0, react_1.useRef)(effect);
7
- // update the ref each render so if it changed the newest callback will be invoked
8
- effectRef.current = effect;
9
- (0, react_1.useEffect)(() => {
10
- return () => {
11
- effectRef.current();
12
- };
7
+ const onUnmount = (0, react_1.useEffectEvent)(effect);
8
+ (0, react_1.useEffect)(() => () => {
9
+ onUnmount();
13
10
  }, []);
14
11
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const react_1 = require("@testing-library/react");
4
+ const use_on_unmount_1 = require("./use-on-unmount");
5
+ test("runs the effect from the latest render, once, on unmount", () => {
6
+ const first = jest.fn();
7
+ const latest = jest.fn();
8
+ const { rerender, unmount } = (0, react_1.renderHook)((props) => (0, use_on_unmount_1.useOnUnmount)(props.effect), {
9
+ initialProps: { effect: first },
10
+ });
11
+ rerender({ effect: latest });
12
+ expect(latest).not.toHaveBeenCalled();
13
+ unmount();
14
+ expect(first).not.toHaveBeenCalled();
15
+ expect(latest).toHaveBeenCalledTimes(1);
16
+ });
@@ -1,2 +1,10 @@
1
1
  import { DependencyList, EffectCallback } from "react";
2
+ /**
3
+ * Runs `effect` when `deps` change, not on mount.
4
+ *
5
+ * It compares the deps with those of the previous run instead of skipping "the first run": StrictMode runs a mount
6
+ * effect twice in development, and a first-run flag let the second one through. A consequence: an effect that is
7
+ * reconnected with the same deps (StrictMode, an `<Activity>` hidden and shown again) does not run either, and its
8
+ * cleanup has run. Work that must survive that, like a pending timer, belongs in a plain `useEffect`.
9
+ */
2
10
  export declare function useOnUpdate(effect: EffectCallback, deps: DependencyList): void;
@@ -2,11 +2,23 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useOnUpdate = useOnUpdate;
4
4
  const react_1 = require("react");
5
+ function haveSameDeps(a, b) {
6
+ return a.length === b.length && a.every((dep, index) => Object.is(dep, b.at(index)));
7
+ }
8
+ /**
9
+ * Runs `effect` when `deps` change, not on mount.
10
+ *
11
+ * It compares the deps with those of the previous run instead of skipping "the first run": StrictMode runs a mount
12
+ * effect twice in development, and a first-run flag let the second one through. A consequence: an effect that is
13
+ * reconnected with the same deps (StrictMode, an `<Activity>` hidden and shown again) does not run either, and its
14
+ * cleanup has run. Work that must survive that, like a pending timer, belongs in a plain `useEffect`.
15
+ */
5
16
  function useOnUpdate(effect, deps) {
6
- const firstRun = (0, react_1.useRef)(true);
17
+ const previousDeps = (0, react_1.useRef)(null);
7
18
  (0, react_1.useEffect)(() => {
8
- if (firstRun.current) {
9
- firstRun.current = false;
19
+ const previous = previousDeps.current;
20
+ previousDeps.current = deps;
21
+ if (previous === null || haveSameDeps(previous, deps)) {
10
22
  return;
11
23
  }
12
24
  return effect();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
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_on_update_1 = require("./use-on-update");
39
+ function Probe(props) {
40
+ const effect = props.effect;
41
+ const value = props.value;
42
+ // `effect` is the same jest.fn on every render, so only `value` decides.
43
+ (0, use_on_update_1.useOnUpdate)(() => effect(value), [effect, value]);
44
+ return null;
45
+ }
46
+ test("does not run on mount", () => {
47
+ const effect = jest.fn();
48
+ (0, react_1.render)(react_2.default.createElement(Probe, { effect: effect, value: 1 }));
49
+ expect(effect).not.toHaveBeenCalled();
50
+ });
51
+ test("does not run on mount under StrictMode either", () => {
52
+ const effect = jest.fn();
53
+ (0, react_1.render)(react_2.default.createElement(react_2.StrictMode, null,
54
+ react_2.default.createElement(Probe, { effect: effect, value: 1 })));
55
+ expect(effect).not.toHaveBeenCalled();
56
+ });
57
+ test("runs when a dependency changes, and cleans up before the next run", () => {
58
+ const cleanup = jest.fn();
59
+ const effect = jest.fn(() => cleanup);
60
+ const { rerender } = (0, react_1.render)(react_2.default.createElement(react_2.StrictMode, null,
61
+ react_2.default.createElement(Probe, { effect: effect, value: 1 })));
62
+ rerender(react_2.default.createElement(react_2.StrictMode, null,
63
+ react_2.default.createElement(Probe, { effect: effect, value: 2 })));
64
+ expect(effect).toHaveBeenCalledTimes(1);
65
+ rerender(react_2.default.createElement(react_2.StrictMode, null,
66
+ react_2.default.createElement(Probe, { effect: effect, value: 3 })));
67
+ expect(cleanup).toHaveBeenCalledTimes(1);
68
+ expect(effect).toHaveBeenCalledTimes(2);
69
+ });
70
+ test("does not run on a re-render with the same dependencies", () => {
71
+ const effect = jest.fn();
72
+ const { rerender } = (0, react_1.render)(react_2.default.createElement(Probe, { effect: effect, value: 1 }));
73
+ rerender(react_2.default.createElement(Probe, { effect: effect, value: 1 }));
74
+ expect(effect).not.toHaveBeenCalled();
75
+ });
@@ -1 +1,6 @@
1
+ /**
2
+ * @deprecated Returns a ref whose only use is reading `.current` during render, which React 19 asks not to do.
3
+ * To react to a change, keep the previous value in state and compare during render
4
+ * (https://react.dev/reference/react/useState#storing-information-from-previous-renders).
5
+ */
1
6
  export declare function usePrevious<T>(current: T): import("react").RefObject<T>;
@@ -2,6 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.usePrevious = usePrevious;
4
4
  const react_1 = require("react");
5
+ /**
6
+ * @deprecated Returns a ref whose only use is reading `.current` during render, which React 19 asks not to do.
7
+ * To react to a change, keep the previous value in state and compare during render
8
+ * (https://react.dev/reference/react/useState#storing-information-from-previous-renders).
9
+ */
5
10
  function usePrevious(current) {
6
11
  const storedValue = (0, react_1.useRef)(current);
7
12
  (0, react_1.useEffect)(() => {
@@ -11,11 +11,9 @@ function useWindowScroll() {
11
11
  y: window.scrollY,
12
12
  });
13
13
  handler();
14
- window.addEventListener("scroll", handler, {
15
- capture: false,
16
- passive: true,
17
- });
18
- return () => window.removeEventListener("scroll", handler);
14
+ const controller = new AbortController();
15
+ window.addEventListener("scroll", handler, { capture: false, passive: true, signal: controller.signal });
16
+ return () => controller.abort();
19
17
  }, [setState]);
20
18
  return state;
21
19
  }
@@ -42,8 +42,10 @@ describe("useWindowScroll", () => {
42
42
  expect(result.current).toEqual({ x: 100, y: 200 });
43
43
  });
44
44
  it("should clean up the event listener on unmount", () => {
45
+ var _a, _b;
45
46
  const { unmount } = (0, react_1.renderHook)(() => (0, use_window_scroll_1.useWindowScroll)());
46
47
  unmount();
47
- expect(window.removeEventListener).toHaveBeenCalledWith("scroll", expect.any(Function));
48
+ const listenerOptions = (_a = window.addEventListener.mock.calls.find(([type]) => type === "scroll")) === null || _a === void 0 ? void 0 : _a[2];
49
+ expect((_b = listenerOptions === null || listenerOptions === void 0 ? void 0 : listenerOptions.signal) === null || _b === void 0 ? void 0 : _b.aborted).toBe(true);
48
50
  });
49
51
  });
@@ -11,8 +11,9 @@ function useWindowSize() {
11
11
  height: window.innerHeight,
12
12
  });
13
13
  handler();
14
- window.addEventListener("resize", handler);
15
- return () => window.removeEventListener("resize", handler);
14
+ const controller = new AbortController();
15
+ window.addEventListener("resize", handler, { signal: controller.signal });
16
+ return () => controller.abort();
16
17
  }, [setState]);
17
18
  return state;
18
19
  }
@@ -31,8 +31,10 @@ describe("useWindowSize", () => {
31
31
  expect(result.current).toEqual({ width: 1024, height: 768 });
32
32
  });
33
33
  it("should clean up the event listener on unmount", () => {
34
+ var _a, _b;
34
35
  const { unmount } = (0, react_1.renderHook)(() => (0, use_window_size_1.useWindowSize)());
35
36
  unmount();
36
- expect(window.removeEventListener).toHaveBeenCalledWith("resize", expect.any(Function));
37
+ const listenerOptions = (_a = window.addEventListener.mock.calls.find(([type]) => type === "resize")) === null || _a === void 0 ? void 0 : _a[2];
38
+ expect((_b = listenerOptions === null || listenerOptions === void 0 ? void 0 : listenerOptions.signal) === null || _b === void 0 ? void 0 : _b.aborted).toBe(true);
37
39
  });
38
40
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxf/core-react",
3
- "version": "13.0.0",
3
+ "version": "14.0.0",
4
4
  "description": "UXF Core",
5
5
  "author": "UX Fans s.r.o",
6
6
  "license": "MIT",
@@ -12,14 +12,20 @@
12
12
  "typecheck": "tsc --noEmit"
13
13
  },
14
14
  "peerDependencies": {
15
- "@uxf/core": "13.0.0",
15
+ "@uxf/core": "14.0.0",
16
+ "next": ">=16.0.0",
16
17
  "react": "^19.3.0",
17
18
  "react-dom": "^19.3.0"
18
19
  },
20
+ "peerDependenciesMeta": {
21
+ "next": {
22
+ "optional": true
23
+ }
24
+ },
19
25
  "devDependencies": {
20
26
  "@types/react": "19.3.0",
21
27
  "@types/react-dom": "19.3.0",
22
- "@uxf/core": "13.0.0",
28
+ "@uxf/core": "14.0.0",
23
29
  "react": "19.3.0",
24
30
  "react-dom": "19.3.0"
25
31
  }
@@ -53,6 +53,8 @@ function rotateXYByAngle(pos, angle) {
53
53
  return [x, y];
54
54
  }
55
55
  function getHandlers(set, handlerProps) {
56
+ // The document listeners of the mouse drag in progress, removed together on mouseup or unmount.
57
+ let mouseDrag;
56
58
  const onStart = (event) => {
57
59
  const isTouch = "touches" in event;
58
60
  // if more than a single touch don't track, for now...
@@ -63,10 +65,12 @@ function getHandlers(set, handlerProps) {
63
65
  var _a;
64
66
  // setup mouse listeners on document to track swipe since swipe can leave container
65
67
  if (props.trackMouse && !isTouch) {
68
+ mouseDrag === null || mouseDrag === void 0 ? void 0 : mouseDrag.abort();
69
+ mouseDrag = new AbortController();
66
70
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
67
- document.addEventListener(mouseMove, onMove);
71
+ document.addEventListener(mouseMove, onMove, { signal: mouseDrag.signal });
68
72
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
69
- document.addEventListener(mouseUp, onUp);
73
+ document.addEventListener(mouseUp, onUp, { signal: mouseDrag.signal });
70
74
  }
71
75
  // eslint-disable-next-line no-restricted-syntax
72
76
  const { clientX, clientY } = isTouch ? event.touches[0] : event;
@@ -174,10 +178,8 @@ function getHandlers(set, handlerProps) {
174
178
  });
175
179
  };
176
180
  const cleanUpMouse = () => {
177
- // safe to just call removeEventListener
178
- document.removeEventListener(mouseMove, onMove);
179
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
180
- document.removeEventListener(mouseUp, onUp);
181
+ mouseDrag === null || mouseDrag === void 0 ? void 0 : mouseDrag.abort();
182
+ mouseDrag = undefined;
181
183
  };
182
184
  const onUp = (e) => {
183
185
  cleanUpMouse();
@@ -217,17 +219,16 @@ function getHandlers(set, handlerProps) {
217
219
  ],
218
220
  [touchEnd, onEnd, baseOptions],
219
221
  ];
220
- tls.forEach(([e, h, o]) => el.addEventListener(e, h, o));
221
- // return properly scoped cleanup method for removing listeners, options not required
222
- cleanup = () => tls.forEach(([e, h]) => el.removeEventListener(e, h));
222
+ const controller = new AbortController();
223
+ tls.forEach(([e, h, o]) => el.addEventListener(e, h, { ...o, signal: controller.signal }));
224
+ cleanup = () => controller.abort();
223
225
  }
224
226
  return cleanup;
225
227
  };
226
228
  const onRef = (el) => {
227
- // "inline" ref functions are called twice on render, once with null then again with DOM element
228
- // ignore null here
229
+ // With the cleanup returned below, React 19 does not call the ref with null any more.
229
230
  if (el === null) {
230
- return;
231
+ return undefined;
231
232
  }
232
233
  set((state, props) => {
233
234
  // if the same DOM el as previous just return state
@@ -247,6 +248,15 @@ function getHandlers(set, handlerProps) {
247
248
  // store event attached DOM el for comparison, clean up, and re-attachment
248
249
  return { ...state, el, ...addState };
249
250
  });
251
+ // The element is detached (removed, swapped, or the component unmounts): stop listening on it.
252
+ return () => set((state) => {
253
+ var _a;
254
+ if (state.el !== el) {
255
+ return state;
256
+ }
257
+ (_a = state.cleanUpTouch) === null || _a === void 0 ? void 0 : _a.call(state);
258
+ return { ...state, el: undefined, cleanUpTouch: undefined };
259
+ });
250
260
  };
251
261
  // set ref callback to attach touch event listeners
252
262
  const output = {
@@ -256,7 +266,7 @@ function getHandlers(set, handlerProps) {
256
266
  if (handlerProps.trackMouse) {
257
267
  output.onMouseDown = onStart;
258
268
  }
259
- return [output, attachTouch];
269
+ return [output, attachTouch, cleanUpMouse];
260
270
  }
261
271
  function updateTransientState(state, props, previousProps, attachTouch) {
262
272
  // if trackTouch is off or there is no el, then remove handlers if necessary and exit
@@ -289,30 +299,35 @@ function updateTransientState(state, props, previousProps, attachTouch) {
289
299
  }
290
300
  return state;
291
301
  }
292
- function useSwipeable(options) {
293
- const transientState = (0, react_1.useRef)({ ...initialState });
294
- const transientProps = (0, react_1.useRef)({
295
- ...defaultProps,
296
- });
297
- // track previous rendered props
298
- const previousProps = (0, react_1.useRef)({
299
- ...transientProps.current,
300
- });
301
- previousProps.current = { ...transientProps.current };
302
- // update current render props & defaults
303
- transientProps.current = {
304
- ...defaultProps,
305
- ...options,
306
- };
302
+ function withDefaults(options) {
303
+ const props = { ...defaultProps, ...options };
307
304
  // Force defaults for config properties
308
305
  let defaultKey;
309
306
  for (defaultKey in defaultProps) {
310
307
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
311
- if (transientProps.current[defaultKey] === void 0) {
312
- transientProps.current[defaultKey] = defaultProps[defaultKey];
308
+ if (props[defaultKey] === void 0) {
309
+ props[defaultKey] = defaultProps[defaultKey];
313
310
  }
314
311
  }
315
- const [handlers, attachTouch] = (0, react_1.useMemo)(() => getHandlers((stateSetter) => (transientState.current = stateSetter(transientState.current, transientProps.current)), { trackMouse: options.trackMouse }), [options.trackMouse]);
316
- transientState.current = updateTransientState(transientState.current, transientProps.current, previousProps.current, attachTouch);
312
+ return props;
313
+ }
314
+ function useSwipeable(options) {
315
+ const transientState = (0, react_1.useRef)({ ...initialState });
316
+ // The props of the last commit, read by the handlers when an event fires. Written after commit, never during
317
+ // render, together with attaching or detaching the touch listeners: a render React discards must leave
318
+ // neither its props nor its listeners behind.
319
+ // Starts with this render's props: the ref callback attaches the touch listeners during the first commit,
320
+ // before any effect, and must already see them.
321
+ const [initialProps] = (0, react_1.useState)(() => withDefaults(options));
322
+ const transientProps = (0, react_1.useRef)(initialProps);
323
+ const [handlers, attachTouch, cleanUpMouse] = (0, react_1.useMemo)(() => getHandlers((stateSetter) => (transientState.current = stateSetter(transientState.current, transientProps.current)), { trackMouse: options.trackMouse }), [options.trackMouse]);
324
+ (0, react_1.useLayoutEffect)(() => {
325
+ const previousProps = transientProps.current;
326
+ transientProps.current = withDefaults(options);
327
+ transientState.current = updateTransientState(transientState.current, transientProps.current, previousProps, attachTouch);
328
+ });
329
+ // On unmount, in the middle of a mouse drag: the listeners on the document. The element's own touch listeners
330
+ // go with the ref's cleanup.
331
+ (0, react_1.useLayoutEffect)(() => cleanUpMouse, [cleanUpMouse]);
317
332
  return handlers;
318
333
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,59 @@
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 use_swipeable_1 = require("./use-swipeable");
9
+ function Swipeable(props) {
10
+ const handlers = (0, use_swipeable_1.useSwipeable)(props);
11
+ return props.isShown === false ? null : react_2.default.createElement("div", { ...handlers }, "swipe");
12
+ }
13
+ function swipeLeft(element) {
14
+ const touch = (clientX) => ({ touches: [{ clientX, clientY: 0 }], timeStamp: 1 });
15
+ react_1.fireEvent.touchStart(element, touch(200));
16
+ react_1.fireEvent.touchMove(element, touch(100));
17
+ react_1.fireEvent.touchMove(element, touch(0));
18
+ react_1.fireEvent.touchEnd(element, { touches: [] });
19
+ }
20
+ test("a swipe reaches the latest callback", () => {
21
+ const first = jest.fn();
22
+ const latest = jest.fn();
23
+ const { getByText, rerender } = (0, react_1.render)(react_2.default.createElement(Swipeable, { onSwipedLeft: first }));
24
+ rerender(react_2.default.createElement(Swipeable, { onSwipedLeft: latest }));
25
+ swipeLeft(getByText("swipe"));
26
+ expect(first).not.toHaveBeenCalled();
27
+ expect(latest).toHaveBeenCalledTimes(1);
28
+ });
29
+ test("unmounting in the middle of a mouse drag stops tracking the mouse on the document", () => {
30
+ const onSwiping = jest.fn();
31
+ const { getByText, unmount } = (0, react_1.render)(react_2.default.createElement(Swipeable, { onSwiping: onSwiping, trackMouse: true }));
32
+ react_1.fireEvent.mouseDown(getByText("swipe"), { clientX: 0, clientY: 0 });
33
+ unmount();
34
+ react_1.fireEvent.mouseMove(document, { clientX: 100, clientY: 0 });
35
+ expect(onSwiping).not.toHaveBeenCalled();
36
+ });
37
+ test("after unmounting, touches on the element no longer count", () => {
38
+ const onSwiped = jest.fn();
39
+ const { getByText, unmount } = (0, react_1.render)(react_2.default.createElement(Swipeable, { onSwiped: onSwiped }));
40
+ const element = getByText("swipe");
41
+ unmount();
42
+ swipeLeft(element);
43
+ expect(onSwiped).not.toHaveBeenCalled();
44
+ });
45
+ test("an element removed while the hook stays mounted stops counting touches", () => {
46
+ const onSwiped = jest.fn();
47
+ const { getByText, rerender } = (0, react_1.render)(react_2.default.createElement(Swipeable, { onSwiped: onSwiped }));
48
+ const element = getByText("swipe");
49
+ rerender(react_2.default.createElement(Swipeable, { isShown: false, onSwiped: onSwiped }));
50
+ swipeLeft(element);
51
+ expect(onSwiped).not.toHaveBeenCalled();
52
+ });
53
+ test("switching trackTouch off after mount stops counting touches", () => {
54
+ const onSwiped = jest.fn();
55
+ const { getByText, rerender } = (0, react_1.render)(react_2.default.createElement(Swipeable, { onSwiped: onSwiped }));
56
+ rerender(react_2.default.createElement(Swipeable, { onSwiped: onSwiped, trackTouch: false }));
57
+ swipeLeft(getByText("swipe"));
58
+ expect(onSwiped).not.toHaveBeenCalled();
59
+ });
@@ -2,5 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.replaceVariables = replaceVariables;
4
4
  function replaceVariables(translation, options) {
5
- return Object.keys(options).reduce((result, variable) => result.replace(new RegExp(`{{${variable}}}`, "g"), options[variable]), translation);
5
+ return Object.keys(options).reduce(
6
+ // A literal search instead of a RegExp built from the name, and a replacer function instead of a string, so
7
+ // that neither the name nor the value is interpreted (`.` in a name, `$&` or `$$` in a value).
8
+ (result, variable) => result.replaceAll(`{{${variable}}}`, () => String(options[variable])), translation);
6
9
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const replace_variables_1 = require("./replace-variables");
4
+ test("replaces every occurrence of a variable", () => {
5
+ expect((0, replace_variables_1.replaceVariables)("{{name}} and {{name}}", { name: "Eva" })).toBe("Eva and Eva");
6
+ });
7
+ test('puts "$" in a value literally', () => {
8
+ expect((0, replace_variables_1.replaceVariables)("Price: {{price}}", { price: "$$5" })).toBe("Price: $$5");
9
+ expect((0, replace_variables_1.replaceVariables)("Hi {{name}}", { name: "a$&b" })).toBe("Hi a$&b");
10
+ });
11
+ test("treats a variable name as text, not as a regular expression", () => {
12
+ expect((0, replace_variables_1.replaceVariables)("{{a.b}} {{axb}}", { "a.b": "1" })).toBe("1 {{axb}}");
13
+ });
@@ -1,2 +0,0 @@
1
- import { ReactNode } from "react";
2
- export declare function ViewportHeightPolyfill(): ReactNode;