fix(virtualization): measure natural rows and align viewport geometry

This commit is contained in:
maoyingjie
2026-10-29 17:13:12 +08:00
parent 9f7eb1fa8d
commit 5a00e25a25
18 changed files with 770 additions and 257 deletions
+15 -7
View File
@@ -77,20 +77,20 @@ import {
ListBox 通过 `virtualized` 仅渲染视口附近的行,高效展示大数据集。下面保留基线的 1000 条数据、50px 固定行高和 400px 视口。完整数据传给 `items`,首字母导航、全选和范围选择使用完整集合。
Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`;布局参数在 ListBox 上直接提供(见下文 ListLayout 映射)。支持竖向固定与可变行高、数据驱动的虚拟分组标题(`items` 项的 `heading` 字段)、`#loader` 加载行以及 `gap` / `padding` 行流布局。拖放布局(放置指示线)在 Vue 侧没有对应实现,`dropIndicatorThickness` 不提供(见 ListLayout 映射记录)。滚动容器自动探测:列表自身可滚时绑定自身,否则绑定最近的滚动祖先(例如弹层整体滚动并配 sticky 搜索框的 Autocomplete)。
Vue 使用与 Table 共用的虚拟行几何与 ResizeObserver 测量适配,不导出 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)是示例传值而非布局默认值,示例保持原值不机械统一。
不导出 React Aria 的 `ListLayout` 实例;等价布局参数直接在 ListBox 上提供,单位均为 px。固定源布局默认 rowHeight 48、headingHeight 48、loaderHeight 48、gap 0、padding 0;Vue ListBox 沿用数据模式 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`),没有可变标题测量路径;如实记录为差异。 |
| `estimatedRowHeight` | `estimatedRowHeight` | 函数行高返回 `undefined` 时先估算(数据模式默认 50),挂载后按自然内容测量并修正。 |
| `headingHeight` | `headingHeight`(number 或函数) | 按条目索引指定标题高度;返回 `undefined` 开启自然测量。非虚拟分组仍用 `ListBoxSection`。 |
| `estimatedHeadingHeight` | `estimatedHeadingHeight` | `headingHeight` 函数返回 `undefined` 时使用的初始估算(默认 48);随后测量真实标题。 |
| `loaderHeight` | `loaderHeight` + `#loader` 插槽 | `#loader` 存在时渲染为行流末尾的内容行。 |
| `dropIndicatorThickness` | 不提供 | Vue 侧 ListBox/Table 没有拖放实现,无放置指示线可度量;不补空参数冒充能力。 |
| `gap` | `gap` | 内容行之间的间距,计入较早一行的行占位;padding 行不计。 |
@@ -182,9 +182,10 @@ Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状
| `as` | `string` | `"div"` | 根原生标签。 |
| `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`。每次布局重读,响应式高度无需重挂载。 |
| `rowHeight` | `number \| (index: number) => number \| undefined` | `50` | 每行高度(px)。函数映射行索引到可变行高,返回 `undefined` 时先估算再按自然内容测量;响应式高度无需重挂载。 |
| `estimatedRowHeight` | `number` | `rowHeight` 数值或 `50` | 可变行高函数返回 `undefined` 时的回退高度(px)。 |
| `headingHeight` | `number` | `48` | 虚拟分组标题行高度(px)。 |
| `headingHeight` | `number \| (index: number) => number \| undefined` | `48` | 虚拟分组标题行高度(px)。 |
| `estimatedHeadingHeight` | `number` | `48` | 未知标题挂载前的估算(px),自然测量后修正。 |
| `loaderHeight` | `number` | `48` | `#loader` 加载行高度(px)。 |
| `gap` | `number` | `0` | 内容行(条目/标题/加载行)之间的间距(px);padding 行不计 gap。 |
| `padding` | `number` | `0` | 列表内边距(px),渲染为行流两端的占位行。 |
@@ -261,3 +262,10 @@ node SSR 输出选中状态、名称和描述;虚拟列表首屏为滚动容
## 相关组件
[Select 选择器](./select) · [ComboBox 组合框](./combo-box) · [Avatar 头像](./avatar)
### 未知高度与滚动容器
`row-height` 或 `heading-height` 函数返回 `undefined` 时,先按对应 estimated 高度建立窗口,挂载后使用 ResizeObserver 测量自然内容。显式数字高度由调用方保证适合内容;不要同时给未知高度条目强制固定 CSS 高度。`gap` 是内容行之间的空白,不计入条目自己的内容高度;标题、条目和加载行均参与行流,padding 在两端。
测量缓存按保留类型的逻辑 key 存储,数字 `0` 与字符串 `"0"` 不会串用。容器宽度改变后重测可见内容、失效窗口外的旧宽度缓存;测量修正会保持当前滚动锚点。父滚动容器在空集合时也按 overflow 配置绑定,异步追加不需要重挂载;支持列表自滚与 Autocomplete sticky 搜索框的整体滚动。PageUp/PageDown 使用可见视口和实际行偏移计算目标。`overscan` 可响应式更新。
+21 -3
View File
@@ -251,6 +251,7 @@ Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制
| --------------- | ---------- | ------- | ------------------------------ |
| `as` | `string` | `'tr'` | 行标签 |
| `rowKey` | `TableKey` | 必填 | 稳定逻辑 key;代替 React 的 id |
| `height` | `number` | — | 精确虚拟行高(px);省略保留自然高度,未知行使用 measureRow 测量。 |
| `isDisabled` | `boolean` | `false` | 行禁用,不抢子控件事件 |
| `level` | `number` | — | 树形行层级,从 1 开始 |
| `hasChildItems` | `boolean` | `false` | 是否有树子项 |
@@ -332,19 +333,19 @@ Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制
### TableLayout 与 Vue 虚拟滚动
未导出 React Aria TableLayout 类;行几何由公共组合式 `useVirtualRows` / `bindVirtualRows` 提供(纯测量,无状态内核:选择、身份与焦点仍归集合/表格模型)。示例使用固定 42px 行高、300px 滚动视口和 overscan 窗口(对齐上游 `layoutOptions.rowHeight/headingHeight = 42`;42 是示例显式值,布局默认 48),按完整 rowKeys 处理键盘请求;aria-rowcount 包括表头,aria-rowindex 为逻辑位置。仅当前窗口挂载。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)。 |
| `estimatedRowHeight` | `number \| (index: number) => number` | `48` | 未知行挂载前的估算高度(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 侧无拖放实现,不提供空参数。
`window` 提供 `start` / `end` / `padTop` / `padBottom`(渲染 `<tr>` 占位的 spacer 高度,padTop + 已渲染行占位(含 gap)+ padBottom 恒等于 `totalHeight`),`scrollToIndex` 按行偏移滚动并夹在行流内,`bindVirtualRows` 把窗口更新绑定到滚动容器(滚动与容器缩放)。TableHeader 始终挂载,表头高度通过实际 DOM 行流起点测量,不增加一个脱离真实表头的估算参数;可用 TableHeader 的 style 设置高度(本例 42px)。`dropIndicatorThickness` 同 ListBox——Vue 侧无拖放实现,不提供空参数。
## 无障碍
@@ -353,3 +354,20 @@ Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制
## 相关组件
[Pagination 分页](./pagination) · [Checkbox 复选框](./checkbox) · [Chip 标签](./chip)
### 自然测量与精确行高
`useVirtualRows` 只管理布局几何,选择与键盘身份仍由 TableContent 的完整 `rowKeys` 管理。新增能力:
| API | 说明 |
| --- | --- |
| `keys?: MaybeRefOrGetter<readonly (string \| number)[]>` | 与行索引对应的稳定身份,保留数字/字符串类型;缺省按索引缓存。 |
| `measureRow(index, element)` | 绑定自然高度行的 DOM/组件 ref。rowHeight 函数返回 undefined 时,先估算,再观察真实行高。 |
| `resetMeasurements()` | 调用方批量替换窗口外内容后,主动失效旧尺寸缓存。 |
| `bindVirtualRows(rows, viewport, { content?, scrollPaddingStart? })` | content 是行流原点,表格默认识别真实 tbody;sticky 遮挡高度可传数字或 getter。绑定负责 scroll、resize 和清理。 |
| `TableRow.height?: number` | 显式虚拟行高度(px)。内部保留原生 th/td,并用内容盒承接 padding,避免 42px 行被原生单元格最小内容撑成 45px;省略时保留原有自然布局。 |
未知高度行使用 `:ref="el => rows.measureRow(index, el)"`,并省略 `TableRow.height`;已知高度行传 `:height="height"`。已知行高不应小于需要展示的内容。`gap` 属于行间距:Table 消费方可用不参与导航的 presentation spacer 行渲染;加载行在行流尾部预留中渲染,不要重复叠加高度。示例保留原生滚动 div,移除额外 table-fixed/ellipsis 限制,42px 的模型与实际行高一致。
滚动定位会计入 tbody/表头原点及 sticky 遮挡;未知目标挂载测量后会进一步校准。宽度变化会重测自然行并失效窗口外旧尺寸;测量修正保持滚动锚点。使用组合式函数时应处于 Vue setup/effectScope 中,以随组件清理测量观察器。
+10 -16
View File
@@ -118,7 +118,10 @@ function focusRow(_key: string | number, index: number) {
let detach: (() => void) | undefined;
onMounted(() => {
const element = scrollElement();
if (element) detach = bindVirtualRows(rows, element);
if (element)
detach = bindVirtualRows(rows, element, {
content: element.querySelector("tbody") ?? undefined,
});
});
onUnmounted(() => detach?.());
</script>
@@ -133,12 +136,12 @@ onUnmounted(() => detach?.());
>
<TableContent
aria-label="1000 行虚拟化表格"
class="min-w-[700px] table-fixed"
class="min-w-[700px]"
:row-keys="rowKeys"
:aria-rowcount="users.length + 1"
@focus-row="focusRow"
>
<TableHeader aria-rowindex="1" class="h-full w-full">
<TableHeader aria-rowindex="1" style="height: 42px" class="w-full">
<TableColumn id="name" is-row-header :min-width="160">
姓名
</TableColumn>
@@ -155,24 +158,15 @@ onUnmounted(() => detach?.());
:key="user.id"
:row-key="user.id"
:aria-rowindex="user.id + 1"
:style="{ height: ITEM_HEIGHT + 'px' }"
:height="ITEM_HEIGHT"
>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
<TableCell>
{{ user.name }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
<TableCell>
{{ user.role }}
</TableCell>
<TableCell
class="whitespace-nowrap overflow-hidden text-ellipsis"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
<TableCell>
{{ user.email }}
</TableCell>
</TableRow>
+5 -2
View File
@@ -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 示例窗口经 useVirtualRows 支持可变行高/估算回退/gap/padding/加载行预留;headingHeight(分区表头)与 dropIndicatorThickness(拖放)不提供;TanStack 分页行模型;RAC TableLayout 不导出,见 M36 与 HD-09 |
| table | 验证中(M36 + 保真返修) | 15 部件;选择/排序/原生语义;13 演示;TableBody `#empty` 空状态;全选半选;defaultWidth 的 1fr 按原生 auto 弹性适配,不承诺 fr 比例;虚拟化 42px 示例窗口经 useVirtualRows 支持可变行高/估算回退/gap/padding/加载行预留;表头按真实 tbody 原点测量;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 上下文。 |
@@ -313,4 +313,7 @@ ComboBox 异步例补滚动到底自动增量加载(IntersectionObserver 哨
## 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)。
固定源 ListLayout/TableLayout 的布局默认与示例显式传值分别记录:布局行高48,示例Table42、ListBox/Autocomplete50;Vue ListBox沿用数据模式默认50,Table估算缺省48。ListBox支持函数式rowHeight/headingHeight、对应estimated高度、类型保真的实测缓存、分组标题/loader/gap/padding;与Table共用useVirtualRows窗口与测量。父滚动绑定支持空→长集合和sticky遮挡,选择与焦点仍归既有集合模型。TableRow.height提供精确原生行几何,表头始终挂载并按真实tbody原点测量;未知行绑定measureRow后自然测量,容器变宽/变窄重测,测量修正保留锚点。正式表格示例42px模型/DOM一致,保留外层原生滚动div,移除额外table-fixed/ellipsis。无拖放实现,不提供空dropIndicatorThickness。Autocomplete整体滚动高度max-h-[min(400px,70vh)]仍是上游可用空间钳制的近似差异。最终证据见[任务结果](tasks/results/HD-09-VIRTUALIZATION.md)。
HD09-R1:ListBox 与 Table 共用 useVirtualRows 的自然测量、类型保真尺寸缓存、前缀和窗口及滚动锚定。ListBox 补 estimatedHeadingHeight/函数式 headingHeight;父滚动容器支持空→长集合和 sticky 遮挡。TableRow.height 是 Vue 的精确几何适配,保留原生行头,TableHeader 常驻并按真实 tbody 起点测量;不再将表头误称为未实现的分区布局。正式表格示例 42px 模型/DOM 一致,移除多余截断和固定列布局。以任务结果最终验收节覆盖原实施记录中的估算回退和45px边框裁决。
+7 -5
View File
@@ -1,5 +1,5 @@
<!-- task-metadata
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"needs-revision","requires":["docs/tasks/HD-QUEUE.md"],"sources":["apps/docs/src/demos/cn/table/virtualization.tsx"],"checks":["pnpm exec vitest run tests/collection-filter-virtual.test.ts tests/table.test.ts tests/collection-state.test.ts","pnpm exec vitest run tests/virtual-rows.test.ts","pnpm typecheck"]}
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"implemented","requires":["docs/tasks/HD-QUEUE.md"],"sources":["apps/docs/src/demos/cn/table/virtualization.tsx"],"checks":["pnpm exec vitest run tests/collection-filter-virtual.test.ts tests/table.test.ts tests/collection-state.test.ts","pnpm exec vitest run tests/virtual-rows.test.ts","pnpm typecheck","node scripts/check-package.mjs virtual-rows list-box b02-pickers api-root-aliases m35-m36"]}
-->
# HD-09-VIRTUALIZATION:Table 与 ListBox 虚拟布局能力
@@ -32,10 +32,12 @@
复核入口ee37e66;集成人已补修typed key并提供公开复现夹具,提交ae27fb28d19f5611d23b5926a961e84e01be0002。上述执行范围勾选仅保留原实施记录,当前未验收;准确问题与实测数据见同一结果文件末节。继续当前任务分支,不从main重做。
- [ ] R1-01(P1):估算高度须有实际测量/修正路径,处理未知内容和标题高度、宽度变化、缓存失效与滚动锚定。当前undefined→固定回退不能作为已完成的估算能力;128px内容落在56px占位内已重叠。不得仅改称“不支持”核销原任务。
- [ ] R1-02(P1):统一Table实际行几何与窗口算法;42px模型/45px实测导致渲染行数变化时scrollHeight漂移,不可称为无影响边框差异。核对基线列布局/截断,恢复或用具体布局证据解释;保留原生行头和HD-08成果。
- [ ] R1-03(P1):scrollToIndex/绑定需要考虑行流在滚动容器中的起点及表头;小于视口的目标行必须完整可见,不能只断言DOM已挂载。夹具定位当前目标底部超出视口36px;同时修正“第150行”按钮的0/1基索引口径。
- [ ] R1-04(P1):父滚动容器绑定在空→长列表、过滤/追加、布局改变后仍须正确;不要只在root引用变化时查找“当前已溢出”的祖先。现有延后加载场景把10008px列表当视口,200px父容器一次挂载200项。保持sticky搜索与单一焦点模型,覆盖PageUp/Down。
- [x] R1-01(P1):估算高度须有实际测量/修正路径,处理未知内容和标题高度、宽度变化、缓存失效与滚动锚定。当前undefined→固定回退不能作为已完成的估算能力;128px内容落在56px占位内已重叠。不得仅改称“不支持”核销原任务。
- [x] R1-02(P1):统一Table实际行几何与窗口算法;42px模型/45px实测导致渲染行数变化时scrollHeight漂移,不可称为无影响边框差异。核对基线列布局/截断,恢复或用具体布局证据解释;保留原生行头和HD-08成果。
- [x] R1-03(P1):scrollToIndex/绑定需要考虑行流在滚动容器中的起点及表头;小于视口的目标行必须完整可见,不能只断言DOM已挂载。夹具定位当前目标底部超出视口36px;同时修正“第150行”按钮的0/1基索引口径。
- [x] R1-04(P1):父滚动容器绑定在空→长列表、过滤/追加、布局改变后仍须正确;不要只在root引用变化时查找“当前已溢出”的祖先。现有延后加载场景把10008px列表当视口,200px父容器一次挂载200项。保持sticky搜索与单一焦点模型,覆盖PageUp/Down。
- [x] typed key:0与"0"曾均变为item-0,重排触发Duplicate collection key错误;集成人改用既有encodeKey并补状态保持回归。返修不得回退。
返修后重跑本卡全部范围、相关单测与类型、真实浏览器、最终tarball及必要构建,更新同一结果表。测量/滚动修复后须同时覆盖普通与sticky父容器、长→短→长、异步空→长、估算→实测、容器宽度变化;不以既有整数预设行高夹具代替未知高度验收。不合main、不push,交回复核。
用户随后授权本会话继续直接修复;R1四项已按下方最终结果节关闭,历史返修说明保留作追溯,最终状态以元数据为准。
+2
View File
@@ -384,3 +384,5 @@ Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该
## 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 零拖放实现,不提供。
HD09-R1:自然行/标题测量、类型保真尺寸缓存和滚动绑定为本库Vue适配;ListBox复用同一useVirtualRows几何,保留既有集合选择/焦点模型,不引入React状态或第二套全局协议。Table原生th/td的padding最小高度与42px虚拟行冲突已证实,新增TableRow.height内容盒适配,不改变非虚拟表格默认DOM。TableLayout headingHeight对应常驻表头,按真实tbody原点处理,纠正原“无分区表头模型所以不提供”的解释。
+11
View File
@@ -275,6 +275,17 @@
* (UA bold/center neutralised) while caller text-align/font-weight keep
* cascading into every cell — scoping the reset to `th` preserves ancestor
* inheritance for the regular td cells. */
/* Explicit virtual row heights must not be enlarged by native cell padding.
Keep the original padding on an inset content box, with native th/td intact. */
.hv-table__cell[data-fixed-height] {
position: relative;
padding: 0;
overflow: clip;
}
.hv-table__fixed-cell-content {
@apply absolute inset-x-0 top-1/2 -translate-y-1/2 px-4 py-3;
}
th.hv-table__cell {
text-align: inherit;
font-weight: inherit;
@@ -1,132 +1,145 @@
/**
* 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.
*/
/** Shared virtual geometry; collection selection and logical identity stay with their owners. */
import {
computed,
shallowRef,
toValue,
nextTick,
getCurrentScope,
onScopeDispose,
type ComputedRef,
type MaybeRefOrGetter,
} from "vue";
import type { CollectionKey } from "./keys";
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. */
/** Stable typed identities for measured rows. Defaults to the row index. */
keys?: MaybeRefOrGetter<readonly CollectionKey[]>;
/** Undefined heights are estimated until measureRow observes the real row. */
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. */
estimatedRowHeight?: number | ((index: number) => number);
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 VirtualRowsBindingOptions {
/** Element at the row stream origin (e.g. tbody below the table header). */
content?: HTMLElement;
/** Visible sticky chrome occluding the start of the viewport, in px. */
scrollPaddingStart?: number | (() => 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;
/** Ref callback for naturally sized rows (accepts a DOM node or Vue component ref). */
measureRow: (index: number, element: unknown) => void;
/** Invalidate offscreen cached content sizes after caller-owned data changes. */
resetMeasurements: () => void;
}
const positive = (value: number | undefined, fallback: number) =>
value != null && Number.isFinite(value) && value > 0 ? value : fallback;
const nonnegative = (value: number | undefined) =>
value != null && Number.isFinite(value) ? Math.max(0, value) : 0;
const binders = new WeakMap<
UseVirtualRows,
(element: HTMLElement, options: VirtualRowsBindingOptions) => () => 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 sizes = shallowRef(new Map<CollectionKey, number>());
const nodes = new Map<HTMLElement, CollectionKey>();
const rowKeys = computed(() =>
options.keys ? toValue(options.keys) : undefined,
);
const keyAt = (index: number) => rowKeys.value?.[index] ?? index;
const rawHeight = (index: number) =>
typeof options.rowHeight === "function"
? options.rowHeight(index)
: options.rowHeight;
const estimate = (index: number) =>
positive(
typeof options.estimatedRowHeight === "function"
? options.estimatedRowHeight(index)
: options.estimatedRowHeight,
48,
);
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 rawCount = toValue(options.count);
const count = Number.isFinite(rawCount)
? Math.max(0, Math.floor(rawCount))
: 0;
const gap = nonnegative(options.gap),
pad = nonnegative(options.padding),
loader = nonnegative(options.loaderHeight);
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;
const raw = rawHeight(i);
top += positive(raw ?? sizes.value.get(keyAt(i)), estimate(i));
if (i < count - 1) top += gap;
}
offsets[count] = top;
return { count, pad, loaderSpan, offsets };
return {
count,
offsets,
pad,
loaderSpan: loader > 0 ? loader + (count ? gap : 0) : 0,
};
});
const rowOffsetOf = (index: number) =>
geometry.value.offsets[Math.min(Math.max(index, 0), geometry.value.count)];
geometry.value.offsets[
Math.min(geometry.value.count, Math.max(0, Math.floor(index) || 0))
]!;
const rowExtentOf = (index: number) =>
rowOffsetOf(index + 1) - rowOffsetOf(index);
const totalHeight = computed(
() =>
geometry.value.offsets[geometry.value.count]! +
rowOffsetOf(geometry.value.count) +
geometry.value.loaderSpan +
geometry.value.pad,
);
const window = computed<VirtualRowWindow>(() => {
function firstAt(top: number) {
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;
let lo = 0,
hi = count;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (offsets[mid + 1]! <= top) lo = mid + 1;
else hi = 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;
return lo;
}
const window = computed(() => {
const { count, offsets } = geometry.value;
const overscan = Math.floor(nonnegative(options.overscan ?? 8));
const start = Math.max(0, firstAt(state.value.scrollTop) - overscan);
let lo = start,
hi = count;
const limit = state.value.scrollTop + state.value.viewport;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (offsets[mid]! < limit) lo = mid + 1;
else hi = mid;
}
const end = Math.min(count, endLow + overscan);
// Keep an initial window while a hidden/unmeasured container mounts.
const end = Math.min(
count,
Math.max(lo + overscan, start + (count ? 1 : 0)),
);
return {
start,
end,
@@ -135,35 +148,250 @@ export function useVirtualRows(options: UseVirtualRowsOptions): UseVirtualRows {
};
});
function update(scrollTop: number, viewportHeight: number) {
state.value = { scrollTop, viewport: viewportHeight };
const top = nonnegative(scrollTop),
viewport = nonnegative(viewportHeight);
if (state.value.scrollTop !== top || state.value.viewport !== viewport)
state.value = { scrollTop: top, viewport };
}
function scrollToIndex(element: HTMLElement, index: number) {
const top = rowOffsetOf(index);
const extent = rowExtentOf(index);
if (top < element.scrollTop) element.scrollTop = top;
let binding:
| {
element: HTMLElement;
options: VirtualRowsBindingOptions;
origin: () => number;
inset: () => number;
measure: () => void;
}
| undefined;
let pendingTarget:
| { element: HTMLElement; key: CollectionKey; scrollTop?: number }
| undefined;
function withAnchor(change: () => void) {
const index = firstAt(state.value.scrollTop);
const anchorKey = keyAt(index),
before = rowOffsetOf(index);
change();
if (binding && index < geometry.value.count) {
const keys = rowKeys.value;
const nextIndex = keys ? keys.indexOf(anchorKey) : index;
if (nextIndex >= 0) {
const delta = rowOffsetOf(nextIndex) - before;
if (delta) {
binding.element.scrollTop += delta;
if (pendingTarget?.element === binding.element)
pendingTarget.scrollTop = binding.element.scrollTop;
}
}
binding.measure();
}
}
function resetMeasurements() {
if (sizes.value.size)
withAnchor(() => {
sizes.value = new Map();
});
}
function measureNodes() {
const next = new Map(sizes.value);
let changed = false;
for (const [node, key] of nodes) {
if (!node.isConnected) {
observer?.unobserve(node);
nodes.delete(node);
continue;
}
const h = node.getBoundingClientRect().height;
if (
Number.isFinite(h) &&
h > 0 &&
Math.abs((next.get(key) ?? 0) - h) > 0.25
) {
next.set(key, h);
changed = true;
}
}
if (changed)
withAnchor(() => {
sizes.value = next;
});
if (pendingTarget && next.has(pendingTarget.key)) {
const target = pendingTarget;
pendingTarget = undefined;
const keys = rowKeys.value;
const index = keys ? keys.indexOf(target.key) : Number(target.key);
if (index >= 0) scrollToIndex(target.element, index);
}
}
const observer =
typeof ResizeObserver === "undefined"
? undefined
: new ResizeObserver(measureNodes);
let queued = false;
function queueMeasurement() {
if (queued) return;
queued = true;
void nextTick(() => {
queued = false;
measureNodes();
});
}
function measureRow(index: number, value: unknown) {
const element =
value instanceof HTMLElement
? value
: (value as { $el?: unknown } | null)?.$el;
if (!(element instanceof HTMLElement) || rawHeight(index) !== undefined) {
queueMeasurement();
return;
}
const key = keyAt(index);
if (nodes.get(element) !== key) {
nodes.set(element, key);
observer?.observe(element);
}
queueMeasurement();
}
function scrollToIndex(element: HTMLElement, requested: number) {
if (!geometry.value.count) return;
const index = Math.max(
0,
Math.min(geometry.value.count - 1, Math.floor(requested) || 0),
);
const b = binding?.element === element ? binding : undefined;
if (rawHeight(index) === undefined && !sizes.value.has(keyAt(index)))
pendingTarget = { element, key: keyAt(index) };
const origin = b?.origin() ?? 0,
inset = b?.inset() ?? 0;
const top = origin + rowOffsetOf(index),
extent = rowExtentOf(index);
if (
top < element.scrollTop + inset ||
extent > element.clientHeight - inset
)
element.scrollTop = Math.max(0, top - inset);
else if (top + extent > element.scrollTop + element.clientHeight)
element.scrollTop = top + extent - element.clientHeight;
update(element.scrollTop, element.clientHeight);
if (pendingTarget?.element === element)
pendingTarget.scrollTop = element.scrollTop;
if (b) b.measure();
else update(element.scrollTop, element.clientHeight);
}
return { window, rowOffsetOf, rowExtentOf, totalHeight, update, scrollToIndex };
const rows: UseVirtualRows = {
window,
rowOffsetOf,
rowExtentOf,
totalHeight,
update,
scrollToIndex,
measureRow,
resetMeasurements,
};
let disposeBinding: (() => void) | undefined;
binders.set(rows, (element, config) => {
disposeBinding?.();
config = {
...config,
content:
config.content ??
element.querySelector<HTMLElement>(
'[data-slot="table-content"] > tbody',
) ??
undefined,
};
const origin = () =>
config.content
? config.content.getBoundingClientRect().top -
element.getBoundingClientRect().top -
element.clientTop +
element.scrollTop
: 0;
const inset = () =>
nonnegative(
typeof config.scrollPaddingStart === "function"
? config.scrollPaddingStart()
: config.scrollPaddingStart,
);
let width = element.clientWidth;
const measure = () => {
if (element.clientWidth !== width) {
width = element.clientWidth;
// Retain connected rows until their own ResizeObserver reports the
// new natural size. Resetting them to estimates can toggle scrollbars
// repeatedly when the whole collection is near the viewport height.
const visible = new Set(
[...nodes].filter(([node]) => node.isConnected).map(([, key]) => key),
);
withAnchor(() => {
sizes.value = new Map(
[...sizes.value].filter(([key]) => visible.has(key)),
);
});
}
update(
Math.max(0, element.scrollTop + inset() - origin()),
Math.max(0, element.clientHeight - inset()),
);
};
binding = { element, options: config, origin, inset, measure };
const previousAnchor = element.style.overflowAnchor;
element.style.overflowAnchor = "none";
const resize =
typeof ResizeObserver === "undefined"
? undefined
: new ResizeObserver(measure);
resize?.observe(element);
if (config.content) {
for (
let node: HTMLElement | null = config.content;
node && node !== element;
node = node.parentElement
) {
resize?.observe(node);
// Header/sticky chrome may move the stream without resizing it.
for (
let previous = node.previousElementSibling;
previous;
previous = previous.previousElementSibling
)
resize?.observe(previous);
}
}
const onScroll = () => {
if (
pendingTarget?.element === element &&
pendingTarget.scrollTop != null &&
Math.abs(pendingTarget.scrollTop - element.scrollTop) > 1
)
pendingTarget = undefined;
measure();
};
element.addEventListener("scroll", onScroll, { passive: true });
let live = true;
const dispose = () => {
if (!live) return;
live = false;
resize?.disconnect();
element.removeEventListener("scroll", onScroll);
element.style.overflowAnchor = previousAnchor;
if (binding?.element === element) binding = undefined;
};
disposeBinding = dispose;
measure();
return dispose;
});
if (getCurrentScope())
onScopeDispose(() => {
observer?.disconnect();
nodes.clear();
disposeBinding?.();
});
return rows;
}
/**
* Attach the window updater to a scroll container: recomputes on scroll and on
* container resize. Returns a cleanup callable.
*/
/** Bind a real scroll viewport and the row stream's actual origin. */
export function bindVirtualRows(
rows: UseVirtualRows,
element: HTMLElement,
options: VirtualRowsBindingOptions = {},
): () => 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();
};
return binders.get(rows)!(element, options);
}
+161 -89
View File
@@ -8,6 +8,7 @@ import {
onBeforeUpdate,
onBeforeUnmount,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
@@ -16,7 +17,7 @@ import {
watch,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { bindVirtualRows, useVirtualRows } from "../collection/virtual-rows";
import { listboxVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import Header from "../header/HeaderRoot.vue";
@@ -251,107 +252,166 @@ const source = computed(() => visibleItems.value);
* `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 };
| { key: string; kind: "pad"; height: number; gap: number }
| {
key: string;
kind: "heading";
height: number | undefined;
gap: number;
text: string;
estimate: number;
}
| {
key: string;
kind: "item";
height: number | undefined;
gap: number;
item: T;
index: number;
estimate: number;
}
| { key: string; kind: "loader"; height: number; gap: 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;
const prev = rows.at(-1);
if (row.kind !== "pad" && prev && prev.kind !== "pad")
prev.gap = Math.max(0, props.gap);
rows.push(row);
};
if (props.padding > 0)
push({ key: "pad-top", kind: "pad", height: props.padding });
items.forEach((item, index) => {
push({ key: "pad-top", kind: "pad", height: props.padding, gap: 0 });
source.value.forEach((item, index) => {
if (item.heading)
push({
key: `heading-${index}`,
key: `heading-${encodeKey(item.id)}`,
kind: "heading",
height: props.headingHeight,
height:
typeof props.headingHeight === "function"
? props.headingHeight(index)
: props.headingHeight,
estimate: props.estimatedHeadingHeight ?? 48,
text: item.heading,
gap: 0,
});
const height =
(typeof props.rowHeight === "function"
? props.rowHeight(index)
: props.rowHeight) ?? fallbackRowHeight.value;
push({ key: `item-${encodeKey(item.id)}`, kind: "item", height, item, index });
push({
key: `item-${encodeKey(item.id)}`,
kind: "item",
height:
typeof props.rowHeight === "function"
? props.rowHeight(index)
: props.rowHeight,
estimate: fallbackRowHeight.value,
item,
index,
gap: 0,
});
});
if (slots.loader)
push({ key: "loader", kind: "loader", height: props.loaderHeight });
if (slots.loader && props.loaderHeight > 0)
push({ key: "loader", kind: "loader", height: props.loaderHeight, gap: 0 });
if (props.padding > 0)
push({ key: "pad-bottom", kind: "pad", height: props.padding });
push({ key: "pad-bottom", kind: "pad", height: props.padding, gap: 0 });
return rows;
});
/** Row stream index for a logical item index (headings/pads shift the row). */
const virtualLayout = useVirtualRows({
count: () => virtualRows.value.length,
keys: () => virtualRows.value.map((row) => row.key),
rowHeight: (index) => {
const row = virtualRows.value[index];
return row?.height === undefined ? undefined : row.height + row.gap;
},
estimatedRowHeight: (index) => {
const row = virtualRows.value[index];
return (
(row && "estimate" in row ? row.estimate : fallbackRowHeight.value) +
(row?.gap ?? 0)
);
},
get overscan() {
return props.overscan;
},
});
const windowItems = computed(() => {
const { start, end } = virtualLayout.window.value;
return virtualRows.value
.slice(start, end)
.map((data, index) => ({ data, index: start + index }));
});
const wrapperProps = computed(() => ({
style: {
height: `${virtualLayout.totalHeight.value}px`,
paddingTop: `${virtualLayout.window.value.padTop}px`,
boxSizing: "border-box" as const,
overflowAnchor: "none" as const,
},
}));
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 {
list: windowItems,
containerProps,
wrapperProps,
scrollTo,
} = useVirtualList(virtualRows, {
itemHeight: (rowIndex: number) =>
virtualRows.value[rowIndex]?.height ?? fallbackRowHeight.value,
overscan: props.overscan,
});
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 virtualContent = shallowRef<HTMLElement | null>(null);
function resolveScrollParent() {
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;
// Overflow policy matters even before an asynchronous collection overflows.
for (let node: HTMLElement | null = el; node; node = node.parentElement)
if (/^(auto|scroll)$/.test(getComputedStyle(node).overflowY)) return node;
return el;
}
let scrollParent: HTMLElement | null = null;
function onVirtualScroll() {
containerProps.onScroll();
let boundContent: HTMLElement | null = null;
let detachVirtual: (() => void) | undefined;
function stickyInset() {
if (!scrollParent || scrollParent === root.value) return 0;
let inset = 0;
// Measure preceding sticky chrome, including caller-owned search wrappers.
for (
let node = root.value;
node && node !== scrollParent;
node = node.parentElement
) {
for (
let previous = node.previousElementSibling;
previous;
previous = previous.previousElementSibling
) {
const style = getComputedStyle(previous);
if (style.position === "sticky" && style.top !== "auto")
inset = Math.max(
inset,
(parseFloat(style.top) || 0) +
previous.getBoundingClientRect().height,
);
}
}
return inset;
}
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" },
);
function refreshVirtualBinding() {
const parent = props.virtualized ? resolveScrollParent() : null;
if (parent === scrollParent && virtualContent.value === boundContent) return;
detachVirtual?.();
detachVirtual = undefined;
scrollParent = parent;
boundContent = virtualContent.value;
if (parent && boundContent)
detachVirtual = bindVirtualRows(virtualLayout, parent, {
content: boundContent,
scrollPaddingStart: stickyInset,
});
}
watch([root, virtualContent, () => props.virtualized], refreshVirtualBinding, {
flush: "post",
});
onUpdated(refreshVirtualBinding);
onBeforeUnmount(() => {
scrollParent?.removeEventListener("scroll", onVirtualScroll);
detachVirtual?.();
scrollParent = null;
});
let restoringFocus = false;
@@ -391,12 +451,6 @@ 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 row offset (item rows may sit behind heading/padding rows); the
@@ -413,17 +467,8 @@ async function revealRow(key: ListBoxKey, valid: () => boolean) {
if (index < 0 || !valid()) return;
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 + row.height > element.scrollTop + element.clientHeight)
) {
if (!valid()) return;
scrollTo(rowIndex);
}
if (element && valid()) virtualLayout.scrollToIndex(element, rowIndex);
await waitForMountedRow(key, valid);
return;
}
@@ -584,11 +629,29 @@ function keydown(event: KeyboardEvent) {
const height = props.virtualized
? activeHeight
: current?.getBoundingClientRect().height || activeHeight;
const page = Math.max(
const viewport = Math.max(
1,
Math.floor((root.value?.clientHeight ?? 0) / height),
((scrollParent ?? root.value)?.clientHeight ?? 0) - stickyInset(),
);
target = index + (event.key === "PageDown" ? page : -page);
if (props.virtualized && index >= 0) {
const direction = event.key === "PageDown" ? 1 : -1;
const offsetOf = (itemIndex: number) => {
const logical = source.value.findIndex(
(item) => item.id === items[itemIndex].key,
);
return virtualLayout.rowOffsetOf(rowIndexOfItem(logical));
};
const goal = offsetOf(index) + viewport * direction;
target = index;
while (target + direction >= 0 && target + direction < items.length) {
target += direction;
if (direction > 0 ? offsetOf(target) >= goal : offsetOf(target) <= goal)
break;
}
} else {
const page = Math.max(1, Math.floor(viewport / height));
target = index + (event.key === "PageDown" ? page : -page);
}
} else if (event.key === backward) target = index - 1;
else if (event.key === forward) target = index + 1;
if (target !== undefined) {
@@ -800,6 +863,7 @@ defineExpose({
<slot v-if="!visibleItems.length" name="empty" />
<div
v-if="virtualized"
ref="virtualContent"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
@@ -808,7 +872,15 @@ defineExpose({
v-for="entry in windowItems"
:key="entry.data.key"
role="presentation"
:style="{ height: `${entry.data.height}px` }"
:ref="(element) => virtualLayout.measureRow(entry.index, element)"
:style="{
height:
entry.data.height === undefined
? undefined
: `${entry.data.height + entry.data.gap}px`,
paddingBottom: `${entry.data.gap}px`,
boxSizing: 'border-box',
}"
>
<div v-if="entry.data.kind === 'pad'" aria-hidden="true" />
<Header v-else-if="entry.data.kind === 'heading'">
@@ -44,7 +44,9 @@ export interface ListBoxOptions<T extends ListBoxDataItem = ListBoxDataItem> {
/** Fallback height in px for variable rows whose function returns undefined. */
estimatedRowHeight?: number;
/** Heading row height in px for virtualized `heading` rows. */
headingHeight?: number;
headingHeight?: number | ((index: number) => number | undefined);
/** Estimate used until an unknown heading is measured. */
estimatedHeadingHeight?: 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). */
@@ -51,17 +51,23 @@ export default defineComponent({
tabindex: attrs.tabindex ?? -1,
class: [ctx?.slots.value.cell(), attrs.class],
"data-slot": "table-cell",
"data-fixed-height": row?.height?.value != null || undefined,
"data-tree-column": isTreeColumn.value || undefined,
"data-level": row?.level,
colspan: props.colspan,
},
slots.default?.({
isExpanded: row?.isExpanded.value ?? false,
hasChildItems: row?.hasChildItems ?? false,
isDisabled: row?.isDisabled.value ?? false,
isTreeColumn: isTreeColumn.value,
isSelected: row?.isSelected.value ?? false,
}),
(() => {
const content = slots.default?.({
isExpanded: row?.isExpanded.value ?? false,
hasChildItems: row?.hasChildItems ?? false,
isDisabled: row?.isDisabled.value ?? false,
isTreeColumn: isTreeColumn.value,
isSelected: row?.isSelected.value ?? false,
});
return row?.height?.value != null
? [h("div", { class: "hv-table__fixed-cell-content" }, content)]
: content;
})(),
);
},
});
@@ -31,6 +31,8 @@ export default defineComponent({
level: { type: Number, default: undefined },
rowKey: { type: [String, Number] as PropType<TableKey>, required: true },
isDisabled: { type: Boolean, default: false },
/** Exact virtual-row extent; omitted rows retain natural table sizing. */
height: { type: Number, default: undefined },
hasChildItems: { type: Boolean, default: false },
as: { type: String, default: "tr" },
},
@@ -76,6 +78,7 @@ export default defineComponent({
isSelected,
isDisabled,
isExpanded,
height: computed(() => props.height),
get hasChildItems() {
return props.hasChildItems;
},
@@ -100,13 +103,11 @@ export default defineComponent({
"aria-expanded": props.hasChildItems ? isExpanded.value : undefined,
"aria-level": props.level,
// 1-based level for CSS indent (matches upstream --table-row-level).
style:
props.level != null
? ({ "--table-row-level": String(props.level) } as Record<
string,
string
>)
: undefined,
style: {
height: props.height != null ? `${props.height}px` : undefined,
"--table-row-level":
props.level != null ? String(props.level) : undefined,
},
"aria-selected":
ctx && ctx.selectionMode.value !== "none"
? isSelected.value
@@ -48,6 +48,7 @@ export const tableContextKey: InjectionKey<TableContextValue> =
Symbol("hv-table");
export interface TableRowContextValue {
height?: ComputedRef<number | undefined>;
nextCellIndex: () => number;
key: TableKey;
isSelected: ComputedRef<boolean>;
+1
View File
@@ -468,6 +468,7 @@ export {
type UseVirtualRows,
type VirtualRowHeight,
type VirtualRowWindow,
type VirtualRowsBindingOptions,
} from "./components/collection/virtual-rows";
export type { ConfigProviderProps } from "./types";
+74 -17
View File
@@ -107,9 +107,13 @@ 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 unknownTableRows = ref(false);
const tableWidth = ref(800);
const tableRowHeight = (index: number) =>
unknownTableRows.value ? undefined : index % 2 ? 44 : 72;
const tableRows = useVirtualRows({
count: () => tableCount.value,
keys: () => Array.from({ length: tableCount.value }, (_, i) => i + 1),
rowHeight: tableRowHeight,
estimatedRowHeight: fallbackRow,
loaderHeight: 40,
@@ -136,7 +140,10 @@ function jumpToRow(index: number) {
let detach: (() => void) | undefined;
onMounted(() => {
const element = scrollElement();
if (element) detach = bindVirtualRows(tableRows, element);
if (element)
detach = bindVirtualRows(tableRows, element, {
content: element.querySelector("tbody") ?? undefined,
});
});
onUnmounted(() => detach?.());
</script>
@@ -183,7 +190,8 @@ onUnmounted(() => detach?.());
virtualized
:row-height="resolvedRowHeight"
:estimated-row-height="fallbackRow"
:heading-height="headingHeight"
:heading-height="estimatedRows ? () => undefined : headingHeight"
:estimated-heading-height="32"
:loader-height="40"
:gap="8"
:padding="12"
@@ -277,7 +285,13 @@ onUnmounted(() => detach?.());
<section style="display: grid; gap: 8px">
<h2>表格虚拟窗口(useVirtualRows)</h2>
<div style="display: flex; gap: 8px">
<Button size="sm" variant="secondary" @click="jumpToRow(150)">
<Button @click="unknownTableRows = !unknownTableRows">
切换表格未知行高
</Button>
<Button @click="tableWidth = tableWidth === 800 ? 520 : 800">
表格宽度 {{ tableWidth }}
</Button>
<Button size="sm" variant="secondary" @click="jumpToRow(149)">
定位第 150 行
</Button>
<Button
@@ -293,12 +307,18 @@ onUnmounted(() => detach?.());
<div
ref="scrollRef"
data-slot="table-virtual-viewport"
style="height: 300px; width: 100%; overflow: auto"
:style="{
height: '300px',
width: `${tableWidth}px`,
overflow: 'auto',
}"
>
<TableContent
aria-label="可变行高表格"
style="min-width: 520px; table-layout: fixed"
:aria-rowcount="tableCount + 1"
:row-keys="tableItems.map((row) => row.id)"
@focus-row="(_key, index) => jumpToRow(index)"
>
<TableHeader aria-rowindex="1">
<TableColumn id="name" is-row-header :min-width="160">
@@ -311,22 +331,59 @@ onUnmounted(() => detach?.());
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>
<template v-for="row in visibleTableRows" :key="row.id">
<TableRow
:row-key="row.id"
:aria-rowindex="row.id + 1"
:ref="(node) => tableRows.measureRow(row.id - 1, node)"
:height="tableRowHeight(row.id - 1)"
>
<TableCell>{{ row.name }}</TableCell>
<TableCell>
{{
unknownTableRows
? "需要测量的表格内容,宽度改变后会重新换行。".repeat(
10,
)
: "行高 44/72 交替"
}}
</TableCell>
</TableRow>
<tr
v-if="row.id < tableCount"
aria-hidden="true"
style="height: 4px"
/>
</template>
<tr
v-if="tableWindow.end < tableCount"
aria-hidden="true"
:style="{ height: tableWindow.padBottom + 'px' }"
/>
<template v-else>
<tr
v-if="tableCount"
aria-hidden="true"
style="height: 4px"
/>
<tr role="presentation">
<td colspan="2" style="padding: 0">
<div
role="status"
data-probe-table-loader
style="
height: 40px;
display: flex;
align-items: center;
justify-content: center;
"
>
加载更多…
</div>
</td>
</tr>
<tr aria-hidden="true" style="height: 12px" />
</template>
</TableBody>
</TableContent>
</div>
+2 -2
View File
@@ -260,8 +260,8 @@
]
},
"virtual-rows": {
"exports": ["useVirtualRows", "bindVirtualRows"],
"css": ["data-virtualized", "[data-slot=list-box][data-virtualized]"]
"exports": ["useVirtualRows", "bindVirtualRows", "TableRow"],
"css": ["data-virtualized", "[data-slot=list-box][data-virtualized]", "hv-table__fixed-cell-content"]
},
"list-box": {
"exports": [
+18 -4
View File
@@ -9,12 +9,13 @@ import {
type UseVirtualRowsOptions,
type VirtualRowHeight,
type VirtualRowWindow,
type VirtualRowsBindingOptions,
type TableRowProps,
} 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 variable: VirtualRowHeight = (index: number) => (index % 2 ? 44 : 72);
const partial: VirtualRowHeight = (index: number) =>
index % 2 ? undefined : 40;
const options: UseVirtualRowsOptions = {
@@ -33,7 +34,15 @@ 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);
const binding: VirtualRowsBindingOptions = {
content: element,
scrollPaddingStart: () => 48,
};
const detach: () => void = bindVirtualRows(rows, element, binding);
rows.measureRow(0, element);
rows.resetMeasurements();
const fixedRow: TableRowProps = { rowKey: 0, height: 42 };
void fixedRow;
rows.scrollToIndex(element, 10);
// @ts-expect-error Row heights are px numbers or index functions, not strings
@@ -52,7 +61,8 @@ const listProps: ListBoxProps = {
virtualized: true,
rowHeight: (index: number) => (index % 2 ? 64 : 40),
estimatedRowHeight: 50,
headingHeight: 32,
headingHeight: () => undefined,
estimatedHeadingHeight: 32,
loaderHeight: 40,
gap: 8,
padding: 12,
@@ -82,3 +92,7 @@ void [
badHeading,
badRowFn,
];
// @ts-expect-error Native row height uses px numbers
const badTableRow: TableRowProps = { rowKey: 1, height: "42px" };
void badTableRow;
+94 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref, type PropType } from "vue";
import {
@@ -6,6 +6,14 @@ import {
ListBoxItem,
ListBoxItemIndicator,
useVirtualRows,
bindVirtualRows,
Table,
TableContent,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
} from "../packages/vue/src";
import type { ListBoxDataItem } from "../packages/vue/src/components/list-box/context";
@@ -313,3 +321,88 @@ it("review: numeric and string keys preserve local row identity on reorder", asy
"number:0/number:0",
]);
});
it("measures unknown rows by typed key and preserves the scroll anchor", async () => {
const keys = ref<(number | string)[]>(
Array.from({ length: 20 }, (_, i) => i),
);
const rows = useVirtualRows({
count: 20,
keys,
rowHeight: () => undefined,
estimatedRowHeight: 50,
overscan: 0,
});
const viewport = document.createElement("div");
document.body.append(viewport);
Object.defineProperty(viewport, "clientHeight", { value: 100 });
viewport.scrollTop = 300;
const detach = bindVirtualRows(rows, viewport);
const node = document.createElement("div");
viewport.append(node);
vi.spyOn(node, "getBoundingClientRect").mockReturnValue({
height: 100,
} as DOMRect);
rows.measureRow(0, node);
await nextTick();
expect(rows.rowExtentOf(0)).toBe(100);
expect(viewport.scrollTop).toBe(350);
expect(rows.window.value.start).toBe(6);
keys.value = ["0", ...keys.value.slice(1)];
expect(rows.rowExtentOf(0)).toBe(50); // string zero must not reuse numeric zero's size
detach();
viewport.remove();
rows.measureRow(0, null);
await nextTick();
});
it("scroll positioning includes the body origin and sticky occlusion", () => {
const rows = useVirtualRows({ count: 30, rowHeight: 50 });
const viewport = document.createElement("div"),
body = document.createElement("div");
Object.defineProperty(viewport, "clientHeight", { value: 200 });
vi.spyOn(viewport, "getBoundingClientRect").mockImplementation(
() => ({ top: 0 }) as DOMRect,
);
vi.spyOn(body, "getBoundingClientRect").mockImplementation(
() => ({ top: 36 - viewport.scrollTop }) as DOMRect,
);
const detach = bindVirtualRows(rows, viewport, {
content: body,
scrollPaddingStart: 40,
});
rows.scrollToIndex(viewport, 10);
expect(viewport.scrollTop).toBe(386); // 36 + row top500 + height50 - viewport200
rows.scrollToIndex(viewport, 0);
expect(viewport.scrollTop).toBe(0);
detach();
});
it("explicit TableRow height uses a content box without changing ordinary cells", () => {
const root = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableContent, () => [
h(TableHeader, () =>
h(TableColumn, { isRowHeader: true }, () => "Header"),
),
h(TableBody, () => [
h(TableRow, { rowKey: 1, height: 42 }, () =>
h(TableCell, () => "Fixed"),
),
h(TableRow, { rowKey: 2 }, () => h(TableCell, () => "Natural")),
]),
]),
),
}),
);
wrappers.push(root);
expect(root.findAll('[data-slot="table-cell"]')[0].attributes("scope")).toBe(
"row",
);
expect(root.findAll(".hv-table__fixed-cell-content")).toHaveLength(1);
expect(
root.findAll('[data-slot="table-row"]')[1].attributes("style") ?? "",
).not.toContain("height");
});