Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-scroll-shadow.ts

70 lines2.0 KB

1import { useCallback, useEffect, useRef, useState } from "react";
2​
3export interface UseScrollShadowReturn {
4 scrollRef: React.RefObject<HTMLDivElement | null>;
5 canScrollUp: boolean;
6 canScrollDown: boolean;
7}
8​
9/**
10 * Hook that tracks scroll position to determine if scroll shadows should be visible
11 * at the top and bottom of a scrollable container.
12 *
13 * @returns Object containing the scroll ref and boolean flags for shadow visibility
14 */
15export function useScrollShadow(): UseScrollShadowReturn {
16 const scrollRef = useRef<HTMLDivElement>(null);
17 const [canScrollUp, setCanScrollUp] = useState(false);
18 const [canScrollDown, setCanScrollDown] = useState(false);
19​
20 const updateScrollShadows = useCallback(() => {
21 const element = scrollRef.current;
22 if (!element) return;
23​
24 const { scrollTop, scrollHeight, clientHeight } = element;
25​
26 // Can scroll up if we're not at the top
27 setCanScrollUp(scrollTop > 0);
28​
29 // Can scroll down if we're not at the bottom
30 // Add a small threshold (1px) to account for sub-pixel rendering
31 setCanScrollDown(scrollTop + clientHeight < scrollHeight - 1);
32 }, []);
33​
34 useEffect(() => {
35 const element = scrollRef.current;
36 if (!element) return;
37​
38 // Initial check
39 updateScrollShadows();
40​
41 // Update on scroll
42 element.addEventListener("scroll", updateScrollShadows, { passive: true });
43​
44 // Update on resize using ResizeObserver
45 const resizeObserver = new ResizeObserver(() => {
46 updateScrollShadows();
47 });
48​
49 resizeObserver.observe(element);
50​
51 // Also observe changes to the content inside
52 const mutationObserver = new MutationObserver(() => {
53 updateScrollShadows();
54 });
55​
56 mutationObserver.observe(element, {
57 childList: true,
58 subtree: true,
59 attributes: false,
60 });
61​
62 return () => {
63 element.removeEventListener("scroll", updateScrollShadows);
64 resizeObserver.disconnect();
65 mutationObserver.disconnect();
66 };
67 }, [updateScrollShadows]);
68​
69 return { scrollRef, canScrollUp, canScrollDown };