All files / src/gestures PanSession.ts

91.49% Statements 86/94
79.17% Branches 38/48
100% Functions 13/13
92.94% Lines 79/85

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312  33x 33x 33x 33x 33x 33x                                                                                                                                                                                                       33x                 38x         38x         38x                   38x             38x     38x     38x   38x 38x   38x 38x 38x   38x   38x   38x 38x     38x             38x 72x   72x 72x           72x   72x   58x 58x 58x   58x   58x 34x 34x     58x     38x 66x 66x     66x           66x     38x 37x   37x   37x         37x 2x     37x     33x 1x     33x 71x 71x   33x           141x       290x     145x 145x                 145x       203x       145x 87x     58x 58x 58x 58x 152x 152x       7x   145x     58x       58x 58x       58x         58x     58x       58x    
import { EventInfo } from "../events/types"
import { isTouchEvent, isMouseEvent } from "./utils/event-type"
import { extractEventInfo } from "../events/event-info"
import sync, { getFrameData, cancelSync } from "framesync"
import { secondsToMilliseconds } from "../utils/time-conversion"
import { addPointerEvent } from "../events/use-pointer-event"
import { distance, pipe } from "popmotion"
import { Point, TransformPoint } from "../projection/geometry/types"
 
export type AnyPointerEvent = MouseEvent | TouchEvent | PointerEvent
 
/**
 * Passed in to pan event handlers like `onPan` the `PanInfo` object contains
 * information about the current state of the tap gesture such as its
 * `point`, `delta`, `offset` and `velocity`.
 *
 * ```jsx
 * <motion.div onPan={(event, info) => {
 *   console.log(info.point.x, info.point.y)
 * }} />
 * ```
 *
 * @public
 */
export interface PanInfo {
    /**
     * Contains `x` and `y` values for the current pan position relative
     * to the device or page.
     *
     * ```jsx
     * function onPan(event, info) {
     *   console.log(info.point.x, info.point.y)
     * }
     *
     * <motion.div onPan={onPan} />
     * ```
     *
     * @public
     */
    point: Point
    /**
     * Contains `x` and `y` values for the distance moved since
     * the last event.
     *
     * ```jsx
     * function onPan(event, info) {
     *   console.log(info.delta.x, info.delta.y)
     * }
     *
     * <motion.div onPan={onPan} />
     * ```
     *
     * @public
     */
    delta: Point
    /**
     * Contains `x` and `y` values for the distance moved from
     * the first pan event.
     *
     * ```jsx
     * function onPan(event, info) {
     *   console.log(info.offset.x, info.offset.y)
     * }
     *
     * <motion.div onPan={onPan} />
     * ```
     *
     * @public
     */
    offset: Point
    /**
     * Contains `x` and `y` values for the current velocity of the pointer, in px/ms.
     *
     * ```jsx
     * function onPan(event, info) {
     *   console.log(info.velocity.x, info.velocity.y)
     * }
     *
     * <motion.div onPan={onPan} />
     * ```
     *
     * @public
     */
    velocity: Point
}
 
export type PanHandler = (event: Event, info: PanInfo) => void
interface PanSessionHandlers {
    onSessionStart: PanHandler
    onStart: PanHandler
    onMove: PanHandler
    onEnd: PanHandler
    onSessionEnd: PanHandler
}
 
interface PanSessionOptions {
    transformPagePoint?: TransformPoint
}
 
interface TimestampedPoint extends Point {
    timestamp: number
}
 
/**
 * @internal
 */
export class PanSession {
    /**
     * @internal
     */
    private history: TimestampedPoint[]
 
    /**
     * @internal
     */
    private startEvent: AnyPointerEvent | null = null
 
    /**
     * @internal
     */
    private lastMoveEvent: AnyPointerEvent | null = null
 
    /**
     * @internal
     */
    private lastMoveEventInfo: EventInfo | null = null
 
    /**
     * @internal
     */
    private transformPagePoint?: TransformPoint
 
    /**
     * @internal
     */
    private handlers: Partial<PanSessionHandlers> = {}
 
    /**
     * @internal
     */
    private removeListeners: Function
 
    constructor(
        event: AnyPointerEvent,
        handlers: Partial<PanSessionHandlers>,
        { transformPagePoint }: PanSessionOptions = {}
    ) {
        // If we have more than one touch, don't start detecting this gesture
        Iif (isTouchEvent(event) && event.touches.length > 1) return
 
        this.handlers = handlers
        this.transformPagePoint = transformPagePoint
 
        const info = extractEventInfo(event)
        const initialInfo = transformPoint(info, this.transformPagePoint)
        const { point } = initialInfo
 
        const { timestamp } = getFrameData()
 
        this.history = [{ ...point, timestamp }]
 
        const { onSessionStart } = handlers
        onSessionStart &&
            onSessionStart(event, getPanInfo(initialInfo, this.history))
 
        this.removeListeners = pipe(
            addPointerEvent(window, "pointermove", this.handlePointerMove),
            addPointerEvent(window, "pointerup", this.handlePointerUp),
            addPointerEvent(window, "pointercancel", this.handlePointerUp)
        )
    }
 
