1b972a78ba
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.
356 lines
12 KiB
TypeScript
356 lines
12 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([
|
|
"猫",
|
|
"鸟",
|
|
"鱼",
|
|
"仓鼠",
|
|
]);
|
|
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("狗");
|
|
});
|
|
});
|