fix(pickers): rework B02 against the public review
Restore native clearing, unify the form/field protocol with the other choice families (per-key entries, disabled and removed keys omitted, shared form owner), synchronise ComboBox text by key identity, keep filtering out of open composition sessions, and stop stealing focus when a controlled close is rejected. Also merge caller refs/ARIA/disabled, implement asChild, autoFocus and ComboBox variant, use a locale-aware base matcher, and put the indicator class and slot on the icon element the ported CSS selects.
This commit is contained in:
@@ -179,19 +179,20 @@ describe("Autocomplete docs and demos", () => {
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const hidden = [
|
||||
...(wrapper.element as HTMLElement).querySelectorAll<HTMLInputElement>(
|
||||
'input[type="hidden"][name]',
|
||||
),
|
||||
];
|
||||
expect(hidden.map((input) => input.name).sort()).toEqual([
|
||||
"country",
|
||||
"state",
|
||||
]);
|
||||
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 root = wrapper.element as HTMLElement;
|
||||
const form = (root.matches("form") ? root : root.querySelector("form"))!;
|
||||
const form = pickerForm;
|
||||
const submit = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLButtonElement>('button[type="submit"]')!;
|
||||
|
||||
+206
-1
@@ -683,9 +683,11 @@ describe("Autocomplete ported style hooks", () => {
|
||||
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(
|
||||
'[data-slot="autocomplete-indicator"] [data-slot="autocomplete-default-indicator"]',
|
||||
'.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
@@ -693,3 +695,206 @@ describe("Autocomplete ported style hooks", () => {
|
||||
).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,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);
|
||||
});
|
||||
@@ -175,15 +175,45 @@ describe("ComboBox docs and demos", () => {
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const hidden = [
|
||||
...(wrapper.element as HTMLElement).querySelectorAll<HTMLInputElement>(
|
||||
'input[type="hidden"][name]',
|
||||
),
|
||||
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"]'),
|
||||
];
|
||||
expect(hidden.map((input) => input.name).sort()).toEqual([
|
||||
"animal",
|
||||
"animal-text",
|
||||
]);
|
||||
// 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();
|
||||
});
|
||||
|
||||
@@ -713,3 +713,186 @@ describe("ComboBox ported style hooks", () => {
|
||||
).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,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,
|
||||
};
|
||||
Reference in New Issue
Block a user