@fibery/react 1.6.0 → 2.0.1

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 (64) hide show
  1. package/lib/compose-event-handlers.d.ts +6 -0
  2. package/lib/compose-event-handlers.js +9 -0
  3. package/lib/create-context.d.ts +6 -0
  4. package/lib/create-context.js +18 -0
  5. package/lib/get-ref-value.d.ts +6 -0
  6. package/lib/get-ref-value.js +5 -0
  7. package/lib/has-non-empty-child.d.ts +5 -0
  8. package/lib/has-non-empty-child.js +6 -0
  9. package/lib/prevent-default.d.ts +6 -0
  10. package/lib/prevent-default.js +6 -0
  11. package/lib/react-node-to-string.d.ts +10 -0
  12. package/lib/react-node-to-string.js +24 -0
  13. package/lib/shared-query-client-provider.d.ts +5 -0
  14. package/lib/shared-query-client-provider.js +5 -0
  15. package/lib/stop-propagation.d.ts +4 -0
  16. package/lib/stop-propagation.js +6 -0
  17. package/lib/use-callback-ref.d.ts +10 -0
  18. package/lib/use-callback-ref.js +17 -0
  19. package/lib/use-composed-refs.d.ts +10 -0
  20. package/lib/use-composed-refs.js +20 -0
  21. package/lib/use-controllable-state/index.d.ts +2 -0
  22. package/lib/use-controllable-state/index.js +2 -0
  23. package/lib/use-controllable-state/use-controllable-state.d.ts +17 -0
  24. package/lib/use-controllable-state/use-controllable-state.js +35 -0
  25. package/lib/use-drag.d.ts +25 -0
  26. package/lib/use-drag.js +78 -0
  27. package/lib/use-focus-outside.d.ts +13 -0
  28. package/lib/use-focus-outside.js +29 -0
  29. package/lib/use-is-mounted.d.ts +4 -0
  30. package/lib/use-is-mounted.js +15 -0
  31. package/lib/use-pointer-down-outside.d.ts +15 -0
  32. package/lib/use-pointer-down-outside.js +68 -0
  33. package/lib/use-previous.d.ts +4 -0
  34. package/lib/use-previous.js +11 -0
  35. package/lib/use-resize-observer.d.ts +14 -0
  36. package/lib/use-resize-observer.js +35 -0
  37. package/lib/use-restore-focus.d.ts +10 -0
  38. package/lib/use-restore-focus.js +26 -0
  39. package/lib/use-size.d.ts +14 -0
  40. package/lib/use-size.js +37 -0
  41. package/{src/wrap.tsx → lib/wrap.d.ts} +5 -20
  42. package/lib/wrap.js +28 -0
  43. package/package.json +17 -34
  44. package/src/compose-event-handlers.ts +0 -13
  45. package/src/create-context.ts +0 -21
  46. package/src/get-ref-value.ts +0 -5
  47. package/src/has-non-empty-child.ts +0 -5
  48. package/src/prevent-default.ts +0 -3
  49. package/src/react-node-to-string.ts +0 -37
  50. package/src/shared-query-client-provider.tsx +0 -7
  51. package/src/stop-propagation.ts +0 -3
  52. package/src/use-callback-ref.ts +0 -18
  53. package/src/use-composed-refs.ts +0 -27
  54. package/src/use-controllable-state/index.ts +0 -1
  55. package/src/use-controllable-state/use-controllable-state.test.ts +0 -46
  56. package/src/use-controllable-state/use-controllable-state.ts +0 -61
  57. package/src/use-drag.ts +0 -96
  58. package/src/use-focus-outside.ts +0 -34
  59. package/src/use-is-mounted.ts +0 -15
  60. package/src/use-pointer-down-outside.tsx +0 -80
  61. package/src/use-previous.ts +0 -9
  62. package/src/use-resize-observer.ts +0 -50
  63. package/src/use-restore-focus.ts +0 -31
  64. package/src/use-size.ts +0 -53
