motion-dom 14.3.1 → 14.4.0
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.
- package/dist/cjs/index.js +6669 -5559
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/animation/animate/element.mjs +16 -1
- package/dist/es/animation/animate/element.mjs.map +1 -1
- package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +5 -1
- package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -1
- package/dist/es/events/add-pointer-event.mjs +9 -0
- package/dist/es/events/add-pointer-event.mjs.map +1 -0
- package/dist/es/events/event-info.mjs +14 -0
- package/dist/es/events/event-info.mjs.map +1 -0
- package/dist/es/gestures/drag/VisualElementDragControls.mjs +606 -0
- package/dist/es/gestures/drag/VisualElementDragControls.mjs.map +1 -0
- package/dist/es/gestures/drag/index.mjs +82 -0
- package/dist/es/gestures/drag/index.mjs.map +1 -0
- package/dist/es/gestures/drag/utils/constraints.mjs +129 -0
- package/dist/es/gestures/drag/utils/constraints.mjs.map +1 -0
- package/dist/es/gestures/pan/PanSession.mjs +269 -0
- package/dist/es/gestures/pan/PanSession.mjs.map +1 -0
- package/dist/es/index.mjs +6 -0
- package/dist/es/index.mjs.map +1 -1
- package/dist/es/layout/LayoutAnimationBuilder.mjs +21 -1
- package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
- package/dist/es/utils/distance.mjs +10 -0
- package/dist/es/utils/distance.mjs.map +1 -0
- package/dist/index.d.ts +238 -3
- package/dist/motion-dom.dev.js +6687 -5577
- package/dist/motion-dom.js +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VisualElementDragControls.mjs","sources":["../../../../src/gestures/drag/VisualElementDragControls.ts"],"sourcesContent":["import { Axis, invariant, Point } from \"motion-utils\"\nimport { animateMotionValue } from \"../../animation/interfaces/motion-value\"\nimport type { Transition } from \"../../animation/types\"\nimport { getVariableValue } from \"../../animation/utils/css-variables-conversion\"\nimport { isCSSVariableToken } from \"../../animation/utils/is-css-variable\"\nimport { addDomEvent } from \"../../events/add-dom-event\"\nimport { addPointerEvent } from \"../../events/add-pointer-event\"\nimport { frame } from \"../../frameloop/frame\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport {\n convertBoundingBoxToBox,\n convertBoxToBoundingBox,\n} from \"../../projection/geometry/conversion\"\nimport { calcLength } from \"../../projection/geometry/delta-calc\"\nimport { createBox } from \"../../projection/geometry/models\"\nimport type { LayoutUpdateData } from \"../../projection/node/types\"\nimport { eachAxis } from \"../../projection/utils/each-axis\"\nimport { measurePageBox } from \"../../projection/utils/measure\"\nimport type { VisualElement } from \"../../render/VisualElement\"\nimport { resize } from \"../../resize\"\nimport { mixNumber } from \"../../utils/mix/number\"\nimport { percent, px } from \"../../value/types/numbers/units\"\nimport { addValueToWillChange } from \"../../value/will-change/add-will-change\"\nimport type { PanInfo } from \"../pan/types\"\nimport { PanSession } from \"../pan/PanSession\"\nimport { isElementTextInput } from \"../press/utils/is-keyboard-accessible\"\nimport { setDragLock } from \"./state/set-active\"\nimport type { ResolvedConstraints } from \"./types\"\nimport {\n applyConstraints,\n calcOrigin,\n calcRelativeConstraints,\n calcViewportConstraints,\n defaultElastic,\n rebaseAxisConstraints,\n resolveDragElastic,\n} from \"./utils/constraints\"\n\nexport const elementDragControls = new WeakMap<\n VisualElement,\n VisualElementDragControls\n>()\n\nexport interface DragControlOptions {\n /**\n * This distance after which dragging starts and a direction is locked in.\n *\n * @public\n */\n distanceThreshold?: number\n\n /**\n * Whether to immediately snap to the cursor when dragging starts.\n *\n * @public\n */\n snapToCursor?: boolean\n}\n\ntype DragDirection = \"x\" | \"y\"\n\nexport class VisualElementDragControls {\n private visualElement: VisualElement<HTMLElement>\n\n private panSession?: PanSession\n\n private openDragLock: VoidFunction | null = null\n\n isDragging = false\n private currentDirection: DragDirection | null = null\n\n private originPoint: Point = { x: 0, y: 0 }\n\n /**\n * The permitted boundaries of travel, in pixels.\n */\n private constraints: ResolvedConstraints | false = false\n\n private hasMutatedConstraints = false\n\n /**\n * The per-axis resolved elastic values.\n */\n private elastic = createBox()\n\n /**\n * The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments.\n */\n private latestPointerEvent: PointerEvent | null = null\n\n /**\n * The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments.\n */\n private latestPanInfo: PanInfo | null = null\n\n /**\n * Where drag options are read from. By default these are the\n * VisualElement's props (as with a React `motion` component), but the\n * vanilla `drag()` API provides its own.\n */\n private readProps: () => MotionNodeOptions\n\n constructor(\n visualElement: VisualElement<HTMLElement>,\n readProps: () => MotionNodeOptions = () => visualElement.getProps()\n ) {\n this.visualElement = visualElement\n this.readProps = readProps\n }\n\n start(\n originEvent: PointerEvent,\n { snapToCursor = false, distanceThreshold }: DragControlOptions = {}\n ) {\n /**\n * Don't start dragging if this component is exiting\n */\n const { presenceContext } = this.visualElement\n if (presenceContext && presenceContext.isPresent === false) return\n\n const onSessionStart = (event: PointerEvent) => {\n if (snapToCursor) this.snapToCursor(event)\n this.stopAnimation()\n }\n\n const onStart = (event: PointerEvent, info: PanInfo) => {\n // Attempt to grab the global drag gesture lock - maybe make this part of PanSession\n const { drag, dragPropagation, onDragStart } = this.getProps()\n\n if (drag && !dragPropagation) {\n if (this.openDragLock) this.openDragLock()\n\n this.openDragLock = setDragLock(drag)\n\n // If we don 't have the lock, don't start dragging\n if (!this.openDragLock) return\n }\n\n this.latestPointerEvent = event\n this.latestPanInfo = info\n this.isDragging = true\n\n this.currentDirection = null\n\n this.resolveConstraints()\n\n if (this.visualElement.projection) {\n this.visualElement.projection.isAnimationBlocked = true\n this.visualElement.projection.target = undefined\n }\n\n /**\n * Record gesture origin and pointer offset\n */\n eachAxis((axis) => {\n let current = this.getAxisMotionValue(axis).get() || 0\n\n /**\n * If the MotionValue is a CSS variable, like \"var(--y)\",\n * resolve it so it can be converted to px below.\n */\n if (isCSSVariableToken(current)) {\n current =\n getVariableValue(\n current,\n this.visualElement.current!\n ) || 0\n }\n\n /**\n * If the MotionValue is a px or percentage value convert to px\n */\n if (px.test(current)) {\n current = parseFloat(current)\n } else if (percent.test(current)) {\n const { projection } = this.visualElement\n\n if (projection && projection.layout) {\n const measuredAxis = projection.layout.layoutBox[axis]\n\n if (measuredAxis) {\n const length = calcLength(measuredAxis)\n current = length * (parseFloat(current) / 100)\n }\n }\n }\n\n this.originPoint[axis] = current\n })\n\n // Fire onDragStart event\n if (onDragStart) {\n frame.update(() => onDragStart(event, info), false, true)\n }\n\n addValueToWillChange(this.visualElement, \"transform\")\n\n const { animationState } = this.visualElement\n animationState && animationState.setActive(\"whileDrag\", true)\n }\n\n const onMove = (event: PointerEvent, info: PanInfo) => {\n this.latestPointerEvent = event\n this.latestPanInfo = info\n\n const {\n dragPropagation,\n dragDirectionLock,\n onDirectionLock,\n onDrag,\n } = this.getProps()\n\n // If we didn't successfully receive the gesture lock, early return.\n if (!dragPropagation && !this.openDragLock) return\n\n const { offset } = info\n // Attempt to detect drag direction if directionLock is true\n if (dragDirectionLock && this.currentDirection === null) {\n this.currentDirection = getCurrentDirection(offset)\n\n /**\n * Wait for more movement until a direction is set. Once\n * it is, apply this move too: it can be the last before\n * release when the browser coalesces a fast gesture.\n */\n if (this.currentDirection === null) return\n\n onDirectionLock && onDirectionLock(this.currentDirection)\n }\n\n // Update each point with the latest position\n this.updateAxis(\"x\", info.point, offset)\n this.updateAxis(\"y\", info.point, offset)\n\n /**\n * Ideally we would leave the renderer to fire naturally at the end of\n * this frame but if the element is about to change layout as the result\n * of a re-render we want to ensure the browser can read the latest\n * bounding box to ensure the pointer and element don't fall out of sync.\n */\n this.visualElement.render()\n\n /**\n * This must fire after the render call as it might trigger a state\n * change which itself might trigger a layout update.\n */\n if (onDrag) {\n frame.update(() => onDrag(event, info), false, true)\n }\n }\n\n const onSessionEnd = (event: PointerEvent, info: PanInfo) => {\n this.latestPointerEvent = event\n this.latestPanInfo = info\n\n this.stop(event, info)\n\n this.latestPointerEvent = null\n this.latestPanInfo = null\n }\n\n const resumeAnimation = () => {\n const { dragSnapToOrigin: snap } = this.getProps()\n if (snap || this.constraints) {\n this.startAnimation({ x: 0, y: 0 })\n }\n }\n\n const { dragSnapToOrigin } = this.getProps()\n this.panSession = new PanSession(\n originEvent,\n {\n onSessionStart,\n onStart,\n onMove,\n onSessionEnd,\n resumeAnimation,\n },\n {\n transformPagePoint: this.visualElement.getTransformPagePoint(),\n dragSnapToOrigin,\n distanceThreshold,\n contextWindow:\n this.visualElement.current?.ownerDocument.defaultView,\n element: this.visualElement.current,\n }\n )\n }\n\n stop(event?: PointerEvent, panInfo?: PanInfo) {\n const finalEvent = event || this.latestPointerEvent\n const finalPanInfo = panInfo || this.latestPanInfo\n\n const isDragging = this.isDragging\n this.cancel()\n if (!isDragging || !finalPanInfo || !finalEvent) return\n\n const { velocity } = finalPanInfo\n this.startAnimation(velocity)\n\n const { onDragEnd } = this.getProps()\n if (onDragEnd) {\n frame.postRender(() => onDragEnd(finalEvent, finalPanInfo))\n }\n }\n\n cancel() {\n this.isDragging = false\n\n const { projection, animationState } = this.visualElement\n\n if (projection) {\n projection.isAnimationBlocked = false\n }\n\n this.endPanSession()\n\n const { dragPropagation } = this.getProps()\n\n if (!dragPropagation && this.openDragLock) {\n this.openDragLock()\n this.openDragLock = null\n }\n\n animationState && animationState.setActive(\"whileDrag\", false)\n }\n\n /**\n * Clean up the pan session without modifying other drag state.\n * This is used during unmount to ensure event listeners are removed\n * without affecting projection animations or drag locks.\n */\n endPanSession() {\n this.panSession && this.panSession.end()\n this.panSession = undefined\n }\n\n private updateAxis(axis: DragDirection, _point: Point, offset?: Point) {\n const { drag } = this.getProps()\n\n // If we're not dragging this axis, do an early return.\n if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return\n\n const axisValue = this.getAxisMotionValue(axis)\n let next = this.originPoint[axis] + offset[axis]\n\n // Apply constraints\n if (this.constraints && this.constraints[axis]) {\n next = applyConstraints(\n next,\n this.constraints[axis],\n this.elastic[axis]\n )\n }\n\n axisValue.set(next)\n }\n\n private resolveConstraints() {\n const { dragConstraints, dragElastic } = this.getProps()\n\n const layout =\n this.visualElement.projection &&\n !this.visualElement.projection.layout\n ? this.visualElement.projection.measure(false)\n : this.visualElement.projection?.layout\n\n const prevConstraints = this.constraints\n\n if (isElementConstraints(dragConstraints)) {\n if (!this.constraints) {\n this.constraints = this.resolveRefConstraints()\n }\n } else {\n if (dragConstraints && layout) {\n this.constraints = calcRelativeConstraints(\n layout.layoutBox,\n dragConstraints\n )\n } else {\n this.constraints = false\n }\n }\n\n this.elastic = resolveDragElastic(dragElastic)\n\n /**\n * If we're outputting to external MotionValues, we want to rebase the measured constraints\n * from viewport-relative to component-relative. This only applies to relative (non-ref)\n * constraints, as ref-based constraints from calcViewportConstraints are already in the\n * correct coordinate space for the motion value transform offset.\n */\n if (\n prevConstraints !== this.constraints &&\n !isElementConstraints(dragConstraints) &&\n layout &&\n this.constraints &&\n !this.hasMutatedConstraints\n ) {\n eachAxis((axis) => {\n if (\n this.constraints !== false &&\n this.getAxisMotionValue(axis)\n ) {\n this.constraints[axis] = rebaseAxisConstraints(\n layout.layoutBox[axis],\n this.constraints[axis]\n )\n }\n })\n }\n }\n\n private resolveRefConstraints() {\n const { dragConstraints: constraints, onMeasureDragConstraints } =\n this.getProps()\n if (!isElementConstraints(constraints)) return false\n\n const constraintsElement = resolveConstraintsElement(constraints)\n\n invariant(\n !!constraintsElement,\n \"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.\",\n \"drag-constraints-ref\"\n )\n\n const { projection } = this.visualElement\n\n // TODO\n if (!projection || !projection.layout) return false\n\n /**\n * Refresh the root scroll offset so the constraint's viewport box\n * translates to correct page coordinates. The scroll captured at\n * drag mount can be stale if the document was scrolled afterwards —\n * e.g. via the browser restoring scroll on refresh, or an ancestor\n * layout effect running after this element's mount (#2829).\n *\n * Clear the cached scroll first so `updateScroll` bypasses its\n * per-animationId cache and re-reads the live value.\n */\n if (projection.root) {\n projection.root.scroll = undefined\n projection.root.updateScroll()\n }\n\n const constraintsBox = measurePageBox(\n constraintsElement as HTMLElement,\n projection.root!,\n this.visualElement.getTransformPagePoint()\n )\n\n let measuredConstraints = calcViewportConstraints(\n projection.layout.layoutBox,\n constraintsBox\n )\n\n /**\n * If there's an onMeasureDragConstraints listener we call it and\n * if different constraints are returned, set constraints to that\n */\n if (onMeasureDragConstraints) {\n const userConstraints = onMeasureDragConstraints(\n convertBoxToBoundingBox(measuredConstraints)\n )\n\n this.hasMutatedConstraints = !!userConstraints\n\n if (userConstraints) {\n measuredConstraints = convertBoundingBoxToBox(userConstraints)\n }\n }\n\n return measuredConstraints\n }\n\n private startAnimation(velocity: Point) {\n const {\n drag,\n dragMomentum,\n dragElastic,\n dragTransition,\n dragSnapToOrigin,\n onDragTransitionEnd,\n } = this.getProps()\n\n const constraints: Partial<ResolvedConstraints> = this.constraints || {}\n\n const momentumAnimations = eachAxis((axis) => {\n if (!shouldDrag(axis, drag, this.currentDirection)) {\n return\n }\n\n let transition = (constraints && constraints[axis]) || {}\n\n if (\n dragSnapToOrigin === true ||\n (dragSnapToOrigin as unknown) === axis\n )\n transition = { min: 0, max: 0 }\n\n /**\n * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame\n * of spring animations so we should look into adding a disable spring option to `inertia`.\n * We could do something here where we affect the `bounceStiffness` and `bounceDamping`\n * using the value of `dragElastic`.\n */\n const bounceStiffness = dragElastic ? 200 : 1000000\n const bounceDamping = dragElastic ? 40 : 10000000\n\n const inertia: Transition = {\n type: \"inertia\",\n velocity: dragMomentum ? velocity[axis] : 0,\n bounceStiffness,\n bounceDamping,\n timeConstant: 750,\n restDelta: 1,\n restSpeed: 10,\n ...dragTransition,\n ...transition,\n }\n\n // If we're not animating on an externally-provided `MotionValue` we can use the\n // component's animation controls which will handle interactions with whileHover (etc),\n // otherwise we just have to animate the `MotionValue` itself.\n return this.startAxisValueAnimation(axis, inertia)\n })\n\n // Run all animations and then resolve the new drag constraints.\n return Promise.all(momentumAnimations).then(onDragTransitionEnd)\n }\n\n private startAxisValueAnimation(\n axis: DragDirection,\n transition: Transition\n ) {\n const axisValue = this.getAxisMotionValue(axis)\n\n addValueToWillChange(this.visualElement, axis)\n\n return axisValue.start(\n animateMotionValue(\n axis,\n axisValue,\n 0,\n transition,\n this.visualElement,\n false\n )\n )\n }\n\n private stopAnimation() {\n eachAxis((axis) => this.getAxisMotionValue(axis).stop())\n }\n\n /**\n * Drag works differently depending on which props are provided.\n *\n * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.\n * - Otherwise, we apply the delta to the x/y motion values.\n */\n private getAxisMotionValue(axis: DragDirection) {\n const dragKey =\n `_drag${axis.toUpperCase()}` as `_drag${Uppercase<DragDirection>}`\n const props = this.readProps()\n const externalMotionValue = props[dragKey]\n\n return externalMotionValue\n ? externalMotionValue\n : this.visualElement.getValue(\n axis,\n this.visualElement.latestValues[axis] ?? 0\n )\n }\n\n /**\n * Measure the live box - projection.layout may or may not include the\n * drag transform, depending on when it was measured.\n */\n private snapToCursor({ clientX, clientY }: PointerEvent) {\n const { drag } = this.getProps()\n const point = { x: clientX, y: clientY }\n const cursor =\n this.visualElement.getTransformPagePoint()?.(point) || point\n const box = this.visualElement.measureViewportBox()\n\n eachAxis((axis) => {\n if (!shouldDrag(axis, drag, this.currentDirection)) return\n\n const axisValue = this.getAxisMotionValue(axis)\n const { min, max } = box[axis]\n\n axisValue.set(\n (axisValue.get() || 0) + cursor[axis] - mixNumber(min, max, 0.5)\n )\n })\n }\n\n /**\n * When the viewport resizes we want to check if the measured constraints\n * have changed and, if so, reposition the element within those new constraints\n * relative to where it was before the resize.\n */\n scalePositionWithinConstraints() {\n if (!this.visualElement.current) return\n\n const { drag, dragConstraints } = this.getProps()\n const { projection } = this.visualElement\n if (\n !isElementConstraints(dragConstraints) ||\n !projection ||\n !this.constraints\n )\n return\n\n /**\n * Stop current animations as there can be visual glitching if we try to do\n * this mid-animation\n */\n this.stopAnimation()\n\n /**\n * Record the relative position of the dragged element relative to the\n * constraints box and save as a progress value.\n */\n const constraints = this.constraints as ResolvedConstraints\n const boxProgress = { x: 0, y: 0 }\n eachAxis((axis) => {\n const latest = this.getAxisMotionValue(axis).get()\n boxProgress[axis] = calcOrigin(\n { min: latest, max: latest },\n constraints[axis] as Axis\n )\n })\n\n /**\n * Update the layout of this element and resolve the latest drag constraints\n */\n const { transformTemplate } = this.visualElement.getProps()\n this.visualElement.current.style.transform = transformTemplate\n ? transformTemplate({}, \"\")\n : \"none\"\n projection.root && projection.root.updateScroll()\n projection.updateLayout()\n\n /**\n * Reset constraints so resolveConstraints() will recalculate them\n * with the freshly measured layout rather than returning the cached value.\n */\n this.constraints = false\n this.resolveConstraints()\n\n /**\n * For each axis, calculate the current progress of the layout axis\n * within the new constraints.\n */\n eachAxis((axis) => {\n const axisValue = this.getAxisMotionValue(axis)\n\n /**\n * An element resting at its origin has no offset to preserve,\n * and re-projecting 0 into the new constraints would move it.\n */\n if (!shouldDrag(axis, drag, null) || !axisValue.get()) return\n\n /**\n * Calculate a new transform based on the previous box progress\n */\n const { min, max } = (this.constraints as ResolvedConstraints)[\n axis\n ] as Axis\n axisValue.set(mixNumber(min, max, boxProgress[axis]))\n })\n\n /**\n * Flush the updated transform to the DOM synchronously to prevent\n * a visual flash at the element's CSS layout position (0,0) when\n * the transform was stripped for measurement.\n */\n this.visualElement.render()\n }\n\n addListeners() {\n if (!this.visualElement.current) return\n elementDragControls.set(this.visualElement, this)\n const element = this.visualElement.current\n\n /**\n * Attach a pointerdown event listener on this DOM element to initiate drag tracking.\n */\n const stopPointerListener = addPointerEvent(\n element,\n \"pointerdown\",\n (event) => {\n const { drag, dragListener = true } = this.getProps()\n const target = event.target as Element\n\n /**\n * Only block drag if clicking on a text input child element\n * (input, textarea, select, contenteditable) where users might\n * want to select text or interact with the control.\n *\n * Buttons and links don't block drag since they don't have\n * click-and-move actions of their own.\n */\n const isClickingTextInputChild =\n target !== element && isElementTextInput(target)\n\n if (drag && dragListener && !isClickingTextInputChild) {\n this.start(event)\n }\n }\n )\n\n /**\n * If using ref-based constraints, observe both the draggable element\n * and the constraint container for size changes via ResizeObserver.\n * Setup is deferred because dragConstraints.current is null when\n * addListeners first runs (React hasn't committed the ref yet).\n */\n let stopResizeObservers: VoidFunction | undefined\n\n const measureDragConstraints = () => {\n const { dragConstraints } = this.getProps()\n const constraintsElement =\n isElementConstraints(dragConstraints) &&\n resolveConstraintsElement(dragConstraints)\n\n if (constraintsElement) {\n this.constraints = this.resolveRefConstraints()\n\n if (!stopResizeObservers) {\n stopResizeObservers = startResizeObservers(\n element,\n constraintsElement as HTMLElement,\n () => this.scalePositionWithinConstraints()\n )\n }\n }\n }\n\n const { projection } = this.visualElement\n\n const stopMeasureLayoutListener = projection!.addEventListener(\n \"measure\",\n measureDragConstraints\n )\n\n if (projection && !projection!.layout) {\n projection.root && projection.root.updateScroll()\n projection.updateLayout()\n }\n\n frame.read(measureDragConstraints)\n\n /**\n * Attach a window resize listener to scale the draggable target within its defined\n * constraints as the window resizes.\n */\n const stopResizeListener = addDomEvent(window, \"resize\", () =>\n this.scalePositionWithinConstraints()\n )\n\n /**\n * If the element's layout changes, calculate the delta and apply that to\n * the drag gesture's origin point.\n */\n const stopLayoutUpdateListener = projection!.addEventListener(\n \"didUpdate\",\n (({ delta, hasLayoutChanged }: LayoutUpdateData) => {\n if (this.isDragging && hasLayoutChanged) {\n eachAxis((axis) => {\n const motionValue = this.getAxisMotionValue(axis)\n if (!motionValue) return\n\n this.originPoint[axis] += delta[axis].translate\n motionValue.set(\n motionValue.get() + delta[axis].translate\n )\n })\n\n this.visualElement.render()\n }\n }) as any\n )\n\n return () => {\n stopResizeListener()\n stopPointerListener()\n stopMeasureLayoutListener()\n stopLayoutUpdateListener && stopLayoutUpdateListener()\n stopResizeObservers && stopResizeObservers()\n }\n }\n\n getProps(): MotionNodeOptions {\n const props = this.readProps()\n const {\n drag = false,\n dragDirectionLock = false,\n dragPropagation = false,\n dragConstraints = false,\n dragElastic = defaultElastic,\n dragMomentum = true,\n } = props\n return {\n ...props,\n drag,\n dragDirectionLock,\n dragPropagation,\n dragConstraints,\n dragElastic,\n dragMomentum,\n }\n }\n}\n\ntype ConstraintsElement = Element | { current: Element | null }\n\n/**\n * `dragConstraints` can be an element, or a ref (`{ current }`) to one.\n */\nfunction isElementConstraints(\n constraints: MotionNodeOptions[\"dragConstraints\"]\n): constraints is ConstraintsElement {\n return (\n !!constraints &&\n typeof constraints === \"object\" &&\n (\"current\" in constraints || \"nodeType\" in constraints)\n )\n}\n\nconst resolveConstraintsElement = (constraints: ConstraintsElement) =>\n \"current\" in constraints ? constraints.current : constraints\n\nfunction skipFirstCall(callback: VoidFunction): VoidFunction {\n let isFirst = true\n return () => {\n if (isFirst) {\n isFirst = false\n return\n }\n callback()\n }\n}\n\nfunction startResizeObservers(\n element: HTMLElement,\n constraintsElement: HTMLElement,\n onResize: VoidFunction\n): VoidFunction {\n const stopElement = resize(element, skipFirstCall(onResize))\n const stopContainer = resize(constraintsElement, skipFirstCall(onResize))\n return () => {\n stopElement()\n stopContainer()\n }\n}\n\nfunction shouldDrag(\n direction: DragDirection,\n drag: boolean | DragDirection | undefined,\n currentDirection: null | DragDirection\n) {\n return (\n (drag === true || drag === direction) &&\n (currentDirection === null || currentDirection === direction)\n )\n}\n\n/**\n * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower\n * than the provided threshold, return `null`.\n *\n * @param offset - The x/y offset from origin.\n * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.\n */\nfunction getCurrentDirection(\n offset: Point,\n lockThreshold = 10\n): DragDirection | null {\n let direction: DragDirection | null = null\n\n if (Math.abs(offset.y) > lockThreshold) {\n direction = \"y\"\n } else if (Math.abs(offset.x) > lockThreshold) {\n direction = \"x\"\n }\n\n return direction\n}\n\nexport function expectsResolvedDragConstraints({\n dragConstraints,\n onMeasureDragConstraints,\n}: MotionNodeOptions)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,SAAS,GAAG,GAAG;IACnB;SAAO,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,aAAa,EAAE;QAC3C,SAAS,GAAG,GAAG;IACnB;AAEA,IAAA,OAAO,SAAS;AACpB;SAEgB,8BAA8B,CAAC,EAC3C,eAAe,EACf,wBAAwB,GACR,EAAA;IAChB,OAAO,oBAAoB,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,wBAAwB;AAC9E;;;;"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { acquireProjectionNode } from '../../layout/LayoutAnimationBuilder.mjs';
|
|
2
|
+
import { resolveElements } from '../../utils/resolve-elements.mjs';
|
|
3
|
+
import { VisualElementDragControls } from './VisualElementDragControls.mjs';
|
|
4
|
+
|
|
5
|
+
const toProps = ({ axis, constraints, elastic, momentum, transition, snapToOrigin, directionLock, propagation, onStart, onMove, onEnd, onDirectionLock, onTransitionEnd, onMeasureConstraints, }) => ({
|
|
6
|
+
drag: axis || true,
|
|
7
|
+
dragConstraints: constraints,
|
|
8
|
+
dragElastic: elastic,
|
|
9
|
+
dragMomentum: momentum,
|
|
10
|
+
dragTransition: transition,
|
|
11
|
+
dragSnapToOrigin: snapToOrigin,
|
|
12
|
+
dragDirectionLock: directionLock,
|
|
13
|
+
dragPropagation: propagation,
|
|
14
|
+
onDragStart: onStart,
|
|
15
|
+
onDrag: onMove,
|
|
16
|
+
onDragEnd: onEnd,
|
|
17
|
+
onDirectionLock,
|
|
18
|
+
onDragTransitionEnd: onTransitionEnd,
|
|
19
|
+
onMeasureDragConstraints: onMeasureConstraints,
|
|
20
|
+
});
|
|
21
|
+
const dragStyles = [
|
|
22
|
+
"user-select",
|
|
23
|
+
"-webkit-user-select",
|
|
24
|
+
"-webkit-touch-callout",
|
|
25
|
+
"touch-action",
|
|
26
|
+
];
|
|
27
|
+
/**
|
|
28
|
+
* Apply the styles React's drag prop applies, so touch input drags
|
|
29
|
+
* instead of panning the page, and text selection and native drag (ghost
|
|
30
|
+
* image) don't interrupt the gesture. Returns a function that restores
|
|
31
|
+
* the element's previous values.
|
|
32
|
+
*/
|
|
33
|
+
function applyDragStyles(element, axis) {
|
|
34
|
+
const { style } = element;
|
|
35
|
+
const draggable = element.getAttribute("draggable");
|
|
36
|
+
const prev = dragStyles.map((key) => style.getPropertyValue(key));
|
|
37
|
+
const touchAction = axis ? "pan-" + (axis === "x" ? "y" : "x") : "none";
|
|
38
|
+
dragStyles.forEach((key, i) => style.setProperty(key, i < 3 ? "none" : touchAction));
|
|
39
|
+
element.setAttribute("draggable", "false");
|
|
40
|
+
return () => {
|
|
41
|
+
dragStyles.forEach((key, i) => style.setProperty(key, prev[i]));
|
|
42
|
+
draggable === null
|
|
43
|
+
? element.removeAttribute("draggable")
|
|
44
|
+
: element.setAttribute("draggable", draggable);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Make elements draggable. Returns a function that removes the gesture.
|
|
49
|
+
*
|
|
50
|
+
* ```javascript
|
|
51
|
+
* const stop = drag("#box", { axis: "x", constraints: { left: 0, right: 300 } })
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* The element's `x` and `y` are motion values shared with `animate()`
|
|
55
|
+
* and `animateLayout()`, so these can animate the element after a drag.
|
|
56
|
+
*
|
|
57
|
+
* @public
|
|
58
|
+
*/
|
|
59
|
+
function drag(elementOrSelector, options = {}) {
|
|
60
|
+
const props = toProps(options);
|
|
61
|
+
const cleanups = resolveElements(elementOrSelector).map((element) => {
|
|
62
|
+
const [node, release] = acquireProjectionNode(element);
|
|
63
|
+
/**
|
|
64
|
+
* Measure layout even when not animating it, as constraints and
|
|
65
|
+
* layout-shift correction are computed from it.
|
|
66
|
+
*/
|
|
67
|
+
node.setOptions({ alwaysMeasureLayout: true });
|
|
68
|
+
const controls = new VisualElementDragControls(node.options.visualElement, () => props);
|
|
69
|
+
const removeListeners = controls.addListeners();
|
|
70
|
+
const removeStyles = applyDragStyles(element, options.axis);
|
|
71
|
+
return () => {
|
|
72
|
+
removeStyles();
|
|
73
|
+
removeListeners?.();
|
|
74
|
+
controls.cancel();
|
|
75
|
+
release();
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
return () => cleanups.forEach((cleanup) => cleanup());
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export { drag };
|
|
82
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/gestures/drag/index.ts"],"sourcesContent":["import type { BoundingBox } from \"motion-utils\"\nimport type { InertiaOptions } from \"../../animation/types\"\nimport { acquireProjectionNode } from \"../../layout/LayoutAnimationBuilder\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport type { VisualElement } from \"../../render/VisualElement\"\nimport {\n resolveElements,\n type ElementOrSelector,\n} from \"../../utils/resolve-elements\"\nimport type { DragElastic, DragHandler } from \"./types\"\nimport { VisualElementDragControls } from \"./VisualElementDragControls\"\n\n/**\n * @public\n */\nexport interface DragOptions {\n /**\n * Restrict dragging to a single axis. By default an element can be\n * dragged on both axes.\n */\n axis?: \"x\" | \"y\"\n\n /**\n * The permitted draggable area. Either `top`/`left`/`right`/`bottom`\n * distances in pixels, relative to the element's origin, or an element\n * the draggable element must stay within.\n */\n constraints?: Partial<BoundingBox> | Element\n\n /**\n * How far, from `0` to `1`, the element can move outside its\n * constraints. Can be set per edge. Defaults to `0.35`.\n */\n elastic?: DragElastic\n\n /**\n * Whether to carry the gesture's velocity into an inertia animation\n * on release. Defaults to `true`.\n */\n momentum?: boolean\n\n /**\n * Options for the inertia animation that runs on release.\n */\n transition?: InertiaOptions\n\n /**\n * Animate back to the origin on release.\n */\n snapToOrigin?: boolean | \"x\" | \"y\"\n\n /**\n * Lock dragging to the first axis the pointer moves along.\n */\n directionLock?: boolean\n\n /**\n * Allow drag gestures to start on parent elements that are also\n * draggable. By default, only the innermost draggable element moves.\n */\n propagation?: boolean\n\n onStart?: DragHandler\n onMove?: DragHandler\n onEnd?: DragHandler\n onDirectionLock?: (axis: \"x\" | \"y\") => void\n onTransitionEnd?: () => void\n\n /**\n * Called when element constraints are measured. Return a new\n * `BoundingBox` to override them.\n */\n onMeasureConstraints?: (constraints: BoundingBox) => BoundingBox | void\n}\n\nconst toProps = ({\n axis,\n constraints,\n elastic,\n momentum,\n transition,\n snapToOrigin,\n directionLock,\n propagation,\n onStart,\n onMove,\n onEnd,\n onDirectionLock,\n onTransitionEnd,\n onMeasureConstraints,\n}: DragOptions): MotionNodeOptions => ({\n drag: axis || true,\n dragConstraints: constraints,\n dragElastic: elastic,\n dragMomentum: momentum,\n dragTransition: transition,\n dragSnapToOrigin: snapToOrigin,\n dragDirectionLock: directionLock,\n dragPropagation: propagation,\n onDragStart: onStart,\n onDrag: onMove,\n onDragEnd: onEnd,\n onDirectionLock,\n onDragTransitionEnd: onTransitionEnd,\n onMeasureDragConstraints: onMeasureConstraints,\n})\n\nconst dragStyles = [\n \"user-select\",\n \"-webkit-user-select\",\n \"-webkit-touch-callout\",\n \"touch-action\",\n]\n\n/**\n * Apply the styles React's drag prop applies, so touch input drags\n * instead of panning the page, and text selection and native drag (ghost\n * image) don't interrupt the gesture. Returns a function that restores\n * the element's previous values.\n */\nfunction applyDragStyles(element: HTMLElement, axis?: \"x\" | \"y\") {\n const { style } = element\n const draggable = element.getAttribute(\"draggable\")\n const prev = dragStyles.map((key) => style.getPropertyValue(key))\n const touchAction = axis ? \"pan-\" + (axis === \"x\" ? \"y\" : \"x\") : \"none\"\n\n dragStyles.forEach((key, i) =>\n style.setProperty(key, i < 3 ? \"none\" : touchAction)\n )\n element.setAttribute(\"draggable\", \"false\")\n\n return () => {\n dragStyles.forEach((key, i) => style.setProperty(key, prev[i]))\n draggable === null\n ? element.removeAttribute(\"draggable\")\n : element.setAttribute(\"draggable\", draggable)\n }\n}\n\n/**\n * Make elements draggable. Returns a function that removes the gesture.\n *\n * ```javascript\n * const stop = drag(\"#box\", { axis: \"x\", constraints: { left: 0, right: 300 } })\n * ```\n *\n * The element's `x` and `y` are motion values shared with `animate()`\n * and `animateLayout()`, so these can animate the element after a drag.\n *\n * @public\n */\nexport function drag(\n elementOrSelector: ElementOrSelector,\n options: DragOptions = {}\n): VoidFunction {\n const props = toProps(options)\n\n const cleanups = resolveElements(elementOrSelector).map((element) => {\n const [node, release] = acquireProjectionNode(element as HTMLElement)\n\n /**\n * Measure layout even when not animating it, as constraints and\n * layout-shift correction are computed from it.\n */\n node.setOptions({ alwaysMeasureLayout: true })\n\n const controls = new VisualElementDragControls(\n node.options.visualElement as VisualElement<HTMLElement>,\n () => props\n )\n const removeListeners = controls.addListeners()\n const removeStyles = applyDragStyles(\n element as HTMLElement,\n options.axis\n )\n\n return () => {\n removeStyles()\n removeListeners?.()\n controls.cancel()\n release()\n }\n })\n\n return () => cleanups.forEach((cleanup) => cleanup())\n}\n"],"names":[],"mappings":";;;;AA2EA,MAAM,OAAO,GAAG,CAAC,EACb,IAAI,EACJ,WAAW,EACX,OAAO,EACP,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,OAAO,EACP,MAAM,EACN,KAAK,EACL,eAAe,EACf,eAAe,EACf,oBAAoB,GACV,MAAyB;IACnC,IAAI,EAAE,IAAI,IAAI,IAAI;AAClB,IAAA,eAAe,EAAE,WAAW;AAC5B,IAAA,WAAW,EAAE,OAAO;AACpB,IAAA,YAAY,EAAE,QAAQ;AACtB,IAAA,cAAc,EAAE,UAAU;AAC1B,IAAA,gBAAgB,EAAE,YAAY;AAC9B,IAAA,iBAAiB,EAAE,aAAa;AAChC,IAAA,eAAe,EAAE,WAAW;AAC5B,IAAA,WAAW,EAAE,OAAO;AACpB,IAAA,MAAM,EAAE,MAAM;AACd,IAAA,SAAS,EAAE,KAAK;IAChB,eAAe;AACf,IAAA,mBAAmB,EAAE,eAAe;AACpC,IAAA,wBAAwB,EAAE,oBAAoB;AACjD,CAAA,CA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AAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,qBAAqB,CAAC,OAAsB,CAAC;AAErE;;;AAGG;QACH,IAAI,CAAC,UAAU,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC;AAE9C,QAAA,MAAM,QAAQ,GAAG,IAAI,yBAAyB,CAC1C,IAAI,CAAC,OAAO,CAAC,aAA2C,EACxD,MAAM,KAAK,CACd;AACD,QAAA,MAAM,eAAe,GAAG,QAAQ,CAAC,YAAY,EAAE;QAC/C,MAAM,YAAY,GAAG,eAAe,CAChC,OAAsB,EACtB,OAAO,CAAC,IAAI,CACf;AAED,QAAA,OAAO,MAAK;AACR,YAAA,YAAY,EAAE;YACd,eAAe,IAAI;YACnB,QAAQ,CAAC,MAAM,EAAE;AACjB,YAAA,OAAO,EAAE;AACb,QAAA,CAAC;AACL,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,MAAM,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,KAAK,OAAO,EAAE,CAAC;AACzD;;;;"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { calcLength } from '../../../projection/geometry/delta-calc.mjs';
|
|
2
|
+
import { mixNumber } from '../../../utils/mix/number.mjs';
|
|
3
|
+
import { progress, clamp } from 'motion-utils';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Apply constraints to a point. These constraints are both physical along an
|
|
7
|
+
* axis, and an elastic factor that determines how much to constrain the point
|
|
8
|
+
* by if it does lie outside the defined parameters.
|
|
9
|
+
*/
|
|
10
|
+
function applyConstraints(point, { min, max }, elastic) {
|
|
11
|
+
if (min !== undefined && point < min) {
|
|
12
|
+
// If we have a min point defined, and this is outside of that, constrain
|
|
13
|
+
point = elastic
|
|
14
|
+
? mixNumber(min, point, elastic.min)
|
|
15
|
+
: Math.max(point, min);
|
|
16
|
+
}
|
|
17
|
+
else if (max !== undefined && point > max) {
|
|
18
|
+
// If we have a max point defined, and this is outside of that, constrain
|
|
19
|
+
point = elastic
|
|
20
|
+
? mixNumber(max, point, elastic.max)
|
|
21
|
+
: Math.min(point, max);
|
|
22
|
+
}
|
|
23
|
+
return point;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Calculate constraints in terms of the viewport when defined relatively to the
|
|
27
|
+
* measured axis. This is measured from the nearest edge, so a max constraint of 200
|
|
28
|
+
* on an axis with a max value of 300 would return a constraint of 500 - axis length
|
|
29
|
+
*/
|
|
30
|
+
function calcRelativeAxisConstraints(axis, min, max) {
|
|
31
|
+
return {
|
|
32
|
+
min: min !== undefined ? axis.min + min : undefined,
|
|
33
|
+
max: max !== undefined
|
|
34
|
+
? axis.max + max - (axis.max - axis.min)
|
|
35
|
+
: undefined,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Calculate constraints in terms of the viewport when
|
|
40
|
+
* defined relatively to the measured bounding box.
|
|
41
|
+
*/
|
|
42
|
+
function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {
|
|
43
|
+
return {
|
|
44
|
+
x: calcRelativeAxisConstraints(layoutBox.x, left, right),
|
|
45
|
+
y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Calculate viewport constraints when defined as another viewport-relative axis
|
|
50
|
+
*/
|
|
51
|
+
function calcViewportAxisConstraints(layoutAxis, constraintsAxis) {
|
|
52
|
+
let min = constraintsAxis.min - layoutAxis.min;
|
|
53
|
+
let max = constraintsAxis.max - layoutAxis.max;
|
|
54
|
+
// If the constraints axis is actually smaller than the layout axis then we can
|
|
55
|
+
// flip the constraints
|
|
56
|
+
if (constraintsAxis.max - constraintsAxis.min <
|
|
57
|
+
layoutAxis.max - layoutAxis.min) {
|
|
58
|
+
[min, max] = [max, min];
|
|
59
|
+
}
|
|
60
|
+
return { min, max };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Calculate viewport constraints when defined as another viewport-relative box
|
|
64
|
+
*/
|
|
65
|
+
function calcViewportConstraints(layoutBox, constraintsBox) {
|
|
66
|
+
return {
|
|
67
|
+
x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),
|
|
68
|
+
y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Calculate a transform origin relative to the source axis, between 0-1, that results
|
|
73
|
+
* in an aesthetically pleasing scale/transform needed to project from source to target.
|
|
74
|
+
*/
|
|
75
|
+
function calcOrigin(source, target) {
|
|
76
|
+
let origin = 0.5;
|
|
77
|
+
const sourceLength = calcLength(source);
|
|
78
|
+
const targetLength = calcLength(target);
|
|
79
|
+
if (targetLength > sourceLength) {
|
|
80
|
+
origin = progress(target.min, target.max - sourceLength, source.min);
|
|
81
|
+
}
|
|
82
|
+
else if (sourceLength > targetLength) {
|
|
83
|
+
origin = progress(source.min, source.max - targetLength, target.min);
|
|
84
|
+
}
|
|
85
|
+
return clamp(0, 1, origin);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Rebase the calculated viewport constraints relative to the layout.min point.
|
|
89
|
+
*/
|
|
90
|
+
function rebaseAxisConstraints(layout, constraints) {
|
|
91
|
+
const relativeConstraints = {};
|
|
92
|
+
if (constraints.min !== undefined) {
|
|
93
|
+
relativeConstraints.min = constraints.min - layout.min;
|
|
94
|
+
}
|
|
95
|
+
if (constraints.max !== undefined) {
|
|
96
|
+
relativeConstraints.max = constraints.max - layout.min;
|
|
97
|
+
}
|
|
98
|
+
return relativeConstraints;
|
|
99
|
+
}
|
|
100
|
+
const defaultElastic = 0.35;
|
|
101
|
+
/**
|
|
102
|
+
* Accepts a dragElastic prop and returns resolved elastic values for each axis.
|
|
103
|
+
*/
|
|
104
|
+
function resolveDragElastic(dragElastic = defaultElastic) {
|
|
105
|
+
if (dragElastic === false) {
|
|
106
|
+
dragElastic = 0;
|
|
107
|
+
}
|
|
108
|
+
else if (dragElastic === true) {
|
|
109
|
+
dragElastic = defaultElastic;
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
x: resolveAxisElastic(dragElastic, "left", "right"),
|
|
113
|
+
y: resolveAxisElastic(dragElastic, "top", "bottom"),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function resolveAxisElastic(dragElastic, minLabel, maxLabel) {
|
|
117
|
+
return {
|
|
118
|
+
min: resolvePointElastic(dragElastic, minLabel),
|
|
119
|
+
max: resolvePointElastic(dragElastic, maxLabel),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function resolvePointElastic(dragElastic, label) {
|
|
123
|
+
return typeof dragElastic === "number"
|
|
124
|
+
? dragElastic
|
|
125
|
+
: dragElastic[label] || 0;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export { applyConstraints, calcOrigin, calcRelativeAxisConstraints, calcRelativeConstraints, calcViewportAxisConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveAxisElastic, resolveDragElastic, resolvePointElastic };
|
|
129
|
+
//# sourceMappingURL=constraints.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constraints.mjs","sources":["../../../../../src/gestures/drag/utils/constraints.ts"],"sourcesContent":["import { calcLength } from \"../../../projection/geometry/delta-calc\"\nimport { mixNumber } from \"../../../utils/mix/number\"\nimport type { DragElastic, ResolvedConstraints } from \"../types\"\nimport {\n Axis,\n BoundingBox,\n Box,\n progress as calcProgress,\n clamp,\n Point,\n} from \"motion-utils\"\n\n/**\n * Apply constraints to a point. These constraints are both physical along an\n * axis, and an elastic factor that determines how much to constrain the point\n * by if it does lie outside the defined parameters.\n */\nexport function applyConstraints(\n point: number,\n { min, max }: Partial<Axis>,\n elastic?: Axis\n): number {\n if (min !== undefined && point < min) {\n // If we have a min point defined, and this is outside of that, constrain\n point = elastic\n ? mixNumber(min, point, elastic.min)\n : Math.max(point, min)\n } else if (max !== undefined && point > max) {\n // If we have a max point defined, and this is outside of that, constrain\n point = elastic\n ? mixNumber(max, point, elastic.max)\n : Math.min(point, max)\n }\n\n return point\n}\n\n/**\n * Calculates a min projection point based on a pointer, pointer progress\n * within the drag target, and constraints.\n *\n * For instance if an element was 100px width, we were dragging from 0.25\n * along this axis, the pointer is at 200px, and there were no constraints,\n * we would calculate a min projection point of 175px.\n */\nexport function calcConstrainedMinPoint(\n point: number,\n length: number,\n progress: number,\n constraints?: Partial<Axis>,\n elastic?: Axis\n): number {\n // Calculate a min point for this axis and apply it to the current pointer\n const min = point - length * progress\n\n return constraints ? applyConstraints(min, constraints, elastic) : min\n}\n\n/**\n * Calculate constraints in terms of the viewport when defined relatively to the\n * measured axis. This is measured from the nearest edge, so a max constraint of 200\n * on an axis with a max value of 300 would return a constraint of 500 - axis length\n */\nexport function calcRelativeAxisConstraints(\n axis: Axis,\n min?: number,\n max?: number\n): Partial<Axis> {\n return {\n min: min !== undefined ? axis.min + min : undefined,\n max:\n max !== undefined\n ? axis.max + max - (axis.max - axis.min)\n : undefined,\n }\n}\n\n/**\n * Calculate constraints in terms of the viewport when\n * defined relatively to the measured bounding box.\n */\nexport function calcRelativeConstraints(\n layoutBox: Box,\n { top, left, bottom, right }: Partial<BoundingBox>\n): ResolvedConstraints {\n return {\n x: calcRelativeAxisConstraints(layoutBox.x, left, right),\n y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),\n }\n}\n\n/**\n * Calculate viewport constraints when defined as another viewport-relative axis\n */\nexport function calcViewportAxisConstraints(\n layoutAxis: Axis,\n constraintsAxis: Axis\n) {\n let min = constraintsAxis.min - layoutAxis.min\n let max = constraintsAxis.max - layoutAxis.max\n\n // If the constraints axis is actually smaller than the layout axis then we can\n // flip the constraints\n if (\n constraintsAxis.max - constraintsAxis.min <\n layoutAxis.max - layoutAxis.min\n ) {\n ;[min, max] = [max, min]\n }\n\n return { min, max }\n}\n\n/**\n * Calculate viewport constraints when defined as another viewport-relative box\n */\nexport function calcViewportConstraints(layoutBox: Box, constraintsBox: Box) {\n return {\n x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),\n y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),\n }\n}\n\n/**\n * Calculate a transform origin relative to the source axis, between 0-1, that results\n * in an aesthetically pleasing scale/transform needed to project from source to target.\n */\nexport function calcOrigin(source: Axis, target: Axis): number {\n let origin = 0.5\n const sourceLength = calcLength(source)\n const targetLength = calcLength(target)\n\n if (targetLength > sourceLength) {\n origin = calcProgress(target.min, target.max - sourceLength, source.min)\n } else if (sourceLength > targetLength) {\n origin = calcProgress(source.min, source.max - targetLength, target.min)\n }\n\n return clamp(0, 1, origin)\n}\n\n/**\n * Calculate the relative progress of one constraints box relative to another.\n * Imagine a page scroll bar. At the top, this would return 0, at the bottom, 1.\n * Anywhere in-between, a value between 0 and 1.\n *\n * This also handles flipped constraints, for instance a draggable container within\n * a smaller viewport like a scrollable view.\n */\nexport function calcProgressWithinConstraints(\n layoutBox: Box,\n constraintsBox: Box\n): Point {\n return {\n x: calcOrigin(layoutBox.x, constraintsBox.x),\n y: calcOrigin(layoutBox.y, constraintsBox.y),\n }\n}\n\n/**\n * Calculate the an axis position based on two axes and a progress value.\n */\nexport function calcPositionFromProgress(\n axis: Axis,\n constraints: Axis,\n progress: number\n): Axis {\n const axisLength = axis.max - axis.min\n const min = mixNumber(\n constraints.min,\n constraints.max - axisLength,\n progress\n )\n return { min, max: min + axisLength }\n}\n\n/**\n * Rebase the calculated viewport constraints relative to the layout.min point.\n */\nexport function rebaseAxisConstraints(\n layout: Axis,\n constraints: Partial<Axis>\n): Partial<Axis> {\n const relativeConstraints: Partial<Axis> = {}\n\n if (constraints.min !== undefined) {\n relativeConstraints.min = constraints.min - layout.min\n }\n\n if (constraints.max !== undefined) {\n relativeConstraints.max = constraints.max - layout.min\n }\n\n return relativeConstraints\n}\n\nexport const defaultElastic = 0.35\n/**\n * Accepts a dragElastic prop and returns resolved elastic values for each axis.\n */\nexport function resolveDragElastic(\n dragElastic: DragElastic = defaultElastic\n): Box {\n if (dragElastic === false) {\n dragElastic = 0\n } else if (dragElastic === true) {\n dragElastic = defaultElastic\n }\n\n return {\n x: resolveAxisElastic(dragElastic, \"left\", \"right\"),\n y: resolveAxisElastic(dragElastic, \"top\", \"bottom\"),\n }\n}\n\nexport function resolveAxisElastic(\n dragElastic: DragElastic,\n minLabel: string,\n maxLabel: string\n): Axis {\n return {\n min: resolvePointElastic(dragElastic, minLabel),\n max: resolvePointElastic(dragElastic, maxLabel),\n }\n}\n\nexport function resolvePointElastic(\n dragElastic: DragElastic,\n label: string\n): number {\n return typeof dragElastic === \"number\"\n ? dragElastic\n : dragElastic[label as keyof typeof dragElastic] || 0\n}\n"],"names":["calcProgress"],"mappings":";;;;AAYA;;;;AAIG;AACG,SAAU,gBAAgB,CAC5B,KAAa,EACb,EAAE,GAAG,EAAE,GAAG,EAAiB,EAC3B,OAAc,EAAA;IAEd,IAAI,GAAG,KAAK,SAAS,IAAI,KAAK,GAAG,GAAG,EAAE;;AAElC,QAAA,KAAK,GAAG;cACF,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG;cACjC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC;IAC9B;SAAO,IAAI,GAAG,KAAK,SAAS,IAAI,KAAK,GAAG,GAAG,EAAE;;AAEzC,QAAA,KAAK,GAAG;cACF,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG;cACjC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC;IAC9B;AAEA,IAAA,OAAO,KAAK;AAChB;AAuBA;;;;AAIG;SACa,2BAA2B,CACvC,IAAU,EACV,GAAY,EACZ,GAAY,EAAA;IAEZ,OAAO;AACH,QAAA,GAAG,EAAE,GAAG,KAAK,SAAS,GAAG,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,SAAS;QACnD,GAAG,EACC,GAAG,KAAK;AACJ,cAAE,IA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,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,CAAC;KACtD;AACL;SAEgB,kBAAkB,CAC9B,WAAwB,EACxB,QAAgB,EAChB,QAAgB,EAAA;IAEhB,OAAO;AACH,QAAA,GAAG,EAAE,mBAAmB,CAAC,WAAW,EAAE,QAAQ,CAAC;AAC/C,QAAA,GAAG,EAAE,mBAAmB,CAAC,WAAW,EAAE,QAAQ,CAAC;KAClD;AACL;AAEM,SAAU,mBAAmB,CAC/B,WAAwB,EACxB,KAAa,EAAA;IAEb,OAAO,OAAO,WAAW,KAAK;AAC1B,UAAE;AACF,UAAE,WAAW,CAAC,KAAiC,CAAC,IAAI,CAAC;AAC7D;;;;"}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { addPointerEvent } from '../../events/add-pointer-event.mjs';
|
|
2
|
+
import { extractEventInfo } from '../../events/event-info.mjs';
|
|
3
|
+
import { frame, cancelFrame } from '../../frameloop/frame.mjs';
|
|
4
|
+
import { frameData } from '../../frameloop/frame-data.mjs';
|
|
5
|
+
import { time } from '../../frameloop/sync-time.mjs';
|
|
6
|
+
import { distance2D } from '../../utils/distance.mjs';
|
|
7
|
+
import { isPrimaryPointer } from '../utils/is-primary-pointer.mjs';
|
|
8
|
+
import { pipe, secondsToMilliseconds, millisecondsToSeconds } from 'motion-utils';
|
|
9
|
+
|
|
10
|
+
const overflowStyles = /*#__PURE__*/ new Set(["auto", "scroll"]);
|
|
11
|
+
class PanSession {
|
|
12
|
+
constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element, } = {}) {
|
|
13
|
+
this.startEvent = null;
|
|
14
|
+
this.lastMoveEvent = null;
|
|
15
|
+
this.lastMoveEventInfo = null;
|
|
16
|
+
/**
|
|
17
|
+
* Raw (untransformed) event info, re-transformed each frame
|
|
18
|
+
* so transformPagePoint sees the current parent matrix.
|
|
19
|
+
*/
|
|
20
|
+
this.lastRawMoveEventInfo = null;
|
|
21
|
+
this.handlers = {};
|
|
22
|
+
this.contextWindow = window;
|
|
23
|
+
/**
|
|
24
|
+
* Scroll positions of scrollable ancestors and window.
|
|
25
|
+
*/
|
|
26
|
+
this.scrollPositions = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* Cleanup function for scroll listeners.
|
|
29
|
+
*/
|
|
30
|
+
this.removeScrollListeners = null;
|
|
31
|
+
this.onElementScroll = (event) => {
|
|
32
|
+
this.handleScroll(event.target);
|
|
33
|
+
};
|
|
34
|
+
this.onWindowScroll = () => {
|
|
35
|
+
this.handleScroll(window);
|
|
36
|
+
};
|
|
37
|
+
this.updatePoint = () => {
|
|
38
|
+
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
|
|
39
|
+
return;
|
|
40
|
+
this.hasPendingMove = false;
|
|
41
|
+
// Re-transform raw point through current transformPagePoint so
|
|
42
|
+
// animated parent transforms (e.g. rotation) are picked up each frame
|
|
43
|
+
if (this.lastRawMoveEventInfo) {
|
|
44
|
+
this.lastMoveEventInfo = transformPoint(this.lastRawMoveEventInfo, this.transformPagePoint);
|
|
45
|
+
}
|
|
46
|
+
const info = getPanInfo(this.lastMoveEventInfo, this.history);
|
|
47
|
+
const isPanStarted = this.startEvent !== null;
|
|
48
|
+
// Only start panning if the offset is larger than 3 pixels. If we make it
|
|
49
|
+
// any larger than this we'll want to reset the pointer history
|
|
50
|
+
// on the first update to avoid visual snapping to the cursor.
|
|
51
|
+
const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold;
|
|
52
|
+
if (!isPanStarted && !isDistancePastThreshold)
|
|
53
|
+
return;
|
|
54
|
+
const { point } = info;
|
|
55
|
+
this.history.push({ ...point, timestamp: time.now() });
|
|
56
|
+
const { onStart, onMove } = this.handlers;
|
|
57
|
+
if (!isPanStarted) {
|
|
58
|
+
onStart && onStart(this.lastMoveEvent, info);
|
|
59
|
+
this.startEvent = this.lastMoveEvent;
|
|
60
|
+
}
|
|
61
|
+
onMove && onMove(this.lastMoveEvent, info);
|
|
62
|
+
};
|
|
63
|
+
this.handlePointerMove = (event, info) => {
|
|
64
|
+
this.lastMoveEvent = event;
|
|
65
|
+
this.lastRawMoveEventInfo = info;
|
|
66
|
+
this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);
|
|
67
|
+
this.hasPendingMove = true;
|
|
68
|
+
// Throttle mouse move event to once per frame
|
|
69
|
+
frame.update(this.updatePoint, true);
|
|
70
|
+
};
|
|
71
|
+
this.handlePointerUp = (event, info) => {
|
|
72
|
+
// Browsers flush a coalesced pointermove immediately before
|
|
73
|
+
// pointerup, so the final move can still be waiting for a frame.
|
|
74
|
+
this.hasPendingMove && this.updatePoint();
|
|
75
|
+
this.end();
|
|
76
|
+
const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;
|
|
77
|
+
// Resume animation if dragSnapToOrigin is set OR if no drag started (user just clicked)
|
|
78
|
+
// This ensures constraint animations continue when interrupted by a click
|
|
79
|
+
if (this.dragSnapToOrigin || !this.startEvent) {
|
|
80
|
+
resumeAnimation && resumeAnimation();
|
|
81
|
+
}
|
|
82
|
+
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
|
|
83
|
+
return;
|
|
84
|
+
const panInfo = getPanInfo(event.type === "pointercancel"
|
|
85
|
+
? this.lastMoveEventInfo
|
|
86
|
+
: transformPoint(info, this.transformPagePoint), this.history);
|
|
87
|
+
if (this.startEvent && onEnd) {
|
|
88
|
+
onEnd(event, panInfo);
|
|
89
|
+
}
|
|
90
|
+
onSessionEnd && onSessionEnd(event, panInfo);
|
|
91
|
+
};
|
|
92
|
+
// If we have more than one touch, don't start detecting this gesture
|
|
93
|
+
if (!isPrimaryPointer(event))
|
|
94
|
+
return;
|
|
95
|
+
this.dragSnapToOrigin = dragSnapToOrigin;
|
|
96
|
+
this.handlers = handlers;
|
|
97
|
+
this.transformPagePoint = transformPagePoint;
|
|
98
|
+
this.distanceThreshold = distanceThreshold;
|
|
99
|
+
this.contextWindow = contextWindow || window;
|
|
100
|
+
const info = extractEventInfo(event);
|
|
101
|
+
const initialInfo = transformPoint(info, this.transformPagePoint);
|
|
102
|
+
const { point } = initialInfo;
|
|
103
|
+
const { timestamp } = frameData;
|
|
104
|
+
this.history = [{ ...point, timestamp }];
|
|
105
|
+
const { onSessionStart } = handlers;
|
|
106
|
+
onSessionStart &&
|
|
107
|
+
onSessionStart(event, getPanInfo(initialInfo, this.history));
|
|
108
|
+
// Listen in the capture phase so a descendant calling
|
|
109
|
+
// stopPropagation() (e.g. in its own pointerup handler) can't
|
|
110
|
+
// prevent the gesture from ending. See #2794.
|
|
111
|
+
const eventOptions = { passive: true, capture: true };
|
|
112
|
+
this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove, eventOptions), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp, eventOptions), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp, eventOptions));
|
|
113
|
+
// Start scroll tracking if element provided
|
|
114
|
+
if (element) {
|
|
115
|
+
this.startScrollTracking(element);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Start tracking scroll on ancestors and window.
|
|
120
|
+
*/
|
|
121
|
+
startScrollTracking(element) {
|
|
122
|
+
// Store initial scroll positions for scrollable ancestors
|
|
123
|
+
let current = element.parentElement;
|
|
124
|
+
while (current) {
|
|
125
|
+
const style = getComputedStyle(current);
|
|
126
|
+
if (overflowStyles.has(style.overflowX) ||
|
|
127
|
+
overflowStyles.has(style.overflowY)) {
|
|
128
|
+
this.scrollPositions.set(current, {
|
|
129
|
+
x: current.scrollLeft,
|
|
130
|
+
y: current.scrollTop,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
current = current.parentElement;
|
|
134
|
+
}
|
|
135
|
+
// Track window scroll
|
|
136
|
+
this.scrollPositions.set(window, {
|
|
137
|
+
x: window.scrollX,
|
|
138
|
+
y: window.scrollY,
|
|
139
|
+
});
|
|
140
|
+
// Capture listener catches element scroll events as they bubble
|
|
141
|
+
window.addEventListener("scroll", this.onElementScroll, {
|
|
142
|
+
capture: true,
|
|
143
|
+
});
|
|
144
|
+
// Direct window scroll listener (window scroll doesn't bubble)
|
|
145
|
+
window.addEventListener("scroll", this.onWindowScroll);
|
|
146
|
+
this.removeScrollListeners = () => {
|
|
147
|
+
window.removeEventListener("scroll", this.onElementScroll, {
|
|
148
|
+
capture: true,
|
|
149
|
+
});
|
|
150
|
+
window.removeEventListener("scroll", this.onWindowScroll);
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Handle scroll compensation during drag.
|
|
155
|
+
*
|
|
156
|
+
* For element scroll: adjusts history origin since pageX/pageY doesn't change.
|
|
157
|
+
* For window scroll: adjusts lastMoveEventInfo since pageX/pageY would change.
|
|
158
|
+
*/
|
|
159
|
+
handleScroll(target) {
|
|
160
|
+
const initial = this.scrollPositions.get(target);
|
|
161
|
+
if (!initial)
|
|
162
|
+
return;
|
|
163
|
+
const isWindow = target === window;
|
|
164
|
+
const current = isWindow
|
|
165
|
+
? { x: window.scrollX, y: window.scrollY }
|
|
166
|
+
: {
|
|
167
|
+
x: target.scrollLeft,
|
|
168
|
+
y: target.scrollTop,
|
|
169
|
+
};
|
|
170
|
+
const delta = { x: current.x - initial.x, y: current.y - initial.y };
|
|
171
|
+
if (delta.x === 0 && delta.y === 0)
|
|
172
|
+
return;
|
|
173
|
+
if (isWindow) {
|
|
174
|
+
// Window scroll: pageX/pageY changes, so update lastMoveEventInfo
|
|
175
|
+
if (this.lastMoveEventInfo) {
|
|
176
|
+
this.lastMoveEventInfo.point.x += delta.x;
|
|
177
|
+
this.lastMoveEventInfo.point.y += delta.y;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
// Element scroll: pageX/pageY unchanged, so adjust history origin
|
|
182
|
+
if (this.history.length > 0) {
|
|
183
|
+
this.history[0].x -= delta.x;
|
|
184
|
+
this.history[0].y -= delta.y;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
this.scrollPositions.set(target, current);
|
|
188
|
+
frame.update(this.updatePoint, true);
|
|
189
|
+
}
|
|
190
|
+
updateHandlers(handlers) {
|
|
191
|
+
this.handlers = handlers;
|
|
192
|
+
}
|
|
193
|
+
end() {
|
|
194
|
+
this.removeListeners && this.removeListeners();
|
|
195
|
+
this.removeScrollListeners && this.removeScrollListeners();
|
|
196
|
+
this.scrollPositions.clear();
|
|
197
|
+
cancelFrame(this.updatePoint);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function transformPoint(info, transformPagePoint) {
|
|
201
|
+
return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
|
|
202
|
+
}
|
|
203
|
+
function subtractPoint(a, b) {
|
|
204
|
+
return { x: a.x - b.x, y: a.y - b.y };
|
|
205
|
+
}
|
|
206
|
+
function getPanInfo({ point }, history) {
|
|
207
|
+
return {
|
|
208
|
+
point,
|
|
209
|
+
delta: subtractPoint(point, lastDevicePoint(history)),
|
|
210
|
+
offset: subtractPoint(point, startDevicePoint(history)),
|
|
211
|
+
velocity: getVelocity(history, 0.1),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function startDevicePoint(history) {
|
|
215
|
+
return history[0];
|
|
216
|
+
}
|
|
217
|
+
function lastDevicePoint(history) {
|
|
218
|
+
return history[history.length - 1];
|
|
219
|
+
}
|
|
220
|
+
function getVelocity(history, timeDelta) {
|
|
221
|
+
if (history.length < 2) {
|
|
222
|
+
return { x: 0, y: 0 };
|
|
223
|
+
}
|
|
224
|
+
let i = history.length - 1;
|
|
225
|
+
let timestampedPoint = null;
|
|
226
|
+
const lastPoint = lastDevicePoint(history);
|
|
227
|
+
while (i >= 0) {
|
|
228
|
+
timestampedPoint = history[i];
|
|
229
|
+
if (lastPoint.timestamp - timestampedPoint.timestamp >
|
|
230
|
+
secondsToMilliseconds(timeDelta)) {
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
i--;
|
|
234
|
+
}
|
|
235
|
+
if (!timestampedPoint) {
|
|
236
|
+
return { x: 0, y: 0 };
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* If the selected point is the pointer-down origin (history[0]),
|
|
240
|
+
* there are better movement points available, and the time gap
|
|
241
|
+
* is suspiciously large (>2x timeDelta), use the next point instead.
|
|
242
|
+
* This prevents stale pointer-down points from diluting velocity
|
|
243
|
+
* in hold-then-flick gestures.
|
|
244
|
+
*/
|
|
245
|
+
if (timestampedPoint === history[0] &&
|
|
246
|
+
history.length > 2 &&
|
|
247
|
+
lastPoint.timestamp - timestampedPoint.timestamp >
|
|
248
|
+
secondsToMilliseconds(timeDelta) * 2) {
|
|
249
|
+
timestampedPoint = history[1];
|
|
250
|
+
}
|
|
251
|
+
const seconds = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);
|
|
252
|
+
if (seconds === 0) {
|
|
253
|
+
return { x: 0, y: 0 };
|
|
254
|
+
}
|
|
255
|
+
const currentVelocity = {
|
|
256
|
+
x: (lastPoint.x - timestampedPoint.x) / seconds,
|
|
257
|
+
y: (lastPoint.y - timestampedPoint.y) / seconds,
|
|
258
|
+
};
|
|
259
|
+
if (currentVelocity.x === Infinity) {
|
|
260
|
+
currentVelocity.x = 0;
|
|
261
|
+
}
|
|
262
|
+
if (currentVelocity.y === Infinity) {
|
|
263
|
+
currentVelocity.y = 0;
|
|
264
|
+
}
|
|
265
|
+
return currentVelocity;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export { PanSession };
|
|
269
|
+
//# sourceMappingURL=PanSession.mjs.map
|