All files / src/gestures/drag VisualElementDragControls.ts

71.33% Statements 204/286
64.49% Branches 138/214
72.22% Functions 26/36
73.79% Lines 183/248

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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 65033x 33x   33x 33x 33x 33x                 33x       33x 33x 33x 33x   33x 33x         33x 33x 33x 33x   33x                                 33x               74x   74x 74x   74x         74x   74x         74x     74x     35x   35x         35x   35x     35x   35x         35x   32x   32x 31x 31x     31x     29x   29x   29x   29x 29x 29x           29x 58x         58x                   58x       29x 29x           35x       53x 53x 53x 53x 53x     53x   47x   47x 3x     3x 2x     3x       44x 44x               44x           44x     35x 34x   35x                       33x 34x 34x 34x   29x 29x   29x 29x     33x 34x 34x 34x   34x 34x   34x 34x 28x 28x     34x     33x 88x     88x   72x 72x     72x 13x             72x     33x 29x 29x 29x   29x         29x 7x         22x       29x           29x           7x 14x 14x                 33x                                                                                             33x   29x 29x 29x 29x 29x 29x 29x   29x   29x 58x 10x     48x   48x               48x 48x   48x                             48x       29x     33x       48x 48x     35x 70x                 33x 262x 262x   262x               33x                                             33x                                                                                                             35x 35x 35x         35x       34x 34x       35x 107x 107x         35x   35x         35x 35x 35x     35x           35x               35x                                 35x 32x 32x 32x       33x 435x   435x 435x 435x 435x 435x 435x 2610x 435x                   33x             146x                             6x   3x   3x 1x 2x 1x     3x     33x            
import { invariant } from "hey-listen"
import { PanSession, AnyPointerEvent, PanInfo } from "../../gestures/PanSession"
import { ResolvedConstraints } from "./types"
import { Lock, getGlobalLock } from "./utils/lock"
import { isRefObject } from "../../utils/is-ref-object"
import { addPointerEvent } from "../../events/use-pointer-event"
import {
    calcRelativeConstraints,
    calcViewportConstraints,
    applyConstraints,
    rebaseAxisConstraints,
    resolveDragElastic,
    defaultElastic,
    calcOrigin,
} from "./utils/constraints"
import { AnimationType } from "../../render/utils/types"
import { VisualElement } from "../../render/types"
import { MotionProps } from "../../motion/types"
import { Point } from "../../projection/geometry/types"
import { createBox } from "../../projection/geometry/models"
import { eachAxis } from "../../projection/utils/each-axis"
import { measurePageBox } from "../../projection/utils/measure"
import { extractEventInfo } from "../../events/event-info"
import { Transition } from "../../types"
import { startAnimation } from "../../animation/utils/transitions"
import {
    convertBoundingBoxToBox,
    convertBoxToBoundingBox,
} from "../../projection/geometry/conversion"
import { LayoutUpdateData } from "../../projection/node/types"
import { addDomEvent } from "../../events/use-dom-event"
import { mix } from "popmotion"
import { percent } from "style-value-types"
import { calcLength } from "../../projection/geometry/delta-calc"
 
export const elementDragControls = new WeakMap<
    VisualElement,
    VisualElementDragControls
>()
 
export interface DragControlOptions {
    snapToCursor?: boolean
    cursorProgress?: Point
}
 
type DragDirection = "x" | "y"
 
/**
 *
 */
// let latestPointerEvent: AnyPointerEvent
 
export class VisualElementDragControls {
    private visualElement: VisualElement
 
    private panSession?: PanSession
 
    // This is a reference to the global drag gesture lock, ensuring only one component
    // can "capture" the drag of one or both axes.
    // TODO: Look into moving this into pansession?
    private openGlobalLock: Lock | null = null
 
    isDragging = false
    private currentDirection: DragDirection | null = null
 
    private originPoint: Point = { x: 0, y: 0 }
 