@@ -0,0 +1,14 @@
1
+ import { RefObject } from "react";
2
+ //#region src/use-size.d.ts
3
+ type Size = {
4
+ width: number;
5
+ height: number;
6
+ };
7
+ /**
8
+ * React hook for watching size changes of HTML elements
9
+ */
10
+ declare const useSize: <TargetElement extends HTMLElement>(
11
+ /** React ref created by `useRef()` or an HTML element */
12
+ target: RefObject<TargetElement> | TargetElement | null) => Size;
13
+ //#endregion
14
+ export { useSize };
@@ -0,0 +1,37 @@
1
+ import { getRefValue } from "./get-ref-value.js";
2
+ import { useResizeObserver } from "./use-resize-observer.js";
3
+ import { useLayoutEffect, useState } from "react";
4
+ //#region src/use-size.ts
5
+ const calculateSize = (element) => {
6
+ const rect = element?.getBoundingClientRect();
7
+ return {
8
+ width: rect?.width || 0,
9
+ height: rect?.height || 0
10
+ };
11
+ };
12
+ /**
13
+ * React hook for watching size changes of HTML elements
14
+ */
15
+ const useSize = (target) => {
16
+ const [size, setSize] = useState(() => {
17
+ const element = getRefValue(target);
18
+ return calculateSize(element);
19
+ });
20
+ useLayoutEffect(() => {
21
+ const element = getRefValue(target);
22
+ if (!element) return;
23
+ setSize(calculateSize(element));
24
+ }, [target]);
25
+ useResizeObserver(target, (entry) => {
26
+ setSize((oldSize) => {
27
+ const newSize = {
28
+ width: entry.borderBoxSize[0].inlineSize,
29
+ height: entry.borderBoxSize[0].blockSize
30
+ };
31
+ return newSize.width !== oldSize.width || newSize.height !== oldSize.height ? newSize : oldSize;
32
+ });
33
+ });
34
+ return size;
35
+ };
36
+ //#endregion
37
+ export { useSize };
@@ -1,12 +1,10 @@
1
+ //#region src/wrap.d.ts
1
2
  type OwnProps<Wrapper extends React.ElementType> = {
2
3
  if?: boolean;
3
4
  with: Wrapper;
4
5
  children: React.ReactNode;
5
6
  };
6
-
7
- type Props<Wrapper extends React.ElementType> = OwnProps<Wrapper> &
8
- Omit<React.ComponentPropsWithoutRef<Wrapper>, keyof OwnProps<Wrapper>>;
9
-
7
+ type Props<Wrapper extends React.ElementType> = OwnProps<Wrapper> & Omit<React.ComponentPropsWithoutRef<Wrapper>, keyof OwnProps<Wrapper>>;
10
8
  /**
11
9
  * React component to conditionally wrap children
12
10
  * WARNING!: use carefully since it causes re-mount of component when condition changes
@@ -24,19 +22,6 @@ type Props<Wrapper extends React.ElementType> = OwnProps<Wrapper> &
24
22
  * </Wrap>
25
23
  * ```
26
24
  */
