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

App.svelte

98 lines2.5 KB

1<script lang="ts">
2 import {
3 createVirtualizer,
4 elementScroll,
5 type VirtualizerOptions,
6 } from '@tanstack/svelte-virtual'
7 import { onMount } from 'svelte'
8​
9 let virtualListEl: HTMLDivElement
10 let time = Date.now()
11 let randomIndex = Math.floor(Math.random() * 10000)
12 let scrollToFn: VirtualizerOptions<any, any>['scrollToFn'] = () => {}
13​
14 function easeInOutQuint(t: number) {
15 return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t
16 }
17​
18 $: virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
19 count: 10000,
20 getScrollElement: () => virtualListEl,
21 estimateSize: () => 35,
22 overscan: 5,
23 scrollToFn,
24 })
25​
26 onMount(() => {
27 scrollToFn = (offset, canSmooth, instance) => {
28 const duration = 1000
29 const start = virtualListEl.scrollTop
30 const startTime = (time = Date.now())
31​
32 function run() {
33 if (time !== startTime) return
34 const now = Date.now()
35 const elapsed = now - startTime
36 const progress = easeInOutQuint(Math.min(elapsed / duration, 1))
37 const interpolated = start + (offset - start) * progress
38​
39 if (elapsed < duration) {
40 elementScroll(interpolated, canSmooth, instance)
41 requestAnimationFrame(run)
42 } else {
43 elementScroll(interpolated, canSmooth, instance)
44 }
45 }
46​
47 requestAnimationFrame(run)
48 }
49 })
50</script>
51​
52<main>
53 <p>
54 This smooth scroll example uses the <code>`scrollToFn`</code> to implement a
55 custom scrolling function for the methods like
56 <code>`scrollToIndex`</code> and <code>`scrollToOffset`</code>
57 </p>
58 <br />
59 <br />
60​
61 <div>
62 <button
63 on:click={() => {
64 $virtualizer.scrollToIndex(randomIndex)
65 randomIndex = Math.floor(Math.random() * 10000)
66 }}
67 >
68 Scroll To Random Index ({randomIndex})
69 </button>
70 </div>
71​
72 <br />
73 <br />
74​
75 <div class="list scroll-container" bind:this={virtualListEl}>
76 <div
77 style="position: relative; height: {$virtualizer.getTotalSize()}px; width: 100%;"
78 >
79 {#each $virtualizer.getVirtualItems() as row (row.index)}
80 <div
81 class:list-item-even={row.index % 2 === 0}
82 class:list-item-odd={row.index % 2 === 1}
83 style="position: absolute; top: 0; left: 0; width: 100%; height: {row.size}px; transform: translateY({row.start}px);"
84 >
85 Row {row.index}
86 </div>
87 {/each}
88 </div>
89 </div>
90</main>
91​
92<style>
93 .scroll-container {
94 height: 200px;
95 width: 400px;
96 overflow: auto;
97 }
98</style>