Merge Select migration and browser verification

# Conflicts:
#	AGENTS.md
#	docs/migration-handoff.md
#	docs/upstream.md
#	docs/verification.md
#	package.json
#	packages/styles/src/index.ts
#	packages/vue/src/index.ts
#	packages/vue/src/types.ts
#	tests/package/README.md
This commit is contained in:
maoyingjie
2026-10-23 23:00:28 +08:00
54 changed files with 4347 additions and 34 deletions
+2
View File
@@ -19,3 +19,5 @@ M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制
LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。
M33–M34 使用 consume-m33-m34.mjs / m33-m34-contract.ts;同样复制到独立 tarball 消费工程,分别运行 node 与两种解析模式的 tsc。包括所有公开部件、真正 node SSR、CSS 关键帧与策略/尺寸/方向的正反类型检查。集成验证目录为 /private/tmp/heroui-m33-consumer,不复用其他并行任务的临时产物。
SELECT-01 增加 `consume-select.mjs` / `select-contract.ts`。新 tarball 安装后运行 ESM/SSR/CSS 脚本,两种模块解析模式都纳入类型正反例;数字/字符串/空 key、六部件、validate 与事件载荷推断不应退化。保留旧组件消费回归。
+70
View File
@@ -0,0 +1,70 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
Select,
SelectTrigger,
SelectValue,
SelectIndicator,
SelectClearButton,
SelectPopover,
ListBox,
ListBoxItem,
Label,
selectVariants,
} from "@heroui-vue/components";
const html = await renderToString(
createSSRApp({
render: () =>
h(
Select,
{
defaultValue: [0, "0", ""],
selectionMode: "multiple",
name: "choices",
},
() => [
h(Label, {}, () => "Choice"),
h(SelectTrigger, {}, () => [
h(SelectValue),
h(SelectClearButton),
h(SelectIndicator),
]),
h(SelectPopover, {}, () =>
h(ListBox, {}, () => [
h(ListBoxItem, { id: 0, textValue: "Numeric" }, () => "Numeric"),
h(ListBoxItem, { id: "0", textValue: "String" }, () => "String"),
h(ListBoxItem, { id: "", textValue: "Empty" }, () => "Empty"),
]),
),
],
),
}),
);
assert(html.includes("Numeric, String, Empty"));
assert(html.includes('name="choices"'));
assert.equal((html.match(/data-index="\d" selected/g) ?? []).length, 3);
assert(!html.includes('role="listbox"'));
assert(html.includes('aria-haspopup="listbox"'));
assert(
selectVariants({ variant: "secondary" })
.base()
.includes("hv-select--secondary"),
);
const css = readFileSync(
new URL(import.meta.resolve("@heroui-vue/styles/css")),
"utf8",
);
for (const part of [
".hv-select",
".hv-select__trigger",
".hv-select__value",
".hv-select__clear-button",
".hv-select__indicator",
".hv-select__popover",
])
assert(css.includes(part));
console.log(
"Select independent tarball: ESM, SSR labels, raw native values, variants and CSS passed.",
);
+77
View File
@@ -0,0 +1,77 @@
import {
Select,
SelectRoot,
SelectTrigger,
SelectValue,
SelectIndicator,
SelectClearButton,
SelectPopover,
selectVariants,
type SelectProps,
type SelectValueProps,
type SelectPopoverProps,
type SelectModelValue,
} from "@heroui-vue/components";
const value: SelectModelValue = [0, "0", ""];
const props: SelectProps = {
modelValue: value,
selectionMode: "multiple",
variant: "secondary",
autoComplete: "country",
items: [{ id: 0, textValue: "Zero" }],
onChange: (next) => {
if (Array.isArray(next)) next.forEach((key) => String(key));
},
validate: (next) => (next === null ? "Required" : undefined),
onOpenChange: (open) => Boolean(open),
};
const part: SelectValueProps = { as: "span" };
const popup: SelectPopoverProps = { placement: "bottom start", offset: 8 };
// @ts-expect-error Keys are strings or numbers, never objects
const badValue: SelectProps = { modelValue: { id: 0 } };
// @ts-expect-error Selection mode is constrained
const badMode: SelectProps = { selectionMode: "checkbox" };
// @ts-expect-error Variants are constrained
const badVariant: SelectProps = { variant: "solid" };
// @ts-expect-error Metadata text is required
const badItems: SelectProps = { items: [{ id: 0 }] };
// @ts-expect-error Model listener receives SelectModelValue, not boolean
const badEvent: SelectProps = { onChange: (value: boolean) => value };
// @ts-expect-error Popover placement is constrained
const badPlacement: SelectPopoverProps = { placement: "diagonal" };
const badComponent: InstanceType<typeof Select>["$props"] = {
// @ts-expect-error Generated component props are also constrained
modelValue: [false],
};
void [
Select,
SelectRoot,
SelectTrigger,
SelectValue,
SelectIndicator,
SelectClearButton,
SelectPopover,
selectVariants,
props,
part,
popup,
badValue,
badMode,
badVariant,
badItems,
badEvent,
badPlacement,
badComponent,
];
type RootSlot = Parameters<
NonNullable<InstanceType<typeof Select>["$slots"]["default"]>
>[0];
const slotState: RootSlot = {
value: 0,
isOpen: false,
selectedItems: [{ key: 0, textValue: "Zero" }],
};
const selectedKey: string | number = slotState.selectedItems[0].key;
// @ts-expect-error Root scoped slot keys must retain their actual type
const booleanKey: boolean = slotState.selectedItems[0].key;
void [selectedKey, booleanKey];
+86
View File
@@ -0,0 +1,86 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
Select,
SelectTrigger,
SelectValue,
SelectPopover,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Label,
Description,
} from "../packages/vue/src";
function select() {
return h(
Select,
{ defaultValue: [0, "0", ""], selectionMode: "multiple", name: "choices" },
() => [
h(Label, {}, () => "选择"),
h(SelectTrigger, {}, () => h(SelectValue)),
h(Description, {}, () => "帮助"),
h(SelectPopover, {}, () =>
h(ListBox, {}, () => [
h(ListBoxItem, { id: 0 }, () => [
h(Label, {}, () => "Number"),
h(Description, {}, () => "Excluded"),
h(ListBoxItemIndicator),
]),
h(ListBoxItem, { id: "0" }, () => "String"),
h(ListBoxItem, { id: "" }, () => "Empty"),
]),
),
],
);
}
describe("Select server rendering", () => {
it("renders closed metadata and repeated native selected values without browser globals", async () => {
expect(typeof window).toBe("undefined");
const html = await renderToString(
createSSRApp({ render: () => h("form", [select(), select()]) }),
);
expect(html.match(/Number, String, Empty/g)).toHaveLength(2);
expect(html.match(/data-index="\d" selected/g)).toHaveLength(6);
expect(html).not.toContain('role="listbox"');
expect(html).not.toContain("Excluded");
const ids = [...html.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]);
expect(new Set(ids).size).toBe(ids.length);
for (const match of html.matchAll(
/aria-(?:labelledby|describedby)="([^"]+)"/g,
))
for (const id of match[1].split(" ")) expect(ids).toContain(id);
});
it("uses explicit metadata for opaque options and isolates SSR request IDs", async () => {
const app = () =>
createSSRApp({
render: () =>
h(
Select,
{ defaultValue: 0, items: [{ id: 0, textValue: "Known" }] },
() => h(SelectTrigger, {}, () => h(SelectValue)),
),
});
const first = await renderToString(app());
expect(first).toContain("Known");
expect(first).toBe(await renderToString(app()));
});
it("rejects duplicate or malformed keys before mounting", async () => {
const app = (items: { id: string | number; textValue: string }[]) =>
createSSRApp({
render: () =>
h(Select, { items }, () =>
h(SelectTrigger, {}, () => h(SelectValue)),
),
});
await expect(
renderToString(
app([
{ id: "a", textValue: "A" },
{ id: "a", textValue: "B" },
]),
),
).rejects.toThrow("Duplicate collection key");
});
});
+715
View File
@@ -0,0 +1,715 @@
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");
});
it("reveals only the currently focused owned option after popup positioning starts", async () => {
const w = fixture(`<Select default-value="last">${content}</Select>`);
await trigger(w).trigger("click");
await flushPromises();
const active = option(3);
const reveal = vi.fn();
active.scrollIntoView = reveal;
const popup = document.querySelector<HTMLElement>(
'[data-slot="select-popover"]',
)!;
popup.dispatchEvent(new Event("animationstart", { bubbles: true }));
expect(reveal).toHaveBeenCalledOnce();
active.dispatchEvent(new Event("animationstart", { bubbles: true }));
expect(reveal).toHaveBeenCalledOnce();
(trigger(w).element as HTMLElement).focus();
popup.dispatchEvent(new Event("animationstart", { bubbles: true }));
expect(reveal).toHaveBeenCalledOnce();
});