feat(collections): virtual row layout with variable heights, headings, loader and gap/padding

ListBox virtualized mode grows a full row stream (padding spacers, data-driven
heading rows, item rows, #loader row) with px semantics mapped from the pinned
ListLayout contract: rowHeight may be a per-index function falling back to
estimatedRowHeight, gap sits between content rows only, padding is end
spacers, and every input is re-read per layout pass. Scroll ownership resolves
to the list root or the nearest scrolling ancestor so popovers scroll as a
whole with a sticky search field (data-virtualized hook; the historical 320px
self-scroll rule stays for non-virtualized lists).

Table gains the public useVirtualRows/bindVirtualRows pure geometry helpers
(prefix sums + binary search, no state kernel): variable heights, estimated
fallback, gap/padding and a loader reservation that stays consistent with the
rendered spacers. headingHeight and dropIndicatorThickness remain unavailable
(no sectioned header model, no drag-and-drop) and are recorded as such.

Pinned demo values stay explicit (table 42px, list-box/autocomplete 50px);
the table demo scrolls an outer viewport div because a native table cannot be
a scroll container (verified: 300px height blown out to 45036px).
This commit is contained in:
maoyingjie
2026-10-29 16:21:09 +08:00
parent dd4f04c200
commit 9e8d89e48d
16 changed files with 1127 additions and 114 deletions
+276
View File
@@ -0,0 +1,276 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref, type PropType } from "vue";
import {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
useVirtualRows,
} 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<Item[]>, 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<string, unknown> = {}) {
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");
});
});