From 285196bd901a9fd9877b9b426b1896faf795b70d Mon Sep 17 00:00:00 2001 From: tilenmiklavic Date: Sun, 13 Oct 2024 17:12:11 +0200 Subject: [PATCH] fix: dont trigger long press on scroll --- index.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index f6e4fe2..5457508 100644 --- a/index.js +++ b/index.js @@ -662,17 +662,19 @@ export function useLockBodyScroll() { } export function useLongPress(callback, options = {}) { - const { threshold = 400, onStart, onFinish, onCancel } = options; + const { threshold = 400, onStart, onFinish, onCancel, allowScroll = true, scrollThreshold = 20 } = options; const isLongPressActive = React.useRef(false); const isPressed = React.useRef(false); const timerId = React.useRef(); + let startY; return React.useMemo(() => { if (typeof callback !== "function") { return {}; - } + } const start = (event) => { + startY = event.touches[0].clientY; if (!isMouseEvent(event) && !isTouchEvent(event)) return; if (onStart) { @@ -707,15 +709,23 @@ export function useLongPress(callback, options = {}) { } }; + const move = (event) => { + if (!allowScroll && Math.abs(event.touches[0].clientY - startY) > scrollThreshold) { + cancel(event) + } + } + const mouseHandlers = { onMouseDown: start, onMouseUp: cancel, onMouseLeave: cancel, + onMouseMove: move, }; const touchHandlers = { onTouchStart: start, onTouchEnd: cancel, + onTouchMove: move, }; return {