` 不能当滚动容器(高度为最小值、实测撑到 45036px),表格示例外层滚动 div 是结构差异的如实适配。动态过滤、异步追加与跨窗口键盘后逻辑身份/选择/`aria-posinset`(相对完整集合)保持;真实浏览器几何与滚动定位见 [任务结果](tasks/results/HD-09-VIRTUALIZATION.md)。
diff --git a/docs/upstream.md b/docs/upstream.md
index 5191cf6..8bb4709 100644
--- a/docs/upstream.md
+++ b/docs/upstream.md
@@ -169,7 +169,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
## LISTBOX-01(2026-10-23)
-固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示曾改为内联状态反馈(2026-10-28 HD-02 已按固定基线恢复为 alert 反馈与原结构),React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 固定行高虚拟化。依据、差异与限制见 [LISTBOX-01](component-notes.md)。
+固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示曾改为内联状态反馈(2026-10-28 HD-02 已按固定基线恢复为 alert 反馈与原结构),React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 虚拟行序列(固定/可变行高、heading/loader 行、gap/padding,语义映射见 list-box.md 的 ListLayout 映射表)。依据、差异与限制见 [LISTBOX-01](component-notes.md)。
## M33–M34(2026-10-23)
@@ -380,3 +380,7 @@ Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该
- 子菜单 hover 延迟契约对齐 react-aria `useSubmenuTrigger`(`delay` 默认 200ms、任何 open 请求先取消挂起定时、指针离开取消),Apache-2.0;实现为受控 open 门 + 定时器(Reka 2.11 的固定 100ms 悬停计时不可配置,见 DropdownSubmenuTrigger.vue 注释)。
- Autocomplete/ComboBox 的 `selectedItem`/`selectedItems.item` 插槽数据对应上游 `selectedItem`/`(T | null)[] selectedItems` 的值语义;以 Vue 插槽数据补齐,不复制 item 子树(固定源 Callout 的 children 复制行为不移植)。
- `createBaseContains` 与 `useFilter({sensitivity:"base"}).contains` 语义一致(locale 敏感折叠),作为公开过滤器与默认谓词共用。
+
+## HD-09 虚拟布局(2026-10-29)
+
+固定 ce90ea3 的 `TableLayout`/`ListLayout` 布局契约(table.mdx / list-box.mdx 参数表)与三个虚拟化示例(table 42px、list-box/autocomplete 50px 显式行高;autocomplete 弹层整体滚动 + sticky 搜索框)。`packages/vue/src/components/collection/virtual-rows.ts` 为自研纯测量实现(前缀和+二分),仅语义对齐契约(gap 在内容行之间、padding 为两端占位、loader 预留在行流末尾),非上游代码移植;ListBox 行序列走 VueUse `useVirtualList`(函数式 itemHeight)。autocomplete.css 的虚拟化弹层滚动规则为本仓新增(历史 320px 列表自滚规则限定 `:not([data-virtualized])` 保留);上游样式无 max-h 限制,`max-h-[min(400px,70vh)]` 是近似可用空间钳制的替代,差异如实记录。dropIndicatorThickness 对应拖放布局,Vue 侧 ListBox/Table 零拖放实现,不提供。
diff --git a/packages/styles/components/autocomplete.css b/packages/styles/components/autocomplete.css
index c74dd2a..8c7e09f 100644
--- a/packages/styles/components/autocomplete.css
+++ b/packages/styles/components/autocomplete.css
@@ -200,10 +200,24 @@
* popover itself is constrained (e.g. inside a Modal, or a short viewport). Without
* it the list keeps its full 320px and its overflow is clipped by the popover, making
* the last options unreachable. */
- [data-slot="list-box"] {
+ [data-slot="list-box"]:not([data-virtualized]) {
@apply max-h-[320px] min-h-0 scrollbar overflow-y-auto p-1.5 outline-none;
}
+ /* Virtualized lists scroll the popover content as a whole (the pinned
+ * upstream layout): the row window binds to this scrolling ancestor and the
+ * search field can stay sticky at its top. The height cap stands in for the
+ * upstream overlay's available-space clamp. */
+ &:has([data-slot="list-box"][data-virtualized]) [data-slot="autocomplete-filter"] {
+ @apply max-h-[min(400px,70vh)] overflow-y-auto;
+ }
+
+ [data-slot="list-box"][data-virtualized] {
+ @apply min-h-0 p-1.5 outline-none;
+ max-height: none;
+ overflow: visible;
+ }
+
[data-slot="list-box-item"] {
@apply px-2.5;
}
diff --git a/packages/vue/src/components/collection/virtual-rows.ts b/packages/vue/src/components/collection/virtual-rows.ts
new file mode 100644
index 0000000..c270b60
--- /dev/null
+++ b/packages/vue/src/components/collection/virtual-rows.ts
@@ -0,0 +1,169 @@
+/**
+ * Row geometry for table-shaped virtual windows. Pure measurement helpers —
+ * no state kernel: selection, identity and focus stay with the existing
+ * collection/table models. Heights are px; a row height function returning
+ * `undefined` falls back to `estimatedRowHeight`, and every input is read on
+ * each layout pass (prefix sums, binary search) so reactive values update the
+ * window without a remount.
+ *
+ * Geometry semantics match the pinned ListLayout/TableLayout contracts: `gap`
+ * is the spacing between rows (body rows and the trailing loader row), while
+ * `padding` is list padding rendered as spacer rows at both ends and carries
+ * no gap. The loader area is a reservation at the end of the row stream (after
+ * the last row's gap and before the trailing padding): it is included in
+ * `totalHeight` and in `window.padBottom`, so a caller rendering a physical
+ * loader row should place it inside that reserved span.
+ */
+import {
+ computed,
+ shallowRef,
+ toValue,
+ type ComputedRef,
+ type MaybeRefOrGetter,
+} from "vue";
+
+export type VirtualRowHeight = number | ((index: number) => number | undefined);
+
+export interface UseVirtualRowsOptions {
+ /** Number of virtualized body rows. */
+ count: MaybeRefOrGetter;
+ /** Row height in px; a function maps the row index to a variable height. */
+ rowHeight: VirtualRowHeight;
+ /** Fallback height in px for rows whose height function returns undefined. */
+ estimatedRowHeight?: number;
+ /** Loader row reservation in px at the end of the row stream. */
+ loaderHeight?: number;
+ /** Gap in px between rows (body rows and the trailing loader reservation). */
+ gap?: number;
+ /** List padding in px as spacer rows at both ends. */
+ padding?: number;
+ /** Extra rows rendered beyond the viewport. */
+ overscan?: number;
+}
+
+export interface VirtualRowWindow {
+ /** First rendered body row index. */
+ start: number;
+ /** Body row index after the last rendered row. */
+ end: number;
+ /** Spacer height in px before the first rendered row (incl. padding). */
+ padTop: number;
+ /**
+ * Spacer height in px after the last rendered row: the unrendered rows, the
+ * loader reservation and the trailing padding.
+ */
+ padBottom: number;
+}
+
+export interface UseVirtualRows {
+ window: ComputedRef;
+ /** Top offset in px of a body row within the row stream. */
+ rowOffsetOf: (index: number) => number;
+ /** Rendered extent in px of a body row (its height plus the gap after it). */
+ rowExtentOf: (index: number) => number;
+ /** Total row-stream height in px (padding, rows, gaps, loader reservation). */
+ totalHeight: ComputedRef;
+ /** Recompute the window from a scroll position. */
+ update: (scrollTop: number, viewportHeight: number) => void;
+ /** Scroll a row into a viewport element, clamped to the row stream. */
+ scrollToIndex: (element: HTMLElement, index: number) => void;
+}
+
+export function useVirtualRows(options: UseVirtualRowsOptions): UseVirtualRows {
+ const overscan = options.overscan ?? 8;
+ const state = shallowRef({ scrollTop: 0, viewport: 0 });
+ /** Prefix sums: offsets[i] = row stream top of body row i (incl. padding). */
+ const geometry = computed(() => {
+ const count = Math.max(0, toValue(options.count) ?? 0);
+ const gap = (options.gap ?? 0) > 0 ? (options.gap ?? 0) : 0;
+ const pad = (options.padding ?? 0) > 0 ? (options.padding ?? 0) : 0;
+ const loader = (options.loaderHeight ?? 0) > 0 ? (options.loaderHeight ?? 0) : 0;
+ // Rows and the loader reservation are content rows: gaps sit between
+ // them, never between padding and content.
+ const loaderSpan = loader > 0 ? (count > 0 ? gap : 0) + loader : 0;
+ const offsets = new Float64Array(count + 1);
+ let top = pad;
+ for (let i = 0; i < count; i++) {
+ offsets[i] = top;
+ const raw =
+ typeof options.rowHeight === "function"
+ ? options.rowHeight(i)
+ : options.rowHeight;
+ top += raw ?? options.estimatedRowHeight ?? 50;
+ if (i < count - 1) top += gap;
+ }
+ offsets[count] = top;
+ return { count, pad, loaderSpan, offsets };
+ });
+ const rowOffsetOf = (index: number) =>
+ geometry.value.offsets[Math.min(Math.max(index, 0), geometry.value.count)];
+ const rowExtentOf = (index: number) =>
+ rowOffsetOf(index + 1) - rowOffsetOf(index);
+ const totalHeight = computed(
+ () =>
+ geometry.value.offsets[geometry.value.count]! +
+ geometry.value.loaderSpan +
+ geometry.value.pad,
+ );
+ const window = computed(() => {
+ const { count, offsets } = geometry.value;
+ const { scrollTop, viewport } = state.value;
+ // First row whose extent reaches the viewport top.
+ let low = 0;
+ let high = count;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (offsets[mid + 1]! <= scrollTop) low = mid + 1;
+ else high = mid;
+ }
+ const start = Math.max(0, low - overscan);
+ // First row starting beyond the viewport bottom.
+ let endLow = start;
+ let endHigh = count;
+ const limit = scrollTop + viewport;
+ while (endLow < endHigh) {
+ const mid = (endLow + endHigh) >> 1;
+ if (offsets[mid]! < limit) endLow = mid + 1;
+ else endHigh = mid;
+ }
+ const end = Math.min(count, endLow + overscan);
+ return {
+ start,
+ end,
+ padTop: rowOffsetOf(start),
+ padBottom: Math.max(0, totalHeight.value - rowOffsetOf(end)),
+ };
+ });
+ function update(scrollTop: number, viewportHeight: number) {
+ state.value = { scrollTop, viewport: viewportHeight };
+ }
+ function scrollToIndex(element: HTMLElement, index: number) {
+ const top = rowOffsetOf(index);
+ const extent = rowExtentOf(index);
+ if (top < element.scrollTop) element.scrollTop = top;
+ else if (top + extent > element.scrollTop + element.clientHeight)
+ element.scrollTop = top + extent - element.clientHeight;
+ update(element.scrollTop, element.clientHeight);
+ }
+ return { window, rowOffsetOf, rowExtentOf, totalHeight, update, scrollToIndex };
+}
+
+/**
+ * Attach the window updater to a scroll container: recomputes on scroll and on
+ * container resize. Returns a cleanup callable.
+ */
+export function bindVirtualRows(
+ rows: UseVirtualRows,
+ element: HTMLElement,
+): () => void {
+ const measure = () => rows.update(element.scrollTop, element.clientHeight);
+ const observer =
+ typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
+ observer?.observe(element);
+ element.addEventListener("scroll", measure, { passive: true });
+ measure();
+ return () => {
+ element.removeEventListener("scroll", measure);
+ observer?.disconnect();
+ };
+}
diff --git a/packages/vue/src/components/list-box/ListBox.vue b/packages/vue/src/components/list-box/ListBox.vue
index cb38117..4e92eda 100644
--- a/packages/vue/src/components/list-box/ListBox.vue
+++ b/packages/vue/src/components/list-box/ListBox.vue
@@ -10,12 +10,16 @@ import {
onMounted,
provide,
ref,
+ shallowRef,
useAttrs,
+ useSlots,
+ watch,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
+import Header from "../header/HeaderRoot.vue";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
@@ -37,6 +41,10 @@ const props = withDefaults(defineProps>(), {
variant: "default",
as: "div",
rowHeight: 50,
+ headingHeight: 48,
+ loaderHeight: 48,
+ gap: 0,
+ padding: 0,
overscan: 5,
});
const owner = inject(collectionOwnerKey, undefined);
@@ -62,7 +70,9 @@ const emit = defineEmits<{
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
+ loader?: () => unknown;
}>();
+const slots = useSlots();
const attrs = useAttrs();
const instance = getCurrentInstance()!;
const modelPresence = () =>
@@ -231,6 +241,63 @@ const visibleItems = computed(() => {
return items.filter((item) => visible.has(item.id));
});
const source = computed(() => visibleItems.value);
+/**
+ * Virtualized row stream: padding spacers, optional heading rows (from the
+ * item `heading` field), the item rows themselves and an optional loader row.
+ * Row heights are px and re-read on every layout pass, so reactive heights or
+ * props update the window without a remount. `gap` is the spacing between
+ * content rows (item/heading/loader), counted into the earlier row's wrapper
+ * height to keep one geometry source; padding spacers carry no gap.
+ * `padding` renders as spacer rows at both ends.
+ */
+type VirtualRow =
+ | { key: string; kind: "pad"; height: number }
+ | { key: string; kind: "heading"; height: number; text: string }
+ | { key: string; kind: "item"; height: number; item: T; index: number }
+ | { key: string; kind: "loader"; height: number };
+const fallbackRowHeight = computed(
+ () =>
+ props.estimatedRowHeight ??
+ (typeof props.rowHeight === "number" ? props.rowHeight : 50),
+);
+const virtualRows = computed(() => {
+ const items = source.value as T[];
+ const gap = props.gap > 0 ? props.gap : 0;
+ const rows: VirtualRow[] = [];
+ const push = (row: VirtualRow) => {
+ // Gap sits between content rows only (pinned ListLayout semantics).
+ const prev = rows[rows.length - 1];
+ if (row.kind !== "pad" && prev && prev.kind !== "pad") prev.height += gap;
+ rows.push(row);
+ };
+ if (props.padding > 0)
+ push({ key: "pad-top", kind: "pad", height: props.padding });
+ items.forEach((item, index) => {
+ if (item.heading)
+ push({
+ key: `heading-${index}`,
+ kind: "heading",
+ height: props.headingHeight,
+ text: item.heading,
+ });
+ const height =
+ (typeof props.rowHeight === "function"
+ ? props.rowHeight(index)
+ : props.rowHeight) ?? fallbackRowHeight.value;
+ push({ key: `item-${item.id}`, kind: "item", height, item, index });
+ });
+ if (slots.loader)
+ push({ key: "loader", kind: "loader", height: props.loaderHeight });
+ if (props.padding > 0)
+ push({ key: "pad-bottom", kind: "pad", height: props.padding });
+ return rows;
+});
+/** Row stream index for a logical item index (headings/pads shift the row). */
+function rowIndexOfItem(index: number): number {
+ return virtualRows.value.findIndex(
+ (row) => row.kind === "item" && row.index === index,
+ );
+}
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
@@ -238,11 +305,55 @@ const {
containerProps,
wrapperProps,
scrollTo,
-} = useVirtualList(source, {
- itemHeight: () => props.rowHeight,
+} = useVirtualList(virtualRows, {
+ itemHeight: (rowIndex: number) =>
+ virtualRows.value[rowIndex]?.height ?? fallbackRowHeight.value,
overscan: props.overscan,
});
-const root = containerProps.ref;
+const root = shallowRef(null);
+/**
+ * The scroll container drives the virtual window: the list root when it
+ * scrolls itself (fixed rows inside a sized box) and the nearest scrolling
+ * ancestor otherwise (popover-wide scrolling with sticky chrome, like the
+ * pinned autocomplete example).
+ */
+function resolveScrollParent(): HTMLElement | null {
+ const el = root.value;
+ if (!el) return null;
+ const scrolls = (node: HTMLElement) => {
+ const overflowY = getComputedStyle(node).overflowY;
+ return (
+ (overflowY === "auto" || overflowY === "scroll") &&
+ node.scrollHeight > node.clientHeight + 1
+ );
+ };
+ if (scrolls(el)) return el;
+ for (let node = el.parentElement; node; node = node.parentElement)
+ if (scrolls(node)) return node;
+ return el;
+}
+let scrollParent: HTMLElement | null = null;
+function onVirtualScroll() {
+ containerProps.onScroll();
+}
+watch(
+ root,
+ (el) => {
+ scrollParent?.removeEventListener("scroll", onVirtualScroll);
+ scrollParent = null;
+ if (!el || !props.virtualized) return;
+ const parent = resolveScrollParent();
+ if (!parent) return;
+ scrollParent = parent;
+ containerProps.ref.value = parent;
+ parent.addEventListener("scroll", onVirtualScroll, { passive: true });
+ },
+ { flush: "post" },
+);
+onBeforeUnmount(() => {
+ scrollParent?.removeEventListener("scroll", onVirtualScroll);
+ scrollParent = null;
+});
let restoringFocus = false;
function restoreFocus() {
restoringFocus = true;
@@ -280,10 +391,18 @@ async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
await nextFrame();
}
}
+/** Row stream top offset in px (sum of the heights before the row). */
+function rowOffsetOf(rowIndex: number): number {
+ let top = 0;
+ for (let i = 0; i < rowIndex; i++) top += virtualRows.value[i]!.height;
+ return top;
+}
/**
* Bring a row into view without taking DOM focus. Virtualized lists move the
- * window by index; ordinary lists scroll the mounted row (the row itself may
- * sit inside any scroll container supplied by the caller).
+ * window by row offset (item rows may sit behind heading/padding rows); the
+ * scroll container may be any scrolling ancestor; ordinary lists scroll the
+ * mounted row (the row itself may sit inside any scroll container supplied by
+ * the caller).
*/
async function revealRow(key: ListBoxKey, valid: () => boolean) {
// Every side effect is guarded: filtering, closing, unmounting or a newer
@@ -292,15 +411,18 @@ async function revealRow(key: ListBoxKey, valid: () => boolean) {
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0 || !valid()) return;
- const rowTop = index * props.rowHeight;
- const element = root.value;
+ const rowIndex = rowIndexOfItem(index);
+ if (rowIndex < 0) return;
+ const row = virtualRows.value[rowIndex]!;
+ const rowTop = rowOffsetOf(rowIndex);
+ const element = scrollParent ?? root.value;
if (
element &&
(rowTop < element.scrollTop ||
- rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
+ rowTop + row.height > element.scrollTop + element.clientHeight)
) {
if (!valid()) return;
- scrollTo(index);
+ scrollTo(rowIndex);
}
await waitForMountedRow(key, valid);
return;
@@ -455,9 +577,13 @@ function keydown(event: KeyboardEvent) {
.ordered()
.find((member) => member.key() === active.value)
?.element();
+ const activeHeight =
+ (typeof props.rowHeight === "function"
+ ? props.rowHeight(index)
+ : props.rowHeight) ?? fallbackRowHeight.value;
const height = props.virtualized
- ? props.rowHeight
- : current?.getBoundingClientRect().height || props.rowHeight;
+ ? activeHeight
+ : current?.getBoundingClientRect().height || activeHeight;
const page = Math.max(
1,
Math.floor((root.value?.clientHeight ?? 0) / height),
@@ -590,7 +716,9 @@ function rootAttrs() {
throw new TypeError("Single ListBox accepts at most one selected key.");
if (
props.virtualized &&
- (!props.items || props.orientation !== "vertical" || props.rowHeight <= 0)
+ (!props.items ||
+ props.orientation !== "vertical" ||
+ (typeof props.rowHeight === "number" && props.rowHeight <= 0))
)
throw new Error(
"Virtualized ListBox requires items, vertical orientation and a positive rowHeight.",
@@ -610,6 +738,9 @@ function rootAttrs() {
dir: dir.value,
"data-slot": "list-box",
"data-hv-listbox": "",
+ // Styling hook: virtualized lists bind their row window to a scrolling
+ // ancestor and must not be forced into a self-scrolling box.
+ "data-virtualized": props.virtualized ? "" : undefined,
"data-disabled": disabled.value || undefined,
"aria-disabled": disabled.value || undefined,
"aria-readonly": readOnly.value || undefined,
@@ -645,7 +776,8 @@ function rootAttrs() {
)
void focus(active.value);
},
- onScroll: props.virtualized ? containerProps.onScroll : undefined,
+ // Virtualized scrolling is owned by the resolved scroll parent (native
+ // listener); the root itself needs no scroll handler.
});
}
defineExpose({
@@ -674,11 +806,20 @@ defineExpose({
>
-
+
+
+ {{ entry.data.text }}
+
+
+
diff --git a/packages/vue/src/components/list-box/context.ts b/packages/vue/src/components/list-box/context.ts
index c7b4159..73e678c 100644
--- a/packages/vue/src/components/list-box/context.ts
+++ b/packages/vue/src/components/list-box/context.ts
@@ -8,6 +8,12 @@ export interface ListBoxDataItem {
id: ListBoxKey;
textValue?: string;
isDisabled?: boolean;
+ /**
+ * Virtualized grouping: a heading row is rendered before this item. The
+ * heading is a display row (like the non-virtual ListBoxSection header) and
+ * never participates in selection or the `aria-posinset` item indexing.
+ */
+ heading?: string;
}
/** Shared schema: generic SFC parameter extraction can erase its prop types. */
export interface ListBoxOptions {
@@ -28,7 +34,23 @@ export interface ListBoxOptions {
as?: string;
items?: readonly T[];
virtualized?: boolean;
- rowHeight?: number;
+ /**
+ * Row height in px. A number is the fixed row height; a function maps the
+ * item index to its height (variable rows), returning `undefined` to fall
+ * back to `estimatedRowHeight`. Re-read on every layout pass, so reactive
+ * heights update the window without a remount.
+ */
+ rowHeight?: number | ((index: number) => number | undefined);
+ /** Fallback height in px for variable rows whose function returns undefined. */
+ estimatedRowHeight?: number;
+ /** Heading row height in px for virtualized `heading` rows. */
+ headingHeight?: number;
+ /** Loader row height in px for the virtualized `#loader` row. */
+ loaderHeight?: number;
+ /** Gap in px between rows (counted after every row but the last). */
+ gap?: number;
+ /** List padding in px rendered as spacer rows at both ends. */
+ padding?: number;
overscan?: number;
}
export interface ListBoxItemState {
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index e3c1fa7..21e829d 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -456,6 +456,19 @@ export { useLocale } from "./providers/context";
* component (virtualized or async sources) and wants matching semantics.
*/
export { createBaseContains } from "./components/collection/match";
+/**
+ * Row geometry for virtualized table/list windows (px units): variable row
+ * heights, loader rows, gap/padding and scroll-to-index. Pure measurement —
+ * selection, identity and focus stay with the existing collection models.
+ */
+export {
+ useVirtualRows,
+ bindVirtualRows,
+ type UseVirtualRowsOptions,
+ type UseVirtualRows,
+ type VirtualRowHeight,
+ type VirtualRowWindow,
+} from "./components/collection/virtual-rows";
export type { ConfigProviderProps } from "./types";
export { default as Modal } from "./components/modal/Modal";
diff --git a/tests/fixtures/virtual-rows.vue b/tests/fixtures/virtual-rows.vue
new file mode 100644
index 0000000..3b674db
--- /dev/null
+++ b/tests/fixtures/virtual-rows.vue
@@ -0,0 +1,244 @@
+
+
+
+
+
+
可变行高 / 分组 / 加载行 / gap / padding
+
+
+
+
+
+
+
+
+
+
+
+
+ 高度随索引变化
+
+
+
+
+
+
+
+
+
+
+
已选:{{ selected.join(",") || "无" }}
+
+
+
+
表格虚拟窗口(useVirtualRows)
+
+
+
+
+
+
+
+
+
+
+ 名称
+
+ 说明
+
+
+
+
+ {{ row.name }}
+ 行高 44/72 交替
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/package/client-checks.json b/tests/package/client-checks.json
index 272431c..626bb4a 100644
--- a/tests/package/client-checks.json
+++ b/tests/package/client-checks.json
@@ -259,6 +259,10 @@
"data-exiting"
]
},
+ "virtual-rows": {
+ "exports": ["useVirtualRows", "bindVirtualRows"],
+ "css": ["data-virtualized", "[data-slot=list-box][data-virtualized]"]
+ },
"list-box": {
"exports": [
"ListBox",
diff --git a/tests/package/virtual-rows-contract.ts b/tests/package/virtual-rows-contract.ts
new file mode 100644
index 0000000..597f1f4
--- /dev/null
+++ b/tests/package/virtual-rows-contract.ts
@@ -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,
+];
diff --git a/tests/virtual-rows.test.ts b/tests/virtual-rows.test.ts
new file mode 100644
index 0000000..850fc35
--- /dev/null
+++ b/tests/virtual-rows.test.ts
@@ -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, 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");
+ });
+});