    /**
     * The permitted boundaries of travel, in pixels.
     */
    private constraints: ResolvedConstraints | false = false
 
    private hasMutatedConstraints = false
 
    /**
     * The per-axis resolved elastic values.
     */
    private elastic = createBox()
 
    constructor(visualElement: VisualElement) {
        this.visualElement = visualElement
    }
 
    start(
        originEvent: AnyPointerEvent,
        { snapToCursor = false }: DragControlOptions = {}
    ) {
        /**
         * Don't start dragging if this component is exiting
         */
        Iif (this.visualElement.isPresent === false) return
 
        const onSessionStart = (event: AnyPointerEvent) => {
            // Stop any animations on both axis values immediately. This allows the user to throw and catch
            // the component.
            this.stopAnimation()
 
            Iif (snapToCursor) {
                this.snapToCursor(extractEventInfo(event, "page").point)
            }
        }
 
        const onStart = (event: AnyPointerEvent, info: PanInfo) => {
            // Attempt to grab the global drag gesture lock - maybe make this part of PanSession
            const { drag, dragPropagation, onDragStart } = this.getProps()
 
            if (drag && !dragPropagation) {
                Iif (this.openGlobalLock) this.openGlobalLock()
                this.openGlobalLock = getGlobalLock(drag)
 
                // If we don 't have the lock, don't start dragging
                if (!this.openGlobalLock) return
            }
 
            this.isDragging = true
 
            this.currentDirection = null
 
            this.resolveConstraints()
 
            Eif (this.visualElement.projection) {
                this.visualElement.projection.isAnimationBlocked = true
                this.visualElement.projection.target = undefined
            }
 
            /**
             * Record gesture origin
             */
            eachAxis((axis) => {
                let current = this.getAxisMotionValue(axis).get() || 0
 
                /**
                 * If the MotionValue is a percentage value convert to px
                 */
                Iif (percent.test(current)) {
                    const measuredAxis =
                        this.visualElement.projection?.layout?.actual[axis]
 
                    if (measuredAxis) {
                        const length = calcLength(measuredAxis)
                        current = length * (parseFloat(current) / 100)
                    }
                }
 
                this.originPoint[axis] = current
            })
 
            // Fire onDragStart event
            onDragStart?.(event, info)
            this.visualElement.animationState?.setActive(
                AnimationType.Drag,
                true
            )
        }
 
        const onMove = (event: AnyPointerEvent, info: PanInfo) => {
            // latestPointerEvent = event
 
            const {
                dragPropagation,
                dragDirectionLock,
                onDirectionLock,
                onDrag,
            } = this.getProps()
 
            // If we didn't successfully receive the gesture lock, early return.
            if (!dragPropagation && !this.openGlobalLock) return
 
            const { offset } = info
            // Attempt to detect drag direction if directionLock is true
            if (dragDirectionLock && this.currentDirection === null) {
                this.currentDirection = getCurrentDirection(offset)
 
                // If we've successfully set a direction, notify listener
                if (this.currentDirection !== null) {
                    onDirectionLock?.(this.currentDirection)
                }
 
                return
            }
 
            // Update each point with the latest position
            this.updateAxis("x", info.point, offset)
            this.updateAxis("y", info.point, offset)
 
            /**
             * Ideally we would leave the renderer to fire naturally at the end of
             * this frame but if the element is about to change layout as the result
             * of a re-render we want to ensure the browser can read the latest
             * bounding box to ensure the pointer and element don't fall out of sync.
             */
            this.visualElement.syncRender()
 
            /**
             * This must fire after the syncRender call as it might trigger a state
             * change which itself might trigger a layout update.
             */
            onDrag?.(event, info)
        }
 
        const onSessionEnd = (event: AnyPointerEvent, info: PanInfo) =>
            this.stop(event, info)
 
        this.panSession = new PanSession(
            originEvent,
            {
                onSessionStart,
                onStart,
                onMove,
                onSessionEnd,
            },
            { transformPagePoint: this.visualElement.getTransformPagePoint() }
        )
    }
 
