Files
heroui-vue/tests/tag-error-message.test.ts
T

1379 lines
42 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { afterEach, describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
import { mount } from "@vue/test-utils";
import { createApp, defineComponent, h, nextTick, ref } from "vue";
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
TagRemoveButton,
} from "../packages/vue/src";
type Item = { id: string | number; label: string; disabled?: boolean };
type Mounted = ReturnType<typeof mount>;
// Each case queries inside its own root: a shared document hides ordering bugs.
const wrappers: Mounted[] = [];
/** Vue skips an invoker when the event timestamp is not newer than the listener
* attachment time (`e._vts <= invoker.attached`). Synthetic dispatch inside the
* same millisecond is ignored, so move past that millisecond first. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 2));
async function mountGroup(
options: {
tags?: Item[];
props?: Record<string, unknown>;
groupProps?: Record<string, unknown>;
slots?: Record<string, unknown>;
content?: (item: Item) => unknown;
} = {},
) {
const tags = options.tags ?? [
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行" },
{ id: "gaming", label: "游戏" },
];
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(
TagGroup,
{ selectionMode: "single", "aria-label": "分类", ...options.props },
{
default: () => [
h(TagGroupList, options.groupProps ?? {}, {
default: () => [
...tags.map((tag) =>
h(
Tag,
{ id: tag.id, key: tag.id, isDisabled: tag.disabled },
{
default: () =>
options.content ? options.content(tag) : tag.label,
},
),
),
...(((options.slots?.default as unknown[]) ??
[]) as never[]),
],
}),
],
},
);
},
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
return wrapper;
}
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 row = (label: string) =>
queryAll('[data-slot="tag"]').find(
(element) => element.textContent?.replace(/\s+/g, "") === label,
);
afterEach(async () => {
// Unmount through Vue so the registry/focus cleanup runs; never yank the DOM
// out from under a live tree.
while (wrappers.length) wrappers.pop()?.unmount();
await nextTick();
await settle();
vi.restoreAllMocks();
});
describe("TagGroup structure", () => {
it("exposes the baseline data-slots and BEM blocks", async () => {
await mountGroup();
const root = queryOne('[data-slot="tag-group"]')!;
const list = queryOne('[data-slot="tag-group-list"]')!;
expect(root.className).toContain("hv-tag-group");
expect(root.className).not.toContain("hv-tag-group__list");
expect(list.className).toContain("hv-tag-group__list");
expect(list.className).not.toContain("hv-tag-group ");
expect(queryAll('[data-slot="tag"]')).toHaveLength(3);
});
it("renders each tag as a row inside the grid", async () => {
await mountGroup();
const list = queryOne('[data-slot="tag-group-list"]')!;
expect(list.getAttribute("role")).toBe("grid");
expect(list.getAttribute("aria-label")).toBe("分类");
expect(list.getAttribute("aria-atomic")).toBe("false");
expect(list.getAttribute("aria-relevant")).toBe("additions text");
const rows = [...list.querySelectorAll('[data-slot="tag"]')];
expect(rows.map((element) => element.getAttribute("role"))).toEqual([
"row",
"row",
"row",
]);
expect(rows.map((element) => element.textContent?.trim())).toEqual([
"资讯",
"旅行",
"游戏",
]);
});
it("names the grid from Label and describes it with Description and ErrorMessage", async () => {
const named = mount(TagGroup, {
props: { selectionMode: "single" },
slots: {
default: () => [
h(Label, () => "设施"),
h(TagGroupList, null, {
default: () => [h(Tag, { id: "pool" }, () => "游泳池")],
}),
h(Description, () => "可多选"),
h(ErrorMessage, () => "请选择一个设施"),
],
},
attachTo: document.body,
});
wrappers.push(named);
await nextTick();
await settle();
const list = queryOne('[data-slot="tag-group-list"]')!;
const label = queryOne('[data-slot="label"]')!;
const description = queryOne('[data-slot="description"]')!;
const error = queryOne('[data-slot="error-message"]')!;
expect(list.getAttribute("aria-label")).toBeNull();
expect(list.getAttribute("aria-labelledby")).toBe(label.id);
expect(label.tagName).toBe("SPAN");
expect(list.getAttribute("aria-describedby")).toContain(description.id);
expect(list.getAttribute("aria-describedby")).toContain(error.id);
expect(error.className).toContain("hv-error-message");
expect(error.getAttribute("slot")).toBe("errorMessage");
});
it("applies group size and variant to every tag", async () => {
await mountGroup({ props: { size: "lg", variant: "surface" } });
const rows = [...queryAll('[data-slot="tag"]')];
for (const element of rows) {
expect(element.className).toContain("hv-tag--lg");
expect(element.className).toContain("hv-tag--surface");
}
});
it("keeps caller class, attrs and listeners on the semantic nodes", async () => {
const onClick = vi.fn();
const caller = mount(TagGroup, {
props: { selectionMode: "none", class: "caller", onClick },
attrs: { "data-test": "group" },
slots: {
default: () => [
h(
TagGroupList,
{ class: "list-caller" },
{
default: () => [
h(Tag, { id: "a", class: "tag-caller" }, () => "A"),
],
},
),
],
},
attachTo: document.body,
});
wrappers.push(caller);
await nextTick();
await settle();
const root = queryOne('[data-slot="tag-group"]')!;
const list = queryOne('[data-slot="tag-group-list"]')!;
const tag = queryOne('[data-slot="tag"]')!;
expect(root.className).toContain("hv-tag-group");
expect(root.className).toContain("caller");
expect(root.getAttribute("data-test")).toBe("group");
expect(list.className).toContain("hv-tag-group__list");
expect(list.className).toContain("list-caller");
expect(tag.className).toContain("hv-tag");
expect(tag.className).toContain("tag-caller");
expect(tag.getAttribute("aria-selected")).toBeNull();
tag.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onClick).toHaveBeenCalledTimes(1);
});
});
describe("TagGroup selection", () => {
it("toggles a single selection and reflects it in ARIA and data attributes", async () => {
const onUpdate = vi.fn();
await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
const news = row("资讯")!;
expect(news.getAttribute("aria-selected")).toBe("false");
expect(news.hasAttribute("data-selected")).toBe(false);
news.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onUpdate).toHaveBeenCalledTimes(1);
expect(onUpdate.mock.calls[0][0]).toEqual(["news"]);
expect(news.getAttribute("aria-selected")).toBe("true");
expect(news.getAttribute("data-selected")).toBe("true");
});
it("clears a single selection on a second activation", async () => {
const selected = ref<string[]>(["news"]);
const Demo = defineComponent({
setup() {
return () =>
h(
TagGroup,
{
"aria-label": "分类",
selectionMode: "single",
modelValue: selected.value,
"onUpdate:modelValue": (keys: (string | number)[]) => {
selected.value = keys as string[];
},
},
{
default: () => [
h(TagGroupList, null, {
default: () => [
h(
Tag,
{ id: "news", key: "news" },
{ default: () => "资讯" },
),
h(
Tag,
{ id: "travel", key: "travel" },
{ default: () => "旅行" },
),
],
}),
],
},
);
},
});
const wrapper = mount(Demo, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(selected.value).toEqual([]);
expect(row("资讯")!.getAttribute("aria-selected")).toBe("false");
});
it("honours disallowEmptySelection", async () => {
const onUpdate = vi.fn();
await mountGroup({
props: {
modelValue: ["news"],
disallowEmptySelection: true,
"onUpdate:modelValue": onUpdate,
},
});
row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onUpdate).not.toHaveBeenCalled();
expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
});
it("accumulates multiple selection and marks the grid multiselectable", async () => {
const onUpdate = vi.fn();
await mountGroup({
props: { selectionMode: "multiple", "onUpdate:modelValue": onUpdate },
});
const list = queryOne('[data-slot="tag-group-list"]')!;
expect(list.getAttribute("aria-multiselectable")).toBe("true");
row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onUpdate.mock.calls.at(-1)?.[0]).toEqual(["news", "travel"]);
expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
expect(row("旅行")!.getAttribute("aria-selected")).toBe("true");
});
it("keeps the accepted value when the parent rejects the proposal", async () => {
const onUpdate = vi.fn();
await mountGroup({
props: { modelValue: [], "onUpdate:modelValue": onUpdate },
});
row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await nextTick();
expect(onUpdate).toHaveBeenCalledWith(["travel"]);
expect(row("旅行")!.getAttribute("aria-selected")).toBe("false");
});
it("accepts a rejected proposal again after the parent starts accepting", async () => {
const accepted = ref<string[] | null>(null);
const Demo = defineComponent({
setup() {
return () =>
h(
TagGroup,
{
selectionMode: "single",
"aria-label": "分类",
modelValue: accepted.value ?? [],
"onUpdate:modelValue": (keys: (string | number)[]) => {
if (accepted.value !== null) accepted.value = keys as string[];
},
},
{
default: () => [
h(TagGroupList, null, {
default: () => [
h(Tag, { id: "news" }, () => "资讯"),
h(Tag, { id: "travel" }, () => "旅行"),
],
}),
],
},
);
},
});
const wrapper = mount(Demo, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(row("旅行")!.getAttribute("aria-selected")).toBe("false");
accepted.value = [];
await nextTick();
row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(row("旅行")!.getAttribute("aria-selected")).toBe("true");
});
it("disables keys and individual tags without selecting them", async () => {
const onUpdate = vi.fn();
await mountGroup({
tags: [
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行", disabled: true },
{ id: "gaming", label: "游戏" },
],
props: {
disabledKeys: ["gaming"],
"onUpdate:modelValue": onUpdate,
},
});
expect(row("旅行")!.getAttribute("aria-disabled")).toBe("true");
expect(row("旅行")!.getAttribute("data-disabled")).toBe("true");
expect(row("游戏")!.getAttribute("aria-disabled")).toBe("true");
expect(row("资讯")!.hasAttribute("aria-disabled")).toBe(false);
row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
row("游戏")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onUpdate).not.toHaveBeenCalled();
});
it("disables the whole group", async () => {
const onUpdate = vi.fn();
await mountGroup({
props: { isDisabled: true, "onUpdate:modelValue": onUpdate },
});
for (const label of ["资讯", "旅行", "游戏"])
expect(row(label)!.getAttribute("aria-disabled")).toBe("true");
row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onUpdate).not.toHaveBeenCalled();
});
});
describe("TagGroup removal", () => {
it("renders a default remove button only when removal is allowed", async () => {
await mountGroup();
expect(queryOne('[data-slot=\"tag-remove-button\"]')).toBeNull();
await mountGroup({ props: { onRemove: vi.fn() } });
const buttons = [...queryAll('[data-slot="tag-remove-button"]')];
expect(buttons).toHaveLength(3);
expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯");
expect(buttons[0].tagName).toBe("BUTTON");
expect(buttons[0].getAttribute("type")).toBe("button");
});
it("requests removal without changing the selection", async () => {
const onRemove = vi.fn();
const onUpdate = vi.fn();
await mountGroup({ props: { onRemove, "onUpdate:modelValue": onUpdate } });
queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent(
new MouseEvent("click", { bubbles: true }),
);
await nextTick();
expect(onRemove).toHaveBeenCalledTimes(1);
expect(onRemove.mock.calls[0][0]).toEqual(["travel"]);
expect(onUpdate).not.toHaveBeenCalled();
});
it("replaces the default button with a custom TagRemoveButton", async () => {
const onRemove = vi.fn();
const custom = mount(TagGroup, {
props: { selectionMode: "single", "aria-label": "分类", onRemove },
slots: {
default: () => [
h(TagGroupList, null, {
default: () => [
h(
Tag,
{ id: "news" },
{
default: () => [
"资讯",
h(
TagRemoveButton,
{ "data-test": "custom" },
{ default: () => h("span", "×") },
),
],
},
),
],
}),
],
},
attachTo: document.body,
});
wrappers.push(custom);
await nextTick();
await settle();
const buttons = [...queryAll('[data-slot="tag-remove-button"]')];
expect(buttons).toHaveLength(1);
expect(buttons[0].getAttribute("data-test")).toBe("custom");
expect(buttons[0].textContent).toBe("×");
expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯");
buttons[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onRemove).toHaveBeenCalledWith(["news"]);
});
it("removes the focused tag with Delete and Backspace", async () => {
const onRemove = vi.fn();
await mountGroup({ props: { onRemove } });
row("旅行")!.focus();
await nextTick();
row("旅行")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
);
await nextTick();
expect(onRemove).toHaveBeenLastCalledWith(["travel"]);
row("旅行")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Backspace", bubbles: true }),
);
await nextTick();
expect(onRemove).toHaveBeenCalledTimes(2);
expect(onRemove).toHaveBeenLastCalledWith(["travel"]);
});
it("moves focus to the next neighbour after a confirmed removal", async () => {
const tags = ref<Item[]>([
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行" },
{ id: "gaming", label: "游戏" },
]);
const Demo = defineComponent({
setup() {
return () =>
h(
TagGroup,
{
"aria-label": "分类",
onRemove: (keys: (string | number)[]) => {
tags.value = tags.value.filter((tag) => !keys.includes(tag.id));
},
},
{
default: () => [
h(TagGroupList, null, {
default: () =>
tags.value.map((tag) =>
h(
Tag,
{ id: tag.id, key: tag.id },
{ default: () => tag.label },
),
),
}),
],
},
);
},
});
const wrapper = mount(Demo, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
row("旅行")!.focus();
await nextTick();
document
.querySelectorAll<HTMLElement>('[data-slot="tag-remove-button"]')[1]
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await nextTick();
expect(row("旅行")).toBeUndefined();
expect(document.activeElement).toBe(row("游戏"));
});
it("moves focus to the neighbour after removing through the button", async () => {
const tags = ref<Item[]>([
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行" },
{ id: "gaming", label: "游戏" },
]);
const Demo = defineComponent({
setup() {
return () =>
h(
TagGroup,
{
"aria-label": "分类",
onRemove: (keys: (string | number)[]) => {
tags.value = tags.value.filter((tag) => !keys.includes(tag.id));
},
},
{
default: () => [
h(TagGroupList, null, {
default: () =>
tags.value.map((tag) =>
h(
Tag,
{ id: tag.id, key: tag.id },
{ default: () => tag.label },
),
),
}),
],
},
);
},
});
const wrapper = mount(Demo, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent(
new MouseEvent("click", { bubbles: true }),
);
await nextTick();
await nextTick();
expect(row("旅行")).toBeUndefined();
expect(document.activeElement).toBe(row("游戏"));
});
it("focuses the grid when the last tag is removed", async () => {
const tags = ref<Item[]>([{ id: "news", label: "资讯" }]);
const Demo = defineComponent({
setup() {
return () =>
h(
TagGroup,
{
"aria-label": "分类",
onRemove: () => {
tags.value = [];
},
},
{
default: () => [
h(TagGroupList, null, {
default: () =>
tags.value.map((tag) =>
h(
Tag,
{ id: tag.id, key: tag.id },
{ default: () => tag.label },
),
),
}),
],
},
);
},
});
const wrapper = mount(Demo, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
row("资讯")!.focus();
await nextTick();
document
.querySelector<HTMLElement>('[data-slot="tag-remove-button"]')!
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await nextTick();
const list = queryOne('[data-slot="tag-group-list"]')!;
expect(list.children).toHaveLength(0);
expect(list.getAttribute("tabindex")).toBe("0");
expect(document.activeElement).toBe(list);
});
it("keeps the tag and its focus when the parent rejects the removal", async () => {
const onRemove = vi.fn();
await mountGroup({ props: { onRemove } });
row("旅行")!.focus();
await nextTick();
document
.querySelectorAll<HTMLElement>('[data-slot="tag-remove-button"]')[1]
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await nextTick();
expect(onRemove).toHaveBeenCalledTimes(1);
expect(row("旅行")).toBeDefined();
expect(document.activeElement).toBe(row("旅行"));
row("旅行")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
);
await nextTick();
expect(onRemove).toHaveBeenCalledTimes(2);
});
});
describe("TagGroup keyboard", () => {
it("moves focus with the arrow keys, Home and End and skips disabled tags", async () => {
await mountGroup({
tags: [
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行", disabled: true },
{ id: "gaming", label: "游戏" },
],
});
row("资讯")!.focus();
await nextTick();
expect(document.activeElement).toBe(row("资讯"));
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("游戏"));
row("游戏")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("资讯"));
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "End", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("游戏"));
row("游戏")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("资讯"));
});
it("reverses the horizontal direction in RTL", async () => {
await mountGroup({
props: { dir: "rtl" },
tags: [
{ id: "news", label: "资讯" },
{ id: "travel", label: "旅行" },
{ id: "gaming", label: "游戏" },
],
});
row("资讯")!.focus();
await nextTick();
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("旅行"));
row("旅行")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
);
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("资讯"));
});
it("activates once on the Space key sequence and lets the caller cancel", async () => {
const onUpdate = vi.fn();
await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
row("资讯")!.focus();
await nextTick();
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", {
key: " ",
bubbles: true,
cancelable: true,
}),
);
expect(onUpdate).not.toHaveBeenCalled();
row("资讯")!.dispatchEvent(
new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }),
);
await nextTick();
expect(onUpdate).toHaveBeenCalledTimes(1);
const cancel = (event: Event) => event.preventDefault();
const list = queryOne('[data-slot="tag-group-list"]')!;
list.addEventListener("keyup", cancel, true);
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", {
key: " ",
bubbles: true,
cancelable: true,
}),
);
row("资讯")!.dispatchEvent(
new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }),
);
await nextTick();
list.removeEventListener("keyup", cancel, true);
expect(onUpdate).toHaveBeenCalledTimes(1);
});
it("activates with Enter once", async () => {
const onUpdate = vi.fn();
await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
row("旅行")!.focus();
await nextTick();
row("旅行")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),
);
await nextTick();
expect(onUpdate).toHaveBeenCalledTimes(1);
expect(onUpdate).toHaveBeenCalledWith(["travel"]);
});
});
describe("TagGroupList items", () => {
it("renders data items in order and keys them by id", async () => {
const items = [
{ id: "a", name: "A" },
{ id: 2, name: "B" },
{ id: "b", name: "C" },
];
const wrapper = mount(TagGroup, {
props: { "aria-label": "分类" },
slots: {
default: () => [
h(
TagGroupList,
{ items },
{
default: ({
item,
}: {
item: { id: string | number; name: string };
}) => h(Tag, { id: item.id, key: item.id }, () => item.name),
},
),
],
},
attachTo: document.body,
});
wrappers.push(wrapper);
await nextTick();
await settle();
expect(queryAll('[data-slot="tag"]').map((tag) => tag.textContent)).toEqual(
["A", "B", "C"],
);
});
it("renders the empty slot when items is empty", async () => {
const wrapper = mount(TagGroup, {
props: { "aria-label": "分类" },
slots: {
default: () => [
h(
TagGroupList,
{ items: [] as { id: string }[] },
{
default: () => [],
empty: () => h("p", { "data-test": "empty" }, "暂无标签"),
},
),
],
},
attachTo: document.body,
});
wrappers.push(wrapper);
await nextTick();
await settle();
expect(queryAll('[data-slot="tag"]')).toHaveLength(0);
expect(queryOne('[data-test="empty"]')).not.toBeNull();
});
it("rejects duplicate collection keys", async () => {
const errors: string[] = [];
const app = createApp({
render: () =>
h(
TagGroup,
{ "aria-label": "分类" },
{
default: () => [
h(TagGroupList, null, {
default: () => [
h(Tag, { id: "dup" }, () => "A"),
h(Tag, { id: "dup" }, () => "B"),
],
}),
],
},
),
});
app.config.errorHandler = (error) => {
errors.push(String((error as Error).message));
};
app.config.warnHandler = () => {};
const host = document.createElement("div");
document.body.appendChild(host);
app.mount(host);
await nextTick();
app.unmount();
host.remove();
expect(errors.join(" ")).toMatch(/Duplicate collection key/);
});
it("keeps numeric and string keys distinct", async () => {
const onChange = vi.fn();
await mountGroup({
tags: [
{ id: 0, label: "零" },
{ id: "0", label: "字符串零" },
],
props: { onSelectionChange: onChange },
});
row("零")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
expect(onChange).toHaveBeenCalledWith([0]);
expect(row("字符串零")!.getAttribute("aria-selected")).toBe("false");
});
});
describe("ErrorMessage", () => {
it("renders standalone with baseline markers", async () => {
const wrapper = mount(ErrorMessage, {
slots: { default: () => "出错了" },
attachTo: document.body,
});
wrappers.push(wrapper);
await nextTick();
await settle();
const message = queryOne('[data-slot="error-message"]')!;
expect(message.tagName).toBe("P");
expect(message.className).toContain("hv-error-message");
expect(message.getAttribute("slot")).toBe("errorMessage");
expect(message.textContent).toBe("出错了");
expect(message.id).not.toBe("");
});
it("keeps its own unique id per instance", async () => {
const wrapper = mount(
defineComponent({
setup() {
return () =>
h("div", [
h(ErrorMessage, { key: "a" }, () => "一"),
h(ErrorMessage, { key: "b" }, () => "二"),
]);
},
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const [first, second] = queryAll('[data-slot="error-message"]');
expect(first.id).not.toBe(second.id);
});
});
describe("Tag demos and documentation", () => {
const previews = [
"basic",
"sizes",
"variants",
"disabled",
"selection-modes",
"controlled",
"with-error-message",
"with-list-data",
"with-prefix",
"with-remove-button",
"render-function",
"custom-styles",
];
it("includes every preview from the pinned upstream documents", () => {
const document = readFileSync("apps/docs/components/tag-group.md", "utf8");
const names = [
...document.matchAll(/<ComponentPreview name="tag-group-([^"]+)"/g),
].map((match) => match[1]);
expect(document).not.toContain("[!toc]");
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/tag-group-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).not.toContain("className");
}
const errorDocument = readFileSync(
"apps/docs/components/error-message.md",
"utf8",
);
const errorNames = [
...errorDocument.matchAll(
/<ComponentPreview name="error-message-([^"]+)"/g,
),
].map((match) => match[1]);
expect(errorDocument).not.toContain("[!toc]");
expect(errorNames).toEqual(["basic", "custom-styles"]);
for (const name of errorNames) {
const source = readFileSync(
`apps/docs/demos/error-message-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).not.toContain("className");
}
});
it("uses Tabler icons and library parts in the demos", () => {
for (const name of ["basic", "with-prefix", "custom-styles"]) {
const source = readFileSync(
`apps/docs/demos/tag-group-${name}.vue`,
"utf8",
);
expect(source).toContain("@tabler/icons-vue");
expect(source).not.toContain("@gravity-ui/icons");
expect(source).not.toContain("<path");
}
const remove = readFileSync(
"apps/docs/demos/tag-group-with-remove-button.vue",
"utf8",
);
expect(remove).toContain("TagRemoveButton");
expect(remove).toContain("allowsRemoving");
});
it("documents Vue contracts instead of React ones", () => {
for (const page of ["tag-group", "error-message"]) {
const document = readFileSync(`apps/docs/components/${page}.md`, "utf8");
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
expect(document).toContain("`class`");
expect(document).toContain("Vue class 绑定");
}
const tagGroup = readFileSync("apps/docs/components/tag-group.md", "utf8");
expect(tagGroup).toContain("### TagGroupList");
expect(tagGroup).toContain("### TagRemoveButton");
expect(tagGroup).not.toMatch(/\|\s*`TagGroup\.List`\s*\|/);
expect(tagGroup).not.toMatch(/\|\s*`Tag\.RemoveButton`\s*\|/);
});
it("renders every tag-group demo with the library components", async () => {
const modules = import.meta.glob("../apps/docs/demos/tag-group-*.vue");
const errorModules = import.meta.glob(
"../apps/docs/demos/error-message-*.vue",
);
for (const [path, load] of [
...Object.entries(modules),
...Object.entries(errorModules),
]) {
const demo = (await load()) as { default: { name?: string } };
const wrapper = mount(demo.default, { attachTo: document.body });
wrappers.push(wrapper);
await nextTick();
await settle();
expect(
wrapper.element.querySelectorAll(
'[data-slot="tag"], [data-slot="error-message"]',
).length,
path,
).toBeGreaterThan(0);
}
});
});
describe("B03 review regressions", () => {
it("preserves root/list styles and list-local accessible names", async () => {
await mountGroup({
props: { style: { marginTop: "7px" } },
groupProps: {
style: { paddingTop: "9px" },
"aria-label": "Local tags",
"aria-describedby": "external-help",
},
});
expect(queryOne('[data-slot="tag-group"]')!.style.marginTop).toBe("7px");
const list = queryOne('[role="grid"]')!;
expect(list.style.paddingTop).toBe("9px");
expect(list.getAttribute("aria-label")).toBe("Local tags");
expect(list.getAttribute("aria-describedby")).toContain("external-help");
});
it("does not select or navigate from an embedded input or remove button", async () => {
const update = vi.fn();
const remove = vi.fn();
await mountGroup({
props: { "onUpdate:modelValue": update, onRemove: remove },
content: (item) => [item.label, h("input", { "aria-label": "Edit" })],
});
const input = queryOne("input")!;
input.focus();
for (const key of ["ArrowRight", "Home", "Delete", "Enter", " "]) {
input.dispatchEvent(
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }),
);
input.dispatchEvent(
new KeyboardEvent("keyup", { key, bubbles: true, cancelable: true }),
);
}
await nextTick();
expect(document.activeElement).toBe(input);
expect(update).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
const button = queryOne('[data-slot="tag-remove-button"]')!;
button.focus();
button.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Enter",
bubbles: true,
cancelable: true,
}),
);
await nextTick();
expect(update).not.toHaveBeenCalled();
});
it("disables the remove button of an individually disabled tag", async () => {
await mountGroup({
props: { onRemove: vi.fn() },
tags: [{ id: "a", label: "A", disabled: true }],
});
expect(queryOne<HTMLButtonElement>("button")!.disabled).toBe(true);
});
it("clears a pointer press released outside the row", async () => {
await mountGroup();
const tag = row("资讯")!;
tag.dispatchEvent(
new MouseEvent("pointerdown", { button: 0, bubbles: true }),
);
await nextTick();
expect(tag.hasAttribute("data-pressed")).toBe(true);
document.dispatchEvent(new Event("pointerup", { bubbles: true }));
await nextTick();
expect(tag.hasAttribute("data-pressed")).toBe(false);
});
it("provides gridcell children for every grid row", async () => {
await mountGroup();
for (const tag of queryAll('[role="row"]'))
expect(tag.querySelector('[role="gridcell"]')).not.toBeNull();
});
it("does not steal external focus when a previously focused item is removed", async () => {
const tags = ref([
{ id: "a", label: "A" },
{ id: "b", label: "B" },
]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h("div", [
h("input", { "aria-label": "Outside" }),
h(
TagGroup,
{ "aria-label": "Tags" },
{
default: () =>
h(TagGroupList, null, {
default: () =>
tags.value.map((item) =>
h(Tag, { id: item.id, key: item.id }, () => item.label),
),
}),
},
),
]),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
queryOne('[role="row"]')!.focus();
await nextTick();
const outside = queryOne("input")!;
outside.focus();
await nextTick();
tags.value = tags.value.slice(1);
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(outside);
});
});
describe("B03 composition and removal", () => {
it.each([false, true])(
"keeps the custom row root and grid cell with asChild (component=%s)",
async (component) => {
const Custom = defineComponent({
setup:
(_, { slots }) =>
() =>
h("article", { "data-custom": "row" }, slots.default?.()),
});
const wrapper = mount(TagGroup, {
props: { onRemove: vi.fn(), "aria-label": "Custom" },
slots: {
default: () =>
h(TagGroupList, null, {
default: () =>
h(Tag, { id: "custom", asChild: true }, () =>
component
? h(
Custom,
{ "data-custom": "row" },
{ default: () => "Custom" },
)
: h("article", { "data-custom": "row" }, "Custom"),
),
}),
},
attachTo: document.body,
});
wrappers.push(wrapper);
await nextTick();
await settle();
const tag = queryOne('[data-slot="tag"]')!;
expect(tag.tagName).toBe("ARTICLE");
expect(tag.getAttribute("data-custom")).toBe("row");
expect(tag.getAttribute("role")).toBe("row");
expect(tag.querySelector('[role="gridcell"]')!.textContent).toContain(
"Custom",
);
expect(tag.querySelectorAll("button")).toHaveLength(1);
},
);
it("uses actual neighbour order when disabled rows precede a removed row", async () => {
const items = ref([
{ id: "d", label: "Disabled", disabled: true },
{ id: "a", label: "A" },
{ id: "b", label: "B" },
{ id: "c", label: "C" },
]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
TagGroup,
{
"aria-label": "Tags",
onRemove: (keys: (string | number)[]) => {
items.value = items.value.filter(
(item) => !keys.includes(item.id),
);
},
},
{
default: () =>
h(TagGroupList, null, {
default: () =>
items.value.map((item) =>
h(
Tag,
{
id: item.id,
key: item.id,
isDisabled: item.disabled,
},
() => item.label,
),
),
}),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const tag = row("A")!;
tag.focus();
await nextTick();
tag.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Delete",
bubbles: true,
cancelable: true,
}),
);
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("B"));
expect(queryOne('[role="status"]')!.textContent).toContain("A");
});
it("does not announce removal rejected by the parent", async () => {
await mountGroup({ props: { onRemove: vi.fn() } });
row("资讯")!.focus();
await nextTick();
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
);
await nextTick();
expect(queryOne('[role="status"]')!.textContent).toBe("");
expect(document.activeElement).toBe(row("资讯"));
});
});
describe("B03 native focus regressions", () => {
it("restores after native removal clears focus before the registry updates", async () => {
const items = ref(["A", "B"]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
TagGroup,
{
"aria-label": "Native",
onRemove: (keys: (string | number)[]) => {
(document.activeElement as HTMLElement).blur();
items.value = items.value.filter((key) => !keys.includes(key));
},
},
{
default: () =>
h(TagGroupList, null, {
default: () =>
items.value.map((key) =>
h(Tag, { id: key, key }, () => key),
),
}),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const button = row("A")!.querySelector("button")!;
button.focus();
await nextTick();
button.click();
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("B"));
});
it("keeps one default Tab stop in a removable collection", async () => {
await mountGroup({ props: { onRemove: vi.fn() } });
expect(
queryAll('[role="row"]').filter((el) => el.tabIndex === 0),
).toHaveLength(1);
expect(
queryAll<HTMLButtonElement>("button").every((el) => el.tabIndex === -1),
).toBe(true);
});
});