feat: migrate Toast and Table with reviewed state focus and SSR contracts

This commit is contained in:
maoyingjie
2026-10-24 07:19:26 +08:00
parent 0cfe7b6195
commit ed41af5294
95 changed files with 9358 additions and 8 deletions
+57
View File
@@ -0,0 +1,57 @@
import { expect, it, vi } from "vitest";
import { createSSRApp, h, nextTick } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
ToastProvider,
ToastQueue,
Table,
TableContent,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
} from "../packages/vue/src";
it("hydrates toast and table with stable content, then keyboard selection works", async () => {
let queue = new ToastQueue();
queue.add({ title: "Hydrated notice" }, { timeout: 0 });
const Root = {
render: () =>
h("main", [
h(ToastProvider, { queue }),
h(Table, () =>
h(TableContent, { selectionMode: "multiple" }, () => [
h(TableHeader, () =>
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
),
h(TableBody, () =>
h(TableRow, { rowKey: 0 }, () => h(TableCell, () => "Zero")),
),
]),
),
]),
};
const host = document.createElement("div");
document.body.append(host);
host.innerHTML = await renderToString(createSSRApp(Root));
queue.destroy();
queue = new ToastQueue();
queue.add({ title: "Hydrated notice" }, { timeout: 0 });
const error = vi.spyOn(console, "error"),
warn = vi.spyOn(console, "warn");
const app = createSSRApp(Root);
app.mount(host);
await nextTick();
expect(
[...error.mock.calls, ...warn.mock.calls].flat().join(" "),
).not.toMatch(/hydration|mismatch/i);
const row = host.querySelector("tbody tr")!;
row.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true }));
await nextTick();
expect(row.getAttribute("aria-selected")).toBe("true");
app.unmount();
queue.destroy();
host.remove();
error.mockRestore();
warn.mockRestore();
});
+165
View File
@@ -0,0 +1,165 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h } from "vue";
import {
ToastQueue,
ToastProvider,
toast,
toastQueue,
createToastFunction,
Table,
TableContent,
TableHeader,
TableBody,
TableRow,
TableCell,
TableColumn,
TableColumnResizer,
TableSortableColumnHeader,
} 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());
toastQueue.clear();
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
vi.useRealTimers();
document.body.innerHTML = "";
});
it("the exported toast helper is rendered by the default provider", async () => {
vi.useFakeTimers();
const w = mount(ToastProvider);
wrappers.push(w);
toast("global notification", { timeout: 0 });
await flushPromises();
expect(w.text()).toContain("global notification");
});
it("row click listener is forwarded exactly once", async () => {
const onClick = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableBody, {}, () =>
h(TableRow, { rowKey: "one", onClick }, () =>
h(TableCell, {}, () => "One"),
),
),
),
),
}),
);
wrappers.push(w);
await w.get("tr").trigger("click");
expect(onClick).toHaveBeenCalledTimes(1);
});
it("caller preventDefault vetoes sort before the sort proposal", async () => {
const change = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, { onSortChange: change }, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableRow, { rowKey: "head" }, () =>
h(
TableSortableColumnHeader,
{
columnKey: "name",
onClick: (e: MouseEvent) => e.preventDefault(),
},
() => "Name",
),
),
),
),
),
}),
);
wrappers.push(w);
await w.get("button").trigger("click");
expect(change).not.toHaveBeenCalled();
});
it("the first column resize handle changes its containing column", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableRow, { rowKey: "head" }, () => [
h(TableColumn, {}, () => ["First", h(TableColumnResizer)]),
h(TableColumn, {}, () => "Second"),
]),
),
),
),
}),
);
wrappers.push(w);
const th = w.get("th").element as HTMLElement;
Object.defineProperty(th, "getBoundingClientRect", {
value: () => ({ width: 100 }),
});
await w
.get('[data-slot="table-column-resizer"]')
.trigger("keydown", { key: "ArrowRight" });
expect(th.style.width).toBe("108px");
});
it("changing provider queue subscribes to and renders the new queue", async () => {
const a = new ToastQueue(),
b = new ToastQueue();
queues.push(a, b);
const w = mount(ToastProvider, { props: { queue: a } });
wrappers.push(w);
await w.setProps({ queue: b });
b.add({ title: "new queue" }, { timeout: 0 });
await flushPromises();
expect(w.text()).toContain("new queue");
});
it("a completed promise cannot overwrite an explicitly replaced loading entry", async () => {
const q = new ToastQueue({ exitDuration: 0 });
queues.push(q);
const api = createToastFunction(q);
let resolve!: (n: number) => void;
const id = api.promise(
new Promise<number>((r) => {
resolve = r;
}),
{ loading: "loading", success: "old result", error: "failed" },
);
api.update(id, "new content", { timeout: 0 });
resolve(1);
await flushPromises();
expect(q.visibleToasts.find((t) => t.key === id)?.content.title).toBe(
"new content",
);
});
it("default loading content renders the shared Spinner", () => {
const q = new ToastQueue();
queues.push(q);
q.add({ title: "Loading", isLoading: true }, { timeout: 0 });
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
expect(w.find('[data-slot="spinner"]').exists()).toBe(true);
});
it("default action forwards its callback and visual options", async () => {
const action = vi.fn();
const q = new ToastQueue();
queues.push(q);
q.add(
{
title: "Action",
actionProps: { label: "Retry", onClick: action, variant: "danger" },
},
{ timeout: 0 },
);
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
const button = w.findAll("button").find((b) => b.text() === "Retry")!;
await button.trigger("click");
expect(action).toHaveBeenCalledTimes(1);
expect(button.classes()).toContain("hv-button--danger");
});
+106
View File
@@ -0,0 +1,106 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h } from "vue";
import {
ToastQueue,
ToastProvider,
Table,
TableContent,
TableBody,
TableHeader,
TableRow,
TableCell,
TableColumn,
} 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());
document.body.innerHTML = "";
});
it("after queue swap the visible toast close action closes the new queue", async () => {
const a = new ToastQueue({ exitDuration: 0 }),
b = new ToastQueue({ exitDuration: 0 });
queues.push(a, b);
const w = mount(ToastProvider, { props: { queue: a } });
wrappers.push(w);
await w.setProps({ queue: b });
b.add({ title: "new queue toast" }, { timeout: 0 });
await flushPromises();
expect(w.text()).toContain("new queue toast");
await w.get('button[data-slot="toast-close"]').trigger("click");
await flushPromises();
expect(b.visibleToasts).toHaveLength(0);
});
it("row event arrays respect stopImmediatePropagation before other handlers and selection", async () => {
const second = vi.fn(),
select = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(
TableContent,
{ selectionMode: "multiple", onSelectionChange: select },
() =>
h(TableBody, {}, () =>
h(
TableRow,
{
rowKey: "one",
onClick: [
(e: MouseEvent) => e.stopImmediatePropagation(),
second,
],
},
() => h(TableCell, {}, () => "One"),
),
),
),
),
}),
);
wrappers.push(w);
await w.get("tr").trigger("click");
expect(second).not.toHaveBeenCalled();
expect(select).not.toHaveBeenCalled();
});
it("a sortable column forwards user click and honors its cancellation", async () => {
const sort = vi.fn(),
click = vi.fn((e: MouseEvent) => e.preventDefault());
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, { onSortChange: sort }, () =>
h(TableHeader, {}, () =>
h(
TableColumn,
{ id: "name", allowsSorting: true, onClick: click },
() => "Name",
),
),
),
),
}),
);
wrappers.push(w);
await w.get("th").trigger("click");
expect(click).toHaveBeenCalledTimes(1);
expect(sort).not.toHaveBeenCalled();
});
it("baseline table header creates a header row around its columns", async () => {
const mod = await import("../apps/docs/demos/table-sorting.vue");
const w = mount(mod.default);
wrappers.push(w);
expect(w.find("thead > tr > th").exists()).toBe(true);
});
it("baseline sorting exposes the current direction on the real column header", async () => {
const mod = await import("../apps/docs/demos/table-sorting.vue");
const w = mount(mod.default);
wrappers.push(w);
const column = w.findAll("th")[1];
await column.trigger("click");
expect(column.attributes("aria-sort")).toBe("ascending");
});
+142
View File
@@ -0,0 +1,142 @@
import { afterEach, expect, it } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { nextTick, defineComponent, h } from "vue";
import {
ToastQueue,
ToastProvider,
Table,
TableContent,
TableHeader,
TableColumn,
TableColumnResizer,
TableBody,
TableRow,
TableCell,
} 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());
document.body.innerHTML = "";
});
it("column minWidth constrains keyboard resizing", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, { minWidth: 160 }, () => h(TableColumnResizer)),
),
),
),
}),
);
wrappers.push(w);
const th = w.get("th").element as HTMLElement;
Object.defineProperty(th, "getBoundingClientRect", {
value: () => ({ width: 160 }),
});
await w
.get('[data-slot="table-column-resizer"]')
.trigger("keydown", { key: "ArrowLeft" });
expect(parseFloat(th.style.width)).toBeGreaterThanOrEqual(160);
});
it("an unrelated pointer cancellation does not reset an active column drag", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, {}, () => h(TableColumnResizer)),
),
),
),
}),
);
wrappers.push(w);
const th = w.get("th").element as HTMLElement;
Object.defineProperty(th, "getBoundingClientRect", {
value: () => ({ width: 100 }),
});
const handle = w.get('[data-slot="table-column-resizer"]').element;
const pointer = (type: string, id: number, x: number) => {
const e = new MouseEvent(type, { bubbles: true, button: 0, clientX: x });
Object.defineProperty(e, "pointerId", { value: id });
handle.dispatchEvent(e);
};
pointer("pointerdown", 1, 100);
pointer("pointermove", 1, 120);
await nextTick();
expect(th.style.width).toBe("120px");
pointer("pointercancel", 2, 120);
await nextTick();
expect(th.style.width).toBe("120px");
});
it("Space selects the focused selectable table row", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, { selectionMode: "multiple" }, () =>
h(TableBody, {}, () =>
h(TableRow, { rowKey: "one", tabindex: 0 }, () =>
h(TableCell, {}, () => "One"),
),
),
),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const row = w.get("tr");
(row.element as HTMLElement).focus();
expect(document.activeElement).toBe(row.element);
await row.trigger("keydown", { key: " ", code: "Space" });
expect(row.attributes("aria-selected")).toBe("true");
});
it("default toast groups title and description in its content layout", () => {
const q = new ToastQueue();
queues.push(q);
q.add({ title: "Title", description: "Description" }, { timeout: 0 });
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
expect(
w.find('[data-slot="toast-content"] [data-slot="toast-title"]').exists(),
).toBe(true);
expect(
w
.find('[data-slot="toast-content"] [data-slot="toast-description"]')
.exists(),
).toBe(true);
});
it("the provider exposed toast factory uses the current queue after replacement", async () => {
const a = new ToastQueue({ exitDuration: 0 }),
b = new ToastQueue({ exitDuration: 0 });
queues.push(a, b);
const w = mount(ToastProvider, { props: { queue: a } });
wrappers.push(w);
const api = w.vm as unknown as {
toast: () => (message: string, options: { timeout: number }) => string;
};
api.toast()("initial", { timeout: 0 });
await w.setProps({ queue: b });
api.toast()("current", { timeout: 0 });
await flushPromises();
expect(b.visibleToasts.map((t) => t.content.title)).toContain("current");
});
it("selection demo select-all checks the actual row controls", async () => {
const mod = await import("../apps/docs/demos/table-selection.vue");
const w = mount(mod.default);
wrappers.push(w);
const controls = w.findAll('input[type="checkbox"]');
expect(controls.length).toBeGreaterThan(1);
await controls[0].setValue(true);
await flushPromises();
expect(
controls.slice(1).every((c) => (c.element as HTMLInputElement).checked),
).toBe(true);
});
+117
View File
@@ -0,0 +1,117 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h } from "vue";
import {
Table,
TableContent,
TableHeader,
TableColumn,
TableColumnResizer,
TableBody,
TableRow,
TableCell,
ToastProvider,
ToastQueue,
} 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 = "";
});
it("column defaultWidth is applied to its rendered column", () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, { defaultWidth: 180 }, () => "Name"),
),
),
),
}),
);
wrappers.push(w);
expect((w.get("th").element as HTMLElement).style.width).toBe("180px");
});
it("a selectable table supplies a keyboard focus entry without caller tabindex", () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, { selectionMode: "multiple" }, () =>
h(TableBody, {}, () =>
h(TableRow, { rowKey: "one" }, () =>
h(TableCell, {}, () => "One"),
),
),
),
),
}),
);
wrappers.push(w);
expect(w.findAll('[tabindex="0"]').length).toBeGreaterThan(0);
});
it("unmount during an active column drag releases capture", () => {
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, {}, () => h(TableColumnResizer)),
),
),
),
}),
);
const handle = w.get('[data-slot="table-column-resizer"]')
.element as HTMLElement;
const release = vi.fn();
Object.defineProperty(handle, "setPointerCapture", { value: vi.fn() });
Object.defineProperty(handle, "releasePointerCapture", { value: release });
const th = w.get("th").element;
Object.defineProperty(th, "getBoundingClientRect", {
value: () => ({ width: 100 }),
});
for (const [type, x] of [
["pointerdown", 100],
["pointermove", 120],
] as const) {
const e = new MouseEvent(type, { bubbles: true, button: 0, clientX: x });
Object.defineProperty(e, "pointerId", { value: 7 });
handle.dispatchEvent(e);
}
w.unmount();
expect(release).toHaveBeenCalledWith(7);
});
it("default action respects the caller's disabled state", () => {
const q = new ToastQueue();
queues.push(q);
q.add(
{ title: "Action", actionProps: { label: "Blocked", isDisabled: true } },
{ timeout: 0 },
);
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
const button = w.findAll("button").find((b) => b.text() === "Blocked")!;
expect((button.element as HTMLButtonElement).disabled).toBe(true);
});
it("the default toast demo escapes the containing preview", async () => {
vi.useFakeTimers();
const mod = await import("../apps/docs/demos/toast-default.vue");
const host = document.createElement("div");
host.className = "component-preview-container";
document.body.append(host);
const w = mount(mod.default, { attachTo: host });
wrappers.push(w);
await w.get("button").trigger("click");
await flushPromises();
const region = document.querySelector('[data-slot="toast-region"]')!;
expect(region).not.toBeNull();
expect(region.closest(".component-preview-container")).toBeNull();
});
+145
View File
@@ -0,0 +1,145 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h } from "vue";
import {
ToastQueue,
ToastProvider,
createToastFunction,
Table,
TableContent,
TableHeader,
TableBody,
TableRow,
TableCell,
TableSortableColumnHeader,
} from "../packages/vue/src";
const queues: ToastQueue[] = [];
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
queues.splice(0).forEach((q) => q.destroy());
vi.useRealTimers();
document.body.innerHTML = "";
});
function queue() {
const q = new ToastQueue({ exitDuration: 0 });
queues.push(q);
return q;
}
it("toasts added while paused start their countdown on resume", () => {
vi.useFakeTimers();
const q = queue();
q.pauseAll();
q.add({ title: "paused-add" }, { timeout: 100 });
vi.advanceTimersByTime(500);
expect(q.visibleToasts).toHaveLength(1);
q.resumeAll();
vi.advanceTimersByTime(101);
expect(q.visibleToasts).toHaveLength(0);
});
it("a repeated resume does not leave a stale countdown after a later pause", () => {
vi.useFakeTimers();
const q = queue();
q.add({ title: "x" }, { timeout: 1000 });
vi.advanceTimersByTime(100);
q.resumeAll();
vi.advanceTimersByTime(100);
q.pauseAll();
vi.advanceTimersByTime(2000);
expect(q.visibleToasts).toHaveLength(1);
});
it("promise resolving after early close does not create a replacement notification", async () => {
const q = queue();
const toast = createToastFunction(q);
let resolve!: (n: number) => void;
const id = toast.promise(
new Promise<number>((r) => {
resolve = r;
}),
{ loading: "loading", success: "done", error: "error" },
);
toast.close(id);
expect(q.visibleToasts).toHaveLength(0);
resolve(1);
await flushPromises();
expect(q.visibleToasts).toHaveLength(0);
});
it("variant demo renders actual Vue labels rather than JSX-like literals", async () => {
const mod = await import("../apps/docs/demos/toast-variants.vue");
const w = mount(mod.default);
wrappers.push(w);
expect(w.findAll("button").map((b) => b.text())).toEqual([
"默认 Toast",
"强调 Toast",
"成功 Toast",
"警告 Toast",
"危险 Toast",
]);
});
it("a row action does not select the enclosing row", async () => {
const onSelection = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(
Table,
{ selectionMode: "multiple", onSelectionChange: onSelection },
() =>
h(TableContent, {}, () =>
h(TableBody, {}, () =>
h(TableRow, { rowKey: "a" }, () =>
h(TableCell, {}, () =>
h("button", { type: "button" }, "Edit"),
),
),
),
),
),
}),
);
wrappers.push(w);
await w.get("button").trigger("click");
expect(onSelection).not.toHaveBeenCalled();
});
it("sortable header invokes a user click listener only once", async () => {
const onClick = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableRow, { rowKey: "head" }, () =>
h(
TableSortableColumnHeader,
{ columnKey: "a", onClick },
() => "A",
),
),
),
),
),
}),
);
wrappers.push(w);
await w.get("button").trigger("click");
expect(onClick).toHaveBeenCalledTimes(1);
});
it("hovering the notification region pauses its timeout", async () => {
vi.useFakeTimers();
const q = queue();
q.add({ title: "hover" }, { timeout: 100 });
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
await w.get('[data-slot="toast-region"]').trigger("pointerenter");
vi.advanceTimersByTime(101);
expect(q.visibleToasts).toHaveLength(1);
});
it("default provider renders queued content without requiring a custom renderer", () => {
const q = queue();
q.add({ title: "default content" }, { timeout: 0 });
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
expect(w.text()).toContain("default content");
});
+61
View File
@@ -0,0 +1,61 @@
// @vitest-environment node
import { expect, it } from "vitest";
import { createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
ToastProvider,
ToastQueue,
toast,
toastQueue,
Table,
TableContent,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
} from "../packages/vue/src";
it("shared client toast helper does not retain server-request content", async () => {
expect(toast("request secret")).toBe("");
expect(toastQueue.visibleToasts).toHaveLength(0);
expect(
await renderToString(createSSRApp({ render: () => h(ToastProvider) })),
).not.toContain("request secret");
});
it("explicit request queues render separately without server countdowns", async () => {
const a = new ToastQueue(),
b = new ToastQueue();
a.add({ title: "Request A" });
b.add({ title: "Request B" });
const render = (queue: ToastQueue) =>
renderToString(createSSRApp({ render: () => h(ToastProvider, { queue }) }));
expect(await render(a)).toContain("Request A");
expect(await render(b)).not.toContain("Request A");
expect(a.visibleToasts[0].timer).toBeUndefined();
a.destroy();
b.destroy();
});
it("server table preserves native row-header semantics and accepted numeric selection", async () => {
const html = await renderToString(
createSSRApp({
render: () =>
h(Table, () =>
h(
TableContent,
{ selectionMode: "multiple", selectedKeys: [0] },
() => [
h(TableHeader, () =>
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
),
h(TableBody, () =>
h(TableRow, { rowKey: 0 }, () => h(TableCell, () => "Zero")),
),
],
),
),
}),
);
expect(html).toContain('scope="row"');
expect(html).toContain('aria-selected="true"');
expect(html).not.toContain("<thead><th");
});
+392
View File
@@ -0,0 +1,392 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Table,
TableContent,
TableHeader,
TableColumn,
TableColumnResizer,
TableBody,
TableRow,
TableCell,
TableSortableColumnHeader,
ToastProvider,
ToastQueue,
} 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());
vi.useRealTimers();
document.body.innerHTML = "";
});
function table(
options: Record<string, unknown> = {},
keys: (string | number)[] = [0, "0", "", 3],
) {
const items = ref(keys);
const w = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableContent, options, () => [
h(TableHeader, () => [
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
h(TableColumn, { id: "value" }, () => "Value"),
]),
h(TableBody, () =>
items.value.map((key) =>
h(TableRow, { rowKey: key, key }, () => [
h(TableCell, () => String(key)),
h(TableCell, () => "Value"),
]),
),
),
]),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
return { w, items };
}
it("roves across numeric/string/empty keys, skips disabled rows and extends a range", async () => {
const { w } = table({ selectionMode: "multiple", disabledKeys: ["0"] });
await nextTick();
const rows = w.findAll("tbody tr");
expect(rows.map((r) => r.attributes("tabindex"))).toEqual([
"0",
"-1",
"-1",
"-1",
]);
(rows[0].element as HTMLElement).focus();
await rows[0].trigger("keydown", { key: " " });
await rows[0].trigger("keydown", { key: "ArrowDown", shiftKey: true });
await nextTick();
expect(document.activeElement).toBe(rows[2].element);
expect(
w.findComponent(TableContent).emitted("selectionChange")?.at(-1),
).toEqual([[0, ""]]);
await rows[2].trigger("keydown", { key: "a", ctrlKey: true });
expect(
w.findComponent(TableContent).emitted("selectionChange")?.at(-1),
).toEqual([[0, "", 3]]);
});
it("uses accepted controlled selection and permits the same rejected range proposal again", async () => {
const { w } = table({ selectionMode: "multiple", selectedKeys: [] });
await nextTick();
const rows = w.findAll("tbody tr");
(rows[0].element as HTMLElement).focus();
await rows[2].trigger("click", { shiftKey: true });
await rows[2].trigger("click", { shiftKey: true });
expect(w.findComponent(TableContent).emitted("selectionChange")).toEqual([
[[0, "0", ""]],
[[0, "0", ""]],
]);
expect(rows.every((row) => row.attributes("aria-selected") === "false")).toBe(
true,
);
});
it("moves through cells and honors preventDefault without stealing child controls", async () => {
const { w } = table();
await nextTick();
const rows = w.findAll("tbody tr");
(rows[0].element as HTMLElement).focus();
await rows[0].trigger("keydown", { key: "ArrowRight" });
expect(document.activeElement).toBe(rows[0].findAll("th,td")[0].element);
await w.get("tbody th").trigger("keydown", { key: "ArrowDown" });
expect(document.activeElement).toBe(rows[1].findAll("th,td")[0].element);
});
it("refreshes DOM order after keyed reordering", async () => {
const { w, items } = table();
await nextTick();
items.value = [3, "", 0, "0"];
await nextTick();
const rows = w.findAll("tbody tr");
(rows[0].element as HTMLElement).focus();
await rows[0].trigger("keydown", { key: "ArrowDown" });
expect(document.activeElement).toBe(rows[1].element);
});
it("requests and focuses a previously unmounted logical row", async () => {
const visible = ref([0]);
const onFocusRow = vi.fn((key: string | number) => {
visible.value = [Number(key)];
});
const w = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableContent, { rowKeys: [0, 1, 2], onFocusRow }, () =>
h(TableBody, () =>
visible.value.map((key) =>
h(TableRow, { key, rowKey: key }, () =>
h(TableCell, () => key),
),
),
),
),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
await nextTick();
(w.get("tbody tr").element as HTMLElement).focus();
await w.get("tbody tr").trigger("keydown", { key: "ArrowDown" });
await nextTick();
expect(onFocusRow).toHaveBeenCalledWith(1, 1);
expect(document.activeElement?.textContent).toBe("1");
});
it("maps row headers and tree-column slot metadata only to their actual columns", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableContent, { treeColumn: "name" }, () => [
h(TableHeader, () => [
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
h(TableColumn, { id: "value" }, () => "Value"),
]),
h(TableBody, () =>
h(TableRow, { rowKey: "a", hasChildItems: true }, () => [
h(
TableCell,
{},
{
default: ({ isTreeColumn }: { isTreeColumn: boolean }) =>
String(isTreeColumn),
},
),
h(
TableCell,
{},
{
default: ({ isTreeColumn }: { isTreeColumn: boolean }) =>
String(isTreeColumn),
},
),
]),
),
]),
),
}),
);
wrappers.push(w);
await nextTick();
expect(w.get("tbody th").attributes("scope")).toBe("row");
expect(w.get("tbody th").text()).toBe("true");
expect(w.get("tbody td").text()).toBe("false");
});
it("sorts only the correct column and only once per click", async () => {
const w = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableContent, () =>
h(TableHeader, () =>
["a", "b"].map((id) =>
h(TableColumn, { id, allowsSorting: true }, () =>
h(TableSortableColumnHeader, { columnKey: id }, () => id),
),
),
),
),
),
}),
);
wrappers.push(w);
await w.findAll("button")[1].trigger("click");
expect(w.findComponent(TableContent).emitted("sortChange")).toEqual([
[{ column: "b", direction: "ascending" }],
]);
expect(
w.findAll('[data-slot="table-sortable-column-indicator"]'),
).toHaveLength(1);
expect(w.findAll("th").map((th) => th.attributes("aria-sort"))).toEqual([
"none",
"ascending",
]);
});
it("controlled column width proposals respect max, RTL and rejection/retry", async () => {
const update = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, { dir: "rtl" }, () =>
h(TableContent, () =>
h(TableHeader, () =>
h(
TableColumn,
{ width: 100, maxWidth: 110, "onUpdate:width": update },
() => h(TableColumnResizer),
),
),
),
),
}),
);
wrappers.push(w);
const th = w.get("th").element as HTMLElement;
vi.spyOn(th, "getBoundingClientRect").mockReturnValue({
width: 100,
} as DOMRect);
const handle = w.get('[role="separator"]');
await handle.trigger("keydown", { key: "ArrowLeft", shiftKey: true });
await handle.trigger("keydown", { key: "ArrowLeft", shiftKey: true });
expect(update.mock.calls).toEqual([[110], [110]]);
expect(th.style.width).toBe("100px");
});
it("default toast anatomy separates indicator/text/actions; overflow is inert", async () => {
const q = new ToastQueue();
queues.push(q);
for (let i = 0; i < 4; i++)
q.add(
{
title: "Title",
description: "Description",
actionProps: { label: "Action" },
},
{ timeout: 0 },
);
const w = mount(ToastProvider, { props: { queue: q } });
wrappers.push(w);
await nextTick();
const card = w.get('[data-slot="toast"]');
expect(
card.get('[data-slot="toast-content"]').findAll("button"),
).toHaveLength(0);
expect(card.findAll(':scope > [data-slot="toast-indicator"]')).toHaveLength(
1,
);
expect(w.get('[data-hidden="true"]').attributes("inert")).toBeDefined();
});
it("Alt+T enters the live stack, close focuses its neighbor, Escape returns to trigger", async () => {
const trigger = document.createElement("button");
document.body.append(trigger);
trigger.focus();
const q = new ToastQueue();
queues.push(q);
const first = q.add({ title: "First" }, { timeout: 0 });
const second = q.add({ title: "Second" }, { timeout: 0 });
const w = mount(ToastProvider, {
props: { queue: q },
attachTo: document.body,
});
wrappers.push(w);
await nextTick();
document.dispatchEvent(
new KeyboardEvent("keydown", { code: "KeyT", altKey: true, bubbles: true }),
);
await nextTick();
expect(document.activeElement?.textContent).toBe("Second");
q.close(second);
await nextTick();
await nextTick();
expect(document.activeElement?.textContent).toBe("First");
document.activeElement?.dispatchEvent(
new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
);
await nextTick();
expect(document.activeElement).toBe(trigger);
});
it("one provider unmount cannot release another provider hover pause on the same queue", async () => {
vi.useFakeTimers();
const q = new ToastQueue({ exitDuration: 0 });
queues.push(q);
q.add({ title: "Shared" }, { timeout: 1000 });
const a = mount(ToastProvider, { props: { queue: q } }),
b = mount(ToastProvider, { props: { queue: q } });
wrappers.push(b);
a.element.dispatchEvent(new MouseEvent("pointerenter"));
b.element.dispatchEvent(new MouseEvent("pointerenter"));
a.unmount();
vi.advanceTimersByTime(2000);
expect(q.visibleToasts).toHaveLength(1);
});
it("default toast action stopImmediatePropagation vetoes automatic close", async () => {
const queue = new ToastQueue();
queues.push(queue);
queue.add(
{
title: "Action",
actionProps: {
label: "Keep",
onClick: (event) => event.stopImmediatePropagation(),
},
},
{ timeout: 0 },
);
const w = mount(ToastProvider, { props: { queue } });
wrappers.push(w);
await w.get('[data-slot="toast-action-button"]').trigger("click");
expect(queue.getExitingKeys().size).toBe(0);
expect(queue.visibleToasts).toHaveLength(1);
});
it("load-more observes its scroll container and deduplicates an in-flight request", async () => {
const observers: {
callback: IntersectionObserverCallback;
options?: IntersectionObserverInit;
disconnect: ReturnType<typeof vi.fn>;
}[] = [];
vi.stubGlobal(
"IntersectionObserver",
class {
disconnect = vi.fn();
observe = vi.fn();
unobserve = vi.fn();
constructor(
callback: IntersectionObserverCallback,
options?: IntersectionObserverInit,
) {
observers.push({ callback, options, disconnect: this.disconnect });
}
},
);
const { TableLoadMoreItem, TableLoadMoreContent, TableScrollContainer } =
await import("../packages/vue/src");
const loading = ref(false);
const load = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Table, () =>
h(TableScrollContainer, () =>
h(TableContent, () =>
h(TableBody, () =>
h(
TableLoadMoreItem,
{ isLoading: loading.value, onLoadMore: load },
() => h(TableLoadMoreContent, () => "Loading"),
),
),
),
),
),
}),
);
wrappers.push(w);
const observer = observers.at(-1)!;
expect(observer.options?.root).toBe(
w.get('[data-slot="table-scroll-container"]').element,
);
expect(
w.find('tbody > tr > td > [data-slot="table-load-more-content"]').exists(),
).toBe(true);
const entry = [{ isIntersecting: true }] as IntersectionObserverEntry[];
observer.callback(entry, {} as IntersectionObserver);
observer.callback(entry, {} as IntersectionObserver);
expect(load).toHaveBeenCalledTimes(1);
loading.value = true;
await nextTick();
loading.value = false;
await nextTick();
expect(load).toHaveBeenCalledTimes(2);
w.unmount();
wrappers.pop();
observer.callback(entry, {} as IntersectionObserver);
expect(load).toHaveBeenCalledTimes(2);
vi.unstubAllGlobals();
});
+2
View File
@@ -19,3 +19,5 @@ M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制
LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。
M33–M34 使用 consume-m33-m34.mjs / m33-m34-contract.ts;同样复制到独立 tarball 消费工程,分别运行 node 与两种解析模式的 tsc。包括所有公开部件、真正 node SSR、CSS 关键帧与策略/尺寸/方向的正反类型检查。集成验证目录为 /private/tmp/heroui-m33-consumer,不复用其他并行任务的临时产物。
M35–M36 使用 `consume-m35-m36.mjs` / `m35-m36-contract.ts`,新建 `/private/tmp/heroui-m35-consumer`。pnpm 11 的本地样式 tarball override 写在消费者 `pnpm-workspace.yaml`;不依赖已弃用的 package.json pnpm 字段。分别验证 ESM/CSS、真正 node SSR、所有部件导出,以及 bundler/NodeNext 类型正反例(含 Promise 参数推断)。
+78
View File
@@ -0,0 +1,78 @@
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 [
"Toast",
"ToastRoot",
"ToastProvider",
"ToastContent",
"ToastIndicator",
"ToastTitle",
"ToastDescription",
"ToastActionButton",
"ToastCloseButton",
"ToastQueue",
"toast",
"toastQueue",
"createToastFunction",
"Table",
"TableRoot",
"TableContent",
"TableHeader",
"TableColumn",
"TableBody",
"TableRow",
"TableCell",
"TableScrollContainer",
"TableFooter",
"TableResizableContainer",
"TableColumnResizer",
"TableLoadMore",
"TableLoadMoreItem",
"TableLoadMoreContent",
"TableCollection",
"TableSortableColumnHeader",
])
assert(lib[name], name);
assert.equal(lib.toast("server secret"), "");
assert.equal(lib.toastQueue.visibleToasts.length, 0);
const queue = new lib.ToastQueue();
queue.add({ title: "Request-local notification" });
const html = await renderToString(
createSSRApp({
render: () =>
h("main", [
h(lib.ToastProvider, { queue }),
h(lib.Table, () =>
h(
lib.TableContent,
{ selectionMode: "single", selectedKeys: [0] },
() => [
h(lib.TableHeader, () =>
h(lib.TableColumn, { isRowHeader: true }, () => "Name"),
),
h(lib.TableBody, () =>
h(lib.TableRow, { rowKey: 0 }, () =>
h(lib.TableCell, () => "Zero"),
),
),
],
),
),
]),
}),
);
assert(html.includes("Request-local notification"));
assert(html.includes('scope="row"'));
assert(html.includes('aria-selected="true"'));
queue.destroy();
const css = readFileSync(
new URL(import.meta.resolve("@heroui-vue/styles/css")),
"utf8",
);
assert(css.includes(".hv-toast-region"));
assert(css.includes(".hv-table__column-resizer"));
assert(css.includes("data-exiting"));
console.log("M35/M36 tarball exports, actual node SSR and CSS passed");
+72
View File
@@ -0,0 +1,72 @@
import {
toast,
type ToastProviderProps,
type ToastActionButtonProps,
type TableContentProps,
type TableColumnProps,
type TableCellProps,
type TableLoadMoreItemProps,
type TableKey,
} from "@heroui-vue/components";
const provider: ToastProviderProps = {
placement: "top end",
maxVisibleToasts: 2,
};
const action: ToastActionButtonProps = {
variant: "tertiary",
size: "sm",
isDisabled: true,
};
const content: TableContentProps = {
selectionMode: "multiple",
selectedKeys: [0, "0", ""],
rowKeys: [0, 1],
onFocusRow: (key: TableKey, index: number) => {
void [key, index];
},
};
const column: TableColumnProps = {
width: 120,
minWidth: 80,
maxWidth: 200,
"onUpdate:width": (value) => {
const n: number = value;
void n;
},
};
const cell: TableCellProps = { colspan: 3 };
const loader: TableLoadMoreItemProps = { hasMore: false, scrollOffset: 40 };
toast.promise(Promise.resolve({ filename: "file.pdf" }), {
loading: "Loading",
success: (data) => {
const name: string = data.filename;
// @ts-expect-error preserve contextual payload inference
const number: number = data.filename;
// @ts-expect-error no nonexistent payload property
void data.unknown;
return name;
},
error: (error) => error.message,
});
// @ts-expect-error unknown placement
const badProvider: ToastProviderProps = { placement: "diagonal" };
// @ts-expect-error action variant constrained
const badAction: ToastActionButtonProps = { variant: "neon" };
// @ts-expect-error selection key cannot be object
const badKeys: TableContentProps = { selectedKeys: [{}] };
// @ts-expect-error width is scalar
const badWidth: TableColumnProps = { width: [100] };
// @ts-expect-error helper rejects arbitrary object content
toast({ secret: 123 });
void [
provider,
action,
content,
column,
cell,
loader,
badProvider,
badAction,
badKeys,
badWidth,
];
+204
View File
@@ -0,0 +1,204 @@
import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
TableSortableColumnHeader,
} from "../packages/vue/src";
afterEach(async () => {
await flushPromises();
document.body.innerHTML = "";
});
function mountTable(props: Record<string, unknown> = {}, rows = ["1", "2"]) {
return mount(
defineComponent({
setup: () => ({ props, rows }),
render: () =>
h(TableScrollContainer, () =>
h(Table, props, () =>
h(TableContent, () => [
h(TableHeader, () => [
h(TableColumn, { id: "name", allowsSorting: true }, () =>
h(
TableSortableColumnHeader,
{ sortDirection: undefined },
() => "名",
),
),
]),
h(TableBody, () =>
rows.map((id) =>
h(TableRow, { rowKey: id }, () =>
h(TableCell, () => `row-${id}`),
),
),
),
]),
),
),
}),
{ attachTo: document.body },
);
}
it("renders table semantics and data-slots", () => {
const w = mountTable();
expect(w.find('[data-slot="table"]').exists()).toBe(true);
expect(w.find("table").exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(2);
expect(w.find('[data-slot="table-sortable-column-header"]').exists()).toBe(
true,
);
w.unmount();
});
it("selection toggles and respects disabledKeys", async () => {
const selected = ref<(string | number)[]>([]);
const w = mount(
defineComponent({
setup: () => ({ selected }),
render: () =>
h(Table, () =>
h(
TableContent,
{
selectionMode: "multiple",
selectedKeys: selected.value,
disabledKeys: ["2"],
"onUpdate:selectedKeys": (k: (string | number)[]) => {
selected.value = k;
},
},
() =>
h(TableBody, () =>
["1", "2"].map((id) =>
h(TableRow, { rowKey: id }, () => h(TableCell, () => id)),
),
),
),
),
}),
{ attachTo: document.body },
);
await w.findAll('[data-slot="table-row"]')[0].trigger("click");
await nextTick();
expect(selected.value).toEqual(["1"]);
await w.findAll('[data-slot="table-row"]')[1].trigger("click");
await nextTick();
expect(selected.value).toEqual(["1"]);
await w.findAll('[data-slot="table-row"]')[0].trigger("click");
await nextTick();
expect(selected.value).toEqual([]);
w.unmount();
});
it("sortable header updates sort direction and emits sortChange", async () => {
const w = mountTable();
const col = w.get('[data-slot="table-column"]');
expect(col.attributes("data-allows-sorting")).toBe("true");
expect(
w
.get('[data-slot="table-sortable-column-header"]')
.attributes("data-direction"),
).toBeUndefined();
await col.trigger("click");
await nextTick();
expect(
w
.get('[data-slot="table-sortable-column-header"]')
.attributes("data-direction"),
).toBe("ascending");
await col.trigger("click");
await nextTick();
expect(
w
.get('[data-slot="table-sortable-column-header"]')
.attributes("data-direction"),
).toBe("descending");
w.unmount();
});
it("mounts all 13 demos without Vue warnings", async () => {
const names = [
"basic",
"secondary-variant",
"async-loading",
"sorting",
"selection",
"expandable-rows",
"pagination",
"column-resizing",
"empty-state",
"virtualization",
"tanstack-table",
"custom-cells",
"custom-styles",
];
expect(names).toHaveLength(13);
const warnings: string[] = [];
const spy = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args.map(String).join(" "));
});
for (const name of names) {
const mod = await import(`../apps/docs/demos/table-${name}.vue`);
const w = mount(mod.default, { attachTo: document.body });
await nextTick();
expect(w.html().length).toBeGreaterThan(0);
w.unmount();
}
spy.mockRestore();
expect(warnings).toEqual([]);
});
it("controlled sort-descriptor updates via v-model", async () => {
const descriptor = ref<{
column: string;
direction: "ascending" | "descending";
} | null>(null);
const w = mount(
defineComponent({
setup: () => ({ descriptor }),
render: () =>
h(Table, () =>
h(
TableContent,
{
sortDescriptor: descriptor.value,
"onUpdate:sortDescriptor": (d: any) => {
descriptor.value = d;
},
},
() =>
h(TableHeader, () =>
h(TableRow, { rowKey: "head" }, () =>
h(TableColumn, { id: "name", allowsSorting: true }, () =>
h(
TableSortableColumnHeader,
{
sortDirection: descriptor.value?.direction as
"ascending" | "descending" | undefined,
},
() => "名",
),
),
),
),
),
),
}),
{ attachTo: document.body },
);
await w.find('[data-slot="table-column"]').trigger("click");
await nextTick();
expect(descriptor.value).toEqual({ column: "name", direction: "ascending" });
w.unmount();
});
+249
View File
@@ -0,0 +1,249 @@
import { describe, expect, it, vi, afterEach } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, nextTick } from "vue";
import {
ToastQueue,
createToastFunction,
ToastProvider,
ToastContent,
ToastTitle,
ToastDescription,
ToastIndicator,
ToastCloseButton,
} from "../packages/vue/src";
afterEach(async () => {
await flushPromises();
document.body.innerHTML = "";
});
describe("ToastQueue", () => {
it("add returns stable key and default timeout auto-closes", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
const key = q.add({ title: "hi" });
expect(key).toBeTruthy();
expect(q.visibleToasts).toHaveLength(1);
vi.advanceTimersByTime(4000);
// exit duration 300ms keeps node conceptually; queue removes after exit
vi.advanceTimersByTime(300);
expect(q.visibleToasts).toHaveLength(0);
vi.useRealTimers();
});
it("timeout 0 stays open and update preserves key/position", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
const a = q.add({ title: "a" }, { timeout: 0 });
const b = q.add({ title: "b" }, { timeout: 0 });
expect(q.update(a, { title: "a2" })).toBe(true);
expect(q.visibleToasts.map((t) => t.key)).toEqual([b, a]); // newest first
expect((q.visibleToasts[1].content as { title: string }).title).toBe("a2");
vi.advanceTimersByTime(10000);
expect(q.visibleToasts).toHaveLength(2);
vi.useRealTimers();
});
it("pause/resume keeps remaining time", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
q.add({ title: "x" }, { timeout: 1000 });
vi.advanceTimersByTime(400);
q.pauseAll();
vi.advanceTimersByTime(5000);
expect(q.visibleToasts).toHaveLength(1);
q.resumeAll();
vi.advanceTimersByTime(600);
expect(q.visibleToasts).toHaveLength(1);
vi.advanceTimersByTime(300);
expect(q.visibleToasts).toHaveLength(0);
vi.useRealTimers();
});
it("toast helper variants and promise settle in place", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
const toast = createToastFunction(q);
const id = toast.success("ok");
expect(q.visibleToasts).toHaveLength(1);
const pid = toast.promise(Promise.resolve(1), {
loading: "loading",
success: (n: number) => `done ${n}`,
error: "fail",
});
expect(q.visibleToasts).toHaveLength(2);
await Promise.resolve();
await Promise.resolve();
await flushPromises();
expect(q.visibleToasts.find((t) => t.key === pid)?.content).toMatchObject({
variant: "success",
});
toast.close(id);
vi.advanceTimersByTime(400);
expect(q.visibleToasts.some((t) => t.key === id)).toBe(false);
vi.useRealTimers();
});
});
describe("ToastProvider UI", () => {
it("renders toasts from queue with title/description/indicator", async () => {
const q = new ToastQueue();
q.add(
{ title: "Hello", description: "World", variant: "success" },
{ timeout: 0 },
);
const w = mount(
defineComponent({
components: {
ToastProvider,
ToastContent,
ToastTitle,
ToastDescription,
ToastIndicator,
ToastCloseButton,
},
setup: () => ({ q }),
template: `
<ToastProvider :queue="q">
<template #default="{ toast, close }">
<ToastContent>
<ToastIndicator :variant="toast.variant" />
<ToastTitle>{{ toast.title }}</ToastTitle>
<ToastDescription>{{ toast.description }}</ToastDescription>
<ToastCloseButton @click="close()" />
</ToastContent>
</template>
</ToastProvider>
`,
}),
{ attachTo: document.body },
);
await nextTick();
expect(w.text()).toContain("Hello");
expect(w.text()).toContain("World");
expect(w.find('[data-slot="toast-region"]').exists()).toBe(true);
expect(w.find('[data-slot="toast"]').exists()).toBe(true);
w.unmount();
q.destroy();
});
});
describe("ToastQueue lifecycle edges", () => {
it("close fires onClose at most once and clear closes all", async () => {
vi.useFakeTimers();
const q = new ToastQueue({ exitDuration: 100 });
const onClose = vi.fn();
const key = q.add({ title: "a" }, { timeout: 0, onClose });
q.close(key);
q.close(key);
expect(onClose).toHaveBeenCalledTimes(1);
q.add({ title: "b" }, { timeout: 0 });
q.add({ title: "c" }, { timeout: 0 });
q.clear();
vi.advanceTimersByTime(200);
expect(q.visibleToasts).toHaveLength(0);
vi.useRealTimers();
});
it("custom queue instances are isolated", async () => {
const q1 = new ToastQueue();
const q2 = new ToastQueue();
q1.add({ title: "1" }, { timeout: 0 });
expect(q1.visibleToasts).toHaveLength(1);
expect(q2.visibleToasts).toHaveLength(0);
q1.destroy();
q2.destroy();
});
it("promise after early close does not resurrect the toast", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
const toast = createToastFunction(q);
let resolve!: (v: number) => void;
const p = new Promise<number>((r) => {
resolve = r;
});
const id = toast.promise(p, {
loading: "l",
success: "s",
error: "e",
});
toast.close(id);
vi.advanceTimersByTime(500);
resolve(1);
await flushPromises();
expect(q.visibleToasts.some((t) => t.key === id)).toBe(false);
vi.useRealTimers();
});
it("destroy clears timers and subscriptions", async () => {
vi.useFakeTimers();
const q = new ToastQueue();
const fn = vi.fn();
q.subscribe(fn);
q.add({ title: "x" }, { timeout: 50 });
q.destroy();
vi.advanceTimersByTime(500);
expect(q.visibleToasts).toHaveLength(0);
vi.useRealTimers();
});
});
describe("Toast demos", () => {
it("mounts all 11 baseline demos without Vue warnings", async () => {
const names = [
"default",
"variants",
"placements",
"expanded",
"simple",
"custom-indicator",
"custom-toast",
"promise",
"callbacks",
"custom-queue",
"custom-styles",
];
expect(names).toHaveLength(11);
const warnings: string[] = [];
const spy = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args.map(String).join(" "));
});
for (const name of names) {
const mod = await import(`../apps/docs/demos/toast-${name}.vue`);
const w = mount(mod.default, { attachTo: document.body });
await nextTick();
expect(w.html().length).toBeGreaterThan(0);
w.unmount();
}
spy.mockRestore();
expect(warnings).toEqual([]);
});
});
it("re-renders when a toast is added after mount", async () => {
const q = new ToastQueue();
const w = mount(
defineComponent({
components: { ToastProvider, ToastContent, ToastTitle },
setup: () => ({ q }),
template: `
<ToastProvider :queue="q">
<template #default="{ toast: item }">
<ToastContent><ToastTitle>{{ item.title }}</ToastTitle></ToastContent>
</template>
</ToastProvider>
`,
}),
{ attachTo: document.body },
);
await nextTick();
expect(w.find('[data-slot="toast"]').exists()).toBe(false);
q.add({ title: "after-mount" }, { timeout: 0 });
await nextTick();
await flushPromises();
expect(w.find('[data-slot="toast"]').exists()).toBe(true);
expect(w.text()).toContain("after-mount");
w.unmount();
q.destroy();
});