Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add holdDelay option #155

Closed
wants to merge 9 commits into from
34 changes: 34 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,14 @@ export type DragOptions = {
* Fires when dragging ends
*/
onDragEnd?: (data: DragEventData) => void;

/**
* Time in milliseconds a user must hold before dragging starts.
* This can help prevent accidental drags.
*
* @default 0ms
*/
holdDelay?: number;
};

const enum DEFAULT_CLASS {
Expand Down Expand Up @@ -267,6 +275,7 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
onDragStart,
onDrag,
onDragEnd,
holdDelay = 0,
} = options;

let active = false;
Expand Down Expand Up @@ -373,11 +382,26 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
return inverseScale;
};

let holdTimeout: number | undefined;
let draggingAllowed = false;

function dragStart(e: PointerEvent) {
if (disabled) return;

if (e.button === 2) return;

// Start the hold delay timer
if (holdDelay > 0) {
holdTimeout = window.setTimeout(() => {
draggingAllowed = true;
fireSvelteDragStartEvent();
}, holdDelay);
} else {
draggingAllowed = true;
fireSvelteDragStartEvent();
}


activePointers.add(e.pointerId);

if (ignoreMultitouch && activePointers.size > 1) return e.preventDefault();
Expand Down Expand Up @@ -438,6 +462,14 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
}

function dragEnd(e: PointerEvent) {
if (holdTimeout) {
clearTimeout(holdTimeout);
}

draggingAllowed = false;

if (!draggingAllowed) return;

activePointers.delete(e.pointerId);

if (!active) return;
Expand All @@ -459,6 +491,8 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
}

function drag(e: PointerEvent) {
if (!draggingAllowed) return;

if (!active || (ignoreMultitouch && activePointers.size > 1)) return;

if (recomputeBounds.drag) computedBounds = computeBoundRect(bounds, node);
Expand Down