    private updatePoint = () => {
        Iif (!(this.lastMoveEvent && this.lastMoveEventInfo)) return
 
        const info = getPanInfo(this.lastMoveEventInfo, this.history)
        const isPanStarted = this.startEvent !== null
 
        // Only start panning if the offset is larger than 3 pixels. If we make it
        // any larger than this we'll want to reset the pointer history
        // on the first update to avoid visual snapping to the cursoe.
        const isDistancePastThreshold =
            distance(info.offset, { x: 0, y: 0 }) >= 3
 
        if (!isPanStarted && !isDistancePastThreshold) return
 
        const { point } = info
        const { timestamp } = getFrameData()
        this.history.push({ ...point, timestamp })
 
        const { onStart, onMove } = this.handlers
 
        if (!isPanStarted) {
            onStart && onStart(this.lastMoveEvent, info)
            this.startEvent = this.lastMoveEvent
        }
 
        onMove && onMove(this.lastMoveEvent, info)
    }
 
    private handlePointerMove = (event: AnyPointerEvent, info: EventInfo) => {
        this.lastMoveEvent = event
        this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint)
 
        // Because Safari doesn't trigger mouseup events when it's above a `<select>`
        Iif (isMouseEvent(event) && event.buttons === 0) {
            this.handlePointerUp(event, info)
            return
        }
 
        // Throttle mouse move event to once per frame
        sync.update(this.updatePoint, true)
    }
 
    private handlePointerUp = (event: AnyPointerEvent, info: EventInfo) => {
        this.end()
 
        const { onEnd, onSessionEnd } = this.handlers
 
        const panInfo = getPanInfo(
            transformPoint(info, this.transformPagePoint),
            this.history
        )
 
        if (this.startEvent && onEnd) {
            onEnd(event, panInfo)
        }
 
        onSessionEnd && onSessionEnd(event, panInfo)
    }
 
    updateHandlers(handlers: Partial<PanSessionHandlers>) {
        this.handlers = handlers
    }
 
    end() {
        this.removeListeners && this.removeListeners()
        cancelSync.update(this.updatePoint)
    }
}
 
function transformPoint(
    info: EventInfo,
    transformPagePoint?: (point: Point) => Point
) {
    return transformPagePoint ? { point: transformPagePoint(info.point) } : info
}
 
function subtractPoint(a: Point, b: Point): Point {
    return { x: a.x - b.x, y: a.y - b.y }
}
 
function getPanInfo({ point }: EventInfo, history: TimestampedPoint[]) {
    return {
        point,
        delta: subtractPoint(point, lastDevicePoint(history)),
        offset: subtractPoint(point, startDevicePoint(history)),
        velocity: getVelocity(history, 0.1),
    }
}
 
function startDevicePoint(history: TimestampedPoint[]): TimestampedPoint {
    return history[0]
}
 
function lastDevicePoint(history: TimestampedPoint[]): TimestampedPoint {
    return history[history.length - 1]
}
 
function getVelocity(history: TimestampedPoint[], timeDelta: number): Point {
    if (history.length < 2) {
        return { x: 0, y: 0 }
    }
 
    let i = history.length - 1
    let timestampedPoint: TimestampedPoint | null = null
    const lastPoint = lastDevicePoint(history)
    while (i >= 0) {
        timestampedPoint = history[i]
        if (
            lastPoint.timestamp - timestampedPoint.timestamp >
            secondsToMilliseconds(timeDelta)
        ) {
            break
        }
        i--
    }
 
    Iif (!timestampedPoint) {
        return { x: 0, y: 0 }
    }
 
    const time = (lastPoint.timestamp - timestampedPoint.timestamp) / 1000
    Iif (time === 0) {
        return { x: 0, y: 0 }
    }
 
    const currentVelocity = {
        x: (lastPoint.x - timestampedPoint.x) / time,
        y: (lastPoint.y - timestampedPoint.y) / time,
    }
 
    Iif (currentVelocity.x === Infinity) {
        currentVelocity.x = 0
    }
    Iif (currentVelocity.y === Infinity) {
        currentVelocity.y = 0
    }
 
    return currentVelocity
}