Compare commits
4 Commits
aac93db658
...
c34faccd70
| Author | SHA1 | Date | |
|---|---|---|---|
| c34faccd70 | |||
| c019768e6a | |||
| 86d76a0675 | |||
| 658dfbb7d9 |
@@ -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)。
|
||||
|
||||
@@ -35,3 +35,8 @@
|
||||
- HD-07-FIELD-OTP执行中:分支task/hd-07-field-otp,实际起点27cc62e36f16bc16843ccf25f202340eeac38871;本会话亲自补字段focus/autoFocus/错误数组与ValidityState、SearchField槽value,以及OTP autoFocus/pasteTransformer/textAlign和固定1.5.0的pattern/complete契约,完成后按用户授权合并push。
|
||||
|
||||
- HD-07 已完成验收:实施2d7e3d4e1e12403bb90e92e393bc7fb798a5a2ba;字段共享autoFocus/focus/validationErrors/ValidityState、SearchField槽value、OTP四项props与固定1.5.0整值pattern/accepted complete全部核销,见results/HD-07-FIELD-OTP.md。全量111文件1654项、类型、最终docs/playground构建、四组tarball与真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,下一项HD-08未启动,保留5173/5174。
|
||||
|
||||
- HD-08-TABLE已实施待复核,工作区释放;分支task/hd-08-table,起点aac93db65812a273c887709af4bf1a846439d8bb(main tip,含HD-07验收),实施658dfbb7d920255e48e1b9cf99e15e34f11ec640。
|
||||
- [结果](results/HD-08-TABLE.md)逐条核销:范围1空状态默认跨全部实际叶子列(选择列/包装列自注册计数、动态增减响应、显式colspan优先、不探测未知组件);范围2排序点击/Enter/Space保持单次激活(实测1/1/1),真实:focus-visible转发到th的data-focus-visible钩子恢复基线inset焦点环(浅深双主题实测、按钮UA环列内抑制;非删button非补类名),aria-sort="none"核实为基线行为不改;范围3移植react-stately calculateColumnSizes实现Nfr权重分配(固定/百分比先扣、min/max违规冻结再分配、级联取整、table-layout:fixed精确几何、容器缩放重分配、拖动冻结、RTL同几何反向拖动;900/620/1400三档真实浏览器几何逐毫符合约束),未测量环境保持原生宽度;范围4保留th scope=row/圆角/resizer z-index,text-start/font-normal实测确认阻断调用方继承后收窄为th.hv-table__cell{inherit}。全量111文件1657项、typecheck、build:docs、m35-m36(补两CSS标记)/handbook-styles最终tarball通过;fixture落tests/fixtures/table-layout.vue(playground注册)。遗留:虚拟化归HD-09;auto+fr混合口径与拖动中间分布差异已记录。
|
||||
|
||||
- HD-08 已验收:复核86d76a0,集成人补修c019768e6ac45410cd0f403a325ee0de9727e4eb,关闭固定列maxWidth/CSS不一致、无效fr不收敛及补修后的父容器缩小约束问题。全量111文件1658项、类型、最终docs/playground构建、m35-m36/handbook-styles最终tarball和真实浏览器空态/键盘焦点/几何/拖动/RTL通过,见同一结果表。按用户授权合入main并push origin/main;工作区释放,保留5173/5174,下一任务未启动。
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
<!-- task-metadata
|
||||
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"pending","requires":["docs/tasks/HD-QUEUE.md"],"sources":["packages/react/src/components/table/table.tsx"],"checks":["pnpm exec vitest run tests/table.test.ts tests/regressions/toast-table/sorting-and-actions.test.ts tests/regressions/toast-table/resize-selection.test.ts tests/regressions/toast-table/empty-state-and-labels.test.ts","pnpm typecheck"]}
|
||||
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"accepted","requires":["docs/tasks/HD-QUEUE.md"],"sources":["packages/react/src/components/table/table.tsx"],"checks":["pnpm exec vitest run tests/table.test.ts tests/regressions/toast-table/sorting-and-actions.test.ts tests/regressions/toast-table/resize-selection.test.ts tests/regressions/toast-table/empty-state-and-labels.test.ts","pnpm typecheck","node scripts/check-package.mjs m35-m36 handbook-styles"]}
|
||||
-->
|
||||
|
||||
# HD-08-TABLE:Table 空状态、排序焦点与列宽
|
||||
|
||||
优先级:P1。证据范围:审计组 02;详见 [清单入口](HD-QUEUE.md) 和其中证据链接。
|
||||
|
||||
## 执行范围
|
||||
|
||||
- [ ] 空状态默认跨实际全部叶子列,显式 colspan 仍优先;覆盖列动态变化、选择列及自定义包装,不能执行未知组件 setup/render 探测。
|
||||
- [ ] 排序交互保留可访问键盘行为并恢复基线焦点环,不能简单删掉 button 或只补一个类名。
|
||||
- [ ] defaultWidth=Nfr 按权重分配剩余宽度,协调固定/百分比/min/max/用户拖动后的宽度;不能继续将 fr 静默转 auto。
|
||||
- [ ] 保留 th scope=row、对应圆角选择器和 resizer z-index 修复;必要时缩小 text-start/font-normal 的适用范围以保留调用方继承。
|
||||
- [x] 空状态默认跨实际全部叶子列,显式 colspan 仍优先;覆盖列动态变化、选择列及自定义包装,不能执行未知组件 setup/render 探测。
|
||||
- [x] 排序交互保留可访问键盘行为并恢复基线焦点环,不能简单删掉 button 或只补一个类名。
|
||||
- [x] defaultWidth=Nfr 按权重分配剩余宽度,协调固定/百分比/min/max/用户拖动后的宽度;不能继续将 fr 静默转 auto。
|
||||
- [x] 保留 th scope=row、对应圆角选择器和 resizer z-index 修复;必要时缩小 text-start/font-normal 的适用范围以保留调用方继承。
|
||||
|
||||
## 用户可见通过条件
|
||||
|
||||
@@ -26,4 +27,3 @@
|
||||
结果写到 `docs/tasks/results/HD-08-TABLE.md`,逐条记录改动或“无需修改”的证据及限制;只在本卡元数据更新状态。核实后无需修改是有效结论,不为凑修复量重写底座。普通实施提交自己的分支,不合 main、不 push、不派发其他会话。
|
||||
|
||||
仅浏览器客户端;不开发或运行 SSR/水合/Nuxt 服务端、逐像素自动对比、完整读屏或真机矩阵专项。
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# HD-08-TABLE 结果记录
|
||||
|
||||
- 任务卡:[HD-08-TABLE](../HD-08-TABLE.md);固定上游 `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`(`heroui/packages/react/src/components/table/table.tsx` 及其 react-aria/react-stately 依赖)。
|
||||
- 分支 task/hd-08-table;起点 aac93db65812a273c887709af4bf1a846439d8bb(main tip,含 HD-07 验收);实施 658dfbb7d920255e48e1b9cf99e15e34f11ec640(14 文件,table 组件/宽度模块/样式/契约、fixture、测试、文档与记录源);记录提交为本文件所在提交。主会话实施/自测,未合 main、未 push。
|
||||
- 本卡不实现 HD-09 的 Table/ListBox 虚拟化,未另建 Table 状态内核(宽度解析为独立纯函数模块,无新状态源)。
|
||||
|
||||
## 范围 1:空状态跨全部实际叶子列
|
||||
|
||||
**修改**。TableBody 空状态 `colspan` 默认由固定 `1` 改为**实际叶子列数**(`ctx.columns` 自注册计数,DOM 序无关),显式 `colspan` 仍优先。覆盖:
|
||||
|
||||
| 场景 | 证据 |
|
||||
| ------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| 静态 3 列(含选择列、包装组件渲染的 TableColumn) | 单测:默认 colspan=3(自注册计数包含 TableColumnWrapper 子组件渲染的列与选择列) |
|
||||
| 列动态增减 | 单测:增 1 列→4,移除→3(columns map 为响应式注册表,重渲染同步) |
|
||||
| 显式 colspan 优先 | 单测:`:colspan="1"` → "1"(既有 visual-contracts 的显式 `colspan: 1` 钉点原样通过) |
|
||||
| 0→多行→0 | 既有 empty-state-and-labels 8 项(含包装集合回归/强制空态)全通过 |
|
||||
| 未知组件 | 保持 vnode 级 `slotLooksPopulated` 判定,**未**执行未知组件 setup/render 探测 |
|
||||
| 文档示例实测 | table-empty-state 演示空单元 colspan="4" = 表头 4 列(真实浏览器) |
|
||||
|
||||
未测量/无列环境回退 1,不写 `colspan="0"`。
|
||||
|
||||
## 范围 2:排序单次激活与基线焦点环
|
||||
|
||||
**现状核实**(真实浏览器实测先行):点击/Enter/Space 触发按钮的排序激活**本就各一次**(MutationObserver 计 aria-sort 变化:1/1/1);缺口是焦点环——焦点在内嵌 button(UA 默认环),`th` 的基线 inset 环规则(`.hv-table__column:focus-visible`)永不命中。
|
||||
|
||||
**修改**(非删 button、非补类名):保留触发按钮作为键盘/焦点适配层与既有 API(columnKey/isDisabled/合并 onClick),把**真实 `:focus-visible` 判定**(与 HD-06 相同的 `matches(':focus-visible')` 模式)转发到 `th` 的既有 `[data-focus-visible]` 钩子,基线 inset 环(`box-shadow: inset 0 0 0 2px var(--focus)`)随之生效;按钮的 UA 轮廓仅在列内抑制(`.hv-table__column .hv-table__sortable-column-trigger`),列外使用保留默认环。激活路径零改动:
|
||||
|
||||
- 单测:两次点击 = 两次 sortChange(button→冒泡→列单一排序路径);焦点转发 set/remove `[data-focus-visible]`。
|
||||
- 真实浏览器(tests/fixtures/table-layout):click/Enter/Space 各 1 次激活;真实 Tab 键聚焦触发按钮时 `th[data-focus-visible="true"]` + `oklch(0.6204 0.195 253.83) 0 0 0 2px inset` 环、按钮 outline none——**浅色与深色主题逐一实测**(`--focus` 为两主题共享 accent,值一致属预期)。
|
||||
|
||||
**无需修改(核实项)**:可排序未排序列输出 `aria-sort="none"`——基线 react-aria `useTableColumnHeader` 同样输出 `isSorted ? sortDirection : 'none'`(其源码实证;审计"上游只在排序时输出"有误),维持现状。
|
||||
|
||||
## 范围 3:defaultWidth="Nfr" 权重分配
|
||||
|
||||
**修改**。`packages/vue/src/components/table/widths.ts` 移植 react-stately `TableUtils.js` 的 `calculateColumnSizes`(flexbox §9.7 grow-only 解析 + min/max 违规冻结 + 级联取整,Apache-2.0 来源记录)并接线:
|
||||
|
||||
- px/`N%` 固定列先扣(百分比按表宽解析),`Nfr` 按权重分享剩余宽度;未设宽度的列**仅在存在 fr 列时**按 `1fr` 参与(基线 TableColumnLayout 默认语义),无 fr 的表布局零改动。
|
||||
- min/max 对份额生效:违规列冻结、余量再分配直至收敛;整数级联取整保持分配总和;可行约束且有可分配余量时列宽和=表宽,约束总和本身超出/不足表宽时不作无条件等宽承诺。
|
||||
- 存在 fr 列时表启用 `table-layout: fixed`(与基线 ResizableTableContainer 内的 `tableLayout: 'fixed'` 一致)实现精确几何。
|
||||
- 容器缩放(ResizeObserver)重分配;拖动列经既有 setWidth 冻结为像素宽度、fr 列重分享(对齐基线 changedColumns 冻结语义);RTL 几何一致、拖动方向反向(既有 resizer direction 逻辑)。
|
||||
- 未测量环境(jsdom/隐藏)不写宽度——既有 `defaultWidth 1fr does not write an invalid CSS width` 钉点(style.width="")原样通过。
|
||||
|
||||
**真实浏览器几何**(tests/fixtures/table-layout,容器 900/620/1400,Playwright 真实交互):
|
||||
|
||||
| 场景 | 实测 | 约束核对 |
|
||||
| -------------------- | --------------------- | ------------------------------------------------------------------------ |
|
||||
| 900 初始(表宽 892) | 178 / 356 / 180 / 178 | 1fr:2fr=178:356 恰 1:2 ✓;固定列 180 ✓;20% 列=178(892×20%)✓;和=892 ✓ |
|
||||
| 1400(表宽 1392) | 324 / 648 / 180 / 240 | 1:2 ✓;**max 钳制**:20%=278→240 ✓;和=1392 ✓ |
|
||||
| 620(表宽 612) | 120 / 190 / 180 / 122 | **min 钳制**:1fr 均分 103→120 冻结、余量归 2fr ✓;和=612 ✓ |
|
||||
| 拖动 +60px(LTR) | 238 / 296 / 180 / 178 | 拖动列=178+60=238 冻结 ✓;fr 重分享 296 ✓ |
|
||||
| 拖动后缩放至 1400 | 238 / 734 / 180 / 240 | 拖动列保持 238 ✓;fr 重分享 734 ✓ |
|
||||
| RTL | 238 / 734 / 180 / 240 | 几何不变 ✓ |
|
||||
| RTL 拖动 +40px 右 | 198 / 774 / 180 / 240 | 方向反转(238−40=198)✓ |
|
||||
|
||||
`table-layout: fixed` 各场景实测生效;无页面错误。
|
||||
|
||||
## 范围 4:保留项与 text-start/font-normal 核实
|
||||
|
||||
**保留(git diff 核对零改动)**:原生 `th scope="row"`(TableCell)、`:is(td, th.hv-table__cell)` 圆角选择器、`.table__column-resizer` 的 `z-index: 1` 命中区修复、HD-01~HD-07 成果。
|
||||
|
||||
**核实→缩小作用域**:`.table__cell` 的 `@apply text-start font-normal` 实测**确实阻断调用方继承**(祖先 `font-bold text-center` 下 td/th 行头仍 400/start,基线 td 行头应继承 600/center)。收窄为 `th.hv-table__cell { text-align: inherit; font-weight: inherit }`:
|
||||
|
||||
- 行头 th 中和 UA 加粗/居中(基线 td 排版)且完整跟随调用方级联;普通 td 恢复继承(实测 600/center 与基线语义一致)。
|
||||
- 默认无祖先样式时渲染(normal/start)与收窄前一致。
|
||||
|
||||
## 检查与验证
|
||||
|
||||
- `node scripts/task-check.mjs HD-08-TABLE`(head aac93db)✅
|
||||
- 卡内 checks:`vitest run tests/table.test.ts tests/regressions/toast-table/{sorting-and-actions,resize-selection,empty-state-and-labels}.test.ts`(24 项)✅、`pnpm typecheck` ✅
|
||||
- 全量 `pnpm exec vitest run`:**111 文件 / 1657 项**(新增 3:空态跨列、fr 分发与钳制、单次激活+焦点转发)✅;既有断言零修改零跳过
|
||||
- `pnpm build:docs` ✅;prettier ✅
|
||||
- 最终 tarball:`node scripts/check-package.mjs m35-m36 handbook-styles` ✅(m35-m36 契约增量补 `th.hv-table__cell`、`.hv-table__sortable-column-trigger` 两个 CSS 标记,锁定收窄后的规则进入最终产物)
|
||||
- 真实浏览器(playwright-core + 系统 Chrome):tests/fixtures/table-layout(playground 5174 注册)几何/钳制/拖动/RTL/主题表,文档站 5173 的 table-column-resizing(160/220/120/200=700 与基线算法逐毫一致)、table-empty-state(colspan=4)、table-sorting 焦点环;截图 hd08-table-layout-dark.png 存档
|
||||
|
||||
## 未完成与限制
|
||||
|
||||
1. 虚拟化(TableLayout/ListLayout 能力面)明确归 HD-09;本卡未触碰 table-virtualization 的固定行高窗口实现。
|
||||
2. 未测量环境(jsdom)下 fr 列不写宽度(保持原生),fr 分发语义由纯函数单测与真实浏览器几何覆盖;这是刻意设计(避免首帧 0 宽写入)。
|
||||
3. 混合 auto(未设宽度)+ fr 的表在 fr 模式下未设宽度列按 `1fr` 参与分配(基线 TableColumnLayout 语义);这是口径变化点,已在 table.md 注明。
|
||||
4. 拖动时仅拖动列冻结(基线另有"左侧列冻结为先前像素"的连续拖动细节),fr 列实时重分享;几何约束满足但拖动过程中的中间分布与基线可能不同,未见可见回归。
|
||||
5. 排序焦点环转发基于 `:focus-visible` 真实判定;Firefox 对 `:focus-visible` 的启发式与 Chromium 略有差异,本轮以系统 Chrome 验证,未做多引擎矩阵。
|
||||
|
||||
|
||||
## 集成人复核与补修(2026-10-29)
|
||||
|
||||
复核入口 `86d76a0675b2afc94284c4d6a1e0eea17bfd440f`。用户授权少量问题直接补修后合并push;补修 **`c019768e6ac45410cd0f403a325ee0de9727e4eb`**,原实施658dfbb保留。
|
||||
|
||||
| 问题 | 复现与处理 | 最终证据 |
|
||||
| --- | --- | --- |
|
||||
| 固定宽度与maxWidth冲突 | 原宽度解析扣除钳制后的100,但实际固定列仍写width/min-width180;900容器中列宽205/409/180/98,挤压了20%列。统一将全部列(含固定/百分比)解析结果写入DOM,受管布局不再把原始width作为额外min-width。 | 同场景修复后205/409/100/178,总892;测试增量覆盖固定列max钳制与实际style。 |
|
||||
| 无效fr不能收敛 | oopsfr/NaNfr/Infinityfr/1e999fr产生非有限因子,违规冻结循环无法收敛。仅有限数值因子进入算法,其他按1fr回退,沿用格式错误回退的已有方向。 | 新单测四种非法因子均返回有限份额300/600;浏览器切“无效fr回退”仍可操作,178/356/180/178。 |
|
||||
| 补修引出的缩小约束 | 全部列写像素后,已分配列宽可能撑住table,单看table矩形不能检测父容器缩小。增加父内容宽约束与ResizeObserver,保留显式table min-width的主动横向溢出。 | 浏览器1400→620后1392宽324/648/180/240回到612宽120/190/180/122;测试覆盖父容器小于旧table宽时的重新分配。 |
|
||||
| 测试和许可记录 | 修正focus测试在spy安装后才取originalMatches的递归风险;新用例卸载wrapper,保留全部原断言。补保留Adobe Copyright2022声明,组件包已有LICENSE.react-aria继续随产物发布;清除TableColumn过期“未实现fr”注释。 | Prettier、diff检查与全量回归通过。 |
|
||||
|
||||
### 独立复核验证
|
||||
|
||||
- 最终全量 **111文件 / 1658项通过**(原实施1657 + 新非法因子回归1;原宽度用例增量覆盖固定列/父容器边界);`pnpm typecheck`通过,扩展fixture后再次类型检查通过。
|
||||
- 最终 `node scripts/check-package.mjs m35-m36 handbook-styles`通过:tarball ESM/CSS、bundler/NodeNext类型正反例;随后最终dist的docs与playground生产构建通过,仅既有文档chunk提示。代码Prettier与git diff --check通过。
|
||||
- 真实浏览器使用5174 `?table-layout`公开夹具,无源码注入或合成事件。常规900/1400/620依次为178/356/180/178、324/648/180/240、120/190/180/122;固定列max100、无效fr场景见上表。
|
||||
- 620容器真实指针拖首手柄向右40:120/190→160/150;切RTL后向右20:160/150→140/170,后两列180/122保持。
|
||||
- 点击姓名后ascending,真实Tab/Shift+Tab后Enter变descending,Space再变ascending;浅/深均命中th[data-focus-visible=true],实际box-shadow为2px inset focus环。
|
||||
- 浏览器无数据时colspan4,增加列变5,显示3行时空态消失,再清空并移除列回colspan4;未知包装与选择列仍由原自注册单测覆盖。
|
||||
|
||||
原范围均已核销。状态 **accepted**,按用户授权合入main并push origin/main;保留5173/5174。虚拟化仍归HD-09,原记录的拖动时左侧列冻结分布差异保留为明确边界,不伪称完全复刻React布局状态。未开展SSR/水合/Nuxt服务端或逐像素专项;未自动开始下一张卡。
|
||||
+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,12 +80,16 @@ 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`;
|
||||
// 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;
|
||||
};
|
||||
@@ -97,9 +112,13 @@ 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"
|
||||
resolvedWidth.value === undefined &&
|
||||
typeof width.value === "number"
|
||||
? Math.max(props.minWidth ?? 0, width.value)
|
||||
: props.minWidth,
|
||||
),
|
||||
|
||||
@@ -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 } 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,87 @@ 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 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) => {
|
||||
// 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(() =>
|
||||
[...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);
|
||||
if (element.value.parentElement)
|
||||
layoutObserver.observe(element.value.parentElement);
|
||||
}
|
||||
});
|
||||
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,10 @@ 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,196 @@
|
||||
/**
|
||||
* Column width resolution for managed tables (explicit `fr` widths).
|
||||
*
|
||||
* Ported from react-stately `TableUtils.js` / `TableColumnLayout.js`
|
||||
* 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
|
||||
* 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$)/);
|
||||
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). */
|
||||
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
+136
@@ -0,0 +1,136 @@
|
||||
<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);
|
||||
const layoutCase = ref("baseline");
|
||||
const showRows = ref(true);
|
||||
const extraColumn = 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="layoutCase">
|
||||
<option value="baseline">常规列宽</option>
|
||||
<option value="fixed-max">固定列超出上限</option>
|
||||
<option value="invalid-fr">无效 fr 回退</option>
|
||||
</select>
|
||||
</label>
|
||||
<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>
|
||||
<label>
|
||||
<input v-model="showRows" type="checkbox" />
|
||||
显示数据
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="extraColumn" 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"
|
||||
:width="layoutCase === 'invalid-fr' ? 'oopsfr' : undefined"
|
||||
:min-width="120"
|
||||
>
|
||||
<TableSortableColumnHeader>姓名</TableSortableColumnHeader>
|
||||
<TableColumnResizer />
|
||||
</TableColumn>
|
||||
<TableColumn id="role" default-width="2fr" :min-width="100">
|
||||
角色
|
||||
<TableColumnResizer />
|
||||
</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 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>
|
||||
</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": [
|
||||
|
||||
@@ -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,
|
||||
@@ -202,3 +206,183 @@ 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");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
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 maxFixed = 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, maxWidth: maxFixed.value },
|
||||
() => "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"]);
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
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 originalMatches = HTMLElement.prototype.matches;
|
||||
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);
|
||||
});
|
||||
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();
|
||||
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