Skip to content

Commit

Permalink
Add holdDelay property to delay dragging
Browse files Browse the repository at this point in the history
  • Loading branch information
houtan-rocky committed Apr 22, 2024
1 parent f0a60b4 commit 6377d81
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
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);
}

if (!draggingAllowed) return;

draggingAllowed = false;

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
1 change: 1 addition & 0 deletions packages/svelte/demo/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@
progressX.set(offsetX);
progressY.set(offsetY);
},
holdDelay: 200
}}
class="box"
>
Expand Down

0 comments on commit 6377d81

Please sign in to comment.