fix: retain pending Toast and Table fidelity corrections

This commit is contained in:
maoyingjie
2026-10-25 21:24:09 +08:00
parent 2ce80b17da
commit a2ca6ed0b8
42 changed files with 2153 additions and 260 deletions
+288
View File
@@ -0,0 +1,288 @@
import { afterEach, expect, it } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, ref } from "vue";
import {
Table,
TableContent,
TableBody,
TableCollection,
TableRow,
TableCell,
ToastProvider,
ToastQueue,
createToastFunction,
ToastContent,
ToastTitle,
ToastDescription,
} from "../packages/vue/src";
const cleanup: (() => void)[] = [];
afterEach(() => {
cleanup
.splice(0)
.reverse()
.forEach((fn) => fn());
document.body.innerHTML = "";
});
it("TableBody preserves a populated TableCollection when #empty is supplied", () => {
const w = mount(
defineComponent({
setup: () => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{},
{
default: () =>
h(
TableCollection,
{ items: ["A"] },
{
default: ({ item }: { item: string }) =>
h(TableRow, { rowKey: item }, () =>
h(TableCell, {}, () => item),
),
},
),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
}),
);
cleanup.push(() => w.unmount());
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
expect(w.find('[data-test="empty"]').exists()).toBe(false);
});
it("Toast root follows explicit Title and Description ids", async () => {
const q = new ToastQueue();
cleanup.push(() => q.destroy());
const toast = createToastFunction(q);
const w = mount(
defineComponent({
setup: () => () =>
h(
ToastProvider,
{ queue: q, to: "body" },
{
default: () =>
h(ToastContent, {}, () => [
h(ToastTitle, { id: "custom-title" }, () => "Title"),
h(
ToastDescription,
{ id: "custom-description" },
() => "Description",
),
]),
},
),
}),
{ attachTo: document.body },
);
cleanup.push(() => w.unmount());
toast("Title", { timeout: 0 });
await flushPromises();
const root = document.querySelector('[data-slot="toast"]')!;
expect(root.getAttribute("aria-labelledby")).toBe("custom-title");
expect(root.getAttribute("aria-describedby")).toBe("custom-description");
});
it("title-only Toast does not reference a nonexistent description", async () => {
const q = new ToastQueue();
cleanup.push(() => q.destroy());
const toast = createToastFunction(q);
const w = mount(ToastProvider, {
props: { queue: q, to: "body" },
attachTo: document.body,
});
cleanup.push(() => w.unmount());
toast("Title only", { timeout: 0 });
await flushPromises();
const root = document.querySelector('[data-slot="toast"]')!;
const refs = (root.getAttribute("aria-describedby") ?? "")
.split(/\s+/)
.filter(Boolean);
for (const id of refs) expect(document.getElementById(id)).not.toBeNull();
});
it("Toast part ids react to later id attribute changes", async () => {
const title = ref("title-before");
const description = ref("description-before");
const q = new ToastQueue();
cleanup.push(() => q.destroy());
const w = mount(
defineComponent({
setup: () => () =>
h(
ToastProvider,
{ queue: q, to: "body" },
{
default: () =>
h(ToastContent, {}, () => [
h(ToastTitle, { id: title.value }, () => "Title"),
h(
ToastDescription,
{ id: description.value },
() => "Description",
),
]),
},
),
}),
{ attachTo: document.body },
);
cleanup.push(() => w.unmount());
createToastFunction(q)("Title", { timeout: 0 });
await flushPromises();
title.value = "title-after";
description.value = "description-after";
await flushPromises();
const root = document.querySelector('[data-slot="toast"]')!;
expect(root.querySelector('[data-slot="toast-title"]')?.id).toBe(
"title-after",
);
expect(root.getAttribute("aria-labelledby")).toBe("title-after");
expect(root.querySelector('[data-slot="toast-description"]')?.id).toBe(
"description-after",
);
expect(root.getAttribute("aria-describedby")).toBe("description-after");
});
it("wrapped collection transitions back to empty without swallowing its future rows", async () => {
const items = ref<string[]>(["A"]);
const Rows = defineComponent({
name: "Rows",
setup: () => () =>
h(
TableCollection,
{ items: items.value },
{
default: ({ item }: { item: string }) =>
h(TableRow, { rowKey: item }, () => h(TableCell, {}, () => item)),
},
),
});
const w = mount(
defineComponent({
setup: () => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{},
{
default: () => h(Rows),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
}),
);
cleanup.push(() => w.unmount());
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
items.value = [];
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
expect(w.find('[data-test="empty"]').exists()).toBe(true);
items.value = ["B"];
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
expect(w.find('[data-test="empty"]').exists()).toBe(false);
});
it("forced empty state does not expose existing data rows", async () => {
const w = mount(
defineComponent({
setup: () => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{ empty: true },
{
default: () =>
h(TableRow, { rowKey: "A" }, () =>
h(TableCell, {}, () => "A"),
),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
}),
);
cleanup.push(() => w.unmount());
await flushPromises();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
});
it("observes native rows rendered by an anonymous wrapper as data changes", async () => {
const items = ref<string[]>([]);
const Rows = () =>
items.value.map((item) => h("tr", { key: item }, [h("td", item)]));
const w = mount(
defineComponent({
setup: () => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{},
{
default: () => h(Rows),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
}),
);
cleanup.push(() => w.unmount());
await flushPromises();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
items.value = ["A"];
await flushPromises();
expect(w.find('[data-test="empty"]').exists()).toBe(false);
expect(w.find("tbody").text()).toBe("A");
items.value = [];
await flushPromises();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
});
it("switches forced empty off and restores the data row", async () => {
const empty = ref(false);
const w = mount(
defineComponent({
setup: () => () =>
h(Table, {}, () =>
h(TableContent, { selectionMode: "multiple" }, () =>
h(
TableBody,
{ empty: empty.value },
{
default: () =>
h(TableRow, { rowKey: "A" }, () =>
h(TableCell, {}, () => "A"),
),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
}),
);
cleanup.push(() => w.unmount());
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
empty.value = true;
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
expect(w.find('[data-test="empty"]').exists()).toBe(true);
empty.value = false;
await flushPromises();
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
expect(w.find('[data-test="empty"]').exists()).toBe(false);
});
+444
View File
@@ -0,0 +1,444 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, ref, nextTick, computed } from "vue";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
EmptyState,
Table,
TableBody,
TableCell,
TableColumn,
TableCollection,
TableContent,
TableHeader,
TableRow,
ToastActionButton,
ToastCloseButton,
ToastContent,
ToastDescription,
ToastIndicator,
ToastProvider,
ToastQueue,
ToastTitle,
createToastFunction,
} from "../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
const queues: ToastQueue[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
queues.splice(0).forEach((q) => q.destroy());
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
vi.useRealTimers();
document.body.innerHTML = "";
});
function mountDemo(setup: () => unknown, render?: () => unknown) {
const w = mount(
defineComponent(
render
? { setup: setup as never, render: render as never }
: { setup: setup as never },
),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
it("TableBody #empty renders EmptyState without a data row", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, { "aria-label": "空表格" }, () => [
h(TableHeader, {}, () => h(TableColumn, {}, () => "姓名")),
h(
TableBody,
{ colspan: 1 },
{
empty: () =>
h(EmptyState, {}, () =>
h("span", { class: "msg" }, "未找到结果"),
),
},
),
]),
),
);
const body = w.get("tbody");
expect(body.attributes("data-empty")).toBeDefined();
expect(w.findAll("tr[data-slot='table-row']").length).toBe(0);
expect(w.find(".msg").text()).toBe("未找到结果");
expect(w.find("td[data-slot='table-empty-cell']").attributes("colspan")).toBe(
"1",
);
// Presentation row must not look like a selectable data row.
expect(w.find("tr[data-slot='table-empty-row']").attributes("role")).toBe(
"presentation",
);
expect(
w.find("tr[data-slot='table-empty-row']").attributes("aria-selected"),
).toBeUndefined();
});
it("TableBody keeps data rows when present and ignores #empty", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () => [
h(
TableBody,
{},
{
default: () =>
h(TableRow, { rowKey: "1" }, () => h(TableCell, {}, () => "A")),
empty: () => h("span", { class: "msg" }, "未找到结果"),
},
),
]),
),
);
expect(w.find(".msg").exists()).toBe(false);
expect(w.findAll("tr[data-slot='table-row']").length).toBe(1);
expect(w.get("tbody").attributes("data-empty")).toBeUndefined();
});
it("select-all checkbox supports indeterminate and shows 全部 when complete", async () => {
const users = [
{ id: "1", name: "Kate" },
{ id: "2", name: "John" },
{ id: "3", name: "Sara" },
];
const selectedKeys = ref<string[]>([]);
const w = mountDemo(
() => {
const allChecked = computed(
() => users.length > 0 && selectedKeys.value.length === users.length,
);
const someChecked = computed(
() => selectedKeys.value.length > 0 && !allChecked.value,
);
return {
selectedKeys,
allChecked,
someChecked,
users,
};
},
function (this: {
selectedKeys: string[];
allChecked: boolean;
someChecked: boolean;
users: typeof users;
}) {
return h("div", [
h(Checkbox, {
ariaLabel: "全选",
isSelected: this.allChecked,
isIndeterminate: this.someChecked,
"onUpdate:checked": () => {
this.selectedKeys = this.allChecked
? []
: this.users.map((u) => u.id);
},
}),
h(
"p",
{ class: "summary" },
this.allChecked
? "全部"
: this.selectedKeys.length
? this.selectedKeys.join(", ")
: "无",
),
]);
},
);
expect(w.find(".summary").text()).toBe("无");
const input = w.get("input");
expect(input.element.indeterminate).toBe(false);
selectedKeys.value = ["1"];
await nextTick();
expect(w.find(".summary").text()).toBe("1");
expect(w.get("input").element.indeterminate).toBe(true);
selectedKeys.value = ["1", "2", "3"];
await nextTick();
expect(w.find(".summary").text()).toBe("全部");
expect(w.get("input").element.indeterminate).toBe(false);
expect(w.get("input").element.checked).toBe(true);
});
it("row checkbox click does not also toggle row selection", async () => {
const selectionChanges: unknown[] = [];
const w = mountDemo(
() => ({ selectionChanges }),
function (this: { selectionChanges: unknown[] }) {
return h(Table, {}, () =>
h(
TableContent,
{
selectionMode: "multiple",
onSelectionChange: (keys: unknown) =>
this.selectionChanges.push(keys),
},
() =>
h(TableBody, {}, () =>
h(
TableRow,
{ rowKey: "1" },
{
default: () => [
h(TableCell, {}, () =>
h(
Checkbox,
{},
{
default: () => [
h(
CheckboxContent,
{},
{
default: () => [
h(CheckboxControl, {}, () =>
h(CheckboxIndicator),
),
],
},
),
],
},
),
),
h(TableCell, {}, () => "Kate"),
],
},
),
),
),
);
},
);
const label = w.get("label[data-slot='checkbox-content']");
await label.trigger("click");
await nextTick();
// Clicking the choice control must not bubble into row selection.
expect(
(w.vm as unknown as { selectionChanges: unknown[] }).selectionChanges,
).toEqual([]);
});
it("toast root is alertdialog with title/description ids and content role=alert", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
const w = mountDemo(
() => ({ queue }),
() =>
h(
ToastProvider,
{ queue: queue as never, to: "body" },
{
default: ({
toast: item,
close,
}: {
toast: { title: string; description: string };
close: () => void;
}) =>
h(ToastContent, {}, () => [
h(ToastTitle, () => item.title),
h(ToastDescription, () => item.description),
h(ToastActionButton, { onClick: () => close() }, () => "忽略"),
h(ToastCloseButton, { onClick: () => close() }),
]),
},
),
);
toast("您已被邀请加入团队", {
description: "Bob 邀请您加入 HeroUI 团队",
timeout: 0,
});
await flushPromises();
await nextTick();
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
expect(root).toBeTruthy();
expect(root.getAttribute("role")).toBe("alertdialog");
expect(root.getAttribute("aria-modal")).toBe("false");
const title = root.querySelector('[data-slot="toast-title"]') as HTMLElement;
const desc = root.querySelector(
'[data-slot="toast-description"]',
) as HTMLElement;
expect(title.id).toBeTruthy();
expect(desc.id).toBeTruthy();
expect(root.getAttribute("aria-labelledby")).toBe(title.id);
expect(root.getAttribute("aria-describedby")).toBe(desc.id);
const content = root.querySelector(
'[data-slot="toast-content"]',
) as HTMLElement;
expect(content.getAttribute("role")).toBe("alert");
expect(content.getAttribute("aria-atomic")).toBe("true");
// After mount the alert payload is visible so it can be announced.
await nextTick();
expect(content.getAttribute("aria-hidden")).not.toBe("true");
// Close button keeps an accessible name.
const close = root.querySelector("[data-slot='toast-close']");
expect(close?.getAttribute("aria-label")).toBeTruthy();
void w;
});
it("toast indicator sets data-swapped only after the first paint", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
mountDemo(
() => ({ queue }),
() =>
h(
ToastProvider,
{ queue: queue as never, to: "body" },
{
default: ({
toast: item,
}: {
toast: { title: string; isLoading?: boolean; variant?: string };
}) =>
h(ToastContent, {}, () => [
h(ToastTitle, () => item.title),
h(
ToastIndicator,
{ variant: (item.variant ?? "default") as never },
item.isLoading
? () => h("span", { "data-slot": "spinner" })
: undefined,
),
]),
},
),
);
const loadingId = toast("正在上传文件…", { isLoading: true, timeout: 0 });
await flushPromises();
await nextTick();
const indicator = () =>
document.querySelector('[data-slot="toast-indicator"]') as HTMLElement;
expect(indicator().getAttribute("data-swapped")).toBeNull();
toast.update(loadingId, "文件已上传", {
isLoading: false,
variant: "success",
timeout: 0,
});
await flushPromises();
await nextTick();
expect(indicator().getAttribute("data-swapped")).toBe("true");
});
it("column defaultWidth 1fr does not write an invalid CSS width", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, { id: "name", defaultWidth: "1fr" }, () => "姓名"),
),
),
),
);
const th = w.get("th");
expect((th.element as HTMLElement).style.width).toBe("");
expect(th.attributes("data-default-width")).toBe("1fr");
});
it("tree column cell gets data-tree-column and row level variable", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, { treeColumn: "name" }, () => [
h(TableHeader, {}, () =>
h(TableColumn, { id: "name" }, () => "姓名"),
),
h(TableBody, {}, () =>
h(TableRow, { rowKey: "1", level: 2, hasChildItems: true }, () =>
h(TableCell, {}, () => "文档"),
),
),
]),
),
);
const tr = w.get("tr[data-slot='table-row']");
expect(tr.attributes("data-level")).toBe("2");
expect(
(tr.element as HTMLElement).style.getPropertyValue("--table-row-level"),
).toBe("2");
const td = w.get("td[data-slot='table-cell']");
expect(td.attributes("data-tree-column")).toBeDefined();
});
it("TableCollection empty ↔ non-empty toggles the empty slot", async () => {
const items = ref<string[]>([]);
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{ colspan: 1 },
{
default: () =>
h(
TableCollection,
{ items: items.value },
{
default: ({ item }: { item: string }) =>
h(TableRow, { rowKey: item }, () =>
h(TableCell, {}, () => item),
),
},
),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
);
expect(w.find('[data-test="empty"]').exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
items.value = ["A", "B"];
await nextTick();
expect(w.find('[data-test="empty"]').exists()).toBe(false);
expect(w.findAll('[data-slot="table-row"]').length).toBe(2);
items.value = [];
await nextTick();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
});
it("title-only toast omits aria-describedby when no description part exists", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
mountDemo(
() => ({ queue }),
() => h(ToastProvider, { queue: queue as never, to: "body" }),
);
toast("标题独占", { timeout: 0 });
await flushPromises();
await nextTick();
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
const refs = (root.getAttribute("aria-describedby") ?? "")
.split(/\s+/)
.filter(Boolean);
expect(refs.length).toBe(0);
const labelled = root.getAttribute("aria-labelledby");
expect(labelled && document.getElementById(labelled)).toBeTruthy();
});