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.
This commit is contained in:
@@ -90,10 +90,10 @@ export default defineComponent({
|
||||
* (TableRow/native tr, TableCollection.items) and no rows registered.
|
||||
*/
|
||||
empty: { type: Boolean, default: undefined },
|
||||
/** Colspan of the empty-state cell. */
|
||||
/** Colspan of the empty-state cell. Defaults to the real leaf column count. */
|
||||
colspan: {
|
||||
type: [Number, String] as PropType<number | string>,
|
||||
default: 1,
|
||||
default: undefined,
|
||||
},
|
||||
},
|
||||
setup(props, { slots }) {
|
||||
@@ -134,6 +134,11 @@ export default defineComponent({
|
||||
function renderEmptyRow() {
|
||||
const content = slots.empty?.();
|
||||
if (!content) return null;
|
||||
// Explicit colspan wins; otherwise span every real leaf column
|
||||
// (selection and wrapper-rendered TableColumns self-register), falling
|
||||
// back to a single cell before any column is known.
|
||||
const columns = ctx?.columns?.value.size ?? 0;
|
||||
const colspan = props.colspan ?? (columns > 0 ? columns : 1);
|
||||
return h(
|
||||
"tr",
|
||||
{
|
||||
@@ -147,7 +152,7 @@ export default defineComponent({
|
||||
{
|
||||
class: "hv-table__empty-cell",
|
||||
"data-slot": "table-empty-cell",
|
||||
colspan: props.colspan,
|
||||
colspan,
|
||||
role: "presentation",
|
||||
},
|
||||
content,
|
||||
|
||||
@@ -42,7 +42,16 @@ export default defineComponent({
|
||||
([node, id, isRowHeader]) => {
|
||||
if (!ctx?.columns) return;
|
||||
const next = new Map(ctx.columns.value);
|
||||
if (node) next.set(token, { node, id, isRowHeader });
|
||||
if (node)
|
||||
next.set(token, {
|
||||
node,
|
||||
id,
|
||||
isRowHeader,
|
||||
widthSpec,
|
||||
applyWidth: (px: number | undefined) => {
|
||||
resolvedWidth.value = px;
|
||||
},
|
||||
});
|
||||
else next.delete(token);
|
||||
ctx.columns.value = next;
|
||||
},
|
||||
@@ -59,6 +68,8 @@ export default defineComponent({
|
||||
const width = computed(() =>
|
||||
props.width !== undefined ? props.width : internalWidth.value,
|
||||
);
|
||||
/** Pixel width resolved by the managed (fr) layout; unset stays native. */
|
||||
const resolvedWidth = ref<number | undefined>(undefined);
|
||||
const setWidth = (next: number) => {
|
||||
if (props.width === undefined) internalWidth.value = next;
|
||||
emit("update:width", next);
|
||||
@@ -69,6 +80,11 @@ export default defineComponent({
|
||||
width,
|
||||
setWidth,
|
||||
});
|
||||
const widthSpec = () => ({
|
||||
width: width.value,
|
||||
minWidth: props.minWidth,
|
||||
maxWidth: props.maxWidth,
|
||||
});
|
||||
const cssWidth = (value: string | number | undefined) => {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value === "number") return `${value}px`;
|
||||
@@ -97,7 +113,10 @@ export default defineComponent({
|
||||
ref: element,
|
||||
class: [ctx?.slots.value.column(), attrs.class],
|
||||
style: {
|
||||
width: cssWidth(width.value),
|
||||
width:
|
||||
resolvedWidth.value !== undefined
|
||||
? `${resolvedWidth.value}px`
|
||||
: cssWidth(width.value),
|
||||
minWidth: cssWidth(
|
||||
typeof width.value === "number"
|
||||
? Math.max(props.minWidth ?? 0, width.value)
|
||||
|
||||
@@ -8,13 +8,17 @@ import {
|
||||
ref,
|
||||
shallowRef,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
watch,
|
||||
type PropType,
|
||||
} from "vue";
|
||||
import { useTableNavigation } from "./navigation";
|
||||
import { useCollectionSelection } from "../collection/selection";
|
||||
import { calculateColumnSizes, isStaticWidth } from "./widths";
|
||||
|
||||
import type { TableKey } from "./context";
|
||||
import type { TableKey, TableColumnRegistration } from "./context";
|
||||
import { tableContextKey, type TableSortDirection } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
@@ -175,13 +179,14 @@ export default defineComponent({
|
||||
emit("expandedChange", next);
|
||||
}
|
||||
|
||||
const columns = shallowRef(new Map<symbol, TableColumnRegistration>());
|
||||
provide(tableContextKey, {
|
||||
...(parentCtx ?? {
|
||||
slots: computed(() => ({}) as never),
|
||||
variant: computed(() => "primary"),
|
||||
}),
|
||||
navigation,
|
||||
columns: shallowRef(new Map()),
|
||||
columns,
|
||||
columnDefinitions: shallowRef([]),
|
||||
selectionMode: computed(() => props.selectionMode),
|
||||
selectedKeys,
|
||||
@@ -198,12 +203,68 @@ export default defineComponent({
|
||||
sort,
|
||||
});
|
||||
|
||||
/**
|
||||
* Managed column widths: when any column declares an `fr` width the pinned
|
||||
* baseline weight semantics apply (react-stately TableColumnLayout): static
|
||||
* widths (px / %) are taken first, fr columns share the remaining width by
|
||||
* weight with min/max clamping, and unset columns count as 1fr. Unmeasured
|
||||
* environments (jsdom, display:none) keep native widths untouched.
|
||||
*/
|
||||
const managedLayout = ref(false);
|
||||
function orderedColumns() {
|
||||
return [...columns.value.values()].sort((a, b) =>
|
||||
a.node.compareDocumentPosition(b.node) & 2 ? 1 : -1,
|
||||
);
|
||||
}
|
||||
function recomputeLayout() {
|
||||
const entries = orderedColumns();
|
||||
const specs = entries.map((entry) => entry.widthSpec?.() ?? {});
|
||||
const managed = specs.some(
|
||||
(spec) => typeof spec.width === "string" && spec.width.endsWith("fr"),
|
||||
);
|
||||
if (!managed) {
|
||||
managedLayout.value = false;
|
||||
for (const entry of entries) entry.applyWidth?.(undefined);
|
||||
return;
|
||||
}
|
||||
const availableWidth =
|
||||
element.value?.getBoundingClientRect().width ?? 0;
|
||||
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]);
|
||||
});
|
||||
}
|
||||
const layoutSignature = computed(() =>
|
||||
[...columns.value.values()]
|
||||
.map((entry) => {
|
||||
const spec = entry.widthSpec?.();
|
||||
return `${String(spec?.width)}|${spec?.minWidth}|${spec?.maxWidth}`;
|
||||
})
|
||||
.join(";"),
|
||||
);
|
||||
watch([layoutSignature, columns], () => void nextTick(recomputeLayout), {
|
||||
flush: "post",
|
||||
});
|
||||
let layoutObserver: ResizeObserver | undefined;
|
||||
onMounted(() => {
|
||||
recomputeLayout();
|
||||
if (typeof ResizeObserver !== "undefined" && element.value) {
|
||||
layoutObserver = new ResizeObserver(() => recomputeLayout());
|
||||
layoutObserver.observe(element.value);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => layoutObserver?.disconnect());
|
||||
|
||||
return () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(attrs, {
|
||||
ref: element,
|
||||
class: parentCtx?.slots.value.content(),
|
||||
style: managedLayout.value ? { tableLayout: "fixed" } : undefined,
|
||||
"data-slot": "table-content",
|
||||
role:
|
||||
attrs.role ??
|
||||
|
||||
@@ -95,6 +95,21 @@ export default defineComponent({
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
/**
|
||||
* The trigger button owns keyboard focus (click/Enter/Space each activate
|
||||
* once through the column's single sort path). The visible focus ring
|
||||
* stays on the column header like the pinned baseline, by forwarding the
|
||||
* real `:focus-visible` state onto the th's existing `data-focus-visible`
|
||||
* hook — the trigger's own native outline is suppressed inside a column.
|
||||
*/
|
||||
const forwardFocusVisible = (event: FocusEvent, active: boolean) => {
|
||||
const trigger = event.currentTarget as HTMLElement | null;
|
||||
const th = trigger?.closest("th");
|
||||
if (!th) return;
|
||||
if (active && trigger?.matches(":focus-visible"))
|
||||
th.setAttribute("data-focus-visible", "true");
|
||||
else th.removeAttribute("data-focus-visible");
|
||||
};
|
||||
return h(
|
||||
props.as,
|
||||
{
|
||||
@@ -121,6 +136,9 @@ export default defineComponent({
|
||||
if (!column?.allowsSorting.value && props.columnKey && ctx)
|
||||
ctx.sort(props.columnKey);
|
||||
},
|
||||
onFocus: (event: FocusEvent) => forwardFocusVisible(event, true),
|
||||
onBlur: (event: FocusEvent) =>
|
||||
forwardFocusVisible(event, false),
|
||||
},
|
||||
),
|
||||
[slots.default?.(), renderIndicator()],
|
||||
|
||||
@@ -7,11 +7,23 @@ import type { tableVariants } from "@heroui-vue/styles";
|
||||
export type TableSlots = ReturnType<typeof tableVariants>;
|
||||
export type TableSortDirection = "ascending" | "descending" | "none";
|
||||
|
||||
export interface TableColumnRegistration {
|
||||
node: HTMLElement;
|
||||
id?: string;
|
||||
isRowHeader: boolean;
|
||||
/** Reactive width spec for managed (fr) layout: controlled or default width. */
|
||||
widthSpec?: () => {
|
||||
width?: string | number;
|
||||
minWidth?: number;
|
||||
maxWidth?: number;
|
||||
};
|
||||
/** Apply (or clear, with undefined) a computed pixel width on a flexible column. */
|
||||
applyWidth?: (px: number | undefined) => void;
|
||||
}
|
||||
|
||||
export interface TableContextValue {
|
||||
columnDefinitions?: Ref<{ id?: string; isRowHeader: boolean }[]>;
|
||||
columns?: Ref<
|
||||
Map<symbol, { node: HTMLElement; id?: string; isRowHeader: boolean }>
|
||||
>;
|
||||
columns?: Ref<Map<symbol, TableColumnRegistration>>;
|
||||
navigation?: ReturnType<typeof useTableNavigation>;
|
||||
slots: ComputedRef<TableSlots>;
|
||||
variant: ComputedRef<string>;
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* 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
|
||||
* 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
|
||||
* integer sizes sum exactly to the available width.
|
||||
*/
|
||||
|
||||
export type TableColumnWidthSpec = string | number | undefined;
|
||||
|
||||
export interface TableColumnSizeInput {
|
||||
/** Resolved width spec: px number, "N%", "Nfr" or undefined (= 1fr here). */
|
||||
width?: TableColumnWidthSpec;
|
||||
minWidth?: TableColumnWidthSpec;
|
||||
maxWidth?: TableColumnWidthSpec;
|
||||
}
|
||||
|
||||
/** Static widths are numbers or integer percents, matching the baseline parser. */
|
||||
export function isStaticWidth(width: TableColumnWidthSpec): boolean {
|
||||
return (
|
||||
width != null && (!isNaN(Number(width)) || /^\d+%$/.test(String(width)))
|
||||
);
|
||||
}
|
||||
|
||||
/** "Nfr" weight; invalid fr strings fall back to 1 like the baseline. */
|
||||
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;
|
||||
}
|
||||
|
||||
/** Resolve a static width against the available width (percent support). */
|
||||
export function parseStaticWidth(
|
||||
width: TableColumnWidthSpec,
|
||||
availableWidth: number,
|
||||
): number {
|
||||
if (typeof width === "string") {
|
||||
const match = width.match(/^(\d+)(?=%$)/);
|
||||
if (!match)
|
||||
throw new Error(
|
||||
"Only percentages or numbers are supported for static column widths",
|
||||
);
|
||||
return availableWidth * (parseFloat(match[0]) / 100);
|
||||
}
|
||||
return width as number;
|
||||
}
|
||||
|
||||
export function resolveMaxWidth(
|
||||
maxWidth: TableColumnWidthSpec,
|
||||
availableWidth: number,
|
||||
): number {
|
||||
return maxWidth != null
|
||||
? parseStaticWidth(maxWidth, availableWidth)
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
|
||||
export function resolveMinWidth(
|
||||
minWidth: TableColumnWidthSpec,
|
||||
availableWidth: number,
|
||||
): number {
|
||||
return minWidth != null ? parseStaticWidth(minWidth, availableWidth) : 0;
|
||||
}
|
||||
|
||||
interface FlexItem {
|
||||
frozen: boolean;
|
||||
baseSize: number;
|
||||
hypotheticalMainSize: number;
|
||||
min: number;
|
||||
max: number;
|
||||
flex: number;
|
||||
targetMainSize: number;
|
||||
violation: number;
|
||||
}
|
||||
|
||||
function cascadeRounding(items: FlexItem[]): number[] {
|
||||
// Rounds floats that sum to an integer into integers with the same sum.
|
||||
let fpTotal = 0;
|
||||
let intTotal = 0;
|
||||
const rounded: number[] = [];
|
||||
for (const item of items) {
|
||||
const float = item.targetMainSize;
|
||||
const integer = Math.round(float + fpTotal) - intTotal;
|
||||
fpTotal += float;
|
||||
intTotal += integer;
|
||||
rounded.push(integer);
|
||||
}
|
||||
return rounded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve every column width (px) for the given available width.
|
||||
* Unset widths count as `1fr`, matching the pinned TableColumnLayout default.
|
||||
*/
|
||||
export function calculateColumnSizes(
|
||||
availableWidth: number,
|
||||
columns: TableColumnSizeInput[],
|
||||
): number[] {
|
||||
const originalWidth = availableWidth;
|
||||
const flooredWidth = Math.floor(availableWidth);
|
||||
const hasFractionalWidth = availableWidth - flooredWidth > 0;
|
||||
availableWidth = flooredWidth;
|
||||
|
||||
let hasNonFrozenItems = false;
|
||||
const flexItems: FlexItem[] = columns.map((column) => {
|
||||
const width = column.width ?? "1fr";
|
||||
let frozen = false;
|
||||
let baseSize = 0;
|
||||
let flex = 0;
|
||||
let targetMainSize = 0;
|
||||
if (isStaticWidth(width)) {
|
||||
baseSize = parseStaticWidth(width, availableWidth);
|
||||
frozen = true;
|
||||
} else {
|
||||
flex = parseFractionalUnit(width);
|
||||
if (flex <= 0) frozen = true;
|
||||
}
|
||||
const min = resolveMinWidth(column.minWidth, availableWidth);
|
||||
const max = resolveMaxWidth(column.maxWidth, availableWidth);
|
||||
const hypotheticalMainSize = Math.max(min, Math.min(baseSize, max));
|
||||
// Flexbox §9.7 grow-only resolution.
|
||||
if (frozen) targetMainSize = hypotheticalMainSize;
|
||||
else if (baseSize > hypotheticalMainSize) {
|
||||
frozen = true;
|
||||
targetMainSize = hypotheticalMainSize;
|
||||
}
|
||||
if (!frozen) hasNonFrozenItems = true;
|
||||
return {
|
||||
frozen,
|
||||
baseSize,
|
||||
hypotheticalMainSize,
|
||||
min,
|
||||
max,
|
||||
flex,
|
||||
targetMainSize,
|
||||
violation: 0,
|
||||
};
|
||||
});
|
||||
|
||||
while (hasNonFrozenItems) {
|
||||
let usedWidth = 0;
|
||||
let flexFactors = 0;
|
||||
for (const item of flexItems) {
|
||||
if (item.frozen) usedWidth += item.targetMainSize;
|
||||
else {
|
||||
usedWidth += item.baseSize;
|
||||
flexFactors += item.flex;
|
||||
}
|
||||
}
|
||||
const remainingFreeSpace = availableWidth - usedWidth;
|
||||
if (remainingFreeSpace > 0)
|
||||
for (const item of flexItems) {
|
||||
if (!item.frozen) {
|
||||
const ratio = item.flex / flexFactors;
|
||||
item.targetMainSize = item.baseSize + ratio * remainingFreeSpace;
|
||||
}
|
||||
}
|
||||
let totalViolation = 0;
|
||||
for (const item of flexItems) {
|
||||
item.violation = 0;
|
||||
if (!item.frozen) {
|
||||
const { min, max, targetMainSize } = item;
|
||||
item.targetMainSize = Math.max(min, Math.min(targetMainSize, max));
|
||||
item.violation = item.targetMainSize - targetMainSize;
|
||||
totalViolation += item.violation;
|
||||
}
|
||||
}
|
||||
hasNonFrozenItems = false;
|
||||
for (const item of flexItems) {
|
||||
if (totalViolation === 0 || Math.sign(totalViolation) === Math.sign(item.violation))
|
||||
item.frozen = true;
|
||||
else if (!item.frozen) hasNonFrozenItems = true;
|
||||
}
|
||||
}
|
||||
|
||||
const columnSizes = cascadeRounding(flexItems);
|
||||
// Give the leftover sub-pixel width to the last column so the sizes sum
|
||||
// exactly to the (possibly fractional) available width.
|
||||
if (hasFractionalWidth && columnSizes.length > 0) {
|
||||
const tableFractionalWidth = String(originalWidth).split(".")[1];
|
||||
const columnWidth = String(columnSizes[columnSizes.length - 1]);
|
||||
columnSizes[columnSizes.length - 1] = Number(
|
||||
`${columnWidth}.${tableFractionalWidth}`,
|
||||
);
|
||||
}
|
||||
return columnSizes;
|
||||
}
|
||||
Reference in New Issue
Block a user