Files
heroui-vue/tests/table.test.ts
T
maoyingjie 658dfbb7d9 fix(table): full-width empty state, sort focus ring and fr column widths
HD-08 scope, against heroui ce90ea3 table sources and their
react-aria/react-stately dependencies:

- TableBody empty state now spans every real leaf column by default
  (self-registered TableColumns — selection and wrapper-rendered ones
  included — reactively following column changes), explicit colspan
  still wins, and the vnode-level empty detection keeps avoiding
  unknown-component setup/render probing
- sorting keeps one activation per click/Enter/Space (single sort path
  via the column) while the baseline focus ring returns: the trigger
  button keeps keyboard focus and forwards its real :focus-visible
  state to the th's existing [data-focus-visible] hook, so the inset
  ring lands on the column header like the pinned source and the UA
  outline is suppressed only inside a column; aria-sort="none" on
  sortable unsorted columns matches useTableColumnHeader and stays
- defaultWidth="Nfr" distributes the remaining width by weight
  instead of silently becoming auto: widths.ts ports react-stately's
  calculateColumnSizes (static px/% first, fr flex-grow sharing,
  min/max violation freezing, cascade rounding); fr mode locks
  table-layout: fixed for exact geometry, re-shares on container
  resize, freezes dragged columns to their pixel width and keeps
  geometry (with flipped drag direction) in RTL; unmeasured
  environments keep native widths
- .table__cell's text-start/font-normal verified to block caller
  inheritance and narrowed to th.hv-table__cell { inherit }, keeping
  the baseline td row-header typography while ancestor align/weight
  cascade into cells again; th scope=row, corner selectors and the
  resizer z-index fix are untouched
- tests/fixtures/table-layout.vue (playground) drives the real-browser
  geometry/drag/RTL/theme verification; m35-m36 contract pins the two
  new CSS markers in the final tarball

Full suite 111 files / 1657 tests, typecheck, build:docs and the
m35-m36 + handbook-styles tarball contracts pass.
2026-10-29 10:59:24 +08:00

356 lines
11 KiB
TypeScript

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();
});
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");
});
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 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 }, () => "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"]);
} 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 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);
});
const originalMatches = HTMLElement.prototype.matches;
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();
}
});