Files
heroui-vue/tests/combo-box.test.ts
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

899 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 } from "vue";
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
ComboBoxValue,
Description,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
} from "../packages/vue/src";
const settle = () => new Promise((resolve) => setTimeout(resolve, 3));
const mounted: { unmount: () => void; element: Element }[] = [];
type Item = { id: string | number; text: string; disabled?: boolean };
const animals: Item[] = [
{ id: "cat", text: "猫" },
{ id: "dog", text: "狗" },
{ id: "bird", text: "鸟" },
{ id: "fish", text: "鱼" },
];
function mountCombo(
props: Record<string, unknown> = {},
options: { items?: Item[]; value?: boolean } = {},
) {
const items = options.items ?? animals;
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(
ComboBox,
{ "aria-label": "动物", ...props },
{
default: () => [
h(Label, () => "最喜欢的动物"),
h(ComboBoxInputGroup, null, {
default: () => [
h(Input, { placeholder: "搜索动物…" }),
h(ComboBoxTrigger),
],
}),
options.value
? h(ComboBoxValue, { placeholder: "未选择" })
: null,
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
items.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
isDisabled: item.disabled,
},
() => item.text,
),
),
empty: () =>
h("p", { "data-test": "empty" }, "没有匹配项"),
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
return wrapper;
}
const input = () =>
document.querySelector<HTMLInputElement>('[data-slot="input"]')!;
const rowTexts = () =>
[...document.querySelectorAll('[role="option"]')]
.filter((row) => !row.hasAttribute("data-filtered"))
.map((row) => row.textContent?.trim());
async function type(value: string) {
const element = input();
element.value = value;
element.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await settle();
}
async function press(key: string, init: KeyboardEventInit = {}) {
input().dispatchEvent(
new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
...init,
}),
);
await nextTick();
await settle();
}
afterEach(async () => {
while (mounted.length) mounted.pop()?.unmount();
await nextTick();
await settle();
vi.restoreAllMocks();
document.body.innerHTML = "";
});
describe("ComboBox input semantics", () => {
it("exposes one combobox control with label and ARIA wiring", async () => {
mountCombo();
await nextTick();
const element = input();
const label = document.querySelector("label")!;
expect(element.getAttribute("role")).toBe("combobox");
expect(element.getAttribute("aria-expanded")).toBe("false");
expect(element.getAttribute("aria-autocomplete")).toBe("list");
expect(element.getAttribute("aria-haspopup")).toBe("listbox");
expect(element.id).toBeTruthy();
expect(label.getAttribute("for")).toBe(element.id);
expect(
document
.querySelector('[data-slot="combo-box-trigger"]')!
.getAttribute("tabindex"),
).toBe("-1");
});
it("opens on focus, filters with the input and keeps focus in the input", async () => {
mountCombo();
await nextTick();
input().focus();
input().dispatchEvent(new FocusEvent("focus"));
await nextTick();
await settle();
expect(input().getAttribute("aria-expanded")).toBe("true");
await type("狗");
expect(rowTexts()).toEqual(["狗"]);
expect(document.activeElement).toBe(input());
const id = input().getAttribute("aria-activedescendant");
expect(id).toBeTruthy();
const option = document.getElementById(id!);
expect(option?.getAttribute("role")).toBe("option");
expect(option?.textContent?.trim()).toBe("狗");
});
it("confirms with Enter, writes the text back and closes", async () => {
const onChange = vi.fn();
mountCombo({ onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
await press("ArrowDown");
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("dog");
expect(input().value).toBe("狗");
expect(input().getAttribute("aria-expanded")).toBe("false");
expect(input().getAttribute("aria-activedescendant")).toBeNull();
});
it("closes on Escape without changing the value", async () => {
const onChange = vi.fn();
mountCombo({ onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
await press("Escape");
expect(input().getAttribute("aria-expanded")).toBe("false");
expect(onChange).not.toHaveBeenCalled();
});
it("does not confirm while an IME composition is active", async () => {
const onChange = vi.fn();
mountCombo({ onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
await press("Enter", { isComposing: true });
expect(onChange).not.toHaveBeenCalled();
await press("Enter", { keyCode: 229 });
expect(onChange).not.toHaveBeenCalled();
});
it("clears the selection when the text stops matching it", async () => {
const onChange = vi.fn();
mountCombo({ onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("cat");
await type("狗");
expect(onChange).toHaveBeenLastCalledWith(null);
});
it("keeps a typed custom value when allowsCustomValue is set", async () => {
const onChange = vi.fn();
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
await press("Enter");
await type("独角兽");
// Typing a non-matching value must not clear the accepted custom text.
expect(onChange).toHaveBeenLastCalledWith("cat");
expect(input().value).toBe("独角兽");
});
it("commits a typed custom value with Enter", async () => {
const onChange = vi.fn();
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
await nextTick();
input().focus();
await type("独角兽");
await press("Enter");
// The typed text itself becomes the value, like the baseline.
expect(onChange).toHaveBeenLastCalledWith("独角兽");
expect(input().value).toBe("独角兽");
expect(input().getAttribute("aria-expanded")).toBe("false");
});
it("commits the typed text when the filter excluded every record", async () => {
const onChange = vi.fn();
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
// The accepted row is filtered out, so the custom text must still commit.
await type("独角兽");
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("独角兽");
expect(input().value).toBe("独角兽");
});
});
describe("ComboBox selection state", () => {
it("keeps the accepted value when the parent rejects the proposal", async () => {
mountCombo({ selectedKey: null, onSelectionChange: () => {} });
await nextTick();
input().focus();
await press("ArrowDown");
await press("Enter");
await settle();
// The rejected value never becomes accepted: nothing is selected.
expect(document.querySelector('[aria-selected="true"]')).toBeNull();
// And the proposal can be made again once the parent accepts the same key.
await press("ArrowDown");
await press("Enter");
expect(document.querySelector('[aria-selected="true"]')).toBeNull();
});
it("reflects an externally changed selected key", async () => {
const selected = ref<string | number | null>("dog");
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(
ComboBox,
{
"aria-label": "动物",
selectedKey: selected.value,
onSelectionChange: (key: string | number | null) =>
(selected.value = key),
},
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
await nextTick();
await settle();
expect(input().value).toBe("狗");
selected.value = "cat";
await nextTick();
await settle();
expect(input().value).toBe("猫");
});
it("skips disabled keys and does not select them", async () => {
const onChange = vi.fn();
mountCombo(
{ disabledKeys: ["cat"], onSelectionChange: onChange },
{ items: animals },
);
await nextTick();
input().focus();
await press("ArrowDown");
expect(
document.querySelector('[role="option"]')!.getAttribute("aria-disabled"),
).toBe("true");
await press("Enter");
expect(onChange).toHaveBeenLastCalledWith("dog");
});
it("does not open or select while disabled", async () => {
const onChange = vi.fn();
mountCombo({ isDisabled: true, onSelectionChange: onChange });
await nextTick();
input().focus();
await press("ArrowDown");
expect(input().getAttribute("aria-expanded")).toBe("false");
expect(onChange).not.toHaveBeenCalled();
});
it("keeps the input read-only without selecting", async () => {
const onChange = vi.fn();
mountCombo({ isReadOnly: true, onSelectionChange: onChange });
await nextTick();
expect(input().readOnly).toBe(true);
input().focus();
await press("ArrowDown");
expect(input().getAttribute("aria-expanded")).toBe("false");
});
it("shows multiple values and keeps accepted keys when filtered out", async () => {
const selected = ref<(string | number)[]>(["cat", "dog"]);
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(
ComboBox,
{
"aria-label": "动物",
selectionMode: "multiple",
modelValue: selected.value,
"onUpdate:modelValue": (value: unknown) =>
(selected.value = (value ?? []) as (string | number)[]),
},
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(ComboBoxValue, { placeholder: "未选择" }),
h(ComboBoxPopover, null, {
default: () =>
h(
ListBox,
{ selectionMode: "multiple" },
{
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
},
),
}),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
await nextTick();
await settle();
const value = () =>
document
.querySelector('[data-slot="combo-box-value"]')!
.textContent?.trim();
expect(value()).toBe("猫, 狗");
input().focus();
await type("鸟");
expect(value()).toBe("猫, 狗");
expect(selected.value).toEqual(["cat", "dog"]);
});
});
describe("ComboBox form and validation", () => {
it("submits the key or the text 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 = `${data.get("animal")}|${data.get("animal-text")}`;
},
},
{
default: () => [
h(
ComboBox,
{
"aria-label": "key",
name: "animal",
formValue: "key",
defaultSelectedKey: "cat",
},
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
}),
}),
],
},
),
h(
ComboBox,
{
"aria-label": "text",
name: "animal-text",
formValue: "text",
defaultSelectedKey: "dog",
},
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
}),
}),
],
},
),
h(
"button",
{ type: "submit", "data-test": "submit" },
"提交",
),
h("p", { "data-test": "result" }, submitted.value),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
await nextTick();
await settle();
(
document.querySelector('[data-test="submit"]') as HTMLButtonElement
).click();
await nextTick();
expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
"cat|狗",
);
});
it("blocks native submit when required and empty", async () => {
const wrapper = mount(
defineComponent({
setup() {
const submitted = ref(0);
return () =>
h(
Form,
{
onSubmit: (event: Event) => {
event.preventDefault();
submitted.value += 1;
},
},
{
default: () => [
h(
ComboBox,
{ "aria-label": "动物", name: "animal", isRequired: true },
{
default: () => [
h(Label, () => "动物"),
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
}),
}),
h(FieldError, () => "请选择动物"),
],
},
),
h(
"button",
{ type: "submit", "data-test": "submit" },
"提交",
),
h("p", { "data-test": "submitted" }, String(submitted.value)),
],
},
);
},
}),
{ attachTo: document.body },
);
mounted.push(wrapper);
await nextTick();
await settle();
const form = document.querySelector("form")!;
const blocked = !form.checkValidity();
expect(blocked).toBe(true);
expect(input().required).toBe(true);
});
it("surfaces a Description and an ErrorMessage through aria-describedby", async () => {
mount(
defineComponent({
setup() {
return () =>
h(
ComboBox,
{ "aria-label": "动物", isInvalid: true },
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [h(Input, {}), h(ComboBoxTrigger)],
}),
h(Description, () => "选择一种动物"),
h(FieldError, () => "请选择动物"),
h(ComboBoxPopover, null, {
default: () =>
h(ListBox, null, {
default: () =>
animals.map((item) =>
h(
ListBoxItem,
{
id: item.id,
key: item.id,
textValue: item.text,
},
() => item.text,
),
),
}),
}),
],
},
);
},
}),
{ attachTo: document.body },
);
await nextTick();
await settle();
const described = input().getAttribute("aria-describedby") ?? "";
const description = document.querySelector('[data-slot="description"]')!;
const error = document.querySelector('[data-slot="field-error"]')!;
expect(described).toContain(description.id);
expect(described).toContain(error.id);
});
});
describe("ComboBox menu trigger", () => {
it("opens on input only for menu-trigger=input", async () => {
mountCombo({ menuTrigger: "input" });
await nextTick();
input().focus();
await nextTick();
await settle();
expect(input().getAttribute("aria-expanded")).toBe("false");
await type("猫");
expect(input().getAttribute("aria-expanded")).toBe("true");
});
it("stays closed on focus for menu-trigger=manual and opens with ArrowDown", async () => {
mountCombo({ menuTrigger: "manual" });
await nextTick();
input().focus();
await nextTick();
await settle();
expect(input().getAttribute("aria-expanded")).toBe("false");
await press("ArrowDown");
expect(input().getAttribute("aria-expanded")).toBe("true");
});
it("toggles from the trigger button", async () => {
mountCombo();
await nextTick();
const trigger = document.querySelector<HTMLButtonElement>(
'[data-slot="combo-box-trigger"]',
)!;
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(input().getAttribute("aria-expanded")).toBe("true");
});
});
describe("ComboBox ported style hooks", () => {
it("emits the data-slot values the ported CSS targets", async () => {
const css = readFileSync(
"packages/styles/components/combo-box.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-open="true"] [data-slot="combo-box-trigger-default-icon"]',
);
mountCombo();
await nextTick();
input().focus();
await nextTick();
await settle();
const trigger = document.querySelector('[data-slot="combo-box-trigger"]')!;
expect(trigger.getAttribute("data-open")).toBe("true");
expect(
trigger.querySelector('[data-slot="combo-box-trigger-default-icon"]'),
).not.toBeNull();
});
});
describe("ComboBox filtering and composition", () => {
it("inherits an accent-insensitive base matcher", async () => {
mountCombo({}, { items: [{ id: "cafe", text: "Café" }] });
await nextTick();
input().focus();
await nextTick();
await settle();
await type("cafe");
expect(rowTexts()).toEqual(["Café"]);
await type("CAFÉ");
expect(rowTexts()).toEqual(["Café"]);
// Decomposed input still matches the precomposed label.
await type("cafe\u0301");
expect(rowTexts()).toEqual(["Café"]);
});
it("lets a custom defaultFilter win over the built-in matcher", async () => {
const defaultFilter = vi.fn(
(text: string, query: string) => !query || text === query,
);
mountCombo({ defaultFilter });
await nextTick();
input().focus();
await nextTick();
await settle();
await type("猫");
expect(defaultFilter).toHaveBeenCalled();
expect(rowTexts()).toEqual(["猫"]);
// The built-in contains() would match "猫" inside "熊猫"; the custom one does not.
await type("熊");
expect(rowTexts()).toEqual([]);
});
it("filters only after an open composition session ends", async () => {
mountCombo();
await nextTick();
input().focus();
await nextTick();
await settle();
expect(rowTexts()).toHaveLength(4);
input().dispatchEvent(new CompositionEvent("compositionstart"));
await nextTick();
await type("狗");
expect(rowTexts()).toHaveLength(4);
input().dispatchEvent(new CompositionEvent("compositionend"));
await nextTick();
await settle();
expect(rowTexts()).toEqual(["狗"]);
});
});
describe("ComboBox field protocol", () => {
it("lets the user clear a required value, then blocks the submit", async () => {
const update = vi.fn();
mountCombo({
name: "animal",
defaultValue: "cat",
isRequired: true,
"onUpdate:modelValue": update,
});
await nextTick();
await settle();
expect(input().value).toBe("猫");
await type("");
expect(update).toHaveBeenLastCalledWith(null);
expect(input().value).toBe("");
// The emptied field is invalid for native validation, not un-editable.
expect(input().checkValidity()).toBe(false);
});
it("associates the input and its reset handling with an external form", async () => {
const external = document.createElement("form");
external.id = "external-form";
document.body.appendChild(external);
mountCombo({
name: "animal",
form: "external-form",
defaultValue: "cat",
});
await nextTick();
await settle();
expect(input().form).toBe(external);
expect(new FormData(external).get("animal")).toBe("cat");
// An accepted reset restores the initial value through the same owner.
const reset = new Event("reset", { cancelable: true });
external.dispatchEvent(reset);
await nextTick();
await settle();
expect(new FormData(external).get("animal")).toBe("cat");
// A cancelled reset leaves the field untouched.
const cancelled = new Event("reset", { cancelable: true });
cancelled.preventDefault();
external.dispatchEvent(cancelled);
await nextTick();
await settle();
expect(input().value).toBe("猫");
external.remove();
});
it("submits no entry for a disabled field", async () => {
mountCombo({ name: "animal", defaultValue: "cat", isDisabled: true });
await nextTick();
await settle();
expect(
document.querySelector('[data-slot="combo-box-form-value"]'),
).toBeNull();
});
});
describe("ComboBox asChild, variant and autoFocus", () => {
it("keeps the caller's root element, handlers and ref", async () => {
const onClick = vi.fn();
const hostRef = ref<HTMLElement>();
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
ComboBox,
{ asChild: true },
{
default: () =>
h(
"section",
{ ref: hostRef, "data-test": "host", onClick },
"picker",
),
},
),
}),
{ attachTo: document.body },
);
await nextTick();
const host = wrapper.element as HTMLElement;
expect(host.tagName).toBe("SECTION");
expect(host.getAttribute("data-slot")).toBe("combo-box");
expect(host.classList.contains("hv-combo-box")).toBe(true);
expect(host.textContent).toContain("picker");
expect(hostRef.value).toBe(host);
host.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(onClick).toHaveBeenCalledTimes(1);
});
it("lets an explicit Input variant override the inherited one", async () => {
mount(
defineComponent({
setup: () => () =>
h(
ComboBox,
{ variant: "secondary" },
{
default: () => [
h(ComboBoxInputGroup, null, {
default: () => [
h(Input, { variant: "primary" }),
h(ComboBoxTrigger),
],
}),
],
},
),
}),
{ attachTo: document.body },
);
await nextTick();
expect(input().classList.contains("hv-input--primary")).toBe(true);
expect(input().classList.contains("hv-input--secondary")).toBe(false);
});
it("skips autoFocus when the field is disabled", async () => {
mountCombo({ autoFocus: true, isDisabled: true });
await nextTick();
await settle();
expect(document.activeElement).not.toBe(input());
});
});