xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / components / src / virtual-list.test.ts

12.6 KB
1import { describe, expect, test } from "bun:test";
2import { Text, VStack } from "@cel-tui/core";
3import type { ContainerNode } from "@cel-tui/types";
4import { layout } from "../../core/src/layout.js";
5import { getMaxScrollOffset } from "../../core/src/scroll.js";
6import { VirtualList as PublicVirtualList } from "./index.js";
7import {
8  calculateVirtualWindow,
9  VirtualList,
10  type VirtualListScrollReason,
11} from "./virtual-list.js";
12
13interface Row {
14  id: string;
15  height: number;
16  label?: string;
17}
18
19function fixedRows(count: number, height = 1, prefix = "row"): Row[] {
20  return Array.from({ length: count }, (_, index) => ({
21    id: `${prefix}-${index}`,
22    height,
23  }));
24}
25
26function renderedRows(node: ContainerNode): number {
27  const block = node.children.find(
28    (child) => child.type === "vstack" && child.children.length > 0,
29  );
30  return block?.type === "vstack" ? block.children.length : 0;
31}
32
33function createFixedList(
34  options: {
35    overscan?: number;
36    maxCachedItems?: number;
37    maxRenderedItems?: number;
38    defaultScrollOffset?: number;
39    defaultStickToBottom?: boolean;
40  } = {},
41) {
42  return VirtualList<Row>({
43    itemKey: (row) => row.id,
44    renderItem: (row) => VStack({ height: row.height }, []),
45    estimatedItemHeight: 1,
46    ...options,
47  });
48}
49
50describe("calculateVirtualWindow", () => {
51  test("keeps the visible window even when overscan exceeds the hard cap", () => {
52    const starts = Array.from({ length: 1_000 }, (_, index) => index);
53    const ends = starts.map((start) => start + 1);
54    const range = calculateVirtualWindow({ starts, ends }, 500, 10, 10_000, 20);
55
56    expect(range.end - range.start).toBe(20);
57    expect(range.start).toBeLessThanOrEqual(500);
58    expect(range.end).toBeGreaterThanOrEqual(510);
59  });
60});
61
62describe("VirtualList", () => {
63  test("is available from the public components barrel", () => {
64    expect(PublicVirtualList).toBe(VirtualList);
65  });
66
67  test("measures variable-height rows and replaces estimates incrementally", () => {
68    const rows: Row[] = [
69      { id: "a", height: 1 },
70      { id: "b", height: 3 },
71      { id: "c", height: 2 },
72      { id: "d", height: 4 },
73    ];
74    const list = createFixedList({ overscan: 8 });
75
76    const node = list({ items: rows, width: 20, height: 3 });
77    const state = list.getState();
78
79    expect(state.totalHeight).toBe(10);
80    expect(state.measuredItems).toBe(4);
81    expect(state.cachedItems).toBe(4);
82    expect(renderedRows(node)).toBe(4);
83    expect(state.visibleStart).toBe(0);
84  });
85
86  test("includes configured cell gaps in prefix and scroll extents", () => {
87    const list = VirtualList<Row>({
88      itemKey: (row) => row.id,
89      renderItem: (row) => VStack({ height: row.height }, []),
90      estimatedItemHeight: 1,
91      gap: 2,
92      overscan: 20,
93    });
94
95    const node = list({
96      items: [
97        { id: "a", height: 1 },
98        { id: "b", height: 2 },
99        { id: "c", height: 3 },
100      ],
101      width: 20,
102      height: 4,
103    });
104
105    expect(list.getState()).toMatchObject({
106      totalHeight: 10,
107      maxScrollOffset: 6,
108    });
109    expect(getMaxScrollOffset(layout(node, 20, 4))).toBe(6);
110  });
111
112  test("keeps rendered allocation bounded independently of collection length", () => {
113    const rows = fixedRows(10_000);
114    let renderCalls = 0;
115    const list = VirtualList<Row>({
116      itemKey: (row) => row.id,
117      renderItem: (row) => {
118        renderCalls++;
119        return Text(row.id);
120      },
121      estimatedItemHeight: 1,
122      overscan: 4,
123      maxRenderedItems: 32,
124    });
125
126    const node = list({ items: rows, width: 80, height: 12 });
127
128    expect(list.getState().renderedItems).toBeLessThanOrEqual(32);
129    expect(renderedRows(node)).toBeLessThanOrEqual(32);
130    expect(renderCalls).toBeLessThanOrEqual(32 * 3);
131    expect(list.getState().totalHeight).toBe(10_000);
132  });
133
134  test("supports controlled scrolling without mutating the supplied offset", () => {
135    const rows = fixedRows(100);
136    const events: Array<[number, number, VirtualListScrollReason]> = [];
137    const list = createFixedList({ overscan: 0 });
138    const onScroll = (
139      offset: number,
140      maxOffset: number,
141      reason: VirtualListScrollReason,
142    ) => {
143      events.push([offset, maxOffset, reason]);
144    };
145
146    const first = list({
147      items: rows,
148      width: 20,
149      height: 10,
150      scrollOffset: 0,
151      onScroll,
152    });
153    first.props.onScroll?.(20, 90);
154
155    expect(events).toEqual([[20, 90, "input"]]);
156    expect(list.getState().scrollOffset).toBe(0);
157
158    list({
159      items: rows,
160      width: 20,
161      height: 10,
162      scrollOffset: 20,
163      onScroll,
164    });
165    expect(list.getState().scrollOffset).toBe(20);
166    expect(list.getState().anchorKey).toBe("row-20");
167  });
168
169  test("manages omitted scrollOffset internally", () => {
170    const rows = fixedRows(100);
171    const list = createFixedList({ overscan: 0 });
172    const first = list({ items: rows, width: 20, height: 10 });
173
174    first.props.onScroll?.(25, 90);
175    list({ items: rows, width: 20, height: 10 });
176
177    expect(list.getState().scrollOffset).toBe(25);
178    expect(list.getState().anchorKey).toBe("row-25");
179  });
180
181  test("sticks to appended content until wheel input leaves the bottom", () => {
182    let rows = fixedRows(20);
183    const stickyChanges: boolean[] = [];
184    const list = createFixedList({
185      overscan: 0,
186      defaultStickToBottom: true,
187    });
188
189    let node = list({
190      items: rows,
191      width: 20,
192      height: 5,
193      onStickToBottomChange: (stuck) => stickyChanges.push(stuck),
194    });
195    expect(list.getState()).toMatchObject({
196      scrollOffset: 15,
197      stickToBottom: true,
198      anchorKey: "row-15",
199    });
200
201    rows = [...rows, ...fixedRows(5, 1, "new")];
202    node = list({
203      items: rows,
204      width: 20,
205      height: 5,
206      onStickToBottomChange: (stuck) => stickyChanges.push(stuck),
207    });
208    expect(list.getState().scrollOffset).toBe(20);
209
210    node.props.onScroll?.(16, 20);
211    list({ items: rows, width: 20, height: 5 });
212    expect(list.getState()).toMatchObject({
213      scrollOffset: 16,
214      stickToBottom: false,
215    });
216    expect(stickyChanges).toEqual([false]);
217
218    rows = [...rows, ...fixedRows(5, 1, "later")];
219    list({ items: rows, width: 20, height: 5 });
220    expect(list.getState().anchorKey).toBe("row-16");
221    expect(list.getState().scrollOffset).toBe(16);
222  });
223
224  test("preserves the core Infinity means scroll-to-end convention", () => {
225    let rows = fixedRows(20);
226    const list = createFixedList({ overscan: 0 });
227
228    list({
229      items: rows,
230      width: 20,
231      height: 5,
232      scrollOffset: Infinity,
233    });
234    expect(list.getState()).toMatchObject({
235      scrollOffset: 15,
236      stickToBottom: true,
237    });
238
239    rows = [...rows, ...fixedRows(5, 1, "new")];
240    list({
241      items: rows,
242      width: 20,
243      height: 5,
244      scrollOffset: Infinity,
245    });
246    expect(list.getState()).toMatchObject({
247      scrollOffset: 20,
248      anchorKey: "new-0",
249    });
250  });
251
252  test("preserves a keyed viewport anchor across prepend and removal", () => {
253    let rows = fixedRows(50);
254    const list = createFixedList({
255      overscan: 8,
256      defaultScrollOffset: 20,
257    });
258
259    list({ items: rows, width: 20, height: 5 });
260    expect(list.getState().anchorKey).toBe("row-20");
261
262    const prepended = fixedRows(5, 2, "old");
263    rows = [...prepended, ...rows];
264    list({ items: rows, width: 20, height: 5 });
265    expect(list.getState()).toMatchObject({
266      anchorKey: "row-20",
267      scrollOffset: 30,
268    });
269
270    rows = rows.slice(3);
271    list({ items: rows, width: 20, height: 5 });
272    expect(list.getState()).toMatchObject({
273      anchorKey: "row-20",
274      scrollOffset: 24,
275    });
276  });
277
278  test("compensates when a measured row above the anchor changes height", () => {
279    let rows = fixedRows(8);
280    const list = createFixedList({
281      overscan: 0,
282      defaultScrollOffset: 3,
283    });
284
285    list({ items: rows, width: 20, height: 2 });
286    expect(list.getState()).toMatchObject({
287      anchorKey: "row-3",
288      scrollOffset: 3,
289    });
290
291    rows = rows.map((row, index) =>
292      index === 0 ? { ...row, height: 4 } : row,
293    );
294    list({ items: rows, width: 20, height: 2 });
295
296    expect(list.getState()).toMatchObject({
297      anchorKey: "row-3",
298      scrollOffset: 6,
299      totalHeight: 11,
300    });
301  });
302
303  test("invalidates measured heights and reflows at a new width", () => {
304    const rows = [
305      { id: "a", text: "abcdefghij" },
306      { id: "b", text: "abcdefghij" },
307      { id: "c", text: "abcdefghij" },
308    ];
309    let renderCalls = 0;
310    const list = VirtualList<(typeof rows)[number]>({
311      itemKey: (row) => row.id,
312      renderItem: (row) => {
313        renderCalls++;
314        return Text(row.text, { wrap: "word" });
315      },
316      estimatedItemHeight: 1,
317      overscan: 20,
318      defaultScrollOffset: 1,
319    });
320
321    list({ items: rows, width: 10, height: 2 });
322    expect(list.getState().totalHeight).toBe(3);
323    const callsAtWideWidth = renderCalls;
324
325    list({ items: rows, width: 5, height: 2 });
326    expect(renderCalls).toBeGreaterThan(callsAtWideWidth);
327    expect(list.getState()).toMatchObject({
328      anchorKey: "b",
329      scrollOffset: 2,
330      totalHeight: 6,
331      cachedItems: 3,
332    });
333  });
334
335  test("applies and reports controlled anchor compensation", () => {
336    let rows = fixedRows(20);
337    const events: Array<[number, VirtualListScrollReason]> = [];
338    const list = createFixedList({ overscan: 8 });
339    const onScroll = (
340      offset: number,
341      _maxOffset: number,
342      reason: VirtualListScrollReason,
343    ) => {
344      events.push([offset, reason]);
345    };
346
347    list({
348      items: rows,
349      width: 20,
350      height: 5,
351      scrollOffset: 10,
352      onScroll,
353    });
354    rows = [{ id: "old", height: 3 }, ...rows];
355    const anchored = list({
356      items: rows,
357      width: 20,
358      height: 5,
359      scrollOffset: 10,
360      onScroll,
361    });
362
363    expect(anchored.props.scrollOffset).toBe(13);
364    expect(list.getState().anchorKey).toBe("row-10");
365    expect(events).toContainEqual([13, "anchor"]);
366
367    list({
368      items: rows,
369      width: 20,
370      height: 5,
371      scrollOffset: 10,
372      onScroll: (offset, _maxOffset, reason) => {
373        events.push([offset, reason]);
374      },
375    });
376    expect(events).toEqual([[13, "anchor"]]);
377  });
378
379  test("bounds and eagerly releases its measurement cache", () => {
380    const rows = fixedRows(100);
381    const list = createFixedList({
382      overscan: 0,
383      maxCachedItems: 3,
384      maxRenderedItems: 8,
385    });
386
387    for (const offset of [0, 20, 40]) {
388      list({ items: rows, width: 20, height: 3, scrollOffset: offset });
389      expect(list.getState().cachedItems).toBeLessThanOrEqual(3);
390    }
391
392    list.dispose();
393    expect(list.getState()).toMatchObject({ cachedItems: 0, measuredItems: 0 });
394
395    list({ items: rows, width: 20, height: 3 });
396    expect(list.getState().cachedItems).toBeGreaterThan(0);
397  });
398
399  test("supports explicit invalidation for mutable item content", () => {
400    const rows = fixedRows(3);
401    const list = createFixedList({ overscan: 8 });
402    list({ items: rows, width: 20, height: 2 });
403    expect(list.getState().totalHeight).toBe(3);
404
405    const firstRow = rows[0];
406    if (!firstRow) throw new Error("Expected a first row");
407    firstRow.height = 4;
408    list.invalidate("row-0");
409    list({ items: rows, width: 20, height: 2 });
410    expect(list.getState().totalHeight).toBe(6);
411  });
412
413  test("exposes imperative uncontrolled scrolling and reset", () => {
414    const rows = fixedRows(20);
415    const list = createFixedList({ overscan: 0 });
416    list({ items: rows, width: 20, height: 5 });
417
418    list.scrollTo(8);
419    list({ items: rows, width: 20, height: 5 });
420    expect(list.getState().scrollOffset).toBe(8);
421
422    list.scrollToEnd();
423    list({ items: rows, width: 20, height: 5 });
424    expect(list.getState()).toMatchObject({
425      scrollOffset: 15,
426      stickToBottom: true,
427    });
428
429    list.reset();
430    expect(list.getState()).toMatchObject({
431      scrollOffset: 0,
432      cachedItems: 0,
433      stickToBottom: false,
434    });
435  });
436
437  test("keeps numeric and string keys distinct", () => {
438    const list = VirtualList<{ id: string | number }>({
439      itemKey: (row) => row.id,
440      renderItem: (row) => Text(String(row.id)),
441    });
442
443    expect(() =>
444      list({
445        items: [{ id: 1 }, { id: "1" }],
446        width: 20,
447        height: 5,
448      }),
449    ).not.toThrow();
450  });
451
452  test("rejects duplicate typed item keys deterministically", () => {
453    const list = VirtualList<Row>({
454      itemKey: () => "same",
455      renderItem: (row) => VStack({ height: row.height }, []),
456    });
457
458    expect(() => list({ items: fixedRows(2), width: 20, height: 5 })).toThrow(
459      'Duplicate VirtualList item key: string "same"',
460    );
461  });
462});