Compare commits

...

4 Commits

Author SHA1 Message Date
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
25 changed files with 922 additions and 90 deletions
+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"` 冲突)。
@@ -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),
);
});
@@ -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>
+7
View File
@@ -24,6 +24,13 @@ const labs = [
() => import("../../../tests/fixtures/table-layout.vue"),
),
},
{
key: "collections-rtl",
title: "子菜单延迟与 RTL 定位",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/collections-rtl.vue"),
),
},
{
key: "button-group-dropdown",
title: "按钮组与下拉根属性",
+4
View File
@@ -306,3 +306,7 @@ 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)。
+5
View File
@@ -40,3 +40,8 @@
- [结果](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未启动。
+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 服务端、逐像素自动对比、完整读屏或真机矩阵专项。
+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服务端、逐像素或完整设备/读屏矩阵。
+6
View File
@@ -374,3 +374,9 @@ 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 敏感折叠),作为公开过滤器与默认谓词共用。
@@ -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 {
@@ -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(),
+7
View File
@@ -449,6 +449,13 @@ 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";
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>
@@ -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(",");
},
}),
+2 -1
View File
@@ -80,7 +80,8 @@
"AutocompletePopover",
"AutocompleteFilter",
"comboBoxVariants",
"autocompleteVariants"
"autocompleteVariants",
"createBaseContains"
],
"css": [
".hv-combo-box",
@@ -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");
});