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
+244
View File
@@ -0,0 +1,244 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import {
Button,
Description,
Header,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
bindVirtualRows,
useVirtualRows,
} from "@heroui-vue/components";
/**
* HD-09 virtual layout harness: variable row heights, heading rows, loader
* rows, gap/padding, container resizing, scroll positioning and keyboard
* navigation across unmounted windows — with selection identity kept over
* filtering and appends.
*/
const headingHeight = 32;
const fallbackRow = 48;
const rowHeight = (index: number) =>
index % 3 === 0 ? 40 : index % 3 === 1 ? 64 : 80;
const query = ref("");
const allItems = ref(
Array.from({ length: 800 }, (_, index) => ({
id: index + 1,
textValue: `条目 ${index + 1}`,
heading: index % 5 === 0 ? `分组 ${Math.floor(index / 5) + 1}` : undefined,
})),
);
const filteredItems = computed(() => {
const text = query.value.trim();
if (!text) return allItems.value;
return allItems.value.filter((item) => item.textValue.includes(text));
});
const selected = ref<(string | number)[]>([]);
const listHeight = ref(320);
const loading = ref(false);
function appendItems() {
loading.value = true;
setTimeout(() => {
const start = allItems.value.length;
allItems.value = [
...allItems.value,
...Array.from({ length: 100 }, (_, index) => ({
id: start + index + 1,
textValue: `条目 ${start + index + 1}`,
heading:
(start + index) % 5 === 0
? `分组 ${Math.floor((start + index) / 5) + 1}`
: undefined,
})),
];
loading.value = false;
}, 300);
}
function selectFarItem() {
selected.value = [allItems.value[600]?.id ?? 601];
listboxRef.value?.focus(selected.value[0] as never);
}
const listboxRef = ref<{ focus: (key?: never) => void } | null>(null);
// ---- variable-height table window ----
const tableCount = ref(300);
const tableRowHeight = (index: number) => (index % 2 ? 44 : 72);
const tableRows = useVirtualRows({
count: () => tableCount.value,
rowHeight: tableRowHeight,
estimatedRowHeight: fallbackRow,
loaderHeight: 40,
gap: 4,
padding: 12,
overscan: 6,
});
const tableWindow = tableRows.window;
const tableItems = computed(() =>
Array.from({ length: tableCount.value }, (_, index) => ({
id: index + 1,
name: `行 ${index + 1}`,
})),
);
const visibleTableRows = computed(() =>
tableItems.value.slice(tableWindow.value.start, tableWindow.value.end),
);
const scrollRef = ref<HTMLElement | null>(null);
const scrollElement = () => scrollRef.value;
function jumpToRow(index: number) {
const element = scrollElement();
if (element) tableRows.scrollToIndex(element, index);
}
let detach: (() => void) | undefined;
onMounted(() => {
const element = scrollElement();
if (element) detach = bindVirtualRows(tableRows, element);
});
onUnmounted(() => detach?.());
</script>
<template>
<main style="padding: 24px; display: grid; gap: 24px">
<section style="display: grid; gap: 8px">
<h2>可变行高 / 分组 / 加载行 / gap / padding</h2>
<div style="display: flex; gap: 8px; align-items: center">
<Label for="virtual-filter">过滤</Label>
<Input
id="virtual-filter"
:model-value="query"
placeholder="按文本过滤…"
@update:model-value="query = $event"
/>
<Button
size="sm"
variant="secondary"
@click="listHeight = listHeight === 320 ? 520 : 320"
>
容器高度 {{ listHeight }}
</Button>
<Button size="sm" variant="secondary" @click="appendItems">
追加 100 项
</Button>
<Button size="sm" variant="secondary" @click="selectFarItem">
选中并定位第 601 项
</Button>
</div>
<ListBox
id="virtual-listbox"
ref="listboxRef"
:items="filteredItems"
v-model="selected"
selection-mode="multiple"
virtualized
:row-height="rowHeight"
:estimated-row-height="fallbackRow"
:heading-height="headingHeight"
:loader-height="40"
:gap="8"
:padding="12"
:style="{
height: listHeight + 'px',
width: '320px',
overflowY: 'auto',
}"
aria-label="虚拟行验证列表"
>
<template #default="{ item }">
<ListBoxItem
:id="item.id"
:text-value="item.textValue"
style="height: 100%"
>
<div style="display: flex; flex-direction: column">
<Label>{{ item.textValue }}</Label>
<Description>高度随索引变化</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</template>
<template #loader>
<div
data-slot="virtual-loader"
style="display: flex; align-items: center; justify-content: center"
>
<Button size="sm" variant="ghost" @click="appendItems">
加载更多…
</Button>
</div>
</template>
</ListBox>
<p data-probe-selected>已选:{{ selected.join(",") || "无" }}</p>
</section>
<section style="display: grid; gap: 8px">
<h2>表格虚拟窗口(useVirtualRows)</h2>
<div style="display: flex; gap: 8px">
<Button size="sm" variant="secondary" @click="jumpToRow(150)">
定位第 150 行
</Button>
<Button
size="sm"
variant="secondary"
@click="tableCount = tableCount === 300 ? 600 : 300"
>
行数 {{ tableCount }}
</Button>
</div>
<Table>
<TableScrollContainer>
<div
ref="scrollRef"
data-slot="table-virtual-viewport"
style="height: 300px; width: 100%; overflow: auto"
>
<TableContent
aria-label="可变行高表格"
style="min-width: 520px; table-layout: fixed"
:aria-rowcount="tableCount + 1"
>
<TableHeader aria-rowindex="1">
<TableColumn id="name" is-row-header :min-width="160">
名称
</TableColumn>
<TableColumn id="info" :min-width="200">说明</TableColumn>
</TableHeader>
<TableBody>
<tr
aria-hidden="true"
:style="{ height: tableWindow.padTop + 'px' }"
/>
<TableRow
v-for="row in visibleTableRows"
:key="row.id"
:row-key="row.id"
:aria-rowindex="row.id + 1"
:style="{
height: `${tableRows.rowExtentOf(row.id - 1)}px`,
}"
>
<TableCell>{{ row.name }}</TableCell>
<TableCell>行高 44/72 交替</TableCell>
</TableRow>
<tr
aria-hidden="true"
:style="{ height: tableWindow.padBottom + 'px' }"
/>
</TableBody>
</TableContent>
</div>
</TableScrollContainer>
</Table>
</section>
</main>
</template>
+4
View File
@@ -259,6 +259,10 @@
"data-exiting"
]
},
"virtual-rows": {
"exports": ["useVirtualRows", "bindVirtualRows"],
"css": ["data-virtualized", "[data-slot=list-box][data-virtualized]"]
},
"list-box": {
"exports": [
"ListBox",
+84
View File
@@ -0,0 +1,84 @@
import {
ListBox,
ListBoxItem,
bindVirtualRows,
useVirtualRows,
type ListBoxDataItem,
type ListBoxProps,
type UseVirtualRows,
type UseVirtualRowsOptions,
type VirtualRowHeight,
type VirtualRowWindow,
} from "@heroui-vue/components";
// ---- row geometry API (px units; see the ListLayout/TableLayout mapping) ----
const fixed: VirtualRowHeight = 50;
const variable: VirtualRowHeight = (index: number) =>
index % 2 ? 44 : 72;
const partial: VirtualRowHeight = (index: number) =>
index % 2 ? undefined : 40;
const options: UseVirtualRowsOptions = {
count: 1000,
rowHeight: variable,
estimatedRowHeight: 48,
loaderHeight: 48,
gap: 8,
padding: 12,
overscan: 8,
};
const rows: UseVirtualRows = useVirtualRows(options);
const window: VirtualRowWindow = rows.window.value;
const total: number = rows.totalHeight.value;
const offset: number = rows.rowOffsetOf(10);
const extent: number = rows.rowExtentOf(10);
rows.update(0, 300);
declare const element: HTMLElement;
const detach: () => void = bindVirtualRows(rows, element);
rows.scrollToIndex(element, 10);
// @ts-expect-error Row heights are px numbers or index functions, not strings
const badHeight: VirtualRowHeight = "50px";
// @ts-expect-error count is required
const missingCount: UseVirtualRowsOptions = { rowHeight: 50 };
// ---- ListBox virtual layout options (ListLayout mapping) ----
const heading: ListBoxDataItem = {
id: 1,
textValue: "Item",
heading: "Group 1",
};
const listProps: ListBoxProps = {
items: [heading],
virtualized: true,
rowHeight: (index: number) => (index % 2 ? 64 : 40),
estimatedRowHeight: 50,
headingHeight: 32,
loaderHeight: 40,
gap: 8,
padding: 12,
};
// @ts-expect-error Heights are px numbers, not strings
const badHeading: ListBoxProps = { headingHeight: "32px" };
// @ts-expect-error Variable row height functions return numbers or undefined
const badRowFn: ListBoxProps = { rowHeight: () => "50" };
void [
ListBox,
ListBoxItem,
fixed,
variable,
partial,
options,
rows,
window,
total,
offset,
extent,
detach,
badHeight,
missingCount,
heading,
listProps,
badHeading,
badRowFn,
];
+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");
});
});