|
| 1 | +interface DragOptions { |
| 2 | + /** Callback that runs as dragging occurs. */ |
| 3 | + onMove: (x: number, y: number) => void; |
| 4 | + /** Callback that runs when dragging stops. */ |
| 5 | + onStop: () => void; |
| 6 | + /** |
| 7 | + * When an initial event is passed, the first drag will be triggered immediately using the coordinates therein. This |
| 8 | + * is useful when the drag is initiated by a mousedown/touchstart event but you want the initial "click" to activate |
| 9 | + * a drag (e.g. positioning a handle initially at the click target). |
| 10 | + */ |
| 11 | + initialEvent: PointerEvent; |
| 12 | +} |
| 13 | + |
| 14 | +export const drag = ( |
| 15 | + container: HTMLElement, |
| 16 | + options?: Partial<DragOptions> |
| 17 | +) => { |
| 18 | + function move(pointerEvent: PointerEvent) { |
| 19 | + const dims = container.getBoundingClientRect(); |
| 20 | + const defaultView = container.ownerDocument.defaultView!; |
| 21 | + const offsetX = dims.left + defaultView.pageXOffset; |
| 22 | + const offsetY = dims.top + defaultView.pageYOffset; |
| 23 | + const x = pointerEvent.pageX - offsetX; |
| 24 | + const y = pointerEvent.pageY - offsetY; |
| 25 | + |
| 26 | + if (options?.onMove) { |
| 27 | + options.onMove(x, y); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + function stop() { |
| 32 | + document.removeEventListener('pointermove', move); |
| 33 | + document.removeEventListener('pointerup', stop); |
| 34 | + |
| 35 | + if (options?.onStop) { |
| 36 | + options.onStop(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + document.addEventListener('pointermove', move, { passive: true }); |
| 41 | + document.addEventListener('pointerup', stop); |
| 42 | + |
| 43 | + // If an initial event is set, trigger the first drag immediately |
| 44 | + if (options?.initialEvent) { |
| 45 | + move(options.initialEvent); |
| 46 | + } |
| 47 | +}; |
0 commit comments