Commit 30d7e0a3 by 胡悦

chore(agent-admin/web): 删除本地UI包并清理规范,修复测试超时

- 删除 `workspace/agent-admin/web/packages/ui` 本地UI组件源码目录,消除误用入口
- 从 `tsconfig.app.json` 移除 `packages/ui/src` 的类型检查包含配置
- 更新根目录与后台的README、前端基础文档、OpenSpec规范,明确组件来源为 `tdesign-react`、`tdesign-icons-react` 和全局业务组件包 `@gl/business-components`
- 新增独立页面页头吸顶的OpenSpec规范、设计方案与实施任务
- 修复官网Agent展示配置编辑页的测试超时问题,将逐字输入改为一次性 change 事件避免并发超时
1 parent 7c16dd2a
Showing 56 changed files with 355 additions and 3230 deletions
...@@ -132,3 +132,4 @@ ...@@ -132,3 +132,4 @@
- 2026-06-09:用户确认后已按 TDD 实施 `standardize-independent-page-right-actions`。全局 `web-desktop-ui-standard`、`frontend-conventions.md`、`component-guidelines.md` 与项目 `admin-shell` 规范已同步为“独立页左侧只放标题/说明,右侧放 `返回` 和其他页面级操作”;已迁移 Agent 新增/编辑、岗位标签新增/编辑、渠道活码新增/编辑、官网岗位展示新增/编辑、官网 Agent 展示配置页。聚焦测试通过 `5 files / 120 passed / 2 skipped`,`npm run typecheck`、`npm run build`、全局与项目 `openspec validate standardize-independent-page-right-actions --strict` 均通过;浏览器布局验证按用户要求由用户自行完成,OpenSpec tasks 中 4.5 保持未勾选。 - 2026-06-09:用户确认后已按 TDD 实施 `standardize-independent-page-right-actions`。全局 `web-desktop-ui-standard`、`frontend-conventions.md`、`component-guidelines.md` 与项目 `admin-shell` 规范已同步为“独立页左侧只放标题/说明,右侧放 `返回` 和其他页面级操作”;已迁移 Agent 新增/编辑、岗位标签新增/编辑、渠道活码新增/编辑、官网岗位展示新增/编辑、官网 Agent 展示配置页。聚焦测试通过 `5 files / 120 passed / 2 skipped`,`npm run typecheck`、`npm run build`、全局与项目 `openspec validate standardize-independent-page-right-actions --strict` 均通过;浏览器布局验证按用户要求由用户自行完成,OpenSpec tasks 中 4.5 保持未勾选。
- 2026-06-09:已核对并归档 `refine-search-filter-single-row-responsive`。归档前确认 `SearchFilter` 实现、组件/Demo 测试和 active spec 对齐:操作按钮进入同一响应式 flex 流,顺序为 `查询`、`重置`、`展开/收起`,按布局测量判断是否超过两行,并保持自然换行。验证通过 `openspec validate refine-search-filter-single-row-responsive --strict`、`npm test -- --run src/business-components/global-business-components.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`npm run typecheck`、`npm run build`;随后 `openspec archive refine-search-filter-single-row-responsive --yes` 生成 `openspec/changes/archive/2026-06-09-refine-search-filter-single-row-responsive/`,并将规则合入 `openspec/specs/global-search-filter/spec.md`。归档后 `openspec validate global-search-filter --strict` 通过;OpenSpec telemetry 仍有 PostHog DNS 警告但退出码为 0。 - 2026-06-09:已核对并归档 `refine-search-filter-single-row-responsive`。归档前确认 `SearchFilter` 实现、组件/Demo 测试和 active spec 对齐:操作按钮进入同一响应式 flex 流,顺序为 `查询`、`重置`、`展开/收起`,按布局测量判断是否超过两行,并保持自然换行。验证通过 `openspec validate refine-search-filter-single-row-responsive --strict`、`npm test -- --run src/business-components/global-business-components.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`npm run typecheck`、`npm run build`;随后 `openspec archive refine-search-filter-single-row-responsive --yes` 生成 `openspec/changes/archive/2026-06-09-refine-search-filter-single-row-responsive/`,并将规则合入 `openspec/specs/global-search-filter/spec.md`。归档后 `openspec validate global-search-filter --strict` 通过;OpenSpec telemetry 仍有 PostHog DNS 警告但退出码为 0。
- 2026-06-09:用户浏览器验证通过后,已补齐并归档 `standardize-independent-page-right-actions`。项目级 change 归档到 `workspace/agent-admin/web/openspec/changes/archive/2026-06-09-standardize-independent-page-right-actions/`,并合入 `openspec/specs/admin-shell/spec.md`;全局 change 归档到 `architecture-spec/openspec/changes/archive/2026-06-09-standardize-independent-page-right-actions/`,并合入 `openspec/specs/web-desktop-ui-standard/spec.md`。归档前后验证通过:两侧 `openspec validate standardize-independent-page-right-actions --strict`、相关独立页测试 `102 passed / 2 skipped`、`npm run typecheck`、`npm run build`、归档后 `openspec validate admin-shell --strict` 与 `openspec validate web-desktop-ui-standard --strict`。OpenSpec telemetry 仍因受限网络出现 PostHog DNS 警告但退出码为 0。 - 2026-06-09:用户浏览器验证通过后,已补齐并归档 `standardize-independent-page-right-actions`。项目级 change 归档到 `workspace/agent-admin/web/openspec/changes/archive/2026-06-09-standardize-independent-page-right-actions/`,并合入 `openspec/specs/admin-shell/spec.md`;全局 change 归档到 `architecture-spec/openspec/changes/archive/2026-06-09-standardize-independent-page-right-actions/`,并合入 `openspec/specs/web-desktop-ui-standard/spec.md`。归档前后验证通过:两侧 `openspec validate standardize-independent-page-right-actions --strict`、相关独立页测试 `102 passed / 2 skipped`、`npm run typecheck`、`npm run build`、归档后 `openspec validate admin-shell --strict` 与 `openspec validate web-desktop-ui-standard --strict`。OpenSpec telemetry 仍因受限网络出现 PostHog DNS 警告但退出码为 0。
- 2026-06-09:用户确认删除旧本地 UI 包后,已实施 `remove-local-ui-package`:删除 `workspace/agent-admin/web/packages/ui`,从 `tsconfig.app.json` 移除 `packages/ui/src`,更新 README、前端地基文档和 `admin-ui-runtime-dependency` 稳定规范,当前后台基础控件来源为 `tdesign-react`/`tdesign-icons-react`,业务组合能力来源为 `@gl/business-components`。全量测试中官网 Agent 展示配置编辑页的 101 字输入用例在并发下 5s 超时,已将该用例从逐字 `user.type` 改为一次 `fireEvent.change`,保持 100 字截断和计数断言。验证通过:`npm run scan:local-ui-runtime-deps`、`npm run typecheck`、`npm test`(51 files / 633 passed / 9 skipped)、`openspec validate remove-local-ui-package --strict`;OpenSpec telemetry 仍有 PostHog DNS 警告但退出码为 0。
# 多项目前端工作区 # 多项目前端工作区
这是一个独立新建的 monorepo 工作区,用于沉淀 OpenSpec + Superpowers 工作流、公司 Web 桌面端设计规范、前端工程规则和后续多个项目可复用的组件规范。 这是一个独立新建的 monorepo 工作区,用于沉淀 OpenSpec + Superpowers 工作流、公司 Web 桌面端设计规范、前端工程规则和后续多个项目可复用的组件使用规则。
首个业务项目是 AI 大模型后台管理平台,放在 `workspace/agent-admin/`。当前阶段只沉淀项目规范和需求确认流程;业务开发需等待 PRD 二次确认、OpenSpec change 完成并获得确认后再开始。 首个业务项目是 AI 大模型后台管理平台,放在 `workspace/agent-admin/`。当前阶段只沉淀项目规范和需求确认流程;业务开发需等待 PRD 二次确认、OpenSpec change 完成并获得确认后再开始。
## 项目范围 ## 项目范围
- 工作区级共享能力:OpenSpec + Superpowers 工作流、公司 Web 桌面端组件规范、前端工程配置。 - 工作区级共享能力:OpenSpec + Superpowers 工作流、公司 Web 桌面端组件使用规则、前端工程配置。
- 首个业务应用:Agent 管理、Agent 群管理、官网配置。 - 首个业务应用:Agent 管理、Agent 群管理、官网配置。
- 后续业务应用:可在 `workspace/` 下新增项目,并复用共享规范和组件。 - 后续业务应用:可在 `workspace/` 下新增项目,并复用共享规范;具体组件来源以各项目文档为准。
- 管家 Agent 路由与运行时能力,后续需单独确认边界。 - 管家 Agent 路由与运行时能力,后续需单独确认边界。
- 后端技术栈暂不锁定,后续可根据确认结果选择 Python 或其他方案。 - 后端技术栈暂不锁定,后续可根据确认结果选择 Python 或其他方案。
- Agent 管理相关项目都由 `workspace/agent-admin/` 管理,管理后台前端位于 `web/`,单页面项目位于 `single-page/`,后端预留在 `backend/`;各项目独立管理自己的 OpenSpec、组件/模块和工程配置。 - Agent 管理相关项目都由 `workspace/agent-admin/` 管理,管理后台前端位于 `web/`,单页面项目位于 `single-page/`,后端预留在 `backend/`;各项目独立管理自己的 OpenSpec、组件/模块和工程配置。
...@@ -19,7 +19,12 @@ ...@@ -19,7 +19,12 @@
AGENTS.md # 工作区级 Agent 协作规则 AGENTS.md # 工作区级 Agent 协作规则
.agents/ # 团队 skills 引用,当前受本机沙箱限制暂未创建 .agents/ # 团队 skills 引用,当前受本机沙箱限制暂未创建
architecture-spec/ # 全局架构、OpenSpec、UI 和工程规范 architecture-spec/ # 全局架构、OpenSpec、UI 和工程规范
workspace/agent-admin/ # 首个业务项目:Agent 管理平台 docs/ # 工作区级 Superpowers 设计与计划文档
openspec/ # 工作区级 OpenSpec 变更与稳定规范
packages/ # 工作区级共享包
business-components/ # 跨项目业务组合组件
workspace/
agent-admin/ # Agent 管理相关项目集合
``` ```
## 工作流 ## 工作流
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
React + Vite + TypeScript 应用代码放在本目录下。页面实现必须遵循公司 Web 桌面端设计规范,并优先遵循本项目 `docs/` 下的项目级前端地基文档。 React + Vite + TypeScript 应用代码放在本目录下。页面实现必须遵循公司 Web 桌面端设计规范,并优先遵循本项目 `docs/` 下的项目级前端地基文档。
本目录独立管理后台前端的 OpenSpec、组件、接口契约和工程配置。当前阶段只沉淀项目级前端地基,不把本项目实践直接升级为 monorepo 全局前端地基。 本目录独立管理后台前端的 OpenSpec、接口契约和工程配置。后台页面基础控件直接使用 TDesign,业务组合能力优先从全局业务组件包复用。
职责范围: 职责范围:
...@@ -15,7 +15,6 @@ React + Vite + TypeScript 应用代码放在本目录下。页面实现必须遵 ...@@ -15,7 +15,6 @@ React + Vite + TypeScript 应用代码放在本目录下。页面实现必须遵
目录说明: 目录说明:
- `openspec/`:前端页面和交互行为的 OpenSpec。 - `openspec/`:前端页面和交互行为的 OpenSpec。
- `packages/ui/`:前端可复用 UI 组件。
- `packages/config/`:前端工程配置。 - `packages/config/`:前端工程配置。
- `packages/utils/`:前端通用工具。 - `packages/utils/`:前端通用工具。
- `packages/contracts/`:前端视角的字段、枚举、payload 和 mock 数据。 - `packages/contracts/`:前端视角的字段、枚举、payload 和 mock 数据。
......
...@@ -53,7 +53,6 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有 ...@@ -53,7 +53,6 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有
| `src/layouts/` | 管理后台基础布局。 | | `src/layouts/` | 管理后台基础布局。 |
| `src/routes/` | 路由页面和页面级组合。 | | `src/routes/` | 路由页面和页面级组合。 |
| `src/styles/` | reset、设计 token、全局样式入口。 | | `src/styles/` | reset、设计 token、全局样式入口。 |
| `packages/ui/` | 本项目当前使用的可复用 UI 组件。 |
| `packages/contracts/` | 前端视角接口契约、字段、枚举、payload 和 mock 数据。 | | `packages/contracts/` | 前端视角接口契约、字段、枚举、payload 和 mock 数据。 |
| `packages/config/` | 前端工程配置沉淀。 | | `packages/config/` | 前端工程配置沉淀。 |
| `packages/utils/` | 前端通用工具沉淀。 | | `packages/utils/` | 前端通用工具沉淀。 |
...@@ -93,7 +92,8 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有 ...@@ -93,7 +92,8 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有
## 6. 组件使用规则 ## 6. 组件使用规则
- 页面优先使用 `packages/ui` 中已有组件。 - 页面基础控件优先直接使用 `tdesign-react`,图标直接使用 `tdesign-icons-react`。
- 跨页面复用的搜索区、状态占位、媒体墙等业务组合能力优先从 `@gl/business-components` 使用。
- 页面不得为了单个场景临时堆一套与组件库重复的按钮、表单、表格、状态标签或反馈样式。 - 页面不得为了单个场景临时堆一套与组件库重复的按钮、表单、表格、状态标签或反馈样式。
- 组件能力不足时,先记录缺口和业务场景,再判断是扩展组件 props、增加组合组件,还是只在页面层处理。 - 组件能力不足时,先记录缺口和业务场景,再判断是扩展组件 props、增加组合组件,还是只在页面层处理。
- 组件内部样式由组件负责,业务页面只通过 props、`className`、`style` 或 CSS 变量做受控扩展。 - 组件内部样式由组件负责,业务页面只通过 props、`className`、`style` 或 CSS 变量做受控扩展。
...@@ -112,7 +112,7 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有 ...@@ -112,7 +112,7 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有
## 6.2 Markdown 与抽屉内容区边界 ## 6.2 Markdown 与抽屉内容区边界
- 当前 `packages/ui` 尚未沉淀通用 Markdown 渲染器或统一的代码块样式组件。 - 当前后台未沉淀通用 Markdown 渲染器或统一的代码块样式组件。
- 如业务页面需要展示 Markdown,可先在页面层使用现有容器、文本和代码样式能力完成基础渲染,不把通用 Markdown 能力混进业务 OpenSpec。 - 如业务页面需要展示 Markdown,可先在页面层使用现有容器、文本和代码样式能力完成基础渲染,不把通用 Markdown 能力混进业务 OpenSpec。
- 当前 `Drawer` 组件提供基础浮层承载能力,但未把“内容区独立滚动”抽象成通用组件能力;如果后续多个页面都需要同类能力,再单独提升为地基或基础组件改造。 - 当前 `Drawer` 组件提供基础浮层承载能力,但未把“内容区独立滚动”抽象成通用组件能力;如果后续多个页面都需要同类能力,再单独提升为地基或基础组件改造。
......
# 删除后台本地 UI 包实施计划
## 1. 规范锁定
- [ ] 创建 `remove-local-ui-package` OpenSpec change。
- [ ] 将稳定规范中的“旧本地 UI 包目录暂时保留”替换为“旧本地 UI 包源码已删除”。
- [ ] 通过 `openspec validate remove-local-ui-package --strict`。
## 2. 清理实现
- [ ] 删除 `workspace/agent-admin/web/packages/ui`。
- [ ] 从 `tsconfig.app.json` 移除 `packages/ui/src`。
- [ ] 更新当前 README 和前端基础文档中的组件来源说明。
## 3. 验证
- [ ] 运行 `npm run scan:local-ui-runtime-deps`。
- [ ] 运行 `npm run typecheck`。
- [ ] 运行 `npm test`。
- [ ] 运行 `openspec validate remove-local-ui-package --strict`。
# 删除后台本地 UI 包设计
## 背景
`migrate-admin-ui-to-global-tdesign` 已完成并归档,当前 `workspace/agent-admin/web/src` 对本地 `packages/ui` 的运行时 import 为 0。旧目录 `workspace/agent-admin/web/packages/ui` 仍保留,且 `tsconfig.app.json` 仍把 `packages/ui/src` 纳入后台应用类型检查范围。
这使当前系统同时存在“运行时已脱离旧 UI 包”和“旧 UI 包源码仍被项目配置保留”的矛盾。既然页面已经统一使用 `tdesign-react` 与 `@gl/business-components`,旧源码继续留在后台项目中会制造误用入口和维护噪音。
## 已确认范围
### 本轮包含
- 删除 `workspace/agent-admin/web/packages/ui` 旧本地组件源码目录。
- 从 `workspace/agent-admin/web/tsconfig.app.json` 移除 `packages/ui/src`。
- 更新当前后台 README、前端基础文档和 `admin-ui-runtime-dependency` 规范,不再描述或要求保留旧本地 UI 包。
- 保留 `check:local-ui-runtime-deps` / `scan:local-ui-runtime-deps` 作为运行时代码防回归门禁。
### 本轮不包含
- 不修改 `workspace/agent-admin/web/src` 的页面交互与业务逻辑。
- 不迁移或删除根目录 `packages/business-components`。
- 不处理历史 archive 中的旧迁移记录。
- 不处理 `workspace/agent-admin/single-page`。
## 方案比较
### 方案 A:删除旧目录并更新当前配置与规范
删除 `web/packages/ui`,移除 TypeScript include,并更新当前协作文档和稳定规范。保留扫描脚本继续防止新的 `packages/ui` 运行时 import。
优点:边界最清晰,能从源码层面消除误用入口;改动集中且容易验证。
缺点:历史迁移 archive 仍会保留旧引用,需要接受历史记录不作为当前规范。
### 方案 B:保留旧目录,仅标记废弃
只更新 README 和文档,保留源码。
优点:改动更小。
缺点:旧组件仍会被 IDE 搜索、类型检查和人工浏览发现,容易继续被误用。
### 方案 C:迁到 archive 目录保留源码
把旧源码移动到某个 archive 路径。
优点:源码仍可就地查看。
缺点:仍会制造维护边界,且历史归档已经能保留迁移背景。
## 采用方案
采用方案 A。
## 验收标准
- `workspace/agent-admin/web/packages/ui` 不存在。
- `workspace/agent-admin/web/tsconfig.app.json` 不再 include `packages/ui/src`。
- 当前后台 README、前端基础文档和稳定 OpenSpec 不再把旧本地 UI 包描述为保留对象或当前组件入口。
- `npm run scan:local-ui-runtime-deps` 输出 0 条。
- `npm run typecheck` 通过。
- `npm test` 通过。
- `openspec validate remove-local-ui-package --strict` 通过。
# Design: 修复独立页面页头吸顶错位
## 方案
独立页面继续渲染在 `BusinessAdminShell` 的内容区内。页面自身不创建新的全屏 `fixed` header,也不通过 `margin-top`、`padding-top` 或 `height: calc(100vh - xx)` 为 fixed header 手动补位。
独立页面的页头操作区使用 sticky 吸顶:
- sticky 元素位于页面内容结构顶部。
- sticky 的 `top` 相对于后台内容滚动容器,默认为 `0`。
- sticky 页头必须具备不透明背景、边框和足够 `z-index`,避免内容滚动时视觉穿透。
- 页头右侧操作区必须 `shrink-0`,避免标题过长时挤压 `返回`、`保存` 等按钮。
## 实现策略
优先收敛独立页面页头的通用 class 或组件样式,减少各页面复制 `sticky top-0` 时出现细节漂移。若短期先改页面 class,也必须保持同一套布局规则。
需要重点检查以下页面类型:
- Agent 新增/编辑页。
- 岗位标签新增/编辑页。
- 员工渠道活码新增/编辑页。
- 官网岗位展示新增/编辑页。
- 官网 Agent 展示配置页。
## 风险与处理
- 风险:sticky 元素被外层异常 `overflow`、`transform` 或额外滚动容器影响。处理:验证 sticky 参照为后台内容滚动容器,并避免在独立页根节点再创建不必要的全屏滚动。
- 风险:页头吸顶后覆盖首段内容。处理:保持页头仍占据文档流位置,不使用 fixed,因此内容自然从页头后开始。
- 风险:长标题挤压操作按钮。处理:标题区域 `min-width: 0`,操作区 `shrink-0`。
## 验证
- 运行相关单元测试或组件测试。
- 运行类型检查。
- 使用浏览器打开一个长表单独立页,滚动页面,确认页头吸顶、操作按钮可点击、内容不穿透且无双滚动条。
# Proposal: 修复独立页面页头吸顶错位
## 背景
管理后台独立新增、编辑和配置页面已经要求页头操作区在滚动时保持可见,但当前实现和规范没有明确页头吸顶必须以内容滚动容器为参照,也没有明确禁止使用 `fixed` 加手动补位。页面滚动时容易出现页头、内容卡片和全局 header 的视觉错位。
## 目标
- 独立页面页头使用 `position: sticky` 在页面内容滚动容器内吸顶。
- 独立页面页头不得使用 `position: fixed` 脱离后台 shell 布局。
- 页面内容滚动时,页头背景、边框和层级保持稳定,滚动内容不得穿透或覆盖页头。
- 保持现有页面的返回、保存、校验、请求和路由行为不变。
## 非目标
- 不调整全局后台 shell 的菜单、面包屑、用户区和退出登录行为。
- 不改变列表页滚动模型、表格分页、筛选或虚拟滚动规则。
- 不改变独立页面字段、保存 payload、权限和业务状态。
## 影响范围
- 影响项目 OpenSpec:`openspec/specs/admin-shell/spec.md`。
- 影响前端实现:独立新增、编辑、配置页面的页头吸顶样式和必要的共享样式收敛。
- 影响验证:需要覆盖至少一个长表单独立页滚动时页头吸顶且不遮挡操作按钮。
# admin-shell Delta
## MODIFIED Requirements
### Requirement: 独立页面页头操作区
岗位 Agent 管理后台 SHALL 为新增、编辑、配置等独立页面提供一致且滚动可见的页头操作区。页头左侧只展示页面标题、说明和状态摘要等页面识别信息;页头右侧 MUST 展示 `返回` 和其他页面级操作按钮。独立页面页头 MUST 使用内容滚动容器内的 sticky 吸顶实现,不得使用 `position: fixed` 脱离后台 shell 布局。
#### Scenario: 独立页面右侧集中展示操作按钮
- **WHEN** 已登录用户打开新增、编辑、配置等独立页面
- **THEN** 独立页面页头左侧展示页面标题和必要说明
- **AND** 独立页面页头左侧不展示 `返回` 入口或其他按钮
- **AND** 独立页面页头右侧展示 `返回` 入口
- **AND** 独立页面页头右侧展示 `保存` 等主操作
- **AND** 独立页面页头右侧不展示 `取消` 按钮
#### Scenario: 右侧操作区按钮排序
- **WHEN** 独立页面页头右侧同时存在 `返回`、主操作和其他页面级操作
- **THEN** `返回` 位于右侧操作区内靠左位置
- **AND** 主操作位于右侧操作区内靠右位置
- **AND** 其他次级页面级操作位于 `返回` 和主操作之间,或收敛到更多操作菜单
#### Scenario: 滚动时保持页头操作区可见
- **WHEN** 已登录用户在新增、编辑、配置等独立页面向下滚动表单内容
- **THEN** 独立页面页头操作区使用 sticky 方式保持在内容滚动容器顶部可见
- **AND** 独立页面页头不得使用 fixed 定位或依赖页面级手动补位保持可见
- **AND** `返回` 和 `保存` 等页面级操作入口保持可点击
- **AND** 滚动内容不得覆盖页头操作区
- **AND** 页头右侧操作区不得被页面标题或说明挤压到不可见
# Tasks
## 1. OpenSpec
- [x] 1.1 新增 `admin-shell` 规范 delta,明确独立页面页头必须在内容滚动容器内 sticky 吸顶。
- [x] 1.2 明确独立页面页头不得使用 fixed 和手动补位。
- [x] 1.3 运行 `openspec validate fix-independent-page-sticky-header --strict`。
## 2. 实现
- [ ] 2.1 检查独立页面页头实现,识别导致 sticky 错位的外层滚动或样式问题。
- [ ] 2.2 收敛独立页面页头吸顶样式,保持 `返回`、`保存` 等操作在右侧可见。
- [ ] 2.3 清理独立页面中与 fixed header 补位相关的样式,如 `margin-top`、`padding-top` 或不必要的 `height: calc(...)`。
## 3. 验证
- [ ] 3.1 运行相关测试。
- [ ] 3.2 运行类型检查。
- [ ] 3.3 浏览器验证长表单独立页滚动时页头吸顶、无错位、无双滚动条、按钮可点击。
## Context
`migrate-admin-ui-to-global-tdesign` 已归档,后台运行时代码的 UI 依赖边界已经收敛:基础控件直接来自 `tdesign-react`,图标来自 `tdesign-icons-react`,业务组合能力来自 `@gl/business-components`。当前剩余问题是旧目录 `workspace/agent-admin/web/packages/ui` 仍存在,且 `tsconfig.app.json` 仍 include `packages/ui/src`。
## Goals / Non-Goals
**Goals:**
- 删除旧本地 UI 包源码目录,消除新的误用入口。
- 让后台 TypeScript 配置不再纳入旧包源码。
- 更新当前协作文档和稳定规范,使当前组件来源与实际实现一致。
- 保留运行时 import 扫描门禁,防止后续重新引入旧路径。
**Non-Goals:**
- 不修改页面交互、业务逻辑、接口契约或路由结构。
- 不迁移或重构 `@gl/business-components`。
- 不批量改写历史 archive 中的迁移记录。
- 不处理 `workspace/agent-admin/single-page`。
## Decisions
1. 删除旧目录,而不是仅标记废弃。
旧目录已经不再被 `web/src` 运行时代码引用,保留源码只会让搜索、IDE 补全和人工维护继续暴露过时入口。删除目录后,误用会直接变成路径不存在,边界更清楚。
2. 保留 `check:local-ui-runtime-deps` 和 `scan:local-ui-runtime-deps`。
即使旧目录删除,扫描脚本仍能防止运行时代码重新引入 `packages/ui` 风格的路径或相对旧路径引用。该门禁成本低,且与迁移验收目标一致。
3. 当前文档只更新活跃协作口径,历史 archive 不改写。
archive 是迁移过程记录,保留旧描述有助于追溯;当前 README、基础文档和稳定 spec 才代表最新工程约束。
## Risks / Trade-offs
- 历史迁移测试或文档如果仍假设旧目录存在,删除后可能暴露陈旧断言。缓解方式:先搜索当前引用,再只更新活跃配置、文档和必要测试。
- 删除旧组件测试会减少旧组件自身的测试覆盖,但这些组件已不是当前产品运行时能力。缓解方式:当前页面、全局业务组件和 TDesign 迁移后的测试继续覆盖实际用户路径。
- 若第三方或本地脚本仍手动读取 `web/packages/ui`,删除会使脚本失败。缓解方式:用 `rg` 和现有扫描命令确认当前仓库无运行时依赖,并在最终说明中标出删除范围。
## Migration Plan
1. 删除 `workspace/agent-admin/web/packages/ui`。
2. 更新 `tsconfig.app.json`,移除 `packages/ui/src`。
3. 更新当前 README、前端基础文档和 `admin-ui-runtime-dependency` 稳定规范。
4. 运行 `npm run scan:local-ui-runtime-deps`、`npm run typecheck`、`npm test` 和 `openspec validate remove-local-ui-package --strict`。
## Open Questions
无。
## Why
后台页面已经完成 TDesign 与全局业务组件迁移,`workspace/agent-admin/web/src` 对本地 `packages/ui` 的运行时 import 为 0。继续保留 `workspace/agent-admin/web/packages/ui` 会制造误用入口,并让当前构建配置和规范仍背负旧组件包。
## What Changes
- 删除 `workspace/agent-admin/web/packages/ui` 旧本地 UI 组件源码目录。
- 从后台应用 TypeScript 配置中移除 `packages/ui/src`。
- 更新当前后台 README、前端基础文档和稳定规范,把当前组件来源明确为 `tdesign-react`、`tdesign-icons-react` 和 `@gl/business-components`。
- 保留本地 UI 运行时依赖扫描脚本,继续作为防止 `web/src` 重新引入旧路径的门禁。
- 不修改后台页面业务逻辑、路由、接口契约和 `@gl/business-components`。
## Capabilities
### New Capabilities
- 无。
### Modified Capabilities
- `admin-ui-runtime-dependency`: 将旧本地 UI 包的策略从“迁移后暂时保留”调整为“清理删除,并从当前类型检查范围移除”。
## Impact
- 受影响目录:`workspace/agent-admin/web/packages/ui`。
- 受影响配置:`workspace/agent-admin/web/tsconfig.app.json`。
- 受影响文档:`workspace/agent-admin/web/README.md`、`workspace/agent-admin/web/docs/frontend-foundation.md`、`workspace/agent-admin/web/openspec/specs/admin-ui-runtime-dependency/spec.md`。
- 不影响后端 API、页面行为、根目录 `packages/business-components` 和历史 OpenSpec archive。
## MODIFIED Requirements
### Requirement: 后台运行时代码不再依赖本地 UI 包
系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具,并且后台应用类型检查范围 MUST 不再纳入旧本地 UI 包源码目录。
#### Scenario: 扫描后台运行时 import
- **WHEN** 对 `workspace/agent-admin/web/src` 执行本地 UI 包依赖扫描
- **THEN** 扫描结果不包含指向 `packages/ui` 或 `packages/ui/src` 的运行时 import
#### Scenario: 类型检查不纳入旧本地 UI 包
- **WHEN** 查看 `workspace/agent-admin/web/tsconfig.app.json`
- **THEN** `include` 不包含 `packages/ui/src`
## REMOVED Requirements
### Requirement: 旧本地 UI 包目录暂时保留
系统 MUST 在本轮迁移中保留 `workspace/agent-admin/web/packages/ui` 目录,不把旧源码删除作为零运行时依赖验收条件。
#### Scenario: 完成运行时依赖迁移
- **WHEN** `workspace/agent-admin/web/src` 已达到零本地 UI 包运行时依赖
- **THEN** `workspace/agent-admin/web/packages/ui` 目录仍可保留,等待后续独立清理
## ADDED Requirements
### Requirement: 旧本地 UI 包源码已删除
系统 MUST 删除 `workspace/agent-admin/web/packages/ui` 遗留源码目录,并且当前后台协作文档 MUST 不再把该目录描述为当前组件入口或保留目标。
#### Scenario: 旧本地 UI 包目录不存在
- **WHEN** 检查 `workspace/agent-admin/web/packages/ui`
- **THEN** 该路径不存在
#### Scenario: 当前文档说明新的组件来源
- **WHEN** 查看当前后台 README 和前端基础文档
- **THEN** 文档将基础控件来源描述为 `tdesign-react` / `tdesign-icons-react`
- **AND** 文档将业务组合组件来源描述为 `@gl/business-components`
- **AND** 文档不要求保留 `workspace/agent-admin/web/packages/ui`
## 1. 建立清理基线
- [x] 1.1 扫描 `workspace/agent-admin/web/src`,确认当前运行时代码对 `packages/ui` 为 0 import
- [x] 1.2 搜索当前配置、文档和测试中仍引用 `workspace/agent-admin/web/packages/ui` 或 `packages/ui/src` 的位置
## 2. 清理旧本地 UI 包
- [x] 2.1 删除 `workspace/agent-admin/web/packages/ui` 旧源码目录
- [x] 2.2 从 `workspace/agent-admin/web/tsconfig.app.json` 移除 `packages/ui/src`
- [x] 2.3 更新当前后台 README 和前端基础文档的组件来源说明
- [x] 2.4 更新 `admin-ui-runtime-dependency` 稳定规范,移除“旧本地 UI 包目录暂时保留”要求
## 3. 验证
- [x] 3.1 运行 `npm run scan:local-ui-runtime-deps`
- [x] 3.2 运行 `npm run typecheck`
- [x] 3.3 运行 `npm test`
- [x] 3.4 运行 `openspec validate remove-local-ui-package --strict`
# admin-ui-runtime-dependency Specification # admin-ui-runtime-dependency Specification
## Purpose ## Purpose
TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Purpose after archive. 约束后台运行时代码的 UI 依赖边界:基础控件直接来自 TDesign,跨页面业务组合能力来自全局业务组件包,旧本地 UI 包不再作为当前源码入口保留。
## Requirements ## Requirements
### Requirement: 后台运行时代码不再依赖本地 UI 包 ### Requirement: 后台运行时代码不再依赖本地 UI 包
系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具。 系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具,并且后台应用类型检查范围 MUST 不再纳入旧本地 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`。
...@@ -64,12 +68,18 @@ TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Pur ...@@ -64,12 +68,18 @@ TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Pur
- **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件 - **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件
- **AND** 页面不依赖旧本地 UI 包 - **AND** 页面不依赖旧本地 UI 包
### Requirement: 旧本地 UI 包目录暂时保留 ### Requirement: 旧本地 UI 包源码已删除
系统 MUST 在本轮迁移中保留 `workspace/agent-admin/web/packages/ui` 目录,不把旧源码删除作为零运行时依赖验收条件。 系统 MUST 删除 `workspace/agent-admin/web/packages/ui` 遗留源码目录,并且当前后台协作文档 MUST 不再把该目录描述为当前组件入口或保留目标。
#### Scenario: 检查旧源码目录
- **WHEN** 检查 `workspace/agent-admin/web/packages/ui`
- **THEN** 该路径不存在
#### Scenario: 完成运行时依赖迁移 #### Scenario: 检查当前后台协作文档
- **WHEN** `workspace/agent-admin/web/src` 已达到零本地 UI 包运行时依赖 - **WHEN** 阅读当前后台 README 和前端基础文档
- **THEN** `workspace/agent-admin/web/packages/ui` 目录仍可保留,等待后续独立清理 - **THEN** 文档说明基础控件来自 `tdesign-react` 或 `tdesign-icons-react`
- **AND** 文档说明业务组合能力来自 `@gl/business-components`
- **AND** 文档不要求保留 `workspace/agent-admin/web/packages/ui`
### Requirement: 本轮表单迁移保持页面级组合 ### Requirement: 本轮表单迁移保持页面级组合
系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。 系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。
...@@ -83,4 +93,3 @@ TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Pur ...@@ -83,4 +93,3 @@ TBD - created by archiving change migrate-admin-ui-to-global-tdesign. Update Pur
- **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单 - **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单
- **THEN** 本轮继续使用页面级组合 - **THEN** 本轮继续使用页面级组合
- **AND** 系统不为这些内容扩展新的配置协议 - **AND** 系统不为这些内容扩展新的配置协议
# Web UI Components
这里放当前目录结构下首个承载的可复用 UI 组件。
组件必须遵循公司 Web 桌面端设计规范,以及 `architecture-spec/docs/architecture/component-guidelines.md`。
实现边界:
- 组件按全局可复用资产设计,不绑定单一业务页面。
- 组件内部不使用 Tailwind CSS。
- 组件需要自带完整规范样式,使用 CSS Variables + CSS Modules / 普通 CSS。
- 组件实现必须先有接口定义和失败测试,再补逻辑、样式和审核注释。
当前稳定导出入口为 `src/index.ts`,业务页面应从该入口消费组件。已建立的一期基础交互组件包括 `Button`、`Input`、`Textarea`、`SearchInput`、`Checkbox`、`Radio`、`Switch` 和 `Upload`。
`Upload` 组件族提供文件拖拽上传和图片/视频媒体墙两种设计形态,只负责 UI 状态和回调,不内置真实上传传输、业务校验或预览弹层。
.root {
display: grid;
width: 100%;
gap: var(--gl-spacing-md);
}
.fieldWidth {
width: 100%;
}
.fieldWidth[data-width='360'] {
max-width: 360px;
}
.fieldWidth[data-width='420'] {
max-width: 420px;
}
.fieldWidth[data-width='450'] {
max-width: 450px;
}
.fieldWidth[data-width] {
box-sizing: border-box;
}
.count {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: 18px;
}
.displayText {
min-height: var(--gl-control-height-md);
padding-top: 2px;
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
}
.readonlyPill {
display: inline-flex;
min-height: var(--gl-control-height-md);
align-items: center;
padding: 0 var(--gl-spacing-sm);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
}
.uploadBox {
display: grid;
gap: var(--gl-spacing-sm);
}
.uploadPreview {
display: grid;
gap: var(--gl-spacing-xs);
padding: var(--gl-spacing-sm);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
}
.uploadMedia {
display: block;
width: 100%;
max-width: 320px;
max-height: 220px;
border-radius: 8px;
object-fit: cover;
}
.uploadVideo {
width: 100%;
max-width: 320px;
max-height: 220px;
border-radius: 8px;
background: #000;
}
.uploadName {
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
word-break: break-all;
}
.uploadMeta {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: 18px;
}
.uploadActions {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-sm);
}
.uploadButton {
display: inline-flex;
min-height: var(--gl-control-height-md);
align-items: center;
justify-content: center;
padding: 0 var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-primary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
cursor: pointer;
}
.uploadButton:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.hiddenInput {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
clip-path: inset(50%);
white-space: nowrap;
}
.button {
display: inline-flex;
min-width: 64px;
align-items: center;
justify-content: center;
gap: var(--gl-spacing-xs);
border: 1px solid transparent;
border-radius: var(--gl-radius-sm);
font-weight: 500;
line-height: var(--gl-line-height-sm);
letter-spacing: 0;
cursor: pointer;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease,
opacity 120ms ease;
}
.button:focus-visible {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 24%, transparent);
outline-offset: 2px;
}
.button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.small {
height: 28px;
padding: 0 var(--gl-spacing-md);
font-size: var(--gl-font-size-xs);
}
.medium {
height: var(--gl-control-height-md);
padding: 0 var(--gl-spacing-lg);
font-size: var(--gl-font-size-sm);
}
.large {
height: 40px;
padding: 0 var(--gl-spacing-xl);
font-size: var(--gl-font-size-md);
}
.primary {
color: #fff;
background: var(--gl-color-primary);
}
.primary:hover:not(:disabled) {
background: var(--gl-color-primary-hover);
}
.default {
color: var(--gl-color-text-primary);
border-color: var(--gl-color-border-primary);
background: var(--gl-color-bg-container);
}
.default:hover:not(:disabled) {
border-color: var(--gl-color-primary);
color: var(--gl-color-primary);
}
.outline {
color: var(--gl-color-primary);
border-color: var(--gl-color-primary);
background: transparent;
}
.outline:hover:not(:disabled),
.text:hover:not(:disabled) {
background: color-mix(in srgb, var(--gl-color-primary) 8%, transparent);
}
.text {
min-width: auto;
color: var(--gl-color-primary);
background: transparent;
}
.danger {
color: #fff;
background: var(--gl-color-danger, #d92d20);
}
.icon {
display: inline-flex;
line-height: 0;
}
.spinner {
width: 14px;
height: 14px;
border: 2px solid currentColor;
border-top-color: transparent;
border-radius: 999px;
animation: spin 720ms linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
import type { ButtonHTMLAttributes, ReactNode } from 'react';
import styles from './Button.module.css';
import { cx } from './utils';
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
/** 组件库按钮的视觉类型,映射设计规范中的主按钮、次按钮、描边、文本和危险操作。 */
variant?: 'primary' | 'default' | 'outline' | 'text' | 'danger';
/** 控件高度尺寸,默认对齐桌面端 32px 表单控件高度。 */
size?: 'small' | 'medium' | 'large';
/** loading 时按钮进入忙碌态,同时禁用点击以避免重复提交。 */
loading?: boolean;
/** 左侧图标区域,业务侧可传入图标节点但不接管按钮核心样式。 */
icon?: ReactNode;
}
export function Button({
children,
className,
disabled,
icon,
loading = false,
size = 'medium',
type = 'button',
variant = 'default',
...props
}: ButtonProps) {
const isDisabled = disabled || loading;
return (
<button
className={cx(styles.button, styles[variant], styles[size], className)}
disabled={isDisabled}
type={type}
aria-busy={loading || undefined}
{...props}
>
{loading ? <span className={styles.spinner} aria-hidden="true" /> : null}
{!loading && icon ? <span className={styles.icon}>{icon}</span> : null}
{children}
</button>
);
}
.label {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-sm);
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-sm);
cursor: pointer;
}
.labelDisabled {
cursor: not-allowed;
opacity: 0.55;
}
.box {
display: inline-grid;
width: 16px;
height: 16px;
flex: 0 0 16px;
place-items: center;
border: 1px solid var(--gl-color-border-primary);
border-radius: 2px;
background: var(--gl-color-bg-container);
color: #fff;
transition:
background-color 120ms ease,
border-color 120ms ease;
}
.input {
position: absolute;
opacity: 0;
}
.input:focus-visible + .box {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 22%, transparent);
outline-offset: 2px;
}
.input:checked + .box,
.mixed {
border-color: var(--gl-color-primary);
background: var(--gl-color-primary);
}
import { forwardRef, useEffect, useRef } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';
import styles from './Checkbox.module.css';
import { cx } from './utils';
export interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type'> {
/** 复选框右侧文本,保持 label 包裹以扩大可点击区域。 */
label?: ReactNode;
/** 半选态用于树、表格批量选择等父子级选择场景。 */
indeterminate?: boolean;
onChange?: (checked: boolean) => void;
}
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(
{ checked, className, disabled, indeterminate = false, label, onChange, ...props },
forwardedRef,
) {
const innerRef = useRef<HTMLInputElement | null>(null);
const accessibleLabel = typeof label === 'string' ? label : props['aria-label'];
useEffect(() => {
if (innerRef.current) {
innerRef.current.indeterminate = indeterminate;
}
}, [indeterminate]);
return (
<label className={cx(styles.label, disabled && styles.labelDisabled, className)}>
<input
{...props}
ref={(node) => {
innerRef.current = node;
if (typeof forwardedRef === 'function') {
forwardedRef(node);
} else if (forwardedRef) {
forwardedRef.current = node;
}
}}
className={styles.input}
checked={checked}
disabled={disabled}
type="checkbox"
aria-label={accessibleLabel}
aria-checked={indeterminate ? 'mixed' : checked}
onChange={(event) => onChange?.(event.target.checked)}
/>
<span className={cx(styles.box, indeterminate && styles.mixed)} aria-hidden="true">
{indeterminate ? '−' : checked ? '✓' : null}
</span>
{label}
</label>
);
});
import type { InputHTMLAttributes } from 'react';
import styles from './Shared.module.css';
import { Input } from './Input';
export interface ColorPickerProps {
/** ColorPicker 先支持预设色和原生颜色输入,后续可扩展完整色板。 */
value?: string;
presets?: string[];
onChange?: (value: string) => void;
onClose?: () => void;
}
export function ColorPicker({ presets = ['#2468f2', '#039855', '#d92d20', '#dc6803'], value, onChange }: ColorPickerProps) {
return (
<div className={styles.row}>
{presets.map((color) => (
<button
key={color}
className={styles.control}
type="button"
aria-label={`选择颜色 ${color}`}
aria-pressed={color === value}
style={{ width: 28, height: 28, background: color }}
onClick={() => onChange?.(color)}
/>
))}
<input aria-label="自定义颜色" type="color" value={value} onChange={(event) => onChange?.(event.target.value)} />
</div>
);
}
export interface ColorInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'prefix' | 'value'> {
value?: string;
onChange?: (value: string) => void;
}
export function ColorInput({ value, onChange, ...props }: ColorInputProps) {
return <Input {...props} value={value} prefix={<span style={{ display: 'inline-block', width: 14, height: 14, borderRadius: 2, background: value }} />} onChange={onChange} />;
}
import type { ReactNode } from 'react';
import styles from './Shared.module.css';
import { cx } from './utils';
export interface CardProps {
/** Card 仅作为内容容器,不嵌套页面大区块。 */
title?: ReactNode;
extra?: ReactNode;
children?: ReactNode;
}
export function Card({ children, extra, title }: CardProps) {
return (
<section className={styles.card}>
{(title || extra) ? <header className={styles.between}><strong>{title}</strong>{extra}</header> : null}
{children}
</section>
);
}
export interface TagProps {
/** Tag 表达小粒度状态,closable 时只通知业务侧关闭意图。 */
status?: 'default' | 'success' | 'warning' | 'error' | 'info';
closable?: boolean;
onClose?: () => void;
children?: ReactNode;
}
export function Tag({ children, closable, onClose, status = 'default' }: TagProps) {
return (
<span className={cx(styles.tag, status !== 'default' && styles[status])}>
{children}
{closable ? (
<button
className={styles.tagCloseButton}
type="button"
aria-label={`关闭${children}`}
onClick={(event) => {
event.stopPropagation();
onClose?.();
}}
>
×
</button>
) : null}
</span>
);
}
export interface BadgeProps {
count?: number;
dot?: boolean;
status?: 'success' | 'processing' | 'error' | 'warning';
children?: ReactNode;
}
export function Badge({ children, count, dot, status }: BadgeProps) {
return (
<span className={styles.row}>
{children}
{dot ? <span className={cx(styles.statusDot, styles.info)}>{status === 'processing' ? '●' : '•'}</span> : null}
{count !== undefined ? <span className={cx(styles.tag, styles.error)}>{count}</span> : null}
</span>
);
}
export interface AvatarProps {
/** Avatar 文本态使用姓名首字作为圆形头像,视觉上固定为主色蓝底白字。 */
name?: string;
src?: string;
}
export function Avatar({ name = '?', src }: AvatarProps) {
return src ? (
<img className={cx(styles.avatar, styles.avatarCircle)} src={src} alt={name} width={32} height={32} />
) : (
<span className={cx(styles.avatar, styles.avatarCircle, styles.avatarText)} aria-label={name}>
{name.slice(0, 1)}
</span>
);
}
export interface AvatarGroupProps {
maxCount?: number;
children: ReactNode[];
}
export function AvatarGroup({ children, maxCount = children.length }: AvatarGroupProps) {
const visible = children.slice(0, maxCount);
const rest = children.length - visible.length;
return <span className={styles.avatarGroup}>{visible}{rest > 0 ? <span className={cx(styles.avatar, styles.avatarCircle, styles.avatarText)}>+{rest}</span> : null}</span>;
}
export interface StatisticProps {
title: ReactNode;
value: number | string;
prefix?: ReactNode;
suffix?: ReactNode;
trend?: 'up' | 'down';
}
export function Statistic({ prefix, suffix, title, trend, value }: StatisticProps) {
return <div className={styles.stack}><span className={styles.muted}>{title}</span><strong>{prefix}{value}{suffix}</strong>{trend ? <span>{trend === 'up' ? '上升' : '下降'}</span> : null}</div>;
}
export interface ProgressProps {
/** percentPosition 控制百分比文案相对进度条的位置,none 可用于紧凑场景。 */
percent: number;
status?: 'normal' | 'active' | 'success' | 'error';
percentPosition?: 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'none';
}
const progressPositionClass = {
left: styles.progressLeft,
right: styles.progressRight,
'top-left': styles.progressTopLeft,
'top-right': styles.progressTopRight,
'bottom-left': styles.progressBottomLeft,
'bottom-right': styles.progressBottomRight,
none: styles.progressNone,
};
export function Progress({ percent, percentPosition = 'right', status = 'normal' }: ProgressProps) {
const safePercent = Math.min(100, Math.max(0, percent));
const percentNode = percentPosition === 'none' ? null : <span className={styles.progressPercent}>{percent}%</span>;
return (
<div className={cx(styles.progressRoot, progressPositionClass[percentPosition])} data-testid="progress-root">
{(percentPosition === 'top-left' || percentPosition === 'top-right') ? percentNode : null}
<div className={styles.progressTrack} role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={safePercent}>
<div className={cx(styles.progressFill, status === 'error' && styles.progressError, status === 'success' && styles.progressSuccess)} data-testid="progress-fill" style={{ width: `${safePercent}%` }} />
</div>
{(percentPosition === 'left' || percentPosition === 'right' || percentPosition === 'bottom-left' || percentPosition === 'bottom-right') ? percentNode : null}
</div>
);
}
export interface TimelineItem {
title: ReactNode;
time?: ReactNode;
description?: ReactNode;
status?: 'done' | 'active' | 'wait' | 'error';
}
export function Timeline({ items }: { items: TimelineItem[] }) {
return <ol className={styles.stack}>{items.map((item, index) => <li key={index}><strong>{item.title}</strong> <span className={styles.muted}>{item.time}</span>{item.description ? <div>{item.description}</div> : null}</li>)}</ol>;
}
import { useEffect, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { Button } from './Button';
import { Icon } from './Icon';
import type { IconName } from './Icon';
import styles from './Shared.module.css';
import { cx } from './utils';
export interface AlertProps {
/** Alert 用于页面内反馈,type 决定语义色,不承载业务状态计算。 */
type?: 'info' | 'success' | 'warning' | 'error';
title?: ReactNode;
closable?: boolean;
onClose?: () => void;
children?: ReactNode;
}
export function Alert({ children, closable, onClose, title, type = 'info' }: AlertProps) {
return (
<div className={cx(styles.card, styles[type])} role="alert">
<div className={styles.between}>
<strong>{title}</strong>
{closable ? <button className={styles.plainButton} type="button" aria-label={`关闭${title}`} onClick={onClose}>×</button> : null}
</div>
{children}
</div>
);
}
export interface MessageItem {
/** key 用于区分消息实例,并作为自动关闭和手动关闭回调的稳定标识。 */
key: string;
type?: 'info' | 'success' | 'warning' | 'error';
content: ReactNode;
duration?: number;
closable?: boolean;
onClose?: (key: string) => void;
}
export interface MessageProps {
/** Message 用于右上角全局轻量反馈,不打断用户当前操作流。 */
items: MessageItem[];
defaultDuration?: number;
onClose?: (key: string) => void;
}
const messageIcon: Record<Required<MessageItem>['type'], { label: string; name: IconName }> = {
error: { label: '错误提示', name: 'close-circle' },
info: { label: '信息提示', name: 'info-circle' },
success: { label: '成功提示', name: 'check-circle' },
warning: { label: '警告提示', name: 'warning-circle' },
};
function MessageNotice({ defaultDuration, item, onClose }: { defaultDuration: number; item: MessageItem; onClose?: (key: string) => void }) {
const [visible, setVisible] = useState(true);
const type = item.type ?? 'info';
const close = () => {
setVisible(false);
item.onClose?.(item.key);
onClose?.(item.key);
};
useEffect(() => {
const duration = item.duration ?? defaultDuration;
if (duration <= 0) return undefined;
const timer = window.setTimeout(close, duration);
return () => window.clearTimeout(timer);
}, [defaultDuration, item.duration, item.key]);
if (!visible) return null;
return (
<div className={cx(styles.messageItem, styles[type])} role={type === 'error' ? 'alert' : 'status'} aria-label={String(item.content)}>
<span className={styles.messageContent}>
<Icon className={styles.messageIcon} label={messageIcon[type].label} name={messageIcon[type].name} size={16} />
<span>{item.content}</span>
</span>
{item.closable ? (
<button className={styles.plainButton} type="button" aria-label={`关闭${item.content}`} onClick={close}>
×
</button>
) : null}
</div>
);
}
export function Message({ defaultDuration = 3000, items, onClose }: MessageProps) {
return (
<div className={styles.messageTopRight} role="region" aria-label="全局消息提示">
{items.map((item) => (
<MessageNotice defaultDuration={defaultDuration} item={item} key={item.key} onClose={onClose} />
))}
</div>
);
}
export interface TooltipProps {
/** Tooltip 只展示辅助说明,不承载可点击操作。 */
content: ReactNode;
children: ReactNode;
}
export function Tooltip({ children, content }: TooltipProps) {
const [open, setOpen] = useState(false);
return (
<span className={styles.stack} onMouseEnter={() => setOpen(true)} onFocus={() => setOpen(true)}>
{children}
{open ? <span className={styles.popup} role="tooltip">{content}</span> : null}
</span>
);
}
export interface PopconfirmProps {
/** 二次确认用于破坏性或高风险操作,确认和取消都交给业务侧处理。 */
title: ReactNode;
children: ReactNode;
onConfirm?: () => void;
onCancel?: () => void;
}
export function Popconfirm({ children, onCancel, onConfirm, title }: PopconfirmProps) {
const [open, setOpen] = useState(false);
return (
<span className={styles.stack}>
<span onClick={() => setOpen(true)}>{children}</span>
{open ? (
<span className={cx(styles.popup, styles.popconfirmPopup)} role="dialog" aria-label={String(title)}>
<strong>{title}</strong>
<span className={styles.popconfirmActions} data-testid="popconfirm-actions">
<Button size="small" onClick={() => { setOpen(false); onCancel?.(); }}>取消</Button>
<Button size="small" variant="primary" onClick={() => { setOpen(false); onConfirm?.(); }}>确认</Button>
</span>
</span>
) : null}
</span>
);
}
export interface ModalProps {
/** Modal 是受控浮层,open 为唯一显示来源,避免内部状态和业务状态分叉。 */
open?: boolean;
title: ReactNode;
confirmLoading?: boolean;
footer?: ReactNode;
children?: ReactNode;
onOk?: () => void;
onCancel?: () => void;
}
export function Modal({ children, confirmLoading, footer, onCancel, onOk, open, title }: ModalProps) {
if (!open) return null;
return (
<div className={styles.overlay}>
<section className={styles.dialog} role="dialog" aria-modal="true" aria-label={String(title)}>
<header className={cx(styles.section, styles.between)}>
<strong>{title}</strong>
<button className={styles.plainButton} type="button" aria-label={`关闭${title}`} onClick={onCancel}>×</button>
</header>
<div className={styles.section}>{children}</div>
<footer className={cx(styles.section, styles.row, styles.modalFooter)} data-testid="modal-footer">
{footer ?? (
<>
<Button onClick={onCancel}>取消</Button>
<Button variant="primary" aria-busy={confirmLoading || undefined} onClick={onOk}>确定</Button>
</>
)}
</footer>
</section>
</div>
);
}
export interface DrawerProps {
/** Drawer 保留底层页面上下文,适合列表页侧边编辑或详情查看。 */
open?: boolean;
title: ReactNode;
placement?: 'left' | 'right';
/** width 支持数字像素值或 CSS 宽度字符串,方便页面按场景控制 320px/480px/640px 等宽度。 */
width?: number | string;
footer?: ReactNode;
children?: ReactNode;
onClose?: () => void;
}
const formatDrawerWidth = (width: number | string) => (typeof width === 'number' ? `${width}px` : width);
export function Drawer({ children, footer, onClose, open, placement = 'right', title, width = '420px' }: DrawerProps) {
if (!open) return null;
const drawerStyle: CSSProperties = {
width: formatDrawerWidth(width),
...(placement === 'left' ? { left: 0, right: 'auto' } : undefined),
};
return (
<div className={styles.drawerOverlay} data-testid="drawer-overlay">
<aside className={styles.drawer} style={drawerStyle} role="dialog" aria-modal="true" aria-label={String(title)}>
<header className={cx(styles.drawerHeader, styles.between)}>
<strong>{title}</strong>
<button className={styles.plainButton} type="button" aria-label={`关闭${title}`} onClick={onClose}>×</button>
</header>
<div className={styles.drawerBody}>{children}</div>
{footer ? <footer className={styles.drawerFooter}>{footer}</footer> : null}
</aside>
</div>
);
}
import { cloneElement, createContext, isValidElement, useContext, useEffect, useMemo, useRef, useState } from 'react';
import type { FormEvent, ReactElement, ReactNode } from 'react';
import styles from './Shared.module.css';
import { cx } from './utils';
/** 判断子元素是否为简单输入控件(应建立 label 关联) */
const isSimpleInputControl = (child: ReactNode): boolean => {
if (!isValidElement(child)) return false;
// Input、Textarea、Select 等简单输入控件应建立 label 关联
// 上传组件(含隐藏 file input)不建立关联,避免误触发
const type = child.type;
if (typeof type === 'string') {
return type === 'input' || type === 'textarea' || type === 'select';
}
// 对于自定义组件,检查 displayName 或组件名
const displayName = (type as { displayName?: string }).displayName ?? '';
const name = typeof type === 'function' ? type.name : '';
const componentName = displayName || name;
// 简单输入控件:Input、Textarea、Select、DatePicker
// 复杂控件:MediaWall、UploadDragger、Upload、Switch(不含隐藏 file input,但已有语义)
const simpleControls = ['Input', 'Textarea', 'Select', 'DatePicker'];
return simpleControls.some((ctrl) => componentName.includes(ctrl));
};
/** 生成唯一字段 id */
const useFieldId = (name: string | undefined, testIdLabel: string): string => {
const idRef = useRef<string | undefined>(undefined);
if (!idRef.current) {
idRef.current = name ?? `field-${testIdLabel}-${Math.random().toString(36).slice(2, 8)}`;
}
return idRef.current;
};
export type FormValues = Record<string, unknown>;
export interface FormRule {
/** 必填规则用于提交前阻止空值,并把错误展示在字段下方。 */
required?: boolean;
message?: string;
}
export interface FormProps {
/** 初始值只在表单首次挂载时注入,后续字段值由 Form 内部状态托管。 */
initialValues?: FormValues;
/** 表单项列数,默认每个 FormItem 独占一行,双列时两个 FormItem 一行。 */
columns?: 1 | 2;
children: ReactNode;
className?: string;
onFinish?: (values: FormValues) => void;
}
interface FormContextValue {
errors: Record<string, string>;
registerField: (name: string, rules: FormRule[]) => () => void;
setFieldValue: (name: string, value: unknown) => void;
values: FormValues;
}
const FormContext = createContext<FormContextValue | null>(null);
const isEmptyValue = (value: unknown) => value === undefined || value === null || String(value).trim() === '';
export function Form({ children, className, columns = 1, initialValues = {}, onFinish }: FormProps) {
const [values, setValues] = useState<FormValues>(initialValues);
const [errors, setErrors] = useState<Record<string, string>>({});
const rulesRef = useRef<Record<string, FormRule[]>>({});
const contextValue = useMemo<FormContextValue>(() => ({
errors,
registerField: (name, rules) => {
rulesRef.current[name] = rules;
return () => {
delete rulesRef.current[name];
};
},
setFieldValue: (name, value) => {
setValues((current) => ({ ...current, [name]: value }));
setErrors((current) => {
if (!current[name]) {
return current;
}
const nextErrors = { ...current };
delete nextErrors[name];
return nextErrors;
});
},
values,
}), [errors, values]);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const nextErrors: Record<string, string> = {};
Object.entries(rulesRef.current).forEach(([name, rules]) => {
const requiredRule = rules.find((rule) => rule.required);
if (requiredRule && isEmptyValue(values[name])) {
nextErrors[name] = requiredRule.message ?? '该字段为必填项';
}
});
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
onFinish?.(values);
}
};
return (
<FormContext.Provider value={contextValue}>
<form
className={cx(styles.form, columns === 2 ? styles.formColumnsTwo : styles.formColumnsOne, className)}
data-testid="form-root"
onSubmit={handleSubmit}
>
{children}
</form>
</FormContext.Provider>
);
}
export interface FormItemProps {
/** 表单项负责把标签、必填、帮助和错误信息放在字段附近。 */
label: ReactNode;
/** 输入控件右侧的弱提示文字,用于短说明,不替代控件下方 help。 */
tips?: ReactNode;
name?: string;
required?: boolean;
rules?: FormRule[];
layout?: 'vertical' | 'horizontal';
/** 在双列表单中控制单项宽度,span=2 可独占整行。 */
span?: 1 | 2;
help?: ReactNode;
error?: ReactNode;
children: ReactNode;
}
const labelToTestId = (label: ReactNode) => (typeof label === 'string' || typeof label === 'number' ? String(label) : 'field');
export function FormItem({ children, error, help, label, layout = 'vertical', name, required, rules = [], span = 1, tips }: FormItemProps) {
const form = useContext(FormContext);
const fieldRules = required && !rules.some((rule) => rule.required) ? [{ required: true }, ...rules] : rules;
const fieldError = (name ? form?.errors[name] : undefined) ?? error;
const isRequired = required || fieldRules.some((rule) => rule.required);
const testIdLabel = labelToTestId(label);
const fieldId = useFieldId(name, testIdLabel);
const isSimpleInput = isSimpleInputControl(children);
useEffect(() => {
if (!form || !name) {
return undefined;
}
return form.registerField(name, fieldRules);
}, [fieldRules, form, name]);
const control = name && form && isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, {
'aria-invalid': fieldError ? true : undefined,
id: isSimpleInput ? fieldId : undefined,
onChange: (nextValue: unknown) => {
const originalOnChange = (children as ReactElement<{ onChange?: (value: unknown) => void }>).props.onChange;
originalOnChange?.(nextValue);
form.setFieldValue(name, typeof nextValue === 'object' && nextValue !== null && 'target' in nextValue
? (nextValue as { target?: { value?: unknown } }).target?.value
: nextValue);
},
status: typeof children.type === 'string' ? undefined : fieldError ? 'error' : undefined,
value: form.values[name] ?? '',
})
: isSimpleInput && isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, { id: fieldId })
: children;
return (
<div
className={cx(
styles.formItem,
layout === 'horizontal' ? styles.formItemHorizontal : styles.formItemVertical,
span === 2 ? styles.formItemSpanTwo : styles.formItemSpanOne,
)}
data-testid={`form-item-${testIdLabel}`}
>
<label className={styles.formLabel} data-testid={`form-label-${testIdLabel}`} htmlFor={isSimpleInput ? fieldId : undefined}>
{isRequired ? <span className={styles.formRequired}>*</span> : null}
<span>{label}</span>
</label>
<span className={styles.formControl}>
<span className={styles.formMain} data-testid={`form-main-${testIdLabel}`}>
{control}
{tips ? <span className={styles.formTips}>{tips}</span> : null}
</span>
{help ? <span className={styles.muted}>{help}</span> : null}
<span className={styles.formErrorSlot} data-testid={`form-error-${testIdLabel}`}>
{fieldError ? <span role="alert" aria-label={String(fieldError)} className={styles.formErrorText}>{fieldError}</span> : null}
</span>
</span>
</div>
);
}
export type IconName =
| 'check-circle'
| 'chevron-down'
| 'chevron-left'
| 'chevron-right'
| 'close-circle'
| 'download'
| 'eye'
| 'file'
| 'info-circle'
| 'play'
| 'plus'
| 'refresh'
| 'search'
| 'trash'
| 'upload'
| 'warning-circle';
export interface IconProps {
name: IconName;
size?: number;
label?: string;
className?: string;
}
const paths: Record<IconName, string> = {
'check-circle': 'M9 12l2 2 4-5 M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18',
'chevron-down': 'M6 9l6 6 6-6',
'chevron-left': 'M15 6l-6 6 6 6',
'chevron-right': 'M9 6l6 6-6 6',
'close-circle': 'M9 9l6 6 M15 9l-6 6 M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18',
download: 'M12 3v12 M7 10l5 5 5-5 M5 21h14',
eye: 'M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6 M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6',
file: 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5z M14 3v5h5',
'info-circle': 'M12 10v6 M12 7h.01 M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18',
play: 'M8 5v14l11-7-11-7z',
plus: 'M12 5v14 M5 12h14',
refresh: 'M20 6v5h-5 M4 18v-5h5 M18.5 9A7 7 0 0 0 6.8 6.8L4 11 M5.5 15A7 7 0 0 0 17.2 17.2L20 13',
search: 'M10.5 17a6.5 6.5 0 1 1 4.6-1.9L20 20',
trash: 'M4 7h16 M10 11v6 M14 11v6 M6 7l1 14h10l1-14 M9 7V4h6v3',
upload: 'M12 21V9 M7 14l5-5 5 5 M5 21h14',
'warning-circle': 'M12 8v5 M12 16h.01 M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18',
};
/** 组件库内部统一图标资产,避免各组件散落使用临时文本箭头。 */
export function Icon({ className, label, name, size = 16 }: IconProps) {
return (
<svg
aria-hidden={label ? undefined : 'true'}
aria-label={label}
className={className}
data-icon={name}
fill="none"
height={size}
role={label ? 'img' : undefined}
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2.4"
viewBox="0 0 24 24"
width={size}
>
<path d={paths[name]} />
</svg>
);
}
.field {
display: inline-flex;
width: 100%;
min-width: 0;
align-items: center;
gap: var(--gl-spacing-xs);
min-height: var(--gl-control-height-md);
padding: 0 var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-primary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
transition:
border-color 120ms ease,
box-shadow 120ms ease,
background-color 120ms ease;
}
.field:hover {
border-color: var(--gl-color-primary);
}
.field:focus-within {
border-color: var(--gl-color-primary);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--gl-color-primary) 18%, transparent);
}
.fieldDisabled {
cursor: not-allowed;
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-secondary);
}
.fieldError {
border-color: var(--gl-color-danger, #d92d20);
}
.fieldWarning {
border-color: var(--gl-color-warning, #dc6803);
}
.fieldSuccess {
border-color: var(--gl-color-success, #039855);
}
.affix {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-sm);
}
.counter {
flex: 0 0 auto;
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
white-space: nowrap;
}
.input {
width: 100%;
min-width: 0;
height: 30px;
border: 0;
outline: 0;
background: transparent;
color: inherit;
font: inherit;
font-size: var(--gl-font-size-sm);
}
.input::placeholder {
color: var(--gl-color-text-secondary);
}
.input:disabled {
cursor: not-allowed;
}
.iconButton {
display: inline-flex;
width: 20px;
height: 20px;
flex: 0 0 auto;
align-items: center;
justify-content: center;
border: 0;
border-radius: var(--gl-radius-sm);
background: transparent;
color: var(--gl-color-text-secondary);
cursor: pointer;
}
.iconButton:hover:not(:disabled) {
color: var(--gl-color-text-primary);
background: var(--gl-color-fill-hover);
}
.searchButton {
width: auto;
padding: 0 var(--gl-spacing-xs);
font-size: var(--gl-font-size-sm);
}
import { forwardRef, useState } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';
import styles from './Input.module.css';
import { Icon } from './Icon';
import { cx } from './utils';
export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'prefix' | 'size'> {
/** 左侧前缀,可用于金额、图标或字段上下文提示。 */
prefix?: ReactNode;
/** 右侧后缀,可用于单位、状态图标或补充信息。 */
suffix?: ReactNode;
/** 状态样式用于和 FormItem 校验信息协同展示。 */
status?: 'default' | 'success' | 'warning' | 'error';
/** 是否显示输入长度,默认使用简洁的当前值/上限格式。 */
showCount?: boolean;
/** 是否展示清空按钮,受控和非受控场景都通过字符串值回调给业务侧。 */
allowClear?: boolean;
onChange?: (value: string) => void;
onClear?: () => void;
}
export interface SearchInputProps extends InputProps {
/** 点击搜索按钮或按下 Enter 时触发,参数为当前输入值。 */
onSearch?: (value: string) => void;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
allowClear = false,
className,
defaultValue,
disabled,
onChange,
onClear,
prefix,
status = 'default',
suffix,
showCount = false,
value,
...props
},
ref,
) {
const [innerValue, setInnerValue] = useState(defaultValue?.toString() ?? '');
const currentValue = value === undefined ? innerValue : String(value);
const emitChange = (nextValue: string) => {
if (value === undefined) {
setInnerValue(nextValue);
}
onChange?.(nextValue);
};
const clearLabel = props['aria-label'] ? `清空${props['aria-label']}` : '清空输入';
const countLabel = props.maxLength !== undefined ? `${currentValue.length}/${props.maxLength}` : String(currentValue.length);
return (
<span
className={cx(
styles.field,
status === 'error' && styles.fieldError,
status === 'warning' && styles.fieldWarning,
status === 'success' && styles.fieldSuccess,
disabled && styles.fieldDisabled,
className,
)}
>
{prefix ? <span className={styles.affix}>{prefix}</span> : null}
<input
{...props}
ref={ref}
className={styles.input}
disabled={disabled}
value={currentValue}
aria-invalid={status === 'error' || undefined}
onChange={(event) => emitChange(event.target.value)}
/>
{showCount ? <span className={styles.counter}>{countLabel}</span> : null}
{allowClear && currentValue ? (
<button
aria-label={clearLabel}
className={styles.iconButton}
disabled={disabled}
type="button"
onClick={() => {
emitChange('');
onClear?.();
}}
>
×
</button>
) : null}
{suffix ? <span className={styles.affix}>{suffix}</span> : null}
</span>
);
});
export const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(function SearchInput(
{ onChange, onClear, onKeyDown, onSearch, prefix = <Icon label="搜索图标" name="search" size={18} />, ...props },
ref,
) {
const [searchValue, setSearchValue] = useState(props.defaultValue?.toString() ?? props.value?.toString() ?? '');
const currentValue = props.value === undefined ? searchValue : String(props.value);
const handleSearch = () => {
onSearch?.(currentValue);
};
return (
<Input
{...props}
ref={ref}
prefix={prefix}
onChange={(nextValue) => {
if (props.value === undefined) {
setSearchValue(nextValue);
}
onChange?.(nextValue);
}}
onClear={() => {
if (props.value === undefined) {
setSearchValue('');
}
onClear?.();
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
onSearch?.(currentValue);
}
onKeyDown?.(event);
}}
suffix={
<button className={cx(styles.iconButton, styles.searchButton)} type="button" onClick={handleSearch}>
搜索
</button>
}
/>
);
});
import type { ReactNode } from 'react';
import styles from './Shared.module.css';
import { Icon } from './Icon';
import { cx } from './utils';
export interface TabsItem {
key: string;
label: ReactNode;
disabled?: boolean;
children?: ReactNode;
}
export interface NavigationItem {
key: string;
label: ReactNode;
disabled?: boolean;
children?: NavigationItem[];
}
export interface NavigationProps {
/** Navigation 通过受控 activeKey 承载后台层级菜单,业务侧只传配置和路由状态。 */
activeKey?: string;
items: NavigationItem[];
ariaLabel?: string;
onChange?: (key: string) => void;
}
export function Navigation({ activeKey, ariaLabel = '导航', items, onChange }: NavigationProps) {
return (
<nav className={styles.navigation} aria-label={ariaLabel}>
{items.map((item) => {
const hasChildren = Boolean(item.children?.length);
const parentActive = hasChildren && item.children?.some((child) => child.key === activeKey);
return (
<div key={item.key} className={styles.navigationGroup}>
<button
className={styles.navigationItem}
data-active-parent={parentActive ? 'true' : undefined}
disabled={item.disabled}
type="button"
onClick={() => {
if (!item.disabled) onChange?.(item.key);
}}
>
{item.label}
</button>
{hasChildren ? (
<div className={styles.navigationChildren}>
{item.children?.map((child) => {
const selected = child.key === activeKey;
return (
<button
key={child.key}
className={cx(styles.navigationItem, styles.navigationChild, selected && styles.navigationItemActive)}
aria-current={selected ? 'page' : undefined}
disabled={child.disabled}
type="button"
onClick={() => {
if (!child.disabled) onChange?.(child.key);
}}
>
{child.label}
</button>
);
})}
</div>
) : null}
</div>
);
})}
</nav>
);
}
export interface TabsProps {
/** Tabs 采用受控 activeKey,切换只通过 onChange 通知业务侧。 */
activeKey: string;
items: TabsItem[];
onChange?: (key: string) => void;
}
export function Tabs({ activeKey, items, onChange }: TabsProps) {
const active = items.find((item) => item.key === activeKey);
return (
<div className={styles.tabs}>
<div className={styles.tabList} role="tablist">
{items.map((item) => (
<button
key={item.key}
className={styles.tab}
disabled={item.disabled}
role="tab"
type="button"
aria-selected={item.key === activeKey}
onClick={() => {
if (!item.disabled) onChange?.(item.key);
}}
>
{item.label}
</button>
))}
</div>
<div role="tabpanel">{active?.children}</div>
</div>
);
}
export interface StepsProps {
current: number;
status?: 'process' | 'finish' | 'error';
items: Array<{ title: ReactNode }>;
}
export function Steps({ current, items, status = 'process' }: StepsProps) {
return (
<ol className={styles.row}>
{items.map((item, index) => {
const state = index < current ? '完成' : index === current && status === 'error' ? '错误' : index === current ? '进行中' : '等待';
return <li key={index} className={styles.stack}><strong>{item.title}</strong><span>{state}</span></li>;
})}
</ol>
);
}
export interface CollapseItem {
key: string;
title: ReactNode;
children?: ReactNode;
disabled?: boolean;
}
export interface CollapseProps {
/** Collapse 支持多面板展开,activeKeys 由外部控制。 */
activeKeys: string[];
items: CollapseItem[];
onChange?: (keys: string[]) => void;
}
export function Collapse({ activeKeys, items, onChange }: CollapseProps) {
return (
<div className={styles.stack}>
{items.map((item) => {
const open = activeKeys.includes(item.key);
return (
<section key={item.key} className={styles.panel}>
<button
className={cx(styles.fieldButton, styles.control)}
disabled={item.disabled}
type="button"
aria-expanded={open}
onClick={() => onChange?.(open ? activeKeys.filter((key) => key !== item.key) : [...activeKeys, item.key])}
>
<span>{item.title}</span>
<Icon name={open ? 'chevron-down' : 'chevron-right'} />
</button>
{open ? <div className={styles.section}>{item.children}</div> : null}
</section>
);
})}
</div>
);
}
export interface EmptyProps {
description?: ReactNode;
action?: ReactNode;
}
export function Empty({ action, description = '暂无数据' }: EmptyProps) {
return <div className={styles.stack}><div className={styles.muted}>{description}</div>{action}</div>;
}
export interface StatePlaceholderProps {
/** StatePlaceholder 表达内容区状态;失败态明确区别于空数据,不使用“暂无数据”兜底。 */
state: 'empty' | 'filtered-empty' | 'error' | 'forbidden' | 'offline';
title?: ReactNode;
description?: ReactNode;
primaryAction?: ReactNode;
secondaryAction?: ReactNode;
icon?: ReactNode;
}
const stateDefaults: Record<StatePlaceholderProps['state'], { title: string; description: string; role: 'status' | 'alert'; icon: ReactNode }> = {
empty: { title: '暂无数据', description: '当前内容为空', role: 'status', icon: <Icon name="file" /> },
'filtered-empty': { title: '未找到匹配结果', description: '请调整搜索或筛选条件', role: 'status', icon: <Icon name="search" /> },
error: { title: '加载失败', description: '数据请求失败,请稍后重试', role: 'alert', icon: <Icon name="warning-circle" /> },
forbidden: { title: '权限受限', description: '当前账号暂无访问权限', role: 'alert', icon: <Icon name="close-circle" /> },
offline: { title: '网络不可用', description: '请检查网络连接后重试', role: 'alert', icon: <Icon name="refresh" /> },
};
const stateClassNames: Record<StatePlaceholderProps['state'], string | undefined> = {
empty: undefined,
'filtered-empty': styles.statePlaceholderFiltered,
error: styles.statePlaceholderError,
forbidden: styles.statePlaceholderForbidden,
offline: styles.statePlaceholderOffline,
};
export function StatePlaceholder({ description, icon, primaryAction, secondaryAction, state, title }: StatePlaceholderProps) {
const defaults = stateDefaults[state];
const resolvedTitle = title ?? defaults.title;
return (
<div className={cx(styles.statePlaceholder, stateClassNames[state])} role={defaults.role} aria-label={String(resolvedTitle)}>
<div className={styles.statePlaceholderIcon} aria-hidden="true">{icon ?? defaults.icon}</div>
<strong className={styles.statePlaceholderTitle}>{resolvedTitle}</strong>
<div className={styles.muted}>{description ?? defaults.description}</div>
{(primaryAction || secondaryAction) ? <div className={styles.statePlaceholderActions}>{primaryAction}{secondaryAction}</div> : null}
</div>
);
}
export function Skeleton({ active = false }: { active?: boolean }) {
return <div aria-label="加载占位" className={cx(styles.skeleton, active && styles.stack)} style={{ width: '100%', height: 16 }} />;
}
export function SkeletonAvatar() {
return <div aria-label="头像加载占位" className={styles.skeleton} style={{ width: 32, height: 32, borderRadius: 999 }} />;
}
export function SkeletonParagraph({ rows = 3 }: { rows?: number }) {
return <div aria-label="段落加载占位" className={styles.stack}>{Array.from({ length: rows }, (_, index) => <div key={index} className={styles.skeleton} style={{ width: `${100 - index * 12}%`, height: 14 }} />)}</div>;
}
export function SkeletonButton() {
return <div aria-label="按钮加载占位" className={styles.skeleton} style={{ width: 72, height: 32 }} />;
}
export function SkeletonInput() {
return <div aria-label="输入框加载占位" className={styles.skeleton} style={{ width: 180, height: 32 }} />;
}
import { useState } from 'react';
import styles from './Shared.module.css';
import { cx } from './utils';
export interface PaginationProps {
/** current/pageSize/total 共同描述后台列表分页状态。 */
current: number;
pageSize: number;
total: number;
pageSizeOptions?: number[];
onChange?: (page: number, pageSize: number) => void;
}
export function Pagination({ current, pageSize, pageSizeOptions = [10, 20, 50], total, onChange }: PaginationProps) {
const [jump, setJump] = useState('');
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const pages = Array.from({ length: Math.min(totalPages, 5) }, (_, index) => index + 1);
const submitJump = () => onChange?.(Number(jump), pageSize);
return (
<div className={styles.between}>
<span className={styles.muted}>共 {total} 条</span>
<div className={styles.row}>
{pages.map((page) => (
<button key={page} className={cx(styles.control, page === current && styles.paginationCurrent)} type="button" aria-label={`第 ${page} 页`} aria-current={page === current ? 'page' : undefined} onClick={() => onChange?.(page, pageSize)}>
{page}
</button>
))}
<select aria-label="每页条数" className={styles.control} value={pageSize} onChange={(event) => onChange?.(1, Number(event.target.value))}>
{pageSizeOptions.map((option) => (
<option key={option} value={option}>
{option} 条/页
</option>
))}
</select>
<input
aria-label="跳至页码"
className={styles.control}
value={jump}
onChange={(event) => setJump(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') submitJump();
}}
/>
<button className={styles.control} type="button" onClick={submitJump}>
跳转
</button>
</div>
</div>
);
}
.label {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-sm);
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-sm);
cursor: pointer;
}
.labelDisabled {
cursor: not-allowed;
opacity: 0.55;
}
.dot {
display: inline-grid;
width: 16px;
height: 16px;
flex: 0 0 16px;
place-items: center;
border: 1px solid var(--gl-color-border-primary);
border-radius: 999px;
background: var(--gl-color-bg-container);
transition: border-color 120ms ease;
}
.dot::after {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--gl-color-primary);
content: '';
transform: scale(0);
transition: transform 120ms ease;
}
.input {
position: absolute;
opacity: 0;
}
.input:focus-visible + .dot {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 22%, transparent);
outline-offset: 2px;
}
.input:checked + .dot {
border-color: var(--gl-color-primary);
}
.input:checked + .dot::after {
transform: scale(1);
}
import { forwardRef } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';
import styles from './Radio.module.css';
import { cx } from './utils';
export interface RadioProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type'> {
/** 单选项文本,业务侧通过相同 name 组合出互斥选择组。 */
label?: ReactNode;
onChange?: (value: string) => void;
}
export const Radio = forwardRef<HTMLInputElement, RadioProps>(function Radio(
{ className, disabled, label, onChange, value, ...props },
ref,
) {
const accessibleLabel = typeof label === 'string' ? label : props['aria-label'];
return (
<label className={cx(styles.label, disabled && styles.labelDisabled, className)}>
<input
{...props}
ref={ref}
className={styles.input}
disabled={disabled}
type="radio"
value={value}
aria-label={accessibleLabel}
onChange={() => undefined}
onClick={() => {
if (!disabled) {
onChange?.(String(value ?? ''));
}
}}
/>
<span className={styles.dot} aria-hidden="true" />
{label}
</label>
);
});
.root {
display: grid;
gap: var(--gl-spacing-md);
}
.viewport {
overflow: hidden;
transition: max-height 240ms ease;
will-change: max-height;
}
.fields {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-md) var(--gl-spacing-lg);
align-items: flex-start;
}
.item {
box-sizing: border-box;
display: flex;
align-items: center;
gap: var(--gl-spacing-sm);
width: var(--gl-search-item-width, 284px);
min-width: 0;
}
.itemWide {
width: var(--gl-search-item-wide-width, 484px);
}
.label {
flex: 0 0 var(--gl-search-label-width, 72px);
min-width: 0;
overflow: hidden;
color: var(--gl-color-text-secondary);
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
}
.control {
flex: 0 0 auto;
width: var(--gl-search-control-width, 200px);
min-width: 0;
}
.controlWide {
width: var(--gl-search-control-wide-width, 400px);
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--gl-spacing-sm);
}
.toggleButton {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-xs);
}
.toggleIcon {
transition: transform 240ms ease;
}
.toggleIconExpanded {
transform: rotate(180deg);
}
.searchButton,
.resetButton {
min-width: 88px;
}
import { useState, type ReactNode } from 'react';
import { Select as TDesignSelect } from 'tdesign-react';
import type {
SelectOption as TDesignSelectOption,
SelectValue,
} from 'tdesign-react/es/select/type';
export interface SelectOption {
label: ReactNode;
value: string;
disabled?: boolean;
}
interface SelectBaseProps {
options: SelectOption[];
placeholder?: string;
allowClear?: boolean;
disabled?: boolean;
className?: string;
'aria-label'?: string;
}
export interface SelectSingleProps extends SelectBaseProps {
multiple?: false;
value?: string;
onChange?: (value: string | undefined, option: SelectOption | undefined) => void;
}
export interface SelectMultipleProps extends SelectBaseProps {
multiple: true;
value?: string[];
onChange?: (value: string[], option: SelectOption | undefined) => void;
}
export type SelectProps = SelectSingleProps | SelectMultipleProps;
function toTDesignOptions(options: SelectOption[]): TDesignSelectOption[] {
return options.map((option) => ({
label: option.label,
value: option.value,
disabled: option.disabled,
}));
}
function normalizeSingleValue(value: SelectValue): string | undefined {
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : undefined;
return typeof value === 'string' ? value : undefined;
}
function normalizeMultipleValue(value: SelectValue): string[] {
if (!Array.isArray(value)) return typeof value === 'string' ? [value] : [];
return value.filter((item): item is string => typeof item === 'string');
}
export function Select(props: SelectProps) {
const {
allowClear,
className,
disabled,
options,
placeholder = '请选择',
multiple,
value,
onChange,
'aria-label': ariaLabel,
} = props;
const isControlled = Object.prototype.hasOwnProperty.call(props, 'value');
const [innerValue, setInnerValue] = useState<string | string[] | undefined>(multiple ? [] : undefined);
const currentValue = isControlled ? value : innerValue;
const selectedOption = !multiple && typeof currentValue === 'string'
? options.find((item) => item.value === currentValue)
: undefined;
return (
<TDesignSelect
aria-label={ariaLabel}
className={className}
clearable={allowClear}
disabled={disabled}
inputProps={{
'aria-disabled': disabled,
'aria-label': ariaLabel,
role: 'combobox',
} as never}
multiple={multiple}
options={toTDesignOptions(options)}
placeholder={placeholder}
value={currentValue}
valueDisplay={!multiple ? selectedOption?.label : undefined}
onChange={(nextValue, context) => {
const changedOption = context.option as { value?: unknown } | undefined;
const option = context.option
? options.find((item) => item.value === String(changedOption?.value))
: undefined;
if (multiple) {
const normalizedValue = normalizeMultipleValue(nextValue);
if (!isControlled) setInnerValue(normalizedValue);
(onChange as SelectMultipleProps['onChange'] | undefined)?.(normalizedValue, option);
return;
}
const normalizedValue = normalizeSingleValue(nextValue);
if (!isControlled) setInnerValue(normalizedValue);
(onChange as SelectSingleProps['onChange'] | undefined)?.(normalizedValue, option);
}}
/>
);
}
.switch {
position: relative;
display: inline-flex;
width: 38px;
height: 22px;
align-items: center;
border: 0;
border-radius: 999px;
background: var(--gl-color-text-secondary);
cursor: pointer;
transition:
background-color 120ms ease,
opacity 120ms ease;
}
.switch:focus-visible {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 24%, transparent);
outline-offset: 2px;
}
.switch:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.checked {
background: var(--gl-color-primary);
}
.handle {
position: absolute;
left: 3px;
width: 16px;
height: 16px;
border-radius: 999px;
background: #fff;
box-shadow: 0 1px 2px rgb(16 24 40 / 16%);
transition: transform 120ms ease;
}
.checked .handle {
transform: translateX(16px);
}
.loading .handle::after {
position: absolute;
inset: 4px;
border: 1px solid var(--gl-color-primary);
border-top-color: transparent;
border-radius: 999px;
animation: spin 720ms linear infinite;
content: '';
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
import { forwardRef } from 'react';
import type { ButtonHTMLAttributes } from 'react';
import styles from './Switch.module.css';
import { cx } from './utils';
export interface SwitchProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
/** 受控开关值;组件只通过 onChange 请求变更,不自行持久化业务状态。 */
checked?: boolean;
/** loading 表示异步变更中,期间禁用点击并暴露 aria-busy。 */
loading?: boolean;
onChange?: (checked: boolean) => void;
}
export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(function Switch(
{ checked = false, className, disabled, loading = false, onChange, type, ...props },
ref,
) {
const isDisabled = disabled || loading;
return (
<button
{...props}
className={cx(styles.switch, checked && styles.checked, loading && styles.loading, className)}
disabled={isDisabled}
ref={ref}
role="switch"
type={type ?? 'button'}
aria-checked={checked}
aria-busy={loading || undefined}
onClick={() => onChange?.(!checked)}
>
<span className={styles.handle} aria-hidden="true" />
</button>
);
});
import { isValidElement, type ReactNode } from 'react';
import styles from './Shared.module.css';
import { Empty, type EmptyProps } from './Navigation';
export interface TableColumn<T extends Record<string, unknown>> {
title: ReactNode;
dataIndex?: keyof T;
key?: string;
sorter?: boolean;
render?: (value: unknown, record: T, index: number) => ReactNode;
}
export interface TableProps<T extends Record<string, unknown>> {
/** rowKey 固定每行身份,是列表选择、更新和测试定位的基础。 */
rowKey: keyof T | ((record: T) => string);
columns: Array<TableColumn<T>>;
dataSource: T[];
loading?: boolean;
/** empty 是表格空数据时的统一插槽;新代码优先使用它承载说明、操作或完整自定义节点。 */
empty?: ReactNode | EmptyProps;
/** emptyText 保留兼容早期纯文本空状态,后续业务建议迁移到 empty。 */
emptyText?: ReactNode;
rowSelection?: {
selectedRowKeys: string[];
onChange?: (keys: string[], rows: T[]) => void;
};
onSort?: (key: string, order: 'ascend' | 'descend') => void;
}
function getKey<T extends Record<string, unknown>>(rowKey: TableProps<T>['rowKey'], record: T) {
return typeof rowKey === 'function' ? rowKey(record) : String(record[rowKey]);
}
function isEmptyConfig(empty: TableProps<Record<string, unknown>>['empty']): empty is EmptyProps {
return Boolean(empty && typeof empty === 'object' && !Array.isArray(empty) && !isValidElement(empty));
}
function renderEmptyState(empty: TableProps<Record<string, unknown>>['empty'], emptyText: ReactNode) {
if (isEmptyConfig(empty)) {
return <Empty {...empty} />;
}
return empty ?? <Empty description={emptyText} />;
}
function renderLoadingRows(columnCount: number) {
return Array.from({ length: 3 }, (_, rowIndex) => (
<tr key={rowIndex} aria-label="加载占位行">
{Array.from({ length: columnCount }, (_, columnIndex) => (
<td key={columnIndex}>
<span className={styles.tableSkeletonLine} />
</td>
))}
</tr>
));
}
export function Table<T extends Record<string, unknown>>({ columns, dataSource, empty, emptyText = '暂无数据', loading, rowKey, rowSelection, onSort }: TableProps<T>) {
const columnCount = columns.length + (rowSelection ? 1 : 0);
if (loading) {
return (
<div role="status" aria-label="表格加载中" className={styles.tableLoading}>
<table className={styles.table}>
<thead>
<tr>
{rowSelection ? <th>选择</th> : null}
{columns.map((column) => {
const key = String(column.key ?? column.dataIndex ?? column.title);
return <th key={key} scope="col">{column.title}</th>;
})}
</tr>
</thead>
<tbody>{renderLoadingRows(columnCount)}</tbody>
</table>
</div>
);
}
return (
<table className={styles.table}>
<thead>
<tr>
{rowSelection ? <th>选择</th> : null}
{columns.map((column) => {
const key = String(column.key ?? column.dataIndex ?? column.title);
return (
<th key={key} scope="col">
{column.sorter ? (
<button className={styles.sortButton} type="button" aria-label={`按${column.title}排序`} onClick={() => onSort?.(key, 'ascend')}>
{column.title}
</button>
) : (
column.title
)}
</th>
);
})}
</tr>
</thead>
<tbody>
{dataSource.length === 0 ? (
<tr>
<td className={styles.tableEmptyCell} colSpan={columnCount}>
<div role="status" aria-label="表格空状态" className={styles.tableEmpty}>
{renderEmptyState(empty, emptyText)}
</div>
</td>
</tr>
) : null}
{dataSource.map((record, rowIndex) => {
const key = getKey(rowKey, record);
const selected = rowSelection?.selectedRowKeys.includes(key) ?? false;
return (
<tr key={key}>
{rowSelection ? (
<td>
<input
aria-label={`选择${String(record.name ?? key)}`}
checked={selected}
type="checkbox"
onChange={() => {
const nextKeys = selected ? rowSelection.selectedRowKeys.filter((item) => item !== key) : [...rowSelection.selectedRowKeys, key];
const nextRows = dataSource.filter((item) => nextKeys.includes(getKey(rowKey, item)));
rowSelection.onChange?.(nextKeys, nextRows);
}}
/>
</td>
) : null}
{columns.map((column, columnIndex) => {
const columnKey = String(column.key ?? column.dataIndex ?? columnIndex);
const value = column.dataIndex ? record[column.dataIndex] : undefined;
return <td key={columnKey}>{column.render ? column.render(value, record, rowIndex) : String(value ?? '-')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
.field {
display: flex;
width: 100%;
min-width: 0;
flex-direction: column;
gap: var(--gl-spacing-xs);
min-height: 96px;
padding: var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-primary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
transition:
border-color 120ms ease,
box-shadow 120ms ease,
background-color 120ms ease;
}
.field:hover {
border-color: var(--gl-color-primary);
}
.field:focus-within {
border-color: var(--gl-color-primary);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--gl-color-primary) 18%, transparent);
}
.fieldDisabled {
cursor: not-allowed;
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-secondary);
}
.fieldError {
border-color: var(--gl-color-danger, #d92d20);
}
.fieldWarning {
border-color: var(--gl-color-warning, #dc6803);
}
.fieldSuccess {
border-color: var(--gl-color-success, #039855);
}
.textarea {
width: 100%;
min-width: 0;
flex: 1 1 auto;
resize: vertical;
border: 0;
outline: 0;
background: transparent;
color: inherit;
font: inherit;
font-size: var(--gl-font-size-sm);
line-height: 1.6;
}
.textarea::placeholder {
color: var(--gl-color-text-secondary);
}
.textarea:disabled {
cursor: not-allowed;
}
.footer {
align-self: flex-end;
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
white-space: nowrap;
}
import { forwardRef, useState } from 'react';
import type { TextareaHTMLAttributes } from 'react';
import styles from './Textarea.module.css';
import { cx } from './utils';
export interface TextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'size'> {
/** 状态样式用于和 FormItem 校验信息协同展示。 */
status?: 'default' | 'success' | 'warning' | 'error';
/** 是否显示输入长度,默认使用简洁的当前值/上限格式。 */
showCount?: boolean;
onChange?: (value: string) => void;
}
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(function Textarea(
{
className,
defaultValue,
disabled,
onChange,
rows = 4,
showCount = false,
status = 'default',
value,
...props
},
ref,
) {
const [innerValue, setInnerValue] = useState(defaultValue?.toString() ?? '');
const currentValue = value === undefined ? innerValue : String(value);
const emitChange = (nextValue: string) => {
if (value === undefined) {
setInnerValue(nextValue);
}
onChange?.(nextValue);
};
// 多行输入的长度提示放在右下角,既不挤压正文,也能保持简洁可扫读。
const countLabel = props.maxLength !== undefined ? `${currentValue.length}/${props.maxLength}` : String(currentValue.length);
return (
<span
className={cx(
styles.field,
status === 'error' && styles.fieldError,
status === 'warning' && styles.fieldWarning,
status === 'success' && styles.fieldSuccess,
disabled && styles.fieldDisabled,
className,
)}
>
<textarea
{...props}
ref={ref}
className={styles.textarea}
disabled={disabled}
rows={rows}
value={currentValue}
aria-invalid={status === 'error' || undefined}
onChange={(event) => emitChange(event.target.value)}
/>
{showCount ? <span className={styles.footer}>{countLabel}</span> : null}
</span>
);
});
import { useState } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react';
import styles from './Shared.module.css';
import { Icon } from './Icon';
import { cx, notifyPopupOpen, useExclusivePopup } from './utils';
const selectPopupOpenEvent = 'gl-select-popup-open';
export interface TreeSelectNode {
label: ReactNode;
value: string;
disabled?: boolean;
children?: TreeSelectNode[];
}
export interface TreeSelectProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> {
/** 树节点保留 children 结构,供组织、分类、权限范围等层级选择使用。 */
treeData: TreeSelectNode[];
value?: string;
placeholder?: string;
onChange?: (value: string, node: TreeSelectNode) => void;
}
function findNode(nodes: TreeSelectNode[], value?: string): TreeSelectNode | undefined {
for (const node of nodes) {
if (node.value === value) return node;
const child = findNode(node.children ?? [], value);
if (child) return child;
}
return undefined;
}
export function TreeSelect({ treeData, value, placeholder = '请选择', onChange, ...props }: TreeSelectProps) {
const [open, setOpen] = useState(false);
const popupId = useExclusivePopup(selectPopupOpenEvent, setOpen);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [innerValue, setInnerValue] = useState<string | undefined>(value);
const currentValue = value ?? innerValue;
const currentNode = findNode(treeData, currentValue);
const renderNodes = (nodes: TreeSelectNode[], level = 0): ReactNode[] =>
nodes.flatMap((node) => {
const hasChildren = Boolean(node.children?.length);
const isExpanded = expanded.has(node.value);
const item = (
<div
key={node.value}
className={cx(styles.treeItem, node.value === currentValue && styles.optionSelected, node.disabled && styles.disabled)}
role="treeitem"
aria-expanded={hasChildren ? isExpanded : undefined}
aria-disabled={node.disabled || undefined}
aria-selected={!hasChildren && node.value === currentValue}
style={{ paddingLeft: 8 + level * 16 }}
onClick={() => {
if (node.disabled) return;
if (hasChildren) {
const nextExpanded = new Set(expanded);
if (isExpanded) {
nextExpanded.delete(node.value);
} else {
nextExpanded.add(node.value);
}
setExpanded(nextExpanded);
return;
}
if (value === undefined) setInnerValue(node.value);
onChange?.(node.value, node);
setOpen(false);
}}
>
{hasChildren ? <Icon name={isExpanded ? 'chevron-down' : 'chevron-right'} /> : <span className={styles.treeSpacer} />}
{node.label}
</div>
);
return isExpanded && node.children ? [item, ...renderNodes(node.children, level + 1)] : [item];
});
const toggleOpen = () => {
setOpen((nextOpen) => {
if (!nextOpen) notifyPopupOpen(selectPopupOpenEvent, popupId);
return !nextOpen;
});
};
return (
<span className={styles.selectWrapper}>
<button {...props} className={cx(styles.control, styles.fieldButton)} role="combobox" aria-expanded={open} type="button" onClick={toggleOpen}>
<span>{currentNode?.label ?? placeholder}</span>
<Icon className={styles.fieldIcon} name={open ? 'chevron-down' : 'chevron-right'} />
</button>
{open ? (
<div className={cx(styles.popup, styles.selectPopup)} role="tree">
{renderNodes(treeData)}
</div>
) : null}
</span>
);
}
.root {
display: grid;
width: 100%;
max-width: 500px;
gap: var(--gl-spacing-lg);
}
.dragger {
display: flex;
width: 100%;
height: 208px;
box-sizing: border-box;
flex-direction: column;
align-items: center;
justify-content: center;
padding: var(--gl-spacing-xl);
border: 1px dashed var(--gl-color-border-primary);
border-radius: 12px;
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
cursor: pointer;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease,
opacity 120ms ease;
}
.dragger:hover:not(:disabled),
.draggerActive {
border-color: var(--gl-color-primary);
background: color-mix(in srgb, var(--gl-color-primary) 4%, #fff);
}
.dragger:focus-visible {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 24%, transparent);
outline-offset: 2px;
}
.dragger:disabled,
.draggerDisabled {
cursor: not-allowed;
opacity: 0.55;
}
.uploadIcon {
display: inline-flex;
width: 64px;
height: 64px;
align-items: center;
justify-content: center;
margin-bottom: var(--gl-spacing-lg);
border-radius: 999px;
background: color-mix(in srgb, var(--gl-color-primary) 10%, #fff);
color: var(--gl-color-primary);
}
.draggerTitle {
font-size: var(--gl-font-size-sm);
font-weight: 600;
line-height: var(--gl-line-height-md);
}
.draggerHelper {
margin-top: var(--gl-spacing-sm);
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: var(--gl-line-height-sm);
}
.mediaRoot {
display: grid;
gap: var(--gl-spacing-sm);
}
.mediaVideoPreview {
width: 100%;
height: 100%;
background: #000;
object-fit: cover;
}
import { Upload } from 'tdesign-react';
import type { UploadFile as TDesignUploadFile, TdUploadProps } from 'tdesign-react/es/upload/type';
type UploadProps = TdUploadProps;
import styles from './Upload.module.css';
import { cx } from './utils';
export type UploadFileStatus = 'success' | 'progress' | 'fail' | 'waiting';
export interface UploadFileItem {
id: string;
name: string;
size: number;
status: UploadFileStatus;
progress?: number;
errorMessage?: string;
previewable?: boolean;
url?: string;
}
export interface UploadDraggerProps {
/** UploadDragger 使用 TDesign Upload 的 file-flow 主题,提供文件列表、进度、预览等内置功能 */
files: UploadFileItem[];
title?: string;
helperText?: string;
accept?: string;
multiple?: boolean;
disabled?: boolean;
className?: string;
style?: React.CSSProperties;
onSelectFiles?: (files: File[]) => void;
onPreview?: (id: string) => void;
onDownload?: (id: string) => void;
onRemove?: (id: string) => void;
onRetry?: (id: string) => void;
onCancel?: (id: string) => void;
}
/** 将 UploadFileItem 转换为 TDesign UploadFile */
function toTDesignFile(item: UploadFileItem): TDesignUploadFile {
return {
uid: item.id,
name: item.name,
size: item.size,
status: item.status,
percent: item.progress,
response: item.errorMessage ? { error: item.errorMessage } : undefined,
url: item.url,
};
}
/** 将 TDesign UploadFile 转换为 UploadFileItem */
function fromTDesignFile(file: TDesignUploadFile): UploadFileItem {
return {
id: file.uid || String(file.name),
name: file.name || '',
size: file.size || 0,
status: (file.status as UploadFileStatus) || 'waiting',
progress: file.percent,
errorMessage: file.response?.error,
url: file.url,
previewable: !!file.url,
};
}
export function UploadDragger({
accept,
className,
disabled = false,
files,
helperText = '支持分片断点续传,单文件上限 1GB',
multiple = true,
onCancel,
onDownload,
onPreview,
onRemove,
onRetry,
onSelectFiles,
style,
title = '点击或拖拽文件到此上传',
}: UploadDraggerProps) {
const tdesignFiles = files.map(toTDesignFile);
const handleChange: UploadProps['onChange'] = (value, context) => {
const { trigger, file, files: changedFiles } = context;
if (trigger === 'add' && file?.raw) {
onSelectFiles?.([file.raw]);
} else if (trigger === 'remove' && file) {
onRemove?.(fromTDesignFile(file).id);
} else if (trigger === 'abort' && file) {
onCancel?.(fromTDesignFile(file).id);
} else if (trigger === 'progress-fail' && file) {
onRetry?.(fromTDesignFile(file).id);
}
};
const handlePreview: UploadProps['onPreview'] = ({ file }) => {
const item = fromTDesignFile(file);
if (item.previewable) {
onPreview?.(item.id);
}
};
const handleRemove: UploadProps['onRemove'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
const item = fromTDesignFile(file);
onRemove?.(item.id);
};
return (
<div className={cx(styles.root, className)} style={style}>
<Upload
accept={accept}
autoUpload={false}
disabled={disabled}
draggable
files={tdesignFiles}
multiple={multiple}
theme="file-flow"
tips={helperText}
onChange={handleChange}
onPreview={handlePreview}
onRemove={handleRemove}
trigger={() => (
<div className={cx(styles.dragger, disabled && styles.draggerDisabled)} data-testid="upload-dragger">
<span className={styles.uploadIcon} aria-hidden="true">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
</span>
<span className={styles.draggerTitle}>{title}</span>
<span className={styles.draggerHelper}>{helperText}</span>
</div>
)}
/>
</div>
);
}
export interface MediaWallItem {
id: string;
type: 'image' | 'video';
src: string;
alt: string;
}
export interface MediaWallProps {
/** MediaWall 使用 TDesign Upload 的 image 主题,内置图片预览功能 */
items: MediaWallItem[];
helperText?: string;
accept?: string;
multiple?: boolean;
disabled?: boolean;
/** 最大上传数量,达到上限时隐藏上传按钮 */
maxCount?: number;
className?: string;
style?: React.CSSProperties;
/** 预览回调,用于视频播放或自定义预览逻辑。图片预览默认使用 TDesign 内置 ImageViewer */
onPreview?: (item: MediaWallItem) => void;
onRemove?: (item: MediaWallItem) => void;
onSelectFiles?: (files: File[]) => void;
}
export function MediaWall({
accept = 'image/*,video/*',
className,
disabled = false,
helperText,
items,
maxCount,
multiple = true,
onPreview,
onRemove,
onSelectFiles,
style,
}: MediaWallProps) {
const tdesignFiles: TDesignUploadFile[] = items.map((item) => ({
uid: item.id,
name: item.alt,
url: item.src,
status: 'success',
type: item.type === 'image' ? 'image' : 'video',
}));
// 判断是否需要自定义预览处理(有视频或有自定义 onPreview)
const hasVideo = items.some((item) => item.type === 'video');
const needCustomPreview = hasVideo || !!onPreview;
const itemById = new Map(items.map((item) => [item.id, item]));
const handleChange: UploadProps['onChange'] = (value, context) => {
const { trigger, file } = context;
if (trigger === 'add' && file?.raw) {
onSelectFiles?.([file.raw]);
}
};
const handlePreview: UploadProps['onPreview'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
const item: MediaWallItem = {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
onPreview?.(item);
};
const handleRemove: UploadProps['onRemove'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
const item: MediaWallItem = {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
onRemove?.(item);
};
const renderVideoFileList: UploadProps['fileListDisplay'] = ({ files }) => (
<div className="t-upload__card-container">
{files.map((file) => {
const item = itemById.get(file.uid || '') ?? {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
return (
<div className="t-upload__card-item" key={item.id}>
{item.type === 'video' ? (
<video
className={styles.mediaVideoPreview}
src={item.src}
aria-label={item.alt || '视频预览'}
muted
playsInline
preload="metadata"
/>
) : (
<img src={item.src} alt={item.alt} />
)}
<div className="t-upload__card-mask">
<button
type="button"
className="t-upload__card-mask-item"
aria-label="预览"
disabled={disabled}
onClick={(e) => {
e.stopPropagation();
onPreview?.(item);
}}
>
<span className="t-icon t-icon-browse" />
</button>
<button
type="button"
className="t-upload__card-mask-item"
aria-label="删除"
disabled={disabled}
onClick={(e) => {
e.stopPropagation();
onRemove?.(item);
}}
>
<span className="t-icon t-icon-delete" />
</button>
</div>
</div>
);
})}
</div>
);
return (
<div
className={cx(styles.mediaRoot, className)}
style={style}
onClick={(e) => e.stopPropagation()}
>
<Upload
accept={accept}
autoUpload={false}
disabled={disabled}
files={tdesignFiles}
max={maxCount}
multiple={multiple}
theme="image"
tips={helperText}
onChange={handleChange}
// 只有需要自定义预览时才传递 onPreview,否则让 TDesign 内置 ImageViewer 处理
onPreview={needCustomPreview ? handlePreview : undefined}
onRemove={handleRemove}
fileListDisplay={hasVideo ? renderVideoFileList : undefined}
/>
</div>
);
}
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import {
Button,
Checkbox,
Input,
Radio,
SearchInput,
Textarea,
Switch,
} from '../index';
describe('shared UI basic controls', () => {
it('exports the first task baseline from the shared UI boundary', () => {
expect(Button).toBeTypeOf('function');
expect(Input).toBeTypeOf('object');
expect(SearchInput).toBeTypeOf('object');
expect(Checkbox).toBeTypeOf('object');
expect(Radio).toBeTypeOf('object');
expect(Switch).toBeTypeOf('object');
});
it('renders Button variants and blocks clicks while loading or disabled', () => {
const onClick = vi.fn();
render(
<>
<Button variant="primary" size="large" onClick={onClick}>
保存
</Button>
<Button loading onClick={onClick}>
提交中
</Button>
<Button disabled onClick={onClick}>
不可用
</Button>
</>,
);
fireEvent.click(screen.getByRole('button', { name: '保存' }));
fireEvent.click(screen.getByRole('button', { name: /提交中/ }));
fireEvent.click(screen.getByRole('button', { name: '不可用' }));
expect(onClick).toHaveBeenCalledTimes(1);
expect(screen.getByRole('button', { name: /提交中/ })).toBeDisabled();
expect(screen.getByRole('button', { name: /提交中/ })).toHaveAttribute('aria-busy', 'true');
});
it('supports controlled and uncontrolled Input values with clear and status states', () => {
const onControlledChange = vi.fn();
const onClear = vi.fn();
render(
<>
<Input
aria-label="受控输入"
value="已填写"
allowClear
status="error"
onChange={onControlledChange}
onClear={onClear}
/>
<Input aria-label="非受控输入" defaultValue="初始值" prefix="¥" suffix="元" />
</>,
);
fireEvent.click(screen.getByRole('button', { name: '清空受控输入' }));
fireEvent.change(screen.getByLabelText('非受控输入'), { target: { value: '99' } });
expect(onControlledChange).toHaveBeenCalledWith('');
expect(onClear).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText('非受控输入')).toHaveValue('99');
expect(screen.getByLabelText('受控输入')).toHaveAttribute('aria-invalid', 'true');
expect(screen.getByText('¥')).toBeInTheDocument();
expect(screen.getByText('元')).toBeInTheDocument();
});
it('renders concise Input and Textarea count display when showCount is enabled', () => {
const onTextareaChange = vi.fn();
render(
<>
<Input aria-label="字数输入" defaultValue="合同" maxLength={10} showCount />
<Textarea aria-label="备注" defaultValue="已填写" maxLength={20} showCount onChange={onTextareaChange} />
</>,
);
fireEvent.change(screen.getByLabelText('备注'), { target: { value: '已填写更多内容' } });
expect(screen.getByText('2/10')).toBeInTheDocument();
expect(screen.getByText('7/20')).toBeInTheDocument();
expect(onTextareaChange).toHaveBeenCalledWith('已填写更多内容');
});
it('triggers SearchInput search from enter, button click, and clear', () => {
const onSearch = vi.fn();
const onClear = vi.fn();
render(
<SearchInput
aria-label="搜索关键字"
defaultValue="合同"
allowClear
onSearch={onSearch}
onClear={onClear}
/>,
);
fireEvent.keyDown(screen.getByLabelText('搜索关键字'), { key: 'Enter' });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
fireEvent.click(screen.getByRole('button', { name: '清空搜索关键字' }));
expect(onSearch).toHaveBeenNthCalledWith(1, '合同');
expect(onSearch).toHaveBeenNthCalledWith(2, '合同');
expect(onClear).toHaveBeenCalledTimes(1);
});
it('renders SearchInput with a design-sized search icon asset', () => {
render(<SearchInput aria-label="搜索关键字" defaultValue="合同" />);
const icon = screen.getByLabelText('搜索图标');
expect(icon).toHaveAttribute('data-icon', 'search');
expect(icon).toHaveAttribute('width', '18');
expect(icon).toHaveAttribute('height', '18');
});
it('renders Checkbox checked, indeterminate, disabled states and change callback', () => {
const onChange = vi.fn();
render(
<>
<Checkbox label="启用" checked onChange={onChange} />
<Checkbox label="部分选择" indeterminate />
<Checkbox label="禁用" disabled />
</>,
);
fireEvent.click(screen.getByLabelText('启用'));
fireEvent.click(screen.getByLabelText('禁用'));
expect(onChange).toHaveBeenCalledWith(false);
expect(screen.getByLabelText('部分选择')).toHaveAttribute('aria-checked', 'mixed');
expect(screen.getByLabelText('禁用')).toBeDisabled();
});
it('renders Radio as a controlled single option and respects disabled state', () => {
const onChange = vi.fn();
render(
<>
<Radio label="按项目" name="range" value="project" checked onChange={onChange} />
<Radio label="按组织" name="range" value="org" disabled onChange={onChange} />
</>,
);
fireEvent.click(screen.getByLabelText('按项目'));
fireEvent.click(screen.getByLabelText('按组织'));
expect(onChange).toHaveBeenCalledWith('project');
expect(screen.getByLabelText('按组织')).toBeDisabled();
});
it('toggles Switch and ignores interaction while loading or disabled', () => {
const onChange = vi.fn();
render(
<>
<Switch aria-label="启用审批" checked={false} onChange={onChange} />
<Switch aria-label="同步中" checked loading onChange={onChange} />
<Switch aria-label="禁止切换" checked disabled onChange={onChange} />
</>,
);
fireEvent.click(screen.getByRole('switch', { name: '启用审批' }));
fireEvent.click(screen.getByRole('switch', { name: '同步中' }));
fireEvent.click(screen.getByRole('switch', { name: '禁止切换' }));
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith(true);
expect(screen.getByRole('switch', { name: '同步中' })).toHaveAttribute('aria-busy', 'true');
expect(screen.getByRole('switch', { name: '禁止切换' })).toBeDisabled();
});
});
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import styles from './Shared.module.css';
import {
Collapse,
ColorInput,
ColorPicker,
Empty,
Navigation,
Skeleton,
SkeletonAvatar,
SkeletonButton,
SkeletonInput,
SkeletonParagraph,
Steps,
Tabs,
} from '../index';
describe('navigation, placeholder and color components', () => {
it('switches Tabs and skips disabled tabs', () => {
const onChange = vi.fn();
render(
<Tabs
activeKey="base"
onChange={onChange}
items={[
{ key: 'base', label: '基础信息', children: '基础内容' },
{ key: 'advanced', label: '高级配置', children: '高级内容' },
{ key: 'disabled', label: '禁用页签', disabled: true, children: '禁用内容' },
]}
/>,
);
fireEvent.click(screen.getByRole('tab', { name: '高级配置' }));
fireEvent.click(screen.getByRole('tab', { name: '禁用页签' }));
expect(screen.getByText('基础内容')).toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith('advanced');
expect(onChange).toHaveBeenCalledTimes(1);
});
it('renders Steps with current and error states', () => {
render(<Steps current={1} status="error" items={[{ title: '提交' }, { title: '审批' }, { title: '完成' }]} />);
expect(screen.getByText('提交')).toBeInTheDocument();
expect(screen.getByText('审批')).toBeInTheDocument();
expect(screen.getByText('错误')).toBeInTheDocument();
});
it('renders Empty and Skeleton placeholders', () => {
render(
<>
<Empty description="暂无项目" action={<button type="button">新建项目</button>} />
<Skeleton active />
<SkeletonAvatar />
<SkeletonParagraph rows={2} />
<SkeletonButton />
<SkeletonInput />
</>,
);
expect(screen.getByText('暂无项目')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新建项目' })).toBeInTheDocument();
expect(screen.getAllByLabelText(/加载占位/).length).toBeGreaterThanOrEqual(5);
});
it('toggles Collapse panels with controlled callbacks', () => {
const onChange = vi.fn();
render(
<Collapse
activeKeys={['one']}
onChange={onChange}
items={[
{ key: 'one', title: '基础设置', children: '设置内容' },
{ key: 'two', title: '高级设置', children: '高级内容' },
]}
/>,
);
fireEvent.click(screen.getByRole('button', { name: '高级设置' }));
expect(screen.getByText('设置内容')).toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith(['one', 'two']);
});
it('renders hierarchical navigation with active child and parent states', () => {
const onChange = vi.fn();
render(
<Navigation
activeKey="agent-list"
onChange={onChange}
items={[
{
key: 'agent-management',
label: 'Agent管理',
children: [{ key: 'agent-list', label: 'Agent列表' }],
},
]}
/>,
);
const parentItem = screen.getByRole('button', { name: 'Agent管理' });
const childItem = screen.getByRole('button', { name: 'Agent列表' });
expect(parentItem).toHaveAttribute('data-active-parent', 'true');
expect(parentItem).not.toHaveClass('navigationItemParentActive');
expect(childItem).toHaveAttribute('aria-current', 'page');
expect(childItem).toHaveClass(styles.navigationItemActive, styles.navigationChild);
fireEvent.click(childItem);
expect(onChange).toHaveBeenCalledWith('agent-list');
});
it('selects preset colors and edits color input values', () => {
const onPickerChange = vi.fn();
const onInputChange = vi.fn();
render(
<>
<ColorPicker value="#2468f2" presets={['#2468f2', '#039855']} onChange={onPickerChange} />
<ColorInput aria-label="主题色" value="#2468f2" onChange={onInputChange} />
</>,
);
fireEvent.click(screen.getByRole('button', { name: '选择颜色 #039855' }));
fireEvent.change(screen.getByLabelText('主题色'), { target: { value: '#d92d20' } });
expect(onPickerChange).toHaveBeenCalledWith('#039855');
expect(onInputChange).toHaveBeenCalledWith('#d92d20');
});
});
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { SearchFilter } from '../index';
describe('SearchFilter', () => {
it('renders default select all option and keeps number inputs digits only', () => {
const onSearch = vi.fn();
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input', defaultValue: '合同' },
{ key: 'count', label: '数量', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
]}
onSearch={onSearch}
/>,
);
fireEvent.change(screen.getByLabelText('数量'), { target: { value: '12a3' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByLabelText('数量')).toHaveValue('123');
expect(onSearch).toHaveBeenCalledWith({
keyword: '合同',
count: '123',
status: '',
});
});
it('uses default placeholders for input and number input while preserving explicit placeholders', () => {
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '项目名称', type: 'input' },
{ key: 'code', label: '项目编号', type: 'numberInput' },
{ key: 'owner', label: '负责人', type: 'input', placeholder: '搜索负责人姓名' },
]}
/>,
);
expect(screen.getByLabelText('项目名称')).toHaveAttribute('placeholder', '搜索项目名称');
expect(screen.getByLabelText('项目编号')).toHaveAttribute('placeholder', '请输入数字');
expect(screen.getByLabelText('负责人')).toHaveAttribute('placeholder', '搜索负责人姓名');
});
it('shows expand and collapse controls when the configured fields exceed one visible row', () => {
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input' },
{ key: 'code', label: '编号', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{ key: 'owner', label: '负责人', type: 'input' },
{ key: 'createdAt', label: '创建日期', type: 'datePicker' },
{ key: 'period', label: '时间范围', type: 'datePicker', range: true },
]}
/>,
);
expect(screen.getByRole('button', { name: '展开' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '展开' }));
expect(screen.getByRole('button', { name: '收起' })).toBeInTheDocument();
});
it('resets field values and calls the reset callback', () => {
const onReset = vi.fn();
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input', defaultValue: '项目' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
defaultValue: 'enabled',
},
]}
onReset={onReset}
/>,
);
fireEvent.change(screen.getByLabelText('关键词'), { target: { value: '合同' } });
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(onReset).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText('关键词')).toHaveValue('项目');
});
});
import { useEffect, useId } from 'react';
export function cx(...values: Array<string | false | null | undefined>) {
return values.filter(Boolean).join(' ');
}
export function notifyPopupOpen(eventName: string, id: string) {
window.dispatchEvent(new CustomEvent(eventName, { detail: id }));
}
export function useExclusivePopup(eventName: string, setOpen: (open: boolean) => void) {
const id = useId();
useEffect(() => {
const closeOtherPopup = (event: Event) => {
if ((event as CustomEvent<string>).detail !== id) setOpen(false);
};
window.addEventListener(eventName, closeOtherPopup);
return () => window.removeEventListener(eventName, closeOtherPopup);
}, [eventName, id, setOpen]);
return id;
}
export type { ButtonProps } from './components/Button';
export { Button } from './components/Button';
export type { ColorInputProps, ColorPickerProps } from './components/Color';
export { ColorInput, ColorPicker } from './components/Color';
export type { CheckboxProps } from './components/Checkbox';
export { Checkbox } from './components/Checkbox';
export type { DatePickerProps, DateRangePickerProps } from './components/DatePicker';
export { DatePicker, DateRangePicker } from './components/DatePicker';
export type { AvatarProps, AvatarGroupProps, BadgeProps, CardProps, ProgressProps, StatisticProps, TagProps, TimelineItem } from './components/Display';
export { Avatar, AvatarGroup, Badge, Card, Progress, Statistic, Tag, Timeline } from './components/Display';
export type { AlertProps, DrawerProps, MessageItem, MessageProps, ModalProps, PopconfirmProps, TooltipProps } from './components/Feedback';
export { Alert, Drawer, Message, Modal, Popconfirm, Tooltip } from './components/Feedback';
export type { FormItemProps, FormProps, FormRule, FormValues } from './components/FormItem';
export { Form, FormItem } from './components/FormItem';
export type { InputProps, SearchInputProps } from './components/Input';
export { Input, SearchInput } from './components/Input';
export type { TextareaProps } from './components/Textarea';
export { Textarea } from './components/Textarea';
export type { CollapseItem, CollapseProps, EmptyProps, NavigationItem, NavigationProps, StatePlaceholderProps, StepsProps, TabsItem, TabsProps } from './components/Navigation';
export { Collapse, Empty, Navigation, Skeleton, SkeletonAvatar, SkeletonButton, SkeletonInput, SkeletonParagraph, StatePlaceholder, Steps, Tabs } from './components/Navigation';
export type { PaginationProps } from './components/Pagination';
export { Pagination } from './components/Pagination';
export type { RadioProps } from './components/Radio';
export { Radio } from './components/Radio';
export type { SelectOption, SelectProps } from './components/Select';
export { Select } from './components/Select';
export type { SearchFilterDateField, SearchFilterField, SearchFilterInputField, SearchFilterNumberInputField, SearchFilterProps, SearchFilterSelectField, SearchFilterValue, SearchFilterValues } from './components/SearchFilter';
export { SearchFilter } from './components/SearchFilter';
export type { SwitchProps } from './components/Switch';
export { Switch } from './components/Switch';
export type { TableColumn, TableProps } from './components/Table';
export { Table } from './components/Table';
export type { TreeSelectNode, TreeSelectProps } from './components/TreeSelect';
export { TreeSelect } from './components/TreeSelect';
export type { MediaWallItem, MediaWallProps, UploadDraggerProps, UploadFileItem, UploadFileStatus } from './components/Upload';
export { MediaWall, UploadDragger } from './components/Upload';
...@@ -395,7 +395,7 @@ describe('Agent display config edit modal', () => { ...@@ -395,7 +395,7 @@ describe('Agent display config edit modal', () => {
const longContent = '测'.repeat(101); const longContent = '测'.repeat(101);
await user.clear(contentInput); await user.clear(contentInput);
await user.type(contentInput, longContent); fireEvent.change(contentInput, { target: { value: longContent } });
expect(contentInput).toHaveValue('测'.repeat(100)); expect(contentInput).toHaveValue('测'.repeat(100));
expect(within(modal).getByText('100/100')).toBeInTheDocument(); expect(within(modal).getByText('100/100')).toBeInTheDocument();
await user.click(within(modal).getByRole('button', { name: '确定' })); await user.click(within(modal).getByRole('button', { name: '确定' }));
......
...@@ -28,5 +28,5 @@ ...@@ -28,5 +28,5 @@
"jsx": "react-jsx", "jsx": "react-jsx",
"types": ["vitest/globals", "@testing-library/jest-dom"] "types": ["vitest/globals", "@testing-library/jest-dom"]
}, },
"include": ["src", "packages/ui/src", "packages/contracts", "../../../packages/business-components/src"] "include": ["src", "packages/contracts", "../../../packages/business-components/src"]
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!