-
-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathRowVirtualizerDynamic.svelte
More file actions
95 lines (86 loc) · 2.31 KB
/
RowVirtualizerDynamic.svelte
File metadata and controls
95 lines (86 loc) · 2.31 KB
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
<script lang="ts">
import { faker } from '@faker-js/faker'
import { createVirtualizer } from '@tanstack/svelte-virtual'
let virtualListEl = $state<HTMLDivElement | null>(null)
let virtualItemEls = $state<HTMLDivElement[]>([])
function randomNumber(min: number, max: number) {
return faker.number.int({ min, max })
}
const sentences = new Array(10000)
.fill(true)
.map(() => faker.lorem.sentence(randomNumber(20, 70)))
const count = sentences.length
let makeGetScrollElement = (scrollElement: HTMLDivElement | null) => () =>
scrollElement
let virtualizer = $derived(
createVirtualizer<HTMLDivElement, HTMLDivElement>({
count,
getScrollElement: makeGetScrollElement(virtualListEl),
estimateSize: () => 45,
}),
)
let items = $derived($virtualizer.getVirtualItems())
$effect(() => {
if (virtualItemEls.length)
virtualItemEls.forEach((el) => $virtualizer.measureElement(el))
})
</script>
<div>
<button
onclick={() => {
$virtualizer.scrollToIndex(0)
}}
>
scroll to the top
</button>
<span style="padding: 0 4px;"></span>
<button
onclick={() => {
$virtualizer.scrollToIndex(count / 2)
}}
>
scroll to the middle
</button>
<span style="padding: 0 4px;"></span>
<button
onclick={() => {
$virtualizer.scrollToIndex(count - 1)
}}
>
scroll to the end
</button>
<hr />
<div class="list scroll-container" bind:this={virtualListEl}>
<div
style="position: relative; height: {$virtualizer.getTotalSize()}px; width: 100%;"
>
<div
style="position: absolute; top: 0; left: 0; width: 100%; transform: translateY({items[0]
? items[0].start
: 0}px);"
>
{#each items as row, idx (row.index)}
<div
bind:this={virtualItemEls[idx]}
data-index={row.index}
class:list-item-even={row.index % 2 === 0}
class:list-item-odd={row.index % 2 === 1}
>
<div style="padding: 10px 0;">
<div>Row {row.index}</div>
<div>{sentences[row.index]}</div>
</div>
</div>
{/each}
</div>
</div>
</div>
</div>
<style>
.scroll-container {
height: 400px;
width: 400px;
overflow-y: auto;
contain: 'strict';
}
</style>