fix(table): align constrained widths and guard invalid fr factors
This commit is contained in:
@@ -88,9 +88,8 @@ export default defineComponent({
|
||||
const cssWidth = (value: string | number | undefined) => {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value === "number") return `${value}px`;
|
||||
// CSS Grid fr units are not valid table widths. Treat Nfr as a flexible
|
||||
// column (native width:auto sharing remaining space). This does not
|
||||
// implement RAC fr weight proportions across columns.
|
||||
// fr is resolved by TableContent after measurement. Leave native layout
|
||||
// untouched until a managed pixel width is available.
|
||||
if (/^\d+(\.\d+)?fr$/.test(value)) return undefined;
|
||||
return value;
|
||||
};
|
||||
@@ -118,7 +117,8 @@ export default defineComponent({
|
||||
? `${resolvedWidth.value}px`
|
||||
: cssWidth(width.value),
|
||||
minWidth: cssWidth(
|
||||
typeof width.value === "number"
|
||||
resolvedWidth.value === undefined &&
|
||||
typeof width.value === "number"
|
||||
? Math.max(props.minWidth ?? 0, width.value)
|
||||
: props.minWidth,
|
||||
),
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "vue";
|
||||
import { useTableNavigation } from "./navigation";
|
||||
import { useCollectionSelection } from "../collection/selection";
|
||||
import { calculateColumnSizes, isStaticWidth } from "./widths";
|
||||
import { calculateColumnSizes } from "./widths";
|
||||
|
||||
import type { TableKey, TableColumnRegistration } from "./context";
|
||||
import { tableContextKey, type TableSortDirection } from "./context";
|
||||
@@ -227,14 +227,31 @@ export default defineComponent({
|
||||
for (const entry of entries) entry.applyWidth?.(undefined);
|
||||
return;
|
||||
}
|
||||
const availableWidth =
|
||||
element.value?.getBoundingClientRect().width ?? 0;
|
||||
const table = element.value;
|
||||
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;
|
||||
managedLayout.value = true;
|
||||
const sizes = calculateColumnSizes(availableWidth, specs);
|
||||
entries.forEach((entry, index) => {
|
||||
if (isStaticWidth(specs[index].width)) entry.applyWidth?.(undefined);
|
||||
else entry.applyWidth?.(sizes[index]);
|
||||
// Static columns must use the same clamped sizes deducted from the
|
||||
// remaining space, rather than their original width/percentage.
|
||||
entry.applyWidth?.(sizes[index]);
|
||||
});
|
||||
}
|
||||
const layoutSignature = computed(() =>
|
||||
@@ -254,6 +271,8 @@ export default defineComponent({
|
||||
if (typeof ResizeObserver !== "undefined" && element.value) {
|
||||
layoutObserver = new ResizeObserver(() => recomputeLayout());
|
||||
layoutObserver.observe(element.value);
|
||||
if (element.value.parentElement)
|
||||
layoutObserver.observe(element.value.parentElement);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => layoutObserver?.disconnect());
|
||||
|
||||
@@ -136,7 +136,8 @@ export default defineComponent({
|
||||
if (!column?.allowsSorting.value && props.columnKey && ctx)
|
||||
ctx.sort(props.columnKey);
|
||||
},
|
||||
onFocus: (event: FocusEvent) => forwardFocusVisible(event, true),
|
||||
onFocus: (event: FocusEvent) =>
|
||||
forwardFocusVisible(event, true),
|
||||
onBlur: (event: FocusEvent) =>
|
||||
forwardFocusVisible(event, false),
|
||||
},
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
* Column width resolution for managed tables (explicit `fr` widths).
|
||||
*
|
||||
* 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 / %)
|
||||
* are taken first, fractional widths share the remaining space by weight,
|
||||
* 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 {
|
||||
if (!width || typeof width === "number") return 1;
|
||||
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). */
|
||||
@@ -169,7 +173,10 @@ export function calculateColumnSizes(
|
||||
}
|
||||
hasNonFrozenItems = false;
|
||||
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;
|
||||
else if (!item.frozen) hasNonFrozenItems = true;
|
||||
}
|
||||
|
||||
Vendored
+35
-2
@@ -24,6 +24,9 @@ const widths = [620, 900, 1400];
|
||||
const hostWidth = ref(900);
|
||||
const rtl = ref(false);
|
||||
const dark = ref(false);
|
||||
const layoutCase = ref("baseline");
|
||||
const showRows = ref(true);
|
||||
const extraColumn = ref(false);
|
||||
watch(
|
||||
dark,
|
||||
(value) => {
|
||||
@@ -41,6 +44,14 @@ const rows = [
|
||||
<template>
|
||||
<main style="padding: 24px; display: grid; 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>
|
||||
容器宽度
|
||||
<select v-model.number="hostWidth">
|
||||
@@ -57,6 +68,14 @@ const rows = [
|
||||
<input v-model="dark" type="checkbox" />
|
||||
深色主题
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="showRows" type="checkbox" />
|
||||
显示数据
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="extraColumn" type="checkbox" />
|
||||
增加列
|
||||
</label>
|
||||
</div>
|
||||
<div
|
||||
id="table-host"
|
||||
@@ -72,6 +91,7 @@ const rows = [
|
||||
id="name"
|
||||
allows-sorting
|
||||
default-width="1fr"
|
||||
:width="layoutCase === 'invalid-fr' ? 'oopsfr' : undefined"
|
||||
:min-width="120"
|
||||
>
|
||||
<TableSortableColumnHeader>姓名</TableSortableColumnHeader>
|
||||
@@ -81,18 +101,31 @@ const rows = [
|
||||
角色
|
||||
<TableColumnResizer />
|
||||
</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>
|
||||
<TableColumn v-if="extraColumn" id="extra">附加列</TableColumn>
|
||||
</TableHeader>
|
||||
<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.role }}</TableCell>
|
||||
<TableCell>在职</TableCell>
|
||||
<TableCell>{{ row.email }}</TableCell>
|
||||
<TableCell v-if="extraColumn">附加内容</TableCell>
|
||||
</TableRow>
|
||||
<template #empty>未找到结果</template>
|
||||
</TableBody>
|
||||
</TableContent>
|
||||
</TableScrollContainer>
|
||||
|
||||
+35
-2
@@ -1,6 +1,10 @@
|
||||
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,
|
||||
@@ -247,6 +251,7 @@ it("empty state spans every leaf column by default and honors explicit colspan",
|
||||
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 () => {
|
||||
@@ -271,6 +276,7 @@ it("managed fr widths distribute the remaining space by weight with min/max clam
|
||||
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 }),
|
||||
@@ -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 },
|
||||
() => "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;
|
||||
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;
|
||||
@@ -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
|
||||
// real :focus-visible state (baseline position).
|
||||
const originalMatches = HTMLElement.prototype.matches;
|
||||
const matches = vi
|
||||
.spyOn(HTMLElement.prototype, "matches")
|
||||
.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 originalMatches.call(this, selector);
|
||||
});
|
||||
const originalMatches = HTMLElement.prototype.matches;
|
||||
let triggerFocused = false;
|
||||
try {
|
||||
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();
|
||||
} 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]);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user