    private stop(event: AnyPointerEvent, info: PanInfo) {
        const isDragging = this.isDragging
        this.cancel()
        if (!isDragging) return
 
        const { velocity } = info
        this.startAnimation(velocity)
 
        const { onDragEnd } = this.getProps()
        onDragEnd?.(event, info)
    }
 
    private cancel() {
        this.isDragging = false
        Eif (this.visualElement.projection) {
            this.visualElement.projection.isAnimationBlocked = false
        }
        this.panSession?.end()
        this.panSession = undefined
 
        const { dragPropagation } = this.getProps()
        if (!dragPropagation && this.openGlobalLock) {
            this.openGlobalLock()
            this.openGlobalLock = null
        }
 
        this.visualElement.animationState?.setActive(AnimationType.Drag, false)
    }
 
    private updateAxis(axis: DragDirection, _point: Point, offset?: Point) {
        const { drag } = this.getProps()
 
        // If we're not dragging this axis, do an early return.
        if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return
 
        const axisValue = this.getAxisMotionValue(axis)
        let next = this.originPoint[axis] + offset[axis]
 
        // Apply constraints
        if (this.constraints && this.constraints[axis]) {
            next = applyConstraints(
                next,
                this.constraints[axis],
                this.elastic[axis]
            )
        }
 
        axisValue.set(next)
    }
 
    private resolveConstraints() {
        const { dragConstraints, dragElastic } = this.getProps()
        const { layout } = this.visualElement.projection || {}
        const prevConstraints = this.constraints
 
        Iif (dragConstraints && isRefObject(dragConstraints)) {
            if (!this.constraints) {
                this.constraints = this.resolveRefConstraints()
            }
        } else {
            if (dragConstraints && layout) {
                this.constraints = calcRelativeConstraints(
                    layout.actual,
                    dragConstraints
                )
            } else {
                this.constraints = false
            }
        }
 
        this.elastic = resolveDragElastic(dragElastic)
 
        /**
         * If we're outputting to external MotionValues, we want to rebase the measured constraints
         * from viewport-relative to component-relative.
         */
        if (
            prevConstraints !== this.constraints &&
            layout &&
            this.constraints &&
            !this.hasMutatedConstraints
        ) {
            eachAxis((axis) => {
                Eif (this.getAxisMotionValue(axis)) {
                    this.constraints[axis] = rebaseAxisConstraints(
                        layout.actual[axis],
                        this.constraints[axis]
                    )
                }
            })
        }
    }
 
    private resolveRefConstraints() {
        const { dragConstraints: constraints, onMeasureDragConstraints } =
            this.getProps()
        if (!constraints || !isRefObject(constraints)) return false
 
        const constraintsElement = constraints.current as HTMLElement
 
        invariant(
            constraintsElement !== null,
            "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop."
        )
 
        const { projection } = this.visualElement
 
        // TODO
        if (!projection || !projection.layout) return false
 
        const constraintsBox = measurePageBox(
            constraintsElement,
            projection.root!,
            this.visualElement.getTransformPagePoint()
        )
 
        let measuredConstraints = calcViewportConstraints(
            projection.layout.actual,
            constraintsBox
        )
 
        /**
         * If there's an onMeasureDragConstraints listener we call it and
         * if different constraints are returned, set constraints to that
         */
        if (onMeasureDragConstraints) {
            const userConstraints = onMeasureDragConstraints(
                convertBoxToBoundingBox(measuredConstraints)
            )
 
            this.hasMutatedConstraints = !!userConstraints
 
            if (userConstraints) {
                measuredConstraints = convertBoundingBoxToBox(userConstraints)
            }
        }
 
        return measuredConstraints
    }
 
