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
+157 -16
View File
@@ -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<ListBoxOptions<T>>(), {
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<VirtualRow[]>(() => {
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<HTMLElement | null>(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({
>
<div
v-for="entry in windowItems"
:key="entry.data.id"
:key="entry.data.key"
role="presentation"
:style="{ height: `${rowHeight}px` }"
:style="{ height: `${entry.data.height}px` }"
>
<slot :item="entry.data" :index="entry.index" />
<div v-if="entry.data.kind === 'pad'" aria-hidden="true" />
<Header v-else-if="entry.data.kind === 'heading'">
{{ entry.data.text }}
</Header>
<slot
v-else-if="entry.data.kind === 'item'"
:item="entry.data.item"
:index="entry.data.index"
/>
<slot v-else name="loader" />
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
@@ -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<T extends ListBoxDataItem = ListBoxDataItem> {
@@ -28,7 +34,23 @@ export interface ListBoxOptions<T extends ListBoxDataItem = ListBoxDataItem> {
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 {