-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathdrag.ts
62 lines (54 loc) · 2.05 KB
/
drag.ts
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
interface DragOptions {
/** Callback that runs as dragging occurs. */
onMove: (x: number, y: number) => void;
/** Callback that runs when dragging stops. */
onStop: () => void;
/**
* When an initial event is passed, the first drag will be triggered immediately using the coordinates therein. This
* is useful when the drag is initiated by a mousedown/touchstart event but you want the initial "click" to activate
* a drag (e.g. positioning a handle initially at the click target).
*/
initialEvent: PointerEvent;
}
export const drag = (
container: HTMLElement,
options?: Partial<DragOptions>,
) => {
function move(event: PointerEvent | TouchEvent) {
const dims = container.getBoundingClientRect();
const defaultView = container.ownerDocument.defaultView!;
const offsetX = dims.left + defaultView.scrollX;
const offsetY = dims.top + defaultView.scrollY;
let pointerEvent: PointerEvent | Touch;
// TouchEvent is not available in Firefox
if ('TouchEvent' in window && event instanceof TouchEvent) {
pointerEvent = event.touches[0];
} else if (event instanceof MouseEvent) {
// Some browsers seem to return PointerEvent instead of MouseEvent for click event.
// We can use MouseEvent as PointerEvent inherits from MouseEvent.
// Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1675847
// Safari: https://bugs.webkit.org/show_bug.cgi?id=218665
pointerEvent = event;
} else {
return;
}
const x = pointerEvent.pageX - offsetX;
const y = pointerEvent.pageY - offsetY;
if (options?.onMove) {
options.onMove(x, y);
}
}
function stop() {
document.removeEventListener('pointermove', move);
document.removeEventListener('pointerup', stop);
if (options?.onStop) {
options.onStop();
}
}
document.addEventListener('pointermove', move, { passive: true });
document.addEventListener('pointerup', stop);
// If an initial event is set, trigger the first drag immediately
if (options?.initialEvent) {
move(options.initialEvent);
}
};