merge: integrate public collection picker migration
# Conflicts: # AGENTS.md # docs/compatibility.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:
@@ -0,0 +1,210 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { nextTick, type Component } from "vue";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 6));
|
||||
const mounted: { unmount: () => void }[] = [];
|
||||
|
||||
const previews = [
|
||||
"default",
|
||||
"variants",
|
||||
"full-width",
|
||||
"with-description",
|
||||
"required",
|
||||
"disabled",
|
||||
"with-disabled-options",
|
||||
"allows-empty-collection",
|
||||
"with-sections",
|
||||
"multiple-select",
|
||||
"controlled",
|
||||
"controlled-multiple",
|
||||
"controlled-open-state",
|
||||
"asynchronous-filtering",
|
||||
"custom-indicator",
|
||||
"custom-value",
|
||||
"on-surface",
|
||||
"virtualization",
|
||||
"user-selection",
|
||||
"user-selection-multiple",
|
||||
"location-search",
|
||||
"tag-group-selection",
|
||||
"email-recipients",
|
||||
"custom-styles",
|
||||
];
|
||||
|
||||
afterEach(async () => {
|
||||
while (mounted.length) mounted.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("Autocomplete docs and demos", () => {
|
||||
it("keeps the pinned preview order and one demo per preview", () => {
|
||||
const document = readFileSync(
|
||||
"apps/docs/components/autocomplete.md",
|
||||
"utf8",
|
||||
);
|
||||
const names = [
|
||||
...document.matchAll(/<ComponentPreview name="autocomplete-([^"]+)"/g),
|
||||
].map((match) => match[1]);
|
||||
|
||||
expect(names).toEqual(previews);
|
||||
for (const name of previews) {
|
||||
const source = readFileSync(
|
||||
`apps/docs/demos/autocomplete-${name}.vue`,
|
||||
"utf8",
|
||||
);
|
||||
expect(source, name).toContain("<template>");
|
||||
expect(source, name).not.toContain("className");
|
||||
expect(source, name).not.toContain("@gravity-ui/icons");
|
||||
expect(source, name).not.toContain("<path");
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the baseline search field shell and empty state in every demo", () => {
|
||||
for (const name of previews) {
|
||||
const source = readFileSync(
|
||||
`apps/docs/demos/autocomplete-${name}.vue`,
|
||||
"utf8",
|
||||
);
|
||||
// Upstream renders SearchField autoFocus name="search" variant="secondary"
|
||||
// with a clear button; the popover filter must keep that whole shell.
|
||||
const fields = [...source.matchAll(/<SearchField\b[^>]*>/g)];
|
||||
expect(fields.length, name).toBeGreaterThan(0);
|
||||
for (const [tag] of fields) {
|
||||
expect(tag, name).toMatch(/\bvariant="secondary"/);
|
||||
expect(tag, name).toMatch(/\bname="search"/);
|
||||
expect(tag, name).toMatch(/\bauto-focus/);
|
||||
}
|
||||
expect(source, name).toContain("SearchFieldClearButton");
|
||||
// The ported .hv-empty-state padding must not be overridden per demo.
|
||||
expect(source, name).not.toMatch(/<EmptyState\s+class=/);
|
||||
expect(source, name).not.toContain("alert(");
|
||||
}
|
||||
});
|
||||
|
||||
it("documents Vue props instead of React ones", () => {
|
||||
const document = readFileSync(
|
||||
"apps/docs/components/autocomplete.md",
|
||||
"utf8",
|
||||
);
|
||||
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
|
||||
expect(document).toContain("`class`");
|
||||
expect(document).toContain("Vue class 绑定");
|
||||
for (const part of [
|
||||
"AutocompleteTrigger",
|
||||
"AutocompleteValue",
|
||||
"AutocompleteIndicator",
|
||||
"AutocompleteClearButton",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
])
|
||||
expect(document, part).toContain(`### ${part}`);
|
||||
expect(document).not.toContain("[!toc]");
|
||||
// React object-style part names must not appear as API table entries.
|
||||
expect(document).not.toMatch(/\|\s*`Autocomplete\.[A-Z]\w*`\s*\|/);
|
||||
});
|
||||
|
||||
it("mounts every demo with a named trigger", async () => {
|
||||
const modules = import.meta.glob("../apps/docs/demos/autocomplete-*.vue");
|
||||
expect(Object.keys(modules)).toHaveLength(previews.length);
|
||||
|
||||
for (const [path, load] of Object.entries(modules)) {
|
||||
const demo = (await load()) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
const triggers = (wrapper.element as HTMLElement).querySelectorAll(
|
||||
'[data-slot="autocomplete-trigger"]',
|
||||
);
|
||||
expect(triggers.length, path).toBeGreaterThan(0);
|
||||
for (const element of triggers) {
|
||||
expect(element.getAttribute("role"), path).toBe("button");
|
||||
expect(element.getAttribute("aria-expanded"), path).toBe("false");
|
||||
}
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("opens and filters inside representative demos", async () => {
|
||||
for (const name of [
|
||||
"default",
|
||||
"multiple-select",
|
||||
"with-sections",
|
||||
"custom-styles",
|
||||
"virtualization",
|
||||
]) {
|
||||
const demo = (await import(
|
||||
`../apps/docs/demos/autocomplete-${name}.vue`
|
||||
)) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const trigger = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
|
||||
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
const search = document.querySelector<HTMLInputElement>(
|
||||
'[data-slot="search-field-input"]',
|
||||
);
|
||||
expect(search, name).not.toBeNull();
|
||||
expect(trigger.getAttribute("aria-expanded"), name).toBe("true");
|
||||
const id = search!.getAttribute("aria-activedescendant");
|
||||
expect(id, name).toBeTruthy();
|
||||
expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
|
||||
"option",
|
||||
);
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("submits the required and name demos", async () => {
|
||||
const formDemo =
|
||||
(await import("../apps/docs/demos/autocomplete-required.vue")) as {
|
||||
default: Component;
|
||||
};
|
||||
const wrapper = mount(formDemo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const root = wrapper.element as HTMLElement;
|
||||
const pickerForm = (
|
||||
root.matches("form") ? root : root.querySelector("form")
|
||||
)!;
|
||||
// Empty required pickers submit no entry; the Form guard blocks the submit.
|
||||
expect(new FormData(pickerForm as HTMLFormElement).has("state")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(new FormData(pickerForm as HTMLFormElement).has("country")).toBe(
|
||||
false,
|
||||
);
|
||||
// `Form` renders novalidate and guards submit itself: an empty required
|
||||
// field must keep the demo's status line empty.
|
||||
const form = pickerForm;
|
||||
const submit = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLButtonElement>('button[type="submit"]')!;
|
||||
submit.click();
|
||||
await nextTick();
|
||||
expect(form.getAttribute("novalidate")).not.toBeNull();
|
||||
expect(
|
||||
(wrapper.element as HTMLElement)
|
||||
.querySelector('[role="status"]')
|
||||
?.textContent?.trim() ?? "",
|
||||
).toBe("");
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,900 @@
|
||||
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<string, unknown>,
|
||||
options: { states?: State[]; empty?: boolean; description?: boolean } = {},
|
||||
emits: Record<string, unknown> = {},
|
||||
) {
|
||||
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<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
|
||||
const search = () =>
|
||||
document.querySelector<HTMLInputElement>('[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<HTMLElement>('[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();
|
||||
|
||||
// The class, the `data-slot` and `data-open` must share one element, or the
|
||||
// ported `.hv-autocomplete__indicator[...]` rules never match.
|
||||
expect(
|
||||
document.querySelector(
|
||||
'.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
document.querySelector('[data-slot="autocomplete-clear-button-icon"]'),
|
||||
).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Autocomplete filter protocol", () => {
|
||||
it("inherits an accent-insensitive base matcher", async () => {
|
||||
track(
|
||||
shell(
|
||||
{},
|
||||
{ states: [{ id: "cafe", name: "Café" }] as unknown as State[] },
|
||||
),
|
||||
);
|
||||
await nextTick();
|
||||
await open();
|
||||
await type("cafe");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
await type("CAFÉ");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
await type("cafe\u0301");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
});
|
||||
|
||||
it("filters only after an open composition session ends", async () => {
|
||||
track(shell({}));
|
||||
await nextTick();
|
||||
await open();
|
||||
expect(rowTexts()).toHaveLength(3);
|
||||
|
||||
search().dispatchEvent(new CompositionEvent("compositionstart"));
|
||||
await nextTick();
|
||||
await type("Texas");
|
||||
expect(rowTexts()).toHaveLength(3);
|
||||
|
||||
search().dispatchEvent(new CompositionEvent("compositionend"));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(rowTexts()).toEqual(["Texas"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Autocomplete native layer", () => {
|
||||
it("keeps the caller's cancel on the clear button", async () => {
|
||||
const change = vi.fn();
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
Autocomplete,
|
||||
{ defaultValue: "a", onChange: change },
|
||||
{
|
||||
default: () => [
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton, {
|
||||
onClick: (event: MouseEvent) => event.preventDefault(),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
track(wrapper as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
document
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="autocomplete-clear-button"]',
|
||||
)!
|
||||
.click();
|
||||
await settle();
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("submits one entry per key and none for a disabled field", async () => {
|
||||
const multi = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h("form", null, [
|
||||
h(Autocomplete, {
|
||||
name: "choice",
|
||||
selectionMode: "multiple",
|
||||
defaultValue: ["california", "texas"],
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
track(multi as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const form = multi.element as HTMLFormElement;
|
||||
expect(new FormData(form).getAll("choice")).toEqual([
|
||||
"california",
|
||||
"texas",
|
||||
]);
|
||||
multi.unmount();
|
||||
mounted.pop();
|
||||
|
||||
const disabled = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h("form", null, [
|
||||
h(Autocomplete, {
|
||||
name: "choice",
|
||||
defaultValue: "california",
|
||||
isDisabled: true,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
track(disabled as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(
|
||||
new FormData(disabled.element as HTMLFormElement).has("choice"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("maps the source items prop onto the closed-state text", async () => {
|
||||
track(
|
||||
shell({
|
||||
items: [
|
||||
{ id: "california", textValue: "California" },
|
||||
{ id: "texas", textValue: "Texas" },
|
||||
],
|
||||
defaultValue: "texas",
|
||||
}),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(valueText()).toBe("Texas");
|
||||
});
|
||||
|
||||
it("tags a custom indicator with the baseline slot contract", async () => {
|
||||
track(
|
||||
mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Autocomplete, null, {
|
||||
default: () => [
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteIndicator, null, {
|
||||
default: () => h("i", { "data-test": "icon" }),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const custom = document.querySelector('[data-test="icon"]')!;
|
||||
expect(custom.getAttribute("data-slot")).toBe("autocomplete-indicator");
|
||||
expect(custom.classList.contains("hv-autocomplete__indicator")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,389 @@
|
||||
import Surface from "../packages/vue/src/components/surface/Surface.vue";
|
||||
import { surfaceContextKey } from "../packages/vue/src/components/surface/context";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h, ref, inject } from "vue";
|
||||
import {
|
||||
Button,
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownItem,
|
||||
Menu,
|
||||
} from "../packages/vue/src";
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => {
|
||||
cleanup
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((fn) => fn());
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
async function render(
|
||||
menuProps: Record<string, unknown>,
|
||||
children: () => unknown,
|
||||
) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, menuProps, { default: children }),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
return w;
|
||||
}
|
||||
it("section disabledKeys work when selection is inherited", async () => {
|
||||
await render({ selectionMode: "multiple" }, () =>
|
||||
h(DropdownSection, { disabledKeys: ["x"] }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="menu-item"]')
|
||||
?.getAttribute("aria-disabled"),
|
||||
).toBe("true");
|
||||
});
|
||||
it("root disabledKeys remain effective in a section with its own selection", async () => {
|
||||
await render({ disabledKeys: ["x"] }, () =>
|
||||
h(DropdownSection, { selectionMode: "multiple" }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="menu-item"]')
|
||||
?.getAttribute("aria-disabled"),
|
||||
).toBe("true");
|
||||
});
|
||||
it("single-selection closeOnSelect=false keeps the menu open", async () => {
|
||||
await render({ selectionMode: "single" }, () =>
|
||||
h(DropdownItem, { id: "x", closeOnSelect: false }, () => "X"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
it("multiple-selection closeOnSelect=true closes the menu", async () => {
|
||||
await render({ selectionMode: "multiple" }, () =>
|
||||
h(DropdownItem, { id: "x", closeOnSelect: true }, () => "X"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("typed numeric and string keys never create duplicate DOM ids", async () => {
|
||||
await render({ selectionMode: "multiple" }, () => [
|
||||
h(DropdownItem, { id: 0 }, () => "Number"),
|
||||
h(DropdownItem, { id: "0" }, () => "String"),
|
||||
]);
|
||||
const nodes = Array.from(
|
||||
document.querySelectorAll('[data-slot="menu-item"]'),
|
||||
);
|
||||
expect(new Set(nodes.map((n) => n.id)).size).toBe(nodes.length);
|
||||
});
|
||||
it("standalone Menu does not lock body scrolling or disable outside controls", async () => {
|
||||
const outside = document.createElement("button");
|
||||
document.body.append(outside);
|
||||
const w = mount(Menu, {
|
||||
slots: { default: () => h(DropdownItem, { id: "x" }, () => "X") },
|
||||
attachTo: document.body,
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(document.body.style.overflow).not.toBe("hidden");
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
expect(outside.getAttribute("aria-hidden")).not.toBe("true");
|
||||
});
|
||||
it("native link menu items retain anchor href semantics", async () => {
|
||||
await render({}, () =>
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "link", href: "/target", target: "_blank" },
|
||||
() => "Go",
|
||||
),
|
||||
);
|
||||
const item = document.querySelector('[data-slot="menu-item"]')!;
|
||||
expect(item.tagName).toBe("A");
|
||||
expect(item.getAttribute("href")).toBe("/target");
|
||||
});
|
||||
it("longPress cannot open a disabled actual trigger", async () => {
|
||||
vi.useFakeTimers();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress", modal: false }, () => [
|
||||
h(DropdownTrigger, {}, () =>
|
||||
h(Button, { isDisabled: true }, () => "Hold"),
|
||||
),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await w.get("button").trigger("pointerdown", {
|
||||
pointerType: "mouse",
|
||||
button: 0,
|
||||
isPrimary: true,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("cancelled trigger keydown does not open longPress menu", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress", modal: false }, () => [
|
||||
h(
|
||||
DropdownTrigger,
|
||||
{ onKeydown: (e: KeyboardEvent) => e.preventDefault() },
|
||||
() => h(Button, {}, () => "Hold"),
|
||||
),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await w.get("button").trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("root menu's accessible name follows its labelled DropdownMenu", async () => {
|
||||
await render({ "aria-label": "File actions" }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
);
|
||||
const menu = document.querySelector('[role="menu"]')!;
|
||||
expect(menu.getAttribute("aria-label")).toBe("File actions");
|
||||
});
|
||||
|
||||
it("submenu Menu owns its selection instead of inheriting a parent section owner", async () => {
|
||||
await render({}, () =>
|
||||
h(
|
||||
DropdownSection,
|
||||
{ selectionMode: "multiple", selectedKeys: ["outer"] },
|
||||
() =>
|
||||
h(DropdownMenu, { selectionMode: "none" }, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document.querySelector('[data-slot="menu-item"]')?.getAttribute("role"),
|
||||
).toBe("menuitem");
|
||||
});
|
||||
|
||||
it("dropdown popover resets inherited Surface context like the fixed upstream", async () => {
|
||||
const Inspector = defineComponent({
|
||||
setup() {
|
||||
const ctx = inject(surfaceContextKey, null);
|
||||
return () =>
|
||||
h("span", { "data-test": "surface" }, ctx?.variant.value ?? "none");
|
||||
},
|
||||
});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Surface, { variant: "secondary" }, () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, {}, () => h(Inspector)),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-test="surface"]')?.textContent).toBe(
|
||||
"default",
|
||||
);
|
||||
});
|
||||
|
||||
it("submenu panel preserves a caller keydown listener", async () => {
|
||||
const keydown = vi.fn();
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, { onKeydown: keydown }, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
const panel = document.querySelector("[data-submenu-content]")!;
|
||||
expect(panel).not.toBeNull();
|
||||
panel.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(keydown).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("default action activation closes its dropdown", async () => {
|
||||
await render({}, () => h(DropdownItem, { id: "default" }, () => "Action"));
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="menu"]')).toBeNull();
|
||||
});
|
||||
it.each([
|
||||
["single", false, true],
|
||||
["multiple", true, false],
|
||||
] as const)(
|
||||
"menu-level close policy for %s is honoured",
|
||||
async (selectionMode, shouldCloseOnSelect, staysOpen) => {
|
||||
await render({ selectionMode, shouldCloseOnSelect }, () =>
|
||||
h(DropdownItem, { id: "policy" }, () => "Policy"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(!!document.querySelector('[role="menu"]')).toBe(staysOpen);
|
||||
},
|
||||
);
|
||||
it("root popover preserves a user keydown callback", async () => {
|
||||
const callback = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, { onKeydown: callback }, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
document.querySelector('[role="menu"]')!.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "a",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
async function openConfiguredSubmenu(props: Record<string, unknown>) {
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, props, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-key="sub"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
return document.querySelector("[data-submenu-content]") as HTMLElement;
|
||||
}
|
||||
it("submenu preserves the panel's data and style attributes", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
"data-custom": "kept",
|
||||
style: { borderTopWidth: "7px" },
|
||||
});
|
||||
expect(panel.getAttribute("data-custom")).toBe("kept");
|
||||
expect(panel.style.borderTopWidth).toBe("7px");
|
||||
});
|
||||
it("submenu honours isKeyboardDismissDisabled", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
isKeyboardDismissDisabled: true,
|
||||
});
|
||||
const item = panel.querySelector('[data-slot="menu-item"]') as HTMLElement;
|
||||
item.focus();
|
||||
item.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Escape",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
|
||||
});
|
||||
it("standalone Menu keeps its own accessible name", async () => {
|
||||
const w = mount(Menu, {
|
||||
attrs: { "aria-label": "Standalone actions" },
|
||||
slots: { default: () => h(DropdownItem, { id: "a" }, () => "A") },
|
||||
attachTo: document.body,
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="menu"]')?.getAttribute("aria-label"),
|
||||
).toBe("Standalone actions");
|
||||
});
|
||||
|
||||
it("submenu keeps a directly supplied panel accessible name", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
"aria-label": "Direct submenu name",
|
||||
"aria-describedby": "explicit-description",
|
||||
});
|
||||
expect(panel.getAttribute("aria-label")).toBe("Direct submenu name");
|
||||
expect(panel.getAttribute("aria-describedby")).toBe("explicit-description");
|
||||
});
|
||||
it("submenu preserves a caller's openAutoFocus callback", async () => {
|
||||
const callback = vi.fn();
|
||||
await openConfiguredSubmenu({ onOpenAutoFocus: callback });
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("submenu respects the menu's shouldFocusWrap navigation", async () => {
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, { shouldFocusWrap: true }, () => [
|
||||
h(DropdownItem, { id: "first", textValue: "First" }, () => "First"),
|
||||
h(DropdownItem, { id: "last", textValue: "Last" }, () => "Last"),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-key="sub"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
const panel = document.querySelector("[data-submenu-content]")!;
|
||||
const first = panel.querySelector('[data-key="first"]') as HTMLElement;
|
||||
const last = panel.querySelector('[data-key="last"]') as HTMLElement;
|
||||
first.focus();
|
||||
await flushPromises();
|
||||
first.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "ArrowUp",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(last);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,162 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { Button, DropdownTrigger } from "../packages/vue/src";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
DropdownRoot,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from "../packages/vue/src";
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => {
|
||||
cleanup
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((fn) => fn());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
async function renderMenu(
|
||||
menuProps = {},
|
||||
itemProps = {},
|
||||
children = () => "A",
|
||||
) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, menuProps, () =>
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "a", textValue: "A", ...itemProps },
|
||||
children,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
return document.querySelector('[data-slot="menu-item"]') as HTMLElement;
|
||||
}
|
||||
it("selected multiple item exposes checked menu semantics and source CSS selected state", async () => {
|
||||
const node = await renderMenu(
|
||||
{ selectionMode: "multiple", selectedKeys: ["a"] },
|
||||
{},
|
||||
() => [h(DropdownItemIndicator, { type: "dot" }), "A"] as never,
|
||||
);
|
||||
expect(node.getAttribute("role")).toBe("menuitemcheckbox");
|
||||
expect(node.getAttribute("aria-checked")).toBe("true");
|
||||
});
|
||||
it("preventing click prevents action and default close", async () => {
|
||||
const action = vi.fn();
|
||||
const node = await renderMenu(
|
||||
{ onAction: action },
|
||||
{ onClick: (e: MouseEvent) => e.preventDefault() },
|
||||
);
|
||||
node.click();
|
||||
await flushPromises();
|
||||
expect(action).not.toHaveBeenCalled();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
it("submenu trigger has one menuitem DOM node rather than nested interactive items", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub", textValue: "Sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "child" }, () => "Child"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="menuitem"] [role="menuitem"]'),
|
||||
).toBeNull();
|
||||
});
|
||||
it("standalone exported Menu and MenuItem do not require an internal DropdownMenuRoot", () => {
|
||||
expect(() => {
|
||||
const w = mount(Menu, {
|
||||
slots: { default: () => h(MenuItem, { id: "a" }, () => "A") },
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("stopImmediatePropagation stops subsequent user handlers and activation", async () => {
|
||||
const action = vi.fn();
|
||||
const second = vi.fn();
|
||||
const node = await renderMenu(
|
||||
{ onAction: action },
|
||||
{
|
||||
onClick: [(e: MouseEvent) => e.stopImmediatePropagation(), second],
|
||||
},
|
||||
);
|
||||
node.click();
|
||||
await flushPromises();
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
expect(action).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("longPress trigger does not open on a short click of the actual button", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress" }, () => [
|
||||
h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
(w.get("button").element as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("longPress keyboard Enter opens instead of toggling twice", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress" }, () => [
|
||||
h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
await w.get("button").trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent } from "vue";
|
||||
import {
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
Input,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
Autocomplete,
|
||||
AutocompleteTrigger,
|
||||
AutocompletePopover,
|
||||
AutocompleteFilter,
|
||||
SearchField,
|
||||
SearchFieldInput,
|
||||
} from "../packages/vue/src";
|
||||
import { createBaseContains } from "../packages/vue/src/components/collection/match";
|
||||
const components = {
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
Input,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
Autocomplete,
|
||||
AutocompleteTrigger,
|
||||
AutocompletePopover,
|
||||
AutocompleteFilter,
|
||||
SearchField,
|
||||
SearchFieldInput,
|
||||
};
|
||||
const roots: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
roots.splice(0).forEach((w) => w.unmount());
|
||||
document.body.innerHTML = "";
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
function view(template: string) {
|
||||
const w = mount(defineComponent({ components, template }), {
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
return w;
|
||||
}
|
||||
describe("public picker integration", () => {
|
||||
it("retains Vue string template refs on the actual composed Input and clears them on removal", async () => {
|
||||
const w = view(
|
||||
'<ComboBox><ComboBoxInputGroup><Input ref="consumerInput"/><ComboBoxTrigger/></ComboBoxInputGroup><ComboBoxPopover><ListBox><ListBoxItem id="a">Alpha</ListBoxItem></ListBox></ComboBoxPopover></ComboBox>',
|
||||
);
|
||||
await flushPromises();
|
||||
expect((w.vm.$refs.consumerInput as { $el: Element }).$el).toBe(
|
||||
w.get("input[role=combobox]").element,
|
||||
);
|
||||
w.unmount();
|
||||
roots.splice(roots.indexOf(w), 1);
|
||||
expect(w.vm.$refs.consumerInput).toBeNull();
|
||||
});
|
||||
it("retains a string template ref on the teleported search input", async () => {
|
||||
const w = view(
|
||||
'<Autocomplete default-open><AutocompleteTrigger>Choose</AutocompleteTrigger><AutocompletePopover><AutocompleteFilter><SearchField><SearchFieldInput ref="consumerSearch"/></SearchField><ListBox><ListBoxItem id="a">Alpha</ListBoxItem></ListBox></AutocompleteFilter></AutocompletePopover></Autocomplete>',
|
||||
);
|
||||
await flushPromises();
|
||||
expect((w.vm.$refs.consumerSearch as { $el: Element }).$el).toBe(
|
||||
document.querySelector("input[role=combobox]"),
|
||||
);
|
||||
});
|
||||
it("respects a caller-disabled Autocomplete trigger before opening", async () => {
|
||||
const w = view(
|
||||
'<Autocomplete><AutocompleteTrigger disabled>Choose</AutocompleteTrigger><AutocompletePopover><ListBox><ListBoxItem id="a">Alpha</ListBoxItem></ListBox></AutocompletePopover></Autocomplete>',
|
||||
);
|
||||
await w.get('[data-slot="autocomplete-trigger"]').trigger("click");
|
||||
expect(
|
||||
w.get('[data-slot="autocomplete-trigger"]').attributes("aria-expanded"),
|
||||
).toBe("false");
|
||||
expect(
|
||||
w.get('[data-slot="autocomplete-trigger"]').attributes("aria-disabled"),
|
||||
).toBe("true");
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
["tr", "İstanbul", "istanbul", true],
|
||||
["tr", "Isparta", "ısparta", true],
|
||||
["tr", "Isparta", "isparta", false],
|
||||
["de", "Fußgänger", "fuss", true],
|
||||
["en", "Café", "cafe\u0301", true],
|
||||
])("locale filter %s: %s / %s", (locale, text, query, expected) => {
|
||||
expect(createBaseContains(locale)(text, query)).toBe(expected);
|
||||
});
|
||||
@@ -0,0 +1,448 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref, type Ref } from "vue";
|
||||
import {
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
Autocomplete,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteFilter,
|
||||
Input,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldClearButton,
|
||||
} from "../packages/vue/src";
|
||||
const roots: { unmount(): void }[] = [];
|
||||
const tick = async () => {
|
||||
await nextTick();
|
||||
await new Promise((r) => setTimeout(r, 6));
|
||||
};
|
||||
afterEach(async () => {
|
||||
while (roots.length) roots.pop()!.unmount();
|
||||
await tick();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
type Item = { id: string | number; textValue: string };
|
||||
const defaults: Item[] = [
|
||||
{ id: 0, textValue: "Numeric Zero" },
|
||||
{ id: "0", textValue: "String Zero" },
|
||||
{ id: "a", textValue: "Alpha" },
|
||||
{ id: "b", textValue: "Beta" },
|
||||
];
|
||||
function picker(
|
||||
kind: "combo" | "auto",
|
||||
props: () => Record<string, unknown> = () => ({}),
|
||||
opts: {
|
||||
items?: Ref<Item[]>;
|
||||
inputProps?: Record<string, unknown>;
|
||||
filterProps?: Record<string, unknown>;
|
||||
} = {},
|
||||
) {
|
||||
const items = opts.items ?? ref(defaults);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h("form", null, [
|
||||
h(
|
||||
kind === "combo" ? ComboBox : Autocomplete,
|
||||
{ "aria-label": "Picker", ...props() },
|
||||
{
|
||||
default: () => [
|
||||
kind === "combo"
|
||||
? h(ComboBoxInputGroup, null, {
|
||||
default: () => [
|
||||
h(Input, opts.inputProps),
|
||||
h(ComboBoxTrigger),
|
||||
],
|
||||
})
|
||||
: h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton),
|
||||
h(AutocompleteIndicator),
|
||||
],
|
||||
}),
|
||||
h(
|
||||
kind === "combo" ? ComboBoxPopover : AutocompletePopover,
|
||||
null,
|
||||
{
|
||||
default: () => {
|
||||
const list = h(ListBox, null, {
|
||||
default: () =>
|
||||
items.value.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
});
|
||||
return kind === "combo"
|
||||
? list
|
||||
: h(AutocompleteFilter, opts.filterProps, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "Search" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [
|
||||
h(SearchFieldInput, opts.inputProps),
|
||||
h(SearchFieldClearButton),
|
||||
],
|
||||
}),
|
||||
},
|
||||
),
|
||||
list,
|
||||
],
|
||||
});
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
roots.push(w);
|
||||
return w;
|
||||
}
|
||||
const comboInput = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="input"]')!;
|
||||
const searchInput = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="search-field-input"]')!;
|
||||
async function open(kind: "combo" | "auto") {
|
||||
if (kind === "combo") comboInput().focus();
|
||||
else
|
||||
document
|
||||
.querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!
|
||||
.click();
|
||||
await tick();
|
||||
}
|
||||
async function type(el: HTMLInputElement, text: string) {
|
||||
el.value = text;
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await tick();
|
||||
}
|
||||
|
||||
it("native cancelable clear click actually clears Autocomplete", async () => {
|
||||
const change = vi.fn();
|
||||
picker("auto", () => ({ defaultValue: "a", onChange: change }));
|
||||
await tick();
|
||||
document
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="autocomplete-clear-button"]',
|
||||
)!
|
||||
.click();
|
||||
await tick();
|
||||
expect(change).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s disabled fields do not submit a value",
|
||||
async (kind) => {
|
||||
const w = picker(kind, () => ({
|
||||
name: "choice",
|
||||
defaultValue: "a",
|
||||
isDisabled: true,
|
||||
}));
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).has("choice")).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s multiple values use same-name entries",
|
||||
async (kind) => {
|
||||
const w = picker(kind, () => ({
|
||||
name: "choice",
|
||||
selectionMode: "multiple",
|
||||
defaultValue: ["a", "b"],
|
||||
}));
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).getAll("choice")).toEqual(
|
||||
["a", "b"],
|
||||
);
|
||||
},
|
||||
);
|
||||
it("ComboBox external clear clears displayed text", async () => {
|
||||
const selected = ref<string | null>("a");
|
||||
picker("combo", () => ({ modelValue: selected.value }));
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("Alpha");
|
||||
selected.value = null;
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it("ComboBox keeps numeric and string keys distinct in external text synchronization", async () => {
|
||||
const selected = ref<string | number>(0);
|
||||
picker("combo", () => ({ modelValue: selected.value }));
|
||||
await tick();
|
||||
selected.value = "0";
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("String Zero");
|
||||
});
|
||||
it("ComboBox accepts selected label updates without an item-count change", async () => {
|
||||
const items = ref<Item[]>([{ id: "a", textValue: "Old" }]);
|
||||
picker("combo", () => ({ modelValue: "a" }), { items });
|
||||
await tick();
|
||||
items.value = [{ id: "a", textValue: "New" }];
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("New");
|
||||
});
|
||||
it("ComboBox respects a controlled empty inputValue", async () => {
|
||||
picker("combo", () => ({ modelValue: "a", inputValue: "" }));
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it("ComboBox allows clearing a required selection before validation", async () => {
|
||||
const update = vi.fn();
|
||||
picker("combo", () => ({
|
||||
defaultValue: "a",
|
||||
isRequired: true,
|
||||
"onUpdate:modelValue": update,
|
||||
}));
|
||||
await tick();
|
||||
await type(comboInput(), "");
|
||||
expect(update).toHaveBeenLastCalledWith(null);
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s asChild uses the supplied root",
|
||||
async (kind) => {
|
||||
// The ordinary component tree is the one custom wrapper supplied to the root.
|
||||
const Root = kind === "combo" ? ComboBox : Autocomplete;
|
||||
const w = mount(Root, {
|
||||
props: { asChild: true },
|
||||
slots: {
|
||||
default: () => h("section", { "data-custom": "root" }, "Custom"),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(w.element.tagName).toBe("SECTION");
|
||||
},
|
||||
);
|
||||
it("ComboBox autoFocus focuses its composed input", async () => {
|
||||
picker("combo", () => ({ autoFocus: true }));
|
||||
await tick();
|
||||
expect(document.activeElement).toBe(comboInput());
|
||||
});
|
||||
it("ComboBox secondary variant reaches its input", async () => {
|
||||
picker("combo", () => ({ variant: "secondary" }));
|
||||
await tick();
|
||||
expect(comboInput().classList.contains("hv-input--secondary")).toBe(true);
|
||||
});
|
||||
it("ComboBox preserves caller input component ref", async () => {
|
||||
const inputRef = ref();
|
||||
picker("combo", () => ({}), { inputProps: { ref: inputRef } });
|
||||
await tick();
|
||||
expect(inputRef.value).toBeTruthy();
|
||||
});
|
||||
it("Autocomplete preserves caller search-input component ref", async () => {
|
||||
const inputRef = ref();
|
||||
picker("auto", () => ({}), { inputProps: { ref: inputRef } });
|
||||
await tick();
|
||||
await open("auto");
|
||||
expect(inputRef.value).toBeTruthy();
|
||||
});
|
||||
it("Autocomplete search clear resets its filter", async () => {
|
||||
picker("auto");
|
||||
await tick();
|
||||
await open("auto");
|
||||
await type(searchInput(), "Beta");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(1);
|
||||
document
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="search-field-clear-button"]',
|
||||
)!
|
||||
.click();
|
||||
await tick();
|
||||
expect(searchInput().value).toBe("");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(4);
|
||||
});
|
||||
it("ComboBox respects an active composition session even on an unflagged Enter", async () => {
|
||||
const change = vi.fn();
|
||||
picker("combo", () => ({ onChange: change }));
|
||||
await tick();
|
||||
await open("combo");
|
||||
comboInput().dispatchEvent(
|
||||
new CompositionEvent("compositionstart", { bubbles: true }),
|
||||
);
|
||||
comboInput().dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await tick();
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s does not filter during a composition session",
|
||||
async (kind) => {
|
||||
picker(kind);
|
||||
await tick();
|
||||
await open(kind);
|
||||
const input = kind === "combo" ? comboInput() : searchInput();
|
||||
input.dispatchEvent(
|
||||
new CompositionEvent("compositionstart", { bubbles: true }),
|
||||
);
|
||||
input.value = "qqq";
|
||||
input.dispatchEvent(
|
||||
new InputEvent("input", { bubbles: true, isComposing: true }),
|
||||
);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(4);
|
||||
},
|
||||
);
|
||||
it("Autocomplete keeps filter focus when parent rejects closing", async () => {
|
||||
picker("auto", () => ({ open: true }));
|
||||
await tick();
|
||||
const input = searchInput();
|
||||
input.focus();
|
||||
await type(input, "Beta");
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await tick();
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="autocomplete-trigger"]')!
|
||||
.getAttribute("aria-expanded"),
|
||||
).toBe("true");
|
||||
expect(document.activeElement).toBe(input);
|
||||
});
|
||||
it("Autocomplete preserves an explicit search input accessible name", async () => {
|
||||
picker("auto", () => ({}), {
|
||||
inputProps: { "aria-label": "Specific search" },
|
||||
});
|
||||
await tick();
|
||||
await open("auto");
|
||||
expect(searchInput().getAttribute("aria-label")).toBe("Specific search");
|
||||
});
|
||||
it("ComboBox input participates in its explicitly associated form", async () => {
|
||||
const external = document.createElement("form");
|
||||
external.id = "external-form";
|
||||
document.body.appendChild(external);
|
||||
picker("combo", () => ({ form: "external-form", name: "choice" }));
|
||||
await tick();
|
||||
expect(comboInput().form).toBe(external);
|
||||
});
|
||||
it("Autocomplete clear button retains a caller disabled attribute", async () => {
|
||||
const w = mount(Autocomplete, {
|
||||
props: { defaultValue: "a" },
|
||||
slots: {
|
||||
default: () =>
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton, { disabled: true }),
|
||||
],
|
||||
}),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="autocomplete-clear-button"]',
|
||||
)!.disabled,
|
||||
).toBe(true);
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s does not submit a removed selection as a valid option",
|
||||
async (kind) => {
|
||||
const items = ref<Item[]>([...defaults]);
|
||||
const w = picker(kind, () => ({ defaultValue: "a", name: "choice" }), {
|
||||
items,
|
||||
});
|
||||
await tick();
|
||||
items.value = items.value.filter((i) => i.id !== "a");
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).get("choice")).not.toBe(
|
||||
"a",
|
||||
);
|
||||
},
|
||||
);
|
||||
it("Autocomplete default base-sensitivity filter matches accents", async () => {
|
||||
picker("auto", () => ({}), {
|
||||
items: ref([{ id: "cafe", textValue: "Café" }]),
|
||||
});
|
||||
await tick();
|
||||
await open("auto");
|
||||
await type(searchInput(), "cafe");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(1);
|
||||
});
|
||||
it("Autocomplete default indicator matches its size selector", async () => {
|
||||
picker("auto");
|
||||
await tick();
|
||||
// The shipped rule requires class and data-slot on the same element.
|
||||
expect(
|
||||
document.querySelector(
|
||||
'.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("ComboBox custom text is the submitted text after editing a selected item", async () => {
|
||||
const w = picker("combo", () => ({
|
||||
defaultValue: "a",
|
||||
allowsCustomValue: true,
|
||||
name: "choice",
|
||||
}));
|
||||
await tick();
|
||||
await type(comboInput(), "Custom animal");
|
||||
expect(new FormData(w.element as HTMLFormElement).get("choice")).toBe(
|
||||
"Custom animal",
|
||||
);
|
||||
});
|
||||
it("ComboBox trigger retains a caller disabled attribute", async () => {
|
||||
const w = mount(ComboBox, {
|
||||
slots: {
|
||||
default: () =>
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input), h(ComboBoxTrigger, { disabled: true })],
|
||||
}),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="combo-box-trigger"]',
|
||||
)!.disabled,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
|
||||
import { ListBox, ListBoxItem } from "../packages/vue/src";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionOwner,
|
||||
type OwnedCollection,
|
||||
} from "../packages/vue/src/components/collection/owner";
|
||||
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
|
||||
const mounted: { unmount(): void }[] = [];
|
||||
afterEach(() => {
|
||||
while (mounted.length) mounted.pop()!.unmount();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await new Promise((r) => setTimeout(r, 3));
|
||||
};
|
||||
function setupList(virtualized = false) {
|
||||
let collection: OwnedCollection | undefined;
|
||||
const items = Array.from({ length: 6 }, (_, id) => ({
|
||||
id,
|
||||
textValue: `Row ${id}`,
|
||||
}));
|
||||
const activeKey = ref<string | number>();
|
||||
const owner: CollectionOwner = {
|
||||
keys: computed(() => []),
|
||||
mode: computed(() => "single"),
|
||||
disabled: computed(() => false),
|
||||
readOnly: computed(() => false),
|
||||
disabledKeys: computed(() => []),
|
||||
id: "probe",
|
||||
labelledBy: () => undefined,
|
||||
ariaLabel: () => "Probe",
|
||||
request: () => {},
|
||||
action: () => {},
|
||||
leave: () => {},
|
||||
connect: (c) => {
|
||||
collection = c;
|
||||
return () => {
|
||||
collection = undefined;
|
||||
};
|
||||
},
|
||||
filter: (r) => r.key === 3,
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
};
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
provide(collectionOwnerKey, owner);
|
||||
return () =>
|
||||
h(
|
||||
ListBox,
|
||||
{ items, virtualized, rowHeight: 40, overscan: 8 },
|
||||
{
|
||||
default: ({ item }: { item: (typeof items)[number] }) =>
|
||||
h(ListBoxItem, { id: item.id }, () => item.textValue),
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
return { wrapper, collection: () => collection };
|
||||
}
|
||||
it("preserves caller hidden on an ordinary ListBoxItem", async () => {
|
||||
const w = mount(ListBox, {
|
||||
slots: {
|
||||
default: () =>
|
||||
h(ListBoxItem, { id: "hidden", hidden: true }, () => "Hidden"),
|
||||
},
|
||||
});
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
expect(w.find('[role="option"]').attributes("hidden")).toBeDefined();
|
||||
});
|
||||
it("reveal scrolls a mounted ordinary row without moving DOM focus", async () => {
|
||||
const { wrapper, collection } = setupList();
|
||||
await settle();
|
||||
const node = wrapper.findAll('[role="option"]')[3].element;
|
||||
const scroll = vi.fn();
|
||||
Object.defineProperty(node, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: scroll,
|
||||
});
|
||||
await collection()!.reveal!(3);
|
||||
expect(scroll).toHaveBeenCalled();
|
||||
});
|
||||
it("virtual window contains no fixed height slots for filtered-out rows", async () => {
|
||||
const { wrapper } = setupList(true);
|
||||
await settle();
|
||||
expect(
|
||||
wrapper.findAll(
|
||||
'[data-slot="list-box-virtual-content"] > [role="presentation"]',
|
||||
),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
it("restores keyboard highlight intent after a pointer interaction", async () => {
|
||||
const w = mount(Harness, { attachTo: document.body });
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
const input = w.find("input");
|
||||
await input.setValue("");
|
||||
await settle();
|
||||
await w.findAll('[role="option"]')[0].trigger("pointerdown");
|
||||
await input.trigger("keydown", { key: "ArrowDown" });
|
||||
await settle();
|
||||
expect(w.find('[data-focused="true"]').attributes("data-focus-visible")).toBe(
|
||||
"true",
|
||||
);
|
||||
});
|
||||
it("has instance-unique names and controls in the verification harness", async () => {
|
||||
const w = mount(
|
||||
defineComponent({ setup: () => () => h("div", [h(Harness), h(Harness)]) }),
|
||||
);
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
const ids = w.findAll("[id]").map((n) => n.attributes("id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { afterEach, it, expect, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
|
||||
import { ListBox, ListBoxItem } from "../packages/vue/src";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionOwner,
|
||||
type OwnedCollection,
|
||||
} from "../packages/vue/src/components/collection/owner";
|
||||
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
|
||||
const roots: { unmount(): void }[] = [];
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await new Promise((r) => setTimeout(r, 3));
|
||||
};
|
||||
afterEach(() => {
|
||||
while (roots.length) roots.pop()!.unmount();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
it("does not scroll a reveal request after filtering invalidates it", async () => {
|
||||
let collection: OwnedCollection | undefined;
|
||||
const visible = ref(true);
|
||||
const activeKey = ref<string | number>();
|
||||
const owner: CollectionOwner = {
|
||||
keys: computed(() => []),
|
||||
mode: computed(() => "single"),
|
||||
disabled: computed(() => false),
|
||||
readOnly: computed(() => false),
|
||||
disabledKeys: computed(() => []),
|
||||
id: "pending-reveal",
|
||||
labelledBy: () => undefined,
|
||||
ariaLabel: () => undefined,
|
||||
request: () => {},
|
||||
action: () => {},
|
||||
leave: () => {},
|
||||
connect: (c) => {
|
||||
collection = c;
|
||||
return () => {};
|
||||
},
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
filter: () => visible.value,
|
||||
};
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
provide(collectionOwnerKey, owner);
|
||||
return () =>
|
||||
h(ListBox, null, () => h(ListBoxItem, { id: "a" }, () => "A"));
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
roots.push(w);
|
||||
await settle();
|
||||
const spy = vi.fn();
|
||||
Object.defineProperty(w.find('[role="option"]').element, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: spy,
|
||||
});
|
||||
const pending = collection!.reveal!("a");
|
||||
visible.value = false;
|
||||
await pending;
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not select the parent option when a nested button is clicked", async () => {
|
||||
const w = mount(Harness, { attachTo: document.body });
|
||||
roots.push(w);
|
||||
await settle();
|
||||
await w.find("input").setValue("");
|
||||
await settle();
|
||||
const row = w.find('[role="option"]').element;
|
||||
const button = document.createElement("button");
|
||||
row.appendChild(button);
|
||||
button.click();
|
||||
await settle();
|
||||
expect(w.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
it("shows pointer pressed state while preserving input focus", async () => {
|
||||
const w = mount(Harness, { attachTo: document.body });
|
||||
roots.push(w);
|
||||
await settle();
|
||||
await w.find("input").setValue("");
|
||||
await settle();
|
||||
const row = w.find('[role="option"]');
|
||||
await row.trigger("pointerdown", { button: 0 });
|
||||
await settle();
|
||||
expect(row.attributes("data-pressed")).toBe("true");
|
||||
});
|
||||
it.each(["removed", "disabled"])(
|
||||
"does not confirm a dynamically %s active option",
|
||||
async (mode) => {
|
||||
const w = mount(Harness, {
|
||||
props: {
|
||||
options: [
|
||||
{ id: "a", text: "A" },
|
||||
{ id: "b", text: "B" },
|
||||
],
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await settle();
|
||||
await w.find("input").setValue("");
|
||||
await settle();
|
||||
expect(w.vm.activeKey).toBe("a");
|
||||
await w.setProps({
|
||||
options:
|
||||
mode === "removed"
|
||||
? [{ id: "b", text: "B" }]
|
||||
: [
|
||||
{ id: "a", text: "A", disabled: true },
|
||||
{ id: "b", text: "B" },
|
||||
],
|
||||
});
|
||||
await settle();
|
||||
await w.find("input").trigger("keydown", { key: "Enter" });
|
||||
await settle();
|
||||
expect(
|
||||
w.emitted("proposal")?.some((args) => args[0] === "a") ?? false,
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
it("provides filtered-empty feedback for the static slot collection", async () => {
|
||||
const w = mount(Harness, { attachTo: document.body });
|
||||
roots.push(w);
|
||||
await settle();
|
||||
await w.find("input").setValue("no-match");
|
||||
await settle();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
});
|
||||
it("can filter a record outside the initially mounted virtual window", async () => {
|
||||
const options = Array.from({ length: 100 }, (_, i) => ({
|
||||
id: i,
|
||||
text: `Row ${i}`,
|
||||
}));
|
||||
const w = mount(Harness, {
|
||||
props: { virtualized: true, options },
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await settle();
|
||||
await w.find("input").setValue("Row 99");
|
||||
await settle();
|
||||
expect(
|
||||
w.findAll('[role="option"]').some((row) => row.text().trim() === "Row 99"),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,754 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import { ListBox, ListBoxItem } from "../packages/vue/src";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionOwner,
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../packages/vue/src/components/collection/owner";
|
||||
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
|
||||
|
||||
const wrappers: { unmount: () => void; element: Element }[] = [];
|
||||
|
||||
// jsdom gaps used by the virtualized reveal path; fill only when missing.
|
||||
if (typeof Element.prototype.scrollTo !== "function")
|
||||
Element.prototype.scrollTo = () => {};
|
||||
|
||||
function pointerEvent(type: string) {
|
||||
return new MouseEvent(type, { bubbles: true, cancelable: true });
|
||||
}
|
||||
|
||||
/** Vue skips an invoker when `e._vts <= invoker.attached`; cross the millisecond. */
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 2));
|
||||
|
||||
function root(): HTMLElement {
|
||||
return (wrappers.at(-1)?.element as HTMLElement | undefined) ?? document.body;
|
||||
}
|
||||
const queryAll = <T extends Element = HTMLElement>(selector: string) => {
|
||||
const element = root();
|
||||
const found = [...element.querySelectorAll<T>(selector)];
|
||||
if (element.matches(selector)) found.unshift(element as unknown as T);
|
||||
return found;
|
||||
};
|
||||
const queryOne = <T extends Element = HTMLElement>(selector: string) =>
|
||||
queryAll<T>(selector)[0] ?? null;
|
||||
const rowTexts = () =>
|
||||
queryAll('[data-slot="list-box-item"]')
|
||||
.filter((row) => !row.hasAttribute("data-filtered"))
|
||||
.map((row) => row.textContent?.trim());
|
||||
|
||||
async function mountHarness(props: Record<string, unknown> = {}) {
|
||||
const wrapper = mount(Harness, { props, attachTo: document.body });
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
const inputEl = () =>
|
||||
queryOne<HTMLInputElement>('[data-test="harness-input"]')!;
|
||||
|
||||
async function type(value: string) {
|
||||
const element = inputEl();
|
||||
element.value = value;
|
||||
element.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function press(key: string, init: KeyboardEventInit = {}) {
|
||||
inputEl().dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...init,
|
||||
}),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (wrappers.length) wrappers.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("collection filter", () => {
|
||||
it("hides non-matching rows but keeps their text and mount state", async () => {
|
||||
await mountHarness();
|
||||
expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
|
||||
|
||||
await type("狗");
|
||||
|
||||
expect(rowTexts()).toEqual(["狗"]);
|
||||
const filtered = queryAll('[data-slot="list-box-item"]').filter((row) =>
|
||||
row.hasAttribute("data-filtered"),
|
||||
);
|
||||
expect(filtered).toHaveLength(4);
|
||||
// Filtered rows stay mounted so their text and selection survive.
|
||||
expect(filtered.map((row) => row.textContent?.trim())).toEqual([
|
||||
"猫",
|
||||
"鸟",
|
||||
"鱼",
|
||||
"仓鼠",
|
||||
]);
|
||||
// Hidden for assistive tech and without the stylesheet; the library CSS
|
||||
// additionally forces display:none (verified in the browser pass).
|
||||
expect(filtered[0].hasAttribute("hidden")).toBe(true);
|
||||
expect(filtered[0].getAttribute("data-filtered")).toBe("true");
|
||||
expect(getComputedStyle(filtered[0]).display).toBe("none");
|
||||
expect(queryOne('[data-test="hidden-count"]')!.textContent).toContain("4");
|
||||
});
|
||||
|
||||
it("keeps an accepted value when its row is filtered out", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
|
||||
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
|
||||
|
||||
await type("狗");
|
||||
|
||||
expect(rowTexts()).toEqual(["狗"]);
|
||||
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
|
||||
expect(
|
||||
queryAll('[aria-selected="true"]').map((row) => row.textContent?.trim()),
|
||||
).toEqual(["猫"]);
|
||||
});
|
||||
|
||||
it("navigates only the visible rows and skips disabled ones", async () => {
|
||||
const wrapper = await mountHarness({
|
||||
options: [
|
||||
{ id: "cat", text: "猫" },
|
||||
{ id: "dog", text: "狗", disabled: true },
|
||||
{ id: "bird", text: "鸟" },
|
||||
{ id: "fish", text: "鱼" },
|
||||
],
|
||||
});
|
||||
await type("鸟");
|
||||
await press("ArrowDown");
|
||||
expect(wrapper.vm.activeKey).toBe("bird");
|
||||
|
||||
// "狗" is disabled and "猫"/"鱼" are filtered out: the only row is 鸟.
|
||||
await press("ArrowDown");
|
||||
expect(wrapper.vm.activeKey).toBe("bird");
|
||||
expect(rowTexts()).toEqual(["鸟"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("virtual focus", () => {
|
||||
it("keeps DOM focus in the input and points activedescendant at the mounted row", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
expect(document.activeElement).toBe(inputEl());
|
||||
|
||||
await press("ArrowDown");
|
||||
await press("ArrowDown");
|
||||
|
||||
expect(document.activeElement).toBe(inputEl());
|
||||
expect(wrapper.vm.activeKey).toBe("dog");
|
||||
const id = inputEl().getAttribute("aria-activedescendant");
|
||||
expect(id).toBeTruthy();
|
||||
const option = document.getElementById(id!);
|
||||
expect(option).not.toBeNull();
|
||||
expect(option!.getAttribute("data-slot")).toBe("list-box-item");
|
||||
expect(option!.textContent?.trim()).toBe("狗");
|
||||
expect(option!.getAttribute("data-focused")).toBe("true");
|
||||
// The highlighted row is not a tab stop.
|
||||
expect(option!.getAttribute("tabindex")).toBe("-1");
|
||||
expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
|
||||
"-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("updates activedescendant after filtering changes the visible set", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("鼠");
|
||||
expect(wrapper.vm.activeKey).toBe("hamster");
|
||||
const id = inputEl().getAttribute("aria-activedescendant");
|
||||
expect(document.getElementById(id!)?.textContent?.trim()).toBe("仓鼠");
|
||||
|
||||
await type("不存在");
|
||||
expect(wrapper.vm.activeKey).toBeUndefined();
|
||||
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
|
||||
expect(rowTexts()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not move focus when a row is clicked", async () => {
|
||||
await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("狗");
|
||||
const row = queryAll('[data-slot="list-box-item"]').find(
|
||||
(item) => !item.hasAttribute("data-filtered"),
|
||||
)!;
|
||||
row.dispatchEvent(pointerEvent("pointerdown"));
|
||||
row.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
row.dispatchEvent(pointerEvent("pointerup"));
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
expect(document.activeElement).toBe(inputEl());
|
||||
});
|
||||
});
|
||||
|
||||
describe("controlled rejection", () => {
|
||||
it("keeps the accepted value when the parent rejects the proposal", async () => {
|
||||
const wrapper = await mountHarness({ acceptSelection: false });
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
|
||||
expect(wrapper.emitted("proposal")).toEqual([["cat"], ["dog"]]);
|
||||
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
|
||||
expect(wrapper.vm.accepted).toBeNull();
|
||||
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("无");
|
||||
expect(queryAll('[aria-selected="true"]')).toHaveLength(0);
|
||||
|
||||
// A rejected proposal can be repeated once the parent accepts.
|
||||
await wrapper.setProps({ acceptSelection: true });
|
||||
await settle();
|
||||
await press("Enter");
|
||||
expect(wrapper.vm.accepted).toBe("dog");
|
||||
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["dog"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("IME composition", () => {
|
||||
it("does not confirm or filter while composing", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await press("ArrowDown");
|
||||
expect(wrapper.vm.activeKey).toBe("cat");
|
||||
|
||||
inputEl().dispatchEvent(new CompositionEvent("compositionstart"));
|
||||
inputEl().value = "gou";
|
||||
inputEl().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
// Composition text does not filter yet.
|
||||
expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
|
||||
|
||||
await press("Enter", { isComposing: true });
|
||||
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
|
||||
|
||||
inputEl().dispatchEvent(new CompositionEvent("compositionend"));
|
||||
await nextTick();
|
||||
await settle();
|
||||
// The committed text now filters, and no row was selected on the way.
|
||||
expect(rowTexts()).toEqual([]);
|
||||
expect(wrapper.vm.accepted).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("reveal without DOM focus", () => {
|
||||
it("exposes the mounted option id and leaves DOM focus alone", async () => {
|
||||
const activeKey = ref<string | number>();
|
||||
let collection: OwnedCollection | undefined;
|
||||
const owner = {
|
||||
keys: ref([]),
|
||||
mode: ref("single"),
|
||||
disabled: ref(false),
|
||||
readOnly: ref(false),
|
||||
disabledKeys: ref([]),
|
||||
id: "reveal-list",
|
||||
labelledBy: () => undefined,
|
||||
ariaLabel: () => undefined,
|
||||
request: () => {},
|
||||
action: () => {},
|
||||
leave: () => {},
|
||||
connect: (next: OwnedCollection) => {
|
||||
collection = next;
|
||||
return () => {
|
||||
collection = undefined;
|
||||
};
|
||||
},
|
||||
filter: (record: CollectionRecord) => !record.text.includes("隐藏"),
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
} as unknown as CollectionOwner;
|
||||
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(ListBox, { "aria-label": "行" }, () => [
|
||||
h(ListBoxItem, { id: "a" }, () => "第一行"),
|
||||
h(ListBoxItem, { id: "b" }, () => "隐藏行"),
|
||||
h(ListBoxItem, { id: "c" }, () => "第三行"),
|
||||
]);
|
||||
},
|
||||
}),
|
||||
{
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
provide: { [collectionOwnerKey as unknown as string]: owner },
|
||||
},
|
||||
},
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
const outside = document.createElement("button");
|
||||
document.body.appendChild(outside);
|
||||
outside.focus();
|
||||
expect(document.activeElement).toBe(outside);
|
||||
|
||||
await collection?.reveal?.("c");
|
||||
await nextTick();
|
||||
|
||||
expect(document.activeElement).toBe(outside);
|
||||
const id = collection?.optionId?.("c");
|
||||
expect(id).toBeTruthy();
|
||||
expect(document.getElementById(id!)?.textContent?.trim()).toBe("第三行");
|
||||
expect(collection?.items().map((item) => item.key)).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("standalone ListBox unchanged", () => {
|
||||
it("still moves DOM focus into the list and keeps one tab stop", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", [
|
||||
h(ListBox, { "aria-label": "动物" }, () => [
|
||||
h(ListBoxItem, { id: "cat" }, () => "猫"),
|
||||
h(ListBoxItem, { id: "dog" }, () => "狗"),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
const rows = queryAll('[data-slot="list-box-item"]');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.map((row) => row.getAttribute("tabindex"))).toEqual([
|
||||
"0",
|
||||
"-1",
|
||||
]);
|
||||
expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
|
||||
"-1",
|
||||
);
|
||||
// No owner filter is provided, so nothing is hidden.
|
||||
expect(rows.some((row) => row.hasAttribute("data-filtered"))).toBe(false);
|
||||
|
||||
rows[0].dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(document.activeElement?.textContent?.trim()).toBe("狗");
|
||||
});
|
||||
});
|
||||
|
||||
describe("B02a review regressions", () => {
|
||||
it("cancels the pointer default only for plain row presses", async () => {
|
||||
await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("狗");
|
||||
const row = queryAll('[data-slot="list-box-item"]').find(
|
||||
(item) => !item.hasAttribute("data-filtered"),
|
||||
)!;
|
||||
|
||||
const pointer = pointerEvent("pointerdown");
|
||||
row.dispatchEvent(pointer);
|
||||
const mouse = new MouseEvent("mousedown", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
row.dispatchEvent(mouse);
|
||||
await nextTick();
|
||||
|
||||
// The default focus transfer is cancelled so the input keeps focus.
|
||||
expect(pointer.defaultPrevented).toBe(true);
|
||||
expect(mouse.defaultPrevented).toBe(true);
|
||||
|
||||
// A nested control keeps its own focus behaviour.
|
||||
const nested = document.createElement("button");
|
||||
row.appendChild(nested);
|
||||
const nestedPointer = pointerEvent("pointerdown");
|
||||
nested.dispatchEvent(nestedPointer);
|
||||
expect(nestedPointer.defaultPrevented).toBe(false);
|
||||
|
||||
// A caller that already cancelled is not overridden into a second action.
|
||||
const cancelled = new MouseEvent("mousedown", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
cancelled.preventDefault();
|
||||
row.dispatchEvent(cancelled);
|
||||
});
|
||||
|
||||
it("keeps caller hidden semantics next to filtering", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
await type("狗");
|
||||
// Filtered row is hidden by the filter, not by a caller attribute.
|
||||
const filtered = queryAll('[data-slot="list-box-item"]').find((item) =>
|
||||
item.hasAttribute("data-filtered"),
|
||||
)!;
|
||||
expect(filtered.hasAttribute("hidden")).toBe(true);
|
||||
|
||||
// Visible rows never gain hidden from the filter.
|
||||
const visible = queryAll('[data-slot="list-box-item"]').find(
|
||||
(item) => !item.hasAttribute("data-filtered"),
|
||||
)!;
|
||||
expect(visible.hasAttribute("hidden")).toBe(false);
|
||||
expect(wrapper.vm.accepted).toBeNull();
|
||||
});
|
||||
|
||||
it("computes virtual aria positions from the visible subset", async () => {
|
||||
const wrapper = await mountHarness({ virtualized: true });
|
||||
await type("鼠");
|
||||
const rows = queryAll('[data-slot="list-box-item"]');
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].getAttribute("aria-posinset")).toBe("1");
|
||||
expect(rows[0].getAttribute("aria-setsize")).toBe("1");
|
||||
expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([
|
||||
"hamster",
|
||||
]);
|
||||
});
|
||||
|
||||
it("renders the empty channel when filtering removes every row", async () => {
|
||||
await mountHarness({ virtualized: true });
|
||||
await type("不存在");
|
||||
expect(rowTexts()).toEqual([]);
|
||||
expect(queryOne('[data-test="empty"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("scrolls an ordinary mounted row on reveal and on keyboard focus", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const rows = queryAll('[data-slot="list-box-item"]');
|
||||
const spy = vi.fn();
|
||||
Object.defineProperty(rows[4], "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: spy,
|
||||
});
|
||||
await wrapper.vm.activeKey;
|
||||
await press("ArrowUp");
|
||||
expect(spy).toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(inputEl());
|
||||
});
|
||||
|
||||
it("clears activedescendant when closed and after filtering hides the row", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await press("ArrowDown");
|
||||
const openId = inputEl().getAttribute("aria-activedescendant");
|
||||
expect(openId).toBeTruthy();
|
||||
|
||||
await press("Escape");
|
||||
expect(wrapper.vm.open).toBe(false);
|
||||
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
|
||||
|
||||
await press("ArrowDown");
|
||||
await type("鼠");
|
||||
expect(
|
||||
document
|
||||
.getElementById(inputEl().getAttribute("aria-activedescendant")!)
|
||||
?.textContent?.trim(),
|
||||
).toBe("仓鼠");
|
||||
await type("不存在");
|
||||
expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps activedescendant in sync when a row press moves the active key", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const rows = queryAll('[data-slot="list-box-item"]');
|
||||
rows[2].dispatchEvent(pointerEvent("pointerdown"));
|
||||
rows[2].dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(wrapper.vm.activeKey).toBe("bird");
|
||||
const id = inputEl().getAttribute("aria-activedescendant");
|
||||
expect(id).toBeTruthy();
|
||||
expect(document.getElementById(id!)?.textContent?.trim()).toBe("鸟");
|
||||
});
|
||||
|
||||
it("keeps the shared keyboard modality recoverable after a pointer press", async () => {
|
||||
await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const rows = queryAll('[data-slot="list-box-item"]');
|
||||
rows[0].dispatchEvent(pointerEvent("pointerdown"));
|
||||
await nextTick();
|
||||
await press("ArrowDown");
|
||||
const focused = queryOne('[data-focused="true"]');
|
||||
expect(focused).not.toBeNull();
|
||||
expect(focused!.getAttribute("data-focus-visible")).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("B02a round 2 regressions", () => {
|
||||
const rows = () => queryAll('[data-slot="list-box-item"]');
|
||||
const visibleRows = () =>
|
||||
rows().filter((row) => !row.hasAttribute("data-filtered"));
|
||||
|
||||
it("keeps the pressed lifecycle while cancelling the focus transfer", async () => {
|
||||
await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const row = visibleRows()[0];
|
||||
|
||||
row.dispatchEvent(pointerEvent("pointerdown"));
|
||||
await nextTick();
|
||||
expect(row.getAttribute("data-pressed")).toBe("true");
|
||||
|
||||
// Release outside the row still clears the local press state.
|
||||
document.dispatchEvent(pointerEvent("pointerup"));
|
||||
await nextTick();
|
||||
expect(row.hasAttribute("data-pressed")).toBe(false);
|
||||
|
||||
// A caller that cancelled first never starts a press.
|
||||
const cancel = (event: Event) => event.preventDefault();
|
||||
row.addEventListener("pointerdown", cancel, true);
|
||||
row.dispatchEvent(pointerEvent("pointerdown"));
|
||||
await nextTick();
|
||||
expect(row.hasAttribute("data-pressed")).toBe(false);
|
||||
row.removeEventListener("pointerdown", cancel, true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"custom role button",
|
||||
() => {
|
||||
const element = document.createElement("span");
|
||||
element.setAttribute("role", "button");
|
||||
return element;
|
||||
},
|
||||
],
|
||||
[
|
||||
"contenteditable empty",
|
||||
() => {
|
||||
const element = document.createElement("div");
|
||||
element.setAttribute("contenteditable", "");
|
||||
return element;
|
||||
},
|
||||
],
|
||||
[
|
||||
"contenteditable plaintext",
|
||||
() => {
|
||||
const element = document.createElement("div");
|
||||
element.setAttribute("contenteditable", "plaintext-only");
|
||||
return element;
|
||||
},
|
||||
],
|
||||
])("does not activate the row for a nested %s", async (_label, make) => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const row = visibleRows()[0];
|
||||
const nested = make();
|
||||
row.appendChild(nested);
|
||||
|
||||
nested.dispatchEvent(pointerEvent("pointerdown"));
|
||||
nested.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
expect(wrapper.emitted("proposal")).toBeUndefined();
|
||||
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
|
||||
expect(document.activeElement).toBe(inputEl());
|
||||
});
|
||||
|
||||
it("does not scroll a reveal request after the collection closes", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await type("");
|
||||
const spy = vi.fn();
|
||||
const target = visibleRows()[2];
|
||||
Object.defineProperty(target, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: spy,
|
||||
});
|
||||
const collection = (wrapper.vm as unknown as { $: unknown }) && undefined;
|
||||
void collection;
|
||||
// Close first, then ask for a reveal: closed collections reject new work.
|
||||
await press("Escape");
|
||||
expect(wrapper.vm.open).toBe(false);
|
||||
spy.mockClear();
|
||||
await nextTick();
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the active key when filtering hides the active row", async () => {
|
||||
const visible = ref(true);
|
||||
const activeKey = ref<string | number>("cat");
|
||||
const owner = {
|
||||
keys: ref([]),
|
||||
mode: ref("single"),
|
||||
disabled: ref(false),
|
||||
readOnly: ref(false),
|
||||
disabledKeys: ref([]),
|
||||
id: "reconcile-list",
|
||||
labelledBy: () => undefined,
|
||||
ariaLabel: () => undefined,
|
||||
request: () => {},
|
||||
action: () => {},
|
||||
leave: () => {},
|
||||
connect: () => () => {},
|
||||
filter: (record: CollectionRecord) =>
|
||||
visible.value && record.key === "cat",
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
isOpen: () => true,
|
||||
} as unknown as CollectionOwner;
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(ListBox, { "aria-label": "行" }, () => [
|
||||
h(ListBoxItem, { id: "cat" }, () => "猫"),
|
||||
h(ListBoxItem, { id: "dog" }, () => "狗"),
|
||||
]);
|
||||
},
|
||||
}),
|
||||
{
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
provide: { [collectionOwnerKey as unknown as string]: owner },
|
||||
},
|
||||
},
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(activeKey.value).toBe("cat");
|
||||
|
||||
visible.value = false;
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(activeKey.value).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the accepted value separate from a removed active candidate", async () => {
|
||||
const wrapper = await mountHarness();
|
||||
inputEl().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
expect(wrapper.vm.accepted).toBe("cat");
|
||||
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
|
||||
|
||||
const proposalsBefore = wrapper.emitted("proposal")?.length ?? 0;
|
||||
await wrapper.setProps({ options: [{ id: "dog", text: "狗" }] });
|
||||
await settle();
|
||||
// History stays visible; the removed row can no longer be confirmed.
|
||||
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
|
||||
await press("Enter");
|
||||
expect(wrapper.emitted("proposal")?.length ?? 0).toBe(proposalsBefore);
|
||||
});
|
||||
|
||||
it("shows the empty channel in static, items and virtualized modes", async () => {
|
||||
await mountHarness();
|
||||
await type("不存在");
|
||||
expect(queryOne('[data-test="empty"]')).not.toBeNull();
|
||||
expect(visibleRows()).toHaveLength(0);
|
||||
expect(rows().length).toBeGreaterThan(0);
|
||||
wrappers.pop()?.unmount();
|
||||
await settle();
|
||||
|
||||
await mountHarness({ virtualized: true, options: [{ id: 1, text: "一" }] });
|
||||
await type("不存在");
|
||||
expect(queryOne('[data-test="empty"]')).not.toBeNull();
|
||||
wrappers.pop()?.unmount();
|
||||
await settle();
|
||||
|
||||
const wrapper = await mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
ListBox,
|
||||
{ items: [] as { id: string }[] },
|
||||
{
|
||||
default: () => [],
|
||||
empty: () => h("p", { "data-test": "items-empty" }, "空"),
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(queryOne('[data-test="items-empty"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("maps the full data set so an unmounted virtual row can be filtered", async () => {
|
||||
const options = Array.from({ length: 100 }, (_, index) => ({
|
||||
id: index,
|
||||
text: `Row ${index}`,
|
||||
}));
|
||||
const wrapper = await mountHarness({ virtualized: true, options });
|
||||
await type("Row 99");
|
||||
expect(visibleRows().map((row) => row.textContent?.trim())).toEqual([
|
||||
"Row 99",
|
||||
]);
|
||||
expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([99]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("B02a final boundary checks", () => {
|
||||
it("shows static empty feedback for an initially empty or removed collection", async () => {
|
||||
const options = ref<string[]>([]);
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
options.value.map((id) =>
|
||||
h(ListBoxItem, { id, key: id }, () => id),
|
||||
),
|
||||
empty: () => h("p", { "data-test": "static-empty" }, "Empty"),
|
||||
}),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(queryOne('[data-test="static-empty"]')).not.toBeNull();
|
||||
options.value = ["A"];
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(queryOne('[data-test="static-empty"]')).toBeNull();
|
||||
options.value = [];
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(queryOne('[data-test="static-empty"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("does not press the parent row from an embedded control", async () => {
|
||||
await mountHarness();
|
||||
await type("");
|
||||
const row = queryAll('[role="option"]')[0];
|
||||
const button = document.createElement("button");
|
||||
row.appendChild(button);
|
||||
const down = pointerEvent("pointerdown");
|
||||
button.dispatchEvent(down);
|
||||
await nextTick();
|
||||
expect(down.defaultPrevented).toBe(false);
|
||||
expect(row.hasAttribute("data-pressed")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { nextTick, type Component } from "vue";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 4));
|
||||
const mounted: { unmount: () => void }[] = [];
|
||||
|
||||
const previews = [
|
||||
"default",
|
||||
"full-width",
|
||||
"with-description",
|
||||
"required",
|
||||
"disabled",
|
||||
"with-disabled-options",
|
||||
"with-sections",
|
||||
"controlled",
|
||||
"controlled-input-value",
|
||||
"asynchronous-loading",
|
||||
"default-selected-key",
|
||||
"allows-custom-value",
|
||||
"custom-indicator",
|
||||
"custom-value",
|
||||
"custom-filtering",
|
||||
"render-function",
|
||||
"menu-trigger",
|
||||
"form-value",
|
||||
"validation-behavior",
|
||||
"custom-validation",
|
||||
"read-only",
|
||||
"multiple-selection",
|
||||
"on-surface",
|
||||
"custom-styles",
|
||||
];
|
||||
|
||||
afterEach(async () => {
|
||||
while (mounted.length) mounted.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("ComboBox docs and demos", () => {
|
||||
it("keeps the pinned preview order and one demo per preview", () => {
|
||||
const document = readFileSync("apps/docs/components/combo-box.md", "utf8");
|
||||
const names = [
|
||||
...document.matchAll(/<ComponentPreview name="combo-box-([^"]+)"/g),
|
||||
].map((match) => match[1]);
|
||||
|
||||
expect(names).toEqual(previews);
|
||||
for (const name of previews) {
|
||||
const source = readFileSync(
|
||||
`apps/docs/demos/combo-box-${name}.vue`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(source, name).toContain("<template>");
|
||||
expect(source, name).not.toContain("className");
|
||||
expect(source, name).not.toContain("@gravity-ui/icons");
|
||||
expect(source, name).not.toContain("<path");
|
||||
}
|
||||
});
|
||||
|
||||
it("documents Vue props and events instead of React ones", () => {
|
||||
const document = readFileSync("apps/docs/components/combo-box.md", "utf8");
|
||||
|
||||
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
|
||||
expect(document).toContain("`class`");
|
||||
expect(document).toContain("Vue class 绑定");
|
||||
expect(document).toContain("### ComboBoxInputGroup");
|
||||
expect(document).toContain("### ComboBoxValue");
|
||||
expect(document).toContain("### ComboBoxTrigger");
|
||||
expect(document).toContain("### ComboBoxPopover");
|
||||
expect(document).not.toContain("[!toc]");
|
||||
expect(document).not.toContain("ComboBox.List");
|
||||
});
|
||||
|
||||
it("mounts every demo with a real combobox control", async () => {
|
||||
const modules = import.meta.glob("../apps/docs/demos/combo-box-*.vue");
|
||||
expect(Object.keys(modules)).toHaveLength(previews.length);
|
||||
|
||||
for (const [path, load] of Object.entries(modules)) {
|
||||
vi.useFakeTimers();
|
||||
const demo = (await load()) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
const inputs = (wrapper.element as HTMLElement).querySelectorAll(
|
||||
'[role="combobox"]',
|
||||
);
|
||||
|
||||
expect(inputs.length, path).toBeGreaterThan(0);
|
||||
// Every combobox must be a real text input with a label association.
|
||||
for (const input of inputs) {
|
||||
expect(input.tagName, path).toBe("INPUT");
|
||||
expect(input.getAttribute("aria-expanded"), path).toBe("false");
|
||||
expect(input.id, path).not.toBe("");
|
||||
}
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
vi.useRealTimers();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("opens, filters and selects inside representative demos", async () => {
|
||||
const load = (name: string) =>
|
||||
import(`../apps/docs/demos/combo-box-${name}.vue`);
|
||||
|
||||
for (const name of ["default", "with-sections", "custom-styles"]) {
|
||||
const demo = (await load(name)) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const input = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLInputElement>('[role="combobox"]')!;
|
||||
input.focus();
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "ArrowDown",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input.getAttribute("aria-expanded"), name).toBe("true");
|
||||
const id = input.getAttribute("aria-activedescendant");
|
||||
expect(id, name).toBeTruthy();
|
||||
expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
|
||||
"option",
|
||||
);
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a preselected item's text in the input", async () => {
|
||||
for (const [name, expected] of [
|
||||
["default-selected-key", "猫"],
|
||||
["disabled", "猫"],
|
||||
["read-only", "猫"],
|
||||
] as const) {
|
||||
const demo = (await import(
|
||||
`../apps/docs/demos/combo-box-${name}.vue`
|
||||
)) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const input = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLInputElement>('[role="combobox"]')!;
|
||||
expect(input.value, name).toBe(expected);
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("submits form-value demos through hidden inputs", async () => {
|
||||
const demo =
|
||||
(await import("../apps/docs/demos/combo-box-form-value.vue")) as {
|
||||
default: Component;
|
||||
};
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const form = (wrapper.element as HTMLElement).matches("form")
|
||||
? (wrapper.element as HTMLFormElement)
|
||||
: (wrapper.element as HTMLElement).querySelector("form")!;
|
||||
// Nothing selected yet: an empty picker submits no entry at all.
|
||||
expect(new FormData(form).has("animal")).toBe(false);
|
||||
|
||||
for (const input of [
|
||||
...form.querySelectorAll<HTMLInputElement>('[data-slot="input"]'),
|
||||
]) {
|
||||
input.focus();
|
||||
await settle();
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "ArrowDown",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
}
|
||||
|
||||
const data = new FormData(form);
|
||||
const inputs = [
|
||||
...form.querySelectorAll<HTMLInputElement>('[data-slot="input"]'),
|
||||
];
|
||||
// Both pickers confirmed the same row: key mode submits the id, text mode
|
||||
// the label — never a comma-joined string.
|
||||
expect(data.get("animal")).toBe("cat");
|
||||
expect(data.get("animal-text")).toBe("猫");
|
||||
expect(data.getAll("animal")).toEqual(["cat"]);
|
||||
expect(inputs.map((input) => input.value)).toEqual(["猫", "猫"]);
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,898 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import {
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
ComboBoxValue,
|
||||
Description,
|
||||
FieldError,
|
||||
Form,
|
||||
Input,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
} from "../packages/vue/src";
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 3));
|
||||
const mounted: { unmount: () => void; element: Element }[] = [];
|
||||
|
||||
type Item = { id: string | number; text: string; disabled?: boolean };
|
||||
const animals: Item[] = [
|
||||
{ id: "cat", text: "猫" },
|
||||
{ id: "dog", text: "狗" },
|
||||
{ id: "bird", text: "鸟" },
|
||||
{ id: "fish", text: "鱼" },
|
||||
];
|
||||
|
||||
function mountCombo(
|
||||
props: Record<string, unknown> = {},
|
||||
options: { items?: Item[]; value?: boolean } = {},
|
||||
) {
|
||||
const items = options.items ?? animals;
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{ "aria-label": "动物", ...props },
|
||||
{
|
||||
default: () => [
|
||||
h(Label, () => "最喜欢的动物"),
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [
|
||||
h(Input, { placeholder: "搜索动物…" }),
|
||||
h(ComboBoxTrigger),
|
||||
],
|
||||
}),
|
||||
options.value
|
||||
? h(ComboBoxValue, { placeholder: "未选择" })
|
||||
: null,
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
items.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
isDisabled: item.disabled,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
empty: () =>
|
||||
h("p", { "data-test": "empty" }, "没有匹配项"),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
const input = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="input"]')!;
|
||||
const rowTexts = () =>
|
||||
[...document.querySelectorAll('[role="option"]')]
|
||||
.filter((row) => !row.hasAttribute("data-filtered"))
|
||||
.map((row) => row.textContent?.trim());
|
||||
|
||||
async function type(value: string) {
|
||||
const element = input();
|
||||
element.value = value;
|
||||
element.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
async function press(key: string, init: KeyboardEventInit = {}) {
|
||||
input().dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...init,
|
||||
}),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (mounted.length) mounted.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("ComboBox input semantics", () => {
|
||||
it("exposes one combobox control with label and ARIA wiring", async () => {
|
||||
mountCombo();
|
||||
await nextTick();
|
||||
const element = input();
|
||||
const label = document.querySelector("label")!;
|
||||
|
||||
expect(element.getAttribute("role")).toBe("combobox");
|
||||
expect(element.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(element.getAttribute("aria-autocomplete")).toBe("list");
|
||||
expect(element.getAttribute("aria-haspopup")).toBe("listbox");
|
||||
expect(element.id).toBeTruthy();
|
||||
expect(label.getAttribute("for")).toBe(element.id);
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="combo-box-trigger"]')!
|
||||
.getAttribute("tabindex"),
|
||||
).toBe("-1");
|
||||
});
|
||||
|
||||
it("opens on focus, filters with the input and keeps focus in the input", async () => {
|
||||
mountCombo();
|
||||
await nextTick();
|
||||
input().focus();
|
||||
input().dispatchEvent(new FocusEvent("focus"));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
await type("狗");
|
||||
expect(rowTexts()).toEqual(["狗"]);
|
||||
expect(document.activeElement).toBe(input());
|
||||
|
||||
const id = input().getAttribute("aria-activedescendant");
|
||||
expect(id).toBeTruthy();
|
||||
const option = document.getElementById(id!);
|
||||
expect(option?.getAttribute("role")).toBe("option");
|
||||
expect(option?.textContent?.trim()).toBe("狗");
|
||||
});
|
||||
|
||||
it("confirms with Enter, writes the text back and closes", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith("dog");
|
||||
expect(input().value).toBe("狗");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(input().getAttribute("aria-activedescendant")).toBeNull();
|
||||
});
|
||||
|
||||
it("closes on Escape without changing the value", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Escape");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not confirm while an IME composition is active", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Enter", { isComposing: true });
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await press("Enter", { keyCode: 229 });
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the selection when the text stops matching it", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
expect(onChange).toHaveBeenLastCalledWith("cat");
|
||||
|
||||
await type("狗");
|
||||
expect(onChange).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
|
||||
it("keeps a typed custom value when allowsCustomValue is set", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
await type("独角兽");
|
||||
// Typing a non-matching value must not clear the accepted custom text.
|
||||
expect(onChange).toHaveBeenLastCalledWith("cat");
|
||||
expect(input().value).toBe("独角兽");
|
||||
});
|
||||
|
||||
it("commits a typed custom value with Enter", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await type("独角兽");
|
||||
await press("Enter");
|
||||
|
||||
// The typed text itself becomes the value, like the baseline.
|
||||
expect(onChange).toHaveBeenLastCalledWith("独角兽");
|
||||
expect(input().value).toBe("独角兽");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("commits the typed text when the filter excluded every record", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
// The accepted row is filtered out, so the custom text must still commit.
|
||||
await type("独角兽");
|
||||
await press("Enter");
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith("独角兽");
|
||||
expect(input().value).toBe("独角兽");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox selection state", () => {
|
||||
it("keeps the accepted value when the parent rejects the proposal", async () => {
|
||||
mountCombo({ selectedKey: null, onSelectionChange: () => {} });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
await settle();
|
||||
// The rejected value never becomes accepted: nothing is selected.
|
||||
expect(document.querySelector('[aria-selected="true"]')).toBeNull();
|
||||
// And the proposal can be made again once the parent accepts the same key.
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
expect(document.querySelector('[aria-selected="true"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("reflects an externally changed selected key", async () => {
|
||||
const selected = ref<string | number | null>("dog");
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{
|
||||
"aria-label": "动物",
|
||||
selectedKey: selected.value,
|
||||
onSelectionChange: (key: string | number | null) =>
|
||||
(selected.value = key),
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().value).toBe("狗");
|
||||
|
||||
selected.value = "cat";
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().value).toBe("猫");
|
||||
});
|
||||
|
||||
it("skips disabled keys and does not select them", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo(
|
||||
{ disabledKeys: ["cat"], onSelectionChange: onChange },
|
||||
{ items: animals },
|
||||
);
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
expect(
|
||||
document.querySelector('[role="option"]')!.getAttribute("aria-disabled"),
|
||||
).toBe("true");
|
||||
await press("Enter");
|
||||
expect(onChange).toHaveBeenLastCalledWith("dog");
|
||||
});
|
||||
|
||||
it("does not open or select while disabled", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ isDisabled: true, onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the input read-only without selecting", async () => {
|
||||
const onChange = vi.fn();
|
||||
mountCombo({ isReadOnly: true, onSelectionChange: onChange });
|
||||
await nextTick();
|
||||
expect(input().readOnly).toBe(true);
|
||||
input().focus();
|
||||
await press("ArrowDown");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("shows multiple values and keeps accepted keys when filtered out", async () => {
|
||||
const selected = ref<(string | number)[]>(["cat", "dog"]);
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{
|
||||
"aria-label": "动物",
|
||||
selectionMode: "multiple",
|
||||
modelValue: selected.value,
|
||||
"onUpdate:modelValue": (value: unknown) =>
|
||||
(selected.value = (value ?? []) as (string | number)[]),
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(ComboBoxValue, { placeholder: "未选择" }),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(
|
||||
ListBox,
|
||||
{ selectionMode: "multiple" },
|
||||
{
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
},
|
||||
),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const value = () =>
|
||||
document
|
||||
.querySelector('[data-slot="combo-box-value"]')!
|
||||
.textContent?.trim();
|
||||
expect(value()).toBe("猫, 狗");
|
||||
|
||||
input().focus();
|
||||
await type("鸟");
|
||||
expect(value()).toBe("猫, 狗");
|
||||
expect(selected.value).toEqual(["cat", "dog"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox form and validation", () => {
|
||||
it("submits the key or the text through a hidden input", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const submitted = ref("");
|
||||
return () =>
|
||||
h(
|
||||
Form,
|
||||
{
|
||||
onSubmit: (event: Event) => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(
|
||||
event.currentTarget as HTMLFormElement,
|
||||
);
|
||||
submitted.value = `${data.get("animal")}|${data.get("animal-text")}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(
|
||||
ComboBox,
|
||||
{
|
||||
"aria-label": "key",
|
||||
name: "animal",
|
||||
formValue: "key",
|
||||
defaultSelectedKey: "cat",
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
ComboBox,
|
||||
{
|
||||
"aria-label": "text",
|
||||
name: "animal-text",
|
||||
formValue: "text",
|
||||
defaultSelectedKey: "dog",
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
"button",
|
||||
{ type: "submit", "data-test": "submit" },
|
||||
"提交",
|
||||
),
|
||||
h("p", { "data-test": "result" }, submitted.value),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
(
|
||||
document.querySelector('[data-test="submit"]') as HTMLButtonElement
|
||||
).click();
|
||||
await nextTick();
|
||||
expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
|
||||
"cat|狗",
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks native submit when required and empty", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const submitted = ref(0);
|
||||
return () =>
|
||||
h(
|
||||
Form,
|
||||
{
|
||||
onSubmit: (event: Event) => {
|
||||
event.preventDefault();
|
||||
submitted.value += 1;
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(
|
||||
ComboBox,
|
||||
{ "aria-label": "动物", name: "animal", isRequired: true },
|
||||
{
|
||||
default: () => [
|
||||
h(Label, () => "动物"),
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
h(FieldError, () => "请选择动物"),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
"button",
|
||||
{ type: "submit", "data-test": "submit" },
|
||||
"提交",
|
||||
),
|
||||
h("p", { "data-test": "submitted" }, String(submitted.value)),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const form = document.querySelector("form")!;
|
||||
const blocked = !form.checkValidity();
|
||||
expect(blocked).toBe(true);
|
||||
expect(input().required).toBe(true);
|
||||
});
|
||||
|
||||
it("surfaces a Description and an ErrorMessage through aria-describedby", async () => {
|
||||
mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{ "aria-label": "动物", isInvalid: true },
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input, {}), h(ComboBoxTrigger)],
|
||||
}),
|
||||
h(Description, () => "选择一种动物"),
|
||||
h(FieldError, () => "请选择动物"),
|
||||
h(ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
animals.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.text,
|
||||
},
|
||||
() => item.text,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const described = input().getAttribute("aria-describedby") ?? "";
|
||||
const description = document.querySelector('[data-slot="description"]')!;
|
||||
const error = document.querySelector('[data-slot="field-error"]')!;
|
||||
expect(described).toContain(description.id);
|
||||
expect(described).toContain(error.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox menu trigger", () => {
|
||||
it("opens on input only for menu-trigger=input", async () => {
|
||||
mountCombo({ menuTrigger: "input" });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
await type("猫");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("true");
|
||||
});
|
||||
|
||||
it("stays closed on focus for menu-trigger=manual and opens with ArrowDown", async () => {
|
||||
mountCombo({ menuTrigger: "manual" });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().getAttribute("aria-expanded")).toBe("false");
|
||||
await press("ArrowDown");
|
||||
expect(input().getAttribute("aria-expanded")).toBe("true");
|
||||
});
|
||||
|
||||
it("toggles from the trigger button", async () => {
|
||||
mountCombo();
|
||||
await nextTick();
|
||||
const trigger = document.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="combo-box-trigger"]',
|
||||
)!;
|
||||
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().getAttribute("aria-expanded")).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox ported style hooks", () => {
|
||||
it("emits the data-slot values the ported CSS targets", async () => {
|
||||
const css = readFileSync(
|
||||
"packages/styles/components/combo-box.css",
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Only class names carry the hv- prefix: data-slot values are a DOM
|
||||
// contract, so a prefixed value would leave the ported rules dead.
|
||||
expect(css).not.toMatch(/data-slot="hv-/);
|
||||
expect(css).toContain(
|
||||
'&[data-open="true"] [data-slot="combo-box-trigger-default-icon"]',
|
||||
);
|
||||
|
||||
mountCombo();
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
const trigger = document.querySelector('[data-slot="combo-box-trigger"]')!;
|
||||
expect(trigger.getAttribute("data-open")).toBe("true");
|
||||
expect(
|
||||
trigger.querySelector('[data-slot="combo-box-trigger-default-icon"]'),
|
||||
).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox filtering and composition", () => {
|
||||
it("inherits an accent-insensitive base matcher", async () => {
|
||||
mountCombo({}, { items: [{ id: "cafe", text: "Café" }] });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
await type("cafe");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
await type("CAFÉ");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
// Decomposed input still matches the precomposed label.
|
||||
await type("cafe\u0301");
|
||||
expect(rowTexts()).toEqual(["Café"]);
|
||||
});
|
||||
|
||||
it("lets a custom defaultFilter win over the built-in matcher", async () => {
|
||||
const defaultFilter = vi.fn(
|
||||
(text: string, query: string) => !query || text === query,
|
||||
);
|
||||
mountCombo({ defaultFilter });
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
await type("猫");
|
||||
expect(defaultFilter).toHaveBeenCalled();
|
||||
expect(rowTexts()).toEqual(["猫"]);
|
||||
// The built-in contains() would match "猫" inside "熊猫"; the custom one does not.
|
||||
await type("熊");
|
||||
expect(rowTexts()).toEqual([]);
|
||||
});
|
||||
|
||||
it("filters only after an open composition session ends", async () => {
|
||||
mountCombo();
|
||||
await nextTick();
|
||||
input().focus();
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(rowTexts()).toHaveLength(4);
|
||||
|
||||
input().dispatchEvent(new CompositionEvent("compositionstart"));
|
||||
await nextTick();
|
||||
await type("狗");
|
||||
expect(rowTexts()).toHaveLength(4);
|
||||
|
||||
input().dispatchEvent(new CompositionEvent("compositionend"));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(rowTexts()).toEqual(["狗"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox field protocol", () => {
|
||||
it("lets the user clear a required value, then blocks the submit", async () => {
|
||||
const update = vi.fn();
|
||||
mountCombo({
|
||||
name: "animal",
|
||||
defaultValue: "cat",
|
||||
isRequired: true,
|
||||
"onUpdate:modelValue": update,
|
||||
});
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().value).toBe("猫");
|
||||
|
||||
await type("");
|
||||
expect(update).toHaveBeenLastCalledWith(null);
|
||||
expect(input().value).toBe("");
|
||||
// The emptied field is invalid for native validation, not un-editable.
|
||||
expect(input().checkValidity()).toBe(false);
|
||||
});
|
||||
|
||||
it("associates the input and its reset handling with an external form", async () => {
|
||||
const external = document.createElement("form");
|
||||
external.id = "external-form";
|
||||
document.body.appendChild(external);
|
||||
mountCombo({
|
||||
name: "animal",
|
||||
form: "external-form",
|
||||
defaultValue: "cat",
|
||||
});
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().form).toBe(external);
|
||||
expect(new FormData(external).get("animal")).toBe("cat");
|
||||
|
||||
// An accepted reset restores the initial value through the same owner.
|
||||
const reset = new Event("reset", { cancelable: true });
|
||||
external.dispatchEvent(reset);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(new FormData(external).get("animal")).toBe("cat");
|
||||
|
||||
// A cancelled reset leaves the field untouched.
|
||||
const cancelled = new Event("reset", { cancelable: true });
|
||||
cancelled.preventDefault();
|
||||
external.dispatchEvent(cancelled);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(input().value).toBe("猫");
|
||||
external.remove();
|
||||
});
|
||||
|
||||
it("submits no entry for a disabled field", async () => {
|
||||
mountCombo({ name: "animal", defaultValue: "cat", isDisabled: true });
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(
|
||||
document.querySelector('[data-slot="combo-box-form-value"]'),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComboBox asChild, variant and autoFocus", () => {
|
||||
it("keeps the caller's root element, handlers and ref", async () => {
|
||||
const onClick = vi.fn();
|
||||
const hostRef = ref<HTMLElement>();
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{ asChild: true },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
"section",
|
||||
{ ref: hostRef, "data-test": "host", onClick },
|
||||
"picker",
|
||||
),
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
const host = wrapper.element as HTMLElement;
|
||||
expect(host.tagName).toBe("SECTION");
|
||||
expect(host.getAttribute("data-slot")).toBe("combo-box");
|
||||
expect(host.classList.contains("hv-combo-box")).toBe(true);
|
||||
expect(host.textContent).toContain("picker");
|
||||
expect(hostRef.value).toBe(host);
|
||||
host.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("lets an explicit Input variant override the inherited one", async () => {
|
||||
mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
ComboBox,
|
||||
{ variant: "secondary" },
|
||||
{
|
||||
default: () => [
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [
|
||||
h(Input, { variant: "primary" }),
|
||||
h(ComboBoxTrigger),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
expect(input().classList.contains("hv-input--primary")).toBe(true);
|
||||
expect(input().classList.contains("hv-input--secondary")).toBe(false);
|
||||
});
|
||||
|
||||
it("skips autoFocus when the field is disabled", async () => {
|
||||
mountCombo({ autoFocus: true, isDisabled: true });
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(document.activeElement).not.toBe(input());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
// These identifiers are valid browser inputs; the jsdom fallback must not
|
||||
// hide selector errors or fail to resolve them during Presence animations.
|
||||
it.each([
|
||||
["-1menu", "-\\31 menu"],
|
||||
["-", "\\-"],
|
||||
["0menu", "\\30 menu"],
|
||||
["a.b", "a\\.b"],
|
||||
["\u0000", "\uFFFD"],
|
||||
["\u0001a\u007f", "\\1 a\\7f "],
|
||||
["通知_--menu", "通知_--menu"],
|
||||
])("CSS.escape serializes %j like a browser", (input, expected) => {
|
||||
expect(CSS.escape(input)).toBe(expected);
|
||||
});
|
||||
@@ -37,3 +37,5 @@ COLOR-04 增加 `consume-color-slider-foundation.mjs`,在 `/private/tmp/heroui
|
||||
COLOR-06 增加 `consume-color-field-protocol.mjs`,在 `/private/tmp/heroui-color-field-consumer` 验证两份最终 tarball 的字段/输入组暂存 CSS 与没有提前公开占位;同时保留 Calendar/DateField/Select 的 ESM/SSR/CSS 和 strict NodeNext/bundler 类型正反例。组合字段当前内部实现,其 Props/slots 行为与 SSR/水合在工作区测试;COLOR-07 公共批次须补完整产物契约。
|
||||
|
||||
COLOR-08 增加 `consume-color-picker-protocol.mjs`,最终 tarball 在 `/private/tmp/heroui-color-picker-consumer` 验证 Picker CSS 暂存和没有公共占位,保留旧 Calendar/DateField/Select 运行/SSR/CSS 及双解析模式类型契约。Picker 内部三部件已接入组合夹具,公开批次仍须补完整公共 Props/事件/插槽产物验收。
|
||||
|
||||
B03 使用 `consume-b03-tag-error-message.mjs` / `b03-tag-error-message-contract.ts`,消费者目录 `/private/tmp/heroui-b03-consumer`(pnpm 11 的样式包 override 写在 `pnpm-workspace.yaml`)。验证 ESM 运行时(导出、SSR HTML 契约)、编译产物 CSS 选择器,以及 Tag/TagGroup/TagGroupList/TagRemoveButton/ErrorMessage 的正反类型(bundler 与 NodeNext)。
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# B01 独立浏览器消费夹具
|
||||
|
||||
用打包产物(`pnpm pack` 生成的 `@heroui-vue/components` / `@heroui-vue/styles` tarball)在独立 Vue 应用中真实挂载,覆盖:
|
||||
|
||||
- `selection`:带 `contain/isolation/overflow:hidden` 祖先的分组级多选长菜单(验证 Portal 脱离裁切、高度上限、真实 `role="menu"` 名称)。
|
||||
- `submenu`:三级子菜单 + 链接型菜单项。
|
||||
- `modal`:Modal 内的 Dropdown(验证层级与关闭顺序、滚动锁释放)。
|
||||
- `standalone`:独立 `Menu` 内联列表(无滚动锁、无浮动定位、不抢焦点)。
|
||||
|
||||
## 使用方式
|
||||
|
||||
```bash
|
||||
# 1. 在库仓库打包
|
||||
pnpm build
|
||||
pnpm --filter @heroui-vue/styles exec pnpm pack --pack-destination /tmp/heroui-b01-consumer
|
||||
pnpm --filter @heroui-vue/components exec pnpm pack --pack-destination /tmp/heroui-b01-consumer
|
||||
|
||||
# 2. 复制本目录到消费工程并安装
|
||||
cp -R tests/package/b01-consumer-app/. /tmp/heroui-b01-consumer/app/
|
||||
cd /tmp/heroui-b01-consumer && pnpm install
|
||||
|
||||
# 3. 打包成静态产物(esbuild 只作为构建工具,运行期仅依赖 tarball)
|
||||
esbuild app/main.js --bundle --format=esm --outfile=app/bundle.js --loader:.css=css
|
||||
|
||||
# 4. 静态服务后打开(`?only=selection|submenu|modal|standalone` 可单例)
|
||||
python3 -m http.server 5199 --bind 127.0.0.1 --directory app
|
||||
```
|
||||
|
||||
`consume-b01-menu-dropdown.mjs` 只做导出/CSS 存在性检查;真实挂载行为以本夹具的浏览器结果为准。
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>B01 consumer</title>
|
||||
<link rel="stylesheet" href="./bundle.css" />
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./bundle.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,253 @@
|
||||
import { createApp, h, ref, defineComponent } from "vue";
|
||||
import {
|
||||
Button,
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
Header,
|
||||
Label,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Modal,
|
||||
ModalTrigger,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeader,
|
||||
ModalHeading,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
ModalCloseTrigger,
|
||||
} from "@heroui-vue/components";
|
||||
import "@heroui-vue/styles/css";
|
||||
|
||||
const selected = ref(["a"]);
|
||||
const actions = [];
|
||||
window.__actions = actions;
|
||||
|
||||
const fruits = ["a", "b", "c", "d", "e", "f", "g", "h"];
|
||||
const names = ["苹果", "香蕉", "樱桃", "橙子", "梨", "葡萄", "西瓜", "芒果"];
|
||||
|
||||
const SelectionCase = defineComponent({
|
||||
name: "SelectionCase",
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", { "data-case": "clipping", class: "clip-ancestor" }, [
|
||||
h(DropdownRoot, { modal: false }, () => [
|
||||
h(DropdownTrigger, null, () =>
|
||||
h(Button, { "aria-label": "水果" }, () => "选择水果"),
|
||||
),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(
|
||||
DropdownMenu,
|
||||
{
|
||||
"aria-label": "水果操作",
|
||||
selectionMode: "multiple",
|
||||
selectedKeys: selected.value,
|
||||
"onUpdate:selectedKeys": (k) => (selected.value = k),
|
||||
},
|
||||
() =>
|
||||
h(DropdownSection, null, () => [
|
||||
h(Header, null, () => "水果"),
|
||||
...fruits.map((id, index) =>
|
||||
h(DropdownItem, { id, textValue: names[index] }, () => [
|
||||
h(DropdownItemIndicator),
|
||||
h(Label, null, () => names[index]),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const SubmenuCase = defineComponent({
|
||||
name: "SubmenuCase",
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", { "data-case": "submenu", class: "case" }, [
|
||||
h(DropdownRoot, { modal: false }, () => [
|
||||
h(DropdownTrigger, null, () =>
|
||||
h(Button, { "aria-label": "分享" }, () => "分享"),
|
||||
),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(
|
||||
DropdownMenu,
|
||||
{ onAction: (k) => actions.push(String(k)) },
|
||||
() => [
|
||||
h(DropdownItem, { id: "copy", textValue: "复制链接" }, () =>
|
||||
h(Label, null, () => "复制链接"),
|
||||
),
|
||||
h(DropdownSubmenuTrigger, null, () => [
|
||||
h(DropdownItem, { id: "more", textValue: "更多" }, () => [
|
||||
h(Label, null, () => "更多"),
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(DropdownMenu, null, () => [
|
||||
h(DropdownItem, { id: "wa", textValue: "WhatsApp" }, () =>
|
||||
h(Label, null, () => "WhatsApp"),
|
||||
),
|
||||
h(DropdownItem, { id: "tg", textValue: "Telegram" }, () =>
|
||||
h(Label, null, () => "Telegram"),
|
||||
),
|
||||
h(DropdownSubmenuTrigger, null, () => [
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "mail", textValue: "邮件" },
|
||||
() => [
|
||||
h(Label, null, () => "邮件"),
|
||||
h(DropdownSubmenuIndicator),
|
||||
],
|
||||
),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(DropdownMenu, null, () =>
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "work", textValue: "工作邮箱" },
|
||||
() => h(Label, null, () => "工作邮箱"),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "link", textValue: "文档", href: "#docs" },
|
||||
() => h(Label, null, () => "文档链接"),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const ModalCase = defineComponent({
|
||||
name: "ModalCase",
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", { "data-case": "modal", class: "case" }, [
|
||||
h(Modal, null, () => [
|
||||
h(ModalTrigger, null, () => h(Button, null, () => "打开组合复核")),
|
||||
h(ModalBackdrop, null, () =>
|
||||
h(ModalContainer, null, () =>
|
||||
h(ModalDialog, null, () => [
|
||||
h(ModalHeader, null, () =>
|
||||
h(ModalHeading, null, () => "模态内菜单"),
|
||||
),
|
||||
h(ModalBody, null, () => [
|
||||
h(DropdownRoot, { modal: false }, () => [
|
||||
h(DropdownTrigger, null, () =>
|
||||
h(Button, { "aria-label": "菜单" }, () => "菜单"),
|
||||
),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(DropdownMenu, null, () => [
|
||||
h(DropdownItem, { id: "m1", textValue: "一" }, () =>
|
||||
h(Label, null, () => "一"),
|
||||
),
|
||||
h(DropdownItem, { id: "m2", textValue: "二" }, () =>
|
||||
h(Label, null, () => "二"),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
h(ModalFooter, null, () =>
|
||||
h(ModalCloseTrigger, null, () =>
|
||||
h(Button, null, () => "关闭"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const WrapCase = defineComponent({
|
||||
name: "WrapCase",
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", { "data-case": "wrap", class: "case" }, [
|
||||
h(DropdownRoot, { modal: false }, () => [
|
||||
h(DropdownTrigger, null, () =>
|
||||
h(Button, { "aria-label": "循环" }, () => "循环"),
|
||||
),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(DropdownMenu, null, () =>
|
||||
h(DropdownSubmenuTrigger, null, () => [
|
||||
h(DropdownItem, { id: "wrap-sub", textValue: "子菜单" }, () => [
|
||||
h(Label, null, () => "子菜单"),
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, null, () =>
|
||||
h(DropdownMenu, { shouldFocusWrap: true }, () => [
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "wrap-first", textValue: "First" },
|
||||
() => h(Label, null, () => "First"),
|
||||
),
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "wrap-last", textValue: "Last" },
|
||||
() => h(Label, null, () => "Last"),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const StandaloneCase = defineComponent({
|
||||
name: "StandaloneCase",
|
||||
setup() {
|
||||
return () =>
|
||||
h("div", { "data-case": "standalone", class: "case" }, [
|
||||
h(Menu, { "aria-label": "内联菜单" }, () => [
|
||||
h(MenuItem, { id: "s1" }, () => "内联项一"),
|
||||
h(MenuItem, { id: "s2" }, () => "内联项二"),
|
||||
]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const only = new URLSearchParams(location.search).get("only");
|
||||
const cases = {
|
||||
selection: SelectionCase,
|
||||
submenu: SubmenuCase,
|
||||
modal: ModalCase,
|
||||
standalone: StandaloneCase,
|
||||
wrap: WrapCase,
|
||||
};
|
||||
const shown = only && cases[only] ? [cases[only]] : Object.values(cases);
|
||||
|
||||
createApp(
|
||||
defineComponent({
|
||||
name: "App",
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
"main",
|
||||
{ style: "display:flex;flex-direction:column;gap:16px;padding:16px" },
|
||||
shown.map((component) => h(component)),
|
||||
);
|
||||
},
|
||||
}),
|
||||
).mount("#app");
|
||||
@@ -0,0 +1,16 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, "PingFang SC", sans-serif;
|
||||
}
|
||||
.clip-ancestor {
|
||||
overflow: hidden;
|
||||
contain: content;
|
||||
isolation: isolate;
|
||||
height: 64px;
|
||||
border: 1px dashed #bbb;
|
||||
}
|
||||
.case {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuItemIndicator,
|
||||
MenuItemSubmenuIndicator,
|
||||
MenuSection,
|
||||
type DropdownRootProps,
|
||||
type DropdownMenuProps,
|
||||
type DropdownItemProps,
|
||||
type DropdownItemIndicatorProps,
|
||||
type MenuRootProps,
|
||||
type MenuItemProps,
|
||||
type MenuItemIndicatorProps,
|
||||
type MenuSectionProps,
|
||||
type MenuKey,
|
||||
type MenuSelectionMode,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const mode: MenuSelectionMode = "multiple";
|
||||
const keys: MenuKey[] = ["a", 0, ""];
|
||||
|
||||
const root: DropdownRootProps = {
|
||||
trigger: "longPress",
|
||||
longPressDuration: 400,
|
||||
modal: true,
|
||||
dir: "rtl",
|
||||
};
|
||||
// @ts-expect-error unknown trigger mode
|
||||
const badTrigger: DropdownRootProps = { trigger: "hover" };
|
||||
|
||||
const menu: MenuRootProps = {
|
||||
selectionMode: mode,
|
||||
selectedKeys: keys,
|
||||
disabledKeys: ["b"],
|
||||
};
|
||||
// @ts-expect-error selectionMode must be none|single|multiple
|
||||
const badMode: MenuRootProps = { selectionMode: "multiple2" };
|
||||
|
||||
const item: MenuItemProps = {
|
||||
id: "a",
|
||||
textValue: "A",
|
||||
variant: "danger",
|
||||
isDisabled: true,
|
||||
closeOnSelect: false,
|
||||
};
|
||||
// @ts-expect-error variant is default|danger only
|
||||
const badVariant: MenuItemProps = { variant: "primary" };
|
||||
|
||||
const indicator: MenuItemIndicatorProps = { type: "dot" };
|
||||
// @ts-expect-error type is checkmark|dot
|
||||
const badIndicator: MenuItemIndicatorProps = { type: "cross" };
|
||||
|
||||
const section: MenuSectionProps = {
|
||||
selectionMode: "single",
|
||||
selectedKeys: ["x"],
|
||||
};
|
||||
|
||||
const dItem: DropdownItemProps = {
|
||||
id: "x",
|
||||
textValue: "X",
|
||||
variant: "default",
|
||||
};
|
||||
const dInd: DropdownItemIndicatorProps = { type: "checkmark" };
|
||||
const dMenu: DropdownMenuProps = { selectionMode: "none" };
|
||||
|
||||
export const parts = [
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuItemIndicator,
|
||||
MenuItemSubmenuIndicator,
|
||||
MenuSection,
|
||||
] as const;
|
||||
|
||||
export const values = {
|
||||
root,
|
||||
menu,
|
||||
item,
|
||||
indicator,
|
||||
section,
|
||||
dItem,
|
||||
dInd,
|
||||
dMenu,
|
||||
badTrigger,
|
||||
badMode,
|
||||
badVariant,
|
||||
badIndicator,
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
DropdownItem,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
} from "@heroui-vue/components";
|
||||
// Valid API values must be accepted by the actual public Vue component types,
|
||||
// not only by separately exported aliases.
|
||||
export const item: InstanceType<typeof DropdownItem>["$props"] = {
|
||||
id: "item",
|
||||
variant: "danger",
|
||||
};
|
||||
export const menu: InstanceType<typeof DropdownMenu>["$props"] = {
|
||||
selectionMode: "multiple",
|
||||
selectedKeys: [0, "0"],
|
||||
};
|
||||
export const section: InstanceType<typeof DropdownSection>["$props"] = {
|
||||
selectionMode: "single",
|
||||
};
|
||||
@@ -0,0 +1,251 @@
|
||||
import { h } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
ComboBoxValue,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
type AutocompleteItem,
|
||||
type AutocompleteProps,
|
||||
type AutocompleteState,
|
||||
type AutocompleteValueState,
|
||||
type AutocompleteValueProps,
|
||||
type ComboBoxItem,
|
||||
type ComboBoxProps,
|
||||
type ComboBoxState,
|
||||
type ComboBoxValueProps,
|
||||
type ComboBoxValueState,
|
||||
type ComboBoxModelValue,
|
||||
type CollectionKey,
|
||||
type ValidateResult,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keys: numbers and strings stay distinct, null means "no selection".
|
||||
// ---------------------------------------------------------------------------
|
||||
const stringKey: ComboBoxModelValue = "cat";
|
||||
const numericKey: ComboBoxModelValue = 0;
|
||||
const emptyKey: ComboBoxModelValue = "";
|
||||
const cleared: ComboBoxModelValue = null;
|
||||
const multiple: ComboBoxModelValue = ["cat", 0];
|
||||
// @ts-expect-error a key is a string or a finite number
|
||||
const objectKey: ComboBoxModelValue = { id: "cat" };
|
||||
// @ts-expect-error undefined is not a selection state; use null
|
||||
const missingKey: ComboBoxModelValue = undefined;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ComboBox props
|
||||
// ---------------------------------------------------------------------------
|
||||
const comboProps: ComboBoxProps = {
|
||||
modelValue: stringKey,
|
||||
defaultValue: numericKey,
|
||||
selectionMode: "multiple",
|
||||
inputValue: "",
|
||||
defaultInputValue: "",
|
||||
items: [{ id: 0, textValue: "Zero", isDisabled: false }],
|
||||
disabledKeys: ["a", 0, ""],
|
||||
open: false,
|
||||
defaultOpen: false,
|
||||
isDisabled: false,
|
||||
isReadOnly: false,
|
||||
isRequired: false,
|
||||
isInvalid: false,
|
||||
allowsCustomValue: true,
|
||||
allowsEmptyCollection: true,
|
||||
menuTrigger: "manual",
|
||||
shouldFocusWrap: true,
|
||||
fullWidth: true,
|
||||
variant: "secondary",
|
||||
name: "animal",
|
||||
form: "external-form",
|
||||
formValue: "text",
|
||||
autoComplete: "off",
|
||||
autoFocus: true,
|
||||
validationBehavior: "aria",
|
||||
placeholder: "Select an item",
|
||||
as: "section",
|
||||
asChild: false,
|
||||
class: ["hv-combo-box", { "is-dense": true }],
|
||||
};
|
||||
// @ts-expect-error selectionMode is a closed union
|
||||
const badMode: ComboBoxProps = { selectionMode: "triple" };
|
||||
// @ts-expect-error variant is a closed union
|
||||
const badVariant: ComboBoxProps = { variant: "tertiary" };
|
||||
// @ts-expect-error formValue only allows key or text
|
||||
const badFormValue: ComboBoxProps = { formValue: "both" };
|
||||
|
||||
// `validate` keeps its parameter and result types.
|
||||
const comboWithValidate: ComboBoxProps = {
|
||||
validate: (value) => {
|
||||
const accepted: ComboBoxModelValue = value;
|
||||
void accepted;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
// @ts-expect-error validate must return a validation result, not a boolean flag object
|
||||
const badValidate: ComboBoxProps = { validate: () => ({ ok: true }) };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Autocomplete props, including the source `items` mapping
|
||||
// ---------------------------------------------------------------------------
|
||||
const autocompleteItems: AutocompleteItem[] = [
|
||||
{ id: "california", textValue: "California" },
|
||||
{ id: 0, textValue: "Zero", isDisabled: true },
|
||||
];
|
||||
// @ts-expect-error items need a textValue for filtering and display
|
||||
const itemsWithoutText: AutocompleteItem[] = [{ id: "a" }];
|
||||
|
||||
const autocompleteProps: AutocompleteProps = {
|
||||
modelValue: cleared,
|
||||
value: multiple,
|
||||
defaultValue: ["a", "b"],
|
||||
items: autocompleteItems,
|
||||
selectionMode: "multiple",
|
||||
disabledKeys: ["a"],
|
||||
open: true,
|
||||
isOpen: true,
|
||||
defaultOpen: false,
|
||||
isDisabled: false,
|
||||
isRequired: true,
|
||||
isInvalid: false,
|
||||
allowsEmptyCollection: false,
|
||||
placeholder: "Select an item",
|
||||
name: "state",
|
||||
form: "external-form",
|
||||
fullWidth: true,
|
||||
variant: "primary",
|
||||
validationBehavior: "native",
|
||||
as: "div",
|
||||
asChild: true,
|
||||
validate: (value): ValidateResult => (Array.isArray(value) ? true : null),
|
||||
};
|
||||
const badAutocompleteValidate: AutocompleteProps = {
|
||||
// @ts-expect-error validate must not widen to an arbitrary return type
|
||||
validate: () => Symbol("nope"),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Events keep their payload types
|
||||
// ---------------------------------------------------------------------------
|
||||
const comboEvents = h(ComboBox, {
|
||||
"onUpdate:modelValue": (value: ComboBoxModelValue) => void value,
|
||||
onChange: (value: ComboBoxModelValue) => void value,
|
||||
"onUpdate:selectedKey": (key: CollectionKey | null) => void key,
|
||||
selectionChange: (key: CollectionKey | null) => void key,
|
||||
"onUpdate:inputValue": (text: string) => void text,
|
||||
inputChange: (text: string) => void text,
|
||||
"onUpdate:open": (open: boolean) => void open,
|
||||
openChange: (open: boolean) => void open,
|
||||
});
|
||||
const badComboEvent = h(ComboBox, {
|
||||
// @ts-expect-error the model event carries the value, never the input text
|
||||
"onUpdate:modelValue": (text: string) => void text,
|
||||
});
|
||||
|
||||
// Root scoped slots expose the open/selection state.
|
||||
const comboState = (state: ComboBoxState): string =>
|
||||
`${state.isOpen}:${state.inputValue}:${state.selectedKeys.length}`;
|
||||
const autocompleteState = (state: AutocompleteState): string =>
|
||||
`${state.isOpen}:${state.selectedKeys.length}`;
|
||||
const comboValueState = (state: ComboBoxValueState): string =>
|
||||
`${state.isPlaceholder}:${state.selectedItems.length}`;
|
||||
|
||||
const autocompleteEvents = h(Autocomplete, {
|
||||
"onUpdate:modelValue": (value: ComboBoxModelValue) => void value,
|
||||
onChange: (value: ComboBoxModelValue) => void value,
|
||||
"onUpdate:open": (open: boolean) => void open,
|
||||
openChange: (open: boolean) => void open,
|
||||
clear: () => undefined,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parts: every public part accepts the documented props and slots
|
||||
// ---------------------------------------------------------------------------
|
||||
const comboTree = h(ComboBox, { "aria-label": "动物" }, () => [
|
||||
h(ComboBoxInputGroup, { class: "w-full" }, () => "input"),
|
||||
h(ComboBoxValue, { placeholder: "未选择" }),
|
||||
h(ComboBoxPopover, { placement: "top", offset: 4, shouldFlip: false }, () =>
|
||||
h(ListBox, { "aria-label": "动物" }, () =>
|
||||
h(ListBoxItem, { id: 0, textValue: "Zero" }, () => "Zero"),
|
||||
),
|
||||
),
|
||||
h(ComboBoxTrigger, { isDisabled: true }),
|
||||
]);
|
||||
// @ts-expect-error placement is a closed union
|
||||
const badPlacement = h(ComboBoxPopover, { placement: "middle" });
|
||||
|
||||
const autocompleteTree = h(Autocomplete, { "aria-label": "州" }, () => [
|
||||
h(AutocompleteTrigger, { isDisabled: false }, () => [
|
||||
h(AutocompleteValue, null, {
|
||||
// Scoped slot state keeps its documented, exported shape.
|
||||
default: (state: AutocompleteValueState) => {
|
||||
const placeholder: boolean = state.isPlaceholder;
|
||||
const joined: string = state.selectedText || state.defaultChildren;
|
||||
const keys = state.selectedItems.map((item) => item.key);
|
||||
return placeholder ? joined : keys.join(",");
|
||||
},
|
||||
}),
|
||||
h(AutocompleteClearButton),
|
||||
h(AutocompleteIndicator),
|
||||
]),
|
||||
h(AutocompletePopover, { placement: "bottom end" }, () =>
|
||||
h(
|
||||
AutocompleteFilter,
|
||||
{ filter: (text, input) => text.includes(input) },
|
||||
() =>
|
||||
h(ListBox, null, () =>
|
||||
h(ListBoxItem, { id: "a", textValue: "A" }, () => "A"),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
const valueProps: ComboBoxValueProps = { placeholder: "未选择" };
|
||||
const autocompleteValueProps: AutocompleteValueProps = {};
|
||||
// @ts-expect-error ComboBoxValue has no `items` prop
|
||||
const badValueProps: ComboBoxValueProps = { items: [] };
|
||||
|
||||
const item: ComboBoxItem = { id: 0, textValue: "Zero" };
|
||||
const autocompleteFirstItem: AutocompleteItem = autocompleteItems[0]!;
|
||||
|
||||
export {
|
||||
comboState,
|
||||
comboValueState,
|
||||
autocompleteState,
|
||||
autocompleteEvents,
|
||||
autocompleteFirstItem,
|
||||
autocompleteProps,
|
||||
autocompleteTree,
|
||||
autocompleteValueProps,
|
||||
badAutocompleteValidate,
|
||||
badComboEvent,
|
||||
badFormValue,
|
||||
badMode,
|
||||
badPlacement,
|
||||
badValidate,
|
||||
badValueProps,
|
||||
badVariant,
|
||||
cleared,
|
||||
comboEvents,
|
||||
comboProps,
|
||||
comboTree,
|
||||
comboWithValidate,
|
||||
emptyKey,
|
||||
item,
|
||||
itemsWithoutText,
|
||||
missingKey,
|
||||
multiple,
|
||||
numericKey,
|
||||
objectKey,
|
||||
stringKey,
|
||||
valueProps,
|
||||
};
|
||||
@@ -0,0 +1,121 @@
|
||||
import { h } from "vue";
|
||||
import {
|
||||
ErrorMessage,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
TagRemoveButton,
|
||||
type TagGroupProps,
|
||||
type TagGroupListProps,
|
||||
type TagKey,
|
||||
type TagProps,
|
||||
type TagRemoveButtonProps,
|
||||
type TagRenderState,
|
||||
type ErrorMessageProps,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const key: TagKey = "news";
|
||||
const numericKey: TagKey = 0;
|
||||
// @ts-expect-error collection keys are strings or finite numbers
|
||||
const invalidKey: TagKey = {};
|
||||
|
||||
const groupProps: TagGroupProps = {
|
||||
selectionMode: "multiple",
|
||||
modelValue: [key, numericKey],
|
||||
defaultValue: [],
|
||||
disabledKeys: [key],
|
||||
isDisabled: false,
|
||||
disallowEmptySelection: true,
|
||||
size: "lg",
|
||||
variant: "surface",
|
||||
dir: "rtl",
|
||||
as: "section",
|
||||
asChild: false,
|
||||
};
|
||||
// @ts-expect-error selectionMode is a closed union
|
||||
const badMode: TagGroupProps = { selectionMode: "triple" };
|
||||
// @ts-expect-error size is a closed union
|
||||
const badSize: TagGroupProps = { size: "xl" };
|
||||
|
||||
// `items` keeps the caller's item type: extra fields are allowed and reach the
|
||||
// scoped slot unchanged.
|
||||
const listProps: TagGroupListProps<{ id: string; name: string }> = {
|
||||
items: [{ id: "a", name: "A" }],
|
||||
as: "div",
|
||||
};
|
||||
// @ts-expect-error items must carry a collection key
|
||||
const listPropsWithoutId: TagGroupListProps<{ name: string }> = {
|
||||
items: [{ name: "A" }],
|
||||
};
|
||||
|
||||
const tagProps: TagProps = { id: key, textValue: "资讯", isDisabled: false };
|
||||
const removeProps: TagRemoveButtonProps = {
|
||||
textValue: "资讯",
|
||||
isDisabled: true,
|
||||
};
|
||||
// ErrorMessage declares no props of its own: content, `id` and `class` are
|
||||
// ordinary attributes / slots.
|
||||
const messageProps: ErrorMessageProps = {};
|
||||
|
||||
const state: TagRenderState = {
|
||||
isSelected: true,
|
||||
isDisabled: false,
|
||||
isHovered: false,
|
||||
isPressed: false,
|
||||
isFocused: true,
|
||||
isFocusVisible: true,
|
||||
allowsRemoving: true,
|
||||
};
|
||||
|
||||
const tree = h(
|
||||
TagGroup,
|
||||
{
|
||||
selectionMode: "single",
|
||||
modelValue: [key],
|
||||
"onUpdate:modelValue": (keys: TagKey[]) => keys.length,
|
||||
onSelectionChange: (keys: TagKey[]) => keys,
|
||||
onRemove: (keys: TagKey[]) => keys,
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(TagGroupList, null, {
|
||||
default: () =>
|
||||
h(
|
||||
Tag,
|
||||
{ id: key },
|
||||
{
|
||||
default: (tagState: TagRenderState) =>
|
||||
tagState.isSelected ? "selected" : "tag",
|
||||
},
|
||||
),
|
||||
empty: () =>
|
||||
h(ErrorMessage, { ...messageProps, id: "error" }, () => "empty"),
|
||||
}),
|
||||
h(Tag, tagProps, {
|
||||
default: () => [
|
||||
"资讯",
|
||||
h(TagRemoveButton, removeProps, { default: () => "x" }),
|
||||
],
|
||||
}),
|
||||
h(ErrorMessage, null, () => "请选择"),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
// @ts-expect-error Tag requires a collection key
|
||||
const missingId = h(Tag, {});
|
||||
|
||||
// @ts-expect-error remove button text must be a string
|
||||
const badRemoveText = h(TagRemoveButton, { textValue: 1 });
|
||||
|
||||
void [
|
||||
listPropsWithoutId,
|
||||
invalidKey,
|
||||
badMode,
|
||||
badSize,
|
||||
state,
|
||||
tree,
|
||||
missingId,
|
||||
badRemoveText,
|
||||
groupProps,
|
||||
];
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Independent ESM/CSS consumption for B01 Menu/Dropdown.
|
||||
* Copy into a fresh consumer that installs packed tarballs (no source alias).
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const mod = await import("@heroui-vue/components");
|
||||
const {
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownSection,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuItemIndicator,
|
||||
MenuItemSubmenuIndicator,
|
||||
MenuSection,
|
||||
} = mod;
|
||||
|
||||
const expected = {
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownSection,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuItemIndicator,
|
||||
MenuItemSubmenuIndicator,
|
||||
MenuSection,
|
||||
};
|
||||
for (const [name, value] of Object.entries(expected)) {
|
||||
if (!value) {
|
||||
console.error("missing export", name);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const cssPath = import.meta.resolve("@heroui-vue/styles/css");
|
||||
const css = readFileSync(new URL(cssPath), "utf8");
|
||||
for (const token of [
|
||||
"hv-menu-item",
|
||||
"hv-menu-item__indicator--submenu",
|
||||
"hv-dropdown__popover",
|
||||
"hv-dropdown__menu",
|
||||
"data-selected",
|
||||
]) {
|
||||
if (!css.includes(token)) {
|
||||
console.error("css missing", token);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("b01 menu/dropdown ESM+CSS consume ok");
|
||||
@@ -0,0 +1,159 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import * as lib from "@heroui-vue/components";
|
||||
|
||||
for (const name of [
|
||||
"ComboBox",
|
||||
"ComboBoxInputGroup",
|
||||
"ComboBoxTrigger",
|
||||
"ComboBoxValue",
|
||||
"ComboBoxPopover",
|
||||
"Autocomplete",
|
||||
"AutocompleteTrigger",
|
||||
"AutocompleteValue",
|
||||
"AutocompleteIndicator",
|
||||
"AutocompleteClearButton",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
"comboBoxVariants",
|
||||
"autocompleteVariants",
|
||||
])
|
||||
assert(lib[name], name);
|
||||
|
||||
const items = [
|
||||
{ id: "cat", textValue: "猫" },
|
||||
{ id: "dog", textValue: "狗" },
|
||||
];
|
||||
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h("main", [
|
||||
h(
|
||||
lib.ComboBox,
|
||||
{ "aria-label": "动物", defaultSelectedKey: "cat", name: "animal" },
|
||||
{
|
||||
default: () => [
|
||||
h(lib.Label, null, () => "动物"),
|
||||
h(lib.ComboBoxInputGroup, null, {
|
||||
default: () => [h(lib.Input, {}), h(lib.ComboBoxTrigger)],
|
||||
}),
|
||||
h(lib.ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(lib.ListBox, null, {
|
||||
default: () =>
|
||||
items.map((item) =>
|
||||
h(
|
||||
lib.ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
lib.Autocomplete,
|
||||
{ "aria-label": "州", name: "state", defaultValue: "dog" },
|
||||
{
|
||||
default: () => [
|
||||
h(lib.AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(lib.AutocompleteValue),
|
||||
h(lib.AutocompleteClearButton),
|
||||
h(lib.AutocompleteIndicator),
|
||||
],
|
||||
}),
|
||||
h(lib.AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(lib.AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
lib.SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(lib.SearchFieldGroup, null, {
|
||||
default: () => [h(lib.SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(lib.ListBox, null, {
|
||||
default: () =>
|
||||
items.map((item) =>
|
||||
h(
|
||||
lib.ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
assert(html.includes('data-slot="combo-box"'), "combo-box root");
|
||||
assert(html.includes('role="combobox"'), "combobox input role");
|
||||
assert(html.includes('data-slot="combo-box-trigger"'), "combo box trigger");
|
||||
assert(html.includes('name="animal"'), "combo box form name");
|
||||
assert(html.includes('data-slot="autocomplete"'), "autocomplete root");
|
||||
assert(
|
||||
html.includes('data-slot="autocomplete-trigger"'),
|
||||
"autocomplete trigger",
|
||||
);
|
||||
assert(html.includes('role="button"'), "autocomplete trigger is a button");
|
||||
assert(html.includes('name="state"'), "autocomplete form name");
|
||||
assert(html.includes("猫"), "combo box preselected label");
|
||||
|
||||
const css = readFileSync(
|
||||
"node_modules/@heroui-vue/styles/dist/styles.css",
|
||||
"utf8",
|
||||
);
|
||||
for (const rule of [
|
||||
".hv-combo-box",
|
||||
".hv-combo-box__input-group",
|
||||
".hv-combo-box__trigger",
|
||||
".hv-combo-box__popover",
|
||||
".hv-combo-box__value",
|
||||
".hv-autocomplete",
|
||||
".hv-autocomplete__trigger",
|
||||
".hv-autocomplete__value",
|
||||
".hv-autocomplete__indicator",
|
||||
".hv-autocomplete__clear-button",
|
||||
".hv-autocomplete__popover",
|
||||
".hv-autocomplete--secondary",
|
||||
])
|
||||
assert(css.includes(rule), `missing CSS ${rule}`);
|
||||
|
||||
assert(
|
||||
lib
|
||||
.comboBoxVariants({ fullWidth: true })
|
||||
.base()
|
||||
.includes("hv-combo-box--full-width"),
|
||||
);
|
||||
assert(
|
||||
lib
|
||||
.autocompleteVariants({ variant: "secondary" })
|
||||
.base()
|
||||
.includes("hv-autocomplete--secondary"),
|
||||
);
|
||||
|
||||
console.log("B02 pickers consumption OK");
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import * as lib from "@heroui-vue/components";
|
||||
|
||||
for (const name of [
|
||||
"TagGroup",
|
||||
"TagGroupList",
|
||||
"Tag",
|
||||
"TagRemoveButton",
|
||||
"ErrorMessage",
|
||||
"tagVariants",
|
||||
"tagGroupVariants",
|
||||
"errorMessageVariants",
|
||||
])
|
||||
assert(lib[name], name);
|
||||
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(
|
||||
lib.TagGroup,
|
||||
{
|
||||
"aria-label": "分类",
|
||||
selectionMode: "multiple",
|
||||
modelValue: ["news"],
|
||||
onRemove: () => {},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(lib.TagGroupList, null, {
|
||||
default: () => [
|
||||
h(lib.Tag, { id: "news" }, { default: () => "资讯" }),
|
||||
h(
|
||||
lib.Tag,
|
||||
{ id: 0, isDisabled: true },
|
||||
{ default: () => "零" },
|
||||
),
|
||||
],
|
||||
}),
|
||||
h(lib.ErrorMessage, null, { default: () => "请至少选择一项" }),
|
||||
],
|
||||
},
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
assert(html.includes('role="grid"'), "grid role on the list");
|
||||
assert(html.includes('aria-label="分类"'), "grid carries the group label");
|
||||
assert(html.includes('aria-multiselectable="true"'), "multiple selection flag");
|
||||
assert(html.includes('role="row"'), "rows for tags");
|
||||
assert(html.includes('aria-selected="true"'), "accepted selection");
|
||||
assert(html.includes('aria-disabled="true"'), "disabled tag");
|
||||
assert(html.includes("Remove tag 资讯"), "composed remove button name");
|
||||
assert(html.includes('data-slot="tag-remove-button"'), "remove button slot");
|
||||
assert(html.includes('data-slot="error-message"'), "error message slot");
|
||||
assert(html.includes('slot="errorMessage"'), "baseline error message marker");
|
||||
|
||||
const css = readFileSync(
|
||||
"node_modules/@heroui-vue/styles/dist/styles.css",
|
||||
"utf8",
|
||||
);
|
||||
for (const rule of [
|
||||
".hv-tag",
|
||||
".hv-tag--sm",
|
||||
".hv-tag--lg",
|
||||
".hv-tag--surface",
|
||||
".hv-tag__remove-button",
|
||||
".hv-tag-group",
|
||||
".hv-tag-group__list",
|
||||
".hv-error-message",
|
||||
])
|
||||
assert(css.includes(rule), `missing CSS rule ${rule}`);
|
||||
// The list padding rule must survive minification for Description/ErrorMessage.
|
||||
assert(
|
||||
/\.hv-tag-group\s*\[data-slot=["']?error-message/.test(css),
|
||||
"missing tag-group error-message padding rule",
|
||||
);
|
||||
|
||||
assert.equal(typeof lib.tagVariants({ size: "sm" }).base, "function");
|
||||
assert(lib.tagVariants({ size: "sm" }).base().includes("hv-tag--sm"));
|
||||
assert(
|
||||
lib.tagVariants({ variant: "surface" }).base().includes("hv-tag--surface"),
|
||||
);
|
||||
assert(lib.errorMessageVariants().includes("hv-error-message"));
|
||||
|
||||
console.log("B03 tag/error-message consumption OK");
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* jsdom lacks parts of the CSSOM. Reka's Presence uses `CSS.escape` when it
|
||||
* resolves exiting children, so tests that dispatch real `animationend` events
|
||||
* need the same capability a browser provides. Only fills the gap; never
|
||||
* overrides an existing implementation.
|
||||
*/
|
||||
type CssEscapeHost = { escape?: (value: string) => string };
|
||||
const cssGlobal = globalThis as unknown as { CSS?: CssEscapeHost };
|
||||
|
||||
if (!cssGlobal.CSS) cssGlobal.CSS = {};
|
||||
|
||||
if (typeof cssGlobal.CSS.escape !== "function") {
|
||||
// CSSOM identifier serialization, including leading digits after a minus,
|
||||
// control characters and the otherwise-invalid single minus identifier.
|
||||
const escapeIdentifier = (value: string) => {
|
||||
const input = String(value);
|
||||
let output = "";
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const char = input[index];
|
||||
const code = input.charCodeAt(index);
|
||||
if (code === 0) {
|
||||
output += "\uFFFD";
|
||||
} else if (
|
||||
(code >= 1 && code <= 0x1f) ||
|
||||
code === 0x7f ||
|
||||
(code >= 0x30 &&
|
||||
code <= 0x39 &&
|
||||
(index === 0 || (index === 1 && input[0] === "-")))
|
||||
) {
|
||||
output += `\\${code.toString(16)} `;
|
||||
} else if (index === 0 && code === 0x2d && input.length === 1) {
|
||||
output += "\\-";
|
||||
} else if (
|
||||
code >= 0x80 ||
|
||||
code === 0x2d ||
|
||||
code === 0x5f ||
|
||||
(code >= 0x30 && code <= 0x39) ||
|
||||
(code >= 0x41 && code <= 0x5a) ||
|
||||
(code >= 0x61 && code <= 0x7a)
|
||||
) {
|
||||
output += char;
|
||||
} else {
|
||||
output += `\\${char}`;
|
||||
}
|
||||
}
|
||||
return output;
|
||||
};
|
||||
cssGlobal.CSS.escape = escapeIdentifier;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** jsdom has no Element.scrollTo. Supply only the method used by VueUse;
|
||||
* geometry and visible-window assertions still belong to real browser checks.
|
||||
* Set up each test realm explicitly so probes work alone and in any order. */
|
||||
if (
|
||||
typeof Element !== "undefined" &&
|
||||
typeof Element.prototype.scrollTo !== "function"
|
||||
) {
|
||||
Element.prototype.scrollTo = () => {};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user