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, options: { states?: State[]; empty?: boolean; description?: boolean } = {}, emits: Record = {}, ) { 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('[data-slot="autocomplete-trigger"]')!; const search = () => document.querySelector('[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('[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(); expect( document.querySelector( '[data-slot="autocomplete-indicator"] [data-slot="autocomplete-default-indicator"]', ), ).not.toBeNull(); expect( document.querySelector('[data-slot="autocomplete-clear-button-icon"]'), ).not.toBeNull(); }); });