Compare commits
11 Commits
aa881d21d5
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2eb787a0bb | |||
| 6d9e3f31cf | |||
| 5a00e25a25 | |||
| 9f7eb1fa8d | |||
| ae27fb28d1 | |||
| ee37e66d37 | |||
| 9e8d89e48d | |||
| dd4f04c200 | |||
| 4bfc2ef170 | |||
| 652cf854be | |||
| 28b0b3f0b6 |
@@ -127,9 +127,7 @@ html {
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
}
|
||||
/* Section tabs keep their text treatment on hover; selection controls color. */
|
||||
.docs-nav-sections nav .hv-link,
|
||||
.docs-nav-sections nav .hv-link:is(:hover, [data-hovered="true"]) {
|
||||
.docs-nav-sections nav .hv-link {
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -146,6 +144,11 @@ html {
|
||||
border-color: var(--accent);
|
||||
color: var(--foreground);
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.docs-nav-sections nav .hv-link:is(:hover, [data-hovered="true"]) {
|
||||
color: var(--foreground);
|
||||
}
|
||||
}
|
||||
.docs-theme-wide {
|
||||
padding: 2px;
|
||||
border-radius: 999px;
|
||||
@@ -474,6 +477,7 @@ html {
|
||||
margin-left: auto;
|
||||
}
|
||||
.search-trigger .hv-kbd {
|
||||
color: inherit;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
font-size: 14px;
|
||||
@@ -485,6 +489,11 @@ html {
|
||||
box-shadow: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.search-trigger:is(:hover, [data-hovered="true"]) {
|
||||
color: var(--foreground);
|
||||
}
|
||||
}
|
||||
.dark .search-trigger {
|
||||
background: color-mix(
|
||||
in oklab,
|
||||
@@ -720,8 +729,7 @@ html {
|
||||
.docs-nav-sections nav {
|
||||
gap: 20px;
|
||||
}
|
||||
.docs-nav-sections nav .hv-link,
|
||||
.docs-nav-sections nav .hv-link:is(:hover, [data-hovered="true"]) {
|
||||
.docs-nav-sections nav .hv-link {
|
||||
font-size: 13px;
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
|
||||
@@ -77,10 +77,27 @@ import {
|
||||
|
||||
ListBox 通过 `virtualized` 仅渲染视口附近的行,高效展示大数据集。下面保留基线的 1000 条数据、50px 固定行高和 400px 视口。完整数据传给 `items`,首字母导航、全选和范围选择使用完整集合。
|
||||
|
||||
Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`。当前支持竖向固定行高列表;可变行高、虚拟分组标题和拖放布局尚未支持。
|
||||
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 ListBox 沿用数据模式 rowHeight 默认 50,其余对应默认保持。上游三个虚拟化示例的显式值(Table 42、ListBox/Autocomplete 50)是示例传值而非布局默认值,示例保持原值不机械统一。
|
||||
|
||||
| ListLayout 参数 | Vue 对应 | 更新语义 |
|
||||
| --- | --- | --- |
|
||||
| `rowHeight` | `rowHeight`(number 或 `(index) => number \| undefined`) | 每次布局重读;响应式高度变化无需重挂载。 |
|
||||
| `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 行不计。 |
|
||||
| `padding` | `padding` | 行流两端的占位行,不计 gap。 |
|
||||
|
||||
虚拟分组标题是数据驱动的(`items` 项的 `heading` 字段);动态过滤与异步追加后,条目按逻辑 `id` 保持身份、选择与键盘导航,`aria-posinset` / `aria-setsize` 始终相对完整可见集合计算,窗口外未挂载的行不丢失身份。
|
||||
|
||||
### 自定义勾选图标
|
||||
|
||||
<ComponentPreview name="list-box-custom-check-icon" />
|
||||
@@ -163,10 +180,16 @@ 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` | `number` | `rowHeight` 数值或 `50` | 可变行高函数返回 `undefined` 时的回退高度(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),渲染为行流两端的占位行。 |
|
||||
| `overscan` | `number` | `5` | 视口外额外渲染的行数,初始化时确定。 |
|
||||
| `aria-label` / `aria-labelledby` | `string` | — | 根列表框的可访问名称。 |
|
||||
| `class` / `style` / DOM 事件 | Vue 原生属性 | — | 透传到根 role=listbox 节点,类增量合并。 |
|
||||
|
||||
@@ -182,6 +205,7 @@ Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状
|
||||
| --------------- | ------------------------------------- | -------------------------------------------- |
|
||||
| 默认插槽 | 数据模式 `{ item: T, index: number }` | 静态部件模式直接放置 Item / Section。 |
|
||||
| `empty` | 无 | items 为空时的内容。 |
|
||||
| `loader` | 无 | 虚拟行流末尾的加载行(如「加载更多」),按 `loaderHeight` 计高。 |
|
||||
| `focus(key?)` | `ListBoxKey?` | 聚焦根或指定可用项;虚拟项先滚动到可见范围。 |
|
||||
| `selectAll()` | 无 | 多选模式下提出全选,跳过禁用项。 |
|
||||
| `element` | `HTMLElement` | 根元素引用。 |
|
||||
@@ -238,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` 可响应式更新。
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -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,7 +333,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 \| (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 + 已渲染行占位(含 gap)+ padBottom 恒等于 `totalHeight`),`scrollToIndex` 按行偏移滚动并夹在行流内,`bindVirtualRows` 把窗口更新绑定到滚动容器(滚动与容器缩放)。TableHeader 始终挂载,表头高度通过实际 DOM 行流起点测量,不增加一个脱离真实表头的估算参数;可用 TableHeader 的 style 设置高度(本例 42px)。`dropIndicatorThickness` 同 ListBox——Vue 侧无拖放实现,不提供空参数。
|
||||
|
||||
## 无障碍
|
||||
|
||||
@@ -341,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 中,以随组件清理测量观察器。
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableScrollContainer,
|
||||
bindVirtualRows,
|
||||
useVirtualRows,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
interface User {
|
||||
@@ -95,96 +97,86 @@ 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, {
|
||||
content: element.querySelector("tbody") ?? undefined,
|
||||
});
|
||||
});
|
||||
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"
|
||||
:style="{ height: ITEM_HEIGHT + 'px' }"
|
||||
<TableContent
|
||||
aria-label="1000 行虚拟化表格"
|
||||
class="min-w-[700px]"
|
||||
:row-keys="rowKeys"
|
||||
:aria-rowcount="users.length + 1"
|
||||
@focus-row="focusRow"
|
||||
>
|
||||
<TableHeader aria-rowindex="1" style="height: 42px" class="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"
|
||||
:height="ITEM_HEIGHT"
|
||||
>
|
||||
{{ 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>
|
||||
{{ user.name }}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{{ user.role }}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{{ user.email }}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<tr
|
||||
aria-hidden="true"
|
||||
:style="{ height: rowWindow.padBottom + 'px' }"
|
||||
/>
|
||||
</TableBody>
|
||||
</TableContent>
|
||||
</div>
|
||||
</TableScrollContainer>
|
||||
</Table>
|
||||
</template>
|
||||
|
||||
@@ -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: "按钮组与下拉根属性",
|
||||
|
||||
+10
-3
@@ -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/加载行预留;表头按真实 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 上下文。 |
|
||||
@@ -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,10 @@ 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 的布局默认与示例显式传值分别记录:布局行高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边框裁决。
|
||||
|
||||
@@ -45,3 +45,11 @@
|
||||
- [结果](results/HD-10-COLLECTIONS.md)逐条核销:范围1 ComboBox异步例补滚动到底自动增量加载(哨兵+续载链)、防重复/旧请求/过期响应(abort+序号令牌)、失败重试与SWAPI差异注记;Select既有IntersectionObserver真实网络滚动实测(20→180无重复)未重复实现。范围2 createBaseContains公开导出与虚拟化示例/默认过滤共用(cafe匹配Café既有测试钉住)。范围3触发器role/tabindex/删除键/完整焦点模型真实浏览器核实(单停靠、Enter/Space/Escape/Delete/IME/单多选全过,无需修改);插槽数据补齐组合能力(AutocompleteValue selectedItem+items源数据item、ComboBox根 selectedItem,不复制子组件)。范围4子菜单delay对齐固定源契约(默认200ms/自定义600ms/键盘32ms立即/指针离开取消),RTL定位实测向左(LTR向右),顺带移除side/align无效透传;Button/Avatar布局补偿浏览器证明生效后保留。全量111文件1666项、typecheck、build:docs、b02-pickers/api-root-aliases最终tarball(含类型双解析)通过;RTL夹具落tests/fixtures/collections-rtl.vue(playground注册)。
|
||||
|
||||
- HD-10 已验收:复核d152856,集成人补修bf6cf0f8d12fe54a72e5ff524b1b05dbaadcfe86,关闭子菜单delay对点击/禁用的回归并补取消、父关闭清理。全量111文件1672项、类型、最终docs/playground构建、b01-menu-dropdown/b02-pickers/api-root-aliases最终tarball及真实浏览器异步/重试/滚动/RTL/焦点通过,见同一结果表。按用户授权合入main并push origin/main;工作区释放,保留5173/5174,下一项HD-09未启动。
|
||||
|
||||
- DOCS-HEADER-HOVER-PARITY按用户授权集成main:合入4bfc2ef(实现652cf85),未引入分支末尾重复示例提交6049437;集成验证与推送见同一任务结果。
|
||||
|
||||
- HD-09 虚拟布局已实施待复核:分支 task/hd-09-virtualization(起点 dd4f04c,实现 9e8d89e)。ListBox 虚拟行序列(可变行高/heading/loader/gap/padding/滚动父级)、公共 useVirtualRows/bindVirtualRows、autocomplete 弹层整体滚动+sticky 搜索框、dropIndicatorThickness 记录不补;68 项卡内+全量 1683、typecheck、build:docs、virtual-rows/list-box/b02-pickers/api-root-aliases tarball 与真实浏览器几何/键盘/定位验证通过。结果见 docs/tasks/results/HD-09-VIRTUALIZATION.md;5173/5174 保留。
|
||||
|
||||
- HD-09 集成人复核ee37e66,未验收,待HD09-R1;四项布局阻断(估算未实测、Table42/45几何漂移、定位未计表头、父容器空→长绑定失败)见同一结果表。typed key已补修ae27fb28d19f5611d23b5926a961e84e01be0002,定向69项及类型通过;复现夹具保留。工作区交回当前task/hd-09-virtualization继续返修,未合main、未push,保留5173/5174。
|
||||
|
||||
- HD-09 已验收:用户要求继续后由集成人完成R1,主修复5a00e25a25bec484f3f0067545e992fa39ce53d3、动态loader补修6d9e3f31cf0883cce416ce1056f675a65a536ec6;四项阻断与typed key全部关闭,见同一结果文件最终节。全量112文件1688项、类型、最终五组tarball、docs/playground构建及自然测量/宽度变化/定位/sticky/追加过滤/加载行真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,保留5173/5174,下一项未启动。
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<!-- task-metadata
|
||||
{"base":"df954afaced8cea6a49171ebf6594726bb273aa7","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"implemented","requires":["apps/docs/.vitepress/theme/shell.css"],"sources":["apps/docs/src/components/search-dialog.tsx","apps/docs/src/components/fumadocs/ui/search-toggle.tsx"],"checks":["pnpm exec vitest run tests/docs-shell.test.ts"]}
|
||||
-->
|
||||
# DOCS-HEADER-HOVER-PARITY
|
||||
|
||||
用户截图澄清:未选中导航hover文字/图标由muted变foreground,顶部搜索入口文字/图标/快捷键也变foreground;无下划线,当前分区底线不移动。此前将要求理解为颜色不变,现予纠正。仅文档使用处CSS,不更改公共Link/Button/Kbd默认行为或真正SearchField占位符令牌。浅深主题真实hover核对normal/hover,390px字号、选中标记及焦点保留。提交分支,不合main不push;不启动HD-01任务。
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- task-metadata
|
||||
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"pending","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 typecheck"]}
|
||||
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"accepted","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 虚拟布局能力
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
|
||||
## 执行范围
|
||||
|
||||
- [ ] 在现有集合/表格模型上补固定源实际使用的可变行高与估算、分组标题、加载行、gap/padding 能力;公开 Vue API 草案须明确各参数的单位、默认值和更新语义,不要求复制 RAC 类。
|
||||
- [ ] Table 42px 与 ListBox 50px 不统一机械改48:先核固定源示例显式 rowHeight、实际布局默认值和行样式。恢复对应示例的滚动容器、列布局、截断策略及 Autocomplete sticky 搜索框。
|
||||
- [ ] 虚拟分组、动态过滤、异步追加后保持选择、键盘焦点与 aria 索引;不能让窗口外条目丢失逻辑身份。
|
||||
- [ ] dropIndicatorThickness 属于拖放布局契约,先确认支持范围;未支持拖放时记录边界,不补空参数冒充能力。
|
||||
- [x] 在现有集合/表格模型上补固定源实际使用的可变行高与估算、分组标题、加载行、gap/padding 能力;公开 Vue API 草案须明确各参数的单位、默认值和更新语义,不要求复制 RAC 类。
|
||||
- [x] Table 42px 与 ListBox 50px 不统一机械改48:先核固定源示例显式 rowHeight、实际布局默认值和行样式。恢复对应示例的滚动容器、列布局、截断策略及 Autocomplete sticky 搜索框。
|
||||
- [x] 虚拟分组、动态过滤、异步追加后保持选择、键盘焦点与 aria 索引;不能让窗口外条目丢失逻辑身份。
|
||||
- [x] dropIndicatorThickness 属于拖放布局契约,先确认支持范围;未支持拖放时记录边界,不补空参数冒充能力。
|
||||
|
||||
## 用户可见通过条件
|
||||
|
||||
@@ -27,3 +27,17 @@
|
||||
|
||||
仅浏览器客户端;不开发或运行 SSR/水合/Nuxt 服务端、逐像素自动对比、完整读屏或真机矩阵专项。
|
||||
|
||||
|
||||
## HD09-R1:集成人复核返修(2026-10-29)
|
||||
|
||||
复核入口ee37e66;集成人已补修typed key并提供公开复现夹具,提交ae27fb28d19f5611d23b5926a961e84e01be0002。上述执行范围勾选仅保留原实施记录,当前未验收;准确问题与实测数据见同一结果文件末节。继续当前任务分支,不从main重做。
|
||||
|
||||
- [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四项已按下方最终结果节关闭,历史返修说明保留作追溯,最终状态以元数据为准。
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
| 卡 | 用途 |
|
||||
| ----------------------------------------- | ----------------------------------------------------------- |
|
||||
| [硬差异修复清单](HD-QUEUE.md) | 13张修复/核实任务卡、优先级、审计纠正与验收边界;按用户选择串行执行 |
|
||||
| [DOCS-HEADER-HOVER-PARITY](DOCS-HEADER-HOVER-PARITY.md) | 按用户官方截图纠正导航与搜索入口hover变深 |
|
||||
| [DOCS-NAVIGATION-TEXT-STATE](DOCS-NAVIGATION-TEXT-STATE.md) | 顶部两个分区入口hover文字保持原色/字体 |
|
||||
| [DOCS-CONTROL-STATES](DOCS-CONTROL-STATES.md) | 字段 placeholder 主题与文档控件状态/语义排查 |
|
||||
| [DOCS-NAVIGATION-HOVER](DOCS-NAVIGATION-HOVER.md) | 顶部导航与组件总览悬停样式 |
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# DOCS-HEADER-HOVER-PARITY
|
||||
|
||||
分支task/docs-header-hover-parity;起点df954afaced8cea6a49171ebf6594726bb273aa7;实施652cf854be7b056e6e24606e773ea93f842d22d7。主会话实施/自测,未合main、未push。
|
||||
|
||||
纠正先前对用户意图的误解:用户四张官方截图要求hover变深,之前DOCS-NAVIGATION-TEXT-STATE把“不出现下划线”错误扩展为“文字颜色不变”。新结果覆盖该旧验收目标,旧记录保留追溯。
|
||||
|
||||
仅文档shell.css修改:导航hover/data-hovered改用foreground,图标currentColor跟随;保留无下划线及当前分区底线。顶部搜索Button入口hover也变foreground,内部Kbd设color:inherit使文字/图标/快捷键同步。普通Link/Button/Kbd默认样式不变,实际弹窗SearchField的placeholder主题修复保留。
|
||||
|
||||
真实浏览器5173/components:组件当前选中,快速开始normal为muted .5517,真实hover为foreground .2103,图标同步;hover移开恢复muted;组件aria-current=page及accent底线保持,快速开始底线仍透明,两个链接均无下划线。搜索normal的Button/svg/span/两Kbd均muted .5517,hover五处均foreground .2103。深色重复验证muted .705→foreground .9911,离开恢复;结束恢复跟随系统。390×844悬停两个导航字号仍13px。截图临存/private/tmp/header-nav-hover.png与header-search-hover.png。
|
||||
|
||||
复现:打开/components,移入快速开始,确认字体/图标变为与当前组件同前景色且底线仍仅组件有;移出恢复灰色。移入顶部搜索入口,搜索图标/文字/快捷键同步变深,移出恢复。浅深主题重复。
|
||||
|
||||
pnpm exec vitest run tests/docs-shell.test.ts:13项通过;git diff --check通过。仅文档CSS修改,未重复整库构建/打包。键盘焦点规则未改;未执行SSR/水合/Nuxt或逐像素/完整读屏专项。未启动HD-01,原5173/5174服务保留。
|
||||
|
||||
## main 集成(2026-10-29)
|
||||
|
||||
用户明确授权合main并push。集成前main=aa881d2,origin/main已fetch且与本地一致;合并4bfc2ef(包含实现652cf85),不引入分支后来混入的重复示例提交6049437。唯一冲突ACTIVE保留main所有新任务交接并追加本次记录,其他文件自动合并。全量111文件/1672项、pnpm typecheck、pnpm build:docs均通过,保留既有大chunk提示。未涉及公共包API,未重复产物检查。合并提交含本记录;随后推送origin/main,以远端HEAD核对成功为准。
|
||||
@@ -0,0 +1,154 @@
|
||||
# HD-09-VIRTUALIZATION 结果:Table 与 ListBox 虚拟布局能力
|
||||
|
||||
- 起点:`dd4f04c20019315bc5a7208a229c81a108b1d4ed`(main,含 HD-08、HD-10、Header hover 修复)
|
||||
- 实现:`9e8d89e`(分支 `task/hd-09-virtualization`)
|
||||
- 固定源:`ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`(只读对照 `/Users/maoyingjie/Documents/OpenSourceProjects/heroui/heroui`)
|
||||
- 范围:单目录串行;不含 SSR/水合/Nuxt、逐像素与完整读屏矩阵专项。
|
||||
|
||||
## 契约核对(补能力前)
|
||||
|
||||
固定源布局契约(table.mdx `TableLayout` 与 list-box.mdx `ListLayout` 参数表相同):`rowHeight` 48、`estimatedRowHeight` 无默认、`headingHeight` 48、`estimatedHeadingHeight` 无默认、`loaderHeight` 48、`dropIndicatorThickness` 2、`gap` 0、`padding` 0。显式传值仅出现在三个上游虚拟化示例:table/virtualization.tsx `rowHeight/headingHeight: 42`、list-box/virtualization.tsx 与 autocomplete/virtualization.tsx `rowHeight: 50`——均为示例值而非布局默认,本卡未机械统一(示例保持原值)。上游样式(autocomplete.styles.ts / popover.styles.ts)无 max-h/overflow 限制:弹层整体滚动 + sticky 搜索框是固定源模型(autocomplete-virtualization.tsx 的 `SearchField className="sticky top-0 z-10"`)。
|
||||
|
||||
## 执行范围逐项核销
|
||||
|
||||
### 1. 可变行高、估算高度、分组标题、加载行、gap/padding(已补)
|
||||
|
||||
- **ListBox**(`packages/vue/src/components/list-box/ListBox.vue`、`context.ts`):虚拟行序列扩展为 padding 占位行、数据驱动分组标题行(`ListBoxDataItem.heading`,按 `headingHeight` 计高,不参与选择与 `aria-posinset`)、条目行、`#loader` 插槽加载行。`rowHeight` 扩展为 `number | ((index) => number | undefined)`(函数返回 `undefined` 回退 `estimatedRowHeight`,最终回退 50);`gap` 仅在内容行(条目/标题/加载行)之间,计入较早一行的行占位;`padding` 为两端占位、不计 gap。每次布局重读全部高度输入(响应式更新无需重挂载)。行序列内核仍是 VueUse `useVirtualList`(函数式 itemHeight 原生支持可变行高),未新增同义状态内核。
|
||||
- **Table**(新增 `packages/vue/src/components/collection/virtual-rows.ts`):公共 `useVirtualRows` / `bindVirtualRows` 纯几何(前缀和 + 二分,无状态内核):可变行高、`estimatedRowHeight` 回退、`gap`(计入 `rowExtentOf`)、`padding`(计入 `padTop`/`padBottom`)、`loaderHeight` 行流末尾预留(在末行 gap 之后、尾 padding 之前,计入 `totalHeight` 与 `window.padBottom`,保证 padTop + 已渲染行 + padBottom ≡ totalHeight 无空洞);`scrollToIndex` 按行偏移滚动并夹在行流内;`bindVirtualRows` 绑定滚动与容器缩放。公共导出含类型(`UseVirtualRowsOptions`/`UseVirtualRows`/`VirtualRowHeight`/`VirtualRowWindow`)。
|
||||
- **Vue API 单位/默认/更新语义**:见 apps/docs/components/list-box.md「ListLayout 映射」表与 table.md「TableLayout 与 Vue 虚拟滚动」表(px 单位、默认值 rowHeight 50(数据模式)/headingHeight 48/loaderHeight 48/gap 0/padding 0、函数式行高语义、逐布局重读)。
|
||||
|
||||
### 2. 示例显式值、滚动容器、列布局、截断与 sticky(已恢复/保留)
|
||||
|
||||
- **table-virtualization**:保持 42px 显式行高(上游 layoutOptions 值)、`minWidth` 列布局(160/220/240)、单元格 `whitespace-nowrap overflow-hidden text-ellipsis` 截断、`h-[300px] min-w-[700px]` 表格与外层 `data-slot="table-virtual-viewport"` 滚动 div(`h-[300px] w-full overflow-auto`)。**裁决依据(浏览器实证)**:原生 `<table>` 不能当滚动容器——给 table 元素 `h-[300px]` 后 computed height 被内容撑到 45036px、`overflow-y: visible`(height 是最小高度且 overflow 需要确定高度);固定源滚动的是 `Table.Content` 虚拟网格(非 table 元素),结构差异决定外层滚动 div 是如实适配而非简化。表格行 inline 高 45 vs 42 为 border 排版(42 + 边框折叠),非布局偏差。
|
||||
- **list-box-virtualization**:核对后与上游一致(50px 双行、`h-[400px] w-[300px] overflow-y-auto`),**无需修改**(diff 空)。
|
||||
- **autocomplete-virtualization**:恢复弹层整体滚动 + sticky 搜索框。`autocomplete.css` 历史规则 `[data-slot="list-box"] { max-h-[320px] overflow-y-auto }`(列表自滚)限定 `:not([data-virtualized])` 保留(非虚拟化行为不变);虚拟化时 ListBox 输出 `data-virtualized` 钩子,filter 容器 `max-h-[min(400px,70vh)] overflow-y-auto` 承担弹层整体滚动,SearchField `sticky top-0 z-10` 钉在顶部。`max-h` 是上游可用空间钳制的近似替代(上游样式无 max-h 限制),差异如实记录。
|
||||
- 虚拟行高由组件布局参数承担,不照搬 RAC 类名;`[role="presentation"] > [data-slot="list-box-item"]` 宽度补偿 CSS(上游 react-aria 绝对定位行的移植遗留)对两滚模式仍成立,未改动。
|
||||
|
||||
### 3. 虚拟分组、动态过滤、异步追加的身份/选择/键盘/aria(已验证)
|
||||
|
||||
真实浏览器(playwright-core + 系统 Chrome,5173/5174)跨窗口键盘 ArrowDown×45 → 焦点条目「条目 46」`aria-posinset=46 / aria-setsize=900`(相对完整可见集合);Space 选择 `已选:46`,滚动离开再回(scrollTop 900→0)选择保持;过滤「条目 12」后渲染 7 项、选中 601 仍在;异步追加 100 项(61920→69672)后行流无空洞、选择保持。单测 `tests/virtual-rows.test.ts` 覆盖 heading 行不进 posinset 索引、loader 行独立计高、选择经逻辑 key emit 且受控回流标记、aria-setsize 恒为全集。
|
||||
|
||||
### 4. dropIndicatorThickness(记录,不补)
|
||||
|
||||
`grep` 确认 packages/vue 的 list-box/table 零拖放实现(无 drag/drop 代码):该参数度量放置指示线,无拖放则无对象,不补空参数冒充能力。已在 list-box.md / table.md 映射表记录为「不提供」。
|
||||
|
||||
## 用户可见通过条件(浏览器几何实测,对照固定源)
|
||||
|
||||
夹具 `tests/fixtures/virtual-rows.vue`(playground `?virtual-rows`)+ 三个文档示例(5173),记录于 scratchpad `verify-hd09.mjs` → `hd09.json`:
|
||||
|
||||
| 场景 | 实测 | 语义核对 |
|
||||
| --- | --- | --- |
|
||||
| 变高/分组/加载行/gap/padding(夹具) | pad 12(不计 gap)、heading wrapper 40=32+8、item 48/72/88=40/64/80+8、loader 40;几何衔接 top 4→16→56→104→176→264 无空洞 | gap 仅内容行之间、padding 两端;loaderHeight 独立 |
|
||||
| 滚动到底 | scrollTop 61600/61920、loader 行可见(40px) | 加载行可达 |
|
||||
| 异步追加 | 61920→69672、渲染 15 行、无跳位 | 行流连续 |
|
||||
| 跨窗口键盘 + 选择 | 条目 46、posinset 46/setsize 900、Space 选择保持 | 完整集合索引 |
|
||||
| 滚动定位(选中第 601 项) | scrollTop 46452、选中行可见 | revealRow 行偏移正确 |
|
||||
| 过滤 | 7 项、选中 601 保持 | 逻辑身份 |
|
||||
| 容器缩放 | 320→520 渲染 12→18 行 | bindVirtualRows/ResizeObserver |
|
||||
| 表格段变高(44/72+gap4、pad 12、loader 40) | 行 76/48 交替、padTop 12、scrollHeight 18700(含 loader 预留,DOM 自洽) | padTop+行+padBottom ≡ totalHeight |
|
||||
| 表格定位第 150 行 | scrollTop 9088、可见 行 141–157(含 overscan 6) | 前缀和偏移 |
|
||||
| 表格行数 300→600 | 37244→37300 对应、渲染 17 行 | count 响应式 |
|
||||
| 文档 list-box-virtualization | 50008/400 滚动、14 行、行高 50、到底 Benjamin Mar | 对照上游 50px/1000 项 |
|
||||
| 文档 table-virtualization | 外层 div 滚动 42084/300、16 行、行高 45(=42+border)、到底正常 | 对照上游 42px/1000 项 |
|
||||
| 文档 autocomplete-virtualization | filter 滚动 50056/400(overflow auto)、行高 50、14 行、到底 Benjamin Mar | 弹层整体滚动 |
|
||||
| autocomplete sticky | 滚 800px 后搜索框 top 相对 filter = 4(sticky top-0)、posinset 12 与滚动位一致、18 行 | sticky 搜索框恢复 |
|
||||
|
||||
“Benjamin Mar”=固定源生成数据末项 Benjamin Martinez,与上游一致。
|
||||
|
||||
## 启动与复现
|
||||
|
||||
```bash
|
||||
node scripts/task-check.mjs HD-09-VIRTUALIZATION # 前置通过
|
||||
pnpm exec vitest run tests/collection-filter-virtual.test.ts tests/table.test.ts \
|
||||
tests/collection-state.test.ts tests/virtual-rows.test.ts # 68 项
|
||||
pnpm test # 全量 112 文件 1683 项
|
||||
pnpm typecheck # vue-tsc 干净
|
||||
pnpm build:docs # 文档构建成功
|
||||
pnpm --filter playground build
|
||||
node scripts/check-package.mjs virtual-rows list-box b02-pickers api-root-aliases
|
||||
# 浏览器:5173/5174 在跑;scratchpad pw/verify-hd09.mjs、diag-auto-virt2.mjs、diag-auto-struct.mjs
|
||||
```
|
||||
|
||||
## 检查结果
|
||||
|
||||
- 卡内 checks:`tests/collection-filter-virtual.test.ts tests/table.test.ts tests/collection-state.test.ts`(57 项)+ 新增 `tests/virtual-rows.test.ts`(11 项)= 68 项全过。
|
||||
- 全量 vitest 112 文件 1683 项全过(HD-10 基线 1672 + 11)。typecheck 干净。build:docs 与 playground build 成功。
|
||||
- tarball 契约(最终打包产物、无源码 alias):新增 `tests/package/virtual-rows-contract.ts`(useVirtualRows/bindVirtualRows 选项与类型、ListBoxOptions 虚拟参数、`@ts-expect-error` 负例)+ `client-checks.json` 注册 `virtual-rows`(exports `useVirtualRows`/`bindVirtualRows`,CSS `data-virtualized` 钩子);`virtual-rows`/`list-box`/`b02-pickers`/`api-root-aliases` 四项通过(CSS token 按压缩产物实际形式匹配)。
|
||||
- 保留成果回归:HD-08(fr 列宽/上下限/容器缩放/排序焦点/自动空态跨列、th 行头/圆角/resizer)与 HD-10(共享 locale 过滤、异步防污染、插槽数据、子菜单 delay/RTL)对应套件全过;5173/5174 服务保留。
|
||||
- 文档/矩阵/来源同步:apps/docs/components/list-box.md(ListLayout 映射表)、table.md(TableLayout 映射表 + useVirtualRows 表)、docs/compatibility.md(HD-09 段与条目更新)、docs/upstream.md(HD-09 来源记录)。
|
||||
|
||||
## 限制与差异(如实记录)
|
||||
|
||||
- `estimatedHeadingHeight` / `headingHeight`(TableLayout):Vue 表格无分区表头模型,Table 侧不提供;ListBox 侧 `headingHeight` 固定(无可变标题测量)。
|
||||
- `dropIndicatorThickness`:拖放零实现,不提供(任务 4 按记录处理)。
|
||||
- autocomplete 弹层滚动高度 `max-h-[min(400px,70vh)]` 为近似可用空间钳制(上游无 max-h 限制、由 overlay 约束),属样式差异。
|
||||
- `overscan` 初始化时确定(VueUse 语义),动态调整未支持;虚拟模式要求 `items` + 竖向方向(违例抛错,语义不变)。
|
||||
- 表格示例行 inline 高 45px 为 42px + 边框排版差(border-collapse 排版),几何口径以布局参数为准。
|
||||
- 全量 vitest 偶发并发超时属环境性(隔离复跑全过,已有先例记录);本次全量一次通过。
|
||||
|
||||
|
||||
## 集成人复核:HD09-R1(2026-10-29,未验收)
|
||||
|
||||
复核入口 **ee37e66d37a128fb3cc28b6adb6af585675c0511**。原实施记录中的“逐项核销/无空洞/无跳位”不能作为最终验收结论;以下实际场景仍有阻断,暂不合main、不push。当前分支保留,用户无需重新提供旧聊天。
|
||||
|
||||
### 已直接补修
|
||||
|
||||
**ae27fb28d19f5611d23b5926a961e84e01be0002**:ListBox行wrapper由`item-${id}`改为`item-${encodeKey(id)}`,复用既有类型保真编码。新增测试让数字0与字符串0条目带组件局部状态后重排:修复前报`Duplicate collection key: 0`并出现卸载异常;修复后顺序正确且创建时身份与当前身份保持一致。浏览器夹具“反转零标识”实测为`当前 string:0 / 创建时 string:0`、`当前 number:0 / 创建时 number:0`。此项不再阻断,但返修须保留。
|
||||
|
||||
### 未关闭问题与准确复现
|
||||
|
||||
| ID | 严重度/位置 | 实测证据与影响 | 返修要求 |
|
||||
| --- | --- | --- | --- |
|
||||
| R1-01 | P1,ListBox虚拟行序列 / useVirtualRows geometry | `rowHeight`返回undefined只采用estimatedRowHeight,未观察行元素实际高度、未回写测量。5174 `?virtual-rows` 点击“切换未知行高”,原生换行内容高128,连续三行占位各56(48估算+8gap),top156/212/268,内容明显重叠。原夹具仅预先给出40/64/80,不足以证明未知内容的估算→实测闭环。标题估算亦明确未补,与任务范围不符。 | 在现有模型上补实际测量和修正,处理行/标题高度、宽度改变、过滤重排的类型保真缓存及锚定;不能只加一个永不校准的fallback或用差异文档把本卡能力移除。 |
|
||||
| R1-02 | P1,apps/docs/demos/table-virtualization.vue | 5173 `/components/table#虚拟滚动`,首屏16行均`style.height=42px`但实际45px,总scrollHeight42084;实际滚动后24行、aria-rowindex45–68、scrollTop2160,总scrollHeight42108。仅窗口项数变化就多出24px,模型与DOM不自洽。原报告“42+边框非布局偏差”结论不成立。table-fixed/额外ellipsis仍沿用,固定源对应示例没有这些类,尚未核销原恢复要求。 | 行布局/测量与spacer必须共享真实几何,保持固定集合总高度稳定并覆盖到底/反向滚动;对列布局和截断逐项恢复或提供确切适配证据,不用新增截断掩盖宽度问题。 |
|
||||
| R1-03 | P1,virtual-rows.ts scrollToIndex / bindVirtualRows | 原夹具点击“定位第150行”(调用索引150,实际第151行),scrollTop9088。视口top548/bottom848,目标top808/bottom884,高76的目标行仍有36px在视口外;表头恰为36px。算法只把正文offset当容器offset,缺行流原点/表头偏移。overscan使目标已挂载不能证明可见。 | 明确并处理行流起点与滚动坐标的关系,确保目标行实际可见;修正按钮0/1基口径,补真实矩形断言。 |
|
||||
| R1-04 | P1,ListBox.vue resolveScrollParent与watch(root) | 新夹具“加载父容器列表”:先挂载空集合,200px overflow父容器含48px固定搜索区;到达200项后root引用未变,旧绑定仍以列表自身为容器。浏览器实际listHeight10008、parentHeight200、scrollHeight10056、已挂载200项,未保持虚拟窗口。此场景等价异步初次响应/空过滤恢复,不是额外新功能。 | 不能以当前scrollHeight>clientHeight作为唯一祖先选择条件并只查一次;在数据/布局更新后正确绑定测量、scroll监听及清理,处理父级行流偏移和sticky区域。 |
|
||||
|
||||
复现已保存在 `tests/fixtures/virtual-rows.vue`(5174/?virtual-rows),仅公开组件组合、按钮和文本内容;未通过浏览器脚本修改状态或补发事件。Table正式示例没有做“修正截图”的补丁;保留原实现用于返修验证。上述父滚动容器、测量与坐标问题需要联动修改,超出少量边角修补,因此未强行集成。
|
||||
|
||||
### 本轮实际检查
|
||||
|
||||
- 原实现定向4文件/68项通过、typecheck通过,说明原用例未覆盖上述真实几何,并不免除返修。
|
||||
- typed key探针修复前失败,补修后定向4文件/**69项通过**;新复现夹具最终`pnpm typecheck`通过。修改代码Prettier、`git diff --check`通过。
|
||||
- 本轮未合并,所以未重复执行整库发布构建/最终tarball或把原1683项通过描述为补修后全量通过。返修完成后需针对最终代码重新做相关套件、构建、产物与浏览器验收。
|
||||
- 保留VueUse/Reka已有基础设施及HD-08/HD-10成果,未新增依赖;保留5173/5174。无SSR/水合/Nuxt服务端或逐像素专项。
|
||||
|
||||
继续任务:在当前`task/hd-09-virtualization`从本复核提交继续,按任务卡HD09-R1清单关闭四项,再更新本节问题状态与证据;不新建平行任务、不合main、不push。
|
||||
|
||||
## HD09-R1 最终修复与验收(2026-10-29)
|
||||
|
||||
用户随后明确要求本会话继续实施。本节覆盖前述未验收结论和原实施的限制说明;原证据保留,便于追溯,不代表问题仍未解决。
|
||||
|
||||
- 复核与typed key补修:ae27fb28d19f5611d23b5926a961e84e01be0002。
|
||||
- 测量、滚动与表格几何修复:**5a00e25a25bec484f3f0067545e992fa39ce53d3**。
|
||||
- 动态loader占位补修:**6d9e3f31cf0883cce416ce1056f675a65a536ec6**。
|
||||
- 沿用当前task/hd-09-virtualization,起点dd4f04c与原实施9e8d89e保留;未回退HD-08/HD-10或Header成果,无新增依赖。
|
||||
|
||||
### R1逐项关闭
|
||||
|
||||
| 项 | 最终处理 | 场景与证据 |
|
||||
| --- | --- | --- |
|
||||
| R1-01:估算→实测闭环 | useVirtualRows新增measureRow、稳定keys与resetMeasurements。函数行高返回undefined时先估算,挂载后ResizeObserver读取自然高度并更新前缀和。ListBox与Table复用同一几何;ListBox补函数式headingHeight与estimatedHeadingHeight。实测缓存保留key类型,宽度变化失效窗口外旧尺寸、重测可见内容;测量修正保留首个可见锚点。 | 未知ListBox内容128px/外层136px(含8px空白gap),无重叠;未知标题自然26px/外层34px。Table未知内容在800宽时205px,缩至520后重测305px,行间仍4px。新单测验证实测高度、typed cache与锚点(上方行增加50,scrollTop300→350且首可见逻辑行不变)。 |
|
||||
| R1-02:Table模型/DOM一致 | 新增TableRow.height作为精确几何的Vue适配。原生th/td保留,padding放入内部内容盒,避免原生单元格最小高度把42撑成45;省略height时保持自然DOM/排版供测量。内容盒保留普通流与继承对齐,不改非虚拟表格。正式示例移除额外table-fixed/ellipsis,保留700px最小宽与列minWidth。 | 正式示例表头42、数据行42,1000行滚动总高**42042**。首屏、滚动和Ctrl+End到末行、Ctrl+Home返回时总高一致;末行Benjamin Martinez完整可见,不再随窗口项数漂移。新单测确认fixed内容盒仅用于显式height行,原生行头scope=row保留。 |
|
||||
| R1-03:行流原点与定位 | bindVirtualRows新增content/scrollPaddingStart,Table默认识别真实tbody;观察表头与行流尺寸,定位计入实际起点和sticky遮挡。未知目标实测后再校准,用户滚动离开则取消待完成定位;修正第150行按钮为索引149。 | 已知第150行完整可见;未知表格第150行实测205px,目标top483/bottom688,视口392–692,包含全部内容。父容器Home后第1项相对视口top48,恰位于48px sticky区域下面;End到第200项完整可见。单测覆盖36px表头原点与40px sticky遮挡。 |
|
||||
| R1-04:父容器动态绑定 | 依据overflow策略选择容器,不依赖挂载时是否已溢出;root/content/virtualized变化与组件更新时检查绑定,scroll/resize监听按绑定清理。整体滚动时使用行流坐标;PageUp/Down按真实几何和可见视口定位。 | 200px父容器空→200项后仅挂载约9项,End/ Home跨窗口往返正确。未知主列表定位第601项后PageDown到第604项;位置与aria-posinset一致。过滤“条目 12”后aria-setsize11且仍选601;恢复并追加100项后setsize900,选择仍601。 |
|
||||
| 动态loader残留 | slots对象本身不提供依赖追踪:同步记录loader插槽是否存在,及时失效行流。保留loaderHeight与真实slot,避免关闭后空留48px。 | 新回归在items不变时移除条件loader:补修前仍2行、补修后仅1条数据行。表格末尾实际loader40px,滚到底时top640/bottom680、视口392–692,完整可达;总高仍18700。 |
|
||||
|
||||
### 最终验证
|
||||
|
||||
- `pnpm exec vitest run`:**112文件 / 1688项通过**(原1683 + typed key1 + 实测/原点/精确TableRow3 + 动态loader1)。原断言未删除/skip,不放宽超时。
|
||||
- `pnpm typecheck`通过。最终额外夹具的完整rowKeys/focusRow组合也通过类型与playground构建。
|
||||
- 最终 `node scripts/check-package.mjs virtual-rows list-box b02-pickers api-root-aliases m35-m36`通过:独立tarball ESM/CSS、bundler/NodeNext类型正反例;覆盖measureRow/bind配置、函数式标题估算、TableRow.height与原有选择器/Table契约,CSS精确行内容盒进入产物。
|
||||
- 最终库dist后的docs与playground生产构建通过。仅既有文档chunk大小提示;代码Prettier和git diff --check通过。
|
||||
- 真实浏览器使用5174 `?virtual-rows`与5173正式Table虚拟化示例;本节记录实际DOM矩形与真实点击/键盘/滚动,不以挂载、CSS token或代数恒等式替代可见性。
|
||||
- 源码/文档/兼容矩阵/来源同步。纠正旧报告中的“45px边框差异不影响布局”“Vue无表头模型”“仅回退值代表估算完成”“overscan仅初始化”口径;原实现的VueUse范围计算被共享行几何承接,集合身份/选择/焦点状态仍是同一份。
|
||||
|
||||
### 当前边界
|
||||
|
||||
- 显式数字行高由调用方保证容纳内容;未知内容不要强制固定CSS高度,应返回undefined并绑定measureRow。TableHeader常驻,因此按实际tbody原点处理表头,无需提供一个脱离DOM的表头估算参数。
|
||||
- 估算行在未访问前仍使用估算值,访问后校准,这是估算语义;批量替换窗口外内容的组合式消费者可调用resetMeasurements。组合式应在Vue setup/effectScope中使用,以随生命周期清理测量观察器。
|
||||
- ListBox沿用默认50px以兼容已有数据模式;公共Table几何的默认估算为48px。三个固定源示例仍分别显式42/50/50,不混淆默认与示例传值。
|
||||
- Table gap/loader由消费方在预留空间中渲染presentation行,避免双算高度;夹具提供实际示例。无拖放,不提供dropIndicatorThickness;Autocomplete的400px/70vh高度上限仍是已披露的可用空间近似。
|
||||
- 浏览器客户端范围;未执行SSR/水合/Nuxt服务端、逐像素或完整设备/读屏矩阵。
|
||||
|
||||
R1四项及typed key均已关闭。本会话完成最终验收,按用户授权合入main并push origin/main;保留5173/5174,未自动启动下一任务。
|
||||
+7
-1
@@ -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,9 @@ 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 零拖放实现,不提供。
|
||||
|
||||
HD09-R1:自然行/标题测量、类型保真尺寸缓存和滚动绑定为本库Vue适配;ListBox复用同一useVirtualRows几何,保留既有集合选择/焦点模型,不引入React状态或第二套全局协议。Table原生th/td的padding最小高度与42px虚拟行冲突已证实,新增TableRow.height内容盒适配,不改变非虚拟表格默认DOM。TableLayout headingHeight对应常驻表头,按真实tbody原点处理,纠正原“无分区表头模型所以不提供”的解释。
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
/** 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 {
|
||||
count: MaybeRefOrGetter<number>;
|
||||
/** 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;
|
||||
estimatedRowHeight?: number | ((index: number) => number);
|
||||
loaderHeight?: number;
|
||||
gap?: number;
|
||||
padding?: number;
|
||||
overscan?: number;
|
||||
}
|
||||
export interface VirtualRowWindow {
|
||||
start: number;
|
||||
end: number;
|
||||
padTop: number;
|
||||
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>;
|
||||
rowOffsetOf: (index: number) => number;
|
||||
rowExtentOf: (index: number) => number;
|
||||
totalHeight: ComputedRef<number>;
|
||||
update: (scrollTop: number, viewportHeight: number) => void;
|
||||
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 state = shallowRef({ scrollTop: 0, viewport: 0 });
|
||||
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 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 = rawHeight(i);
|
||||
top += positive(raw ?? sizes.value.get(keyAt(i)), estimate(i));
|
||||
if (i < count - 1) top += gap;
|
||||
}
|
||||
offsets[count] = top;
|
||||
return {
|
||||
count,
|
||||
offsets,
|
||||
pad,
|
||||
loaderSpan: loader > 0 ? loader + (count ? gap : 0) : 0,
|
||||
};
|
||||
});
|
||||
const rowOffsetOf = (index: number) =>
|
||||
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(
|
||||
() =>
|
||||
rowOffsetOf(geometry.value.count) +
|
||||
geometry.value.loaderSpan +
|
||||
geometry.value.pad,
|
||||
);
|
||||
function firstAt(top: number) {
|
||||
const { count, offsets } = geometry.value;
|
||||
let lo = 0,
|
||||
hi = count;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (offsets[mid + 1]! <= top) lo = mid + 1;
|
||||
else hi = 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;
|
||||
}
|
||||
// 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,
|
||||
padTop: rowOffsetOf(start),
|
||||
padBottom: Math.max(0, totalHeight.value - rowOffsetOf(end)),
|
||||
};
|
||||
});
|
||||
function update(scrollTop: number, viewportHeight: number) {
|
||||
const top = nonnegative(scrollTop),
|
||||
viewport = nonnegative(viewportHeight);
|
||||
if (state.value.scrollTop !== top || state.value.viewport !== viewport)
|
||||
state.value = { scrollTop: top, viewport };
|
||||
}
|
||||
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;
|
||||
if (pendingTarget?.element === element)
|
||||
pendingTarget.scrollTop = element.scrollTop;
|
||||
if (b) b.measure();
|
||||
else update(element.scrollTop, element.clientHeight);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** Bind a real scroll viewport and the row stream's actual origin. */
|
||||
export function bindVirtualRows(
|
||||
rows: UseVirtualRows,
|
||||
element: HTMLElement,
|
||||
options: VirtualRowsBindingOptions = {},
|
||||
): () => void {
|
||||
return binders.get(rows)!(element, options);
|
||||
}
|
||||
@@ -8,19 +8,24 @@ import {
|
||||
onBeforeUpdate,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useAttrs,
|
||||
useSlots,
|
||||
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";
|
||||
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
|
||||
import { useCollectionSelection } from "../collection/selection";
|
||||
import { useCollectionRegistry } from "../collection/registry";
|
||||
import { collectionOwnerKey } from "../collection/owner";
|
||||
import { assertKey } from "../collection/keys";
|
||||
import { assertKey, encodeKey } from "../collection/keys";
|
||||
import {
|
||||
listBoxKey,
|
||||
type ListBoxDataItem,
|
||||
@@ -37,6 +42,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 +71,10 @@ const emit = defineEmits<{
|
||||
defineSlots<{
|
||||
default?: (props: { item: T; index: number }) => unknown;
|
||||
empty?: () => unknown;
|
||||
loader?: () => unknown;
|
||||
}>();
|
||||
const slots = useSlots();
|
||||
const hasLoader = ref(Boolean(slots.loader));
|
||||
const attrs = useAttrs();
|
||||
const instance = getCurrentInstance()!;
|
||||
const modelPresence = () =>
|
||||
@@ -76,6 +88,7 @@ const selectedPresence = () =>
|
||||
const controlled = ref(modelPresence() || selectedPresence());
|
||||
const hasModel = ref(modelPresence());
|
||||
onBeforeUpdate(() => {
|
||||
hasLoader.value = Boolean(slots.loader);
|
||||
hasModel.value = modelPresence();
|
||||
controlled.value = hasModel.value || selectedPresence();
|
||||
});
|
||||
@@ -231,18 +244,178 @@ const visibleItems = computed(() => {
|
||||
return items.filter((item) => visible.has(item.id));
|
||||
});
|
||||
const source = computed(() => visibleItems.value);
|
||||
// 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(source, {
|
||||
itemHeight: () => props.rowHeight,
|
||||
overscan: props.overscan,
|
||||
/**
|
||||
* 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; 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 rows: VirtualRow[] = [];
|
||||
const push = (row: VirtualRow) => {
|
||||
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, gap: 0 });
|
||||
source.value.forEach((item, index) => {
|
||||
if (item.heading)
|
||||
push({
|
||||
key: `heading-${encodeKey(item.id)}`,
|
||||
kind: "heading",
|
||||
height:
|
||||
typeof props.headingHeight === "function"
|
||||
? props.headingHeight(index)
|
||||
: props.headingHeight,
|
||||
estimate: props.estimatedHeadingHeight ?? 48,
|
||||
text: item.heading,
|
||||
gap: 0,
|
||||
});
|
||||
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 (hasLoader.value && 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, gap: 0 });
|
||||
return rows;
|
||||
});
|
||||
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,
|
||||
);
|
||||
}
|
||||
const root = shallowRef<HTMLElement | null>(null);
|
||||
const virtualContent = shallowRef<HTMLElement | null>(null);
|
||||
function resolveScrollParent() {
|
||||
const el = root.value;
|
||||
if (!el) return null;
|
||||
// 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;
|
||||
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;
|
||||
}
|
||||
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(() => {
|
||||
detachVirtual?.();
|
||||
scrollParent = null;
|
||||
});
|
||||
const root = containerProps.ref;
|
||||
let restoringFocus = false;
|
||||
function restoreFocus() {
|
||||
restoringFocus = true;
|
||||
@@ -282,8 +455,10 @@ async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
|
||||
}
|
||||
/**
|
||||
* 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,16 +467,10 @@ 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;
|
||||
if (
|
||||
element &&
|
||||
(rowTop < element.scrollTop ||
|
||||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
|
||||
) {
|
||||
if (!valid()) return;
|
||||
scrollTo(index);
|
||||
}
|
||||
const rowIndex = rowIndexOfItem(index);
|
||||
if (rowIndex < 0) return;
|
||||
const element = scrollParent ?? root.value;
|
||||
if (element && valid()) virtualLayout.scrollToIndex(element, rowIndex);
|
||||
await waitForMountedRow(key, valid);
|
||||
return;
|
||||
}
|
||||
@@ -455,14 +624,36 @@ 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;
|
||||
const page = Math.max(
|
||||
? activeHeight
|
||||
: current?.getBoundingClientRect().height || activeHeight;
|
||||
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) {
|
||||
@@ -590,7 +781,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 +803,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 +841,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({
|
||||
@@ -668,17 +865,35 @@ 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"
|
||||
>
|
||||
<div
|
||||
v-for="entry in windowItems"
|
||||
:key="entry.data.id"
|
||||
:key="entry.data.key"
|
||||
role="presentation"
|
||||
:style="{ height: `${rowHeight}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',
|
||||
}"
|
||||
>
|
||||
<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,25 @@ 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 | ((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). */
|
||||
gap?: number;
|
||||
/** List padding in px rendered as spacer rows at both ends. */
|
||||
padding?: number;
|
||||
overscan?: number;
|
||||
}
|
||||
export interface ListBoxItemState {
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -456,6 +456,20 @@ 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,
|
||||
type VirtualRowsBindingOptions,
|
||||
} from "./components/collection/virtual-rows";
|
||||
export type { ConfigProviderProps } from "./types";
|
||||
|
||||
export { default as Modal } from "./components/modal/Modal";
|
||||
|
||||
Vendored
+394
@@ -0,0 +1,394 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
onMounted,
|
||||
onUnmounted,
|
||||
ref,
|
||||
type PropType,
|
||||
} 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);
|
||||
const estimatedRows = ref(false);
|
||||
const resolvedRowHeight = (index: number) =>
|
||||
estimatedRows.value ? undefined : rowHeight(index);
|
||||
const mixedItems = ref([
|
||||
{ id: 0, textValue: "数字零" },
|
||||
{ id: "0", textValue: "字符串零" },
|
||||
]);
|
||||
const delayedItems = ref<{ id: number; textValue: string }[]>([]);
|
||||
const StatefulItem = defineComponent({
|
||||
props: {
|
||||
item: {
|
||||
type: Object as PropType<{ id: string | number; textValue: string }>,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
setup(props) {
|
||||
const born = `${typeof props.item.id}:${props.item.id}`;
|
||||
return () =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{ id: props.item.id, textValue: props.item.textValue },
|
||||
() => `当前 ${typeof props.item.id}:${props.item.id} / 创建时 ${born}`,
|
||||
);
|
||||
},
|
||||
});
|
||||
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 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,
|
||||
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, {
|
||||
content: element.querySelector("tbody") ?? undefined,
|
||||
});
|
||||
});
|
||||
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>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
@click="estimatedRows = !estimatedRows"
|
||||
>
|
||||
切换未知行高
|
||||
</Button>
|
||||
</div>
|
||||
<ListBox
|
||||
id="virtual-listbox"
|
||||
ref="listboxRef"
|
||||
:items="filteredItems"
|
||||
v-model="selected"
|
||||
selection-mode="multiple"
|
||||
virtualized
|
||||
:row-height="resolvedRowHeight"
|
||||
:estimated-row-height="fallbackRow"
|
||||
:heading-height="estimatedRows ? () => undefined : headingHeight"
|
||||
:estimated-heading-height="32"
|
||||
: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: estimatedRows ? 'auto' : '100%' }"
|
||||
>
|
||||
<div style="display: flex; flex-direction: column">
|
||||
<Label>{{ item.textValue }}</Label>
|
||||
<Description>高度随索引变化</Description>
|
||||
<Description v-if="estimatedRows">
|
||||
{{ "这是一段需要自动换行的未知高度内容。".repeat(6) }}
|
||||
</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>
|
||||
<h2>不同类型 key 的局部状态</h2>
|
||||
<Button @click="mixedItems = [...mixedItems].reverse()">
|
||||
反转零标识
|
||||
</Button>
|
||||
<ListBox
|
||||
:items="mixedItems"
|
||||
virtualized
|
||||
:row-height="50"
|
||||
:overscan="5"
|
||||
style="height: 160px; overflow-y: auto"
|
||||
aria-label="零标识列表"
|
||||
>
|
||||
<template #default="{ item }"><StatefulItem :item="item" /></template>
|
||||
</ListBox>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<Button
|
||||
@click="
|
||||
delayedItems = Array.from({ length: 200 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
textValue: `延后条目 ${i + 1}`,
|
||||
}))
|
||||
"
|
||||
>
|
||||
加载父容器列表
|
||||
</Button>
|
||||
<div
|
||||
data-probe-late-viewport
|
||||
style="height: 200px; width: 320px; overflow-y: auto"
|
||||
>
|
||||
<div style="height: 48px; position: sticky; top: 0">固定搜索区域</div>
|
||||
<ListBox
|
||||
:items="delayedItems"
|
||||
virtualized
|
||||
:row-height="50"
|
||||
aria-label="延后加载列表"
|
||||
>
|
||||
<template #default="{ item }">
|
||||
<ListBoxItem
|
||||
:id="item.id"
|
||||
:text-value="item.textValue"
|
||||
style="height: 50px"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</ListBoxItem>
|
||||
</template>
|
||||
</ListBox>
|
||||
</div>
|
||||
</section>
|
||||
<section style="display: grid; gap: 8px">
|
||||
<h2>表格虚拟窗口(useVirtualRows)</h2>
|
||||
<div style="display: flex; gap: 8px">
|
||||
<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
|
||||
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: `${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">
|
||||
名称
|
||||
</TableColumn>
|
||||
<TableColumn id="info" :min-width="200">说明</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<tr
|
||||
aria-hidden="true"
|
||||
:style="{ height: tableWindow.padTop + 'px' }"
|
||||
/>
|
||||
<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>
|
||||
</TableScrollContainer>
|
||||
</Table>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
@@ -259,6 +259,10 @@
|
||||
"data-exiting"
|
||||
]
|
||||
},
|
||||
"virtual-rows": {
|
||||
"exports": ["useVirtualRows", "bindVirtualRows", "TableRow"],
|
||||
"css": ["data-virtualized", "[data-slot=list-box][data-virtualized]", "hv-table__fixed-cell-content"]
|
||||
},
|
||||
"list-box": {
|
||||
"exports": [
|
||||
"ListBox",
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
bindVirtualRows,
|
||||
useVirtualRows,
|
||||
type ListBoxDataItem,
|
||||
type ListBoxProps,
|
||||
type UseVirtualRows,
|
||||
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 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 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
|
||||
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: () => undefined,
|
||||
estimatedHeadingHeight: 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,
|
||||
];
|
||||
|
||||
// @ts-expect-error Native row height uses px numbers
|
||||
const badTableRow: TableRowProps = { rowKey: 1, height: "42px" };
|
||||
void badTableRow;
|
||||
@@ -0,0 +1,436 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref, type PropType } from "vue";
|
||||
import {
|
||||
ListBox,
|
||||
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";
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
it("review: numeric and string keys preserve local row identity on reorder", async () => {
|
||||
const Stateful = defineComponent({
|
||||
props: {
|
||||
item: {
|
||||
type: Object as PropType<{ id: string | number }>,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
setup(props) {
|
||||
const born = `${typeof props.item.id}:${props.item.id}`;
|
||||
return () =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{ id: props.item.id },
|
||||
() => `${typeof props.item.id}:${props.item.id}/${born}`,
|
||||
);
|
||||
},
|
||||
});
|
||||
const items = [{ id: 0 }, { id: "0" }];
|
||||
const w = mount(ListBox, {
|
||||
props: { items, virtualized: true, rowHeight: 50 },
|
||||
slots: {
|
||||
default: ({ item }: { item: { id: string | number } }) =>
|
||||
h(Stateful, { item }),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
await w.setProps({ items: [...items].reverse() });
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(w.findAll('[role="option"]').map((x) => x.text())).toEqual([
|
||||
"string:0/string:0",
|
||||
"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");
|
||||
});
|
||||
|
||||
it("removes a conditional loader reservation without changing the items", async () => {
|
||||
const show = ref(true);
|
||||
const items = [{ id: 1, textValue: "One" }];
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(
|
||||
ListBox,
|
||||
{ items, virtualized: true, overscan: 20 },
|
||||
{
|
||||
default: ({ item }: { item: (typeof items)[number] }) =>
|
||||
h(ListBoxItem, { id: item.id }, () => item.textValue),
|
||||
...(show.value ? { loader: () => h("span", "Loading") } : {}),
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(rowWrappers()).toHaveLength(2);
|
||||
show.value = false;
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(rowWrappers()).toHaveLength(1);
|
||||
});
|
||||
Reference in New Issue
Block a user