389 lines
12 KiB
TypeScript
389 lines
12 KiB
TypeScript
import { afterEach, expect, it, vi } from "vitest";
|
|
import { mount, flushPromises } from "@vue/test-utils";
|
|
import { defineComponent, h, nextTick, ref } from "vue";
|
|
import {
|
|
calculateColumnSizes,
|
|
parseFractionalUnit,
|
|
} from "../packages/vue/src/components/table/widths";
|
|
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();
|
|
});
|
|
|
|
it("empty state spans every leaf column by default and honors explicit colspan", async () => {
|
|
const extra = ref(false);
|
|
const explicit = ref<number | undefined>(undefined);
|
|
const Wrapper = defineComponent({
|
|
props: { id: { type: String, required: true } },
|
|
setup:
|
|
(props, { slots }) =>
|
|
() =>
|
|
h(TableColumn, { id: props.id }, slots),
|
|
});
|
|
const w = mount(
|
|
defineComponent({
|
|
setup: () => ({ extra, explicit }),
|
|
render: () =>
|
|
h(Table, () =>
|
|
h(TableContent, () => [
|
|
h(TableHeader, () => [
|
|
h(TableColumn, { id: "name" }, () => "名"),
|
|
// Selection column and a wrapper-rendered column must count too.
|
|
h(TableColumn, { id: "select" }, () => "选"),
|
|
h(Wrapper, { id: "role" }, () => "角"),
|
|
...(extra.value
|
|
? [h(TableColumn, { id: "more" }, () => "增")]
|
|
: []),
|
|
]),
|
|
h(TableBody, { colspan: explicit.value }, { empty: () => "空" }),
|
|
]),
|
|
),
|
|
}),
|
|
{ attachTo: document.body },
|
|
);
|
|
await nextTick();
|
|
const cell = () =>
|
|
w.find("td[data-slot='table-empty-cell']").element as HTMLElement;
|
|
expect(cell().getAttribute("colspan")).toBe("3");
|
|
extra.value = true;
|
|
await nextTick();
|
|
expect(cell().getAttribute("colspan")).toBe("4");
|
|
extra.value = false;
|
|
await nextTick();
|
|
expect(cell().getAttribute("colspan")).toBe("3");
|
|
explicit.value = 1;
|
|
await nextTick();
|
|
expect(cell().getAttribute("colspan")).toBe("1");
|
|
w.unmount();
|
|
});
|
|
|
|
it("managed fr widths distribute the remaining space by weight with min/max clamping", async () => {
|
|
const original = HTMLElement.prototype.getBoundingClientRect;
|
|
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
|
|
function (this: HTMLElement) {
|
|
const width =
|
|
this.getAttribute("data-slot") === "table-content" ? 900 : 0;
|
|
return {
|
|
width,
|
|
height: 0,
|
|
x: 0,
|
|
y: 0,
|
|
top: 0,
|
|
left: 0,
|
|
right: width,
|
|
bottom: 0,
|
|
toJSON: () => ({}),
|
|
} as DOMRect;
|
|
},
|
|
);
|
|
try {
|
|
const minA = ref<number | undefined>(undefined);
|
|
const maxB = ref<number | undefined>(undefined);
|
|
const maxFixed = ref<number | undefined>(undefined);
|
|
const w = mount(
|
|
defineComponent({
|
|
setup: () => ({ minA, maxB }),
|
|
render: () =>
|
|
h(Table, () =>
|
|
h(TableContent, () =>
|
|
h(TableHeader, () => [
|
|
h(
|
|
TableColumn,
|
|
{ id: "a", defaultWidth: "1fr", minWidth: minA.value },
|
|
() => "A",
|
|
),
|
|
h(
|
|
TableColumn,
|
|
{ id: "b", defaultWidth: "2fr", maxWidth: maxB.value },
|
|
() => "B",
|
|
),
|
|
h(
|
|
TableColumn,
|
|
{ id: "c", width: 300, maxWidth: maxFixed.value },
|
|
() => "C",
|
|
),
|
|
]),
|
|
),
|
|
),
|
|
}),
|
|
{ attachTo: document.body },
|
|
);
|
|
await flushPromises();
|
|
const widths = () =>
|
|
w.findAll("th").map((th) => (th.element as HTMLElement).style.width);
|
|
// 900 available - 300 fixed = 600 shared 1:2 → 200 / 400.
|
|
expect(widths()).toEqual(["200px", "400px", "300px"]);
|
|
// Exact geometry: managed tables lock the layout algorithm.
|
|
expect((w.get("table").element as HTMLElement).style.tableLayout).toBe(
|
|
"fixed",
|
|
);
|
|
|
|
// Min clamp: raising A's floor to 400 freezes it and B takes the rest.
|
|
minA.value = 400;
|
|
await flushPromises();
|
|
expect(widths()).toEqual(["400px", "200px", "300px"]);
|
|
|
|
// Max clamp: capping B at 150 freezes it; A shares the remainder alone.
|
|
maxB.value = 150;
|
|
await flushPromises();
|
|
expect(widths()).toEqual(["450px", "150px", "300px"]);
|
|
maxFixed.value = 100;
|
|
await flushPromises();
|
|
expect(widths()).toEqual(["650px", "150px", "100px"]);
|
|
expect((w.findAll("th")[2].element as HTMLElement).style.minWidth).toBe("");
|
|
// Existing assigned pixels must not mask a narrower parent viewport.
|
|
Object.defineProperty(w.get("table").element.parentElement, "clientWidth", {
|
|
configurable: true,
|
|
value: 600,
|
|
});
|
|
maxFixed.value = 120;
|
|
await flushPromises();
|
|
expect(widths()).toEqual(["400px", "80px", "120px"]);
|
|
w.unmount();
|
|
} finally {
|
|
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockRestore();
|
|
void original;
|
|
}
|
|
});
|
|
|
|
it("sort activates once per click and forwards focus-visible to the column header", async () => {
|
|
const w = mountTable({ onSortChange: vi.fn() });
|
|
await flushPromises();
|
|
const th = w.get("th[data-allows-sorting]");
|
|
const button = w.get("button.hv-table__sortable-column-trigger");
|
|
await button.trigger("click");
|
|
await button.trigger("click");
|
|
const changes = w.getComponent(TableContent).emitted("sortChange") ?? [];
|
|
// One activation per click across the button → column bubbling path.
|
|
expect(changes).toHaveLength(2);
|
|
|
|
// The trigger owns keyboard focus; the ring is carried by the th through its
|
|
// real :focus-visible state (baseline position).
|
|
const originalMatches = HTMLElement.prototype.matches;
|
|
const matches = vi
|
|
.spyOn(HTMLElement.prototype, "matches")
|
|
.mockImplementation(function (this: HTMLElement, selector: string) {
|
|
if (selector === ":focus-visible")
|
|
return this.tagName === "BUTTON" && triggerFocused;
|
|
return originalMatches.call(this, selector);
|
|
});
|
|
let triggerFocused = false;
|
|
try {
|
|
triggerFocused = true;
|
|
await button.trigger("focus");
|
|
expect(th.attributes("data-focus-visible")).toBe("true");
|
|
triggerFocused = false;
|
|
await button.trigger("blur");
|
|
expect(th.attributes("data-focus-visible")).toBeUndefined();
|
|
} finally {
|
|
matches.mockRestore();
|
|
w.unmount();
|
|
}
|
|
});
|
|
|
|
it("invalid fr factors fall back to a finite share and terminate allocation", () => {
|
|
for (const spec of ["oopsfr", "NaNfr", "Infinityfr", "1e999fr"]) {
|
|
expect(parseFractionalUnit(spec)).toBe(1);
|
|
expect(
|
|
calculateColumnSizes(900, [{ width: spec }, { width: "2fr" }]),
|
|
).toEqual([300, 600]);
|
|
}
|
|
});
|