react-panel-layout 0.7.0 → 0.7.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 (44) hide show
  1. package/dist/{FloatingWindow-Bw2djgpz.js → FloatingWindow-CE-WzkNv.js} +2 -2
  2. package/dist/{FloatingWindow-Bw2djgpz.js.map → FloatingWindow-CE-WzkNv.js.map} +1 -1
  3. package/dist/{FloatingWindow-Cvyokf0m.cjs → FloatingWindow-DpFpmX1f.cjs} +2 -2
  4. package/dist/{FloatingWindow-Cvyokf0m.cjs.map → FloatingWindow-DpFpmX1f.cjs.map} +1 -1
  5. package/dist/{GridLayout-DNOClFzz.cjs → GridLayout-EwKszYBy.cjs} +2 -2
  6. package/dist/{GridLayout-DNOClFzz.cjs.map → GridLayout-EwKszYBy.cjs.map} +1 -1
  7. package/dist/{GridLayout-B4aCqSyd.js → GridLayout-kiWdpMLQ.js} +2 -2
  8. package/dist/{GridLayout-B4aCqSyd.js.map → GridLayout-kiWdpMLQ.js.map} +1 -1
  9. package/dist/{PanelSystem-B8Igvnb2.cjs → PanelSystem-Dmy5YI_6.cjs} +2 -2
  10. package/dist/{PanelSystem-B8Igvnb2.cjs.map → PanelSystem-Dmy5YI_6.cjs.map} +1 -1
  11. package/dist/{PanelSystem-DDUSFjXD.js → PanelSystem-DrYsYwuV.js} +3 -3
  12. package/dist/{PanelSystem-DDUSFjXD.js.map → PanelSystem-DrYsYwuV.js.map} +1 -1
  13. package/dist/config.cjs +1 -1
  14. package/dist/config.js +2 -2
  15. package/dist/dialog/index.d.ts +1 -1
  16. package/dist/grid.cjs +1 -1
  17. package/dist/grid.js +2 -2
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.js +4 -4
  20. package/dist/modules/dialog/DialogContainer.d.ts +22 -2
  21. package/dist/modules/dialog/Modal.d.ts +23 -2
  22. package/dist/modules/dialog/SwipeDialogContainer.d.ts +6 -2
  23. package/dist/modules/dialog/types.d.ts +12 -0
  24. package/dist/panels.cjs +1 -1
  25. package/dist/panels.js +1 -1
  26. package/dist/stack.cjs +1 -1
  27. package/dist/stack.js +1 -1
  28. package/dist/{useAnimationFrame-Bg4e-H8O.js → useAnimationFrame-CRuFlk5t.js} +16 -16
  29. package/dist/useAnimationFrame-CRuFlk5t.js.map +1 -0
  30. package/dist/useAnimationFrame-XRpDXkwV.cjs +2 -0
  31. package/dist/useAnimationFrame-XRpDXkwV.cjs.map +1 -0
  32. package/dist/window.cjs +1 -1
  33. package/dist/window.js +1 -1
  34. package/package.json +1 -1
  35. package/src/dialog/index.ts +2 -0
  36. package/src/hooks/gesture/useSwipeInput.spec.ts +69 -0
  37. package/src/hooks/gesture/useSwipeInput.ts +2 -0
  38. package/src/modules/dialog/DialogContainer.tsx +39 -5
  39. package/src/modules/dialog/Modal.tsx +46 -4
  40. package/src/modules/dialog/SwipeDialogContainer.tsx +12 -2
  41. package/src/modules/dialog/types.ts +14 -0
  42. package/dist/useAnimationFrame-BZ6D2lMq.cjs +0 -2
  43. package/dist/useAnimationFrame-BZ6D2lMq.cjs.map +0 -1
  44. package/dist/useAnimationFrame-Bg4e-H8O.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnimationFrame-XRpDXkwV.cjs","sources":["../src/hooks/gesture/usePointerTracking.ts","../src/hooks/gesture/useDirectionalLock.ts","../src/hooks/gesture/utils.ts","../src/hooks/gesture/types.ts","../src/hooks/gesture/useSwipeInput.ts","../src/hooks/gesture/useEdgeSwipeInput.ts","../src/hooks/gesture/useNativeGestureGuard.ts","../src/hooks/useAnimationFrame.ts"],"sourcesContent":["/**\n * @file Hook for tracking pointer state during gestures.\n *\n * Provides low-level pointer tracking with position, velocity, and timing.\n * This hook serves as the foundation for higher-level gesture hooks.\n */\nimport * as React from \"react\";\nimport { useDocumentPointerEvents } from \"../useDocumentPointerEvents.js\";\nimport { useEffectEvent } from \"../useEffectEvent.js\";\nimport type {\n PointerTrackingState,\n TimestampedPoint,\n UsePointerTrackingOptions,\n UsePointerTrackingResult,\n} from \"./types.js\";\n\n/**\n * Initial state for pointer tracking.\n */\nconst INITIAL_STATE: PointerTrackingState = {\n isDown: false,\n start: null,\n current: null,\n pointerId: null,\n wasCanceled: false,\n};\n\n/**\n * Creates a timestamped point from pointer event coordinates.\n */\nconst createTimestampedPoint = (clientX: number, clientY: number): TimestampedPoint => ({\n x: clientX,\n y: clientY,\n timestamp: performance.now(),\n});\n\n/**\n * Hook for tracking pointer state during gestures.\n *\n * Tracks pointer down/move/up events and provides position and timing data\n * that can be used by higher-level gesture detection hooks.\n *\n * @example\n * ```tsx\n * const { state, onPointerDown, reset } = usePointerTracking({\n * enabled: true,\n * primaryOnly: true,\n * });\n *\n * return (\n * <div onPointerDown={onPointerDown}>\n * {state.isDown && <span>Tracking...</span>}\n * </div>\n * );\n * ```\n */\nexport function usePointerTracking(options: UsePointerTrackingOptions): UsePointerTrackingResult {\n const { enabled, primaryOnly = true } = options;\n\n const [state, setState] = React.useState<PointerTrackingState>(INITIAL_STATE);\n\n const reset = React.useCallback(() => {\n setState(INITIAL_STATE);\n }, []);\n\n const handlePointerDown = useEffectEvent((event: React.PointerEvent) => {\n if (!enabled) {\n return;\n }\n\n // Filter non-primary pointers if primaryOnly is set\n if (primaryOnly && !event.isPrimary) {\n return;\n }\n\n // Only track left mouse button or touch/pen\n if (event.pointerType === \"mouse\" && event.button !== 0) {\n return;\n }\n\n const point = createTimestampedPoint(event.clientX, event.clientY);\n\n setState({\n isDown: true,\n start: point,\n current: point,\n pointerId: event.pointerId,\n wasCanceled: false,\n });\n });\n\n const handlePointerMove = useEffectEvent((event: PointerEvent) => {\n // Verify this is the tracked pointer\n if (state.pointerId !== event.pointerId) {\n return;\n }\n\n const point = createTimestampedPoint(event.clientX, event.clientY);\n\n setState((prev) => ({\n ...prev,\n current: point,\n }));\n });\n\n const handlePointerUp = useEffectEvent(() => {\n setState(INITIAL_STATE);\n });\n\n const handlePointerCancel = useEffectEvent(() => {\n setState({ ...INITIAL_STATE, wasCanceled: true });\n });\n\n // Use document-level pointer events for tracking after pointer down\n const shouldTrackDocument = state.isDown ? enabled : false;\n useDocumentPointerEvents(shouldTrackDocument, {\n onMove: handlePointerMove,\n onUp: handlePointerUp,\n onCancel: handlePointerCancel,\n });\n\n // Reset state when disabled\n React.useEffect(() => {\n if (!enabled && state.isDown) {\n reset();\n }\n }, [enabled, state.isDown, reset]);\n\n return {\n state,\n onPointerDown: handlePointerDown,\n reset,\n };\n}\n","/**\n * @file Hook for locking gesture direction after threshold is exceeded.\n *\n * Once the user moves beyond the lock threshold, the direction is locked\n * to either horizontal or vertical, preventing diagonal gestures from\n * triggering both scroll and swipe.\n */\nimport * as React from \"react\";\nimport type {\n GestureAxis,\n UseDirectionalLockOptions,\n UseDirectionalLockResult,\n} from \"./types.js\";\n\nconst DEFAULT_LOCK_THRESHOLD = 10;\n\n/**\n * Determines which axis the gesture is primarily moving along.\n *\n * @param deltaX - Horizontal displacement from start\n * @param deltaY - Vertical displacement from start\n * @returns The dominant axis, or null if movement is insufficient\n */\nconst determineAxis = (deltaX: number, deltaY: number): GestureAxis | null => {\n const absX = Math.abs(deltaX);\n const absY = Math.abs(deltaY);\n\n // Require at least some movement in one direction\n if (absX === 0 && absY === 0) {\n return null;\n }\n\n // Use a 1.5x ratio to ensure clear direction before locking\n // This prevents near-diagonal gestures from locking prematurely\n if (absX > absY * 1.5) {\n return \"horizontal\";\n }\n\n if (absY > absX * 1.5) {\n return \"vertical\";\n }\n\n // Still ambiguous\n return null;\n};\n\n/**\n * Hook for locking gesture direction after threshold is exceeded.\n *\n * This hook tracks pointer movement and locks to horizontal or vertical\n * direction once the movement exceeds the configured threshold. This\n * prevents diagonal gestures from triggering both scroll and swipe behaviors.\n *\n * @example\n * ```tsx\n * const { state: tracking, onPointerDown } = usePointerTracking({ enabled: true });\n * const { lockedAxis, isLocked } = useDirectionalLock({\n * tracking,\n * lockThreshold: 10,\n * });\n *\n * // lockedAxis will be \"horizontal\" or \"vertical\" once determined\n * ```\n */\nexport function useDirectionalLock(options: UseDirectionalLockOptions): UseDirectionalLockResult {\n const { tracking, lockThreshold = DEFAULT_LOCK_THRESHOLD } = options;\n\n const [lockedAxis, setLockedAxis] = React.useState<GestureAxis | null>(null);\n\n const reset = React.useCallback(() => {\n setLockedAxis(null);\n }, []);\n\n // Determine direction when tracking is active\n React.useEffect(() => {\n // Reset lock when pointer is released\n if (!tracking.isDown) {\n if (lockedAxis !== null) {\n reset();\n }\n return;\n }\n\n // Already locked, no need to recalculate\n if (lockedAxis !== null) {\n return;\n }\n\n // Need start and current positions\n if (!tracking.start || !tracking.current) {\n return;\n }\n\n const deltaX = tracking.current.x - tracking.start.x;\n const deltaY = tracking.current.y - tracking.start.y;\n\n // Check if we've exceeded the lock threshold\n const distance = Math.max(Math.abs(deltaX), Math.abs(deltaY));\n if (distance < lockThreshold) {\n return;\n }\n\n // Try to determine axis\n const axis = determineAxis(deltaX, deltaY);\n if (axis !== null) {\n setLockedAxis(axis);\n }\n }, [tracking.isDown, tracking.start, tracking.current, lockedAxis, lockThreshold, reset]);\n\n return {\n lockedAxis,\n isLocked: lockedAxis !== null,\n reset,\n };\n}\n","/**\n * @file Utility functions for gesture detection hooks.\n *\n * Contains shared calculations and helper functions used across\n * gesture-related hooks to avoid code duplication.\n */\nimport type * as React from \"react\";\n\n/**\n * Calculate velocity from displacement and time elapsed.\n *\n * @param displacement - Distance traveled in pixels\n * @param startTime - Start timestamp in milliseconds\n * @param currentTime - Current timestamp in milliseconds\n * @returns Velocity in pixels per millisecond\n */\nexport const calculateVelocity = (\n displacement: number,\n startTime: number,\n currentTime: number,\n): number => {\n const elapsed = currentTime - startTime;\n if (elapsed <= 0) {\n return 0;\n }\n return displacement / elapsed;\n};\n\n/**\n * Determine direction from displacement.\n *\n * @param displacement - Distance from start position\n * @returns -1 for backward (left/up), 0 for no movement, 1 for forward (right/down)\n */\nexport const determineDirection = (displacement: number): -1 | 0 | 1 => {\n if (displacement > 0) {\n return 1;\n }\n if (displacement < 0) {\n return -1;\n }\n return 0;\n};\n\n/**\n * Container props type for gesture handling.\n */\nexport type GestureContainerProps = React.HTMLAttributes<HTMLElement> & {\n style: React.CSSProperties;\n};\n\n/**\n * Merge multiple container props objects for gesture handling.\n *\n * Combines style objects and chains onPointerDown handlers.\n * Useful when combining multiple gesture hooks that each provide\n * their own container props (e.g., swipe input + native gesture guard).\n *\n * @param propsArray - Array of container props to merge\n * @returns Merged container props with combined styles and handlers\n */\nexport const mergeGestureContainerProps = (\n ...propsArray: GestureContainerProps[]\n): GestureContainerProps => {\n const mergedStyle: React.CSSProperties = {};\n const pointerDownHandlers: Array<\n ((event: React.PointerEvent<HTMLElement>) => void) | undefined\n > = [];\n\n for (const props of propsArray) {\n Object.assign(mergedStyle, props.style);\n if (props.onPointerDown) {\n pointerDownHandlers.push(props.onPointerDown);\n }\n }\n\n const handlePointerDown = (event: React.PointerEvent<HTMLElement>) => {\n for (const handler of pointerDownHandlers) {\n handler?.(event);\n }\n };\n\n return {\n onPointerDown: handlePointerDown,\n style: mergedStyle,\n };\n};\n\n// ============================================================================\n// Scroll Detection Utilities\n// ============================================================================\n\n/**\n * Compute scroll size for an element based on axis.\n */\nfunction computeScrollSize(element: HTMLElement, isHorizontal: boolean): number {\n if (isHorizontal) {\n return element.scrollWidth - element.clientWidth;\n }\n return element.scrollHeight - element.clientHeight;\n}\n\n/**\n * Check if an element is scrollable in any direction.\n */\nexport function isScrollableElement(element: HTMLElement): boolean {\n const style = getComputedStyle(element);\n\n const isScrollableX =\n (style.overflowX === \"scroll\" || style.overflowX === \"auto\") &&\n element.scrollWidth > element.clientWidth;\n\n const isScrollableY =\n (style.overflowY === \"scroll\" || style.overflowY === \"auto\") &&\n element.scrollHeight > element.clientHeight;\n\n if (isScrollableX) {\n return true;\n }\n return isScrollableY;\n}\n\n/**\n * Check if we should start drag based on scroll state.\n * Returns false if the target is inside a scrollable element.\n */\nexport function shouldStartDrag(\n event: React.PointerEvent,\n container: HTMLElement,\n): boolean {\n // eslint-disable-next-line no-restricted-syntax -- loop variable requires let\n let current = event.target as HTMLElement | null;\n\n while (current !== null && current !== container) {\n if (isScrollableElement(current)) {\n return false;\n }\n current = current.parentElement;\n }\n\n return true;\n}\n\n/**\n * Check if an element or its ancestors are scrollable in the specified direction.\n * Returns true if scrolling is possible and would block the swipe gesture.\n *\n * @param element - The target element to check\n * @param container - The container boundary\n * @param axis - The axis to check (\"x\" or \"y\")\n * @param direction - The swipe direction (1 = right/down, -1 = left/up)\n */\nexport function isScrollableInDirection(\n element: HTMLElement,\n container: HTMLElement,\n axis: \"x\" | \"y\",\n direction: 1 | -1,\n): boolean {\n // eslint-disable-next-line no-restricted-syntax -- loop variable requires let\n let current: HTMLElement | null = element;\n\n while (current !== null && current !== container) {\n const style = getComputedStyle(current);\n const isHorizontal = axis === \"x\";\n\n const overflow = isHorizontal ? style.overflowX : style.overflowY;\n const isScrollable = overflow === \"scroll\" || overflow === \"auto\";\n\n if (isScrollable) {\n const scrollSize = computeScrollSize(current, isHorizontal);\n\n if (scrollSize > 0) {\n const scrollPos = isHorizontal ? current.scrollLeft : current.scrollTop;\n\n // If swiping in close direction and not at boundary, block swipe\n if (direction === -1 && scrollPos > 1) {\n return true; // Can scroll left/up, block swipe\n }\n if (direction === 1 && scrollPos < scrollSize - 1) {\n return true; // Can scroll right/down, block swipe\n }\n }\n }\n\n current = current.parentElement;\n }\n\n return false;\n}\n","/**\n * @file Type definitions for gesture input detection hooks.\n *\n * These types support the separation of concerns:\n * - Operation: what to do (navigate, push, pop)\n * - Input: how to command (swipe, click, keyboard)\n * - Presentation: how to show (animation, transition)\n *\n * This file defines types for the Input layer, including the abstract\n * ContinuousOperationState that represents any continuous state transition\n * (whether controlled by human gesture or system animation).\n */\nimport type * as React from \"react\";\n\n/**\n * Axis for gesture detection.\n */\nexport type GestureAxis = \"horizontal\" | \"vertical\";\n\n/**\n * 2D vector for displacement and velocity.\n */\nexport type Vector2 = {\n x: number;\n y: number;\n};\n\n// ============================================================================\n// Continuous Operation State\n// ============================================================================\n// A continuous operation is any state transition that occurs over time,\n// where progress can be observed incrementally. The controlling agent\n// may be human (gesture) or system (animation).\n\n/**\n * Phase of a continuous operation lifecycle.\n * - \"idle\": No operation in progress\n * - \"operating\": Operation is in progress (human or system controlled)\n * - \"ended\": Operation has completed\n */\nexport type ContinuousOperationPhase = \"idle\" | \"operating\" | \"ended\";\n\n/**\n * State of a continuous operation.\n *\n * This is the abstract representation of any operation that occurs over time,\n * whether controlled by human gesture or system animation. Components that\n * accept this state can respond to both input types uniformly.\n */\nexport type ContinuousOperationState = {\n /** Current phase of the operation */\n phase: ContinuousOperationPhase;\n /** Displacement from start position in pixels */\n displacement: Vector2;\n /** Current velocity in pixels per millisecond */\n velocity: Vector2;\n};\n\n/**\n * Initial idle state for ContinuousOperationState.\n */\nexport const IDLE_CONTINUOUS_OPERATION_STATE: ContinuousOperationState = {\n phase: \"idle\",\n displacement: { x: 0, y: 0 },\n velocity: { x: 0, y: 0 },\n};\n\n/**\n * Convert SwipeInputPhase to ContinuousOperationPhase.\n * - \"idle\" → \"idle\"\n * - \"tracking\" | \"swiping\" → \"operating\"\n * - \"ended\" → \"ended\"\n */\nexport function toContinuousPhase(phase: SwipeInputPhase): ContinuousOperationPhase {\n if (phase === \"idle\") {\n return \"idle\";\n }\n if (phase === \"ended\") {\n return \"ended\";\n }\n return \"operating\";\n}\n\n/**\n * Convert SwipeInputState to ContinuousOperationState.\n */\nexport function toContinuousOperationState(state: SwipeInputState): ContinuousOperationState {\n return {\n phase: toContinuousPhase(state.phase),\n displacement: state.displacement,\n velocity: state.velocity,\n };\n}\n\n// ============================================================================\n// Swipe Input (concrete implementation of continuous operation)\n// ============================================================================\n\n/**\n * Phase of swipe input lifecycle.\n * - \"idle\": No swipe in progress\n * - \"tracking\": Pointer down, tracking movement (direction not yet locked)\n * - \"swiping\": Direction locked, actively swiping\n * - \"ended\": Swipe gesture completed\n */\nexport type SwipeInputPhase = \"idle\" | \"tracking\" | \"swiping\" | \"ended\";\n\n/**\n * Point with timestamp for velocity calculation.\n */\nexport type TimestampedPoint = {\n x: number;\n y: number;\n timestamp: number;\n};\n\n/**\n * Swipe input state during gesture.\n */\nexport type SwipeInputState = {\n /** Current phase of the swipe input */\n phase: SwipeInputPhase;\n /** Displacement from start position in pixels */\n displacement: Vector2;\n /** Current velocity in pixels per millisecond */\n velocity: Vector2;\n /**\n * Direction of movement as a number.\n * -1 = backward (left/up), 0 = no movement, 1 = forward (right/down)\n */\n direction: -1 | 0 | 1;\n};\n\n/**\n * Thresholds for swipe input recognition.\n */\nexport type SwipeInputThresholds = {\n /** Minimum distance in pixels to trigger swipe. @default 50 */\n distanceThreshold: number;\n /** Minimum velocity in px/ms to trigger swipe. @default 0.3 */\n velocityThreshold: number;\n /** Distance threshold before direction is locked. @default 10 */\n lockThreshold: number;\n};\n\n/**\n * Options for usePointerTracking hook.\n */\nexport type UsePointerTrackingOptions = {\n /** Whether tracking is enabled */\n enabled: boolean;\n /** Restrict to primary pointer only (ignore multitouch). @default true */\n primaryOnly?: boolean;\n};\n\n/**\n * Result from usePointerTracking hook.\n */\nexport type UsePointerTrackingResult = {\n /** Current tracking state */\n state: PointerTrackingState;\n /** Handler to attach to onPointerDown */\n onPointerDown: (event: React.PointerEvent) => void;\n /** Reset tracking state */\n reset: () => void;\n};\n\n/**\n * Internal pointer tracking state.\n */\nexport type PointerTrackingState = {\n /** Whether pointer is currently down */\n isDown: boolean;\n /** Start position and timestamp */\n start: TimestampedPoint | null;\n /** Current position and timestamp */\n current: TimestampedPoint | null;\n /** Active pointer ID */\n pointerId: number | null;\n /** Whether tracking ended via pointercancel (not pointerup) */\n wasCanceled: boolean;\n};\n\n/**\n * Options for useDirectionalLock hook.\n */\nexport type UseDirectionalLockOptions = {\n /** Pointer tracking state from usePointerTracking */\n tracking: PointerTrackingState;\n /** Lock threshold in pixels. @default 10 */\n lockThreshold?: number;\n};\n\n/**\n * Result from useDirectionalLock hook.\n */\nexport type UseDirectionalLockResult = {\n /** Locked axis, or null if not yet locked */\n lockedAxis: GestureAxis | null;\n /** Whether lock has been determined */\n isLocked: boolean;\n /** Reset the lock state */\n reset: () => void;\n};\n\n/**\n * Options for useScrollBoundary hook.\n */\nexport type UseScrollBoundaryOptions = {\n /** Scroll container ref. If null, checks document scroll. */\n containerRef: React.RefObject<HTMLElement | null>;\n /** Axis to monitor */\n axis: GestureAxis;\n /** Tolerance in pixels for \"at boundary\" detection. @default 1 */\n tolerance?: number;\n};\n\n/**\n * Result from useScrollBoundary hook.\n */\nexport type UseScrollBoundaryResult = {\n /** Whether at the start boundary (top/left) */\n atStart: boolean;\n /** Whether at the end boundary (bottom/right) */\n atEnd: boolean;\n /** Current scroll position */\n scrollPosition: number;\n /** Maximum scroll position */\n maxScrollPosition: number;\n};\n\n/**\n * Filter function to determine if a pointer event should start tracking.\n * Receives the pointer event and container element.\n * Return true to allow tracking, false to ignore the event.\n */\nexport type PointerStartFilter = (\n event: React.PointerEvent,\n container: HTMLElement,\n) => boolean;\n\n/**\n * Options for useSwipeInput hook.\n */\nexport type UseSwipeInputOptions = {\n /** Ref to the container element */\n containerRef: React.RefObject<HTMLElement | null>;\n /** Axis to detect swipes on */\n axis: GestureAxis;\n /** Whether swipe detection is enabled. @default true */\n enabled?: boolean;\n /** Swipe thresholds configuration */\n thresholds?: Partial<SwipeInputThresholds>;\n /** Callback when swipe is completed */\n onSwipeEnd?: (state: SwipeInputState) => void;\n /** Whether to enable trackpad two-finger swipe (wheel events). @default true */\n enableWheel?: boolean;\n /**\n * Optional filter to determine if a pointer event should start tracking.\n * If provided, only events that pass this filter will be tracked.\n * Useful for edge-based swipe detection.\n */\n pointerStartFilter?: PointerStartFilter;\n};\n\n/**\n * Result from useSwipeInput hook.\n */\nexport type UseSwipeInputResult = {\n /** Current swipe input state */\n state: SwipeInputState;\n /** Props to spread on the container element */\n containerProps: React.HTMLAttributes<HTMLElement> & {\n style: React.CSSProperties;\n };\n};\n\n/**\n * Edge for edge-originated gestures.\n */\nexport type GestureEdge = \"left\" | \"right\" | \"top\" | \"bottom\";\n\n/**\n * Options for useEdgeSwipeInput hook.\n */\nexport type UseEdgeSwipeInputOptions = {\n /** Ref to the container element */\n containerRef: React.RefObject<HTMLElement | null>;\n /** Which edge to detect swipes from */\n edge: GestureEdge;\n /** Width of the edge detection zone in pixels. @default 20 */\n edgeWidth?: number;\n /** Whether edge swipe detection is enabled. @default true */\n enabled?: boolean;\n /** Swipe thresholds configuration */\n thresholds?: Partial<SwipeInputThresholds>;\n /** Callback when edge swipe is completed */\n onSwipeEnd?: (state: SwipeInputState) => void;\n};\n\n/**\n * Result from useEdgeSwipeInput hook.\n */\nexport type UseEdgeSwipeInputResult = {\n /** Whether the current gesture started from the edge */\n isEdgeGesture: boolean;\n /** Current swipe input state */\n state: SwipeInputState;\n /** Props to spread on the container element */\n containerProps: React.HTMLAttributes<HTMLElement> & {\n style: React.CSSProperties;\n };\n};\n\n/**\n * Options for useNativeGestureGuard hook.\n */\nexport type UseNativeGestureGuardOptions = {\n /** Ref to the container element */\n containerRef: React.RefObject<HTMLElement | null>;\n /** Whether the guard is active */\n active: boolean;\n /** Prevent iOS/macOS edge back gesture. @default true */\n preventEdgeBack?: boolean;\n /** Prevent overscroll bounce effect. @default true */\n preventOverscroll?: boolean;\n /** Width of edge zone where back gesture is prevented. @default 20 */\n edgeWidth?: number;\n};\n\n/**\n * Result from useNativeGestureGuard hook.\n */\nexport type UseNativeGestureGuardResult = {\n /** Props to spread on the container element */\n containerProps: React.HTMLAttributes<HTMLElement> & {\n style: React.CSSProperties;\n };\n};\n\n/**\n * Default swipe input thresholds.\n *\n * - distanceThreshold: 100px is ~27% of a 375px mobile screen\n * - velocityThreshold: 0.5px/ms = 500px/s, a moderate flick speed\n * - lockThreshold: 10px before direction is locked\n */\nexport const DEFAULT_SWIPE_THRESHOLDS: SwipeInputThresholds = {\n distanceThreshold: 100,\n velocityThreshold: 0.5,\n lockThreshold: 10,\n};\n\n/**\n * Default edge width for edge gesture detection.\n */\nexport const DEFAULT_EDGE_WIDTH = 20;\n\n/**\n * Initial idle state for SwipeInputState.\n */\nexport const IDLE_SWIPE_INPUT_STATE: SwipeInputState = {\n phase: \"idle\",\n displacement: { x: 0, y: 0 },\n velocity: { x: 0, y: 0 },\n direction: 0,\n};\n","/**\n * @file Hook for detecting swipe gestures on a container element.\n *\n * Combines pointer tracking and directional locking to detect swipe gestures.\n * Also supports trackpad two-finger swipe via wheel events.\n * Returns swipe state and container props for gesture handling.\n */\nimport * as React from \"react\";\nimport { usePointerTracking } from \"./usePointerTracking.js\";\nimport { useDirectionalLock } from \"./useDirectionalLock.js\";\nimport { useEffectEvent } from \"../useEffectEvent.js\";\nimport { calculateVelocity, determineDirection } from \"./utils.js\";\nimport type {\n GestureAxis,\n SwipeInputState,\n SwipeInputThresholds,\n UseSwipeInputOptions,\n UseSwipeInputResult,\n Vector2,\n} from \"./types.js\";\nimport { DEFAULT_SWIPE_THRESHOLDS, IDLE_SWIPE_INPUT_STATE } from \"./types.js\";\n\n/** Idle timeout to reset wheel state after swipe stops */\nconst WHEEL_RESET_TIMEOUT = 150;\n\n/**\n * Evaluate swipe end and call callback if threshold is met.\n */\nconst evaluateSwipeEnd = (\n displacement: Vector2,\n velocity: Vector2,\n axis: GestureAxis,\n thresholds: SwipeInputThresholds,\n onSwipeEnd: ((state: SwipeInputState) => void) | undefined,\n): void => {\n const axisDisplacement = axis === \"horizontal\" ? displacement.x : displacement.y;\n const axisVelocity = axis === \"horizontal\" ? velocity.x : velocity.y;\n\n const absDisplacement = Math.abs(axisDisplacement);\n const absVelocity = Math.abs(axisVelocity);\n\n const triggered = absDisplacement >= thresholds.distanceThreshold || absVelocity >= thresholds.velocityThreshold;\n\n if (triggered) {\n const direction = determineDirection(axisDisplacement);\n const endState: SwipeInputState = {\n phase: \"ended\",\n displacement,\n velocity,\n direction,\n };\n onSwipeEnd?.(endState);\n }\n};\n\n/**\n * Hook for detecting swipe gestures on a container element.\n */\nexport function useSwipeInput(options: UseSwipeInputOptions): UseSwipeInputResult {\n const {\n containerRef,\n axis,\n enabled = true,\n thresholds: customThresholds,\n onSwipeEnd,\n enableWheel = true,\n pointerStartFilter,\n } = options;\n\n const thresholds: SwipeInputThresholds = {\n ...DEFAULT_SWIPE_THRESHOLDS,\n ...customThresholds,\n };\n\n // Stable callback for swipe end\n const handleSwipeEnd = useEffectEvent(onSwipeEnd);\n\n // ===== Pointer-based swipe tracking =====\n const { state: tracking, onPointerDown: baseOnPointerDown } = usePointerTracking({\n enabled,\n });\n\n // Wrap pointer down handler with optional filter\n const onPointerDown = React.useCallback(\n (event: React.PointerEvent) => {\n if (!enabled) {\n return;\n }\n if (pointerStartFilter) {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n if (!pointerStartFilter(event, container)) {\n return;\n }\n }\n baseOnPointerDown(event);\n },\n [enabled, pointerStartFilter, containerRef, baseOnPointerDown],\n );\n\n const { lockedAxis, isLocked } = useDirectionalLock({\n tracking,\n lockThreshold: thresholds.lockThreshold,\n });\n\n const lastActiveStateRef = React.useRef<SwipeInputState | null>(null);\n\n // Prevent native scroll when swiping on iOS\n const isLockedToSwipeAxisRef = React.useRef(false);\n\n React.useEffect(() => {\n isLockedToSwipeAxisRef.current = isLocked ? lockedAxis === axis : false;\n }, [isLocked, lockedAxis, axis]);\n\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container || !enabled) {\n return;\n }\n const disableTouchMove = (event: TouchEvent) => {\n event.preventDefault();\n };\n const handleTouchStart = (event: TouchEvent) => {\n if (isLockedToSwipeAxisRef.current) {\n event.preventDefault();\n }\n document.addEventListener(\"touchmove\", disableTouchMove, { passive: false });\n };\n const handleTouchEnd = () => {\n document.removeEventListener(\"touchmove\", disableTouchMove);\n };\n document.addEventListener(\"touchend\", handleTouchEnd);\n document.addEventListener(\"touchcancel\", handleTouchEnd);\n container.addEventListener(\"touchstart\", handleTouchStart, { passive: false });\n\n return () => {\n container.removeEventListener(\"touchstart\", handleTouchStart);\n document.removeEventListener(\"touchend\", handleTouchEnd);\n document.removeEventListener(\"touchcancel\", handleTouchEnd);\n // Must also remove disableTouchMove in case unmount happens during active touch\n document.removeEventListener(\"touchmove\", disableTouchMove);\n };\n }, [containerRef, enabled]);\n\n // ===== Wheel-based swipe tracking =====\n const [wheelState, setWheelState] = React.useState<SwipeInputState>(IDLE_SWIPE_INPUT_STATE);\n const wheelAccumulatedRef = React.useRef({ x: 0, y: 0 });\n const wheelIdleTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const wheelLockedRef = React.useRef(false);\n const wheelLockedAxisRef = React.useRef<GestureAxis | null>(null);\n\n const resetWheelState = React.useCallback(() => {\n wheelAccumulatedRef.current = { x: 0, y: 0 };\n wheelLockedRef.current = false;\n wheelLockedAxisRef.current = null;\n setWheelState(IDLE_SWIPE_INPUT_STATE);\n }, []);\n\n const endWheelSwipe = React.useCallback(() => {\n const displacement = { ...wheelAccumulatedRef.current };\n evaluateSwipeEnd(displacement, { x: 0, y: 0 }, axis, thresholds, handleSwipeEnd);\n resetWheelState();\n }, [axis, thresholds, handleSwipeEnd, resetWheelState]);\n\n const handleWheel = useEffectEvent((event: WheelEvent) => {\n if (!enabled || !enableWheel || tracking.isDown) {\n return;\n }\n\n const { deltaX, deltaY } = event;\n\n // Direction lock\n if (!wheelLockedRef.current) {\n const absX = Math.abs(deltaX);\n const absY = Math.abs(deltaY);\n\n if (absX >= thresholds.lockThreshold || absY >= thresholds.lockThreshold) {\n wheelLockedRef.current = true;\n wheelLockedAxisRef.current = absX > absY ? \"horizontal\" : \"vertical\";\n }\n }\n\n // If locked to wrong axis, ignore\n if (wheelLockedRef.current && wheelLockedAxisRef.current !== axis) {\n return;\n }\n\n // Accumulate displacement (negate: wheel delta is scroll direction)\n wheelAccumulatedRef.current.x -= deltaX;\n wheelAccumulatedRef.current.y -= deltaY;\n\n const accumulated = wheelAccumulatedRef.current;\n const axisDisplacement = axis === \"horizontal\" ? accumulated.x : accumulated.y;\n\n setWheelState({\n phase: \"swiping\",\n displacement: { ...accumulated },\n velocity: { x: 0, y: 0 },\n direction: determineDirection(axisDisplacement),\n });\n\n // When wheel stops, treat as \"release\"\n if (wheelIdleTimerRef.current !== null) {\n clearTimeout(wheelIdleTimerRef.current);\n }\n wheelIdleTimerRef.current = setTimeout(endWheelSwipe, WHEEL_RESET_TIMEOUT);\n });\n\n // Set up wheel event listener\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container || !enabled || !enableWheel) {\n return;\n }\n\n const listener = (event: WheelEvent) => {\n event.preventDefault();\n handleWheel(event);\n };\n\n container.addEventListener(\"wheel\", listener, { passive: false });\n\n return () => {\n container.removeEventListener(\"wheel\", listener);\n if (wheelIdleTimerRef.current !== null) {\n clearTimeout(wheelIdleTimerRef.current);\n }\n };\n }, [containerRef, enabled, enableWheel, handleWheel]);\n\n React.useEffect(() => {\n return () => {\n if (wheelIdleTimerRef.current !== null) {\n clearTimeout(wheelIdleTimerRef.current);\n }\n };\n }, []);\n\n // ===== Pointer swipe state =====\n const pointerState = React.useMemo<SwipeInputState>(() => {\n if (!tracking.isDown || !tracking.start || !tracking.current) {\n return IDLE_SWIPE_INPUT_STATE;\n }\n\n const deltaX = tracking.current.x - tracking.start.x;\n const deltaY = tracking.current.y - tracking.start.y;\n const displacement = { x: deltaX, y: deltaY };\n\n const velocity = {\n x: calculateVelocity(deltaX, tracking.start.timestamp, tracking.current.timestamp),\n y: calculateVelocity(deltaY, tracking.start.timestamp, tracking.current.timestamp),\n };\n\n if (!isLocked || lockedAxis !== axis) {\n return { phase: \"tracking\", displacement, velocity, direction: 0 };\n }\n\n const axisDisplacement = axis === \"horizontal\" ? deltaX : deltaY;\n return {\n phase: \"swiping\",\n displacement,\n velocity,\n direction: determineDirection(axisDisplacement),\n };\n }, [tracking.isDown, tracking.start, tracking.current, isLocked, lockedAxis, axis]);\n\n React.useEffect(() => {\n if (pointerState.phase !== \"idle\") {\n lastActiveStateRef.current = pointerState;\n }\n }, [pointerState]);\n\n // Handle pointer up (but not cancel)\n React.useEffect(() => {\n if (tracking.isDown) {\n return;\n }\n\n const lastState = lastActiveStateRef.current;\n if (!lastState || (lastState.phase !== \"swiping\" && lastState.phase !== \"tracking\")) {\n return;\n }\n\n lastActiveStateRef.current = null;\n\n // Skip navigation if the gesture was canceled (e.g., browser took over for native scroll)\n if (tracking.wasCanceled) {\n return;\n }\n\n evaluateSwipeEnd(lastState.displacement, lastState.velocity, axis, thresholds, handleSwipeEnd);\n }, [tracking.isDown, tracking.wasCanceled, axis, thresholds, handleSwipeEnd]);\n\n // Merge states\n const state = pointerState.phase !== \"idle\" ? pointerState : wheelState;\n\n const containerProps = React.useMemo(() => {\n const touchAction = axis === \"horizontal\" ? \"pan-y pinch-zoom\" : \"pan-x pinch-zoom\";\n return {\n onPointerDown,\n style: {\n touchAction,\n userSelect: \"none\" as const,\n WebkitUserSelect: \"none\" as const,\n },\n };\n }, [axis, onPointerDown]);\n\n return { state, containerProps };\n}\n","/**\n * @file Hook for detecting swipe gestures that originate from the edge of a container.\n *\n * Edge swipes are commonly used for \"swipe back\" navigation in mobile apps.\n * This hook detects swipes that start within a configurable edge zone.\n *\n * Built on top of useSwipeInput with edge zone filtering.\n */\nimport * as React from \"react\";\nimport { useSwipeInput } from \"./useSwipeInput.js\";\nimport type {\n GestureAxis,\n GestureEdge,\n SwipeInputState,\n UseEdgeSwipeInputOptions,\n UseEdgeSwipeInputResult,\n} from \"./types.js\";\nimport { DEFAULT_EDGE_WIDTH, DEFAULT_SWIPE_THRESHOLDS, IDLE_SWIPE_INPUT_STATE } from \"./types.js\";\n\n/**\n * Get the axis associated with an edge.\n */\nconst getAxisForEdge = (edge: GestureEdge): GestureAxis => {\n if (edge === \"left\" || edge === \"right\") {\n return \"horizontal\";\n }\n return \"vertical\";\n};\n\n/**\n * Check if a point is within the edge zone of a container.\n */\nconst isInEdgeZone = (\n clientX: number,\n clientY: number,\n container: HTMLElement,\n edge: GestureEdge,\n edgeWidth: number,\n): boolean => {\n const rect = container.getBoundingClientRect();\n\n switch (edge) {\n case \"left\":\n return clientX >= rect.left && clientX <= rect.left + edgeWidth;\n case \"right\":\n return clientX >= rect.right - edgeWidth && clientX <= rect.right;\n case \"top\":\n return clientY >= rect.top && clientY <= rect.top + edgeWidth;\n case \"bottom\":\n return clientY >= rect.bottom - edgeWidth && clientY <= rect.bottom;\n }\n};\n\n/**\n * Hook for detecting swipe gestures that originate from the edge of a container.\n *\n * This is useful for implementing \"swipe back\" navigation patterns where\n * the user must start their swipe from the edge of the screen.\n *\n * @example\n * ```tsx\n * const containerRef = useRef<HTMLDivElement>(null);\n * const { isEdgeGesture, state, containerProps } = useEdgeSwipeInput({\n * containerRef,\n * edge: \"left\",\n * edgeWidth: 20,\n * onSwipeEnd: (state) => {\n * if (state.direction === 1) goBack();\n * },\n * });\n *\n * return <div ref={containerRef} {...containerProps}>{children}</div>;\n * ```\n */\nexport function useEdgeSwipeInput(options: UseEdgeSwipeInputOptions): UseEdgeSwipeInputResult {\n const {\n containerRef,\n edge,\n edgeWidth = DEFAULT_EDGE_WIDTH,\n enabled = true,\n thresholds: customThresholds,\n onSwipeEnd,\n } = options;\n\n const thresholds = {\n ...DEFAULT_SWIPE_THRESHOLDS,\n ...customThresholds,\n };\n\n const axis = getAxisForEdge(edge);\n\n // Track whether the current gesture started from the edge\n const [isEdgeGesture, setIsEdgeGesture] = React.useState(false);\n\n // Create edge zone filter for pointer events\n const pointerStartFilter = React.useCallback(\n (event: React.PointerEvent, container: HTMLElement): boolean => {\n const inEdge = isInEdgeZone(event.clientX, event.clientY, container, edge, edgeWidth);\n setIsEdgeGesture(inEdge);\n return inEdge;\n },\n [edge, edgeWidth],\n );\n\n // Use base swipe input with edge filtering\n const { state, containerProps } = useSwipeInput({\n containerRef,\n axis,\n enabled,\n thresholds,\n onSwipeEnd,\n enableWheel: false, // Edge swipe doesn't use wheel events\n pointerStartFilter,\n });\n\n // Reset edge gesture state when swipe ends\n React.useEffect(() => {\n if (state.phase === \"idle\") {\n setIsEdgeGesture(false);\n }\n }, [state.phase]);\n\n // If not an edge gesture, return idle state\n const effectiveState: SwipeInputState = isEdgeGesture ? state : IDLE_SWIPE_INPUT_STATE;\n\n return {\n isEdgeGesture,\n state: effectiveState,\n containerProps,\n };\n}\n","/**\n * @file Hook for preventing conflicts with native OS gestures.\n *\n * This hook helps prevent conflicts with:\n * - iOS/macOS edge swipe back navigation\n * - Overscroll bounce effects\n *\n * It applies appropriate CSS properties and event handlers to the container.\n */\nimport * as React from \"react\";\nimport type {\n UseNativeGestureGuardOptions,\n UseNativeGestureGuardResult,\n} from \"./types.js\";\nimport { DEFAULT_EDGE_WIDTH } from \"./types.js\";\n\n/**\n * Check if a pointer event is within the left edge zone.\n */\nconst isInLeftEdge = (clientX: number, container: HTMLElement, edgeWidth: number): boolean => {\n const rect = container.getBoundingClientRect();\n return clientX >= rect.left && clientX <= rect.left + edgeWidth;\n};\n\n/**\n * Hook for preventing conflicts with native OS gestures.\n *\n * When active, this hook:\n * - Prevents iOS/macOS edge back gesture by capturing pointerdown events in the edge zone\n * - Prevents overscroll bounce effect using CSS overscroll-behavior\n * - Dynamically applies overscroll-behavior: none to html element during gesture\n *\n * @example\n * ```tsx\n * const containerRef = useRef<HTMLDivElement>(null);\n * const { containerProps } = useNativeGestureGuard({\n * containerRef,\n * active: isSwipeActive,\n * preventEdgeBack: true,\n * preventOverscroll: true,\n * });\n *\n * return <div ref={containerRef} {...containerProps}>{children}</div>;\n * ```\n */\nexport function useNativeGestureGuard(options: UseNativeGestureGuardOptions): UseNativeGestureGuardResult {\n const {\n containerRef,\n active,\n preventEdgeBack = true,\n preventOverscroll = true,\n edgeWidth = DEFAULT_EDGE_WIDTH,\n } = options;\n\n // Track previous html overscroll-behavior value for restoration\n const previousHtmlOverscrollRef = React.useRef<string | null>(null);\n\n // Apply overscroll-behavior to html synchronously (called from onPointerDown)\n const applyHtmlOverscroll = React.useCallback(() => {\n if (!preventOverscroll) {\n return;\n }\n\n const html = document.documentElement;\n if (previousHtmlOverscrollRef.current === null) {\n previousHtmlOverscrollRef.current = html.style.overscrollBehavior;\n }\n html.style.overscrollBehavior = \"none\";\n }, [preventOverscroll]);\n\n // Remove overscroll-behavior from html when gesture ends\n React.useEffect(() => {\n if (active || !preventOverscroll) {\n return;\n }\n\n // Cleanup: restore previous value when deactivated\n if (previousHtmlOverscrollRef.current !== null) {\n document.documentElement.style.overscrollBehavior = previousHtmlOverscrollRef.current;\n previousHtmlOverscrollRef.current = null;\n }\n }, [active, preventOverscroll]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (previousHtmlOverscrollRef.current !== null) {\n document.documentElement.style.overscrollBehavior = previousHtmlOverscrollRef.current;\n previousHtmlOverscrollRef.current = null;\n }\n };\n }, []);\n\n // Pointer down handler that prevents edge back gesture\n // Note: This must run on EVERY pointerdown in edge zone, not just when active,\n // because browser gesture recognition starts immediately on first touch.\n const onPointerDown = React.useCallback((event: React.PointerEvent) => {\n if (!preventEdgeBack) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n // Prevent for touch events in the left edge zone\n // This must happen immediately, before we know if it's \"our\" gesture\n if (event.pointerType === \"touch\" && isInLeftEdge(event.clientX, container, edgeWidth)) {\n // Apply html overscroll-behavior synchronously before browser can recognize gesture\n applyHtmlOverscroll();\n // Prevent the browser from handling this as a back gesture\n event.preventDefault();\n }\n }, [preventEdgeBack, containerRef, edgeWidth, applyHtmlOverscroll]);\n\n // Build container props\n // Styles are applied immediately (not waiting for active) to prevent browser gestures\n const containerProps = React.useMemo(() => {\n const style: React.CSSProperties = {\n // Always apply to prevent browser navigation gestures\n overscrollBehavior: preventOverscroll ? \"contain\" : undefined,\n WebkitOverflowScrolling: \"touch\",\n };\n\n return {\n onPointerDown: preventEdgeBack ? onPointerDown : undefined,\n style,\n };\n }, [preventOverscroll, preventEdgeBack, onPointerDown]);\n\n return {\n containerProps,\n };\n}\n","/**\n * @file Generic requestAnimationFrame-based animation hook.\n *\n * Provides a reusable animation loop with easing support.\n * This is the foundation for more specific animation hooks.\n */\nimport * as React from \"react\";\n\n/**\n * Easing function type.\n * Takes a progress value (0-1) and returns an eased value (0-1).\n */\nexport type EasingFunction = (t: number) => number;\n\n/**\n * Built-in easing functions.\n */\nexport const easings = {\n /** Linear (no easing) */\n linear: (t: number): number => t,\n\n /** Ease out cubic */\n easeOutCubic: (t: number): number => 1 - Math.pow(1 - t, 3),\n\n /** Ease out expo (similar to cubic-bezier(0.22, 1, 0.36, 1)) */\n easeOutExpo: (t: number): number => {\n if (t === 1) {\n return 1;\n }\n return 1 - Math.pow(2, -10 * t);\n },\n\n /** Ease out quart */\n easeOutQuart: (t: number): number => 1 - Math.pow(1 - t, 4),\n\n /** Ease in out cubic */\n easeInOutCubic: (t: number): number => {\n if (t < 0.5) {\n return 4 * t * t * t;\n }\n return 1 - Math.pow(-2 * t + 2, 3) / 2;\n },\n\n /** Ease in expo (accelerating, for \"suck in\" effect) */\n easeInExpo: (t: number): number => {\n if (t === 0) {\n return 0;\n }\n return Math.pow(2, 10 * t - 10);\n },\n} as const;\n\n/**\n * Animation state passed to callbacks.\n */\nexport type AnimationState = {\n /** Raw progress (0-1) */\n progress: number;\n /** Eased progress (0-1) */\n easedProgress: number;\n /** Elapsed time in ms */\n elapsed: number;\n /** Whether animation is complete */\n isComplete: boolean;\n};\n\n/**\n * Options for useAnimationFrame hook.\n */\nexport type UseAnimationFrameOptions = {\n /** Duration of animation in milliseconds */\n duration?: number;\n /** Easing function for the animation */\n easing?: EasingFunction;\n /** Callback called every frame with animation state */\n onFrame?: (state: AnimationState) => void;\n /** Callback when animation completes */\n onComplete?: () => void;\n};\n\n/**\n * Result from useAnimationFrame hook.\n */\nexport type UseAnimationFrameResult = {\n /** Whether animation is currently running */\n isAnimating: boolean;\n /** Start the animation */\n start: () => void;\n /** Cancel the animation */\n cancel: () => void;\n};\n\n/** Default animation duration in ms */\nconst DEFAULT_DURATION = 300;\n\n/**\n * Generic requestAnimationFrame-based animation hook.\n *\n * Provides a reusable animation loop with progress calculation and easing.\n * Use this as a building block for specific animation behaviors.\n *\n * @example\n * ```tsx\n * const { start, isAnimating } = useAnimationFrame({\n * duration: 300,\n * easing: easings.easeOutExpo,\n * onFrame: ({ easedProgress }) => {\n * const value = fromValue + (toValue - fromValue) * easedProgress;\n * element.style.transform = `translateX(${value}px)`;\n * },\n * onComplete: () => console.log('Done!'),\n * });\n *\n * // Start animation\n * start();\n * ```\n */\nexport function useAnimationFrame(options: UseAnimationFrameOptions): UseAnimationFrameResult {\n const {\n duration = DEFAULT_DURATION,\n easing = easings.easeOutExpo,\n onFrame,\n onComplete,\n } = options;\n\n const [isAnimating, setIsAnimating] = React.useState(false);\n const rafIdRef = React.useRef<number | null>(null);\n const startTimeRef = React.useRef<number | null>(null);\n\n // Use refs for callbacks to avoid stale closures\n const onFrameRef = React.useRef(onFrame);\n const onCompleteRef = React.useRef(onComplete);\n React.useEffect(() => {\n onFrameRef.current = onFrame;\n onCompleteRef.current = onComplete;\n }, [onFrame, onComplete]);\n\n const cancel = React.useCallback(() => {\n if (rafIdRef.current !== null) {\n cancelAnimationFrame(rafIdRef.current);\n rafIdRef.current = null;\n }\n startTimeRef.current = null;\n setIsAnimating(false);\n }, []);\n\n const start = React.useCallback(() => {\n // Cancel any existing animation\n cancel();\n\n setIsAnimating(true);\n startTimeRef.current = null;\n\n const step = (timestamp: number) => {\n if (startTimeRef.current === null) {\n startTimeRef.current = timestamp;\n }\n\n const elapsed = timestamp - startTimeRef.current;\n const progress = Math.min(elapsed / duration, 1);\n const easedProgress = easing(progress);\n const isComplete = progress >= 1;\n\n const state: AnimationState = {\n progress,\n easedProgress,\n elapsed,\n isComplete,\n };\n\n onFrameRef.current?.(state);\n\n if (!isComplete) {\n rafIdRef.current = requestAnimationFrame(step);\n } else {\n // Animation complete\n rafIdRef.current = null;\n startTimeRef.current = null;\n setIsAnimating(false);\n onCompleteRef.current?.();\n }\n };\n\n rafIdRef.current = requestAnimationFrame(step);\n }, [duration, easing, cancel]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (rafIdRef.current !== null) {\n cancelAnimationFrame(rafIdRef.current);\n }\n };\n }, []);\n\n return {\n isAnimating,\n start,\n cancel,\n };\n}\n\n/**\n * Interpolate between two values using eased progress.\n */\nexport function interpolate(from: number, to: number, easedProgress: number): number {\n return from + (to - from) * easedProgress;\n}\n"],"names":["INITIAL_STATE","createTimestampedPoint","clientX","clientY","usePointerTracking","options","enabled","primaryOnly","state","setState","React","reset","handlePointerDown","useEffectEvent","event","point","handlePointerMove","prev","handlePointerUp","handlePointerCancel","shouldTrackDocument","useDocumentPointerEvents","DEFAULT_LOCK_THRESHOLD","determineAxis","deltaX","deltaY","absX","absY","useDirectionalLock","tracking","lockThreshold","lockedAxis","setLockedAxis","axis","calculateVelocity","displacement","startTime","currentTime","elapsed","determineDirection","mergeGestureContainerProps","propsArray","mergedStyle","pointerDownHandlers","props","handler","computeScrollSize","element","isHorizontal","isScrollableInDirection","container","direction","current","style","overflow","scrollSize","scrollPos","IDLE_CONTINUOUS_OPERATION_STATE","DEFAULT_SWIPE_THRESHOLDS","DEFAULT_EDGE_WIDTH","IDLE_SWIPE_INPUT_STATE","WHEEL_RESET_TIMEOUT","evaluateSwipeEnd","velocity","thresholds","onSwipeEnd","axisDisplacement","axisVelocity","absDisplacement","absVelocity","useSwipeInput","containerRef","customThresholds","enableWheel","pointerStartFilter","handleSwipeEnd","baseOnPointerDown","onPointerDown","isLocked","lastActiveStateRef","isLockedToSwipeAxisRef","disableTouchMove","handleTouchStart","handleTouchEnd","wheelState","setWheelState","wheelAccumulatedRef","wheelIdleTimerRef","wheelLockedRef","wheelLockedAxisRef","resetWheelState","endWheelSwipe","handleWheel","accumulated","listener","pointerState","lastState","containerProps","getAxisForEdge","edge","isInEdgeZone","edgeWidth","rect","useEdgeSwipeInput","isEdgeGesture","setIsEdgeGesture","inEdge","isInLeftEdge","useNativeGestureGuard","active","preventEdgeBack","preventOverscroll","previousHtmlOverscrollRef","applyHtmlOverscroll","html","easings","DEFAULT_DURATION","useAnimationFrame","duration","easing","onFrame","onComplete","isAnimating","setIsAnimating","rafIdRef","startTimeRef","onFrameRef","onCompleteRef","cancel","start","step","timestamp","progress","easedProgress","isComplete","interpolate","from","to"],"mappings":"qXAmBMA,EAAsC,CAC1C,OAAQ,GACR,MAAO,KACP,QAAS,KACT,UAAW,KACX,YAAa,EACf,EAKMC,EAAyB,CAACC,EAAiBC,KAAuC,CACtF,EAAGD,EACH,EAAGC,EACH,UAAW,YAAY,IAAA,CACzB,GAsBO,SAASC,EAAmBC,EAA8D,CAC/F,KAAM,CAAE,QAAAC,EAAS,YAAAC,EAAc,EAAA,EAASF,EAElC,CAACG,EAAOC,CAAQ,EAAIC,EAAM,SAA+BV,CAAa,EAEtEW,EAAQD,EAAM,YAAY,IAAM,CACpCD,EAAST,CAAa,CACxB,EAAG,CAAA,CAAE,EAECY,EAAoBC,iBAAgBC,GAA8B,CAWtE,GAVI,CAACR,GAKDC,GAAe,CAACO,EAAM,WAKtBA,EAAM,cAAgB,SAAWA,EAAM,SAAW,EACpD,OAGF,MAAMC,EAAQd,EAAuBa,EAAM,QAASA,EAAM,OAAO,EAEjEL,EAAS,CACP,OAAQ,GACR,MAAOM,EACP,QAASA,EACT,UAAWD,EAAM,UACjB,YAAa,EAAA,CACd,CACH,CAAC,EAEKE,EAAoBH,iBAAgBC,GAAwB,CAEhE,GAAIN,EAAM,YAAcM,EAAM,UAC5B,OAGF,MAAMC,EAAQd,EAAuBa,EAAM,QAASA,EAAM,OAAO,EAEjEL,EAAUQ,IAAU,CAClB,GAAGA,EACH,QAASF,CAAA,EACT,CACJ,CAAC,EAEKG,EAAkBL,EAAAA,eAAe,IAAM,CAC3CJ,EAAST,CAAa,CACxB,CAAC,EAEKmB,EAAsBN,EAAAA,eAAe,IAAM,CAC/CJ,EAAS,CAAE,GAAGT,EAAe,YAAa,GAAM,CAClD,CAAC,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strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./FloatingWindow-Cvyokf0m.cjs"),b=require("react/jsx-runtime"),z=require("react"),p=require("./useDocumentPointerEvents-DxDSOtip.cjs"),m=require("./useIsomorphicLayoutEffect-DGRNF4Lf.cjs"),E=require("./styles-qf6ptVLD.cjs"),R=require("./useFloatingState-C4kRaW_R.cjs");function P(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const c=P(z),M=()=>typeof window>"u"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight},j=(e,t,n,r,o)=>{const s=e+n>o.width?Math.max(0,o.width-n):e,i=t+r>o.height?Math.max(0,o.height-r):t;return{x:s,y:i}},S=new Map,L=e=>{const t=`resize-box:${e}`,n=S.get(t);if(n)return n;const r=new Map,o=new ResizeObserver(i=>{for(const a of i){const u=r.get(a.target);u&&u(a)}}),s={observe(i,a){return r.set(i,a),o.observe(i,{box:e}),()=>{r.delete(i),o.unobserve(i)}}};return S.set(t,s),s},C=e=>{const t=e.getBoundingClientRect();return{target:e,contentRect:t,borderBoxSize:[{inlineSize:t.width,blockSize:t.height}],contentBoxSize:[{inlineSize:t.width,blockSize:t.height}],devicePixelContentBoxSize:[]}},k=e=>{if(e.borderBoxSize?.length>0){const t=e.borderBoxSize[0];return new DOMRect(0,0,t.inlineSize,t.blockSize)}return e.contentRect};function I(e,{box:t="content-box"}){const[n,r]=c.useState(null);m.useIsomorphicLayoutEffect(()=>{const s=e.current;if(!s){r(null);return}return r(C(s)),L(t).observe(s,r)},[e,t]);const o=c.useMemo(()=>n?k(n):null,[n]);return{entry:n,rect:o}}const q={border:"none",padding:0,background:"transparent"},B={position:"fixed",zIndex:E.DIALOG_OVERLAY_Z_INDEX},F=typeof window<"u"&&typeof document<"u",_=({anchor:e,onClose:t,children:n,contentClassName:r,contentStyle:o,dataAttributes:s,onKeyDown:i,onPositionChange:a})=>{const u=c.useRef(null),{rect:l}=I(u,{box:"border-box"}),d=c.useMemo(()=>{const f=M(),h=l?.width??0,y=l?.height??0;return j(e.x,e.y,h,y,f)},[e.x,e.y,l?.width,l?.height]),g=p.useEffectEvent(a);c.useEffect(()=>{g?.(d)},[d]);const v=p.useEffectEvent(t);c.useEffect(()=>{const f=h=>{h.target instanceof Node&&u.current&&!u.current.contains(h.target)&&v()};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[]);const D=c.useMemo(()=>({...B,...o,left:d.x,top:d.y}),[o,d.x,d.y]),O=c.useMemo(()=>s?Object.entries(s).reduce((f,[h,y])=>(y==null||(f[`data-${h}`]=y),f),{}):{},[s]);return b.jsx("div",{ref:u,className:r,style:D,onKeyDown:i,...O,children:n})},N=({visible:e,onClose:t,anchor:n,children:r,contentClassName:o,contentStyle:s,dataAttributes:i,onKeyDown:a,onPositionChange:u})=>{const l=c.useRef(null);m.useIsomorphicLayoutEffect(()=>{if(!l.current)return;const g=l.current;e?g.showModal():g.open&&g.close()},[e]);const d=c.useCallback(g=>{g.preventDefault(),t()},[t]);return b.jsx("dialog",{ref:l,style:q,onCancel:d,children:b.jsx(c.Activity,{mode:e?"visible":"hidden",children:b.jsx(_,{anchor:n,onClose:t,contentClassName:o,contentStyle:s,dataAttributes:i,onKeyDown:a,onPositionChange:u,children:r})})})},x=e=>F?b.jsx(N,{...e}):null;x.displayName="DialogOverlay";exports.Drawer=w.Drawer;exports.DrawerLayers=w.DrawerLayers;exports.FloatingWindow=w.FloatingWindow;exports.PopupLayerPortal=w.PopupLayerPortal;exports.SwipeSafeZone=w.SwipeSafeZone;exports.useDrawerState=w.useDrawerState;exports.useFloatingState=R.useFloatingState;exports.DialogOverlay=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./FloatingWindow-DpFpmX1f.cjs"),b=require("react/jsx-runtime"),z=require("react"),p=require("./useDocumentPointerEvents-DxDSOtip.cjs"),m=require("./useIsomorphicLayoutEffect-DGRNF4Lf.cjs"),E=require("./styles-qf6ptVLD.cjs"),R=require("./useFloatingState-C4kRaW_R.cjs");function P(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const c=P(z),M=()=>typeof window>"u"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight},j=(e,t,n,r,o)=>{const s=e+n>o.width?Math.max(0,o.width-n):e,i=t+r>o.height?Math.max(0,o.height-r):t;return{x:s,y:i}},S=new Map,L=e=>{const t=`resize-box:${e}`,n=S.get(t);if(n)return n;const r=new Map,o=new ResizeObserver(i=>{for(const a of i){const u=r.get(a.target);u&&u(a)}}),s={observe(i,a){return r.set(i,a),o.observe(i,{box:e}),()=>{r.delete(i),o.unobserve(i)}}};return S.set(t,s),s},C=e=>{const t=e.getBoundingClientRect();return{target:e,contentRect:t,borderBoxSize:[{inlineSize:t.width,blockSize:t.height}],contentBoxSize:[{inlineSize:t.width,blockSize:t.height}],devicePixelContentBoxSize:[]}},k=e=>{if(e.borderBoxSize?.length>0){const t=e.borderBoxSize[0];return new DOMRect(0,0,t.inlineSize,t.blockSize)}return e.contentRect};function I(e,{box:t="content-box"}){const[n,r]=c.useState(null);m.useIsomorphicLayoutEffect(()=>{const s=e.current;if(!s){r(null);return}return r(C(s)),L(t).observe(s,r)},[e,t]);const o=c.useMemo(()=>n?k(n):null,[n]);return{entry:n,rect:o}}const q={border:"none",padding:0,background:"transparent"},B={position:"fixed",zIndex:E.DIALOG_OVERLAY_Z_INDEX},F=typeof window<"u"&&typeof document<"u",_=({anchor:e,onClose:t,children:n,contentClassName:r,contentStyle:o,dataAttributes:s,onKeyDown:i,onPositionChange:a})=>{const u=c.useRef(null),{rect:l}=I(u,{box:"border-box"}),d=c.useMemo(()=>{const f=M(),h=l?.width??0,y=l?.height??0;return j(e.x,e.y,h,y,f)},[e.x,e.y,l?.width,l?.height]),g=p.useEffectEvent(a);c.useEffect(()=>{g?.(d)},[d]);const v=p.useEffectEvent(t);c.useEffect(()=>{const f=h=>{h.target instanceof Node&&u.current&&!u.current.contains(h.target)&&v()};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[]);const D=c.useMemo(()=>({...B,...o,left:d.x,top:d.y}),[o,d.x,d.y]),O=c.useMemo(()=>s?Object.entries(s).reduce((f,[h,y])=>(y==null||(f[`data-${h}`]=y),f),{}):{},[s]);return b.jsx("div",{ref:u,className:r,style:D,onKeyDown:i,...O,children:n})},N=({visible:e,onClose:t,anchor:n,children:r,contentClassName:o,contentStyle:s,dataAttributes:i,onKeyDown:a,onPositionChange:u})=>{const l=c.useRef(null);m.useIsomorphicLayoutEffect(()=>{if(!l.current)return;const g=l.current;e?g.showModal():g.open&&g.close()},[e]);const d=c.useCallback(g=>{g.preventDefault(),t()},[t]);return b.jsx("dialog",{ref:l,style:q,onCancel:d,children:b.jsx(c.Activity,{mode:e?"visible":"hidden",children:b.jsx(_,{anchor:n,onClose:t,contentClassName:o,contentStyle:s,dataAttributes:i,onKeyDown:a,onPositionChange:u,children:r})})})},x=e=>F?b.jsx(N,{...e}):null;x.displayName="DialogOverlay";exports.Drawer=w.Drawer;exports.DrawerLayers=w.DrawerLayers;exports.FloatingWindow=w.FloatingWindow;exports.PopupLayerPortal=w.PopupLayerPortal;exports.SwipeSafeZone=w.SwipeSafeZone;exports.useDrawerState=w.useDrawerState;exports.useFloatingState=R.useFloatingState;exports.DialogOverlay=x;
2
2
  //# sourceMappingURL=window.cjs.map
package/dist/window.js CHANGED
@@ -1,4 +1,4 @@
1
- import { D as A, b as G, F as K, P as T, S as W, d as q } from "./FloatingWindow-Bw2djgpz.js";
1
+ import { D as A, b as G, F as K, P as T, S as W, d as q } from "./FloatingWindow-CE-WzkNv.js";
2
2
  import { jsx as m } from "react/jsx-runtime";
3
3
  import * as c from "react";
4
4
  import { u as p } from "./useDocumentPointerEvents-DXxw3qWj.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-panel-layout",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "license": "Unlicense",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -74,8 +74,10 @@ export { useDialogContainer } from "../modules/dialog/useDialogContainer.js";
74
74
  // Types
75
75
  export type {
76
76
  ModalProps,
77
+ ModalHandle,
77
78
  ModalHeader,
78
79
  DialogContainerProps,
80
+ DialogContainerHandle,
79
81
  DialogTransitionMode,
80
82
  AlertOptions,
81
83
  ConfirmOptions,
@@ -426,6 +426,75 @@ describe("useSwipeInput", () => {
426
426
  });
427
427
  });