    private startAnimation(velocity: Point) {
        const {
            drag,
            dragMomentum,
            dragElastic,
            dragTransition,
            dragSnapToOrigin,
            onDragTransitionEnd,
        } = this.getProps()
 
        const constraints = this.constraints || {}
 
        const momentumAnimations = eachAxis((axis) => {
            if (!shouldDrag(axis, drag, this.currentDirection)) {
                return
            }
 
            let transition = constraints?.[axis] ?? {}
 
            Iif (dragSnapToOrigin) transition = { min: 0, max: 0 }
 
            /**
             * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame
             * of spring animations so we should look into adding a disable spring option to `inertia`.
             * We could do something here where we affect the `bounceStiffness` and `bounceDamping`
             * using the value of `dragElastic`.
             */
            const bounceStiffness = dragElastic ? 200 : 1000000
            const bounceDamping = dragElastic ? 40 : 10000000
 
            const inertia = {
                type: "inertia",
                velocity: dragMomentum ? velocity[axis] : 0,
                bounceStiffness,
                bounceDamping,
                timeConstant: 750,
                restDelta: 1,
                restSpeed: 10,
                ...dragTransition,
                ...transition,
            }
 
            // If we're not animating on an externally-provided `MotionValue` we can use the
            // component's animation controls which will handle interactions with whileHover (etc),
            // otherwise we just have to animate the `MotionValue` itself.
            return this.startAxisValueAnimation(axis, inertia)
        })
 
        // Run all animations and then resolve the new drag constraints.
        return Promise.all(momentumAnimations).then(onDragTransitionEnd)
    }
 
    private startAxisValueAnimation(
        axis: DragDirection,
        transition: Transition
    ) {
        const axisValue = this.getAxisMotionValue(axis)
        return startAnimation(axis, axisValue, 0, transition)
    }
 
    private stopAnimation() {
        eachAxis((axis) => this.getAxisMotionValue(axis).stop())
    }
 
    /**
     * Drag works differently depending on which props are provided.
     *
     * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
     * - Otherwise, we apply the delta to the x/y motion values.
     */
    private getAxisMotionValue(axis: DragDirection) {
        const dragKey = "_drag" + axis.toUpperCase()
        const externalMotionValue = this.visualElement.getProps()[dragKey]
 
        return externalMotionValue
            ? externalMotionValue
            : this.visualElement.getValue(
                  axis,
                  this.visualElement.getProps().initial?.[axis] ?? 0
              )
    }
 
    private snapToCursor(point: Point) {
        eachAxis((axis) => {
            const { drag } = this.getProps()
 
            // If we're not dragging this axis, do an early return.
            if (!shouldDrag(axis, drag, this.currentDirection)) return
 
            const { projection } = this.visualElement
            const axisValue = this.getAxisMotionValue(axis)
 
            if (projection && projection.layout) {
                const { min, max } = projection.layout.actual[axis]
 
                axisValue.set(point[axis] - mix(min, max, 0.5))
            }
        })
    }
 
    /**
     * When the viewport resizes we want to check if the measured constraints
     * have changed and, if so, reposition the element within those new constraints
     * relative to where it was before the resize.
     */
    scalePositionWithinConstraints() {
        const { drag, dragConstraints } = this.getProps()
        const { projection } = this.visualElement
        if (!isRefObject(dragConstraints) || !projection || !this.constraints)
            return
 
        /**
         * Stop current animations as there can be visual glitching if we try to do
         * this mid-animation
         */
        this.stopAnimation()
 
        /**
         * Record the relative position of the dragged element relative to the
         * constraints box and save as a progress value.
         */
        const boxProgress = { x: 0, y: 0 }
        eachAxis((axis) => {
            const axisValue = this.getAxisMotionValue(axis)
            if (axisValue) {
                const latest = axisValue.get()
                boxProgress[axis] = calcOrigin(
                    { min: latest, max: latest },
                    this.constraints[axis]
                )
            }
        })
 
        /**
         * Update the layout of this element and resolve the latest drag constraints
         */
        const { transformTemplate } = this.visualElement.getProps()
        this.visualElement.getInstance().style.transform = transformTemplate
            ? transformTemplate({}, "")
            : "none"
        projection.root?.updateScroll()
        projection.updateLayout()
        this.resolveConstraints()
 
        /**
         * For each axis, calculate the current progress of the layout axis
         * within the new constraints.
         */
        eachAxis((axis) => {
            if (!shouldDrag(axis, drag, null)) return
 
            /**
             * Calculate a new transform based on the previous box progress
             */
            const axisValue = this.getAxisMotionValue(axis)
            const { min, max } = this.constraints[axis]
            axisValue.set(mix(min, max, boxProgress[axis]))
        })
    }
 
