feat: migrate Select with field, collection and SSR contracts
This commit is contained in:
@@ -0,0 +1,696 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { createSSRApp, defineComponent, h, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
Modal,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeading,
|
||||
ModalBody,
|
||||
ModalTrigger,
|
||||
Button,
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectClearButton,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
Label,
|
||||
Description,
|
||||
Header,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
} from "../packages/vue/src";
|
||||
const components = {
|
||||
Modal,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeading,
|
||||
ModalBody,
|
||||
ModalTrigger,
|
||||
Button,
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectClearButton,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
Label,
|
||||
Description,
|
||||
Header,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
};
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
const options =
|
||||
'<ListBoxItem :id="0"><Label>Zero number</Label><Description>Details</Description><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="0"><Label>Zero string</Label><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="disabled" is-disabled>Disabled</ListBoxItem><ListBoxItem id="last">Last</ListBoxItem>';
|
||||
const content = `<Label>Choice</Label><SelectTrigger><SelectValue/><SelectClearButton/><SelectIndicator/></SelectTrigger><Description>Help</Description><FieldError/><SelectPopover><ListBox>${options}</ListBox></SelectPopover>`;
|
||||
function fixture(template: string, setup = () => ({})) {
|
||||
const wrapper = mount(defineComponent({ components, setup, template }), {
|
||||
attachTo: document.body,
|
||||
});
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
const trigger = (w: ReturnType<typeof mount>) =>
|
||||
w.get('[data-slot="select-trigger"]');
|
||||
const option = (index: number) =>
|
||||
document.querySelectorAll<HTMLElement>('[role="option"]')[index];
|
||||
async function clickOption(index: number) {
|
||||
option(index).click();
|
||||
await flushPromises();
|
||||
}
|
||||
const data = () => [...new FormData(document.querySelector("form")!).entries()];
|
||||
describe("Select public contracts", () => {
|
||||
it("plans closed labels and submits raw numeric/string keys once", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :default-value="0">${content}</Select></form>`,
|
||||
);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
expect(document.querySelector('[role="listbox"]')).toBeNull();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="listbox"]')).not.toBeNull();
|
||||
expect(option(0).getAttribute("aria-selected")).toBe("true");
|
||||
await clickOption(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([["0"]]);
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero string");
|
||||
});
|
||||
it("uses parent accepted multiple values, retries rejected proposals, and keeps the popup open", async () => {
|
||||
const value = ref<(string | number)[]>([0]);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" selection-mode="multiple" :model-value="value">${content}</Select></form>`,
|
||||
() => ({ value }),
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(1);
|
||||
await clickOption(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([[[0, "0"]], [[0, "0"]]]);
|
||||
expect(option(1).getAttribute("aria-selected")).toBe("false");
|
||||
value.value = [0, "0"];
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([
|
||||
["choice", "0"],
|
||||
["choice", "0"],
|
||||
]);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
it("clears without toggling, supports closed Delete only with a clear affordance", async () => {
|
||||
const w = fixture(`<Select default-value="last">${content}</Select>`);
|
||||
await w
|
||||
.get('[data-slot="select-clear-button"]')
|
||||
.trigger("click", { button: 0 });
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
expect(w.getComponent(components.Select).emitted("clear")).toHaveLength(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([[null]]);
|
||||
const plain = fixture(
|
||||
`<Select default-value="last">${content.replace("<SelectClearButton/>", "")}</Select>`,
|
||||
);
|
||||
await trigger(plain).trigger("keydown", { key: "Delete" });
|
||||
expect(
|
||||
plain.getComponent(components.Select).emitted("change"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("honors disabled/readonly state and native reset", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(data()).toEqual([]);
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
w.unmount();
|
||||
wrappers.pop();
|
||||
document.body.innerHTML = "";
|
||||
const readonly = fixture(
|
||||
`<form><Select is-read-only name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(readonly).trigger("click");
|
||||
expect(trigger(readonly).attributes("aria-expanded")).toBe("false");
|
||||
await trigger(readonly).trigger("keydown", { key: "Delete" });
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
});
|
||||
it("links field labels, descriptions and errors without option leakage", async () => {
|
||||
const w = fixture(`<Select is-required>${content}</Select>`);
|
||||
const t = trigger(w);
|
||||
const ids = t.attributes("aria-labelledby")!.split(" ");
|
||||
expect(
|
||||
ids.map((id) => document.getElementById(id)?.textContent).join(" "),
|
||||
).toContain("Choice");
|
||||
expect(t.attributes("aria-describedby")).toBeTruthy();
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(false);
|
||||
await flushPromises();
|
||||
expect(t.attributes("aria-invalid")).toBe("true");
|
||||
await t.trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(true);
|
||||
expect(t.attributes("aria-labelledby")).toBe(ids.join(" "));
|
||||
});
|
||||
it("allows trigger event cancellation and honors explicit root accessible names", async () => {
|
||||
const w = fixture(
|
||||
`<Select aria-label="Named">${content.replace("<SelectTrigger>", "<SelectTrigger @click.prevent>")}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
expect(trigger(w).attributes("aria-label")).toBe("Named");
|
||||
});
|
||||
it("renders selected labels and native submission on SSR without mounting popup", async () => {
|
||||
const app = createSSRApp(
|
||||
defineComponent({
|
||||
components,
|
||||
template: `<Select name="choice" :default-value="0">${content}</Select>`,
|
||||
}),
|
||||
);
|
||||
const html = await renderToString(app);
|
||||
expect(html).toContain("Zero number");
|
||||
expect(html).not.toContain('role="listbox"');
|
||||
expect(html).toContain('name="choice"');
|
||||
expect(html).toContain('value="0" data-index="0" selected');
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select form and collection changes", () => {
|
||||
it("uses native autocomplete proposals and restores rejected parent values", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" auto-complete="country" :model-value="0">${content}</Select></form>`,
|
||||
);
|
||||
const native = w.get<HTMLSelectElement>("select");
|
||||
expect(native.attributes("autocomplete")).toBe("country");
|
||||
native.element.selectedIndex = 2;
|
||||
await native.trigger("change");
|
||||
await flushPromises();
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([["0"]]);
|
||||
expect(native.element.selectedIndex).toBe(1);
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
});
|
||||
it("omits removed or disabled selected options from FormData and constraints", async () => {
|
||||
const show = ref(true),
|
||||
disabled = ref(false);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="a" is-required><Label>Dynamic</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem v-if="show" id="a" :is-disabled="disabled">Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
() => ({ show, disabled }),
|
||||
);
|
||||
expect(data()).toEqual([["choice", "a"]]);
|
||||
disabled.value = true;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
disabled.value = false;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "a"]]);
|
||||
show.value = false;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("omits Fieldset-disabled values and preserves readonly values", async () => {
|
||||
const w = fixture(
|
||||
`<form><Fieldset disabled><Select name="choice" default-value="last">${content}</Select></Fieldset></form>`,
|
||||
);
|
||||
expect(trigger(w).attributes("disabled")).toBeDefined();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("keeps controlled reset and cancelled reset without synthetic changes", async () => {
|
||||
const w = fixture(
|
||||
`<form @reset.prevent><Select name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "Backspace" });
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[null]]);
|
||||
});
|
||||
it("counts conditional clear affordances and honors actual trigger disabled state", async () => {
|
||||
const clear = ref(true),
|
||||
disabled = ref(true);
|
||||
const w = fixture(
|
||||
`<Select default-value="last">${content.replace("<SelectTrigger>", '<SelectTrigger :is-disabled="disabled">').replace("<SelectClearButton/>", '<SelectClearButton v-if="clear"/>')}</Select>`,
|
||||
() => ({ clear, disabled }),
|
||||
);
|
||||
await w
|
||||
.get('[data-slot="select-clear-button"]')
|
||||
.trigger("click", { button: 0 });
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
disabled.value = false;
|
||||
clear.value = false;
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
clear.value = true;
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[null]]);
|
||||
});
|
||||
it("keeps open controlled, retries rejected openings and respects explicit undefined precedence", async () => {
|
||||
const w = fixture(
|
||||
`<Select :open="undefined" :is-open="true">${content}</Select>`,
|
||||
);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
await trigger(w).trigger("click");
|
||||
await trigger(w).trigger("click");
|
||||
expect(w.getComponent(Select).emitted("update:open")).toEqual([
|
||||
[true],
|
||||
[true],
|
||||
]);
|
||||
});
|
||||
it("focuses the selected option on open and skips disabled items", async () => {
|
||||
const w = fixture(`<Select default-value="last">${content}</Select>`);
|
||||
await trigger(w).trigger("keydown", { key: "ArrowDown" });
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(option(3));
|
||||
option(3).dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(option(0));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select popup boundary", () => {
|
||||
it("uses a presentation popup and a named listbox with correct ARIA ownership", async () => {
|
||||
const w = fixture(`<Select>${content}</Select>`);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const popup = document.querySelector('[data-slot="select-popover"]')!;
|
||||
expect(popup).not.toBeNull();
|
||||
expect(popup.getAttribute("role")).toBe("presentation");
|
||||
const list = document.querySelector('[role="listbox"]')!;
|
||||
expect(trigger(w).attributes("aria-controls")).toBe(list.id);
|
||||
expect(trigger(w).attributes("aria-haspopup")).toBe("listbox");
|
||||
expect(list.getAttribute("aria-labelledby")).toBe(
|
||||
w.get('[data-slot="label"]').attributes("id"),
|
||||
);
|
||||
});
|
||||
it("leaves Tab default traversal at the trigger without looping in the portal", async () => {
|
||||
const w = fixture(
|
||||
`<div><Select>${content}</Select><button>After</button></div>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const event = new KeyboardEvent("keydown", {
|
||||
key: "Tab",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
option(0).dispatchEvent(event);
|
||||
await flushPromises();
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("keeps controlled native selected options on reset even when Vue props did not change", async () => {
|
||||
const value = ref<string | number | (string | number)[] | null>("last");
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :model-value="value">${content}</Select></form>`,
|
||||
() => ({ value }),
|
||||
);
|
||||
value.value = 0;
|
||||
await flushPromises();
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select hydration and baseline demos", () => {
|
||||
it("hydrates default closed metadata, IDs and native selection without mismatches", async () => {
|
||||
const Component = defineComponent({
|
||||
components,
|
||||
template: `<Select name="choice" :default-value="0">${content}</Select>`,
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
host.innerHTML = await renderToString(createSSRApp(Component));
|
||||
document.body.append(host);
|
||||
const before = host.querySelector('[data-slot="select-trigger"]');
|
||||
const warnings: string[] = [];
|
||||
const app = createSSRApp(Component);
|
||||
app.config.warnHandler = (message) => warnings.push(message);
|
||||
app.mount(host);
|
||||
await flushPromises();
|
||||
try {
|
||||
expect(warnings).toEqual([]);
|
||||
expect(host.querySelector('[data-slot="select-trigger"]')).toBe(before);
|
||||
expect(
|
||||
host.querySelector("select")?.selectedOptions[0].dataset.index,
|
||||
).toBe("0");
|
||||
} finally {
|
||||
app.unmount();
|
||||
}
|
||||
});
|
||||
it("mounts all nineteen source demos with unique IDs and real async data", async () => {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = async () =>
|
||||
new Response(
|
||||
JSON.stringify({ next: null, results: [{ name: "bulbasaur" }] }),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
try {
|
||||
const demos = import.meta.glob("../apps/docs/demos/select-*.vue", {
|
||||
eager: true,
|
||||
import: "default",
|
||||
});
|
||||
expect(Object.keys(demos)).toHaveLength(19);
|
||||
const warnings: string[] = [];
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(
|
||||
"main",
|
||||
Object.values(demos).map((component) =>
|
||||
h(component as ReturnType<typeof defineComponent>),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
config: { warnHandler: (message) => warnings.push(message) },
|
||||
},
|
||||
},
|
||||
);
|
||||
wrappers.push(w);
|
||||
await flushPromises();
|
||||
expect(warnings).toEqual([]);
|
||||
const ids = w.findAll("[id]").map((node) => node.attributes("id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
expect(w.findAll('[data-slot="select-trigger"]')).toHaveLength(23);
|
||||
const asyncDemo = w
|
||||
.findAllComponents(Select)
|
||||
.find(
|
||||
(component) => component.props("placeholder") === "请选择宝可梦",
|
||||
)!;
|
||||
expect(asyncDemo.get("select").text()).toContain("bulbasaur");
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select names, cancellation and closed keyboard", () => {
|
||||
it("moves focus on field Label click without opening the menu", async () => {
|
||||
const w = fixture(`<Select>${content}</Select>`);
|
||||
await w.get('[data-slot="label"]').trigger("click");
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("supports closed typeahead and skips disabled options without editing during IME", async () => {
|
||||
const w = fixture(
|
||||
`<Select><Label>People</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="a" text-value="Liam Smith">Liam Smith</ListBoxItem><ListBoxItem id="b" text-value="Liam Jones">Liam Jones</ListBoxItem><ListBoxItem id="c" is-disabled text-value="Martha">Martha</ListBoxItem></ListBox></SelectPopover></Select>`,
|
||||
);
|
||||
for (const key of ["l", "i", "a", "m"])
|
||||
await trigger(w).trigger("keydown", { key });
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Liam Smith");
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([["a"]]);
|
||||
await trigger(w).trigger("keydown", { key: "m", isComposing: true });
|
||||
expect(w.getComponent(Select).emitted("change")).toHaveLength(1);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("respects ListBox activation cancellation before selection or closing", async () => {
|
||||
const w = fixture(
|
||||
`<Select>${content.replace("<ListBox>", "<ListBox @keydown.prevent>")}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
option(0).dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
it("keeps aria validation nonblocking and refreshes Form server errors", async () => {
|
||||
const errors = ref<Record<string, string>>({ choice: "Server error" });
|
||||
const w = fixture(
|
||||
`<Form :validation-errors="errors" validation-behavior="aria"><Select name="choice" is-required>${content}</Select></Form>`,
|
||||
() => ({ errors }),
|
||||
);
|
||||
expect(trigger(w).attributes("aria-invalid")).toBe("true");
|
||||
expect(w.text()).toContain("Server error");
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(true);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.text()).not.toContain("Server error");
|
||||
errors.value = { choice: "Refreshed" };
|
||||
await flushPromises();
|
||||
expect(w.text()).toContain("Refreshed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select metadata and identity", () => {
|
||||
it("retains empty-string identities through native form submission", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value=""><Label>Empty</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="">Empty key</ListBoxItem><ListBoxItem id="a">Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
);
|
||||
expect(data()).toEqual([["choice", ""]]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Empty key");
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(option(0).getAttribute("aria-selected")).toBe("true");
|
||||
});
|
||||
it("associates an external form dynamically and restores reset values", async () => {
|
||||
const owner = ref("one");
|
||||
const w = fixture(
|
||||
`<div><form id="one"></form><form id="two"></form><Select :form="owner" name="choice" default-value="last">${content}</Select></div>`,
|
||||
() => ({ owner }),
|
||||
);
|
||||
owner.value = "two";
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
(w.get("#one").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
w.get('[data-slot="select-value"]').attributes("data-placeholder"),
|
||||
).toBe("true");
|
||||
(w.get("#two").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
new FormData(w.get("#two").element as HTMLFormElement).get("choice"),
|
||||
).toBe("last");
|
||||
});
|
||||
it("refreshes explicit asynchronous selected metadata before opening", async () => {
|
||||
const items = ref<{ id: number; textValue: string }[]>([]);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :model-value="0" :items="items"><Label>Async</Label><SelectTrigger><SelectValue/></SelectTrigger></Select></form>`,
|
||||
() => ({ items }),
|
||||
);
|
||||
expect(data()).toEqual([]);
|
||||
items.value = [{ id: 0, textValue: "Loaded label" }];
|
||||
await flushPromises();
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Loaded label");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
items.value = [];
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("gives root accessible names to the popup list and keeps cancellation intact", async () => {
|
||||
const w = fixture(`<Select aria-label="Root name">${content}</Select>`);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="listbox"]')?.getAttribute("aria-label"),
|
||||
).toBe("Root name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select integration boundaries", () => {
|
||||
it("keeps a nested Modal open when its Select handles Escape", async () => {
|
||||
const w = fixture(
|
||||
`<Modal><ModalTrigger>Open modal</ModalTrigger><ModalBackdrop><ModalContainer><ModalDialog><ModalHeading>Parent dialog</ModalHeading><ModalBody><Select>${content}</Select></ModalBody></ModalDialog></ModalContainer></ModalBackdrop></Modal>`,
|
||||
);
|
||||
await w.get('[data-slot="modal-trigger"]').trigger("click");
|
||||
await flushPromises();
|
||||
const selectTrigger = document.querySelector<HTMLElement>(
|
||||
'[data-slot="select-trigger"]',
|
||||
)!;
|
||||
selectTrigger.click();
|
||||
await flushPromises();
|
||||
expect(option(0)).toBeTruthy();
|
||||
option(0).dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Escape",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(selectTrigger.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("honors open autofocus cancellation and native handler array stop semantics", async () => {
|
||||
const calls: string[] = [];
|
||||
const stop = (event: Event) => {
|
||||
calls.push("first");
|
||||
event.stopImmediatePropagation();
|
||||
};
|
||||
const second = () => calls.push("second");
|
||||
const w = fixture(
|
||||
`<Select>${content.replace("<SelectTrigger>", '<SelectTrigger :onKeydown="[stop,second]">').replace("<SelectPopover>", "<SelectPopover @open-auto-focus.prevent>")}</Select>`,
|
||||
() => ({ stop, second }),
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "ArrowDown" });
|
||||
expect(calls).toEqual(["first"]);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
(trigger(w).element as HTMLElement).focus();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
});
|
||||
it("honors per-item cancellation before changing or closing", async () => {
|
||||
const w = fixture(
|
||||
`<Select>${content.replace('<ListBoxItem :id="0">', '<ListBoxItem :id="0" @select.prevent>')}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select async demo lifecycle", () => {
|
||||
it("loads a second page, retains existing options on failure, and retries", async () => {
|
||||
const original = globalThis.fetch;
|
||||
const cursors: string[] = [];
|
||||
let call = 0;
|
||||
globalThis.fetch = async (input) => {
|
||||
cursors.push(String(input));
|
||||
call++;
|
||||
if (call === 2) return new Response("", { status: 503 });
|
||||
return new Response(
|
||||
JSON.stringify(
|
||||
call === 1
|
||||
? {
|
||||
next: "https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
results: [{ name: "bulbasaur" }],
|
||||
}
|
||||
: { next: null, results: [{ name: "ivysaur" }] },
|
||||
),
|
||||
{ status: 200 },
|
||||
);
|
||||
};
|
||||
try {
|
||||
const { default: Demo } =
|
||||
await import("../apps/docs/demos/select-asynchronous-loading.vue");
|
||||
const w = mount(Demo, { attachTo: document.body });
|
||||
wrappers.push(w);
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const more = [
|
||||
...document.querySelectorAll<HTMLButtonElement>(
|
||||
'[data-slot="select-popover"] button',
|
||||
),
|
||||
].find((button) => button.textContent?.includes("加载更多"))!;
|
||||
more.click();
|
||||
await flushPromises();
|
||||
expect(w.get("select").text()).toContain("bulbasaur");
|
||||
const retry = [
|
||||
...document.querySelectorAll<HTMLButtonElement>(
|
||||
'[data-slot="select-popover"] button',
|
||||
),
|
||||
].find((button) => button.textContent?.includes("重试"))!;
|
||||
expect(retry).toBeTruthy();
|
||||
retry.click();
|
||||
await flushPromises();
|
||||
await vi.waitFor(() =>
|
||||
expect(w.get("select").text()).toContain("ivysaur"),
|
||||
);
|
||||
expect(cursors).toEqual([
|
||||
"https://pokeapi.co/api/v2/pokemon",
|
||||
"https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
"https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
]);
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
it("aborts the pending request on unmount", async () => {
|
||||
const original = globalThis.fetch;
|
||||
let signal: AbortSignal | undefined;
|
||||
globalThis.fetch = async (_input, init) => {
|
||||
signal = init?.signal ?? undefined;
|
||||
return new Promise<Response>(() => {});
|
||||
};
|
||||
try {
|
||||
const { default: Demo } =
|
||||
await import("../apps/docs/demos/select-asynchronous-loading.vue");
|
||||
const w = mount(Demo, { attachTo: document.body });
|
||||
expect(signal?.aborted).toBe(false);
|
||||
w.unmount();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select dynamic mode", () => {
|
||||
it("adapts uncontrolled single/multiple shapes and reset without synthetic edits", async () => {
|
||||
const mode = ref<"single" | "multiple">("single");
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :selection-mode="mode" default-value="last">${content}</Select></form>`,
|
||||
() => ({ mode }),
|
||||
);
|
||||
mode.value = "multiple";
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[["last", 0]]]);
|
||||
mode.value = "single";
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
expect(w.getComponent(Select).emitted("change")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps locally disabled options out of the native submission even with explicit text metadata", () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="a" :items="[{ id:'a', textValue:'Alpha' }]"><Label>Metadata</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="a" is-disabled>Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
);
|
||||
expect(data()).toEqual([]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Alpha");
|
||||
});
|
||||
Reference in New Issue
Block a user