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
@@ -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<number>;
/** 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<VirtualRowWindow>;
/** 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<number>;
/** 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<VirtualRowWindow>(() => {
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();
};
}
+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 {