ComboBox and Autocomplete need two capabilities the collection protocol did not express: filtering a collection by an external input value, and keeping DOM focus in the composite's input while an active option is tracked for aria-activedescendant. Both are opt-in members on CollectionOwner plus optionId/reveal on the owned collection. Standalone ListBox and Select provide none of them and keep their previous behaviour: DOM focus still moves into the list, one roving tab stop, no row filtering. Filtered rows stay mounted with data-filtered (display:none) so their text and accepted selection survive; only display, aria positions and keyboard navigation see the visible subset. Under virtual focus the list never takes DOM focus, never exposes a roving tab stop, and leaves keyboard handling to the composite; reveal() scrolls a virtualized window and waits for the row to mount before the composite reads its id. Includes the playground verification page, a ten-case suite and the B02a section of the migration report.
23 KiB
B02 ComboBox / Autocomplete — 审计、协议扩展与实现
分支 feat/b02-combobox-autocomplete,起点 84c4893(本地 main,含 B03 修复 20d34d7 与合并 eb10b6a)。按用户 2026-10-25 的分段安排推进:B02a 最小共享协议扩展(已实现)→ B02b ComboBox → B02c Autocomplete → B02d 收口。每段独立提交,不合 main、不推送。
固定基线 HeroUI 3.2.6 / ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960。建议开发端口 5182(已确认空闲;5174/5176/5181/5183 被其他工作区占用)。
1. 源契约:ComboBox(5 部件)
源文件:packages/react/src/components/combo-box/combo-box.tsx、packages/styles/components/combo-box.css、packages/styles/src/components/combo-box/combo-box.styles.ts、中文正文 (pickers)/combo-box.mdx、演示 demos/cn/combo-box(24 例)。
| 部件 | 源实现 | 关键 Props / 标记 |
|---|---|---|
ComboBox |
RAC ComboBox + FieldSlotsGate |
全部 RAC ComboBox props + variant(primary/secondary,默认 primary)、fullWidth(默认 false)、menuTrigger(默认 focus);data-slot="combo-box" |
ComboBox.InputGroup |
集合槽注入器:除末个子元素外为 siblings,末位必须是 Trigger;渲染 RAC Group + 内层 dom.div |
className、render;两处 data-slot="combo-box-input-group" |
ComboBox.Value |
RAC ComboBoxValue |
placeholder、children(含 render 函数);data-slot="combo-box-value" |
ComboBox.Trigger |
RAC Button |
默认子元素 IconChevronDown(data-slot="combo-box-trigger-default-icon");data-open、data-slot="combo-box-trigger";隐藏时返回 null |
ComboBox.Popover |
RAC Popover + SurfaceContext{variant:"default"} |
placement(默认 bottom);data-slot="combo-box-popover" |
变体槽:base / inputGroup / popover / trigger / value;fullWidth 追加 combo-box--full-width、combo-box__input-group--full-width。
CSS 要点:根 flex flex-col gap-1;无效时隐藏 [data-slot="description"];[data-slot="input"] 为 min-w-0 flex-1,紧跟 trigger 时 pe-7,并额外提供 :focus(不只是 focus-visible)的 status-focused-field;trigger 绝对定位 end-0 top-1/2 pe-2,data-open 时图标 rotate-180;popover min-w-(--trigger-width)、border-radius: min(32px, var(--radius-3xl))、进出场动画与 data-placement 位移;popover 内 [data-slot="list-box"] 为 p-1.5,item px-2.5 且单选的 checkmark 不做 transition。
公开预览清单(24,正文顺序):default(用法)、full-width、with-description、required、disabled、with-disabled-options、with-sections、controlled、controlled-input-value、asynchronous-loading、default-selected-key、allows-custom-value、custom-indicator、custom-value、custom-filtering、render-function、menu-trigger、form-value、validation-behavior、custom-validation、read-only、multiple-selection、on-surface、custom-styles。每例都有对应 .tsx,无孤儿文件。
各例关键差异(供实现后逐项核销):default 6 项(aardvark/cat/dog/kangaroo/panda/snake → 土豚/猫/狗/袋鼠/熊猫/蛇);full-width 3 项且外层 w-[400px];with-sections 12 项分北美洲/欧洲/亚洲三组 + Separator;controlled 5 项;controlled-input-value 受控 inputValue;asynchronous-loading 用 useAsyncList + SWAPI 真实网络、allowsEmptyCollection、Collection + ListBoxLoadMoreItem + Spinner + EmptyState;menu-trigger 三块(focus/input/manual);form-value 两个 ComboBox(formValue="key" name=animal、formValue="text" name=animal-text)+ Form + FieldError,输出 key:…。文本:…。;validation-behavior 两个 Form(native/aria);custom-validation validate 对 selectedKey 判定(空 → 请选择一种动物;snake → 不允许选择蛇);read-only isReadOnly + defaultSelectedKey="cat";multiple-selection 需同时在根与 ListBox 传 selectionMode="multiple" 并放 ComboBox.Value placeholder="未选择任何动物";on-surface 用 Surface + variant="secondary";custom-styles 用 data-[focused=true]/data-[selected=true] 定制 item。
2. 源契约:Autocomplete(7 部件)
源文件:packages/react/src/components/autocomplete/autocomplete.tsx、packages/styles/components/autocomplete.css、packages/styles/src/components/autocomplete/autocomplete.styles.ts、中文正文 (pickers)/autocomplete.mdx、演示 demos/cn/autocomplete(24 例)。
| 部件 | 源实现 | 关键 Props / 标记 |
|---|---|---|
Autocomplete(Root) |
RAC Select + FieldSlotsGate |
RAC Select props + fullWidth、variant(primary/secondary)、onClear;data-slot="autocomplete" |
Autocomplete.Trigger |
RAC Group |
点击时 state.toggle()(点在 ClearButton 内不切换);data-slot="autocomplete-trigger" |
Autocomplete.Value |
RAC SelectValue |
render 值 {defaultChildren, isPlaceholder, state, selectedItems, selectedText};data-slot="autocomplete-value" |
Autocomplete.Indicator |
RAC Button + 默认 IconChevronDown |
有子元素时 clone 并注入 class/data-slot/data-open;data-slot="autocomplete-indicator"、默认图标 autocomplete-default-indicator |
Autocomplete.Popover |
RAC Popover + SurfaceContext |
placement(默认 bottom)、--trigger-width 由 ResizeObserver 写入;data-slot="autocomplete-popover" |
Autocomplete.Filter |
RAC Autocomplete |
filter(text, input)、受控 inputValue、onInputChange;data-slot="autocomplete-filter" |
Autocomplete.ClearButton |
原生 button |
aria-label="Clear selection"、tabIndex=-1、data-empty、disabled=isDisabled;data-slot="autocomplete-clear-button" |
变体槽:base / clearButton / filter / indicator / popover / trigger / value;fullWidth 追加 autocomplete--full-width、autocomplete__trigger--full-width;variant 追加 autocomplete--primary / autocomplete--secondary。
CSS 要点:trigger 是 min-h-9 rounded-field border bg-field px-3 py-2 text-sm shadow-field 的可点击容器(不是 input),:has(.autocomplete__indicator) 时 pe-7,hover 排除 clear-button hover,invalid 用 status-invalid-field;--secondary 变体把背景改为 --default(无阴影);value flex-1 text-start text-base sm:text-sm,data-placeholder 用 field-placeholder 色,并隐藏 list-box-item-indicator;indicator 绝对定位 end-2,data-open 时 rotate-180;popover flex w-(--trigger-width) max-w-(--trigger-width) flex-col ... pt-2,进出场动画,内含 [data-slot="list-box"] max-h-[320px] min-h-0 overflow-y-auto p-1.5、[data-slot="search-field"] px-3 py-1、[data-slot="empty-state"] 居中 muted;虚拟行需要 [role="presentation"] > [data-slot="list-box-item"] { width: calc(100% - var(--spacing) * 3) };clear-button 24px 盒、data-empty 时 opacity-0 pointer-events-none。
公开预览清单(24,正文顺序):default(用法)、variants、full-width、with-description、required、disabled、with-disabled-options、allows-empty-collection、with-sections、multiple-select、controlled、controlled-multiple、controlled-open-state、asynchronous-filtering、custom-indicator、custom-value、on-surface、virtualization、高级示例:user-selection、user-selection-multiple、location-search、tag-group-selection、email-recipients、custom-styles。每例都有对应 .tsx。
3. 两者不是同一组件(组合差异)
| 维度 | ComboBox | Autocomplete |
|---|---|---|
| 底座语义 | RAC ComboBox(可编辑输入 + listbox) |
RAC Select + Autocomplete(选择器 + 弹层内搜索框) |
| 值输入方式 | 输入框文本即过滤条件,选中项回写输入框文本 | 触发器只显示值,搜索框在弹层内;触发文本不参与过滤 |
| 触发器 | InputGroup 内 Input + 绝对定位 Trigger 按钮 |
Trigger(可点击容器)+ Value + ClearButton + Indicator |
| 已选值展示 | Value 仅多选常用;单选值在输入框里 |
Value 是主要展示;多选常配合 TagGroup |
| 空集合 | allowsEmptyCollection(配合 async) |
allowsEmptyCollection(允许 0 项仍可交互) |
| 表单值 | formValue="key"|"text",allowsCustomValue 时强制文本 |
单一 name 提交 key |
| 自定义值 | allowsCustomValue(输入任意文本) |
不支持(值来自集合) |
| 过滤入口 | 根 defaultFilter |
Autocomplete.Filter filter / 受控 inputValue |
结论:必须分别实现两套部件与状态语义,不能用一个“可筛选输入框”顶替两者。
4. 复用计划(现有基建)
- 字段/校验:
useChoiceField+FieldError/Label/Description(B03 已验证的 field 协议),useChoiceValue处理受控/拒绝/默认值。 - 集合:
collection/selection(已接受值)、collection/registry(挂载成员、DOM 顺序)、collectionOwnerKey(ListBox 已消费:keys/mode/disabled/request/action/leave/connect)。 - 弹层:
components/popover/Popover+useOverlayState(Select 已用;非模态、Teleport、外部点击、退出动画)。 - 列表:公共
ListBox/ListBoxItem/ListBoxSection(演示已经直接使用)。 - 输入:
Input(ComboBox)与SearchField/SearchFieldGroup/SearchFieldInput(Autocomplete 弹层内搜索)。 - 展示值:
TagGroup/Tag(多选 Value 渲染)、Avatar、EmptyState、Spinner、Surface。
5. 共享缺口与 B02a 已落地的可选协议
两个缺口都在集成人维护的 collection 与 list-box 目录内。用户已明确授权本批做支持过滤与输入端虚拟焦点所必需的最小扩展(覆盖原提示词中禁止修改这些共享文件的限制),并保留 ListBox/Select 的默认行为。实现见第 8 节。
5.1 集合过滤(ComboBox defaultFilter、Autocomplete Filter filter)
- 复现:
<ComboBox><Input/><Trigger/></ComboBox><Popover><ListBox>静态 Item…</ListBox></Popover>;输入“猫”后源实现把不匹配项从集合中移除,键盘导航也只在匹配项之间移动。当前ListBox的known()/eligible()只按disabled过滤,没有“不可见”概念;静态子节点也无法被上层过滤。 - 最小接口建议(
CollectionOwner,可选、缺省不改变现状):visible?: (key: CollectionKey) => boolean。ListBox的eligible()/available()尊重它,ListBoxItem在为 false 时不渲染(或hidden,但需要同时不参与导航与aria-setsize)。 - 受影响:
collection/owner.ts、list-box/ListBox.vue、list-box/ListBoxItem.vue、list-box/context.ts;Select传入undefined时行为不变。 - 现有可绕过范围:数据驱动示例(
ListBox :items)可由调用方自行过滤(async/hybrid/virtualization 三例即如此),但源示例里的大多数是静态子节点 + 库内过滤,绕不过。
5.2 虚拟焦点 / aria-activedescendant(两者的键盘协作)
- 复现:ARIA combobox 模式要求 DOM 焦点留在输入框(ComboBox 的
Input、Autocomplete 弹层内的SearchField.Input),用aria-activedescendant指向高亮项。当前ListBox一律把 DOM 焦点移到条目(focus(key)→element.focus(),条目为 rovingtabindex),并把键盘处理挂在列表根上。焦点一旦离开输入框,连续输入就会中断;且在弹层里会多出第二个 Tab 入口。 - 最小接口建议:
CollectionOwner增加可选virtualFocus?: () => boolean与activeKey?: Ref<Key | undefined>;虚拟焦点开启时ListBox不移动 DOM 焦点、不设 rovingtabindex,仅把data-focused/data-active标记给活动项,aria-activedescendant由调用方(ComboBox/Autocomplete)在输入框上写出。 - 受影响:同上四个文件;
Select保持现状(它本来就应该把焦点移入列表)。 - 替代方案(需确认):由集成人先在 main 上补这两个可选成员,本批直接消费;或授权本批在分支内实现并随报告逐条说明(B03 的经验是共享改动会在合并时被逐项复核)。
6. 建议的实施拆分
本批源规模:12 个部件、48 个基线示例、2 页中文正文(754 行)、约 20 组行为契约(输入/选择/过滤/异步/IME/虚拟化/表单/校验)。相对 B03(3 个家族 14 例)大约 3–4 倍。
建议顺序(若同意继续):
- B02a ComboBox:先落地 5.1 + 5.2 的可选协议(若授权),实现 5 部件 + 24 例 + 文档 + 测试 + 独立消费 + 浏览器(IME、menuTrigger 三态、formValue、validate、多选 Value)。
- B02b Autocomplete:在稳定的过滤/虚拟焦点机制上实现 7 部件 + 24 例 + 文档 + 测试;多选 Value 按源文档的
selectedText提示处理(不复制 item children)。
若必须一次交回,建议至少先落地 5.1/5.2 的协议决策,再开始写 48 个演示,避免返工。
7. 待确认的框架差异(先记录,实现时逐条核销)
ListBox的空态是empty插槽,源是renderEmptyState;演示中<ListBox />自闭合 0 项(allows-empty-collection)需要对应写法。- 源
ComboBox.Value在多选时按集合分隔符连接 item children;Vue 侧不复制 children,改为selectedText等作用域值(与源文档给Autocomplete.Value的selectedText建议一致)。 - 源
renderprop → Vueas/as-child(与 B01/B03 一致);render-function示例保持源div根 +data-custom="foo"。 - 源
Collection(@react-stately)与Virtualizer:Vue 侧用ListBox :items+virtualized能力,异步用调用方状态;不引入第二个集合内核。 - 源
useFilter是公开导出;Vue 侧是否需要提供等价useFilter(contains/startsWith/endsWith + sensitivity)需要在实现时决定并写进 API 表,不能用私有实现假装等价。 IconChevronDown/CloseIcon默认图形:沿用本库既有基线图标做法(不自绘 SVG)。
8. B02a:最小共享协议扩展(已实现并单独提交)
范围:只增加可选的私有协议成员与消费端分支,不新增 ListBox 公共 prop、不复制集合内核、不改 Select/字段/弹层内核。
8.1 协议增量
collection/owner.ts:
export interface CollectionView {
filter?: (record: CollectionRecord) => boolean; // 展示与导航过滤
virtualFocus?: () => boolean; // 焦点留在组合体输入框
activeKey?: Ref<CollectionKey | undefined>; // 由组合体驱动的活动项
}
export interface OwnedCollection {
items: () => CollectionRecord[]; // 完整数据
focus: (edge: "first" | "last" | "selected") => Promise<void>;
optionId?: (key: CollectionKey) => string | undefined; // aria-activedescendant 用
reveal?: (key: CollectionKey) => Promise<void>; // 只滚动/等挂载,不取焦点
}
export interface CollectionOwner extends CollectionView {
/* 原有成员不变 */
}
四个成员全部可选;未提供的调用方(独立 ListBox、Select)行为完全不变。
8.2 数据层次(对应“完整数据 / 可见数据 / 可导航项 / 已挂载节点”)
| 层次 | 来源 | 用途 |
|---|---|---|
| 完整数据 | known()(items + registry 合并) |
已接受值、文本标签、表单提交、disabledKeys 判定 |
| 可见数据 | visibleKnown() = known() + filter |
渲染与 aria-setsize/posinset(虚拟化时) |
| 可导航项 | eligible() = 可见数据 - 禁用 |
方向键/Home/End/typeahead/全选/选区范围 |
| 已挂载节点 | registry.ordered()(DOM 顺序) |
邻项、焦点目标、optionId |
过滤不会清除已接受值,也不会卸载行:ListBoxItem 输出 data-filtered="true"(CSS display:none,见 list-box-item.css 新规则),因此文本与选择都保留。hidden 属性同时存在,但 display:flex 会覆盖它,故以属性选择器规则为准。
8.3 虚拟焦点
ListBox在virtualFocus()为真时:根tabindex=-1、条目恒为tabindex=-1(不再有 roving tab stop)、focus()不调用条目的element.focus(),只更新活动项、必要时滚动并await nextTick();keydown/keyup直接返回,键盘由组合体输入框负责。reveal(key)与focus(key)共用scrollRowIntoView;reveal只滚动并等待一帧,供组合体在行挂载后再读optionId(虚拟化时序)。ListBoxItem的isFocused/data-focused在虚拟焦点下取active === id;isFocusVisible要求键盘意图(keyboard)成立。active在虚拟焦点下直接读owner.activeKey.value,ListBox 不另存一份活动状态;focus()在用户点击条目时把该 key 写回activeKey(值相同则不写),不建立互相 watch 的环。
8.4 验证页
apps/playground/src/FilterVirtualLab.vue(http://localhost:5182/?filter-virtual),载体是 packages/vue/tests/fixtures/FilterVirtualCombobox.vue —— 一个最小组合框验证夹具(不是公共 ComboBox,也不会被导出)。三个实例:过滤 + 虚拟焦点、受控拒绝、关闭过滤的对照。
8.5 自动化结果(B02a)
tests/collection-filter-virtual.test.ts(10 项,已加入 test:unit 列表):
- 输入“狗”后只剩 1 行可见,4 行
data-filtered且计算样式display: none,行仍挂载、文本完整。 - 先选中“猫”再把“猫”过滤掉:已选文本仍是“猫”,该行仍
aria-selected="true"。 - 过滤后方向键只在可见且非禁用的行之间移动(只剩“鸟”时反复按下仍为“鸟”)。
- 输入框保持
document.activeElement;两次 ArrowDown 后aria-activedescendant指向已挂载的data-slot="list-box-item"节点,该节点可聚焦属性为-1、data-focused="true"、处于可见状态;列表根tabindex=-1。 - 过滤使可见集合变化后
aria-activedescendant同步更新;无匹配时移除该属性且无可见行。 - 点击行不会把焦点从输入框移走。
- 受控拒绝:
proposal发出两次(cat、dog),update:modelValue未发出、已接受值保持 null;父级改为接受后同一提案可再次提交成功。 - IME:composition 期间的输入不触发过滤,
isComposing的 Enter 不确认选择;compositionend 后才过滤。 reveal()不抢外部焦点,并给出已挂载行的optionId(该行的文本可查)。- 独立 ListBox 回归:仍移动真实焦点、保持一个 Tab 入口、无
data-filtered。
全量:pnpm typecheck 通过;pnpm test 75 文件 / 995 项通过(含既有 ListBox/Select/其它套件,无新增失败);pnpm build:playground、pnpm build:docs 通过;Prettier 与 git diff --check 通过。
8.6 浏览器证据(5182,Chromium/IAB)
- 输入“狗”:可见行
["狗"],4 行data-filtered且display: none,计数器“已隐藏:4”。 document.activeElement仍是[data-test="harness-input"];aria-activedescendant="v-1",该节点data-slot="list-box-item"、文本“狗”、data-focused="true"、tabindex="-1"、display: flex;列表根tabindex="-1";被过滤行tabindex="-1"。- 清空输入后两次 ArrowDown → 活动项“鸟”,Enter → 已选“鸟”、输入框回写“鸟”;再输入“猫”后可见行只剩“猫”,已选仍为“鸟”,且“鸟”行保持
aria-selected="true"(过滤不影响已接受值)。 - 受控拒绝实例:ArrowDown + Enter 后已选仍为“无”、无
aria-selected、焦点仍在输入框。 - 关闭过滤实例:输入“狗”后“已隐藏:0”、5 行可见。
未验证:真实 IME 组合输入(自动化后端无法产生系统 IME 序列,只用 CompositionEvent/isComposing 覆盖);虚拟化窗口内 reveal → 挂载 → optionId 的浏览器时序(jsdom 无布局,留到 B02d 与 ComboBox 一起在浏览器验证);读屏软件。
8.7 待复核要点
- 是否接受把
optionId/reveal放在OwnedCollection(集合侧实现)而不是CollectionOwner(组合体实现);reveal的语义是“滚动并等待挂载”,不改变选择。 data-filtered采用 CSSdisplay:none(而非卸载)以保住文本与选择;如果集成人更希望卸载,需要同时提供“完整数据”的独立来源,否则被过滤的已选项会失去标签。virtualFocus下 ListBox 完全不处理键盘(keydown/keyup提前返回);组合体必须自己实现方向键、Enter、Esc、Tab 与 IME 守卫。