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
+28 -5
View File
@@ -77,10 +77,27 @@ import {
ListBox 通过 `virtualized` 仅渲染视口附近的行,高效展示大数据集。下面保留基线的 1000 条数据、50px 固定行高和 400px 视口。完整数据传给 `items`,首字母导航、全选和范围选择使用完整集合。
Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`。当前支持竖向固定行高列表;可变行高、虚拟分组标题和拖放布局尚未支持。
Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`;布局参数在 ListBox 上直接提供(见下文 ListLayout 映射)。支持竖向固定与可变行高、数据驱动的虚拟分组标题(`items` 项的 `heading` 字段)、`#loader` 加载行以及 `gap` / `padding` 行流布局。拖放布局(放置指示线)在 Vue 侧没有对应实现,`dropIndicatorThickness` 不提供(见 ListLayout 映射记录)。滚动容器自动探测:列表自身可滚时绑定自身,否则绑定最近的滚动祖先(例如弹层整体滚动并配 sticky 搜索框的 Autocomplete)。
<ComponentPreview name="list-box-virtualization" />
#### ListLayout 映射
不导出 React Aria 的 `ListLayout` 实例;等价布局参数直接在 ListBox 上提供,单位均为 px、默认值与固定源布局契约一致(rowHeight 48、headingHeight 48、loaderHeight 48、gap 0、padding 0;Vue 侧 `rowHeight` 的数据模式默认值为 50,与基线示例一致)。上游三个虚拟化示例的显式值(Table 42、ListBox/Autocomplete 50)是示例传值而非布局默认值,示例保持原值不机械统一。
| ListLayout 参数 | Vue 对应 | 更新语义 |
| --- | --- | --- |
| `rowHeight` | `rowHeight`(number 或 `(index) => number \| undefined`) | 每次布局重读;响应式高度变化无需重挂载。 |
| `estimatedRowHeight` | `estimatedRowHeight` | 函数行高返回 `undefined` 时的回退;无默认,回退到 `rowHeight` 数值(数据模式 50)。 |
| `headingHeight` | `headingHeight` | 虚拟 `heading` 行计高;非虚拟模式的分组仍用 `ListBoxSection`,语义与渲染结构不同。 |
| `estimatedHeadingHeight` | 不提供 | Vue 侧标题行高固定(`headingHeight`),没有可变标题测量路径;如实记录为差异。 |
| `loaderHeight` | `loaderHeight` + `#loader` 插槽 | `#loader` 存在时渲染为行流末尾的内容行。 |
| `dropIndicatorThickness` | 不提供 | Vue 侧 ListBox/Table 没有拖放实现,无放置指示线可度量;不补空参数冒充能力。 |
| `gap` | `gap` | 内容行之间的间距,计入较早一行的行占位;padding 行不计。 |
| `padding` | `padding` | 行流两端的占位行,不计 gap。 |
虚拟分组标题是数据驱动的(`items` 项的 `heading` 字段);动态过滤与异步追加后,条目按逻辑 `id` 保持身份、选择与键盘导航,`aria-posinset` / `aria-setsize` 始终相对完整可见集合计算,窗口外未挂载的行不丢失身份。
### 自定义勾选图标
<ComponentPreview name="list-box-custom-check-icon" />
@@ -163,10 +180,15 @@ Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状
| `loop` | `boolean` | `false` | 方向键到边界后循环。 |
| `variant` | `"default" \| "danger"` | `"default"` | 视觉变体。 |
| `as` | `string` | `"div"` | 根原生标签。 |
| `items` | `readonly T[]`,`T extends ListBoxDataItem` | — | 数据集合,具备唯一的 `id`;作用域插槽接收 `item` 和 `index`。 |
| `virtualized` | `boolean` | `false` | 开启竖向固定行高虚拟列表,必须提供 `items`。 |
| `rowHeight` | `number` | `50` | 每行高度(px),必须为正数。 |
| `overscan` | `number` | `5` | 视口外额外渲染的行数,初始化时确定。 |
| `items` | `readonly T[]`,`T extends ListBoxDataItem` | — | 数据集合,具备唯一的 `id`;作用域插槽接收 `item` 和 `index`。虚拟模式下可选 `heading` 字段在其行前渲染分组标题行(仅 `headingHeight` 计高,不参与选择与 `aria-posinset` 索引)。 |
| `virtualized` | `boolean` | `false` | 开启竖向虚拟列表,必须提供 `items`。 |
| `rowHeight` | `number \| (index: number) => number \| undefined` | `50` | 每行高度(px)。函数映射行索引到可变行高,返回 `undefined` 回退 `estimatedRowHeight`。每次布局重读,响应式高度无需重挂载。 |
| `estimatedRowHeight` | `number` | `rowHeight` 数值或 `50` | 可变行高函数返回 `undefined` 时的回退高度(px)。 |
| `headingHeight` | `number` | `48` | 虚拟分组标题行高度(px)。 |
| `loaderHeight` | `number` | `48` | `#loader` 加载行高度(px)。 |
| `gap` | `number` | `0` | 内容行(条目/标题/加载行)之间的间距(px);padding 行不计 gap。 |
| `padding` | `number` | `0` | 列表内边距(px),渲染为行流两端的占位行。 |
| `overscan` | `number` | `5` | 视口外额外渲染的行数,初始化时确定。 |
| `aria-label` / `aria-labelledby` | `string` | — | 根列表框的可访问名称。 |
| `class` / `style` / DOM 事件 | Vue 原生属性 | — | 透传到根 role=listbox 节点,类增量合并。 |
@@ -182,6 +204,7 @@ Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状
| --------------- | ------------------------------------- | -------------------------------------------- |
| 默认插槽 | 数据模式 `{ item: T, index: number }` | 静态部件模式直接放置 Item / Section。 |
| `empty` | 无 | items 为空时的内容。 |
| `loader` | 无 | 虚拟行流末尾的加载行(如「加载更多」),按 `loaderHeight` 计高。 |
| `focus(key?)` | `ListBoxKey?` | 聚焦根或指定可用项;虚拟项先滚动到可见范围。 |
| `selectAll()` | 无 | 多选模式下提出全选,跳过禁用项。 |
| `element` | `HTMLElement` | 根元素引用。 |
+14 -2
View File
@@ -96,7 +96,7 @@ import {
### 虚拟滚动
仅渲染视口内可见行,从而高效展示大数据集。本库使用固定行高窗口替代 React Aria `Virtualizer`。
仅渲染视口内可见行,从而高效展示大数据集。本库以 `useVirtualRows` 行几何组合式替代 React Aria `Virtualizer`,支持固定与可变行高、`gap` / `padding` 与加载行预留(见下文 TableLayout 映射)。示例保留基线的 42px 显式行高、300px 视口与外层滚动容器:原生 `<table>` 不能作为滚动容器(`height` 是最小高度且 `overflow` 需要确定高度,实测 300px 被内容撑到 45036px),而固定源滚动的是虚拟网格元素;列宽用 `minWidth`(fr 语义由 TableContent 列布局承担),长文本按列宽截断。
<ComponentPreview name="table-virtualization" minHeight="380px" />
@@ -332,7 +332,19 @@ Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制
### TableLayout 与 Vue 虚拟滚动
未导出 React Aria TableLayout 类。示例使用固定 42px 行高、300px 滚动视口和 overscan 窗口(对齐上游 `layoutOptions.rowHeight/headingHeight = 42`),按完整 rowKeys 处理键盘请求;aria-rowcount 包括表头,aria-rowindex 为逻辑位置。仅当前窗口挂载。可变高度、拖放指标与 RAC 虚拟布局扩展暂不支持,不能把固定行高示例用于多行自动换高的数据。TanStack 示例使用可选 table-core 数据模型(含 `getPaginationRowModel`),库运行时不依赖它。
未导出 React Aria TableLayout 类;行几何由公共组合式 `useVirtualRows` / `bindVirtualRows` 提供(纯测量,无状态内核:选择、身份与焦点仍归集合/表格模型)。示例使用固定 42px 行高、300px 滚动视口和 overscan 窗口(对齐上游 `layoutOptions.rowHeight/headingHeight = 42`;42 是示例显式值,布局默认 48),按完整 rowKeys 处理键盘请求;aria-rowcount 包括表头,aria-rowindex 为逻辑位置。仅当前窗口挂载。TanStack 示例使用可选 table-core 数据模型(含 `getPaginationRowModel`),库运行时不依赖它。
| `useVirtualRows` 选项 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| `count` | `MaybeRefOrGetter<number>` | — | 表体行数;getter 响应式更新行流。 |
| `rowHeight` | `number \| (index: number) => number \| undefined` | — | 行高(px);函数映射行索引到可变行高,返回 `undefined` 回退 `estimatedRowHeight`。每次布局重读。 |
| `estimatedRowHeight` | `number` | `50` | 可变行高回退(px)。 |
| `loaderHeight` | `number` | `0` | 行流末尾的加载行预留(px),在最后一行的 gap 之后、尾部 padding 之前;计入 `totalHeight` 与 `window.padBottom`。 |
| `gap` | `number` | `0` | 行之间的间距(px),计入较早一行的 `rowExtentOf`;padding 不计 gap。 |
| `padding` | `number` | `0` | 列表内边距(px),计入行流两端(`padTop` 含头部、`padBottom` 含尾部)。 |
| `overscan` | `number` | `8` | 视口外额外渲染的行数。 |
`window` 提供 `start` / `end` / `padTop` / `padBottom`(渲染 `<tr>` 占位的 spacer 高度,padTop + 已渲染行 + padBottom 恒等于 `totalHeight`),`scrollToIndex` 按行偏移滚动并夹在行流内,`bindVirtualRows` 把窗口更新绑定到滚动容器(滚动与容器缩放)。TableLayout 的 `headingHeight` / `estimatedHeadingHeight` 不提供:Vue 表格没有分区表头模型,如实记录为差异;`dropIndicatorThickness` 同 ListBox——Vue 侧无拖放实现,不提供空参数。
## 无障碍
@@ -156,12 +156,10 @@ const keepResults = () => true;
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
<ListBox
:items="filteredUsers"
class="max-h-[320px] overflow-y-auto"
:row-height="50"
virtualized
>
<!-- The popover scrolls as a whole (pinned layout): the virtual
window binds to that scrolling ancestor, keeping the search
field sticky at its top. -->
<ListBox :items="filteredUsers" :row-height="50" virtualized>
<template #default="{ item }">
<ListBoxItem :id="item.id" :text-value="item.name" class="h-full">
<div class="flex flex-col">
+77 -79
View File
@@ -9,6 +9,8 @@ import {
TableHeader,
TableRow,
TableScrollContainer,
bindVirtualRows,
useVirtualRows,
} from "@heroui-vue/components";
interface User {
@@ -95,96 +97,92 @@ const users = generateUsers(1000);
// Matches the fixed upstream Virtualizer layoutOptions (rowHeight/headingHeight 42).
const ITEM_HEIGHT = 42;
const rowKeys = users.map((user) => user.id);
const VIEWPORT = 300;
const OVERSCAN = 8;
const scrollTop = ref(0);
const scrollEl = ref<HTMLElement | null>(null);
const startIndex = computed(() =>
Math.max(0, Math.floor(scrollTop.value / ITEM_HEIGHT) - OVERSCAN),
const rows = useVirtualRows({
count: () => users.length,
rowHeight: ITEM_HEIGHT,
overscan: 8,
});
const rowWindow = rows.window;
const scrollRef = ref<HTMLElement | null>(null);
const visible = computed(() =>
users.slice(rowWindow.value.start, rowWindow.value.end),
);
const endIndex = computed(() =>
Math.min(
users.length,
Math.ceil((scrollTop.value + VIEWPORT) / ITEM_HEIGHT) + OVERSCAN,
),
);
const visible = computed(() => users.slice(startIndex.value, endIndex.value));
const padTop = computed(() => startIndex.value * ITEM_HEIGHT);
const padBottom = computed(() => (users.length - endIndex.value) * ITEM_HEIGHT);
// The scrolling container is the viewport wrapper: a native table cannot be
// one (its height is a minimum and overflow needs a definite height — the
// pinned source scrolls its virtual grid, a non-table element).
const scrollElement = () => scrollRef.value ?? null;
function focusRow(_key: string | number, index: number) {
const node = scrollEl.value;
if (!node) return;
const top = index * ITEM_HEIGHT;
if (top < node.scrollTop) node.scrollTop = top;
else if (top + ITEM_HEIGHT > node.scrollTop + VIEWPORT)
node.scrollTop = top + ITEM_HEIGHT - VIEWPORT;
scrollTop.value = node.scrollTop;
}
function onScroll(event: Event) {
scrollTop.value = (event.target as HTMLElement).scrollTop;
const element = scrollElement();
if (element) rows.scrollToIndex(element, index);
}
let detach: (() => void) | undefined;
onMounted(() => {
scrollEl.value?.addEventListener("scroll", onScroll, { passive: true });
});
onUnmounted(() => {
scrollEl.value?.removeEventListener("scroll", onScroll);
const element = scrollElement();
if (element) detach = bindVirtualRows(rows, element);
});
onUnmounted(() => detach?.());
</script>
<template>
<Table>
<div
ref="scrollEl"
class="h-[300px] w-full overflow-auto"
data-slot="table-virtual-viewport"
>
<TableContent
aria-label="1000 行虚拟化表格"
class="min-w-[700px] table-fixed"
:row-keys="rowKeys"
:aria-rowcount="users.length + 1"
@focus-row="focusRow"
<TableScrollContainer>
<div
ref="scrollRef"
class="h-[300px] w-full overflow-auto"
data-slot="table-virtual-viewport"
>
<TableHeader aria-rowindex="1" class="h-full w-full">
<TableColumn id="name" is-row-header :min-width="160">
姓名
</TableColumn>
<TableColumn id="role" :min-width="220">角色</TableColumn>
<TableColumn id="email" :min-width="240">邮箱</TableColumn>
</TableHeader>
<TableBody>
<tr aria-hidden="true" :style="{ height: padTop + 'px' }" />
<TableRow
v-for="user in visible"
:key="user.id"
:row-key="user.id"
:aria-rowindex="user.id + 1"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
<TableContent
aria-label="1000 行虚拟化表格"
class="min-w-[700px] table-fixed"
:row-keys="rowKeys"
:aria-rowcount="users.length + 1"
@focus-row="focusRow"
>
<TableHeader aria-rowindex="1" class="h-full w-full">
<TableColumn id="name" is-row-header :min-width="160">
姓名
</TableColumn>
<TableColumn id="role" :min-width="220">角色</TableColumn>
<TableColumn id="email" :min-width="240">邮箱</TableColumn>
</TableHeader>
<TableBody>
<tr
aria-hidden="true"
:style="{ height: rowWindow.padTop + 'px' }"
/>
<TableRow
v-for="user in visible"
:key="user.id"
:row-key="user.id"
:aria-rowindex="user.id + 1"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.name }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.role }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.email }}
</TableCell>
</TableRow>
<tr aria-hidden="true" :style="{ height: padBottom + 'px' }" />
</TableBody>
</TableContent>
</div>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.name }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.role }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
{{ user.email }}
</TableCell>
</TableRow>
<tr
aria-hidden="true"
:style="{ height: rowWindow.padBottom + 'px' }"
/>
</TableBody>
</TableContent>
</div>
</TableScrollContainer>
</Table>
</template>
+7
View File
@@ -31,6 +31,13 @@ const labs = [
() => import("../../../tests/fixtures/collections-rtl.vue"),
),
},
{
key: "virtual-rows",
title: "虚拟行布局(变高/分组/加载行)",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/virtual-rows.vue"),
),
},
{
key: "button-group-dropdown",
title: "按钮组与下拉根属性",
+7 -3
View File
@@ -72,7 +72,7 @@
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 |
| input-otp | 验证中(M32) | Root/Group/Slot/Separator + 3 正则常量;Reka PinInput 底座;字符串+索引数组;reset/Fieldset/Form/ARIA/mask 已接入;11/11 例;自动填充/IME/读屏未真机验证 |
| alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default |
| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项固定行高虚拟化;差异见 LISTBOX-01 |
| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项虚拟化(固定/可变行高、数据驱动分组标题、#loader 加载行、gap/padding、滚动父级探测);拖放布局未支持故无 dropIndicatorThickness;差异见 LISTBOX-01 与 HD-09 |
| list-box-item | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| list-box-section | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| dropdown | 验证中(B01) | Root/Trigger/Popover/Menu/Section/Item/ItemIndicator/SubmenuIndicator/SubmenuTrigger;17/17 基线例;Reka DropdownMenu;数组选择模型 |
@@ -85,7 +85,7 @@
| select | 验证中(SELECT-01) | 六部件、19/19 例、单/多选、清空、字段/原生提交/SSR/异步;复用 ListBox + Popover,重点浏览器已验,限制见 SELECT-01 |
| meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress |
| slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 |
| table | 验证中(M36 + 保真返修) | 15 部件;选择/排序/原生语义;13 演示;TableBody `#empty` 空状态;全选半选;defaultWidth 的 1fr 按原生 auto 弹性适配,不承诺 fr 比例;虚拟化固定 42px 窗口、TanStack 分页行模型;RAC TableLayout 不导出,见 M36 |
| table | 验证中(M36 + 保真返修) | 15 部件;选择/排序/原生语义;13 演示;TableBody `#empty` 空状态;全选半选;defaultWidth 的 1fr 按原生 auto 弹性适配,不承诺 fr 比例;虚拟化 42px 示例窗口经 useVirtualRows 支持可变行高/估算回退/gap/padding/加载行预留;headingHeight(分区表头)与 dropIndicatorThickness(拖放)不提供;TanStack 分页行模型;RAC TableLayout 不导出,见 M36 与 HD-09 |
| calendar | 已迁移(有已知差异) | 月/周/日、多选、焦点/翻页、国际历法、年份层与 19 预览;局部日期视图/键盘适配,默认历法边界等差异见 DATE-03。 |
| range-calendar | 已迁移(客户端,有已知差异) | RangeCalendar/Root、九个具名日历部件、共享六个 CalendarYearPicker 部件;20/20 基线例;点击/键盘/鼠标拖选、受控拒绝、跨月/RTL;触屏长按拖选未实现,见 RANGE-CALENDAR 结果。 |
| calendar-year-picker | 已迁移(DATE-03) | 六个独立具名部件、三列年份、窗口/格式/era、覆盖测量、焦点与关闭;不导出 React 上下文。 |
@@ -207,7 +207,7 @@ React render 自定义根类型不支持;原生 attrs/具名部件/作用域
## M35–M36 Toast / Table 接手收尾(2026-10-24)
Toast 11/11 与 Table 13/13 预览、各部件 Props、文档和默认源样式已接入。队列隔离/测量/焦点/SSR 与表格导航/范围/逻辑行/响应式列宽已补齐,详见 [最终验收](component-notes.md)。Table 虚拟化为固定行高窗口,不导出 RAC TableLayout,不声称可变行高/拖放/完整 RAC API。读屏、真机、Nuxt 和自动逐像素未验。
Toast 11/11 与 Table 13/13 预览、各部件 Props、文档和默认源样式已接入。队列隔离/测量/焦点/SSR 与表格导航/范围/逻辑行/响应式列宽已补齐,详见 [最终验收](component-notes.md)。Table 虚拟化经 useVirtualRows 支持可变行高与布局参数(不导出 RAC TableLayout 实例),拖放与分区表头布局不支持,不声称完整 RAC API。读屏、真机、Nuxt 和自动逐像素未验。
## DOCS-01 文档架构(2026-10-24)
@@ -310,3 +310,7 @@ TableBody 空状态默认跨全部实际叶子列(含选择列与包装渲染
## HD-10 异步加载、过滤与触发器语义(2026-10-29)
ComboBox 异步例补滚动到底自动增量加载(IntersectionObserver 哨兵 + 续载链,等价固定源 ListBoxLoadMoreItem 的集合变更重挂载语义),保留取消旧请求(AbortController)与过期响应保护(单调序号令牌);查询切换不混入旧数据;失败进入错误态并可重试(本地数据源以「模拟加载失败」开关注入失败)。本地数据源与固定源 SWAPI 的差异(12 条本地角色/模拟 300ms 延迟/可注入失败)已在示例注释与 combo-box.md 说明。Select 异步例的 IntersectionObserver 未重复实现,真实网络滚动触发经浏览器验证(20→180 条无重复)。Autocomplete 虚拟化例与默认过滤共用 `createBaseContains`(Intl.Collator base 敏感,大小写与变音折叠,cafe 匹配 Café);该匹配器从包根公开,与默认谓词同一实现。Autocomplete 触发器语义经真实浏览器核实:role=button/tabindex=0 为单一 Tab 停靠点(clear button tabindex=-1)、Tab 离开组合、Enter/Space 打开、Escape 关闭并回焦、Delete/Backspace 清除、组合输入(isComposing/229)不触发;插槽数据补齐组合能力——`AutocompleteValue` 提供 `selectedItem` 与携带源数据 `item` 的 `selectedItems`,`ComboBox` 根插槽补 `selectedItem`(均取自根 `items`,集合自发现项为 undefined),不执行未知组件 setup/render、不复制子组件。Dropdown 子菜单 hover 延迟对齐固定源 `useSubmenuTrigger` 契约:新增 `delay`(默认 200ms),底层 Reka 的固定 100ms 悬停计时经受控 open 门重定为该延迟,键盘展开立即生效并取消挂起悬停、指针离开取消;RTL 定位由 Reka 按方向固定(贴父项向右、RTL 向左),真实浏览器 RTL/LTR 几何与延迟实测见 [任务结果](tasks/results/HD-10-COLLECTIONS.md)。Button/Avatar 触发器布局补偿保留(浏览器证据:补偿规则胜出,inline-flex 经 flex 子项块化显示为 flex,非基线 inline-block)。
## HD-09 虚拟布局能力(2026-10-29)
虚拟行高布局对齐固定源 ListLayout/TableLayout 契约(rowHeight 48、headingHeight 48、loaderHeight 48、dropIndicatorThickness 2、gap 0、padding 0;42/50 为上游示例显式值而非布局默认,示例保持原值)。ListBox 补可变行高(`rowHeight` 函数式 + `estimatedRowHeight` 回退)、数据驱动分组标题(`items` 项 `heading` 字段,按 `headingHeight` 计高,不参与选择与 `aria-posinset`)、`#loader` 加载行与 `gap`/`padding` 行流(gap 仅内容行之间、padding 为两端占位);滚动父级自动探测(自身可滚绑定自身,否则最近滚动祖先)支撑 Autocomplete 弹层整体滚动 + sticky 搜索框(`[data-slot="list-box"][data-virtualized]` 排除历史 320px 自滚规则,filter 按 `max-h-[min(400px,70vh)]` 滚动,近似上游可用空间钳制)。Table 侧公共 `useVirtualRows`/`bindVirtualRows`(纯几何,前缀和+二分)支持可变行高、估算回退、gap/padding 与加载行预留(计入 `totalHeight`/`padBottom`);`headingHeight`/`estimatedHeadingHeight` 无分区表头模型不提供,`dropIndicatorThickness` 因拖放零实现不补空参数。原生 `<table>` 不能当滚动容器(高度为最小值、实测撑到 45036px),表格示例外层滚动 div 是结构差异的如实适配。动态过滤、异步追加与跨窗口键盘后逻辑身份/选择/`aria-posinset`(相对完整集合)保持;真实浏览器几何与滚动定位见 [任务结果](tasks/results/HD-09-VIRTUALIZATION.md)。
+5 -1
View File
@@ -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 零拖放实现,不提供。
+15 -1
View File
@@ -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;
}
@@ -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 {
+13
View File
@@ -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";
+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");
});
});