-
Notifications
You must be signed in to change notification settings - Fork 1
/
virtual.tsx
106 lines (96 loc) · 2.57 KB
/
virtual.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import {
forwardRef,
useMemo,
useState,
type ForwardedRef,
type HTMLAttributes,
type ReactNode,
type SyntheticEvent,
} from 'react';
import { useThrottledCallback } from './hooks/use-throttled-callback.js';
import { Block, type FlexProps } from './layout.js';
import type { ReactHTMLElementsHacked } from './types.js';
import {
innerClassName,
itemClassName,
windowClassName,
} from './virtual.css.js';
export type VirtualizedListProps<
T extends keyof ReactHTMLElementsHacked = 'div',
> = FlexProps<T> & {
numItems: number;
renderItem: (
props: { index: number } & HTMLAttributes<HTMLDivElement>,
) => ReactNode;
itemHeight: number | ((props: { index: number }) => number);
listHeight: number;
overscan?: number;
};
export const VirtualizedList = forwardRef(
<T extends keyof ReactHTMLElementsHacked = 'div'>(
{
numItems,
itemHeight,
renderItem,
listHeight,
overscan = 0,
...props
}: VirtualizedListProps<T>,
forwardedRef?: ForwardedRef<ReactHTMLElementsHacked[T]>,
) => {
const [scrollTop, setScrollTop] = useState(0);
const throttledSetScrollTop = useThrottledCallback(setScrollTop, 100);
const fakeArray = useMemo(
() => Array.from({ length: numItems }, (_, index) => index),
[numItems],
);
const [innerHeight, items] = fakeArray.reduce<[number, ReactNode[]]>(
(previousValue, index) => {
const [itemTop, els] = previousValue;
const thisHeight =
typeof itemHeight === 'function' ? itemHeight({ index }) : itemHeight;
const visible =
itemTop + thisHeight >= scrollTop - overscan &&
itemTop <= scrollTop + listHeight + overscan;
const nextTop = itemTop + thisHeight;
if (visible) {
return [
nextTop,
[
...els,
renderItem({
index,
className: itemClassName,
style: {
top: `${itemTop}px`,
height: `${thisHeight}px`,
},
}),
],
];
}
return [nextTop, els];
},
[0, []],
);
return (
<Block
className={windowClassName}
onScroll={(e: SyntheticEvent) =>
throttledSetScrollTop(e.currentTarget.scrollTop)
}
ref={forwardedRef}
{...props}
>
<Block
className={innerClassName}
style={{
height: `${innerHeight}px`,
}}
>
{items}
</Block>
</Block>
);
},
);