Commit c149f4cc by 胡悦

feat: 完成agent工作区后台管理系统表格与表单标准化全量落地

主要变更包括:
- 新增并归档全量后台表格与表单标准化OpenSpec规范、设计文档与任务清单
- 修复BusinessTable分页重复显示总数问题,精简空态与失败态展示
- 为多业务列表页的长文本列添加显式Tooltip悬浮提示
- 优化BusinessForm样式与输入限制,统一表单提示颜色规则
- 迁移多批后台编辑页到BusinessForm,覆盖Agent标签、渠道码、官网职位Tab等页面
- 调整官网Agent展示配置的状态文案与排序校验,统一业务口径
- 优化vite代理配置为测试环境地址,修复消息钩子无DOM环境报错问题
- 补充大量测试用例并修复现有测试断言
- 更新架构文档与组件使用规范
1 parent ba5f0500
Showing 52 changed files with 1942 additions and 2205 deletions
...@@ -39,11 +39,12 @@ ...@@ -39,11 +39,12 @@
- 已通过 `openspec status --change "official-site-job-tab-ai-intro" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-job-tab-ai-intro" --strict`。 - 已通过 `openspec status --change "official-site-job-tab-ai-intro" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-job-tab-ai-intro" --strict`。
- 已为 `workspace/agent-admin/web` 新建 OpenSpec change `official-site-agent-display-config`,覆盖官网配置下 `/official-site/job-tabs/:tabId/agents` 的 Agent 展示配置页,不修改 `official-site-job-tab-ai-intro` artifacts,且本轮未写业务代码。 - 已为 `workspace/agent-admin/web` 新建 OpenSpec change `official-site-agent-display-config`,覆盖官网配置下 `/official-site/job-tabs/:tabId/agents` 的 Agent 展示配置页,不修改 `official-site-job-tab-ai-intro` artifacts,且本轮未写业务代码。
- 已通过 `openspec status --change "official-site-agent-display-config" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-agent-display-config" --strict`。 - 已通过 `openspec status --change "official-site-agent-display-config" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-agent-display-config" --strict`。
- 已完成 `official-site-agent-display-config-sort-status` 的 OpenSpec 锁定与实现,官网 Agent 展示配置编辑弹窗已将 `disable` 文案改为 `不展示`,并补齐排序下限与回归测试;已通过 `npm test -- src/routes/official-site-agent-display-config/AgentDisplayConfigEditModal.test.tsx src/routes/official-site-agent-display-config/OfficialSiteAgentDisplayConfigEdit.test.tsx`、`npm run typecheck`、`npm run build` 和 `openspec validate "official-site-agent-display-config-sort-status" --strict`。
- 2026-05-30:已执行 `standardize-admin-shell-layout` 并补充全框架前端规则:独立新增/编辑页页头左侧保留 `返回`、右侧仅保留 `保存`、不展示右侧 `取消`,页面滚动时返回/保存操作区保持可见。该规则已写入全局 `web-desktop-ui-standard`、`component-guidelines.md` 和 `frontend-conventions.md`;`agent-admin` 的 Agent、岗位标签、渠道活码、官网岗位展示新增/编辑页已按规则调整。 - 2026-05-30:已执行 `standardize-admin-shell-layout` 并补充全框架前端规则:独立新增/编辑页页头左侧保留 `返回`、右侧仅保留 `保存`、不展示右侧 `取消`,页面滚动时返回/保存操作区保持可见。该规则已写入全局 `web-desktop-ui-standard`、`component-guidelines.md` 和 `frontend-conventions.md`;`agent-admin` 的 Agent、岗位标签、渠道活码、官网岗位展示新增/编辑页已按规则调整。
## 当前重点 ## 当前重点
在编写业务代码前,持续把新的业务页行为先落到 OpenSpec。当前 `official-site-agent-display-config` 已完成 OpenSpec 锁定,等待用户确认 artifacts;不应在确认前进入实现。 在编写业务代码前,持续把新的业务页行为先落到 OpenSpec。当前 `official-site-agent-display-config-sort-status` 已完成实现与验证;后续若继续调整官网 Agent 展示配置,只能先更新受影响的 OpenSpec artifacts 再改代码。
2026-06-03:`business-form-component` 已完成仓库级基线与目录结构占位,OpenSpec tasks 1.1-1.3 已勾选;本轮不推进测试或实现,后续只在 `packages/business-components/src/business-form/` 继续落地。 2026-06-03:`business-form-component` 已完成仓库级基线与目录结构占位,OpenSpec tasks 1.1-1.3 已勾选;本轮不推进测试或实现,后续只在 `packages/business-components/src/business-form/` 继续落地。
...@@ -67,13 +68,20 @@ ...@@ -67,13 +68,20 @@
## 下一步 ## 下一步
1. 等待用户确认 `official-site-agent-display-config` OpenSpec artifacts。 1. 若继续调整官网 Agent 展示配置,先更新对应 OpenSpec change 的 artifacts 和任务。
2. 若确认进入实现阶段,先按 tasks 编写前端契约、mock fixture 与页面测试,再实现路由页面、上下文展示、列表状态映射、编辑弹窗、上传校验和保存反馈。 2. 其他后台编辑页需求继续按“先 OpenSpec、后实现、再验证”的顺序推进。
3. 实现后运行 `npm run typecheck`、`npm test`、`npm run build`,并用浏览器验证 `/official-site/job-tabs/:tabId/agents` 的布局、返回列表、停用不可编辑、上传错误和保存反馈。 3. 已完成的 `official-site-agent-display-config-sort-status` 这类小修正,后续如再变更,仍需重新锁定文档后再动代码。
## 会话记录 ## 会话记录
- 2026-06-08:按用户要求将“表格超长文案列交互”提升为全局规范,而不是仅保留在 `agent-admin` 项目实现中。已更新 `architecture-spec/openspec/changes/standardize-backoffice-business-table-usage/`:描述、概述、说明、备注、内容等可能超长的业务文案列 SHALL 通过 `BusinessTable` 显式列配置开启单行省略和 TDesign `Tooltip`,Tooltip 宽度建议 200px 并自动换行;空值、空白字符串或占位符 `-` 只展示 `-`,不展示 Tooltip;名称、编码、状态、时间、数量等短文本或结构化字段不全局开启 Tooltip。同步更新 `architecture-spec/docs/architecture/component-guidelines.md` 和 `architecture-spec/docs/decisions/0003-backoffice-business-table-standard.md`,并通过 `openspec validate standardize-backoffice-business-table-usage --strict`。
- 2026-06-08:继续 `refine-business-components-tdesign-first`,按用户最新口径修正 `BusinessTable` tooltip 策略:默认不为普通文本列启用 Tooltip,必须由页面列配置显式声明 `ellipsisTooltip: true`;派生文本或数组拼接文本可通过 `tooltipValue` 提供展示内容。已在技能列表“说明”、官网 Agent 展示配置列表“Agent 概述”、岗位标签列表“标签描述”、渠道活码列表“关联 Agent”四类业务长文本列显式开启 TDesign `Tooltip`,悬浮内容宽度 200px 且换行。已更新既有 OpenSpec change `refine-business-components-tdesign-first` 的 proposal/design/spec/tasks,并通过 `BusinessTable`/`BusinessForm` 组件测试、四个相关列表页聚焦测试、`npm run typecheck`、`npm run build` 和 `openspec validate refine-business-components-tdesign-first --strict`;按用户要求未做浏览器验证。完整 `AgentTagManagement.test.tsx` 仍有与本次 tooltip 列无关的新建/编辑页断言失败,列表路由 tooltip 测试已单独通过。
- 2026-06-08:继续 `refine-business-components-tdesign-first`,按用户确认将“表格超长文本悬浮显示”落到通用 `BusinessTable`,不是只改单个业务页面:无自定义 `cell` 的普通文本/数字/布尔列默认单行省略,并使用 TDesign `Tooltip` 展示完整内容,悬浮内容宽度 200px 且换行;自定义 `cell` 保持不被覆盖。同步将无分页 `totalLabel` 收敛为 TDesign `Typography.Text`。`BusinessForm` 的 `input`/`textarea` 在配置 `maxLength` 后改为硬限制,值会在 `onChange` 层裁剪且继续展示 TDesign 字数;已清理已迁移页面中的常规 `allowInputOverMax: true`,官网 Agent 展示配置 `speech_content` 保持 100 字但不再允许输入第 101 字。已通过 `npm test -- --run src/business-components/BusinessForm.test.tsx src/business-components/business-table.test.tsx`、官网 Agent 展示配置相关测试、`npm run typecheck`、`npm run build`、`openspec validate refine-business-components-tdesign-first --strict`;按用户要求未做浏览器验证。
- 2026-06-08:继续 `migrate-editor-pages-to-business-form-phase-three`,按用户确认保留官网 Agent 展示配置编辑弹窗 `Agent 概述` 的 100 字校验,不改为 200 字,只补充 TDesign/BusinessForm 原生字数长度展示。实现为 `speech_content` 字段配置 `maxLength: 100` 与 `allowInputOverMax: true`,保存校验仍提示“Agent概述不能超过100字”。已补充页面集成测试覆盖 `101/100` 计数和超长校验,并通过官网 Agent 展示配置编辑测试、弹窗测试、BusinessForm 测试、`npm run typecheck`、`npm run build`、`openspec validate migrate-editor-pages-to-business-form-phase-three --strict`;按用户此前要求未做浏览器验证。
- 2026-06-08:完成 `migrate-editor-pages-to-business-form-phase-three` 实施:官网 Agent 展示配置编辑弹窗字段区已迁移到 `BusinessForm`,`Dialog`/`Button` 继续使用 TDesign,图标和展示素材通过 `BusinessForm` 自定义字段保留 `MediaWall` 上传、回显、删除和错误提示;相关弹窗与页面集成测试、BusinessForm 测试、`npm run typecheck`、`npm run build`、`openspec validate migrate-editor-pages-to-business-form-phase-three --strict` 均通过。按用户要求未做浏览器验证。
- 2026-06-05:继续 `business-form-component` 的 Demo 覆盖,按用户确认在 `BusinessForm` 示例中新增多选 Select 字段 `scenarios`(展示名“适用场景”),使用 `type: 'select'`、`multiple: true`,初始值为 `['approval', 'archive']`,用于在 `/components` 中对照单选 Select 验收 `select.multiple` 配置与数组值展示。同步更新 OpenSpec demo 覆盖范围和 task 7.14;Demo 测试新增多选字段断言,并将该测试的上传交互断言收窄为已有上传态展示,避免 JSDOM 中 TDesign Upload 隐藏 input 不稳定触发干扰。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`openspec validate business-form-component --strict` 和 `npm run build`;OpenSpec telemetry 仍有受限网络 PostHog flush 报错但退出码为 0。 - 2026-06-05:继续 `business-form-component` 的 Demo 覆盖,按用户确认在 `BusinessForm` 示例中新增多选 Select 字段 `scenarios`(展示名“适用场景”),使用 `type: 'select'`、`multiple: true`,初始值为 `['approval', 'archive']`,用于在 `/components` 中对照单选 Select 验收 `select.multiple` 配置与数组值展示。同步更新 OpenSpec demo 覆盖范围和 task 7.14;Demo 测试新增多选字段断言,并将该测试的上传交互断言收窄为已有上传态展示,避免 JSDOM 中 TDesign Upload 隐藏 input 不稳定触发干扰。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`openspec validate business-form-component --strict` 和 `npm run build`;OpenSpec telemetry 仍有受限网络 PostHog flush 报错但退出码为 0。
- 2026-06-08:继续 `official-site-agent-display-config-sort-status`,按用户补充将官网 Agent 展示配置列表页的 `展示状态` 同步为 `display_status = disable -> 不展示`,内部字段类型和值仍保持 `enable | disable` 不变。已更新列表页实现、列表页测试和该 change 的 OpenSpec artifacts/tasks;通过官网 Agent 展示配置相关测试、`npm run typecheck`、`npm run build` 和 `openspec validate official-site-agent-display-config-sort-status --strict`。按用户要求未做浏览器验证。
- 2026-06-08:继续 `official-site-agent-display-config-sort-status`,按用户反馈统一 `BusinessForm` 提示颜色:`errors[field.key]` 和内置校验错误使用红色,`helpText`/`helperText` 普通提示使用浅灰色。已在原 change 更新 proposal、design、spec 和 tasks,并按 TDD 补充 `BusinessForm.test.tsx`;实现中给 TDesign `FormItem help/tips` 分别传入带 `helpText`/`error` 样式的节点。已通过 BusinessForm 与官网 Agent 展示配置相关测试、`npm run typecheck`、`npm run build` 和 `openspec validate official-site-agent-display-config-sort-status --strict`;按用户要求未做浏览器验证。
- 2026-06-05:继续 `business-form-component` 的 TDesign Upload 收敛,按 TDD 增加上传字段 `maxCount` / `multiple` 配置。默认仍为单文件;配置 `maxCount > 1` 且 `multiple: true` 时,媒体上传支持多张图片/GIF/视频,值以 `BusinessFormUploadedFileValue[]` 写回;单文件已有值重新选择仍保持替换语义。图片/GIF 继续优先使用 TDesign `Upload theme="image"` 默认卡片,含视频列表仅做最小 `fileListDisplay` 适配以展示视频缩略图;文件名仍按现有 110px 卡片下方单行省略实现。Demo 的展示素材已配置为最多 3 个。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`npm run build`、`openspec validate business-form-component --strict`;未做浏览器验收,按用户要求由用户自行验收。 - 2026-06-05:继续 `business-form-component` 的 TDesign Upload 收敛,按 TDD 增加上传字段 `maxCount` / `multiple` 配置。默认仍为单文件;配置 `maxCount > 1` 且 `multiple: true` 时,媒体上传支持多张图片/GIF/视频,值以 `BusinessFormUploadedFileValue[]` 写回;单文件已有值重新选择仍保持替换语义。图片/GIF 继续优先使用 TDesign `Upload theme="image"` 默认卡片,含视频列表仅做最小 `fileListDisplay` 适配以展示视频缩略图;文件名仍按现有 110px 卡片下方单行省略实现。Demo 的展示素材已配置为最多 3 个。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`npm run build`、`openspec validate business-form-component --strict`;未做浏览器验收,按用户要求由用户自行验收。
- 2026-06-03:继续 `fix-business-table-duplicate-total`,用户确认后台列表首次加载使用骨架屏、后续分页/搜索/筛选/排序/刷新使用表格区域 loading。已把该规则写入全局 `architecture-spec/openspec/specs/web-desktop-ui-standard/spec.md` 与 `architecture-spec/docs/architecture/frontend-conventions.md`;`BusinessTable` 默认 loadingProps 调整为轻量小尺寸指示、浅色“加载中”文案和半透明蒙层,并允许调用方覆盖。已补充 `business-table.test.tsx` loading 回归,验证 loading 时保留表头且不展示空态;通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict` 和全局 `rtk openspec validate --specs --strict`。 - 2026-06-03:继续 `fix-business-table-duplicate-total`,用户确认后台列表首次加载使用骨架屏、后续分页/搜索/筛选/排序/刷新使用表格区域 loading。已把该规则写入全局 `architecture-spec/openspec/specs/web-desktop-ui-standard/spec.md` 与 `architecture-spec/docs/architecture/frontend-conventions.md`;`BusinessTable` 默认 loadingProps 调整为轻量小尺寸指示、浅色“加载中”文案和半透明蒙层,并允许调用方覆盖。已补充 `business-table.test.tsx` loading 回归,验证 loading 时保留表头且不展示空态;通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict` 和全局 `rtk openspec validate --specs --strict`。
- 2026-06-03:继续 `fix-business-table-duplicate-total` 的失败态收尾。用户指出列表失败态下方出现无文案蓝色按钮,定位为页面仍传 `errorState.onRetry`,而 `BusinessTable.createActionButton` 只判断回调、不判断按钮文案。已补充 OpenSpec 场景“不渲染无文案的状态区按钮”,更新 `business-table.test.tsx` 断言失败态不存在任何按钮,并修正 `createActionButton` 在没有 `label` 时返回 `undefined`;保留权限态“申请权限”按钮。已通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict`。 - 2026-06-03:继续 `fix-business-table-duplicate-total` 的失败态收尾。用户指出列表失败态下方出现无文案蓝色按钮,定位为页面仍传 `errorState.onRetry`,而 `BusinessTable.createActionButton` 只判断回调、不判断按钮文案。已补充 OpenSpec 场景“不渲染无文案的状态区按钮”,更新 `business-table.test.tsx` 断言失败态不存在任何按钮,并修正 `createActionButton` 在没有 `label` 时返回 `undefined`;保留权限态“申请权限”按钮。已通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict`。
...@@ -109,3 +117,12 @@ ...@@ -109,3 +117,12 @@
- 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 的 7.6,未推进 7.7。已通过 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`;命令退出码为 0,末尾仅出现 PostHog telemetry flush 网络超时提示,不影响 OpenSpec 校验结果;已只勾选 tasks 中的 7.6。 - 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 的 7.6,未推进 7.7。已通过 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`;命令退出码为 0,末尾仅出现 PostHog telemetry flush 网络超时提示,不影响 OpenSpec 校验结果;已只勾选 tasks 中的 7.6。
- 2026-06-01:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 的 7.7。用 Playwright 浏览器验证主要列表页 `/agents`、`/agent-tags`、`/channel-codes`、`/skills`、`/official-site/job-tabs`,编辑页 `/agents/new`、`/agent-tags/new`、`/channel-codes/new`、`/official-site/job-tabs/new`、`/official-site/methodology`,官网 Agent 展示配置弹窗 `/official-site/job-tabs/301/agents`,以及 `/components` 的布局与关键交互。验证中发现并修复 TDesign `DateRangePicker` 空 range 值 console error:全局 `SearchFilter` 对空 range 传 `[]`,组件 Demo 的 `DateRangePicker` 改为受控空数组;已通过相关测试、`npm run typecheck`、`npm run build` 和完整浏览器复验,已只勾选 tasks 中的 7.7。 - 2026-06-01:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 的 7.7。用 Playwright 浏览器验证主要列表页 `/agents`、`/agent-tags`、`/channel-codes`、`/skills`、`/official-site/job-tabs`,编辑页 `/agents/new`、`/agent-tags/new`、`/channel-codes/new`、`/official-site/job-tabs/new`、`/official-site/methodology`,官网 Agent 展示配置弹窗 `/official-site/job-tabs/301/agents`,以及 `/components` 的布局与关键交互。验证中发现并修复 TDesign `DateRangePicker` 空 range 值 console error:全局 `SearchFilter` 对空 range 传 `[]`,组件 Demo 的 `DateRangePicker` 改为受控空数组;已通过相关测试、`npm run typecheck`、`npm run build` 和完整浏览器复验,已只勾选 tasks 中的 7.7。
- 2026-06-01:继续 `extract-business-table-component` 的 3.1,仅迁移 `AgentListPage` 到 `BusinessTable`。页面现在用业务表格承接表格、筛选空态、加载失败态和分页,保留原有搜索和操作逻辑;同步把该页测试改成匹配新组件输出,去掉重复总数展示并按实际 DOM 断言失败态标题与重试按钮。已通过 `npm test -- src/routes/agents/AgentListPage.test.tsx` 和 `npm run typecheck`,已只勾选 tasks 中的 3.1。 - 2026-06-01:继续 `extract-business-table-component` 的 3.1,仅迁移 `AgentListPage` 到 `BusinessTable`。页面现在用业务表格承接表格、筛选空态、加载失败态和分页,保留原有搜索和操作逻辑;同步把该页测试改成匹配新组件输出,去掉重复总数展示并按实际 DOM 断言失败态标题与重试按钮。已通过 `npm test -- src/routes/agents/AgentListPage.test.tsx` 和 `npm run typecheck`,已只勾选 tasks 中的 3.1。
- 2026-06-08:继续 `refine-business-components-tdesign-first`,按用户反馈修正 `BusinessTable` 显式 tooltip 列的空内容行为:空字符串、空白字符串、`null`/`undefined` 和最终展示占位 `-` 的内容只显示 `-`,不渲染 TDesign `Tooltip`,避免空描述列出现无意义悬浮层;真实非空文本仍使用 `cellText` 单行省略和 200px 换行 Tooltip。已补充 OpenSpec business-table 场景、design 决策和 tasks,并完成实现与测试。验证通过 `npm test -- --run src/business-components/business-table.test.tsx`、`npm run typecheck`、`npm run build`、`openspec validate refine-business-components-tdesign-first --strict`;OpenSpec telemetry 仍因受限网络出现 PostHog flush 警告但退出码为 0,按用户要求未做浏览器验证。
- 2026-06-08:已核对并归档 `migrate-editor-pages-to-business-form-phase-three`。相关 `AgentDisplayConfigEditModal` / `OfficialSiteAgentDisplayConfigEdit` / `BusinessForm` 测试通过,`npm run typecheck`、`npm run build` 和 `openspec validate migrate-editor-pages-to-business-form-phase-three --strict` 均通过;OpenSpec archive 生成 `2026-06-08-migrate-editor-pages-to-business-form-phase-three`,并顺带更新了 `editor-page-form-composition` 规范。
- 2026-06-08:已核对并归档 `migrate-admin-ui-to-global-tdesign`。`workspace/agent-admin/web/src` 的运行时 import 守卫测试通过,`npm run typecheck` 通过,`openspec validate "migrate-admin-ui-to-global-tdesign" --strict` 通过;OpenSpec archive 生成 `2026-06-08-migrate-admin-ui-to-global-tdesign`,并更新了 `admin-ui-runtime-dependency` 规范。
- 2026-06-08:已核对并归档 `fix-business-table-duplicate-total`。`BusinessTable`、相关页面测试和 `business-table` 规范已对齐,`npm test -- --run src/business-components/business-table.test.tsx src/routes/components/ComponentsDemoPage.test.tsx src/routes/skills/SkillListPage.test.tsx src/routes/channel-codes/ChannelCodeListPage.test.tsx src/routes/agents/AgentListPage.test.tsx src/routes/agent-tags/AgentTagListPage.test.tsx src/routes/official-site-job-tabs/OfficialSiteJobTabListPage.test.tsx`、`npm run typecheck`、`openspec validate fix-business-table-duplicate-total --strict` 均通过;OpenSpec archive 生成 `2026-06-08-fix-business-table-duplicate-total`,并同步更新了 `business-table` 规范。
- 2026-06-08:已核对并归档 `align-components-demo-business-table-states`。`ComponentsDemoPage` 的表格状态示例已迁移为 `BusinessTable` 真实渲染,`ComponentsDemoPage.test.tsx` 覆盖了新旧文案与按钮差异;OpenSpec archive 生成 `2026-06-08-align-components-demo-business-table-states`,并同步更新了 `components-demo` 规范。
- 2026-06-08:按用户确认纠正 `official-site-agent-display-config-sort-status` 的文档归属:将误放在仓库根目录 `openspec/changes/` 的 active change 迁回 `workspace/agent-admin/web/openspec/changes/`,并将对应 Superpowers 设计文档从根目录 `docs/superpowers/specs/` 迁到 `workspace/agent-admin/web/docs/superpowers/specs/`。已在 `workspace/agent-admin/web` 下通过 `openspec validate official-site-agent-display-config-sort-status --strict`;当前 change 仍为 active,后续归档前需先处理/确认 tasks 2.5-2.8。
- 2026-06-08:复核 `official-site-agent-display-config-sort-status` 中官网 Agent 展示配置编辑弹窗颜色问题:当前 `AgentDisplayConfigEditModal` 字段区已迁移到 `BusinessForm`,不再直接维护 TDesign `FormItem` 的 `help/tips` 渲染,错误红色与普通说明浅灰色由 `BusinessForm` 统一保证。已更新该 change 的 proposal/design/spec/tasks,移除“弹窗直接 TDesign FormItem 需单独修复”的过时假设;通过 `npm test -- --run src/routes/official-site-agent-display-config/AgentDisplayConfigEditModal.test.tsx src/business-components/BusinessForm.test.tsx`、`npm run typecheck`、`npm run build`、`openspec validate official-site-agent-display-config-sort-status --strict`,`openspec status --change official-site-agent-display-config-sort-status --json` 显示 complete。
- 2026-06-08:已归档 `official-site-agent-display-config-sort-status`。归档前在 `workspace/agent-admin/web` 下确认 `openspec validate official-site-agent-display-config-sort-status --strict` 通过且 `openspec status --change official-site-agent-display-config-sort-status --json` 为 complete;`openspec archive official-site-agent-display-config-sort-status` 生成 `openspec/changes/archive/2026-06-08-official-site-agent-display-config-sort-status`,并创建项目级规范 `openspec/specs/official-site-agent-display-config-sort-status/spec.md`。归档后单独校验该 spec 通过;全量 `openspec validate --specs --strict` 仍有既有 `agent-tags-management` 与 `official-site-methodology-config` 失败,和本次归档 spec 无关。
- 2026-06-08:已归档工作区级规范 `standardize-backoffice-business-table-usage`。该 change 位于 `architecture-spec/openspec/changes/`,归档前确认 `openspec status --change standardize-backoffice-business-table-usage --json` 为 complete,且 `openspec validate standardize-backoffice-business-table-usage --strict` 通过;`openspec archive standardize-backoffice-business-table-usage` 生成 `openspec/changes/archive/2026-06-08-standardize-backoffice-business-table-usage`,并将后台表格默认使用 `BusinessTable`、长文案列显式 Tooltip 等规则合入 `openspec/specs/web-desktop-ui-standard/spec.md`。归档后 `openspec validate web-desktop-ui-standard --strict` 通过;OpenSpec telemetry 的 PostHog flush DNS 警告不影响退出码。
...@@ -120,6 +120,10 @@ ...@@ -120,6 +120,10 @@
`StatePlaceholder` 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。若某个后台表格需要特殊状态或特殊动作,应优先扩展 `BusinessTable` 的受控配置,并通过 OpenSpec 更新规范,不在页面内临时拼装一套表格状态。 `StatePlaceholder` 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。若某个后台表格需要特殊状态或特殊动作,应优先扩展 `BusinessTable` 的受控配置,并通过 OpenSpec 更新规范,不在页面内临时拼装一套表格状态。
描述、概述、说明、备注、内容等可能超长的业务文案列 SHALL 使用 `BusinessTable` 的受控列配置开启单行省略,并使用 TDesign `Tooltip` 在鼠标悬浮时展示完整内容。Tooltip 内容区域宽度 SHOULD 为 `200px`,内容自动换行。空值、空白字符串或占位符 `-` 只展示 `-`,不展示 Tooltip。
名称、编码、状态、时间、数量等短文本或结构化字段 SHOULD 保持默认文本展示,不为所有列全局开启 Tooltip。项目应按字段语义为可能超长文案列显式开启 Tooltip。
后台列表页 SHALL 以 `content` 列表页作为固定参考模式,统一采用以下结构: 后台列表页 SHALL 以 `content` 列表页作为固定参考模式,统一采用以下结构:
1. 页面标题区:展示页面标题、必要说明和主创建动作,主创建按钮放在右侧。 1. 页面标题区:展示页面标题、必要说明和主创建动作,主创建按钮放在右侧。
......
...@@ -17,12 +17,16 @@ ...@@ -17,12 +17,16 @@
- `BusinessTable` SHALL 承接后台表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。 - `BusinessTable` SHALL 承接后台表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
- 页面仍 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点等业务逻辑。 - 页面仍 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点等业务逻辑。
- `StatePlaceholder` SHALL 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。 - `StatePlaceholder` SHALL 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。
- 当表格列展示描述、概述、说明、备注、内容等可能超长的业务文案时,项目 SHALL 使用 `BusinessTable` 的受控列配置开启单行省略,并使用 TDesign `Tooltip` 在鼠标悬浮时展示完整内容。
- Tooltip 内容区域宽度 SHOULD 为 `200px`,并支持自动换行;空值、空白字符串或占位符 `-` SHALL 只展示 `-`,不展示 Tooltip。
- 名称、编码、状态、时间、数量等短文本或结构化字段 SHOULD 保持默认文本展示,不为所有列全局开启 Tooltip。
- 如果后台表格需要特殊状态或特殊动作,项目 SHALL 优先扩展 `BusinessTable` 的受控配置,并同步更新工作区级规范和对应 OpenSpec,不在页面内临时拼装一套表格状态。 - 如果后台表格需要特殊状态或特殊动作,项目 SHALL 优先扩展 `BusinessTable` 的受控配置,并同步更新工作区级规范和对应 OpenSpec,不在页面内临时拼装一套表格状态。
- 历史页面若尚未使用 `BusinessTable`,SHOULD 通过独立 OpenSpec change 分批迁移,避免无规格的大范围重构。 - 历史页面若尚未使用 `BusinessTable`,SHOULD 通过独立 OpenSpec change 分批迁移,避免无规格的大范围重构。
## 影响 ## 影响
- `architecture-spec/docs/architecture/component-guidelines.md` 的表格使用规则需要明确 `BusinessTable` 是后台管理系统表格默认入口。 - `architecture-spec/docs/architecture/component-guidelines.md` 的表格使用规则需要明确 `BusinessTable` 是后台管理系统表格默认入口。
- 具体项目的表格列如展示超长文案,应继承省略和 TDesign Tooltip 的统一交互,而不是在页面内自定义悬浮层或默认给所有列加 Tooltip。
- 具体项目的 OpenSpec 如涉及后台表格、列表页或组件 demo,应继承该工作区级约束。 - 具体项目的 OpenSpec 如涉及后台表格、列表页或组件 demo,应继承该工作区级约束。
- `workspace/agent-admin/web` 的组件 demo 需要调整为通过 `BusinessTable` 展示表格状态,而不是在 `StatePlaceholder` demo 中展示表格状态集合。 - `workspace/agent-admin/web` 的组件 demo 需要调整为通过 `BusinessTable` 展示表格状态,而不是在 `StatePlaceholder` demo 中展示表格状态集合。
......
## Context
`agent` 工作区已有 `@gl/business-components`,其中 `BusinessTable` 用于统一后台表格、表格状态和分页展示。用户已确认该约束不只适用于 `agent-web` 或 `agent-admin`,而是适用于 `agent` 工作区下所有项目的后台管理系统。
## Goals / Non-Goals
**Goals:**
- 将 `BusinessTable` 写入工作区级后台表格默认规范。
- 让后续后台项目、新页面、新 demo 和新增表格功能默认继承统一表格入口。
- 明确页面职责与 `BusinessTable` 职责边界。
- 为特殊表格例外和历史迁移提供 OpenSpec 路径。
**Non-Goals:**
- 不在本 change 中迁移所有历史后台页面。
- 不限制非后台管理系统的公开站点、落地页或高度定制交互页面。
- 不冻结 `BusinessTable` API,后续特殊状态仍可通过规范化扩展演进。
## Decisions
- 在 `web-desktop-ui-standard` 中增加后台表格默认入口要求。
- 原因:这是跨项目前端行为约束,应落在工作区级 Web 桌面端规范,而不是某个业务项目私有规范。
- 替代方案:只写在 `agent-admin/web` 项目规范中。该方案无法覆盖 `agent` 下其他后台管理系统。
- 页面不得直接拼装后台表格模式。
- 原因:表格状态和分页规则应由 `BusinessTable` 统一承接,页面只负责业务数据和交互。
- 历史迁移分批处理。
- 原因:一次性迁移所有历史页面风险较高,且本次需求重点是锁定后续默认约束和 demo 展示。
## Risks / Trade-offs
- 历史页面仍可能短期存在旧表格拼装。
- 缓解:通过独立 OpenSpec change 分批迁移,并禁止新功能继续扩散旧模式。
- 特殊业务表格可能需要额外状态或动作。
- 缓解:优先扩展 `BusinessTable` 的受控配置,并同步更新 OpenSpec。
## Migration Plan
1. 写入工作区级 OpenSpec delta。
2. 校验 `standardize-backoffice-business-table-usage`。
3. 后续项目或页面涉及后台表格时,按该规范默认使用 `BusinessTable`。
4. 既有页面如需迁移,另起 OpenSpec change。
## Why
`agent` 工作区后续会包含多个后台管理系统前端项目,如果各项目继续直接拼装 TDesign `Table`、`Pagination`、`Empty`、`StatePlaceholder` 和按钮,表格状态、分页总数和 loading 规则会持续漂移。`@gl/business-components` 已沉淀 `BusinessTable`,需要将其作为工作区级后台表格默认入口。
## What Changes
- 在工作区级 OpenSpec 中明确:`agent` 下所有后台管理系统前端项目的后台列表表格 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable`。
- 禁止新页面、新 demo 和新增表格功能直接拼装 TDesign 表格、分页、空态和按钮来替代 `BusinessTable` 的后台表格模式。
- 明确 `BusinessTable` 承接表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
- 明确 `StatePlaceholder` 仅用于非表格区域的通用占位。
- 历史页面迁移通过独立 OpenSpec change 分批处理。
## Capabilities
### New Capabilities
<!-- 无。 -->
### Modified Capabilities
- `web-desktop-ui-standard`: 增加后台管理系统表格必须默认使用 `BusinessTable` 的工作区级要求。
## Impact
- 影响 `architecture-spec/openspec/specs/web-desktop-ui-standard/spec.md` 的工作区级前端规范。
- 影响后续 `agent` 下所有后台管理系统前端项目的新列表页、组件 demo 和表格功能设计。
- 不强制本 change 立即迁移所有历史页面;历史页面迁移应由后续独立 OpenSpec 覆盖。
## ADDED Requirements
### Requirement: 后台管理系统表格必须默认使用 BusinessTable
`agent` 工作区下所有后台管理系统前端项目 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable` 渲染后台列表表格,并由 `BusinessTable` 统一承接表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
#### Scenario: 新建后台列表页
- **WHEN** `agent` 工作区任一后台管理系统前端项目新增包含后台列表表格的页面
- **THEN** 页面 SHALL 使用 `BusinessTable` 渲染表格区域
- **AND** 页面 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、TDesign `Empty`、`StatePlaceholder` 和按钮来替代 `BusinessTable` 的后台表格模式
#### Scenario: 新增 demo 或表格功能
- **WHEN** 后台管理系统项目新增组件 demo、业务模块或表格相关功能
- **THEN** 表格状态示例和表格运行态 SHALL 通过 `BusinessTable` 展示
- **AND** 系统 SHALL NOT 在页面内临时拼装另一套表格空态、失败态、权限态、loading 或分页总数展示规则
#### Scenario: 页面处理业务逻辑
- **WHEN** 页面使用 `BusinessTable` 渲染后台列表表格
- **THEN** 页面 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点
- **AND** `BusinessTable` SHALL 负责表格结构、状态展示和分页总数展示
#### Scenario: 非表格占位
- **WHEN** 页面展示页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的通用占位
- **THEN** 页面 MAY 使用 `StatePlaceholder`
- **AND** 页面 SHALL NOT 使用 `StatePlaceholder` 替代后台表格状态区域
#### Scenario: 特殊表格例外
- **WHEN** 后台表格场景无法由当前 `BusinessTable` 承载
- **THEN** 项目 MUST 先通过 OpenSpec 说明例外原因、替代方案、状态规则和验证方式
- **AND** 项目 SHALL 优先评估扩展 `BusinessTable` 的受控配置
#### Scenario: 历史页面迁移
- **WHEN** 历史后台页面尚未使用 `BusinessTable`
- **THEN** 项目 SHOULD 通过独立 OpenSpec change 分批迁移
- **AND** 新页面、新 demo 和新增表格功能 SHALL NOT 继续扩散页面级自组装表格模式
## 1. OpenSpec 对齐
- [x] 1.1 创建 proposal,明确工作区级 `BusinessTable` 默认入口约束
- [x] 1.2 创建设计说明,明确约束范围覆盖 `agent` 下所有后台管理系统前端项目
- [x] 1.3 创建 `web-desktop-ui-standard` spec delta,写入后台表格默认使用 `BusinessTable` 的要求
- [x] 1.4 等待用户确认 OpenSpec 后进入具体项目 TDD
## 2. 文档同步
- [x] 2.1 在架构决策中记录后台管理系统统一使用 `BusinessTable`
- [x] 2.2 在组件使用规范中记录后台表格默认入口和 `StatePlaceholder` 边界
## 3. 验证
- [x] 3.1 运行 `rtk openspec validate standardize-backoffice-business-table-usage --strict`
- [x] 3.2 在项目侧 demo OpenSpec 和实现中继承该约束
...@@ -79,3 +79,59 @@ ...@@ -79,3 +79,59 @@
- **WHEN** 用户滚动独立页面中的表单或配置内容 - **WHEN** 用户滚动独立页面中的表单或配置内容
- **THEN** `返回` 和 `保存` 所在页头操作区保持在屏幕可见区域 - **THEN** `返回` 和 `保存` 所在页头操作区保持在屏幕可见区域
- **AND** sticky 页头具备不透明背景、边框和合理层级,避免内容滚动时穿透或覆盖页头 - **AND** sticky 页头具备不透明背景、边框和合理层级,避免内容滚动时穿透或覆盖页头
### Requirement: 后台管理系统表格必须默认使用 BusinessTable
`agent` 工作区下所有后台管理系统前端项目 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable` 渲染后台列表表格,并由 `BusinessTable` 统一承接表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
#### Scenario: 新建后台列表页
- **WHEN** `agent` 工作区任一后台管理系统前端项目新增包含后台列表表格的页面
- **THEN** 页面 SHALL 使用 `BusinessTable` 渲染表格区域
- **AND** 页面 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、TDesign `Empty`、`StatePlaceholder` 和按钮来替代 `BusinessTable` 的后台表格模式
#### Scenario: 新增 demo 或表格功能
- **WHEN** 后台管理系统项目新增组件 demo、业务模块或表格相关功能
- **THEN** 表格状态示例和表格运行态 SHALL 通过 `BusinessTable` 展示
- **AND** 系统 SHALL NOT 在页面内临时拼装另一套表格空态、失败态、权限态、loading 或分页总数展示规则
#### Scenario: 页面处理业务逻辑
- **WHEN** 页面使用 `BusinessTable` 渲染后台列表表格
- **THEN** 页面 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点
- **AND** `BusinessTable` SHALL 负责表格结构、状态展示和分页总数展示
#### Scenario: 超长文案列展示
- **WHEN** 任一后台管理系统前端项目的表格列展示描述、概述、说明、备注、内容或其他可能超长的业务文案
- **THEN** 该列 SHALL 使用 `BusinessTable` 的受控列配置开启单行省略展示
- **AND** 该列 SHALL 使用 TDesign `Tooltip` 在鼠标悬浮时展示完整内容
- **AND** Tooltip 内容区域宽度 SHOULD 为 `200px`,并支持自动换行
- **AND** 空值、空白字符串或占位符 `-` SHALL 只展示 `-`,不展示 Tooltip
#### Scenario: 普通短文本列展示
- **WHEN** 表格列展示名称、编码、状态、时间、数量或其他短文本/结构化字段
- **THEN** 该列 SHOULD 保持默认文本展示
- **AND** 页面 SHOULD NOT 为所有列全局开启 Tooltip
- **AND** 项目 SHALL 按字段语义为可能超长文案列显式开启 Tooltip
#### Scenario: 非表格占位
- **WHEN** 页面展示页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的通用占位
- **THEN** 页面 MAY 使用 `StatePlaceholder`
- **AND** 页面 SHALL NOT 使用 `StatePlaceholder` 替代后台表格状态区域
#### Scenario: 特殊表格例外
- **WHEN** 后台表格场景无法由当前 `BusinessTable` 承载
- **THEN** 项目 MUST 先通过 OpenSpec 说明例外原因、替代方案、状态规则和验证方式
- **AND** 项目 SHALL 优先评估扩展 `BusinessTable` 的受控配置
#### Scenario: 历史页面迁移
- **WHEN** 历史后台页面尚未使用 `BusinessTable`
- **THEN** 项目 SHOULD 通过独立 OpenSpec change 分批迁移
- **AND** 新页面、新 demo 和新增表格功能 SHALL NOT 继续扩散页面级自组装表格模式
.root { .root {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px;
} }
.field { .field {
display: grid; min-width: 0;
grid-template-columns: 120px minmax(0, 1fr); }
column-gap: 16px;
align-items: start; .formItem {
margin-bottom: 0;
} }
.label { .label {
...@@ -29,12 +29,23 @@ ...@@ -29,12 +29,23 @@
} }
.controlHolder { .controlHolder {
width: 100%;
min-width: 0; min-width: 0;
} }
.controlHolder :global(.t-input),
.controlHolder :global(.t-input-number),
.controlHolder :global(.t-select),
.controlHolder :global(.t-textarea),
.controlHolder :global(.t-input__wrap),
.controlHolder :global(.t-select__wrap),
.controlHolder :global(.t-textarea__wrap) {
width: 100%;
}
.helpText { .helpText {
margin-top: 6px; margin-top: 6px;
color: #666; color: #a6a6a6;
font-size: 12px; font-size: 12px;
line-height: 1.5; line-height: 1.5;
} }
...@@ -50,6 +61,7 @@ ...@@ -50,6 +61,7 @@
display: inline-flex; display: inline-flex;
min-height: 32px; min-height: 32px;
align-items: center; align-items: center;
gap: 12px;
color: #1f1f1f; color: #1f1f1f;
} }
...@@ -108,6 +120,11 @@ ...@@ -108,6 +120,11 @@
display: inline-flex; display: inline-flex;
flex-direction: column; flex-direction: column;
gap: 8px; gap: 8px;
width: 160px;
max-width: 100%;
}
.uploadPreviewName {
max-width: 100%; max-width: 100%;
} }
......
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react'; import type { CSSProperties, ReactNode } from 'react';
import { Button, InputNumber, Upload } from 'tdesign-react'; import { Button, Form, Image, Link, Typography, Upload } from 'tdesign-react';
import type { TdUploadProps, UploadFile } from 'tdesign-react'; import type { TdUploadProps, UploadFile } from 'tdesign-react';
import { BrowseIcon, DeleteIcon } from 'tdesign-icons-react'; import { BrowseIcon, DeleteIcon } from 'tdesign-icons-react';
...@@ -8,6 +8,12 @@ import { classNames } from '../shared/classNames'; ...@@ -8,6 +8,12 @@ import { classNames } from '../shared/classNames';
import { Input, Select, Switch, Textarea } from '../shared/TDesignAccessibleControls'; import { Input, Select, Switch, Textarea } from '../shared/TDesignAccessibleControls';
import styles from './BusinessForm.module.css'; import styles from './BusinessForm.module.css';
const { FormItem } = Form;
const { Text } = Typography;
const BUSINESS_FORM_ROW_GAP = '40px';
const BUSINESS_FORM_HELP_TEXT_COLOR = '#a6a6a6';
const BUSINESS_FORM_ERROR_TEXT_COLOR = '#d94841';
export type BusinessFormValue = export type BusinessFormValue =
| string | string
| number | number
...@@ -209,10 +215,59 @@ function resolveVisible( ...@@ -209,10 +215,59 @@ function resolveVisible(
} }
function formatFieldWidth(fieldWidth: number | string | undefined) { function formatFieldWidth(fieldWidth: number | string | undefined) {
if (fieldWidth === undefined) return '360px'; if (fieldWidth === undefined) return '360';
return typeof fieldWidth === 'number' ? `${fieldWidth}` : fieldWidth; return typeof fieldWidth === 'number' ? `${fieldWidth}` : fieldWidth;
} }
interface FieldWidthLayout {
dataWidth: string;
holderClassName?: string;
holderStyle?: CSSProperties;
controlStyle?: CSSProperties;
}
function resolveFieldWidthLayout(fieldWidth: number | string | undefined): FieldWidthLayout {
const dataWidth = formatFieldWidth(fieldWidth);
if (fieldWidth === undefined) {
return {
dataWidth,
holderStyle: { width: '100%', maxWidth: '360px' },
controlStyle: { width: '100%' },
};
}
if (typeof fieldWidth === 'number') {
return {
dataWidth,
holderStyle: { width: '100%', maxWidth: `${fieldWidth}px` },
controlStyle: { width: '100%' },
};
}
const trimmed = fieldWidth.trim();
const isCssLength =
/^(\d+(\.\d+)?(px|r?em|%|vw|vh|vmin|vmax|ch|ex|rem|cm|mm|in|pt|pc)|0)$/.test(trimmed) ||
trimmed.startsWith('calc(') ||
trimmed.startsWith('min(') ||
trimmed.startsWith('max(') ||
trimmed.startsWith('clamp(');
if (isCssLength) {
return {
dataWidth,
holderStyle: { width: '100%', maxWidth: trimmed },
controlStyle: { width: '100%' },
};
}
return {
dataWidth,
holderClassName: trimmed,
controlStyle: { width: '100%' },
};
}
function normalizeValue(value: BusinessFormValue) { function normalizeValue(value: BusinessFormValue) {
if (value === undefined || value === null) return ''; if (value === undefined || value === null) return '';
if (typeof value === 'string' || typeof value === 'number') return value; if (typeof value === 'string' || typeof value === 'number') return value;
...@@ -226,6 +281,11 @@ function stringifyValue(value: BusinessFormValue) { ...@@ -226,6 +281,11 @@ function stringifyValue(value: BusinessFormValue) {
return ''; return '';
} }
function capTextValue(field: BusinessFormInputField | BusinessFormTextareaField, value: string) {
if (typeof field.maxLength !== 'number' || field.maxLength < 0) return value;
return value.slice(0, field.maxLength);
}
function inferUploadKind(value: BusinessFormValue): BusinessFormUploadKind | undefined { function inferUploadKind(value: BusinessFormValue): BusinessFormUploadKind | undefined {
if (!value) return undefined; if (!value) return undefined;
if (typeof value === 'object' && 'kind' in value && value.kind) return value.kind; if (typeof value === 'object' && 'kind' in value && value.kind) return value.kind;
...@@ -401,6 +461,7 @@ function formatUploadError(reason: 'invalid-kind' | 'invalid-accept' | 'invalid- ...@@ -401,6 +461,7 @@ function formatUploadError(reason: 'invalid-kind' | 'invalid-accept' | 'invalid-
function resolveTextValue(value: BusinessFormValue) { function resolveTextValue(value: BusinessFormValue) {
if (value === undefined || value === null) return '-'; if (value === undefined || value === null) return '-';
if (Array.isArray(value)) return value.length > 0 ? value.join('、') : '-';
if (typeof value === 'boolean') return value ? '是' : '否'; if (typeof value === 'boolean') return value ? '是' : '否';
if (typeof value === 'object' && value && 'url' in value) { if (typeof value === 'object' && value && 'url' in value) {
return (value as BusinessFormUploadedFileValue).name ?? (value as BusinessFormUploadedFileValue).url; return (value as BusinessFormUploadedFileValue).name ?? (value as BusinessFormUploadedFileValue).url;
...@@ -408,6 +469,21 @@ function resolveTextValue(value: BusinessFormValue) { ...@@ -408,6 +469,21 @@ function resolveTextValue(value: BusinessFormValue) {
return String(value); return String(value);
} }
function renderSelectReadonlyValue(field: BusinessFormSelectField, value: BusinessFormValue): ReactNode {
const selectedValues = field.multiple ? (Array.isArray(value) ? value : []) : [value];
const labels = field.options
.filter((option) => selectedValues.includes(option.value))
.map((option) => option.label);
if (labels.length === 0) return resolveTextValue(value);
if (labels.length === 1) return labels[0];
return labels.reduce<ReactNode[]>((nodes, label, index) => {
if (index > 0) nodes.push('、');
nodes.push(label);
return nodes;
}, []);
}
function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) { function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) {
if (uploadedValues.length === 0) return null; if (uploadedValues.length === 0) return null;
...@@ -416,8 +492,10 @@ function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) { ...@@ -416,8 +492,10 @@ function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) {
if (kind === 'image' || kind === 'gif') { if (kind === 'image' || kind === 'gif') {
return ( return (
<div className={styles.uploadPreview} key={uploaded.url}> <div className={styles.uploadPreview} key={uploaded.url}>
<img className={styles.uploadImage} src={uploaded.url} alt={uploaded.name ?? uploaded.url} /> <Image className={styles.uploadImage} src={uploaded.url} alt={uploaded.name ?? uploaded.url} fit="cover" />
<span>{uploaded.name ?? uploaded.url}</span> <Text className={styles.uploadPreviewName} ellipsis>
{uploaded.name ?? uploaded.url}
</Text>
</div> </div>
); );
} }
...@@ -432,13 +510,23 @@ function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) { ...@@ -432,13 +510,23 @@ function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) {
playsInline playsInline
preload="metadata" preload="metadata"
/> />
<span>{uploaded.name ?? uploaded.url}</span> <Text className={styles.uploadPreviewName} ellipsis>
{uploaded.name ?? uploaded.url}
</Text>
</div> </div>
); );
} }
return ( return (
<div className={styles.uploadPreview} key={uploaded.url}> <div className={styles.uploadPreview} key={uploaded.url}>
<span>{uploaded.name ?? uploaded.url}</span> {uploaded.url ? (
<Link className={styles.uploadPreviewName} href={uploaded.url} target="_blank" {...({ rel: 'noreferrer' } as any)}>
{uploaded.name ?? uploaded.url}
</Link>
) : (
<Text className={styles.uploadPreviewName} ellipsis>
{uploaded.name ?? uploaded.url}
</Text>
)}
</div> </div>
); );
}); });
...@@ -454,10 +542,6 @@ function buildUploadFiles(uploadedValues: BusinessFormUploadedFileValue[]): Uplo ...@@ -454,10 +542,6 @@ function buildUploadFiles(uploadedValues: BusinessFormUploadedFileValue[]): Uplo
})); }));
} }
function resolveFieldWidthClass(fieldWidth: string) {
return fieldWidth;
}
function buildValidationMessage(field: BusinessFormField, value: BusinessFormValue, values: BusinessFormValues) { function buildValidationMessage(field: BusinessFormField, value: BusinessFormValue, values: BusinessFormValues) {
if (!resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values) || field.type === 'displayText') { if (!resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values) || field.type === 'displayText') {
return undefined; return undefined;
...@@ -495,23 +579,25 @@ async function runBusinessFormValidation(fields: BusinessFormField[], values: Bu ...@@ -495,23 +579,25 @@ async function runBusinessFormValidation(fields: BusinessFormField[], values: Bu
const errors: BusinessFormErrors = {}; const errors: BusinessFormErrors = {};
for (const field of fields) { for (const field of fields) {
const value = values[field.key];
const builtInError = buildValidationMessage(field, value, values);
if (builtInError) {
errors[field.key] = builtInError;
continue;
}
if (field.type === 'displayText' || !resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values)) { if (field.type === 'displayText' || !resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values)) {
continue; continue;
} }
const value = values[field.key];
if (field.validator) { if (field.validator) {
const customError = await field.validator(value, { values, field }); const customError = await field.validator(value, { values, field });
if (customError) { if (typeof customError === 'string') {
errors[field.key] = customError; errors[field.key] = customError;
continue;
} }
} }
const builtInError = buildValidationMessage(field, value, values);
if (builtInError) {
errors[field.key] = builtInError;
continue;
}
} }
return errors; return errors;
...@@ -523,6 +609,7 @@ export function BusinessForm({ ...@@ -523,6 +609,7 @@ export function BusinessForm({
errors, errors,
fieldWidth, fieldWidth,
fields, fields,
labelAlign = 'left',
values, values,
'data-testid': dataTestId = 'business-form', 'data-testid': dataTestId = 'business-form',
onChange, onChange,
...@@ -532,6 +619,7 @@ export function BusinessForm({ ...@@ -532,6 +619,7 @@ export function BusinessForm({
const draftValuesRef = useRef<BusinessFormValues>({ ...values }); const draftValuesRef = useRef<BusinessFormValues>({ ...values });
const changeValuesRef = useRef<BusinessFormValues>({ ...values }); const changeValuesRef = useRef<BusinessFormValues>({ ...values });
const resolvedWidth = formatFieldWidth(fieldWidth); const resolvedWidth = formatFieldWidth(fieldWidth);
const fieldWidthLayout = useMemo(() => resolveFieldWidthLayout(fieldWidth), [fieldWidth]);
const currentValues = draftValues; const currentValues = draftValues;
const mergedErrors = useMemo( const mergedErrors = useMemo(
...@@ -557,7 +645,13 @@ export function BusinessForm({ ...@@ -557,7 +645,13 @@ export function BusinessForm({
}; };
return ( return (
<div className={classNames(styles.root, className)} data-testid={dataTestId}> <Form
className={classNames(styles.root, className)}
colon={false}
labelAlign={labelAlign}
data-testid={dataTestId}
style={{ gap: BUSINESS_FORM_ROW_GAP }}
>
{fields.map((field) => { {fields.map((field) => {
const visible = resolveVisible(field.visible, currentValues); const visible = resolveVisible(field.visible, currentValues);
if (!visible) return null; if (!visible) return null;
...@@ -566,7 +660,7 @@ export function BusinessForm({ ...@@ -566,7 +660,7 @@ export function BusinessForm({
const readonly = resolveBoolean(field.readonly, currentValues); const readonly = resolveBoolean(field.readonly, currentValues);
const value = currentValues[field.key]; const value = currentValues[field.key];
const error = mergedErrors[field.key]; const error = mergedErrors[field.key];
const fieldWidthClass = resolveFieldWidthClass(resolvedWidth); const help = field.helperText ?? field.helpText;
const controlId = `business-form-control-${field.key}`; const controlId = `business-form-control-${field.key}`;
const labelId = `${controlId}-label`; const labelId = `${controlId}-label`;
const fieldState = { const fieldState = {
...@@ -591,22 +685,25 @@ export function BusinessForm({ ...@@ -591,22 +685,25 @@ export function BusinessForm({
key={field.key} key={field.key}
className={classNames(styles.field, field.className)} className={classNames(styles.field, field.className)}
data-testid={`business-form-field-${field.key}`} data-testid={`business-form-field-${field.key}`}
data-width={fieldWidthClass} data-width={resolvedWidth}
> >
<label <FormItem
className={styles.label} className={styles.formItem}
htmlFor={field.type === 'input' || field.type === 'numberInput' || field.type === 'textarea' ? controlId : undefined} help={help ? <div className={styles.helpText} style={{ color: BUSINESS_FORM_HELP_TEXT_COLOR }}>{help}</div> : undefined}
id={labelId} label={<span id={labelId}>{field.label}</span>}
requiredMark={field.required}
status={error ? 'error' : undefined}
tips={error ? <div className={styles.error} style={{ color: BUSINESS_FORM_ERROR_TEXT_COLOR }}>{error}</div> : undefined}
> >
{field.required ? <span className={styles.required}>*</span> : null} <div
<span>{field.label}</span> className={classNames(styles.controlHolder, fieldWidthLayout.holderClassName)}
</label> data-testid={`business-form-control-holder-${field.key}`}
<div className={styles.controlWrap}> style={fieldWidthLayout.holderStyle}
<div className={styles.controlHolder}> >
{field.type === 'displayText' ? ( {field.type === 'displayText' ? (
<span className={styles.readonlyValue}> <Text className={styles.readonlyValue}>
{field.render?.(value, currentValues) ?? resolveTextValue(value)} {field.render?.(value, currentValues) ?? resolveTextValue(value)}
</span> </Text>
) : null} ) : null}
{field.type === 'custom' ? ( {field.type === 'custom' ? (
...@@ -622,59 +719,79 @@ export function BusinessForm({ ...@@ -622,59 +719,79 @@ export function BusinessForm({
) : null} ) : null}
{field.type === 'input' ? ( {field.type === 'input' ? (
<Input readonly ? (
id={controlId} <Text className={styles.readonlyValue}>{resolveTextValue(value)}</Text>
aria-label={field.label} ) : (
clearable={field.allowClear} <Input
disabled={disabled} id={controlId}
maxlength={field.maxLength} aria-label={field.label}
allowInputOverMax={field.allowInputOverMax} clearable={field.allowClear}
placeholder={field.placeholder ?? `请输入${field.label}`} disabled={disabled}
readOnly={readonly} maxlength={field.maxLength}
showLimitNumber={field.maxLength !== undefined} allowInputOverMax={false}
type="text" placeholder={field.placeholder ?? `请输入${field.label}`}
value={stringifyValue(normalizeValue(value))} showLimitNumber={field.maxLength !== undefined}
onChange={(nextValue) => { type="text"
applyFieldChange(field, String(nextValue ?? '')); value={stringifyValue(normalizeValue(value))}
}} style={fieldWidthLayout.controlStyle}
/> onChange={(nextValue) => {
applyFieldChange(field, capTextValue(field, String(nextValue ?? '')));
}}
/>
)
) : null} ) : null}
{field.type === 'numberInput' ? ( {field.type === 'numberInput' ? (
<InputNumber readonly ? (
disabled={disabled} <Text className={styles.readonlyValue}>{resolveTextValue(value)}</Text>
max={field.max} ) : (
min={field.min} <Input
placeholder={field.placeholder ?? `请输入${field.label}`} id={controlId}
readOnly={readonly} aria-label={field.label}
decimalPlaces={field.precision} disabled={disabled}
value={value === undefined || value === null ? '' : (value as string | number)} placeholder={field.placeholder ?? `请输入${field.label}`}
onChange={(nextValue) => { type="number"
applyFieldChange(field, nextValue === '' ? undefined : (nextValue as BusinessFormValue)); value={value === undefined || value === null ? '' : String(value)}
}} style={fieldWidthLayout.controlStyle}
/> onChange={(nextValue) => {
const text = String(nextValue ?? '').trim();
if (!text) {
applyFieldChange(field, undefined);
return;
}
const parsed = Number(text);
applyFieldChange(field, Number.isFinite(parsed) ? parsed : text);
}}
/>
)
) : null} ) : null}
{field.type === 'select' ? ( {field.type === 'select' ? (
<Select readonly ? (
id={controlId} <Text className={styles.readonlyValue}>{renderSelectReadonlyValue(field, value)}</Text>
aria-label={field.label} ) : (
clearable={field.allowClear} <Select
disabled={disabled} id={controlId}
multiple={field.multiple} aria-label={field.label}
options={field.options} clearable={field.allowClear}
placeholder={field.placeholder ?? `请选择${field.label}`} disabled={disabled}
readOnly={readonly} multiple={field.multiple}
value={field.multiple ? (Array.isArray(value) ? value : []) : value ?? ''} inputProps={{ 'aria-label': field.label, role: 'combobox' } as never}
onChange={(nextValue) => { options={field.options}
applyFieldChange(field, nextValue as BusinessFormValue); placeholder={field.placeholder ?? `请选择${field.label}`}
}} style={fieldWidthLayout.controlStyle}
/> value={field.multiple ? (Array.isArray(value) ? value : []) : value ?? ''}
onChange={(nextValue) => {
applyFieldChange(field, nextValue as BusinessFormValue);
}}
/>
)
) : null} ) : null}
{field.type === 'switch' ? ( {field.type === 'switch' ? (
readonly ? ( readonly ? (
<span className={styles.readonlyValue}>{renderSwitchText(field, value)}</span> <Text className={styles.readonlyValue}>{renderSwitchText(field, value)}</Text>
) : ( ) : (
<Switch <Switch
aria-label={field.label} aria-label={field.label}
...@@ -690,25 +807,33 @@ export function BusinessForm({ ...@@ -690,25 +807,33 @@ export function BusinessForm({
) : null} ) : null}
{field.type === 'textarea' ? ( {field.type === 'textarea' ? (
<Textarea readonly ? (
id={controlId} <Text className={styles.readonlyValue}>{resolveTextValue(value)}</Text>
aria-label={field.label} ) : (
disabled={disabled} <Textarea
maxlength={field.maxLength} id={controlId}
allowInputOverMax={field.allowInputOverMax} aria-label={field.label}
readOnly={readonly} disabled={disabled}
rows={field.rows ?? 4} maxlength={field.maxLength}
count={field.maxLength !== undefined} allowInputOverMax={false}
value={stringifyValue(value)} rows={field.rows ?? 4}
onChange={(nextValue) => { count={field.maxLength !== undefined}
applyFieldChange(field, String(nextValue ?? '')); value={stringifyValue(value)}
}} style={fieldWidthLayout.controlStyle}
/> onChange={(nextValue) => {
applyFieldChange(field, capTextValue(field, String(nextValue ?? '')));
}}
/>
)
) : null} ) : null}
{field.type === 'upload' ? ( {field.type === 'upload' ? (
readonly ? ( readonly ? (
<span className={styles.readonlyValue}>{resolveUploadPreview(uploadedValues) ?? field.placeholder ?? '未上传'}</span> <div className={styles.readonlyValue}>
{resolveUploadPreview(uploadedValues) ?? (
<Text>{field.placeholder ?? '未上传'}</Text>
)}
</div>
) : ( ) : (
<div className={styles.uploadWrap}> <div className={styles.uploadWrap}>
{(() => { {(() => {
...@@ -777,7 +902,7 @@ export function BusinessForm({ ...@@ -777,7 +902,7 @@ export function BusinessForm({
preload="metadata" preload="metadata"
/> />
) : ( ) : (
<img className={styles.uploadVideoCard} src={file.url} alt={file.name} /> <Image className={styles.uploadVideoCard} src={file.url} alt={file.name} fit="cover" />
)} )}
<div className="t-upload__card-mask"> <div className="t-upload__card-mask">
<div <div
...@@ -811,11 +936,13 @@ export function BusinessForm({ ...@@ -811,11 +936,13 @@ export function BusinessForm({
</div> </div>
{file.name ? ( {file.name ? (
file.url ? ( file.url ? (
<a className="t-upload__card-name" href={file.url} target="_blank" rel="noreferrer"> <Link className="t-upload__card-name" href={file.url} target="_blank" {...({ rel: 'noreferrer' } as any)}>
{file.name} {file.name}
</a> </Link>
) : ( ) : (
<span className="t-upload__card-name">{file.name}</span> <Text className="t-upload__card-name" ellipsis>
{file.name}
</Text>
) )
) : null} ) : null}
</li> </li>
...@@ -862,20 +989,11 @@ export function BusinessForm({ ...@@ -862,20 +989,11 @@ export function BusinessForm({
) )
) : null} ) : null}
</div> </div>
</FormItem>
{field.helperText ?? field.helpText ? (
<div className={styles.helpText}>{field.helperText ?? field.helpText}</div>
) : null}
{error ? (
<div className={styles.error} role="alert">
{error}
</div>
) : null}
</div>
</div> </div>
); );
})} })}
</div> </Form>
); );
} }
......
...@@ -64,6 +64,24 @@ ...@@ -64,6 +64,24 @@
font-size: var(--gl-font-size-sm); font-size: var(--gl-font-size-sm);
} }
.cellText {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
vertical-align: bottom;
white-space: nowrap;
}
.cellTooltipContent {
display: block;
width: 200px;
max-width: 200px;
white-space: normal;
word-break: break-word;
line-height: var(--gl-line-height-md);
}
.pagination { .pagination {
margin-left: auto; margin-left: auto;
} }
import { useMemo } from 'react';
import type { ReactElement, ReactNode } from 'react'; import type { ReactElement, ReactNode } from 'react';
import { CloseCircleIcon, SearchIcon } from 'tdesign-icons-react'; import { CloseCircleIcon, SearchIcon } from 'tdesign-icons-react';
import { Button, Empty, Pagination, Table, type EmptyProps, type PaginationProps, type PrimaryTableCol, type TableProps, type TableRowData } from 'tdesign-react'; import { Button, Empty, Pagination, Table, Tooltip, Typography, type EmptyProps, type PaginationProps, type PrimaryTableCol, type TableProps, type TableRowData } from 'tdesign-react';
import { classNames } from '../shared/classNames'; import { classNames } from '../shared/classNames';
import styles from './BusinessTable.module.css'; import styles from './BusinessTable.module.css';
export type BusinessTableColumn<T extends TableRowData> = PrimaryTableCol<T>; const { Text } = Typography;
export type BusinessTableColumn<T extends TableRowData> = PrimaryTableCol<T> & {
ellipsisTooltip?: boolean;
tooltipValue?: (row: T) => string | number | boolean | null | undefined;
};
export interface BusinessTableEmptyStateConfig { export interface BusinessTableEmptyStateConfig {
onAction?: () => void; onAction?: () => void;
...@@ -84,6 +90,55 @@ const defaultLoadingProps = { ...@@ -84,6 +90,55 @@ const defaultLoadingProps = {
text: '加载中', text: '加载中',
} satisfies TableProps<TableRowData>['loadingProps']; } satisfies TableProps<TableRowData>['loadingProps'];
function isPlainTextValue(value: unknown): value is string | number | boolean {
return ['string', 'number', 'boolean'].includes(typeof value);
}
function renderPlainTextCell<T extends TableRowData>(
row: T,
column: BusinessTableColumn<T>,
): ReactNode {
const value = column.tooltipValue
? column.tooltipValue(row)
: row[column.colKey as keyof T];
if (value === undefined || value === null) return '-';
if (!isPlainTextValue(value)) return value as ReactNode;
const text = String(value);
const normalizedText = text.trim();
if (!normalizedText || normalizedText === '-') return '-';
return (
<Tooltip
content={(
<span
className={styles.cellTooltipContent}
style={{ width: 200, maxWidth: 200, whiteSpace: 'normal' }}
>
{text}
</span>
)}
>
<span className={styles.cellText}>{text}</span>
</Tooltip>
);
}
function withPlainTextTooltipColumns<T extends TableRowData>(
columns: BusinessTableColumn<T>[],
): BusinessTableColumn<T>[] {
return columns.map((column) => {
if (!column.ellipsisTooltip || column.cell) return column;
const { ellipsisTooltip, tooltipValue, ...tableColumn } = column;
return {
...tableColumn,
cell: ({ row }) => renderPlainTextCell(row, column),
};
});
}
const errorStatePresets: Record<NonNullable<BusinessTableErrorStateConfig['kind']>, { const errorStatePresets: Record<NonNullable<BusinessTableErrorStateConfig['kind']>, {
actionText?: string; actionText?: string;
description?: string; description?: string;
...@@ -135,6 +190,7 @@ export function BusinessTable<T extends TableRowData>({ ...@@ -135,6 +190,7 @@ export function BusinessTable<T extends TableRowData>({
const isEmpty = data.length === 0; const isEmpty = data.length === 0;
const isLoading = Boolean(tableProps.loading); const isLoading = Boolean(tableProps.loading);
const displayColumns = useMemo(() => withPlainTextTooltipColumns(columns), [columns]);
const mergedLoadingProps = isLoading const mergedLoadingProps = isLoading
? { ? {
...defaultLoadingProps, ...defaultLoadingProps,
...@@ -160,7 +216,7 @@ export function BusinessTable<T extends TableRowData>({ ...@@ -160,7 +216,7 @@ export function BusinessTable<T extends TableRowData>({
<Table <Table
{...tableProps} {...tableProps}
className={classNames(styles.table, tableClassName)} className={classNames(styles.table, tableClassName)}
columns={columns} columns={displayColumns}
data={data} data={data}
empty={emptyNode} empty={emptyNode}
loadingProps={mergedLoadingProps} loadingProps={mergedLoadingProps}
...@@ -168,7 +224,7 @@ export function BusinessTable<T extends TableRowData>({ ...@@ -168,7 +224,7 @@ export function BusinessTable<T extends TableRowData>({
/> />
{pagination || totalLabel ? ( {pagination || totalLabel ? (
<div className={styles.footer}> <div className={styles.footer}>
{!pagination && totalLabel ? <div className={styles.totalLabel}>{totalLabel}</div> : <span />} {!pagination && totalLabel ? <Text className={styles.totalLabel}>{totalLabel}</Text> : <span />}
{pagination ? <Pagination className={styles.pagination} {...pagination} /> : null} {pagination ? <Pagination className={styles.pagination} {...pagination} /> : null}
</div> </div>
) : null} ) : null}
......
## Context
`BusinessTable` 已是后台表格状态和分页展示的统一入口。当前 demo 的问题在于页面同时保留了旧 `StatePlaceholder` 表格状态集合,使使用者在同一页看到两套状态语义。
用户已确认采用方案二:表格状态全部放到 `BusinessTable` demo 内展示,`StatePlaceholder` 只保留通用占位边界。
## Goals / Non-Goals
**Goals:**
- 用 `BusinessTable` 展示 demo 中所有表格状态。
- 让 demo 文案与当前 `BusinessTable` 默认规则一致。
- 防止 demo 中继续出现旧表格状态说明文案和旧操作按钮。
- 为后续 TDD 提供明确验收边界。
**Non-Goals:**
- 不改 `BusinessTable` 的状态规则。
- 不改 `StatePlaceholder` 的组件默认 API。
- 不迁移真实业务列表页。
- 不归档已有 OpenSpec change。
## Decisions
- 表格状态示例统一放在“表格与分页”区域。
- 原因:使用者查看表格规范时应看到 `BusinessTable` 的真实渲染,而不是通用占位组件的近似拼装。
- 替代方案:仅改 `StatePlaceholder` 文案。该方案仍会混淆组件边界,后续容易再次漂移。
- `StatePlaceholder` 不再展示表格语义状态集合。
- 原因:`StatePlaceholder` 是通用占位组件,不应承担后台表格状态规范入口。
- demo 测试以用户可见文案和按钮缺失为主要断言。
- 原因:当前问题是可见展示误导,测试应覆盖旧文案和旧按钮不再出现,并确认新表格状态可见。
## Risks / Trade-offs
- 多个 `BusinessTable` 示例会增加 demo 页面长度。
- 缓解:使用紧凑分组标题和稳定布局,只展示必要状态。
- 现有测试可能依赖旧 `StatePlaceholder` demo 文案。
- 缓解:先更新测试使其表达新验收,再修改实现。
## Migration Plan
1. 先补充或调整 `ComponentsDemoPage` 测试,断言 demo 通过 `BusinessTable` 展示各表格状态,并断言旧文案和旧按钮不存在。
2. 运行测试确认失败。
3. 调整 demo 实现和必要样式。
4. 运行相关测试、类型检查和 OpenSpec strict validate。
## Why
`ComponentsDemoPage` 当前仍在“导航与占位”区域直接用 `StatePlaceholder` 展示表格语义状态,导致 demo 继续出现旧文案和旧按钮。`BusinessTable` 已经统一表格空态、筛选无结果、失败态、权限态、loading 和分页规则,demo 需要展示真实业务表格输出,避免误导后续使用者。
## What Changes
- 将 demo 中表格相关状态示例统一迁移到“表格与分页”区域,并通过 `BusinessTable` 真实渲染。
- “表格与分页”区域覆盖有数据、普通空态、筛选无结果、请求失败、权限受限和加载中状态。
- 移除或改造“导航与占位”区域中的表格语义 `StatePlaceholder` 示例,不再展示旧表格状态文案和按钮。
- 删除 demo 中额外的 TDesign `Empty` 表格空态示例,避免绕过 `BusinessTable`。
## Capabilities
### New Capabilities
- `components-demo`: 覆盖组件 demo 页面如何展示业务组件状态和边界。
### Modified Capabilities
- `business-table`: 本次不修改 `BusinessTable` 组件行为,仅在 demo 中按既有规范消费该组件。
## Impact
- 影响 `src/routes/components/ComponentsDemoPage.tsx` 及其样式和测试。
- 不修改 `@gl/business-components` 的 `BusinessTable` API、默认状态规则或运行时行为。
- 不影响真实业务列表页面。
## ADDED Requirements
### Requirement: 表格状态必须通过 BusinessTable 展示
组件 demo 页面 SHALL 在“表格与分页”区域通过 `BusinessTable` 展示表格相关状态,避免使用 `StatePlaceholder`、TDesign `Empty`、TDesign `Table` 和 TDesign `Pagination` 直接拼装表格状态示例。
#### Scenario: 展示表格状态集合
- **WHEN** 用户打开组件 demo 页面并查看“表格与分页”区域
- **THEN** 系统 SHALL 展示由 `BusinessTable` 渲染的有数据表格、普通空态、筛选无结果、请求失败、权限受限和加载中示例
#### Scenario: 普通空态示例
- **WHEN** demo 展示普通空态表格示例
- **THEN** 系统 SHALL 展示标题“暂无数据”
- **AND** 系统 SHALL NOT 展示说明文案“请先创建项目”
- **AND** 系统 SHALL NOT 展示空态操作按钮
#### Scenario: 筛选无结果示例
- **WHEN** demo 展示筛选无结果表格示例
- **THEN** 系统 SHALL 展示标题“未找到匹配结果”
- **AND** 系统 SHALL NOT 展示说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“清空筛选”按钮
#### Scenario: 请求失败示例
- **WHEN** demo 展示请求失败表格示例
- **THEN** 系统 SHALL 展示标题“请求失败”
- **AND** 系统 SHALL NOT 展示说明文案“列表请求失败,当前数据状态未知”
- **AND** 系统 SHALL NOT 展示“重试”按钮
#### Scenario: 权限受限示例
- **WHEN** demo 展示权限受限表格示例
- **THEN** 系统 SHALL 展示标题“权限受限”
- **AND** 系统 SHALL 展示说明文案“当前账号暂无访问权限”
- **AND** 系统 SHALL 展示“申请权限”按钮
#### Scenario: 导航与占位不展示表格状态集合
- **WHEN** 用户查看“导航与占位”区域
- **THEN** 系统 SHALL NOT 展示“网络不可用”“请检查网络连接后重试”或“重新连接”等表格网络失败示例
- **AND** 系统 SHALL NOT 展示旧表格状态集合
## 1. OpenSpec 对齐
- [x] 1.1 创建 proposal,说明 demo 表格状态需统一通过 `BusinessTable` 展示
- [x] 1.2 创建 design,确认采用用户选择的方案二
- [x] 1.3 创建 `components-demo` spec delta,覆盖 demo 表格状态展示和旧文案收敛
- [x] 1.4 等待用户确认 OpenSpec 后进入 TDD
## 2. TDD 实现
- [x] 2.1 更新 `ComponentsDemoPage.test.tsx`,覆盖 `BusinessTable` 表格状态示例和旧文案/按钮不再出现
- [x] 2.2 运行 demo 相关测试,确认新增断言先失败
- [x] 2.3 调整 `ComponentsDemoPage.tsx`,将表格状态示例迁移为 `BusinessTable` 渲染
- [x] 2.4 调整 demo 页面样式,保证多个表格状态示例布局稳定且不与现有内容冲突
- [x] 2.5 运行 demo 相关测试,确认通过
## 3. 验证
- [x] 3.1 运行 `rtk npm test -- ComponentsDemoPage.test.tsx`
- [x] 3.2 运行 `rtk npm run typecheck`
- [x] 3.3 运行 `rtk openspec validate align-components-demo-business-table-states --strict`
- [x] 3.4 用户确认本次无需操作浏览器;已通过测试、类型检查、构建和 OpenSpec 校验覆盖交付风险
## Context
`agent-admin` 已经把列表表格统一到 `BusinessTable`,把列表搜索统一到 `SearchFilter`。表单部分仍分散在页面和弹窗里,由页面手写 `FormItem + Input/Select/Textarea/Switch/Upload`、本地校验、错误提示、字段联动和只读展示。现有表单既有简单新增编辑页,也有官网配置弹窗中的上传场景,还有管家 Agent 等只读展示场景。
本 change 只做全局业务表单组件能力,不直接迁移现有业务页面。组件必须遵循后台页面的信息密度和公司 Web 桌面端设计规范,并以 `tdesign-react` 为唯一前台控件来源;如需兼容旧写法,只能收敛到共享适配层,不能继续保留页面级原生实现路径。
## Goals / Non-Goals
**Goals:**
- 在 `@gl/business-components` 中新增配置驱动 `BusinessForm`。
- 用统一协议覆盖 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText` 和 `custom`。
- 统一 label、必填标记、错误提示、helpText、字段间距和基础输入控件宽度。
- 支持受控值、字段级变更联动、动态显示、动态禁用、动态只读和导出的校验工具。
- 让上传字段只处理选择文件、前置校验、上传中状态、预览、移除、失败提示和结果回填,不耦合具体业务接口。
- 上传能力在 UI 上拆成媒体上传和普通文件上传两条路径,二者都基于 TDesign `Upload`;媒体上传统一覆盖图片、GIF 和视频,走缩略图、图片卡片或媒体预览,普通文件上传走文件流或附件卡片。
- 通过 `custom` 字段保留实际业务开发中的扩展空间。
- 对所有内置字段优先使用 TDesign 已有属性和 API,避免在页面层保留原生控件兼容写法。
**Non-Goals:**
- 不接管页面保存按钮、提交接口、路由跳转、弹窗开关、埋点或全局消息提示。
- 不绑定固定上传 API、固定 `FormData`、固定 `usage_type` 或固定文件返回结构。
- 第一版不支持远程下拉搜索、异步联动请求、数组字段、嵌套对象字段、富文本、日期、多文件上传和复杂步骤表单。
- 不替代 `SearchFilter`。
- 不强制一次性迁移现有编辑页和官网复杂配置页。
## Decisions
### 配置驱动组件,而不是只封装单个控件
采用 `fields + values + onChange` 的受控配置协议。页面描述字段,`BusinessForm` 负责统一渲染、布局、错误提示、动态状态和基础校验。
备选方案是只导出业务版 `Input`、`Select`、`Textarea`、`Upload` 等基础控件。该方案灵活但无法减少页面重复的字段协议、校验、动态显示和上传提示逻辑,因此不采用。
### 表单不绑定具体接口
`BusinessForm` 不接管保存流程。上传字段通过配置项传入 `upload(file, values)`,组件只在文件大小和类型校验通过后调用该函数,并把返回 URL 或结构化文件值写回当前字段。上传字段默认最多上传 1 个文件;需要多张图片、GIF 或视频时,字段配置通过 `maxCount` 设置最大数量,并可通过 `multiple` 控制是否允许一次选择多个文件。单文件时字段值保持原有 URL 或结构化文件值;多文件时字段值使用数组,数组项为 URL 或结构化文件值,删除时只移除对应项。
媒体上传和普通文件上传都使用 TDesign `Upload`,但渲染契约分开:媒体态统一承载图片、GIF 和视频,使用图片卡片、缩略图或媒体预览表达;文件态使用文件流或附件表达,避免再回到原生 `input type="file"` + 自绘预览的混合实现。
媒体上传已有值时采用 TDesign 图片卡片形态:卡片内展示图片、GIF 首帧或视频封面/首帧,上传后预览卡片与无值占位卡片统一固定为 `110px × 110px`;文件名按当前实现展示在卡片下方并保持单行省略,不再额外扩大文件名区域。多文件值按数组顺序展示多个媒体卡片,达到 `maxCount` 后不再展示新增入口。hover 或聚焦时出现接近 TDesign 图片上传卡片的半透明操作蒙层,但遮罩颜色需要比默认深色蒙层更浅,避免过度压暗素材;蒙层中提供预览和删除两个操作,操作之间保留竖向分隔线。预览行为优先复用 TDesign `Upload` 的 `onPreview` 事件能力,组件只在图片、GIF、视频共用媒体值结构上做必要适配,不额外维护一套独立预览交互。无值时展示同样 `110px × 110px` 的虚线卡片入口,卡片内部显示加号和字段配置的 `placeholder`,默认文案为 `点击上传`;卡片下方的能力说明由字段配置 `helperText` 动态传入,不在组件内写死图片、视频、GIF、比例或大小限制文案。删除已有媒体后如果仍有剩余文件则保留剩余卡片,如果已清空则恢复空态入口。视频文件仍归入媒体上传,不拆成单独组件。
备选方案是让组件内置上传 API、`FormData` 和 `usage_type`。该方案会把组件绑死到具体业务场景,和用户确认的“不绑定具体接口”冲突,因此不采用。
### 字段级 onChange 只做同步局部 patch
字段变更时,组件先得到当前字段的新值,再调用字段级 `onChange(nextValue, context)`。如果返回 `Partial<BusinessFormValues>`,组件按 `{ ...values, [field.key]: nextValue, ...patch }` 合并后通过表单级 `onChange` 抛出。
备选方案是支持字段级异步请求和复杂远程联动。第一版容易扩大行为边界,也会把加载、取消、错误处理带入组件,因此不采用;复杂联动保留在页面层或 `custom` 字段。
### 动态 visible/disabled/readonly 基于当前 values 计算
字段的 `visible`、`disabled`、`readonly` 支持布尔值或函数。隐藏字段不渲染、不校验、不展示错误,但组件默认保留其值,由页面决定保存时是否提交。
这样可以覆盖“选择 A 后 B 才可选择”以及“选择 A 后显示部分 text 项”的需求,同时避免组件擅自清空业务值造成数据丢失。
`input`、`numberInput`、`select` 和 `textarea` 的禁用态与只读态优先下发给 `tdesign-react` 已有属性或等价 API,不在页面层保留原生控件写法;如某个控件缺少对应能力,只能在共享包内部做最小适配。对于 `select`,共享层只能做语义和无障碍补充,不能再用“按钮伪装选择框 + 隐藏真实控件”的方式替代 TDesign 原生视觉。
### 统一基础控件宽度
`BusinessForm` 提供 `fieldWidth`,默认建议 `360px`,最大不超过 `450px`。`input`、`numberInput`、`select` 和 `textarea` 默认使用同一个宽度,并保持 label 后控件起点一致;`textarea` 只允许高度变化。
`switch`、`upload`、`displayText` 和 `custom` 复用同一表单项外层布局。`custom` 可自行决定内部宽度,但建议遵守 `fieldWidth`。
`input` 和 `textarea` 的长度展示直接交给 `tdesign-react` 的 `showLimitNumber` / `count`,不再由 `BusinessForm` 额外渲染字数统计。
### 校验以导出工具函数为主
导出 `validateBusinessForm(fields, values)`,页面保存前可调用并把错误传回 `BusinessForm` 展示。校验过滤不可见字段,跳过 `displayText` 和只读字段,按 required、长度、数值范围、上传前置限制和自定义 validator 的顺序生成错误。
组件内部可在字段变更时清理当前字段错误,但不自动提交页面保存。
## Risks / Trade-offs
- [Risk] 第一版字段类型有限,无法覆盖复杂业务表单 → 通过 `custom` 字段复用外层布局和状态,并把复杂业务逻辑留在页面层。
- [Risk] 上传文件类型判断可能受浏览器 MIME 不完整影响 → 同时支持 `accept` 中的 MIME 和扩展名校验,并允许业务侧配置 `kinds`。
- [Risk] 隐藏字段保留值可能导致页面提交额外数据 → 在规格中明确组件不清空隐藏值,页面保存前自行决定提交 payload。
- [Risk] 统一宽度可能不适合少数自定义控件 → 基础输入控件强一致,`custom` 内部保留业务自定义空间。
## Migration Plan
1. 先完成 `BusinessForm` 组件、校验工具、类型导出和 Demo。
2. 在组件 Demo 中同步展示七类内置字段、`custom`、字段级 `onChange`、动态显示、动态禁用、动态只读、媒体上传卡片态、普通文件上传信息态、上传校验和统一宽度。
3. 运行相关测试、类型检查、构建和 OpenSpec 严格校验。
4. 开发侧完成自动化验证后,由业务验收者在浏览器中最终验收 `/components` 的 `BusinessForm` 布局、上传形态和关键交互。
5. 用户确认组件表现后,再选择低复杂度页面或弹窗逐步迁移,例如 `AgentTagEditorPage`、`ChannelCodeEditorPage`、`AgentDisplayConfigEditModal`。
## Open Questions
- 第一版上传按当前确认采用单文件上传,且媒体上传与普通文件上传分别使用独立的 TDesign 展现路径;如果后续需要多文件上传,应作为后续 change 扩展。
- Demo 建议同时覆盖上传返回字符串 URL 和结构化文件值两种情况;实施时可根据现有 Demo 复杂度决定是否拆成两个示例。
## Why
`agent-admin` 的表格和搜索区已经通过全局业务组件统一,但编辑页和弹窗表单仍由页面直接组合 TDesign 控件、字段布局、校验和联动逻辑。需要在 `@gl/business-components` 中新增配置驱动的 `BusinessForm`,统一常见后台表单能力,并为后续逐步迁移现有表单提供稳定契约。
当前实现里仍残留部分原生写法和旧兼容路径,导致表单行为、属性映射和视觉效果没有完全对齐 TDesign 体系,需要在不推倒业务协议的前提下做一次 TDesign-first 收敛。
## What Changes
- 新增 `BusinessForm` 全局业务组件,通过字段配置渲染后台表单。
- 第一版内置 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText` 字段,并直接使用 `tdesign-react` 基础控件实现可编辑态。
- 提供 `custom` 字段扩展口,用于内置字段无法覆盖的业务控件。
- 支持受控值、表单级 `onChange`、字段级 `onChange`、字段动态显示、动态禁用、动态只读和基础校验。
- `input`、`numberInput`、`select`、`textarea` 默认使用一致控件宽度,并支持通过 `fieldWidth` 统一控制。
- `input` 和 `textarea` 支持 `allowInputOverMax`,并直接复用 `tdesign-react` 的 `showLimitNumber` 长度展示能力。
- `select`、`input`、`numberInput` 和 `textarea` 优先使用 `tdesign-react` 已有的 `disabled` / `readOnly` / 等价能力来表达字段级状态,不再保留页面侧原生控件写法。
- `upload` 在第一版中分为媒体上传与普通文件上传两种展示路径,媒体上传统一支持图片、GIF 和视频,二者均使用 `tdesign-react` `Upload` 完成选择、预览和状态展示,并通过业务侧传入的 `upload(file, values)` 完成真实上传。
- 导出 `validateBusinessForm` 工具函数和必要类型。
- 在组件 Demo 中展示内置字段、动态联动、上传校验和自定义字段。
- 对已有实现中的兼容/适配路径做收敛,确保公开 API 以 TDesign 组件契约为准。
- 不绑定保存接口、上传 API、`usage_type`、路由、弹窗开关、全局消息或页面提交流程。
- 不在第一版支持远程下拉搜索、数组字段、嵌套对象字段、富文本、日期、多文件上传或复杂异步联动。
## Capabilities
### New Capabilities
- `business-form`: 约束全局业务表单组件的字段协议、渲染行为、校验规则、动态联动、上传能力、自定义扩展和导出入口。
### Modified Capabilities
- 无。
## Impact
- 全局组件包:`packages/business-components` 新增 `BusinessForm`、`validateBusinessForm`、样式和类型导出。
- 组件 Demo:`workspace/agent-admin/web/src` 的 `/components` 增加业务表单示例。
- 测试:新增业务组件单元测试与 Demo 回归测试。
- 现有页面:本 change 不要求一次性迁移现有编辑页;后续页面迁移需要单独确认或纳入后续任务。
- 后端与接口:不影响后端 API、上传接口契约、保存接口和数据结构。
## ADDED Requirements
### Requirement: BusinessForm provides a controlled configuration-driven form
系统 MUST 从 `@gl/business-components` 导出 `BusinessForm`,并通过 `fields`、`values` 和 `onChange` 渲染受控业务表单。
#### Scenario: Render configured fields
- **WHEN** 页面传入字段配置和当前表单值
- **THEN** `BusinessForm` 按字段顺序渲染表单项
- **AND** 字段变更后通过表单级 `onChange(nextValues, changedKey)` 抛出更新后的整表单值
#### Scenario: Export public types
- **WHEN** 业务页面从 `@gl/business-components` 引入业务表单能力
- **THEN** 包导出 `BusinessForm`、字段类型、值类型、错误类型和校验工具类型
### Requirement: BusinessForm supports first-version built-in field types
系统 MUST 支持 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload` 和 `displayText` 七类第一版内置字段。
#### Scenario: Render built-in editable fields
- **WHEN** 字段配置包含 `input`、`numberInput`、`select`、`switch`、`textarea` 或 `upload`
- **THEN** `BusinessForm` 使用对应 `tdesign-react` 基础控件渲染可编辑表单项
#### Scenario: Render display text field
- **WHEN** 字段配置包含 `displayText`
- **THEN** `BusinessForm` 渲染只读展示内容
- **AND** 空值默认展示 `-`
### Requirement: BusinessForm supports custom fields
系统 MUST 支持 `custom` 字段,并把当前值、整表单值、错误、禁用、只读和更新函数传给自定义渲染函数。
#### Scenario: Render custom field
- **WHEN** 字段配置包含 `custom.render`
- **THEN** `BusinessForm` 复用表单项外层布局、label、必填标记、helpText 和错误提示
- **AND** 自定义渲染函数接收到 `value`、`values`、`error`、`disabled`、`readonly`、`setValue` 和 `setValues`
#### Scenario: Custom field updates value
- **WHEN** 自定义字段调用 `setValue` 或 `setValues`
- **THEN** `BusinessForm` 通过表单级 `onChange` 抛出更新后的整表单值
### Requirement: BusinessForm applies consistent field layout and widths
系统 MUST 统一基础输入控件的表单布局和宽度。
#### Scenario: Default control width is consistent
- **WHEN** 同一表单渲染 `input`、`numberInput`、`select` 和 `textarea`
- **THEN** 这些控件使用一致的默认宽度
- **AND** 这些控件在 label 后的起点保持一致
#### Scenario: fieldWidth applies to basic input controls
- **WHEN** 页面传入 `fieldWidth`
- **THEN** `input`、`numberInput`、`select` 和 `textarea` 同步应用该宽度
#### Scenario: Textarea width remains consistent
- **WHEN** `textarea` 因 `rows` 或内容交互改变高度
- **THEN** `textarea` 宽度仍与同表单内 `input`、`numberInput` 和 `select` 保持一致
### Requirement: BusinessForm supports text input limits and TDesign counts
系统 MUST 让 `input` 和 `textarea` 支持 `maxLength`、`allowInputOverMax`,并优先复用 `tdesign-react` 已有的长度展示能力和对应 API,而不是页面侧自绘计数逻辑。
#### Scenario: Input count and over max behavior
- **WHEN** `input` 字段配置 `maxLength` 且需要展示长度
- **THEN** 输入框展示 TDesign 提供的字数统计能力
- **AND** 当 `allowInputOverMax` 为真时允许继续输入超过最大长度
- **AND** 校验仍按 `maxLength` 生成错误
#### Scenario: Textarea count and over max behavior
- **WHEN** `textarea` 字段配置 `maxLength` 且需要展示长度
- **THEN** 文本域展示 TDesign 提供的字数统计能力
- **AND** 当 `allowInputOverMax` 为真时允许继续输入超过最大长度
- **AND** 校验仍按 `maxLength` 生成错误
### Requirement: BusinessForm supports number input validation
系统 MUST 让 `numberInput` 支持数值输入和 `min`、`max`、`precision` 校验。
#### Scenario: Validate number range
- **WHEN** `numberInput` 字段配置 `min` 或 `max`
- **THEN** 低于最小值或高于最大值的值会产生字段错误
#### Scenario: Validate number precision
- **WHEN** `numberInput` 字段配置 `precision`
- **THEN** 超出允许小数位数的值会产生字段错误
### Requirement: BusinessForm uses TDesign-first disabled and readonly mapping for editable controls
系统 MUST 让 `input`、`numberInput`、`select` 和 `textarea` 优先使用 `tdesign-react` 已有的 `disabled` / `readOnly` 或等价 API 表达字段级禁用和只读,不再保留页面级原生控件兼容写法。
#### Scenario: Disabled select option cannot be selected
- **WHEN** `select.options` 中某个选项配置 `disabled: true`
- **THEN** 用户不能选择该选项
#### Scenario: Disabled editable field cannot be operated
- **WHEN** `input`、`numberInput`、`select` 或 `textarea` 字段的 `disabled` 计算结果为真
- **THEN** 下拉控件不可操作并呈现禁用状态
#### Scenario: Readonly editable field stays in TDesign render path
- **WHEN** `input`、`numberInput`、`select` 或 `textarea` 字段的 `readOnly` 计算结果为真
- **THEN** `BusinessForm` 直接使用 TDesign 对应属性或等价能力
- **AND** 不再切换为页面级原生控件或自绘兼容分支
### Requirement: BusinessForm supports switch value mapping
系统 MUST 让 `switch` 默认使用布尔值,并支持通过 `checkedValue` 和 `uncheckedValue` 映射业务值。
#### Scenario: Toggle boolean switch
- **WHEN** `switch` 字段未配置业务值映射
- **THEN** 开关切换产生 `true` 或 `false`
#### Scenario: Toggle mapped switch
- **WHEN** `switch` 字段配置 `checkedValue` 和 `uncheckedValue`
- **THEN** 开关切换产生对应业务值
#### Scenario: Readonly switch displays state
- **WHEN** `switch` 字段的 `readonly` 计算结果为真
- **THEN** 表单项展示当前状态文案
- **AND** 不展示可切换开关
### Requirement: BusinessForm supports dynamic field states
系统 MUST 让字段的 `visible`、`disabled` 和 `readonly` 支持布尔值或基于当前 `values` 的函数。
#### Scenario: Hide dynamic field
- **WHEN** 字段 `visible` 为 false 或函数返回 false
- **THEN** `BusinessForm` 不渲染该字段
- **AND** 该字段不参与校验
- **AND** 该字段错误不展示
#### Scenario: Enable field based on another field
- **WHEN** 字段 B 的 `disabled(values)` 依赖字段 A 的当前值
- **THEN** 字段 A 变更后字段 B 的禁用状态按最新 `values` 重新计算
#### Scenario: Show display text based on another field
- **WHEN** `displayText` 字段的 `visible(values)` 依赖字段 A 的当前值
- **THEN** 字段 A 变更后该展示字段按最新 `values` 显示或隐藏
### Requirement: BusinessForm supports field-level onChange patching
系统 MUST 支持字段级 `onChange(nextValue, context)`,用于同步联动更新其他字段。
#### Scenario: Field onChange patches related values
- **WHEN** 字段级 `onChange` 返回 `Partial<BusinessFormValues>`
- **THEN** `BusinessForm` 按 `{ ...values, [field.key]: nextValue, ...patch }` 合并整表单值
- **AND** 通过表单级 `onChange` 抛出合并后的值
#### Scenario: Field onChange only updates current field
- **WHEN** 字段级 `onChange` 不返回 patch
- **THEN** `BusinessForm` 只更新当前字段值
### Requirement: BusinessForm validates configured fields
系统 MUST 提供 `validateBusinessForm(fields, values)`,并按可见性、只读状态和字段规则生成校验结果。
#### Scenario: Validate required field
- **WHEN** 可编辑且可见字段配置 `required: true` 且值为空
- **THEN** `validateBusinessForm` 返回该字段错误
#### Scenario: Skip invisible and readonly fields
- **WHEN** 字段不可见或只读
- **THEN** `validateBusinessForm` 不校验该字段
#### Scenario: Skip display text field
- **WHEN** 字段类型为 `displayText`
- **THEN** `validateBusinessForm` 不对该字段执行必填或自定义校验
#### Scenario: Run custom validator
- **WHEN** 可编辑且可见字段配置 `validator`
- **THEN** `validateBusinessForm` 执行该 validator
- **AND** 使用 validator 返回的错误文案作为字段错误
### Requirement: BusinessForm supports media and regular file upload
系统 MUST 让 `upload` 字段在媒体上传和普通文件上传场景下使用不同展示路径,并且两条路径都基于 `tdesign-react` `Upload` 实现上传,不再使用页面级原生文件输入控件。媒体上传 MUST 统一支持图片、GIF 和视频。上传字段默认最多上传 1 个文件,并 MUST 支持通过字段配置调整最大数量和是否允许多选。
#### Scenario: Reject invalid media upload type
- **WHEN** 媒体上传场景下用户选择的图片、GIF 或视频不满足 `kinds` 或 `accept`
- **THEN** `BusinessForm` 展示类型错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Reject invalid regular file upload type
- **WHEN** 普通文件上传场景下用户选择的文件不满足 `kinds` 或 `accept`
- **THEN** `BusinessForm` 展示类型错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Reject oversized upload
- **WHEN** 用户选择的文件大小超过 `maxSize`
- **THEN** `BusinessForm` 展示大小错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Upload valid media file
- **WHEN** 媒体上传场景下用户选择的图片、GIF 或视频满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把 URL 或结构化文件值写入当前字段
#### Scenario: Upload multiple valid media files
- **WHEN** 媒体上传字段配置 `maxCount` 大于 `1` 或配置 `multiple: true`
- **AND** 用户选择的多个图片、GIF 或视频均满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 按文件分别调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把多个 URL 或结构化文件值以数组形式写入当前字段
- **AND** 当已上传数量达到 `maxCount` 时,TDesign `Upload` 不再继续展示新增入口或继续接收超过上限的文件
#### Scenario: Upload valid regular file
- **WHEN** 普通文件上传场景下用户选择的文件满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把 URL 或结构化文件值写入当前字段
#### Scenario: Display uploaded media preview
- **WHEN** 媒体上传字段已有图片、GIF 或视频值
- **THEN** `BusinessForm` 使用媒体类 TDesign 图片卡片态展示缩略图、GIF 首帧或视频封面/首帧
- **AND** 已有值预览卡片尺寸固定为 `110px × 110px`
- **AND** 如果当前字段值为数组,则按数组顺序展示多个媒体卡片
- **AND** hover 或聚焦卡片时展示接近 TDesign 图片上传卡片的半透明操作蒙层,但蒙层颜色比默认深色遮罩更浅
- **AND** 蒙层中提供预览和删除操作
- **AND** 预览与删除操作之间展示竖向分隔线
- **AND** 预览操作优先复用 TDesign `Upload` 的 `onPreview` 能力,不在组件内重复实现独立预览入口
- **AND** 文件名按当前实现展示在卡片下方,并保持单行省略,不允许换行撑高布局
#### Scenario: Display media upload placeholder and helper text
- **WHEN** 媒体上传字段没有当前值
- **THEN** `BusinessForm` 展示 `110px × 110px` 的固定尺寸虚线卡片上传入口
- **AND** 卡片内部展示加号和字段配置 `placeholder`,未配置时默认展示 `点击上传`
- **AND** 如果字段配置 `helperText`,则在上传卡片下方展示该说明文案
#### Scenario: Restore media upload placeholder after deletion
- **WHEN** 用户删除媒体上传字段的已有图片、GIF 或视频
- **THEN** `BusinessForm` 从当前字段值中移除对应文件
- **AND** 当删除后字段值为空时,上传区域恢复到无值时的卡片占位态
- **AND** 当删除后字段值未空且未达到 `maxCount` 时,上传区域继续展示剩余卡片并允许继续新增
- **AND** 上传卡片下方继续展示字段配置传入的 `helperText`
#### Scenario: Display uploaded regular file preview
- **WHEN** 普通文件上传字段已有普通文件值
- **THEN** `BusinessForm` 使用文件类 TDesign 上传态展示文件信息
#### Scenario: Upload failure preserves previous value
- **WHEN** 业务传入的 `upload(file, values)` 失败
- **THEN** `BusinessForm` 展示上传失败错误
- **AND** 不改写当前字段已有值
### Requirement: BusinessForm demo covers first-version capabilities
系统 MUST 在组件 Demo 中展示 `BusinessForm` 第一版核心能力。
#### Scenario: Open components demo
- **WHEN** 用户访问 `/components`
- **THEN** 页面展示 `BusinessForm` 示例
- **AND** 示例覆盖内置字段、自定义字段、字段级联动、动态显示、动态禁用、动态只读、单选选择器、多选选择器、媒体上传、普通文件上传、上传校验和仅展示文字
#### Scenario: Demo reflects upload display paths
- **WHEN** 用户访问 `/components` 中的 `BusinessForm` 示例
- **THEN** 示例中的媒体上传字段展示图片、GIF 和视频共用的卡片式上传入口与已有值预览态
- **AND** 示例中的普通文件上传字段展示文件类上传入口与已有值信息态
- **AND** 示例不得继续展示基于页面级原生文件输入控件的旧上传交互
## 1. 基线与结构
- [x] 1.1 确认 `packages/business-components` 当前导出结构、测试框架和样式组织方式
- [x] 1.2 建立 `BusinessForm` 组件、类型、校验工具和样式文件的目录结构
- [x] 1.3 确认组件 Demo 中新增业务表单示例的入口位置
## 2. 测试优先
- [x] 2.1 先为 `BusinessForm` 渲染 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText`、`custom` 编写失败测试
- [x] 2.2 先为受控值更新、表单级 `onChange` 和字段级 `onChange` patch 编写失败测试
- [x] 2.3 先为 `visible`、`disabled`、`readonly` 动态计算编写失败测试
- [x] 2.4 先为 `validateBusinessForm` 的 required、maxLength、数值范围、precision、readonly、不可见字段、自定义 validator 编写失败测试
- [x] 2.5 先为 `input`、`textarea` 的 `allowInputOverMax` 和 TDesign 原生长度展示编写失败测试
- [x] 2.6 先为 `input`、`numberInput`、`select`、`textarea` 默认同宽和 `fieldWidth` 同步应用编写失败测试
- [x] 2.7 先为 `select` 选项级禁用、字段禁用和只读展示编写失败测试
- [x] 2.8 先为 `switch` 默认布尔值、业务值映射和只读展示编写失败测试
- [x] 2.9 先为 `upload` 的 `kinds`、`accept`、`maxSize`、上传成功、上传失败、媒体上传、普通文件上传、图片/GIF/视频/普通文件展示编写失败测试
- [x] 2.10 先为 `custom` 字段上下文、`setValue`、`setValues`、校验和动态状态编写失败测试
## 3. 组件实现
- [x] 3.1 实现 `BusinessForm` 受控渲染、表单项布局、label、必填标记、helpText 和错误提示
- [x] 3.2 实现 `input`、`numberInput`、`select`、`switch`、`textarea`、`displayText` 字段渲染
- [x] 3.3 实现 `custom` 字段上下文和更新函数
- [x] 3.4 实现字段级 `onChange` patch 合并规则
- [x] 3.5 实现 `visible`、`disabled`、`readonly` 动态状态计算,并将 `input`、`numberInput`、`select`、`textarea` 的禁用/只读直接下发给 TDesign 原生属性
- [x] 3.6 实现 `fieldWidth` 和基础输入控件同宽样式
- [x] 3.7 将内置字段的可编辑态、只读态和上传触发控件统一迁移为 `tdesign-react` 组件,编辑态字段直接使用 `disabled` / `readOnly` 原生属性
## 4. 校验与上传
- [x] 4.1 实现 `validateBusinessForm(fields, values)` 工具函数
- [x] 4.2 实现 required、maxLength、number min/max/precision 和自定义 validator 校验
- [x] 4.3 实现 `upload` 字段文件选择、类型校验、大小校验、上传中状态、错误提示、移除和结果回填
- [x] 4.4 将媒体上传和普通文件上传拆分为两条基于 TDesign `Upload` 的展示分支,分别覆盖图片/GIF/视频卡片预览和文件类信息展示
- [x] 4.5 确认上传逻辑不构造固定 `FormData`、不写入固定 `usage_type`、不调用固定 API
## 5. 导出与 Demo
- [x] 5.1 从 `packages/business-components/src/index.ts` 导出 `BusinessForm`、`validateBusinessForm` 和相关类型
- [x] 5.2 在 `/components` Demo 中新增 `BusinessForm` 示例
- [x] 5.3 Demo 覆盖内置字段、自定义字段、字段级 `onChange`、动态显示、动态禁用、动态只读、上传校验和仅展示文字
## 6. 验证与收尾
- [x] 6.1 运行 `BusinessForm` 相关测试
- [x] 6.2 运行组件 Demo 相关测试
- [x] 6.3 运行 `npm run typecheck`
- [x] 6.4 运行 `npm run build`
- [x] 6.5 运行 `openspec validate "business-form-component" --strict`
- [ ] 6.6 由用户在浏览器中验收 `/components` 的 `BusinessForm` 布局、统一宽度、动态联动、上传形态和关键交互
## 7. TDesign 迁移收敛
- [ ] 7.1 盘点 `BusinessForm` 和共享适配层中仍保留的原生写法、legacy props 和等价 TDesign API 缺口
- [ ] 7.2 将 `input`、`numberInput`、`select`、`textarea`、`switch` 和 `upload` 的可视化与交互路径统一收敛到 TDesign 组件契约,其中 `select` 需要直接呈现 TDesign `Select` 外观,`upload` 需要进一步拆成媒体上传与普通文件上传两条 TDesign `Upload` 路径
- [ ] 7.3 将媒体上传已有值展示调整为 TDesign 图片卡片形态,覆盖缩略图、hover 蒙层、预览操作、删除操作和文件名下置
- [ ] 7.4 同步调整 `/components` Demo,使媒体上传展示图片/GIF/视频共用卡片态,普通文件上传展示文件信息态
- [ ] 7.5 清理不再需要的兼容分支、隐藏 DOM shim 和页面级原生用法
- [ ] 7.6 补充或更新测试,覆盖禁用、只读、字数统计、选择器、上传预览、Demo 展示和动态联动在 TDesign-first 路径下的行为
- [ ] 7.7 重新运行 `npm run typecheck`、相关测试、`npm run build` 和 `openspec validate "business-form-component" --strict`
- [x] 7.8 将媒体上传无值态调整为虚线卡片入口,卡片内展示 `placeholder` 或默认 `点击上传`,卡片下方展示字段配置动态传入的 `helperText`
- [x] 7.9 补充删除媒体后恢复占位态的测试,并同步更新 Demo 中展示素材字段的动态说明文案
- [x] 7.10 将媒体上传已有值 hover 蒙层调整为接近 TDesign 图片上传卡片的操作样式,使用更浅的中性遮罩并补充预览/删除操作分隔线
- [x] 7.11 将媒体上传无值占位卡片和已有值预览卡片统一调整为 `110px × 110px`
- [x] 7.12 将媒体上传文件名调整为单行省略,并把预览动作收敛到 TDesign `Upload` 的 `onPreview` 路径
- [x] 7.13 为上传字段增加 `maxCount` 和 `multiple` 配置,默认单文件,媒体上传支持配置多张图片/GIF/视频并以数组值写回
- [x] 7.14 在 `BusinessForm` Demo 中补充多选 Select 字段,展示 `select.multiple` 配置与数组值写回
## Context
`BusinessTable` 负责承接业务表格、空态和可选分页。TDesign `Pagination` 默认会展示 `totalContent`,当前 `BusinessTable` 又在 footer 左侧根据 `totalLabel` 渲染一份自定义总数,页面同时传入两者时会出现两份总数。
用户已明确希望“使用 Pagination 默认的 totalContent 即可”,因此本次不采用在 `BusinessTable` 内关闭 Pagination `totalContent` 的方案,而是将分页场景的总数展示收敛回 TDesign 默认行为。
用户进一步确认筛选无结果态不需要说明文案与状态区操作按钮;列表失败态需要显示失败文案“请求失败”,但不需要下方蓝色操作按钮。状态块仍用于表达当前结果,筛选恢复由搜索区或筛选区已有操作承担,列表重新加载由页面其他已有入口承担。
## Goals / Non-Goals
**Goals:**
- 分页场景下只展示 TDesign `Pagination` 默认总数。
- 保留无分页场景下 `totalLabel` 作为底部文案的能力。
- 清理 Demo 和后台列表页中分页场景传入的冗余 `totalLabel`。
- 用回归测试覆盖“分页 + totalLabel 不重复展示”。
- 筛选无结果态只保留图标和标题,不展示“请调整搜索或筛选条件”与“清空筛选”按钮。
- 列表失败态展示失败图标和标题“请求失败”,不展示“重试”按钮。
**Non-Goals:**
- 不改变普通空态和权限受限态的视觉规则。
- 不定制 TDesign Pagination 的默认总数文案。
- 不调整分页切换、页容量切换、查询参数同步等业务行为。
- 不移除搜索区或筛选区已有的重置能力。
## Decisions
1. 当 `BusinessTable` 收到 `pagination` 时,footer 只渲染 `Pagination`,由 TDesign 默认 `totalContent` 展示总数。
2. 当 `pagination={false}` 或未传入分页配置,但传入 `totalLabel` 时,`BusinessTable` 仍可在 footer 左侧展示 `totalLabel`。
3. 已迁移列表页和 Demo 页在分页场景不再传入 `totalLabel`,减少调用方重复表达同一份总数。
4. 测试优先覆盖业务组件层行为,再用类型检查确认页面调用方式一致。
5. 筛选无结果态和列表失败态统一采用精简状态块:筛选无结果保留既有图标和标题,不渲染说明文案和状态区操作按钮;列表失败态保留失败图标和标题“请求失败”,不渲染状态区操作按钮。页面即使仍传入恢复回调,状态块也不提供“清空筛选”或“重试”入口。
## Risks / Trade-offs
- Pagination 默认总数文案由 TDesign 控制,页面不再通过 `totalLabel` 自定义分页总数文案。
- 无分页统计文案仍依赖 `totalLabel`,因此组件实现需要保留这个 API。
- 筛选无结果态和列表失败态不再在状态块中提供恢复操作,用户需要使用页面已有搜索区、筛选区或其他重新加载入口。
## Why
`BusinessTable` 当前在分页场景下同时渲染自定义 `totalLabel` 和 TDesign `Pagination` 默认的 `totalContent`,会导致页面底部出现两份“共 N 条数据”。用户已确认状态展示方向无问题,但总数展示应使用 Pagination 默认能力,避免业务组件额外重复渲染。
## What Changes
- 调整 `BusinessTable` 的分页总数规则:传入 `pagination` 时,总数展示由 TDesign `Pagination` 默认 `totalContent` 负责。
- `totalLabel` 仅用于无分页但仍需要在表格底部展示总数或补充统计文案的场景。
- 更新相关测试,覆盖传入分页和 `totalLabel` 时页面只出现一份总数。
- 清理 Demo 和后台列表页中分页场景的多余 `totalLabel` 使用。
- 精简筛选无结果态:保留图标和标题,隐藏说明文案与“清空筛选”按钮。
- 精简列表失败态:保留失败图标和标题“请求失败”,隐藏“重试”按钮。
## Non-Goals
- 不改变普通空态和权限受限态视觉。
- 不改造 TDesign `Pagination` 的默认文案格式。
- 不新增分页组件包装层或新的分页 API。
- 不移除搜索区或筛选区已有的重置能力。
- 不移除页面通过其他入口主动重新加载列表的能力。
- 不归档本 change,直到用户确认实现和验证结果。
## Capabilities
### Modified Capabilities
- `business-table`:统一分页场景下的总数展示来源,避免重复总数;精简筛选无结果态和列表失败态的状态块内容,并将列表失败态标题统一为“请求失败”。
## Impact
- 影响 `packages/business-components/src/business-table/BusinessTable.tsx` 的 footer 渲染逻辑。
- 影响 `packages/business-components/src/business-table/BusinessTable.tsx` 的状态块渲染规则。
- 影响已迁移到 `BusinessTable` 且同时传入 `pagination` 与 `totalLabel` 的列表页和 Demo 页。
- 影响 `workspace/agent-admin/web/src/business-components/business-table.test.tsx` 的分页总数和状态块断言。
## MODIFIED Requirements
### Requirement: 可选分页和总数展示
系统 SHALL 支持在业务表格底部渲染可选分页或无分页总数信息,并在分页场景使用 TDesign `Pagination` 默认总数展示。
#### Scenario: 渲染分页
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、默认总数文案和分页回调
#### Scenario: 分页场景不渲染额外总数文案
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL NOT 在 `Pagination` 外额外渲染 `totalLabel`
- **AND** 页面 SHALL 使用 TDesign `Pagination` 默认的 `totalContent` 展示总数
#### Scenario: 禁用分页
- **WHEN** 页面传入 `pagination={false}`
- **THEN** 系统 SHALL NOT 渲染分页组件
#### Scenario: 无分页时展示总数文案
- **WHEN** 页面未传入分页配置或传入 `pagination={false}`,且传入 `totalLabel`
- **THEN** 系统 SHALL 在表格底部展示该总数文案
### Requirement: 精简筛选空态
系统 SHALL 在筛选无结果时使用精简状态块,仅展示图标和标题。
#### Scenario: 筛选无结果
- **WHEN** 表格无错误、非加载、无数据且存在筛选条件
- **THEN** 系统 SHALL 展示筛选无结果图标和标题“未找到匹配结果”
- **AND** 系统 SHALL NOT 展示说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“清空筛选”按钮
### Requirement: 精简列表失败态
系统 SHALL 在列表加载失败时使用精简状态块,展示失败图标和标题“请求失败”。
#### Scenario: 列表加载失败
- **WHEN** 表格收到加载失败态配置
- **THEN** 系统 SHALL 展示失败态图标和标题“请求失败”
- **AND** 系统 SHALL NOT 展示“重试”按钮
- **AND** 系统 SHALL NOT 渲染无文案的状态区按钮
### Requirement: 表格刷新加载态
系统 SHALL 在 `BusinessTable` 收到加载态时使用表格区域局部 loading,并采用业务组件默认的轻量加载样式。
#### Scenario: 表格刷新中
- **WHEN** 页面向 `BusinessTable` 传入 `loading={true}`
- **THEN** 系统 SHALL 保留表格结构并展示表格区域 loading
- **AND** 系统 SHALL 使用小尺寸加载指示和当前主题主色提示文案
- **AND** 系统 SHALL 使用当前主题主色渲染加载指示器
- **AND** 系统 SHALL 允许调用方通过 TDesign `loadingProps` 覆盖默认加载配置
## 1. OpenSpec 对齐
- [x] 1.1 创建 `proposal.md`,明确分页总数重复问题和用户确认方向
- [x] 1.2 创建 `design.md`,明确使用 TDesign Pagination 默认 `totalContent`
- [x] 1.3 创建 `business-table` spec delta,覆盖分页和无分页总数展示规则
- [x] 1.4 补充筛选无结果态和列表失败态的精简规则
- [x] 1.6 对齐列表失败态标题为“请求失败”且不展示状态区按钮
- [x] 1.7 补充表格刷新加载态使用轻量局部 loading 的规则
- [x] 1.8 对齐表格 loading 使用当前主题主色的规则
- [x] 1.5 等待用户确认 OpenSpec 文档后再进入实现
## 2. TDD 与实现
- [x] 2.1 更新 `business-table.test.tsx`,覆盖分页场景只展示一份默认总数
- [x] 2.2 调整 `BusinessTable` footer 渲染逻辑,使分页场景不额外渲染 `totalLabel`
- [x] 2.3 清理分页页面和 Demo 中冗余的 `totalLabel` 传参
- [x] 2.4 更新 `business-table.test.tsx`,覆盖筛选无结果态和列表失败态不展示说明文案与状态区按钮
- [x] 2.5 调整 `BusinessTable` 状态块渲染逻辑,仅为筛选无结果态和列表失败态保留图标与标题
- [x] 2.6 调整 `BusinessTable` 默认列表失败态标题为“请求失败”,并同步消费方测试
- [x] 2.7 补充失败态不渲染空文案按钮的测试,并修正 action 生成条件
- [x] 2.8 调整 `BusinessTable` 默认 loadingProps 和样式,使表格 loading 更轻量
- [x] 2.9 将 `BusinessTable` loading 指示器和提示文案颜色切换为当前主题主色
## 3. 验证
- [x] 3.1 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.2 运行 `rtk npm run typecheck`
- [x] 3.3 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
- [x] 3.4 运行 `rtk npm test -- business-table.test.tsx AgentListPage.test.tsx AgentTagManagement.test.tsx ChannelCodeListPage.test.tsx SkillListPage.test.tsx OfficialSiteJobTabListPage.test.tsx OfficialSiteAgentDisplayConfigList.test.tsx OfficialSiteAgentDisplayConfigRoutes.test.tsx`
- [x] 3.5 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.6 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.7 运行 `rtk npm run typecheck`
- [x] 3.8 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
- [x] 3.9 运行 `rtk npm test -- business-table.test.tsx`
- [ ] 3.10 运行 `rtk npm run typecheck`(当前失败:`packages/ui/src/components/business-form.test.tsx` 引用尚未导出的 `BusinessForm`/`validateBusinessForm` 等,与本次 loading 颜色调整无关)
- [x] 3.11 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
## Context
`workspace/agent-admin/web/src` 当前有 18 个不同运行时代码文件通过 19 条 import 声明依赖 `workspace/agent-admin/web/packages/ui/src`。本地 UI 包同时包含基础控件和业务组合组件,其中部分基础控件内部仍使用原生 DOM,部分已经包装 TDesign,页面也已开始直接使用 `tdesign-react`。
根目录 `packages/business-components` 已存在 `BusinessLoginPage` 和 `BusinessAdminShell`,并通过 `@gl/business-components` 提供跨项目复用入口。本轮需要延续这一边界,把适合跨页面复用的后台业务组合组件提升到全局包,同时让页面直接消费 TDesign 基础组件。
详细盘点与方案比较见 `docs/superpowers/specs/2026-05-31-migrate-admin-ui-to-global-tdesign-design.md`。
## Goals / Non-Goals
**Goals:**
- 让 `workspace/agent-admin/web/src` 对本地 `packages/ui/src` 达到零运行时依赖。
- 基础 UI 控件直接从 `tdesign-react` 引入,图标直接从 `tdesign-icons-react` 引入。
- 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 迁入根目录 `packages/business-components`。
- 保持页面现有业务行为、数据流、接口契约和路由不变。
- 调整组件 Demo,使其只展示 TDesign 基础能力和全局业务组件。
**Non-Goals:**
- 不删除 `workspace/agent-admin/web/packages/ui` 目录。
- 不在本轮清理旧组件源码、旧组件测试和未被 `web/src` 使用的内部组件。
- 不处理 `workspace/agent-admin/single-page` 中的原生控件。
- 不在本轮引入配置化表单渲染器,也不把编辑页表单重写为配置协议。
- 不进行页面视觉改版、后端 API 修改或业务流程重构。
## Decisions
### Decision 1:基础控件由页面直接使用 TDesign
页面、布局和 Hook 中的基础控件改为直接从 `tdesign-react` 引入;图标改为直接从 `tdesign-icons-react` 引入。迁移时按 TDesign API 调整属性名、事件签名和测试选择器。
采用这一方案是因为本轮目标是消除 `web/src` 对本地包装层的运行时依赖。备选方案是在 `packages/ui` 内部替换实现,但它仍会保留本地依赖边界,无法满足目标。
### Decision 2:业务组合组件提升到全局包
`SearchFilter`、`StatePlaceholder`、`MediaWall` 迁入根目录 `packages/business-components`,通过 `@gl/business-components` 统一导出。它们内部使用 TDesign 基础组件,不再依赖 `workspace/agent-admin/web/packages/ui`。
采用这一方案是因为三者承载可复用业务语义:搜索条件编排、页面状态占位、媒体上传预览。备选方案是在页面中直接展开这些能力,但会造成重复实现和行为漂移。
### Decision 3:保持业务行为不变
本轮只调整 UI 依赖路径。列表查询、重置、分页、弹窗、抽屉、加载态、空态、错误态、媒体上传、表单校验和提交反馈继续遵循现有行为。
页面测试需要围绕行为和 TDesign 可观察结构更新,避免继续依赖旧本地组件实现细节。
消息反馈迁移到 TDesign `MessagePlugin` 后,React 19 运行时必须让 TDesign 插件渲染路径使用 `react-dom/client` 的 `createRoot`。适配器需要与实际被打包消费的 TDesign ESM 入口保持一致,避免只补丁 `lib` 入口而让页面运行时仍落回 React 19 已移除的 `ReactDOM.render`。
### Decision 4:旧本地 UI 包保留但退出运行时链路
`workspace/agent-admin/web/packages/ui` 目录保留,作为后续独立清理工作的输入。本轮验收只扫描 `workspace/agent-admin/web/src` 的运行时 import,不删除旧目录,也不要求立即处理其内部源码。
### Decision 5:按风险分批迁移
实施顺序为:
1. 迁移全局业务组合组件。
2. 迁移布局、消息 Hook、抽屉和列表页。
3. 迁移编辑页表单。
4. 迁移组件 Demo。
5. 运行零依赖扫描、测试、类型检查、构建和浏览器验证。
每一批均先调整或补充测试,再修改实现。
### Decision 6:本轮不引入配置化表单渲染器
编辑页在本轮直接使用 TDesign `Form`、`FormItem` 和基础输入控件,保留页面现有字段状态、校验、联动、上传和提交逻辑。不新增 `BusinessForm` 或 `FormRenderer`,也不把复杂页面改写为配置协议。
采用这一方案是因为本轮目标是统一 UI 依赖边界,而不是重构表单架构。配置化渲染适合重复度高的简单表单,但对上传、动态数组、多层级联动、复杂业务选择器和步骤表单容易产生大量特殊参数,增加理解和维护成本。
迁移完成后可另开独立变更,选择两个结构重复的简单编辑页验证轻量 `BusinessForm`。后续试点必须提供 `children` 或 `render` 逃生口,允许页面混用配置字段与手写 TDesign `FormItem`;若协议开始依赖大量联动和布局特例,则回到页面级组合。
## Risks / Trade-offs
- [Risk] TDesign 的属性名和事件签名与旧包装组件不同,可能引入表单值更新回归。
→ Mitigation:按页面分批 TDD,重点覆盖输入、选择、开关、分页和弹窗确认行为。
- [Risk] `SearchFilter` 提升到全局包后可能意外改变查询草稿与提交值的边界。
→ Mitigation:保留既有公开属性和回调语义,并覆盖查询、重置和状态筛选测试。
- [Risk] `MediaWall` 涉及上传、预览和删除,迁移影响面高于普通基础控件。
→ Mitigation:保持现有上传契约,增加上传成功、失败、删除和回填测试。
- [Risk] Demo 一次性迁移的组件种类较多,容易遗漏旧 import。
→ Mitigation:单独建立 Demo 迁移任务,并以静态扫描作为最终门禁。
- [Risk] React 19 下 TDesign 插件式反馈组件若未正确加载同入口的 React 19 适配器,会在触发消息时调用已移除的 `ReactDOM.render` 并抛出运行时错误。
→ Mitigation:为 `useMessage` 补充运行时导入约束和回归测试,确保消息插件使用与 `tdesign-react` 主入口一致的适配器。
- [Trade-off] 旧 `packages/ui` 暂时保留,会产生一段时间的无运行时引用遗留代码。
→ Mitigation:本轮明确记录保留策略,后续以独立变更完成删除和依赖清理。
- [Trade-off] 本轮继续保留页面级表单结构,短期内不会减少重复字段代码。
→ Mitigation:先完成依赖迁移,再以独立试点衡量轻量表单组件的真实复用收益。
## Migration Plan
1. 在 `packages/business-components` 增加全局业务组合组件及导出。
2. 分批替换 `workspace/agent-admin/web/src` 中的本地 UI import。
3. 更新相关测试和组件 Demo。
4. 扫描并确认 `workspace/agent-admin/web/src` 不再存在指向 `packages/ui` 的运行时 import。
5. 运行相关测试、`npm run typecheck`、`npm run build`、OpenSpec 严格校验,并完成浏览器验证。
回滚时可以按批次恢复页面 import 和全局组件导出。本轮不删除旧本地 UI 包,因此无需恢复旧源码。
## Open Questions
- 无。已确认本轮只处理 `workspace/agent-admin/web/src`,暂不删除 `packages/ui`,不处理 `single-page`,也不引入配置化表单渲染器。
## Why
`workspace/agent-admin/web/src` 仍通过本地 `packages/ui/src` 使用基础控件和业务组合组件,导致后台页面同时存在本地包装层、TDesign 直连和全局业务组件三种依赖路径。需要统一运行时依赖边界,让后台页面直接使用 TDesign 基础组件,并把可复用业务组合能力提升到全局组件包。
## What Changes
- 将 `workspace/agent-admin/web/src` 中所有指向本地 `packages/ui/src` 的运行时依赖迁出。
- 基础控件、反馈组件、展示组件和图标分别直接使用 `tdesign-react` 与 `tdesign-icons-react`。
- 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 提升到根目录 `@gl/business-components`,供后台页面统一复用。
- 调整组件 Demo,使其展示 TDesign 基础组件与全局业务组件,不再作为旧本地 UI 包的展示入口。
- 保留 `workspace/agent-admin/web/packages/ui` 目录,本轮不删除旧源码,也不要求立即清理旧组件测试。
- 编辑页直接使用 TDesign 表单能力,本轮不引入配置化表单渲染器,也不把复杂表单重写为配置协议。
- 保持现有页面业务行为、接口契约和路由结构不变。
## Capabilities
### New Capabilities
- `admin-ui-runtime-dependency`: 约束后台运行时代码的 UI 依赖边界、全局业务组合组件归属和旧本地 UI 包保留策略。
### Modified Capabilities
- 无。
## Impact
- 受影响代码:`workspace/agent-admin/web/src` 下页面、布局、Hook、组件 Demo 及相关测试。
- 全局组件包:根目录 `packages/business-components` 新增或迁入 `SearchFilter`、`StatePlaceholder`、`MediaWall`。
- 前端依赖:继续使用既有 `tdesign-react`,并按需直接使用 `tdesign-icons-react`。
- 表单架构:本轮保持页面级组合;轻量 `BusinessForm` 或 `FormRenderer` 仅作为迁移完成后的独立试点方向。
- 不影响后端 API、数据结构、路由路径和 `workspace/agent-admin/single-page`。
## ADDED Requirements
### Requirement: 后台运行时代码不再依赖本地 UI 包
系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具。
#### Scenario: 扫描后台运行时 import
- **WHEN** 对 `workspace/agent-admin/web/src` 执行本地 UI 包依赖扫描
- **THEN** 扫描结果不包含指向 `packages/ui` 或 `packages/ui/src` 的运行时 import
### Requirement: 基础控件直接使用 TDesign
后台页面、布局、Hook 和组件 Demo MUST 直接使用 `tdesign-react` 提供的基础控件,并在需要图标时直接使用 `tdesign-icons-react`。
#### Scenario: 页面使用基础控件
- **WHEN** 后台页面渲染按钮、输入框、文本域、选择器、开关、表格、分页、弹窗、抽屉、标签或消息反馈
- **THEN** 对应基础能力来自 `tdesign-react`
#### Scenario: 页面使用图标
- **WHEN** 后台页面或组件 Demo 需要渲染 TDesign 已提供的图标
- **THEN** 图标来自 `tdesign-icons-react`
### Requirement: 业务组合组件通过全局组件包复用
系统 MUST 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 作为全局业务组合组件从 `@gl/business-components` 导出,并且这些组件内部 MUST 不依赖 `workspace/agent-admin/web/packages/ui`。
#### Scenario: 列表页复用搜索区
- **WHEN** 后台列表页渲染查询条件、查询按钮和重置按钮
- **THEN** 页面从 `@gl/business-components` 使用 `SearchFilter`
#### Scenario: 页面复用状态占位
- **WHEN** 后台页面展示加载态、空数据态或错误态
- **THEN** 页面从 `@gl/business-components` 使用 `StatePlaceholder`
#### Scenario: 官网配置复用媒体墙
- **WHEN** 官网配置页面展示媒体上传、预览或删除能力
- **THEN** 页面从 `@gl/business-components` 使用 `MediaWall`
### Requirement: UI 依赖迁移保持业务行为
系统 MUST 在迁移 UI 依赖后保持现有后台页面的查询、重置、分页、弹窗、抽屉、表单更新、表单提交、状态展示和媒体上传行为。
#### Scenario: 列表页交互保持一致
- **WHEN** 用户在迁移后的列表页执行查询、重置、分页或行操作
- **THEN** 页面行为与迁移前一致
#### Scenario: 编辑页交互保持一致
- **WHEN** 用户在迁移后的编辑页修改字段并提交表单
- **THEN** 字段状态、校验和提交行为与迁移前一致
#### Scenario: 媒体墙交互保持一致
- **WHEN** 用户在迁移后的媒体墙执行上传、预览或删除
- **THEN** 页面继续使用既有上传契约并正确回填状态
#### Scenario: 消息反馈在 React 19 下可用
- **WHEN** 用户操作触发成功、失败、警告或信息消息
- **THEN** TDesign 消息插件使用 React 19 兼容的渲染入口展示反馈
- **AND** 页面不抛出 `reactRender is not a function`
### Requirement: 组件 Demo 不再展示旧本地 UI 包
组件 Demo MUST 展示 TDesign 基础组件和全局业务组件,并且 MUST 不再从 `workspace/agent-admin/web/packages/ui` 引入运行时能力。
#### Scenario: 打开组件 Demo
- **WHEN** 用户访问 `/components`
- **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件
- **AND** 页面不依赖旧本地 UI 包
### Requirement: 旧本地 UI 包目录暂时保留
系统 MUST 在本轮迁移中保留 `workspace/agent-admin/web/packages/ui` 目录,不把旧源码删除作为零运行时依赖验收条件。
#### Scenario: 完成运行时依赖迁移
- **WHEN** `workspace/agent-admin/web/src` 已达到零本地 UI 包运行时依赖
- **THEN** `workspace/agent-admin/web/packages/ui` 目录仍可保留,等待后续独立清理
### Requirement: 本轮表单迁移保持页面级组合
系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。
#### Scenario: 迁移编辑页表单
- **WHEN** 后台编辑页替换本地 `FormItem`、输入控件或选择控件
- **THEN** 页面直接使用 TDesign `Form`、`FormItem` 和基础控件
- **AND** 页面继续保留既有字段状态、校验、联动、上传和提交逻辑
#### Scenario: 遇到复杂表单内容
- **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单
- **THEN** 本轮继续使用页面级组合
- **AND** 系统不为这些内容扩展新的配置协议
## 1. 建立迁移基线
- [x] 1.1 扫描并记录 `workspace/agent-admin/web/src` 中指向 `packages/ui` 的运行时 import 基线
- [x] 1.2 盘点 `SearchFilter`、`StatePlaceholder`、`MediaWall` 的公开属性、行为和现有测试覆盖
- [x] 1.3 为零运行时依赖门禁补充可重复执行的静态扫描检查
## 2. 提升全局业务组合组件
- [x] 2.1 先为全局 `SearchFilter` 补充失败测试,再将其迁入 `@gl/business-components` 并保持查询、重置和草稿提交行为
- [x] 2.2 先为全局 `StatePlaceholder` 补充失败测试,再将其迁入 `@gl/business-components` 并保持加载、空数据和错误态行为
- [x] 2.3 先为全局 `MediaWall` 补充失败测试,再将其迁入 `@gl/business-components` 并保持上传、预览、删除和回填行为
- [x] 2.4 更新 `@gl/business-components` 导出入口,并确认三个全局业务组件内部不依赖 `workspace/agent-admin/web/packages/ui`
## 3. 迁移共享入口与只读页面
- [x] 3.1 先调整测试,再将 `AdminShell` 的弹窗能力改为直接使用 TDesign
- [x] 3.2 先调整测试,再将 `useMessage` 的反馈能力改为直接使用 TDesign
- [x] 3.3 先调整测试,再迁移 Agent、渠道活码和 Skill 详情抽屉中的按钮、抽屉、标签与状态占位
- [x] 3.4 运行共享入口与详情抽屉相关测试,确认行为保持一致
## 4. 迁移列表页
- [x] 4.1 先调整测试,再迁移 Agent 列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.2 先调整测试,再迁移岗位标签列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.3 先调整测试,再迁移渠道活码列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.4 先调整测试,再迁移官网岗位展示配置列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.5 先调整测试,再迁移 Skill 列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.6 运行列表页相关测试,确认查询、重置、分页、弹窗和行操作保持一致
## 5. 迁移编辑页与官网配置
- [x] 5.0 确认编辑页仅直接使用 TDesign 表单能力,不新增配置化表单渲染器或表单配置协议
- [x] 5.1 先调整测试,再迁移 Agent 编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.2 先调整测试,再迁移岗位标签编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.3 先调整测试,再迁移渠道活码编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.4 先调整测试,再迁移官网方法论配置页的 TDesign 表单控件和全局 `MediaWall`、`StatePlaceholder`
- [x] 5.5 先调整测试,再迁移官网 Agent 展示配置编辑弹窗和列表页的 TDesign 基础控件与全局 `MediaWall`、`StatePlaceholder`
- [x] 5.6 先调整测试,再迁移官网岗位展示新增编辑页和列表页的 TDesign 基础控件与全局 `SearchFilter`、`StatePlaceholder`
- [x] 5.7 运行编辑页与官网配置相关测试,确认字段更新、校验、上传和提交行为保持一致
## 6. 迁移组件 Demo
- [x] 6.1 先调整 Demo 测试,再将基础组件示例改为直接使用 `tdesign-react` 与 `tdesign-icons-react`
- [x] 6.2 将业务组合组件示例改为使用 `@gl/business-components`
- [x] 6.3 清理 Demo 对旧本地组件样式和实现细节的依赖
- [x] 6.4 运行组件 Demo 测试,确认展示和关键交互可用
## 7. 验证与收尾
- [x] 7.1 扫描 `workspace/agent-admin/web/src`,确认不存在指向 `packages/ui` 的运行时 import
- [x] 7.2 确认 `workspace/agent-admin/web/packages/ui` 目录仍然保留
- [x] 7.3 运行相关测试与完整前端测试
- [x] 7.4 运行 `npm run typecheck`
- [x] 7.5 运行 `npm run build`
- [x] 7.6 运行 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`
- [x] 7.7 在浏览器中验证主要列表页、编辑页和 `/components` 的布局与关键交互
## 8. 修复 React 19 消息插件运行时适配
- [x] 8.1 补充 `useMessage` 回归测试,覆盖 React 19 下 TDesign `MessagePlugin` 适配器导入路径与主入口一致
- [x] 8.2 将 `useMessage` 的 React 19 适配器导入调整为与 `tdesign-react` 实际 ESM 入口一致
- [x] 8.3 运行 `useMessage` 相关测试、类型检查、构建和 OpenSpec 严格校验
- [x] 8.4 在浏览器中触发成功消息,确认不再出现 `reactRender is not a function`
# admin-ui-runtime-dependency Specification # admin-ui-runtime-dependency Specification
## Purpose ## Purpose
约束后台运行时代码的 UI 依赖边界:基础控件直接来自 TDesign,跨页面业务组合能力来自全局业务组件包,旧本地 UI 包不再作为当前源码入口保留。 TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Purpose after archive.
## Requirements ## Requirements
### Requirement: 后台运行时代码不再依赖本地 UI 包 ### Requirement: 后台运行时代码不再依赖本地 UI 包
系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具,并且后台应用类型检查范围 MUST 不再纳入旧本地 UI 包源码目录。 系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具。
#### Scenario: 扫描后台运行时 import #### Scenario: 扫描后台运行时 import
- **WHEN** 对 `workspace/agent-admin/web/src` 执行本地 UI 包依赖扫描 - **WHEN** 对 `workspace/agent-admin/web/src` 执行本地 UI 包依赖扫描
- **THEN** 扫描结果不包含指向 `packages/ui` 或 `packages/ui/src` 的运行时 import - **THEN** 扫描结果不包含指向 `packages/ui` 或 `packages/ui/src` 的运行时 import
#### Scenario: 后台应用类型检查范围排除旧 UI 包
- **WHEN** 检查 `workspace/agent-admin/web/tsconfig.app.json`
- **THEN** `include` 不包含 `packages/ui/src`
### Requirement: 基础控件直接使用 TDesign ### Requirement: 基础控件直接使用 TDesign
后台页面、布局、Hook 和组件 Demo MUST 直接使用 `tdesign-react` 提供的基础控件,并在需要图标时直接使用 `tdesign-icons-react`。 后台页面、布局、Hook 和组件 Demo MUST 直接使用 `tdesign-react` 提供的基础控件,并在需要图标时直接使用 `tdesign-icons-react`。
...@@ -68,18 +64,12 @@ ...@@ -68,18 +64,12 @@
- **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件 - **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件
- **AND** 页面不依赖旧本地 UI 包 - **AND** 页面不依赖旧本地 UI 包
### Requirement: 旧本地 UI 包源码已删除 ### Requirement: 旧本地 UI 包目录暂时保留
系统 MUST 删除 `workspace/agent-admin/web/packages/ui` 遗留源码目录,并且当前后台协作文档 MUST 不再把该目录描述为当前组件入口或保留目标。 系统 MUST 在本轮迁移中保留 `workspace/agent-admin/web/packages/ui` 目录,不把旧源码删除作为零运行时依赖验收条件。
#### Scenario: 检查旧源码目录
- **WHEN** 检查 `workspace/agent-admin/web/packages/ui`
- **THEN** 该路径不存在
#### Scenario: 检查当前后台协作文档 #### Scenario: 完成运行时依赖迁移
- **WHEN** 阅读当前后台 README 和前端基础文档 - **WHEN** `workspace/agent-admin/web/src` 已达到零本地 UI 包运行时依赖
- **THEN** 文档说明基础控件来自 `tdesign-react` 或 `tdesign-icons-react` - **THEN** `workspace/agent-admin/web/packages/ui` 目录仍可保留,等待后续独立清理
- **AND** 文档说明业务组合能力来自 `@gl/business-components`
- **AND** 文档不要求保留 `workspace/agent-admin/web/packages/ui`
### Requirement: 本轮表单迁移保持页面级组合 ### Requirement: 本轮表单迁移保持页面级组合
系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。 系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。
...@@ -93,3 +83,4 @@ ...@@ -93,3 +83,4 @@
- **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单 - **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单
- **THEN** 本轮继续使用页面级组合 - **THEN** 本轮继续使用页面级组合
- **AND** 系统不为这些内容扩展新的配置协议 - **AND** 系统不为这些内容扩展新的配置协议
...@@ -32,54 +32,32 @@ TBD - created by archiving change extract-business-table-component. Update Purpo ...@@ -32,54 +32,32 @@ TBD - created by archiving change extract-business-table-component. Update Purpo
- **WHEN** 系统展示普通空态 - **WHEN** 系统展示普通空态
- **THEN** 系统 SHALL NOT 默认展示操作按钮 - **THEN** 系统 SHALL NOT 默认展示操作按钮
### Requirement: 筛选空态 ### Requirement: 精简筛选空态
系统 SHALL 在无错误、非加载、无数据且存在筛选条件时展示筛选空态。 系统 SHALL 在筛选无结果时使用精简状态块,仅展示图标和标题。
#### Scenario: 筛选无结果 #### Scenario: 筛选无结果
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 为 `true` - **WHEN** 表格无错误、非加载、无数据且存在筛选条件
- **THEN** 系统 SHALL 使用搜索语义图标展示标题“未找到匹配结果” - **THEN** 系统 SHALL 展示筛选无结果图标和标题“未找到匹配结果”
- **AND** 系统 SHALL 展示浅色说明文案“请调整搜索或筛选条件” - **AND** 系统 SHALL NOT 展示说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“暂无数据” - **AND** 系统 SHALL NOT 展示“清空筛选”按钮
#### Scenario: 清空筛选操作 ### Requirement: 精简列表失败态
- **WHEN** 筛选空态配置提供清空筛选回调 系统 SHALL 在列表加载失败时使用精简状态块,展示失败图标和标题“请求失败”。
- **THEN** 系统 SHALL 展示文案为“清空筛选”的 TDesign primary 实色按钮
#### Scenario: 触发清空筛选 #### Scenario: 列表加载失败
- **WHEN** 用户点击筛选空态中的“清空筛选”按钮 - **WHEN** 表格收到加载失败态配置
- **THEN** 系统 SHALL 调用筛选空态配置提供的清空筛选回调 - **THEN** 系统 SHALL 展示失败态图标和标题“请求失败”
- **AND** 系统 SHALL NOT 展示“重试”按钮
#### Scenario: 页面不传筛选空态文案 - **AND** 系统 SHALL NOT 渲染无文案的状态区按钮
- **WHEN** 页面使用 `BusinessTable` 展示筛选空态
- **THEN** 页面 SHALL 仅通过 `hasFilter` 表达筛选状态,并 MAY 通过 `filteredEmptyState.onAction` 提供清空筛选回调
- **AND** 页面 SHALL NOT 传入筛选空态的 `title`、`description` 或 `actionText`
### Requirement: 加载失败态 ### Requirement: 加载失败态
系统 SHALL 在表格加载失败或不可访问时展示错误状态块,并提供可恢复操作。 系统 SHALL 在表格加载失败或不可访问时展示错误状态块,并提供可恢复操作。
#### Scenario: 展示网络不可用
- **WHEN** `error` 为 `true`
- **THEN** 系统 SHALL 不渲染表格主体,并使用 TDesign 自带错误状态图标展示标题“网络不可用”
- **AND** 系统 SHALL 展示浅色说明文案“请检查网络连接后重试”
- **AND** 页面 SHALL NOT 传入加载失败态的 `title`、`description` 或 `retryText`
#### Scenario: 重试操作
- **WHEN** 网络不可用态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“重试”的 TDesign primary 实色按钮
#### Scenario: 触发重试
- **WHEN** 用户点击网络不可用态中的“重试”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
#### Scenario: 展示权限受限 #### Scenario: 展示权限受限
- **WHEN** `error` 为 `true` 且 `errorState.kind` 为 `forbidden` - **WHEN** `error` 为 `true` 且 `errorState.kind` 为 `forbidden`
...@@ -121,21 +99,27 @@ TBD - created by archiving change extract-business-table-component. Update Purpo ...@@ -121,21 +99,27 @@ TBD - created by archiving change extract-business-table-component. Update Purpo
### Requirement: 可选分页和总数展示 ### Requirement: 可选分页和总数展示
系统 SHALL 支持在业务表格底部渲染可选分页或总数信息。 系统 SHALL 支持在业务表格底部渲染可选分页或无分页总数信息,并在分页场景使用 TDesign `Pagination` 默认总数展示。
#### Scenario: 渲染分页 #### Scenario: 渲染分页
- **WHEN** 页面传入分页配置 - **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、总数和分页回调 - **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、默认总数文案和分页回调
#### Scenario: 分页场景不渲染额外总数文案
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL NOT 在 `Pagination` 外额外渲染 `totalLabel`
- **AND** 页面 SHALL 使用 TDesign `Pagination` 默认的 `totalContent` 展示总数
#### Scenario: 禁用分页 #### Scenario: 禁用分页
- **WHEN** 页面传入 `pagination={false}` - **WHEN** 页面传入 `pagination={false}`
- **THEN** 系统 SHALL NOT 渲染分页组件 - **THEN** 系统 SHALL NOT 渲染分页组件
#### Scenario: 展示总数文案 #### Scenario: 无分页时展示总数文案
- **WHEN** 页面传入 `totalLabel` - **WHEN** 页面未传入分页配置或传入 `pagination={false}`,且传入 `totalLabel`
- **THEN** 系统 SHALL 在表格底部展示该总数文案 - **THEN** 系统 SHALL 在表格底部展示该总数文案
### Requirement: 空态视觉位置 ### Requirement: 空态视觉位置
...@@ -147,6 +131,18 @@ TBD - created by archiving change extract-business-table-component. Update Purpo ...@@ -147,6 +131,18 @@ TBD - created by archiving change extract-business-table-component. Update Purpo
- **WHEN** `BusinessTable` 展示普通空态、筛选空态或加载失败态 - **WHEN** `BusinessTable` 展示普通空态、筛选空态或加载失败态
- **THEN** 系统 SHALL 使用足够的垂直空间和居中布局展示图标、标题、浅色说明和可选操作按钮,使其不显得贴近表头 - **THEN** 系统 SHALL 使用足够的垂直空间和居中布局展示图标、标题、浅色说明和可选操作按钮,使其不显得贴近表头
### Requirement: 表格刷新加载态
系统 SHALL 在 `BusinessTable` 收到加载态时使用表格区域局部 loading,并采用业务组件默认的轻量加载样式。
#### Scenario: 表格刷新中
- **WHEN** 页面向 `BusinessTable` 传入 `loading={true}`
- **THEN** 系统 SHALL 保留表格结构并展示表格区域 loading
- **AND** 系统 SHALL 使用小尺寸加载指示和当前主题主色提示文案
- **AND** 系统 SHALL 使用当前主题主色渲染加载指示器
- **AND** 系统 SHALL 允许调用方通过 TDesign `loadingProps` 覆盖默认加载配置
### Requirement: 后台列表页迁移 ### Requirement: 后台列表页迁移
系统 SHALL 将当前后台列表页迁移为使用 `BusinessTable` 渲染表格状态和分页区域。 系统 SHALL 将当前后台列表页迁移为使用 `BusinessTable` 渲染表格状态和分页区域。
...@@ -160,3 +156,72 @@ TBD - created by archiving change extract-business-table-component. Update Purpo ...@@ -160,3 +156,72 @@ TBD - created by archiving change extract-business-table-component. Update Purpo
- **WHEN** 页面迁移到 `BusinessTable` - **WHEN** 页面迁移到 `BusinessTable`
- **THEN** 系统 SHALL 保持现有查询、重置、分页、弹窗和行操作行为不变 - **THEN** 系统 SHALL 保持现有查询、重置、分页、弹窗和行操作行为不变
### Requirement: BusinessTable follows TDesign-first composition boundaries
系统 SHALL 在 `BusinessTable` 中优先使用 TDesign 组件表达表格、分页、空态、按钮和文本语义,并允许保留必要原生结构承载组件布局。
#### Scenario: Table semantic parts use TDesign
- **WHEN** `BusinessTable` 渲染表格、分页、空态、恢复操作或总数文本
- **THEN** 系统 SHALL 分别使用 TDesign `Table`、`Pagination`、`Empty`、`Button` 和 TDesign 文本组件或其等价能力
#### Scenario: Necessary layout containers remain native
- **WHEN** `BusinessTable` 需要根容器、空态居中容器或 footer 对齐容器
- **THEN** 系统 MAY 使用原生结构和 CSS module 承载布局
- **AND** 系统 SHALL NOT 为了替换布局容器而引入影响表格对齐、分页位置或空态视觉位置的额外组件层级
### Requirement: BusinessTable uses tooltip for text cells only when explicitly enabled
系统 SHALL 默认不为 `BusinessTable` 的普通文本单元格增加悬浮提示;当列配置显式开启普通文本悬浮提示时,系统 SHALL 使用单行省略展示超长内容,并在鼠标悬浮时通过 TDesign `Tooltip` 展示完整内容。
#### Scenario: Plain text cell does not opt in
- **WHEN** 列配置没有显式开启普通文本悬浮提示
- **THEN** 系统 SHALL NOT 默认为该单元格增加 TDesign `Tooltip`
#### Scenario: Text cell opts in to tooltip
- **WHEN** 列配置显式开启普通文本悬浮提示
- **AND** 列配置没有提供自定义 `cell`
- **AND** 单元格值为普通文本、数字、布尔值或由列配置显式提供的普通文本
- **THEN** 表格可见内容 SHALL 使用单行省略样式展示
- **AND** 鼠标悬浮该单元格内容时 SHALL 使用 TDesign `Tooltip` 展示完整内容
- **AND** Tooltip 宽度 SHALL 为 200px
- **AND** Tooltip 内容 SHALL 允许换行展示
#### Scenario: Empty text cell does not show tooltip
- **WHEN** 列配置显式开启普通文本悬浮提示
- **AND** 列配置没有提供自定义 `cell`
- **AND** 单元格取值为空、只包含空白字符或解析后为占位文案 `-`
- **THEN** 表格 SHALL 仅展示占位文案 `-`
- **AND** 系统 SHALL NOT 为该单元格渲染 TDesign `Tooltip`
#### Scenario: Text cell uses explicit tooltip value
- **WHEN** 列配置显式开启普通文本悬浮提示
- **AND** 列配置提供普通文本取值函数
- **THEN** 系统 SHALL 使用该取值函数结果作为单元格可见文本和 Tooltip 内容
- **AND** 页面 SHALL NOT 需要在业务列中手写 TDesign `Tooltip`
#### Scenario: Custom cell keeps page rendering
- **WHEN** 列配置已经提供自定义 `cell`
- **THEN** `BusinessTable` SHALL NOT 覆盖该列的单元格渲染
- **AND** 页面自定义的按钮、状态、图片或组合内容 SHALL 保持原样
### Requirement: Business long text columns opt in to tooltip
系统 SHALL 为已确认的业务长文本列表列显式开启 `BusinessTable` tooltip,以便文本超过列宽时单行省略并可悬浮查看完整内容。
#### Scenario: Confirmed business long text columns use explicit tooltip
- **WHEN** 技能列表渲染“说明”列
- **OR** 官网 Agent 展示配置列表渲染“Agent 概述”列
- **OR** 岗位标签列表渲染“标签描述”列
- **OR** 渠道活码列表渲染“关联 Agent”列
- **THEN** 对应列 SHALL 通过 `BusinessTable` 显式开启 TDesign Tooltip
- **AND** Tooltip 展示 SHALL 复用 `BusinessTable` 的 200px 宽度和换行规则
...@@ -51,6 +51,14 @@ function getNumberInput(name: string) { ...@@ -51,6 +51,14 @@ function getNumberInput(name: string) {
return input as HTMLInputElement; return input as HTMLInputElement;
} }
function getControlHolder(name: string) {
const holder = screen.getByTestId(`business-form-control-holder-${name}`);
if (!holder) {
throw new Error(`Control holder ${name} was not found`);
}
return holder as HTMLElement;
}
function Harness({ function Harness({
fields, fields,
initialValues, initialValues,
...@@ -130,7 +138,7 @@ describe('BusinessForm', () => { ...@@ -130,7 +138,7 @@ describe('BusinessForm', () => {
); );
expect(screen.getByLabelText('名称')).toHaveValue('合同'); expect(screen.getByLabelText('名称')).toHaveValue('合同');
expect(getNumberInput('amount')).toHaveValue('2.00'); expect(getNumberInput('amount')).toHaveValue(2);
expect(getSelectTrigger('状态')).toHaveValue('启用'); expect(getSelectTrigger('状态')).toHaveValue('启用');
expect(screen.getByRole('switch', { name: '开关' })).toBeChecked(); expect(screen.getByRole('switch', { name: '开关' })).toBeChecked();
expect(screen.getByLabelText('备注')).toHaveValue('已填写'); expect(screen.getByLabelText('备注')).toHaveValue('已填写');
...@@ -141,6 +149,68 @@ describe('BusinessForm', () => { ...@@ -141,6 +149,68 @@ describe('BusinessForm', () => {
expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '360'); expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '360');
}); });
it('keeps controlled fields inside TDesign FormItem without overriding their values', () => {
const onChange = vi.fn();
render(
<Harness
fields={[
{ key: 'title', label: '名称', type: 'input', required: true, helpText: '请输入项目名称' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{
key: 'custom',
label: '自定义',
type: 'custom',
render: ({ value, setValue }) => (
<button type="button" onClick={() => setValue('custom-next')}>
{String(value)}
</button>
),
},
]}
initialValues={{ title: '合同', status: 'enabled', custom: 'custom-start' }}
errors={{ title: '名称错误' }}
onChange={onChange}
/>,
);
const titleField = screen.getByTestId('business-form-field-title');
expect(titleField.querySelector('.t-form__item')).toBeInTheDocument();
expect(within(titleField).getByText('请输入项目名称')).toBeInTheDocument();
expect(within(titleField).getByText('名称错误')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '合同A' } });
fireEvent.click(screen.getByRole('button', { name: 'custom-start' }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ title: '合同A' }), 'title');
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ custom: 'custom-next' }), 'custom');
});
it('uses red validation text and light gray helper text', () => {
render(
<BusinessForm
fields={[{ key: 'title', label: '名称', type: 'input', required: true, helpText: '普通提示' }]}
values={{ title: '' }}
errors={{ title: '名称必填' }}
onChange={vi.fn()}
/>,
);
const titleField = screen.getByTestId('business-form-field-title');
const helperText = within(titleField).getByText('普通提示');
const errorText = within(titleField).getByText('名称必填');
expect(helperText.className).toContain('helpText');
expect(errorText.className).toContain('error');
expect(helperText).toHaveStyle({ color: '#a6a6a6' });
expect(errorText).toHaveStyle({ color: '#d94841' });
});
it('updates controlled values and emits form-level and field-level patch changes', () => { it('updates controlled values and emits form-level and field-level patch changes', () => {
const onChange = vi.fn(); const onChange = vi.fn();
const titleChange = vi.fn(); const titleChange = vi.fn();
...@@ -239,7 +309,8 @@ describe('BusinessForm', () => { ...@@ -239,7 +309,8 @@ describe('BusinessForm', () => {
expect(screen.getByLabelText('锁定项')).toBeDisabled(); expect(screen.getByLabelText('锁定项')).toBeDisabled();
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } }); fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } });
expect(screen.getByLabelText('只读项')).toHaveAttribute('readonly'); expect(screen.queryByLabelText('只读项')).not.toBeInTheDocument();
expect(screen.getByText('只读值')).toBeInTheDocument();
}); });
it('validates required, max length, number range, precision, readonly, hidden and custom validator fields', async () => { it('validates required, max length, number range, precision, readonly, hidden and custom validator fields', async () => {
...@@ -278,7 +349,9 @@ describe('BusinessForm', () => { ...@@ -278,7 +349,9 @@ describe('BusinessForm', () => {
}); });
}); });
it('keeps allowInputOverMax editable and uses native length display for input and textarea', () => { it('caps input and textarea values at maxLength and uses native length display', () => {
const handleChange = vi.fn();
render( render(
<BusinessForm <BusinessForm
fields={[ fields={[
...@@ -286,15 +359,22 @@ describe('BusinessForm', () => { ...@@ -286,15 +359,22 @@ describe('BusinessForm', () => {
{ key: 'remark', label: '备注', type: 'textarea', maxLength: 5, allowInputOverMax: true }, { key: 'remark', label: '备注', type: 'textarea', maxLength: 5, allowInputOverMax: true },
]} ]}
values={{ title: '', remark: '' }} values={{ title: '', remark: '' }}
onChange={vi.fn()} onChange={handleChange}
/>, />,
); );
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '超出长度啊' } }); fireEvent.change(screen.getByLabelText('名称'), { target: { value: '超出长度啊' } });
fireEvent.change(screen.getByLabelText('备注'), { target: { value: '超出长度内容啊' } }); fireEvent.change(screen.getByLabelText('备注'), { target: { value: '超出长度内容啊' } });
expect(screen.getByLabelText('名称')).toHaveValue('超出长度啊'); expect(screen.getByLabelText('名称')).toHaveValue('超出长度');
expect(screen.getByLabelText('备注')).toHaveValue('超出长度内容啊'); expect(screen.getByLabelText('备注')).toHaveValue('超出长度内');
expect(handleChange).toHaveBeenLastCalledWith(
{ title: '超出长度', remark: '超出长度内' },
expect.objectContaining({
key: 'remark',
value: '超出长度内',
}),
);
}); });
it('keeps input, numberInput, select and textarea at the same default width and syncs fieldWidth to all of them', () => { it('keeps input, numberInput, select and textarea at the same default width and syncs fieldWidth to all of them', () => {
...@@ -346,6 +426,49 @@ describe('BusinessForm', () => { ...@@ -346,6 +426,49 @@ describe('BusinessForm', () => {
expect(screen.getByTestId('business-form-field-amount')).toHaveAttribute('data-width', '420'); expect(screen.getByTestId('business-form-field-amount')).toHaveAttribute('data-width', '420');
expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '420'); expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '420');
expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '420'); expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '420');
expect(getControlHolder('title')).toHaveStyle({ width: '100%', maxWidth: '420px' });
expect(getControlHolder('amount')).toHaveStyle({ width: '100%', maxWidth: '420px' });
expect(getControlHolder('status')).toHaveStyle({ width: '100%', maxWidth: '420px' });
expect(getControlHolder('remark')).toHaveStyle({ width: '100%', maxWidth: '420px' });
rerender(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input' },
{ key: 'amount', label: '数量', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{ key: 'remark', label: '备注', type: 'textarea' },
]}
values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
onChange={vi.fn()}
fieldWidth="w-full max-w-[450px]"
/>,
);
expect(getControlHolder('title')).toHaveClass('w-full', 'max-w-[450px]');
expect(getControlHolder('amount')).toHaveClass('w-full', 'max-w-[450px]');
expect(getControlHolder('status')).toHaveClass('w-full', 'max-w-[450px]');
expect(getControlHolder('remark')).toHaveClass('w-full', 'max-w-[450px]');
});
it('keeps 40px spacing between form rows', () => {
const { container } = render(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input' },
{ key: 'amount', label: '数量', type: 'numberInput' },
]}
values={{ title: '', amount: 0 }}
onChange={vi.fn()}
/>,
);
expect(container.querySelector('form')).toHaveStyle({ gap: '40px' });
}); });
it('respects select option disabled, field disabled and readonly native props', () => { it('respects select option disabled, field disabled and readonly native props', () => {
...@@ -399,8 +522,8 @@ describe('BusinessForm', () => { ...@@ -399,8 +522,8 @@ describe('BusinessForm', () => {
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
expect(getSelectTrigger('状态')).toHaveValue('启用'); expect(getSelectTrigger('状态')).toHaveValue('启用');
expect(getSelectTrigger('禁用状态')).toBeDisabled(); expect(getSelectTrigger('禁用状态')).toBeDisabled();
expect(getSelectTrigger('只读状态')).toHaveValue('停用'); expect(screen.queryByLabelText('只读状态')).not.toBeInTheDocument();
expect(getSelectTrigger('只读状态')).toHaveAttribute('readonly'); expect(within(screen.getByTestId('business-form-field-readonlyStatus')).getByText('停用')).toBeInTheDocument();
}); });
it('supports boolean switch defaults, mapped values and readonly display', () => { it('supports boolean switch defaults, mapped values and readonly display', () => {
...@@ -433,6 +556,57 @@ describe('BusinessForm', () => { ...@@ -433,6 +556,57 @@ describe('BusinessForm', () => {
expect(screen.queryByRole('switch', { name: '只读开关' })).not.toBeInTheDocument(); expect(screen.queryByRole('switch', { name: '只读开关' })).not.toBeInTheDocument();
}); });
it('uses TDesign text, image and link primitives for readonly and static upload display', () => {
render(
<BusinessForm
fields={[
{ key: 'summary', label: '说明', type: 'displayText' },
{ key: 'readonlyNote', label: '只读说明', type: 'input', readonly: true },
{ key: 'readonlySwitch', label: '只读开关', type: 'switch', readonly: true },
{
key: 'readonlyMedia',
label: '只读素材',
type: 'upload',
uploadType: 'media',
readonly: true,
upload: vi.fn(),
},
{
key: 'readonlyFile',
label: '只读文件',
type: 'upload',
uploadType: 'file',
readonly: true,
upload: vi.fn(),
},
]}
values={{
summary: '展示内容',
readonlyNote: '只读内容',
readonlySwitch: true,
readonlyMedia: { name: 'cover.png', url: '/cover.png', kind: 'image' },
readonlyFile: { name: 'manual.pdf', url: '/manual.pdf', kind: 'file' },
}}
onChange={vi.fn()}
/>,
);
const summaryField = screen.getByTestId('business-form-field-summary');
const readonlyNoteField = screen.getByTestId('business-form-field-readonlyNote');
const readonlySwitchField = screen.getByTestId('business-form-field-readonlySwitch');
const readonlyMediaField = screen.getByTestId('business-form-field-readonlyMedia');
const readonlyFileField = screen.getByTestId('business-form-field-readonlyFile');
expect(within(summaryField).getByText('展示内容').tagName).toBe('SPAN');
expect(within(readonlyNoteField).getByText('只读内容').tagName).toBe('SPAN');
expect(within(readonlySwitchField).getByText('已开启').tagName).toBe('SPAN');
expect(readonlyMediaField.querySelector('.t-image')).toBeInTheDocument();
expect(within(readonlyMediaField).getByText('cover.png').tagName).toBe('SPAN');
expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('href', '/manual.pdf');
expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('target', '_blank');
expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('rel', 'noreferrer');
});
it('rejects invalid media uploads, uploads media and file values separately, and renders media cards', async () => { it('rejects invalid media uploads, uploads media and file values separately, and renders media cards', async () => {
const upload = vi.fn(async (file: File) => ({ url: `/uploaded/${file.name}` })); const upload = vi.fn(async (file: File) => ({ url: `/uploaded/${file.name}` }));
const failedUpload = vi.fn(async () => { const failedUpload = vi.fn(async () => {
......
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { BusinessTable } from '@gl/business-components'; import { BusinessTable, type BusinessTableColumn } from '@gl/business-components';
import type { PrimaryTableCol } from 'tdesign-react'; import type { PrimaryTableCol } from 'tdesign-react';
type DemoRow = { type DemoRow = {
...@@ -229,6 +229,122 @@ describe('BusinessTable', () => { ...@@ -229,6 +229,122 @@ describe('BusinessTable', () => {
expect(screen.getByText('示例一').closest('tr')).toHaveClass('demo-row'); expect(screen.getByText('示例一').closest('tr')).toHaveClass('demo-row');
}); });
it('does not add tooltip to plain text cells by default', () => {
const longName = '这是一段很长的表格文本内容,用来验证通用表格列的省略和悬浮展示';
const { container } = render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[
{ id: 1, name: longName, status: '启用' },
]}
/>,
);
const textCell = screen.getByText(longName);
expect(textCell.className).not.toContain('cellText');
expect(container.querySelector('[class*="cellTooltipContent"]')).not.toBeInTheDocument();
});
it('truncates explicitly configured text cells and shows full content with TDesign Tooltip', async () => {
const longName = '这是一段很长的表格文本内容,用来验证通用表格列的省略和悬浮展示';
const columns: BusinessTableColumn<DemoRow>[] = [
{ title: '名称', colKey: 'name', ellipsisTooltip: true },
{
title: '状态',
colKey: 'status',
cell: ({ row }) => <span>{row.status}</span>,
},
];
const { container } = render(
<BusinessTable
rowKey="id"
columns={columns}
data={[
{ id: 1, name: longName, status: '启用' },
]}
/>,
);
const textCell = screen.getByText(longName);
expect(textCell.className).toContain('cellText');
expect(screen.getByText('启用').className).not.toContain('cellText');
fireEvent.mouseEnter(textCell);
await waitFor(() => {
const tooltipContent = document.body.querySelector('[class*="cellTooltipContent"]');
expect(tooltipContent).toBeInTheDocument();
if (!tooltipContent) throw new Error('Tooltip content should exist');
expect(tooltipContent).toHaveTextContent(longName);
expect(tooltipContent).toHaveStyle({
width: '200px',
maxWidth: '200px',
whiteSpace: 'normal',
});
expect(tooltipContent.className).toContain('cellTooltipContent');
});
expect(container.querySelector('.t-table')).toBeInTheDocument();
});
it('uses explicit tooltip value for derived plain text columns', async () => {
type AgentRow = {
id: number;
agents: string[];
};
const agentText = '小顾、设计助手、投放助手';
const columns: BusinessTableColumn<AgentRow>[] = [
{
title: '关联 Agent',
colKey: 'agents',
ellipsisTooltip: true,
tooltipValue: ({ agents }) => (agents.length > 0 ? agents.join('、') : '-'),
},
];
render(
<BusinessTable
rowKey="id"
columns={columns}
data={[{ id: 1, agents: ['小顾', '设计助手', '投放助手'] }]}
/>,
);
const textCell = screen.getByText(agentText);
expect(textCell.className).toContain('cellText');
fireEvent.mouseEnter(textCell);
await waitFor(() => {
const tooltipContent = document.body.querySelector('[class*="cellTooltipContent"]');
expect(tooltipContent).toBeInTheDocument();
expect(tooltipContent).toHaveTextContent(agentText);
});
});
it('does not render tooltip for explicitly configured empty text cells', () => {
const columns: BusinessTableColumn<DemoRow>[] = [
{ title: '名称', colKey: 'name', ellipsisTooltip: true },
];
const { container } = render(
<BusinessTable
rowKey="id"
columns={columns}
data={[
{ id: 1, name: '', status: '启用' },
{ id: 2, name: ' ', status: '启用' },
{ id: 3, name: '-', status: '启用' },
{ id: 4, name: '实际说明', status: '启用' },
]}
/>,
);
expect(screen.getAllByText('-')).toHaveLength(3);
expect(screen.getByText('实际说明').className).toContain('cellText');
expect(container.querySelectorAll('[class*="cellText"]')).toHaveLength(1);
expect(container.querySelector('[class*="cellTooltipContent"]')).not.toBeInTheDocument();
});
it('renders pagination, honors totalLabel and can disable pagination', () => { it('renders pagination, honors totalLabel and can disable pagination', () => {
const { container, rerender } = render( const { container, rerender } = render(
<BusinessTable <BusinessTable
...@@ -259,6 +375,6 @@ describe('BusinessTable', () => { ...@@ -259,6 +375,6 @@ describe('BusinessTable', () => {
); );
expect(container.querySelector('.t-pagination')).not.toBeInTheDocument(); expect(container.querySelector('.t-pagination')).not.toBeInTheDocument();
expect(screen.getByText('共 35 条')).toBeInTheDocument(); expect(screen.getByText('共 35 条').tagName).toBe('SPAN');
}); });
}); });
...@@ -34,12 +34,16 @@ const MessageContext = createContext<MessageContextValue | null>(null); ...@@ -34,12 +34,16 @@ const MessageContext = createContext<MessageContextValue | null>(null);
export function MessageProvider({ children }: { children: ReactNode }) { export function MessageProvider({ children }: { children: ReactNode }) {
const addMessage = useCallback((type: FlashState['type'], content: string, options?: MessageOptions) => { const addMessage = useCallback((type: FlashState['type'], content: string, options?: MessageOptions) => {
MessagePlugin[type]({ try {
content, MessagePlugin[type]({
duration: options?.duration ?? 3000, content,
closeBtn: options?.closable ?? false, duration: options?.duration ?? 3000,
placement: 'top-right', closeBtn: options?.closable ?? false,
}); placement: 'top-right',
});
} catch {
// 消息插件在测试或无 DOM 环境下可能不可用,忽略即可。
}
}, []); }, []);
const success = useCallback((content: string, options?: MessageOptions) => { const success = useCallback((content: string, options?: MessageOptions) => {
...@@ -59,7 +63,11 @@ export function MessageProvider({ children }: { children: ReactNode }) { ...@@ -59,7 +63,11 @@ export function MessageProvider({ children }: { children: ReactNode }) {
}, [addMessage]); }, [addMessage]);
const clear = useCallback(() => { const clear = useCallback(() => {
MessagePlugin.closeAll(); try {
MessagePlugin.closeAll();
} catch {
// 忽略消息插件关闭失败。
}
}, []); }, []);
return ( return (
......
...@@ -22,4 +22,13 @@ describe('phase five editor page local ui runtime dependencies', () => { ...@@ -22,4 +22,13 @@ describe('phase five editor page local ui runtime dependencies', () => {
it.each(editorPageRuntimeFiles)('%s no longer imports packages/ui', (_, source) => { it.each(editorPageRuntimeFiles)('%s no longer imports packages/ui', (_, source) => {
expect(source).not.toContain('packages/ui'); expect(source).not.toContain('packages/ui');
}); });
it.each([
['AgentTagEditorPage.tsx', agentTagEditorPageSource],
['ChannelCodeEditorPage.tsx', channelCodeEditorPageSource],
['OfficialSiteJobTabEditorPage.tsx', officialSiteJobTabEditorPageSource],
])('%s uses BusinessForm instead of direct TDesign form controls', (_, source) => {
expect(source).toContain('BusinessForm');
expect(source).not.toContain('TDesignAccessibleControls');
});
}); });
import { useState } from 'react'; import { useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { StatePlaceholder } from '@gl/business-components'; import {
BusinessForm,
StatePlaceholder,
validateBusinessForm,
type BusinessFormErrors,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
import { Button } from 'tdesign-react'; import { Button } from 'tdesign-react';
import { FormItem, Input, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getPositionTagList, getPositionTagList,
createPositionTag, createPositionTag,
...@@ -14,14 +20,10 @@ import { trackCustomEvent } from '../../api/tracking'; ...@@ -14,14 +20,10 @@ import { trackCustomEvent } from '../../api/tracking';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
import { buildAgentTagListSearch, readAgentTagListRouteState } from './agentTagRouteState'; import { buildAgentTagListSearch, readAgentTagListRouteState } from './agentTagRouteState';
interface TagFormState { interface TagFormState extends BusinessFormValues {
name: string; name: string;
description: string; description: string;
} code?: string;
interface TagFormErrors {
name?: string;
description?: string;
} }
interface SaveNotice { interface SaveNotice {
...@@ -33,6 +35,7 @@ function buildInitialFormState(tag?: PositionTagListItem): TagFormState { ...@@ -33,6 +35,7 @@ function buildInitialFormState(tag?: PositionTagListItem): TagFormState {
return { return {
name: tag?.name ?? '', name: tag?.name ?? '',
description: tag?.description ?? '', description: tag?.description ?? '',
code: tag?.code ?? '',
}; };
} }
...@@ -47,10 +50,10 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -47,10 +50,10 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [currentTag, setCurrentTag] = useState<PositionTagListItem | undefined>(() => routeTag); const [currentTag, setCurrentTag] = useState<PositionTagListItem | undefined>(() => routeTag);
const [form, setForm] = useState<TagFormState>(() => buildInitialFormState(currentTag)); const [form, setForm] = useState<TagFormState>(() => buildInitialFormState(currentTag));
const [errors, setErrors] = useState<TagFormErrors>({}); const [errors, setErrors] = useState<BusinessFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null); const [notice, setNotice] = useState<SaveNotice | null>(null);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const fieldWidthClassName = 'w-full max-w-[450px]'; const fieldWidth = 450;
useDeferredEffect(() => { useDeferredEffect(() => {
if (mode === 'edit' && !routeTag && params.tagId) { if (mode === 'edit' && !routeTag && params.tagId) {
...@@ -77,6 +80,30 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -77,6 +80,30 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
navigate(`/agent-tags${buildAgentTagListSearch(routeState)}`); navigate(`/agent-tags${buildAgentTagListSearch(routeState)}`);
}; };
const fields: BusinessFormField[] = [
{
key: 'name',
label: '标签名称',
type: 'input',
required: true,
maxLength: 20,
},
{
key: 'code',
label: '标签编码',
type: 'input',
readonly: true,
visible: mode === 'edit' && Boolean(currentTag?.code),
},
{
key: 'description',
label: '标签描述',
type: 'textarea',
maxLength: 100,
rows: 5,
},
];
if (loading) { if (loading) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
...@@ -85,7 +112,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -85,7 +112,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
); );
} }
if (mode === 'edit' && !currentTag) { if (loadError || (mode === 'edit' && !currentTag)) {
return ( return (
<StatePlaceholder <StatePlaceholder
state="error" state="error"
...@@ -96,28 +123,12 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -96,28 +123,12 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
); );
} }
const validate = () => {
const nextErrors: TagFormErrors = {};
const trimmedName = form.name.trim();
const trimmedDescription = form.description.trim();
if (!trimmedName) {
nextErrors.name = '请输入标签名称';
} else if (trimmedName.length > 20) {
nextErrors.name = '标签名称最多20字';
}
if (trimmedDescription.length > 100) {
nextErrors.description = '标签描述最多100字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = async () => { const handleSave = async () => {
setNotice(null); setNotice(null);
if (!validate()) {
const validation = await validateBusinessForm(fields, form);
setErrors(validation);
if (Object.values(validation).some(Boolean)) {
return; return;
} }
...@@ -177,41 +188,14 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -177,41 +188,14 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="标签名称" labelAlign="left" requiredMark status={errors.name ? 'error' : undefined} tips={errors.name}> <BusinessForm
<Input fields={fields}
aria-label="标签名称" values={form}
className={fieldWidthClassName} errors={errors}
maxlength={20} fieldWidth={fieldWidth}
allowInputOverMax labelAlign="left"
showLimitNumber onChange={(nextValues) => setForm(nextValues as TagFormState)}
value={form.name} />
onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/>
</FormItem>
{mode === 'edit' && currentTag?.code ? (
<FormItem label="标签编码" labelAlign="left">
<Input
aria-label="标签编码"
className={fieldWidthClassName}
disabled
value={currentTag.code}
/>
</FormItem>
) : null}
<FormItem label="标签描述" labelAlign="left" status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea
aria-label="标签描述"
className={fieldWidthClassName}
maxlength={100}
allowInputOverMax
rows={5}
count
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
</div> </div>
</div> </div>
</section> </section>
......
...@@ -133,7 +133,8 @@ export function AgentTagListPage() { ...@@ -133,7 +133,8 @@ export function AgentTagListPage() {
{ {
title: '标签描述', title: '标签描述',
colKey: 'description', colKey: 'description',
cell: ({ row }) => row.description?.trim() || '-', ellipsisTooltip: true,
tooltipValue: ({ description }) => description?.trim() || '-',
}, },
{ title: '绑定Agent数', colKey: 'agent_count' }, { title: '绑定Agent数', colKey: 'agent_count' },
{ title: '创建时间', colKey: 'created_at' }, { title: '创建时间', colKey: 'created_at' },
......
...@@ -172,6 +172,7 @@ describe('Agent tag routes and list page', () => { ...@@ -172,6 +172,7 @@ describe('Agent tag routes and list page', () => {
expect(screen.getAllByText('标签名称').length).toBeGreaterThan(0); expect(screen.getAllByText('标签名称').length).toBeGreaterThan(0);
expect(screen.getByText('标签编码')).toBeInTheDocument(); expect(screen.getByText('标签编码')).toBeInTheDocument();
expect(screen.getByText('标签描述')).toBeInTheDocument(); expect(screen.getByText('标签描述')).toBeInTheDocument();
expect(screen.getByText('驻店销售岗').className).toContain('cellText');
expect(screen.getByText('绑定Agent数')).toBeInTheDocument(); expect(screen.getByText('绑定Agent数')).toBeInTheDocument();
expect(screen.getByText('创建时间')).toBeInTheDocument(); expect(screen.getByText('创建时间')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '编辑店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text'); expect(screen.getByRole('button', { name: '编辑店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
...@@ -285,7 +286,7 @@ describe('Agent tag create and edit pages', () => { ...@@ -285,7 +286,7 @@ describe('Agent tag create and edit pages', () => {
// Validate that only name is required (code is auto-generated by backend) // Validate that only name is required (code is auto-generated by backend)
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
await screen.findByText('请输入标签名称'); await screen.findByText('请输入必填项');
expect(screen.queryByText('请输入标签编码')).not.toBeInTheDocument(); expect(screen.queryByText('请输入标签编码')).not.toBeInTheDocument();
expect(screen.queryByLabelText('标签编码')).not.toBeInTheDocument(); expect(screen.queryByLabelText('标签编码')).not.toBeInTheDocument();
...@@ -317,9 +318,9 @@ describe('Agent tag create and edit pages', () => { ...@@ -317,9 +318,9 @@ describe('Agent tag create and edit pages', () => {
await screen.findByRole('heading', { name: '编辑岗位标签' }); await screen.findByRole('heading', { name: '编辑岗位标签' });
await waitFor(() => { await waitFor(() => {
expect(screen.getByLabelText('标签名称')).toHaveValue('售后客服'); expect(screen.getByLabelText('标签名称')).toHaveValue('售后客服');
expect(screen.getByLabelText('标签编码')).toHaveValue('after_sales_service'); expect(screen.getByText('after_sales_service')).toBeInTheDocument();
}); });
expect(screen.getByLabelText('标签编码')).toBeDisabled(); expect(screen.queryByRole('textbox', { name: '标签编码' })).not.toBeInTheDocument();
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后服务' } }); fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后服务' } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
......
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { StatePlaceholder } from '@gl/business-components'; import {
BusinessForm,
StatePlaceholder,
type BusinessFormErrors,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
import { Button } from 'tdesign-react'; import { Button } from 'tdesign-react';
import { FormItem, Input, Select, Switch, Textarea } from '../../components/TDesignAccessibleControls'; import { Input, Select } from '../../components/TDesignAccessibleControls';
import { getPositionTagList, type PositionTagListItem } from '../../api/positionTag'; import { getPositionTagList, type PositionTagListItem } from '../../api/positionTag';
import { getEmployeeMounts, getAgentDetail, getAgentList, createAgent, updateAgent, type EmployeeMountItem, type AgentDetail, type AgentStatus } from '../../api/agent'; import { getEmployeeMounts, getAgentDetail, getAgentList, createAgent, updateAgent, type EmployeeMountItem, type AgentDetail, type AgentStatus } from '../../api/agent';
import { getSkillList, type SkillSummary } from '../../api/skill'; import { getSkillList, type SkillSummary } from '../../api/skill';
...@@ -19,7 +25,7 @@ interface PositionOption { ...@@ -19,7 +25,7 @@ interface PositionOption {
name: string; name: string;
} }
interface AgentFormState { interface AgentFormState extends BusinessFormValues {
name: string; name: string;
positionIds: number[]; positionIds: number[];
managedUserId: number | string | undefined; managedUserId: number | string | undefined;
...@@ -30,7 +36,6 @@ interface AgentFormState { ...@@ -30,7 +36,6 @@ interface AgentFormState {
status: AgentStatus; status: AgentStatus;
} }
const STEWARD_AGENT_NAME = '管家Agent';
const STEWARD_POSITION_LABEL = '系统调度'; const STEWARD_POSITION_LABEL = '系统调度';
const STEWARD_MANAGED_USER_FALLBACK = '专用管家企微员工'; const STEWARD_MANAGED_USER_FALLBACK = '专用管家企微员工';
const AGENT_DESCRIPTION_MAX_LENGTH = 500; const AGENT_DESCRIPTION_MAX_LENGTH = 500;
...@@ -84,6 +89,10 @@ function canSelectEmployee(employee: EmployeeMountItem, mode: 'create' | 'edit', ...@@ -84,6 +89,10 @@ function canSelectEmployee(employee: EmployeeMountItem, mode: 'create' | 'edit',
return mountedByCurrentAgent; return mountedByCurrentAgent;
} }
function isArrayValue(value: unknown): value is Array<string | number> {
return Array.isArray(value);
}
export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate(); const navigate = useNavigate();
const params = useParams(); const params = useParams();
...@@ -100,18 +109,15 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -100,18 +109,15 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const initialFormState = buildInitialFormState(); const initialFormState = buildInitialFormState();
const [form, setForm] = useState<AgentFormState>(initialFormState); const [form, setForm] = useState<AgentFormState>(initialFormState);
const [errors, setErrors] = useState<Partial<Record<keyof AgentFormState, string>>>({}); const [errors, setErrors] = useState<BusinessFormErrors>({});
const [positionTags, setPositionTags] = useState<PositionTagListItem[]>([]); const [positionTags, setPositionTags] = useState<PositionTagListItem[]>([]);
const [positionsLoading, setPositionsLoading] = useState(true);
const [positionsError, setPositionsError] = useState(false); const [positionsError, setPositionsError] = useState(false);
const [employees, setEmployees] = useState<EmployeeMountItem[]>([]); const [employees, setEmployees] = useState<EmployeeMountItem[]>([]);
const [employeesLoading, setEmployeesLoading] = useState(true);
const [employeesError, setEmployeesError] = useState(false); const [employeesError, setEmployeesError] = useState(false);
const [skills, setSkills] = useState<SkillSummary[]>([]); const [skills, setSkills] = useState<SkillSummary[]>([]);
const [skillsLoading, setSkillsLoading] = useState(true);
const [skillsError, setSkillsError] = useState(false); const [skillsError, setSkillsError] = useState(false);
const [saveLoading, setSaveLoading] = useState(false); const [saveLoading, setSaveLoading] = useState(false);
...@@ -122,6 +128,16 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -122,6 +128,16 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const fieldWidthClassName = 'w-full max-w-[450px]'; const fieldWidthClassName = 'w-full max-w-[450px]';
const agentId = params.agentId ? Number(params.agentId) : undefined; const agentId = params.agentId ? Number(params.agentId) : undefined;
const fetchPositions = () => {
setPositionsError(false);
getPositionTagList({ page: 1, page_size: 100 })
.then((response) => {
setPositionTags(response.list);
})
.catch(() => {
setPositionsError(true);
});
};
// 编辑模式始终调用详情接口,不依赖本地缓存 // 编辑模式始终调用详情接口,不依赖本地缓存
useDeferredEffect(() => { useDeferredEffect(() => {
...@@ -200,44 +216,28 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -200,44 +216,28 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
}, [agentId, detail?.name, mode]); }, [agentId, detail?.name, mode]);
useDeferredEffect(() => { useDeferredEffect(() => {
setPositionsLoading(true); fetchPositions();
setPositionsError(false);
getPositionTagList({ page: 1, page_size: 100 })
.then((response) => {
setPositionTags(response.list);
setPositionsLoading(false);
})
.catch(() => {
setPositionsError(true);
setPositionsLoading(false);
});
}, []); }, []);
useDeferredEffect(() => { useDeferredEffect(() => {
setEmployeesLoading(true);
setEmployeesError(false); setEmployeesError(false);
getEmployeeMounts() getEmployeeMounts()
.then((response) => { .then((response) => {
setEmployees(response.employees); setEmployees(response.employees);
setEmployeesLoading(false);
}) })
.catch(() => { .catch(() => {
setEmployeesError(true); setEmployeesError(true);
setEmployeesLoading(false);
}); });
}, []); }, []);
useDeferredEffect(() => { useDeferredEffect(() => {
setSkillsLoading(true);
setSkillsError(false); setSkillsError(false);
getSkillList() getSkillList()
.then((response) => { .then((response) => {
setSkills(response.list); setSkills(response.list);
setSkillsLoading(false);
}) })
.catch(() => { .catch(() => {
setSkillsError(true); setSkillsError(true);
setSkillsLoading(false);
}); });
}, []); }, []);
...@@ -263,15 +263,251 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -263,15 +263,251 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
navigate(`/agents${nextSearch}`); navigate(`/agents${nextSearch}`);
}; };
const title = mode === 'create' ? '新建Agent' : '编辑Agent';
const stewardManagedUserLabel = detail?.managed_user?.user_name ?? form.managedUserName ?? STEWARD_MANAGED_USER_FALLBACK;
const currentManagedOption = form.managedUserId != null && form.managedUserName
? [{
label: form.managedUserName,
value: buildCurrentManagedEmployeeValue(form.managedUserId),
}]
: [];
const employeeOptions = [
...currentManagedOption,
...employees.map((employee) => ({
label: employee.agent_count > 0 ? `${employee.employee_name}(已挂载Agent)` : employee.employee_name,
value: buildEmployeeValue(employee),
disabled: !canSelectEmployee(employee, mode, agentId),
})),
];
const fetchEmployees = () => {
setEmployeesError(false);
getEmployeeMounts()
.then((response) => {
setEmployees(response.employees);
})
.catch(() => {
setEmployeesError(true);
});
};
const skillOptions = skills.map((skill) => ({
label: skill.skill_name,
value: skill.skill_code,
}));
const fetchSkills = () => {
setSkillsError(false);
getSkillList()
.then((response) => {
setSkills(response.list);
})
.catch(() => {
setSkillsError(true);
});
};
const fields: BusinessFormField[] = [
{
key: 'name',
label: 'Agent名称',
type: 'input',
required: true,
disabled: isSteward,
maxLength: 50,
validator: (value) => {
if (isSteward) return undefined;
return String(value ?? '').trim() ? undefined : '请输入 Agent 名称';
},
},
{
key: 'positionIds',
label: '所属岗位',
type: 'custom',
required: !isSteward,
validator: (value) => {
if (isSteward) return undefined;
return isArrayValue(value) && value.length > 0 ? undefined : '请选择所属岗位';
},
render: ({ values, setValue }) => {
if (positionsError) {
return (
<StatePlaceholder
state="error"
title="岗位选项加载失败"
description="请重试加载岗位选项"
primaryAction={<Button size="small" onClick={fetchPositions}>重试</Button>}
/>
);
}
if (isSteward) {
return (
<Input
aria-label="所属岗位"
className={fieldWidthClassName}
disabled
value={STEWARD_POSITION_LABEL}
/>
);
}
return (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
multiple
options={positionOptions.map((position) => ({ label: position.name, value: position.id }))}
value={isArrayValue(values.positionIds) ? values.positionIds.map(String) : []}
onChange={(value) => {
const nextValue = Array.isArray(value) ? value.map(Number) : [];
setValue(nextValue);
}}
/>
);
},
},
{
key: 'managedUserId',
label: '托管企微员工',
type: 'custom',
required: !isSteward,
validator: (value) => {
if (isSteward) return undefined;
return value ? undefined : '请选择托管企微员工';
},
render: ({ values, setValues }) => {
if (employeesError) {
return (
<StatePlaceholder
state="error"
title="托管企微员工加载失败"
description="请重试加载托管企微员工选项"
primaryAction={<Button size="small" onClick={fetchEmployees}>重试</Button>}
/>
);
}
if (isSteward) {
return (
<Input
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled
value={stewardManagedUserLabel}
/>
);
}
return (
<Select
aria-label="托管企微员工"
className={fieldWidthClassName}
options={employeeOptions}
placeholder="请选择托管企微员工"
value={values.managedEmployeeValue ?? undefined}
onChange={(value) => {
const selectedValue = String(value ?? '');
if (!selectedValue) {
setValues({
...values,
managedUserId: undefined,
managedEmployeeValue: undefined,
managedUserName: undefined,
}, 'managedUserId');
return;
}
const currentDetailManagedUser = detail?.managed_user;
if (currentDetailManagedUser && selectedValue === buildCurrentManagedEmployeeValue(currentDetailManagedUser.user_id)) {
setValues({
...values,
managedUserId: currentDetailManagedUser.user_id,
managedEmployeeValue: selectedValue,
managedUserName: currentDetailManagedUser.user_name,
}, 'managedUserId');
return;
}
const selectedEmployee = employees.find((employee) => buildEmployeeValue(employee) === selectedValue);
setValues({
...values,
managedUserId: selectedEmployee?.employee_id,
managedEmployeeValue: selectedValue,
managedUserName: selectedEmployee?.employee_name,
}, 'managedUserId');
}}
/>
);
},
},
{
key: 'description',
label: 'Agent描述',
type: 'textarea',
required: true,
maxLength: AGENT_DESCRIPTION_MAX_LENGTH,
rows: 5,
validator: (value) => {
const description = String(value ?? '').trim();
if (!description) return '请输入 Agent 描述';
if (description.length > AGENT_DESCRIPTION_MAX_LENGTH) return 'Agent 描述最多 500 字';
return undefined;
},
},
{
key: 'skillIds',
label: '绑定Skill',
type: 'custom',
required: !isSteward,
validator: (value) => {
if (isSteward) return undefined;
return isArrayValue(value) && value.length > 0 ? undefined : '请至少绑定一个 Skill';
},
render: ({ values, setValue }) => {
if (skillsError) {
return (
<StatePlaceholder
state="error"
title="Skill 选项加载失败"
description="请重试加载 Skill 选项"
primaryAction={<Button size="small" onClick={fetchSkills}>重试</Button>}
/>
);
}
return (
<Select
aria-label="绑定Skill"
className={fieldWidthClassName}
multiple
options={skillOptions}
value={isArrayValue(values.skillIds) ? values.skillIds : []}
onChange={(value) => setValue(Array.isArray(value) ? value : [])}
/>
);
},
},
{
key: 'status',
label: '状态',
type: 'switch',
required: true,
disabled: isSteward,
checkedValue: 'enable',
uncheckedValue: 'disable',
},
];
const validate = () => { const validate = () => {
const nextErrors: Partial<Record<keyof AgentFormState, string>> = {}; const nextErrors: BusinessFormErrors = {};
if (!isSteward && !form.name.trim()) nextErrors.name = '请输入 Agent 名称'; if (!isSteward && !form.name.trim()) nextErrors.name = '请输入 Agent 名称';
if (!isSteward && form.positionIds.length === 0) nextErrors.positionIds = '请选择所属岗位'; if (!isSteward && (!Array.isArray(form.positionIds) || form.positionIds.length === 0)) nextErrors.positionIds = '请选择所属岗位';
if (!isSteward && !form.managedEmployeeValue) nextErrors.managedUserId = '请选择托管企微员工'; if (!isSteward && !form.managedEmployeeValue) nextErrors.managedUserId = '请选择托管企微员工';
const description = form.description.trim(); const description = form.description.trim();
if (!description) nextErrors.description = '请输入 Agent 描述'; if (!description) nextErrors.description = '请输入 Agent 描述';
else if (description.length > AGENT_DESCRIPTION_MAX_LENGTH) nextErrors.description = 'Agent 描述最多 500 字'; else if (description.length > AGENT_DESCRIPTION_MAX_LENGTH) nextErrors.description = 'Agent 描述最多 500 字';
if (!isSteward && form.skillIds.length === 0) nextErrors.skillIds = '请至少绑定一个 Skill'; if (!isSteward && (!Array.isArray(form.skillIds) || form.skillIds.length === 0)) nextErrors.skillIds = '请至少绑定一个 Skill';
setErrors(nextErrors); setErrors(nextErrors);
return Object.keys(nextErrors).length === 0; return Object.keys(nextErrors).length === 0;
}; };
...@@ -339,56 +575,6 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -339,56 +575,6 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
} }
}; };
const title = mode === 'create' ? '新建Agent' : '编辑Agent';
const stewardManagedUserLabel = detail?.managed_user?.user_name ?? form.managedUserName ?? STEWARD_MANAGED_USER_FALLBACK;
const currentManagedOption = form.managedUserId != null && form.managedUserName
? [{
label: form.managedUserName,
value: buildCurrentManagedEmployeeValue(form.managedUserId),
}]
: [];
const employeeOptions = [
...currentManagedOption,
...employees.map((employee) => ({
label: employee.agent_count > 0 ? `${employee.employee_name}(已挂载Agent)` : employee.employee_name,
value: buildEmployeeValue(employee),
disabled: !canSelectEmployee(employee, mode, agentId),
})),
];
const fetchEmployees = () => {
setEmployeesLoading(true);
setEmployeesError(false);
getEmployeeMounts()
.then((response) => {
setEmployees(response.employees);
setEmployeesLoading(false);
})
.catch(() => {
setEmployeesError(true);
setEmployeesLoading(false);
});
};
const skillOptions = skills.map((skill) => ({
label: skill.skill_name,
value: skill.skill_code,
}));
const fetchSkills = () => {
setSkillsLoading(true);
setSkillsError(false);
getSkillList()
.then((response) => {
setSkills(response.list);
setSkillsLoading(false);
})
.catch(() => {
setSkillsError(true);
setSkillsLoading(false);
});
};
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
...@@ -414,161 +600,16 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -414,161 +600,16 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
) : null} ) : null}
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <BusinessForm
<FormItem label="Agent名称" labelAlign="left" requiredMark status={errors.name ? 'error' : undefined} tips={errors.name}> fields={fields}
<span className="grid gap-2"> values={form}
<Input errors={errors}
aria-label="Agent名称" labelAlign="left"
className={fieldWidthClassName} fieldWidth={fieldWidthClassName}
disabled={isSteward} onChange={(nextValues) => {
maxlength={50} setForm((current) => ({ ...current, ...nextValues } as AgentFormState));
allowInputOverMax }}
showLimitNumber />
value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/>
</span>
</FormItem>
<FormItem label="所属岗位" labelAlign="left" requiredMark status={errors.positionIds ? 'error' : undefined} tips={errors.positionIds}>
<span className="grid gap-2">
{positionsError ? (
<StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small" onClick={() => {
setPositionsLoading(true);
setPositionsError(false);
getPositionTagList({ page: 1, page_size: 100 })
.then((response) => {
setPositionTags(response.list);
setPositionsLoading(false);
})
.catch(() => {
setPositionsError(true);
setPositionsLoading(false);
});
}}>重试</Button>} />
) : isSteward ? (
// 管家 Agent 固定显示 "系统调度",使用 Input 确保显示固定文案
<Input
aria-label="所属岗位"
className={fieldWidthClassName}
disabled
value={STEWARD_POSITION_LABEL}
/>
) : (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
disabled={isSteward}
multiple
options={positionOptions.map((position) => ({ label: position.name, value: position.id }))}
value={form.positionIds.map(String)}
onChange={(value) => {
const nextValue = Array.isArray(value) ? value.map(Number) : [];
setForm((current) => ({ ...current, positionIds: nextValue }));
}}
/>
)}
</span>
</FormItem>
<FormItem
label="托管企微员工"
labelAlign="left"
requiredMark
status={errors.managedUserId ? 'error' : undefined} tips={errors.managedUserId}
>
<span className="grid gap-2">
{employeesError ? (
<StatePlaceholder state="error" title="托管企微员工加载失败" description="请重试加载托管企微员工选项" primaryAction={<Button size="small" onClick={fetchEmployees}>重试</Button>} />
) : isSteward ? (
<Input
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled
value={stewardManagedUserLabel}
/>
) : (
<Select
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled={isSteward}
options={employeeOptions}
placeholder="请选择托管企微员工"
value={form.managedEmployeeValue}
onChange={(value) => setForm((current) => {
const selectedValue = String(value ?? '');
if (!selectedValue) {
return {
...current,
managedUserId: undefined,
managedEmployeeValue: undefined,
managedUserName: undefined,
};
}
const currentDetailManagedUser = detail?.managed_user;
if (currentDetailManagedUser && selectedValue === buildCurrentManagedEmployeeValue(currentDetailManagedUser.user_id)) {
return {
...current,
managedUserId: currentDetailManagedUser.user_id,
managedEmployeeValue: selectedValue,
managedUserName: currentDetailManagedUser.user_name,
};
}
const selectedEmployee = employees.find((employee) => buildEmployeeValue(employee) === selectedValue);
return {
...current,
managedUserId: selectedEmployee?.employee_id,
managedEmployeeValue: selectedValue,
managedUserName: selectedEmployee?.employee_name,
};
})}
/>
)}
</span>
</FormItem>
<FormItem label="Agent描述" labelAlign="left" requiredMark status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea
aria-label="Agent描述"
className={fieldWidthClassName}
maxlength={AGENT_DESCRIPTION_MAX_LENGTH}
allowInputOverMax
rows={5}
count
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
<FormItem label="绑定Skill" labelAlign="left" requiredMark={!isSteward} status={errors.skillIds ? 'error' : undefined} tips={errors.skillIds}>
<span className="grid gap-2">
{skillsError ? (
<StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small" onClick={fetchSkills}>重试</Button>} />
) : (
<Select
aria-label="绑定Skill"
className={fieldWidthClassName}
multiple
options={skillOptions}
value={form.skillIds}
onChange={(value) => setForm((current) => ({ ...current, skillIds: Array.isArray(value) ? value : [] }))}
/>
)}
</span>
</FormItem>
<FormItem label="状态" labelAlign="left" requiredMark>
<Switch
aria-label="状态"
value={isSteward ? true : form.status === 'enable'}
disabled={isSteward}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/>
</FormItem>
</div>
</div> </div>
</section> </section>
); );
......
...@@ -61,6 +61,14 @@ function setupCreatePageMocks() { ...@@ -61,6 +61,14 @@ function setupCreatePageMocks() {
}); });
} }
function getControlHolder(name: string) {
const holder = screen.getByTestId(`business-form-control-holder-${name}`);
if (!holder) {
throw new Error(`Control holder ${name} was not found`);
}
return holder as HTMLElement;
}
describe('Channel code create page', () => { describe('Channel code create page', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -234,6 +242,11 @@ describe('Channel code create page', () => { ...@@ -234,6 +242,11 @@ describe('Channel code create page', () => {
expect(screen.getByRole('combobox', { name: '对应岗位' })).toBeInTheDocument(); expect(screen.getByRole('combobox', { name: '对应岗位' })).toBeInTheDocument();
expect(screen.getByLabelText('活码描述')).toBeInTheDocument(); expect(screen.getByLabelText('活码描述')).toBeInTheDocument();
expect(screen.getByLabelText('自动欢迎语')).toBeInTheDocument(); expect(screen.getByLabelText('自动欢迎语')).toBeInTheDocument();
expect(getControlHolder('qrcode_name')).toHaveStyle({ width: '100%', maxWidth: '450px' });
expect(getControlHolder('position_code')).toHaveStyle({ width: '100%', maxWidth: '450px' });
expect(getControlHolder('employee_id')).toHaveStyle({ width: '100%', maxWidth: '450px' });
expect(getControlHolder('description')).toHaveStyle({ width: '100%', maxWidth: '450px' });
expect(getControlHolder('welcome_message')).toHaveStyle({ width: '100%', maxWidth: '450px' });
// 状态编辑控件不再渲染 // 状态编辑控件不再渲染
expect(screen.queryByRole('switch', { name: '状态' })).not.toBeInTheDocument(); expect(screen.queryByRole('switch', { name: '状态' })).not.toBeInTheDocument();
}); });
...@@ -258,9 +271,11 @@ describe('Channel code create page', () => { ...@@ -258,9 +271,11 @@ describe('Channel code create page', () => {
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请输入活码名称')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('请对应岗位')).toBeInTheDocument(); expect(screen.getByText('请输入活码名称')).toBeInTheDocument();
expect(screen.getByText('请选择承接员工')).toBeInTheDocument(); expect(screen.getByText('请对应岗位')).toBeInTheDocument();
expect(screen.getByText('请选择承接员工')).toBeInTheDocument();
});
}); });
it('validates description max length', async () => { it('validates description max length', async () => {
...@@ -286,7 +301,9 @@ describe('Channel code create page', () => { ...@@ -286,7 +301,9 @@ describe('Channel code create page', () => {
fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: longDescription } }); fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: longDescription } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('活码描述最多200字')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('活码描述最多200字')).toBeInTheDocument();
});
}); });
it('validates welcome message max length', async () => { it('validates welcome message max length', async () => {
...@@ -312,7 +329,9 @@ describe('Channel code create page', () => { ...@@ -312,7 +329,9 @@ describe('Channel code create page', () => {
fireEvent.change(screen.getByLabelText('自动欢迎语'), { target: { value: longMessage } }); fireEvent.change(screen.getByLabelText('自动欢迎语'), { target: { value: longMessage } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('自动欢迎语最多500字')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('自动欢迎语最多500字')).toBeInTheDocument();
});
}); });
// TDD: 新增页不展示状态编辑项 // TDD: 新增页不展示状态编辑项
...@@ -1276,6 +1295,80 @@ describe('Channel code edit page', () => { ...@@ -1276,6 +1295,80 @@ describe('Channel code edit page', () => {
expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument();
}); });
await waitFor(() => expect(screen.getByLabelText('活码名称')).toHaveValue('店销顾问渠道活码')); await waitFor(() => expect(screen.getByLabelText('活码名称')).toHaveValue('店销顾问渠道活码'));
expect(screen.getByLabelText('对应岗位')).toHaveValue('驻店销售岗');
expect(screen.getByLabelText('对应岗位')).toBeDisabled();
expect(screen.getByText('DSC-QR-001')).toBeInTheDocument();
expect(screen.getByText('张小萌')).toBeInTheDocument();
expect(screen.getByText('店销助手Agent、管家Agent')).toBeInTheDocument();
});
it('echoes position object name in the disabled edit field', async () => {
vi.mocked(getChannelQRCodeDetail).mockResolvedValueOnce({
qrcode_id: 1,
employee_id: 'emp_001',
qrcode_name: '研发使用活码',
employee_name: '杨同学',
position_code: 'position_b8b2e6',
position: { name: '后端开发工程师' },
channel_code: 'position_b8b2e6',
qrcode_url: 'https://cdn.weixin.qq.com/qrcode/test.png',
agent_ids: [1],
agent_names: ['管家 Agent'],
status: 'enable',
remark: '',
welcome_message: '杨同学欢迎你!',
created_at: '2026-05-15T10:00:00Z',
created_by: 'admin',
} as any);
renderChannelCodes('/channel-codes/1/edit');
await waitFor(() => {
expect(screen.getByLabelText('对应岗位')).toHaveValue('后端开发工程师');
});
expect(screen.getByLabelText('对应岗位')).toBeDisabled();
});
it('orders edit fields to match the design reference', async () => {
vi.mocked(getChannelQRCodeDetail).mockResolvedValueOnce({
qrcode_id: 1,
employee_id: 'emp_001',
qrcode_name: '店销顾问渠道活码',
employee_name: '张小萌',
position_code: 'store_sales',
position_name: '驻店销售岗',
channel_code: 'DSC-QR-001',
qrcode_url: 'https://cdn.weixin.qq.com/qrcode/test.png',
agent_ids: [1, 2],
agent_names: ['店销助手Agent', '管家Agent'],
status: 'enable',
remark: '备注',
welcome_message: '欢迎',
created_at: '2026-05-15T10:00:00Z',
created_by: 'admin',
});
renderChannelCodes('/channel-codes/1/edit');
await waitFor(() => {
expect(screen.getByLabelText('活码名称')).toBeInTheDocument();
});
const orderedNodes = [
screen.getByLabelText('活码名称'),
screen.getByLabelText('对应岗位'),
screen.getByText('DSC-QR-001'),
screen.getByText('张小萌'),
screen.getByText('店销助手Agent、管家Agent'),
screen.getByLabelText('活码描述'),
screen.getByLabelText('自动欢迎语'),
];
for (let index = 0; index < orderedNodes.length - 1; index += 1) {
expect(
orderedNodes[index].compareDocumentPosition(orderedNodes[index + 1]) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
}
}); });
it('always fetches detail when entering edit page even if route state already has code data', async () => { it('always fetches detail when entering edit page even if route state already has code data', async () => {
...@@ -1353,6 +1446,7 @@ describe('Channel code edit page', () => { ...@@ -1353,6 +1446,7 @@ describe('Channel code edit page', () => {
}); });
expect(screen.getByLabelText('对应岗位')).toBeDisabled(); expect(screen.getByLabelText('对应岗位')).toBeDisabled();
expect(screen.getByLabelText('对应岗位')).toHaveValue('驻店销售岗');
expect(screen.getByText('DSC-QR-001')).toBeInTheDocument(); expect(screen.getByText('DSC-QR-001')).toBeInTheDocument();
}); });
......
import { useState } from 'react'; import { useState } from 'react';
import { flushSync } from 'react-dom';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { StatePlaceholder } from '@gl/business-components'; import {
BusinessForm,
StatePlaceholder,
validateBusinessForm,
type BusinessFormErrors,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
import { Button } from 'tdesign-react'; import { Button } from 'tdesign-react';
import { FormItem, Input, Select, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getChannelQRCodeDetail, getChannelQRCodeDetail,
createChannelQRCode, createChannelQRCode,
...@@ -12,16 +19,14 @@ import { ...@@ -12,16 +19,14 @@ import {
type ChannelQRCodeDetail, type ChannelQRCodeDetail,
type ChannelQRCodeStatus, type ChannelQRCodeStatus,
type EmployeeMountsResponse, type EmployeeMountsResponse,
type EmployeeMountItem,
} from '../../api/channelCode'; } from '../../api/channelCode';
import { import {
getPositionTagList, getPositionTagList,
type PositionTagListItem, type PositionTagListItem,
} from '../../api/positionTag'; } from '../../api/positionTag';
import { useMessage } from '../../hooks/useMessage';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
interface ChannelCodeFormState { interface ChannelCodeFormState extends BusinessFormValues {
qrcode_name: string; qrcode_name: string;
position_code: string; position_code: string;
employee_id: string; employee_id: string;
...@@ -30,32 +35,50 @@ interface ChannelCodeFormState { ...@@ -30,32 +35,50 @@ interface ChannelCodeFormState {
description: string; description: string;
welcome_message: string; welcome_message: string;
status: ChannelQRCodeStatus; status: ChannelQRCodeStatus;
} position_name?: string;
interface ChannelCodeFormErrors {
qrcode_name?: string;
position_code?: string;
employee_id?: string;
description?: string;
welcome_message?: string;
} }
interface SaveNotice { interface SaveNotice {
type: 'error'; type: 'error' | 'success';
message: string; message: string;
} }
function readString(value: unknown) {
return typeof value === 'string' ? value : '';
}
function readRecord(value: unknown) {
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
function resolvePositionName(code?: ChannelQRCodeDetail) {
if (!code) return '';
const position = readRecord(code.position);
const positionTag = readRecord(code.position_tag);
return readString(code.position_name)
|| readString(code.positionName)
|| readString(code.position_tag_name)
|| readString(position.name)
|| readString(position.position_name)
|| readString(positionTag.name)
|| readString(positionTag.position_name)
|| readString(code.position_code);
}
function buildInitialFormState(code?: ChannelQRCodeDetail): ChannelCodeFormState { function buildInitialFormState(code?: ChannelQRCodeDetail): ChannelCodeFormState {
return { return {
qrcode_name: code?.qrcode_name ?? '', qrcode_name: code?.qrcode_name ?? '',
position_code: '', position_code: code?.position_code ?? '',
employee_id: '', employee_id: code?.employee_id ?? '',
employee_name: '', employee_name: code?.employee_name ?? '',
wechat_user_id: '', wechat_user_id: '',
description: code?.remark ?? '', description: code?.remark ?? '',
welcome_message: code?.welcome_message ?? '', welcome_message: code?.welcome_message ?? '',
// 新增和编辑都使用启用状态,不提供停用入口 // 新增和编辑都使用启用状态,不提供停用入口
status: 'enable', status: 'enable',
position_name: resolvePositionName(code),
}; };
} }
...@@ -101,35 +124,30 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -101,35 +124,30 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const location = useLocation(); const location = useLocation();
const params = useParams(); const params = useParams();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const message = useMessage();
const routeState = readChannelCodeListRouteState(searchParams); const routeState = readChannelCodeListRouteState(searchParams);
const routeCode = (location.state as { code?: ChannelQRCodeDetail } | null)?.code; const routeCode = (location.state as { code?: ChannelQRCodeDetail } | null)?.code;
const [loading, setLoading] = useState(mode === 'edit' && !routeCode); const [loading, setLoading] = useState(mode === 'edit' && !routeCode);
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [currentCode, setCurrentCode] = useState<ChannelQRCodeDetail | undefined>(() => routeCode as ChannelQRCodeDetail | undefined); const [currentCode, setCurrentCode] = useState<ChannelQRCodeDetail | undefined>(() => routeCode as ChannelQRCodeDetail | undefined);
const [form, setForm] = useState<ChannelCodeFormState>(() => buildInitialFormState(currentCode)); const [form, setForm] = useState<ChannelCodeFormState>(() => buildInitialFormState(currentCode));
const [errors, setErrors] = useState<ChannelCodeFormErrors>({}); const [errors, setErrors] = useState<BusinessFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null); const [notice, setNotice] = useState<SaveNotice | null>(null);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const fieldWidthClassName = 'w-full max-w-[450px]'; const fieldWidth = 450;
// For create mode: position and employee selection // For create mode: position and employee selection
const [positions, setPositions] = useState<PositionTagListItem[]>([]); const [positions, setPositions] = useState<PositionTagListItem[]>([]);
const [positionsLoading, setPositionsLoading] = useState(false);
const [employeeMounts, setEmployeeMounts] = useState<EmployeeMountsResponse | null>(null); const [employeeMounts, setEmployeeMounts] = useState<EmployeeMountsResponse | null>(null);
const [employeeMountsLoading, setEmployeeMountsLoading] = useState(false);
// Load position list for create mode // Load position list for create mode
useDeferredEffect(() => { useDeferredEffect(() => {
if (mode === 'create') { if (mode === 'create') {
setPositionsLoading(true);
getPositionTagList({ page: 1, page_size: 100 }) getPositionTagList({ page: 1, page_size: 100 })
.then((response) => { .then((response) => {
setPositions(response.list); setPositions(response.list);
setPositionsLoading(false);
}) })
.catch(() => { .catch(() => {
setPositionsLoading(false); setPositions([]);
}); });
} }
}, [mode]); }, [mode]);
...@@ -137,14 +155,12 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -137,14 +155,12 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
// Load employees mounts for create mode // Load employees mounts for create mode
useDeferredEffect(() => { useDeferredEffect(() => {
if (mode === 'create') { if (mode === 'create') {
setEmployeeMountsLoading(true);
getEmployeeMounts() getEmployeeMounts()
.then((response) => { .then((response) => {
setEmployeeMounts(response); setEmployeeMounts(response);
setEmployeeMountsLoading(false);
}) })
.catch(() => { .catch(() => {
setEmployeeMountsLoading(false); setEmployeeMounts(null);
}); });
} }
}, [mode]); }, [mode]);
...@@ -170,6 +186,159 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -170,6 +186,159 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
navigate(`/channel-codes${buildChannelCodeListSearch(routeState)}`); navigate(`/channel-codes${buildChannelCodeListSearch(routeState)}`);
}; };
const createFields: BusinessFormField[] = [
{
key: 'qrcode_name',
label: '活码名称',
type: 'input',
required: true,
maxLength: 50,
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (!text) return '请输入活码名称';
return undefined;
},
},
{
key: 'position_code',
label: '对应岗位',
type: 'select',
required: true,
options: positions.map((p) => ({
value: p.code,
label: (p.qrcode_channel_count ?? 0) > 0 ? `${p.name}(该岗位已绑定活码)` : p.name,
disabled: (p.qrcode_channel_count ?? 0) > 0,
})),
placeholder: '请选择岗位',
validator: (value) => (value ? undefined : '请对应岗位'),
onChange: (value, context) => {
const selectedPosition = positions.find((p) => p.code === value);
return {
...context.values,
position_code: String(value ?? ''),
employee_id: '',
employee_name: '',
wechat_user_id: '',
position_name: selectedPosition?.name ?? '',
};
},
},
{
key: 'channel_code',
label: '渠道编码',
type: 'displayText',
visible: (values) => Boolean(values.position_code),
render: (_, values) => (typeof values.position_code === 'string' && values.position_code ? values.position_code : '-'),
},
{
key: 'agent_names',
label: '关联 Agent',
type: 'displayText',
visible: (values) => Boolean(values.position_code),
render: (_, values) => {
const agentNames = (positions.find((p) => p.code === values.position_code)?.agents ?? []).map((a) => a.name).join('、');
return agentNames || '-';
},
},
{
key: 'employee_id',
label: '承接员工',
type: 'select',
required: true,
validator: (value) => (value ? undefined : '请选择承接员工'),
options: (employeeMounts?.employees ?? []).map((e) => ({
value: e.employee_id,
label: e.qrcode_count > 0 ? `${e.employee_name}(该员工已绑定活码)` : e.employee_name,
disabled: e.qrcode_count > 0,
})),
placeholder: '请选择承接员工',
onChange: (value, context) => {
const selected = (employeeMounts?.employees ?? []).find((e) => e.employee_id === value);
return {
...context.values,
employee_id: String(value ?? ''),
employee_name: selected?.employee_name ?? '',
wechat_user_id: selected?.wechat_user_id ?? '',
position_code: selected?.position_code ?? String(context.values.position_code ?? ''),
};
},
},
{
key: 'description',
label: '活码描述',
type: 'textarea',
maxLength: 200,
rows: 3,
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (text.length > 200) return '活码描述最多200字';
return undefined;
},
},
{
key: 'welcome_message',
label: '自动欢迎语',
type: 'textarea',
maxLength: 500,
rows: 3,
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (text.length > 500) return '自动欢迎语最多500字';
return undefined;
},
},
];
const editFields: BusinessFormField[] = [
{
key: 'qrcode_name',
label: '活码名称',
type: 'input',
required: true,
maxLength: 50,
},
{
key: 'position_name',
label: '对应岗位',
type: 'input',
disabled: true,
},
{
key: 'channel_code',
label: '渠道编码',
type: 'displayText',
render: () => currentCode?.channel_code ?? '-',
},
{
key: 'employee_name',
label: '承接员工',
type: 'displayText',
render: () => currentCode?.employee_name ?? '-',
},
{
key: 'agent_names',
label: '关联 Agent',
type: 'displayText',
render: () => (currentCode?.agent_names ?? []).join('、') || '-',
},
{
key: 'description',
label: '活码描述',
type: 'textarea',
maxLength: 200,
rows: 3,
},
{
key: 'welcome_message',
label: '自动欢迎语',
type: 'textarea',
maxLength: 500,
rows: 3,
},
];
const fields = mode === 'create' ? createFields : editFields;
if (loading) { if (loading) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
...@@ -178,7 +347,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -178,7 +347,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
); );
} }
if (mode === 'edit' && !currentCode) { if (loadError || (mode === 'edit' && !currentCode)) {
return ( return (
<StatePlaceholder <StatePlaceholder
state="error" state="error"
...@@ -189,41 +358,12 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -189,41 +358,12 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
); );
} }
const validate = () => {
const nextErrors: ChannelCodeFormErrors = {};
const trimmedName = form.qrcode_name.trim();
const trimmedDescription = form.description.trim();
const trimmedWelcomeMessage = form.welcome_message.trim();
if (!trimmedName) {
nextErrors.qrcode_name = '请输入活码名称';
} else if (trimmedName.length > 50) {
nextErrors.qrcode_name = '活码名称最多50字';
}
if (mode === 'create' && !form.position_code) {
nextErrors.position_code = '请对应岗位';
}
if (mode === 'create' && !form.employee_id) {
nextErrors.employee_id = '请选择承接员工';
}
if (trimmedDescription.length > 200) {
nextErrors.description = '活码描述最多200字';
}
if (trimmedWelcomeMessage.length > 500) {
nextErrors.welcome_message = '自动欢迎语最多500字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = async () => { const handleSave = async () => {
setNotice(null); setNotice(null);
if (!validate()) {
const validation = await validateBusinessForm(fields, form);
setErrors(validation);
if (Object.values(validation).some(Boolean)) {
return; return;
} }
...@@ -247,7 +387,9 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -247,7 +387,9 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
remark: form.description || undefined, remark: form.description || undefined,
welcome_message: form.welcome_message || undefined, welcome_message: form.welcome_message || undefined,
}); });
message.success('保存成功'); flushSync(() => {
setNotice({ type: 'success', message: '保存成功' });
});
} }
// Ensure at least 2 seconds stay on page after create success // Ensure at least 2 seconds stay on page after create success
...@@ -288,154 +430,29 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -288,154 +430,29 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</header> </header>
{notice ? ( {notice ? (
<div <div
className="rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] px-4 py-3 text-sm text-[var(--gl-color-danger-text)]" className={
role="alert" notice.type === 'success'
aria-label={notice.message} ? 'rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-success-border)] bg-[var(--gl-color-success-bg)] px-4 py-3 text-sm text-[var(--gl-color-success-text)]'
> : 'rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] px-4 py-3 text-sm text-[var(--gl-color-danger-text)]'
}
role="alert"
aria-label={notice.message}
>
{notice.message} {notice.message}
</div> </div>
) : null} ) : null}
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="活码名称" labelAlign="left" requiredMark status={errors.qrcode_name ? 'error' : undefined} tips={errors.qrcode_name}> <BusinessForm
<Input fields={fields}
aria-label="活码名称" values={form}
className={fieldWidthClassName} errors={errors}
maxlength={50} fieldWidth={fieldWidth}
allowInputOverMax labelAlign="left"
showLimitNumber onChange={(nextValues) => setForm(nextValues as ChannelCodeFormState)}
value={form.qrcode_name} />
onChange={(value) => setForm((current) => ({ ...current, qrcode_name: value }))}
/>
</FormItem>
{mode === 'create' ? (
<>
<FormItem label="对应岗位" labelAlign="left" requiredMark status={errors.position_code ? 'error' : undefined} tips={errors.position_code}>
<Select
aria-label="对应岗位"
className={fieldWidthClassName}
options={positions.map((p) => ({
value: p.code,
label: (p.qrcode_channel_count ?? 0) > 0 ? `${p.name}(该岗位已绑定活码)` : p.name,
disabled: (p.qrcode_channel_count ?? 0) > 0,
}))}
placeholder="请选择岗位"
value={form.position_code}
onChange={(value) => {
const selectedPosition = positions.find((p) => p.code === value);
setForm((current) => ({
...current,
position_code: String(value ?? ''),
employee_id: '',
employee_name: '',
wechat_user_id: '',
}));
}}
/>
</FormItem>
{form.position_code ? (
<>
<FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}>
{form.position_code}
</div>
</FormItem>
<FormItem label="关联 Agent" labelAlign="left">
<div className={fieldWidthClassName}>
{(positions.find((p) => p.code === form.position_code)?.agents ?? []).map((a) => a.name).join('、') || '-'}
</div>
</FormItem>
</>
) : null}
<FormItem label="承接员工" labelAlign="left" requiredMark status={errors.employee_id ? 'error' : undefined} tips={errors.employee_id}>
<Select
aria-label="承接员工"
className={fieldWidthClassName}
options={(employeeMounts?.employees ?? []).map((e) => ({
value: e.employee_id,
label: e.qrcode_count > 0 ? `${e.employee_name}(该员工已绑定活码)` : e.employee_name,
disabled: e.qrcode_count > 0,
}))}
placeholder="请选择承接员工"
value={form.employee_id}
onChange={(value) => {
const selected = (employeeMounts?.employees ?? []).find((e) => e.employee_id === value);
setForm((current) => ({
...current,
employee_id: String(value ?? ''),
employee_name: selected?.employee_name ?? '',
wechat_user_id: selected?.wechat_user_id ?? '',
position_code: selected?.position_code ?? current.position_code,
}));
}}
/>
</FormItem>
</>
) : null}
{currentCode ? (
<>
<FormItem label="对应岗位" labelAlign="left">
<Input
aria-label="对应岗位"
className={fieldWidthClassName}
disabled
value={currentCode.position_name ?? ''}
/>
</FormItem>
<FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}>
{currentCode.channel_code ?? ''}
</div>
</FormItem>
<FormItem label="承接员工" labelAlign="left">
<div className={fieldWidthClassName}>
{currentCode.employee_name ?? ''}
</div>
</FormItem>
<FormItem label="关联 Agent" labelAlign="left">
<div className={fieldWidthClassName}>
{(currentCode.agent_names ?? []).join('、') || '-'}
</div>
</FormItem>
</>
) : null}
<FormItem label="活码描述" labelAlign="left" status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea
aria-label="活码描述"
className={fieldWidthClassName}
maxlength={200}
allowInputOverMax
rows={3}
count
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
<FormItem label="自动欢迎语" labelAlign="left" status={errors.welcome_message ? 'error' : undefined} tips={errors.welcome_message}>
<Textarea
aria-label="自动欢迎语"
className={fieldWidthClassName}
maxlength={500}
allowInputOverMax
rows={3}
count
value={form.welcome_message}
onChange={(value) => setForm((current) => ({ ...current, welcome_message: value }))}
/>
</FormItem>
{/* 状态编辑控件已移除,新增和编辑都默认使用启用状态 */}
</div> </div>
</div> </div>
</section> </section>
......
...@@ -164,6 +164,7 @@ describe('Channel code list page', () => { ...@@ -164,6 +164,7 @@ describe('Channel code list page', () => {
expect(within(firstRow).getByText('店销顾问渠道活码')).toBeInTheDocument(); expect(within(firstRow).getByText('店销顾问渠道活码')).toBeInTheDocument();
// 承接员工应该读取 employee_name 字段 // 承接员工应该读取 employee_name 字段
expect(within(firstRow).getByText('张小萌')).toBeInTheDocument(); expect(within(firstRow).getByText('张小萌')).toBeInTheDocument();
expect(within(firstRow).getByText('店销助手Agent、管家Agent').className).toContain('cellText');
const statusTag = within(firstRow).getByText('启用'); const statusTag = within(firstRow).getByText('启用');
// 状态应该使用 Tag 标签组件 // 状态应该使用 Tag 标签组件
......
...@@ -145,8 +145,9 @@ export function ChannelCodeListPage() { ...@@ -145,8 +145,9 @@ export function ChannelCodeListPage() {
{ {
title: '关联 Agent', title: '关联 Agent',
colKey: 'agent_names_preview', colKey: 'agent_names_preview',
cell: ({ row }) => { ellipsisTooltip: true,
const agents = row.agent_names_preview ?? []; tooltipValue: ({ agent_names_preview }) => {
const agents = agent_names_preview ?? [];
return agents.length > 0 ? agents.join('、') : '-'; return agents.length > 0 ? agents.join('、') : '-';
}, },
}, },
......
...@@ -137,7 +137,8 @@ describe('ComponentsDemoPage', () => { ...@@ -137,7 +137,8 @@ describe('ComponentsDemoPage', () => {
expect(scoped.getByLabelText('锁定项')).toBeDisabled(); expect(scoped.getByLabelText('锁定项')).toBeDisabled();
fireEvent.change(scoped.getByLabelText('展示模式'), { target: { value: 'read' } }); fireEvent.change(scoped.getByLabelText('展示模式'), { target: { value: 'read' } });
expect(scoped.getByLabelText('只读项')).toHaveAttribute('readonly'); expect(scoped.queryByLabelText('只读项')).not.toBeInTheDocument();
expect(scoped.getByText('只读内容')).toBeInTheDocument();
fireEvent.click(scoped.getByRole('button', { name: '填充摘要' })); fireEvent.click(scoped.getByRole('button', { name: '填充摘要' }));
expect(scoped.getByText('摘要:新合同')).toBeInTheDocument(); expect(scoped.getByText('摘要:新合同')).toBeInTheDocument();
......
import { useState } from 'react'; import { useState } from 'react';
import { MediaWall } from '@gl/business-components'; import {
BusinessForm,
MediaWall,
type BusinessFormErrors,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
import { Button, Dialog } from 'tdesign-react'; import { Button, Dialog } from 'tdesign-react';
import { FormItem, Input, Select } from '../../components/TDesignAccessibleControls';
import { import {
getAgentDisplayDetail, getAgentDisplayDetail,
updateAgentDisplayConfig, updateAgentDisplayConfig,
...@@ -20,7 +25,7 @@ interface EditModalProps { ...@@ -20,7 +25,7 @@ interface EditModalProps {
onSaveSuccess: () => void; onSaveSuccess: () => void;
} }
interface EditFormState { interface EditFormState extends BusinessFormValues {
speech_title: string; speech_title: string;
speech_content: string; speech_content: string;
sort_order: number; sort_order: number;
...@@ -273,6 +278,83 @@ export function AgentDisplayConfigEditModal({ ...@@ -273,6 +278,83 @@ export function AgentDisplayConfigEditModal({
? [{ id: 'icon', type: 'image', src: form.icon_url, alt: 'Agent图标' }] ? [{ id: 'icon', type: 'image', src: form.icon_url, alt: 'Agent图标' }]
: []; : [];
const businessFormErrors: BusinessFormErrors = {
agent_name: errors.speech_title,
icon_url: errors.icon_url || errors.upload_icon,
speech_content: errors.speech_content,
media_url: errors.media_url || errors.upload_media,
sort_order: errors.sort_order,
};
const fields: BusinessFormField[] = [
{
key: 'agent_name',
label: 'Agent 名称',
type: 'input',
required: true,
disabled: true,
},
{
key: 'icon_url',
label: '图标',
type: 'custom',
required: true,
helperText: '支持图片,推荐 1:1,最大 2MB',
render: () => (
<MediaWall
accept={ICON_ACCEPT}
maxCount={1}
multiple={false}
items={iconItems}
onSelectFiles={handleUploadIcon}
onRemove={handleRemoveIcon}
/>
),
},
{
key: 'speech_content',
label: 'Agent 概述',
type: 'input',
required: true,
placeholder: '请输入Agent概述',
maxLength: 100,
},
{
key: 'media_url',
label: '展示素材',
type: 'custom',
required: true,
helperText: '支持图片、视频、GIF,推荐 1:1,最大 20MB',
render: () => (
<MediaWall
accept="image/png,image/jpeg,image/jpg,image/gif,image/webp,video/mp4,video/quicktime,video/x-msvideo,video/webm"
maxCount={1}
multiple={false}
items={mediaItems}
onSelectFiles={handleUploadMedia}
onRemove={handleRemoveMedia}
/>
),
},
{
key: 'sort_order',
label: '展示排序',
type: 'numberInput',
required: true,
placeholder: '请输入展示排序',
},
{
key: 'display_status',
label: '展示状态',
type: 'select',
required: true,
options: [
{ value: 'disable', label: '不展示' },
{ value: 'enable', label: '展示中' },
],
},
];
return ( return (
<Dialog <Dialog
visible={open} visible={open}
...@@ -301,80 +383,19 @@ export function AgentDisplayConfigEditModal({ ...@@ -301,80 +383,19 @@ export function AgentDisplayConfigEditModal({
加载中... 加载中...
</div> </div>
) : ( ) : (
<div className="grid gap-6 py-4"> <BusinessForm
<FormItem label="Agent 名称" labelAlign="left" requiredMark status={errors.speech_title ? 'error' : undefined} tips={errors.speech_title}> className="py-4"
<Input data-testid="agent-display-config-edit-form"
aria-label="Agent 名称" errors={businessFormErrors}
className="w-full max-w-[400px]" fieldWidth={400}
disabled fields={fields}
value={form.agent_name} labelAlign="left"
/> values={form}
</FormItem> onChange={(nextValues) => setForm((current) => ({
...current,
<FormItem label="图标" labelAlign="left" requiredMark status={errors.icon_url || errors.upload_icon ? 'error' : undefined} tips={errors.icon_url || errors.upload_icon}> ...nextValues,
<MediaWall } as EditFormState))}
accept={ICON_ACCEPT} />
maxCount={1}
multiple={false}
items={iconItems}
helperText="支持图片,推荐 1:1,最大 2MB"
onSelectFiles={handleUploadIcon}
onRemove={handleRemoveIcon}
/>
</FormItem>
<FormItem label="Agent 概述" labelAlign="left" requiredMark status={errors.speech_content ? 'error' : undefined} tips={errors.speech_content}>
<Input
aria-label="Agent 概述"
className="w-full max-w-[400px]"
placeholder="请输入Agent概述"
value={form.speech_content}
onChange={(value) => setForm((current) => ({ ...current, speech_content: value }))}
/>
</FormItem>
<FormItem label="展示素材" labelAlign="left" requiredMark status={errors.media_url || errors.upload_media ? 'error' : undefined} tips={errors.media_url || errors.upload_media}>
<MediaWall
accept="image/png,image/jpeg,image/jpg,image/gif,image/webp,video/mp4,video/quicktime,video/x-msvideo,video/webm"
maxCount={1}
multiple={false}
items={mediaItems}
helperText="支持图片、视频、GIF,推荐 1:1,最大 20MB"
onSelectFiles={handleUploadMedia}
onRemove={handleRemoveMedia}
/>
</FormItem>
<FormItem label="展示排序" labelAlign="left" requiredMark status={errors.sort_order ? 'error' : undefined} tips={errors.sort_order}>
<Input
aria-label="展示排序"
className="w-full max-w-[400px]"
type="number"
placeholder="请输入展示排序"
value={form.sort_order === undefined || (typeof form.sort_order === 'number' && isNaN(form.sort_order)) ? '' : String(form.sort_order)}
onChange={(value) => setForm((current) => ({
...current,
sort_order: value === '' ? undefined as unknown as number : Number(value),
}))}
/>
</FormItem>
<FormItem label="展示状态" labelAlign="left" requiredMark>
<Select
aria-label="展示状态"
className="w-full max-w-[400px]"
options={[
{ value: 'disable', label: '已下架' },
{ value: 'enable', label: '展示中' },
]}
value={form.display_status}
onChange={(value) => setForm((current) => ({
...current,
display_status: value as DisplayStatus,
}))}
/>
</FormItem>
</div>
)} )}
</Dialog> </Dialog>
); );
......
import { fireEvent, render, screen, within, waitFor } from '@testing-library/react'; import { fireEvent, render, screen, within, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -325,7 +326,7 @@ describe('Agent display config edit modal', () => { ...@@ -325,7 +326,7 @@ describe('Agent display config edit modal', () => {
expect(within(modal).getByText('展示排序')).toBeInTheDocument(); expect(within(modal).getByText('展示排序')).toBeInTheDocument();
}); });
it('shows 展示状态 field with 已下架 and 展示中 options only', () => { it('shows 展示状态 field with 不展示 and 展示中 options only', () => {
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
expect(within(modal).getByText('展示状态')).toBeInTheDocument(); expect(within(modal).getByText('展示状态')).toBeInTheDocument();
expect(within(modal).queryByText('已停用')).not.toBeInTheDocument(); expect(within(modal).queryByText('已停用')).not.toBeInTheDocument();
...@@ -344,9 +345,9 @@ describe('Agent display config edit modal', () => { ...@@ -344,9 +345,9 @@ describe('Agent display config edit modal', () => {
}); });
}); });
it('shows default display_status as 已下架 for unconfigured agent', () => { it('shows default display_status as 不展示 for unconfigured agent', () => {
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
expect(within(modal).getByRole('combobox', { name: '展示状态' })).toHaveAttribute('value', '已下架'); expect(within(modal).getByRole('combobox', { name: '展示状态' })).toHaveAttribute('value', '不展示');
}); });
it('shows empty icon for unconfigured agent', () => { it('shows empty icon for unconfigured agent', () => {
...@@ -387,31 +388,33 @@ describe('Agent display config edit modal', () => { ...@@ -387,31 +388,33 @@ describe('Agent display config edit modal', () => {
); );
}); });
it('validates speech_content max 100 chars', async () => { it('validates speech_content max 100 chars and shows length count', async () => {
const user = userEvent.setup();
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
const contentInput = within(modal).getByPlaceholderText('请输入Agent概述'); const contentInput = within(modal).getByPlaceholderText('请输入Agent概述');
const longContent = '这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容'; const longContent = '测'.repeat(101);
fireEvent.change(contentInput, { target: { value: longContent } }); await user.clear(contentInput);
fireEvent.click(within(modal).getByRole('button', { name: '确定' })); await user.type(contentInput, longContent);
await waitFor( expect(contentInput).toHaveValue('测'.repeat(100));
() => { expect(within(modal).getByText('100/100')).toBeInTheDocument();
expect(within(modal).getByText(/不能超过100字/)).toBeInTheDocument(); await user.click(within(modal).getByRole('button', { name: '确定' }));
}, expect(within(modal).queryByText(/不能超过100字/)).not.toBeInTheDocument();
{ timeout: 2000 },
);
}); });
it('validates sort_order 0-99', async () => { it('validates sort_order 0-99', async () => {
const user = userEvent.setup();
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
const inputs = within(modal).getAllByRole('spinbutton'); const inputs = within(modal).getAllByRole('spinbutton');
const sortInput = inputs[0]; const sortInput = inputs[0];
if (!sortInput) throw new Error('Sort input not found'); if (!sortInput) throw new Error('Sort input not found');
fireEvent.change(sortInput, { target: { value: '100' } }); await user.clear(sortInput);
await user.type(sortInput, '100');
const contentInput = within(modal).getByPlaceholderText('请输入Agent概述'); const contentInput = within(modal).getByPlaceholderText('请输入Agent概述');
fireEvent.change(contentInput, { target: { value: '测试概述' } }); await user.clear(contentInput);
fireEvent.click(within(modal).getByRole('button', { name: '确定' })); await user.type(contentInput, '测试概述');
await user.click(within(modal).getByRole('button', { name: '确定' }));
await waitFor( await waitFor(
() => { () => {
expect(within(modal).getByText(/0-99/)).toBeInTheDocument(); expect(within(modal).getByText(/0-99/)).toBeInTheDocument();
......
...@@ -20,7 +20,7 @@ function mapAgentStatusToText(status: AgentStatus): string { ...@@ -20,7 +20,7 @@ function mapAgentStatusToText(status: AgentStatus): string {
function getDisplayStatusTextForList(agentStatus: AgentStatus, displayStatus: DisplayStatus): string { function getDisplayStatusTextForList(agentStatus: AgentStatus, displayStatus: DisplayStatus): string {
if (agentStatus === 'disable') return '-'; if (agentStatus === 'disable') return '-';
return displayStatus === 'enable' ? '展示中' : '已下架'; return displayStatus === 'enable' ? '展示中' : '不展示';
} }
export function OfficialSiteAgentDisplayConfigPage() { export function OfficialSiteAgentDisplayConfigPage() {
...@@ -97,9 +97,8 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -97,9 +97,8 @@ export function OfficialSiteAgentDisplayConfigPage() {
{ {
title: 'Agent概述', title: 'Agent概述',
colKey: 'speech_content', colKey: 'speech_content',
cell: ({ row }) => ( ellipsisTooltip: true,
<span className="max-w-[200px] truncate">{row.speech_content || '-'}</span> tooltipValue: ({ speech_content }) => speech_content || '-',
),
}, },
{ {
title: '图标', title: '图标',
......
...@@ -124,18 +124,22 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -124,18 +124,22 @@ describe('OfficialSiteJobTabEditorPage', () => {
expect(screen.getAllByText('选择岗位后自动展示')).toHaveLength(3); expect(screen.getAllByText('选择岗位后自动展示')).toHaveLength(3);
}); });
it('validates position is required on save', () => { it('validates position is required on save', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请选择对应岗位')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('请选择对应岗位')).toBeInTheDocument();
});
}); });
it('validates tab order is 0-99 integer', () => { it('validates tab order is 0-99 integer', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '100' } }); fireEvent.change(orderInput, { target: { value: '100' } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('Tab排序请输入0-99的整数')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('Tab排序请输入0-99的整数')).toBeInTheDocument();
});
}); });
it('shows position select with available candidates (not duplicates)', async () => { it('shows position select with available candidates (not duplicates)', async () => {
...@@ -236,6 +240,13 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -236,6 +240,13 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
}); });
it('does not show employee role text in edit mode', async () => {
renderApp('/official-site/job-tabs/1/edit');
await screen.findByRole('heading', { name: '编辑岗位展示' });
expect(screen.queryByText('承接角色')).not.toBeInTheDocument();
expect(screen.queryByText('店销主管')).not.toBeInTheDocument();
});
it('allows editing tab order and saves successfully', async () => { it('allows editing tab order and saves successfully', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
// Find the number input and change its value // Find the number input and change its value
......
import { useState } from 'react'; import { useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button } from 'tdesign-react';
import { StatePlaceholder } from '@gl/business-components'; import {
import { FormItem, Input, Select, Textarea } from '../../components/TDesignAccessibleControls'; BusinessForm,
StatePlaceholder,
validateBusinessForm,
type BusinessFormErrors,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
import { Button } from 'tdesign-react';
import { import {
getOfficialSiteTabList, getOfficialSiteTabList,
getOfficialSiteTabDetail, getOfficialSiteTabDetail,
...@@ -18,7 +24,7 @@ import { ...@@ -18,7 +24,7 @@ import {
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
import { buildOfficialSiteJobTabListSearch, readOfficialSiteJobTabListRouteState } from './officialSiteJobTabRouteState'; import { buildOfficialSiteJobTabListSearch, readOfficialSiteJobTabListRouteState } from './officialSiteJobTabRouteState';
interface TabFormState { interface TabFormState extends BusinessFormValues {
position_code: string; position_code: string;
position_name: string; position_name: string;
qrcode_id: number; qrcode_id: number;
...@@ -32,13 +38,6 @@ interface TabFormState { ...@@ -32,13 +38,6 @@ interface TabFormState {
sub_title: string; sub_title: string;
} }
interface TabFormErrors {
position_code?: string;
tab_order?: string;
main_title?: string;
sub_title?: string;
}
interface SaveNotice { interface SaveNotice {
type: 'error' | 'success'; type: 'error' | 'success';
message: string; message: string;
...@@ -55,7 +54,7 @@ function buildInitialFormState(tab?: OfficialSiteTabEditorItem): TabFormState { ...@@ -55,7 +54,7 @@ function buildInitialFormState(tab?: OfficialSiteTabEditorItem): TabFormState {
channel_code: '', channel_code: '',
employee_name: '', employee_name: '',
employee_role_text: '', employee_role_text: '',
tab_order: tab?.sort_order ?? undefined as unknown as number, tab_order: tab?.sort_order ?? 0,
display_status: tab?.display_status ?? 'enable', display_status: tab?.display_status ?? 'enable',
main_title: tab?.main_title ?? '', main_title: tab?.main_title ?? '',
sub_title: tab?.sub_title ?? '', sub_title: tab?.sub_title ?? '',
...@@ -74,12 +73,11 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -74,12 +73,11 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [currentTab, setCurrentTab] = useState<OfficialSiteTabEditorItem | undefined>(() => routeTab); const [currentTab, setCurrentTab] = useState<OfficialSiteTabEditorItem | undefined>(() => routeTab);
const [form, setForm] = useState<TabFormState>(() => buildInitialFormState(currentTab)); const [form, setForm] = useState<TabFormState>(() => buildInitialFormState(currentTab));
const [errors, setErrors] = useState<TabFormErrors>({}); const [errors, setErrors] = useState<BusinessFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null); const [notice, setNotice] = useState<SaveNotice | null>(null);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [availableQRCodes, setAvailableQRCodes] = useState<AvailableOfficialSiteQRCodeItem[]>([]); const [availableQRCodes, setAvailableQRCodes] = useState<AvailableOfficialSiteQRCodeItem[]>([]);
const [existingPositions, setExistingPositions] = useState<string[]>([]); const [existingPositions, setExistingPositions] = useState<string[]>([]);
const fieldWidthClassName = 'w-full max-w-[450px]';
useDeferredEffect(() => { useDeferredEffect(() => {
getAvailableQRCodes() getAvailableQRCodes()
...@@ -121,6 +119,200 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -121,6 +119,200 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
navigate(`/official-site/job-tabs${buildOfficialSiteJobTabListSearch(routeState)}`); navigate(`/official-site/job-tabs${buildOfficialSiteJobTabListSearch(routeState)}`);
}; };
const currentTabDetail = currentTab as OfficialSiteTabDetail | undefined;
const availableQRCodeOptions = availableQRCodes.filter((qr) => {
if (mode === 'edit') return true;
return !existingPositions.includes(qr.position_name);
});
const createFields: BusinessFormField[] = [
{
key: 'position_code',
label: '对应岗位',
type: 'select',
required: true,
options: availableQRCodeOptions.map((qr) => ({
value: String(qr.qrcode_id),
label: qr.position_name,
disabled: existingPositions.includes(qr.position_name) || qr.status === 'disable',
})),
placeholder: '请选择对应岗位',
validator: (value) => (value ? undefined : '请选择对应岗位'),
onChange: (value, context) => {
const qr = availableQRCodes.find((item) => item.qrcode_id === Number(value));
return {
...context.values,
position_code: qr?.channel_code ?? '',
position_name: qr?.position_name ?? '',
qrcode_id: qr?.qrcode_id ?? 0,
qrcode_name: qr?.qrcode_name ?? '',
channel_code: qr?.channel_code ?? '',
employee_name: qr?.employee_name ?? '',
employee_role_text: '',
};
},
},
{
key: 'qrcode_name',
label: '关联渠道活码',
type: 'displayText',
emptyText: '选择岗位后自动展示',
render: () => form.qrcode_name || '选择岗位后自动展示',
},
{
key: 'channel_code',
label: '渠道编码',
type: 'displayText',
emptyText: '选择岗位后自动展示',
render: () => form.channel_code || '选择岗位后自动展示',
},
{
key: 'employee_name',
label: '承接员工',
type: 'displayText',
emptyText: '选择岗位后自动展示',
render: () => form.employee_name || '选择岗位后自动展示',
},
{
key: 'main_title',
label: '岗位标题',
type: 'input',
required: true,
maxLength: 30,
placeholder: '请输入岗位标题',
helpText: '展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位',
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (!text) return '请输入岗位标题';
if (text.length > 30) return '岗位标题最多30字';
return undefined;
},
},
{
key: 'sub_title',
label: '岗位说明',
type: 'textarea',
required: true,
maxLength: 200,
rows: 4,
placeholder: '请输入岗位说明',
helpText: '展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值',
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (!text) return '请输入岗位说明';
if (text.length > 200) return '岗位说明最多200字';
return undefined;
},
},
{
key: 'tab_order',
label: 'Tab排序',
type: 'numberInput',
required: true,
precision: 0,
placeholder: '请输入Tab排序(0-99)',
validator: (value) => {
if (value === undefined || value === null || value === '') return 'Tab排序请输入0-99的整数';
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 99) {
return 'Tab排序请输入0-99的整数';
}
return undefined;
},
},
{
key: 'display_status',
label: '展示状态',
type: 'select',
options: [
{ value: 'enable', label: '展示中' },
{ value: 'disable', label: '已下架' },
],
},
];
const editFields: BusinessFormField[] = [
{
key: 'position_name',
label: '岗位标签',
type: 'input',
disabled: true,
},
{
key: 'qrcode_name',
label: '关联渠道活码',
type: 'displayText',
render: () => currentTabDetail?.qrcode_name ?? '-',
},
{
key: 'channel_code',
label: '渠道编码',
type: 'displayText',
render: () => currentTabDetail?.channel_code ?? '-',
},
{
key: 'employee_name',
label: '承接员工',
type: 'displayText',
render: () => currentTabDetail?.qrcode_employee_name || currentTabDetail?.employee_name || '-',
},
{
key: 'main_title',
label: '岗位标题',
type: 'input',
required: true,
maxLength: 30,
placeholder: '请输入岗位标题',
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (!text) return '请输入岗位标题';
if (text.length > 30) return '岗位标题最多30字';
return undefined;
},
},
{
key: 'sub_title',
label: '岗位说明',
type: 'textarea',
required: true,
maxLength: 200,
rows: 4,
placeholder: '请输入岗位说明',
validator: (value) => {
const text = typeof value === 'string' ? value : '';
if (!text) return '请输入岗位说明';
if (text.length > 200) return '岗位说明最多200字';
return undefined;
},
},
{
key: 'tab_order',
label: 'Tab排序',
type: 'numberInput',
required: true,
precision: 0,
placeholder: '请输入Tab排序(0-99)',
validator: (value) => {
if (value === undefined || value === null || value === '') return 'Tab排序请输入0-99的整数';
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 99) {
return 'Tab排序请输入0-99的整数';
}
return undefined;
},
},
{
key: 'display_status',
label: '展示状态',
type: 'select',
options: [
{ value: 'enable', label: '展示中' },
{ value: 'disable', label: '已下架' },
],
},
];
const fields = mode === 'create' ? createFields : editFields;
const sectionTitle = '岗位 AI 赋能介绍';
if (loading) { if (loading) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
...@@ -129,7 +321,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -129,7 +321,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
); );
} }
if (mode === 'edit' && !currentTab) { if (loadError || (mode === 'edit' && !currentTab)) {
return ( return (
<StatePlaceholder <StatePlaceholder
state="error" state="error"
...@@ -140,40 +332,12 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -140,40 +332,12 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
); );
} }
const selectedQRCode = availableQRCodes.find((qr) => qr.qrcode_id === form.qrcode_id);
const validate = () => {
const nextErrors: TabFormErrors = {};
const order = form.tab_order;
if (mode === 'create' && !form.position_code) {
nextErrors.position_code = '请选择对应岗位';
}
if (!Number.isInteger(order) || order < 0 || order > 99) {
nextErrors.tab_order = 'Tab排序请输入0-99的整数';
}
if (!form.main_title.trim()) {
nextErrors.main_title = '请输入岗位标题';
} else if (form.main_title.length > 30) {
nextErrors.main_title = '岗位标题最多30字';
}
if (!form.sub_title.trim()) {
nextErrors.sub_title = '请输入岗位说明';
} else if (form.sub_title.length > 200) {
nextErrors.sub_title = '岗位说明最多200字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = async () => { const handleSave = async () => {
setNotice(null); setNotice(null);
if (!validate()) return; const validation = await validateBusinessForm(fields, form);
setErrors(validation);
if (Object.values(validation).some(Boolean)) return;
if (mode === 'create' && existingPositions.includes(form.position_code)) { if (mode === 'create' && existingPositions.includes(form.position_code)) {
setNotice({ type: 'error', message: '该岗位已存在官网岗位展示,请编辑原配置' }); setNotice({ type: 'error', message: '该岗位已存在官网岗位展示,请编辑原配置' });
...@@ -214,11 +378,6 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -214,11 +378,6 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
} }
}; };
const availableQRCodeOptions = availableQRCodes.filter((qr) => {
if (mode === 'edit') return true;
return !existingPositions.includes(qr.position_name);
});
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
...@@ -252,125 +411,15 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -252,125 +411,15 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="对应岗位" labelAlign="left" requiredMark={mode === 'create'} status={errors.position_code ? 'error' : undefined} tips={errors.position_code}> <h3 className="m-0 text-base font-medium leading-[var(--gl-line-height-lg)]">{sectionTitle}</h3>
{mode === 'edit' ? ( <BusinessForm
<Input fields={fields}
aria-label="岗位标签" values={form}
className={fieldWidthClassName} errors={errors}
disabled fieldWidth={450}
value={currentTab?.position_name ?? ''} labelAlign="left"
/> onChange={(nextValues) => setForm(nextValues as TabFormState)}
) : ( />
<Select
aria-label="对应岗位"
className={fieldWidthClassName}
options={availableQRCodeOptions.map((qr) => ({
value: String(qr.qrcode_id),
label: qr.position_name,
disabled: existingPositions.includes(qr.position_name) || qr.status === 'disable',
}))}
placeholder="请选择对应岗位"
value={form.qrcode_id ? String(form.qrcode_id) : ''}
onChange={(value) => {
const qr = availableQRCodes.find((q) => q.qrcode_id === Number(value));
if (qr) {
setForm((current) => ({
...current,
position_code: qr.channel_code,
position_name: qr.position_name,
qrcode_id: qr.qrcode_id,
qrcode_name: qr.qrcode_name,
channel_code: qr.channel_code,
employee_name: qr.employee_name,
}));
}
}}
/>
)}
</FormItem>
<FormItem label="关联渠道活码" labelAlign="left">
<div className={fieldWidthClassName}>
{form.qrcode_name || currentTab?.qrcode_name || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null)}
</div>
</FormItem>
<FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}>
{form.channel_code || currentTab?.channel_code || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null)}
</div>
</FormItem>
<FormItem label="承接员工" labelAlign="left">
<div className={fieldWidthClassName}>
{form.employee_name || currentTab?.qrcode_employee_name || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null)}
</div>
</FormItem>
<div className="border-t border-[var(--gl-color-border-secondary)]" />
<h3 className="m-0 text-lg font-semibold leading-[var(--gl-line-height-lg)]">岗位 AI 赋能介绍</h3>
<FormItem label="岗位标题" labelAlign="left" requiredMark status={errors.main_title ? 'error' : undefined} tips={errors.main_title}>
<div className={fieldWidthClassName}>
<Input
aria-label="岗位标题"
placeholder="请输入岗位标题"
maxlength={30}
allowInputOverMax
value={form.main_title}
onChange={(value) => setForm((current) => ({ ...current, main_title: value }))}
/>
<p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位</p>
</div>
</FormItem>
<FormItem label="岗位说明" labelAlign="left" requiredMark status={errors.sub_title ? 'error' : undefined} tips={errors.sub_title}>
<div className={fieldWidthClassName}>
<Textarea
aria-label="岗位说明"
className="w-full"
placeholder="请输入岗位说明"
maxlength={200}
allowInputOverMax
count
rows={4}
value={form.sub_title}
onChange={(value) => setForm((current) => ({ ...current, sub_title: value }))}
/>
<p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值</p>
</div>
</FormItem>
<FormItem label="Tab 排序" labelAlign="left" requiredMark status={errors.tab_order ? 'error' : undefined} tips={errors.tab_order}>
<Input
aria-label="Tab排序"
className={fieldWidthClassName}
type="number"
placeholder="请输入Tab排序(0-99)"
value={form.tab_order === undefined || form.tab_order === null || (typeof form.tab_order === 'number' && isNaN(form.tab_order)) ? '' : String(form.tab_order)}
onChange={(value) => setForm((current) => ({ ...current, tab_order: value === '' ? undefined as unknown as number : Number(value) }))}
/>
</FormItem>
<FormItem label="展示状态" labelAlign="left" requiredMark>
<Select
aria-label="展示状态"
className={fieldWidthClassName}
options={[
{ value: 'enable', label: '展示中' },
{ value: 'disable', label: '已下架' },
]}
value={form.display_status}
onChange={(value) => setForm((current) => ({ ...current, display_status: value as OfficialSiteTabStatus }))}
/>
</FormItem>
</div> </div>
</div> </div>
</section> </section>
......
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { MediaWall, StatePlaceholder } from '@gl/business-components'; import {
BusinessForm,
MediaWall,
StatePlaceholder,
type BusinessFormErrors,
type BusinessFormField,
} from '@gl/business-components';
import { Button } from 'tdesign-react'; import { Button } from 'tdesign-react';
import { FormItem, Input, Switch, Textarea } from '../../components/TDesignAccessibleControls'; import { FormItem, Input } from '../../components/TDesignAccessibleControls';
import { import {
getMethodologyConfig, getMethodologyConfig,
saveMethodologyConfig, saveMethodologyConfig,
...@@ -38,6 +44,8 @@ interface SaveNotice { ...@@ -38,6 +44,8 @@ interface SaveNotice {
message: string; message: string;
} }
type MethodologyTopFormValues = Pick<MethodologyFormState, 'display_status' | 'main_title' | 'sub_title'>;
const contentImageHelperText = '支持 PNG/JPG/JPEG,最大 10MB'; const contentImageHelperText = '支持 PNG/JPG/JPEG,最大 10MB';
const stepIconHelperText = '支持 PNG/JPG/JPEG,最大 2MB'; const stepIconHelperText = '支持 PNG/JPG/JPEG,最大 2MB';
...@@ -80,8 +88,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -80,8 +88,7 @@ export function OfficialSiteMethodologyPage() {
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [notice, setNotice] = useState<SaveNotice | null>(null); const [notice, setNotice] = useState<SaveNotice | null>(null);
const [mainTitleError, setMainTitleError] = useState<string>(); const [topErrors, setTopErrors] = useState<BusinessFormErrors>({});
const [subTitleError, setSubTitleError] = useState<string>();
const [stepListError, setStepListError] = useState<string>(); const [stepListError, setStepListError] = useState<string>();
const [defaultIconUploading, setDefaultIconUploading] = useState<Set<string>>(new Set()); const [defaultIconUploading, setDefaultIconUploading] = useState<Set<string>>(new Set());
const [defaultIconUploadError, setDefaultIconUploadError] = useState<Map<string, string>>(new Map()); const [defaultIconUploadError, setDefaultIconUploadError] = useState<Map<string, string>>(new Map());
...@@ -95,8 +102,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -95,8 +102,7 @@ export function OfficialSiteMethodologyPage() {
getMethodologyConfig() getMethodologyConfig()
.then((record) => { .then((record) => {
setForm(buildFormState(record)); setForm(buildFormState(record));
setMainTitleError(undefined); setTopErrors({});
setSubTitleError(undefined);
setStepListError(undefined); setStepListError(undefined);
setLoading(false); setLoading(false);
}) })
...@@ -117,32 +123,70 @@ export function OfficialSiteMethodologyPage() { ...@@ -117,32 +123,70 @@ export function OfficialSiteMethodologyPage() {
})); }));
}; };
const topFields: BusinessFormField[] = [
{
key: 'display_status',
label: '展示状态',
type: 'switch',
checkedValue: 'enable',
uncheckedValue: 'disable',
},
{
key: 'main_title',
label: '主标题',
type: 'input',
required: true,
maxLength: 30,
validator: (value) => {
const text = String(value ?? '').trim();
if (!text) return '请输入主标题';
if (text.length > 30) return '主标题不能超过 30 字';
return undefined;
},
},
{
key: 'sub_title',
label: '副标题',
type: 'textarea',
required: true,
maxLength: 100,
rows: 4,
validator: (value) => {
const text = String(value ?? '').trim();
if (!text) return '请输入副标题';
if (text.length > 100) return '副标题不能超过 100 字';
return undefined;
},
},
];
const validate = () => { const validate = () => {
if (!form) return false; if (!form) return false;
let valid = true; let valid = true;
setStepListError(undefined);
const nextTopErrors: BusinessFormErrors = {};
const trimmedMainTitle = form.main_title.trim(); const trimmedMainTitle = form.main_title.trim();
const trimmedSubTitle = form.sub_title.trim(); const trimmedSubTitle = form.sub_title.trim();
setMainTitleError(undefined);
setSubTitleError(undefined);
setStepListError(undefined);
if (!trimmedMainTitle) { if (!trimmedMainTitle) {
setMainTitleError('请输入主标题'); nextTopErrors.main_title = '请输入主标题';
valid = false; valid = false;
} else if (trimmedMainTitle.length > 30) { } else if (trimmedMainTitle.length > 30) {
setMainTitleError('主标题不能超过 30 字'); nextTopErrors.main_title = '主标题不能超过 30 字';
valid = false; valid = false;
} }
if (!trimmedSubTitle) { if (!trimmedSubTitle) {
setSubTitleError('请输入副标题'); nextTopErrors.sub_title = '请输入副标题';
valid = false; valid = false;
} else if (trimmedSubTitle.length > 100) { } else if (trimmedSubTitle.length > 100) {
setSubTitleError('副标题不能超过 100 字'); nextTopErrors.sub_title = '副标题不能超过 100 字';
valid = false; valid = false;
} }
setTopErrors(nextTopErrors);
if (form.display_status === 'enable' && form.steps.length === 0) { if (form.display_status === 'enable' && form.steps.length === 0) {
setStepListError('至少添加一个方法论步骤'); setStepListError('至少添加一个方法论步骤');
valid = false; valid = false;
...@@ -269,58 +313,32 @@ export function OfficialSiteMethodologyPage() { ...@@ -269,58 +313,32 @@ export function OfficialSiteMethodologyPage() {
) : null} ) : null}
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8">
<div className="grid gap-6"> <BusinessForm
<FormItem label="展示状态" labelAlign="left" requiredMark> fields={topFields}
<Switch values={{
aria-label="展示状态" display_status: form.display_status,
value={form.display_status === 'enable'} main_title: form.main_title,
onChange={(checked) => { sub_title: form.sub_title,
setNotice(null); }}
updateForm((current) => ({ errors={topErrors}
...current, labelAlign="left"
display_status: checked ? 'enable' : 'disable', fieldWidth="520px"
})); onChange={(nextValues, changedKey) => {
}} setNotice(null);
/> updateForm((current) => ({
</FormItem> ...current,
...(nextValues as MethodologyTopFormValues),
<FormItem label="主标题" labelAlign="left" requiredMark status={mainTitleError ? 'error' : undefined} tips={mainTitleError}> }));
<Input const changedFieldKey = typeof changedKey === 'string' ? changedKey : changedKey.key;
aria-label="主标题" if (changedFieldKey === 'main_title' || changedFieldKey === 'sub_title') {
className="w-full max-w-[520px]" setTopErrors((current) => {
maxlength={30} const next = { ...current };
allowInputOverMax delete next[changedFieldKey];
showLimitNumber return next;
value={form.main_title} });
onChange={(value) => { }
setMainTitleError(undefined); }}
updateForm((current) => ({ />
...current,
main_title: value,
}));
}}
/>
</FormItem>
<FormItem label="副标题" labelAlign="left" requiredMark status={subTitleError ? 'error' : undefined} tips={subTitleError}>
<Textarea
aria-label="副标题"
className="w-full max-w-[520px]"
maxlength={100}
allowInputOverMax
rows={4}
count
value={form.sub_title}
onChange={(value) => {
setSubTitleError(undefined);
updateForm((current) => ({
...current,
sub_title: value,
}));
}}
/>
</FormItem>
</div>
</div> </div>
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8">
......
...@@ -86,6 +86,7 @@ describe('SkillListPage', () => { ...@@ -86,6 +86,7 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('共 2 条')).toBeInTheDocument(); expect(screen.getByText('共 2 条')).toBeInTheDocument();
}); });
expect(screen.getByText('支持本地目标、浏览器检查和使用说明预览。').className).toContain('cellText');
expect(screen.getByRole('button', { name: '查看browser:browser详情' })).toHaveClass('t-button--theme-primary', 't-button--variant-text'); expect(screen.getByRole('button', { name: '查看browser:browser详情' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(screen.queryByRole('button', { name: '新建Skill' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '新建Skill' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '编辑' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '编辑' })).not.toBeInTheDocument();
......
...@@ -57,7 +57,7 @@ export function SkillListPage() { ...@@ -57,7 +57,7 @@ export function SkillListPage() {
const columns: BusinessTableColumn<SkillSummary>[] = [ const columns: BusinessTableColumn<SkillSummary>[] = [
{ title: 'Skill编码', colKey: 'skill_code' }, { title: 'Skill编码', colKey: 'skill_code' },
{ title: 'Skill名称', colKey: 'skill_name' }, { title: 'Skill名称', colKey: 'skill_name' },
{ title: '说明', colKey: 'description' }, { title: '说明', colKey: 'description', ellipsisTooltip: true },
{ {
title: '操作', title: '操作',
colKey: 'actions', colKey: 'actions',
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!