|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +interface UseTableScrollProps { |
| 4 | + tableContainerRef: React.RefObject<HTMLDivElement>; |
| 5 | + parentRef: React.RefObject<HTMLElement>; |
| 6 | + dependencies?: any[]; // Optional additional dependencies for the effect |
| 7 | +} |
| 8 | + |
| 9 | +export const useTableScroll = ({ |
| 10 | + tableContainerRef, |
| 11 | + parentRef, |
| 12 | + dependencies = [], |
| 13 | +}: UseTableScrollProps) => { |
| 14 | + // Get the CSS variable value for sticky top offset |
| 15 | + const getStickyTopOffset = React.useCallback(() => { |
| 16 | + // Try to get the variable from parent elements |
| 17 | + if (tableContainerRef.current) { |
| 18 | + const computedStyle = window.getComputedStyle(tableContainerRef.current); |
| 19 | + const stickyTopOffset = computedStyle.getPropertyValue( |
| 20 | + '--data-table-sticky-top-offset', |
| 21 | + ); |
| 22 | + |
| 23 | + return stickyTopOffset ? parseInt(stickyTopOffset, 10) : 0; |
| 24 | + } |
| 25 | + return 0; |
| 26 | + }, [tableContainerRef]); |
| 27 | + |
| 28 | + // Handle table scrolling function |
| 29 | + const handleTableScroll = React.useCallback(() => { |
| 30 | + if (tableContainerRef.current && parentRef.current) { |
| 31 | + // Get the sticky top offset value |
| 32 | + const stickyTopOffset = getStickyTopOffset(); |
| 33 | + |
| 34 | + // Scroll the parent container to the position of the table container |
| 35 | + const tableRect = tableContainerRef.current.getBoundingClientRect(); |
| 36 | + const parentRect = parentRef.current.getBoundingClientRect(); |
| 37 | + const scrollTop = tableRect.top - parentRect.top + parentRef.current.scrollTop; |
| 38 | + if (tableRect.top < parentRect.top) { |
| 39 | + // Adjust scroll position to account for sticky offset |
| 40 | + parentRef.current.scrollTo(0, scrollTop - stickyTopOffset); |
| 41 | + } |
| 42 | + } |
| 43 | + }, [parentRef, tableContainerRef, getStickyTopOffset]); |
| 44 | + |
| 45 | + // Trigger scroll adjustment with dependencies |
| 46 | + React.useLayoutEffect(() => { |
| 47 | + handleTableScroll(); |
| 48 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 49 | + }, [handleTableScroll, ...dependencies]); |
| 50 | + |
| 51 | + return { |
| 52 | + handleTableScroll, |
| 53 | + }; |
| 54 | +}; |
0 commit comments