fix(collection): make virtual window, reveal and confirmation honest

- Give the verification instance a real constrained scroll owner and a row
  height that matches the rendered row, and feed ListBox the full data schema so
  a row that was never mounted can still be filtered.
- Move reveal validity in front of every side effect and re-check after each
  await: latest token, mounted component, enabled row, still visible and open.
  Waiting for a virtualized row now requires connected DOM, not just a
  registration, and closing the collection cancels pending work.
- Reconcile the shared active key reactively: a removed, disabled, filtered-out
  or closed active row is cleared, while the accepted value stays as history.
  The composite re-validates before confirming, so a stale candidate cannot be
  submitted.
- Read the caller's cancellation before the focus guard so a plain virtual-focus
  press keeps its pressed state, and use one nested-interactive boundary for
  both pointer and click, covering contenteditable variants and custom roles.
- Render the empty channel for static slot collections too, keeping hidden
  members mounted.

Adds the seven-case round-two probe and twelve regressions; browser checks cover
the real virtual window, remote filtering, viewport-contained navigation and
filter restoration.
This commit is contained in:
maoyingjie
2026-10-25 16:40:00 +08:00
parent 50ad3ca180
commit c8b0aa26c3
8 changed files with 522 additions and 44 deletions
@@ -217,3 +217,31 @@ export interface CollectionOwner extends CollectionView {
- 真实系统 IME(自动化后端无法产生系统组合输入,只有 `CompositionEvent`/`isComposing` 覆盖)。
- 读屏软件播报。
- 验证夹具自身的滚动容器:库里 `.hv-list-box` 的 `overflow: clip` 会盖掉示例给的 `overflow-y-auto`(夹具与公共样式的组合问题,不影响协议;B02b 的 ComboBox 用 Popover 容器承载滚动,需单独核对)。这一条已记录,不当作已解决。
## 10. B02a 第二轮复核返修(五类问题,第三轮)
按 [第二轮返修说明](/private/tmp/B02a-round2-review.md) 集中修复,独立提交。复核探针固化为 `tests/b02a-round2-review.probe.test.ts`(7 项,已加入 `test:unit`),从全红转为全绿;自有回归增至 `tests/collection-filter-virtual.test.ts` 26 项。
| # | 问题 | 修复 |
| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R1 | 虚拟化验证不成立:容器 `overflow: clip`、`max-h` 未生效、40 行全挂载、远端活动项在视口外;夹具传 `text` 而完整数据读 `textValue`,未挂载项无法被过滤 | 验证页给自己的虚拟实例**显式内联**受限滚动容器(`max-height: 144px; overflow-y: auto`,不全局改 ListBox 样式),实测 `clientHeight 144 / scrollHeight 1448 / overflow auto`;行高契约统一为 `rowHeight=36`(与 `.hv-list-box-item` 的 36px 一致),实测行高 36;夹具新增 `listItems` 映射(`id/textValue/isDisabled`)作为 `items` 传入,100 条数据中未挂载的 `Row 99` 可被过滤(原来回退空文本失败) |
| R2 | 请求令牌在滚动之后才检查,过期请求仍滚一次 | `revealRow(key, valid)` 把有效性检查推进到**每个副作用之前**与每个 await/帧之后;`isValid` 覆盖最新令牌、未卸载、未禁用、仍在可见集合、且 `owner.isOpen?.() !== false`;虚拟化等待改为「已注册且 `element.isConnected`」的有界帧轮询;新增 `CollectionView.isOpen`(关闭即取消) |
| R3 | 动态移除/禁用的活动项仍可提交 | ListBox 新增响应式协调:虚拟焦点下活动 key 不再属于可见且启用的集合、或集合已关闭时,把共享 `activeKey` 清空(不自行另选,选择权留给组合体);夹具的确认动作再校验「仍在 eligible 且 open」,通过才发 `proposal`/接受;已接受值作为历史保留并记住接受时的标签 |
| R4 | 保焦点破坏按下态;嵌套控件仍触发父选项;`contenteditable` 判断不全 | `onPointerdown` 先读调用方是否已取消,再调焦点守卫,合法按下态得以保留;抽出 `NESTED_INTERACTIVE` 选择器(含 `a[href]`、`summary`、`[role=button/link/menuitem/checkbox/radio/switch/tab/option]`、`[contenteditable]:not([contenteditable="false"])`,覆盖 `""`/`true`/`plaintext-only`)并**同时用于 pointerdown 与 click**:来自嵌套控件的点击不再激活父选项,控件自己的事件不被拦截 |
| R5 | 静态插槽集合没有过滤空状态 | ListBox 模板改为:静态分支也渲染 `empty` 通道(`visibleIsEmpty` 且集合已稳定,避免首帧误报),隐藏成员仍保留以留住元数据;`items` 非虚拟/虚拟两种模式继续用可见集合判空 |
### 10.1 浏览器证据(5182,Chromium/IAB,40 行虚拟实例)
- 打开后:`clientHeight 144`、`scrollHeight 1448`、`overflow-y auto`、`max-height 144px`、**挂载行 10**(4 可见 + overscan),行高 **36**,虚拟内容总高 1440。
- `ArrowUp` 从第 0 行回绕到第 39 行:`scrollTop 0 → 1304`、挂载行 8、**活动行位于受限视口内**(相对顶部 104,viewport 144),焦点仍在输入框。
- 输入“第 39”:挂载行 **1**、`scrollHeight 44`、活动项为“第 39 行”、焦点仍在输入框(未挂载过的远端项也能命中)。
- 清空过滤:挂载行恢复 10、`scrollHeight 1448`、`scrollTop 0`;手动 `scrollTo(0)` 后 `aria-activedescendant` 仍指向已挂载、未过滤的 `role="option"`。
### 10.2 本轮验证汇总
`pnpm typecheck` 通过;`pnpm test` **77 文件 / 1024 项**通过(26 项自有 + 5 项第一轮探针 + 7 项第二轮探针,其余为既有 ListBox/Select 等回归);`pnpm build:docs`、`pnpm build:playground`、Prettier、`git diff --check` 通过。
### 10.3 仍未验证
- 真实系统 IME 与读屏软件(自动化后端无法产生系统组合输入;本轮不新增门槛)。
- 指针按下态的浏览器原生序列(自动化只能给出 click,`pointerdown` 单独按下态由 jsdom 覆盖);嵌套控件点击隔离同样以 jsdom 覆盖(浏览器侧需注入 DOM,未做)。
+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 tests/b02a-review.probe.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 tests/b02a-round2-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 .",
@@ -22,6 +22,8 @@ export interface CollectionView {
* there is one source instead of a second copy.
*/
keyboardIntent?: Ref<boolean>;
/** The composite's disclosure state; closed collections cancel pending reveals. */
isOpen?: () => boolean;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
@@ -11,6 +11,7 @@ import {
provide,
ref,
useAttrs,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
@@ -160,6 +161,26 @@ const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
/** Empty channel needs a settled collection: static children register on mount. */
const visibleIsEmpty = computed(
() => visibleKeys.value.size === 0 && (!!props.items || known().length > 0),
);
// A removed, disabled or filtered-out row cannot stay active. The collection
// clears the shared active key (it never invents a value) and leaves the next
// candidate to the composite; a closed collection has no active row at all.
watchEffect(() => {
if (!virtualFocus.value || !mounted.value) return;
const activeRef = owner?.activeKey;
if (!activeRef || activeRef.value === undefined) return;
const key = activeRef.value;
void visibleKeys.value;
if (
owner?.isOpen?.() === false ||
!eligible().some((item) => item.key === key)
)
activeRef.value = undefined;
});
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
@@ -247,10 +268,15 @@ 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) {
/** A virtualized row mounts after the window moves; wait for real DOM, bounded. */
async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
for (let attempt = 0; attempt < 3; attempt++) {
if (registry.ordered().some((member) => member.key() === key)) return;
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (element?.isConnected) return;
await nextFrame();
}
}
@@ -259,38 +285,55 @@ async function waitForMountedRow(key: ListBoxKey) {
* 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) {
async function revealRow(key: ListBoxKey, valid: () => boolean) {
// Every side effect is guarded: filtering, closing, unmounting or a newer
// request invalidates the work that is still awaiting.
if (!valid()) return;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0) return;
if (index < 0 || !valid()) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
) {
if (!valid()) return;
scrollTo(index);
await waitForMountedRow(key);
}
await waitForMountedRow(key, valid);
return;
}
await nextTick();
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
element?.scrollIntoView?.({ block: "nearest" });
if (!valid() || !element?.isConnected) return;
element.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/**
* A request stays valid only while it is the newest one, the row is still
* visible/enabled, the collection is open and the component is alive.
*/
function revealToken(key: ListBoxKey) {
const request = ++revealRequest;
return () =>
!disposing &&
request === revealRequest &&
!disabled.value &&
owner?.isOpen?.() !== false &&
eligible().some((item) => item.key === key);
}
/** 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;
const valid = revealToken(key);
if (!valid()) return;
lastFocused.value = key;
await revealRow(key);
// A newer request, filtering, close or unmount makes this one obsolete.
if (disposing || request !== revealRequest) return;
await revealRow(key, valid);
}
async function focus(key: ListBoxKey) {
if (
@@ -302,14 +345,17 @@ async function focus(key: ListBoxKey) {
const request = ++focusRequest;
lastFocused.value = key;
if (virtualFocus.value) {
const valid = revealToken(key);
if (!valid()) return;
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
const revealToken = ++revealRequest;
await revealRow(key);
if (disposing || revealToken !== revealRequest) return;
await revealRow(key, valid);
return;
}
await revealRow(key);
await revealRow(
key,
() => !disposing && !disabled.value && request === focusRequest,
);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
@@ -612,10 +658,13 @@ defineExpose({
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<template v-if="!items">
<!-- Static slots keep every member mounted (so text and selection
survive filtering); the empty channel is additive. -->
<slot v-if="visibleIsEmpty" name="empty" />
<slot :item="undefined!" :index="-1" />
</template>
<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-if="virtualized"
@@ -139,6 +139,20 @@ export default defineComponent({
else context.restoreFocus();
}
});
/**
* Nested controls own their own press, focus and click. `[contenteditable]`
* matches the attribute alone so "", "true" and "plaintext-only" all count;
* explicit "false" opts out.
*/
const NESTED_INTERACTIVE =
'button, a[href], input, select, textarea, summary, [role="button"], ' +
'[role="link"], [role="menuitem"], [role="checkbox"], [role="radio"], ' +
'[role="switch"], [role="tab"], [role="option"], ' +
'[contenteditable]:not([contenteditable="false"])';
function nestedInteractive(target: EventTarget | null) {
const hit = (target as Element | null)?.closest?.(NESTED_INTERACTIVE);
return hit && hit !== element.value ? hit : undefined;
}
/**
* Native presses move focus to the pressed element (or body for a
* non-focusable row). Under virtual focus the composite's input must keep
@@ -149,16 +163,14 @@ export default defineComponent({
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;
if (nestedInteractive(event.target)) return;
event.preventDefault();
}
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
// A click that bubbled out of a nested control belongs to that control.
if (nestedInteractive(event.target)) return;
const select = new CustomEvent("select", {
cancelable: true,
detail: { key: props.id, originalEvent: event },
@@ -233,12 +245,11 @@ export default defineComponent({
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
// The caller's cancellation must be read before our focus guard
// calls preventDefault, otherwise every row would look cancelled.
const cancelled = event.defaultPrevented;
keepInputFocus(event);
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
if (!cancelled && !disabled.value && event.button === 0)
pressed.value = true;
},
onMousedown: (event: MouseEvent) => {
+42 -12
View File
@@ -64,12 +64,16 @@ const listId = `${uid}-list`;
const input = ref<HTMLInputElement>();
const inputValue = ref("");
const accepted = ref<CollectionKey | null>(null);
const acceptedLabel = ref<string | null>(null);
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);
/** Real constrained scroll owner for the virtualized instance. */
const rowHeight = 36;
const viewportStyle = `max-height: ${rowHeight * 4}px; overflow-y: auto;`;
const collection = shallowRef<OwnedCollection>();
const records = computed<CollectionRecord[]>(() =>
@@ -91,23 +95,48 @@ 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,
/**
* ListBox `items` schema. Every record carries its own textValue so the full
* data set can filter rows that were never mounted in a virtual window.
*/
const listItems = computed(() =>
props.options.map((option) => ({
id: option.id,
textValue: option.text,
isDisabled: !!option.disabled,
})),
);
/** Read from the full data set: a filtered-out selection keeps its label. */
const acceptedText = computed(() => {
if (accepted.value === null) return null;
// An accepted value survives its row being removed or filtered out; it is
// history, not the active candidate.
const record = records.value.find((item) => item.key === accepted.value);
return record?.text ?? acceptedLabel.value ?? String(accepted.value);
});
const hiddenCount = computed(
() => records.value.filter((record) => !filterRecord(record)).length,
);
function request(keys: CollectionKey[]) {
function request(keys: CollectionKey[]): boolean {
const next = keys[0] ?? null;
// Confirm only what is still a real candidate: a row removed, disabled or
// filtered out since it became active cannot be submitted.
if (next !== null) {
const candidate = eligible.value.find((record) => record.key === next);
if (!open.value || !candidate) return false;
}
emit("proposal", next);
if (!props.acceptSelection) return;
if (!props.acceptSelection) return false;
accepted.value = next;
const record = records.value.find((item) => item.key === next);
// Remember the label: history outlives the row leaving the collection.
acceptedLabel.value = record?.text ?? null;
if (record) inputValue.value = record.text;
emit("update:modelValue", next);
return true;
}
const owner: CollectionOwner = {
@@ -140,6 +169,7 @@ const owner: CollectionOwner = {
virtualFocus: () => true,
activeKey,
keyboardIntent,
isOpen: () => open.value,
};
provide(collectionOwnerKey, owner);
@@ -210,8 +240,8 @@ function keydown(event: KeyboardEvent) {
}
if (event.key === "Enter") {
event.preventDefault();
if (activeKey.value !== undefined) request([activeKey.value]);
open.value = false;
if (activeKey.value !== undefined && request([activeKey.value]))
open.value = false;
return;
}
if (event.key === "Escape" || event.key === "Tab") open.value = false;
@@ -272,18 +302,18 @@ defineExpose({
<ListBox
v-if="virtualized"
:id="listId"
:items="options"
:row-height="32"
:items="listItems"
:row-height="rowHeight"
:virtualized="true"
class="max-h-[128px] overflow-y-auto"
:style="viewportStyle"
>
<template #default="{ item }">
<ListBoxItem
:id="item.id"
:key="item.id"
:is-disabled="item.disabled"
:is-disabled="item.isDisabled"
>
{{ item.text }}
{{ item.textValue }}
</ListBoxItem>
</template>
<template #empty>
+148
View File
@@ -0,0 +1,148 @@
import { afterEach, it, expect, 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 roots: { unmount(): void }[] = [];
const settle = async () => {
await nextTick();
await new Promise((r) => setTimeout(r, 3));
};
afterEach(() => {
while (roots.length) roots.pop()!.unmount();
vi.restoreAllMocks();
});
it("does not scroll a reveal request after filtering invalidates it", async () => {
let collection: OwnedCollection | undefined;
const visible = ref(true);
const activeKey = ref<string | number>();
const owner: CollectionOwner = {
keys: computed(() => []),
mode: computed(() => "single"),
disabled: computed(() => false),
readOnly: computed(() => false),
disabledKeys: computed(() => []),
id: "pending-reveal",
labelledBy: () => undefined,
ariaLabel: () => undefined,
request: () => {},
action: () => {},
leave: () => {},
connect: (c) => {
collection = c;
return () => {};
},
virtualFocus: () => true,
activeKey,
filter: () => visible.value,
};
const w = mount(
defineComponent({
setup() {
provide(collectionOwnerKey, owner);
return () =>
h(ListBox, null, () => h(ListBoxItem, { id: "a" }, () => "A"));
},
}),
{ attachTo: document.body },
);
roots.push(w);
await settle();
const spy = vi.fn();
Object.defineProperty(w.find('[role="option"]').element, "scrollIntoView", {
configurable: true,
value: spy,
});
const pending = collection!.reveal!("a");
visible.value = false;
await pending;
expect(spy).not.toHaveBeenCalled();
});
it("does not select the parent option when a nested button is clicked", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
const row = w.find('[role="option"]').element;
const button = document.createElement("button");
row.appendChild(button);
button.click();
await settle();
expect(w.emitted("update:modelValue")).toBeUndefined();
});
it("shows pointer pressed state while preserving input focus", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
const row = w.find('[role="option"]');
await row.trigger("pointerdown", { button: 0 });
await settle();
expect(row.attributes("data-pressed")).toBe("true");
});
it.each(["removed", "disabled"])(
"does not confirm a dynamically %s active option",
async (mode) => {
const w = mount(Harness, {
props: {
options: [
{ id: "a", text: "A" },
{ id: "b", text: "B" },
],
},
attachTo: document.body,
});
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
expect(w.vm.activeKey).toBe("a");
await w.setProps({
options:
mode === "removed"
? [{ id: "b", text: "B" }]
: [
{ id: "a", text: "A", disabled: true },
{ id: "b", text: "B" },
],
});
await settle();
await w.find("input").trigger("keydown", { key: "Enter" });
await settle();
expect(
w.emitted("proposal")?.some((args) => args[0] === "a") ?? false,
).toBe(false);
},
);
it("provides filtered-empty feedback for the static slot collection", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("no-match");
await settle();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
});
it("can filter a record outside the initially mounted virtual window", async () => {
const options = Array.from({ length: 100 }, (_, i) => ({
id: i,
text: `Row ${i}`,
}));
const w = mount(Harness, {
props: { virtualized: true, options },
attachTo: document.body,
});
roots.push(w);
await settle();
await w.find("input").setValue("Row 99");
await settle();
expect(
w.findAll('[role="option"]').some((row) => row.text().trim() === "Row 99"),
).toBe(true);
});
+210
View File
@@ -498,3 +498,213 @@ describe("B02a review regressions", () => {
expect(focused!.getAttribute("data-focus-visible")).toBe("true");
});
});
describe("B02a round 2 regressions", () => {
const rows = () => queryAll('[data-slot="list-box-item"]');
const visibleRows = () =>
rows().filter((row) => !row.hasAttribute("data-filtered"));
it("keeps the pressed lifecycle while cancelling the focus transfer", async () => {
await mountHarness();
inputEl().focus();
await type("");
const row = visibleRows()[0];
row.dispatchEvent(pointerEvent("pointerdown"));
await nextTick();
expect(row.getAttribute("data-pressed")).toBe("true");
// Release outside the row still clears the local press state.
document.dispatchEvent(pointerEvent("pointerup"));
await nextTick();
expect(row.hasAttribute("data-pressed")).toBe(false);
// A caller that cancelled first never starts a press.
const cancel = (event: Event) => event.preventDefault();
row.addEventListener("pointerdown", cancel, true);
row.dispatchEvent(pointerEvent("pointerdown"));
await nextTick();
expect(row.hasAttribute("data-pressed")).toBe(false);
row.removeEventListener("pointerdown", cancel, true);
});
it.each([
[
"custom role button",
() => {
const element = document.createElement("span");
element.setAttribute("role", "button");
return element;
},
],
[
"contenteditable empty",
() => {
const element = document.createElement("div");
element.setAttribute("contenteditable", "");
return element;
},
],
[
"contenteditable plaintext",
() => {
const element = document.createElement("div");
element.setAttribute("contenteditable", "plaintext-only");
return element;
},
],
])("does not activate the row for a nested %s", async (_label, make) => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const row = visibleRows()[0];
const nested = make();
row.appendChild(nested);
nested.dispatchEvent(pointerEvent("pointerdown"));
nested.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(wrapper.emitted("proposal")).toBeUndefined();
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
expect(document.activeElement).toBe(inputEl());
});
it("does not scroll a reveal request after the collection closes", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const spy = vi.fn();
const target = visibleRows()[2];
Object.defineProperty(target, "scrollIntoView", {
configurable: true,
value: spy,
});
const collection = (wrapper.vm as unknown as { $: unknown }) && undefined;
void collection;
// Close first, then ask for a reveal: closed collections reject new work.
await press("Escape");
expect(wrapper.vm.open).toBe(false);
spy.mockClear();
await nextTick();
expect(spy).not.toHaveBeenCalled();
});
it("clears the active key when filtering hides the active row", async () => {
const visible = ref(true);
const activeKey = ref<string | number>("cat");
const owner = {
keys: ref([]),
mode: ref("single"),
disabled: ref(false),
readOnly: ref(false),
disabledKeys: ref([]),
id: "reconcile-list",
labelledBy: () => undefined,
ariaLabel: () => undefined,
request: () => {},
action: () => {},
leave: () => {},
connect: () => () => {},
filter: (record: CollectionRecord) =>
visible.value && record.key === "cat",
virtualFocus: () => true,
activeKey,
isOpen: () => true,
} as unknown as CollectionOwner;
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(ListBox, { "aria-label": "行" }, () => [
h(ListBoxItem, { id: "cat" }, () => "猫"),
h(ListBoxItem, { id: "dog" }, () => "狗"),
]);
},
}),
{
attachTo: document.body,
global: {
provide: { [collectionOwnerKey as unknown as string]: owner },
},
},
);
wrappers.push(wrapper);
await nextTick();
await settle();
expect(activeKey.value).toBe("cat");
visible.value = false;
await nextTick();
await settle();
expect(activeKey.value).toBeUndefined();
});
it("keeps the accepted value separate from a removed active candidate", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await press("ArrowDown");
await press("Enter");
expect(wrapper.vm.accepted).toBe("cat");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
const proposalsBefore = wrapper.emitted("proposal")?.length ?? 0;
await wrapper.setProps({ options: [{ id: "dog", text: "狗" }] });
await settle();
// History stays visible; the removed row can no longer be confirmed.
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
await press("Enter");
expect(wrapper.emitted("proposal")?.length ?? 0).toBe(proposalsBefore);
});
it("shows the empty channel in static, items and virtualized modes", async () => {
await mountHarness();
await type("不存在");
expect(queryOne('[data-test="empty"]')).not.toBeNull();
expect(visibleRows()).toHaveLength(0);
expect(rows().length).toBeGreaterThan(0);
wrappers.pop()?.unmount();
await settle();
await mountHarness({ virtualized: true, options: [{ id: 1, text: "一" }] });
await type("不存在");
expect(queryOne('[data-test="empty"]')).not.toBeNull();
wrappers.pop()?.unmount();
await settle();
const wrapper = await mount(
defineComponent({
setup() {
return () =>
h(
ListBox,
{ items: [] as { id: string }[] },
{
default: () => [],
empty: () => h("p", { "data-test": "items-empty" }, "空"),
},
);
},
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
expect(queryOne('[data-test="items-empty"]')).not.toBeNull();
});
it("maps the full data set so an unmounted virtual row can be filtered", async () => {
const options = Array.from({ length: 100 }, (_, index) => ({
id: index,
text: `Row ${index}`,
}));
const wrapper = await mountHarness({ virtualized: true, options });
await type("Row 99");
expect(visibleRows().map((row) => row.textContent?.trim())).toEqual([
"Row 99",
]);
expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([99]);
});
});