All files / src/gestures use-pan-gesture.ts

100% Statements 24/24
91.67% Branches 11/12
100% Functions 5/5
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 6033x 33x 33x 33x 33x                             33x 14x 14x 14x 14x 14x   14x 14x 14x   14x               2x 2x       14x 7x 1x         3x         14x   14x    
import { useRef, useContext, useEffect } from "react"
import { MotionConfigContext } from "../context/MotionConfigContext"
import { useUnmountEffect } from "../utils/use-unmount-effect"
import { usePointerEvent } from "../events/use-pointer-event"
import { PanSession, PanInfo, AnyPointerEvent } from "./PanSession"
import { FeatureProps } from "../motion/features/types"
 
/**
 *
 * @param handlers -
 * @param ref -
 *
 * @internalremarks
 * Currently this sets new pan gesture functions every render. The memo route has been explored
 * in the past but ultimately we're still creating new functions every render. An optimisation
 * to explore is creating the pan gestures and loading them into a `ref`.
 *
 * @internal
 */
export function usePanGesture({
    onPan,
    onPanStart,
    onPanEnd,
    onPanSessionStart,
    visualElement,
}: FeatureProps) {
    const hasPanEvents = onPan || onPanStart || onPanEnd || onPanSessionStart
    const panSession = useRef<PanSession | null>(null)
    const { transformPagePoint } = useContext(MotionConfigContext)
 
    const handlers = {
        onSessionStart: onPanSessionStart,
        onStart: onPanStart,
        onMove: onPan,
        onEnd: (
            event: MouseEvent | TouchEvent | PointerEvent,
            info: PanInfo
        ) => {
            panSession.current = null
            onPanEnd && onPanEnd(event, info)
        },
    }
 
    useEffect(() => {
        if (panSession.current !== null) {
            panSession.current.updateHandlers(handlers)
        }
    })
 
    function onPointerDown(event: AnyPointerEvent) {
        panSession.current = new PanSession(event, handlers, {
            transformPagePoint,
        })
    }
 
    usePointerEvent(visualElement, "pointerdown", hasPanEvents && onPointerDown)
 
    useUnmountEffect(() => panSession.current && panSession.current.end())
}