Open History to see the last commit
1import { describe, test, expect, beforeEach } from 'vitest'
2import { elementUpdated, fixture, html, waitUntil } from '@open-wc/testing'
3import { LitElement } from 'lit'
4import { VirtualizerController } from '../src'
5import { createRef, ref, Ref } from 'lit/directives/ref.js'
6import { repeat } from 'lit/directives/repeat.js'
7import { customElement } from 'lit/decorators.js'
8β
9const width = 400
10const height = 400
11const count = 50
12β
13@customElement('test-list')
14class List extends LitElement {
15 private scrollElementRef: Ref<HTMLDivElement> = createRef()
16β
17 private virtualizerController: VirtualizerController<HTMLDivElement, Element>
18β
19 constructor() {
20 super()
21 this.virtualizerController = new VirtualizerController(this, {
22 getScrollElement: () => this.scrollElementRef.value,
23 count,
24 estimateSize: () => 50,
25 observeElementRect: (_, cb) => {
26 cb({ height, width })
27 },
28 })
29 }
30β
31 render() {
32 const virtualizer = this.virtualizerController.getVirtualizer()
33 const virtualRows = virtualizer.getVirtualItems()
34β
35 return html`
36 <div>
37 <button
38 @click=${() => {
39 virtualizer.scrollToIndex(count - 1)
40 console.log('scrolled down!')
41 }}
42 >
43 scroll to the end
44 </button>
45 <div class="list scroll-container" ${ref(this.scrollElementRef)}>
46 <div
47 style="position: relative; height: ${virtualizer.getTotalSize()}px; width: 100%;"
48 >
49 <div
50 style="position:absolute;top:0;left:0;width:100%;transform:translateY(${virtualRows[0]
51 ? virtualRows[0].start
52 : 0}px);"
53 >
54 ${repeat(
55 virtualRows,
56 (virtualRow) => virtualRow.key,
57 (virtualRow) =>
58 html` <div
59 data-index="${virtualRow.index}"
60 ${ref(virtualizer.measureElement)}
61 class="${virtualRow.index % 2 === 0
62 ? 'list-item-even'
63 : 'list-item-odd'}"
64 >
65 <div style="padding: 10px 0;">
66 <div>Row ${virtualRow.index}</div>
67 <div>Item ${virtualRow.index}</div>
68 </div>
69 </div>`,
70 )}
71 </div>
72 </div>
73 </div>
74 </div>
75 <style>
76 .list {
77 border: 1px solid #e6e4dc;
78 max-width: 100%;
79 }
80β
81 .list-item-even,
82 .list-item-odd {
83 display: flex;
84 align-items: center;
85 justify-content: center;
86 }
87β
88 .list-item-even {
89 background-color: #e6e4dc;
90 }
91β
92 .scroll-container {
93 height: ${height}px;
94 width: ${width}px;
95 overflow-y: auto;
96 }
97 </style>
98 `
99 }
100}
101β
102test('should render', async () => {
103 const el = await fixture(html`<test-list></test-list>`)
104 await elementUpdated(el)
105 expect(el).toBeTruthy()
106})
107β
108test('should render virtual items', async () => {
109 const el = await fixture(html`<test-list></test-list>`)
110 await elementUpdated(el)
111 await waitUntil(
112 () => el.shadowRoot.querySelector('[data-index="4"]'),
113 'Element did not render virtual items',
114 )
115})