Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

VirtualList.tsx

105 lines2.9 KB

1import { createEffect, createMemo, on, onCleanup } from 'solid-js'
2import { Key } from '@solid-primitives/keyed'
3import { createVirtualizer } from '@tanstack/solid-virtual'
4import type { VirtualItem } from '@tanstack/solid-virtual'
5import type { Accessor, JSX } from 'solid-js'
6​
7type VirtualListProps<T> = {
8 each: ReadonlyArray<T>
9 getKey: (item: T) => VirtualItem['key']
10 class: string
11 contentClass: string
12 children: (item: Accessor<T>) => JSX.Element
14​
15type VisibleRow<T> = {
16 item: T
17 key: VirtualItem['key']
18 index: number
19 start: number
21​
22/**
23 * Renders measured rows for the visible portion of an ordered list.
24 * @param props - The items, stable keys, classes, and row content.
25 * @returns The scroll viewport and its visible rows.
26 */
27export function VirtualList<T>(props: VirtualListProps<T>): JSX.Element {
28 let scrollElement!: HTMLDivElement
29 const keyForIndex = createMemo(() => {
30 const keys = props.each.map(props.getKey)
31 return (index: number) => keys[index] ?? index
32 })
33 const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
34 get count() {
35 return props.each.length
36 },
37 getScrollElement: () => scrollElement,
38 get getItemKey() {
39 return keyForIndex()
40 },
41 estimateSize: () => 28,
42 overscan: 5,
43 useAnimationFrameWithResizeObserver: true,
44 })
45 const rows = createMemo(() => {
46 const items = props.each
47 const visible: Array<VisibleRow<T>> = []
48 for (const entry of virtualizer.getVirtualItems()) {
49 const item = items[entry.index]
50 if (item !== undefined) {
51 visible.push({
52 item,
53 key: props.getKey(item),
54 index: entry.index,
55 start: entry.start,
56 })
57 }
58 }
59 return visible
60 })
61​
62 return (
63 <div ref={scrollElement} class={props.class}>
64 <div
65 class={props.contentClass}
66 style={{
67 position: 'relative',
68 width: '100%',
69 height: `${virtualizer.getTotalSize()}px`,
70 }}
71 >
72 <Key each={rows()} by={(row) => row.key}>
73 {(row) => {
74 let element!: HTMLDivElement
75 createEffect(
76 on(
77 () => row().index,
78 (index) => {
79 element.setAttribute('data-index', String(index))
80 virtualizer.measureElement(element)
81 },
82 ),
83 )
84 onCleanup(() => virtualizer.measureElement(null))
85 return (
86 <div
87 ref={element}
88 data-index={row().index}
89 style={{
90 position: 'absolute',
91 top: 0,
92 left: 0,
93 width: '100%',
94 transform: `translateY(${row().start}px)`,
95 }}
96 >
97 {props.children(() => row().item)}
98 </div>
99 )
100 }}
101 </Key>
102 </div>
103 </div>
104 )