|
| 1 | +import { useCallback, useEffect, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +const EVENT_START_POLL_INTERVAL = 150; |
| 4 | + |
| 5 | +/** |
| 6 | + * Captures scroll (wheel) events on an overflowing element without hijacking |
| 7 | + * an in-progress canvas zoom gesture. |
| 8 | + * |
| 9 | + * Returns a ref to attach to the scrollable element and props to spread onto it. |
| 10 | + * Adds the `nowheel` class only when the pointer entered while no wheel gesture |
| 11 | + * was active and the element has overflow. |
| 12 | + */ |
| 13 | +export function useScrollCapture<T extends HTMLElement = HTMLDivElement>() { |
| 14 | + const ref = useRef<T>(null); |
| 15 | + const [captureScroll, setCaptureScroll] = useState(false); |
| 16 | + const wheelActiveRef = useRef(false); |
| 17 | + const wheelTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null); |
| 18 | + |
| 19 | + // Track global wheel activity so we can distinguish "pointer entered while idle" |
| 20 | + // from "pointer drifted over during a canvas zoom gesture". |
| 21 | + useEffect(() => { |
| 22 | + const onWheel = () => { |
| 23 | + wheelActiveRef.current = true; |
| 24 | + if (wheelTimeoutRef.current) clearTimeout(wheelTimeoutRef.current); |
| 25 | + wheelTimeoutRef.current = setTimeout(() => { |
| 26 | + wheelActiveRef.current = false; |
| 27 | + }, EVENT_START_POLL_INTERVAL); |
| 28 | + }; |
| 29 | + window.addEventListener('wheel', onWheel, { passive: true }); |
| 30 | + return () => window.removeEventListener('wheel', onWheel); |
| 31 | + }, []); |
| 32 | + |
| 33 | + const onMouseEnter = useCallback(() => { |
| 34 | + if (wheelActiveRef.current) return; |
| 35 | + const el = ref.current; |
| 36 | + if (el && el.scrollHeight > el.clientHeight) { |
| 37 | + setCaptureScroll(true); |
| 38 | + } |
| 39 | + }, []); |
| 40 | + |
| 41 | + const onMouseLeave = useCallback(() => { |
| 42 | + setCaptureScroll(false); |
| 43 | + }, []); |
| 44 | + |
| 45 | + return { |
| 46 | + ref, |
| 47 | + scrollCaptureProps: { |
| 48 | + className: captureScroll ? 'nowheel' : undefined, |
| 49 | + onMouseEnter, |
| 50 | + onMouseLeave, |
| 51 | + }, |
| 52 | + }; |
| 53 | +} |
0 commit comments