27
- export const Wrap = <T extends React.ElementType>({
28
- if: condition,
29
- with: With,
30
- children,
31
- className,
32
- ...rest
33
- }: Props<T>): JSX.Element => {
34
- return condition ? (
35
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
- <With {...(rest as any)} className={className}>
37
- {children}
38
- </With>
39
- ) : (
40
- (children as JSX.Element)
41
- );
42
- };
25
+ declare const Wrap: <T extends React.ElementType>({ if: condition, with: With, children, className, ...rest }: Props<T>) => JSX.Element;
26
+ //#endregion
27
+ export { Wrap };
package/lib/wrap.js ADDED
@@ -0,0 +1,28 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ //#region src/wrap.tsx
3
+ /**
4
+ * React component to conditionally wrap children
5
+ * WARNING!: use carefully since it causes re-mount of component when condition changes
6
+ * @example
7
+ * pass react Element
8
+ * ```
9
+ * <Wrap if={clickable} with={AwesomeButton}>
10
+ * Hello
11
+ * </Wrap>
12
+ * ```
13
+ * or use html tag names
14
+ * ```
15
+ * <Wrap if={clickable} with="button">
16
+ * Hello
17
+ * </Wrap>
18
+ * ```
19
+ */
20
+ const Wrap = ({ if: condition, with: With, children, className, ...rest }) => {
21
+ return condition ? /* @__PURE__ */ jsx(With, {
22
+ ...rest,
23
+ className,
24
+ children
25
+ }) : children;
26
+ };
27
+ //#endregion
28
+ export { Wrap };
package/package.json CHANGED
@@ -1,46 +1,29 @@
1
1
  {
2
2
  "name": "@fibery/react",
3
- "version": "1.6.0",
4
- "private": false,
3
+ "version": "2.0.1",
5
4
  "license": "UNLICENSED",
6
5
  "files": [
7
- "src"
6
+ "lib"
8
7
  ],
9
8
  "type": "module",
9
+ "sideEffects": false,
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ "./src/use-controllable-state": {
13
+ "types": "./lib/use-controllable-state/index.d.ts",
14
+ "default": "./lib/use-controllable-state/index.js"
15
+ },
16
+ "./src/*": {
17
+ "types": "./lib/*.d.ts",
18
+ "default": "./lib/*.js"
19
+ }
20
+ },
10
21
  "dependencies": {
11
22
  "@tanstack/react-query": "5.62.7",
12
- "@fibery/helpers": "3.2.0"
13
- },
14
- "devDependencies": {
15
- "@testing-library/react": "16.3.1",
16
- "@testing-library/react-hooks": "8.0.1",
17
- "@types/react": "18.3.12",
18
- "@types/react-dom": "18.3.1",
19
- "react": "18.3.1",
20
- "react-dom": "18.3.1",
21
- "react-test-renderer": "18.3.1",
22
- "typescript": "rc"
23
+ "@fibery/helpers": "3.3.0"
23
24
  },
24
25
  "peerDependencies": {
25
- "react": "18.3.1"
26
- },
27
- "size-limit": [
28
- {
29
- "path": [
30
- "src/**/*.{ts,tsx,js,jsx,css}",
31
- "!src/**/*.test.*",
32
- "!src/**/__tests__/**"
33
- ],
34
- "limit": "8 kB"
35
- }
36
- ],
37
- "scripts": {
38
- "build": "pnpm run typecheck",
39
- "test": "../../scripts/test.sh",
40
- "test:ci": "../../scripts/test.sh --ci",
41
- "test:coverage": "../../scripts/test.sh --ci --coverage",
42
- "lint": "pnpm -w lint .",
43
- "typecheck": "../../scripts/typecheck.sh",
44
- "check": "../../scripts/check.sh"
26
+ "react": "18.3.1",
27
+ "react-dom": "18.3.1"
45
28
  }
46
29
  }
