|
| 1 | +import { type RefObject, useCallback, useState } from 'react' |
| 2 | +import useMouseEvents from './useMouseEvents' |
| 3 | +import useConditionalTimeout from './useConditionalTimeout' |
| 4 | +import createHandlerSetter from './factory/createHandlerSetter' |
| 5 | +import useTouchEvents from './useTouchEvents' |
| 6 | +import { type CallbackSetter } from './shared/types' |
| 7 | + |
| 8 | +/** |
| 9 | + * A hook that facilitates the implementation of the long press functionality on a given target, supporting both mouse and touch events. |
| 10 | + */ |
| 11 | +const useLongPress = <TElement extends HTMLElement>(target: RefObject<TElement>, duration = 500) => { |
| 12 | + const { onMouseDown, onMouseUp, onMouseLeave } = useMouseEvents<TElement>(target, false) |
| 13 | + const { onTouchStart, onTouchEnd } = useTouchEvents(target, false) |
| 14 | + const [isLongPressing, setIsLongPressing] = useState(false) |
| 15 | + const [timerOn, startTimer] = useState(false) |
| 16 | + const [onLongPressStart, setOnLongPressStart] = createHandlerSetter<void>() |
| 17 | + const [onLongPressEnd, setOnLongPressEnd] = createHandlerSetter<void>() |
| 18 | + |
| 19 | + const longPressStart = useCallback((event: MouseEvent | TouchEvent) => { |
| 20 | + event.preventDefault() |
| 21 | + startTimer(true) |
| 22 | + }, []) |
| 23 | + |
| 24 | + const longPressStop = useCallback((event: MouseEvent | TouchEvent) => { |
| 25 | + if (!isLongPressing) return |
| 26 | + clearTimeout() |
| 27 | + setIsLongPressing(false) |
| 28 | + startTimer(false) |
| 29 | + event.preventDefault() |
| 30 | + |
| 31 | + if (onLongPressEnd?.current) { |
| 32 | + onLongPressEnd.current() |
| 33 | + } |
| 34 | + }, [isLongPressing]) |
| 35 | + |
| 36 | + const [, clearTimeout] = useConditionalTimeout(() => { |
| 37 | + setIsLongPressing(true) |
| 38 | + |
| 39 | + if (onLongPressStart?.current) { |
| 40 | + onLongPressStart.current() |
| 41 | + } |
| 42 | + }, duration, timerOn) |
| 43 | + |
| 44 | + onMouseDown(longPressStart) |
| 45 | + onMouseLeave(longPressStop) |
| 46 | + onMouseUp(longPressStop) |
| 47 | + |
| 48 | + onTouchStart(longPressStart) |
| 49 | + onTouchEnd(longPressStop) |
| 50 | + |
| 51 | + return Object.freeze<UseLongPressResult>({ |
| 52 | + isLongPressing, |
| 53 | + onLongPressStart: setOnLongPressStart, |
| 54 | + onLongPressEnd: setOnLongPressEnd |
| 55 | + }) |
| 56 | +} |
| 57 | + |
| 58 | +export interface UseLongPressResult { |
| 59 | + isLongPressing: boolean |
| 60 | + onLongPressStart: CallbackSetter<void> |
| 61 | + onLongPressEnd: CallbackSetter<void> |
| 62 | +} |
| 63 | + |
| 64 | +export default useLongPress |
0 commit comments