Compare commits

...

15 Commits

Author SHA1 Message Date
maoyingjie 2eb787a0bb docs: accept HD-09 measured virtual layout and R1 verification 2026-10-29 17:17:44 +08:00
maoyingjie 6d9e3f31cf fix(list-box): update conditional virtual loader reservations 2026-10-29 17:15:30 +08:00
maoyingjie 5a00e25a25 fix(virtualization): measure natural rows and align viewport geometry 2026-10-29 17:13:12 +08:00
maoyingjie 9f7eb1fa8d docs: record HD-09 review blockers and R1 repair requirements 2026-10-29 16:37:36 +08:00
maoyingjie ae27fb28d1 fix(list-box): preserve typed virtual keys and add HD-09 review repros 2026-10-29 16:36:02 +08:00
maoyingjie ee37e66d37 docs: record HD-09 virtual layout results and layout mapping
Results table with geometry evidence (row heights, visible rows, scroll
sizes against the pinned demos), the native-table scroll-container
verdict, tarball contract extension and the recorded gaps
(estimatedHeadingHeight, dropIndicatorThickness, popover height clamp).
2026-10-29 16:22:46 +08:00
maoyingjie 9e8d89e48d feat(collections): virtual row layout with variable heights, headings, loader and gap/padding
ListBox virtualized mode grows a full row stream (padding spacers, data-driven
heading rows, item rows, #loader row) with px semantics mapped from the pinned
ListLayout contract: rowHeight may be a per-index function falling back to
estimatedRowHeight, gap sits between content rows only, padding is end
spacers, and every input is re-read per layout pass. Scroll ownership resolves
to the list root or the nearest scrolling ancestor so popovers scroll as a
whole with a sticky search field (data-virtualized hook; the historical 320px
self-scroll rule stays for non-virtualized lists).

Table gains the public useVirtualRows/bindVirtualRows pure geometry helpers
(prefix sums + binary search, no state kernel): variable heights, estimated
fallback, gap/padding and a loader reservation that stays consistent with the
rendered spacers. headingHeight and dropIndicatorThickness remain unavailable
(no sectioned header model, no drag-and-drop) and are recorded as such.

Pinned demo values stay explicit (table 42px, list-box/autocomplete 50px);
the table demo scrolls an outer viewport div because a native table cannot be
a scroll container (verified: 300px height blown out to 45036px).
2026-10-29 16:21:09 +08:00
maoyingjie dd4f04c200 Merge header hover parity fixes into main 2026-10-29 15:02:43 +08:00
maoyingjie aa881d21d5 docs: accept HD-10 collections review and submenu fixes 2026-10-29 14:47:56 +08:00
maoyingjie bf6cf0f8d1 fix(dropdown): preserve disabled and click semantics during submenu delays 2026-10-29 14:45:59 +08:00
maoyingjie d1528569a8 docs: record HD-10 collections loading, filtering and submenu results 2026-10-29 13:46:48 +08:00
maoyingjie c8d54abefb feat(collections): auto incremental async loading, shared filtering and submenu delay
HD-10 scope, against heroui ce90ea3 collection sources and their
react-aria/react-stately dependencies:

- the ComboBox async demo now auto-loads on scroll-to-bottom
  (IntersectionObserver sentinel + fill chain mirroring the pinned
  ListBoxLoadMoreItem re-observe semantics), never duplicates requests
  (loading guards + monotonic sequence token), drops stale responses on
  query switches, keeps a retry path for failures (injectable mock
  failure) and documents its differences from the pinned SWAPI source;
  the Select demo's observer stays untouched (real-network scroll
  triggering verified in browser)
- the Autocomplete virtualization demo and the default filter share one
  locale-sensitive matcher: createBaseContains (Intl.Collator base
  sensitivity, cafe matches Cafe with accent folding) is now exported
  from the package root
- Autocomplete trigger semantics verified complete (single tab stop,
  Enter/Space/Escape/Delete/IME, single and multiple selection) and the
  scoped slots gained composition data instead of child copying:
  AutocompleteValue exposes selectedItem and per-entry source item,
  the ComboBox root exposes selectedItem
- DropdownSubmenuTrigger exposes the pinned delay contract (default
  200ms): the controlled open gate retimes Reka's fixed 100ms hover,
  keyboard opens stay immediate and cancel the pending hover, pointer
  leave cancels; the dead side/align forwarding is gone (Reka fixes the
  submenu side per direction); Button/Avatar trigger layout
  compensation kept after browser proof it is what wins the cascade
- tests/fixtures/collections-rtl.vue drives the real-browser delay and
  RTL geometry checks; b02-pickers contract pins the new export and
  slot typing

