feat(collection): add optional filtering and virtual focus for composite pickers

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.
This commit is contained in:
maoyingjie
2026-10-25 14:53:49 +08:00
parent fa73cafd20
commit 1b972a78ba
11 changed files with 849 additions and 30 deletions
+5
View File
@@ -13,6 +13,10 @@ const animationLab =
typeof window !== "undefined" &&
new URLSearchParams(window.location.search).has("overlay-animation");
import OverlayLab from "./OverlayLab.vue";
import FilterVirtualLab from "./FilterVirtualLab.vue";
const filterVirtualLab =
typeof window !== "undefined" &&
new URLSearchParams(window.location.search).has("filter-virtual");
import OverlayComponentsLab from "./OverlayComponentsLab.vue";
const componentsLab =
typeof window !== "undefined" &&
@@ -36,6 +40,7 @@ function save() {
<OverlayAnimationLab v-else-if="animationLab" />
<OverlayComponentsLab v-else-if="componentsLab" />
<OverlayLab v-else-if="overlayLab" />
<FilterVirtualLab v-else-if="filterVirtualLab" />
<div v-else class="lab" :data-theme="dark ? 'dark' : 'light'">
<header>
<a class="wordmark" href="#">
+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">
/**
* B02a verification page: proves the optional collection-owner protocol
* (filter + virtual focus) that ComboBox and Autocomplete will consume.
* This is a harness, not a public component.
*/
import FilterVirtualCombobox from "../../../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
</script>
<template>
<main
class="lab"
data-theme="light"
style="padding: 32px; display: grid; gap: 32px"
>
<header style="display: grid; gap: 8px">
<h1 style="font-size: 20px; font-weight: 600">B02a 过滤与虚拟焦点验证</h1>
<p style="font-size: 13px; color: var(--muted)">
输入“狗”或“鼠”过滤列表;方向键只在可见行之间移动;焦点始终留在输入框,高亮行由
aria-activedescendant 指向。第二个实例的父级拒绝选择提案。
</p>
</header>
<section style="display: grid; gap: 8px">
<h2 style="font-size: 15px; font-weight: 600">1. 过滤 + 虚拟焦点</h2>
<FilterVirtualCombobox />
</section>
<section style="display: grid; gap: 8px">
<h2 style="font-size: 15px; font-weight: 600">
2. 受控拒绝(选择提案不生效)
</h2>
<FilterVirtualCombobox :accept-selection="false" />
</section>
<section style="display: grid; gap: 8px">
<h2 style="font-size: 15px; font-weight: 600">3. 不过滤(对照)</h2>
<FilterVirtualCombobox :filter-enabled="false" />
</section>
</main>
</template>
+86 -4
View File
@@ -1,6 +1,6 @@
# B02 ComboBox / Autocomplete — 审计与设计(阶段一,未实现)
# B02 ComboBox / Autocomplete — 审计、协议扩展与实现
分支 `feat/b02-combobox-autocomplete`,起点 `84c4893`(本地 main,含 B03 修复 `20d34d7` 与合并 `eb10b6a`)。**本文件当前只记录审计、契约与设计决策;组件、文档、演示、测试尚未实现**,不能据此认为本批已交付。
分支 `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 被其他工作区占用)。
@@ -68,9 +68,9 @@ CSS 要点:trigger 是 `min-h-9 rounded-field border bg-field px-3 py-2 text-s
- 输入:`Input`(ComboBox)与 `SearchField`/`SearchFieldGroup`/`SearchFieldInput`(Autocomplete 弹层内搜索)。
- 展示值:`TagGroup`/`Tag`(多选 Value 渲染)、`Avatar`、`EmptyState`、`Spinner`、`Surface`。
## 5. 阻断性共享缺口(需决策,未擅自改协议)
## 5. 共享缺口与 B02a 已落地的可选协议
两个缺口都在集成人维护的 `collection` 与 `list-box` 目录内,本批按约定**不静默修改**。
两个缺口都在集成人维护的 `collection` 与 `list-box` 目录内。用户已明确授权本批做**支持过滤与输入端虚拟焦点所必需的最小扩展**(覆盖原提示词中禁止修改这些共享文件的限制),并保留 ListBox/Select 的默认行为。实现见第 8 节。
### 5.1 集合过滤(ComboBox `defaultFilter`、Autocomplete `Filter filter`)
@@ -105,3 +105,85 @@ CSS 要点:trigger 是 `min-h-9 rounded-field border bg-field px-3 py-2 text-s
4. 源 `Collection`(`@react-stately`)与 `Virtualizer`:Vue 侧用 `ListBox :items` + `virtualized` 能力,异步用调用方状态;不引入第二个集合内核。
5. 源 `useFilter` 是公开导出;Vue 侧是否需要提供等价 `useFilter`(contains/startsWith/endsWith + sensitivity)需要在实现时决定并写进 API 表,不能用私有实现假装等价。
6. `IconChevronDown` / `CloseIcon` 默认图形:沿用本库既有基线图标做法(不自绘 SVG)。
## 8. B02a:最小共享协议扩展(已实现并单独提交)
范围:只增加可选的私有协议成员与消费端分支,**不新增 ListBox 公共 prop、不复制集合内核、不改 Select/字段/弹层内核**。
### 8.1 协议增量
`collection/owner.ts`:
```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. 输入“狗”后只剩 1 行可见,4 行 `data-filtered` 且计算样式 `display: none`,行仍挂载、文本完整。
2. 先选中“猫”再把“猫”过滤掉:已选文本仍是“猫”,该行仍 `aria-selected="true"`。
3. 过滤后方向键只在可见且非禁用的行之间移动(只剩“鸟”时反复按下仍为“鸟”)。
4. 输入框保持 `document.activeElement`;两次 ArrowDown 后 `aria-activedescendant` 指向**已挂载**的 `data-slot="list-box-item"` 节点,该节点可聚焦属性为 `-1`、`data-focused="true"`、处于可见状态;列表根 `tabindex=-1`。
5. 过滤使可见集合变化后 `aria-activedescendant` 同步更新;无匹配时移除该属性且无可见行。
6. 点击行不会把焦点从输入框移走。
7. 受控拒绝:`proposal` 发出两次(`cat`、`dog`),`update:modelValue` 未发出、已接受值保持 null;父级改为接受后同一提案可再次提交成功。
8. IME:composition 期间的输入不触发过滤,`isComposing` 的 Enter 不确认选择;compositionend 后才过滤。
9. `reveal()` 不抢外部焦点,并给出已挂载行的 `optionId`(该行的文本可查)。
10. 独立 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` 采用 CSS `display:none`(而非卸载)以保住文本与选择;如果集成人更希望卸载,需要同时提供“完整数据”的独立来源,否则被过滤的已选项会失去标签。
- `virtualFocus` 下 ListBox 完全不处理键盘(`keydown/keyup` 提前返回);组合体必须自己实现方向键、Enter、Esc、Tab 与 IME 守卫。
+1 -1
View File
@@ -15,7 +15,7 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit",
"test": "vitest run",
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts tests/tag-error-message.test.ts",
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts tests/tag-error-message.test.ts tests/collection-filter-virtual.test.ts",
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts",
"format": "prettier --check .",
"format:fix": "prettier --write .",
@@ -3,6 +3,12 @@
Base list-box item styles
========================================================================== */
/* Owner-filtered rows stay mounted (text and selection survive) but leave
display and keyboard navigation. */
.hv-list-box-item[data-filtered="true"] {
display: none;
}
.hv-list-box-item {
@apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight;
@@ -1,16 +1,35 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { CollectionKey } from "./keys";
export interface CollectionRecord {
key: CollectionKey;
text: string;
disabled: boolean;
}
/** Filtering and virtual focus are optional: absent means the previous behaviour. */
export interface CollectionView {
/**
* Filter over the full data set. Filtered-out records stay mounted and keep
* their text/selection, but leave display and keyboard navigation.
*/
filter?: (record: CollectionRecord) => boolean;
/** Keep DOM focus outside the collection and track `activeKey` instead. */
virtualFocus?: () => boolean;
/** Active key for virtual focus; the owning composite drives it. */
activeKey?: Ref<CollectionKey | undefined>;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
focus: (edge: "first" | "last" | "selected") => Promise<void>;
/** Mounted DOM id of an option, for `aria-activedescendant`. */
optionId?: (key: CollectionKey) => string | undefined;
/**
* Make `key` the revealed row: scroll a virtualized window first, then wait
* for the row to mount. Never moves DOM focus.
*/
reveal?: (key: CollectionKey) => Promise<void>;
}
/** A field composite may own a ListBox, without adding another value store. */
export interface CollectionOwner {
export interface CollectionOwner extends CollectionView {
keys: ComputedRef<readonly CollectionKey[]>;
mode: ComputedRef<"single" | "multiple">;
disabled: ComputedRef<boolean>;
@@ -84,6 +84,10 @@ const disabled = useInheritedDisabled(
);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
// Optional owner-driven view: filtering and virtual focus stay off unless the
// composite asks for them, so standalone ListBox and Select are unchanged.
const virtualFocus = computed(() => !!owner?.virtualFocus?.());
const ownerFilter = computed(() => owner?.filter);
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
let disconnectOwner: (() => void) | undefined;
@@ -92,6 +96,8 @@ onMounted(() => {
if (owner)
disconnectOwner = owner.connect({
items: known,
optionId,
reveal,
focus: async (edge) => {
const available = eligible();
const key =
@@ -144,7 +150,16 @@ const known = () => {
}))
);
};
const eligible = () => known().filter((item) => !item.disabled);
/** Full data set with the owner filter applied: display and navigation only. */
const visibleKnown = () => {
const filter = ownerFilter.value;
const items = known();
return filter ? items.filter((item) => filter(item)) : items;
};
const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
@@ -172,6 +187,7 @@ const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
const items = eligible();
return (
@@ -207,6 +223,37 @@ onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
/** Mounted DOM id of an option; undefined while a virtualized row is unmounted. */
function optionId(key: ListBoxKey): string | undefined {
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
return element?.id || undefined;
}
function scrollRowIntoView(key: ListBoxKey) {
if (!props.virtualized) return;
const index = source.value.findIndex((item) => item.id === key);
if (index < 0) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
}
/** Reveal a row without taking DOM focus (virtual focus / activedescendant). */
async function reveal(key: ListBoxKey) {
if (disposing || disabled.value) return;
if (!eligible().some((item) => item.key === key)) return;
lastFocused.value = key;
scrollRowIntoView(key);
// Wait one tick so a virtualized row is mounted before the consumer reads
// its element id for aria-activedescendant.
await nextTick();
}
async function focus(key: ListBoxKey) {
if (
disposing ||
@@ -216,16 +263,12 @@ async function focus(key: ListBoxKey) {
return;
const request = ++focusRequest;
lastFocused.value = key;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
scrollRowIntoView(key);
if (virtualFocus.value) {
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await nextTick();
return;
}
await nextTick();
if (disposing || request !== focusRequest || disabled.value) return;
@@ -274,6 +317,7 @@ let search = "",
let pendingSpace: ListBoxKey | undefined;
function keydown(event: KeyboardEvent) {
if (
virtualFocus.value ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
@@ -406,6 +450,7 @@ function keydown(event: KeyboardEvent) {
}
}
function keyup(event: KeyboardEvent) {
if (virtualFocus.value) return;
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
@@ -442,14 +487,18 @@ provide(listBoxKey, {
activate,
focus,
virtualized: () => props.virtualized,
virtual: () => virtualFocus.value,
visible: (key) => visibleKeys.value.has(key),
optionId,
restoreFocus,
position: (key) =>
props.virtualized && data.value
? {
index: data.value.findIndex((item) => item.key === key) + 1,
size: data.value.length,
}
: undefined,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = ownerFilter.value ? visibleKnown() : data.value;
return {
index: items.findIndex((item) => item.key === key) + 1,
size: items.length,
};
},
});
function rootAttrs() {
if (mode.value === "single" && selection.keys.value.length > 1)
@@ -483,6 +532,7 @@ function rootAttrs() {
"aria-multiselectable":
mode.value === "none" ? undefined : mode.value === "multiple",
tabindex:
virtualFocus.value ||
disabled.value ||
(mounted.value &&
registry.available().some((member) => member.key() === active.value))
@@ -73,10 +73,16 @@ export default defineComponent({
const state = () => ({
isSelected: context.selected(props.id),
isDisabled: disabled.value,
isFocused: context.focused.value === props.id,
isFocusVisible:
context.focused.value === props.id &&
(context.keyboard.value || !!element.value?.matches(":focus-visible")),
// Under virtual focus the DOM focus stays in the composite's input, so the
// active key is what marks the row as focused.
isFocused: context.virtual()
? context.active.value === props.id
: context.focused.value === props.id,
isFocusVisible: context.virtual()
? context.keyboard.value && context.active.value === props.id
: context.focused.value === props.id &&
(context.keyboard.value ||
!!element.value?.matches(":focus-visible")),
isPressed:
(pressed.value || context.pressed.value === props.id) &&
!disabled.value,
@@ -149,6 +155,7 @@ export default defineComponent({
return () => {
const current = state();
const position = context.position(props.id);
const visible = context.visible(props.id);
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
@@ -160,7 +167,12 @@ export default defineComponent({
variant: props.variant,
}).item(),
tabindex:
!disabled.value && context.active.value === props.id ? 0 : -1,
!disabled.value &&
!context.virtual() &&
context.active.value === props.id
? 0
: -1,
hidden: visible ? undefined : true,
"aria-selected":
context.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
@@ -174,6 +186,7 @@ export default defineComponent({
text.describedBy(),
),
"data-slot": "list-box-item",
"data-filtered": visible ? undefined : true,
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
"data-focused": current.isFocused || undefined,
@@ -56,6 +56,11 @@ export interface ListBoxContext {
activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: ListBoxKey) => Promise<void>;
virtualized: () => boolean;
/** Keep DOM focus outside the collection; only the active key moves. */
virtual: () => boolean;
/** Whether the owner filter currently shows this record. */
visible: (key: ListBoxKey) => boolean;
optionId: (key: ListBoxKey) => string | undefined;
restoreFocus: () => void;
position: (key: ListBoxKey) => { index: number; size: number } | undefined;
}
+243
View File
@@ -0,0 +1,243 @@
<script setup lang="ts">
/**
* B02a verification harness: a minimal combobox that consumes the optional
* owner protocol (filter + virtual focus). It proves the protocol; it is NOT
* the public ComboBox.
*/
import { computed, nextTick, provide, ref, shallowRef } from "vue";
import { ListBox, ListBoxItem } from "@heroui-vue/components";
import {
collectionOwnerKey,
type CollectionOwner,
type CollectionRecord,
type OwnedCollection,
} from "../../src/components/collection/owner";
import type { CollectionKey } from "../../src/components/collection/keys";
interface Option {
id: CollectionKey;
text: string;
disabled?: boolean;
}
const props = withDefaults(
defineProps<{
options?: readonly Option[];
/** When false the parent rejects every selection proposal. */
acceptSelection?: boolean;
filterEnabled?: boolean;
}>(),
{
options: () => [
{ id: "cat", text: "猫" },
{ id: "dog", text: "狗" },
{ id: "bird", text: "鸟" },
{ id: "fish", text: "鱼" },
{ id: "hamster", text: "仓鼠" },
],
acceptSelection: true,
filterEnabled: true,
},
);
const emit = defineEmits<{
"update:modelValue": [key: CollectionKey | null];
proposal: [key: CollectionKey | null];
}>();
const labelId = "b02a-label";
const listId = "b02a-list";
const input = ref<HTMLInputElement>();
const inputValue = ref("");
const accepted = ref<CollectionKey | null>(null);
const activeKey = ref<CollectionKey>();
const activeId = ref<string>();
const open = ref(false);
const composing = ref(false);
const collection = shallowRef<OwnedCollection>();
const records = computed<CollectionRecord[]>(() =>
props.options.map((option) => ({
key: option.id,
text: option.text,
disabled: !!option.disabled,
})),
);
/** Filtering affects display and navigation only; accepted values stay. */
function filterRecord(record: CollectionRecord) {
if (!props.filterEnabled) return true;
const needle = inputValue.value.trim();
return !needle || record.text.includes(needle);
}
const eligible = computed(() =>
records.value.filter((record) => !record.disabled && filterRecord(record)),
);
/** Read from the full data set: a filtered-out selection keeps its label. */
const acceptedText = computed(
() => records.value.find((item) => item.key === accepted.value)?.text ?? null,
);
const hiddenCount = computed(
() => records.value.filter((record) => !filterRecord(record)).length,
);
function request(keys: CollectionKey[]) {
const next = keys[0] ?? null;
emit("proposal", next);
if (!props.acceptSelection) return;
accepted.value = next;
const record = records.value.find((item) => item.key === next);
if (record) inputValue.value = record.text;
emit("update:modelValue", next);
}
const owner: CollectionOwner = {
keys: computed(() => (accepted.value === null ? [] : [accepted.value])),
mode: computed(() => "single" as const),
disabled: computed(() => false),
readOnly: computed(() => false),
disabledKeys: computed(() =>
records.value
.filter((record) => record.disabled)
.map((record) => record.key),
),
id: listId,
labelledBy: () => labelId,
ariaLabel: () => undefined,
request,
action: () => {
open.value = false;
},
leave: () => {
open.value = false;
},
connect: (next: OwnedCollection) => {
collection.value = next;
return () => {
if (collection.value === next) collection.value = undefined;
};
},
filter: filterRecord,
virtualFocus: () => true,
activeKey,
};
provide(collectionOwnerKey, owner);
async function setActive(key: CollectionKey | undefined) {
activeKey.value = key;
if (key === undefined) {
activeId.value = undefined;
return;
}
// Reveal first (mounts a virtualized row), then read the mounted id.
await collection.value?.reveal?.(key);
activeId.value = collection.value?.optionId?.(key);
}
function moveActive(delta: 1 | -1) {
const items = eligible.value;
if (!items.length) {
void setActive(undefined);
return;
}
const index = items.findIndex((item) => item.key === activeKey.value);
const next =
index < 0
? items[delta > 0 ? 0 : items.length - 1]
: items[(index + delta + items.length) % items.length];
void setActive(next.key);
}
function onInput() {
if (composing.value) return;
inputValue.value = input.value?.value ?? "";
open.value = true;
void setActive(eligible.value[0]?.key);
}
function keydown(event: KeyboardEvent) {
// IME: never confirm while composing (Safari reports keyCode 229).
if (event.isComposing || composing.value || event.keyCode === 229) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) open.value = true;
moveActive(event.key === "ArrowDown" ? 1 : -1);
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (activeKey.value !== undefined) request([activeKey.value]);
open.value = false;
return;
}
if (event.key === "Escape" || event.key === "Tab") open.value = false;
}
function compositionStart() {
composing.value = true;
}
function compositionEnd() {
composing.value = false;
onInput();
void nextTick();
}
defineExpose({
inputValue,
accepted,
activeKey,
activeId,
open,
eligible: () => eligible.value,
hiddenCount: () => hiddenCount.value,
});
</script>
<template>
<div class="flex w-[256px] flex-col gap-1">
<label :id="labelId" class="text-sm font-medium" for="b02a-input">
动物(B02a 协议验证)
</label>
<input
id="b02a-input"
ref="input"
:value="inputValue"
aria-autocomplete="list"
:aria-activedescendant="activeId"
:aria-controls="listId"
:aria-expanded="open"
aria-labelledby="b02a-label"
autocomplete="off"
class="rounded-field border border-field-border bg-field px-3 py-2 text-sm"
data-test="harness-input"
role="combobox"
type="text"
@compositionend="compositionEnd"
@compositionstart="compositionStart"
@input="onInput"
@keydown="keydown"
/>
<p class="text-xs text-muted" data-test="accepted">
已选:{{ acceptedText ?? "无" }}
</p>
<p class="text-xs text-muted" data-test="hidden-count">
已隐藏:{{ hiddenCount }}
</p>
<div v-show="open" data-test="popover">
<ListBox :id="listId">
<ListBoxItem
v-for="option in options"
:id="option.id"
:key="option.id"
:is-disabled="option.disabled"
>
{{ option.text }}
</ListBoxItem>
</ListBox>
</div>
</div>
</template>
+355
View File
@@ -0,0 +1,355 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import { ListBox, ListBoxItem } from "../packages/vue/src";
import {
collectionOwnerKey,
type CollectionOwner,
type CollectionRecord,
type OwnedCollection,
} from "../packages/vue/src/components/collection/owner";
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
const wrappers: { unmount: () => void; element: Element }[] = [];
// jsdom gaps used by the virtualized reveal path; fill only when missing.
if (typeof Element.prototype.scrollTo !== "function")
Element.prototype.scrollTo = () => {};
function pointerEvent(type: string) {
return new MouseEvent(type, { bubbles: true, cancelable: true });
}
/** Vue skips an invoker when `e._vts <= invoker.attached`; cross the millisecond. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 2));
function root(): HTMLElement {
return (wrappers.at(-1)?.element as HTMLElement | undefined) ?? document.body;
}
const queryAll = <T extends Element = HTMLElement>(selector: string) => {
const element = root();
const found = [...element.querySelectorAll<T>(selector)];
if (element.matches(selector)) found.unshift(element as unknown as T);
return found;
};
const queryOne = <T extends Element = HTMLElement>(selector: string) =>
queryAll<T>(selector)[0] ?? null;
const rowTexts = () =>
queryAll('[data-slot="list-box-item"]')
.filter((row) => !row.hasAttribute("data-filtered"))
.map((row) => row.textContent?.trim());
async function mountHarness(props: Record<string, unknown> = {}) {
const wrapper = mount(Harness, { props, attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
return wrapper;
}
const inputEl = () =>
queryOne<HTMLInputElement>('[data-test="harness-input"]')!;
async function type(value: string) {
const element = inputEl();
element.value = value;
element.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await settle();
}
async function press(key: string, init: KeyboardEventInit = {}) {
inputEl().dispatchEvent(
new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
...init,
}),
);
await nextTick();
await settle();
}
afterEach(async () => {
while (wrappers.length) wrappers.pop()?.unmount();
await nextTick();
await settle();
vi.restoreAllMocks();
document.body.innerHTML = "";
});
describe("collection filter", () => {
it("hides non-matching rows but keeps their text and mount state", async () => {
await mountHarness();
expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
await type("狗");
expect(rowTexts()).toEqual(["狗"]);
const filtered = queryAll('[data-slot="list-box-item"]').filter((row) =>
row.hasAttribute("data-filtered"),
);
expect(filtered).toHaveLength(4);
// Filtered rows stay mounted so their text and selection survive.
expect(filtered.map((row) => row.textContent?.trim())).toEqual([
"猫",
"鸟",
"鱼",
"仓鼠",
]);
expect(getComputedStyle(filtered[0]).display).toBe("none");
expect(queryOne('[data-test="hidden-count"]')!.textContent).toContain("4");
});
it("keeps an accepted value when its row is filtered out", async () => {
const wrapper = await mountHarness();
await press("ArrowDown");
await press("Enter");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
await type("狗");
expect(rowTexts()).toEqual(["狗"]);
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
expect(
queryAll('[aria-selected="true"]').map((row) => row.textContent?.trim()),
).toEqual(["猫"]);
});
it("navigates only the visible rows and skips disabled ones", async () => {
const wrapper = await mountHarness({
options: [
{ id: "cat", text: "猫" },
{ id: "dog", text: "狗", disabled: true },
{ id: "bird", text: "鸟" },
{ id: "fish", text: "鱼" },
],
});
await type("鸟");
await press("ArrowDown");
expect(wrapper.vm.activeKey).toBe("bird");
// "狗" is disabled and "猫"/"鱼" are filtered out: the only row is 鸟.
await press("ArrowDown");
expect(wrapper.vm.activeKey).toBe("bird");
expect(rowTexts()).toEqual(["鸟"]);
});
});
describe("virtual focus", () => {
it("keeps DOM focus in the input and points activedescendant at the mounted row", async () => {
const wrapper = await mountHarness();
inputEl().focus();
expect(document.activeElement).toBe(inputEl());
await press("ArrowDown");
await press("ArrowDown");
expect(document.activeElement).toBe(inputEl());
expect(wrapper.vm.activeKey).toBe("dog");
const id = inputEl().getAttribute("aria-activedescendant");
expect(id).toBeTruthy();
const option = document.getElementById(id!);
expect(option).not.toBeNull();
expect(option!.getAttribute("data-slot")).toBe("list-box-item");
expect(option!.textContent?.trim()).toBe("狗");
expect(option!.getAttribute("data-focused")).toBe("true");
// The highlighted row is not a tab stop.
expect(option!.getAttribute("tabindex")).toBe("-1");
expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
"-1",
);
});
it("updates activedescendant after filtering changes the visible set", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await type("鼠");
expect(wrapper.vm.activeKey).toBe("hamster");
const id = inputEl().getAttribute("aria-activedescendant");
expect(document.getElementById(id!)?.textContent?.trim()).toBe("仓鼠");
await type("不存在");
expect(wrapper.vm.activeKey).toBeUndefined();
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
expect(rowTexts()).toEqual([]);
});
it("does not move focus when a row is clicked", async () => {
await mountHarness();
inputEl().focus();
await type("狗");
const row = queryAll('[data-slot="list-box-item"]').find(
(item) => !item.hasAttribute("data-filtered"),
)!;
row.dispatchEvent(pointerEvent("pointerdown"));
row.dispatchEvent(new MouseEvent("click", { bubbles: true }));
row.dispatchEvent(pointerEvent("pointerup"));
await nextTick();
await settle();
expect(document.activeElement).toBe(inputEl());
});
});
describe("controlled rejection", () => {
it("keeps the accepted value when the parent rejects the proposal", async () => {
const wrapper = await mountHarness({ acceptSelection: false });
await press("ArrowDown");
await press("Enter");
await press("ArrowDown");
await press("Enter");
expect(wrapper.emitted("proposal")).toEqual([["cat"], ["dog"]]);
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
expect(wrapper.vm.accepted).toBeNull();
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("无");
expect(queryAll('[aria-selected="true"]')).toHaveLength(0);
// A rejected proposal can be repeated once the parent accepts.
await wrapper.setProps({ acceptSelection: true });
await settle();
await press("Enter");
expect(wrapper.vm.accepted).toBe("dog");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["dog"]);
});
});
describe("IME composition", () => {
it("does not confirm or filter while composing", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await press("ArrowDown");
expect(wrapper.vm.activeKey).toBe("cat");
inputEl().dispatchEvent(new CompositionEvent("compositionstart"));
inputEl().value = "gou";
inputEl().dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await settle();
// Composition text does not filter yet.
expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
await press("Enter", { isComposing: true });
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
inputEl().dispatchEvent(new CompositionEvent("compositionend"));
await nextTick();
await settle();
// The committed text now filters, and no row was selected on the way.
expect(rowTexts()).toEqual([]);
expect(wrapper.vm.accepted).toBeNull();
});
});
describe("reveal without DOM focus", () => {
it("exposes the mounted option id and leaves DOM focus alone", async () => {
const activeKey = ref<string | number>();
let collection: OwnedCollection | undefined;
const owner = {
keys: ref([]),
mode: ref("single"),
disabled: ref(false),
readOnly: ref(false),
disabledKeys: ref([]),
id: "reveal-list",
labelledBy: () => undefined,
ariaLabel: () => undefined,
request: () => {},
action: () => {},
leave: () => {},
connect: (next: OwnedCollection) => {
collection = next;
return () => {
collection = undefined;
};
},
filter: (record: CollectionRecord) => !record.text.includes("隐藏"),
virtualFocus: () => true,
activeKey,
} as unknown as CollectionOwner;
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(ListBox, { "aria-label": "行" }, () => [
h(ListBoxItem, { id: "a" }, () => "第一行"),
h(ListBoxItem, { id: "b" }, () => "隐藏行"),
h(ListBoxItem, { id: "c" }, () => "第三行"),
]);
},
}),
{
attachTo: document.body,
global: {
provide: { [collectionOwnerKey as unknown as string]: owner },
},
},
);
wrappers.push(wrapper);
await nextTick();
await settle();
const outside = document.createElement("button");
document.body.appendChild(outside);
outside.focus();
expect(document.activeElement).toBe(outside);
await collection?.reveal?.("c");
await nextTick();
expect(document.activeElement).toBe(outside);
const id = collection?.optionId?.("c");
expect(id).toBeTruthy();
expect(document.getElementById(id!)?.textContent?.trim()).toBe("第三行");
expect(collection?.items().map((item) => item.key)).toEqual([
"a",
"b",
"c",
]);
});
});
describe("standalone ListBox unchanged", () => {
it("still moves DOM focus into the list and keeps one tab stop", async () => {
const wrapper = mount(
defineComponent({
setup() {
return () =>
h("div", [
h(ListBox, { "aria-label": "动物" }, () => [
h(ListBoxItem, { id: "cat" }, () => "猫"),
h(ListBoxItem, { id: "dog" }, () => "狗"),
]),
]);
},
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const rows = queryAll('[data-slot="list-box-item"]');
expect(rows).toHaveLength(2);
expect(rows.map((row) => row.getAttribute("tabindex"))).toEqual([
"0",
"-1",
]);
expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
"-1",
);
// No owner filter is provided, so nothing is hidden.
expect(rows.some((row) => row.hasAttribute("data-filtered"))).toBe(false);
rows[0].dispatchEvent(
new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }),
);
await nextTick();
await settle();
expect(document.activeElement?.textContent?.trim()).toBe("狗");
});
});