From 658dfbb7d920255e48e1b9cf99e15e34f11ec640 Mon Sep 17 00:00:00 2001 From: maoyingjie Date: Thu, 29 Oct 2026 10:59:24 +0800 Subject: [PATCH] fix(table): full-width empty state, sort focus ring and fr column widths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- apps/docs/components/table.md | 36 ++-- apps/playground/src/App.vue | 7 + docs/compatibility.md | 6 +- docs/upstream.md | 7 +- packages/styles/components/table.css | 21 +- .../vue/src/components/table/TableBody.vue | 11 +- .../vue/src/components/table/TableColumn.vue | 23 ++- .../vue/src/components/table/TableContent.vue | 65 +++++- .../table/TableSortableColumnHeader.vue | 18 ++ packages/vue/src/components/table/context.ts | 18 +- packages/vue/src/components/table/widths.ts | 189 ++++++++++++++++++ tests/fixtures/table-layout.vue | 103 ++++++++++ tests/package/client-checks.json | 8 +- tests/table.test.ts | 151 ++++++++++++++ 14 files changed, 629 insertions(+), 34 deletions(-) create mode 100644 packages/vue/src/components/table/widths.ts create mode 100644 tests/fixtures/table-layout.vue diff --git a/apps/docs/components/table.md b/apps/docs/components/table.md index 8131675..e8822ba 100644 --- a/apps/docs/components/table.md +++ b/apps/docs/components/table.md @@ -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 轮廓在列内被抑制。 + ### 选择 @@ -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 下几何一致、拖动方向相反。 @@ -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 diff --git a/apps/playground/src/App.vue b/apps/playground/src/App.vue index 9036444..c693a0d 100644 --- a/apps/playground/src/App.vue +++ b/apps/playground/src/App.vue @@ -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: "按钮组与下拉根属性", diff --git a/docs/compatibility.md b/docs/compatibility.md index 2f0db93..6de7bc5 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -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)。 diff --git a/docs/upstream.md b/docs/upstream.md index b84d925..ee14a83 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -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 一致,不作改动。 diff --git a/packages/styles/components/table.css b/packages/styles/components/table.css index 53fe197..dd57a72 100644 --- a/packages/styles/components/table.css +++ b/packages/styles/components/table.css @@ -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 () 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 () -------------------------------------------------------------------------- */ .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; diff --git a/packages/vue/src/components/table/TableBody.vue b/packages/vue/src/components/table/TableBody.vue index b338926..adb309e 100644 --- a/packages/vue/src/components/table/TableBody.vue +++ b/packages/vue/src/components/table/TableBody.vue @@ -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, - 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, diff --git a/packages/vue/src/components/table/TableColumn.vue b/packages/vue/src/components/table/TableColumn.vue index a80ebd0..7554d1d 100644 --- a/packages/vue/src/components/table/TableColumn.vue +++ b/packages/vue/src/components/table/TableColumn.vue @@ -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(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) diff --git a/packages/vue/src/components/table/TableContent.vue b/packages/vue/src/components/table/TableContent.vue index 86f6dc6..6054b18 100644 --- a/packages/vue/src/components/table/TableContent.vue +++ b/packages/vue/src/components/table/TableContent.vue @@ -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()); 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 ?? diff --git a/packages/vue/src/components/table/TableSortableColumnHeader.vue b/packages/vue/src/components/table/TableSortableColumnHeader.vue index 9482255..5968a14 100644 --- a/packages/vue/src/components/table/TableSortableColumnHeader.vue +++ b/packages/vue/src/components/table/TableSortableColumnHeader.vue @@ -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()], diff --git a/packages/vue/src/components/table/context.ts b/packages/vue/src/components/table/context.ts index cbad1c6..9803505 100644 --- a/packages/vue/src/components/table/context.ts +++ b/packages/vue/src/components/table/context.ts @@ -7,11 +7,23 @@ import type { tableVariants } from "@heroui-vue/styles"; export type TableSlots = ReturnType; 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 - >; + columns?: Ref>; navigation?: ReturnType; slots: ComputedRef; variant: ComputedRef; diff --git a/packages/vue/src/components/table/widths.ts b/packages/vue/src/components/table/widths.ts new file mode 100644 index 0000000..91d0bc6 --- /dev/null +++ b/packages/vue/src/components/table/widths.ts @@ -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; +} diff --git a/tests/fixtures/table-layout.vue b/tests/fixtures/table-layout.vue new file mode 100644 index 0000000..bdbab26 --- /dev/null +++ b/tests/fixtures/table-layout.vue @@ -0,0 +1,103 @@ + + + diff --git a/tests/package/client-checks.json b/tests/package/client-checks.json index 2a11741..32ea40a 100644 --- a/tests/package/client-checks.json +++ b/tests/package/client-checks.json @@ -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": [ diff --git a/tests/table.test.ts b/tests/table.test.ts index 7f5bb6e..b3aee3f 100644 --- a/tests/table.test.ts +++ b/tests/table.test.ts @@ -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(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(undefined); + const maxB = ref(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(); + } +});