fix(collection): close the six review gaps in filtering and virtual focus

- Keep the composite input focused on real pointer presses: cancel the default
  focus transfer for plain row presses only, leaving nested controls and already
  cancelled callers alone.
- Drive the virtual window, total height, reveal index and aria positions from
  the visible subset, and render the empty channel when filtering removes every
  row. Non-virtualized rows stay mounted and are hidden, so their text and
  accepted selection survive.
- Scroll mounted rows for reveal/focus outside virtualization, wait for a
  virtualized row to mount (frame-based, bounded), and drop reveal requests that
  filtering, closing or unmounting made obsolete.
- Stop overwriting caller `hidden`: mergeProps deletes an earlier key when a
  later value is undefined, so the filter now only adds `hidden` when the caller
  did not set it.
- Share keyboard modality through an optional `keyboardIntent` ref so a pointer
  press no longer leaves the active row without data-focus-visible.
- Give the verification harness instance-unique ids and derive
  aria-activedescendant from open state, mounted id and filter visibility.

Adds the reviewer probe plus eight regressions, and a virtualized harness
instance for the browser smoke of filtering plus window/height/positions.
This commit is contained in:
maoyingjie
2026-10-25 16:28:33 +08:00
parent 1b972a78ba
commit 50ad3ca180
9 changed files with 511 additions and 55 deletions
+14
View File
@@ -5,6 +5,11 @@
* This is a harness, not a public component.
*/
import FilterVirtualCombobox from "../../../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
const manyOptions = Array.from({ length: 40 }, (_, index) => ({
id: `row-${index}`,
text: `第 ${index} 行`,
}));
</script>
<template>
@@ -37,5 +42,14 @@ import FilterVirtualCombobox from "../../../packages/vue/tests/fixtures/FilterVi
<h2 style="font-size: 15px; font-weight: 600">3. 不过滤(对照)</h2>
<FilterVirtualCombobox :filter-enabled="false" />
</section>
<section style="display: grid; gap: 8px">
<h2 style="font-size: 15px; font-weight: 600">4. 虚拟窗口 + 过滤</h2>
<p style="font-size: 13px; color: var(--muted)">
40 行数据,只渲染可见 4 行;输入“1”过滤后窗口、总高度与 posinset/setsize
都应随可见集合收缩。
</p>
<FilterVirtualCombobox :options="manyOptions" :virtualized="true" />
</section>
</main>
</template>
@@ -187,3 +187,33 @@ export interface CollectionOwner extends CollectionView {
- 是否接受把 `optionId`/`reveal` 放在 `OwnedCollection`(集合侧实现)而不是 `CollectionOwner`(组合体实现);`reveal` 的语义是“滚动并等待挂载”,不改变选择。
- `data-filtered` 采用 CSS `display:none`(而非卸载)以保住文本与选择;如果集成人更希望卸载,需要同时提供“完整数据”的独立来源,否则被过滤的已选项会失去标签。
- `virtualFocus` 下 ListBox 完全不处理键盘(`keydown/keyup` 提前返回);组合体必须自己实现方向键、Enter、Esc、Tab 与 IME 守卫。
## 9. B02a 复核返修(六类问题,第二轮)
按 [B02a 复核](/private/tmp/B02a-review.md) 集中修复,独立提交。复核探针已固化到 `tests/b02a-review.probe.test.ts` 并加入 `test:unit`,5 项从全红转为全绿;本轮再加 8 项自有回归,合计 `tests/collection-filter-virtual.test.ts` 18 项。
| # | 问题 | 修复 | 证据 |
| --- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | 真实指针点击丢输入焦点(落到 body) | `ListBoxItem` 在虚拟焦点下对 `pointerdown` 与 `mousedown` 的默认焦点转移做 `preventDefault`;嵌套交互控件(`button/a/input/select/textarea/[contenteditable]`)例外;调用方已 `preventDefault` 时不再插手;pointerdown 的按下态逻辑保留 | 浏览器:填“狗”后**真实点击**选项,`document.activeElement` 仍为 input,已选“狗”;单测断言 `pointerdown`/`mousedown` 均 `defaultPrevented`,嵌套 `<button>` 不被取消 |
| 2 | 虚拟窗口仍用完整 items | `visibleItems` 作为 `source`,`useVirtualList` 窗口/总高度、`scrollRowIntoView` 索引、`aria-posinset/setsize` 全部改为可见集合;完整数据仍由 `known()` 提供;`empty` 插槽改为“可见集合为空”时渲染(items 模式) | 浏览器:40 行 → 过滤“第 7”后 `renderedSlots` 40→1、wrapper 高度 1280px→**32px**、`setsize` 40→**1**、`posinset` 1、“已隐藏:39”,焦点仍在输入框;单测断言 6→1 且无固定高度占位 |
| 3 | 普通长列表 reveal/focus 不滚动 | `revealRow()` 区分两条路径:虚拟化按索引滚窗口并 `waitForMountedRow`(最多 3 帧,`requestAnimationFrame` 优先,非浏览器回退 `nextTick`);非虚拟化等一帧后对已挂载行 `scrollIntoView({block:"nearest"})`。`focus` 的虚拟分支复用同一路径,并用 `revealRequest` 令牌丢弃被过滤/关闭/卸载作废的旧请求 | 单测:`scrollIntoView` spy 在无布局环境下被调用且不抢焦点;探针同项通过 |
| 4 | 新增 `hidden` 覆盖调用方属性 | 根因是 `mergeProps` 在后一个值为 `undefined` 时会**删除**前一个键。改为仅在“被过滤且调用方未设置 hidden”时才附加 `hidden`(条件展开,不写 `undefined` 键);`data-filtered` 仍由样式表 `display:none` 负责 | 探针“preserves caller hidden”通过;新增断言:可见行不带 `hidden`,被过滤行同时有 `hidden` 与 `data-filtered` |
| 5 | 指针后键盘意图无法恢复 | `CollectionView` 增加可选 `keyboardIntent?: Ref<boolean>`;`ListBox` 直接**复用**该 ref(不再 `ref(true)`),指针按下仍写 false,组合体在键盘事件里写 true,单一状态源 | 单测与浏览器均通过:指针点击行后再 ArrowDown,活动行同时有 `data-focused="true"` 与 `data-focus-visible="true"` |
| 6 | 验证夹具关联串实例、关闭后残留 activedescendant | 夹具改用 `useId()` 生成 `label/input/list` 三个实例唯一 id;新增 `resolveActiveId()`(要求开放、key 存在、`optionId` 已挂载、未被 `data-filtered` 隐藏)并用 `watchEffect` 统一从“键盘/指针/过滤/开关”任一来源同步;关闭即移除属性 | 浏览器:34 个 id 全部唯一;Escape 后 `aria-expanded="false"` 且 `aria-activedescendant` 为 null;指针点击“鸟”后 activedescendant 同步为“鸟”;过滤掉活动行或关闭时属性消失(单测覆盖三种场景) |
### 9.1 其他变更
- `ListBox` 模板重构为:非 `items` 模式渲染默认插槽;`items` 模式先按可见集合决定是否渲染 `empty`,虚拟化只渲染可见窗口,非虚拟化仍渲染**全部**行(由 `data-filtered` 隐藏),因此复核要求“非虚拟集合保留被过滤成员 DOM”成立。
- 夹具新增 `virtualized` 模式与 `empty` 通道,验证页新增第 4 个实例(40 行 + 虚拟窗口)用于过滤/窗口/高度/posinset 的浏览器烟测。
- 夹具的 `action` 不再关闭弹层(注释说明原因):关闭行为属于 B02b 的 ComboBox,保留开放状态才能观察指针→活动键→activedescendant 的同步。
### 9.2 本轮验证
- `pnpm typecheck` 通过;`pnpm test` **76 文件 / 1008 项**(既有 995 - 10 + 18 + 复核探针 5 = 1008,含全部 ListBox/Select 回归);`pnpm build:playground`、`pnpm build:docs` 通过;Prettier 与 `git diff --check` 通过。
- 浏览器(5182):真实点击保焦点、指针后键盘意图恢复、Escape 清除 activedescendant、40→1 的窗口/高度/posinset 收缩、多实例 id 唯一,均已逐项核对。
### 9.3 仍然未验证
- 真实系统 IME(自动化后端无法产生系统组合输入,只有 `CompositionEvent`/`isComposing` 覆盖)。
- 读屏软件播报。
- 验证夹具自身的滚动容器:库里 `.hv-list-box` 的 `overflow: clip` 会盖掉示例给的 `overflow-y-auto`(夹具与公共样式的组合问题,不影响协议;B02b 的 ComboBox 用 Popover 容器承载滚动,需单独核对)。这一条已记录,不当作已解决。
+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 tests/collection-filter-virtual.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 tests/b02a-review.probe.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 .",
@@ -16,6 +16,12 @@ export interface CollectionView {
virtualFocus?: () => boolean;
/** Active key for virtual focus; the owning composite drives it. */
activeKey?: Ref<CollectionKey | undefined>;
/**
* Keyboard modality shared with the composite that holds DOM focus. The
* collection clears it on pointer presses; the composite sets it on keys, so
* there is one source instead of a second copy.
*/
keyboardIntent?: Ref<boolean>;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
@@ -185,7 +185,8 @@ const selection = useCollectionSelection({
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
// Pointer presses clear keyboard intent; the composite sets it again on keys.
const keyboard = owner?.keyboardIntent ?? ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
@@ -197,7 +198,18 @@ const active = computed(() => {
items[0]?.key
);
});
const source = computed(() => (props.items ? [...props.items] : []));
/**
* Items as the caller passed them, restricted to the visible subset. The full
* data set stays available through `known()` for text and accepted values.
*/
const visibleItems = computed(() => {
const items = props.items ? [...props.items] : [];
const filter = ownerFilter.value;
if (!items.length || !filter) return items;
const visible = visibleKeys.value;
return items.filter((item) => visible.has(item.id));
});
const source = computed(() => visibleItems.value);
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
@@ -231,28 +243,54 @@ function optionId(key: ListBoxKey): string | undefined {
?.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);
const nextFrame = (): Promise<void> =>
typeof requestAnimationFrame === "function"
? new Promise((resolve) => requestAnimationFrame(() => resolve()))
: nextTick();
/** A virtualized row mounts after the window moves; wait for it, bounded. */
async function waitForMountedRow(key: ListBoxKey) {
for (let attempt = 0; attempt < 3; attempt++) {
if (registry.ordered().some((member) => member.key() === key)) return;
await nextFrame();
}
}
/**
* Bring a row into view without taking DOM focus. Virtualized lists move the
* window by index; ordinary lists scroll the mounted row (the row itself may
* sit inside any scroll container supplied by the caller).
*/
async function revealRow(key: ListBoxKey) {
if (props.virtualized) {
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);
await waitForMountedRow(key);
return;
}
await nextTick();
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
element?.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/** 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;
const request = ++revealRequest;
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();
await revealRow(key);
// A newer request, filtering, close or unmount makes this one obsolete.
if (disposing || request !== revealRequest) return;
}
async function focus(key: ListBoxKey) {
if (
@@ -263,14 +301,15 @@ async function focus(key: ListBoxKey) {
return;
const request = ++focusRequest;
lastFocused.value = key;
scrollRowIntoView(key);
if (virtualFocus.value) {
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await nextTick();
const revealToken = ++revealRequest;
await revealRow(key);
if (disposing || revealToken !== revealRequest) return;
return;
}
await nextTick();
await revealRow(key);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
@@ -493,9 +532,9 @@ provide(listBoxKey, {
restoreFocus,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = ownerFilter.value ? visibleKnown() : data.value;
const items = visibleItems.value;
return {
index: items.findIndex((item) => item.key === key) + 1,
index: items.findIndex((item) => item.id === key) + 1,
size: items.length,
};
},
@@ -574,24 +613,28 @@ defineExpose({
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<slot v-else-if="!items.length" name="empty" />
<div
v-else-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<template v-else>
<!-- Filtered-empty still needs a visible channel; non-virtualized rows
keep their DOM and are only hidden by data-filtered. -->
<slot v-if="!visibleItems.length" name="empty" />
<div
v-for="entry in windowItems"
:key="entry.data.id"
v-if="virtualized"
v-bind="wrapperProps"
role="presentation"
:style="{ height: `${rowHeight}px` }"
data-slot="list-box-virtual-content"
>
<slot :item="entry.data" :index="entry.index" />
<div
v-for="entry in windowItems"
:key="entry.data.id"
role="presentation"
:style="{ height: `${rowHeight}px` }"
>
<slot :item="entry.data" :index="entry.index" />
</div>
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
</component>
</template>
@@ -139,6 +139,23 @@ export default defineComponent({
else context.restoreFocus();
}
});
/**
* Native presses move focus to the pressed element (or body for a
* non-focusable row). Under virtual focus the composite's input must keep
* focus, so the default focus transfer is cancelled here — but only for a
* plain row press: nested controls keep their own focus behaviour and a
* caller that already cancelled is respected.
*/
function keepInputFocus(event: MouseEvent | PointerEvent) {
if (!context.virtual() || event.defaultPrevented) return;
if (event instanceof MouseEvent && event.button !== 0) return;
const target = event.target as Element | null;
const nested = target?.closest?.(
'button, a, input, select, textarea, [contenteditable="true"]',
);
if (nested && nested !== element.value) return;
event.preventDefault();
}
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
@@ -156,6 +173,10 @@ export default defineComponent({
const current = state();
const position = context.position(props.id);
const visible = context.visible(props.id);
// Never emit an undefined-valued key over the caller's attribute:
// mergeProps removes the earlier key when a later value is undefined.
const hideFiltered =
!visible && (attrs as Record<string, unknown>).hidden === undefined;
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
@@ -172,7 +193,6 @@ export default defineComponent({
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,
@@ -186,6 +206,10 @@ export default defineComponent({
text.describedBy(),
),
"data-slot": "list-box-item",
// Filtered rows stay mounted and are hidden, not removed, so their
// text and accepted selection survive. `hidden` is only added when the
// caller did not set it; the stylesheet also hides data-filtered.
...(hideFiltered ? { hidden: true } : {}),
"data-filtered": visible ? undefined : true,
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
@@ -209,6 +233,7 @@ export default defineComponent({
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
keepInputFocus(event);
if (
!event.defaultPrevented &&
!disabled.value &&
@@ -216,6 +241,11 @@ export default defineComponent({
)
pressed.value = true;
},
onMousedown: (event: MouseEvent) => {
// Chromium transfers focus on mousedown even when pointerdown was
// cancelled, so the same rule is applied to both events.
keepInputFocus(event);
},
}),
children,
);
+81 -16
View File
@@ -4,7 +4,15 @@
* owner protocol (filter + virtual focus). It proves the protocol; it is NOT
* the public ComboBox.
*/
import { computed, nextTick, provide, ref, shallowRef } from "vue";
import {
computed,
nextTick,
provide,
ref,
shallowRef,
useId,
watchEffect,
} from "vue";
import { ListBox, ListBoxItem } from "@heroui-vue/components";
import {
collectionOwnerKey,
@@ -26,6 +34,8 @@ const props = withDefaults(
/** When false the parent rejects every selection proposal. */
acceptSelection?: boolean;
filterEnabled?: boolean;
/** Render the collection through ListBox's virtualized items mode. */
virtualized?: boolean;
}>(),
{
options: () => [
@@ -37,6 +47,7 @@ const props = withDefaults(
],
acceptSelection: true,
filterEnabled: true,
virtualized: false,
},
);
@@ -45,8 +56,11 @@ const emit = defineEmits<{
proposal: [key: CollectionKey | null];
}>();
const labelId = "b02a-label";
const listId = "b02a-list";
// Instance-unique ids: several harnesses coexist on the verification page.
const uid = useId();
const labelId = `${uid}-label`;
const inputId = `${uid}-input`;
const listId = `${uid}-list`;
const input = ref<HTMLInputElement>();
const inputValue = ref("");
const accepted = ref<CollectionKey | null>(null);
@@ -54,6 +68,8 @@ const activeKey = ref<CollectionKey>();
const activeId = ref<string>();
const open = ref(false);
const composing = ref(false);
/** Shared modality: ListBox clears it on pointer presses, keys restore it. */
const keyboardIntent = ref(true);
const collection = shallowRef<OwnedCollection>();
const records = computed<CollectionRecord[]>(() =>
@@ -108,9 +124,9 @@ const owner: CollectionOwner = {
labelledBy: () => labelId,
ariaLabel: () => undefined,
request,
action: () => {
open.value = false;
},
// The harness stays open after a pick so the active-key/id sync is observable;
// closing behaviour belongs to the real ComboBox.
action: () => {},
leave: () => {
open.value = false;
},
@@ -123,18 +139,42 @@ const owner: CollectionOwner = {
filter: filterRecord,
virtualFocus: () => true,
activeKey,
keyboardIntent,
};
provide(collectionOwnerKey, owner);
/**
* The id is only usable when the list is open and the row is mounted, visible
* and not filtered out; otherwise the attribute must disappear.
*/
function resolveActiveId(): string | undefined {
if (!open.value) return undefined;
const key = activeKey.value;
if (key === undefined) return undefined;
const id = collection.value?.optionId?.(key);
if (!id) return undefined;
const element =
typeof document === "undefined" ? null : document.getElementById(id);
if (!element || element.hasAttribute("data-filtered")) return undefined;
return id;
}
// One derivation for every path that can move the active key: keyboard,
// pointer clicks inside the list, filtering and open/close.
watchEffect(() => {
void eligible.value.length;
void collection.value;
activeId.value = resolveActiveId();
});
async function setActive(key: CollectionKey | undefined) {
activeKey.value = key;
if (key === undefined) {
activeId.value = undefined;
return;
if (key !== undefined) {
// Reveal first (mounts a virtualized row); the effect above re-reads the id
// once the row is actually mounted.
await collection.value?.reveal?.(key);
}
// Reveal first (mounts a virtualized row), then read the mounted id.
await collection.value?.reveal?.(key);
activeId.value = collection.value?.optionId?.(key);
activeId.value = resolveActiveId();
}
function moveActive(delta: 1 | -1) {
@@ -161,6 +201,7 @@ function onInput() {
function keydown(event: KeyboardEvent) {
// IME: never confirm while composing (Safari reports keyCode 229).
if (event.isComposing || composing.value || event.keyCode === 229) return;
keyboardIntent.value = true;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) open.value = true;
@@ -199,18 +240,18 @@ defineExpose({
<template>
<div class="flex w-[256px] flex-col gap-1">
<label :id="labelId" class="text-sm font-medium" for="b02a-input">
<label :id="labelId" class="text-sm font-medium" :for="inputId">
动物(B02a 协议验证)
</label>
<input
id="b02a-input"
:id="inputId"
ref="input"
:value="inputValue"
aria-autocomplete="list"
:aria-activedescendant="activeId"
:aria-controls="listId"
:aria-expanded="open"
aria-labelledby="b02a-label"
:aria-labelledby="labelId"
autocomplete="off"
class="rounded-field border border-field-border bg-field px-3 py-2 text-sm"
data-test="harness-input"
@@ -228,7 +269,28 @@ defineExpose({
已隐藏:{{ hiddenCount }}
</p>
<div v-show="open" data-test="popover">
<ListBox :id="listId">
<ListBox
v-if="virtualized"
:id="listId"
:items="options"
:row-height="32"
:virtualized="true"
class="max-h-[128px] overflow-y-auto"
>
<template #default="{ item }">
<ListBoxItem
:id="item.id"
:key="item.id"
:is-disabled="item.disabled"
>
{{ item.text }}
</ListBoxItem>
</template>
<template #empty>
<p data-test="empty">没有匹配项</p>
</template>
</ListBox>
<ListBox v-else :id="listId">
<ListBoxItem
v-for="option in options"
:id="option.id"
@@ -237,6 +299,9 @@ defineExpose({
>
{{ option.text }}
</ListBoxItem>
<template #empty>
<p data-test="empty">没有匹配项</p>
</template>
</ListBox>
</div>
</div>
+123
View File
@@ -0,0 +1,123 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
import { ListBox, ListBoxItem } from "../packages/vue/src";
import {
collectionOwnerKey,
type CollectionOwner,
type OwnedCollection,
} from "../packages/vue/src/components/collection/owner";
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
const mounted: { unmount(): void }[] = [];
afterEach(() => {
while (mounted.length) mounted.pop()!.unmount();
vi.restoreAllMocks();
});
const settle = async () => {
await nextTick();
await new Promise((r) => setTimeout(r, 3));
};
function setupList(virtualized = false) {
let collection: OwnedCollection | undefined;
const items = Array.from({ length: 6 }, (_, id) => ({
id,
textValue: `Row ${id}`,
}));
const activeKey = ref<string | number>();
const owner: CollectionOwner = {
keys: computed(() => []),
mode: computed(() => "single"),
disabled: computed(() => false),
readOnly: computed(() => false),
disabledKeys: computed(() => []),
id: "probe",
labelledBy: () => undefined,
ariaLabel: () => "Probe",
request: () => {},
action: () => {},
leave: () => {},
connect: (c) => {
collection = c;
return () => {
collection = undefined;
};
},
filter: (r) => r.key === 3,
virtualFocus: () => true,
activeKey,
};
const wrapper = mount(
defineComponent({
setup() {
provide(collectionOwnerKey, owner);
return () =>
h(
ListBox,
{ items, virtualized, rowHeight: 40, overscan: 8 },
{
default: ({ item }: { item: (typeof items)[number] }) =>
h(ListBoxItem, { id: item.id }, () => item.textValue),
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
return { wrapper, collection: () => collection };
}
it("preserves caller hidden on an ordinary ListBoxItem", async () => {
const w = mount(ListBox, {
slots: {
default: () =>
h(ListBoxItem, { id: "hidden", hidden: true }, () => "Hidden"),
},
});
mounted.push(w);
await settle();
expect(w.find('[role="option"]').attributes("hidden")).toBeDefined();
});
it("reveal scrolls a mounted ordinary row without moving DOM focus", async () => {
const { wrapper, collection } = setupList();
await settle();
const node = wrapper.findAll('[role="option"]')[3].element;
const scroll = vi.fn();
Object.defineProperty(node, "scrollIntoView", {
configurable: true,
value: scroll,
});
await collection()!.reveal!(3);
expect(scroll).toHaveBeenCalled();
});
it("virtual window contains no fixed height slots for filtered-out rows", async () => {
const { wrapper } = setupList(true);
await settle();
expect(
wrapper.findAll(
'[data-slot="list-box-virtual-content"] > [role="presentation"]',
),
).toHaveLength(1);
});
it("restores keyboard highlight intent after a pointer interaction", async () => {
const w = mount(Harness, { attachTo: document.body });
mounted.push(w);
await settle();
const input = w.find("input");
await input.setValue("");
await settle();
await w.findAll('[role="option"]')[0].trigger("pointerdown");
await input.trigger("keydown", { key: "ArrowDown" });
await settle();
expect(w.find('[data-focused="true"]').attributes("data-focus-visible")).toBe(
"true",
);
});
it("has instance-unique names and controls in the verification harness", async () => {
const w = mount(
defineComponent({ setup: () => () => h("div", [h(Harness), h(Harness)]) }),
);
mounted.push(w);
await settle();
const ids = w.findAll("[id]").map((n) => n.attributes("id"));
expect(new Set(ids).size).toBe(ids.length);
});
+145
View File
@@ -98,6 +98,10 @@ describe("collection filter", () => {
"鱼",
"仓鼠",
]);
// Hidden for assistive tech and without the stylesheet; the library CSS
// additionally forces display:none (verified in the browser pass).
expect(filtered[0].hasAttribute("hidden")).toBe(true);
expect(filtered[0].getAttribute("data-filtered")).toBe("true");
expect(getComputedStyle(filtered[0]).display).toBe("none");
expect(queryOne('[data-test="hidden-count"]')!.textContent).toContain("4");
});
@@ -353,3 +357,144 @@ describe("standalone ListBox unchanged", () => {
expect(document.activeElement?.textContent?.trim()).toBe("狗");
});
});
describe("B02a review regressions", () => {
it("cancels the pointer default only for plain row presses", async () => {
await mountHarness();
inputEl().focus();
await type("狗");
const row = queryAll('[data-slot="list-box-item"]').find(
(item) => !item.hasAttribute("data-filtered"),
)!;
const pointer = pointerEvent("pointerdown");
row.dispatchEvent(pointer);
const mouse = new MouseEvent("mousedown", {
bubbles: true,
cancelable: true,
});
row.dispatchEvent(mouse);
await nextTick();
// The default focus transfer is cancelled so the input keeps focus.
expect(pointer.defaultPrevented).toBe(true);
expect(mouse.defaultPrevented).toBe(true);
// A nested control keeps its own focus behaviour.
const nested = document.createElement("button");
row.appendChild(nested);
const nestedPointer = pointerEvent("pointerdown");
nested.dispatchEvent(nestedPointer);
expect(nestedPointer.defaultPrevented).toBe(false);
// A caller that already cancelled is not overridden into a second action.
const cancelled = new MouseEvent("mousedown", {
bubbles: true,
cancelable: true,
});
cancelled.preventDefault();
row.dispatchEvent(cancelled);
});
it("keeps caller hidden semantics next to filtering", async () => {
const wrapper = await mountHarness();
await type("狗");
// Filtered row is hidden by the filter, not by a caller attribute.
const filtered = queryAll('[data-slot="list-box-item"]').find((item) =>
item.hasAttribute("data-filtered"),
)!;
expect(filtered.hasAttribute("hidden")).toBe(true);
// Visible rows never gain hidden from the filter.
const visible = queryAll('[data-slot="list-box-item"]').find(
(item) => !item.hasAttribute("data-filtered"),
)!;
expect(visible.hasAttribute("hidden")).toBe(false);
expect(wrapper.vm.accepted).toBeNull();
});
it("computes virtual aria positions from the visible subset", async () => {
const wrapper = await mountHarness({ virtualized: true });
await type("鼠");
const rows = queryAll('[data-slot="list-box-item"]');
expect(rows).toHaveLength(1);
expect(rows[0].getAttribute("aria-posinset")).toBe("1");
expect(rows[0].getAttribute("aria-setsize")).toBe("1");
expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([
"hamster",
]);
});
it("renders the empty channel when filtering removes every row", async () => {
await mountHarness({ virtualized: true });
await type("不存在");
expect(rowTexts()).toEqual([]);
expect(queryOne('[data-test="empty"]')).not.toBeNull();
});
it("scrolls an ordinary mounted row on reveal and on keyboard focus", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const rows = queryAll('[data-slot="list-box-item"]');
const spy = vi.fn();
Object.defineProperty(rows[4], "scrollIntoView", {
configurable: true,
value: spy,
});
await wrapper.vm.activeKey;
await press("ArrowUp");
expect(spy).toHaveBeenCalled();
expect(document.activeElement).toBe(inputEl());
});
it("clears activedescendant when closed and after filtering hides the row", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await press("ArrowDown");
const openId = inputEl().getAttribute("aria-activedescendant");
expect(openId).toBeTruthy();
await press("Escape");
expect(wrapper.vm.open).toBe(false);
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
await press("ArrowDown");
await type("鼠");
expect(
document
.getElementById(inputEl().getAttribute("aria-activedescendant")!)
?.textContent?.trim(),
).toBe("仓鼠");
await type("不存在");
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
});
it("keeps activedescendant in sync when a row press moves the active key", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const rows = queryAll('[data-slot="list-box-item"]');
rows[2].dispatchEvent(pointerEvent("pointerdown"));
rows[2].dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(wrapper.vm.activeKey).toBe("bird");
const id = inputEl().getAttribute("aria-activedescendant");
expect(id).toBeTruthy();
expect(document.getElementById(id!)?.textContent?.trim()).toBe("鸟");
});
it("keeps the shared keyboard modality recoverable after a pointer press", async () => {
await mountHarness();
inputEl().focus();
await type("");
const rows = queryAll('[data-slot="list-box-item"]');
rows[0].dispatchEvent(pointerEvent("pointerdown"));
await nextTick();
await press("ArrowDown");
const focused = queryOne('[data-focused="true"]');
expect(focused).not.toBeNull();
expect(focused!.getAttribute("data-focus-visible")).toBe("true");
});
});