@@ -1,13 +0,0 @@
1
- export function composeEventHandlers<E>(
2
- originalEventHandler?: (event: E) => void,
3
- ourEventHandler?: (event: E) => void,
4
- {checkForDefaultPrevented = true} = {}
5
- ) {
6
- return function handleEvent(event: E) {
7
- originalEventHandler?.(event);
8
-
9
- if (checkForDefaultPrevented === false || !(event as unknown as Event).defaultPrevented) {
10
- ourEventHandler?.(event);
11
- }
12
- };
13
- }
@@ -1,21 +0,0 @@
1
- import * as React from "react";
2
- import type {Context} from "react";
3
-
4
- export const createContext = <CtxType>(
5
- displayName: string,
6
- defaultCtx?: CtxType
7
- ): [React.Provider<CtxType>, () => CtxType, Context<CtxType>] => {
8
- const Context = React.createContext(defaultCtx as CtxType);
9
-
10
- Context.displayName = displayName;
11
-
12
- function useContext() {
13
- const ctx = React.useContext(Context);
14
- if (ctx === undefined) {
15
- throw new Error(`${displayName} consumer must be used within ${displayName}.Provider`);
16
- }
17
- return ctx;
18
- }
19
-
20
- return [Context.Provider, useContext, Context];
21
- };
@@ -1,5 +0,0 @@
1
- import type {RefObject} from "react";
2
-
3
- /** Returns current value if refOrValue is RefObject otherwise returns itself */
4
- export const getRefValue = <Value>(refOrValue: RefObject<Value> | Value | null): Value | null =>
5
- refOrValue && typeof refOrValue === "object" && "current" in refOrValue ? refOrValue.current : refOrValue;
@@ -1,5 +0,0 @@
1
- import {Children} from "react";
2
-
3
- /** React helper which checks whether children has at least one truthy child */
4
- export const hasNonEmptyChild = (children: React.ReactNode): boolean =>
5
- Children.toArray(children).some((value) => Boolean(value));
@@ -1,3 +0,0 @@
1
- export const preventDefault = <Event extends {preventDefault: () => void} = React.SyntheticEvent>(e: Event): void => {
2
- e.preventDefault();
3
- };
@@ -1,37 +0,0 @@
1
- import type {ReactElement, ReactNode} from "react";
2
- import {Children, isValidElement} from "react";
3
-
4
- const nodeToString = (child?: React.ReactNode): string => {
5
- if (typeof child === "string" || typeof child === "number") {
6
- return child.toString();
7
- }
8
-
9
- return "";
10
- };
11
-
12
- const hasChildren = (node: ReactNode): node is ReactElement => isValidElement(node) && Boolean(node.props.children);
13
-
14
- /**
15
- *
16
- * Debug util to get text content of react node. Might be useful for logging.
17
- * Based on https://github.com/fernandopasik/react-children-utilities/blob/main/src/lib/onlyText.ts
18
- */
19
- export const reactNodeToString = (node: ReactNode | ReactNode[]) => {
20
- if (!(node instanceof Array) && !isValidElement(node)) {
21
- return nodeToString(node);
22
- }
23
-
24
- return Children.toArray(node).reduce((text: string, child: ReactNode): string => {
25
- let newText = "";
26
-
27
- if (hasChildren(child)) {
28
- newText = reactNodeToString(child.props.children);
29
- } else if (isValidElement(child) && !hasChildren(child)) {
30
- newText = "";
31
- } else {
32
- newText = nodeToString(child);
33
- }
34
-
35
- return text.concat(newText);
36
- }, "");
37
- };
@@ -1,7 +0,0 @@
1
- import type {QueryClient} from "@tanstack/react-query";
2
-
3
- import {createContext} from "./create-context";
4
-
5
- const [Provider, useContext] = createContext<QueryClient | null>("SharedQueryClientProvider", null);
6
-
7
- export {Provider as SharedQueryClientProvider, useContext as useSharedQueryClient};
@@ -1,3 +0,0 @@
1
- export const stopPropagation = (e: React.SyntheticEvent | Event): void => {
2
- e.stopPropagation();
3
- };
@@ -1,18 +0,0 @@
1
- import {useCallback, useLayoutEffect, useRef} from "react";
2
-
3
- /**
4
- * Hook to wrap callback in ref
5
- * so it doesn't trigger re-renders and remains up-to-date
6
- *
7
- * Could be replaced with https://github.com/reactjs/rfcs/pull/220 in future
8
- */
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
- export const useCallbackRef = <T extends (...args: any[]) => any>(callback?: T): T => {
11
- const callbackRef = useRef(callback);
12
-
13
- useLayoutEffect(() => {
14
- callbackRef.current = callback;
15
- });
16
-
17
- return useCallback(((...args) => callbackRef.current?.(...args)) as T, []);
18
- };
@@ -1,27 +0,0 @@
1
- import type React from "react";
2
- import {useCallback} from "react";
3
-
4
- export const composeRefs = <T>(...refs: Array<React.Ref<T> | undefined>) => {
5
- return function setRefs(node: T) {
6
- refs.forEach((ref) => {
7
- if (!ref) {
8
- return;
9
- }
10
-
11
- if (typeof ref === "function") {
12
- ref(node);
13
- } else {
14
- (ref as React.MutableRefObject<T>).current = node;
15
- }
16
- });
17
- };
18
- };
19
-
20
- /**
21
- * Hook to compose multiple refs
22
- * Accepts callback refs and RefObject(s)
23
- */
24
- export const useComposedRefs = <T>(...refs: Array<React.Ref<T> | undefined>): React.RefCallback<T> => {
25
- // eslint-disable-next-line react-hooks/exhaustive-deps
26
- return useCallback(composeRefs(...refs), refs);
27
- };
@@ -1 +0,0 @@
1
- export * from "./use-controllable-state";
@@ -1,46 +0,0 @@
1
- import {act, renderHook} from "@testing-library/react-hooks";
2
-
3
- import {useControllableState} from "./use-controllable-state";
4
-
5
- describe("useControllableState", () => {
6
- describe("uncontrolled", () => {
7
- it("should work for uncontrolled", () => {
8
- const onChange = vi.fn();
9
- const {result} = renderHook(() => useControllableState({onChange}));
10
- expect(result.current[0]).toBe(undefined);
11
-
12
- act(() => {
13
- result.current[1](true);
14
- });
15
-
16
- expect(result.current[0]).toBe(true);
17
- expect(onChange).toHaveBeenCalledWith(true);
18
- });
19
- it("should work for uncontrolled with default value", () => {
20
- const onChange = vi.fn();
21
- const {result} = renderHook(() => useControllableState({defaultValue: true, onChange}));
22
- expect(result.current[0]).toBe(true);
23
-
24
- act(() => {
25
- result.current[1](false);
26
- });
27
-
28
- expect(result.current[0]).toBe(false);
29
- expect(onChange).toHaveBeenCalledWith(false);
30
- });
31
- });
32
- describe("controlled", () => {
33
- it("should not change internal state. It's controlled by 'value'", () => {
34
- const onChange = vi.fn();
35
- const {result} = renderHook(() => useControllableState({value: true, onChange}));
36
- expect(result.current[0]).toEqual(true);
37
-
38
- act(() => {
39
- result.current[1](false);
40
- });
41
-
42
- expect(result.current[0]).toEqual(true);
43
- expect(onChange).toHaveBeenCalledWith(false);
44
- });
45
- });
46
- });
@@ -1,61 +0,0 @@
1
- import type {Dispatch, SetStateAction} from "react";
2
- import {useCallback, useEffect, useRef, useState} from "react";
3
-
4
- import {useCallbackRef} from "../use-callback-ref";
5
-
6
- type UseControllableStateProps<TState> = {
7
- /** value to be used in controlled mode */
8
- value?: TState;
9
- /** initial value to be used in uncontrolled mode */
10
- defaultValue?: TState;
11
- /** callback for value changes */
12
- onChange?: (state: TState) => unknown;
13
- };
14
-
15
- /**
16
- * React hook to support both controlled/uncontrolled modes
17
- * @see https://reactjs.org/docs/uncontrolled-components.html
18
- */
19
- export const useControllableState = <TState>({
20
- value,
21
- defaultValue,
22
- onChange,
23
- }: UseControllableStateProps<TState>): [TState, Dispatch<SetStateAction<TState>>] => {
24
- const [uncontrolledState, setUncontrolledState] = useState(defaultValue as TState);
25
- const onChangeState = useCallbackRef(onChange);
26
-
27
- const isControlled = value !== undefined;
28
- const state = isControlled ? value : uncontrolledState;
29
-
30
- // Call onChange after uncontrolled state changes via useEffect to avoid calling
31
- // setState on another component during a state updater (which React flags as
32
- // "setState during render" warning in development mode).
33
- const prevUncontrolledStateRef = useRef(uncontrolledState);
34
- useEffect(() => {
35
- if (prevUncontrolledStateRef.current !== uncontrolledState) {
36
- onChangeState(uncontrolledState);
37
- prevUncontrolledStateRef.current = uncontrolledState;
38
- }
39
- });
40
-
41
- const setState = useCallback<Dispatch<SetStateAction<TState>>>(
42
- (nextValue) => {
43
- if (isControlled) {
44
- const nextState = nextValue instanceof Function ? nextValue(value) : nextValue;
45
-
46
- if (value === nextState) {
47
- return;
48
- }
49
- onChangeState(nextState as TState);
50
- } else {
51
- setUncontrolledState((prevValue) => {
52
- const nextState = nextValue instanceof Function ? nextValue(prevValue) : nextValue;
53
- return nextState as TState;
54
- });
55
- }
56
- },
57
- [isControlled, onChangeState, value]
58
- );
59
-
60
- return [state, setState];
61
- };
package/src/use-drag.ts DELETED
@@ -1,96 +0,0 @@
1
- import {useRef} from "react";
2
-
3
- type Point = {
4
- x: number;
5
- y: number;
6
- };
7
-
8
- /**
9
- * very simple hook for simple isolated drag-like operations.
10
- * e.g. dragging border to resize, when you dont need drop targets, auto-scroll, etc.
11
- *
12
- * For complex operations you most likely want to use atlaskit/pragmatic-drag-and-drop
13
- */
14
- export const useDrag = ({
15
- threshold = 0,
16
- onDragStart,
17
- onDrag,
18
- onDragEnd,
19
- }: {
20
- /** Minimum movement before drag starts */
21
- threshold?: number;
22
- onDragStart?: () => void;
23
- onDrag?: (translation: Point) => void;
24
- onDragEnd?: (translation: Point) => void;
25
- }) => {
26
- const ref = useRef<HTMLDivElement>(null);
27
- const state = useRef<"idle" | "press" | "drag" | "drag-end">("idle");
28
-
29
- const lastPosition = useRef<Point>({x: 0, y: 0});
30
- const translation = useRef<Point>({x: 0, y: 0});
31
-
32
- function onClick(e: MouseEvent) {
33
- if (state.current === "drag-end") {
34
- e.preventDefault();
35
- e.stopPropagation();
36
- state.current = "idle";
37
- ref.current?.removeEventListener("click", onClick);
38
- }
39
- }
40
-
41
- function onPointerDown(e: React.PointerEvent) {
42
- lastPosition.current = {x: e.clientX, y: e.clientY};
43
- translation.current = {x: 0, y: 0};
44
- state.current = "press";
45
- ref.current?.setPointerCapture(e.pointerId);
46
- ref.current?.addEventListener("click", onClick);
47
- }
48
-
49
- function onPointerMove(e: React.PointerEvent) {
50
- if (state.current === "press") {
51
- const dx = e.clientX - lastPosition.current.x;
52
- const dy = e.clientY - lastPosition.current.y;
53
- const distance = Math.sqrt(dx * dx + dy * dy);
54
-
55
- if (distance >= threshold) {
56
- state.current = "drag";
57
- onDragStart?.();
58
- }
59
- }
60
-
61
- if (state.current !== "drag") {
62
- return;
63
- }
64
-
65
- const currentPosition = {x: e.clientX, y: e.clientY};
66
-
67
- const dx = currentPosition.x - lastPosition.current.x;
68
- const dy = currentPosition.y - lastPosition.current.y;
69
- lastPosition.current = currentPosition;
70
-
71
- translation.current = {
72
- x: translation.current.x + dx,
73
- y: translation.current.y + dy,
74
- };
75
-
76
- onDrag?.(translation.current);
77
- }
78
-
79
- function onPointerUp(e: React.PointerEvent) {
80
- if (state.current === "drag") {
81
- state.current = "drag-end";
82
- } else {
83
- state.current = "idle";
84
- }
85
-
86
- onDragEnd?.(translation.current);
87
- ref.current?.releasePointerCapture(e.pointerId);
88
- }
89
-
90
- return {
91
- ref,
92
- onPointerDown,
93
- onPointerMove,
94
- onPointerUp,
95
- };
96
- };
@@ -1,34 +0,0 @@
1
- import {useLayoutEffect, useRef} from "react";
2
-
3
- import {useCallbackRef} from "./use-callback-ref";
4
-
5
- type OnFocusOutside = (event: FocusEvent) => void;
6
-
7
- /**
8
- * Hook to react on focus moving outside of react tree including portals
9
- *
10
- * https://github.com/facebook/react/issues/19637#issuecomment-850412650
11
- */
12
- export const useFocusOutside = (onFocusOutside?: OnFocusOutside) => {
13
- const handleFocusOutside = useCallbackRef(onFocusOutside);
14
- const isFocusInsideReactTreeRef = useRef(false);
15
-
16
- useLayoutEffect(() => {
17
- const handleFocus = (event: FocusEvent) => {
18
- if (!isFocusInsideReactTreeRef.current) {
19
- handleFocusOutside(event);
20
- }
21
- };
22
- document.addEventListener("focusin", handleFocus);
23
- return () => document.removeEventListener("focusin", handleFocus);
24
- }, [handleFocusOutside]);
25
-
26
- return {
27
- onFocusCapture: () => {
28
- isFocusInsideReactTreeRef.current = true;
29
- },
30
- onBlurCapture: () => {
31
- isFocusInsideReactTreeRef.current = false;
32
- },
33
- };
34
- };
@@ -1,15 +0,0 @@
1
- import {useCallback, useLayoutEffect, useRef} from "react";
2
-
3
- export function useIsMounted(): () => boolean {
4
- const mountedRef = useRef(false);
5
- const isMounted = useCallback(() => mountedRef.current, []);
6
-
7
- useLayoutEffect(() => {
8
- mountedRef.current = true;
9
- return () => {
10
- mountedRef.current = false;
11
- };
12
- }, []);
13
-
14
- return isMounted;
15
- }
@@ -1,80 +0,0 @@
1
- import {useEffect, useRef} from "react";
2
-
3
- import {useCallbackRef} from "./use-callback-ref";
4
-
5
- /**
6
- * Inspired by radix
7
- * https://github.com/radix-ui/primitives/blob/c31c97274ff357aea99afe6c01c1c8c58b6356e0/packages/react/dismissable-layer/src/DismissableLayer.tsx#L223
8
- */
9
-
10
- /**
11
- * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup`
12
- * to mimic layer dismissing behaviour present in OS.
13
- * Returns props to pass to the node we want to check for outside events.
14
- */
15
- export function usePointerDownOutside(onPointerDownOutside?: (event: PointerEvent) => void) {
16
- const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
17
- const isPointerInsideReactTreeRef = useRef(false);
18
- const handleClickRef = useRef(() => {});
19
-
20
- useEffect(() => {
21
- const handlePointerDown = (event: PointerEvent) => {
22
- if (event.target && !isPointerInsideReactTreeRef.current) {
23
- const handlePointerDown = () => {
24
- handlePointerDownOutside(event);
25
- };
26
-
27
- /**
28
- * On touch devices, we need to wait for a click event because browsers implement
29
- * a ~350ms delay between the time the user stops touching the display and when the
30
- * browser executes events. We need to ensure we don't reactivate pointer-events within
31
- * this timeframe otherwise the browser may execute events that should have been prevented.
32
- *
33
- * Additionally, this also lets us deal automatically with cancellations when a click event
34
- * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc.
35
- *
36
- * This is why we also continuously remove the previous listener, because we cannot be
37
- * certain that it was raised, and therefore cleaned-up.
38
- */
39
- if (event.pointerType === "touch") {
40
- document.removeEventListener("click", handleClickRef.current);
41
- handleClickRef.current = handlePointerDown;
42
- document.addEventListener("click", handleClickRef.current, {once: true});
43
- } else {
44
- handlePointerDown();
45
- }
46
- } else {
47
- // We need to remove the event listener in case the outside click has been canceled.
48
- // See: https://github.com/radix-ui/primitives/issues/2171
49
- document.removeEventListener("click", handleClickRef.current);
50
- }
51
- isPointerInsideReactTreeRef.current = false;
52
- };
53
- /**
54
- * if this hook executes in a component that mounts via a `pointerdown` event, the event
55
- * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid
56
- * this by delaying the event listener registration on the document.
57
- * This is not React specific, but rather how the DOM works, ie:
58
- * ```
59
- * button.addEventListener('pointerdown', () => {
60
- * console.log('I will log');
61
- * document.addEventListener('pointerdown', () => {
62
- * console.log('I will also log');
63
- * })
64
- * });
65
- */
66
- const timerId = window.setTimeout(() => {
67
- document.addEventListener("pointerdown", handlePointerDown);
68
- }, 0);
69
- return () => {
70
- window.clearTimeout(timerId);
71
- document.removeEventListener("pointerdown", handlePointerDown);
72
- document.removeEventListener("click", handleClickRef.current);
73
- };
74
- }, [handlePointerDownOutside]);
75
-
76
- return {
77
- // ensures we check React component tree (not just DOM tree)
78
- onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true),
79
- };
80
- }