|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' |
| 4 | + |
| 5 | +interface UseVirtualListOptions { |
| 6 | + totalCount: number |
| 7 | + estimatedRowHeight: number |
| 8 | + overscanScreens?: number |
| 9 | + maxRenderedItems?: number |
| 10 | + preserveKey?: string |
| 11 | +} |
| 12 | + |
| 13 | +interface VirtualItem { |
| 14 | + index: number |
| 15 | + offsetTop: number |
| 16 | + height: number |
| 17 | +} |
| 18 | + |
| 19 | +interface VirtualRange { |
| 20 | + start: number |
| 21 | + end: number |
| 22 | + paddingTop: number |
| 23 | + paddingBottom: number |
| 24 | + totalHeight: number |
| 25 | + virtualItems: VirtualItem[] |
| 26 | +} |
| 27 | + |
| 28 | +const savedScrollPositions = new Map<string, number>() |
| 29 | + |
| 30 | +export function useVirtualList<T>( |
| 31 | + items: readonly T[], |
| 32 | + { |
| 33 | + totalCount, |
| 34 | + estimatedRowHeight, |
| 35 | + overscanScreens = 3, |
| 36 | + maxRenderedItems = 100, |
| 37 | + preserveKey, |
| 38 | + }: UseVirtualListOptions, |
| 39 | +): VirtualRange & { |
| 40 | + containerRef: RefObject<HTMLDivElement | null> |
| 41 | + topSentinelRef: RefObject<HTMLDivElement | null> |
| 42 | + bottomSentinelRef: RefObject<HTMLDivElement | null> |
| 43 | + visibleItems: readonly T[] |
| 44 | + measureElement: (index: number, element: HTMLElement | null) => void |
| 45 | +} { |
| 46 | + const containerRef = useRef<HTMLDivElement | null>(null) |
| 47 | + const topSentinelRef = useRef<HTMLDivElement | null>(null) |
| 48 | + const bottomSentinelRef = useRef<HTMLDivElement | null>(null) |
| 49 | + const heightsRef = useRef(new Map<number, number>()) |
| 50 | + const [scrollState, setScrollState] = useState({ scrollTop: 0, viewportHeight: 0 }) |
| 51 | + |
| 52 | + const getHeight = useCallback( |
| 53 | + (index: number) => heightsRef.current.get(index) ?? estimatedRowHeight, |
| 54 | + [estimatedRowHeight], |
| 55 | + ) |
| 56 | + |
| 57 | + const getOffsetTop = useCallback( |
| 58 | + (index: number) => { |
| 59 | + let offset = 0 |
| 60 | + for (let i = 0; i < index; i += 1) offset += getHeight(i) |
| 61 | + return offset |
| 62 | + }, |
| 63 | + [getHeight], |
| 64 | + ) |
| 65 | + |
| 66 | + const totalHeight = useMemo(() => { |
| 67 | + let measuredDelta = 0 |
| 68 | + heightsRef.current.forEach((height) => { |
| 69 | + measuredDelta += height - estimatedRowHeight |
| 70 | + }) |
| 71 | + return Math.max(0, totalCount * estimatedRowHeight + measuredDelta) |
| 72 | + }, [estimatedRowHeight, totalCount, scrollState]) |
| 73 | + |
| 74 | + const range = useMemo(() => { |
| 75 | + const { scrollTop, viewportHeight } = scrollState |
| 76 | + const overscanPixels = viewportHeight * overscanScreens |
| 77 | + const requestedStart = Math.max(0, Math.floor((scrollTop - overscanPixels) / estimatedRowHeight)) |
| 78 | + const requestedEnd = Math.min( |
| 79 | + totalCount, |
| 80 | + Math.ceil((scrollTop + viewportHeight + overscanPixels) / estimatedRowHeight), |
| 81 | + ) |
| 82 | + const visibleCenter = Math.max(0, Math.floor((scrollTop + viewportHeight / 2) / estimatedRowHeight)) |
| 83 | + const requestedCount = Math.max(1, requestedEnd - requestedStart) |
| 84 | + const cappedCount = Math.min(maxRenderedItems, requestedCount, totalCount) |
| 85 | + const start = requestedCount > maxRenderedItems |
| 86 | + ? Math.max(0, Math.min(totalCount - cappedCount, visibleCenter - Math.floor(cappedCount / 2))) |
| 87 | + : requestedStart |
| 88 | + const end = Math.min(totalCount, start + cappedCount) |
| 89 | + const paddingTop = getOffsetTop(start) |
| 90 | + const virtualItems = Array.from({ length: end - start }, (_, position) => { |
| 91 | + const index = start + position |
| 92 | + return { index, offsetTop: getOffsetTop(index), height: getHeight(index) } |
| 93 | + }) |
| 94 | + const renderedHeight = virtualItems.reduce((sum, item) => sum + item.height, 0) |
| 95 | + |
| 96 | + return { |
| 97 | + start, |
| 98 | + end, |
| 99 | + paddingTop, |
| 100 | + paddingBottom: Math.max(0, totalHeight - paddingTop - renderedHeight), |
| 101 | + totalHeight, |
| 102 | + virtualItems, |
| 103 | + } |
| 104 | + }, [estimatedRowHeight, getHeight, getOffsetTop, maxRenderedItems, overscanScreens, scrollState, totalCount, totalHeight]) |
| 105 | + |
| 106 | + const updateScrollState = useCallback(() => { |
| 107 | + const container = containerRef.current |
| 108 | + if (!container) return |
| 109 | + const next = { scrollTop: container.scrollTop, viewportHeight: container.clientHeight } |
| 110 | + if (preserveKey) savedScrollPositions.set(preserveKey, next.scrollTop) |
| 111 | + setScrollState((previous) => ( |
| 112 | + previous.scrollTop === next.scrollTop && previous.viewportHeight === next.viewportHeight ? previous : next |
| 113 | + )) |
| 114 | + }, [preserveKey]) |
| 115 | + |
| 116 | + useLayoutEffect(() => { |
| 117 | + const container = containerRef.current |
| 118 | + if (!container) return |
| 119 | + if (preserveKey) container.scrollTop = savedScrollPositions.get(preserveKey) ?? container.scrollTop |
| 120 | + updateScrollState() |
| 121 | + }, [preserveKey, updateScrollState]) |
| 122 | + |
| 123 | + useEffect(() => { |
| 124 | + const container = containerRef.current |
| 125 | + if (!container) return |
| 126 | + const observer = new IntersectionObserver(updateScrollState, { root: container }) |
| 127 | + if (topSentinelRef.current) observer.observe(topSentinelRef.current) |
| 128 | + if (bottomSentinelRef.current) observer.observe(bottomSentinelRef.current) |
| 129 | + container.addEventListener('scroll', updateScrollState, { passive: true }) |
| 130 | + const resizeObserver = new ResizeObserver(updateScrollState) |
| 131 | + resizeObserver.observe(container) |
| 132 | + return () => { |
| 133 | + container.removeEventListener('scroll', updateScrollState) |
| 134 | + observer.disconnect() |
| 135 | + resizeObserver.disconnect() |
| 136 | + } |
| 137 | + }, [updateScrollState]) |
| 138 | + |
| 139 | + const measureElement = useCallback((index: number, element: HTMLElement | null) => { |
| 140 | + if (!element) return |
| 141 | + const nextHeight = element.getBoundingClientRect().height |
| 142 | + if (nextHeight > 0 && heightsRef.current.get(index) !== nextHeight) { |
| 143 | + heightsRef.current.set(index, nextHeight) |
| 144 | + updateScrollState() |
| 145 | + } |
| 146 | + }, [updateScrollState]) |
| 147 | + |
| 148 | + return { |
| 149 | + ...range, |
| 150 | + containerRef, |
| 151 | + topSentinelRef, |
| 152 | + bottomSentinelRef, |
| 153 | + visibleItems: items.slice(range.start, range.end), |
| 154 | + measureElement, |
| 155 | + } |
| 156 | +} |
0 commit comments