MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useAutoScroll

Function useAutoScroll

packages/react-aria/src/dnd/useAutoScroll.ts:27–116  ·  view source on GitHub ↗
(ref: RefObject<Element | null>)

Source from the content-addressed store, hash-verified

25}
26
27export function useAutoScroll(ref: RefObject<Element | null>): AutoScrollAria {
28 let scrollableRef = useRef<Element>(null);
29 let scrollableX = useRef(true);
30 let scrollableY = useRef(true);
31 useEffect(() => {
32 if (ref.current) {
33 scrollableRef.current = isScrollable(ref.current)
34 ? ref.current
35 : getScrollParent(ref.current);
36 let style = window.getComputedStyle(scrollableRef.current);
37 scrollableX.current = /(auto|scroll)/.test(style.overflowX);
38 scrollableY.current = /(auto|scroll)/.test(style.overflowY);
39 }
40 }, [ref]);
41
42 // oxlint-disable-next-line react/react-compiler
43 let state = useRef<{
44 timer: ReturnType<typeof requestAnimationFrame> | undefined;
45 dx: number;
46 dy: number;
47 }>({
48 timer: undefined,
49 dx: 0,
50 dy: 0
51 }).current;
52
53 useEffect(() => {
54 return () => {
55 if (state.timer) {
56 cancelAnimationFrame(state.timer);
57 state.timer = undefined;
58 }
59 };
60 // state will become a new object, so it's ok to use in the dependency array for unmount
61 }, [state]);
62
63 let scroll = useCallback(() => {
64 if (scrollableX.current && scrollableRef.current) {
65 scrollableRef.current.scrollLeft += state.dx;
66 }
67 if (scrollableY.current && scrollableRef.current) {
68 scrollableRef.current.scrollTop += state.dy;
69 }
70
71 if (state.timer) {
72 // oxlint-disable-next-line react/react-compiler
73 state.timer = requestAnimationFrame(scroll);
74 }
75 }, [scrollableRef, state]);
76
77 return {
78 move(x, y) {
79 // Most browsers auto scroll natively, but WebKit on macOS does not (iOS does 🤷‍♂️).
80 // https://bugs.webkit.org/show_bug.cgi?id=222636
81 if (!isWebKit() || isIOS() || !scrollableRef.current) {
82 return;
83 }
84

Callers 1

useDroppableCollectionFunction · 0.90

Calls 2

isScrollableFunction · 0.90
getScrollParentFunction · 0.90

Tested by

no test coverage detected