fix(table): align constrained widths and guard invalid fr factors

This commit is contained in:
maoyingjie
2026-10-29 11:11:10 +08:00
parent 86d76a0675
commit c019768e6a
6 changed files with 110 additions and 17 deletions
@@ -88,9 +88,8 @@ export default defineComponent({
const cssWidth = (value: string | number | undefined) => { const cssWidth = (value: string | number | undefined) => {
if (value === undefined) return undefined; if (value === undefined) return undefined;
if (typeof value === "number") return `${value}px`; if (typeof value === "number") return `${value}px`;
// CSS Grid fr units are not valid table widths. Treat Nfr as a flexible // fr is resolved by TableContent after measurement. Leave native layout
// column (native width:auto sharing remaining space). This does not // untouched until a managed pixel width is available.
// implement RAC fr weight proportions across columns.
if (/^\d+(\.\d+)?fr$/.test(value)) return undefined; if (/^\d+(\.\d+)?fr$/.test(value)) return undefined;
return value; return value;
}; };
@@ -118,7 +117,8 @@ export default defineComponent({
? `${resolvedWidth.value}px` ? `${resolvedWidth.value}px`
: cssWidth(width.value), : cssWidth(width.value),
minWidth: cssWidth( minWidth: cssWidth(
typeof width.value === "number" resolvedWidth.value === undefined &&
typeof width.value === "number"
? Math.max(props.minWidth ?? 0, width.value) ? Math.max(props.minWidth ?? 0, width.value)
: props.minWidth, : props.minWidth,
), ),
@@ -16,7 +16,7 @@ import {
} from "vue"; } from "vue";
import { useTableNavigation } from "./navigation"; import { useTableNavigation } from "./navigation";
import { useCollectionSelection } from "../collection/selection"; import { useCollectionSelection } from "../collection/selection";
import { calculateColumnSizes, isStaticWidth } from "./widths"; import { calculateColumnSizes } from "./widths";
import type { TableKey, TableColumnRegistration } from "./context"; import type { TableKey, TableColumnRegistration } from "./context";
import { tableContextKey, type TableSortDirection } from "./context"; import { tableContextKey, type TableSortDirection } from "./context";
@@ -227,14 +227,31 @@ export default defineComponent({
for (const entry of entries) entry.applyWidth?.(undefined); for (const entry of entries) entry.applyWidth?.(undefined);
return; return;
} }
const availableWidth = const table = element.value;
element.value?.getBoundingClientRect().width ?? 0; let availableWidth = table?.getBoundingClientRect().width ?? 0;
const parent = table?.parentElement;
if (table && parent) {
const parentStyle = getComputedStyle(parent);
const parentWidth =
parent.clientWidth -
(parseFloat(parentStyle.paddingLeft) || 0) -
(parseFloat(parentStyle.paddingRight) || 0);
// Assigned column pixels can keep a table wider than its shrinking
// viewport. Observe that constraint too, retaining an explicit table
// min-width for deliberate horizontal overflow.
if (parentWidth > 0)
availableWidth = Math.max(
parseFloat(getComputedStyle(table).minWidth) || 0,
Math.min(availableWidth, parentWidth),
);
}
if (!(availableWidth > 0)) return; if (!(availableWidth > 0)) return;
managedLayout.value = true; managedLayout.value = true;
const sizes = calculateColumnSizes(availableWidth, specs); const sizes = calculateColumnSizes(availableWidth, specs);
entries.forEach((entry, index) => { entries.forEach((entry, index) => {
if (isStaticWidth(specs[index].width)) entry.applyWidth?.(undefined); // Static columns must use the same clamped sizes deducted from the
else entry.applyWidth?.(sizes[index]); // remaining space, rather than their original width/percentage.
entry.applyWidth?.(sizes[index]);
}); });
} }
const layoutSignature = computed(() => const layoutSignature = computed(() =>
@@ -254,6 +271,8 @@ export default defineComponent({
if (typeof ResizeObserver !== "undefined" && element.value) { if (typeof ResizeObserver !== "undefined" && element.value) {
layoutObserver = new ResizeObserver(() => recomputeLayout()); layoutObserver = new ResizeObserver(() => recomputeLayout());
layoutObserver.observe(element.value); layoutObserver.observe(element.value);
if (element.value.parentElement)
layoutObserver.observe(element.value.parentElement);
} }
}); });
onBeforeUnmount(() => layoutObserver?.disconnect()); onBeforeUnmount(() => layoutObserver?.disconnect());
@@ -136,7 +136,8 @@ export default defineComponent({
if (!column?.allowsSorting.value && props.columnKey && ctx) if (!column?.allowsSorting.value && props.columnKey && ctx)
ctx.sort(props.columnKey); ctx.sort(props.columnKey);
}, },
onFocus: (event: FocusEvent) => forwardFocusVisible(event, true), onFocus: (event: FocusEvent) =>
forwardFocusVisible(event, true),
onBlur: (event: FocusEvent) => onBlur: (event: FocusEvent) =>
forwardFocusVisible(event, false), forwardFocusVisible(event, false),
}, },
+10 -3
View File
@@ -2,7 +2,9 @@
* Column width resolution for managed tables (explicit `fr` widths). * Column width resolution for managed tables (explicit `fr` widths).
* *
* Ported from react-stately `TableUtils.js` / `TableColumnLayout.js` * Ported from react-stately `TableUtils.js` / `TableColumnLayout.js`
* (Apache-2.0, https://github.com/adobe/react-spectrum) to keep the pinned * Copyright 2022 Adobe. All rights reserved.
* Licensed under Apache-2.0 (LICENSE.react-aria in the component package).
* (https://github.com/adobe/react-spectrum) to keep the pinned
* baseline's `defaultWidth="Nfr"` weight semantics: static widths (px / %) * baseline's `defaultWidth="Nfr"` weight semantics: static widths (px / %)
* are taken first, fractional widths share the remaining space by weight, * are taken first, fractional widths share the remaining space by weight,
* min/max clamp with flexbox-style violation freezing, and the rounded * min/max clamp with flexbox-style violation freezing, and the rounded
@@ -29,7 +31,9 @@ export function isStaticWidth(width: TableColumnWidthSpec): boolean {
export function parseFractionalUnit(width: TableColumnWidthSpec): number { export function parseFractionalUnit(width: TableColumnWidthSpec): number {
if (!width || typeof width === "number") return 1; if (!width || typeof width === "number") return 1;
const match = String(width).match(/^(.+)(?=fr$)/); const match = String(width).match(/^(.+)(?=fr$)/);
return match ? parseFloat(match[0]) : 1; const parsed = match ? Number(match[0]) : 1;
// A NaN/Infinity factor prevents violation freezing from converging.
return Number.isFinite(parsed) ? parsed : 1;
} }
/** Resolve a static width against the available width (percent support). */ /** Resolve a static width against the available width (percent support). */
@@ -169,7 +173,10 @@ export function calculateColumnSizes(
} }
hasNonFrozenItems = false; hasNonFrozenItems = false;
for (const item of flexItems) { for (const item of flexItems) {
if (totalViolation === 0 || Math.sign(totalViolation) === Math.sign(item.violation)) if (
totalViolation === 0 ||
Math.sign(totalViolation) === Math.sign(item.violation)
)
item.frozen = true; item.frozen = true;
else if (!item.frozen) hasNonFrozenItems = true; else if (!item.frozen) hasNonFrozenItems = true;
} }
+35 -2
View File
@@ -24,6 +24,9 @@ const widths = [620, 900, 1400];
const hostWidth = ref(900); const hostWidth = ref(900);
const rtl = ref(false); const rtl = ref(false);
const dark = ref(false); const dark = ref(false);
const layoutCase = ref("baseline");
const showRows = ref(true);
const extraColumn = ref(false);
watch( watch(
dark, dark,
(value) => { (value) => {
@@ -41,6 +44,14 @@ const rows = [
<template> <template>
<main style="padding: 24px; display: grid; gap: 16px"> <main style="padding: 24px; display: grid; gap: 16px">
<div style="display: flex; gap: 16px"> <div style="display: flex; gap: 16px">
<label>
边界场景
<select v-model="layoutCase">
<option value="baseline">常规列宽</option>
<option value="fixed-max">固定列超出上限</option>
<option value="invalid-fr">无效 fr 回退</option>
</select>
</label>
<label> <label>
容器宽度 容器宽度
<select v-model.number="hostWidth"> <select v-model.number="hostWidth">
@@ -57,6 +68,14 @@ const rows = [
<input v-model="dark" type="checkbox" /> <input v-model="dark" type="checkbox" />
深色主题 深色主题
</label> </label>
<label>
<input v-model="showRows" type="checkbox" />
显示数据
</label>
<label>
<input v-model="extraColumn" type="checkbox" />
增加列
</label>
</div> </div>
<div <div
id="table-host" id="table-host"
@@ -72,6 +91,7 @@ const rows = [
id="name" id="name"
allows-sorting allows-sorting
default-width="1fr" default-width="1fr"
:width="layoutCase === 'invalid-fr' ? 'oopsfr' : undefined"
:min-width="120" :min-width="120"
> >
<TableSortableColumnHeader>姓名</TableSortableColumnHeader> <TableSortableColumnHeader>姓名</TableSortableColumnHeader>
@@ -81,18 +101,31 @@ const rows = [
角色 角色
<TableColumnResizer /> <TableColumnResizer />
</TableColumn> </TableColumn>
<TableColumn id="status" :width="180">状态</TableColumn> <TableColumn
id="status"
:width="180"
:max-width="layoutCase === 'fixed-max' ? 100 : undefined"
>
状态
</TableColumn>
<TableColumn id="email" width="20%" :max-width="240"> <TableColumn id="email" width="20%" :max-width="240">
邮箱 邮箱
</TableColumn> </TableColumn>
<TableColumn v-if="extraColumn" id="extra">附加列</TableColumn>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
<TableRow v-for="row in rows" :key="row.id" :row-key="row.id"> <TableRow
v-for="row in showRows ? rows : []"
:key="row.id"
:row-key="row.id"
>
<TableCell>{{ row.name }}</TableCell> <TableCell>{{ row.name }}</TableCell>
<TableCell>{{ row.role }}</TableCell> <TableCell>{{ row.role }}</TableCell>
<TableCell>在职</TableCell> <TableCell>在职</TableCell>
<TableCell>{{ row.email }}</TableCell> <TableCell>{{ row.email }}</TableCell>
<TableCell v-if="extraColumn">附加内容</TableCell>
</TableRow> </TableRow>
<template #empty>未找到结果</template>
</TableBody> </TableBody>
</TableContent> </TableContent>
</TableScrollContainer> </TableScrollContainer>
+35 -2
View File
@@ -1,6 +1,10 @@
import { afterEach, expect, it, vi } from "vitest"; import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils"; import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue"; import { defineComponent, h, nextTick, ref } from "vue";
import {
calculateColumnSizes,
parseFractionalUnit,
} from "../packages/vue/src/components/table/widths";
import { import {
Table, Table,
TableBody, TableBody,
@@ -247,6 +251,7 @@ it("empty state spans every leaf column by default and honors explicit colspan",
explicit.value = 1; explicit.value = 1;
await nextTick(); await nextTick();
expect(cell().getAttribute("colspan")).toBe("1"); expect(cell().getAttribute("colspan")).toBe("1");
w.unmount();
}); });
it("managed fr widths distribute the remaining space by weight with min/max clamping", async () => { it("managed fr widths distribute the remaining space by weight with min/max clamping", async () => {
@@ -271,6 +276,7 @@ it("managed fr widths distribute the remaining space by weight with min/max clam
try { try {
const minA = ref<number | undefined>(undefined); const minA = ref<number | undefined>(undefined);
const maxB = ref<number | undefined>(undefined); const maxB = ref<number | undefined>(undefined);
const maxFixed = ref<number | undefined>(undefined);
const w = mount( const w = mount(
defineComponent({ defineComponent({
setup: () => ({ minA, maxB }), setup: () => ({ minA, maxB }),
@@ -288,7 +294,11 @@ it("managed fr widths distribute the remaining space by weight with min/max clam
{ id: "b", defaultWidth: "2fr", maxWidth: maxB.value }, { id: "b", defaultWidth: "2fr", maxWidth: maxB.value },
() => "B", () => "B",
), ),
h(TableColumn, { id: "c", width: 300 }, () => "C"), h(
TableColumn,
{ id: "c", width: 300, maxWidth: maxFixed.value },
() => "C",
),
]), ]),
), ),
), ),
@@ -314,6 +324,19 @@ it("managed fr widths distribute the remaining space by weight with min/max clam
maxB.value = 150; maxB.value = 150;
await flushPromises(); await flushPromises();
expect(widths()).toEqual(["450px", "150px", "300px"]); 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 { } finally {
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockRestore(); vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockRestore();
void original; void original;
@@ -333,6 +356,7 @@ it("sort activates once per click and forwards focus-visible to the column heade
// The trigger owns keyboard focus; the ring is carried by the th through its // The trigger owns keyboard focus; the ring is carried by the th through its
// real :focus-visible state (baseline position). // real :focus-visible state (baseline position).
const originalMatches = HTMLElement.prototype.matches;
const matches = vi const matches = vi
.spyOn(HTMLElement.prototype, "matches") .spyOn(HTMLElement.prototype, "matches")
.mockImplementation(function (this: HTMLElement, selector: string) { .mockImplementation(function (this: HTMLElement, selector: string) {
@@ -340,7 +364,6 @@ it("sort activates once per click and forwards focus-visible to the column heade
return this.tagName === "BUTTON" && triggerFocused; return this.tagName === "BUTTON" && triggerFocused;
return originalMatches.call(this, selector); return originalMatches.call(this, selector);
}); });
const originalMatches = HTMLElement.prototype.matches;
let triggerFocused = false; let triggerFocused = false;
try { try {
triggerFocused = true; triggerFocused = true;
@@ -351,5 +374,15 @@ it("sort activates once per click and forwards focus-visible to the column heade
expect(th.attributes("data-focus-visible")).toBeUndefined(); expect(th.attributes("data-focus-visible")).toBeUndefined();
} finally { } finally {
matches.mockRestore(); 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]);
} }
}); });