Files
heroui-vue/tests/collection-filter-virtual.test.ts
T
maoyingjie 50ad3ca180 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.
2026-10-25 16:28:33 +08:00

501 lines
17 KiB
TypeScript

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([
"猫",
"鸟",
"鱼",
"仓鼠",
]);
// 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");
});
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("狗");
});
});
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");
});
});