[READ-ONLY] Mirror of https://github.com/probablykasper/k5kit. Utilities for TypeScript and Svelte
1<script lang="ts">
2 import { KSelection } from '$lib/selection-svelte.ts'
3 import { RefreshLevel, VirtualGrid } from '$lib/virtual-grid.svelte.ts'
4
5 function generate_source_items(count: number) {
6 return Array.from({ length: count }, () => String(Math.random()).slice(2))
7 }
8 let source_items = generate_source_items(500_000)
9
10 const virtual_grid = VirtualGrid.create(source_items, {
11 row_prepare(source_item, index) {
12 return {
13 id: source_item,
14 n: index + 1,
15 b: source_item,
16 }
17 },
18 row_render(element, item, index) {
19 element.classList.toggle('odd', index % 2 === 0)
20 element.classList.toggle('selected', $selection.has(item.id))
21 },
22 })
23 const columns = [
24 { name: 'n', key: 'n', width: 100 },
25 { name: 'id', key: 'id', width: 50, is_pct: true },
26 { name: 'b', key: 'b', width: 50, is_pct: true },
27 ]
28 $effect(() => {
29 virtual_grid.set_columns(columns)
30 })
31
32 const selection = new KSelection(source_items, {
33 scroll_to({ index }) {
34 virtual_grid.scroll_to_index(index)
35 },
36 })
37 $effect(() => {
38 selection.update_all_items(source_items)
39 })
40 $effect(() => {
41 $selection
42 virtual_grid.refresh(RefreshLevel.AllRows)
43 })
44</script>
45
46<div class="h-screen max-h-screen gap-2 flex flex-col p-5">
47 <h1 class="text-3xl">Virtual grid with row selection</h1>
48 <p>{Intl.NumberFormat().format(500_000)} rows</p>
49 <!-- Virtual grid viewport -->
50 <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
51 <div
52 class="h-full relative overflow-y-auto bg-black/50 border border-white/20 outline-none"
53 tabindex="0"
54 {@attach selection.attach_events((e) => {
55 return virtual_grid.get_row_index_from_event(e)
56 })}
57 >
58 <!-- Virtual grid content -->
59 <div class="virtual-grid" {@attach virtual_grid.attach()}></div>
60 </div>
61</div>
62
63<style>
64 .virtual-grid :global {
65 .row {
66 height: 24px;
67 width: 100%;
68 position: absolute;
69 user-select: none;
70 }
71 .cell {
72 display: block;
73 height: 100%;
74 position: absolute;
75 height: 24px;
76 }
77 .odd {
78 background-color: hsl(0, 0%, 10%);
79 }
80 .selected {
81 background-color: hsl(224, 100%, 51%);
82 color: white;
83 }
84 }
85</style>