Full suite 111 files / 1666 tests, typecheck, build:docs and the
b02-pickers + api-root-aliases tarball contracts pass.
2026-10-29 13:46:34 +08:00
maoyingjie 4bfc2ef170 docs: record corrected reference hover verification 2026-10-28 08:49:27 +08:00
maoyingjie 652cf854be fix(docs): match reference navigation and search hover colors 2026-10-28 08:49:11 +08:00
maoyingjie 28b0b3f0b6 docs: clarify reference header hover behavior 2026-10-28 08:48:35 +08:00
45 changed files with 2974 additions and 248 deletions
+13 -5
View File
@@ -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;
}
+5 -3
View File
@@ -162,7 +162,7 @@ Autocomplete 组件支持两种视觉变体:
::: warning
多选模式下,上游 `Autocomplete.Value` 会把每个选中项在 `ListBox.Item` 中的 children 复制到触发器中,并以符合当前语言环境的分隔符连接:仅包含文本的选项显示为纯文本,但复选框、头像等可见内容会随每个选中项各出现一次;函数形式的 children 也始终以 `isSelected: false` 调用。
本库不复制子树,而是给 `AutocompleteValue` 的作用域插槽提供 `selectedItems`(`{ key, textValue }[]`)与 `selectedText`(纯文本),因此不存在上述重复渲染问题,但函数形式的插槽同样不携带 `isSelected`。
本库不复制子树,而是给 `AutocompleteValue` 的作用域插槽提供 `selectedItems`(`{ key, textValue, item? }[]`,`item` 为根 `items` 中的源数据项)、`selectedItem`(首个选中项)与 `selectedText`(纯文本),调用方可直接用源数据组合头像、可移除标签等丰富展示,因此不存在上述重复渲染问题,但函数形式的插槽同样不携带 `isSelected`。
:::
如需以纯文本显示选中值,请使用 `selectedText`:
@@ -437,15 +437,17 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| `isPlaceholder` | `boolean` | 是否没有选中项 |
| `defaultChildren` | `string`(上游为 `ReactNode`) | 缺省文本(选中项文本以逗号连接,否则占位符) |
| `selectedText` | `string` | 选中项 `textValue` 的连接文本 |
| `selectedItems` | `Array<{ key, textValue }>` | 选中项 |
| `selectedItems` | `Array<{ key, textValue, item? }>` | 选中项;`item` 为根 `items` 中的源数据项(集合自发现的项没有) |
| `selectedItem` | `{ key, textValue, item? } \| null` | 首个选中项(单选即所选项),便于单选组合 |
上游 `state.selectedItems`(节点)在本库中是上表的 `selectedItems`(数据);不复制 item 子树,见「多选」说明。
上游 `state.selectedItems`(节点)在本库中是上表的 `selectedItems`(数据,条目携带源数据 `item`);不复制 item 子树,见「多选」说明。
### 过滤函数(`useFilter` 替代)
上游页面导出的 `useFilter` hook(`contains` / `startsWith` / `endsWith` 与 `sensitivity`)在本库没有对应导出。替代方式:
- `AutocompleteFilter` 的默认谓词等价于 `useFilter({ sensitivity: "base" }).contains`:按 `ConfigProvider` 的 locale 折叠大小写与变音符号,`cafe` 能命中 `Café`
- 调用方自行过滤数据时(虚拟化、异步数据源),可从包根导入 `createBaseContains`(与默认谓词同一实现)保持语义一致:`const { locale } = useLocale(); const contains = createBaseContains(locale.value)`
- 需要 `startsWith` / `endsWith` 等语义时,直接给 `:filter="(text, input) => …"` 传函数
- 数据源或调用方已过滤时(异步、虚拟化示例),传 `:filter="() => true"` 避免二次过滤
+5 -3
View File
@@ -133,6 +133,8 @@ import {
<ComponentPreview name="combo-box-asynchronous-loading" />
示例的本地数据源模拟固定源的 SWAPI 请求状态机(搜索过滤、游标分页、加载中、滚动到底自动增量加载、取消旧请求与过期响应保护、失败重试);与 SWAPI 的差异是数据为固定 12 条本地角色、延迟为模拟值,失败由「模拟加载失败」开关注入。加载行位于 ListBox 之外(固定源为 `ListBoxLoadMoreItem` 行内哨兵),自动触发语义一致。
### 默认选中项
<ComponentPreview name="combo-box-default-selected-key" />
@@ -314,7 +316,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| `placeholder` | `string` | `'Select an item'` | `ComboBoxValue` 的缺省占位文本(上游根上没有该 prop,由 `ComboBoxValue` 的 placeholder 表达) |
| `as` | `string` | `'div'` | 自定义根元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 |
| 默认插槽 | `{ isOpen, inputValue, selectedKey, selectedKeys }` | - | 组件内容;作用域提供当前状态 |
| 默认插槽 | `{ isOpen, inputValue, selectedKey, selectedKeys, selectedItem }` | - | 组件内容;作用域提供当前状态 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
事件:
@@ -334,7 +336,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### 作用域插槽与渲染状态
默认插槽提供 `{ isOpen, inputValue, selectedKey, selectedKeys }`。上游的 `Render Props` 表格里还有 `state` 与 `selectedItem`:本库不暴露 React Aria 的 state 对象,选中项数据可从 `records`/`selectedKeys` 派生(示例见 `@update:model-value` 与 `ComboBoxValue` 的作用域插槽),该差异不另设等价 prop。
默认插槽提供 `{ isOpen, inputValue, selectedKey, selectedKeys, selectedItem }`。上游的 `Render Props` 表格里还有 `state` 与 `selectedItem`:`selectedItem` 以作用域数据补齐(根 `items` 中与单选 key 匹配的源数据项;多选或自定义值时为 `null`,`ComboBoxValue` 的 `selectedItems` 条目也携带同源 `item`),调用方可直接用自己的数据对象组合展示,无需按键反查;本库不暴露 React Aria 的 state 对象,该差异不另设等价 prop。
### ComboBoxInputGroup
@@ -350,7 +352,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| Prop | 类型 | 默认值 | 描述 |
| ------------- | ---------------------------------- | -------------------- | ----------------------------- |
| `placeholder` | `string`(上游为 `ReactNode`) | 根上的 `placeholder` | 未选中任何项时的占位文本 |
| 默认插槽 | `{ isPlaceholder, selectedItems }` | - | 自定义已选值展示 |
| 默认插槽 | `{ isPlaceholder, selectedItems }` | - | 自定义已选值展示;`selectedItems` 条目为 `{ key, textValue, item? }`(`item` 为根 `items` 中的源数据项) |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
### ComboBoxTrigger
+2 -1
View File
@@ -370,6 +370,7 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类
| Slots / Props | 说明 |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 默认插槽 | 第一个子节点是触发条目,其余子节点渲染进子菜单内容 |
| `delay` | 悬停展开延迟(毫秒),默认 `200`(与固定源 `useSubmenuTrigger` 一致);键盘展开立即生效并取消挂起的悬停展开,指针离开取消 |
| `class`/ARIA | 合并到触发条目元素上 |
| 面板参数 | 嵌套 `DropdownPopover` 的 `offset`/`crossOffset`/`shouldFlip`/`containerPadding`/`loop`/`to`、`class`/`style`/`id`/`data-*`/ARIA 与事件都会传给子菜单面板;`isKeyboardDismissDisabled` 为真时 Esc 既不关子层也不关父层,`shouldCloseOnInteractOutside` 返回 `false` 时外部交互不关闭 |
@@ -408,7 +409,7 @@ Dropdown 组件实现 ARIA 菜单模式,并提供:
- 部件导出为具名组件(`DropdownRoot` / `DropdownTrigger` / …),触发器需要显式包裹,官方是把 `Button` 直接放在 `Dropdown` 下。
- `Selection`/`Set` 改为 `MenuKey[]`;`onAction`/`onSelectionChange`/`onClose` 改为 Vue 事件;`isOpen`/`onOpenChange` 改为 `open` + `v-model:open`。
- 官方 `items` + 渲染函数的数据驱动集合用 `v-for` 表达;`renderEmptyState` 对应 `empty` 插槽。不提供 React Collection 对象模型。
- 子菜单悬停展开延迟由底层固定为 100ms,未暴露官方 `delay`(默认 200ms);子菜单面板的 `side`/`align` 由底层固定,只有偏移与碰撞参数可调。
- 子菜单悬停展开延迟由 `DropdownSubmenuTrigger` 的 `delay` 配置(默认 200ms,与固定源 `useSubmenuTrigger` 一致):底层 Reka 的固定 100ms 悬停计时被重定为该延迟,键盘展开立即生效并取消挂起的悬停展开,指针离开取消;子菜单面板的 `side`/`align` 由底层固定(贴父项向右、RTL 反向),只有偏移与碰撞参数可调。
- `DropdownTrigger` 的作用域插槽只提供 `{ isOpen }`,`DropdownPopover` 只提供 `{ isEntering, isExiting, placement }`;官方 Button/Popover 的完整 render props 未全部覆盖。
- `DropdownRoot` 额外渲染一层 `.hv-dropdown` 包裹元素(官方该类没有 DOM 宿主),承载根级 class、style、id、ARIA、data 属性与原生事件。作为 `ButtonGroup` 直接子级时仍保留该容器,接缝样式按容器在组内的位置适配内部触发按钮;根级属性与捕获事件的行为不变。
- 条目 `id` 是业务 key,DOM id 为实例级;官方把 key 直接作为 DOM id(Vue 端避免数字 `0` 与字符串 `"0"` 冲突)。
+36 -5
View File
@@ -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` 可响应式更新。
+32 -2
View File
@@ -96,7 +96,7 @@ import {
### 虚拟滚动
仅渲染视口内可见行,从而高效展示大数据集。本库使用固定行高窗口替代 React Aria `Virtualizer`。
仅渲染视口内可见行,从而高效展示大数据集。本库以 `useVirtualRows` 行几何组合式替代 React Aria `Virtualizer`,支持固定与可变行高、`gap` / `padding` 与加载行预留(见下文 TableLayout 映射)。示例保留基线的 42px 显式行高、300px 视口与外层滚动容器:原生 `<table>` 不能作为滚动容器(`height` 是最小高度且 `overflow` 需要确定高度,实测 300px 被内容撑到 45036px),而固定源滚动的是虚拟网格元素;列宽用 `minWidth`(fr 语义由 TableContent 列布局承担),长文本按列宽截断。
<ComponentPreview name="table-virtualization" minHeight="380px" />
@@ -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 中,以随组件清理测量观察器。
@@ -9,6 +9,7 @@ import {
AutocompletePopover,
AutocompleteTrigger,
AutocompleteValue,
createBaseContains,
Description,
EmptyState,
Label,
@@ -20,6 +21,7 @@ import {
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
useLocale,
type ListBoxKey,
} from "@heroui-vue/components";
@@ -97,15 +99,19 @@ const allUsers = generateUsers(1000);
const selectedKey = ref<ListBoxKey | null>(null);
const searchQuery = ref("");
// 与 AutocompleteFilter 默认谓词共用同一实现(locale 敏感、大小写与变音折叠,
// 例如 cafe 能匹配 Café);本示例自行过滤以驱动虚拟滚动,故关闭集合二次过滤。
const { locale } = useLocale();
const contains = computed(() => createBaseContains(locale.value));
const filteredUsers = computed(() => {
const query = searchQuery.value.trim().toLocaleLowerCase();
const query = searchQuery.value.trim();
if (!query) return allUsers;
return allUsers.filter(
(user) =>
user.name.toLocaleLowerCase().includes(query) ||
user.email.toLocaleLowerCase().includes(query),
contains.value(user.name, query) || contains.value(user.email, query),
);
});
@@ -150,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">
@@ -1,6 +1,11 @@
<!-- 适配:源示例请求 SWAPI,这里用本地异步源演示相同状态(取消旧请求、加载中、增量加载)。 -->
<!-- 适配说明:固定源此例请求 SWAPI(swapi.py4e.com/api/people,useAsyncList 游标分页 + 行内 ListBoxLoadMoreItem 哨兵)。
本示例改用本地异步源模拟同一状态机:搜索过滤、游标分页、加载中、滚动到底自动增量加载、
取消旧请求与过期响应保护、失败重试。与 SWAPI 的差异:数据为固定 12 条本地角色(非 82 条远端人员),
网络延迟为固定 300ms 模拟(不可观测 DNS/网络错误),失败由「模拟加载失败」开关注入。
加载行位于 ListBox 之外(基线为 ListBoxLoadMoreItem 的行内加载行),自动触发语义一致。 -->
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import { useIntersectionObserver } from "@vueuse/core";
import {
Button,
ComboBox,
@@ -39,12 +44,18 @@ const characters: Character[] = [
{ id: "Boba Fett", name: "Boba Fett" },
];
const simulateFailure = ref(false);
const inputValue = ref("");
const items = ref<Character[]>([]);
const loading = ref(false);
const loadingMore = ref(false);
const error = ref(false);
const hasMore = ref(false);
const sentinel = ref<HTMLElement>();
const sentinelVisible = ref(false);
let controller: AbortController | undefined;
/** Monotonic request token: stale responses are dropped even without abort. */
let sequence = 0;
function matches(query: string) {
const text = query.trim().toLocaleLowerCase();
@@ -54,39 +65,53 @@ function matches(query: string) {
);
}
function mockPage(query: string, offset: number, signal: AbortSignal) {
return new Promise<Character[]>((resolve, reject) => {
const timer = setTimeout(() => {
if (simulateFailure.value) {
reject(new Error("模拟加载失败"));
return;
}
resolve(matches(query).slice(offset, offset + PAGE_SIZE));
}, PAGE_DELAY);
signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true },
);
});
}
async function load(query: string, offset: number, append: boolean) {
controller?.abort();
const current = new AbortController();
const token = ++sequence;
controller = current;
error.value = false;
if (append) loadingMore.value = true;
else loading.value = true;
try {
const page = await new Promise<Character[]>((resolve, reject) => {
const timer = setTimeout(() => {
resolve(matches(query).slice(offset, offset + PAGE_SIZE));
}, PAGE_DELAY);
const page = await mockPage(query, offset, current.signal);
current.signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true },
);
});
if (current.signal.aborted) return;
// A newer request superseded this one: drop the stale response.
if (current.signal.aborted || token !== sequence) return;
items.value = append ? [...items.value, ...page] : page;
hasMore.value = offset + page.length < matches(query).length;
} catch {
if (current.signal.aborted) return;
if (current.signal.aborted || token !== sequence) return;
items.value = [];
hasMore.value = false;
error.value = true;
if (!append) {
items.value = [];
hasMore.value = false;
}
} finally {
// A newer request owns the flags once it has taken over the controller.
if (controller === current) {
@@ -94,6 +119,11 @@ async function load(query: string, offset: number, append: boolean) {
loadingMore.value = false;
}
}
// Chain-fill: the fresh page may leave the sentinel inside the viewport, in
// which case scrolling is not needed to request the next one.
if (sentinelVisible.value && hasMore.value && !error.value)
queueMicrotask(() => maybeLoadMore());
}
function handleInputChange(next: string) {
@@ -101,11 +131,25 @@ function handleInputChange(next: string) {
void load(next, 0, false);
}
function loadMore() {
if (loading.value || loadingMore.value || !hasMore.value) return;
function maybeLoadMore() {
if (loading.value || loadingMore.value || error.value || !hasMore.value) return;
void load(inputValue.value, items.value.length, true);
}
function retry() {
if (loading.value || loadingMore.value) return;
void load(inputValue.value, items.value.length, items.value.length > 0);
}
// Scroll-to-bottom auto incremental loading: the sentinel drives the loads and
// in-flight requests are never duplicated. When a fresh page does not push the
// sentinel out of view, the load chain keeps filling (the pinned
// ListBoxLoadMoreItem re-observes per collection change for the same effect).
useIntersectionObserver(sentinel, ([entry]) => {
sentinelVisible.value = !!entry?.isIntersecting;
if (entry?.isIntersecting) maybeLoadMore();
});
onMounted(() => {
void load(inputValue.value, 0, false);
});
@@ -116,41 +160,50 @@ onBeforeUnmount(() => {
</script>
<template>
<ComboBox
allows-empty-collection
class="w-[256px]"
:input-value="inputValue"
@input-change="handleInputChange"
>
<Label>选择角色</Label>
<ComboBoxInputGroup>
<Input placeholder="星球大战角色…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox :aria-busy="loading || undefined">
<ListBoxItem
v-for="item in items"
:id="item.id"
:key="item.id"
:text-value="item.name"
<div class="flex flex-col gap-2">
<ComboBox
allows-empty-collection
class="w-[256px]"
:input-value="inputValue"
@input-change="handleInputChange"
>
<Label>选择角色</Label>
<ComboBoxInputGroup>
<Input placeholder="星球大战角色…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover class="max-h-80">
<ListBox :aria-busy="loading || undefined">
<ListBoxItem
v-for="item in items"
:id="item.id"
:key="item.id"
:text-value="item.name"
>
{{ item.name }}
<ListBoxItemIndicator />
</ListBoxItem>
<template #empty>
<EmptyState />
</template>
</ListBox>
<div ref="sentinel" aria-hidden="true" class="h-px" />
<div
v-if="loadingMore || error"
class="flex items-center justify-center gap-2 py-2"
role="status"
>
{{ item.name }}
<ListBoxItemIndicator />
</ListBoxItem>
<template #empty>
<EmptyState />
</template>
</ListBox>
<div v-if="hasMore" class="flex items-center justify-center gap-2 py-2">
<template v-if="loadingMore">
<Spinner size="sm" />
<span class="text-sm text-muted" role="status">加载更多…</span>
</template>
<Button v-else variant="ghost" size="sm" @click="loadMore">
加载更多…
</Button>
</div>
</ComboBoxPopover>
</ComboBox>
<template v-if="loadingMore">
<Spinner size="sm" />
<span class="text-sm text-muted">加载更多…</span>
</template>
<Button v-else variant="ghost" size="sm" @click="retry">重试</Button>
</div>
</ComboBoxPopover>
</ComboBox>
<label class="flex items-center gap-2 text-sm text-muted">
<input v-model="simulateFailure" type="checkbox" />
模拟加载失败(本地数据源注入;SWAPI 场景为真实网络错误)
</label>
</div>
</template>
+72 -80
View File
@@ -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>
+14
View File
@@ -24,6 +24,20 @@ const labs = [
() => import("../../../tests/fixtures/table-layout.vue"),
),
},
{
key: "collections-rtl",
title: "子菜单延迟与 RTL 定位",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/collections-rtl.vue"),
),
},
{
key: "virtual-rows",
title: "虚拟行布局(变高/分组/加载行)",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/virtual-rows.vue"),
),
},
{
key: "button-group-dropdown",
title: "按钮组与下拉根属性",
+14 -3
View File
@@ -72,7 +72,7 @@
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 |
| input-otp | 验证中(M32) | Root/Group/Slot/Separator + 3 正则常量;Reka PinInput 底座;字符串+索引数组;reset/Fieldset/Form/ARIA/mask 已接入;11/11 例;自动填充/IME/读屏未真机验证 |
| alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default |
| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项固定行高虚拟化;差异见 LISTBOX-01 |
| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项虚拟化(固定/可变行高、数据驱动分组标题、#loader 加载行、gap/padding、滚动父级探测);拖放布局未支持故无 dropIndicatorThickness;差异见 LISTBOX-01 与 HD-09 |
| list-box-item | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| list-box-section | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| dropdown | 验证中(B01) | Root/Trigger/Popover/Menu/Section/Item/ItemIndicator/SubmenuIndicator/SubmenuTrigger;17/17 基线例;Reka DropdownMenu;数组选择模型 |
@@ -85,7 +85,7 @@
| select | 验证中(SELECT-01) | 六部件、19/19 例、单/多选、清空、字段/原生提交/SSR/异步;复用 ListBox + Popover,重点浏览器已验,限制见 SELECT-01 |
| meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress |
| slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 |
| table | 验证中(M36 + 保真返修) | 15 部件;选择/排序/原生语义;13 演示;TableBody `#empty` 空状态;全选半选;defaultWidth 的 1fr 按原生 auto 弹性适配,不承诺 fr 比例;虚拟化固定 42px 窗口、TanStack 分页行模型;RAC TableLayout 不导出,见 M36 |
| table | 验证中(M36 + 保真返修) | 15 部件;选择/排序/原生语义;13 演示;TableBody `#empty` 空状态;全选半选;defaultWidth 的 1fr 按原生 auto 弹性适配,不承诺 fr 比例;虚拟化 42px 示例窗口经 useVirtualRows 支持可变行高/估算回退/gap/padding/加载行预留;表头按真实 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)
@@ -306,3 +306,14 @@ TextField/SearchField共享autoFocus、组内focus状态、字段级validationEr
## HD-08 Table 空状态、排序焦点与列宽(2026-10-29)
TableBody 空状态默认跨全部实际叶子列(含选择列与包装渲染的 TableColumn,随列增减响应式更新;未测量环境回退 1),显式 `colspan` 仍优先;保持 vnode 级空判定,不执行未知组件 setup/render 探测。排序保持列头单一激活路径:点击、Enter、Space 各一次(真实浏览器三手势逐一计数),触发按钮保留键盘焦点与 API,把真实 `:focus-visible` 转发到 `th` 的 `[data-focus-visible]` 钩子,焦点环回到基线位置(th 内嵌 2px 环,按钮 UA 轮廓在列内抑制),浅深主题均实测;`aria-sort="none"` 对可排序未排序列属基线行为(react-aria useTableColumnHeader 同款),维持不变。`defaultWidth="Nfr"` 按固定源权重语义实现(移植 react-stately TableColumnLayout/TableUtils 的 flex-grow 解析,Apache-2.0):px/百分比固定列先扣、fr 列按权重分享剩余宽度、min/max 以违规冻结+再分配收敛、整数级联取整保证列宽和等于表宽;存在 fr 列时未设宽度的列按 `1fr` 参与并启用 `table-layout: fixed` 精确几何,容器缩放重分配、拖动列冻结为像素宽度、RTL 几何一致且拖动方向相反,未测量环境(jsdom)保持原生宽度。保留原生 `th scope=row`、圆角选择器与 resizer `z-index` 修复;`.table__cell` 的 `text-start font-normal` 经实测确认会阻断调用方祖先继承(祖先 font-bold/text-center 不下传),收窄为 `th.hv-table__cell { text-align: inherit; font-weight: inherit }`:行头保持基线 td 排版同时保留调用方级联。真实浏览器几何/拖动/焦点验证见 [任务结果](tasks/results/HD-08-TABLE.md)。
## 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边框裁决。
+13
View File
@@ -40,3 +40,16 @@
- [结果](results/HD-08-TABLE.md)逐条核销:范围1空状态默认跨全部实际叶子列(选择列/包装列自注册计数、动态增减响应、显式colspan优先、不探测未知组件);范围2排序点击/Enter/Space保持单次激活(实测1/1/1),真实:focus-visible转发到th的data-focus-visible钩子恢复基线inset焦点环(浅深双主题实测、按钮UA环列内抑制;非删button非补类名),aria-sort="none"核实为基线行为不改;范围3移植react-stately calculateColumnSizes实现Nfr权重分配(固定/百分比先扣、min/max违规冻结再分配、级联取整、table-layout:fixed精确几何、容器缩放重分配、拖动冻结、RTL同几何反向拖动;900/620/1400三档真实浏览器几何逐毫符合约束),未测量环境保持原生宽度;范围4保留th scope=row/圆角/resizer z-index,text-start/font-normal实测确认阻断调用方继承后收窄为th.hv-table__cell{inherit}。全量111文件1657项、typecheck、build:docs、m35-m36(补两CSS标记)/handbook-styles最终tarball通过;fixture落tests/fixtures/table-layout.vue(playground注册)。遗留:虚拟化归HD-09;auto+fr混合口径与拖动中间分布差异已记录。
- HD-08 已验收:复核86d76a0,集成人补修c019768e6ac45410cd0f403a325ee0de9727e4eb,关闭固定列maxWidth/CSS不一致、无效fr不收敛及补修后的父容器缩小约束问题。全量111文件1658项、类型、最终docs/playground构建、m35-m36/handbook-styles最终tarball和真实浏览器空态/键盘焦点/几何/拖动/RTL通过,见同一结果表。按用户授权合入main并push origin/main;工作区释放,保留5173/5174,下一任务未启动。
- HD-10-COLLECTIONS已实施待复核,工作区释放;分支task/hd-10-collections,起点c34faccd7051a3c17bc510da05858ca29fdaf1cc(main tip,含HD-08验收与集成补修c019768),实施c8d54abefbf668fe10f2f7f6ab6ecca945a471e3。
- [结果](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,下一项未启动。
+6
View File
@@ -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任务。
+19 -5
View File
@@ -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四项已按下方最终结果节关闭,历史返修说明保留作追溯,最终状态以元数据为准。
+6 -6
View File
@@ -1,16 +1,17 @@
<!-- task-metadata
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"pending","requires":["docs/tasks/HD-QUEUE.md"],"sources":["apps/docs/src/demos/cn/combo-box/asynchronous-loading.tsx"],"checks":["pnpm exec vitest run tests/autocomplete.test.ts tests/autocomplete-demos.test.ts tests/combo-box.test.ts tests/combo-box-demos.test.ts tests/select.test.ts tests/b01-menu-dropdown.test.ts tests/regressions/collection/picker-public-contracts.test.ts","pnpm typecheck"]}
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"accepted","requires":["docs/tasks/HD-QUEUE.md"],"sources":["apps/docs/src/demos/cn/combo-box/asynchronous-loading.tsx"],"checks":["pnpm exec vitest run tests/autocomplete.test.ts tests/autocomplete-demos.test.ts tests/combo-box.test.ts tests/combo-box-demos.test.ts tests/select.test.ts tests/b01-menu-dropdown.test.ts tests/regressions/collection/picker-public-contracts.test.ts","pnpm typecheck","node scripts/check-package.mjs b01-menu-dropdown b02-pickers api-root-aliases"]}
-->
# HD-10-COLLECTIONS:异步加载、过滤与触发器语义
优先级:P1。证据范围:审计组 08;详见 [清单入口](HD-QUEUE.md) 和其中证据链接。
## 执行范围
- [ ] ComboBox 异步例补自动增量加载,保留取消旧请求和过期响应保护;明确本地模拟数据与基线 SWAPI 的差异,正常加载路径文案/布局对齐。Select 已有 IntersectionObserver,验证其实际滚动触发而非重复实现。错误重试可保留在异常态,不把重试按钮等同纯手动退化。
- [ ] Autocomplete 虚拟化例的 contains 使用 locale 敏感、大小写/变音折叠的等价过滤;与默认过滤共用逻辑。
- [ ] 核对 Autocomplete 触发器 role=button/tabindex/Delete/Backspace 的完整键盘与焦点模型,修正不符合等价公开组合的停靠点;selectedItems/selectedItem 用 Vue 插槽数据补齐可组合能力,不执行或复制任意子组件。
- [ ] 核对 Dropdown 子菜单固定源实际 delay 和暴露契约,补默认值/配置及 RTL 定位;保留 Button/Avatar 触发器布局补偿,除非浏览器证明其破坏目标效果。
- [x] ComboBox 异步例补自动增量加载,保留取消旧请求和过期响应保护;明确本地模拟数据与基线 SWAPI 的差异,正常加载路径文案/布局对齐。Select 已有 IntersectionObserver,验证其实际滚动触发而非重复实现。错误重试可保留在异常态,不把重试按钮等同纯手动退化。
- [x] Autocomplete 虚拟化例的 contains 使用 locale 敏感、大小写/变音折叠的等价过滤;与默认过滤共用逻辑。
- [x] 核对 Autocomplete 触发器 role=button/tabindex/Delete/Backspace 的完整键盘与焦点模型,修正不符合等价公开组合的停靠点;selectedItems/selectedItem 用 Vue 插槽数据补齐可组合能力,不执行或复制任意子组件。
- [x] 核对 Dropdown 子菜单固定源实际 delay 和暴露契约,补默认值/配置及 RTL 定位;保留 Button/Avatar 触发器布局补偿,除非浏览器证明其破坏目标效果。
## 用户可见通过条件
@@ -26,4 +27,3 @@
结果写到 `docs/tasks/results/HD-10-COLLECTIONS.md`,逐条记录改动或“无需修改”的证据及限制;只在本卡元数据更新状态。核实后无需修改是有效结论,不为凑修复量重写底座。普通实施提交自己的分支,不合 main、不 push、不派发其他会话。
仅浏览器客户端;不开发或运行 SSR/水合/Nuxt 服务端、逐像素自动对比、完整读屏或真机矩阵专项。
+1
View File
@@ -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核对成功为准。
+154
View File
@@ -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,未自动启动下一任务。
+101
View File
@@ -0,0 +1,101 @@
# HD-10-COLLECTIONS 结果记录
- 任务卡:[HD-10-COLLECTIONS](../HD-10-COLLECTIONS.md);固定上游 `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`(`apps/docs/src/demos/cn/combo-box/asynchronous-loading.tsx`、`dropdown.tsx` 及 react-aria/react-stately 依赖)。
- 分支 task/hd-10-collections;起点 c34faccd7051a3c17bc510da05858ca29fdaf1cc(main tip,含 HD-08 验收与集成补修 c019768);实施 c8d54abefbf668fe10f2f7f6ab6ecca945a471e3(21 文件,picker/菜单组件、演示与夹具、契约与测试、文档与记录源);记录提交为本文件所在提交。主会话实施/自测,未合 main、未 push。
- 本卡不扩展 HD-09 虚拟布局;未开展 SSR/水合/Nuxt 专项。
## 范围 1:ComboBox 异步例自动增量加载与请求防污染
**修改**(apps/docs/demos/combo-box-asynchronous-loading.vue 重写):
- **滚动到底自动增量加载**:IntersectionObserver 哨兵(隐藏 1px 元素)驱动 loadMore;加载中显示基线同款加载行(`flex items-center justify-center gap-2 py-2` + Spinner sm + 「加载更多…」,`text-sm text-muted` 保留已纠正的类写法);新页未把哨兵推出视口时续载链保持填充(等价固定源 ListBoxLoadMoreItem 每次集合变更重挂载观察器的语义)。
- **防重复请求/旧请求/过期响应**:`loading || loadingMore || error || !hasMore` 守卫(单测双触发出一次请求);新请求 abort 旧请求(AbortController);单调序号令牌丢弃过期响应(查询切换中途不混入旧数据,单测 + 浏览器实证)。
- **失败重试**:错误态显示「重试」按钮(异常态保留,不退化为纯手动加载);本地数据源以「模拟加载失败」开关注入失败。
- **模拟数据与 SWAPI 的差异**:示例注释与 combo-box.md「异步加载」节明确记载——固定源请求 swapi.py4e.com(useAsyncList 游标分页、82 条远端人员),本例为 12 条本地角色、模拟 300ms 延迟、失败可注入;加载行位于 ListBox 之外(固定源为行内 ListBoxLoadMoreItem 哨兵),自动触发语义一致。
**Select 未重复实现(验证)**:select-asynchronous-loading 的 useIntersectionObserver 真实网络滚动触发经浏览器实测——初始 20 条、滚动自动追加至 180 条、无重复(180 unique),未改其实现。
**证据**:单测 3 项(combo-box-demos.test.ts:自动增量+防重复、过期丢弃、失败重试);真实浏览器(文档站):自动链加载 12/12 无重复、查询切换 vader→solo 仅剩 Han Solo、失败→重试→恢复 8 条。
## 范围 2:过滤逻辑共用与 locale 敏感折叠
**修改**:`createBaseContains`(Intl.Collator `sensitivity: "base"`,与 Autocomplete/ComboBox 默认谓词同一实现)从包根公开;autocomplete-virtualization 示例改用 `useLocale()` + `createBaseContains` 过滤(原 `toLocaleLowerCase().includes` 的大小写折叠但无变音折叠),与默认过滤共用一份逻辑。文档「过滤函数(useFilter 替代)」补公开导出说明。
**证据**:既有组件测试「Autocomplete default base-sensitivity filter matches accents」(`cafe` 命中 `Café`)不变并通过;b02-pickers 类型契约以 `sharedMatcher("Café", "cafe")` 钉签名;真实浏览器验证列表过滤(solo/vader 查询)行为正确。
## 范围 3:Autocomplete 触发器语义与插槽组合能力
**核实(真实浏览器,autocomplete-default / autocomplete-multiple-select)**:
| 项 | 实测 | 结论 |
| ------------------ | ---------------------------------------------------------------------------------- | ------------------------------------- |
| Tab 停靠 | 触发器 `role=button tabindex=0` 唯一停靠;clear button `tabindex=-1`;Tab 离开组合 | 与「单一 Tab 入口」声明一致,无需修改 |
| Enter / Space | 各自打开列表 | ✓ |
| Escape | 关闭并回焦触发器 | ✓ |
| Delete / Backspace | 清除选中("Florida"→占位「选择州/省」;多选两项→占位) | ✓ |
| IME | `isComposing` 的 Enter 不触发 | ✓ |
| 单选 | 选择后触发器显示选中值 | ✓ |
| 多选 | 两项组合显示("CaliforniaTexas")、Delete 整体清除 | ✓ |
role=button/tabindex 与固定源 RAC Group 的差异为既有文档化适配(「单一 Tab 入口」模型),实测无不符合等价公开组合的停靠点,**无需修改**。
**修改(插槽数据补齐组合能力)**:`AutocompleteValue` 作用域插槽补 `selectedItem`(首个/单选项)且 `selectedItems` 条目携带 `item`(根 `items` 中的源数据项);`ComboBox` 根插槽补 `selectedItem`。对齐上游 `selectedItem` 与 `(T | null)[] selectedItems` 的值语义,调用方无需按键反查自己的数据(原示例普遍 `users.find(...)`);不执行未知组件 setup/render、不复制子组件。集合自发现项(无 `items` prop)`item` 为 undefined。类型契约(b02-pickers-contract.ts)与单测(picker-public-contracts +2)钉住形状。
## 范围 4:Dropdown 子菜单 delay、配置契约与 RTL
**核实**:固定源 `useSubmenuTrigger` 的 `delay` 默认 200ms,经 RAC `SubmenuTrigger`/HeroUI `DropdownSubmenuTrigger` 逐层透传为公共 prop;我方此前为 Reka 固定 100ms 且无配置(审计属实)。
**修改**:`DropdownSubmenuTrigger` 新增 `delay` prop(默认 200ms)。实现为受控 open 门 + 悬停定时:hover 启动定时(仅鼠标指针,同 Reka 的 isMouseEvent 门),Reka 的 100ms 早期请求在门内被吞、由配置延迟接管;键盘展开立即生效并取消挂起定时(与基线 `onSubmenuOpen → cancelOpenTimeout` 一致);指针离开/关闭/卸载取消。顺带移除对子菜单面板 `side`/`align` 的无效透传(Reka MenuSubContent 的模板绑定固定 side 且实测透传 attrs 不生效;注释与文档均已声明「底层固定」)。
**真实浏览器证据**(tests/fixtures/collections-rtl.vue,playground 5174 注册;ConfigProvider dir + DropdownRoot dir 双路):
| 项 | RTL 实测 | LTR 实测 |
| ------------------------- | ---------------------------------- | --------------------- |
| 默认延迟(200ms) | 222ms 打开 | 216ms 打开 |
| 自定义 `:delay="600"` | 618ms 打开 | — |
| 键盘展开(ArrowLeft/RTL) | 32ms(立即) | — |
| 定位 | subX 342 < triggerX 536 → **向左** | subX 740 > 536 → 向右 |
定位链路探针证实方向由 ConfigProvider→菜单根逐层解析(早前贴左缘时 side=left 碰壁翻转为 right 属碰撞翻转的正常行为)。文档站另有 hoverDefault 245ms / keyboard 46ms 对照。
**Button/Avatar 触发器布局补偿(保留)**:浏览器证据显示补偿规则 `.hv-dropdown__trigger.hv-button{display:inline-flex}` 实际胜出(inline-flex 作为 flex 子项被块化为 computed `flex`,禁用样式表后回落 `.hv-dropdown__trigger` 的 inline-block 证明补偿在起作用);未发现布局问题,**保留不改**。
## 检查与验证
- `node scripts/task-check.mjs HD-10-COLLECTIONS`(head c34facc)✅
- 卡内 checks:`vitest run` 7 套件(autocomplete/combo-box/select/b01-menu-dropdown/picker-public-contracts 等,175 项,复核实测纠正原计数)✅、`pnpm typecheck` ✅
- 全量 `pnpm exec vitest run`:**111 文件 / 1666 项**(新增 8:3 子菜单 delay 契约、3 异步加载行为、2 插槽数据)✅;既有断言零修改
- `pnpm build:docs` ✅;prettier ✅
- 最终 tarball:`node scripts/check-package.mjs b02-pickers api-root-aliases` ✅(`createBaseContains` 入契约导出;b02-pickers-contract.ts 增 selectedItem/item/匹配器类型正反例,nodenext/bundler 双解析 strict 通过)
- 真实浏览器(playwright-core + 系统 Chrome):异步滚动/防重/过期/重试、触发器键盘/IME/单多选、子菜单延迟/RTL/键盘、触发器布局;截图 hd10-submenu-ltr.png 等存档
- 文档同步:combo-box.md(异步差异说明、插槽表)、autocomplete.md(插槽表、过滤函数节)、dropdown.md(delay 行与差异注记)、兼容矩阵与来源记录
## 未完成与限制
1. RTL 夹具使用 ConfigProvider + DropdownRoot 双路传 dir(二者均实测生效);纯文档示例未包 ConfigProvider,站级 RTL 切换不在本卡范围。
2. Reka MenuSubTrigger 的 100ms 固定计时无法配置,延迟门为受控 open 层重定(DropdownSubmenuTrigger.vue 注释记载机制与基线差异);拖动/触摸指针不启动悬停展开(与 Reka isMouseEvent 一致)。
3. `ComboBoxValue`/`AutocompleteValue` 的 `item` 类型为 `ComboBoxItem`/`AutocompleteItem`(含额外字段的对象经结构性赋值传入,消费者按自身类型收窄);未引入泛型插槽类型。
4. 测试环境偶发并发超时(与本卡改动无关,隔离复跑全过);button-toggle 间歇项已在 HD-08 记录中归档。
## 集成人复核与补修(2026-10-29)
入口 `d1528569a8e7b2aeb589897c63279919d61bd554`,用户授权少量问题直接补修后合并push;补修 **`bf6cf0f8d12fe54a72e5ff524b1b05dbaadcfe86`**。
| 项 | 复现与修复 | 证据 |
| --- | --- | --- |
| 悬停等待期间点击被吞 | 原门禁仅区分全局keydown与hover,点击发生在600ms计时期间也被阻止。改为触发器本地capture记录实际激活事件,click/键盘可绕过hover等待,移除各实例window keydown监听。 | 修复前新增点击探针失败;修复后50ms时点击立即打开,不等待600ms。 |
| 禁用项被hover计时器打开 | 自有定时器绕过底座disabled检查,isDisabled、Menu disabledKeys与等待期间变禁用三种均复现打开。改为读取实际触发器aria-disabled/data-disabled,在排程、到期与底座open请求三个边界校验。 | 三个探针修复前全部失败、修复后全部通过;浏览器禁用分享后菜单项真实aria-disabled=true且无法展开。 |
| click取消与关闭清理 | asChild底座可先于消费方bubble处理器请求open。click的接受延至本次事件链完成后检查defaultPrevented,保持消费方取消与单次回调;键盘仍同步进入底座原焦点路径。父根关闭清除待执行hover并关闭本级。 | 新增消费方preventDefault与父关闭/重开两项回归;取消点击不会绕过延迟,父级关闭后不会残留打开。 |
| 产物契约与变更范围 | 补b01-menu-dropdown最终包的delay number正反例;client-checks.json还原无关整文件格式变化,仅保留createBaseContains增量导出。夹具加入禁用开关,移除源码实验性注释。 | 三组最终tarball双解析/ESM/CSS通过;未更改已有断言或新增依赖。 |
### 最终复核结果
- 全量 `pnpm exec vitest run`:**111文件 / 1672项通过**(原实施1666+本轮6:点击1、两种禁用2、动态禁用1、父关闭1、消费方取消1);`pnpm typecheck`通过。
- 最终 `node scripts/check-package.mjs b01-menu-dropdown b02-pickers api-root-aliases`通过:新增delay类型正反例、选项源数据槽、过滤器导出及原有契约。使用最终dist的docs/playground构建通过;Prettier与git diff --check通过。未因历史间歇项放宽超时或跳过断言。
- 5173正式ComboBox异步示例:打开后4→12条且无重复;快速vader→solo后仅Han Solo。注入失败后空集合+重试按钮,关闭失败开关并重试后仅Darth Vader且重试消失。实际原生指针切换失败开关,未用脚本补发事件。
- 5173正式Select异步例:初始20条,实际在弹层内滚动后40条、40个唯一名称;保留原IntersectionObserver实现。
- 5174 `?collections-rtl`:禁用分享不可展开;启用后RTL真实Home/Down/Left立即展开,焦点到“邮件”,trigger x536/submenu x316且data-side=left。Escape逐级关闭,切LTR点击展开时submenu x约744、data-side=right。保留原实施的200/600ms真实hover测量;本轮对应延迟、离开取消、键盘立即的定时回归重新全量通过,不将单测时钟冒称新的浏览器耗时测量。
- 源码确认虚拟化例与默认过滤共用createBaseContains,locale来自useLocale的响应式computed;既有Café/cafe与组合输入/键盘单多选回归全部保留通过。插槽数据源契约沿用原实施的两个新增运行时断言与最终包类型验证。
无本卡阻断项。状态 **accepted**,按用户授权合入main并push origin/main;保留5173/5174。未启动HD-09或其他任务,未执行SSR/水合/Nuxt服务端、逐像素或完整设备/读屏矩阵。
+13 -1
View File
@@ -169,7 +169,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
## LISTBOX-01(2026-10-23)
固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示曾改为内联状态反馈(2026-10-28 HD-02 已按固定基线恢复为 alert 反馈与原结构),React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 固定行高虚拟化。依据、差异与限制见 [LISTBOX-01](component-notes.md)。
固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示曾改为内联状态反馈(2026-10-28 HD-02 已按固定基线恢复为 alert 反馈与原结构),React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 虚拟行序列(固定/可变行高、heading/loader 行、gap/padding,语义映射见 list-box.md 的 ListLayout 映射表)。依据、差异与限制见 [LISTBOX-01](component-notes.md)。
## M33–M34(2026-10-23)
@@ -374,3 +374,15 @@ Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该
- packages/vue/src/components/table/widths.ts:移植 react-stately `TableUtils.js`(`calculateColumnSizes` flex-grow 列宽解析、min/max 违规冻结、级联取整)与 `TableColumnLayout.js` 的默认宽度语义(未设宽度按 `1fr`),Apache-2.0;仅函数级移植,无新状态内核。
- 排序焦点环转发与空状态跨列自适应为 Vue 适配(基线由 RAC useTableColumnHeader 的 press/focus 与 TableBody colSpan 承担);`aria-sort` 的 `"none"` 输出与基线 useTableColumnHeader 一致,不作改动。
## HD-10 来源(2026-10-29)
- 子菜单 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原点处理,纠正原“无分区表头模型所以不提供”的解释。
+15 -1
View File
@@ -200,10 +200,24 @@
* popover itself is constrained (e.g. inside a Modal, or a short viewport). Without
* it the list keeps its full 320px and its overflow is clipped by the popover, making
* the last options unreachable. */
[data-slot="list-box"] {
[data-slot="list-box"]:not([data-virtualized]) {
@apply max-h-[320px] min-h-0 scrollbar overflow-y-auto p-1.5 outline-none;
}
/* Virtualized lists scroll the popover content as a whole (the pinned
* upstream layout): the row window binds to this scrolling ancestor and the
* search field can stay sticky at its top. The height cap stands in for the
* upstream overlay's available-space clamp. */
&:has([data-slot="list-box"][data-virtualized]) [data-slot="autocomplete-filter"] {
@apply max-h-[min(400px,70vh)] overflow-y-auto;
}
[data-slot="list-box"][data-virtualized] {
@apply min-h-0 p-1.5 outline-none;
max-height: none;
overflow: visible;
}
[data-slot="list-box-item"] {
@apply px-2.5;
}
+11
View File
@@ -275,6 +275,17 @@
* (UA bold/center neutralised) while caller text-align/font-weight keep
* cascading into every cell — scoping the reset to `th` preserves ancestor
* inheritance for the regular td cells. */
/* Explicit virtual row heights must not be enlarged by native cell padding.
Keep the original padding on an inset content box, with native th/td intact. */
.hv-table__cell[data-fixed-height] {
position: relative;
padding: 0;
overflow: clip;
}
.hv-table__fixed-cell-content {
@apply absolute inset-x-0 top-1/2 -translate-y-1/2 px-4 py-3;
}
th.hv-table__cell {
text-align: inherit;
font-weight: inherit;
@@ -453,6 +453,7 @@ export default defineComponent({
textValue:
records.value.find((record) => record.key === key)?.text ??
String(key),
item: props.items?.find((entry) => entry.id === key),
})),
),
selectionMode: computed(() => props.selectionMode),
@@ -20,6 +20,7 @@ export default defineComponent({
defaultChildren,
selectedText,
selectedItems,
selectedItem: selectedItems[0] ?? null,
}) ?? defaultChildren;
return h(
"span",
@@ -5,9 +5,11 @@ import type { CollectionRecord, OwnedCollection } from "../collection/owner";
import type { useChoiceField } from "../choice/shared";
export type AutocompleteValue = CollectionKey | CollectionKey[] | null;
export interface AutocompleteSelectedItem {
export interface AutocompleteSelectedItem<T = AutocompleteItem> {
key: CollectionKey;
textValue: string;
/** Source entry from the root `items` (absent for collection-discovered items). */
item?: T;
}
export interface AutocompleteOptions {
modelValue?: AutocompleteValue;
@@ -42,6 +44,12 @@ export interface AutocompleteValueState {
/** Accepted `textValue`s joined by ", ". */
selectedText: string;
selectedItems: AutocompleteSelectedItem[];
/**
* First accepted entry (the single-select selection), or null. Entries carry
* the source `items` data in `item` so callers can compose rich trigger
* content from their own records without re-mapping keys.
*/
selectedItem: AutocompleteSelectedItem | null;
}
/** Scoped-slot state of the `Autocomplete` root. */
export interface AutocompleteState {
@@ -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);
}
@@ -58,6 +58,7 @@ export default defineComponent({
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
selectedItem: ComboBoxItem | null;
}) => VNodeChild;
}>,
props: {
@@ -653,6 +654,7 @@ export default defineComponent({
textValue:
records.value.find((record) => record.key === key)?.text ??
String(key),
item: props.items?.find((entry) => entry.id === key),
})),
),
selectionMode: computed(() => props.selectionMode),
@@ -792,6 +794,10 @@ export default defineComponent({
? null
: (value.value as CollectionKey | null),
selectedKeys: [...keys.value],
selectedItem:
(!Array.isArray(value.value) && value.value != null
? (props.items?.find((entry) => entry.id === value.value) ?? null)
: null) ?? null,
});
const children = Array.isArray(rendered)
? rendered
@@ -17,6 +17,12 @@ export interface ComboBoxState {
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
/**
* Source entry from the root `items` matching the single selected key
* (null in multiple mode or for custom/discovered values). Lets callers
* compose rich value displays from their own data without re-mapping keys.
*/
selectedItem: ComboBoxItem | null;
}
/** Scoped-slot state of `ComboBoxValue`. */
export interface ComboBoxValueState {
@@ -26,6 +32,8 @@ export interface ComboBoxValueState {
export interface ComboBoxSelectedItem {
key: CollectionKey;
textValue: string;
/** Source entry from the root `items` (absent for collection-discovered items). */
item?: ComboBoxItem;
}
/** Props shared by the SFC and the context; keep one schema. */
export interface ComboBoxOptions {
@@ -7,6 +7,7 @@ import {
inject,
isVNode,
nextTick,
onBeforeUnmount,
onMounted,
provide,
ref,
@@ -31,8 +32,6 @@ import {
submenuOpenKey,
} from "../menu/context";
import { useOverlayAnimation } from "../overlay/animation";
import { resolvePlacement, type OverlayPlacement } from "../overlay/placement";
import { useConfig } from "../../providers/context";
import { elementFromValue, menuSurfaceFromVNode } from "./dom";
import DropdownPopover from "./DropdownPopover.vue";
@@ -104,16 +103,83 @@ function inheritedProps(props: Record<string, unknown> | null) {
export default defineComponent({
name: "DropdownSubmenuTrigger",
inheritAttrs: false,
setup(_, { slots }) {
props: {
/**
* Hover-to-open delay in ms (the pinned useSubmenuTrigger contract).
* Keyboard and programmatic opens stay immediate and cancel the pending
* hover open, matching the baseline.
*/
delay: { type: Number, default: 200 },
},
setup(props, { slots }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const config = useConfig();
provide(submenuContentKey, true);
const subOpen = ref(false);
const triggerRef = ref<unknown>(null);
const contentElement = ref<HTMLElement | null>(null);
const fallbackId = useId();
/**
* Reka's MenuSubTrigger opens submenus after a fixed 100ms hover, while the
* pinned source waits `delay` (200ms by default). The controlled open gate
* below defers hover-driven opens to the configured delay: our own timer
* owns the hover open, early hover requests are swallowed, and keyboard
* opens (which arrive during a keydown) cancel the pending timer and open
* at once like the baseline.
*/
const hoverOpenTimer = ref<ReturnType<typeof setTimeout> | null>(null);
let activationEvent: Event | undefined;
function triggerDisabled() {
const element = elementFromValue(triggerRef.value);
return (
element?.getAttribute("aria-disabled") === "true" ||
element?.hasAttribute("data-disabled") === true
);
}
function clearHoverOpen() {
if (hoverOpenTimer.value) {
clearTimeout(hoverOpenTimer.value);
hoverOpenTimer.value = null;
}
}
function scheduleHoverOpen() {
if (hoverOpenTimer.value || subOpen.value || triggerDisabled()) return;
if (!(props.delay > 0)) {
subOpen.value = true;
return;
}
hoverOpenTimer.value = setTimeout(() => {
hoverOpenTimer.value = null;
if (!triggerDisabled() && dropdownCtx?.open.value !== false)
subOpen.value = true;
}, props.delay);
}
function itemPointerMove(event: Event) {
if ((event as MouseEvent).defaultPrevented) return;
// Same gate as Reka's SubTrigger: only mouse hover starts the open.
if ((event as PointerEvent).pointerType !== "mouse") return;
scheduleHoverOpen();
}
function itemPointerLeave() {
clearHoverOpen();
}
function activationCapture(event: Event) {
activationEvent = event;
queueMicrotask(() => {
if (activationEvent === event) activationEvent = undefined;
});
}
onBeforeUnmount(clearHoverOpen);
watch(
() => dropdownCtx?.open.value,
(open) => {
if (open === false) {
clearHoverOpen();
subOpen.value = false;
}
},
);
const contentAttrs = {
label: ref<string | undefined>(),
labelledBy: ref<string | undefined>(),
@@ -224,9 +290,6 @@ export default defineComponent({
if (!CONTROL_PROPS.has(key)) domProps[key] = value;
}
const placement = (popoverProps.placement as OverlayPlacement) ?? "end";
const position = resolvePlacement(placement, config?.dir.value ?? "ltr");
panelConfig.dismissDisabled =
(popoverProps.isKeyboardDismissDisabled as boolean | undefined) ??
false;
@@ -234,8 +297,10 @@ export default defineComponent({
popoverProps.shouldCloseOnInteractOutside as
((event: Event) => boolean) | undefined;
// Reka fixes the submenu side/align to the parent convention, so only
// the offsets/collision props can be forwarded.
// Reka's MenuSubContent fixes the submenu side/align to the parent
// convention (right in LTR, left in RTL) and only accepts the offsets /
// collision props here: forwarded side/align attrs never reach the
// popper placement (the template binding wins), so they are not passed.
const panelProps: Record<string, unknown> = {
sideOffset:
(popoverProps.sideOffset as number | undefined) ??
@@ -256,9 +321,6 @@ export default defineComponent({
contentAttrs.loop.value ??
false,
};
const side = (popoverProps.side as string | undefined) ?? position.side;
const align =
(popoverProps.align as string | undefined) ?? position.align;
const keydownChain = [
...asArray(popoverProps.onKeydown as Handler),
@@ -309,6 +371,34 @@ export default defineComponent({
{
open: subOpen.value,
"onUpdate:open": (value: boolean) => {
if (value) {
if (triggerDisabled()) {
clearHoverOpen();
return;
}
const click = activationEvent;
if (click?.type === "click") {
// asChild's primitive can request open before the item's
// bubble handlers. Let the complete click chain cancel it.
queueMicrotask(() => {
if (
click.defaultPrevented ||
triggerDisabled() ||
dropdownCtx?.open.value === false
)
return;
clearHoverOpen();
subOpen.value = true;
});
return;
}
// Reka's fixed 100ms hover timer requests the open before the
// configured delay; the delay owns that open instead. Keyboard
// opens arrive during a keydown and pass through at once,
// cancelling the pending hover open like the baseline.
if (hoverOpenTimer.value && !activationEvent) return;
clearHoverOpen();
} else clearHoverOpen();
subOpen.value = value;
},
},
@@ -333,6 +423,17 @@ export default defineComponent({
// Escape with focus on the trigger (pointer-opened
// submenu) must also close only this level.
onKeydown: handleEscape,
onKeydownCapture: [
...asArray(attrs.onKeydownCapture as Handler),
activationCapture,
],
onClickCapture: [
...asArray(attrs.onClickCapture as Handler),
activationCapture,
],
// Hover intent drives the configured open delay.
onPointermove: itemPointerMove,
onPointerleave: itemPointerLeave,
})
: null,
},
@@ -347,8 +448,6 @@ export default defineComponent({
{
...domProps,
...panelProps,
side,
align,
...ariaProps,
class: [
dropdownCtx?.slots.value.popover(),
+250 -35
View File
@@ -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>;
+21
View File
@@ -449,6 +449,27 @@ export {
} from "./composables/useOverlayState";
export { default as ConfigProvider } from "./providers/ConfigProvider.vue";
export { useLocale } from "./providers/context";
/**
* Locale-aware base-sensitivity substring matcher (case + diacritic folding,
* e.g. `cafe` matches `Café`). Same implementation as the Autocomplete /
* ComboBox default filter; use it when a caller filters its own data for the
* 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";
+202
View File
@@ -1316,3 +1316,205 @@ it("menu-level close policy wins over the section mode default", async () => {
await nextTick();
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
});
function mountSubmenuWithDelay(
delay?: number,
itemProps: () => Record<string, unknown> = () => ({}),
menuProps: Record<string, unknown> = {},
rootProps: () => Record<string, unknown> = () => ({}),
) {
return mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true, ...rootProps() }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(DropdownMenu, menuProps, () => [
h(DropdownSubmenuTrigger, { delay }, () => [
h(
DropdownItem,
{ id: "share", textValue: "分享", ...itemProps() },
() => [h(Label, () => "分享"), h(DropdownSubmenuIndicator)],
),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () =>
h(
DropdownItem,
{ id: "whatsapp", textValue: "WhatsApp" },
() => h(Label, () => "WhatsApp"),
),
),
),
]),
]),
),
]),
);
}
function hoverMove(node: Element) {
node.dispatchEvent(pointer("pointermove", { pointerType: "mouse" }));
}
function subContent() {
return document.querySelector("[data-submenu-content]");
}
it("submenu hover opens after the baseline delay (200ms), not Reka's fixed 100ms", async () => {
vi.useFakeTimers();
mountSubmenuWithDelay();
await flushPromises();
await nextTick();
const trigger = document.querySelector(
'[data-slot="menu-item"][data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
// Reka's own 100ms timer requests the open; the configured delay defers it.
await vi.advanceTimersByTimeAsync(150);
await nextTick();
expect(subContent()).toBeNull();
await vi.advanceTimersByTimeAsync(100);
await nextTick();
expect(subContent()).toBeTruthy();
vi.useRealTimers();
});
it("submenu hover honors a custom delay and pointer leave cancels it", async () => {
vi.useFakeTimers();
mountSubmenuWithDelay(600);
await flushPromises();
await nextTick();
const trigger = document.querySelector(
'[data-slot="menu-item"][data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(400);
await nextTick();
expect(subContent()).toBeNull();
trigger.dispatchEvent(pointer("pointerleave", { pointerType: "mouse" }));
await vi.advanceTimersByTimeAsync(500);
await nextTick();
expect(subContent()).toBeNull();
// A fresh hover re-arms the full delay.
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(300);
await nextTick();
expect(subContent()).toBeNull();
await vi.advanceTimersByTimeAsync(350);
await nextTick();
expect(subContent()).toBeTruthy();
vi.useRealTimers();
});
it("keyboard submenu open is immediate and cancels the pending hover open", async () => {
vi.useFakeTimers();
mountSubmenuWithDelay();
await flushPromises();
await nextTick();
const trigger = document.querySelector(
'[data-slot="menu-item"][data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(50);
trigger.focus();
trigger.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowRight",
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
await nextTick();
expect(subContent()).toBeTruthy();
// The cancelled hover timer must not produce a second open request later.
await vi.advanceTimersByTimeAsync(400);
await nextTick();
expect(subContent()).toBeTruthy();
vi.useRealTimers();
});
it("click during the hover delay opens immediately", async () => {
vi.useFakeTimers();
mountSubmenuWithDelay(600);
await flushPromises();
const trigger = document.querySelector(
'[data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(50);
trigger.click();
await flushPromises();
expect(subContent()).toBeTruthy();
});
it.each(["item", "menu"])(
"disabled submenu (%s) never opens from hover",
async (source) => {
vi.useFakeTimers();
mountSubmenuWithDelay(
200,
() => ({ isDisabled: source === "item" }),
source === "menu" ? { disabledKeys: ["share"] } : {},
);
await flushPromises();
const trigger = document.querySelector(
'[data-has-submenu="true"]',
) as HTMLElement;
expect(trigger.getAttribute("aria-disabled")).toBe("true");
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(500);
expect(subContent()).toBeNull();
},
);
it("disabling a submenu during its hover delay prevents the pending open", async () => {
vi.useFakeTimers();
const disabled = ref(false);
mountSubmenuWithDelay(600, () => ({ isDisabled: disabled.value }));
await flushPromises();
const trigger = document.querySelector(
'[data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(150);
disabled.value = true;
await nextTick();
await vi.advanceTimersByTimeAsync(600);
expect(subContent()).toBeNull();
});
it("closing the parent cancels a pending submenu hover", async () => {
vi.useFakeTimers();
const open = ref(true);
mountSubmenuWithDelay(
600,
() => ({}),
{},
() => ({ open: open.value }),
);
await flushPromises();
hoverMove(document.querySelector('[data-has-submenu="true"]')!);
await vi.advanceTimersByTimeAsync(50);
open.value = false;
await nextTick();
await vi.advanceTimersByTimeAsync(700);
open.value = true;
await flushPromises();
expect(subContent()).toBeNull();
});
it("a cancelled submenu click does not bypass the hover delay", async () => {
vi.useFakeTimers();
const click = vi.fn((event: MouseEvent) => event.preventDefault());
mountSubmenuWithDelay(600, () => ({ onClick: click }));
await flushPromises();
const trigger = document.querySelector(
'[data-has-submenu="true"]',
) as HTMLElement;
hoverMove(trigger);
await vi.advanceTimersByTimeAsync(50);
trigger.click();
await flushPromises();
expect(click).toHaveBeenCalledOnce();
expect(subContent()).toBeNull();
});
+110
View File
@@ -218,3 +218,113 @@ describe("ComboBox docs and demos", () => {
mounted.pop();
});
});
describe("asynchronous loading demo", () => {
class FakeIntersectionObserver {
static instances: FakeIntersectionObserver[] = [];
callback: (entries: unknown[]) => void;
constructor(callback: (entries: unknown[]) => void) {
this.callback = callback;
FakeIntersectionObserver.instances.push(this);
}
observe() {}
unobserve() {}
disconnect() {}
trigger(isIntersecting: boolean) {
this.callback([{ isIntersecting }]);
}
static last() {
return FakeIntersectionObserver.instances.at(-1)!;
}
static reset() {
FakeIntersectionObserver.instances = [];
}
}
async function mountAsyncDemo() {
vi.useFakeTimers();
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
FakeIntersectionObserver.reset();
const demo = (
await import("../apps/docs/demos/combo-box-asynchronous-loading.vue")
).default;
const w = mount(demo, { attachTo: document.body });
mounted.push(w);
// Initial page resolves on the simulated latency.
await vi.advanceTimersByTimeAsync(350);
await nextTick();
(w.get('[data-slot="input"]').element as HTMLInputElement).focus();
await nextTick();
return w;
}
const optionNames = () =>
[...document.querySelectorAll('[role="option"]')].map((node) =>
node.textContent?.trim(),
);
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
FakeIntersectionObserver.reset();
});
it("auto-loads the next page when the sentinel intersects, without duplicate requests", async () => {
const w = await mountAsyncDemo();
expect(optionNames()).toHaveLength(4);
// Two intersections in the same tick must start one request only: a
// duplicated fetch would append the same offset twice.
FakeIntersectionObserver.last().trigger(true);
FakeIntersectionObserver.last().trigger(true);
await vi.advanceTimersByTimeAsync(350);
await nextTick();
const afterFirst = optionNames();
expect(afterFirst).toHaveLength(8);
expect(new Set(afterFirst).size).toBe(8);
// The chain fills the remaining page while the sentinel stays visible.
await vi.advanceTimersByTimeAsync(350);
await nextTick();
expect(optionNames()).toHaveLength(12);
expect(document.body.textContent).not.toContain("加载更多…");
void w;
});
it("drops stale responses when the query switches mid-flight", async () => {
await mountAsyncDemo();
const input = document.querySelector<HTMLInputElement>(
'[data-slot="input"]',
)!;
input.value = "vader";
input.dispatchEvent(new Event("input", { bubbles: true }));
await vi.advanceTimersByTimeAsync(100);
input.value = "solo";
input.dispatchEvent(new Event("input", { bubbles: true }));
await vi.advanceTimersByTimeAsync(800);
await nextTick();
const names = optionNames();
expect(names).toEqual(["Han Solo"]);
});
it("retries a failed page from the error state", async () => {
const w = await mountAsyncDemo();
const checkbox = w.get('input[type="checkbox"]');
await checkbox.setValue(true);
FakeIntersectionObserver.last().trigger(true);
await vi.advanceTimersByTimeAsync(350);
await nextTick();
// The error row renders inside the teleported popover surface.
expect(document.body.textContent).toContain("重试");
expect(optionNames()).toHaveLength(4);
await checkbox.setValue(false);
const retry = [...document.querySelectorAll("button")].find(
(button) => button.textContent?.trim() === "重试",
)!;
expect(retry).toBeTruthy();
retry.click();
await vi.advanceTimersByTimeAsync(350);
await nextTick();
expect(document.body.textContent).not.toContain("重试");
expect(optionNames()).toHaveLength(8);
void w;
});
});
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { computed, defineComponent, h, ref } from "vue";
import {
Button,
ConfigProvider,
DropdownItem,
DropdownMenu,
DropdownPopover,
DropdownRoot,
DropdownSubmenuIndicator,
DropdownSubmenuTrigger,
DropdownTrigger,
Label,
useLocale,
} from "@heroui-vue/components";
/**
* HD-10 submenu verification harness: the pinned RTL behaviour (submenu flips
* to the left of its trigger) and the configurable hover delay, driven through
* the public ConfigProvider direction contract.
*/
const rtl = ref(true);
const disabledShare = ref(false);
const opened = ref(0);
const localeDir = useLocale().dir;
const probe = computed(() => `outer-dir=${localeDir.value}`);
const InnerProbe = defineComponent({
setup() {
const dir = useLocale().dir;
return () =>
h("output", { "data-probe-inner": "" }, `inner-dir=${dir.value}`);
},
});
</script>
<template>
<main style="padding: 24px; display: grid; gap: 16px; justify-items: center">
<label>
<input v-model="rtl" type="checkbox" />
RTL(ConfigProvider dir)
</label>
<label>
<input v-model="disabledShare" type="checkbox" />
禁用分享子菜单
</label>
<output data-probe>{{ probe }}</output>
<ConfigProvider :dir="rtl ? 'rtl' : 'ltr'">
<InnerProbe />
<div style="width: 700px; display: flex; justify-content: center">
<DropdownRoot :dir="rtl ? 'rtl' : 'ltr'" @open-change="opened++">
<DropdownTrigger>
<Button aria-label="菜单">菜单</Button>
</DropdownTrigger>
<DropdownPopover>
<DropdownMenu aria-label="示例菜单">
<DropdownItem id="copy" text-value="复制">
<Label>复制</Label>
</DropdownItem>
<!-- Baseline default delay: 200ms. -->
<DropdownSubmenuTrigger>
<DropdownItem
id="share"
text-value="分享"
:is-disabled="disabledShare"
>
<Label>分享(默认延迟)</Label>
<DropdownSubmenuIndicator />
</DropdownItem>
<DropdownPopover>
<DropdownMenu aria-label="分享">
<DropdownItem id="mail" text-value="邮件">
<Label>邮件</Label>
</DropdownItem>
</DropdownMenu>
</DropdownPopover>
</DropdownSubmenuTrigger>
<!-- Custom delay: 600ms. -->
<DropdownSubmenuTrigger :delay="600">
<DropdownItem id="more" text-value="更多">
<Label>更多(600ms 延迟)</Label>
<DropdownSubmenuIndicator />
</DropdownItem>
<DropdownPopover>
<DropdownMenu aria-label="更多">
<DropdownItem id="report" text-value="举报">
<Label>举报</Label>
</DropdownItem>
</DropdownMenu>
</DropdownPopover>
</DropdownSubmenuTrigger>
</DropdownMenu>
</DropdownPopover>
</DropdownRoot>
</div>
</ConfigProvider>
</main>
</template>
+394
View File
@@ -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>
@@ -13,6 +13,7 @@ import {
MenuItemIndicator,
MenuItemSubmenuIndicator,
MenuSection,
type DropdownSubmenuTriggerProps,
type DropdownRootProps,
type DropdownMenuProps,
type DropdownItemProps,
@@ -103,3 +104,9 @@ export const values = {
badVariant,
badIndicator,
};
const submenuDelay: DropdownSubmenuTriggerProps = { delay: 600 };
// @ts-expect-error submenu hover delay is a number of milliseconds
const badSubmenuDelay: DropdownSubmenuTriggerProps = { delay: "slow" };
void submenuDelay;
void badSubmenuDelay;
+8 -1
View File
@@ -14,6 +14,7 @@ import {
ComboBoxValue,
ListBox,
ListBoxItem,
createBaseContains,
type AutocompleteItem,
type AutocompleteProps,
type AutocompleteState,
@@ -152,8 +153,11 @@ const badComboEvent = h(ComboBox, {
});
// Root scoped slots expose the open/selection state.
const sharedMatcher: (text: string, query: string) => boolean =
createBaseContains("zh-CN");
void sharedMatcher("Café", "cafe");
const comboState = (state: ComboBoxState): string =>
`${state.isOpen}:${state.inputValue}:${state.selectedKeys.length}`;
`${state.isOpen}:${state.inputValue}:${state.selectedKeys.length}:${state.selectedItem?.textValue ?? ""}`;
const autocompleteState = (state: AutocompleteState): string =>
`${state.isOpen}:${state.selectedKeys.length}`;
const comboValueState = (state: ComboBoxValueState): string =>
@@ -191,6 +195,9 @@ const autocompleteTree = h(Autocomplete, { "aria-label": "州" }, () => [
const placeholder: boolean = state.isPlaceholder;
const joined: string = state.selectedText || state.defaultChildren;
const keys = state.selectedItems.map((item) => item.key);
// Source `items` data rides along for rich trigger composition.
const source = state.selectedItem?.item?.textValue ?? "";
void source;
return placeholder ? joined : keys.join(",");
},
}),
+6 -1
View File
@@ -80,7 +80,8 @@
"AutocompletePopover",
"AutocompleteFilter",
"comboBoxVariants",
"autocompleteVariants"
"autocompleteVariants",
"createBaseContains"
],
"css": [
".hv-combo-box",
@@ -258,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",
+98
View File
@@ -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;
@@ -446,3 +446,94 @@ it("ComboBox trigger retains a caller disabled attribute", async () => {
)!.disabled,
).toBe(true);
});
it("Autocomplete value slot carries the source items for trigger composition", async () => {
const source = [{ id: 1, textValue: "Kate", avatarUrl: "/kate.png" }];
let state: {
isPlaceholder: boolean;
selectedItem: { key: unknown; item?: { avatarUrl?: string } } | null;
selectedItems: { key: unknown; item?: { avatarUrl?: string } }[];
} | null = null;
const w = mount(
defineComponent({
render: () =>
h(
Autocomplete,
{
items: source as never,
defaultValue: 1,
"aria-label": "Picker",
selectionMode: "single",
},
{
default: () => [
h(AutocompleteTrigger, null, {
default: () =>
h(AutocompleteValue, null, {
default: (slotState: typeof state) => {
state = slotState as never;
return "";
},
}),
}),
h(AutocompletePopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
source.map((item) =>
h(
ListBoxItem,
{ id: item.id, textValue: item.textValue },
() => item.textValue,
),
),
}),
}),
],
},
),
}),
{ attachTo: document.body },
);
roots.push(w);
await tick();
expect(state).not.toBeNull();
expect(state!.isPlaceholder).toBe(false);
// The source entry rides along: no consumer-side key lookups needed.
expect(state!.selectedItem?.key).toBe(1);
expect(state!.selectedItem?.item?.avatarUrl).toBe("/kate.png");
expect(state!.selectedItems[0].item?.avatarUrl).toBe("/kate.png");
});
it("ComboBox root slot exposes the selected source item", async () => {
const source = [
{ id: "a", textValue: "Alpha", meta: "first" },
{ id: "b", textValue: "Beta", meta: "second" },
];
let state: { selectedItem: { id?: unknown; meta?: unknown } | null } | null =
null;
const w = mount(
defineComponent({
render: () =>
h(
ComboBox,
{ items: source as never, defaultValue: "b", "aria-label": "Picker" },
{
default: (slotState: typeof state) => {
state = slotState as never;
return [
h(ComboBoxInputGroup, null, {
default: () => [h(Input), h(ComboBoxTrigger)],
}),
];
},
},
),
}),
{ attachTo: document.body },
);
roots.push(w);
await tick();
expect(state!.selectedItem?.id).toBe("b");
expect(state!.selectedItem?.meta).toBe("second");
});
+436
View File
@@ -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);
});