import { afterEach, describe, expect, it, vi } from "vitest"; import { mount } from "@vue/test-utils"; import { createSSRApp, defineComponent, h, nextTick, ref } from "vue"; import { renderToString } from "@vue/server-renderer"; import { Button, CloseButton, Description, FieldError, FieldGroup, Fieldset, FieldsetActions, FieldsetLegend, Form, Input, Label, Link, SearchField, SearchFieldClearButton, SearchFieldGroup, SearchFieldInput, SearchFieldSearchIcon, Switch, TextArea, TextField, } from "../packages/vue/src"; afterEach(() => { document.body.innerHTML = ""; }); const settle = async () => { await nextTick(); await nextTick(); }; function search( props: Record = {}, inputProps = {}, clearProps = {}, ) { return h(SearchField, props, () => [ h(Label, {}, () => "Search"), h(SearchFieldGroup, {}, () => [ h(SearchFieldSearchIcon), h(SearchFieldInput, inputProps), h(SearchFieldClearButton, clearProps), ]), h(Description, {}, () => "Hint"), h(FieldError), ]); } describe("Fieldset disabled scope", () => { it("renders native semantics and the four baseline parts", () => { const w = mount(Fieldset, { attrs: { class: ["extra", { more: true }], name: "profile" }, slots: { default: () => [ h(FieldsetLegend, {}, () => "Profile"), h(FieldGroup), h(FieldsetActions), ], }, }); expect(w.element.tagName).toBe("FIELDSET"); expect(w.classes()).toContain("hv-fieldset"); expect(w.classes()).toContain("more"); expect(w.get("legend").classes()).toContain("hv-fieldset__legend"); expect(w.get("[data-slot=fieldset-field-group]").classes()).toContain( "hv-fieldset__field-group", ); w.unmount(); }); it("inherits disabled into native and non-native controls, slots and FormData", async () => { const disabled = ref(true); const clicked = vi.fn(); const w = mount( defineComponent({ render: () => h(Form, {}, () => [ h(Fieldset, { disabled: disabled.value }, () => [ h(TextField, { name: "a", defaultValue: "x" }, () => [ h(Label, {}, () => "A"), h(Input), ]), h(TextArea, { name: "b", defaultValue: "y" }), h(Switch, { name: "switch", defaultChecked: true }), h( Button, { onClick: clicked }, { default: (s: { isDisabled: boolean }) => String(s.isDisabled), }, ), h( Link, { href: "#go", onClick: clicked }, { default: (s: { isDisabled: boolean }) => String(s.isDisabled), }, ), h(CloseButton, { onClick: clicked }), search({ name: "query", defaultValue: "q" }), ]), ]), }), { attachTo: document.body }, ); expect(w.get("input[name=a]").attributes("disabled")).toBeDefined(); expect(w.get("textarea").attributes("disabled")).toBeDefined(); expect(w.get("[data-slot=button]").text()).toBe("true"); expect(w.get("a").text()).toBe("true"); await w.get("a").trigger("click"); await w.get("[role=switch]").trigger("click"); expect(clicked).not.toHaveBeenCalled(); expect(w.get("[role=switch]").attributes("aria-checked")).toBe("true"); expect([...new FormData(w.get("form").element as HTMLFormElement)]).toEqual( [], ); disabled.value = false; await settle(); expect(w.get("[data-slot=button]").text()).toBe("false"); expect( Object.fromEntries( new FormData(w.get("form").element as HTMLFormElement), ), ).toEqual({ a: "x", b: "y", switch: "on", query: "q" }); w.unmount(); }); it("preserves the first direct legend exception, nested fieldsets and local disabled", async () => { const w = mount( defineComponent({ render: () => h(Form, {}, () => h(Fieldset, { disabled: true }, () => [ h(FieldsetLegend, {}, () => [ h(Label, { for: "legend-input" }, () => "Exempt label"), h(Input, { id: "legend-input", name: "legend", defaultValue: "allowed", }), h(Button, {}, () => "Legend"), ]), h(FieldsetLegend, {}, () => h(Input, { name: "second" })), h(Fieldset, { disabled: false }, () => [ h(FieldsetLegend, {}, () => h(Input, { name: "innerLegend" })), h(Input, { name: "inner" }), ]), ]), ), }), { attachTo: document.body }, ); expect(w.get("input[name=legend]").attributes("disabled")).toBeUndefined(); expect(w.get('label[for="legend-input"]').classes()).not.toContain( "hv-label--disabled", ); expect(w.get("input[name=second]").attributes("disabled")).toBeDefined(); expect( w.get("input[name=innerLegend]").attributes("disabled"), ).toBeDefined(); expect(w.get("input[name=inner]").attributes("disabled")).toBeDefined(); expect( Object.fromEntries( new FormData(w.get("form").element as HTMLFormElement), ), ).toEqual({ legend: "allowed" }); w.unmount(); }); it("handles a dynamically inserted first legend and native legend children", async () => { const first = ref(true); const w = mount( defineComponent({ render: () => h(Fieldset, { disabled: true }, () => [ first.value ? h(FieldsetLegend, { key: "one" }, () => h(Input, { name: "one" }), ) : null, h("legend", { key: "two" }, [h(Input, { name: "two" })]), ]), }), ); expect(w.get("input[name=two]").attributes("disabled")).toBeDefined(); first.value = false; await settle(); expect(w.get("input[name=two]").attributes("disabled")).toBeUndefined(); w.unmount(); }); }); describe("SearchField shared text state", () => { it("renders search type, unique label/description/error references and empty state", async () => { const w = mount(search({ isInvalid: true })); await settle(); expect(w.get("input").attributes("type")).toBe("search"); expect(w.get("label").attributes("for")).toBe( w.get("input").attributes("id"), ); expect(w.attributes("data-empty")).toBe("true"); expect( w.get("[data-slot=search-field-clear-button]").attributes("tabindex"), ).toBe("-1"); for (const id of w.get("input").attributes("aria-describedby")!.split(" ")) expect(w.find(`[id="${id}"]`).exists()).toBe(true); expect(w.classes()).not.toContain("hv-textfield"); w.unmount(); }); it("clears once, emits the value, focuses the input, and does not submit the form", async () => { const clear = vi.fn(), change = vi.fn(), submit = vi.fn((e: Event) => e.preventDefault()); const w = mount( defineComponent({ render: () => h(Form, { onSubmit: submit }, () => search({ defaultValue: "hello", onClear: clear, "onUpdate:modelValue": change, }), ), }), { attachTo: document.body }, ); await w.get("[data-slot=search-field-clear-button]").trigger("click"); await settle(); expect((w.get("input").element as HTMLInputElement).value).toBe(""); expect(clear).toHaveBeenCalledOnce(); expect(change).toHaveBeenCalledExactlyOnceWith(""); expect(submit).not.toHaveBeenCalled(); expect(document.activeElement).toBe(w.get("input").element); w.unmount(); }); it("restores a rejected root or leaf controlled clear", async () => { for (const leaf of [false, true]) { const change = vi.fn(); const w = mount( search( leaf ? {} : { modelValue: "keep", "onUpdate:modelValue": change }, leaf ? { modelValue: "keep", "onUpdate:modelValue": change } : {}, ), { attachTo: document.body }, ); await w.get("[data-slot=search-field-clear-button]").trigger("click"); await settle(); expect((w.get("input").element as HTMLInputElement).value).toBe("keep"); expect(change).toHaveBeenCalledExactlyOnceWith(""); w.unmount(); } }); it("supports Escape clear and Enter submit once, ignoring IME/repeat and cancellation", async () => { const submit = vi.fn(), clear = vi.fn(); const w = mount( search({ defaultValue: "query", onSubmit: submit, onClear: clear }), ); await w .get("input") .trigger("keydown", { key: "Enter", isComposing: true }); await w.get("input").trigger("keydown", { key: "Enter", keyCode: 229 }); await w.get("input").trigger("keydown", { key: "Enter", repeat: true }); expect(submit).not.toHaveBeenCalled(); await w.get("input").trigger("keydown", { key: "Enter" }); await w.get("input").trigger("keyup", { key: "Enter" }); expect(submit).toHaveBeenCalledExactlyOnceWith("query"); await w.get("input").trigger("keydown", { key: "Escape" }); await settle(); expect(clear).toHaveBeenCalledOnce(); await w.get("input").trigger("keydown", { key: "Escape" }); expect(clear).toHaveBeenCalledOnce(); w.unmount(); const canceled = mount( search( { defaultValue: "q", onSubmit: submit }, { onKeydown: (e: Event) => e.preventDefault() }, ), ); await canceled.get("input").trigger("keydown", { key: "Enter" }); expect(submit).toHaveBeenCalledTimes(1); canceled.unmount(); }); it("lets implicit native form submission proceed without a search submit listener", async () => { const w = mount(search({ defaultValue: "q" })); const event = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, }); w.get("input").element.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); w.unmount(); }); it("respects readonly, disabled, caller cancellation, and native validation", async () => { for (const state of [{ isReadOnly: true }, { isDisabled: true }]) { const clear = vi.fn(); const w = mount(search({ ...state, defaultValue: "q", onClear: clear })); await w.get("[data-slot=search-field-clear-button]").trigger("click"); await w.get("input").trigger("keydown", { key: "Escape" }); expect(clear).not.toHaveBeenCalled(); expect((w.get("input").element as HTMLInputElement).value).toBe("q"); w.unmount(); } const submit = vi.fn(); const w = mount(search({ isRequired: true, onSubmit: submit })); await w.get("input").trigger("keydown", { key: "Enter" }); await settle(); expect(submit).not.toHaveBeenCalled(); expect(w.get("input").attributes("aria-invalid")).toBe("true"); w.unmount(); const canceled = mount( search( { defaultValue: "q" }, {}, { onClick: (e: Event) => e.preventDefault() }, ), ); await canceled .get("[data-slot=search-field-clear-button]") .trigger("click"); await settle(); expect((canceled.get("input").element as HTMLInputElement).value).toBe("q"); canceled.unmount(); }); it("shares FormData, default reset and canceled reset without a second value source", async () => { const w = mount( defineComponent({ render: () => h(Form, {}, () => search({ name: "q", defaultValue: "initial" })), }), { attachTo: document.body }, ); await w.get("input").setValue("changed"); const form = w.get("form").element as HTMLFormElement; expect(Object.fromEntries(new FormData(form))).toEqual({ q: "changed" }); form.reset(); await settle(); expect((w.get("input").element as HTMLInputElement).value).toBe("initial"); form.addEventListener("reset", (e) => e.preventDefault()); await w.get("input").setValue("keep"); form.reset(); await settle(); expect((w.get("input").element as HTMLInputElement).value).toBe("keep"); w.unmount(); }); it("supports SSR and hydration with explicit control ID inside group", async () => { const view = defineComponent({ render: () => search({ name: "q", defaultValue: "query" }, { id: "explicit-search" }), }); const host = document.createElement("div"); host.innerHTML = await renderToString(createSSRApp(view)); document.body.append(host); expect(host.querySelector("label")?.htmlFor).toBe("explicit-search"); const warn = vi.spyOn(console, "warn"), error = vi.spyOn(console, "error"); const app = createSSRApp(view); try { app.mount(host); await settle(); expect(warn).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); } finally { app.unmount(); warn.mockRestore(); error.mockRestore(); host.remove(); } }); it("updates variant, attrs, event handlers and conditional slots without stale classes", async () => { const attrs = ref>({}), variant = ref<"primary" | "secondary">("primary"), prefix = ref(true); const w = mount( defineComponent({ render: () => h(SearchField, { ...attrs.value, variant: variant.value }, () => h(SearchFieldGroup, {}, () => [ prefix.value ? h(SearchFieldSearchIcon) : null, h(SearchFieldInput), h(SearchFieldClearButton), ]), ), }), ); const change = vi.fn(); attrs.value = { class: ["custom", { more: true }], "aria-label": "New", "onUpdate:modelValue": change, }; variant.value = "secondary"; prefix.value = false; await settle(); expect(w.classes()).toContain("hv-search-field--secondary"); expect(w.classes()).not.toContain("hv-search-field--primary"); expect(w.classes()).toContain("more"); expect(w.get("input").attributes("aria-label")).toBe("New"); expect(w.find("[data-slot=search-field-search-icon]").exists()).toBe(false); await w.get("input").setValue("x"); expect(change).toHaveBeenCalledExactlyOnceWith("x"); attrs.value = {}; await settle(); expect(w.classes()).not.toContain("custom"); expect(w.get("input").attributes("aria-label")).toBeUndefined(); attrs.value = { "aria-label": "Again" }; await settle(); expect(w.get("input").attributes("aria-label")).toBe("Again"); w.unmount(); }); }); it("allows root handlers and handler arrays to cancel search keyboard actions", async () => { for (const stop of ["preventDefault", "stopImmediatePropagation"] as const) { const submit = vi.fn(), after = vi.fn(); const w = mount( search({ defaultValue: "q", onSubmit: submit, onKeydown: [(e: KeyboardEvent) => e[stop](), after], }), ); await w.get("input").trigger("keydown", { key: "Enter" }); expect(submit).not.toHaveBeenCalled(); expect(after).toHaveBeenCalledTimes(stop === "preventDefault" ? 1 : 0); w.unmount(); } }); it("preserves a keyed legend control's value when the first-legend exemption moves", async () => { const first = ref(false); const w = mount( defineComponent({ render: () => h(Fieldset, { disabled: true }, () => [ first.value ? h(FieldsetLegend, { key: "first" }, () => "First") : null, h(FieldsetLegend, { key: "second" }, () => h(Input, { name: "keyed" }), ), ]), }), ); await w.get("input").setValue("retained"); first.value = true; await settle(); expect(w.get("input").attributes("disabled")).toBeDefined(); expect((w.get("input").element as HTMLInputElement).value).toBe("retained"); first.value = false; await settle(); expect((w.get("input").element as HTMLInputElement).value).toBe("retained"); w.unmount(); }); it("keeps the baseline preview inventories and exact fieldset submission feedback", async () => { const { readFileSync } = await import("node:fs"); const searchNames = [ "basic", "variants", "on-surface", "with-description", "required", "disabled", "full-width", "validation", "controlled", "form-example", "with-validation", "custom-icons", "with-keyboard-shortcut", "render-function", "custom-styles", ]; const doc = readFileSync("apps/docs/components/search-field.md", "utf8"); expect( [...doc.matchAll(/ m[1], ), ).toEqual(searchNames); for (const name of searchNames) expect( readFileSync(`apps/docs/demos/search-field-${name}.vue`, "utf8"), ).toContain("