Files
heroui-vue/tests/autocomplete.test.ts
T
maoyingjie e34b9debdf fix(pickers): rework B02 against the public review
Restore native clearing, unify the form/field protocol with the other choice
families (per-key entries, disabled and removed keys omitted, shared form
owner), synchronise ComboBox text by key identity, keep filtering out of open
composition sessions, and stop stealing focus when a controlled close is
rejected. Also merge caller refs/ARIA/disabled, implement asChild, autoFocus
and ComboBox variant, use a locale-aware base matcher, and put the indicator
class and slot on the icon element the ported CSS selects.
2026-10-25 20:40:24 +08:00

901 lines
29 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { defineComponent, h, nextTick, ref, type Component } from "vue";
import {
Autocomplete,
AutocompleteClearButton,
AutocompleteFilter,
AutocompleteIndicator,
AutocompletePopover,
AutocompleteTrigger,
AutocompleteValue,
Form,
Label,
ListBox,
ListBoxItem,
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
} from "../packages/vue/src";
const settle = () => new Promise((resolve) => setTimeout(resolve, 4));
const mounted: { unmount: () => void }[] = [];
type State = { id: string | number; name: string; disabled?: boolean };
const states: State[] = [
{ id: "california", name: "California" },
{ id: "texas", name: "Texas" },
{ id: "florida", name: "Florida" },
];
function shell(
props: Record<string, unknown>,
options: { states?: State[]; empty?: boolean; description?: boolean } = {},
emits: Record<string, unknown> = {},
) {
const items = options.states ?? states;
return mount(
defineComponent({
setup() {
return () =>
h(
Autocomplete,
{
"aria-label": "州",
placeholder: "选择州/省",
...emits,
...props,
},
{
default: () => [
h(Label, () => "州"),
h(AutocompleteTrigger, null, {
default: () => [
h(AutocompleteValue),
h(AutocompleteClearButton),
h(AutocompleteIndicator),
],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () => [
h(
SearchField,
{ "aria-label": "搜索州名" },
{
default: () =>
h(SearchFieldGroup, null, {
default: () => [
h(SearchFieldSearchIcon),
h(SearchFieldInput, {
placeholder: "搜索州名…",
}),
],
}),
},
),
h(ListBox, null, {
default: () =>
items.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
isDisabled: state.disabled,
},
() => state.name,
),
),
empty: () =>
h("p", { "data-test": "empty" }, "未找到结果"),
}),
],
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
);
}
function track(wrapper: { unmount: () => void }) {
mounted.push(wrapper);
return wrapper;
}
const trigger = () =>
document.querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
const search = () =>
document.querySelector<HTMLInputElement>('[data-slot="search-field-input"]')!;
const valueText = () =>
document
.querySelector('[data-slot="autocomplete-value"]')
?.textContent?.trim();
const rowTexts = () =>
[...document.querySelectorAll('[role="option"]')]
.filter((row) => !row.hasAttribute("data-filtered"))
.map((row) => row.textContent?.trim());
async function open(wrapper?: { unmount: () => void }) {
void wrapper;
trigger().dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
}
async function press(key: string, init: KeyboardEventInit = {}) {
search().dispatchEvent(
new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
...init,
}),
);
await nextTick();
await settle();
}
async function type(text: string) {
const element = search();
element.value = text;
element.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await settle();
}
afterEach(async () => {
while (mounted.length) mounted.pop()?.unmount();
await nextTick();
await settle();
vi.restoreAllMocks();
document.body.innerHTML = "";
});
describe("Autocomplete trigger", () => {
it("is the single tab entry with placeholder and value semantics", async () => {
track(shell({}));
await nextTick();
await settle();
const element = trigger();
expect(element.getAttribute("role")).toBe("button");
expect(element.getAttribute("tabindex")).toBe("0");
expect(element.getAttribute("aria-haspopup")).toBe("listbox");
expect(element.getAttribute("aria-expanded")).toBe("false");
expect(valueText()).toBe("选择州/省");
expect(
document
.querySelector('[data-slot="autocomplete-clear-button"]')!
.getAttribute("tabindex"),
).toBe("-1");
});
it("opens on click, focuses the search box and filters from there", async () => {
track(shell({}));
await nextTick();
await settle();
await open();
expect(trigger().getAttribute("aria-expanded")).toBe("true");
expect(document.activeElement).toBe(search());
expect(search().getAttribute("role")).toBe("combobox");
const id = search().getAttribute("aria-activedescendant");
expect(document.getElementById(id!)?.getAttribute("role")).toBe("option");
await type("Te");
expect(rowTexts()).toEqual(["Texas"]);
expect(document.activeElement).toBe(search());
const active = search().getAttribute("aria-activedescendant");
expect(document.getElementById(active!)?.textContent?.trim()).toBe("Texas");
});
it("selects with Enter, closes and restores focus to the trigger", async () => {
const onChange = vi.fn();
track(shell({}, {}, { onChange }));
await nextTick();
await settle();
await open();
await type("Te");
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("texas");
expect(trigger().getAttribute("aria-expanded")).toBe("false");
expect(valueText()).toBe("Texas");
expect(document.activeElement).toBe(trigger());
});
it("closes on Escape and on Tab without selecting", async () => {
const onChange = vi.fn();
track(shell({}, {}, { onChange }));
await nextTick();
await settle();
await open();
await press("Escape");
expect(trigger().getAttribute("aria-expanded")).toBe("false");
expect(document.activeElement).toBe(trigger());
await open();
await press("Tab");
expect(trigger().getAttribute("aria-expanded")).toBe("false");
expect(onChange).not.toHaveBeenCalled();
});
it("does not confirm while an IME composition is active", async () => {
const onChange = vi.fn();
track(shell({}, {}, { onChange }));
await nextTick();
await settle();
await open();
await press("Enter", { isComposing: true });
await press("Enter", { keyCode: 229 });
expect(onChange).not.toHaveBeenCalled();
});
it("clears the selection from the clear button", async () => {
const onChange = vi.fn();
const clear = vi.fn();
track(shell({ defaultValue: "texas" }, {}, { onChange, onClear: clear }));
await nextTick();
await settle();
expect(valueText()).toBe("Texas");
document
.querySelector<HTMLElement>('[data-slot="autocomplete-clear-button"]')!
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(onChange).toHaveBeenLastCalledWith(null);
expect(clear).toHaveBeenCalledTimes(1);
expect(valueText()).toBe("选择州/省");
expect(trigger().getAttribute("aria-expanded")).toBe("false");
});
it("stays closed and non-tabbable while disabled", async () => {
track(shell({ isDisabled: true }));
await nextTick();
await settle();
expect(trigger().getAttribute("tabindex")).toBe("-1");
expect(trigger().getAttribute("aria-disabled")).toBe("true");
await open();
expect(trigger().getAttribute("aria-expanded")).toBe("false");
});
it("skips disabled keys while navigating", async () => {
const onChange = vi.fn();
track(
shell(
{},
{
states: [
{ id: "california", name: "California", disabled: true },
{ id: "texas", name: "Texas" },
],
},
{ onChange },
),
);
await nextTick();
await settle();
await open();
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("texas");
});
});
describe("Autocomplete state", () => {
it("shows the empty channel when nothing matches", async () => {
track(shell({}));
await nextTick();
await settle();
await open();
await type("zzz");
expect(rowTexts()).toEqual([]);
expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
});
it("opens an empty collection only when allowed", async () => {
track(shell({ allowsEmptyCollection: true }, { states: [] }));
await nextTick();
await settle();
await open();
expect(trigger().getAttribute("aria-expanded")).toBe("true");
expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
});
it("follows a controlled open state", async () => {
const openState = ref(false);
const onOpenChange = vi.fn((value: boolean) => (openState.value = value));
track(
mount(
defineComponent({
setup() {
return () =>
h(
Autocomplete,
{
"aria-label": "州",
isOpen: openState.value,
onOpenChange,
},
{
default: () => [
h(AutocompleteTrigger, null, {
default: () => [h(AutocompleteValue)],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () => [
h(
SearchField,
{ "aria-label": "搜索" },
{
default: () =>
h(SearchFieldGroup, null, {
default: () => [h(SearchFieldInput)],
}),
},
),
h(ListBox, null, {
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
}),
],
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
) as never,
);
await nextTick();
await settle();
await open();
expect(onOpenChange).toHaveBeenCalledWith(true);
// The parent accepted the proposal, so the controlled state is open.
expect(trigger().getAttribute("aria-expanded")).toBe("true");
openState.value = false;
await nextTick();
await settle();
expect(trigger().getAttribute("aria-expanded")).toBe("false");
});
it("keeps the value when the parent rejects the proposal", async () => {
const onChange = vi.fn();
track(shell({ value: null }, {}, { onChange }));
await nextTick();
await settle();
await open();
await press("Enter");
expect(onChange).toHaveBeenCalledWith("california");
expect(valueText()).toBe("选择州/省");
});
it("accumulates multiple selections and renders tags", async () => {
const selected = ref<(string | number)[]>([]);
track(
mount(
defineComponent({
setup() {
return () =>
h(
Autocomplete,
{
"aria-label": "州",
selectionMode: "multiple",
modelValue: selected.value,
"onUpdate:modelValue": (value: unknown) => {
selected.value = (value ?? []) as (string | number)[];
},
},
{
default: () => [
h(AutocompleteTrigger, null, {
default: () => [h(AutocompleteValue)],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () => [
h(
SearchField,
{ "aria-label": "搜索" },
{
default: () =>
h(SearchFieldGroup, null, {
default: () => [h(SearchFieldInput)],
}),
},
),
h(
ListBox,
{ selectionMode: "multiple" },
{
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
},
),
],
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
) as never,
);
await nextTick();
await settle();
await open();
await press("Enter");
await press("ArrowDown");
await press("Enter");
expect(selected.value).toEqual(["california", "texas"]);
// Multi-select keeps the popover open for further picks.
expect(trigger().getAttribute("aria-expanded")).toBe("true");
expect(
[
...document.querySelectorAll('[role="option"][aria-selected="true"]'),
].map((row) => row.textContent?.trim()),
).toEqual(["California", "Texas"]);
});
});
describe("Autocomplete form and validation", () => {
it("submits the selected key through a hidden input", async () => {
const wrapper = mount(
defineComponent({
setup() {
const submitted = ref("");
return () =>
h(
Form,
{
onSubmit: (event: Event) => {
event.preventDefault();
const data = new FormData(
event.currentTarget as HTMLFormElement,
);
submitted.value = String(data.get("state"));
},
},
{
default: () => [
h(
Autocomplete,
{
"aria-label": "州",
name: "state",
defaultValue: "texas",
},
{
default: () => [
h(AutocompleteTrigger, null, {
default: () => [h(AutocompleteValue)],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () => [
h(
SearchField,
{ "aria-label": "搜索" },
{
default: () =>
h(SearchFieldGroup, null, {
default: () => [h(SearchFieldInput)],
}),
},
),
h(ListBox, null, {
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
}),
],
}),
}),
],
},
),
h(
"button",
{ type: "submit", "data-test": "submit" },
"提交",
),
h("p", { "data-test": "result" }, submitted.value),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper as never);
await nextTick();
await settle();
(
document.querySelector('[data-test="submit"]') as HTMLButtonElement
).click();
await nextTick();
expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
"texas",
);
});
it("blocks native submit when required and empty", async () => {
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(
Form,
{ onSubmit: (event: Event) => event.preventDefault() },
{
default: () => [
h(
Autocomplete,
{
"aria-label": "州",
name: "state",
isRequired: true,
},
{
default: () => [
h(Label, () => "州"),
h(AutocompleteTrigger, null, {
default: () => [h(AutocompleteValue)],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () => [
h(
SearchField,
{ "aria-label": "搜索" },
{
default: () =>
h(SearchFieldGroup, null, {
default: () => [h(SearchFieldInput)],
}),
},
),
h(ListBox, null, {
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
}),
],
}),
}),
],
},
),
h(
"button",
{ type: "submit", "data-test": "submit" },
"提交",
),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper as never);
await nextTick();
await settle();
const form = document.querySelector("form")!;
expect(form.checkValidity()).toBe(false);
});
});
describe("Autocomplete composition", () => {
it("keeps a caller-provided aria-label on the trigger and search box", async () => {
track(shell({}));
await nextTick();
await settle();
expect(trigger().getAttribute("aria-label")).toBe("州");
await open();
expect(search().getAttribute("aria-label")).toBe("州");
});
it("mounts as a reusable component surface", async () => {
const surface: Component = (
await import("../apps/docs/demos/autocomplete-multiple-select.vue")
).default;
const wrapper = mount(surface, { attachTo: document.body });
track(wrapper as never);
await nextTick();
await settle();
expect(trigger().getAttribute("aria-expanded")).toBe("false");
expect(valueText()).toBe("选择州/省");
});
});
describe("Autocomplete ported style hooks", () => {
it("emits the data-slot values the ported CSS targets", async () => {
const css = readFileSync(
"packages/styles/components/autocomplete.css",
"utf8",
);
// Only class names carry the hv- prefix: data-slot values are a DOM
// contract, so a prefixed value would leave the ported rules dead.
expect(css).not.toMatch(/data-slot="hv-/);
expect(css).toContain('&[data-slot="autocomplete-default-indicator"]');
expect(css).toContain('[data-slot="autocomplete-clear-button-icon"]');
track(shell({ defaultValue: "texas" }));
await nextTick();
await settle();
// The class, the `data-slot` and `data-open` must share one element, or the
// ported `.hv-autocomplete__indicator[...]` rules never match.
expect(
document.querySelector(
'.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
),
).not.toBeNull();
expect(
document.querySelector('[data-slot="autocomplete-clear-button-icon"]'),
).not.toBeNull();
});
});
describe("Autocomplete filter protocol", () => {
it("inherits an accent-insensitive base matcher", async () => {
track(
shell(
{},
{ states: [{ id: "cafe", name: "Café" }] as unknown as State[] },
),
);
await nextTick();
await open();
await type("cafe");
expect(rowTexts()).toEqual(["Café"]);
await type("CAFÉ");
expect(rowTexts()).toEqual(["Café"]);
await type("cafe\u0301");
expect(rowTexts()).toEqual(["Café"]);
});
it("filters only after an open composition session ends", async () => {
track(shell({}));
await nextTick();
await open();
expect(rowTexts()).toHaveLength(3);
search().dispatchEvent(new CompositionEvent("compositionstart"));
await nextTick();
await type("Texas");
expect(rowTexts()).toHaveLength(3);
search().dispatchEvent(new CompositionEvent("compositionend"));
await nextTick();
await settle();
expect(rowTexts()).toEqual(["Texas"]);
});
});
describe("Autocomplete native layer", () => {
it("keeps the caller's cancel on the clear button", async () => {
const change = vi.fn();
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
Autocomplete,
{ defaultValue: "a", onChange: change },
{
default: () => [
h(AutocompleteTrigger, null, {
default: () => [
h(AutocompleteValue),
h(AutocompleteClearButton, {
onClick: (event: MouseEvent) => event.preventDefault(),
}),
],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () =>
h(ListBox, null, {
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
}),
}),
}),
],
},
),
}),
{ attachTo: document.body },
);
track(wrapper as never);
await nextTick();
await settle();
document
.querySelector<HTMLButtonElement>(
'[data-slot="autocomplete-clear-button"]',
)!
.click();
await settle();
expect(change).not.toHaveBeenCalled();
});
it("submits one entry per key and none for a disabled field", async () => {
const multi = mount(
defineComponent({
setup: () => () =>
h("form", null, [
h(Autocomplete, {
name: "choice",
selectionMode: "multiple",
defaultValue: ["california", "texas"],
}),
]),
}),
{ attachTo: document.body },
);
track(multi as never);
await nextTick();
await settle();
const form = multi.element as HTMLFormElement;
expect(new FormData(form).getAll("choice")).toEqual([
"california",
"texas",
]);
multi.unmount();
mounted.pop();
const disabled = mount(
defineComponent({
setup: () => () =>
h("form", null, [
h(Autocomplete, {
name: "choice",
defaultValue: "california",
isDisabled: true,
}),
]),
}),
{ attachTo: document.body },
);
track(disabled as never);
await nextTick();
await settle();
expect(
new FormData(disabled.element as HTMLFormElement).has("choice"),
).toBe(false);
});
it("maps the source items prop onto the closed-state text", async () => {
track(
shell({
items: [
{ id: "california", textValue: "California" },
{ id: "texas", textValue: "Texas" },
],
defaultValue: "texas",
}),
);
await nextTick();
await settle();
expect(valueText()).toBe("Texas");
});
it("tags a custom indicator with the baseline slot contract", async () => {
track(
mount(
defineComponent({
setup: () => () =>
h(Autocomplete, null, {
default: () => [
h(AutocompleteTrigger, null, {
default: () => [
h(AutocompleteValue),
h(AutocompleteIndicator, null, {
default: () => h("i", { "data-test": "icon" }),
}),
],
}),
h(AutocompletePopover, null, {
default: () =>
h(AutocompleteFilter, null, {
default: () =>
h(ListBox, null, {
default: () =>
states.map((state) =>
h(
ListBoxItem,
{
id: state.id,
key: state.id,
textValue: state.name,
},
() => state.name,
),
),
}),
}),
}),
],
}),
}),
{ attachTo: document.body },
),
);
await nextTick();
await settle();
const custom = document.querySelector('[data-test="icon"]')!;
expect(custom.getAttribute("data-slot")).toBe("autocomplete-indicator");
expect(custom.classList.contains("hv-autocomplete__indicator")).toBe(true);
});
});