428
428
 
429
+ describe("touch event cleanup on unmount", () => {
430
+ it("removes touchmove listener when unmounted during active touch", () => {
431
+ const containerRef = createRef();
432
+ const removeSpy = vi.spyOn(document, "removeEventListener");
433
+
434
+ const { unmount } = renderHook(() =>
435
+ useSwipeInput({ containerRef, axis: "horizontal" }),
436
+ );
437
+
438
+ // Simulate touchstart to add the touchmove listener
439
+ const touchStartEvent = new TouchEvent("touchstart", {
440
+ touches: [{ clientX: 100, clientY: 100, identifier: 1 } as Touch],
441
+ bubbles: true,
442
+ cancelable: true,
443
+ });
444
+ containerRef.current!.dispatchEvent(touchStartEvent);
445
+
446
+ // Unmount WITHOUT triggering touchend
447
+ unmount();
448
+
449
+ // Verify touchmove listener was removed during cleanup
450
+ const touchMoveRemoveCalls = removeSpy.mock.calls.filter(
451
+ (call) => call[0] === "touchmove",
452
+ );
453
+ expect(touchMoveRemoveCalls.length).toBeGreaterThanOrEqual(1);
454
+
455
+ removeSpy.mockRestore();
456
+ });
457
+
458
+ it("touch scroll should work after component unmount", () => {
459
+ const containerRef = createRef();
460
+
461
+ const { unmount } = renderHook(() =>
462
+ useSwipeInput({ containerRef, axis: "horizontal" }),
463
+ );
464
+
465
+ // Simulate touchstart
466
+ const touchStartEvent = new TouchEvent("touchstart", {
467
+ touches: [{ clientX: 100, clientY: 100, identifier: 1 } as Touch],
468
+ bubbles: true,
469
+ cancelable: true,
470
+ });
471
+ containerRef.current!.dispatchEvent(touchStartEvent);
472
+
473
+ // Unmount without touchend (simulates navigation during touch)
474
+ unmount();
475
+
476
+ // After unmount, touchmove should NOT be prevented
477
+ // Create a new touchmove event and verify it's not prevented
478
+ let wasDefaultPrevented = false;
479
+ const touchMoveEvent = new TouchEvent("touchmove", {
480
+ touches: [{ clientX: 150, clientY: 100, identifier: 1 } as Touch],
481
+ bubbles: true,
482
+ cancelable: true,
483
+ });
484
+
485
+ // Add a listener to check if default was prevented
486
+ const checkListener = (e: Event) => {
487
+ wasDefaultPrevented = e.defaultPrevented;
488
+ };
489
+ document.addEventListener("touchmove", checkListener);
490
+ document.dispatchEvent(touchMoveEvent);
491
+ document.removeEventListener("touchmove", checkListener);
492
+
493
+ // The touchmove should NOT be prevented after unmount
494
+ expect(wasDefaultPrevented).toBe(false);
495
+ });
496
+ });
497
+
429
498
  describe("wheel swipe (trackpad two-finger swipe)", () => {
430
499
  const createContainerRef = (): React.RefObject<HTMLDivElement> => {
431
500
  const element = document.createElement("div");
@@ -139,6 +139,8 @@ export function useSwipeInput(options: UseSwipeInputOptions): UseSwipeInputResul
139
139
  container.removeEventListener("touchstart", handleTouchStart);
140
140
  document.removeEventListener("touchend", handleTouchEnd);
141
141
  document.removeEventListener("touchcancel", handleTouchEnd);
142
+ // Must also remove disableTouchMove in case unmount happens during active touch
143
+ document.removeEventListener("touchmove", disableTouchMove);
142
144
  };
143
145
  }, [containerRef, enabled]);
