import { afterEach, describe, expect, it, vi } from "vitest"; import { mount } from "@vue/test-utils"; import { defineComponent, h, nextTick, ref, type PropType } from "vue"; import { ListBox, ListBoxItem, ListBoxItemIndicator, useVirtualRows, bindVirtualRows, Table, TableContent, TableHeader, TableColumn, TableBody, TableRow, TableCell, } from "../packages/vue/src"; import type { ListBoxDataItem } from "../packages/vue/src/components/list-box/context"; const wrappers: { unmount: () => void; element: Element }[] = []; afterEach(() => { while (wrappers.length) wrappers.pop()!.unmount(); }); // --------------------------------------------------------------------------- // useVirtualRows geometry (pure measurement, px semantics) // --------------------------------------------------------------------------- describe("useVirtualRows geometry", () => { it("lays out fixed rows with gap between rows only", () => { const rows = useVirtualRows({ count: 100, rowHeight: 50, gap: 4, padding: 12, overscan: 0, }); // Padding carries no gap; each row extent is height + gap after it. expect(rows.rowOffsetOf(0)).toBe(12); expect(rows.rowExtentOf(0)).toBe(54); expect(rows.rowExtentOf(99)).toBe(50); // last row: no gap after // Total: pad top + 100 rows + 99 gaps + pad bottom (no loader). expect(rows.totalHeight.value).toBe(12 + 100 * 50 + 99 * 4 + 12); }); it("falls back to estimatedRowHeight for undefined variable heights", () => { const rows = useVirtualRows({ count: 3, rowHeight: (index: number) => (index === 1 ? undefined : 40), estimatedRowHeight: 64, }); expect(rows.rowExtentOf(0)).toBe(40); expect(rows.rowExtentOf(1)).toBe(64); expect(rows.rowExtentOf(2)).toBe(40); expect(rows.totalHeight.value).toBe(144); }); it("reserves the loader span (gap + loader) at the end of the stream", () => { const rows = useVirtualRows({ count: 2, rowHeight: 30, gap: 6, loaderHeight: 40, padding: 10, }); // pad 10 + row 30 + gap 6 + row 30 + (gap 6 + loader 40) + pad 10. expect(rows.totalHeight.value).toBe(10 + 30 + 6 + 30 + 6 + 40 + 10); rows.update(0, 200); // The trailing spacer covers the unrendered span, loader and padding. const window = rows.window.value; expect(window.start).toBe(0); expect(window.end).toBe(2); expect(window.padTop).toBe(10); expect(window.padBottom).toBe(6 + 40 + 10); }); it("windows rows by binary search without gaps or overlaps", () => { const rows = useVirtualRows({ count: 1000, rowHeight: (index: number) => 40 + (index % 3) * 20, gap: 8, overscan: 2, }); rows.update(5000, 300); const { start, end, padTop, padBottom } = rows.window.value; expect(start).toBeGreaterThanOrEqual(0); expect(end).toBeLessThanOrEqual(1000); expect(start).toBeLessThan(end); // padTop + rendered extents + padBottom rebuilds the whole stream. let rendered = 0; for (let i = start; i < end; i++) rendered += rows.rowExtentOf(i); expect(padTop).toBe(rows.rowOffsetOf(start)); expect(padTop + rendered + padBottom).toBe(rows.totalHeight.value); // The viewport is covered: first/last rendered rows straddle it. expect(rows.rowOffsetOf(start)).toBeLessThanOrEqual(5000); expect(rows.rowOffsetOf(end)).toBeGreaterThanOrEqual(5300); }); it("updates the window when count and heights change reactively", () => { const count = ref(50); const tall = ref(false); const rows = useVirtualRows({ count: () => count.value, rowHeight: (index: number) => (tall.value ? 80 : 40), overscan: 0, }); expect(rows.totalHeight.value).toBe(50 * 40); count.value = 60; tall.value = true; expect(rows.totalHeight.value).toBe(60 * 80); }); it("scrolls a row into view clamped to the row stream", () => { const rows = useVirtualRows({ count: 100, rowHeight: 50, padding: 10 }); const element = { scrollTop: 0, clientHeight: 200, } as unknown as HTMLElement; rows.scrollToIndex(element, 10); // Row 10 spans [510, 560): align its bottom with the viewport. expect(element.scrollTop).toBe(360); rows.scrollToIndex(element, 0); expect(element.scrollTop).toBe(10); }); }); // --------------------------------------------------------------------------- // ListBox virtual row stream (headings, loader, identity, aria indexing) // --------------------------------------------------------------------------- interface Item extends ListBoxDataItem { id: number; textValue: string; heading?: string; } function makeItems(count: number): Item[] { return Array.from({ length: count }, (_, index) => ({ id: index + 1, textValue: `条目 ${index + 1}`, heading: index % 4 === 0 ? `分组 ${Math.floor(index / 4) + 1}` : undefined, })); } const RowHarness = defineComponent({ props: { items: { type: Array as PropType, required: true }, modelValue: { type: Array as PropType<(string | number)[]>, default: () => [], }, gap: { type: Number, default: 0 }, padding: { type: Number, default: 0 }, headingHeight: { type: Number, default: 48 }, loaderHeight: { type: Number, default: 48 }, rowHeight: { type: [Number, Function], default: 50 }, overscan: { type: Number, default: 5 }, }, emits: ["update:modelValue"], setup(props, { emit }) { const local = ref([...(props.modelValue as (string | number)[])]); return () => h( ListBox, { items: props.items, virtualized: true, modelValue: local.value, "onUpdate:modelValue": (keys: (string | number)[]) => { local.value = keys; emit("update:modelValue", keys); }, selectionMode: "multiple", rowHeight: props.rowHeight as never, overscan: props.overscan, headingHeight: props.headingHeight, loaderHeight: props.loaderHeight, gap: props.gap, padding: props.padding, class: "h-[200px] overflow-y-auto", "aria-label": "虚拟行测试", }, { default: ({ item }: { item: Item }) => h( ListBoxItem, { id: item.id, textValue: item.textValue }, { default: () => item.textValue, indicator: () => h(ListBoxItemIndicator), }, ), loader: () => h("div", { "data-test": "loader" }, "加载更多"), }, ); }, }); async function mountRows(props: Record = {}) { const wrapper = mount(RowHarness, { props: props as never, attachTo: document.body, }); wrappers.push(wrapper); await nextTick(); await new Promise((resolve) => setTimeout(resolve, 2)); return wrapper; } const rowWrappers = () => [ ...document.querySelectorAll('[data-slot="list-box-virtual-content"] > div'), ]; describe("ListBox virtual row stream", () => { it("renders heading and loader rows with their own heights", async () => { await mountRows({ items: makeItems(40), gap: 8, padding: 12, headingHeight: 32, loaderHeight: 40, rowHeight: 50, }); const rows = rowWrappers(); // Row stream starts with the top padding spacer (no gap on padding). expect(rows[0]!.getAttribute("style")).toContain("height: 12px"); // Heading row: heading height plus the gap after it (content rows only). const headingRow = rows[1]!; expect(headingRow.textContent).toContain("分组 1"); expect(headingRow.getAttribute("style")).toContain("height: 40px"); // Item rows carry height + gap after them. const itemRow = rows[2]!; expect(itemRow.querySelector('[data-slot="list-box-item"]')).toBeTruthy(); expect(itemRow.getAttribute("style")).toContain("height: 58px"); }); it("keeps heading rows out of the aria item indexing", async () => { await mountRows({ items: makeItems(40), rowHeight: 50 }); const options = [...document.querySelectorAll('[role="option"]')]; expect(options.length).toBeGreaterThan(0); // Item 1 is the first option even though a heading precedes it. expect(options[0]!.getAttribute("aria-posinset")).toBe("1"); expect(options[0]!.getAttribute("aria-setsize")).toBe("40"); const headings = [...document.querySelectorAll('[data-slot="header"]')]; expect(headings.length).toBeGreaterThan(0); for (const heading of headings) expect(heading.hasAttribute("aria-posinset")).toBe(false); }); it("renders the loader slot as its own trailing row", async () => { await mountRows({ items: makeItems(3), loaderHeight: 40, padding: 0, overscan: 20, }); const rows = rowWrappers(); const last = rows[rows.length - 1]!; expect(last.querySelector('[data-test="loader"]')).toBeTruthy(); expect(last.getAttribute("style")).toContain("height: 40px"); }); it("keeps logical selection while rows move in and out of the window", async () => { const wrapper = await mountRows({ items: makeItems(40) }); const options = () => [...document.querySelectorAll('[role="option"]')]; // Select the first rendered row through the DOM. options()[0]!.dispatchEvent(new MouseEvent("click", { bubbles: true })); await nextTick(); await new Promise((resolve) => setTimeout(resolve, 2)); // The logical key survives even though the row itself is a moving window. expect(wrapper.emitted("update:modelValue")?.[0]).toEqual([[1]]); // The controlled value flows back and marks the mounted row. expect(options()[0]!.getAttribute("aria-selected")).toBe("true"); }); it("marks the virtualized root and keeps aria-setsize on the full set", async () => { await mountRows({ items: makeItems(40) }); const root = document.querySelector("[data-hv-listbox]")!; expect(root.hasAttribute("data-virtualized")).toBe(true); const options = [...document.querySelectorAll('[role="option"]')]; for (const option of options) expect(option.getAttribute("aria-setsize")).toBe("40"); }); }); it("review: numeric and string keys preserve local row identity on reorder", async () => { const Stateful = defineComponent({ props: { item: { type: Object as PropType<{ id: string | number }>, required: true, }, }, setup(props) { const born = `${typeof props.item.id}:${props.item.id}`; return () => h( ListBoxItem, { id: props.item.id }, () => `${typeof props.item.id}:${props.item.id}/${born}`, ); }, }); const items = [{ id: 0 }, { id: "0" }]; const w = mount(ListBox, { props: { items, virtualized: true, rowHeight: 50 }, slots: { default: ({ item }: { item: { id: string | number } }) => h(Stateful, { item }), }, attachTo: document.body, }); wrappers.push(w); await nextTick(); await nextTick(); await w.setProps({ items: [...items].reverse() }); await nextTick(); await nextTick(); expect(w.findAll('[role="option"]').map((x) => x.text())).toEqual([ "string:0/string:0", "number:0/number:0", ]); }); it("measures unknown rows by typed key and preserves the scroll anchor", async () => { const keys = ref<(number | string)[]>( Array.from({ length: 20 }, (_, i) => i), ); const rows = useVirtualRows({ count: 20, keys, rowHeight: () => undefined, estimatedRowHeight: 50, overscan: 0, }); const viewport = document.createElement("div"); document.body.append(viewport); Object.defineProperty(viewport, "clientHeight", { value: 100 }); viewport.scrollTop = 300; const detach = bindVirtualRows(rows, viewport); const node = document.createElement("div"); viewport.append(node); vi.spyOn(node, "getBoundingClientRect").mockReturnValue({ height: 100, } as DOMRect); rows.measureRow(0, node); await nextTick(); expect(rows.rowExtentOf(0)).toBe(100); expect(viewport.scrollTop).toBe(350); expect(rows.window.value.start).toBe(6); keys.value = ["0", ...keys.value.slice(1)]; expect(rows.rowExtentOf(0)).toBe(50); // string zero must not reuse numeric zero's size detach(); viewport.remove(); rows.measureRow(0, null); await nextTick(); }); it("scroll positioning includes the body origin and sticky occlusion", () => { const rows = useVirtualRows({ count: 30, rowHeight: 50 }); const viewport = document.createElement("div"), body = document.createElement("div"); Object.defineProperty(viewport, "clientHeight", { value: 200 }); vi.spyOn(viewport, "getBoundingClientRect").mockImplementation( () => ({ top: 0 }) as DOMRect, ); vi.spyOn(body, "getBoundingClientRect").mockImplementation( () => ({ top: 36 - viewport.scrollTop }) as DOMRect, ); const detach = bindVirtualRows(rows, viewport, { content: body, scrollPaddingStart: 40, }); rows.scrollToIndex(viewport, 10); expect(viewport.scrollTop).toBe(386); // 36 + row top500 + height50 - viewport200 rows.scrollToIndex(viewport, 0); expect(viewport.scrollTop).toBe(0); detach(); }); it("explicit TableRow height uses a content box without changing ordinary cells", () => { const root = mount( defineComponent({ render: () => h(Table, () => h(TableContent, () => [ h(TableHeader, () => h(TableColumn, { isRowHeader: true }, () => "Header"), ), h(TableBody, () => [ h(TableRow, { rowKey: 1, height: 42 }, () => h(TableCell, () => "Fixed"), ), h(TableRow, { rowKey: 2 }, () => h(TableCell, () => "Natural")), ]), ]), ), }), ); wrappers.push(root); expect(root.findAll('[data-slot="table-cell"]')[0].attributes("scope")).toBe( "row", ); expect(root.findAll(".hv-table__fixed-cell-content")).toHaveLength(1); expect( root.findAll('[data-slot="table-row"]')[1].attributes("style") ?? "", ).not.toContain("height"); });