Drag
newA one-axis drag gesture for mouse, pen and touch that leaves vertical scrolling to the browser on touch screens.
Installation
Usage
import { useDrag } from '@/lib/drag'
const sheet = ref<HTMLElement>()
useDrag(sheet, {
towards: 'bottom',
onMove: (move) => (offset.value = move.movement),
onRelease: (move) => (move.movement > 120 || move.velocity > 0.5 ? close() : (offset.value = 0)),
})
useDrag follows one axis. towards names the side whose direction counts as positive: bottom and right for down and right, top and left for up and left, so move.movement grows as the element is dragged that way and goes negative the other way. Drawer, Swipe Actions and Swipe Snap are built on it.
A press becomes a drag after 10px of travel along the axis. A mouse and a pen drag through pointer events. A finger on a touch screen drags through touch events, so the browser keeps its say over scrolling: a finger that first moves across the axis is left to scroll the page, and one that moves along it takes over. Nothing starts inside [data-no-drag] or while text is selected, and text selection is held off during a drag. When drags nest, the innermost one that starts takes the gesture; an outer drag gets it only when the inner one refuses it through canStart.
| Option | Description |
|---|---|
towards | The side whose direction is positive: top, bottom, left or right. A ref or a getter works too. |
enabled | false detaches the listeners. |
bounds | { min, max } limits for movement; past them it rubber-bands. |
canStart(move) | Return false to refuse a drag once its direction is known. |
onStart(move) | The drag began. |
onMove(move) | Every move while dragging. |
onRelease(move) | The drag ended; move.velocity is the speed over the last 100ms, 0 after a 50ms rest. |
onCancel() | The drag was cancelled or the element went away. |
A move carries movement (pixels along the axis), velocity (pixels per millisecond, positive towards towards), direction (1, -1 or 0), the original event, the pressed target and mouse, true for a mouse. SWIPE_VELOCITY (0.5) is the speed the drawer treats as a flick.