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
+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");
});
});