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:
@@ -60,6 +60,8 @@ import {
|
||||
|
||||
在 `TableColumn` 上使用 `allows-sorting` 属性可启用列排序。在 `TableContent` 上使用 `sort-descriptor` 与 `update:sort-descriptor` 管理排序状态。将标签包裹在 `TableSortableColumnHeader` 中,并传入列的 `sort-direction` 以渲染默认升序/降序指示器。
|
||||
|
||||
列头是唯一的排序入口:点击、Enter、Space 各触发一次排序(`TableSortableColumnHeader` 的触发按钮承担键盘焦点,点击经冒泡汇入列的单一排序路径)。焦点环显示在列头 `th` 上(基线位置):触发按钮把真实 `:focus-visible` 状态转发到 `th` 的 `[data-focus-visible]` 钩子,按钮自身的 UA 轮廓在列内被抑制。
|
||||
|
||||
<ComponentPreview name="table-sorting" minHeight="380px" />
|
||||
|
||||
### 选择
|
||||
@@ -82,7 +84,7 @@ import {
|
||||
|
||||
### 列宽调整
|
||||
|
||||
将表格包裹在 `TableResizableContainer` 中,并在每个可调整宽度的列内添加 `TableColumnResizer`。列可用 `default-width="1fr"` 表示弹性初始宽度(映射为原生 `width: auto`,共享剩余空间;不实现 RAC 的 fr 权重比例)。
|
||||
将表格包裹在 `TableResizableContainer` 中,并在每个可调整宽度的列内添加 `TableColumnResizer`。列可用 `default-width="Nfr"` 表示按权重分配剩余宽度(与固定源一致):数字为 px、`N%` 为百分比,`Nfr` 列共享扣除固定/百分比列后的剩余宽度并按权重比例分配;未显式设置宽度的列在存在 `fr` 列时按 `1fr` 参与分配。`min-width` / `max-width` 对每列份额生效(超出时按 flex 语义冻结违规列并把余量再分配),容器缩放会重新分配、拖动后的列冻结为其像素宽度,RTL 下几何一致、拖动方向相反。
|
||||
|
||||
<ComponentPreview name="table-column-resizing" minHeight="420px" />
|
||||
|
||||
@@ -223,25 +225,25 @@ Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制
|
||||
|
||||
### TableColumn
|
||||
|
||||
| Prop / 事件 | 类型 | 默认值 | 描述 |
|
||||
| ------------------------------- | ------------------ | ------- | --------------------------------------------------------------------- |
|
||||
| `as` | `string` | `'th'` | 列头标签,scope=col |
|
||||
| `id` | `string` | — | 排序与树形列 id |
|
||||
| `allowsSorting` / `isRowHeader` | `boolean` | `false` | 排序列 / 对应正文单元格为 th[scope=row] |
|
||||
| `width` / `defaultWidth` | `number \| string` | — | 受控宽度 / 非受控初始宽度;数字为 px,`Nfr` 为弹性 auto(非权重比例) |
|
||||
| `minWidth` / `maxWidth` | `number` | — | 宽度上下限,优先于 Resizer 的缺省边界 |
|
||||
| `update:width` | `number` | — | 拖动/键盘提出的宽度,可使用 v-model:width |
|
||||
| 默认插槽 | 内容 | — | 列标签及排序、调整手柄 |
|
||||
| Prop / 事件 | 类型 | 默认值 | 描述 |
|
||||
| ------------------------------- | ------------------ | ------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| `as` | `string` | `'th'` | 列头标签,scope=col |
|
||||
| `id` | `string` | — | 排序与树形列 id |
|
||||
| `allowsSorting` / `isRowHeader` | `boolean` | `false` | 排序列 / 对应正文单元格为 th[scope=row] |
|
||||
| `width` / `defaultWidth` | `number \| string` | — | 受控宽度 / 非受控初始宽度;数字为 px,`N%` 为百分比,`Nfr` 按权重分配剩余宽度(存在 fr 列时未设宽度的列按 `1fr` 参与) |
|
||||
| `minWidth` / `maxWidth` | `number` | — | 宽度上下限,优先于 Resizer 的缺省边界 |
|
||||
| `update:width` | `number` | — | 拖动/键盘提出的宽度,可使用 v-model:width |
|
||||
| 默认插槽 | 内容 | — | 列标签及排序、调整手柄 |
|
||||
|
||||
### TableBody
|
||||
|
||||
| Prop / 插槽 | 类型 | 默认值 | 描述 |
|
||||
| ----------- | ------------------ | --------- | --------------------------------------------------------------------------- |
|
||||
| `as` | `string` | `'tbody'` | 正文根 |
|
||||
| `empty` | `boolean` | 自动判断 | 为 `true` 时强制空状态;省略时若默认插槽未渲染任何行则视为空 |
|
||||
| `colspan` | `number \| string` | `1` | 空状态单元格跨列数 |
|
||||
| 默认插槽 | 行内容 | — | 动态行使用 v-for |
|
||||
| `#empty` | 空状态 | — | 空数据时渲染;包在 `role="presentation"` 行内,不参与选择、行计数与键盘导航 |
|
||||
| Prop / 插槽 | 类型 | 默认值 | 描述 |
|
||||
| ----------- | ------------------ | -------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `as` | `string` | `'tbody'` | 正文根 |
|
||||
| `empty` | `boolean` | 自动判断 | 为 `true` 时强制空状态;省略时若默认插槽未渲染任何行则视为空 |
|
||||
| `colspan` | `number \| string` | 自动(实际叶子列数) | 空状态单元格跨列数;缺省跨全部实际叶子列(含选择列与包装渲染的列,随列增减更新),显式值优先 |
|
||||
| 默认插槽 | 行内容 | — | 动态行使用 v-for |
|
||||
| `#empty` | 空状态 | — | 空数据时渲染;包在 `role="presentation"` 行内,不参与选择、行计数与键盘导航 |
|
||||
|
||||
### TableRow
|
||||
|
||||
|
||||
@@ -17,6 +17,13 @@ const labs = [
|
||||
() => import("../../../tests/fixtures/link-focus.vue"),
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "table-layout",
|
||||
title: "表格列宽与排序焦点",
|
||||
component: defineAsyncComponent(
|
||||
() => import("../../../tests/fixtures/table-layout.vue"),
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "button-group-dropdown",
|
||||
title: "按钮组与下拉根属性",
|
||||
|
||||
@@ -295,12 +295,14 @@ HD-01(2026-10-28):按钮/切换组与导航示例已恢复固定cn基线
|
||||
|
||||
`@heroui-vue/styles` 增量补齐固定源缺失的 5 个 tv 映射与类型:`labelVariants`/`descriptionVariants`/`fieldErrorVariants`/`textFieldVariants`/`switchGroupVariants`(hv- 命名空间,变体集合与默认值与 `heroui/packages/styles/src/components/{label,description,field-error,textfield,switch-group}/*.styles.ts` 逐键一致),`@heroui-vue/components` 再导出同一组函数与 `*Variants` 类型。Label/Description/FieldError/useTextField/SwitchGroup 改为消费同一映射,状态类只保留一处来源,渲染类输出不变(tests/shared-field-styles.test.ts 钉住映射输出与组件输出一致)。恢复 `base` 层全局边框色回退 `border-color: var(--border, currentColor)`(与固定源 base/base.css 同选择器、同层序:preflight 之后);独立 tarball 消费者真实浏览器验证浅/深 `--border`、显式边框色(含字段透明边框)、调用方普通 CSS 覆盖(含与库同选择器的注入规则)与 `--border` 缺失时的 currentColor 回退,CSSOM 确认规则位于 base 层且无 `!important`。`view-transition-name`/`::view-transition` 两条上游全局规则经核查无使用证据(库与文档站均未使用 View Transitions API),不迁移、不建专项。chip `size:"md"`、kbd `variant:"default"` 等效默认类、reduced-motion、Spinner 定尺、Table th 行头、定位补偿与 HD-01~HD-04 成果均未改动。见 [任务结果](tasks/results/HD-05-STYLES.md)。
|
||||
|
||||
|
||||
## HD-06 链接与日期焦点(2026-10-29)
|
||||
|
||||
禁用 Link 移除 href/target/download,包括 asChild 子节点的导航属性,保持 aria-disabled、tabindex=-1 与暴露的 focus;启用恢复,用户事件取消和子 ref 保留。Breadcrumbs 当前/禁用项原已用 span,不重复改写;新增按 ConfigProvider locale 的默认名称及 @action(key),保持 id/key 的数字0与空串身份,取消的激活不通知 action。两个日期触发器按实际 :focus-visible 更新状态标记,鼠标/Tab/关闭恢复由浏览器判定。证据见 [HD-06结果](tasks/results/HD-06-LINK-FOCUS.md)。
|
||||
|
||||
|
||||
## HD-07 字段与OTP公共能力(2026-10-29)
|
||||
|
||||
TextField/SearchField共享autoFocus、组内focus状态、字段级validationErrors与Form错误合并;SearchField槽value与文本值同源。FieldError按共享FieldContext可读取ValidityState快照,TextField/SearchField来自真实控件、OTP支持显式validationDetails或原生提交代理。OTP补autoFocus/pasteTransformer/textAlign,整值pattern与accepted complete对照固定input-otp1.5.0:非法整次编辑拒绝、受控拒绝不complete、满值替换不重复、清空重填再通知。PinInput索引空位与单字符串提交保留;视觉槽对齐、跨格选区、密码管理器策略等Vue边界见组件文档及[任务结果](tasks/results/HD-07-FIELD-OTP.md)。
|
||||
|
||||
## HD-08 Table 空状态、排序焦点与列宽(2026-10-29)
|
||||
|
||||
TableBody 空状态默认跨全部实际叶子列(含选择列与包装渲染的 TableColumn,随列增减响应式更新;未测量环境回退 1),显式 `colspan` 仍优先;保持 vnode 级空判定,不执行未知组件 setup/render 探测。排序保持列头单一激活路径:点击、Enter、Space 各一次(真实浏览器三手势逐一计数),触发按钮保留键盘焦点与 API,把真实 `:focus-visible` 转发到 `th` 的 `[data-focus-visible]` 钩子,焦点环回到基线位置(th 内嵌 2px 环,按钮 UA 轮廓在列内抑制),浅深主题均实测;`aria-sort="none"` 对可排序未排序列属基线行为(react-aria useTableColumnHeader 同款),维持不变。`defaultWidth="Nfr"` 按固定源权重语义实现(移植 react-stately TableColumnLayout/TableUtils 的 flex-grow 解析,Apache-2.0):px/百分比固定列先扣、fr 列按权重分享剩余宽度、min/max 以违规冻结+再分配收敛、整数级联取整保证列宽和等于表宽;存在 fr 列时未设宽度的列按 `1fr` 参与并启用 `table-layout: fixed` 精确几何,容器缩放重分配、拖动列冻结为像素宽度、RTL 几何一致且拖动方向相反,未测量环境(jsdom)保持原生宽度。保留原生 `th scope=row`、圆角选择器与 resizer `z-index` 修复;`.table__cell` 的 `text-start font-normal` 经实测确认会阻断调用方祖先继承(祖先 font-bold/text-center 不下传),收窄为 `th.hv-table__cell { text-align: inherit; font-weight: inherit }`:行头保持基线 td 排版同时保留调用方级联。真实浏览器几何/拖动/焦点验证见 [任务结果](tasks/results/HD-08-TABLE.md)。
|
||||
|
||||
+5
-2
@@ -362,12 +362,15 @@ Button/ButtonGroup/ToggleButton/ToggleButtonGroup与指定Accordion/Disclosure
|
||||
- packages/styles/src/index.ts 的 `labelVariants`/`descriptionVariants`/`fieldErrorVariants`/`textFieldVariants`/`switchGroupVariants`:移植 `heroui/packages/styles/src/components/{label/label,description/description,field-error/field-error,textfield/textfield,switch-group/switch-group}.styles.ts`,仅加 `hv-` 前缀;变体键、默认值与 slot 集合逐键保留(Apache-2.0,见 third-party/HEROUI-LICENSE)。
|
||||
- packages/styles/base/base.css:移植 `heroui/packages/styles/base/base.css` 的边框色继承规则(`*, ::after, ::before, ::backdrop, ::file-selector-button { border-color: var(--border, currentColor) }`),导入序保持 preflight 之后的 base 层。同文件的 `:root { view-transition-name: none }` 与 `::view-transition { pointer-events: none }` 未移植:库与文档站均无 View Transitions API 使用证据,按 HD-05 约定记录无需修改,不建立专项。
|
||||
|
||||
|
||||
### HD-06(2026-10-29)
|
||||
|
||||
Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该上游锁文件的 react-aria 3.52.1 `dist/private/intl/breadcrumbs`,仅数据,不引入 React 运行时。Adobe Apache-2.0声明保留于第三方许可及组件包 `LICENSE.react-aria`(随 tarball发布)。Vue identity采用 id/key/index,事件为 @action。日期焦点标记适配真实 DOM :focus-visible。
|
||||
|
||||
|
||||
### HD-07(2026-10-29)
|
||||
|
||||
固定HeroUI ce90ea3的InputOTP公开类型及锁定input-otp1.5.0(npm tarball只读source map)核对:pattern.test整值、pasteTransformer先转换、complete effect只跟随accepted value跨阈值。仅在现有Vue/Reka字段/PinInput边界适配,不安装React或增加运行时依赖;底座多input、索引空位、单字段提交保留。全局/sticky RegExp去状态化延续既有Vue行为;字符选区限单槽,非单input任意跨槽选择。字段错误与focus采用现有共享上下文,新增原生ValidityState快照。
|
||||
|
||||
## HD-08 来源(2026-10-29)
|
||||
|
||||
- packages/vue/src/components/table/widths.ts:移植 react-stately `TableUtils.js`(`calculateColumnSizes` flex-grow 列宽解析、min/max 违规冻结、级联取整)与 `TableColumnLayout.js` 的默认宽度语义(未设宽度按 `1fr`),Apache-2.0;仅函数级移植,无新状态内核。
|
||||
- 排序焦点环转发与空状态跨列自适应为 Vue 适配(基线由 RAC useTableColumnHeader 的 press/focus 与 TableBody colSpan 承担);`aria-sort` 的 `"none"` 输出与基线 useTableColumnHeader 一致,不作改动。
|
||||
|
||||
@@ -170,6 +170,15 @@
|
||||
@apply flex items-center justify-between;
|
||||
}
|
||||
|
||||
/* The trigger button owns keyboard focus (click/Enter/Space activate the
|
||||
column's sort once), but the visible ring stays on the column header like
|
||||
the pinned baseline: the trigger forwards its real `:focus-visible` state to
|
||||
the th's `data-focus-visible` hook, so its own UA outline is suppressed here
|
||||
(scoped: a trigger outside a column keeps the default ring). */
|
||||
.hv-table__column .hv-table__sortable-column-trigger {
|
||||
@apply outline-none;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Sortable Column Indicator — chevron that flips based on `data-direction`.
|
||||
Defaults to pointing up (ascending) and rotates 180° for descending.
|
||||
@@ -261,12 +270,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Native row headers (<th scope="row">) render with the baseline cell
|
||||
* typography: `inherit` replicates the pinned source's td-based row headers
|
||||
* (UA bold/center neutralised) while caller text-align/font-weight keep
|
||||
* cascading into every cell — scoping the reset to `th` preserves ancestor
|
||||
* inheritance for the regular td cells. */
|
||||
th.hv-table__cell {
|
||||
text-align: inherit;
|
||||
font-weight: inherit;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Table Cell (<td>)
|
||||
-------------------------------------------------------------------------- */
|
||||
.hv-table__cell {
|
||||
/* Native row headers must preserve the baseline cell typography/alignment. */
|
||||
@apply text-start font-normal;
|
||||
@apply h-full bg-surface px-4 py-3 align-middle text-sm text-foreground;
|
||||
|
||||
@apply border-b border-separator-tertiary/50;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Vendored
+103
@@ -0,0 +1,103 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableColumn,
|
||||
TableColumnResizer,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableResizableContainer,
|
||||
TableScrollContainer,
|
||||
TableSortableColumnHeader,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
/**
|
||||
* HD-08 column width verification harness: managed `fr` widths share the
|
||||
* remaining space by weight next to fixed/percent columns, min/max clamp the
|
||||
* shares, container resizing re-shares, dragging freezes the touched column
|
||||
* and RTL keeps geometry (only drag direction flips).
|
||||
*/
|
||||
const widths = [620, 900, 1400];
|
||||
const hostWidth = ref(900);
|
||||
const rtl = ref(false);
|
||||
const dark = ref(false);
|
||||
watch(
|
||||
dark,
|
||||
(value) => {
|
||||
document.documentElement.dataset.theme = value ? "dark" : "light";
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
const rows = [
|
||||
{ id: "1", email: "kate@acme.com", name: "Kate Moore", role: "首席执行官" },
|
||||
{ id: "2", email: "john@acme.com", name: "John Smith", role: "首席技术官" },
|
||||
{ id: "3", email: "sara@acme.com", name: "Sara Johnson", role: "首席营销官" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main style="padding: 24px; display: grid; gap: 16px">
|
||||
<div style="display: flex; gap: 16px">
|
||||
<label>
|
||||
容器宽度
|
||||
<select v-model.number="hostWidth">
|
||||
<option v-for="width in widths" :key="width" :value="width">
|
||||
{{ width }}px
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="rtl" type="checkbox" />
|
||||
RTL
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="dark" type="checkbox" />
|
||||
深色主题
|
||||
</label>
|
||||
</div>
|
||||
<div
|
||||
id="table-host"
|
||||
:dir="rtl ? 'rtl' : 'ltr'"
|
||||
:style="{ width: `${hostWidth}px` }"
|
||||
>
|
||||
<Table>
|
||||
<TableResizableContainer>
|
||||
<TableScrollContainer>
|
||||
<TableContent aria-label="列宽验证表格">
|
||||
<TableHeader>
|
||||
<TableColumn
|
||||
id="name"
|
||||
allows-sorting
|
||||
default-width="1fr"
|
||||
:min-width="120"
|
||||
>
|
||||
<TableSortableColumnHeader>姓名</TableSortableColumnHeader>
|
||||
<TableColumnResizer />
|
||||
</TableColumn>
|
||||
<TableColumn id="role" default-width="2fr" :min-width="100">
|
||||
角色
|
||||
<TableColumnResizer />
|
||||
</TableColumn>
|
||||
<TableColumn id="status" :width="180">状态</TableColumn>
|
||||
<TableColumn id="email" width="20%" :max-width="240">
|
||||
邮箱
|
||||
</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="row in rows" :key="row.id" :row-key="row.id">
|
||||
<TableCell>{{ row.name }}</TableCell>
|
||||
<TableCell>{{ row.role }}</TableCell>
|
||||
<TableCell>在职</TableCell>
|
||||
<TableCell>{{ row.email }}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</TableContent>
|
||||
</TableScrollContainer>
|
||||
</TableResizableContainer>
|
||||
</Table>
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
@@ -360,7 +360,13 @@
|
||||
"TableCollection",
|
||||
"TableSortableColumnHeader"
|
||||
],
|
||||
"css": [".hv-toast-region", ".hv-table__column-resizer", "data-exiting"]
|
||||
"css": [
|
||||
".hv-toast-region",
|
||||
".hv-table__column-resizer",
|
||||
"data-exiting",
|
||||
"th.hv-table__cell",
|
||||
".hv-table__sortable-column-trigger"
|
||||
]
|
||||
},
|
||||
"select": {
|
||||
"exports": [
|
||||
|
||||
@@ -202,3 +202,154 @@ it("controlled sort-descriptor updates via v-model", async () => {
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user