    addListeners() {
        elementDragControls.set(this.visualElement, this)
        const element = this.visualElement.getInstance()
 
        /**
         * Attach a pointerdown event listener on this DOM element to initiate drag tracking.
         */
        const stopPointerListener = addPointerEvent(
            element,
            "pointerdown",
            (event) => {
                const { drag, dragListener = true } = this.getProps()
                drag && dragListener && this.start(event)
            }
        )
 
        const measureDragConstraints = () => {
            const { dragConstraints } = this.getProps()
            Iif (isRefObject(dragConstraints)) {
                this.constraints = this.resolveRefConstraints()
            }
        }
 
        const { projection } = this.visualElement
 
        const stopMeasureLayoutListener = projection!.addEventListener(
            "measure",
            measureDragConstraints
        )
 
        Eif (projection && !projection!.layout) {
            projection.root?.updateScroll()
            projection.updateLayout()
        }
 
        measureDragConstraints()
 
        /**
         * Attach a window resize listener to scale the draggable target within its defined
         * constraints as the window resizes.
         */
        const stopResizeListener = addDomEvent(window, "resize", () => {
            this.scalePositionWithinConstraints()
        })
 
        /**
         * If the element's layout changes, calculate the delta and apply that to
         * the drag gesture's origin point.
         */
        projection!.addEventListener("didUpdate", (({
            delta,
            hasLayoutChanged,
        }: LayoutUpdateData) => {
            if (this.isDragging && hasLayoutChanged) {
                eachAxis((axis) => {
                    const motionValue = this.getAxisMotionValue(axis)
                    if (!motionValue) return
 
                    this.originPoint[axis] += delta[axis].translate
                    motionValue.set(motionValue.get() + delta[axis].translate)
                })
 
                this.visualElement.syncRender()
            }
        }) as any)
 
        return () => {
            stopResizeListener()
            stopPointerListener()
            stopMeasureLayoutListener()
        }
    }
 
    getProps(): MotionProps {
        const props = this.visualElement.getProps()
        const {
            drag = false,
            dragDirectionLock = false,
            dragPropagation = false,
            dragConstraints = false,
            dragElastic = defaultElastic,
            dragMomentum = true,
        } = props
        return {
            ...props,
            drag,
            dragDirectionLock,
            dragPropagation,
            dragConstraints,
            dragElastic,
            dragMomentum,
        }
    }
}
 
function shouldDrag(
    direction: DragDirection,
    drag: boolean | DragDirection | undefined,
    currentDirection: null | DragDirection
) {
    return (
        (drag === true || drag === direction) &&
        (currentDirection === null || currentDirection === direction)
    )
}
 
/**
 * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower
 * than the provided threshold, return `null`.
 *
 * @param offset - The x/y offset from origin.
 * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.
 */
function getCurrentDirection(
    offset: Point,
    ElockThreshold = 10
): DragDirection | null {
    let direction: DragDirection | null = null
 
    if (Math.abs(offset.y) > lockThreshold) {
        direction = "y"
    } else if (Math.abs(offset.x) > lockThreshold) {
        direction = "x"
    }
 
    return direction
}
 
export function expectsResolvedDragConstraints({
    dragConstraints,
    onMeasureDragConstraints,
}: MotionProps) {
    return isRefObject(dragConstraints) && !!onMeasureDragConstraints
}