144
146
 
@@ -2,7 +2,7 @@
2
2
  * @file Base dialog container component using native <dialog> element
3
3
  */
4
4
  import * as React from "react";
5
- import type { DialogContainerProps } from "./types.js";
5
+ import type { DialogContainerProps, DialogContainerHandle } from "./types.js";
6
6
  import { useDialogContainer } from "./useDialogContainer.js";
7
7
  import { SwipeDialogContainer } from "./SwipeDialogContainer.js";
8
8
  import {
@@ -35,9 +35,12 @@ const contentStyle: React.CSSProperties = {
35
35
 
36
36
  const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
37
37
 
38
- type DialogContainerImplProps = DialogContainerProps;
38
+ type DialogContainerImplProps = DialogContainerProps & {
39
+ ref?: React.Ref<DialogContainerHandle>;
40
+ };
39
41
 
40
42
  const DialogContainerImpl: React.FC<DialogContainerImplProps> = ({
43
+ ref,
41
44
  visible,
42
45
  onClose,
43
46
  children,
@@ -62,6 +65,17 @@ const DialogContainerImpl: React.FC<DialogContainerImplProps> = ({
62
65
  preventBodyScroll,
63
66
  });
64
67
 
68
+ // For CSS mode, triggerClose just calls onClose immediately
69
+ // (CSS transitions handle the animation via visibility state)
70
+ const triggerClose = React.useCallback(async (): Promise<void> => {
71
+ onClose();
72
+ }, [onClose]);
73
+
74
+ // Expose triggerClose via ref for API consistency
75
+ React.useImperativeHandle(ref, () => ({
76
+ triggerClose,
77
+ }), [triggerClose]);
78
+
65
79
  const backdropStyle = React.useMemo((): string => {
66
80
  if (transitionMode === "none") {
67
81
  return `
@@ -171,18 +185,38 @@ const DialogContainerImpl: React.FC<DialogContainerImplProps> = ({
171
185
  * <div>Swipe down to close</div>
172
186
  * </DialogContainer>
173
187
  * ```
188
+ *
189
+ * @example Using ref to trigger close animation
190
+ * ```tsx
191
+ * const dialogRef = useRef<DialogContainerHandle>(null);
192
+ *
193
+ * <DialogContainer
194
+ * ref={dialogRef}
195
+ * visible={isOpen}
196
+ * onClose={() => setIsOpen(false)}
197
+ * transitionMode="swipe"
198
+ * >
199
+ * <button onClick={() => dialogRef.current?.triggerClose()}>
200
+ * Close with animation
201
+ * </button>
202
+ * </DialogContainer>
203
+ * ```
174
204
  */
175
- export const DialogContainer: React.FC<DialogContainerProps> = (props) => {
205
+ type DialogContainerComponentProps = DialogContainerProps & {
206
+ ref?: React.Ref<DialogContainerHandle>;
207
+ };
208
+
209
+ export const DialogContainer: React.FC<DialogContainerComponentProps> = ({ ref, ...props }) => {
176
210
  if (!isBrowser) {
177
211
  return null;
178
212
  }
179
213
 
180
214
  // Use SwipeDialogContainer for swipe mode
181
215
  if (props.transitionMode === "swipe") {
182
- return <SwipeDialogContainer {...props} />;
216
+ return <SwipeDialogContainer ref={ref} {...props} />;
183
217
  }
184
218
 
185
- return <DialogContainerImpl {...props} />;
219
+ return <DialogContainerImpl ref={ref} {...props} />;
186
220
  };
187
221
 
188
222
  DialogContainer.displayName = "DialogContainer";
@@ -2,7 +2,7 @@
2
2
  * @file Modal component - Centered modal dialog with optional chrome
3
3
  */
4
4
  import * as React from "react";
5
- import type { ModalProps } from "./types";
5
+ import type { ModalProps, ModalHandle, DialogContainerHandle } from "./types";
6
6
  import { DialogContainer } from "./DialogContainer";
7
7
  import {
8
8
  FloatingPanelFrame,
@@ -59,7 +59,11 @@ const ModalContentWithChrome: React.FC<ModalContentProps> = ({
59
59
  >
60
60
  <FloatingPanelTitle>{header?.title}</FloatingPanelTitle>
61
61
  <React.Activity mode={shouldShowClose ? "visible" : "hidden"}>
62
- <FloatingPanelCloseButton onClick={onClose} aria-label="Close modal" style={{ marginLeft: "auto" }} />
62
+ <FloatingPanelCloseButton
63
+ onClick={onClose}
64
+ aria-label="Close modal"
65
+ style={{ marginLeft: "auto" }}
66
+ />
63
67
  </React.Activity>
64
68
  </FloatingPanelHeader>
65
69
  </React.Activity>
@@ -79,6 +83,10 @@ const ModalContentRenderer: React.FC<ModalContentRendererProps> = ({ chrome, chi
79
83
  return <>{children}</>;
80
84
  };
81
85
 
86
+ type ModalComponentProps = ModalProps & {
87
+ ref?: React.Ref<ModalHandle>;
88
+ };
89
+
82
90
  /**
83
91
  * Modal component for displaying centered dialogs.
84
92
  * Uses native <dialog> element for proper accessibility and top-layer rendering.
@@ -98,8 +106,26 @@ const ModalContentRenderer: React.FC<ModalContentRendererProps> = ({ chrome, chi
98
106
  * </form>
99
107
  * </Modal>
100
108
  * ```
109
+ *
110
+ * @example Using ref to trigger close animation
111
+ * ```tsx
112
+ * const modalRef = useRef<ModalHandle>(null);
113
+ *
114
+ * <Modal
115
+ * ref={modalRef}
116
+ * visible={isOpen}
117
+ * onClose={() => setIsOpen(false)}
118
+ * transitionMode="swipe"
119
+ * header={{ title: "Settings" }}
120
+ * >
121
+ * <button onClick={() => modalRef.current?.triggerClose()}>
122
+ * Close with animation
123
+ * </button>
124
+ * </Modal>
125
+ * ```
101
126
  */
102
- export const Modal: React.FC<ModalProps> = ({
127
+ export const Modal: React.FC<ModalComponentProps> = ({
128
+ ref: externalRef,
103
129
  visible,
104
130
  onClose,
105
131
  children,
@@ -124,6 +150,21 @@ export const Modal: React.FC<ModalProps> = ({
124
150
  openDirection = "center",
125
151
  useViewTransition = false,
126
152
  }) => {
153
+ // Internal ref to DialogContainer for close button
154
+ const internalRef = React.useRef<DialogContainerHandle>(null);
155
+
156
+ // Merge refs - expose the same handle to external ref
157
+ React.useImperativeHandle(externalRef, () => ({
158
+ triggerClose: async () => {
159
+ await internalRef.current?.triggerClose();
160
+ },
161
+ }), []);
162
+
163
+ // Handler for close button that triggers animation
164
+ const handleCloseButtonClick = React.useCallback(() => {
165
+ // Use triggerClose to animate, which will call onClose when complete
166
+ internalRef.current?.triggerClose();
167
+ }, []);
127
168
  const computedStyle = React.useMemo((): React.CSSProperties => {
128
169
  const style: React.CSSProperties = { ...modalContentStyle };
129
170
 
@@ -147,6 +188,7 @@ export const Modal: React.FC<ModalProps> = ({
147
188
 
148
189
  return (
149
190
  <DialogContainer
191
+ ref={internalRef}
150
192
  visible={visible}
151
193
  onClose={onClose}
152
194
  position="center"
@@ -169,7 +211,7 @@ export const Modal: React.FC<ModalProps> = ({
169
211
  chrome={chrome}
170
212
  header={header}
171
213
  dismissible={dismissible}
172
- onClose={onClose}
214
+ onClose={handleCloseButtonClick}
173
215
  contentStyle={propContentStyle}
174
216
  >
175
217
  {children}
@@ -6,7 +6,7 @@
6
6
  * positioning and custom transform animations.
7
7
  */
8
8
  import * as React from "react";
9
- import type { DialogContainerProps } from "./types.js";
9
+ import type { DialogContainerProps, DialogContainerHandle } from "./types.js";
10
10
  import { useDialogContainer } from "./useDialogContainer.js";
11
11
  import { useDialogSwipeInput } from "./useDialogSwipeInput.js";
12
12
  import { useDialogTransform } from "./useDialogTransform.js";
@@ -43,13 +43,18 @@ const backdropStyle: React.CSSProperties = {
43
43
  willChange: "opacity",
44
44
  };
45
45
 
46
+ type SwipeDialogContainerProps = DialogContainerProps & {
47
+ ref?: React.Ref<DialogContainerHandle>;
48
+ };
49
+
46
50
  /**
47
51
  * Swipeable dialog container with multi-phase animation.
48
52
  *
49
53
  * Uses native <dialog> for top layer positioning and custom JS animations
50
54
  * for swipe-to-dismiss functionality.
51
55
  */
52
- export const SwipeDialogContainer: React.FC<DialogContainerProps> = ({
56
+ export const SwipeDialogContainer: React.FC<SwipeDialogContainerProps> = ({
57
+ ref,
53
58
  visible,
54
59
  onClose,
55
60
  children,
@@ -106,6 +111,11 @@ export const SwipeDialogContainer: React.FC<DialogContainerProps> = ({
106
111
  onCloseComplete: onClose,
107
112
  });
108
113
 
114
+ // Expose triggerClose via ref
115
+ React.useImperativeHandle(ref, () => ({
116
+ triggerClose,
117
+ }), [triggerClose]);
118
+
109
119
  // Handle backdrop click
110
120
  const handleBackdropClick = React.useCallback(() => {
111
121
  if (!dismissible) {
@@ -4,6 +4,15 @@
4
4
  import type * as React from "react";
5
5
  import type { Position } from "../../types";
6
6
 
7
+ /**
8
+ * Handle exposed by DialogContainer via ref.
9
+ * Allows programmatic control of dialog animations.
10
+ */
11
+ export type DialogContainerHandle = {
12
+ /** Trigger the close animation. Returns a promise that resolves when animation completes. */
13
+ triggerClose: () => Promise<void>;
14
+ };
15
+
7
16
  /**
8
17
  * Transition mode for dialog animations
9
18
  * - "none": No animation
@@ -68,6 +77,11 @@ export type ModalHeader = {
68
77
  showCloseButton?: boolean;
69
78
  };
70
79
 
80
+ /**
81
+ * Alias for DialogContainerHandle (used by Modal)
82
+ */
83
+ export type ModalHandle = DialogContainerHandle;
84
+
71
85
  /**
72
86
  * Props for Modal component
73
87
  */
@@ -1,2 +0,0 @@
1
- "use strict";const V=require("react"),b=require("./useDocumentPointerEvents-DxDSOtip.cjs");function K(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const o=K(V),L={isDown:!1,start:null,current:null,pointerId:null,wasCanceled:!1},z=(t,e)=>({x:t,y:e,timestamp:performance.now()});function H(t){const{enabled:e,primaryOnly:r=!0}=t,[n,s]=o.useState(L),i=o.useCallback(()=>{s(L)},[]),u=b.useEffectEvent(d=>{if(!e||r&&!d.isPrimary||d.pointerType==="mouse"&&d.button!==0)return;const m=z(d.clientX,d.clientY);s({isDown:!0,start:m,current:m,pointerId:d.pointerId,wasCanceled:!1})}),l=b.useEffectEvent(d=>{if(n.pointerId!==d.pointerId)return;const m=z(d.clientX,d.clientY);s(E=>({...E,current:m}))}),a=b.useEffectEvent(()=>{s(L)}),h=b.useEffectEvent(()=>{s({...L,wasCanceled:!0})}),c=n.isDown?e:!1;return b.useDocumentPointerEvents(c,{onMove:l,onUp:a,onCancel:h}),o.useEffect(()=>{!e&&n.isDown&&i()},[e,n.isDown,i]),{state:n,onPointerDown:u,reset:i}}const Z=10,J=(t,e)=>{const r=Math.abs(t),n=Math.abs(e);return r===0&&n===0?null:r>n*1.5?"horizontal":n>r*1.5?"vertical":null};function Q(t){const{tracking:e,lockThreshold:r=Z}=t,[n,s]=o.useState(null),i=o.useCallback(()=>{s(null)},[]);return o.useEffect(()=>{if(!e.isDown){n!==null&&i();return}if(n!==null||!e.start||!e.current)return;const u=e.current.x-e.start.x,l=e.current.y-e.start.y;if(Math.max(Math.abs(u),Math.abs(l))<r)return;const h=J(u,l);h!==null&&s(h)},[e.isDown,e.start,e.current,n,r,i]),{lockedAxis:n,isLocked:n!==null,reset:i}}const W=(t,e,r)=>{const n=r-e;return n<=0?0:t/n},O=t=>t>0?1:t<0?-1:0,$=(...t)=>{const e={},r=[];for(const s of t)Object.assign(e,s.style),s.onPointerDown&&r.push(s.onPointerDown);return{onPointerDown:s=>{for(const i of r)i?.(s)},style:e}};function ee(t,e){return e?t.scrollWidth-t.clientWidth:t.scrollHeight-t.clientHeight}function te(t,e,r,n){let s=t;for(;s!==null&&s!==e;){const i=getComputedStyle(s),u=r==="x",l=u?i.overflowX:i.overflowY;if(l==="scroll"||l==="auto"){const h=ee(s,u);if(h>0){const c=u?s.scrollLeft:s.scrollTop;if(n===-1&&c>1||n===1&&c<h-1)return!0}}s=s.parentElement}return!1}const ne={phase:"idle",displacement:{x:0,y:0},velocity:{x:0,y:0}},G={distanceThreshold:100,velocityThreshold:.5,lockThreshold:10},B=20,R={phase:"idle",displacement:{x:0,y:0},velocity:{x:0,y:0},direction:0},re=150,N=(t,e,r,n,s)=>{const i=r==="horizontal"?t.x:t.y,u=r==="horizontal"?e.x:e.y,l=Math.abs(i),a=Math.abs(u);if(l>=n.distanceThreshold||a>=n.velocityThreshold){const c=O(i);s?.({phase:"ended",displacement:t,velocity:e,direction:c})}};function se(t){const{containerRef:e,axis:r,enabled:n=!0,thresholds:s,onSwipeEnd:i,enableWheel:u=!0,pointerStartFilter:l}=t,a={...G,...s},h=b.useEffectEvent(i),{state:c,onPointerDown:d}=H({enabled:n}),m=o.useCallback(f=>{if(n){if(l){const p=e.current;if(!p||!l(f,p))return}d(f)}},[n,l,e,d]),{lockedAxis:E,isLocked:D}=Q({tracking:c,lockThreshold:a.lockThreshold}),T=o.useRef(null),S=o.useRef(!1);o.useEffect(()=>{S.current=D?E===r:!1},[D,E,r]),o.useEffect(()=>{const f=e.current;if(!f||!n)return;const p=P=>{P.preventDefault()},v=P=>{S.current&&P.preventDefault(),document.addEventListener("touchmove",p,{passive:!1})},w=()=>{document.removeEventListener("touchmove",p)};return document.addEventListener("touchend",w),document.addEventListener("touchcancel",w),f.addEventListener("touchstart",v,{passive:!1}),()=>{f.removeEventListener("touchstart",v),document.removeEventListener("touchend",w),document.removeEventListener("touchcancel",w)}},[e,n]);const[x,k]=o.useState(R),g=o.useRef({x:0,y:0}),y=o.useRef(null),A=o.useRef(!1),C=o.useRef(null),_=o.useCallback(()=>{g.current={x:0,y:0},A.current=!1,C.current=null,k(R)},[]),Y=o.useCallback(()=>{const f={...g.current};N(f,{x:0,y:0},r,a,h),_()},[r,a,h,_]),M=b.useEffectEvent(f=>{if(!n||!u||c.isDown)return;const{deltaX:p,deltaY:v}=f;if(!A.current){const F=Math.abs(p),U=Math.abs(v);(F>=a.lockThreshold||U>=a.lockThreshold)&&(A.current=!0,C.current=F>U?"horizontal":"vertical")}if(A.current&&C.current!==r)return;g.current.x-=p,g.current.y-=v;const w=g.current,P=r==="horizontal"?w.x:w.y;k({phase:"swiping",displacement:{...w},velocity:{x:0,y:0},direction:O(P)}),y.current!==null&&clearTimeout(y.current),y.current=setTimeout(Y,re)});o.useEffect(()=>{const f=e.current;if(!f||!n||!u)return;const p=v=>{v.preventDefault(),M(v)};return f.addEventListener("wheel",p,{passive:!1}),()=>{f.removeEventListener("wheel",p),y.current!==null&&clearTimeout(y.current)}},[e,n,u,M]),o.useEffect(()=>()=>{y.current!==null&&clearTimeout(y.current)},[]);const I=o.useMemo(()=>{if(!c.isDown||!c.start||!c.current)return R;const f=c.current.x-c.start.x,p=c.current.y-c.start.y,v={x:f,y:p},w={x:W(f,c.start.timestamp,c.current.timestamp),y:W(p,c.start.timestamp,c.current.timestamp)};return!D||E!==r?{phase:"tracking",displacement:v,velocity:w,direction:0}:{phase:"swiping",displacement:v,velocity:w,direction:O(r==="horizontal"?f:p)}},[c.isDown,c.start,c.current,D,E,r]);o.useEffect(()=>{I.phase!=="idle"&&(T.current=I)},[I]),o.useEffect(()=>{if(c.isDown)return;const f=T.current;!f||f.phase!=="swiping"&&f.phase!=="tracking"||(T.current=null,!c.wasCanceled&&N(f.displacement,f.velocity,r,a,h))},[c.isDown,c.wasCanceled,r,a,h]);const j=I.phase!=="idle"?I:x,q=o.useMemo(()=>({onPointerDown:m,style:{touchAction:r==="horizontal"?"pan-y pinch-zoom":"pan-x pinch-zoom",userSelect:"none",WebkitUserSelect:"none"}}),[r,m]);return{state:j,containerProps:q}}const oe=t=>t==="left"||t==="right"?"horizontal":"vertical",ce=(t,e,r,n,s)=>{const i=r.getBoundingClientRect();switch(n){case"left":return t>=i.left&&t<=i.left+s;case"right":return t>=i.right-s&&t<=i.right;case"top":return e>=i.top&&e<=i.top+s;case"bottom":return e>=i.bottom-s&&e<=i.bottom}};function ie(t){const{containerRef:e,edge:r,edgeWidth:n=B,enabled:s=!0,thresholds:i,onSwipeEnd:u}=t,l={...G,...i},a=oe(r),[h,c]=o.useState(!1),d=o.useCallback((T,S)=>{const x=ce(T.clientX,T.clientY,S,r,n);return c(x),x},[r,n]),{state:m,containerProps:E}=se({containerRef:e,axis:a,enabled:s,thresholds:l,onSwipeEnd:u,enableWheel:!1,pointerStartFilter:d});return o.useEffect(()=>{m.phase==="idle"&&c(!1)},[m.phase]),{isEdgeGesture:h,state:h?m:R,containerProps:E}}const ue=(t,e,r)=>{const n=e.getBoundingClientRect();return t>=n.left&&t<=n.left+r};function le(t){const{containerRef:e,active:r,preventEdgeBack:n=!0,preventOverscroll:s=!0,edgeWidth:i=B}=t,u=o.useRef(null),l=o.useCallback(()=>{if(!s)return;const c=document.documentElement;u.current===null&&(u.current=c.style.overscrollBehavior),c.style.overscrollBehavior="none"},[s]);o.useEffect(()=>{r||!s||u.current!==null&&(document.documentElement.style.overscrollBehavior=u.current,u.current=null)},[r,s]),o.useEffect(()=>()=>{u.current!==null&&(document.documentElement.style.overscrollBehavior=u.current,u.current=null)},[]);const a=o.useCallback(c=>{if(!n)return;const d=e.current;d&&c.pointerType==="touch"&&ue(c.clientX,d,i)&&(l(),c.preventDefault())},[n,e,i,l]);return{containerProps:o.useMemo(()=>({onPointerDown:n?a:void 0,style:{overscrollBehavior:s?"contain":void 0,WebkitOverflowScrolling:"touch"}}),[s,n,a])}}const X={easeOutExpo:t=>t===1?1:1-Math.pow(2,-10*t)},ae=300;function fe(t){const{duration:e=ae,easing:r=X.easeOutExpo,onFrame:n,onComplete:s}=t,[i,u]=o.useState(!1),l=o.useRef(null),a=o.useRef(null),h=o.useRef(n),c=o.useRef(s);o.useEffect(()=>{h.current=n,c.current=s},[n,s]);const d=o.useCallback(()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),a.current=null,u(!1)},[]),m=o.useCallback(()=>{d(),u(!0),a.current=null;const E=D=>{a.current===null&&(a.current=D);const T=D-a.current,S=Math.min(T/e,1),x=r(S),k=S>=1,g={progress:S,easedProgress:x,elapsed:T,isComplete:k};h.current?.(g),k?(l.current=null,a.current=null,u(!1),c.current?.()):l.current=requestAnimationFrame(E)};l.current=requestAnimationFrame(E)},[e,r,d]);return o.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]),{isAnimating:i,start:m,cancel:d}}function de(t,e,r){return t+(e-t)*r}exports.IDLE_CONTINUOUS_OPERATION_STATE=ne;exports.IDLE_SWIPE_INPUT_STATE=R;exports.easings=X;exports.interpolate=de;exports.isScrollableInDirection=te;exports.mergeGestureContainerProps=$;exports.useAnimationFrame=fe;exports.useEdgeSwipeInput=ie;exports.useNativeGestureGuard=le;exports.usePointerTracking=H;
2
- //# sourceMappingURL=useAnimationFrame-BZ6D2lMq.cjs.map