v 1.0.1
parent
e65daaa39e
commit
550797c35a
|
|
@ -15,3 +15,4 @@ graphy/dist
|
|||
graphy/*.egg-info
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
nex_design_system
|
||||
|
|
@ -42,3 +42,6 @@ backend/models
|
|||
# AI
|
||||
.gemini-clipboard/
|
||||
.claude/
|
||||
|
||||
# Design
|
||||
nex_design_system/
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
# NEX Design System — Agent Entry Rules (0.1.6)
|
||||
|
||||
本文件是 NEX 的 Agent 入口。先确认 NEX 目录位置,再以本文件所在目录为基准读取 `docs/`、`config/` 和 `templates/`。如果本文件被合并到项目根 `AGENTS.md`,必须将文档路径改为项目中的实际安装路径,不得保留失效的相对路径。
|
||||
|
||||
> **本仓库的实际安装路径**(NEX 0.1.6 随仓库置于 `nex_design_system/`,以下路径相对项目根):
|
||||
> 规范 `nex_design_system/docs/`、配置模板 `nex_design_system/config/`、模板 `nex_design_system/templates/`。
|
||||
> 本文件即项目根 `AGENTS.md`,因此 §1 已改写为实际路径,不再使用失效的 `docs/…` 相对路径。
|
||||
|
||||
## 1. 开始任务前必须读取
|
||||
|
||||
1. `nex_design_system/docs/00-governance-and-adaptation.md`
|
||||
2. `nex_design_system/docs/02-design-principles.md`
|
||||
3. `nex_design_system/docs/03-design-tokens.md`
|
||||
4. `nex_design_system/docs/04-layout-system.md`
|
||||
5. `nex_design_system/docs/05-component-system.md`
|
||||
6. `nex_design_system/docs/06-interaction-system.md`
|
||||
7. `nex_design_system/docs/07-page-patterns.md`
|
||||
8. `nex_design_system/docs/08-accessibility-responsive.md`
|
||||
9. `nex_design_system/docs/09-agent-execution-rules.md`
|
||||
10. `nex_design_system/docs/12-responsive-accessibility-quality.md`
|
||||
11. `nex_design_system/docs/14-accessibility-platform-matrix.md`
|
||||
12. 项目根目录 `nex.config.yaml`(如存在)
|
||||
13. 项目级 UI/UX 规范。本项目当前没有独立的「项目设计 specification」文档,
|
||||
实际权威来源为:`frontend/src/styles/design-tokens.css`(Token)、
|
||||
`frontend/src/theme/antdTheme.ts`(antd 主题映射)、
|
||||
`docs/sdd/architecture/standards/nex-conformance-matrix.md`(符合性与例外)、
|
||||
`docs/sdd/architecture/standards/responsive-breakpoint-registry.md`(断点登记)、
|
||||
`docs/quickstart.md` §6(前端约定)。
|
||||
|
||||
只在任务涉及 NexDocus 历史实现或明确要求参考时,读取
|
||||
`nex_design_system/docs/01-project-audit.md`。它不是新项目的实施基线。
|
||||
NEX 0.1.6 包内**不含** `config/reference-nexdocus-profile.example.yaml`
|
||||
(`nex_design_system/config/` 下只有 `project-profile.example.yaml`),引用该文件时按缺失处理。
|
||||
|
||||
## 2. 规范层级
|
||||
|
||||
遵循 NEX 三层模型:
|
||||
|
||||
- **NEX Core**:跨项目质量与设计治理要求。
|
||||
- **Project Design Specification**:本项目视觉、布局、技术和交互的权威具体规范。
|
||||
- **Project Implementation**:当前主题、Token、组件和页面的真实实现。
|
||||
|
||||
NexDocus 参数、示例截图和示例组件名不是跨项目默认值。新项目的技术起步默认值以 `nex.config.yaml` 的 `stack` 为准;它只适用于新项目初始化,不是 NEX Core 对所有项目的强制技术栈。已有项目由项目级规范和真实实现决定。NEX Core 的通用 MUST 要求不能因项目偏好而取消,但可以采用不同技术方式满足。
|
||||
|
||||
## 3. 默认技术栈与自动发现(0.1.6;沿用 0.1.5 默认栈)
|
||||
|
||||
`nex_design_system/config/project-profile.example.yaml` 是带有明确默认技术栈的配置模板。它不是“技术栈自动猜测模板”。
|
||||
|
||||
- **新项目**:`project.lifecycle` 为 `new`,或 `auto` 且仓库为空/没有实际应用代码时,必须把 `stack` 中的默认技术栈作为初始化目标。不得忽略这些选型,也不得再次要求用户填写一份技术栈问卷。
|
||||
- **已有项目**:`project.lifecycle` 为 `existing`,或 `auto` 且仓库已有应用代码/锁文件/构建配置时,以实际项目为准;默认技术栈仅供参考,不得据此替换、升级或迁移现有技术。
|
||||
- `project.type` 默认是 `fullstack`。纯前端或纯后端项目只需覆盖该字段。
|
||||
- 用户可以只覆盖 `stack` 中不符合当前项目意图的字段;未覆盖的默认值仍然有效。
|
||||
|
||||
新项目默认栈详见 `nex_design_system/docs/13-project-stack-defaults.md`,包括 React、TypeScript、Vite、Ant Design、Tailwind CSS v4、Python、FastAPI、SQLite/PostgreSQL 等。依赖版本采用创建时兼容的稳定版本,并提交 lockfile。
|
||||
|
||||
Agent 仍须自动发现已有项目的实际情况,包括:
|
||||
- 项目名称、类型和主要界面语言;
|
||||
- 前后端框架、语言、依赖版本、构建工具和 UI/样式方案;
|
||||
- 项目 UI/UX 规范与设计决策文档;
|
||||
- Token 权威来源、主题链路、共享组件目录和布局模式;
|
||||
- 路由、断点、响应式规则、质量命令、视觉基线和 CI;
|
||||
- 适用的辅助技术验证范围及尚未执行的人工测试。
|
||||
|
||||
无法发现的信息应标记 `UNKNOWN` 并说明证据缺口。不得把 `auto` 当成待用户填写的占位符,也不得为了补全配置而向用户发送长问卷。只有在信息无法从仓库确认且会影响产品选择、数据安全或高风险改动时,才提出最少量的具体问题。
|
||||
|
||||
新项目未覆盖的 `stack` 字段采用默认技术栈。已有项目不采用默认栈迁移,而是优先保留真实、成熟的现有实现;NEX 的通用设计质量要求仍然适用。
|
||||
|
||||
## 4. 开发前审计要求
|
||||
|
||||
修改既有前端前,先检查:
|
||||
|
||||
- 项目技术栈和真实依赖(以锁文件、`package.json`、构建配置为证据)。
|
||||
- 项目级 UI 规范和设计决策记录。
|
||||
- Token 的单一事实来源及其派生链路(CSS、主题库、框架变量等)。
|
||||
- 已有组件、页面模式、主题机制和布局参数。
|
||||
- 现有交互路径、响应式行为、自动化检查与视觉基线。
|
||||
|
||||
将发现映射为 `COMPLIANT`、`ADOPTED`、`ADAPTED`、`DEFERRED` 或 `NOT_APPLICABLE`。优先使用 `nex_design_system/templates/project-conformance-matrix.md`(本项目落地件:`docs/sdd/architecture/standards/nex-conformance-matrix.md`)。如果用户要求只审计,则不得修改业务代码。
|
||||
|
||||
## 5. 强制约束
|
||||
|
||||
1. **先盘点、后复用、再新增。** 先搜索项目现有共享组件和功能等价物。已有组件能满足需求时,不新增重复组件或第二套组件库。
|
||||
2. **项目适配优先。** 不将 NEX 参考项目的技术栈、品牌色、Token 名称、Header/Sider 尺寸、断点、控件高度或页面模式套用到其他项目。
|
||||
3. **不强制 `--nex-*` 命名。** 优先沿用项目现有语义 Token 和权威主题管线。只有项目没有合理命名体系、且批准采用 NEX 前缀时才可新增命名空间。
|
||||
4. **保持 Token 单一事实来源。** 可以由一个源文件/对象/配置单向派生 CSS Variables、组件库主题或框架变量;不得为同一语义值建立彼此独立、人工维护的多份来源。禁止为追求“统一”而破坏已经验证的单向派生链路。
|
||||
5. **保护成熟实现,但不固化缺陷。** 保留已验证的视觉和交互模式。若发现可复现的功能缺陷、安全问题或可访问性缺陷,应说明证据并提出最小修复;不得以“保持现状”为由忽略缺陷。
|
||||
6. **不擅自改变业务交互。** 视觉改造不得改变用户操作路径、数据语义、默认值或业务流程,除非任务明确授权。修复可访问性时应优先保持原操作意图和鼠标行为。
|
||||
7. **不擅自改技术栈。** 不升级框架、替换 UI 库、改变 JS/TS 方案或引入新样式系统,除非用户明确批准。
|
||||
8. **页面模式按需采用。** 只为项目真实存在的页面和工作区选择模式。`NOT_APPLICABLE` 的页面、组件和工作区不应被引入。
|
||||
9. **避免无意义封装。** 不机械包装所有第三方基础组件;只封装重复、高价值、需要统一 API/状态/可访问性行为的模式。
|
||||
10. **交互状态完整。** 适用时覆盖 loading、success、empty、error、disabled、permission-denied 等状态。状态不能只靠颜色表达。
|
||||
11. **可访问性是质量底线。** 自定义交互必须支持键盘、可见焦点和可访问名称;拖拽操作必须提供非拖拽替代路径。
|
||||
12. **滚动和尺寸必须基于实际布局。** 对嵌套 Flex/Grid 工作区检查 `min-width: 0`、`min-height: 0`、滚动容器归属和溢出,不要机械添加固定尺寸或 `overflow: hidden`。
|
||||
13. **不滥用局部覆盖。** 不用大量 `!important`、高优先级选择器或深层第三方 DOM 覆盖来修补应由 Token/主题/共享组件解决的问题;需要时说明范围和原因。
|
||||
14. **响应式断点必须登记。** 新增断点应有语义名称、数值/范围、布局理由、权威来源和边界测试;不得散落增加无法追踪的媒体查询。
|
||||
15. **窄屏数据必须可对账。** 隐藏列、卡片化或折叠详情不得导致重要数据无处可见;必须核验字段、记录数、顺序和动作仍可访问。
|
||||
16. **图标不得污染可访问名称。** 装饰性图标应从辅助技术名称计算中排除;图标与可见文案组合时避免重复朗读;图标本身不能以内部 glyph 名称充当业务文案。
|
||||
17. **真实 AT 验证按风险触发且跨平台选择。** 日常默认 E0–E2;只有复杂自定义控件、拖拽/排序、复合导航、关键数据表格、重要 Live Region 或合同/目标用户要求触发 E3。macOS 使用 VoiceOver,Windows 使用 NVDA(必要时 JAWS/Narrator),Linux 使用 Orca。E3 不适用时记录 `E3_NOT_REQUIRED`;必要但环境不可用时标记 `MANUAL_QA_REQUIRED`。
|
||||
18. **不得擅自启动屏幕阅读器。** 启动、关闭或切换 VoiceOver/NVDA/Orca 等系统 AT 前必须获得用户对本次 E3 的明确授权。记录初始状态,不得关闭用户原本启用的 AT,不得擅改系统级辅助功能设置。日常视觉、浏览器自动化和键盘验收不得启动屏幕阅读器。
|
||||
19. **样式层与性能优化必须有证据。** 不为形式一致进行全量 CSS Layer 迁移;不为消除 Bundle 警告盲目调阈值或分包。先提供级联冲突或实际加载数据,再做最小变更。
|
||||
20. **范围受控。** 不把审计顺手扩展为全项目重构。超出授权范围、影响已有体验或需改变设计决策时,先提交方案并等待批准。
|
||||
|
||||
## 6. 标准工作流
|
||||
|
||||
1. 读取 NEX Core、项目配置和项目级设计规范。
|
||||
2. 检查真实实现并建立符合性/差异映射。
|
||||
3. 明确任务范围、复用组件、可能受影响页面和回归面。
|
||||
4. 对跨组件或跨页面改动先提交实施计划;仅在用户已明确授权的范围内执行。
|
||||
5. 先修正 Token/主题/共享模式,再迁移具体页面;避免一次性机械替换。
|
||||
6. 执行项目实际存在的检查命令;不得虚构 lint、test、视觉测试或脚本结果。
|
||||
7. 验证受影响的主题、视口、键盘路径和交互状态;使用项目现有检查矩阵,不强制所有项目采用同一固定路由数或视口数。
|
||||
8. 汇报改动、规范映射、测试证据、视觉对比、未完成事项和风险。
|
||||
9. 对关键交互区分 E0 源码审阅、E1 自动化、E2 浏览器人工交互和 E3 真实辅助技术验证;E3 按风险触发,不适用时记录 `E3_NOT_REQUIRED`,必要但未执行时标记 `MANUAL_QA_REQUIRED`。
|
||||
|
||||
## 7. 例外记录
|
||||
|
||||
偏离 NEX Core 的 SHOULD 或采用不同项目实现时,记录:规则、状态(通常为 `ADAPTED` / `DEFERRED`)、原因、证据、影响范围、责任人/批准来源和复审条件。不得把单个项目的例外自动推广为全局规范。
|
||||
|
||||
## 8. 完成定义
|
||||
|
||||
只有在以下事项满足后,才能报告任务完成:
|
||||
|
||||
- 项目规范与实现之间没有未说明的重大冲突。
|
||||
- 新增实现优先复用了现有组件、Token 和页面模式。
|
||||
- 没有未经授权改变技术栈、布局基线或业务交互。
|
||||
- 适用的主题、响应式、键盘和状态检查已执行。
|
||||
- 项目真实可用的质量门禁已执行;不可执行项已说明。
|
||||
- 文档、配置和代码行为保持一致。
|
||||
11
README.md
11
README.md
|
|
@ -43,7 +43,7 @@ v1.0.0 · FastAPI + React 18 + MySQL 8 + Redis
|
|||
### 前端
|
||||
| 组件 | 选型 |
|
||||
| --- | --- |
|
||||
| 框架 | React 18 + React Router v6 |
|
||||
| 框架 | React 18(TypeScript,`strict`)+ React Router v6 |
|
||||
| 构建 | Vite 5(`manualChunks` 分包、全部路由 lazy 加载) |
|
||||
| UI | Ant Design 5 + 自研设计令牌(无 Tailwind / postcss) |
|
||||
| 状态 | Zustand + Axios 统一封装 |
|
||||
|
|
@ -149,7 +149,8 @@ cp .env.example .env # 按注释修改密码/端口/存储路径
|
|||
## 🧪 开发与质量
|
||||
|
||||
```bash
|
||||
# 前端:静态检查与构建
|
||||
# 前端:类型检查、静态检查与构建
|
||||
cd frontend && npm run typecheck
|
||||
cd frontend && npm run lint && npm run build
|
||||
|
||||
# 后端:pytest(用例较少,见发布报告 OI 清单)
|
||||
|
|
@ -157,9 +158,11 @@ cd backend && ./venv/bin/pip install -r requirements-dev.txt
|
|||
cd backend && ./venv/bin/python -m pytest
|
||||
```
|
||||
|
||||
- 前端统一使用 `@/` 别名指向 `frontend/src`;新页面必须在 `App.jsx` 用 `lazy()` 注册。
|
||||
- 交互提示统一走 `components/Feedback` 的 `Toast`(`Toast.confirm` 替代 `Modal.confirm`)。
|
||||
- 前端为 TypeScript,统一使用 `@/` 别名指向 `frontend/src`;新页面必须在 `App.tsx` 用 `lazy()` 注册。
|
||||
- 交互提示统一走 `components/Toast/Toast` 的 `Toast`(`Toast.confirm` 替代 `Modal.confirm`);`components/Feedback` 是它依赖的 antd 桥接层。
|
||||
- 颜色/圆角/间距一律取 `styles/design-tokens.css` 与 antd token,禁止硬编码色值。
|
||||
- 接口错误提示统一用 `utils/apiError` 取后端 `detail`;后端返回类型集中在 `types/api.ts`。
|
||||
- 质量门禁:`npm run typecheck`(Vite 构建不做类型检查)、`npm run lint`、`npm run build`。
|
||||
- 数据库结构变更:改 `app/models/`,并在 `app/core/migrations.py` 增加幂等补列逻辑;**不要**再往仓库里追加一次性 `.sql`。
|
||||
|
||||
## 🔒 安全要点
|
||||
|
|
|
|||
|
|
@ -112,11 +112,31 @@ npm run dev
|
|||
|
||||
## 6. 前端约定
|
||||
|
||||
- 开发端口 `5173`,`vite.config.js` 已把 `/api` 代理到 `http://localhost:8000`,因此**前端不需要配置后端地址**。
|
||||
- 路径别名 `@` → `frontend/src`。
|
||||
- 页面一律在 `src/App.jsx` 中用 `lazy()` 注册,路由级懒加载。
|
||||
- 主题/颜色取自 `src/styles/design-tokens.css` 与 `src/theme/antdTheme.js`,不要写死色值。
|
||||
- 全局提示统一 `@/components/Toast`(含 `Toast.confirm`),不要散用 `Modal.confirm` / `message.*`。
|
||||
- 前端为 **TypeScript**(`strict` + `noUnusedLocals` + `noUnusedParameters`),源码只有 `.ts` / `.tsx`。
|
||||
- 开发端口 `5173`,`vite.config.ts` 已把 `/api` 代理到 `http://localhost:8000`,因此**前端不需要配置后端地址**。
|
||||
- 路径别名 `@` → `frontend/src`(`tsconfig.json` 的 `paths` 与 Vite `resolve.alias` 保持一致)。
|
||||
- 页面一律在 `src/App.tsx` 中用 `lazy()` 注册,路由级懒加载。
|
||||
- 主题/颜色取自 `src/styles/design-tokens.css` 与 `src/theme/antdTheme.ts`(唯一 Token 源),不要写死色值。
|
||||
- 全局提示统一 `@/components/Toast/Toast`(含 `Toast.confirm`),不要散用 `Modal.confirm` / `message.*`。
|
||||
- 后端接口的请求/响应类型集中在 `src/types/api.ts`,新增接口时先补契约再写页面。
|
||||
- 接口错误取值统一走 `@/utils/apiError`(`getApiErrorDetail` / `getApiErrorMessage`),不要写 `error.response?.data?.detail`。
|
||||
- 用 `div`/`span` 承载点击时,必须用 `@/utils/a11yActivation` 的 `keyboardActivation()` 补 `role`/`tabIndex`/`onKeyDown`,
|
||||
并给控件可访问名称(`aria-label` 或可见文案);优先直接用原生 `<button>`,只有为保住既有视觉/鼠标行为时才用前者。
|
||||
例外:只用于事件委托、自身 `tabIndex = -1` 的正文容器不需要补,可聚焦的是容器内的 `<a>`。
|
||||
- 图标可访问名称(NEX §5.16):`@ant-design/icons` 会在外层 `<span>` 上输出 `role="img" aria-label="<字形名>"`
|
||||
(如 `file-text`、`caret-down`),字形名会泄进可访问名称。判定只有两条:
|
||||
图标纯属装饰 → 加 `aria-hidden`;图标是控件唯一的名称来源 → 给**控件**加业务语义 `aria-label`,图标同时 `aria-hidden`。
|
||||
名称取自可见文案或同一子树内 Tooltip 的 `title`,不要编造。
|
||||
- antd 自己渲染、我们无法直接加属性的图标,走 `@/utils/antdA11y` 与官方逃生口,**不要**写深层 DOM/CSS 覆盖:
|
||||
`clearInputIcon()` → `allowClear={{ clearIcon }}`;`namePageItem` → `Pagination`/`Table` 的 `itemRender`;
|
||||
`searchEnterButton()` → `Input.Search` 的 `enterButton`;`decorativeSwitcherIcon` → `Tree`/`TreeSelect` 的 `switcherIcon`;
|
||||
`rangeSeparatorWithLabel()` → `RangePicker` 的 `separator`(必须保留 `ant-picker-separator` 类,否则图标会掉一圈字号);
|
||||
`decorativeAlertIcon(type)` → `Alert showIcon` 的图标(antd 会把 `ant-alert-icon` 类合并回来,`type` 要与 `Alert` 的一致);
|
||||
`passwordVisibilityIcon` → `Input.Password` 的可见性切换(`iconRender={passwordVisibilityIcon}`,它是可点控件、必须给名称而不是 `aria-hidden`);
|
||||
表格行选择复选框在 `ListTable` 里已统一用 `rowSelection.columnTitle` / `renderCell` 补 `全选` / `选择第 N 行`,新增表格直接用 `ListTable` 即可;
|
||||
全局的 Tabs 溢出图标在 `App.tsx` 的 `ConfigProvider tabs.moreIcon` 统一设置。
|
||||
- `Select`/`TreeSelect` 的 `placeholder` 只是渲染成普通 span,**不会**成为 combobox 的可访问名称;
|
||||
无可见 label 绑定时必须补 `aria-label`,且取值与占位文案保持一致。
|
||||
|
||||
## 7. 自检清单
|
||||
|
||||
|
|
@ -130,15 +150,18 @@ open http://localhost:5173 # 登录页
|
|||
## 8. 常用开发命令
|
||||
|
||||
```bash
|
||||
cd frontend && npm run lint # ESLint(当前基线:0 error / 25 warning)
|
||||
cd frontend && npm run lint:strict # 警告也视为失败
|
||||
cd frontend && npm run build # 生产构建
|
||||
cd frontend && npm run typecheck # tsc 严格检查(tsconfig.json + tsconfig.node.json)
|
||||
cd frontend && npm run lint # ESLint(当前基线:0 error / 25 warning)
|
||||
cd frontend && npm run lint:strict # 警告也视为失败
|
||||
cd frontend && npm run build # 生产构建
|
||||
|
||||
cd backend && ./venv/bin/pip install -r requirements-dev.txt # 安装 pytest 等开发依赖
|
||||
cd backend && ./venv/bin/python -m pytest # 当前基线:40 passed
|
||||
```
|
||||
|
||||
> 注意:`npx eslint src` 会**秒退且全通过**——ESLint 8 对目录默认只收 `.js`,必须写 `eslint "src/**/*.{js,jsx}"` 或用 `npm run lint`(已带 `--ext js,jsx`)。
|
||||
> 注意:ESLint 8 对目录默认只收 `.js`,因此必须用 `npm run lint`(已带 `--ext ts,tsx`),
|
||||
> 不要直接 `npx eslint src`——那会**秒退且全通过**,等于没检查。
|
||||
> `npm run build` 走的是 Vite(esbuild 只做转译,**不做类型检查**),所以类型问题只能靠 `npm run typecheck` 兜住。
|
||||
|
||||
## 9. 数据库结构与迁移
|
||||
|
||||
|
|
@ -156,7 +179,7 @@ cd backend && ./venv/bin/python -m pytest # 当前基线:
|
|||
| `✗ MySQL 连接失败:Access denied` | 用户/密码/授权主机不匹配;确认对 `DB_NAME` 有权限 |
|
||||
| 后端起来了但某些表不存在 | 模型未在 `app/models/__init__.py` 注册;补 import 后 `--init-db` |
|
||||
| 前端 401 后一直跳登录页 | Token 过期(`ACCESS_TOKEN_EXPIRE_MINUTES`),或 `SECRET_KEY` 改过导致旧 Token 失效 |
|
||||
| 前端请求 404 | 后端未启动/端口不是 8000(改了 `--port` 就要同步改 `vite.config.js` 的 proxy target) |
|
||||
| 前端请求 404 | 后端未启动/端口不是 8000(改了 `--port` 就要同步改 `vite.config.ts` 的 proxy target) |
|
||||
| `pip install` 卡在 torch | 网络问题;用清华源,或临时跳过 `sentence-transformers`(仅本地 Embedding 需要) |
|
||||
| 控制台刷屏 SQL | `DEBUG=True` 的正常行为,关掉即止 |
|
||||
| 端口被占用 | `lsof -ti:8000 \| xargs kill`;后端也可 `./scripts/start.sh --port 8001` |
|
||||
|
|
|
|||
|
|
@ -6,7 +6,13 @@
|
|||
3. **MySQL 5.7.5+ / 生产镜像 MySQL 8.0**,utf8mb4。
|
||||
4. **Redis**:Token 缓存、会话状态、通知等。
|
||||
5. **JWT**(python-jose HS256)+ **bcrypt**(passlib)。
|
||||
6. **前端 React 18 + Vite 5 + Ant Design 5 + Tailwind + Zustand**;路由 React Router v6。
|
||||
6. **前端 React 18(TypeScript)+ Vite 5 + Ant Design 5 + Zustand**;路由 React Router v6;
|
||||
样式为 **CSS Variables + 手写 CSS**:`src/styles/design-tokens.css` 供自定义样式使用,
|
||||
`src/theme/antdTheme.ts` 以 antd 5 的 `ThemeConfig` 供组件内部样式使用。
|
||||
两者是**并行手工维护的同值副本**(明/暗两套取值当前完全一致),并非单向派生,见 OP-10。
|
||||
**仓库内没有 Tailwind / PostCSS**:`package.json` 无相关依赖,`src` 下无 `@apply` 与 `tailwind` 关键字。
|
||||
这一点与 [ADR-0003](decisions/ADR-0003-tech-stack.md) 的文字表述不一致,见 OP-7。
|
||||
类型检查为独立门禁:`npm run typecheck`(`tsc` strict);`npm run build` 走 Vite/esbuild,不做类型检查。
|
||||
7. **Whoosh3**(全文)+ **ZVec**(向量)+ **jieba**(中文分词)。
|
||||
8. **WeasyPrint**(PDF 导出)、**pdfjs-dist/react-pdf**(前端 PDF 预览)、**react-virtuoso/react-window**(虚拟列表)。
|
||||
9. **部署**:Docker Compose v2 + Engine ≥ 25(ADR-0008)。
|
||||
|
|
@ -24,6 +30,10 @@
|
|||
| OP-4 | 测试覆盖 | 仅 3 个后端单测 | 增加集成/E2E,见 OI-3 |
|
||||
| OP-5 | 实时协同编辑 | 明确不在此版本做(vision 边界) | 另立项评估 OT/CRDT |
|
||||
| OP-6 | 多实例/高可用 | 单机部署,无状态服务仅后端(Redis/DB 独立) | 若需要再评估 |
|
||||
| OP-7 | ADR-0003 写了 Tailwind,实现从未引入 | 代码事实:无 Tailwind;README 已按「无 Tailwind」记载 | ADR-0003 属已 Accepted 记录,改动需按 governance 审批矩阵走架构+技术负责人;建议以「实现澄清注记」修订而非新建 ADR |
|
||||
| OP-8 | NEX `tooling` 声明 Prettier / Vitest / Playwright | 三者均未落地:无 `.prettierrc`、无 vitest/playwright 依赖与用例 | 引入属新增技术依赖(NEX 约束 #7/#19),需单独批准后再登记为质量门禁 |
|
||||
| OP-9 | 后端数据库与 `stack.database` 不一致 | 实际为 MySQL 5.7+/8.0(见第 3 条),非 SQLite/PostgreSQL | 已有项目按 NEX §3 保留现状;`stack.database` 仅作为新项目默认值 |
|
||||
| OP-10 | 设计 Token 有两份人工维护来源 | `design-tokens.css` 与 `antdTheme.ts` 同值并行维护,新增/修改色值需改两处;当前取值一致,无实际冲突 | NEX §4 要求单一事实来源;但单向派生(CSS→JS 或 JS→CSS)属样式层重构,按 NEX §5.19 需先给出级联/收益证据再评审,本轮仅登记 |
|
||||
|
||||
## 约束的规格化引用
|
||||
- 以上条目若成为刚性承诺,须固化为 ADR 并登记到 `decisions/README.md`。
|
||||
|
|
|
|||
|
|
@ -6,5 +6,14 @@
|
|||
| --- | --- | --- |
|
||||
| [code-structure-standards.md](code-structure-standards.md) | 规范(强制执行) | 通用代码结构边界、分层模型、前端/后端/CLI 规范、审计清单 |
|
||||
| [code-structure-audit-2026-04-08.md](code-structure-audit-2026-04-08.md) | 审计记录 | 2026-04-08 前后端结构审计与已落地优化项 |
|
||||
| [nex-conformance-matrix.md](nex-conformance-matrix.md) | 符合性矩阵 | 按 NEX 0.1.6 逐条登记项目实现状态、Token 映射、组件复用与例外(2026-11-08) |
|
||||
| [responsive-breakpoint-registry.md](responsive-breakpoint-registry.md) | 断点登记表 | 全站 22 条 `@media` 的语义、理由、边界测试覆盖与例外(2026-11-08) |
|
||||
|
||||
> 来源:原 `docs/code-structure-standards.md`、`docs/code-structure-audit-2026-04-08.md`,于 SDD 整合时迁入。
|
||||
> 来源:`code-structure-*` 两份由原 `docs/code-structure-standards.md`、`docs/code-structure-audit-2026-04-08.md` 于 SDD 整合时迁入;
|
||||
> `nex-*` / `responsive-*` 两份为 NEX 0.1.6 合规审计(2026-11-08)产出。
|
||||
>
|
||||
> `code-structure-audit-2026-04-08.md` 是**当日快照式审计记录**,不作为当前结构基线:
|
||||
> 其中列出的若干前端模块(`useDocumentBrowser`、`documentBrowserUtils`、`useDocumentEditorWorkspace`、`browserIO`、
|
||||
> `useProjectExport` / `useProjectShare` / `useProjectCollaboration` / `useProjectGitRepos`)已在后续重构中被删除,
|
||||
> 仓库现状已查无此文件。当前基线以 `code-structure-standards.md` 与真实代码为准。
|
||||
> 另注:该记录中的前端文件名仍写作 `.js` / `.jsx`,前端已于 2026-11-08 全量迁移为 TypeScript。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
# NEX 项目符合性矩阵(Project Conformance Matrix)
|
||||
|
||||
**项目:** NexDocus
|
||||
**审计日期:** 2026-11-08
|
||||
**实施轮次:** 2026-11-09 复审——把首轮记为 `DEFERRED` 的 §5.16 / §5.11 两项 MUST 实施完毕,本表数字为实施后实测值
|
||||
**NEX 版本:** 0.1.6
|
||||
**项目级规范:** `docs/sdd/architecture/`(技术约束与决策)、`docs/sdd/architecture/standards/code-structure-standards.md`、`docs/quickstart.md` §6(前端约定);Token 权威来源见下表
|
||||
**审计范围:** 全仓前端(`frontend/src` 71 个 `.ts`/`.tsx`,0 个 `.js`/`.jsx`)与 `nex.config.yaml`;后端为 Python/FastAPI,未改动,仅作契约核对
|
||||
|
||||
状态值:`COMPLIANT` / `ADOPTED` / `ADAPTED` / `DEFERRED` / `NOT_APPLICABLE`
|
||||
|
||||
> **生命周期判定**:`project.lifecycle: auto` 且仓库已有 280 个受版本控制文件、锁文件与构建配置,按 **existing** 处理。
|
||||
> 因此 `stack` 中的默认技术栈只作参考,**不**据此迁移现有技术(NEX §3)。
|
||||
> 唯一例外:前端切换 TypeScript 由用户在本轮明确授权(`stack.frontend.language: TypeScript`),记为 `ADAPTED`。
|
||||
|
||||
| NEX 主题/规则 | 项目规范章节 | 实现位置 | 状态 | 证据/测试 | 差异、风险与行动 |
|
||||
|---|---|---|---|---|---|
|
||||
| 设计原则与信息层级 | quickstart §6 | `frontend/src/styles/design-tokens.css`、各页面 CSS | ADAPTED | E0 源码审阅:TSX 层原有 **12 处**字面量色值(6× `#bfbfbf`、4× `#f5222d`、`#f0f0f0`、`#722ed1`/`#8c8c8c`)已全部改消费语义 Token,**0 处**残留;`antdTheme.ts` 中的主题字面量属 antd Token 源,不计入业务层。另在 CSS 层把 3 处 `#f5222d` 的引用改为 `--color-pdf` / `--color-danger-strong`(含渐变端点)。按「含颜色表达式的 CSS 行数」复核:HEAD 非 Token 源为 **199 行**,当前为 **196 行 / 21 个文件**,其余均属历史实现,未在本轮批量替换。亮色取值逐项保持;`--border-color-strong` 在暗色下翻为 `#5a5a5a`,登录图标与上传进度条分隔线由固定灰改为随主题调整 | 属既有实现,非本轮引入;与根 README「禁止硬编码色值」仍存在 CSS 历史字面量差异。已新增 `--color-danger-strong` / `--color-pdf` / `--color-stat-purple` / `--color-stat-gray` 并在明暗两套 Token 中成对定义,保持可见外观;CSS 层全量迁移属跨页面视觉变更,按 §5.19 / §5.20 单列后续评审,不机械替换 |
|
||||
| Token 权威来源 | constraints §6 | `frontend/src/styles/design-tokens.css:10-118`(亮 `:root`)/ `:120-182`(暗 `body.dark`);`frontend/src/theme/antdTheme.ts:90` | ADAPTED | 两份同值并行来源;已逐值核对 7 组语义色(primary / info / success / warning / error / border / border-secondary,注意 antd `colorError` 对应 CSS `--color-danger`)与 3 组圆角(6/8/12)明暗两侧**全部一致** | NEX §4 要求单一来源;单向派生属样式层重构,按 §5.19 先取证,登记为 OP-10 |
|
||||
| 主题映射与派生链路 | quickstart §6 | `frontend/src/App.tsx:56-66` | COMPLIANT | `body.dark` 类切换 + `ConfigProvider` 注入 `getAntdTheme(isDarkMode)`,单向、无回环 | — |
|
||||
| 布局与导航 | constraints §6 | `MainLayout.tsx:31-34`(Header 64px)、`DocumentEditor.tsx:1603`(Sider 280) | COMPLIANT | 沿用项目既有尺寸,未套用 NEX 参考项目数值 | `AppHeader.tsx` 的 `.trigger` 分支恒不渲染(`showLogo` 恒为 false),属既有死代码,仅登记不删除 |
|
||||
| 响应式断点登记与边界测试 | — | 22 条 `@media`,散布 14 个 CSS 文件 | COMPLIANT | 本轮已建立登记表并完成 E2 复测:`docs/sdd/architecture/standards/responsive-breakpoint-registry.md`。7 条宽度断点均覆盖前/到达/后三档,`tablet-landscape-only` 另测区间两端;所有记录回读 `window.innerWidth` 校准,`documentElement.scrollWidth <= innerWidth`,无整页横滚 | 断点仍无集中权威定义,登记即当前治理动作;`prefers-reduced-motion` 未改系统辅助功能设置,记 `MANUAL_QA_REQUIRED`;同断点次要规则未逐一做视觉翻转验证 |
|
||||
| 窄屏表格数据完整性对账 | — | `ListTable.tsx:53`(`scroll.x=1200`)、`SystemLogs.tsx:378`、`Users.tsx:378`、`Roles.tsx:389`、`ModelConfigs.tsx:642` | COMPLIANT | E2 实测 @466px(2026-11-08):4 张表**表头数 = 每行单元格数**且行间一致——Users 10↔10、Roles 10↔10、SystemLogs 9↔9(20 行)、ModelConfigs 8↔8(3 行);无列被隐藏(全站未用 antd `responsive` 列属性,已 grep 确认),表格自身横向滚动(`scrollWidth > clientWidth`),页面级 `scrollWidth ≤ innerWidth` 不产生整页横滚;末列「操作」的编辑/删除/重置等动作在滚动后仍可达 | 窄屏未做「卡片化/折叠详情」,因此不存在字段丢失面;分页总数文案在 SystemLogs 上为空(该表本就未配 `showTotal`),非缺陷 |
|
||||
| 共享组件资产 | code-structure-standards | `frontend/src/components/`(15 项) | COMPLIANT | 见下方「既有组件映射」,本轮复用 `treeUtils` 去掉一处重复实现 | 未发现重复的第二套组件库 |
|
||||
| 主要交互模式 | quickstart §6 | `Toast/Toast.tsx`、`ModeSwitch`、`ProjectFileTree` | COMPLIANT | E2 实测:文件树右键菜单→删除确认→列表刷新链路可用 | — |
|
||||
| Loading / Empty / Error 等状态 | — | 各页面 + `PageLoading`、`Empty`、`Toast` | ADAPTED | E2:Chat 流式(思考中/计时)、ProjectList 空态、DocumentEditor 加载态均实测;状态不仅靠颜色区分 | 错误态文案已统一经 `utils/apiError.ts` 取后端 `detail` |
|
||||
| 键盘与焦点 | — | `index.css:158-161`(全局 `:focus-visible` 描边)、`utils/a11yActivation.ts`、`AppHeader.tsx`、`ModernSidebar.tsx`、`ProjectList.tsx`、`Chat.tsx`、`StatCard.tsx`、`DocumentEditor.tsx`、`DocumentPage.tsx`、`ProjectSharePage.tsx` | COMPLIANT | E2 实测:侧栏主导航 Enter 跳 `/system/users`、Space 跳 `/system/roles`,`:focus-visible` 命中且描边取到 `--color-primary`;项目卡片图标按钮 `项目设置` 按 Enter 打开「编辑项目」、`成员管理` 按 Space 打开「成员管理」且不冒泡触发卡片跳转;文件夹/文件卡片 Enter/Space 分别跳 `?selected=` / `?file=` 且空格不滚动页面;Chat 会话行 Enter 打开会话 | `<div>/<span onClick>` 缺键盘语义 **18 → 4**;余 4 处(3 个 `bytemd-viewer-wrapper` + `LargeMarkdownViewer`)是正文事件委托容器,实测 `tabIndex = -1` 永不成为 tab 停靠点,内部 `<a>` 原生可聚焦并已验证 Enter 触发委托跳转,故不构成键盘缺口。详见 EX-7 |
|
||||
| 自定义控件可访问名称 | — | 14 处 antd `Select` / `TreeSelect`:`Chat.tsx`、`DocumentEditor.tsx`、`DocumentPage.tsx`、`ProjectList.tsx`、`System/{Users,Roles,ModelConfigs}.tsx`、`SystemLogs.tsx` | COMPLIANT | E2 可访问性树实测:加标签前 `combo box` 节点 `Description` 为空;加后为 `Description: 操作类型` / `资源类型` / `筛选提供方` 等,与可见占位文案一致 | antd 把 `placeholder` 渲染成 `.ant-select-selection-placeholder` 普通 span,**不**作为 combobox 的可访问名称,因此纯图标/占位型选择器原本无名。`aria-label` 会被 antd 透传到内部 `<input role="combobox">`,属一等 API,取值与可见文案保持一致以免名称与显示不符。另用严格度量复测 15 个界面(把 `opacity: 0` 的 combobox 内部 input 计入,且不再把「选中值/占位文本」误当作可访问名称):项目自有选择器 **0 无名**;仅剩 antd `Calendar` 表头的年/月选择器属「名称只来自当前值」,见 EX-8 |
|
||||
| 图标与可访问名称 | — | `frontend/src` 271 处 antd 图标(30 个文件):255 处 `aria-hidden` + 16 处业务语义 `aria-label`;antd 内部渲染的图标经 `utils/antdA11y.tsx` 与 `App.tsx` 的 `ConfigProvider tabs.moreIcon` 处理 | COMPLIANT | E0 静态:AST 逐点判定,未处理 **0**(HEAD 基线 **263/263 全部未处理**)。E2 实测 15 个界面(login / dashboard / desktop / projects/my / projects/share / projects/:id/docs / projects/:id/editor / chat / profile / notifications / system 全部 5 页),单页最多 113 个交互控件:字形名污染 **0**、可见且未受保护的泄漏 **0**、未命名交互控件 **0**;HEAD 基线示例:登录页按钮计算名 `arrow-right 立即登录`(重复朗读)、文件树菜单项 `file-text README`、卡片图标按钮读成 `setting`/`team` | 编辑器的 `Segmented` 视图模式项:图标改为 `aria-hidden`、名称放在既有包装 `span` 上,VoiceOver 侧 radio 仍取到 `编辑/分栏/预览/全屏`(包装名沿 name from contents 生效),不再出现图标与文案双节点重复 |
|
||||
| antd 内置控件可访问名称 | — | `utils/antdA11y.tsx`(`clearInputIcon` / `namePageItem` / `searchEnterButton` / `decorativeSwitcherIcon` / `rangeSeparatorWithLabel` / `decorativeAlertIcon` / `passwordVisibilityIcon`)、`ListTable.tsx`、`SystemLogs.tsx`、`NotificationList.tsx`、`ProjectList.tsx`、`Permissions.tsx`、`Chat.tsx`、`LargeMarkdownViewer.tsx`、`ProjectList.tsx` | COMPLIANT | E2 实测:分页按钮计算名由 `left` / `right` 变为 `上一页` / `下一页` / `向后 5 页`,翻页页码与数据均变化、首末边界 `aria-disabled` 正确;清空按钮名 `清空` 且点击仍能清空;`Input.Search` 按钮名 `搜索`,其 class(`ant-input-search-button ant-btn-icon-only`)、尺寸 34×34、边框与文字色与改动前**逐值一致**;`Tree` 展开箭头保留 `ant-tree-switcher-icon`(10px,折叠态 `rotate(-90deg)` 实测 `matrix(0,-1,1,0,0,0)`),点击后 `aria-expanded` false→true;`RangePicker` 分隔符 `至`,其包裹与图标几何 32×16 / 16×16、`fontSize 16px`、颜色 `rgba(0,0,0,.25)` 与改动前逐值一致 | 全部走官方逃生口(`allowClear={{ clearIcon }}`、`Pagination itemRender`、`enterButton` 传 Button、`Tree/TreeSelect switcherIcon`、`RangePicker separator/suffixIcon`、`Alert icon`、`Input.Password iconRender`、`rowSelection.columnTitle`/`renderCell`、`ConfigProvider tabs.moreIcon`),未使用深层 CSS/DOM 覆盖(§5.13);`separator` 必须沿用 `ant-picker-separator` 类,否则丢失 `fontSizeLG` 使图标小一圈(已实测并修正);`Alert showIcon` 的图标计算名为 `exclamation-circle`,改用 `icon={decorativeAlertIcon(type)}` 后 antd 会把 `ant-alert-icon` 类合并到自定义图标上,实测 24×24、`margin-right 12px`、`color rgb(250,173,20)`、消息文本 x=545.44 与改动前逐值一致,且 `unguarded` 泄漏由 1 归零;`Input.Password` 可见性切换(12 处)原名 `eye-invisible`,改用 `iconRender={passwordVisibilityIcon}` 后为 `显示密码`/`隐藏密码`,类名 `anticon-eye-invisible ant-input-password-icon`、16×16、`fontSize 16px`、`color rgba(0,0,0,.45)`、`cursor pointer`、`tabindex=-1` 逐值不变;表格行选择复选框原本包在**内容为空**的 `<label>` 内(算不出名称)、表头那个写死英文 `Select all`,改用 `rowSelection.columnTitle`/`renderCell` 后为 `全选` / `选择第 N 行`,结构与勾选行为不变 |
|
||||
| 真实辅助技术验证证据等级 | nex.config `quality.accessibility` | `nex.config.yaml` `quality.accessibility.evidence` | MANUAL_QA_REQUIRED | 已执行 E0 源码审阅 + E1 自动化(tsc / eslint / build / pytest)+ E2 浏览器人工交互(键盘 Enter/Space、鼠标回归、真实可访问性树取词) | 本轮改动覆盖自定义控件语义(`div`→`role=button`)、图标可访问名称、分页与树形控件,按 §5.17 已属应触发 E3 的范围;但 `auto_start_screen_reader: false` 且启动 VoiceOver 需单独授权,故记 `MANUAL_QA_REQUIRED` 而非 `E3_NOT_REQUIRED`。E2 侧已用 Chrome 真实可访问性树(非自建近似)核对计算名 |
|
||||
| 拖拽替代路径(如适用) | — | `DocumentEditor.tsx:1849`(`onDrop` 图片上传) | COMPLIANT | 拖拽仅承载 OS 文件投递,同页存在「上传文档」按钮与 `<Upload>` 作为非拖拽路径 | 不存在仅能拖拽完成的操作 |
|
||||
| 自动化质量门禁 | quickstart §8 | `package.json` scripts | COMPLIANT | 实施后实测:`typecheck` 0 错、`lint` **0 error / 25 warning**(与迁移前基线一致)、`build` 通过、后端 `./venv/bin/python -m pytest` **40 passed** | 未新增 `eslint-disable`;图标与键盘改动均在 TS/TSX 层,可被既有门禁覆盖 |
|
||||
| 视觉回归基线 | — | 无 | NOT_APPLICABLE | 仓库不存在视觉基线截图或 Percy/Playwright 快照 | 引入 Playwright 属新增依赖,需批准(OP-8) |
|
||||
|
||||
## Token Mapping
|
||||
|
||||
| 语义 | 项目 Token | 权威来源 | 派生链路/消费者 | 状态 |
|
||||
|---|---|---|---|---|
|
||||
| Brand | `--color-primary` 等 6 个 | `design-tokens.css:12-17` | 自定义 CSS 直接引用;antd 侧由 `antdTheme.ts:25` 同值提供 | ADAPTED(EX-1) |
|
||||
| Text Primary | `--text-color` / `-secondary` / `-tertiary` | `design-tokens.css:30-33` | 全站 CSS | COMPLIANT |
|
||||
| Surface | `--card-bg` / 面板变量 | `design-tokens.css:36-49` | 全站 CSS | COMPLIANT |
|
||||
| Border | `--border-color` 等 | `design-tokens.css:50-55` | CSS;antd `colorBorder` 同值并行 | ADAPTED(EX-1) |
|
||||
| Spacing | `--space-*`(4px 基准) | `design-tokens.css:68-76` | 全站 CSS | COMPLIANT |
|
||||
| Typography | **无字号/行高 Token**;仅 `antdTheme.ts:11-16` 定义 `FONT_FAMILY` 与 `fontSize: 14` | antd 侧 `fontSize: 14` | 自定义 CSS 直接写 `font-size: Npx`(172 处),不经 Token | DEFERRED(EX-6) |
|
||||
| Radius | `--radius-xs…xl/pill` | `design-tokens.css:78-83` | CSS;antd `borderRadius*` 同值并行 | ADAPTED(EX-1) |
|
||||
| Elevation / Z-index | `--z-base…--z-notification` | `design-tokens.css:95-102` | 全站 CSS,避免各页抢占层级 | COMPLIANT |
|
||||
|
||||
## Existing Component Mapping
|
||||
|
||||
| NEX 能力 | 项目已有组件 | 位置 | 覆盖程度 | 状态/处理 |
|
||||
|---|---|---|---|---|
|
||||
| Page Heading | `PageHeader` | `components/PageHeader/`(8 处引用) | 全站标题 + 操作区 | ADOPTED |
|
||||
| Search / Filter | `ListActionBar` | `components/ListActionBar/` | 搜索 + 动作 + 刷新 | ADOPTED |
|
||||
| Data Table / List | `ListTable` | `components/ListTable/`(4 处引用) | 选择态、分页、横向滚动 | ADOPTED |
|
||||
| Form | antd `Form` | 各页面直接使用 | 完整 | NOT_APPLICABLE(无需二次封装,符合 §5.9) |
|
||||
| Modal / Drawer | antd `Modal` + 自研 `Toast.confirm` | `components/Toast/`、`components/Feedback/` | 确认弹窗统一走 Toast | ADOPTED |
|
||||
| Empty / Loading / Error | `Empty` / `PageLoading` / `Toast` | `components/` | 三态齐备 | ADOPTED |
|
||||
| 文件树 | `ProjectFileTree` | `components/ProjectFileTree/` | 浏览/编辑/分享三模式共用 | ADOPTED |
|
||||
| 大纲 / 阅读器 | `FloatingToc`、`LargeMarkdownViewer`、`PDFViewer` | `components/` | 编辑与预览共用 | ADOPTED |
|
||||
| 侧边栏(旧) | `ModernSidebar` | `components/ModernSidebar/` | 仅 1 处引用 | 存量,未在本轮清理(§5.20 范围受控) |
|
||||
|
||||
## Exceptions / Decisions
|
||||
|
||||
| 规则 | 状态 | 理由/证据 | 影响范围 | 批准来源 | 复审条件 |
|
||||
|---|---|---|---|---|---|
|
||||
| EX-1 · §4 Token 单一来源 | ADAPTED | `design-tokens.css` 与 `antdTheme.ts` 同值并行,取值核对一致;antd v5 的 token 必须由 JS 传入 `ConfigProvider`,无法直接消费 CSS 变量 | 全站主题 | 现状既有实现,NEX §3「已有项目以实际项目为准」 | 出现任一语义值双源不一致时,先做单向派生再评审 |
|
||||
| EX-2 · §7 不擅自改技术栈(前端 TS) | ADAPTED | 用户本轮明确要求「前端切换成 typescript」,与 `stack.frontend.language` 一致;后端未动 | `frontend/src` 全部源码 | 用户指令(本轮对话) | 若引入新框架/构建工具需再次批准 |
|
||||
| EX-3 · §5.16 图标不得污染可访问名称 | COMPLIANT(已实施) | 原缺陷:antd 图标在外层 `<span>` 输出 `role="img" aria-label="<字形名>"`(`@ant-design/icons/lib/components/AntdIcon.js:57-58`),HEAD 全站 **263 处图标全部未处理**,控件计算名被字形名污染(`arrow-right 立即登录`、`file-text README`、`setting`、`left`)。实施:装饰图标加 `aria-hidden`(250 处);纯图标控件补业务语义 `aria-label`(19 处,取自可见文案或同一子树内的 Tooltip `title`);antd 自己渲染的图标走官方逃生口(见「antd 内置控件可访问名称」行)。静态逐点判定残留 **0**;运行时 12 个界面全部 0 污染 / 0 未命名 | 全站 30 个含图标的文件;仅改可访问性属性,未改可见外观与鼠标行为(§5.6) | 用户指令「继续推进,直到按新规范完整做完」;§5.16 属 MUST,不得长期 DEFERRED | E3 真实屏幕阅读器抽检(启动 VoiceOver 需单独授权);新增图标须沿用「装饰→`aria-hidden`;图标是控件唯一名称来源→业务语义 `aria-label`」判定 |
|
||||
| EX-4 · tooling:Prettier / Vitest / Playwright | DEFERRED | 配置声明但仓库未落地:无 `.prettierrc`,`package.json` 无 vitest/playwright | 质量门禁 | 待批准(OP-8) | 引入即新增依赖,按 §5.7/§5.19 先评审 |
|
||||
| EX-5 · §5.19 性能/分包 | DEFERRED | `build` 提示 4 个 chunk >900 kB(antd 1.30 MB 等),迁移前后一致 | 构建产物 | 现状保留 | 需先有真实加载数据再动 `manualChunks` |
|
||||
| EX-6 · §4/§5.2 排印未 Token 化 | DEFERRED | `design-tokens.css` 未定义任何字号/行高变量(`--font*` 命中 0),而 `src` 下有 **172 处** `font-size: Npx` 与 **64 处** `line-height`,其中最集中的是 14px(38)、12px(36)、16px(23)、13px(22);antd 侧另有 `fontSize: 14`。当前两侧基准一致,但字号无法随主题或全局调整 | 全站自定义样式(236 处声明) | 待批准 | 属批量样式改动:建议先加 `--font-size-*` 阶梯再机械替换并做视觉对账;按 §5.19 需先给出收益证据,本轮仅登记 |
|
||||
| EX-7 · §5.11 自定义交互需支持键盘 | COMPLIANT(已实施) | 基线 HEAD 有 **18 处** `<div>/<span onClick>` 无 `role`/`tabIndex`/`onKeyDown`,现为 **4 处**,且这 4 处实测不构成键盘缺口(见下)。已修 14 处:`AppHeader` 2 处改原生 `<button>`;`ModernSidebar` 3 处(**主导航**,此前键盘完全不可达)、`ProjectList` 成员管理与 4 个卡片图标按钮、`Chat` 会话行、`StatCard`、6 处文件夹/文件卡片(`DocumentEditor` 2、`DocumentPage` 2、`ProjectSharePage` 2)统一改用新增的 `utils/a11yActivation.ts`(`role=button` + `tabIndex=0` + Enter/Space,空格阻止默认滚动)。E2 实测:侧栏 Enter 跳 `/system/users`、Space 跳 `/system/roles`,`:focus-visible` 命中且描边取到 `--color-primary`;卡片图标 Enter 打开「编辑项目」、Space 打开「成员管理」且不冒泡触发卡片跳转;文件夹卡片 Enter→`?selected=guide`、文件卡片 Space→`?file=README.md` 且无滚动副作用;Chat 会话行 Enter 打开会话;鼠标行为不变(§5.6)。残留 4 处均为正文**事件委托容器**(3 个 `bytemd-viewer-wrapper` + `LargeMarkdownViewer`),实测 `tabIndex = -1` 永不成为 tab 停靠点,真正可聚焦的是其内部渲染出的 `<a>`;已验证在 `a[href="./other.md"]` 上按 Enter 触发委托并跳到 `file=other.md`,键盘路径本就完整,给容器补 `role`/`tabIndex` 反而增加无意义停靠点 | `frontend/src` 9 个文件 | 用户指令「继续推进,直到按新规范完整做完」;§5.11 属 MUST | 新增 `div`/`span` 点击必须走 `keyboardActivation()`(已写入 `docs/quickstart.md` §6);E3 抽检待授权 |
|
||||
| EX-8 · §5.11/§5.16 antd `Calendar` 表头选择器无独立名称 | ADAPTED(受上游 API 限制) | `/desktop` 用 `<Calendar fullscreen={false}>`,其表头由 `antd/lib/calendar/Header.js:17-64` 内部渲染两个 `Select`,props 没有 `aria-label`/`placeholder` 出口;实测 VoiceOver 读作「2026年 组合框」——名称来自**当前值**而非控件用途,值一变名称就变。它旁边同时可见「2026年」「11月」文本,因此不构成完全无名(严格度量记为 `name-from-value-only` 而非 `UNNAMED`)。唯一的一等改法是 `headerRender` 自行重写整个表头,属可见结构改动 | `/desktop` 一个组件、2 个选择器 | 现状保留:按 §5.13/§5.19 不为可访问性名称重写 antd 内部结构,也不做深层 DOM 覆盖 | 若要求 AT 明确播报「选择年份/选择月份」,改用 `headerRender` 自定义表头(带 `aria-label` 的 `Select` + `Radio.Group`),需回归日历切换与外观 |
|
||||
|
||||
## Not Applicable
|
||||
|
||||
| NEX 模式/功能 | 不适用理由 | 是否需要后续复审 |
|
||||
|---|---|---|
|
||||
| `stack.preset` 的新项目默认栈(Tailwind v4、SQLite/PostgreSQL) | 已有项目;实际为 CSS Variables + 手写 CSS、MySQL。README 与代码一致,`stack` 仅作新项目默认值 | 否(除非决定引入 Tailwind) |
|
||||
| 视觉回归基线 | 仓库无基线与对比工具,凭空引入会新增依赖 | 是 |
|
||||
| 页面模式(Page Patterns)全量套用 | 只为项目真实存在的页面采用;NEX 参考项目的 Header/Sider 尺寸、断点、控件高度未套用 | 否 |
|
||||
| E3 真实屏幕阅读器验证 | 不再视为不适用:本轮已改动自定义控件语义与全站图标可访问名称,属 §5.17 的触发范围,已改记 `MANUAL_QA_REQUIRED`(见上表) | 是——授权后在 macOS VoiceOver 上抽检侧栏导航、项目卡片图标按钮、文件树展开、分页与表格 |
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
# 响应式断点登记表(Responsive Breakpoint Registry)
|
||||
|
||||
**项目:** NexDocus
|
||||
**权威来源:** 无集中定义——6 个宽度值以字面量散落在 14 个 CSS 文件的 22 条 `@media` 中(本表即为登记动作)
|
||||
**负责人:** 待指派(前端)
|
||||
**最后复核:** 2026-11-09
|
||||
|
||||
状态值:`COMPLIANT`(有登记且有边界测试)/ `ADAPTED`(有登记,边界测试待补)/ `DEFERRED`
|
||||
|
||||
> 说明:项目另有两条由 antd 主题驱动的响应式链路——`ProjectList.tsx` 的栅格 `xs=24 sm=12 md=8 lg=6`,
|
||||
> 以及 `ModelConfigs.tsx:144` 的 `Grid.useBreakpoint()`。实测本仓库 antd 实际取值为
|
||||
> `screenXS=480 / screenXSMax=575 / screenSM=576 / screenMD=768 / screenLG=992 / screenXL=1200 / screenXXL=1600`。
|
||||
> 下列自研 CSS 字面量中有 **5 个与该刻度完全重合**(480/576/768/992/1200),
|
||||
> **只有 `1024px`(2 处)落在 antd 刻度之外**,是本项目独有的断点。
|
||||
> 本表登记自研 CSS 里写死的媒体查询;antd 刻度由主题 token 负责,不重复登记。
|
||||
|
||||
| 名称 | 条件 | 布局问题/理由 | 影响页面/组件 | 权威定义 | 边界测试宽度(前/到达/后) | 证据 | 状态/复审条件 |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `narrow-desktop-down` | `max-width: 1200px` | 桌面端在较小窗口下压缩侧栏与信息列,避免横向溢出 | `Chat.css:1044`、`Login.css:259`、`AdminPages.css:95` | 各文件字面量 | **1201 / 1200 / 1199** | 2026-11-09 E2:Login 左内边距 60→40→40、标题 48→40→40,Chat 会话列 320→300→300,系统日志 4 列→2 列→2 列,三档均无整页横滚 | COMPLIANT(边界已验证)/ 其余同断点规则未逐一验证效果 |
|
||||
| `tablet-landscape-down` | `max-width: 1024px` | 悬浮元素内移并收窄面板宽度,避免遮挡正文 | `FloatingToc.css:197` | 字面量(**不在 antd 刻度上**) | **1025 / 1024 / 1023** | 2026-11-09 E2:浮动目录 `right` 24→24→16px、面板宽 420→420→360px,三档均无整页横滚 | COMPLIANT(边界已验证) |
|
||||
| `tablet-landscape-only` | `min-width: 768px and max-width: 1024px` | 仅平板横屏需要的中间档排布 | `PreviewPage.css:610` | 字面量 | **1025 / 1024 / 769 / 768** | 2026-11-09 E2:外边界 1025px 恢复 `max-width:1100px`、1024px 仍为 `100%`;内边界 769px 仍为 `100%`、768px 恢复 `1100px`,区间两端均正确翻转,四档均无整页横滚 | COMPLIANT(双边界已验证) |
|
||||
| `tablet-portrait-down` | `max-width: 992px` | 两栏改单栏、表单与图表降列 | `Chat.css:1050`、`Desktop.css:99`、`Login.css:273`、`AdminPages.css:101` | 字面量 | **993 / 992 / 991** | 2026-11-09 E2:Login 由双栏→双栏→单栏,Chat 由双栏→双栏→单栏,Desktop `.calendar-card` 400→400→auto,权限页两栏→两栏→单栏,三档均无整页横滚 | COMPLIANT(边界已验证) |
|
||||
| `mobile-down` | `max-width: 768px` | 隐藏非核心的悬浮/装饰元素,主内容全宽;单列堆叠 | `FloatingToc.css:207`、`LargeMarkdownViewer.css:67`、`ListActionBar.css:85`、`PageHeader.css:99`、`DocumentEditor.css:667`、`DocumentPage.css:512`、`PreviewPage.css:535`、`ProfilePage.css:253`、`ModelConfigs.css:157` | 字面量(9 处,最密) | **769 / 768 / 767** | 2026-11-08 旧测:769px `.list-action-bar` 为 `row`+`center`,768/766px 为 `column`+`stretch`。2026-11-09 复测:项目列表工具栏 769→768 翻转为 `column`+`stretch`,浮动目录 769 可见→768 隐藏,Profile 内边距 24→16px,预览正文内边距 16px,三档均无整页横滚 | COMPLIANT(边界已验证)/ 同断点其余规则未逐一验证效果 |
|
||||
| `small-mobile-down` | `max-width: 576px` | 登录页去掉品牌分栏,表单独占全宽 | `Login.css:306` | 字面量 | **577 / 576 / 575** | 2026-11-09 E2:登录右栏内边距 24→24→16px、表单最大宽度 400→400→100%、标题 32→32→28px,三档均无整页横滚 | COMPLIANT(边界已验证) |
|
||||
| `xs-mobile-down` | `max-width: 480px` | 极窄屏下的最小可读排版 | `LargeMarkdownViewer.css:73`、`PreviewPage.css:622` | 字面量 | **481 / 480 / 479** | 2026-11-09 E2:预览正文内边距 16→12→12px;历史 466px 表格对账通过(Users/Roles/SystemLogs/ModelConfigs 表头数=单元格数、动作可达);三档均无整页横滚 | COMPLIANT(边界已验证)/ 未再逐表做 481/480/479 数据对账 |
|
||||
| `reduced-motion` | `prefers-reduced-motion: reduce` | 前庭功能障碍用户降低动画 | `index.css:182` | 字面量 | 未执行系统偏好开关测试 | 2026-11-09 浏览器默认偏好下 `matchMedia` 为 `false`;规则本身经 E0 源码审阅 | ADAPTED / 需在系统层开启后抽检 |
|
||||
|
||||
## 边界测试记录
|
||||
|
||||
| 断点 | 前 | 到达 | 后 | 预期行为 | 实测结果 | 证据 | 通过 |
|
||||
|---|---:|---:|---:|---|---|---|---|
|
||||
| `narrow-desktop-down` (1200) | **1201px** | **1200px** | **1199px** | 进入 ≤1200 后降列/收窄 | Login 左内边距 60→40→40px、标题 48→40→40px;Chat 会话列 320→300→300px;系统日志 4 列→2 列→2 列;`documentElement.scrollWidth == innerWidth` | 2026-11-09 E2 视口覆核 + `getComputedStyle` | **通过** |
|
||||
| `tablet-landscape-down` (1024) | **1025px** | **1024px** | **1023px** | 进入 ≤1024 后悬浮目录内移、面板收窄 | 1025/1024:`right=24px`、面板 420px;1023:`right=16px`、面板 360px;三档无整页横滚 | 2026-11-09 E2 | **通过** |
|
||||
| `tablet-landscape-only` (768–1024) | **1025px / 769px** | **1024px / 768px** | **1023px / 767px** | 双边界区间内预览正文全宽 + 20px 内边距 | 1025/768:正文 `max-width=1100px`;1024/769:`max-width=100%` + 20px;1023/767 延续区间内/移动端规则;边界两侧正确翻转,无整页横滚 | 2026-11-09 E2 | **通过** |
|
||||
| `tablet-portrait-down` (992) | **993px** | **992px** | **991px** | 进入 ≤992 后单栏化 | Login/Chat/权限页 993/992 为双栏、991 为单栏;Desktop 日历卡 400→400→auto;三档无整页横滚 | 2026-11-09 E2 | **通过** |
|
||||
| `mobile-down` (768) | **769px** | **768px** | **767px** | ≤768px 工具栏竖排、悬浮目录隐藏、页面内边距收紧 | 项目列表工具栏 `row`→`column`→`column`;浮动目录 `block`→`none`→`none`;Profile 24→16→16px;三档无整页横滚 | 2026-11-09 E2(结合 2026-11-08 旧测) | **通过** |
|
||||
| `small-mobile-down` (576) | **577px** | **576px** | **575px** | 进入 ≤576 后登录表单全宽、内边距与标题收紧 | 右栏内边距 24→24→16px;表单 `max-width` 400→400→100%;标题 32→32→28px;三档无整页横滚 | 2026-11-09 E2 | **通过** |
|
||||
| `xs-mobile-down` (480) | **481px** | **480px** | **479px** | 进入 ≤480 后预览正文 12px 内边距 | `.preview-content-wrapper` 16→12→12px;三档无整页横滚;466px 历史表格对账仍有效 | 2026-11-09 E2 | **通过** |
|
||||
| `reduced-motion` | — | 系统层开启后 | — | 全局动画/过渡降到 0.001ms | 默认浏览器偏好下 `matchMedia=false`;未改系统辅助功能设置 | 2026-11-09 E0 源码 + E2 只读检测 | 待补(MANUAL_QA_REQUIRED) |
|
||||
|
||||
> 窄屏表格对账(NEX §5.15):全站未使用 antd 列的 `responsive` 属性,也没有把表格改写成卡片或折叠详情,
|
||||
> 因此**不存在「列被隐藏导致数据无处可见」的面**;上述 466px 实测进一步确认字段、记录数、顺序与动作均完整可达。
|
||||
|
||||
## 例外
|
||||
|
||||
| 局部例外 | 理由 | 为何既有断点不够 | 范围 | 批准 | 复审条件 |
|
||||
|---|---|---|---|---|---|
|
||||
| 1024 与 992 并存 | 前者只服务悬浮大纲收窄(2 处),后者服务整页降列(4 处),历史形成 | 1024 是全站唯一不在 antd 刻度上的值,属可归并候选;但改它会改变 2 个文件的排版 | `FloatingToc.css:197`、`PreviewPage.css:610` | 现状保留 | 若要归并到 992/1200,需一次性改并复测全部 22 条规则 |
|
||||
| 无集中变量 | 项目未定义断点 token(CSS 变量无法用于媒体查询条件) | — | 全站 | 现状保留 | 引入 PostCSS/自定义媒体查询工具时统一 |
|
||||
|
||||
## 待办(本轮未做)
|
||||
|
||||
- 7 条宽度断点均已完成前/到达/后三点边界测试;`tablet-landscape-only` 为双边界区间,额外测了两端与区间内档位。仍有部分同断点的次要规则未逐一验证视觉翻转,但所有测试视口的 `documentElement.scrollWidth` 均不超过 `window.innerWidth`。
|
||||
- `reduced-motion` 仍需在系统层开启「减少动态效果」后抽检;本轮未擅自更改系统辅助功能设置,状态记 `MANUAL_QA_REQUIRED`。
|
||||
- 测量提示:浏览器视口覆核的设定值与实际 `innerWidth` 存在非线性偏差(实测请求 691→768、432→480),所有记录均已回读页面内 `window.innerWidth` 校准;后续补测同样不要直接相信设定值。
|
||||
|
|
@ -3,10 +3,12 @@ module.exports = {
|
|||
env: { browser: true, es2021: true },
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:react/recommended',
|
||||
'plugin:react/jsx-runtime',
|
||||
'plugin:react-hooks/recommended',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
|
|
@ -16,14 +18,15 @@ module.exports = {
|
|||
ignorePatterns: ['dist', 'node_modules', 'public'],
|
||||
overrides: [
|
||||
{
|
||||
files: ['vite.config.js'],
|
||||
files: ['vite.config.ts'],
|
||||
env: { node: true, es2022: true },
|
||||
},
|
||||
],
|
||||
rules: {
|
||||
'react/prop-types': 'off',
|
||||
'react/no-unescaped-entities': 'off',
|
||||
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }],
|
||||
'no-unused-vars': 'off',
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }],
|
||||
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,19 @@
|
|||
# NexDocus Frontend
|
||||
|
||||
NexDocus 前端项目 - 基于 React + Vite + Ant Design 构建。
|
||||
NexDocus 前端项目 - 基于 React + TypeScript + Vite + Ant Design 构建。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **框架**: React 18+
|
||||
- **框架**: React 18+(**TypeScript**,`strict` 模式)
|
||||
- **构建工具**: Vite 5+
|
||||
- **UI 组件**: Ant Design 5+
|
||||
- **路由**: React Router v6
|
||||
- **HTTP 客户端**: Axios
|
||||
- **状态管理**: Zustand
|
||||
- **Markdown 编辑器**: @uiw/react-md-editor
|
||||
- **样式**: Tailwind CSS + CSS Modules
|
||||
- **Markdown 编辑器**: ByteMD(`@bytemd/react` + gfm / highlight / frontmatter / breaks / gemoji)
|
||||
- **Markdown 渲染**: react-markdown(+ remark-gfm / rehype-highlight / rehype-raw / rehype-slug)
|
||||
- **样式**: CSS Variables + 手写 CSS(**无 Tailwind、无 CSS Modules**);
|
||||
令牌见 `src/styles/design-tokens.css`,antd 主题映射见 `src/theme/antdTheme.ts`
|
||||
|
||||
## 项目结构
|
||||
|
||||
|
|
@ -20,27 +22,30 @@ frontend/
|
|||
├── public/ # 静态资源
|
||||
├── src/
|
||||
│ ├── api/ # API 请求封装
|
||||
│ │ ├── auth.js # 用户认证
|
||||
│ │ ├── project.js # 项目管理
|
||||
│ │ └── file.js # 文件系统
|
||||
│ │ ├── auth.ts # 用户认证
|
||||
│ │ ├── project.ts # 项目管理
|
||||
│ │ └── file.ts # 文件系统
|
||||
│ ├── components/ # 通用组件
|
||||
│ │ ├── MainLayout/ # 主布局
|
||||
│ │ └── ProtectedRoute.jsx # 路由守卫
|
||||
│ │ └── ProtectedRoute.tsx # 路由守卫
|
||||
│ ├── pages/ # 页面组件
|
||||
│ │ ├── Login/ # 登录页
|
||||
│ │ ├── ProjectList/ # 项目列表页
|
||||
│ │ └── DocumentEditor/ # 文档编辑页
|
||||
│ ├── types/ # 后端接口契约(api.ts)
|
||||
│ ├── stores/ # 状态管理
|
||||
│ │ └── userStore.js # 用户状态
|
||||
│ │ └── userStore.ts # 用户状态
|
||||
│ ├── utils/ # 工具函数
|
||||
│ │ └── request.js # HTTP 请求封装
|
||||
│ ├── App.jsx # 应用入口
|
||||
│ ├── main.jsx # 渲染入口
|
||||
│ │ ├── request.ts # HTTP 请求封装
|
||||
│ │ └── apiError.ts # 接口错误信息统一取值
|
||||
│ ├── App.tsx # 路由与应用入口
|
||||
│ ├── main.tsx # 渲染入口
|
||||
│ └── index.css # 全局样式
|
||||
├── index.html # HTML 模板
|
||||
├── package.json # 项目配置
|
||||
├── vite.config.js # Vite 配置
|
||||
└── tailwind.config.js # Tailwind 配置
|
||||
├── tsconfig.json # TypeScript 配置(strict + noUnusedLocals)
|
||||
├── tsconfig.node.json # vite.config.ts 的类型检查配置
|
||||
└── vite.config.ts # Vite 配置
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
|
@ -49,17 +54,13 @@ frontend/
|
|||
|
||||
```bash
|
||||
npm install
|
||||
# 或
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### 2. 配置环境变量
|
||||
### 2. 后端地址
|
||||
|
||||
编辑 `.env` 文件,配置后端 API 地址:
|
||||
|
||||
```env
|
||||
VITE_API_BASE_URL=http://localhost:8000/api/v1
|
||||
```
|
||||
前端固定请求同源相对路径 `/api/v1`(见 `src/utils/request.ts`),
|
||||
开发环境由 `vite.config.ts` 的 `server.proxy` 转发到 `http://localhost:8000`,
|
||||
生产环境由容器内 nginx 反向代理。**无需配置环境变量。**
|
||||
|
||||
### 3. 启动开发服务器
|
||||
|
||||
|
|
@ -77,19 +78,26 @@ npm run build
|
|||
|
||||
构建产物在 `dist/` 目录。
|
||||
|
||||
### 5. 质量检查
|
||||
|
||||
```bash
|
||||
npm run typecheck # tsc 严格检查(Vite 构建不做类型检查,必须单独跑)
|
||||
npm run lint # ESLint(基线:0 error / 25 warning)
|
||||
npm run lint:strict # 警告也视为失败
|
||||
```
|
||||
|
||||
## 主要功能
|
||||
|
||||
### 用户认证
|
||||
- 用户注册
|
||||
- 用户登录
|
||||
- 自动Token刷新
|
||||
- 退出登录
|
||||
|
||||
### 项目管理
|
||||
- 创建项目
|
||||
- 项目列表
|
||||
- 项目详情
|
||||
- 删除项目(归档)
|
||||
- 项目列表(我创建的 / 我参与的)
|
||||
- 成员与角色管理、所有权转移
|
||||
- 删除项目(要求目录已清空,随后删除物理目录与记录)
|
||||
|
||||
### 文档编辑
|
||||
- 目录树浏览
|
||||
|
|
@ -98,29 +106,31 @@ npm run build
|
|||
- 创建文件/文件夹
|
||||
- 删除文件
|
||||
- 图片上传
|
||||
- PDF 预览(pdfjs-dist / react-pdf)
|
||||
|
||||
## 默认账号
|
||||
|
||||
- 用户名: `admin`
|
||||
- 密码: `admin123`
|
||||
- 密码: `admin@123`(由 `backend/scripts/init_db.py` 首次创建时读取 `ADMIN_PASSWORD`,详见 `docs/quickstart.md`)
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 添加新页面
|
||||
|
||||
1. 在 `src/pages/` 下创建页面组件
|
||||
2. 在 `src/App.jsx` 中添加路由
|
||||
2. 在 `src/App.tsx` 中用 `lazy()` 注册路由
|
||||
3. 如果需要认证,使用 `<ProtectedRoute>` 包裹
|
||||
|
||||
### 添加新 API
|
||||
|
||||
1. 在 `src/api/` 下创建对应的 API 文件
|
||||
2. 使用 `request` 工具发起请求
|
||||
3. 在组件中调用 API
|
||||
2. 先在 `src/types/api.ts` 补后端返回类型(对照后端 Pydantic schema,不要凭猜测写)
|
||||
3. 使用 `request` 工具发起请求,在组件中调用
|
||||
4. 错误提示统一用 `@/utils/apiError` 取后端 `detail`
|
||||
|
||||
### 状态管理
|
||||
|
||||
使用 Zustand 进行状态管理,参考 `src/stores/userStore.js`
|
||||
使用 Zustand 进行状态管理,参考 `src/stores/userStore.ts`
|
||||
|
||||
## 许可证
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,6 @@
|
|||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -38,14 +38,20 @@
|
|||
"zustand": "^4.4.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mark.js": "^8.11.12",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/react": "^18.2.43",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@types/react-highlight-words": "^0.16.7",
|
||||
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
||||
"@typescript-eslint/parser": "^7.18.0",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"eslint": "^8.55.0",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"terser": "^5.46.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^5.0.8"
|
||||
},
|
||||
"engines": {
|
||||
|
|
@ -2206,6 +2212,13 @@
|
|||
"@types/unist": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/jquery": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/@types/jquery/-/jquery-4.0.1.tgz",
|
||||
"integrity": "sha512-9a59A/tycXgYuPABcp6/3spSShn0NT2UOM4EfHvMumjYi4lJWTsK5SZWjhx3yRm9IHGCeWXdV2YfNsrWrft/CA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/js-yaml": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmmirror.com/@types/js-yaml/-/js-yaml-4.0.9.tgz",
|
||||
|
|
@ -2227,6 +2240,16 @@
|
|||
"@types/lodash": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/mark.js": {
|
||||
"version": "8.11.12",
|
||||
"resolved": "https://registry.npmmirror.com/@types/mark.js/-/mark.js-8.11.12.tgz",
|
||||
"integrity": "sha512-244ZnaIBpz4c6xutliAnYVZp6xJlmC569jZqnR3ElO1Y01ooYASSVQEqpd2x0A2UfrgVMs5V9/9tUAdZaDMytQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/jquery": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/mdast": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmmirror.com/@types/mdast/-/mdast-4.0.4.tgz",
|
||||
|
|
@ -2242,6 +2265,16 @@
|
|||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.19.43",
|
||||
"resolved": "https://registry.npmmirror.com/@types/node/-/node-20.19.43.tgz",
|
||||
"integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/parse5": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/@types/parse5/-/parse5-6.0.3.tgz",
|
||||
|
|
@ -2274,6 +2307,16 @@
|
|||
"@types/react": "^18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react-highlight-words": {
|
||||
"version": "0.16.7",
|
||||
"resolved": "https://registry.npmmirror.com/@types/react-highlight-words/-/react-highlight-words-0.16.7.tgz",
|
||||
"integrity": "sha512-+upXTIaRd3rGvh1aDQSs9z5X+sV3UM6Jrmjk03GN2GXl4v/+iOJKQj2LZHo6Vp2IoTvMdtxgME26feqo12xXLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/tern": {
|
||||
"version": "0.23.9",
|
||||
"resolved": "https://registry.npmmirror.com/@types/tern/-/tern-0.23.9.tgz",
|
||||
|
|
@ -2289,6 +2332,238 @@
|
|||
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz",
|
||||
"integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/regexpp": "^4.10.0",
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/type-utils": "7.18.0",
|
||||
"@typescript-eslint/utils": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"graphemer": "^1.4.0",
|
||||
"ignore": "^5.3.1",
|
||||
"natural-compare": "^1.4.0",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@typescript-eslint/parser": "^7.0.0",
|
||||
"eslint": "^8.56.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/parser": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-7.18.0.tgz",
|
||||
"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/typescript-estree": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"debug": "^4.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/scope-manager": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz",
|
||||
"integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/type-utils": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz",
|
||||
"integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/typescript-estree": "7.18.0",
|
||||
"@typescript-eslint/utils": "7.18.0",
|
||||
"debug": "^4.3.4",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/types": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-7.18.0.tgz",
|
||||
"integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz",
|
||||
"integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"debug": "^4.3.4",
|
||||
"globby": "^11.1.0",
|
||||
"is-glob": "^4.0.3",
|
||||
"minimatch": "^9.0.4",
|
||||
"semver": "^7.6.0",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||
"version": "2.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.7.tgz",
|
||||
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
|
||||
"version": "9.0.9",
|
||||
"resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz",
|
||||
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {
|
||||
"version": "7.8.6",
|
||||
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.6.tgz",
|
||||
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/utils": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-7.18.0.tgz",
|
||||
"integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.4.0",
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/typescript-estree": "7.18.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/visitor-keys": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz",
|
||||
"integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"eslint-visitor-keys": "^3.4.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@ungap/structured-clone": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
|
||||
|
|
@ -2508,6 +2783,16 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/array-union": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/array-union/-/array-union-2.1.0.tgz",
|
||||
"integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/array.prototype.findlast": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmmirror.com/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",
|
||||
|
|
@ -2687,6 +2972,19 @@
|
|||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.3.tgz",
|
||||
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fill-range": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/browserslist": {
|
||||
"version": "4.28.1",
|
||||
"resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.28.1.tgz",
|
||||
|
|
@ -4025,6 +4323,19 @@
|
|||
"node": ">=0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/dir-glob": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/dir-glob/-/dir-glob-3.0.1.tgz",
|
||||
"integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-type": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/doctrine": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-2.1.0.tgz",
|
||||
|
|
@ -4579,6 +4890,23 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "^2.0.2",
|
||||
"@nodelib/fs.walk": "^1.2.3",
|
||||
"glob-parent": "^5.1.2",
|
||||
"merge2": "^1.3.0",
|
||||
"micromatch": "^4.0.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
|
|
@ -4629,6 +4957,19 @@
|
|||
"node": "^10.12.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz",
|
||||
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"to-regex-range": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/find-up/-/find-up-5.0.0.tgz",
|
||||
|
|
@ -4901,6 +5242,19 @@
|
|||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/glob-parent": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"is-glob": "^4.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/globals": {
|
||||
"version": "13.24.0",
|
||||
"resolved": "https://registry.npmmirror.com/globals/-/globals-13.24.0.tgz",
|
||||
|
|
@ -4934,6 +5288,27 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/globby": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/globby/-/globby-11.1.0.tgz",
|
||||
"integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"array-union": "^2.1.0",
|
||||
"dir-glob": "^3.0.1",
|
||||
"fast-glob": "^3.2.9",
|
||||
"ignore": "^5.2.0",
|
||||
"merge2": "^1.4.1",
|
||||
"slash": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz",
|
||||
|
|
@ -5729,6 +6104,16 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-number": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz",
|
||||
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-number-object": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/is-number-object/-/is-number-object-1.1.1.tgz",
|
||||
|
|
@ -6650,6 +7035,16 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/merge2": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz",
|
||||
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/micromark/-/micromark-4.0.3.tgz",
|
||||
|
|
@ -7234,6 +7629,20 @@
|
|||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz",
|
||||
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"braces": "^3.0.3",
|
||||
"picomatch": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz",
|
||||
|
|
@ -7595,6 +8004,16 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/path-type": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/path-type/-/path-type-4.0.0.tgz",
|
||||
"integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/pdfjs-dist": {
|
||||
"version": "5.4.296",
|
||||
"resolved": "https://registry.npmmirror.com/pdfjs-dist/-/pdfjs-dist-5.4.296.tgz",
|
||||
|
|
@ -7614,6 +8033,19 @@
|
|||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.2.tgz",
|
||||
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
|
|
@ -9653,6 +10085,16 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/slash": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmmirror.com/slash/-/slash-3.0.0.tgz",
|
||||
"integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz",
|
||||
|
|
@ -9959,6 +10401,19 @@
|
|||
"@popperjs/core": "^2.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/to-regex-range": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-number": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/toggle-selection": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmmirror.com/toggle-selection/-/toggle-selection-1.0.6.tgz",
|
||||
|
|
@ -9985,6 +10440,19 @@
|
|||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmmirror.com/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
|
||||
"integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz",
|
||||
|
|
@ -10095,6 +10563,20 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/unbox-primitive": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
|
||||
|
|
@ -10114,6 +10596,13 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unified": {
|
||||
"version": "11.0.5",
|
||||
"resolved": "https://registry.npmmirror.com/unified/-/unified-11.0.5.tgz",
|
||||
|
|
|
|||
|
|
@ -7,8 +7,9 @@
|
|||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext js,jsx",
|
||||
"lint:strict": "eslint . --ext js,jsx --max-warnings 0"
|
||||
"lint": "eslint . --ext ts,tsx",
|
||||
"lint:strict": "eslint . --ext ts,tsx --max-warnings 0",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.node.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.2.6",
|
||||
|
|
@ -41,14 +42,20 @@
|
|||
"zustand": "^4.4.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mark.js": "^8.11.12",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/react": "^18.2.43",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@types/react-highlight-words": "^0.16.7",
|
||||
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
||||
"@typescript-eslint/parser": "^7.18.0",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"eslint": "^8.55.0",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"terser": "^5.46.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^5.0.8"
|
||||
},
|
||||
"engines": {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { lazy, Suspense, useEffect } from 'react'
|
||||
import { BrowserRouter, Routes, Route, Navigate, useParams, Outlet } from 'react-router-dom'
|
||||
import { App as AntdApp, ConfigProvider, theme } from 'antd'
|
||||
import { EllipsisOutlined } from '@ant-design/icons'
|
||||
import zhCN from 'antd/locale/zh_CN'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/zh-cn'
|
||||
|
|
@ -58,6 +59,7 @@ function App() {
|
|||
return (
|
||||
<ConfigProvider
|
||||
locale={zhCN}
|
||||
tabs={{ moreIcon: <EllipsisOutlined aria-label="更多标签页" /> }}
|
||||
theme={{
|
||||
algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
|
||||
...getAntdTheme(isDarkMode),
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
/**
|
||||
* 用户认证相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*/
|
||||
export function register(data) {
|
||||
return request({
|
||||
url: '/auth/register',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
*/
|
||||
export function login(data) {
|
||||
return request({
|
||||
url: '/auth/login',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
export function getCurrentUser() {
|
||||
return request({
|
||||
url: '/auth/me',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户资料
|
||||
*/
|
||||
export function updateProfile(data) {
|
||||
return request({
|
||||
url: '/auth/profile',
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改密码
|
||||
*/
|
||||
export function changePassword(data) {
|
||||
return request({
|
||||
url: '/auth/change-password',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户的 MCP 凭证
|
||||
*/
|
||||
export function getMcpCredentials() {
|
||||
return request({
|
||||
url: '/auth/mcp-credentials',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新生成当前用户的 MCP Secret
|
||||
*/
|
||||
export function rotateMcpSecret() {
|
||||
return request({
|
||||
url: '/auth/mcp-credentials/rotate-secret',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传用户头像
|
||||
*/
|
||||
export function uploadAvatar(file) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
return request({
|
||||
url: '/auth/upload-avatar',
|
||||
method: 'post',
|
||||
data: formData,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
/**
|
||||
* 用户认证相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { LoginResult, McpCredential, User } from '@/types/api'
|
||||
|
||||
export interface RegisterPayload {
|
||||
username: string
|
||||
password: string
|
||||
nickname?: string
|
||||
email?: string
|
||||
}
|
||||
|
||||
export interface LoginPayload {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface ProfileUpdatePayload {
|
||||
nickname?: string | null
|
||||
email?: string | null
|
||||
phone?: string | null
|
||||
avatar?: string | null
|
||||
}
|
||||
|
||||
/** 资料表单的取值形状:后端字段可为 null,表单初值直接来自用户对象 */
|
||||
export interface ProfileFormValues {
|
||||
username?: string
|
||||
nickname?: string | null
|
||||
email?: string | null
|
||||
phone?: string | null
|
||||
}
|
||||
|
||||
export interface ChangePasswordPayload {
|
||||
old_password: string
|
||||
new_password: string
|
||||
}
|
||||
|
||||
export function register(data: RegisterPayload) {
|
||||
return request<User>({
|
||||
url: '/auth/register',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function login(data: LoginPayload) {
|
||||
return request<LoginResult>({
|
||||
url: '/auth/login',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getCurrentUser() {
|
||||
return request<User>({
|
||||
url: '/auth/me',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function updateProfile(data: ProfileUpdatePayload) {
|
||||
return request<User>({
|
||||
url: '/auth/profile',
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function changePassword(data: ChangePasswordPayload) {
|
||||
return request<null>({
|
||||
url: '/auth/change-password',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getMcpCredentials() {
|
||||
return request<McpCredential>({
|
||||
url: '/auth/mcp-credentials',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function rotateMcpSecret() {
|
||||
return request<McpCredential>({
|
||||
url: '/auth/mcp-credentials/rotate-secret',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
export function uploadAvatar(file: File) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
return request<User>({
|
||||
url: '/auth/upload-avatar',
|
||||
method: 'post',
|
||||
data: formData,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
import request from '@/utils/request'
|
||||
import { getAccessToken } from '@/utils/authStorage'
|
||||
|
||||
export const createChatSession = (projectId, llmConfigId, title = '新对话') => {
|
||||
return request.post('/chat/sessions', {
|
||||
project_id: projectId,
|
||||
llm_config_id: llmConfigId,
|
||||
title,
|
||||
})
|
||||
}
|
||||
|
||||
export const getChatSessions = (projectId = null) => {
|
||||
return request.get('/chat/sessions', {
|
||||
params: projectId ? { project_id: projectId } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
export const getChatMessages = (sessionId) => {
|
||||
return request.get(`/chat/sessions/${sessionId}/messages`)
|
||||
}
|
||||
|
||||
export const sendChatMessage = (sessionId, message) => {
|
||||
return request.post('/chat/send', {
|
||||
session_id: sessionId,
|
||||
message,
|
||||
}, {
|
||||
timeout: 180000,
|
||||
})
|
||||
}
|
||||
|
||||
export const sendChatMessageStream = async (sessionId, message, handlers = {}) => {
|
||||
const token = getAccessToken()
|
||||
const response = await fetch('/api/v1/chat/send/stream', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
message,
|
||||
...(handlers.insertUserMessage === false ? { insert_user_message: false } : {}),
|
||||
}),
|
||||
signal: handlers.signal,
|
||||
})
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
let detail = '发送消息失败'
|
||||
try {
|
||||
const payload = await response.json()
|
||||
detail = payload?.detail || payload?.message || detail
|
||||
} catch {
|
||||
// 响应不是 JSON 时保留通用错误信息
|
||||
}
|
||||
throw new Error(detail)
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder('utf-8')
|
||||
let buffer = ''
|
||||
let completed = false
|
||||
|
||||
const dispatchEvent = (block) => {
|
||||
const lines = block.split('\n')
|
||||
const eventLine = lines.find((line) => line.startsWith('event:'))
|
||||
const dataLine = lines.find((line) => line.startsWith('data:'))
|
||||
if (!eventLine || !dataLine) return
|
||||
const event = eventLine.slice(6).trim()
|
||||
const dataText = dataLine.slice(5).trim()
|
||||
const data = dataText ? JSON.parse(dataText) : null
|
||||
|
||||
if (event === 'ids') handlers.onIds?.(data)
|
||||
if (event === 'references') handlers.onReferences?.(data || [])
|
||||
if (event === 'thinking') handlers.onThinking?.(data)
|
||||
if (event === 'chunk') handlers.onChunk?.(data?.content || '')
|
||||
if (event === 'title') handlers.onTitle?.(data)
|
||||
if (event === 'done') {
|
||||
completed = true
|
||||
handlers.onDone?.(data)
|
||||
}
|
||||
if (event === 'error') {
|
||||
throw new Error(data?.detail || '发送消息失败')
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const blocks = buffer.split('\n\n')
|
||||
buffer = blocks.pop() || ''
|
||||
for (const block of blocks) {
|
||||
dispatchEvent(block)
|
||||
}
|
||||
}
|
||||
if (buffer.trim()) {
|
||||
dispatchEvent(buffer)
|
||||
}
|
||||
if (!completed) {
|
||||
throw new Error('回答生成连接意外中断,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteChatSession = (sessionId) => {
|
||||
return request.delete(`/chat/sessions/${sessionId}`)
|
||||
}
|
||||
|
||||
export const deleteChatMessage = (messageId) => {
|
||||
return request.delete(`/chat/messages/${messageId}`)
|
||||
}
|
||||
|
||||
export const markMessageInterrupted = (messageId) => {
|
||||
return request.post(`/chat/messages/${messageId}/interrupt`)
|
||||
}
|
||||
|
||||
export const updateChatSessionTitle = (sessionId, title) => {
|
||||
return request.put(`/chat/sessions/${sessionId}`, {
|
||||
title,
|
||||
})
|
||||
}
|
||||
|
||||
export const searchChatMessages = (keyword) => {
|
||||
return request.get('/chat/search', {
|
||||
params: { keyword },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
import request from '@/utils/request'
|
||||
import { getAccessToken } from '@/utils/authStorage'
|
||||
import type {
|
||||
ChatMessage,
|
||||
ChatReference,
|
||||
ChatSearchResult,
|
||||
ChatSession,
|
||||
StreamDoneEvent,
|
||||
StreamIdsEvent,
|
||||
StreamThinkingEvent,
|
||||
} from '@/types/api'
|
||||
|
||||
export const createChatSession = (projectId: number, llmConfigId: number, title = '新对话') => {
|
||||
return request.post<ChatSession>('/chat/sessions', {
|
||||
project_id: projectId,
|
||||
llm_config_id: llmConfigId,
|
||||
title,
|
||||
})
|
||||
}
|
||||
|
||||
export const getChatSessions = (projectId: number | null = null) => {
|
||||
return request.get<ChatSession[]>('/chat/sessions', {
|
||||
params: projectId ? { project_id: projectId } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
export const getChatMessages = (sessionId: number) => {
|
||||
return request.get<ChatMessage[]>(`/chat/sessions/${sessionId}/messages`)
|
||||
}
|
||||
|
||||
export const sendChatMessage = (sessionId: number, message: string) => {
|
||||
return request.post('/chat/send', {
|
||||
session_id: sessionId,
|
||||
message,
|
||||
}, {
|
||||
timeout: 180000,
|
||||
})
|
||||
}
|
||||
|
||||
export interface ChatStreamHandlers {
|
||||
/** 传 false 时不落用户消息(用于重新生成) */
|
||||
insertUserMessage?: boolean
|
||||
signal?: AbortSignal
|
||||
onIds?: (data?: StreamIdsEvent | null) => void
|
||||
onReferences?: (data: ChatReference[]) => void
|
||||
onThinking?: (data?: StreamThinkingEvent | null) => void
|
||||
onChunk?: (content: string) => void
|
||||
onTitle?: (data?: { session_id?: number; title?: string } | null) => void
|
||||
onDone?: (data?: StreamDoneEvent | null) => void
|
||||
}
|
||||
|
||||
export const sendChatMessageStream = async (
|
||||
sessionId: number,
|
||||
message: string,
|
||||
handlers: ChatStreamHandlers = {},
|
||||
) => {
|
||||
const token = getAccessToken()
|
||||
const response = await fetch('/api/v1/chat/send/stream', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
message,
|
||||
...(handlers.insertUserMessage === false ? { insert_user_message: false } : {}),
|
||||
}),
|
||||
signal: handlers.signal,
|
||||
})
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
let detail = '发送消息失败'
|
||||
try {
|
||||
const payload = (await response.json()) as { detail?: string; message?: string }
|
||||
detail = payload?.detail || payload?.message || detail
|
||||
} catch {
|
||||
// 响应不是 JSON 时保留通用错误信息
|
||||
}
|
||||
throw new Error(detail)
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder('utf-8')
|
||||
let buffer = ''
|
||||
let completed = false
|
||||
|
||||
const dispatchEvent = (block: string) => {
|
||||
const lines = block.split('\n')
|
||||
const eventLine = lines.find((line) => line.startsWith('event:'))
|
||||
const dataLine = lines.find((line) => line.startsWith('data:'))
|
||||
if (!eventLine || !dataLine) return
|
||||
const event = eventLine.slice(6).trim()
|
||||
const dataText = dataLine.slice(5).trim()
|
||||
const data: unknown = dataText ? JSON.parse(dataText) : null
|
||||
|
||||
if (event === 'ids') handlers.onIds?.(data as StreamIdsEvent | null)
|
||||
if (event === 'references') handlers.onReferences?.((data as ChatReference[] | null) || [])
|
||||
if (event === 'thinking') handlers.onThinking?.(data as StreamThinkingEvent | null)
|
||||
if (event === 'chunk') handlers.onChunk?.((data as { content?: string } | null)?.content || '')
|
||||
if (event === 'title') handlers.onTitle?.(data as { session_id?: number; title?: string } | null)
|
||||
if (event === 'done') {
|
||||
completed = true
|
||||
handlers.onDone?.(data as StreamDoneEvent | null)
|
||||
}
|
||||
if (event === 'error') {
|
||||
throw new Error((data as { detail?: string } | null)?.detail || '发送消息失败')
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const blocks = buffer.split('\n\n')
|
||||
buffer = blocks.pop() || ''
|
||||
for (const block of blocks) {
|
||||
dispatchEvent(block)
|
||||
}
|
||||
}
|
||||
if (buffer.trim()) {
|
||||
dispatchEvent(buffer)
|
||||
}
|
||||
if (!completed) {
|
||||
throw new Error('回答生成连接意外中断,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteChatSession = (sessionId: number) => {
|
||||
return request.delete(`/chat/sessions/${sessionId}`)
|
||||
}
|
||||
|
||||
export const deleteChatMessage = (messageId: number) => {
|
||||
return request.delete(`/chat/messages/${messageId}`)
|
||||
}
|
||||
|
||||
export const markMessageInterrupted = (messageId: number) => {
|
||||
return request.post(`/chat/messages/${messageId}/interrupt`)
|
||||
}
|
||||
|
||||
export const updateChatSessionTitle = (sessionId: number, title: string) => {
|
||||
return request.put<{ session_id: number; title: string }>(`/chat/sessions/${sessionId}`, {
|
||||
title,
|
||||
})
|
||||
}
|
||||
|
||||
export const searchChatMessages = (keyword: string) => {
|
||||
return request.get<ChatSearchResult[]>('/chat/search', {
|
||||
params: { keyword },
|
||||
})
|
||||
}
|
||||
|
|
@ -2,43 +2,37 @@
|
|||
* 管理员仪表盘相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type {
|
||||
ActivityDate,
|
||||
ActivityLog,
|
||||
DashboardStats,
|
||||
PersonalStats,
|
||||
} from '@/types/api'
|
||||
|
||||
/**
|
||||
* 获取管理员仪表盘统计数据
|
||||
*/
|
||||
export function getDashboardStats() {
|
||||
return request({
|
||||
return request<DashboardStats>({
|
||||
url: '/dashboard/stats',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取个人桌面统计数据
|
||||
*/
|
||||
export function getPersonalStats() {
|
||||
return request({
|
||||
return request<PersonalStats>({
|
||||
url: '/dashboard/personal-stats',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定月份有文档操作的日期列表
|
||||
*/
|
||||
export function getDocumentActivityDates(year, month) {
|
||||
return request({
|
||||
export function getDocumentActivityDates(year: number, month: number) {
|
||||
return request<{ dates: ActivityDate[] }>({
|
||||
url: '/dashboard/document-activity-dates',
|
||||
method: 'get',
|
||||
params: { year, month },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定日期的文档操作日志
|
||||
*/
|
||||
export function getDocumentActivity(date) {
|
||||
return request({
|
||||
export function getDocumentActivity(date: string) {
|
||||
return request<{ logs: ActivityLog[] }>({
|
||||
url: '/dashboard/document-activity',
|
||||
method: 'get',
|
||||
params: { date_str: date },
|
||||
|
|
@ -2,61 +2,58 @@
|
|||
* 文件系统相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type {
|
||||
FileContent,
|
||||
FileOperatePayload,
|
||||
FileUploadResult,
|
||||
ImportDocumentsResult,
|
||||
ProjectTreeResponse,
|
||||
} from '@/types/api'
|
||||
|
||||
/**
|
||||
* 获取项目目录树
|
||||
*/
|
||||
export function getProjectTree(projectId) {
|
||||
return request({
|
||||
/** 获取项目目录树 */
|
||||
export function getProjectTree(projectId: number) {
|
||||
return request<ProjectTreeResponse>({
|
||||
url: `/files/${projectId}/tree`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件内容
|
||||
*/
|
||||
export function getFileContent(projectId, path) {
|
||||
/** 获取文件内容 */
|
||||
export function getFileContent(projectId: number, path: string) {
|
||||
// 直接在 URL 中拼接参数,避免 axios 自动编码
|
||||
// 手动编码一次,确保不会双重编码
|
||||
const encodedPath = encodeURIComponent(path)
|
||||
|
||||
return request({
|
||||
return request<FileContent>({
|
||||
url: `/files/${projectId}/file?path=${encodedPath}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存文件内容
|
||||
*/
|
||||
export function saveFile(projectId, data) {
|
||||
return request({
|
||||
/** 保存文件内容 */
|
||||
export function saveFile(projectId: number, data: { path: string; content: string }) {
|
||||
return request<null>({
|
||||
url: `/files/${projectId}/file`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件操作(重命名/删除/创建)
|
||||
*/
|
||||
export function operateFile(projectId, data) {
|
||||
return request({
|
||||
/** 文件操作(重命名/删除/创建) */
|
||||
export function operateFile(projectId: number, data: FileOperatePayload) {
|
||||
return request<null>({
|
||||
url: `/files/${projectId}/file/operate`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*/
|
||||
export function uploadFile(projectId, file, subfolder = 'images') {
|
||||
/** 上传文件 */
|
||||
export function uploadFile(projectId: number, file: File, subfolder = 'images') {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return request({
|
||||
return request<FileUploadResult>({
|
||||
url: `/files/${projectId}/upload?subfolder=${subfolder}`,
|
||||
method: 'post',
|
||||
data: formData,
|
||||
|
|
@ -66,23 +63,19 @@ export function uploadFile(projectId, file, subfolder = 'images') {
|
|||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取资源文件 URL(公开访问,支持分享)
|
||||
*/
|
||||
export function getAssetUrl(projectId, subfolder, filename) {
|
||||
/** 获取资源文件 URL(公开访问,支持分享) */
|
||||
export function getAssetUrl(projectId: number, subfolder: string, filename: string) {
|
||||
return `/api/v1/files/${projectId}/assets/${subfolder}/${filename}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量导入Markdown文档
|
||||
*/
|
||||
export function importDocuments(projectId, files, targetPath = '') {
|
||||
/** 批量导入Markdown文档 */
|
||||
export function importDocuments(projectId: number, files: File[], targetPath = '') {
|
||||
const formData = new FormData()
|
||||
files.forEach((file) => {
|
||||
formData.append('files', file)
|
||||
})
|
||||
|
||||
return request({
|
||||
return request<ImportDocumentsResult>({
|
||||
url: `/files/${projectId}/import-documents?target_path=${targetPath}`,
|
||||
method: 'post',
|
||||
data: formData,
|
||||
|
|
@ -92,26 +85,21 @@ export function importDocuments(projectId, files, targetPath = '') {
|
|||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出目录为ZIP
|
||||
*/
|
||||
export function exportDirectory(projectId, directoryPath = '') {
|
||||
return request({
|
||||
/** 导出目录为ZIP */
|
||||
export function exportDirectory(projectId: number, directoryPath = '') {
|
||||
return request.blob({
|
||||
url: `/files/${projectId}/export-directory`,
|
||||
method: 'get',
|
||||
params: { directory_path: directoryPath },
|
||||
responseType: 'blob',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文档文件(PDF等)
|
||||
*/
|
||||
export function uploadDocument(projectId, file, targetDir = '') {
|
||||
/** 上传文档文件(PDF等) */
|
||||
export function uploadDocument(projectId: number, file: File, targetDir = '') {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return request({
|
||||
return request<FileUploadResult>({
|
||||
url: `/files/${projectId}/upload-document?target_dir=${encodeURIComponent(targetDir)}`,
|
||||
method: 'post',
|
||||
data: formData,
|
||||
|
|
@ -121,19 +109,15 @@ export function uploadDocument(projectId, file, targetDir = '') {
|
|||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文档文件URL(PDF等)
|
||||
*/
|
||||
export function getDocumentUrl(projectId, path) {
|
||||
/** 获取文档文件URL(PDF等) */
|
||||
export function getDocumentUrl(projectId: number, path: string) {
|
||||
// 将路径的每个部分分别编码,但保留斜杠
|
||||
const encodedPath = path.split('/').map(part => encodeURIComponent(part)).join('/')
|
||||
const encodedPath = path.split('/').map((part) => encodeURIComponent(part)).join('/')
|
||||
return `/api/v1/files/${projectId}/document/${encodedPath}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出 Markdown 为 PDF(已登录用户)
|
||||
*/
|
||||
export function getExportPdfUrl(projectId, path) {
|
||||
/** 导出 Markdown 为 PDF(已登录用户) */
|
||||
export function getExportPdfUrl(projectId: number, path: string) {
|
||||
const encodedPath = encodeURIComponent(path)
|
||||
return `/api/v1/files/${projectId}/export-pdf?path=${encodedPath}`
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import request from '@/utils/request'
|
||||
|
||||
// 查询项目向量化进度
|
||||
export const getVectorizeProgress = (projectId) => {
|
||||
return request.get(`/chat/projects/${projectId}/vectorize/progress`)
|
||||
}
|
||||
|
||||
// 触发项目批量向量化(force=false 增量;force=true 全量重建)
|
||||
export const vectorizeProject = (projectId, force = false) => {
|
||||
return request.post(`/chat/projects/${projectId}/vectorize`, { force })
|
||||
}
|
||||
|
||||
// 查询最近一次向量化任务
|
||||
export const getLatestVectorizeTask = (projectId) => {
|
||||
return request.get(`/chat/projects/${projectId}/vectorize/tasks/latest`)
|
||||
}
|
||||
|
||||
// 查询指定向量化任务
|
||||
export const getVectorizeTask = (projectId, taskId) => {
|
||||
return request.get(`/chat/projects/${projectId}/vectorize/tasks/${taskId}`)
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import request from '@/utils/request'
|
||||
import type { VectorizeProgress, VectorizeTask } from '@/types/api'
|
||||
|
||||
// 查询项目向量化进度
|
||||
export const getVectorizeProgress = (projectId: number) => {
|
||||
return request.get<VectorizeProgress>(`/chat/projects/${projectId}/vectorize/progress`)
|
||||
}
|
||||
|
||||
// 触发项目批量向量化(force=false 增量;force=true 全量重建)
|
||||
export const vectorizeProject = (projectId: number, force = false) => {
|
||||
return request.post<VectorizeTask>(`/chat/projects/${projectId}/vectorize`, { force })
|
||||
}
|
||||
|
||||
// 查询最近一次向量化任务
|
||||
export const getLatestVectorizeTask = (projectId: number) => {
|
||||
return request.get<VectorizeTask | null>(`/chat/projects/${projectId}/vectorize/tasks/latest`)
|
||||
}
|
||||
|
||||
// 查询指定向量化任务
|
||||
export const getVectorizeTask = (projectId: number, taskId: string) => {
|
||||
return request.get<VectorizeTask>(`/chat/projects/${projectId}/vectorize/tasks/${taskId}`)
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
import request from '@/utils/request'
|
||||
|
||||
export function getLLMProviderCatalog() {
|
||||
return request({
|
||||
url: '/llm-model-configs/providers',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function getLLMModelConfigs(params) {
|
||||
return request({
|
||||
url: '/llm-model-configs/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
export function getLLMModelConfigDetail(configId) {
|
||||
return request({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function createLLMModelConfig(data) {
|
||||
return request({
|
||||
url: '/llm-model-configs/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function updateLLMModelConfig(configId, data) {
|
||||
return request({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function updateLLMModelConfigStatus(configId, isActive) {
|
||||
return request({
|
||||
url: `/llm-model-configs/${configId}/status`,
|
||||
method: 'put',
|
||||
params: { is_active: isActive },
|
||||
})
|
||||
}
|
||||
|
||||
export function setDefaultLLMModelConfig(configId) {
|
||||
return request({
|
||||
url: `/llm-model-configs/${configId}/default`,
|
||||
method: 'put',
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteLLMModelConfig(configId) {
|
||||
return request({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
export function testLLMModelConfig(data) {
|
||||
const timeoutSeconds = Number(data?.llm_timeout) || 30
|
||||
return request({
|
||||
url: '/llm-model-configs/test',
|
||||
method: 'post',
|
||||
data,
|
||||
timeout: Math.max(timeoutSeconds * 1000 + 5000, 30000),
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import request from '@/utils/request'
|
||||
import type { LLMModelConfig, LLMProvider, LLMTestResult, ModelType } from '@/types/api'
|
||||
|
||||
export interface LLMModelConfigQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
keyword?: string
|
||||
provider?: string
|
||||
model_type?: ModelType
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface LLMModelConfigPayload {
|
||||
model_name?: string
|
||||
model_code?: string
|
||||
model_type: ModelType
|
||||
provider: string
|
||||
endpoint_url?: string
|
||||
llm_model_name: string
|
||||
api_key?: string
|
||||
llm_timeout?: number
|
||||
llm_temperature?: number
|
||||
llm_top_p?: number
|
||||
llm_max_tokens?: number | null
|
||||
llm_system_prompt?: string | null
|
||||
embedding_dimension?: number | null
|
||||
chunk_size?: number | null
|
||||
chunk_overlap?: number | null
|
||||
description?: string | null
|
||||
is_active: boolean
|
||||
is_default: boolean
|
||||
}
|
||||
|
||||
export function getLLMProviderCatalog() {
|
||||
return request<LLMProvider[]>({
|
||||
url: '/llm-model-configs/providers',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function getLLMModelConfigs(params: LLMModelConfigQuery) {
|
||||
return request.list<LLMModelConfig>({
|
||||
url: '/llm-model-configs/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
export function getLLMModelConfigDetail(configId: number) {
|
||||
return request<LLMModelConfig>({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function createLLMModelConfig(data: LLMModelConfigPayload) {
|
||||
return request<LLMModelConfig>({
|
||||
url: '/llm-model-configs/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function updateLLMModelConfig(configId: number, data: Partial<LLMModelConfigPayload>) {
|
||||
return request<LLMModelConfig>({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function updateLLMModelConfigStatus(configId: number, isActive: boolean) {
|
||||
return request<null>({
|
||||
url: `/llm-model-configs/${configId}/status`,
|
||||
method: 'put',
|
||||
params: { is_active: isActive },
|
||||
})
|
||||
}
|
||||
|
||||
export function setDefaultLLMModelConfig(configId: number) {
|
||||
return request<null>({
|
||||
url: `/llm-model-configs/${configId}/default`,
|
||||
method: 'put',
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteLLMModelConfig(configId: number) {
|
||||
return request<null>({
|
||||
url: `/llm-model-configs/${configId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
export function testLLMModelConfig(data: Partial<LLMModelConfigPayload> & { llm_timeout?: number | string }) {
|
||||
const timeoutSeconds = Number(data?.llm_timeout) || 30
|
||||
return request<LLMTestResult>({
|
||||
url: '/llm-model-configs/test',
|
||||
method: 'post',
|
||||
data,
|
||||
timeout: Math.max(timeoutSeconds * 1000 + 5000, 30000),
|
||||
})
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 获取操作日志列表
|
||||
*/
|
||||
export const getOperationLogs = (params) => {
|
||||
return request({
|
||||
url: '/logs/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志统计信息
|
||||
*/
|
||||
export const getLogStats = () => {
|
||||
return request({
|
||||
url: '/logs/stats',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import request from '@/utils/request'
|
||||
import type { LogStats, OperationLog, PagedData } from '@/types/api'
|
||||
|
||||
export interface LogQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
operation_type?: string
|
||||
resource_type?: string
|
||||
user_id?: number
|
||||
/** 页面上由输入框录入,作为查询串下发给后端转成 int */
|
||||
project_id?: number | string
|
||||
start_date?: string
|
||||
end_date?: string
|
||||
}
|
||||
|
||||
/** 获取操作日志列表 */
|
||||
export const getOperationLogs = (params: LogQuery) => {
|
||||
return request<PagedData<OperationLog[]>>({
|
||||
url: '/logs/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取日志统计信息 */
|
||||
export const getLogStats = () => {
|
||||
return request<LogStats>({
|
||||
url: '/logs/stats',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
|
@ -2,22 +2,17 @@
|
|||
* 权限菜单相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { MenuNode } from '@/types/api'
|
||||
|
||||
/**
|
||||
* 获取当前用户的权限菜单
|
||||
*/
|
||||
export function getUserMenus() {
|
||||
return request({
|
||||
return request<MenuNode[]>({
|
||||
url: '/menu/user-menus',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户的权限列表
|
||||
*/
|
||||
export function getUserPermissions() {
|
||||
return request({
|
||||
return request<string[]>({
|
||||
url: '/menu/user-permissions',
|
||||
method: 'get',
|
||||
})
|
||||
|
|
@ -2,63 +2,52 @@
|
|||
* 通知管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { NotificationItem, UnreadByProjectResult } from '@/types/api'
|
||||
|
||||
/**
|
||||
* 获取通知列表
|
||||
*/
|
||||
export function getNotifications(params) {
|
||||
return request({
|
||||
export interface NotificationQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
unread_only?: boolean
|
||||
}
|
||||
|
||||
export function getNotifications(params: NotificationQuery) {
|
||||
return request.list<NotificationItem>({
|
||||
url: '/notifications/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取未读通知数量
|
||||
*/
|
||||
export function getUnreadCount() {
|
||||
return request({
|
||||
return request<{ unread_count: number }>({
|
||||
url: '/notifications/unread-count',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记通知为已读
|
||||
*/
|
||||
export function markAsRead(notificationId) {
|
||||
return request({
|
||||
export function markAsRead(notificationId: string | number) {
|
||||
return request<null>({
|
||||
url: `/notifications/${notificationId}/read`,
|
||||
method: 'put',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 全部标记为已读
|
||||
*/
|
||||
export function markAllAsRead() {
|
||||
return request({
|
||||
return request<null>({
|
||||
url: '/notifications/read-all',
|
||||
method: 'put',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 按项目统计未读通知数量(与消息通知一致)
|
||||
*/
|
||||
export function getUnreadByProject() {
|
||||
return request({
|
||||
return request<UnreadByProjectResult>({
|
||||
url: '/notifications/unread-by-project',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 将指定项目的所有未读通知标记为已读(打开项目时调用)
|
||||
*/
|
||||
export function markProjectNotificationsRead(projectId) {
|
||||
return request({
|
||||
export function markProjectNotificationsRead(projectId: number) {
|
||||
return request<null>({
|
||||
url: `/notifications/read-project/${projectId}`,
|
||||
method: 'put',
|
||||
})
|
||||
|
|
@ -1,254 +0,0 @@
|
|||
/**
|
||||
* 项目管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 获取我的项目列表
|
||||
*/
|
||||
export function getMyProjects() {
|
||||
return request({
|
||||
url: '/projects/',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取我创建的项目列表
|
||||
*/
|
||||
export function getOwnedProjects() {
|
||||
return request({
|
||||
url: '/projects/my',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取我参与的项目列表
|
||||
*/
|
||||
export function getSharedProjects() {
|
||||
return request({
|
||||
url: '/projects/shared',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建项目
|
||||
*/
|
||||
export function createProject(data) {
|
||||
return request({
|
||||
url: '/projects/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目详情
|
||||
*/
|
||||
export function getProject(projectId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新项目信息
|
||||
*/
|
||||
export function updateProject(projectId, data) {
|
||||
return request({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除项目
|
||||
*/
|
||||
export function deleteProject(projectId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 转移项目所有权
|
||||
*/
|
||||
export function transferProject(projectId, newOwnerId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/transfer`,
|
||||
method: 'post',
|
||||
data: { new_owner_id: newOwnerId },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动项目导出任务
|
||||
*/
|
||||
export function startProjectExport(projectId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/export`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目导出任务状态
|
||||
*/
|
||||
export function getProjectExportStatus(projectId, taskId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/export/${taskId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载项目导出 ZIP
|
||||
*/
|
||||
export function downloadProjectExport(projectId, taskId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/export/${taskId}/download`,
|
||||
method: 'get',
|
||||
responseType: 'blob',
|
||||
timeout: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目成员
|
||||
*/
|
||||
export function getProjectMembers(projectId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/members`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加项目成员
|
||||
*/
|
||||
export function addProjectMember(projectId, data) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/members`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除项目成员
|
||||
*/
|
||||
export function removeProjectMember(projectId, userId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/members/${userId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改项目成员角色
|
||||
*/
|
||||
export function updateProjectMemberRole(projectId, userId, role) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/members/${userId}`,
|
||||
method: 'put',
|
||||
data: { role },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Git Pull
|
||||
*/
|
||||
export function gitPull(projectId, repoId = null, force = false, syncScope = null, subPath = '') {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git/pull`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId, force, sync_scope: syncScope || undefined, sub_path: subPath || undefined },
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Git Push
|
||||
*/
|
||||
export function gitPush(projectId, repoId = null, force = false, syncScope = null, subPath = '') {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git/push`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId, force, sync_scope: syncScope || undefined, sub_path: subPath || undefined },
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Git仓库列表
|
||||
*/
|
||||
export function getGitRepos(projectId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git-repos`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加Git仓库
|
||||
*/
|
||||
export function createGitRepo(projectId, data) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git-repos`,
|
||||
method: 'post',
|
||||
data,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新Git仓库
|
||||
*/
|
||||
export function updateGitRepo(projectId, repoId, data) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git-repos/${repoId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除Git仓库
|
||||
*/
|
||||
export function deleteGitRepo(projectId, repoId) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git-repos/${repoId}`,
|
||||
method: 'delete',
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试Git远端仓库认证
|
||||
*/
|
||||
export function testGitRepoConnection(projectId, data) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git-repos/test-connection`,
|
||||
method: 'post',
|
||||
data,
|
||||
timeout: 35000,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Git仓库远端目录结构(用于选择同步目录)
|
||||
*/
|
||||
export function getGitRepoDirectories(projectId, repoId = null) {
|
||||
return request({
|
||||
url: `/projects/${projectId}/git/directories`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId || undefined },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
/**
|
||||
* 项目管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type {
|
||||
ExportTask,
|
||||
GitDirectoriesResult,
|
||||
GitRepo,
|
||||
GitSyncResult,
|
||||
Project,
|
||||
ProjectListItem,
|
||||
ProjectMember,
|
||||
ProjectRole,
|
||||
} from '@/types/api'
|
||||
|
||||
export interface ProjectCreatePayload {
|
||||
name: string
|
||||
description?: string
|
||||
is_public?: 0 | 1
|
||||
}
|
||||
|
||||
export interface ProjectUpdatePayload {
|
||||
name?: string
|
||||
description?: string
|
||||
is_public?: 0 | 1
|
||||
public_access_pass?: string | null
|
||||
cover_image?: string | null
|
||||
status?: number
|
||||
}
|
||||
|
||||
export interface GitRepoPayload {
|
||||
name: string
|
||||
repo_url: string
|
||||
branch?: string
|
||||
username?: string | null
|
||||
token?: string | null
|
||||
is_default?: 0 | 1
|
||||
}
|
||||
|
||||
export type GitRepoUpdatePayload = Partial<GitRepoPayload>
|
||||
|
||||
export interface GitRepoTestPayload {
|
||||
repo_id?: number | null
|
||||
repo_url?: string
|
||||
branch?: string
|
||||
username?: string | null
|
||||
token?: string | null
|
||||
}
|
||||
|
||||
/** 获取我的项目列表 */
|
||||
export function getMyProjects() {
|
||||
return request<ProjectListItem[]>({
|
||||
url: '/projects/',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取我创建的项目列表 */
|
||||
export function getOwnedProjects() {
|
||||
return request<ProjectListItem[]>({
|
||||
url: '/projects/my',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取我参与的项目列表 */
|
||||
export function getSharedProjects() {
|
||||
return request<ProjectListItem[]>({
|
||||
url: '/projects/shared',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 创建项目 */
|
||||
export function createProject(data: ProjectCreatePayload) {
|
||||
return request<Project>({
|
||||
url: '/projects/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取项目详情 */
|
||||
export function getProject(projectId: number) {
|
||||
return request<Project>({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新项目信息 */
|
||||
export function updateProject(projectId: number, data: ProjectUpdatePayload) {
|
||||
return request<Project>({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 删除项目 */
|
||||
export function deleteProject(projectId: number) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/** 转移项目所有权 */
|
||||
export function transferProject(projectId: number, newOwnerId: number) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}/transfer`,
|
||||
method: 'post',
|
||||
data: { new_owner_id: newOwnerId },
|
||||
})
|
||||
}
|
||||
|
||||
/** 启动项目导出任务 */
|
||||
export function startProjectExport(projectId: number) {
|
||||
return request<ExportTask>({
|
||||
url: `/projects/${projectId}/export`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取项目导出任务状态 */
|
||||
export function getProjectExportStatus(projectId: number, taskId: string) {
|
||||
return request<ExportTask>({
|
||||
url: `/projects/${projectId}/export/${taskId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 下载项目导出 ZIP */
|
||||
export function downloadProjectExport(projectId: number, taskId: string) {
|
||||
return request.blob({
|
||||
url: `/projects/${projectId}/export/${taskId}/download`,
|
||||
method: 'get',
|
||||
timeout: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取项目成员 */
|
||||
export function getProjectMembers(projectId: number) {
|
||||
return request<ProjectMember[]>({
|
||||
url: `/projects/${projectId}/members`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 添加项目成员 */
|
||||
export function addProjectMember(projectId: number, data: { user_id: number; role: ProjectRole }) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}/members`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 删除项目成员 */
|
||||
export function removeProjectMember(projectId: number, userId: number) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}/members/${userId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/** 修改项目成员角色 */
|
||||
export function updateProjectMemberRole(projectId: number, userId: number, role: ProjectRole) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}/members/${userId}`,
|
||||
method: 'put',
|
||||
data: { role },
|
||||
})
|
||||
}
|
||||
|
||||
/** Git 同步范围:all = 整个仓库,path = 仅指定目录(后端只接受这两个值) */
|
||||
export type GitSyncScope = 'all' | 'path'
|
||||
|
||||
/** Git Pull */
|
||||
export function gitPull(
|
||||
projectId: number,
|
||||
repoId: number | null = null,
|
||||
force = false,
|
||||
syncScope: GitSyncScope | null = null,
|
||||
subPath = '',
|
||||
) {
|
||||
return request<GitSyncResult>({
|
||||
url: `/projects/${projectId}/git/pull`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId, force, sync_scope: syncScope || undefined, sub_path: subPath || undefined },
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** Git Push */
|
||||
export function gitPush(
|
||||
projectId: number,
|
||||
repoId: number | null = null,
|
||||
force = false,
|
||||
syncScope: GitSyncScope | null = null,
|
||||
subPath = '',
|
||||
) {
|
||||
return request<GitSyncResult>({
|
||||
url: `/projects/${projectId}/git/push`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId, force, sync_scope: syncScope || undefined, sub_path: subPath || undefined },
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取Git仓库列表 */
|
||||
export function getGitRepos(projectId: number) {
|
||||
return request<GitRepo[]>({
|
||||
url: `/projects/${projectId}/git-repos`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 添加Git仓库 */
|
||||
export function createGitRepo(projectId: number, data: GitRepoPayload) {
|
||||
return request<GitRepo>({
|
||||
url: `/projects/${projectId}/git-repos`,
|
||||
method: 'post',
|
||||
data,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新Git仓库 */
|
||||
export function updateGitRepo(projectId: number, repoId: number, data: GitRepoUpdatePayload) {
|
||||
return request<GitRepo>({
|
||||
url: `/projects/${projectId}/git-repos/${repoId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 删除Git仓库 */
|
||||
export function deleteGitRepo(projectId: number, repoId: number) {
|
||||
return request<null>({
|
||||
url: `/projects/${projectId}/git-repos/${repoId}`,
|
||||
method: 'delete',
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 测试Git远端仓库认证 */
|
||||
export function testGitRepoConnection(projectId: number, data: GitRepoTestPayload) {
|
||||
return request<{ success?: boolean; message?: string }>({
|
||||
url: `/projects/${projectId}/git-repos/test-connection`,
|
||||
method: 'post',
|
||||
data,
|
||||
timeout: 35000,
|
||||
skipErrorToast: true,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取Git仓库远端目录结构(用于选择同步目录) */
|
||||
export function getGitRepoDirectories(projectId: number, repoId: number | null = null) {
|
||||
return request<GitDirectoriesResult>({
|
||||
url: `/projects/${projectId}/git/directories`,
|
||||
method: 'post',
|
||||
params: { repo_id: repoId || undefined },
|
||||
})
|
||||
}
|
||||
|
|
@ -2,42 +2,31 @@
|
|||
* 角色权限管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { MenuPermissionNode, Role, RolePermissionDetail } from '@/types/api'
|
||||
|
||||
/**
|
||||
* 获取所有角色列表
|
||||
*/
|
||||
export function getAllRoles() {
|
||||
return request({
|
||||
return request<Role[]>({
|
||||
url: '/role-permissions/roles',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的菜单权限树
|
||||
*/
|
||||
export function getMenuTree() {
|
||||
return request({
|
||||
return request<MenuPermissionNode[]>({
|
||||
url: '/role-permissions/menu-tree',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定角色的权限
|
||||
*/
|
||||
export function getRolePermissions(roleId) {
|
||||
return request({
|
||||
export function getRolePermissions(roleId: number) {
|
||||
return request<RolePermissionDetail>({
|
||||
url: `/role-permissions/roles/${roleId}/permissions`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新角色权限
|
||||
*/
|
||||
export function updateRolePermissions(roleId, menuIds) {
|
||||
return request({
|
||||
export function updateRolePermissions(roleId: number, menuIds: number[]) {
|
||||
return request<null>({
|
||||
url: `/role-permissions/roles/${roleId}/permissions`,
|
||||
method: 'put',
|
||||
data: {
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
/**
|
||||
* 角色管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 获取角色列表
|
||||
*/
|
||||
export function getRoleList(params) {
|
||||
return request({
|
||||
url: '/roles/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色详情
|
||||
*/
|
||||
export function getRoleDetail(roleId) {
|
||||
return request({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新角色
|
||||
*/
|
||||
export function createRole(data) {
|
||||
return request({
|
||||
url: '/roles/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新角色信息
|
||||
*/
|
||||
export function updateRole(roleId, data) {
|
||||
return request({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除角色
|
||||
*/
|
||||
export function deleteRole(roleId) {
|
||||
return request({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色下的用户列表
|
||||
*/
|
||||
export function getRoleUsers(roleId, params) {
|
||||
return request({
|
||||
url: `/roles/${roleId}/users`,
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
/**
|
||||
* 角色管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { Role, User } from '@/types/api'
|
||||
|
||||
export interface RoleQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
keyword?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
export interface RolePayload {
|
||||
role_name: string
|
||||
role_code: string
|
||||
description?: string | null
|
||||
status?: number
|
||||
}
|
||||
|
||||
/** 获取角色列表 */
|
||||
export function getRoleList(params: RoleQuery) {
|
||||
return request.list<Role>({
|
||||
url: '/roles/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取角色详情 */
|
||||
export function getRoleDetail(roleId: number) {
|
||||
return request<Role>({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 创建新角色 */
|
||||
export function createRole(data: RolePayload) {
|
||||
return request<Role>({
|
||||
url: '/roles/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新角色信息 */
|
||||
export function updateRole(roleId: number, data: Partial<RolePayload>) {
|
||||
return request<Role>({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 删除角色 */
|
||||
export function deleteRole(roleId: number) {
|
||||
return request<null>({
|
||||
url: `/roles/${roleId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取角色下的用户列表 */
|
||||
export function getRoleUsers(roleId: number, params: RoleQuery) {
|
||||
return request.list<User>({
|
||||
url: `/roles/${roleId}/users`,
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
/**
|
||||
* 文档搜索相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 搜索文档
|
||||
* @param {string} keyword - 搜索关键词
|
||||
* @param {string} project_id - 项目ID (可选,限制搜索范围)
|
||||
*/
|
||||
export function searchDocuments(keyword, project_id) {
|
||||
return request({
|
||||
url: '/search/documents',
|
||||
method: 'get',
|
||||
params: { keyword, project_id },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 重建搜索索引 (仅管理员)
|
||||
*/
|
||||
export function rebuildIndex() {
|
||||
return request({
|
||||
url: '/search/rebuild-index',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* 文档搜索相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { SearchResult } from '@/types/api'
|
||||
|
||||
/**
|
||||
* 搜索文档
|
||||
* @param keyword 搜索关键词
|
||||
* @param projectId 项目ID(可选,限制搜索范围)
|
||||
*/
|
||||
export function searchDocuments(keyword: string, projectId?: number | string | null) {
|
||||
return request<SearchResult[]>({
|
||||
url: '/search/documents',
|
||||
method: 'get',
|
||||
params: { keyword, project_id: projectId },
|
||||
})
|
||||
}
|
||||
|
||||
/** 重建搜索索引(仅管理员) */
|
||||
export function rebuildIndex() {
|
||||
return request<null>({
|
||||
url: '/search/rebuild-index',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
/**
|
||||
* 分享相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
export function getProjectShareInfo(projectId) {
|
||||
return request({
|
||||
url: `/shares/projects/${projectId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function updateProjectShareSettings(projectId, data) {
|
||||
return request({
|
||||
url: `/shares/projects/${projectId}/settings`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareInfo(projectId, filePath) {
|
||||
return request({
|
||||
url: `/shares/projects/${projectId}/files/share/info`,
|
||||
method: 'get',
|
||||
params: { file_path: filePath },
|
||||
})
|
||||
}
|
||||
|
||||
export function createOrUpdateFileShare(projectId, data) {
|
||||
return request({
|
||||
url: `/shares/projects/${projectId}/files/share`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteFileShare(projectId, filePath) {
|
||||
return request({
|
||||
url: `/shares/projects/${projectId}/files/share`,
|
||||
method: 'delete',
|
||||
params: { file_path: filePath },
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectSharePublicInfo(shareCode) {
|
||||
return request({
|
||||
url: `/shares/project/${shareCode}/info`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function verifyProjectSharePassword(shareCode, password) {
|
||||
return request({
|
||||
url: `/shares/project/${shareCode}/verify`,
|
||||
method: 'post',
|
||||
headers: {
|
||||
'X-Access-Password': password,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareTree(shareCode, password = null) {
|
||||
return request({
|
||||
url: `/shares/project/${shareCode}/tree`,
|
||||
method: 'get',
|
||||
headers: password ? { 'X-Access-Password': password } : {},
|
||||
})
|
||||
}
|
||||
|
||||
export function searchProjectShareDocuments(shareCode, keyword, password = null) {
|
||||
return request({
|
||||
url: `/shares/project/${shareCode}/search`,
|
||||
method: 'get',
|
||||
params: { keyword },
|
||||
headers: password ? { 'X-Access-Password': password } : {},
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareFile(shareCode, path, password = null) {
|
||||
return request({
|
||||
url: `/shares/project/${shareCode}/file`,
|
||||
method: 'get',
|
||||
params: { path },
|
||||
headers: password ? { 'X-Access-Password': password } : {},
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareDocumentUrl(shareCode, path) {
|
||||
const encodedPath = path.split('/').map(part => encodeURIComponent(part)).join('/')
|
||||
return `/api/v1/shares/project/${shareCode}/document/${encodedPath}`
|
||||
}
|
||||
|
||||
export function exportProjectSharePDF(shareCode, path) {
|
||||
const encodedPath = encodeURIComponent(path)
|
||||
return `/api/v1/shares/project/${shareCode}/export-pdf?path=${encodedPath}`
|
||||
}
|
||||
|
||||
export function getFileSharePublicInfo(shareCode) {
|
||||
return request({
|
||||
url: `/shares/files/${shareCode}/info`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function verifyFileSharePassword(shareCode, password) {
|
||||
return request({
|
||||
url: `/shares/files/${shareCode}/verify`,
|
||||
method: 'post',
|
||||
headers: {
|
||||
'X-Access-Password': password,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareContent(shareCode, password = null) {
|
||||
return request({
|
||||
url: `/shares/files/${shareCode}/content`,
|
||||
method: 'get',
|
||||
headers: password ? { 'X-Access-Password': password } : {},
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareDocumentUrl(shareCode) {
|
||||
return `/api/v1/shares/files/${shareCode}/document`
|
||||
}
|
||||
|
||||
export function exportFileSharePDF(shareCode) {
|
||||
return `/api/v1/shares/files/${shareCode}/export-pdf`
|
||||
}
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
/**
|
||||
* 分享相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type {
|
||||
FileShareContent,
|
||||
FileShareInfo,
|
||||
FileSharePublicInfo,
|
||||
FileTreeNode,
|
||||
ProjectShareInfo,
|
||||
ProjectSharePublicInfo,
|
||||
ShareFileContent,
|
||||
ShareSearchResult,
|
||||
} from '@/types/api'
|
||||
|
||||
/**
|
||||
* 项目分享设置:后端只读取 access_pass(置空即取消密码保护),
|
||||
* 开关本身由项目的 is_public 决定,不在这个接口里传。
|
||||
*/
|
||||
export interface ProjectShareSettingsPayload {
|
||||
access_pass?: string | null
|
||||
}
|
||||
|
||||
export interface FileShareCreatePayload {
|
||||
file_path: string
|
||||
access_pass?: string | null
|
||||
}
|
||||
|
||||
/** 密码通过自定义头传递(避免出现在 URL / 访问日志里) */
|
||||
function passwordHeader(password: string | null) {
|
||||
return password ? { 'X-Access-Password': password } : {}
|
||||
}
|
||||
|
||||
export function getProjectShareInfo(projectId: number) {
|
||||
return request<ProjectShareInfo>({
|
||||
url: `/shares/projects/${projectId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function updateProjectShareSettings(projectId: number, data: ProjectShareSettingsPayload) {
|
||||
// 接口只回 message,没有 data
|
||||
return request<null>({
|
||||
url: `/shares/projects/${projectId}/settings`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareInfo(projectId: number, filePath: string) {
|
||||
return request<FileShareInfo>({
|
||||
url: `/shares/projects/${projectId}/files/share/info`,
|
||||
method: 'get',
|
||||
params: { file_path: filePath },
|
||||
})
|
||||
}
|
||||
|
||||
export function createOrUpdateFileShare(projectId: number, data: FileShareCreatePayload) {
|
||||
return request<FileShareInfo>({
|
||||
url: `/shares/projects/${projectId}/files/share`,
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteFileShare(projectId: number, filePath: string) {
|
||||
return request<null>({
|
||||
url: `/shares/projects/${projectId}/files/share`,
|
||||
method: 'delete',
|
||||
params: { file_path: filePath },
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectSharePublicInfo(shareCode: string) {
|
||||
return request<ProjectSharePublicInfo>({
|
||||
url: `/shares/project/${shareCode}/info`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function verifyProjectSharePassword(shareCode: string, password: string) {
|
||||
return request<null>({
|
||||
url: `/shares/project/${shareCode}/verify`,
|
||||
method: 'post',
|
||||
headers: {
|
||||
'X-Access-Password': password,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareTree(shareCode: string, password: string | null = null) {
|
||||
return request<FileTreeNode[]>({
|
||||
url: `/shares/project/${shareCode}/tree`,
|
||||
method: 'get',
|
||||
headers: passwordHeader(password),
|
||||
})
|
||||
}
|
||||
|
||||
export function searchProjectShareDocuments(shareCode: string, keyword: string, password: string | null = null) {
|
||||
return request<ShareSearchResult[]>({
|
||||
url: `/shares/project/${shareCode}/search`,
|
||||
method: 'get',
|
||||
params: { keyword },
|
||||
headers: passwordHeader(password),
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareFile(shareCode: string, path: string, password: string | null = null) {
|
||||
return request<ShareFileContent>({
|
||||
url: `/shares/project/${shareCode}/file`,
|
||||
method: 'get',
|
||||
params: { path },
|
||||
headers: passwordHeader(password),
|
||||
})
|
||||
}
|
||||
|
||||
export function getProjectShareDocumentUrl(shareCode: string, path: string) {
|
||||
const encodedPath = path.split('/').map((part) => encodeURIComponent(part)).join('/')
|
||||
return `/api/v1/shares/project/${shareCode}/document/${encodedPath}`
|
||||
}
|
||||
|
||||
export function exportProjectSharePDF(shareCode: string, path: string) {
|
||||
const encodedPath = encodeURIComponent(path)
|
||||
return `/api/v1/shares/project/${shareCode}/export-pdf?path=${encodedPath}`
|
||||
}
|
||||
|
||||
export function getFileSharePublicInfo(shareCode: string) {
|
||||
return request<FileSharePublicInfo>({
|
||||
url: `/shares/files/${shareCode}/info`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function verifyFileSharePassword(shareCode: string, password: string) {
|
||||
return request<null>({
|
||||
url: `/shares/files/${shareCode}/verify`,
|
||||
method: 'post',
|
||||
headers: {
|
||||
'X-Access-Password': password,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareContent(shareCode: string, password: string | null = null) {
|
||||
return request<FileShareContent>({
|
||||
url: `/shares/files/${shareCode}/content`,
|
||||
method: 'get',
|
||||
headers: passwordHeader(password),
|
||||
})
|
||||
}
|
||||
|
||||
export function getFileShareDocumentUrl(shareCode: string) {
|
||||
return `/api/v1/shares/files/${shareCode}/document`
|
||||
}
|
||||
|
||||
export function exportFileSharePDF(shareCode: string) {
|
||||
return `/api/v1/shares/files/${shareCode}/export-pdf`
|
||||
}
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
/**
|
||||
* 用户管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 获取用户列表
|
||||
*/
|
||||
export function getUserList(params) {
|
||||
return request({
|
||||
url: '/users/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户详情
|
||||
*/
|
||||
export function getUserDetail(userId) {
|
||||
return request({
|
||||
url: `/users/${userId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新用户
|
||||
*/
|
||||
export function createUser(data) {
|
||||
return request({
|
||||
url: '/users/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户信息
|
||||
*/
|
||||
export function updateUser(userId, data) {
|
||||
return request({
|
||||
url: `/users/${userId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除用户
|
||||
*/
|
||||
export function deleteUser(userId) {
|
||||
return request({
|
||||
url: `/users/${userId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户状态(停用/启用)
|
||||
*/
|
||||
export function updateUserStatus(userId, status) {
|
||||
return request({
|
||||
url: `/users/${userId}/status`,
|
||||
method: 'put',
|
||||
params: { status },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户角色
|
||||
*/
|
||||
export function updateUserRoles(userId, roleIds) {
|
||||
return request({
|
||||
url: `/users/${userId}/roles`,
|
||||
method: 'put',
|
||||
data: { role_ids: roleIds },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置用户密码
|
||||
*/
|
||||
export function resetUserPassword(userId) {
|
||||
return request({
|
||||
url: `/users/${userId}/reset-password`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
/**
|
||||
* 用户管理相关 API
|
||||
*/
|
||||
import request from '@/utils/request'
|
||||
import type { User } from '@/types/api'
|
||||
|
||||
export interface UserQuery {
|
||||
page?: number
|
||||
page_size?: number
|
||||
keyword?: string
|
||||
status?: number
|
||||
role_id?: number
|
||||
}
|
||||
|
||||
export interface UserCreatePayload {
|
||||
username: string
|
||||
nickname?: string
|
||||
email?: string
|
||||
phone?: string
|
||||
role_ids: number[]
|
||||
}
|
||||
|
||||
export interface UserUpdatePayload {
|
||||
nickname?: string | null
|
||||
email?: string | null
|
||||
phone?: string | null
|
||||
status?: number
|
||||
}
|
||||
|
||||
/** 获取用户列表 */
|
||||
export function getUserList(params: UserQuery) {
|
||||
return request.list<User>({
|
||||
url: '/users/',
|
||||
method: 'get',
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/** 获取用户详情 */
|
||||
export function getUserDetail(userId: number) {
|
||||
return request<User>({
|
||||
url: `/users/${userId}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
/** 创建用户只回传标识与初始密码(后端不返回完整用户对象) */
|
||||
export interface UserCreateResult {
|
||||
id: number
|
||||
username: string
|
||||
default_password: string
|
||||
}
|
||||
|
||||
/** 重置密码回传新的初始密码 */
|
||||
export interface ResetPasswordResult {
|
||||
default_password: string
|
||||
}
|
||||
|
||||
/** 创建新用户 */
|
||||
export function createUser(data: UserCreatePayload) {
|
||||
return request<UserCreateResult>({
|
||||
url: '/users/',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新用户信息 */
|
||||
export function updateUser(userId: number, data: UserUpdatePayload) {
|
||||
return request<User>({
|
||||
url: `/users/${userId}`,
|
||||
method: 'put',
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
/** 删除用户 */
|
||||
export function deleteUser(userId: number) {
|
||||
return request<null>({
|
||||
url: `/users/${userId}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新用户状态(停用/启用) */
|
||||
export function updateUserStatus(userId: number, status: number) {
|
||||
return request<null>({
|
||||
url: `/users/${userId}/status`,
|
||||
method: 'put',
|
||||
params: { status },
|
||||
})
|
||||
}
|
||||
|
||||
/** 更新用户角色 */
|
||||
export function updateUserRoles(userId: number, roleIds: number[]) {
|
||||
return request<null>({
|
||||
url: `/users/${userId}/roles`,
|
||||
method: 'put',
|
||||
data: { role_ids: roleIds },
|
||||
})
|
||||
}
|
||||
|
||||
/** 重置用户密码 */
|
||||
export function resetUserPassword(userId: number) {
|
||||
return request<ResetPasswordResult>({
|
||||
url: `/users/${userId}/reset-password`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect } from 'react'
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
import { App } from 'antd'
|
||||
import { setFeedbackApi } from './feedbackApi'
|
||||
|
||||
|
|
@ -6,7 +6,7 @@ import { setFeedbackApi } from './feedbackApi'
|
|||
* 把 AntD App 上下文里的 message / notification / modal 注册到全局反馈通道。
|
||||
* 必须渲染在 <ConfigProvider> + <App> 内部。
|
||||
*/
|
||||
export default function FeedbackBridge({ children }) {
|
||||
export default function FeedbackBridge({ children }: { children: ReactNode }) {
|
||||
const api = App.useApp()
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -14,5 +14,5 @@ export default function FeedbackBridge({ children }) {
|
|||
return () => setFeedbackApi(null)
|
||||
}, [api])
|
||||
|
||||
return children
|
||||
return <>{children}</>
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import { Modal, message as staticMessage, notification as staticNotification } from 'antd'
|
||||
|
||||
/**
|
||||
* 全局反馈通道(message / notification / modal)
|
||||
*
|
||||
* AntD 5 的静态方法(message.success、Modal.confirm 等)不会继承 ConfigProvider 的主题,
|
||||
* 暗色模式下会弹出浅色气泡,交互风格也不统一。因此统一通过 FeedbackBridge 注入
|
||||
* App.useApp() 返回的上下文实例,业务代码继续调用 Toast.xxx 即可。
|
||||
*
|
||||
* 静态实例仅作为 React 树之外(如 axios 拦截器)的兜底。
|
||||
*/
|
||||
const fallbackApi = {
|
||||
message: staticMessage,
|
||||
// 静态 Modal.confirm 仅作为 React 树之外的兜底
|
||||
modal: { confirm: (config) => Modal.confirm(config) },
|
||||
notification: staticNotification,
|
||||
}
|
||||
|
||||
let currentApi = fallbackApi
|
||||
|
||||
export function setFeedbackApi(api) {
|
||||
currentApi = api ? { ...fallbackApi, ...api } : fallbackApi
|
||||
}
|
||||
|
||||
export function getFeedbackApi() {
|
||||
return currentApi
|
||||
}
|
||||
|
||||
export default getFeedbackApi
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import { Modal, message as staticMessage, notification as staticNotification } from 'antd'
|
||||
import type { MessageInstance } from 'antd/es/message/interface'
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface'
|
||||
import type { ModalFunc } from 'antd/es/modal/confirm'
|
||||
import type { ModalFuncProps } from 'antd/es/modal/interface'
|
||||
|
||||
/**
|
||||
* 全局反馈通道(message / notification / modal)
|
||||
*
|
||||
* AntD 5 的静态方法(message.success、Modal.confirm 等)不会继承 ConfigProvider 的主题,
|
||||
* 暗色模式下会弹出浅色气泡,交互风格也不统一。因此统一通过 FeedbackBridge 注入
|
||||
* App.useApp() 返回的上下文实例,业务代码继续调用 Toast.xxx 即可。
|
||||
*
|
||||
* 静态实例仅作为 React 树之外(如 axios 拦截器)的兜底。
|
||||
*/
|
||||
export interface FeedbackApi {
|
||||
message: MessageInstance
|
||||
notification: NotificationInstance
|
||||
modal: {
|
||||
/**
|
||||
* 只声明业务实际使用的 confirm:静态 Modal 与 App.useApp().modal 的实现不同,
|
||||
* 但二者都满足这个签名,因此无需 any 断言。
|
||||
*/
|
||||
confirm: (props: ModalFuncProps) => ReturnType<ModalFunc>
|
||||
}
|
||||
}
|
||||
|
||||
const fallbackApi: FeedbackApi = {
|
||||
message: staticMessage,
|
||||
notification: staticNotification,
|
||||
modal: { confirm: Modal.confirm },
|
||||
}
|
||||
|
||||
let currentApi: FeedbackApi = fallbackApi
|
||||
|
||||
export function setFeedbackApi(api: Partial<FeedbackApi> | null) {
|
||||
currentApi = api ? { ...fallbackApi, ...api } : fallbackApi
|
||||
}
|
||||
|
||||
export function getFeedbackApi() {
|
||||
return currentApi
|
||||
}
|
||||
|
||||
export default getFeedbackApi
|
||||
|
|
@ -1,15 +1,49 @@
|
|||
import { useState } from 'react'
|
||||
import { useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import { Anchor, Drawer } from 'antd'
|
||||
import type { AnchorContainer } from 'antd/es/anchor/Anchor'
|
||||
import { FileTextOutlined, MenuOutlined } from '@ant-design/icons'
|
||||
import './FloatingToc.css'
|
||||
|
||||
function buildAnchorItems(items, searchKeyword, renderTitle) {
|
||||
/** 目录条目:既支持源码大纲(MarkdownHeading),也支持虚拟滚动块索引 */
|
||||
export interface TocItem {
|
||||
key: string
|
||||
href: string
|
||||
title: string
|
||||
level: number
|
||||
blockIndex?: number
|
||||
}
|
||||
|
||||
interface AnchorLink {
|
||||
href: string
|
||||
title: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动容器:调用方通常传 ref.current,渲染时机上可能还是 null。
|
||||
* AntD 的类型声明不接受 null,运行时行为与改造前一致,因此集中在这一处断言。
|
||||
*/
|
||||
type TocContainerGetter = () => HTMLElement | null
|
||||
|
||||
interface TocContentProps {
|
||||
items?: TocItem[]
|
||||
getContainer?: TocContainerGetter
|
||||
searchKeyword?: string
|
||||
renderTitle?: (item: TocItem, keyword: string) => ReactNode
|
||||
onItemClick?: (link?: AnchorLink) => void
|
||||
onNavigate?: (href?: string) => void
|
||||
}
|
||||
|
||||
function buildAnchorItems(
|
||||
items: TocItem[],
|
||||
searchKeyword: string,
|
||||
renderTitle?: (item: TocItem, keyword: string) => ReactNode,
|
||||
) {
|
||||
return items.map((item) => ({
|
||||
key: item.key,
|
||||
href: item.href,
|
||||
title: (
|
||||
<div className="floating-toc-item" style={{ paddingLeft: `${(item.level - 1) * 12}px` }}>
|
||||
<FileTextOutlined className="floating-toc-item-icon" />
|
||||
<FileTextOutlined aria-hidden className="floating-toc-item-icon" />
|
||||
<span className="floating-toc-item-title">
|
||||
{renderTitle ? renderTitle(item, searchKeyword) : item.title}
|
||||
</span>
|
||||
|
|
@ -18,7 +52,14 @@ function buildAnchorItems(items, searchKeyword, renderTitle) {
|
|||
}))
|
||||
}
|
||||
|
||||
function TocContent({ items = [], getContainer, searchKeyword = '', renderTitle, onItemClick, onNavigate }) {
|
||||
function TocContent({
|
||||
items = [],
|
||||
getContainer,
|
||||
searchKeyword = '',
|
||||
renderTitle,
|
||||
onItemClick,
|
||||
onNavigate,
|
||||
}: TocContentProps) {
|
||||
const anchorItems = buildAnchorItems(items, searchKeyword, renderTitle)
|
||||
|
||||
return (
|
||||
|
|
@ -27,9 +68,9 @@ function TocContent({ items = [], getContainer, searchKeyword = '', renderTitle,
|
|||
<Anchor
|
||||
affix={false}
|
||||
offsetTop={0}
|
||||
getContainer={getContainer}
|
||||
getContainer={getContainer as (() => AnchorContainer) | undefined}
|
||||
items={anchorItems}
|
||||
onClick={(e, link) => {
|
||||
onClick={(e: MouseEvent<HTMLElement>, link: AnchorLink) => {
|
||||
// antd Anchor 的 link 为 { href, title } 对象
|
||||
// 虚拟滚动场景下目标标题可能不在 DOM 中,由 onNavigate 接管滚动
|
||||
if (onNavigate) {
|
||||
|
|
@ -46,6 +87,11 @@ function TocContent({ items = [], getContainer, searchKeyword = '', renderTitle,
|
|||
)
|
||||
}
|
||||
|
||||
interface TocDrawerProps extends TocContentProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function TocDrawer({
|
||||
open,
|
||||
onClose,
|
||||
|
|
@ -54,7 +100,7 @@ export function TocDrawer({
|
|||
searchKeyword = '',
|
||||
renderTitle,
|
||||
onNavigate,
|
||||
}) {
|
||||
}: TocDrawerProps) {
|
||||
return (
|
||||
<Drawer
|
||||
title="文档索引"
|
||||
|
|
@ -76,6 +122,10 @@ export function TocDrawer({
|
|||
)
|
||||
}
|
||||
|
||||
interface FloatingTocProps extends TocContentProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
export default function FloatingToc({
|
||||
items = [],
|
||||
getContainer,
|
||||
|
|
@ -83,7 +133,7 @@ export default function FloatingToc({
|
|||
renderTitle,
|
||||
onNavigate,
|
||||
className = '',
|
||||
}) {
|
||||
}: FloatingTocProps) {
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
|
||||
return (
|
||||
|
|
@ -95,7 +145,7 @@ export default function FloatingToc({
|
|||
onFocus={() => setDismissed(false)}
|
||||
>
|
||||
<div className="floating-toc-tab">
|
||||
<MenuOutlined />
|
||||
<MenuOutlined aria-hidden />
|
||||
<span>文档索引</span>
|
||||
</div>
|
||||
<div className="floating-toc-panel">
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { useEffect, useRef } from 'react'
|
||||
import type CodeMirror from 'codemirror'
|
||||
import { InfoCircleOutlined } from '@ant-design/icons'
|
||||
import factory from 'codemirror-ssr'
|
||||
import usePlaceholder from 'codemirror-ssr/addon/display/placeholder.js'
|
||||
|
|
@ -27,9 +28,15 @@ function createCodeMirror() {
|
|||
return codemirror
|
||||
}
|
||||
|
||||
export default function LargeMarkdownEditor({ value = '', onChange, placeholder = '' }) {
|
||||
const containerRef = useRef(null)
|
||||
const editorRef = useRef(null)
|
||||
interface LargeMarkdownEditorProps {
|
||||
value?: string
|
||||
onChange?: (value: string) => void
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
export default function LargeMarkdownEditor({ value = '', onChange, placeholder = '' }: LargeMarkdownEditorProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const editorRef = useRef<CodeMirror.Editor | null>(null)
|
||||
const onChangeRef = useRef(onChange)
|
||||
|
||||
// 保持 onChange 最新,但不因其变化而重建编辑器
|
||||
|
|
@ -84,7 +91,7 @@ export default function LargeMarkdownEditor({ value = '', onChange, placeholder
|
|||
return (
|
||||
<div className="large-markdown-editor">
|
||||
<div className="large-markdown-editor-header">
|
||||
<InfoCircleOutlined className="large-markdown-editor-header-icon" />
|
||||
<InfoCircleOutlined aria-hidden className="large-markdown-editor-header-icon" />
|
||||
<span>{LARGE_MARKDOWN_NOTICE}</span>
|
||||
</div>
|
||||
<div className="large-markdown-editor-body" ref={containerRef} />
|
||||
|
|
@ -1,164 +0,0 @@
|
|||
import { forwardRef, useImperativeHandle, useMemo, useRef } from 'react'
|
||||
import { Alert } from 'antd'
|
||||
import { Virtuoso } from 'react-virtuoso'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import rehypeSlug from 'rehype-slug'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import GithubSlugger from 'github-slugger'
|
||||
import FloatingToc from '@/components/FloatingToc/FloatingToc'
|
||||
import './LargeMarkdownViewer.css'
|
||||
|
||||
export const LARGE_MARKDOWN_THRESHOLD = 250000
|
||||
export const LARGE_MARKDOWN_NOTICE = '此文档内容过长,将采用精简模式显示'
|
||||
const MAX_TOC_ITEMS = 500
|
||||
|
||||
export function isLargeMarkdownContent(content = '') {
|
||||
return content.length > LARGE_MARKDOWN_THRESHOLD
|
||||
}
|
||||
|
||||
export function MarkdownSizeNotice({ className = '' }) {
|
||||
return (
|
||||
<div className={`large-markdown-notice${className ? ` ${className}` : ''}`}>
|
||||
<Alert
|
||||
className="large-markdown-alert"
|
||||
type="info"
|
||||
showIcon
|
||||
message={LARGE_MARKDOWN_NOTICE}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 将 markdown 切分为块,并在切分的同时提取标题用于目录导航。
|
||||
// 每个块以标题或空行为边界,目录项记录其所在块索引,便于虚拟滚动定位。
|
||||
function buildBlocksAndToc(content) {
|
||||
if (!content) return { blocks: [], tocItems: [] }
|
||||
|
||||
const blocks = []
|
||||
const tocItems = []
|
||||
const slugger = new GithubSlugger()
|
||||
const lines = content.split('\n')
|
||||
let current = []
|
||||
let inFence = false
|
||||
|
||||
const flush = () => {
|
||||
if (current.length > 0) {
|
||||
blocks.push(current.join('\n'))
|
||||
current = []
|
||||
}
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const isFenceLine = /^\s*(```|~~~)/.test(line)
|
||||
const headingMatch = inFence ? null : line.match(/^(#{1,6})\s+(.+)$/)
|
||||
|
||||
if (headingMatch) {
|
||||
flush()
|
||||
if (tocItems.length < MAX_TOC_ITEMS) {
|
||||
const key = slugger.slug(headingMatch[2].trim())
|
||||
tocItems.push({
|
||||
key: `#${key}`,
|
||||
href: `#${key}`,
|
||||
title: headingMatch[2].trim(),
|
||||
level: headingMatch[1].length,
|
||||
blockIndex: blocks.length, // 该标题即将进入的块的索引
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
current.push(line)
|
||||
|
||||
if (isFenceLine) {
|
||||
inFence = !inFence
|
||||
}
|
||||
|
||||
if (!inFence && line.trim() === '') {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
|
||||
flush()
|
||||
return { blocks, tocItems }
|
||||
}
|
||||
|
||||
const LargeMarkdownViewer = forwardRef(function LargeMarkdownViewer(
|
||||
{ content, components, onClick, searchKeyword = '', renderTitle },
|
||||
ref
|
||||
) {
|
||||
const virtuosoRef = useRef(null)
|
||||
const { blocks: markdownBlocks, tocItems } = useMemo(
|
||||
() => buildBlocksAndToc(content),
|
||||
[content]
|
||||
)
|
||||
|
||||
const hrefToIndex = useMemo(() => {
|
||||
const map = new Map()
|
||||
for (const item of tocItems) {
|
||||
if (!map.has(item.href)) {
|
||||
map.set(item.href, item.blockIndex)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [tocItems])
|
||||
|
||||
const scrollToIndex = (index) => {
|
||||
virtuosoRef.current?.scrollToIndex({
|
||||
index,
|
||||
align: 'start',
|
||||
behavior: 'smooth',
|
||||
})
|
||||
}
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
scrollToTop: () => scrollToIndex(0),
|
||||
// 引用跳转/搜索定位:找到包含关键词的文档块并滚动到该块
|
||||
scrollToKeyword: (keyword) => {
|
||||
if (!keyword) return
|
||||
const index = markdownBlocks.findIndex((block) => block.includes(keyword))
|
||||
if (index >= 0) {
|
||||
scrollToIndex(index)
|
||||
}
|
||||
},
|
||||
}), [markdownBlocks])
|
||||
|
||||
const handleTocNavigate = (link) => {
|
||||
const index = hrefToIndex.get(link)
|
||||
if (typeof index === 'number') {
|
||||
scrollToIndex(index)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="large-markdown-viewer">
|
||||
<MarkdownSizeNotice />
|
||||
<div className="markdown-body markdown-body-large" onClick={onClick}>
|
||||
<Virtuoso
|
||||
ref={virtuosoRef}
|
||||
className="markdown-virtual-list"
|
||||
data={markdownBlocks}
|
||||
itemContent={(index, block) => (
|
||||
<div className="markdown-block" data-index={index}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeRaw, rehypeSlug, rehypeHighlight]}
|
||||
components={components}
|
||||
>
|
||||
{block}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FloatingToc
|
||||
items={tocItems}
|
||||
searchKeyword={searchKeyword}
|
||||
renderTitle={renderTitle}
|
||||
onNavigate={handleTocNavigate}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default LargeMarkdownViewer
|
||||
|
|
@ -0,0 +1,189 @@
|
|||
import { forwardRef, useImperativeHandle, useMemo, useRef, type MouseEvent, type ReactNode } from 'react'
|
||||
import { Alert } from 'antd'
|
||||
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
|
||||
import ReactMarkdown, { type Components } from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import rehypeSlug from 'rehype-slug'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import GithubSlugger from 'github-slugger'
|
||||
import FloatingToc, { type TocItem } from '@/components/FloatingToc/FloatingToc'
|
||||
import { decorativeAlertIcon } from '@/utils/antdA11y'
|
||||
import './LargeMarkdownViewer.css'
|
||||
|
||||
export const LARGE_MARKDOWN_THRESHOLD = 250000
|
||||
export const LARGE_MARKDOWN_NOTICE = '此文档内容过长,将采用精简模式显示'
|
||||
const MAX_TOC_ITEMS = 500
|
||||
|
||||
export interface LargeMarkdownTocItem extends TocItem {
|
||||
blockIndex: number
|
||||
}
|
||||
|
||||
export interface LargeMarkdownViewerHandle {
|
||||
scrollToTop: () => void
|
||||
/** 引用跳转/搜索定位:滚动到第一个包含关键词的文档块 */
|
||||
scrollToKeyword: (keyword: string) => void
|
||||
}
|
||||
|
||||
export function isLargeMarkdownContent(content = ''): boolean {
|
||||
return content.length > LARGE_MARKDOWN_THRESHOLD
|
||||
}
|
||||
|
||||
export function MarkdownSizeNotice({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<div className={`large-markdown-notice${className ? ` ${className}` : ''}`}>
|
||||
<Alert
|
||||
className="large-markdown-alert"
|
||||
type="info"
|
||||
showIcon
|
||||
icon={decorativeAlertIcon('info')}
|
||||
message={LARGE_MARKDOWN_NOTICE}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface BlocksAndToc {
|
||||
blocks: string[]
|
||||
tocItems: LargeMarkdownTocItem[]
|
||||
}
|
||||
|
||||
// 将 markdown 切分为块,并在切分的同时提取标题用于目录导航。
|
||||
// 每个块以标题或空行为边界,目录项记录其所在块索引,便于虚拟滚动定位。
|
||||
function buildBlocksAndToc(content: string): BlocksAndToc {
|
||||
if (!content) return { blocks: [], tocItems: [] }
|
||||
|
||||
const blocks: string[] = []
|
||||
const tocItems: LargeMarkdownTocItem[] = []
|
||||
const slugger = new GithubSlugger()
|
||||
const lines = content.split('\n')
|
||||
let current: string[] = []
|
||||
let inFence = false
|
||||
|
||||
const flush = () => {
|
||||
if (current.length > 0) {
|
||||
blocks.push(current.join('\n'))
|
||||
current = []
|
||||
}
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const isFenceLine = /^\s*(```|~~~)/.test(line)
|
||||
const headingMatch = inFence ? null : line.match(/^(#{1,6})\s+(.+)$/)
|
||||
|
||||
if (headingMatch) {
|
||||
flush()
|
||||
if (tocItems.length < MAX_TOC_ITEMS) {
|
||||
const key = slugger.slug(headingMatch[2].trim())
|
||||
tocItems.push({
|
||||
key: `#${key}`,
|
||||
href: `#${key}`,
|
||||
title: headingMatch[2].trim(),
|
||||
level: headingMatch[1].length,
|
||||
blockIndex: blocks.length, // 该标题即将进入的块的索引
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
current.push(line)
|
||||
|
||||
if (isFenceLine) {
|
||||
inFence = !inFence
|
||||
}
|
||||
|
||||
if (!inFence && line.trim() === '') {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
|
||||
flush()
|
||||
return { blocks, tocItems }
|
||||
}
|
||||
|
||||
interface LargeMarkdownViewerProps {
|
||||
content: string
|
||||
components?: Components | null
|
||||
onClick?: (event: MouseEvent<HTMLDivElement>) => void
|
||||
searchKeyword?: string
|
||||
renderTitle?: (item: TocItem, keyword: string) => ReactNode
|
||||
}
|
||||
|
||||
const LargeMarkdownViewer = forwardRef<LargeMarkdownViewerHandle, LargeMarkdownViewerProps>(
|
||||
function LargeMarkdownViewer({ content, components, onClick, searchKeyword = '', renderTitle }, ref) {
|
||||
const virtuosoRef = useRef<VirtuosoHandle>(null)
|
||||
const { blocks: markdownBlocks, tocItems } = useMemo(
|
||||
() => buildBlocksAndToc(content),
|
||||
[content]
|
||||
)
|
||||
|
||||
const hrefToIndex = useMemo(() => {
|
||||
const map = new Map<string, number>()
|
||||
for (const item of tocItems) {
|
||||
if (!map.has(item.href)) {
|
||||
map.set(item.href, item.blockIndex)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [tocItems])
|
||||
|
||||
const scrollToIndex = (index: number) => {
|
||||
virtuosoRef.current?.scrollToIndex({
|
||||
index,
|
||||
align: 'start',
|
||||
behavior: 'smooth',
|
||||
})
|
||||
}
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
scrollToTop: () => scrollToIndex(0),
|
||||
// 引用跳转/搜索定位:找到包含关键词的文档块并滚动到该块
|
||||
scrollToKeyword: (keyword: string) => {
|
||||
if (!keyword) return
|
||||
const index = markdownBlocks.findIndex((block) => block.includes(keyword))
|
||||
if (index >= 0) {
|
||||
scrollToIndex(index)
|
||||
}
|
||||
},
|
||||
}), [markdownBlocks])
|
||||
|
||||
const handleTocNavigate = (link?: string) => {
|
||||
if (!link) return
|
||||
const index = hrefToIndex.get(link)
|
||||
if (typeof index === 'number') {
|
||||
scrollToIndex(index)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="large-markdown-viewer">
|
||||
<MarkdownSizeNotice />
|
||||
<div className="markdown-body markdown-body-large" onClick={onClick}>
|
||||
<Virtuoso
|
||||
ref={virtuosoRef}
|
||||
className="markdown-virtual-list"
|
||||
data={markdownBlocks}
|
||||
itemContent={(index, block) => (
|
||||
<div className="markdown-block" data-index={index}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeRaw, rehypeSlug, rehypeHighlight]}
|
||||
components={components}
|
||||
>
|
||||
{block}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FloatingToc
|
||||
items={tocItems}
|
||||
searchKeyword={searchKeyword}
|
||||
renderTitle={renderTitle}
|
||||
onNavigate={handleTocNavigate}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
export default LargeMarkdownViewer
|
||||
|
|
@ -1,21 +1,68 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { Button, Input, Space, Popover } from 'antd'
|
||||
import { ReloadOutlined, FilterOutlined } from '@ant-design/icons'
|
||||
import './ListActionBar.css'
|
||||
import { clearInputIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Search } = Input
|
||||
|
||||
export interface ListAction {
|
||||
key: string
|
||||
label: ReactNode
|
||||
icon?: ReactNode
|
||||
type?: 'primary' | 'default' | 'dashed' | 'link' | 'text'
|
||||
disabled?: boolean
|
||||
danger?: boolean
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
export interface ListSelectionInfo {
|
||||
/** 选中数量 */
|
||||
count: number
|
||||
/** 总数量 */
|
||||
total: number
|
||||
/** 是否跨页全选 */
|
||||
isAllPagesSelected: boolean
|
||||
}
|
||||
|
||||
interface ListSearchConfig {
|
||||
placeholder?: string
|
||||
width?: number
|
||||
value?: string
|
||||
onSearch?: (value: string) => void
|
||||
onChange?: (value: string) => void
|
||||
}
|
||||
|
||||
interface ListFilterConfig {
|
||||
content: ReactNode
|
||||
title?: ReactNode
|
||||
visible: boolean
|
||||
onVisibleChange?: (visible: boolean) => void
|
||||
isActive?: boolean
|
||||
selectedLabel?: ReactNode
|
||||
}
|
||||
|
||||
interface ListActionBarProps {
|
||||
/** 左侧操作按钮配置数组 */
|
||||
actions?: ListAction[]
|
||||
/** 批量操作按钮配置数组(仅在有选中项时显示) */
|
||||
batchActions?: ListAction[]
|
||||
/** 选中信息 */
|
||||
selectionInfo?: ListSelectionInfo
|
||||
/** 选择所有页回调 */
|
||||
onSelectAllPages?: () => void
|
||||
/** 清除选择回调 */
|
||||
onClearSelection?: () => void
|
||||
search?: ListSearchConfig
|
||||
/** 高级筛选配置(可选) */
|
||||
filter?: ListFilterConfig
|
||||
/** 是否显示刷新按钮 */
|
||||
showRefresh?: boolean
|
||||
onRefresh?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表操作栏组件
|
||||
* @param {Object} props
|
||||
* @param {Array} props.actions - 左侧操作按钮配置数组
|
||||
* @param {Array} props.batchActions - 批量操作按钮配置数组(仅在有选中项时显示)
|
||||
* @param {Object} props.selectionInfo - 选中信息 { count: 选中数量, total: 总数量, isAllPagesSelected: 是否跨页全选 }
|
||||
* @param {Function} props.onSelectAllPages - 选择所有页回调
|
||||
* @param {Function} props.onClearSelection - 清除选择回调
|
||||
* @param {Object} props.search - 搜索配置
|
||||
* @param {Object} props.filter - 高级筛选配置(可选)
|
||||
* @param {boolean} props.showRefresh - 是否显示刷新按钮
|
||||
* @param {Function} props.onRefresh - 刷新回调
|
||||
* 列表操作栏组件:左侧常规/批量操作,右侧搜索与高级筛选。
|
||||
*/
|
||||
function ListActionBar({
|
||||
actions = [],
|
||||
|
|
@ -27,7 +74,7 @@ function ListActionBar({
|
|||
filter,
|
||||
showRefresh = false,
|
||||
onRefresh,
|
||||
}) {
|
||||
}: ListActionBarProps) {
|
||||
// 是否有选中项
|
||||
const hasSelection = selectionInfo && selectionInfo.count > 0
|
||||
return (
|
||||
|
|
@ -91,8 +138,9 @@ function ListActionBar({
|
|||
<Space.Compact>
|
||||
<Search
|
||||
placeholder={search?.placeholder || '请输入搜索关键词'}
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
style={{ width: search?.width || 280 }}
|
||||
enterButton={searchEnterButton()}
|
||||
onSearch={search?.onSearch}
|
||||
onChange={(e) => search?.onChange?.(e.target.value)}
|
||||
value={search?.value}
|
||||
|
|
@ -102,7 +150,7 @@ function ListActionBar({
|
|||
content={filter.content}
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<FilterOutlined />
|
||||
<FilterOutlined aria-hidden />
|
||||
<span>{filter.title || '高级筛选'}</span>
|
||||
</div>
|
||||
}
|
||||
|
|
@ -113,7 +161,7 @@ function ListActionBar({
|
|||
overlayClassName="filter-popover"
|
||||
>
|
||||
<Button
|
||||
icon={<FilterOutlined />}
|
||||
icon={<FilterOutlined aria-hidden />}
|
||||
type={filter.isActive ? 'primary' : 'default'}
|
||||
>
|
||||
{filter.selectedLabel || '筛选'}
|
||||
|
|
@ -122,7 +170,7 @@ function ListActionBar({
|
|||
)}
|
||||
</Space.Compact>
|
||||
{showRefresh && (
|
||||
<Button icon={<ReloadOutlined />} onClick={onRefresh}>
|
||||
<Button icon={<ReloadOutlined aria-hidden />} onClick={onRefresh}>
|
||||
刷新
|
||||
</Button>
|
||||
)}
|
||||
|
|
@ -1,29 +1,45 @@
|
|||
import { Table } from 'antd'
|
||||
import type { Key, ReactElement, ReactNode } from 'react'
|
||||
import { cloneElement, isValidElement } from 'react'
|
||||
import { Table, type TablePaginationConfig } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { namePageItem } from '@/utils/antdA11y'
|
||||
import './ListTable.css'
|
||||
|
||||
interface ListTableScroll {
|
||||
x?: number | string | true
|
||||
y?: number | string
|
||||
}
|
||||
|
||||
interface ListTableProps<RecordType extends object> {
|
||||
columns: ColumnsType<RecordType>
|
||||
dataSource: RecordType[]
|
||||
/** 行唯一标识字段 */
|
||||
rowKey: Extract<keyof RecordType, string>
|
||||
/** 选中的行 */
|
||||
selectedRowKeys?: Key[]
|
||||
onSelectionChange?: (selectedRowKeys: Key[]) => void
|
||||
/** 是否跨页全选所有数据 */
|
||||
isAllPagesSelected?: boolean
|
||||
/** 总数据量(用于跨页全选) */
|
||||
totalCount?: number
|
||||
onSelectAllPages?: () => void
|
||||
onClearSelection?: () => void
|
||||
pagination?: TablePaginationConfig | false
|
||||
scroll?: ListTableScroll
|
||||
onRowClick?: (record: RecordType) => void
|
||||
/** 当前选中的行 */
|
||||
selectedRow?: RecordType | null
|
||||
loading?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表表格组件
|
||||
* @param {Object} props
|
||||
* @param {Array} props.columns - 表格列配置
|
||||
* @param {Array} props.dataSource - 数据源
|
||||
* @param {string} props.rowKey - 行唯一标识字段
|
||||
* @param {Array} props.selectedRowKeys - 选中的行
|
||||
* @param {Function} props.onSelectionChange - 选择变化回调
|
||||
* @param {boolean} props.isAllPagesSelected - 是否跨页全选所有数据
|
||||
* @param {number} props.totalCount - 总数据量(用于跨页全选)
|
||||
* @param {Function} props.onSelectAllPages - 选择所有页回调
|
||||
* @param {Function} props.onClearSelection - 清除选择回调
|
||||
* @param {Object} props.pagination - 分页配置
|
||||
* @param {Object} props.scroll - 表格滚动配置
|
||||
* @param {Function} props.onRowClick - 行点击回调
|
||||
* @param {Object} props.selectedRow - 当前选中的行
|
||||
* @param {boolean} props.loading - 加载状态
|
||||
* @param {string} props.className - 自定义类名
|
||||
* 列表表格组件:统一表格 + 分页 + 行选择(含跨页全选)的展示与文案。
|
||||
*/
|
||||
function ListTable({
|
||||
function ListTable<RecordType extends object>({
|
||||
columns,
|
||||
dataSource,
|
||||
rowKey = 'id',
|
||||
rowKey,
|
||||
selectedRowKeys = [],
|
||||
onSelectionChange,
|
||||
isAllPagesSelected = false,
|
||||
|
|
@ -35,26 +51,32 @@ function ListTable({
|
|||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
},
|
||||
scroll = { x: 1200},
|
||||
scroll = { x: 1200 },
|
||||
onRowClick,
|
||||
selectedRow,
|
||||
loading = false,
|
||||
className = '',
|
||||
}) {
|
||||
}: ListTableProps<RecordType>) {
|
||||
// 行选择配置
|
||||
const rowSelection = {
|
||||
selectedRowKeys,
|
||||
onChange: (newSelectedRowKeys) => {
|
||||
onChange: (newSelectedRowKeys: Key[]) => {
|
||||
onSelectionChange?.(newSelectedRowKeys)
|
||||
},
|
||||
// 当跨页全选时,禁用单个复选框
|
||||
getCheckboxProps: () => ({
|
||||
disabled: isAllPagesSelected,
|
||||
}),
|
||||
// antd 把行复选框包在内容为空的 `<label>` 里,表头那个又写死英文 `Select all`,
|
||||
// 于是行选择控件算不出可访问名称。两者都走官方钩子补名称,不改结构与鼠标行为。
|
||||
columnTitle: (originNode: ReactNode) => withAriaLabel(originNode, '全选'),
|
||||
renderCell: (_checked: boolean, _record: RecordType, index: number, originNode: ReactNode) =>
|
||||
withAriaLabel(originNode, `选择第 ${index + 1} 行`),
|
||||
}
|
||||
|
||||
// 合并分页配置,添加选择信息显示
|
||||
const mergedPagination = pagination === false ? false : {
|
||||
const mergedPagination: TablePaginationConfig | false = pagination === false ? false : {
|
||||
itemRender: namePageItem,
|
||||
...pagination,
|
||||
showTotal: (total) => (
|
||||
<div className="table-selection-info">
|
||||
|
|
@ -94,7 +116,7 @@ function ListTable({
|
|||
|
||||
return (
|
||||
<div className={`list-table-container ${className}`}>
|
||||
<Table
|
||||
<Table<RecordType>
|
||||
size="middle"
|
||||
rowSelection={rowSelection}
|
||||
columns={columns}
|
||||
|
|
@ -113,3 +135,9 @@ function ListTable({
|
|||
}
|
||||
|
||||
export default ListTable
|
||||
/** 给 antd 复选框元素补 `aria-label`;rc-checkbox 会把未知属性透传到内部 `<input>` */
|
||||
function withAriaLabel(node: ReactNode, label: string): ReactNode {
|
||||
if (!isValidElement(node)) return node
|
||||
return cloneElement(node as ReactElement<{ 'aria-label'?: string }>, { 'aria-label': label })
|
||||
}
|
||||
|
||||
|
|
@ -36,6 +36,12 @@
|
|||
color: var(--text-color-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
/* 折叠按钮是原生 button:清掉浏览器默认外观,保持与原 div 完全一致的视觉 */
|
||||
box-sizing: border-box;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-family: inherit;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
.trigger:hover {
|
||||
|
|
@ -112,6 +118,11 @@ body.dark .workspace-brand-icon {
|
|||
color: var(--text-color-secondary);
|
||||
transition: all 0.2s;
|
||||
background: transparent;
|
||||
/* 原生 button 复位:外观与原来的 div 保持一致,但可聚焦、可回车/空格触发 */
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
border: none;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.header-icon-btn:hover {
|
||||
|
|
|
|||
|
|
@ -16,19 +16,20 @@ import useUserStore from '@/stores/userStore'
|
|||
import useNotificationStore from '@/stores/notificationStore'
|
||||
import useThemeStore from '@/stores/themeStore'
|
||||
import { getNotifications, markAsRead, markAllAsRead } from '@/api/notification'
|
||||
import type { NotificationItem } from '@/types/api'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import './AppHeader.css'
|
||||
|
||||
const { Header } = Layout
|
||||
const { Text } = Typography
|
||||
|
||||
function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
||||
function AppHeader({ collapsed, onToggle, showLogo = true }: { collapsed: boolean; onToggle: () => void; showLogo?: boolean }) {
|
||||
const navigate = useNavigate()
|
||||
const { user } = useUserStore()
|
||||
const { unreadCount, fetchUnreadCount, decrementUnreadCount, resetUnreadCount } = useNotificationStore()
|
||||
const { isDarkMode, toggleTheme } = useThemeStore()
|
||||
|
||||
const [notifications, setNotifications] = useState([])
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [popoverVisible, setPopoverVisible] = useState(false)
|
||||
|
||||
|
|
@ -52,7 +53,7 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleMarkRead = async (id) => {
|
||||
const handleMarkRead = async (id: string | number) => {
|
||||
try {
|
||||
await markAsRead(id)
|
||||
setNotifications(notifications.map(n => n.id === id ? { ...n, is_read: true } : n))
|
||||
|
|
@ -73,7 +74,7 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleNotificationClick = (n) => {
|
||||
const handleNotificationClick = (n: NotificationItem) => {
|
||||
if (!n.is_read) {
|
||||
handleMarkRead(n.id)
|
||||
}
|
||||
|
|
@ -83,11 +84,11 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
}
|
||||
}
|
||||
|
||||
const getCategoryIcon = (category) => {
|
||||
const getCategoryIcon = (category: string) => {
|
||||
switch (category) {
|
||||
case 'project': return <ProjectOutlined style={{ color: 'var(--color-primary)' }} />
|
||||
case 'collaboration': return <TeamOutlined style={{ color: 'var(--color-success)' }} />
|
||||
default: return <NotificationOutlined style={{ color: 'var(--color-warning)' }} />
|
||||
case 'project': return <ProjectOutlined aria-hidden style={{ color: 'var(--color-primary)' }} />
|
||||
case 'collaboration': return <TeamOutlined aria-hidden style={{ color: 'var(--color-success)' }} />
|
||||
default: return <NotificationOutlined aria-hidden style={{ color: 'var(--color-warning)' }} />
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -113,7 +114,7 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
onClick={() => handleNotificationClick(item)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={<Avatar icon={getCategoryIcon(item.category)} />}
|
||||
avatar={<Avatar icon={getCategoryIcon(item.category)} aria-hidden />}
|
||||
title={<Text strong={!item.is_read}>{item.title}</Text>}
|
||||
description={
|
||||
<div>
|
||||
|
|
@ -145,14 +146,20 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
</div>
|
||||
|
||||
{/* 折叠按钮 */}
|
||||
<div className="trigger" onClick={onToggle}>
|
||||
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="trigger"
|
||||
onClick={onToggle}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
{collapsed ? <MenuUnfoldOutlined aria-hidden /> : <MenuFoldOutlined aria-hidden />}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!showLogo && (
|
||||
<div className="workspace-header-brand">
|
||||
<AppstoreOutlined className="workspace-brand-icon" />
|
||||
<AppstoreOutlined aria-hidden className="workspace-brand-icon" />
|
||||
<span className="workspace-brand-title">NexDocus Workspace</span>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -162,9 +169,15 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
<Space size={16} className="header-actions">
|
||||
|
||||
{/* 1. 主题切换 */}
|
||||
<div className="header-icon-btn" title="切换主题" onClick={toggleTheme}>
|
||||
{isDarkMode ? <SunOutlined style={{ fontSize: 18 }} /> : <MoonOutlined style={{ fontSize: 18 }} />}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
title="切换主题"
|
||||
aria-label={isDarkMode ? '切换到浅色主题' : '切换到深色主题'}
|
||||
onClick={toggleTheme}
|
||||
>
|
||||
{isDarkMode ? <SunOutlined aria-hidden style={{ fontSize: 18 }} /> : <MoonOutlined aria-hidden style={{ fontSize: 18 }} />}
|
||||
</button>
|
||||
|
||||
{/* 2. 消息通知 */}
|
||||
<Popover
|
||||
|
|
@ -180,11 +193,16 @@ function AppHeader({ collapsed, onToggle, showLogo = true }) {
|
|||
placement="bottomRight"
|
||||
overlayClassName="header-notification-popover"
|
||||
>
|
||||
<div className="header-icon-btn" title="消息中心">
|
||||
<button
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
title="消息中心"
|
||||
aria-label={`消息中心,${unreadCount > 0 ? `${unreadCount} 条未读` : '暂无未读'}`}
|
||||
>
|
||||
<Badge count={unreadCount} size="small" offset={[2, -2]}>
|
||||
<BellOutlined style={{ fontSize: 18 }} />
|
||||
<BellOutlined style={{ fontSize: 18 }} aria-hidden />
|
||||
</Badge>
|
||||
</div>
|
||||
</button>
|
||||
</Popover>
|
||||
|
||||
</Space>
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, type ReactNode } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import {
|
||||
DashboardOutlined,
|
||||
|
|
@ -22,30 +22,45 @@ import {
|
|||
import { getUserMenus } from '@/api/menu'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import useUserStore from '@/stores/userStore'
|
||||
import ModernSidebar from '../ModernSidebar/ModernSidebar'
|
||||
import ModernSidebar, { type SidebarMenuItem } from '../ModernSidebar/ModernSidebar'
|
||||
import type { MenuNode } from '@/types/api'
|
||||
|
||||
// 图标映射
|
||||
const iconMap = {
|
||||
DashboardOutlined: <DashboardOutlined />,
|
||||
DesktopOutlined: <DesktopOutlined />,
|
||||
GlobalOutlined: <GlobalOutlined />,
|
||||
CloudServerOutlined: <CloudServerOutlined />,
|
||||
FileSearchOutlined: <FileSearchOutlined />,
|
||||
UserOutlined: <UserOutlined />,
|
||||
AppstoreOutlined: <AppstoreOutlined />,
|
||||
SettingOutlined: <SettingOutlined />,
|
||||
BlockOutlined: <BlockOutlined />,
|
||||
FolderOutlined: <FolderOutlined />,
|
||||
FileTextOutlined: <FileTextOutlined />,
|
||||
SafetyOutlined: <SafetyOutlined />,
|
||||
TeamOutlined: <TeamOutlined />,
|
||||
ProjectOutlined: <ProjectOutlined />,
|
||||
ReadOutlined: <ReadOutlined />,
|
||||
BookOutlined: <BookOutlined />,
|
||||
CommentOutlined: <CommentOutlined />,
|
||||
interface BuiltInMenuMeta {
|
||||
path: string
|
||||
icon: string
|
||||
}
|
||||
|
||||
const builtInMenuMetaMap = {
|
||||
interface MenuGroupItem extends SidebarMenuItem {
|
||||
path?: string | null
|
||||
}
|
||||
|
||||
interface MenuGroup {
|
||||
title: string
|
||||
items: MenuGroupItem[]
|
||||
}
|
||||
|
||||
// 图标映射
|
||||
const iconMap: Record<string, ReactNode> = {
|
||||
DashboardOutlined: <DashboardOutlined aria-hidden />,
|
||||
DesktopOutlined: <DesktopOutlined aria-hidden />,
|
||||
GlobalOutlined: <GlobalOutlined aria-hidden />,
|
||||
CloudServerOutlined: <CloudServerOutlined aria-hidden />,
|
||||
FileSearchOutlined: <FileSearchOutlined aria-hidden />,
|
||||
UserOutlined: <UserOutlined aria-hidden />,
|
||||
AppstoreOutlined: <AppstoreOutlined aria-hidden />,
|
||||
SettingOutlined: <SettingOutlined aria-hidden />,
|
||||
BlockOutlined: <BlockOutlined aria-hidden />,
|
||||
FolderOutlined: <FolderOutlined aria-hidden />,
|
||||
FileTextOutlined: <FileTextOutlined aria-hidden />,
|
||||
SafetyOutlined: <SafetyOutlined aria-hidden />,
|
||||
TeamOutlined: <TeamOutlined aria-hidden />,
|
||||
ProjectOutlined: <ProjectOutlined aria-hidden />,
|
||||
ReadOutlined: <ReadOutlined aria-hidden />,
|
||||
BookOutlined: <BookOutlined aria-hidden />,
|
||||
CommentOutlined: <CommentOutlined aria-hidden />,
|
||||
}
|
||||
|
||||
const builtInMenuMetaMap: Record<string, BuiltInMenuMeta> = {
|
||||
dashboard: {
|
||||
path: '/dashboard',
|
||||
icon: 'DashboardOutlined',
|
||||
|
|
@ -88,7 +103,7 @@ const builtInMenuMetaMap = {
|
|||
},
|
||||
}
|
||||
|
||||
const resolveBuiltInMenuMeta = (item) => {
|
||||
const resolveBuiltInMenuMeta = (item: MenuNode): BuiltInMenuMeta | null => {
|
||||
const directMeta = builtInMenuMetaMap[item.menu_code]
|
||||
if (directMeta) {
|
||||
return directMeta
|
||||
|
|
@ -177,11 +192,11 @@ const resolveBuiltInMenuMeta = (item) => {
|
|||
return null
|
||||
}
|
||||
|
||||
function AppSider({ collapsed, onToggle }) {
|
||||
function AppSider({ collapsed, onToggle }: { collapsed: boolean; onToggle: () => void }) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { user, logout } = useUserStore()
|
||||
const [menuGroups, setMenuGroups] = useState([])
|
||||
const [menuGroups, setMenuGroups] = useState<MenuGroup[]>([])
|
||||
|
||||
// 加载菜单数据
|
||||
useEffect(() => {
|
||||
|
|
@ -202,11 +217,11 @@ function AppSider({ collapsed, onToggle }) {
|
|||
}
|
||||
}
|
||||
|
||||
const transformMenuData = (data) => {
|
||||
const groups = []
|
||||
const transformMenuData = (data: MenuNode[]) => {
|
||||
const groups: MenuGroup[] = []
|
||||
|
||||
// 默认组 (用于存放一级菜单即是叶子节点的情况)
|
||||
const defaultGroup = {
|
||||
const defaultGroup: MenuGroup = {
|
||||
title: '', // 空标题或 '通用'
|
||||
items: []
|
||||
}
|
||||
|
|
@ -220,7 +235,7 @@ function AppSider({ collapsed, onToggle }) {
|
|||
const groupItems = validChildren.map(child => {
|
||||
const normalizedChild = normalizeMenuItem(child)
|
||||
const icon = typeof normalizedChild.icon === 'string'
|
||||
? (iconMap[normalizedChild.icon] || <AppstoreOutlined />)
|
||||
? (iconMap[normalizedChild.icon] || <AppstoreOutlined aria-hidden />)
|
||||
: normalizedChild.icon
|
||||
return {
|
||||
key: normalizedChild.menu_code,
|
||||
|
|
@ -238,7 +253,7 @@ function AppSider({ collapsed, onToggle }) {
|
|||
// 一级菜单是叶子节点,放入默认组
|
||||
const normalizedItem = normalizeMenuItem(item)
|
||||
const icon = typeof normalizedItem.icon === 'string'
|
||||
? (iconMap[normalizedItem.icon] || <AppstoreOutlined />)
|
||||
? (iconMap[normalizedItem.icon] || <AppstoreOutlined aria-hidden />)
|
||||
: normalizedItem.icon
|
||||
defaultGroup.items.push({
|
||||
key: normalizedItem.menu_code,
|
||||
|
|
@ -257,7 +272,7 @@ function AppSider({ collapsed, onToggle }) {
|
|||
setMenuGroups(groups)
|
||||
}
|
||||
|
||||
const normalizeMenuItem = (item) => {
|
||||
const normalizeMenuItem = (item: MenuNode): MenuNode => {
|
||||
const builtInMeta = resolveBuiltInMenuMeta(item)
|
||||
|
||||
if (!builtInMeta) {
|
||||
|
|
@ -271,7 +286,7 @@ function AppSider({ collapsed, onToggle }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleNavigate = (key, item) => {
|
||||
const handleNavigate = (_key: string, item: SidebarMenuItem) => {
|
||||
if (item.path) {
|
||||
navigate(item.path)
|
||||
}
|
||||
|
|
@ -327,8 +342,9 @@ function AppSider({ collapsed, onToggle }) {
|
|||
|
||||
const userObj = user ? {
|
||||
name: user.nickname || user.username,
|
||||
role: user.role_name || 'Admin',
|
||||
avatar: getUserAvatarUrl()
|
||||
// 后端当前不下发角色名,侧栏沿用 'Admin' 占位;缺失时这里取到 undefined 即回落默认值
|
||||
role: (user as { role_name?: string }).role_name || 'Admin',
|
||||
avatar: getUserAvatarUrl() ?? undefined
|
||||
} : null
|
||||
|
||||
return (
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, type ReactNode } from 'react'
|
||||
import { Layout } from 'antd'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import AppSider from './AppSider'
|
||||
|
|
@ -8,11 +8,11 @@ import './MainLayout.css'
|
|||
const { Content } = Layout
|
||||
|
||||
// 项目详情页路由(浏览 / 编辑)
|
||||
const isProjectDetailPath = (pathname) => {
|
||||
const isProjectDetailPath = (pathname: string) => {
|
||||
return /^\/projects\/[^/]+\/(docs|editor)(\/|$)/.test(pathname)
|
||||
}
|
||||
|
||||
function MainLayout({ children }) {
|
||||
function MainLayout({ children }: { children: ReactNode }) {
|
||||
const [collapsed, setCollapsed] = useState(true)
|
||||
const location = useLocation()
|
||||
|
||||
|
|
@ -1,7 +1,23 @@
|
|||
import './ModeSwitch.css'
|
||||
|
||||
function ModeSwitch({
|
||||
value = 'view',
|
||||
export interface ModeSwitchOption<T extends string = string> {
|
||||
label: string
|
||||
value: T
|
||||
}
|
||||
|
||||
interface ModeSwitchProps<T extends string = string> {
|
||||
value?: T
|
||||
onChange?: (value: T) => void
|
||||
viewLabel?: string
|
||||
editLabel?: string
|
||||
options?: ModeSwitchOption<T>[]
|
||||
ariaLabel?: string
|
||||
size?: 'default' | 'small'
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
function ModeSwitch<T extends string = 'view' | 'edit'>({
|
||||
value = 'view' as T,
|
||||
onChange,
|
||||
viewLabel = '浏览',
|
||||
editLabel = '编辑',
|
||||
|
|
@ -9,11 +25,11 @@ function ModeSwitch({
|
|||
ariaLabel = '模式切换',
|
||||
size = 'default',
|
||||
disabled = false,
|
||||
}) {
|
||||
const finalOptions = options || [
|
||||
}: ModeSwitchProps<T>) {
|
||||
const finalOptions: ModeSwitchOption<T>[] = options || [
|
||||
{ label: viewLabel, value: 'view' },
|
||||
{ label: editLabel, value: 'edit' },
|
||||
]
|
||||
] as ModeSwitchOption<T>[]
|
||||
const activeIndex = Math.max(
|
||||
0,
|
||||
finalOptions.findIndex((item) => item.value === value)
|
||||
|
|
@ -27,7 +43,7 @@ function ModeSwitch({
|
|||
style={{
|
||||
'--option-count': String(finalOptions.length),
|
||||
'--active-index': String(activeIndex),
|
||||
}}
|
||||
} as React.CSSProperties}
|
||||
>
|
||||
<span className="mode-switch-thumb" aria-hidden="true" />
|
||||
{finalOptions.map((item) => (
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import { Layout, Avatar, Tooltip } from 'antd';
|
||||
import { keyboardActivation, textForAriaLabel } from '@/utils/a11yActivation';
|
||||
import {
|
||||
LogoutOutlined,
|
||||
QuestionCircleOutlined,
|
||||
|
|
@ -10,6 +12,40 @@ import './ModernSidebar.css';
|
|||
|
||||
const { Sider } = Layout;
|
||||
|
||||
export interface SidebarMenuItem {
|
||||
key: string;
|
||||
label: ReactNode;
|
||||
icon?: ReactNode;
|
||||
path?: string | null;
|
||||
}
|
||||
|
||||
export interface SidebarMenuGroup {
|
||||
title?: string;
|
||||
items: SidebarMenuItem[];
|
||||
}
|
||||
|
||||
export interface SidebarUser {
|
||||
name?: string | null;
|
||||
role?: string | null;
|
||||
avatar?: string | null;
|
||||
}
|
||||
|
||||
interface ModernSidebarProps {
|
||||
logo?: ReactNode;
|
||||
menuGroups?: SidebarMenuGroup[];
|
||||
activeKey?: string;
|
||||
onNavigate?: (key: string, item: SidebarMenuItem) => void;
|
||||
user?: SidebarUser | null;
|
||||
onLogout?: () => void;
|
||||
onProfileClick?: () => void;
|
||||
collapsed?: boolean;
|
||||
onCollapse?: (collapsed: boolean) => void;
|
||||
width?: number;
|
||||
collapsedWidth?: number;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
|
||||
const ModernSidebar = ({
|
||||
logo,
|
||||
menuGroups = [],
|
||||
|
|
@ -24,24 +60,33 @@ const ModernSidebar = ({
|
|||
collapsedWidth = 80,
|
||||
className = '',
|
||||
style = {}
|
||||
}) => {
|
||||
|
||||
const handleItemClick = (item) => {
|
||||
}: ModernSidebarProps) => {
|
||||
|
||||
const handleItemClick = (item: SidebarMenuItem) => {
|
||||
if (onNavigate) {
|
||||
onNavigate(item.key, item);
|
||||
}
|
||||
};
|
||||
|
||||
const renderMenuItem = (item) => {
|
||||
/**
|
||||
* 菜单项是自定义 div(不是原生 button),必须补齐键盘语义,
|
||||
* 否则全站主导航对键盘用户完全不可达(NEX §5.11)。
|
||||
* 只加属性、不改标签与样式,视觉与鼠标行为保持原样。
|
||||
*/
|
||||
const renderMenuItem = (item: SidebarMenuItem) => {
|
||||
const isActive = activeKey === item.key;
|
||||
|
||||
const activate = () => handleItemClick(item);
|
||||
|
||||
// 如果是折叠状态,只显示图标,并使用Tooltip
|
||||
if (collapsed) {
|
||||
return (
|
||||
<Tooltip title={item.label} placement="right" key={item.key}>
|
||||
<div
|
||||
<div
|
||||
className={`modern-sidebar-item collapsed ${isActive ? 'active' : ''}`}
|
||||
onClick={() => handleItemClick(item)}
|
||||
aria-label={textForAriaLabel(item.label)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
onClick={activate}
|
||||
{...keyboardActivation(activate)}
|
||||
>
|
||||
<div className="item-icon">{item.icon}</div>
|
||||
</div>
|
||||
|
|
@ -50,16 +95,18 @@ const ModernSidebar = ({
|
|||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
<div
|
||||
key={item.key}
|
||||
className={`modern-sidebar-item ${isActive ? 'active' : ''}`}
|
||||
onClick={() => handleItemClick(item)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
onClick={activate}
|
||||
{...keyboardActivation(activate)}
|
||||
>
|
||||
<div className="item-content">
|
||||
<div className="item-icon">{item.icon}</div>
|
||||
<span className="item-label">{item.label}</span>
|
||||
</div>
|
||||
{isActive && <RightOutlined className="item-arrow" />}
|
||||
{isActive && <RightOutlined className="item-arrow" aria-hidden />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
@ -85,7 +132,7 @@ const ModernSidebar = ({
|
|||
onClick={() => onCollapse && onCollapse(!collapsed)}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
>
|
||||
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
|
||||
{collapsed ? <MenuUnfoldOutlined aria-hidden /> : <MenuFoldOutlined aria-hidden />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
|
@ -108,32 +155,35 @@ const ModernSidebar = ({
|
|||
{/* 帮助支持 */}
|
||||
{!collapsed && (
|
||||
<div className="footer-link">
|
||||
<QuestionCircleOutlined />
|
||||
<QuestionCircleOutlined aria-hidden />
|
||||
<span>帮助支持</span>
|
||||
</div>
|
||||
)}
|
||||
{collapsed && (
|
||||
<Tooltip title="帮助支持" placement="right">
|
||||
<button type="button" className="footer-icon-button">
|
||||
<QuestionCircleOutlined />
|
||||
<button type="button" className="footer-icon-button" aria-label="帮助支持">
|
||||
<QuestionCircleOutlined aria-hidden />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{collapsed && (
|
||||
<Tooltip title="退出登录" placement="right">
|
||||
<button type="button" className="footer-icon-button logout" onClick={onLogout}>
|
||||
<LogoutOutlined />
|
||||
<button type="button" className="footer-icon-button logout" onClick={onLogout} aria-label="退出登录">
|
||||
<LogoutOutlined aria-hidden />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{/* 用户卡片 */}
|
||||
<div className="user-card">
|
||||
<div
|
||||
className="user-info"
|
||||
<div
|
||||
className="user-info"
|
||||
onClick={onProfileClick}
|
||||
style={{ cursor: onProfileClick ? 'pointer' : 'default' }}
|
||||
{...(onProfileClick
|
||||
? { ...keyboardActivation(() => onProfileClick()), 'aria-label': '个人资料' }
|
||||
: {})}
|
||||
>
|
||||
<Avatar
|
||||
size={collapsed ? 32 : 40}
|
||||
|
|
@ -150,8 +200,8 @@ const ModernSidebar = ({
|
|||
)}
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<button type="button" className="logout-btn" onClick={onLogout} title="退出登录">
|
||||
<LogoutOutlined />
|
||||
<button type="button" className="logout-btn" onClick={onLogout} title="退出登录" aria-label="退出登录">
|
||||
<LogoutOutlined aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
import { useState, useMemo, useRef, useEffect, useCallback } from 'react'
|
||||
import { useState, useMemo, useRef, useEffect, useCallback, type RefObject } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Document, Page, pdfjs } from 'react-pdf'
|
||||
import { Button, Space, InputNumber, Spin, Tooltip } from 'antd'
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import {
|
||||
ZoomInOutlined,
|
||||
|
|
@ -18,14 +19,27 @@ import './VirtualPDFViewer.css'
|
|||
// 配置 PDF.js worker
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf-worker/pdf.worker.min.mjs'
|
||||
|
||||
function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false }) {
|
||||
const [numPages, setNumPages] = useState(null)
|
||||
interface VirtualPDFViewerProps {
|
||||
url: string
|
||||
filename?: string
|
||||
/** 把工具栏渲染到页面自身的标题栏里(Portal 目标) */
|
||||
toolbarTarget?: HTMLElement | null
|
||||
compactToolbar?: boolean
|
||||
}
|
||||
|
||||
interface PdfPageSize {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false }: VirtualPDFViewerProps) {
|
||||
const [numPages, setNumPages] = useState<number | null>(null)
|
||||
const [scale, setScale] = useState(1.0)
|
||||
const [pdfOriginalSize, setPdfOriginalSize] = useState({ width: 595, height: 842 }) // 默认 A4
|
||||
const [pdfOriginalSize, setPdfOriginalSize] = useState<PdfPageSize>({ width: 595, height: 842 }) // 默认 A4
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [visiblePages, setVisiblePages] = useState(new Set([1]))
|
||||
const containerRef = useRef(null)
|
||||
const pageRefs = useRef({})
|
||||
const [visiblePages, setVisiblePages] = useState<Set<number>>(new Set([1]))
|
||||
const containerRef: RefObject<HTMLDivElement> = useRef(null)
|
||||
const pageRefs = useRef<Record<number, HTMLDivElement | null>>({})
|
||||
|
||||
// 使用 useMemo 避免不必要的重新加载
|
||||
const fileConfig = useMemo(() => ({ url }), [url])
|
||||
|
|
@ -43,7 +57,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
return Math.ceil(pdfOriginalSize.height * scale) + 60
|
||||
}, [scale, pdfOriginalSize.height])
|
||||
|
||||
const onDocumentLoadError = (error) => {
|
||||
const onDocumentLoadError = (error: unknown) => {
|
||||
console.error('[PDF] Document load error:', error)
|
||||
Toast.error('PDF文件加载失败')
|
||||
}
|
||||
|
|
@ -74,7 +88,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
|
||||
|
||||
// Add buffer pages (2 before and 2 after)
|
||||
const newVisiblePages = new Set()
|
||||
const newVisiblePages = new Set<number>()
|
||||
for (let i = Math.max(1, firstVisiblePage - 2); i <= Math.min(numPages, lastVisiblePage + 2); i++) {
|
||||
newVisiblePages.add(i)
|
||||
}
|
||||
|
|
@ -83,7 +97,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
setCurrentPage(firstVisiblePage)
|
||||
}, [numPages, pageHeight])
|
||||
|
||||
const onDocumentLoadSuccess = useCallback(async (pdf) => {
|
||||
const onDocumentLoadSuccess = useCallback(async (pdf: PDFDocumentProxy) => {
|
||||
setNumPages(pdf.numPages)
|
||||
|
||||
try {
|
||||
|
|
@ -133,8 +147,8 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
setScale((prev) => Math.max(prev - 0.2, 0.5))
|
||||
}
|
||||
|
||||
const handlePageChange = (value) => {
|
||||
if (value >= 1 && value <= numPages && containerRef.current) {
|
||||
const handlePageChange = (value: number | null) => {
|
||||
if (value != null && numPages != null && value >= 1 && value <= numPages && containerRef.current) {
|
||||
const scrollTop = (value - 1) * pageHeight
|
||||
const container = containerRef.current
|
||||
container.scrollTo({ top: scrollTop, behavior: 'auto' })
|
||||
|
|
@ -166,7 +180,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
<Space size={4}>
|
||||
<Tooltip title="回到顶部">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollToTop}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -176,7 +190,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
</Tooltip>
|
||||
<Tooltip title="下载PDF">
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleDownload}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -188,17 +202,18 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
) : (
|
||||
<div className="pdf-toolbar">
|
||||
<Space>
|
||||
<Button icon={<ZoomOutOutlined />} onClick={zoomOut} size="small">
|
||||
<Button icon={<ZoomOutOutlined aria-hidden />} onClick={zoomOut} size="small">
|
||||
缩小
|
||||
</Button>
|
||||
<span className="pdf-toolbar-scale">
|
||||
{Math.round(scale * 100)}%
|
||||
</span>
|
||||
<Button icon={<ZoomInOutlined />} onClick={zoomIn} size="small">
|
||||
<Button icon={<ZoomInOutlined aria-hidden />} onClick={zoomIn} size="small">
|
||||
放大
|
||||
</Button>
|
||||
<Button
|
||||
icon={<LeftOutlined />}
|
||||
icon={<LeftOutlined aria-hidden />}
|
||||
aria-label="上一页"
|
||||
onClick={() => handlePageChange(currentPage - 1)}
|
||||
disabled={currentPage <= 1}
|
||||
size="small"
|
||||
|
|
@ -217,14 +232,15 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
</Button>
|
||||
</Space.Compact>
|
||||
<Button
|
||||
icon={<RightOutlined />}
|
||||
icon={<RightOutlined aria-hidden />}
|
||||
aria-label="下一页"
|
||||
onClick={() => handlePageChange(currentPage + 1)}
|
||||
disabled={currentPage >= (numPages || 0)}
|
||||
size="small"
|
||||
/>
|
||||
<span className="pdf-toolbar-divider" />
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollToTop}
|
||||
size="small"
|
||||
disabled={currentPage === 1}
|
||||
|
|
@ -232,7 +248,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
回到顶部
|
||||
</Button>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleDownload}
|
||||
size="small"
|
||||
>
|
||||
|
|
@ -270,7 +286,7 @@ function VirtualPDFViewer({ url, filename, toolbarTarget, compactToolbar = false
|
|||
return (
|
||||
<div
|
||||
key={pageNumber}
|
||||
ref={el => pageRefs.current[pageNumber] = el}
|
||||
ref={(el) => { pageRefs.current[pageNumber] = el }}
|
||||
className="pdf-page-wrapper"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
|
|
@ -1,20 +1,23 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { ArrowLeftOutlined } from '@ant-design/icons'
|
||||
import './PageHeader.css'
|
||||
|
||||
function PageHeader({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
showBack = false,
|
||||
onBack,
|
||||
extra
|
||||
}) {
|
||||
interface PageHeaderProps {
|
||||
title: ReactNode
|
||||
description?: ReactNode
|
||||
icon?: ReactNode
|
||||
showBack?: boolean
|
||||
onBack?: () => void
|
||||
extra?: ReactNode
|
||||
}
|
||||
|
||||
function PageHeader({ title, description, icon, showBack = false, onBack, extra }: PageHeaderProps) {
|
||||
return (
|
||||
<div className="page-header-standard">
|
||||
<div className="page-header-main">
|
||||
{showBack && (
|
||||
<button className="back-button" onClick={onBack}>
|
||||
<ArrowLeftOutlined />
|
||||
<button type="button" className="back-button" onClick={onBack} aria-label="返回上一页">
|
||||
<ArrowLeftOutlined aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
<div className="page-header-content">
|
||||
|
|
@ -1,11 +1,18 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { Skeleton, Spin } from 'antd'
|
||||
import './PageLoading.css'
|
||||
|
||||
interface PageLoadingProps {
|
||||
tip?: string
|
||||
spinning?: boolean
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面级加载态:路由懒加载(Suspense fallback)与整页数据加载共用,
|
||||
* 保证所有页面的"加载中"表现一致。
|
||||
*/
|
||||
export default function PageLoading({ tip = '加载中...', spinning = true, children }) {
|
||||
export default function PageLoading({ tip = '加载中...', spinning = true, children }: PageLoadingProps) {
|
||||
if (!spinning) return children ?? null
|
||||
|
||||
return (
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
import { useState, useMemo, useRef, useEffect } from 'react'
|
||||
import { Menu, Tooltip, Dropdown, Empty } from 'antd'
|
||||
import { useState, useMemo, useRef, useEffect, type ReactNode } from 'react'
|
||||
import { Menu, Tooltip, Dropdown, Empty, type MenuProps } from 'antd'
|
||||
import type { MenuRef as RcMenuRef } from 'rc-menu'
|
||||
import type { MenuRef as AntdMenuRef } from 'antd/es/menu'
|
||||
import {
|
||||
FolderOutlined,
|
||||
FolderOpenOutlined,
|
||||
|
|
@ -9,6 +11,7 @@ import {
|
|||
ShareAltOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { collectParentKeys, findNodeByKey } from '@/utils/treeUtils'
|
||||
import type { FileTreeNode } from '@/types/api'
|
||||
import './ProjectFileTree.css'
|
||||
|
||||
/**
|
||||
|
|
@ -38,9 +41,17 @@ import './ProjectFileTree.css'
|
|||
* - className: 追加到菜单根节点的 class
|
||||
*/
|
||||
|
||||
type MenuItem = NonNullable<MenuProps['items']>[number]
|
||||
|
||||
interface OverflowTooltipProps {
|
||||
title: ReactNode
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
// 仅当文本被省略(显示不全)时才显示 Tooltip,避免冗余提示
|
||||
function OverflowTooltip({ title, className, children }) {
|
||||
const textRef = useRef(null)
|
||||
function OverflowTooltip({ title, className, children }: OverflowTooltipProps) {
|
||||
const textRef = useRef<HTMLSpanElement>(null)
|
||||
const [overflow, setOverflow] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -63,6 +74,30 @@ function OverflowTooltip({ title, className, children }) {
|
|||
)
|
||||
}
|
||||
|
||||
interface ProjectFileTreeProps {
|
||||
/** 树节点数组(可传过滤后的数据) */
|
||||
treeData: FileTreeNode[]
|
||||
/** 当前选中的节点 key(高亮 + 自动聚焦) */
|
||||
selectedKey?: string | null
|
||||
/** 目录展开状态 */
|
||||
openKeys: string[]
|
||||
onOpenChange?: (keys: string[]) => void
|
||||
/** 菜单项点击(文件夹选中 / 文件打开) */
|
||||
onSelect?: MenuProps['onClick']
|
||||
/** 目录标题点击 */
|
||||
onSelectFolder: (key: string) => void
|
||||
/** 传入则启用右键菜单 */
|
||||
getContextMenuItems?: (node: FileTreeNode) => MenuProps['items'] | null
|
||||
/** 切换文件夹时收拢其它目录 */
|
||||
collapseOnSelect?: boolean
|
||||
/** 是否显示「已分享」角标 */
|
||||
showShareIcon?: boolean
|
||||
/** 是否显示非 md/pdf 文件 */
|
||||
showOtherFiles?: boolean
|
||||
emptyText?: ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
export default function ProjectFileTree({
|
||||
treeData,
|
||||
selectedKey,
|
||||
|
|
@ -76,21 +111,23 @@ export default function ProjectFileTree({
|
|||
showOtherFiles = false,
|
||||
emptyText = '暂无文档',
|
||||
className = '',
|
||||
}) {
|
||||
const menuRef = useRef(null)
|
||||
const prevSelectedKeyRef = useRef(null)
|
||||
}: ProjectFileTreeProps) {
|
||||
// antd 的 MenuRef 声明为 { menu, focus },但它把 ref 原样转发给 rc-menu,
|
||||
// 运行时实际拿到的是 rc-menu 的 { list, focus },因此按 rc-menu 的类型取用。
|
||||
const menuRef = useRef<RcMenuRef | null>(null)
|
||||
const prevSelectedKeyRef = useRef<string | null | undefined>(null)
|
||||
const pendingFocusRef = useRef(false)
|
||||
|
||||
// 根据文件类型返回统一图标(PDF 红色、md 文本、其余通用)
|
||||
const getNodeIcon = (node) => {
|
||||
const getNodeIcon = (node: FileTreeNode) => {
|
||||
const lower = node.title.toLowerCase()
|
||||
if (lower.endsWith('.pdf')) return <FilePdfOutlined style={{ color: '#f5222d' }} />
|
||||
if (lower.endsWith('.md')) return <FileTextOutlined />
|
||||
return <FileOutlined />
|
||||
if (lower.endsWith('.pdf')) return <FilePdfOutlined aria-hidden style={{ color: 'var(--color-pdf)' }} />
|
||||
if (lower.endsWith('.md')) return <FileTextOutlined aria-hidden />
|
||||
return <FileOutlined aria-hidden />
|
||||
}
|
||||
|
||||
// 构建统一的行标签(省略检测 + 分享角标 + 可选右键菜单)
|
||||
const buildLabel = (node) => {
|
||||
const buildLabel = (node: FileTreeNode) => {
|
||||
const isPdf = node.title.toLowerCase().endsWith('.pdf')
|
||||
const titleText = isPdf ? node.title : node.title.replace(/.md$/i, '')
|
||||
|
||||
|
|
@ -98,7 +135,7 @@ export default function ProjectFileTree({
|
|||
<span className="file-tree-label">
|
||||
<OverflowTooltip title={node.title} className="file-tree-label-text">{titleText}</OverflowTooltip>
|
||||
{showShareIcon && node.is_shared && (
|
||||
<ShareAltOutlined className="file-tree-share-icon" title="已分享" />
|
||||
<ShareAltOutlined aria-label="已分享" className="file-tree-share-icon" title="已分享" />
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
|
|
@ -109,8 +146,8 @@ export default function ProjectFileTree({
|
|||
: label
|
||||
}
|
||||
|
||||
const convertTreeToMenuItems = (nodes) => {
|
||||
return nodes.map((node) => {
|
||||
const convertTreeToMenuItems = (nodes: FileTreeNode[]): MenuItem[] => {
|
||||
return nodes.map((node): MenuItem | null => {
|
||||
const label = buildLabel(node)
|
||||
|
||||
if (!node.isLeaf) {
|
||||
|
|
@ -118,7 +155,7 @@ export default function ProjectFileTree({
|
|||
return {
|
||||
key: node.key,
|
||||
label,
|
||||
icon: isOpen ? <FolderOpenOutlined /> : <FolderOutlined />,
|
||||
icon: isOpen ? <FolderOpenOutlined aria-hidden /> : <FolderOutlined aria-hidden />,
|
||||
children: node.children ? convertTreeToMenuItems(node.children) : [],
|
||||
className: selectedKey === node.key ? 'file-tree-folder-selected' : '',
|
||||
onTitleClick: () => onSelectFolder(node.key),
|
||||
|
|
@ -166,7 +203,7 @@ export default function ProjectFileTree({
|
|||
if (!pendingFocusRef.current) return
|
||||
pendingFocusRef.current = false
|
||||
// rc-menu 的 ref 是 { list, focus, ... },根 DOM 在 .list 上
|
||||
const root = menuRef.current && (menuRef.current.list || menuRef.current)
|
||||
const root = menuRef.current?.list
|
||||
if (!root || typeof root.querySelector !== 'function') return
|
||||
const el = root.querySelector(
|
||||
'.ant-menu-item-selected, .ant-menu-submenu-selected > .ant-menu-submenu-title'
|
||||
|
|
@ -184,7 +221,7 @@ export default function ProjectFileTree({
|
|||
|
||||
return (
|
||||
<Menu
|
||||
ref={menuRef}
|
||||
ref={menuRef as unknown as React.Ref<AntdMenuRef>}
|
||||
mode="inline"
|
||||
selectedKeys={selectedKey ? [selectedKey] : []}
|
||||
openKeys={openKeys}
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { Navigate, useLocation } from 'react-router-dom'
|
||||
import { getAccessToken } from '@/utils/authStorage'
|
||||
|
||||
function ProtectedRoute({ children }) {
|
||||
function ProtectedRoute({ children }: { children: ReactNode }) {
|
||||
const location = useLocation()
|
||||
const token = getAccessToken()
|
||||
|
||||
|
|
@ -10,7 +11,7 @@ function ProtectedRoute({ children }) {
|
|||
return <Navigate to={`/login?redirect=${returnTo}`} replace />
|
||||
}
|
||||
|
||||
return children
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default ProtectedRoute
|
||||
|
|
@ -1,15 +1,67 @@
|
|||
/* 统计卡片 */
|
||||
.stat-card {
|
||||
padding: 16px;
|
||||
background: var(--card-bg);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
min-height: clamp(132px, 10vw, 148px);
|
||||
padding: clamp(18px, 1.4vw, 22px);
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(circle at 90% 0%, color-mix(in srgb, var(--stat-accent, var(--color-primary)) 15%, transparent) 0%, transparent 48%),
|
||||
linear-gradient(145deg, color-mix(in srgb, var(--stat-accent, var(--color-primary)) 4%, var(--card-bg)) 0%, var(--card-bg) 58%);
|
||||
border: 1px solid color-mix(in srgb, var(--stat-accent, var(--color-primary)) 22%, var(--border-color));
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, var(--text-color-inverse) 10%, transparent), var(--shadow-1);
|
||||
transition: border-color var(--transition-base), box-shadow var(--transition-base);
|
||||
}
|
||||
|
||||
.stat-card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -64px;
|
||||
bottom: -108px;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
z-index: 0;
|
||||
border: 1px solid color-mix(in srgb, var(--stat-accent, var(--color-primary)) 16%, transparent);
|
||||
border-radius: 50%;
|
||||
box-shadow: inset 0 0 0 34px color-mix(in srgb, var(--stat-accent, var(--color-primary)) 3%, transparent);
|
||||
opacity: 0.72;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
border-color: var(--border-color-strong);
|
||||
box-shadow: var(--panel-shadow);
|
||||
border-color: color-mix(in srgb, var(--stat-accent, var(--color-primary)) 40%, var(--border-color));
|
||||
box-shadow: var(--shadow-2);
|
||||
}
|
||||
|
||||
.stat-card-backdrop-icon {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: -18px;
|
||||
z-index: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.32em;
|
||||
height: 1.32em;
|
||||
font-size: clamp(88px, 8vw, 116px);
|
||||
line-height: 1;
|
||||
color: var(--stat-accent, var(--color-primary));
|
||||
border: 1px solid color-mix(in srgb, var(--stat-accent, var(--color-primary)) 18%, transparent);
|
||||
border-radius: 30px;
|
||||
background: linear-gradient(135deg, color-mix(in srgb, var(--stat-accent, var(--color-primary)) 12%, transparent), color-mix(in srgb, var(--stat-accent, var(--color-primary)) 3%, transparent));
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, var(--text-color-inverse) 12%, transparent);
|
||||
transform: translateY(-50%) rotate(-8deg);
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.stat-card-backdrop-icon > .anticon,
|
||||
.stat-card-backdrop-icon > svg {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
font-size: 1em;
|
||||
opacity: 0.24;
|
||||
}
|
||||
|
||||
/* 一列布局(默认) */
|
||||
|
|
@ -22,6 +74,7 @@
|
|||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: clamp(118px, 9vw, 132px);
|
||||
}
|
||||
|
||||
.stat-card.stat-card-row .stat-card-header {
|
||||
|
|
@ -43,26 +96,28 @@
|
|||
|
||||
/* 卡片头部 */
|
||||
.stat-card-header {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
min-height: 22px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.stat-card-title {
|
||||
font-size: 13px;
|
||||
color: var(--text-color-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.stat-card-icon {
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: clamp(15px, 1vw, 17px);
|
||||
color: var(--text-color);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
|
||||
/* 卡片内容 */
|
||||
.stat-card-body {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
|
|
@ -70,15 +125,18 @@
|
|||
}
|
||||
|
||||
.stat-card-value {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
font-size: clamp(36px, 3vw, 44px);
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
letter-spacing: -1.2px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.stat-card-suffix {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
margin-left: 4px;
|
||||
font-size: clamp(16px, 1.2vw, 18px);
|
||||
font-weight: 600;
|
||||
margin-left: 5px;
|
||||
color: var(--text-color-secondary);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,78 +0,0 @@
|
|||
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons'
|
||||
import './StatCard.css'
|
||||
|
||||
/**
|
||||
* 统计卡片组件
|
||||
* @param {Object} props
|
||||
* @param {string} props.title - 卡片标题
|
||||
* @param {number|string} props.value - 统计值
|
||||
* @param {ReactNode} props.icon - 图标
|
||||
* @param {string} props.color - 主题颜色,默认 'blue'
|
||||
* @param {Object} props.trend - 趋势信息 { value: number, direction: 'up' | 'down' }
|
||||
* @param {string} props.suffix - 后缀单位
|
||||
* @param {string} props.layout - 布局模式: 'column' | 'row',默认 'column'(一列)
|
||||
* @param {string} props.gridColumn - 网格列跨度,如 '1 / -1' 表示占满整行
|
||||
* @param {string} props.className - 自定义类名
|
||||
* @param {Function} props.onClick - 点击事件处理函数
|
||||
* @param {Object} props.style - 自定义样式对象
|
||||
*/
|
||||
function StatCard({
|
||||
title,
|
||||
value,
|
||||
icon,
|
||||
color = 'blue',
|
||||
trend,
|
||||
suffix = '',
|
||||
layout = 'column',
|
||||
gridColumn,
|
||||
className = '',
|
||||
onClick,
|
||||
style: customStyle = {},
|
||||
}) {
|
||||
const colorMap = {
|
||||
blue: 'var(--color-primary)',
|
||||
green: 'var(--color-success)',
|
||||
orange: 'var(--color-warning)',
|
||||
red: 'var(--color-danger)',
|
||||
purple: '#722ed1',
|
||||
gray: '#8c8c8c',
|
||||
}
|
||||
|
||||
const themeColor = colorMap[color] || color
|
||||
|
||||
const style = {
|
||||
...(gridColumn ? { gridColumn } : {}),
|
||||
...customStyle,
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`stat-card stat-card-${layout} ${className}`} style={style} onClick={onClick}>
|
||||
<div className="stat-card-header">
|
||||
<span className="stat-card-title">{title}</span>
|
||||
{icon && (
|
||||
<span className="stat-card-icon" style={{ color: themeColor }}>
|
||||
{icon}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="stat-card-body">
|
||||
<div className="stat-card-value" style={{ color: themeColor }}>
|
||||
{value}
|
||||
{suffix && <span className="stat-card-suffix">{suffix}</span>}
|
||||
</div>
|
||||
|
||||
{trend && (
|
||||
<div
|
||||
className={`stat-card-trend ${trend.direction === 'up' ? 'trend-up' : 'trend-down'}`}
|
||||
>
|
||||
{trend.direction === 'up' ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
|
||||
<span>{Math.abs(trend.value)}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StatCard
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons'
|
||||
import './StatCard.css'
|
||||
import { keyboardActivation } from '@/utils/a11yActivation'
|
||||
|
||||
type StatColor = 'blue' | 'green' | 'orange' | 'red' | 'purple' | 'gray'
|
||||
|
||||
interface StatCardTrend {
|
||||
value: number
|
||||
direction: 'up' | 'down'
|
||||
}
|
||||
|
||||
interface StatCardProps {
|
||||
title: ReactNode
|
||||
value: number | string
|
||||
icon?: ReactNode
|
||||
/** 主题颜色;也允许直接传自定义色值 */
|
||||
color?: StatColor | string
|
||||
trend?: StatCardTrend
|
||||
suffix?: string
|
||||
layout?: 'column' | 'row'
|
||||
/** 网格列跨度,如 '1 / -1' 表示占满整行 */
|
||||
gridColumn?: string
|
||||
className?: string
|
||||
onClick?: () => void
|
||||
style?: CSSProperties
|
||||
}
|
||||
|
||||
const COLOR_MAP: Record<StatColor, string> = {
|
||||
blue: 'var(--color-primary)',
|
||||
green: 'var(--color-success)',
|
||||
orange: 'var(--color-warning)',
|
||||
red: 'var(--color-danger)',
|
||||
purple: 'var(--color-stat-purple)',
|
||||
gray: 'var(--color-stat-gray)',
|
||||
}
|
||||
|
||||
function StatCard({
|
||||
title,
|
||||
value,
|
||||
icon,
|
||||
color = 'blue',
|
||||
trend,
|
||||
suffix = '',
|
||||
layout = 'column',
|
||||
gridColumn,
|
||||
className = '',
|
||||
onClick,
|
||||
style: customStyle = {},
|
||||
}: StatCardProps) {
|
||||
const themeColor = COLOR_MAP[color as StatColor] || color
|
||||
|
||||
const style: CSSProperties & { '--stat-accent'?: string } = {
|
||||
'--stat-accent': themeColor,
|
||||
...(gridColumn ? { gridColumn } : {}),
|
||||
...customStyle,
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`stat-card stat-card-${layout} ${className}`}
|
||||
style={style}
|
||||
onClick={onClick}
|
||||
// 只有真的可点时才声明按钮语义,否则它只是普通展示卡片
|
||||
{...(onClick ? keyboardActivation(onClick) : {})}
|
||||
>
|
||||
{icon && (
|
||||
<span className="stat-card-backdrop-icon" aria-hidden="true">
|
||||
{icon}
|
||||
</span>
|
||||
)}
|
||||
<div className="stat-card-header">
|
||||
<span className="stat-card-title">{title}</span>
|
||||
</div>
|
||||
|
||||
<div className="stat-card-body">
|
||||
<div className="stat-card-value">
|
||||
{value}
|
||||
{suffix && <span className="stat-card-suffix">{suffix}</span>}
|
||||
</div>
|
||||
|
||||
{trend && (
|
||||
<div
|
||||
className={`stat-card-trend ${trend.direction === 'up' ? 'trend-up' : 'trend-down'}`}
|
||||
>
|
||||
{trend.direction === 'up' ? (
|
||||
<ArrowUpOutlined
|
||||
aria-label="上升" />
|
||||
) : (
|
||||
<ArrowDownOutlined
|
||||
aria-label="下降" />
|
||||
)}
|
||||
<span>{Math.abs(trend.value)}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StatCard
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
InfoCircleOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { getFeedbackApi } from '@/components/Feedback/feedbackApi'
|
||||
|
||||
/**
|
||||
* 标准反馈组件(全站唯一入口)
|
||||
*
|
||||
* - 通知统一从右上角滑出,默认 3 秒后消失(配置见 App.jsx 的 <App notification>)
|
||||
* - 内部走 AntD App 上下文实例,因此自动继承明暗主题与圆角等设计规范
|
||||
* - 二次确认统一用 Toast.confirm(),不要再用 Modal.confirm 静态方法
|
||||
*/
|
||||
|
||||
let muteErrorsUntil = 0
|
||||
|
||||
function shouldMuteError() {
|
||||
return Date.now() < muteErrorsUntil
|
||||
}
|
||||
|
||||
const notificationStyle = {
|
||||
borderRadius: 'var(--radius-md)',
|
||||
boxShadow: 'var(--shadow-3)',
|
||||
}
|
||||
|
||||
const ICONS = {
|
||||
success: <CheckCircleOutlined style={{ color: 'var(--color-success)' }} />,
|
||||
error: <CloseCircleOutlined style={{ color: 'var(--color-danger)' }} />,
|
||||
warning: <ExclamationCircleOutlined style={{ color: 'var(--color-warning)' }} />,
|
||||
info: <InfoCircleOutlined style={{ color: 'var(--color-primary)' }} />,
|
||||
}
|
||||
|
||||
const open = (type, message, description, duration) => {
|
||||
getFeedbackApi().notification[type]({
|
||||
message,
|
||||
description,
|
||||
duration,
|
||||
icon: ICONS[type],
|
||||
style: notificationStyle,
|
||||
})
|
||||
}
|
||||
|
||||
const Toast = {
|
||||
/** 短时间内抑制错误/警告提示,用于批量操作失败刷屏的场景 */
|
||||
muteErrors: (durationMs = 2000) => {
|
||||
muteErrorsUntil = Date.now() + durationMs
|
||||
},
|
||||
|
||||
/** 成功通知 @param {string} message @param {string} [description] @param {number} [duration] 秒 */
|
||||
success: (message, description = '', duration = 3) => open('success', message, description, duration),
|
||||
|
||||
/** 错误通知(默认受 muteErrors 抑制) */
|
||||
error: (message, description = '', duration = 3, options = {}) => {
|
||||
if (!options.force && shouldMuteError()) return
|
||||
open('error', message, description, duration)
|
||||
},
|
||||
|
||||
/** 警告通知(默认受 muteErrors 抑制) */
|
||||
warning: (message, description = '', duration = 3, options = {}) => {
|
||||
if (!options.force && shouldMuteError()) return
|
||||
open('warning', message, description, duration)
|
||||
},
|
||||
|
||||
/** 信息通知 */
|
||||
info: (message, description = '', duration = 3) => open('info', message, description, duration),
|
||||
|
||||
/** 自定义通知(透传 AntD notification 配置) */
|
||||
custom: (config) => {
|
||||
getFeedbackApi().notification.open({
|
||||
...config,
|
||||
style: { ...notificationStyle, ...config.style },
|
||||
})
|
||||
},
|
||||
|
||||
/** 轻提示(顶部居中的 message),用于无需用户处理的即时反馈 */
|
||||
toast: (content, type = 'info', duration = 2) => {
|
||||
getFeedbackApi().message[type](content, duration)
|
||||
},
|
||||
|
||||
/**
|
||||
* 二次确认对话框(危险操作请传 okButtonProps={{ danger: true }})
|
||||
* @returns AntD ModalConfirmHandler
|
||||
*/
|
||||
confirm: (config) =>
|
||||
getFeedbackApi().modal.confirm({
|
||||
okText: '确定',
|
||||
cancelText: '取消',
|
||||
...config,
|
||||
}),
|
||||
}
|
||||
|
||||
export default Toast
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
InfoCircleOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import type { ArgsProps as NotificationArgsProps } from 'antd/es/notification/interface'
|
||||
import type { ModalFuncProps } from 'antd/es/modal/interface'
|
||||
import type { ReactNode } from 'react'
|
||||
import { getFeedbackApi } from '@/components/Feedback/feedbackApi'
|
||||
|
||||
/**
|
||||
* 标准反馈组件(全站唯一入口)
|
||||
*
|
||||
* - 通知统一从右上角滑出,默认 3 秒后消失(配置见 App.tsx 的 <App notification>)
|
||||
* - 内部走 AntD App 上下文实例,因此自动继承明暗主题与圆角等设计规范
|
||||
* - 二次确认统一用 Toast.confirm(),不要再用 Modal.confirm 静态方法
|
||||
*/
|
||||
|
||||
type NotificationType = 'success' | 'error' | 'warning' | 'info'
|
||||
type MessageType = 'success' | 'error' | 'warning' | 'info' | 'loading'
|
||||
|
||||
interface ForceOptions {
|
||||
/** 忽略 muteErrors 抑制窗口,始终展示(如登录态失效) */
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
let muteErrorsUntil = 0
|
||||
|
||||
function shouldMuteError() {
|
||||
return Date.now() < muteErrorsUntil
|
||||
}
|
||||
|
||||
const notificationStyle: React.CSSProperties = {
|
||||
borderRadius: 'var(--radius-md)',
|
||||
boxShadow: 'var(--shadow-3)',
|
||||
}
|
||||
|
||||
const ICONS: Record<NotificationType, ReactNode> = {
|
||||
success: <CheckCircleOutlined aria-hidden style={{ color: 'var(--color-success)' }} />,
|
||||
error: <CloseCircleOutlined aria-hidden style={{ color: 'var(--color-danger)' }} />,
|
||||
warning: <ExclamationCircleOutlined aria-hidden style={{ color: 'var(--color-warning)' }} />,
|
||||
info: <InfoCircleOutlined aria-hidden style={{ color: 'var(--color-primary)' }} />,
|
||||
}
|
||||
|
||||
const open = (
|
||||
type: NotificationType,
|
||||
message: ReactNode,
|
||||
description: ReactNode,
|
||||
duration: number,
|
||||
) => {
|
||||
getFeedbackApi().notification[type]({
|
||||
message,
|
||||
description,
|
||||
duration,
|
||||
icon: ICONS[type],
|
||||
style: notificationStyle,
|
||||
})
|
||||
}
|
||||
|
||||
const Toast = {
|
||||
/** 短时间内抑制错误/警告提示,用于批量操作失败刷屏的场景 */
|
||||
muteErrors: (durationMs = 2000) => {
|
||||
muteErrorsUntil = Date.now() + durationMs
|
||||
},
|
||||
|
||||
/** 成功通知 */
|
||||
success: (message: ReactNode, description: ReactNode = '', duration = 3) =>
|
||||
open('success', message, description, duration),
|
||||
|
||||
/** 错误通知(默认受 muteErrors 抑制) */
|
||||
error: (message: ReactNode, description: ReactNode = '', duration = 3, options: ForceOptions = {}) => {
|
||||
if (!options.force && shouldMuteError()) return
|
||||
open('error', message, description, duration)
|
||||
},
|
||||
|
||||
/** 警告通知(默认受 muteErrors 抑制) */
|
||||
warning: (message: ReactNode, description: ReactNode = '', duration = 3, options: ForceOptions = {}) => {
|
||||
if (!options.force && shouldMuteError()) return
|
||||
open('warning', message, description, duration)
|
||||
},
|
||||
|
||||
/** 信息通知 */
|
||||
info: (message: ReactNode, description: ReactNode = '', duration = 3) =>
|
||||
open('info', message, description, duration),
|
||||
|
||||
/** 自定义通知(透传 AntD notification 配置) */
|
||||
custom: (config: Omit<NotificationArgsProps, 'type'> & { type?: NotificationType }) => {
|
||||
getFeedbackApi().notification.open({
|
||||
...config,
|
||||
style: { ...notificationStyle, ...config.style },
|
||||
})
|
||||
},
|
||||
|
||||
/** 轻提示(顶部居中的 message),用于无需用户处理的即时反馈 */
|
||||
toast: (content: ReactNode, type: MessageType = 'info', duration = 2) => {
|
||||
getFeedbackApi().message[type](content, duration)
|
||||
},
|
||||
|
||||
/** 二次确认对话框(危险操作请传 okButtonProps={{ danger: true }}) */
|
||||
confirm: (config: ModalFuncProps) =>
|
||||
getFeedbackApi().modal.confirm({
|
||||
okText: '确定',
|
||||
cancelText: '取消',
|
||||
...config,
|
||||
}),
|
||||
}
|
||||
|
||||
export default Toast
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
import './index.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
const rootElement = document.getElementById('root')
|
||||
if (!rootElement) {
|
||||
throw new Error('缺少 #root 挂载节点')
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(rootElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
|
@ -1,4 +1,10 @@
|
|||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ChangeEvent as ReactChangeEvent,
|
||||
} from 'react'
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import {
|
||||
Avatar,
|
||||
|
|
@ -18,6 +24,7 @@ import {
|
|||
} from 'antd'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { useImeSafeEnter } from '@/utils/ime'
|
||||
import { keyboardActivation } from '@/utils/a11yActivation'
|
||||
import {
|
||||
FolderOutlined,
|
||||
EditOutlined,
|
||||
|
|
@ -42,17 +49,65 @@ import remarkGfm from 'remark-gfm'
|
|||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import 'highlight.js/styles/github.css'
|
||||
import type { Element as HastElement, ElementContent, Root as HastRoot, RootContent } from 'hast'
|
||||
import { createChatSession, deleteChatMessage, deleteChatSession, getChatMessages, getChatSessions, markMessageInterrupted, searchChatMessages, sendChatMessageStream, updateChatSessionTitle } from '@/api/chat'
|
||||
import { getMyProjects } from '@/api/project'
|
||||
import { getLLMModelConfigs } from '@/api/llmModelConfigs'
|
||||
import { getApiErrorMessage } from '@/utils/apiError'
|
||||
import type { TextAreaRef } from 'antd/es/input/TextArea'
|
||||
import type {
|
||||
ChatMessage,
|
||||
ChatReference,
|
||||
ChatSearchResult,
|
||||
ChatSession,
|
||||
CitationOccurrence,
|
||||
LLMModelConfig,
|
||||
ProjectListItem,
|
||||
ThinkingLogEntry,
|
||||
} from '@/types/api'
|
||||
import './Chat.css'
|
||||
import { clearInputIcon, decorativeAlertIcon } from '@/utils/antdA11y'
|
||||
|
||||
const { TextArea } = Input
|
||||
const { Text } = Typography
|
||||
|
||||
const CITATION_RE = /\[(\d+)\]/g
|
||||
|
||||
function formatDuration(ms) {
|
||||
/** 会话消息在页面上的展示状态:后端只有 pending/completed/interrupted/error,
|
||||
* thinking/streaming 由前端流式过程本地维护,completed 统一映射为 done。 */
|
||||
type ChatViewStatus = 'pending' | 'thinking' | 'streaming' | 'done' | 'interrupted' | 'error'
|
||||
|
||||
/**
|
||||
* 聊天消息的前端视图模型。
|
||||
*
|
||||
* 与后端 ChatMessage 不是一份数据:多了流式过程中的临时状态(thinkingStartedAt /
|
||||
* thinkingVisible / referencesVisible / error),id 也允许是未落库的临时串,
|
||||
* 因此单独建模,不与接口类型混用。
|
||||
*/
|
||||
interface ChatViewMessage {
|
||||
id: number | string
|
||||
role: string
|
||||
content: string
|
||||
created_at: string
|
||||
status: ChatViewStatus
|
||||
references?: ChatReference[]
|
||||
durationMs?: number | null
|
||||
thinkingLog?: ThinkingLogEntry[]
|
||||
/** 进入思考态的本地时间戳(ms),用于计时 */
|
||||
thinkingStartedAt?: number
|
||||
thinkingVisible?: boolean
|
||||
referencesVisible?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** 会话按日期分组后的侧边栏结构 */
|
||||
interface ChatSessionGroup {
|
||||
key: string
|
||||
label: string
|
||||
items: ChatSession[]
|
||||
}
|
||||
|
||||
function formatDuration(ms?: number | null) {
|
||||
if (ms == null) return ''
|
||||
const totalSeconds = Math.max(0, ms) / 1000
|
||||
if (totalSeconds < 60) return `${totalSeconds.toFixed(1)} 秒`
|
||||
|
|
@ -61,7 +116,7 @@ function formatDuration(ms) {
|
|||
return `${minutes} 分 ${seconds} 秒`
|
||||
}
|
||||
|
||||
function useElapsedTimer(startedAt, active) {
|
||||
function useElapsedTimer(startedAt?: number | null, active?: boolean) {
|
||||
const [now, setNow] = useState(Date.now())
|
||||
useEffect(() => {
|
||||
if (!active) return undefined
|
||||
|
|
@ -72,13 +127,23 @@ function useElapsedTimer(startedAt, active) {
|
|||
return active ? Math.max(0, now - (startedAt || now)) : null
|
||||
}
|
||||
|
||||
function ThinkingPanel({ active, log = [], startedAt, durationMs, status, visible, onToggle }) {
|
||||
interface ThinkingPanelProps {
|
||||
active?: boolean
|
||||
log?: ThinkingLogEntry[]
|
||||
startedAt?: number | null
|
||||
durationMs?: number | null
|
||||
status?: string
|
||||
visible?: boolean
|
||||
onToggle?: () => void
|
||||
}
|
||||
|
||||
function ThinkingPanel({ active, log = [], startedAt, durationMs, status, visible, onToggle }: ThinkingPanelProps) {
|
||||
const elapsed = useElapsedTimer(startedAt, active)
|
||||
if (active) {
|
||||
return (
|
||||
<div className="chat-thinking-panel active">
|
||||
<div className="chat-thinking-timer">
|
||||
<LoadingOutlined spin /> 思考中 · {formatDuration(elapsed)}
|
||||
<LoadingOutlined spin aria-hidden /> 思考中 · {formatDuration(elapsed)}
|
||||
</div>
|
||||
{log.length > 0 && (
|
||||
<div className="chat-thinking-log">
|
||||
|
|
@ -107,7 +172,7 @@ function ThinkingPanel({ active, log = [], startedAt, durationMs, status, visibl
|
|||
onClick={onToggle}
|
||||
aria-expanded={visible}
|
||||
>
|
||||
<DownOutlined rotate={visible ? 180 : 0} className="chat-thinking-chevron" />
|
||||
<DownOutlined aria-hidden rotate={visible ? 180 : 0} className="chat-thinking-chevron" />
|
||||
<span>思考过程</span>
|
||||
{status === 'interrupted' && <span className="chat-thinking-badge">已停止</span>}
|
||||
{hasDuration && <span className="chat-thinking-duration">· {formatDuration(durationMs)}</span>}
|
||||
|
|
@ -137,16 +202,21 @@ function ThinkingPanel({ active, log = [], startedAt, durationMs, status, visibl
|
|||
// 跳过 code/pre 节点,避免破坏代码块中的方括号内容。
|
||||
function rehypeCitationSup() {
|
||||
// 按引用编号统计出现次数,使同一编号的多处引用可以精确区分
|
||||
const occurrenceCounters = {}
|
||||
const walk = (node, inCode) => {
|
||||
const occurrenceCounters: Record<string, number> = {}
|
||||
// Root 与 Element 的 children 元素类型不同,读写统一按两者并集处理,只在写回处收窄一次
|
||||
type HastChild = ElementContent | RootContent
|
||||
|
||||
const walk = (node: HastElement | HastRoot, inCode: boolean) => {
|
||||
if (!node.children) return
|
||||
const nextChildren = []
|
||||
for (const child of node.children) {
|
||||
const childInCode = inCode || child.tagName === 'code' || child.tagName === 'pre'
|
||||
const children = node.children as HastChild[]
|
||||
const nextChildren: HastChild[] = []
|
||||
for (const child of children) {
|
||||
const childInCode = inCode
|
||||
|| (child.type === 'element' && (child.tagName === 'code' || child.tagName === 'pre'))
|
||||
if (child.type === 'text' && CITATION_RE.test(child.value)) {
|
||||
CITATION_RE.lastIndex = 0
|
||||
let lastPush = 0
|
||||
let match
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = CITATION_RE.exec(child.value)) !== null) {
|
||||
const citationId = match[1]
|
||||
// 即使标记位于代码块内也要计数,保持与后端按文本全文计数的顺序一致
|
||||
|
|
@ -178,12 +248,13 @@ function rehypeCitationSup() {
|
|||
nextChildren.push(child)
|
||||
}
|
||||
}
|
||||
node.children = nextChildren
|
||||
const target = node as HastElement
|
||||
target.children = nextChildren as ElementContent[]
|
||||
}
|
||||
return (tree) => walk(tree, false)
|
||||
return (tree: HastRoot) => walk(tree, false)
|
||||
}
|
||||
|
||||
function formatTime(value) {
|
||||
function formatTime(value?: string | null) {
|
||||
if (!value) return ''
|
||||
return new Date(value).toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
|
|
@ -193,14 +264,14 @@ function formatTime(value) {
|
|||
})
|
||||
}
|
||||
|
||||
function getDateKey(value) {
|
||||
function getDateKey(value?: string | Date | null) {
|
||||
if (!value) return 'unknown'
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return 'unknown'
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function formatDateGroup(value) {
|
||||
function formatDateGroup(value?: string | null) {
|
||||
if (!value || value === 'unknown') return '未知日期'
|
||||
const date = new Date(`${value}T00:00:00`)
|
||||
const today = new Date()
|
||||
|
|
@ -217,7 +288,7 @@ function formatDateGroup(value) {
|
|||
return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
|
||||
}
|
||||
|
||||
function stripMarkdown(text) {
|
||||
function stripMarkdown(text?: string | null) {
|
||||
return (text || '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/[#>*_`~[\]()/]/g, ' ')
|
||||
|
|
@ -226,7 +297,7 @@ function stripMarkdown(text) {
|
|||
}
|
||||
|
||||
// 去掉 markdown 语法标记,使关键词能与渲染后的纯文本精确匹配(用于原文定位)
|
||||
function stripMarkdownForHighlight(text) {
|
||||
function stripMarkdownForHighlight(text?: string | null) {
|
||||
return String(text || '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`([^`]*)`/g, '$1')
|
||||
|
|
@ -244,7 +315,7 @@ function stripMarkdownForHighlight(text) {
|
|||
.trim()
|
||||
}
|
||||
|
||||
function buildDocumentPreviewUrl(projectId, filePath, highlight) {
|
||||
function buildDocumentPreviewUrl(projectId?: number | null, filePath?: string | null, highlight?: string) {
|
||||
if (!projectId || !filePath) return ''
|
||||
const params = new URLSearchParams()
|
||||
params.set('file', filePath)
|
||||
|
|
@ -253,14 +324,14 @@ function buildDocumentPreviewUrl(projectId, filePath, highlight) {
|
|||
}
|
||||
|
||||
// 跳转原文时优先用「支撑句原文」作为定位关键词,文档页据此高亮并滚动到命中位置
|
||||
function getDocumentJumpKeyword(ref, occData) {
|
||||
function getDocumentJumpKeyword(ref?: ChatReference | null, occData?: CitationOccurrence | null) {
|
||||
const quoteText = (occData?.quotes?.[0]?.text || ref?.quotes?.[0]?.text || '').trim()
|
||||
if (quoteText) return stripMarkdownForHighlight(quoteText)
|
||||
const anchor = (ref?.anchor_text || '').trim()
|
||||
return anchor ? stripMarkdownForHighlight(anchor).slice(0, 32) : ''
|
||||
}
|
||||
|
||||
function openDocument(ref, projectId, occData) {
|
||||
function openDocument(ref: ChatReference | null | undefined, projectId?: number | null, occData?: CitationOccurrence | null) {
|
||||
const previewUrl = buildDocumentPreviewUrl(
|
||||
ref?.project_id || projectId,
|
||||
ref?.file_path,
|
||||
|
|
@ -269,21 +340,21 @@ function openDocument(ref, projectId, occData) {
|
|||
if (previewUrl) window.open(previewUrl, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
function getReferenceExcerpt(ref) {
|
||||
function getReferenceExcerpt(ref?: ChatReference | null) {
|
||||
return (ref?.excerpt || ref?.anchor_text || '').trim()
|
||||
}
|
||||
|
||||
function getReferenceContext(ref) {
|
||||
function getReferenceContext(ref?: ChatReference | null) {
|
||||
return (ref?.content || ref?.excerpt || ref?.anchor_text || '').trim()
|
||||
}
|
||||
|
||||
function escapeAngleBrackets(value) {
|
||||
function escapeAngleBrackets(value?: string | null) {
|
||||
return String(value ?? '').replace(/</g, '<').replace(/>/g, '>')
|
||||
}
|
||||
|
||||
// 渲染引用片段:命中的分块区间用「证据条」标出(chat-chunk-band)。
|
||||
// 提问关键词不再高亮——检索是语义匹配,提问词与原文命中并无字面对应。
|
||||
function highlightCitation(text, chunkText) {
|
||||
function highlightCitation(text?: string | null, chunkText?: string | null) {
|
||||
const escaped = escapeAngleBrackets(text)
|
||||
const chunk = escapeAngleBrackets(chunkText)
|
||||
// CommonMark 会在空行处断开段落,跨多段的分块不能整体包 <mark>,否则标签错位
|
||||
|
|
@ -294,7 +365,7 @@ function highlightCitation(text, chunkText) {
|
|||
return `${escaped.slice(0, idx)}<mark class="chat-chunk-band">${chunk}</mark>${escaped.slice(idx + chunk.length)}`
|
||||
}
|
||||
|
||||
function loadPendingStops() {
|
||||
function loadPendingStops(): Record<string, boolean> {
|
||||
try {
|
||||
return JSON.parse(sessionStorage.getItem('nex-chat-pending-stops') || '{}')
|
||||
} catch {
|
||||
|
|
@ -302,7 +373,7 @@ function loadPendingStops() {
|
|||
}
|
||||
}
|
||||
|
||||
function savePendingStops(map) {
|
||||
function savePendingStops(map: Record<string, boolean>) {
|
||||
try {
|
||||
sessionStorage.setItem('nex-chat-pending-stops', JSON.stringify(map))
|
||||
} catch {
|
||||
|
|
@ -310,7 +381,7 @@ function savePendingStops(map) {
|
|||
}
|
||||
}
|
||||
|
||||
function SearchHighlight({ text, keyword }) {
|
||||
function SearchHighlight({ text, keyword }: { text?: string; keyword?: string }) {
|
||||
const value = text || ''
|
||||
if (!keyword) return value
|
||||
return (
|
||||
|
|
@ -323,7 +394,7 @@ function SearchHighlight({ text, keyword }) {
|
|||
)
|
||||
}
|
||||
|
||||
function CitationMarkdown({ children }) {
|
||||
function CitationMarkdown({ children }: { children?: string }) {
|
||||
return (
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
|
|
@ -337,7 +408,7 @@ function CitationMarkdown({ children }) {
|
|||
)
|
||||
}
|
||||
|
||||
function ReferenceCard({ reference, projectId }) {
|
||||
function ReferenceCard({ reference, projectId }: { reference: ChatReference; projectId?: number | null }) {
|
||||
return (
|
||||
<span
|
||||
className="chat-reference-chip"
|
||||
|
|
@ -360,7 +431,7 @@ function ReferenceCard({ reference, projectId }) {
|
|||
)
|
||||
}
|
||||
|
||||
async function copyText(text) {
|
||||
async function copyText(text?: string | null) {
|
||||
const value = text || ''
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
|
|
@ -385,7 +456,14 @@ async function copyText(text) {
|
|||
}
|
||||
}
|
||||
|
||||
function MessageActions({ content, onCopy, onDelete, onRegenerate }) {
|
||||
interface MessageActionsProps {
|
||||
content: string
|
||||
onCopy?: (ok: boolean) => void
|
||||
onDelete?: () => void
|
||||
onRegenerate?: () => void
|
||||
}
|
||||
|
||||
function MessageActions({ content, onCopy, onDelete, onRegenerate }: MessageActionsProps) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const handleCopy = async () => {
|
||||
const ok = await copyText(content)
|
||||
|
|
@ -407,15 +485,15 @@ function MessageActions({ content, onCopy, onDelete, onRegenerate }) {
|
|||
aria-label="重新生成"
|
||||
title="重新生成"
|
||||
>
|
||||
<ReloadOutlined />
|
||||
<ReloadOutlined aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="chat-message-action" onClick={handleCopy} aria-label="复制">
|
||||
{copied ? <CheckOutlined /> : <CopyOutlined />}
|
||||
{copied ? <CheckOutlined aria-hidden /> : <CopyOutlined aria-hidden />}
|
||||
</button>
|
||||
{onDelete && (
|
||||
<button type="button" className="chat-message-action danger" onClick={onDelete} aria-label="删除">
|
||||
<DeleteOutlined />
|
||||
<DeleteOutlined aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -426,11 +504,11 @@ function Chat() {
|
|||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [sessions, setSessions] = useState([])
|
||||
const [projects, setProjects] = useState([])
|
||||
const [models, setModels] = useState([])
|
||||
const [currentSession, setCurrentSession] = useState(null)
|
||||
const [messages, setMessages] = useState([])
|
||||
const [sessions, setSessions] = useState<ChatSession[]>([])
|
||||
const [projects, setProjects] = useState<ProjectListItem[]>([])
|
||||
const [models, setModels] = useState<LLMModelConfig[]>([])
|
||||
const [currentSession, setCurrentSession] = useState<ChatSession | null>(null)
|
||||
const [messages, setMessages] = useState<ChatViewMessage[]>([])
|
||||
// 刷新直达已有会话时,首帧即为加载态,避免闪现「新建对话」页
|
||||
const [loadingSessions, setLoadingSessions] = useState(
|
||||
() => /[?&](session_id|sessionId)=/.test(window.location.search)
|
||||
|
|
@ -440,24 +518,24 @@ function Chat() {
|
|||
const [inputValue, setInputValue] = useState('')
|
||||
const [searchVisible, setSearchVisible] = useState(false)
|
||||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
const [searchResults, setSearchResults] = useState([])
|
||||
const [searchResults, setSearchResults] = useState<ChatSearchResult[]>([])
|
||||
const [searchLoading, setSearchLoading] = useState(false)
|
||||
const [searchedKeyword, setSearchedKeyword] = useState('')
|
||||
const [hasSearched, setHasSearched] = useState(false)
|
||||
const [newQuestion, setNewQuestion] = useState('')
|
||||
const [newProjectId, setNewProjectId] = useState(undefined)
|
||||
const [newModelId, setNewModelId] = useState(undefined)
|
||||
const [newProjectId, setNewProjectId] = useState<number | undefined>(undefined)
|
||||
const [newModelId, setNewModelId] = useState<number | undefined>(undefined)
|
||||
const [projectPickerOpen, setProjectPickerOpen] = useState(false)
|
||||
const [renameVisible, setRenameVisible] = useState(false)
|
||||
const [renameSession, setRenameSession] = useState(null)
|
||||
const [renameSession, setRenameSession] = useState<ChatSession | null>(null)
|
||||
const [renameTitle, setRenameTitle] = useState('')
|
||||
const messageRefs = useRef(new Map())
|
||||
const messageListRef = useRef(null)
|
||||
const nearBottomRef = useRef(true)
|
||||
const composerRef = useRef(null)
|
||||
const abortControllerRef = useRef(null)
|
||||
const messageRefs = useRef(new Map<string, HTMLElement>())
|
||||
const messageListRef = useRef<HTMLDivElement>(null)
|
||||
const nearBottomRef = useRef<boolean>(true)
|
||||
const composerRef = useRef<TextAreaRef>(null)
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const pendingStopsRef = useRef(loadPendingStops())
|
||||
const skipNextOpenSessionRef = useRef(null)
|
||||
const skipNextOpenSessionRef = useRef<number | null>(null)
|
||||
const searchRequestIdRef = useRef(0)
|
||||
const newMode = location.pathname === '/chat/new'
|
||||
|
||||
|
|
@ -481,12 +559,12 @@ function Chat() {
|
|||
const canCreateSession = Boolean(newQuestion.trim() && currentProject && currentModel)
|
||||
const canSendMessage = Boolean(inputValue.trim() && currentSession)
|
||||
|
||||
const markPendingStop = (sessionId) => {
|
||||
const markPendingStop = (sessionId: number) => {
|
||||
pendingStopsRef.current[String(sessionId)] = true
|
||||
savePendingStops(pendingStopsRef.current)
|
||||
}
|
||||
|
||||
const clearPendingStop = (sessionId) => {
|
||||
const clearPendingStop = (sessionId: number) => {
|
||||
if (pendingStopsRef.current[String(sessionId)]) {
|
||||
delete pendingStopsRef.current[String(sessionId)]
|
||||
savePendingStops(pendingStopsRef.current)
|
||||
|
|
@ -494,12 +572,12 @@ function Chat() {
|
|||
}
|
||||
|
||||
const groupedSessions = useMemo(() => {
|
||||
const groups = []
|
||||
const groups: ChatSessionGroup[] = []
|
||||
const groupMap = new Map()
|
||||
sessions.forEach((item) => {
|
||||
const key = getDateKey(item.updated_at || item.created_at)
|
||||
if (!groupMap.has(key)) {
|
||||
const group = {
|
||||
const group: ChatSessionGroup = {
|
||||
key,
|
||||
label: formatDateGroup(key),
|
||||
items: [],
|
||||
|
|
@ -507,7 +585,7 @@ function Chat() {
|
|||
groupMap.set(key, group)
|
||||
groups.push(group)
|
||||
}
|
||||
groupMap.get(key).items.push(item)
|
||||
groupMap.get(key)?.items.push(item)
|
||||
})
|
||||
return groups
|
||||
}, [sessions])
|
||||
|
|
@ -546,7 +624,7 @@ function Chat() {
|
|||
}
|
||||
|
||||
// 会话产生新活动后,本地更新 updated_at 并重排,避免整表重载导致的闪烁/跳动
|
||||
const touchSession = (sessionId) => {
|
||||
const touchSession = (sessionId: number) => {
|
||||
const now = new Date().toISOString()
|
||||
setSessions((prev) => {
|
||||
const next = prev.map((item) => (
|
||||
|
|
@ -558,7 +636,7 @@ function Chat() {
|
|||
})
|
||||
}
|
||||
|
||||
const openSession = async (id, extraQuery = {}) => {
|
||||
const openSession = async (id: number, extraQuery: { message_id?: number } = {}) => {
|
||||
if (!id) return
|
||||
const nextQuery = new URLSearchParams()
|
||||
nextQuery.set('session_id', String(id))
|
||||
|
|
@ -568,29 +646,36 @@ function Chat() {
|
|||
navigate({ pathname: '/chat', search: `?${nextQuery.toString()}` }, { replace: true })
|
||||
}
|
||||
|
||||
const loadSessionMessages = async (id) => {
|
||||
// 后端消息 → 页面视图模型:状态名映射 + 补齐流式相关的本地字段
|
||||
const toViewMessage = (item: ChatMessage): ChatViewMessage => {
|
||||
// 后端返回 completed/interrupted/error/pending,前端统一映射为展示状态
|
||||
let status: ChatViewStatus = (item.status || 'pending') as ChatViewStatus
|
||||
if (status === ('completed' as ChatViewStatus)) status = 'done'
|
||||
if (item.role !== 'assistant') status = 'done'
|
||||
return {
|
||||
id: item.id,
|
||||
role: item.role,
|
||||
content: item.content,
|
||||
created_at: item.created_at,
|
||||
references: item.references || [],
|
||||
status,
|
||||
durationMs: item.duration_ms ?? null,
|
||||
thinkingLog: Array.isArray(item.thinking_log) ? item.thinking_log : [],
|
||||
thinkingVisible: false,
|
||||
}
|
||||
}
|
||||
|
||||
const loadSessionMessages = async (id: number) => {
|
||||
setLoadingMessages(true)
|
||||
try {
|
||||
const res = await getChatMessages(id)
|
||||
const rawMessages = res.data || []
|
||||
const nextMessages = rawMessages.map((item) => {
|
||||
// 后端返回 completed/interrupted/error/pending,前端统一映射为展示状态
|
||||
let status = item.status || 'pending'
|
||||
if (status === 'completed') status = 'done'
|
||||
if (item.role !== 'assistant') status = 'done'
|
||||
return {
|
||||
...item,
|
||||
status,
|
||||
durationMs: item.duration_ms ?? null,
|
||||
thinkingLog: Array.isArray(item.thinking_log) ? item.thinking_log : [],
|
||||
thinkingVisible: false,
|
||||
}
|
||||
})
|
||||
const nextMessages = rawMessages.map(toViewMessage)
|
||||
|
||||
// 停止后后端写入中断状态需要一点时间:若该会话存在未确认的停止,
|
||||
// 且最后一条助手消息仍为空,则把它标记为“已停止”,避免显示“思考中”。
|
||||
if (pendingStopsRef.current[String(id)]) {
|
||||
const lastAssistantIndex = [...nextMessages].reverse().findIndex((m) => m.role === 'assistant')
|
||||
const lastAssistantIndex = [...nextMessages].reverse().findIndex((m: ChatViewMessage) => m.role === 'assistant')
|
||||
if (lastAssistantIndex !== -1) {
|
||||
const idx = nextMessages.length - 1 - lastAssistantIndex
|
||||
const lastAssistant = nextMessages[idx]
|
||||
|
|
@ -699,12 +784,12 @@ function Chat() {
|
|||
}
|
||||
const title = question.length > 24 ? `${question.slice(0, 24)}...` : question
|
||||
setSending(true)
|
||||
let session = null
|
||||
let session: ChatSession | null = null
|
||||
try {
|
||||
const res = await createChatSession(newProjectId, newModelId, title)
|
||||
session = res.data
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || error.message || '新建对话失败')
|
||||
Toast.error(getApiErrorMessage(error, '新建对话失败'))
|
||||
setSending(false)
|
||||
return
|
||||
}
|
||||
|
|
@ -717,11 +802,12 @@ function Chat() {
|
|||
created_at: session.created_at,
|
||||
updated_at: session.updated_at || session.created_at,
|
||||
}
|
||||
const optimisticMessage = {
|
||||
const optimisticMessage: ChatViewMessage = {
|
||||
id: `tmp-${Date.now()}`,
|
||||
role: 'user',
|
||||
role: 'user' as const,
|
||||
content: question,
|
||||
created_at: new Date().toISOString(),
|
||||
status: 'done' as ChatViewStatus,
|
||||
}
|
||||
|
||||
setSessions((prev) => [
|
||||
|
|
@ -742,7 +828,7 @@ function Chat() {
|
|||
})
|
||||
touchSession(nextSession.session_id)
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || error.message || '对话已创建,但首条消息发送失败')
|
||||
Toast.error(getApiErrorMessage(error, '对话已创建,但首条消息发送失败'))
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
|
|
@ -759,7 +845,7 @@ function Chat() {
|
|||
await sendMessageWithStream(currentSession, content)
|
||||
touchSession(currentSession.session_id)
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || error.message || '发送消息失败')
|
||||
Toast.error(getApiErrorMessage(error, '发送消息失败'))
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
|
|
@ -769,7 +855,7 @@ function Chat() {
|
|||
abortControllerRef.current?.abort()
|
||||
}
|
||||
|
||||
const handleRegenerate = async (item) => {
|
||||
const handleRegenerate = async (item: ChatViewMessage) => {
|
||||
if (sending) return
|
||||
const index = messages.findIndex((m) => m.id === item.id)
|
||||
if (index < 0) return
|
||||
|
|
@ -779,9 +865,9 @@ function Chat() {
|
|||
const isRealId = typeof item.id === 'number' || /^\d+$/.test(String(item.id))
|
||||
if (isRealId) {
|
||||
try {
|
||||
await deleteChatMessage(item.id)
|
||||
await deleteChatMessage(Number(item.id))
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除旧回复失败')
|
||||
Toast.error(getApiErrorMessage(error, '删除旧回复失败'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
@ -798,22 +884,38 @@ function Chat() {
|
|||
})
|
||||
touchSession(currentSession.session_id)
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || error.message || '重新生成失败')
|
||||
Toast.error(getApiErrorMessage(error, '重新生成失败'))
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const sendMessageWithStream = async (session, content, options = {}) => {
|
||||
const userMessage = {
|
||||
interface StreamOptions {
|
||||
/** 重新生成/新建会话时复用已有的消息列表,不再叠加 */
|
||||
initialMessages?: ChatViewMessage[]
|
||||
/** 乐观展示的用户消息 id,流式拿到真实 id 后要就地替换 */
|
||||
initialUserMessageId?: number | string
|
||||
/** false 时不把用户消息追加到界面上(重新生成) */
|
||||
includeUserMessage?: boolean
|
||||
/** false 时让后端跳过用户消息落库(重新生成) */
|
||||
insertUserMessage?: boolean
|
||||
}
|
||||
|
||||
const sendMessageWithStream = async (
|
||||
session: ChatSession,
|
||||
content: string,
|
||||
options: StreamOptions = {},
|
||||
) => {
|
||||
const userMessage: ChatViewMessage = {
|
||||
id: `tmp-user-${Date.now()}`,
|
||||
role: 'user',
|
||||
role: 'user' as const,
|
||||
content,
|
||||
created_at: new Date().toISOString(),
|
||||
status: 'done' as ChatViewStatus,
|
||||
}
|
||||
const assistantMessage = {
|
||||
const assistantMessage: ChatViewMessage = {
|
||||
id: `tmp-assistant-${Date.now()}`,
|
||||
role: 'assistant',
|
||||
role: 'assistant' as const,
|
||||
content: '',
|
||||
references: [],
|
||||
status: 'thinking',
|
||||
|
|
@ -833,7 +935,7 @@ function Chat() {
|
|||
|
||||
// 流式过程中后端会回传真实消息 id(ids 事件),这里用可变变量持续追踪当前
|
||||
// 助手消息的 id:替换为真实 id 后,后续 onChunk/onDone 仍能命中同一条消息。
|
||||
let assistantMsgId = assistantMessage.id
|
||||
let assistantMsgId: number | string = assistantMessage.id
|
||||
const tmpUserId = options.initialUserMessageId ?? userMessage.id
|
||||
|
||||
const controller = new AbortController()
|
||||
|
|
@ -863,6 +965,7 @@ function Chat() {
|
|||
)))
|
||||
},
|
||||
onThinking: (entry) => {
|
||||
if (!entry) return
|
||||
setMessages((prev) => prev.map((item) => (
|
||||
item.id === assistantMsgId
|
||||
? {
|
||||
|
|
@ -908,7 +1011,7 @@ function Chat() {
|
|||
},
|
||||
})
|
||||
} catch (error) {
|
||||
const aborted = error?.name === 'AbortError'
|
||||
const aborted = (error as { name?: string } | null)?.name === 'AbortError'
|
||||
if (aborted) {
|
||||
// 会话级待确认标记:兜底覆盖后端中断标记写入前的时间窗口
|
||||
markPendingStop(session.session_id)
|
||||
|
|
@ -944,7 +1047,7 @@ function Chat() {
|
|||
? {
|
||||
...item,
|
||||
status: aborted ? 'interrupted' : 'error',
|
||||
error: aborted ? undefined : (error.message || '回答生成失败,请稍后重试'),
|
||||
error: aborted ? undefined : getApiErrorMessage(error, '回答生成失败,请稍后重试'),
|
||||
durationMs: aborted
|
||||
? Date.now() - (item.thinkingStartedAt || Date.now())
|
||||
: item.durationMs,
|
||||
|
|
@ -963,7 +1066,7 @@ function Chat() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleDeleteMessage = (item) => {
|
||||
const handleDeleteMessage = (item: ChatViewMessage) => {
|
||||
const isTemp = typeof item.id === 'string' && item.id.startsWith('tmp-')
|
||||
if (isTemp) {
|
||||
setMessages((prev) => prev.filter((m) => m.id !== item.id))
|
||||
|
|
@ -977,16 +1080,16 @@ function Chat() {
|
|||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await deleteChatMessage(item.id)
|
||||
await deleteChatMessage(Number(item.id))
|
||||
setMessages((prev) => prev.filter((m) => m.id !== item.id))
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除失败')
|
||||
Toast.error(getApiErrorMessage(error, '删除失败'))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const toggleThinking = (id) => {
|
||||
const toggleThinking = (id: number | string) => {
|
||||
setMessages((prev) => prev.map((item) => (
|
||||
item.id === id ? { ...item, thinkingVisible: !item.thinkingVisible } : item
|
||||
)))
|
||||
|
|
@ -1012,7 +1115,7 @@ function Chat() {
|
|||
setHasSearched(true)
|
||||
} catch (error) {
|
||||
if (requestId === searchRequestIdRef.current) {
|
||||
Toast.error(error.response?.data?.detail || error.message || '搜索失败')
|
||||
Toast.error(getApiErrorMessage(error, '搜索失败'))
|
||||
}
|
||||
} finally {
|
||||
if (requestId === searchRequestIdRef.current) {
|
||||
|
|
@ -1021,7 +1124,7 @@ function Chat() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleSearchKeywordChange = (event) => {
|
||||
const handleSearchKeywordChange = (event: ReactChangeEvent<HTMLInputElement>) => {
|
||||
const value = event.target.value
|
||||
setSearchKeyword(value)
|
||||
if (!value.trim()) {
|
||||
|
|
@ -1039,7 +1142,7 @@ function Chat() {
|
|||
const newSessionImeSubmit = useImeSafeEnter(handleCreateSession, { allowCtrlMeta: true })
|
||||
const searchImeSubmit = useImeSafeEnter(handleSearch)
|
||||
|
||||
const handleSelectSearchResult = async (item) => {
|
||||
const handleSelectSearchResult = async (item: ChatSearchResult) => {
|
||||
setSearchVisible(false)
|
||||
await openSession(item.session_id, { message_id: item.message_id })
|
||||
}
|
||||
|
|
@ -1056,17 +1159,17 @@ function Chat() {
|
|||
item.session_id === renameSession.session_id ? { ...item, title } : item
|
||||
)))
|
||||
if (currentSession?.session_id === renameSession.session_id) {
|
||||
setCurrentSession((prev) => ({ ...prev, title }))
|
||||
setCurrentSession((prev) => (prev ? { ...prev, title } : prev))
|
||||
}
|
||||
setRenameVisible(false)
|
||||
setRenameSession(null)
|
||||
setRenameTitle('')
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '重命名失败')
|
||||
Toast.error(getApiErrorMessage(error, '重命名失败'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteSession = (session) => {
|
||||
const handleDeleteSession = (session: ChatSession) => {
|
||||
Toast.confirm({
|
||||
title: '删除对话',
|
||||
content: `确定删除「${session.title}」吗?删除后无法恢复。`,
|
||||
|
|
@ -1083,7 +1186,7 @@ function Chat() {
|
|||
navigate('/chat', { replace: true })
|
||||
}
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除失败')
|
||||
Toast.error(getApiErrorMessage(error, '删除失败'))
|
||||
}
|
||||
},
|
||||
})
|
||||
|
|
@ -1109,12 +1212,12 @@ function Chat() {
|
|||
const menuItems = [
|
||||
{
|
||||
key: 'rename',
|
||||
icon: <EditOutlined />,
|
||||
icon: <EditOutlined aria-hidden />,
|
||||
label: '重命名',
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
icon: <DeleteOutlined />,
|
||||
icon: <DeleteOutlined aria-hidden />,
|
||||
label: '删除',
|
||||
danger: true,
|
||||
},
|
||||
|
|
@ -1123,6 +1226,10 @@ function Chat() {
|
|||
<div
|
||||
className={`chat-session-item${active ? ' active' : ''}`}
|
||||
onClick={() => openSession(item.session_id)}
|
||||
// 整行点击即打开会话,键盘走同一动作;行内的「更多」按钮自行阻止冒泡
|
||||
{...keyboardActivation(() => openSession(item.session_id))}
|
||||
aria-label={`打开对话:${item.title}`}
|
||||
aria-current={active ? 'true' : undefined}
|
||||
>
|
||||
<div className="chat-session-item-top">
|
||||
<div className="chat-session-title-area">
|
||||
|
|
@ -1151,12 +1258,12 @@ function Chat() {
|
|||
onClick={(event) => event.stopPropagation()}
|
||||
aria-label="更多操作"
|
||||
>
|
||||
<MoreOutlined />
|
||||
<MoreOutlined aria-hidden />
|
||||
</button>
|
||||
</Dropdown>
|
||||
</div>
|
||||
<div className="chat-session-meta">
|
||||
<Tag className="chat-session-meta-text" icon={<FolderOutlined />}>{project?.name || '未命名项目'}</Tag>
|
||||
<Tag className="chat-session-meta-text" icon={<FolderOutlined aria-hidden />}>{project?.name || '未命名项目'}</Tag>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -1242,9 +1349,10 @@ function Chat() {
|
|||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeCitationSup]}
|
||||
components={{
|
||||
sup: ({ children, ...props }) => {
|
||||
const citationId = Number(props['data-citation-id'])
|
||||
const occIndex = Number(props['data-citation-occ'] ?? 0)
|
||||
sup: ({ children, node: _node, ...props }) => {
|
||||
const data = props as Record<string, unknown>
|
||||
const citationId = Number(data['data-citation-id'])
|
||||
const occIndex = Number(data['data-citation-occ'] ?? 0)
|
||||
const ref = refs.find((itemRef) => Number(itemRef.citation_id) === citationId)
|
||||
if (!ref) {
|
||||
return <sup {...props}>{children}</sup>
|
||||
|
|
@ -1281,7 +1389,9 @@ function Chat() {
|
|||
<div key={quoteIdx} className="chat-citation-quote-row">
|
||||
<span className="chat-citation-quote">原文:{quote.text}</span>
|
||||
<LinkOutlined
|
||||
className="chat-citation-quote-open"
|
||||
|
||||
aria-label="查看原文"
|
||||
className="chat-citation-quote-open"
|
||||
title="查看原文"
|
||||
onClick={() => openDocument(ref, projectId, occData)}
|
||||
/>
|
||||
|
|
@ -1294,7 +1404,9 @@ function Chat() {
|
|||
{highlightCitation(context, hasBand ? excerpt : '') || '暂无引用片段'}
|
||||
</CitationMarkdown>
|
||||
<LinkOutlined
|
||||
className="chat-citation-quote-open"
|
||||
|
||||
aria-label="查看原文"
|
||||
className="chat-citation-quote-open"
|
||||
title="查看原文"
|
||||
onClick={() => openDocument(ref, projectId, occData)}
|
||||
/>
|
||||
|
|
@ -1373,7 +1485,7 @@ function Chat() {
|
|||
<div className="chat-composer-actions">
|
||||
<div className="chat-composer-left">
|
||||
<span className="chat-composer-pill chat-composer-kb">
|
||||
<FolderOutlined className="chat-composer-pill-icon" />
|
||||
<FolderOutlined aria-hidden className="chat-composer-pill-icon" />
|
||||
<span className="chat-composer-pill-text">
|
||||
{projects.find((project) => project.id === currentSession?.project_id)?.name || '-'}
|
||||
</span>
|
||||
|
|
@ -1381,7 +1493,7 @@ function Chat() {
|
|||
</div>
|
||||
<div className="chat-composer-right">
|
||||
<span className="chat-composer-pill chat-composer-model">
|
||||
<RobotOutlined className="chat-composer-pill-icon" />
|
||||
<RobotOutlined aria-hidden className="chat-composer-pill-icon" />
|
||||
<span className="chat-composer-pill-text">
|
||||
{models.find((model) => model.config_id === currentSession?.llm_config_id)?.model_name || '-'}
|
||||
</span>
|
||||
|
|
@ -1389,7 +1501,7 @@ function Chat() {
|
|||
{sending ? (
|
||||
<Button
|
||||
shape="circle"
|
||||
icon={<StopOutlined />}
|
||||
icon={<StopOutlined aria-hidden />}
|
||||
onClick={handleStopGenerating}
|
||||
title="停止生成"
|
||||
aria-label="停止生成"
|
||||
|
|
@ -1398,7 +1510,8 @@ function Chat() {
|
|||
) : (
|
||||
<Button
|
||||
shape="circle"
|
||||
icon={<ArrowUpOutlined />}
|
||||
icon={<ArrowUpOutlined aria-hidden />}
|
||||
aria-label="发送消息"
|
||||
onClick={handleSend}
|
||||
disabled={!canSendMessage}
|
||||
aria-disabled={!canSendMessage}
|
||||
|
|
@ -1430,6 +1543,7 @@ function Chat() {
|
|||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
icon={decorativeAlertIcon('warning')}
|
||||
message="暂无可用知识库"
|
||||
description="请先在「项目空间」创建项目,再进入这里提问。"
|
||||
/>
|
||||
|
|
@ -1438,6 +1552,7 @@ function Chat() {
|
|||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
icon={decorativeAlertIcon('warning')}
|
||||
message="暂无可用对话模型"
|
||||
description="请先到「系统管理 - 模型配置」添加并启用对话模型。"
|
||||
/>
|
||||
|
|
@ -1464,12 +1579,13 @@ function Chat() {
|
|||
<Select
|
||||
value={newProjectId}
|
||||
placeholder="选择知识库"
|
||||
aria-label="选择知识库"
|
||||
options={projects.map((item) => ({ label: item.name, value: item.id }))}
|
||||
onChange={(value) => {
|
||||
setNewProjectId(value)
|
||||
setProjectPickerOpen(false)
|
||||
}}
|
||||
suffixIcon={<DownOutlined />}
|
||||
suffixIcon={<DownOutlined aria-hidden />}
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
className="chat-project-picker-select"
|
||||
|
|
@ -1478,12 +1594,12 @@ function Chat() {
|
|||
}
|
||||
>
|
||||
<button type="button" className="chat-composer-plus" aria-label="选择知识库">
|
||||
<PlusOutlined />
|
||||
<PlusOutlined aria-hidden />
|
||||
</button>
|
||||
</Popover>
|
||||
{currentProject && (
|
||||
<span className="chat-composer-pill chat-composer-kb">
|
||||
<FolderOutlined className="chat-composer-pill-icon" />
|
||||
<FolderOutlined aria-hidden className="chat-composer-pill-icon" />
|
||||
<span className="chat-composer-pill-text">{currentProject.name}</span>
|
||||
</span>
|
||||
)}
|
||||
|
|
@ -1492,9 +1608,10 @@ function Chat() {
|
|||
<Select
|
||||
value={newModelId}
|
||||
placeholder="选择模型"
|
||||
aria-label="选择模型"
|
||||
options={models.map((item) => ({ label: item.model_name, value: item.config_id }))}
|
||||
onChange={setNewModelId}
|
||||
suffixIcon={<DownOutlined />}
|
||||
suffixIcon={<DownOutlined aria-hidden />}
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
className="chat-composer-model-select"
|
||||
|
|
@ -1502,7 +1619,7 @@ function Chat() {
|
|||
{sending ? (
|
||||
<Button
|
||||
shape="circle"
|
||||
icon={<StopOutlined />}
|
||||
icon={<StopOutlined aria-hidden />}
|
||||
onClick={handleStopGenerating}
|
||||
title="停止生成"
|
||||
aria-label="停止生成"
|
||||
|
|
@ -1511,7 +1628,8 @@ function Chat() {
|
|||
) : (
|
||||
<Button
|
||||
shape="circle"
|
||||
icon={<ArrowUpOutlined />}
|
||||
icon={<ArrowUpOutlined aria-hidden />}
|
||||
aria-label="开始提问"
|
||||
onClick={handleCreateSession}
|
||||
disabled={!canCreateSession}
|
||||
aria-disabled={!canCreateSession}
|
||||
|
|
@ -1530,11 +1648,11 @@ function Chat() {
|
|||
<aside className="chat-left-panel">
|
||||
<div className="chat-left-actions">
|
||||
<button className="chat-action-entry" onClick={handleStartNew}>
|
||||
<EditOutlined />
|
||||
<EditOutlined aria-hidden />
|
||||
<span>新建对话</span>
|
||||
</button>
|
||||
<button className="chat-action-entry" onClick={() => setSearchVisible(true)}>
|
||||
<SearchOutlined />
|
||||
<SearchOutlined aria-hidden />
|
||||
<span>搜索对话</span>
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -1563,10 +1681,10 @@ function Chat() {
|
|||
value={searchKeyword}
|
||||
onChange={handleSearchKeywordChange}
|
||||
placeholder="输入聊天关键词,仅搜索对话内容"
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
{...searchImeSubmit}
|
||||
/>
|
||||
<Button type="primary" icon={<SearchOutlined />} loading={searchLoading} onClick={handleSearch}>
|
||||
<Button type="primary" icon={<SearchOutlined aria-hidden />} loading={searchLoading} onClick={handleSearch}>
|
||||
搜索
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
|
|
@ -1586,7 +1704,7 @@ function Chat() {
|
|||
renderItem={(item) => (
|
||||
<List.Item className="chat-search-result-item" onClick={() => handleSelectSearchResult(item)}>
|
||||
<List.Item.Meta
|
||||
avatar={<Avatar icon={item.role === 'assistant' ? <RobotOutlined /> : <UserOutlined />} />}
|
||||
avatar={<Avatar icon={item.role === 'assistant' ? <RobotOutlined aria-hidden /> : <UserOutlined aria-hidden />} aria-hidden />}
|
||||
title={
|
||||
<Space wrap>
|
||||
<Text strong>{item.session_title}</Text>
|
||||
|
|
@ -15,7 +15,7 @@ function Constructing() {
|
|||
padding: '50px'
|
||||
}}>
|
||||
<Result
|
||||
icon={<ToolOutlined style={{ fontSize: '72px', color: 'var(--color-primary)' }} />}
|
||||
icon={<ToolOutlined aria-hidden style={{ fontSize: '72px', color: 'var(--color-primary)' }} />}
|
||||
title="功能开发中"
|
||||
subTitle="该功能正在紧张开发中,敬请期待..."
|
||||
extra={
|
||||
|
|
@ -1,23 +1,29 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { Card, Table, Spin, Button } from 'antd'
|
||||
import { UserOutlined, ProjectOutlined, FileTextOutlined, SyncOutlined, DashboardOutlined } from '@ant-design/icons'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { getDashboardStats } from '@/api/dashboard'
|
||||
import { rebuildIndex } from '@/api/search'
|
||||
import type { DashboardStats } from '@/types/api'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import StatCard from '@/components/StatCard/StatCard'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
|
||||
type RecentUser = DashboardStats['recent_users'][number]
|
||||
type RecentProject = DashboardStats['recent_projects'][number]
|
||||
|
||||
function Dashboard() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [rebuilding, setRebuilding] = useState(false)
|
||||
const [stats, setStats] = useState({
|
||||
const [stats, setStats] = useState<DashboardStats['stats']>({
|
||||
user_count: 0,
|
||||
project_count: 0,
|
||||
document_count: 0,
|
||||
})
|
||||
const [recentUsers, setRecentUsers] = useState([])
|
||||
const [recentProjects, setRecentProjects] = useState([])
|
||||
const [recentUsers, setRecentUsers] = useState<RecentUser[]>([])
|
||||
const [recentProjects, setRecentProjects] = useState<RecentProject[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
loadDashboardData()
|
||||
|
|
@ -46,13 +52,13 @@ function Dashboard() {
|
|||
Toast.success('索引重建任务已启动,请稍后搜索尝试')
|
||||
} catch (error) {
|
||||
console.error('Rebuild index error:', error)
|
||||
Toast.error('重建索引失败: ' + (error.response?.data?.detail || error.message))
|
||||
Toast.error(`重建索引失败: ${getApiErrorDetail(error) || '未知错误'}`)
|
||||
} finally {
|
||||
setRebuilding(false)
|
||||
}
|
||||
}
|
||||
|
||||
const userColumns = [
|
||||
const userColumns: ColumnsType<RecentUser> = [
|
||||
{
|
||||
title: '用户名',
|
||||
dataIndex: 'username',
|
||||
|
|
@ -67,11 +73,11 @@ function Dashboard() {
|
|||
title: '创建时间',
|
||||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
render: (text: string | null) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
},
|
||||
]
|
||||
|
||||
const projectColumns = [
|
||||
const projectColumns: ColumnsType<RecentProject> = [
|
||||
{
|
||||
title: '项目名称',
|
||||
dataIndex: 'name',
|
||||
|
|
@ -91,7 +97,7 @@ function Dashboard() {
|
|||
title: '创建时间',
|
||||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
render: (text: string | null) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
},
|
||||
]
|
||||
|
||||
|
|
@ -110,11 +116,11 @@ function Dashboard() {
|
|||
<PageHeader
|
||||
title="管理面板"
|
||||
description="汇总查看用户、项目与文档数据,并执行搜索索引维护操作。"
|
||||
icon={<DashboardOutlined />}
|
||||
icon={<DashboardOutlined aria-hidden />}
|
||||
extra={(
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SyncOutlined spin={rebuilding} />}
|
||||
icon={<SyncOutlined spin={rebuilding} aria-hidden />}
|
||||
onClick={handleRebuildIndex}
|
||||
loading={rebuilding}
|
||||
>
|
||||
|
|
@ -124,9 +130,9 @@ function Dashboard() {
|
|||
/>
|
||||
|
||||
<div className="admin-stats">
|
||||
<StatCard title="用户总数" value={stats.user_count} icon={<UserOutlined />} color="green" />
|
||||
<StatCard title="项目总数" value={stats.project_count} icon={<ProjectOutlined />} color="blue" />
|
||||
<StatCard title="文档总数" value={stats.document_count} icon={<FileTextOutlined />} color="red" />
|
||||
<StatCard title="用户总数" value={stats.user_count} icon={<UserOutlined aria-hidden />} color="green" />
|
||||
<StatCard title="项目总数" value={stats.project_count} icon={<ProjectOutlined aria-hidden />} color="blue" />
|
||||
<StatCard title="文档总数" value={stats.document_count} icon={<FileTextOutlined aria-hidden />} color="red" />
|
||||
</div>
|
||||
|
||||
<div className="admin-stack">
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import type { Dayjs } from 'dayjs'
|
||||
import { Card, Calendar, List, Badge, Empty, Typography, Spin } from 'antd'
|
||||
import { DesktopOutlined, FileTextOutlined, ClockCircleOutlined } from '@ant-design/icons'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { getDocumentActivityDates, getDocumentActivity } from '@/api/dashboard'
|
||||
import type { ActivityDate, ActivityLog } from '@/types/api'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import dayjs from 'dayjs'
|
||||
|
|
@ -14,9 +16,9 @@ const { Text } = Typography
|
|||
function Desktop() {
|
||||
const navigate = useNavigate()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [activityDates, setActivityDates] = useState([])
|
||||
const [selectedDate, setSelectedDate] = useState(dayjs())
|
||||
const [activityLogs, setActivityLogs] = useState([])
|
||||
const [activityDates, setActivityDates] = useState<ActivityDate[]>([])
|
||||
const [selectedDate, setSelectedDate] = useState<Dayjs>(dayjs())
|
||||
const [activityLogs, setActivityLogs] = useState<ActivityLog[]>([])
|
||||
const [currentMonth, setCurrentMonth] = useState(dayjs())
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -25,7 +27,7 @@ function Desktop() {
|
|||
}, [])
|
||||
|
||||
// 加载指定月份有活动的日期
|
||||
const loadActivityDates = async (year, month) => {
|
||||
const loadActivityDates = async (year: number, month: number) => {
|
||||
try {
|
||||
const res = await getDocumentActivityDates(year, month)
|
||||
if (res.data && res.data.dates) {
|
||||
|
|
@ -37,7 +39,7 @@ function Desktop() {
|
|||
}
|
||||
|
||||
// 加载指定日期的活动日志
|
||||
const loadActivityLogs = async (date) => {
|
||||
const loadActivityLogs = async (date: string) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await getDocumentActivity(date)
|
||||
|
|
@ -55,7 +57,7 @@ function Desktop() {
|
|||
}
|
||||
|
||||
// 日历单元格渲染
|
||||
const dateCellRender = (value, info) => {
|
||||
const dateCellRender = (value: Dayjs, info: { type: string; originNode: React.ReactElement }) => {
|
||||
if (info.type !== 'date') return info.originNode
|
||||
|
||||
const dateStr = value.format('YYYY-MM-DD')
|
||||
|
|
@ -83,19 +85,19 @@ function Desktop() {
|
|||
}
|
||||
|
||||
// 日期选择事件
|
||||
const onSelect = (date) => {
|
||||
const onSelect = (date: Dayjs) => {
|
||||
setSelectedDate(date)
|
||||
loadActivityLogs(date.format('YYYY-MM-DD'))
|
||||
}
|
||||
|
||||
// 月份切换事件
|
||||
const onPanelChange = (date) => {
|
||||
const onPanelChange = (date: Dayjs) => {
|
||||
setCurrentMonth(date)
|
||||
loadActivityDates(date.year(), date.month() + 1)
|
||||
}
|
||||
|
||||
// 点击文档打开
|
||||
const handleDocumentClick = (log) => {
|
||||
const handleDocumentClick = (log: ActivityLog) => {
|
||||
// 如果文件不存在,提示无法打开
|
||||
if (!log.file_exists) {
|
||||
Toast.warning('无法打开', '文件不存在或已被删除/移动/重命名')
|
||||
|
|
@ -117,7 +119,7 @@ function Desktop() {
|
|||
<PageHeader
|
||||
title="个人桌面"
|
||||
description="查看文档活动日历与每天的编辑轨迹,快速回到最近处理过的内容。"
|
||||
icon={<DesktopOutlined />}
|
||||
icon={<DesktopOutlined aria-hidden />}
|
||||
/>
|
||||
|
||||
<div className="admin-grid-2 desktop-grid">
|
||||
|
|
@ -135,7 +137,7 @@ function Desktop() {
|
|||
className="admin-card activity-card"
|
||||
title={(
|
||||
<div>
|
||||
<FileTextOutlined style={{ marginRight: 8 }} />
|
||||
<FileTextOutlined style={{ marginRight: 8 }} aria-hidden />
|
||||
{selectedDate.format('YYYY年MM月DD日')} 的文档活动
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -154,7 +156,7 @@ function Desktop() {
|
|||
<List.Item.Meta
|
||||
avatar={(
|
||||
<ClockCircleOutlined
|
||||
style={{
|
||||
aria-hidden style={{
|
||||
fontSize: 20,
|
||||
color: item.file_exists ? 'var(--link-color)' : 'var(--border-color-strong)'
|
||||
}}
|
||||
|
|
@ -187,7 +189,7 @@ function Desktop() {
|
|||
</Text>
|
||||
</div>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{new Date(item.created_at).toLocaleTimeString('zh-CN')}
|
||||
{item.created_at ? new Date(item.created_at).toLocaleTimeString('zh-CN') : '-'}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -362,7 +362,7 @@
|
|||
}
|
||||
|
||||
.docs-folder-item-icon.pdf {
|
||||
color: #f5222d;
|
||||
color: var(--color-pdf);
|
||||
}
|
||||
|
||||
.docs-folder-item-name {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,14 @@
|
|||
import { useState, useEffect, useRef, useMemo } from 'react'
|
||||
import {
|
||||
useMemo,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type HTMLAttributes,
|
||||
type MouseEvent,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import type { Components, ExtraProps } from 'react-markdown'
|
||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { Layout, Spin, Button, Tooltip, Modal, Input, Space, Dropdown, Empty, Switch, Select, TreeSelect, Radio, Alert } from 'antd'
|
||||
import { ShareAltOutlined, FileTextOutlined, FolderOutlined, FolderOpenOutlined, FilePdfOutlined, CopyOutlined, CloudDownloadOutlined, CloudUploadOutlined, ArrowLeftOutlined, ReloadOutlined, VerticalAlignTopOutlined } from '@ant-design/icons'
|
||||
|
|
@ -8,7 +18,7 @@ import 'highlight.js/styles/github.css'
|
|||
import Highlighter from 'react-highlight-words'
|
||||
import Mark from 'mark.js'
|
||||
import { getProjectTree, getFileContent, getDocumentUrl, getExportPdfUrl } from '@/api/file'
|
||||
import { gitPull, gitPush, getGitRepos, getGitRepoDirectories } from '@/api/project'
|
||||
import { gitPull, gitPush, getGitRepos, getGitRepoDirectories, type GitSyncScope } from '@/api/project'
|
||||
import { getFileShareInfo, createOrUpdateFileShare, deleteFileShare } from '@/api/share'
|
||||
import { searchDocuments } from '@/api/search'
|
||||
import { markProjectNotificationsRead } from '@/api/notification'
|
||||
|
|
@ -18,18 +28,32 @@ import FloatingToc from '@/components/FloatingToc/FloatingToc'
|
|||
import Toast from '@/components/Toast/Toast'
|
||||
import ModeSwitch from '@/components/ModeSwitch/ModeSwitch'
|
||||
import ProjectFileTree from '@/components/ProjectFileTree/ProjectFileTree'
|
||||
import LargeMarkdownViewer, { isLargeMarkdownContent } from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import { keyboardActivation } from '@/utils/a11yActivation'
|
||||
import LargeMarkdownViewer, {
|
||||
isLargeMarkdownContent,
|
||||
type LargeMarkdownViewerHandle,
|
||||
} from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import type { TocItem } from '@/components/FloatingToc/FloatingToc'
|
||||
import type {
|
||||
FileShareInfo,
|
||||
FileTreeNode,
|
||||
GitDirectoryNode,
|
||||
GitRepo,
|
||||
ProjectRole,
|
||||
} from '@/types/api'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import { MARKDOWN_VIEWER_PLUGINS } from '@/utils/markdownViewer'
|
||||
import { extractMarkdownHeadings } from '@/utils/markdownToc'
|
||||
import { findNodeByKey, findRootReadme, mergeParentKeys } from '@/utils/treeUtils'
|
||||
import './DocumentPage.css'
|
||||
import { clearInputIcon, decorativeAlertIcon, decorativeSwitcherIcon, passwordVisibilityIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Sider, Content } = Layout
|
||||
const ROOT_FOLDER_KEY = '__root__'
|
||||
|
||||
// 高亮渲染组件
|
||||
const HighlightText = ({ text, keyword }) => {
|
||||
if (!keyword || !text) return text;
|
||||
const HighlightText = ({ text, keyword }: { text?: string | null; keyword?: string }) => {
|
||||
if (!keyword || !text) return <>{text}</>;
|
||||
return (
|
||||
<Highlighter
|
||||
highlightClassName="search-highlight"
|
||||
|
|
@ -41,32 +65,34 @@ const HighlightText = ({ text, keyword }) => {
|
|||
}
|
||||
|
||||
function DocumentPage() {
|
||||
const { projectId } = useParams()
|
||||
const { projectId: projectIdParam } = useParams<{ projectId: string }>()
|
||||
const projectId = Number(projectIdParam)
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [fileTree, setFileTree] = useState([])
|
||||
const [fileTree, setFileTree] = useState<FileTreeNode[]>([])
|
||||
const [selectedFile, setSelectedFile] = useState('')
|
||||
const [selectedNodeKey, setSelectedNodeKey] = useState('')
|
||||
const [markdownContent, setMarkdownContent] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [openKeys, setOpenKeys] = useState([])
|
||||
const [tocItems, setTocItems] = useState([])
|
||||
const [openKeys, setOpenKeys] = useState<string[]>([])
|
||||
const [tocItems, setTocItems] = useState<TocItem[]>([])
|
||||
const [shareModalVisible, setShareModalVisible] = useState(false)
|
||||
const [shareInfo, setShareInfo] = useState(null)
|
||||
const [shareInfo, setShareInfo] = useState<FileShareInfo | null>(null)
|
||||
const [hasPassword, setHasPassword] = useState(false)
|
||||
const [password, setPassword] = useState('')
|
||||
const [userRole, setUserRole] = useState('viewer')
|
||||
const [userRole, setUserRole] = useState<ProjectRole | 'owner'>('viewer')
|
||||
const [pdfUrl, setPdfUrl] = useState('')
|
||||
const [pdfFilename, setPdfFilename] = useState('')
|
||||
const [viewMode, setViewMode] = useState('markdown')
|
||||
const [gitRepos, setGitRepos] = useState([])
|
||||
const [viewMode, setViewMode] = useState<'markdown' | 'pdf' | 'folder'>('markdown')
|
||||
const [gitRepos, setGitRepos] = useState<GitRepo[]>([])
|
||||
// Git 同步范围弹窗状态
|
||||
const [gitSyncModalVisible, setGitSyncModalVisible] = useState(false)
|
||||
const [gitSyncAction, setGitSyncAction] = useState(null) // 'pull' | 'push'
|
||||
const [gitSyncRepoId, setGitSyncRepoId] = useState(null)
|
||||
const [gitSyncScope, setGitSyncScope] = useState('all') // 'all' | 'dir'
|
||||
const [gitSyncAction, setGitSyncAction] = useState<'pull' | 'push' | null>(null)
|
||||
const [gitSyncRepoId, setGitSyncRepoId] = useState<number | null>(null)
|
||||
/** 弹窗内的选择:all = 整仓库,dir = 仅指定目录(提交时映射为后端的 all/path) */
|
||||
const [gitSyncScope, setGitSyncScope] = useState<'all' | 'dir'>('all')
|
||||
const [gitSyncSubPath, setGitSyncSubPath] = useState('')
|
||||
const [gitRemoteDirOptions, setGitRemoteDirOptions] = useState([])
|
||||
const [gitRemoteDirOptions, setGitRemoteDirOptions] = useState<GitDirectoryNode[]>([])
|
||||
const [gitSyncing, setGitSyncing] = useState(false)
|
||||
const [projectName, setProjectName] = useState('')
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
|
|
@ -75,19 +101,19 @@ function DocumentPage() {
|
|||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
// 知识库引用跳转专用:只高亮定位,不触发全文搜索、不过滤文件树
|
||||
const [highlightKeyword, setHighlightKeyword] = useState('')
|
||||
const [matchedFilePaths, setMatchedFilePaths] = useState(new Set())
|
||||
const [matchedFilePaths, setMatchedFilePaths] = useState<Set<string>>(new Set())
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [modeSwitchValue, setModeSwitchValue] = useState('view')
|
||||
|
||||
const contentRef = useRef(null)
|
||||
const largeMarkdownRef = useRef(null)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
const largeMarkdownRef = useRef<LargeMarkdownViewerHandle>(null)
|
||||
const modeSwitchingRef = useRef(false)
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState(null)
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState<HTMLDivElement | null>(null)
|
||||
const isLargeMarkdown = isLargeMarkdownContent(markdownContent)
|
||||
const isViewer = userRole === 'viewer'
|
||||
const canUseGit = userRole === 'owner' || userRole === 'admin'
|
||||
|
||||
const navigateWithTransition = (to) => {
|
||||
const navigateWithTransition = (to: string) => {
|
||||
if (document.startViewTransition) {
|
||||
document.startViewTransition(() => navigate(to))
|
||||
return
|
||||
|
|
@ -95,7 +121,7 @@ function DocumentPage() {
|
|||
navigate(to)
|
||||
}
|
||||
|
||||
const updateSelectedParam = (path, isFile = true) => {
|
||||
const updateSelectedParam = (path: string, isFile = true) => {
|
||||
const nextParams = new URLSearchParams(searchParams)
|
||||
nextParams.delete('file')
|
||||
nextParams.delete('selected')
|
||||
|
|
@ -106,15 +132,18 @@ function DocumentPage() {
|
|||
setSearchParams(nextParams, { replace: true })
|
||||
}
|
||||
|
||||
const updateFileParam = (filePath) => {
|
||||
const updateFileParam = (filePath: string) => {
|
||||
updateSelectedParam(filePath, true)
|
||||
}
|
||||
|
||||
const expandParentFolders = (path) => {
|
||||
const expandParentFolders = (path: string) => {
|
||||
setOpenKeys((prev) => mergeParentKeys(prev, path))
|
||||
}
|
||||
|
||||
const selectFolder = (folderPath, { syncUrl = false, expandSelf = false } = {}) => {
|
||||
const selectFolder = (
|
||||
folderPath: string,
|
||||
{ syncUrl = false, expandSelf = false }: { syncUrl?: boolean; expandSelf?: boolean } = {},
|
||||
) => {
|
||||
setSelectedFile('')
|
||||
setSelectedNodeKey(folderPath)
|
||||
setMarkdownContent('')
|
||||
|
|
@ -132,7 +161,7 @@ function DocumentPage() {
|
|||
}
|
||||
}
|
||||
|
||||
const selectRootFolder = ({ syncUrl = true } = {}) => {
|
||||
const selectRootFolder = ({ syncUrl = true }: { syncUrl?: boolean } = {}) => {
|
||||
setSelectedFile('')
|
||||
setSelectedNodeKey(ROOT_FOLDER_KEY)
|
||||
setMarkdownContent('')
|
||||
|
|
@ -149,9 +178,15 @@ function DocumentPage() {
|
|||
}
|
||||
|
||||
// 获取文件夹内的子节点(与左侧文件树保持一致:文件夹 + md/pdf 文档)
|
||||
const getFolderChildren = (folderPath) => {
|
||||
const getFolderChildren = (folderPath: string) => {
|
||||
const rootNode: FileTreeNode = {
|
||||
key: ROOT_FOLDER_KEY,
|
||||
title: projectName || '根目录',
|
||||
isLeaf: false,
|
||||
children: fileTree,
|
||||
}
|
||||
const node = folderPath === ROOT_FOLDER_KEY
|
||||
? { key: ROOT_FOLDER_KEY, title: projectName || '根目录', isLeaf: false, children: fileTree }
|
||||
? rootNode
|
||||
: folderPath ? findNodeByKey(fileTree, folderPath) : null
|
||||
if (!node || node.isLeaf) return { folders: [], files: [], node }
|
||||
const children = node.children || []
|
||||
|
|
@ -176,10 +211,10 @@ function DocumentPage() {
|
|||
const folderParts = folderPath && folderPath !== ROOT_FOLDER_KEY
|
||||
? folderPath.split('/').filter(Boolean)
|
||||
: []
|
||||
const items = [{
|
||||
const items: Array<{ key: string; label: React.ReactNode; icon: React.ReactNode; onClick?: () => void }> = [{
|
||||
key: ROOT_FOLDER_KEY,
|
||||
label: projectName || '根目录',
|
||||
icon: <FolderOutlined />,
|
||||
icon: <FolderOutlined aria-hidden />,
|
||||
onClick: () => selectRootFolder(),
|
||||
}]
|
||||
|
||||
|
|
@ -190,18 +225,18 @@ function DocumentPage() {
|
|||
items.push({
|
||||
key: path,
|
||||
label: part,
|
||||
icon: <FolderOutlined />,
|
||||
icon: <FolderOutlined aria-hidden />,
|
||||
onClick: () => selectFolder(path, { syncUrl: true }),
|
||||
})
|
||||
})
|
||||
|
||||
if (viewMode !== 'folder' && selectedFile) {
|
||||
const fileName = selectedFile.split('/').filter(Boolean).pop()
|
||||
const fileName = selectedFile.split('/').filter(Boolean).pop() ?? ''
|
||||
const isPdf = fileName.toLowerCase().endsWith('.pdf')
|
||||
items.push({
|
||||
key: selectedFile,
|
||||
label: isPdf ? fileName : fileName.replace(/\.md$/i, ''),
|
||||
icon: isPdf ? <FilePdfOutlined /> : <FileTextOutlined />,
|
||||
icon: isPdf ? <FilePdfOutlined aria-hidden /> : <FileTextOutlined aria-hidden />,
|
||||
})
|
||||
}
|
||||
return items
|
||||
|
|
@ -247,7 +282,7 @@ function DocumentPage() {
|
|||
)
|
||||
}
|
||||
|
||||
const openDocumentPath = (filePath, { syncUrl = false } = {}) => {
|
||||
const openDocumentPath = (filePath: string, { syncUrl = false }: { syncUrl?: boolean } = {}) => {
|
||||
setSelectedFile(filePath)
|
||||
setSelectedNodeKey(filePath)
|
||||
expandParentFolders(filePath)
|
||||
|
|
@ -258,7 +293,7 @@ function DocumentPage() {
|
|||
|
||||
if (filePath.toLowerCase().endsWith('.pdf')) {
|
||||
setPdfUrl(buildDocumentUrl(filePath))
|
||||
setPdfFilename(filePath.split('/').pop())
|
||||
setPdfFilename(filePath.split('/').pop() ?? '')
|
||||
setViewMode('pdf')
|
||||
} else {
|
||||
setViewMode('markdown')
|
||||
|
|
@ -266,7 +301,7 @@ function DocumentPage() {
|
|||
}
|
||||
}
|
||||
|
||||
const buildDocumentUrl = (filePath, refreshKey = null) => {
|
||||
const buildDocumentUrl = (filePath: string, refreshKey: string | number | null = null) => {
|
||||
const params = new URLSearchParams()
|
||||
const token = localStorage.getItem('access_token')
|
||||
|
||||
|
|
@ -338,7 +373,7 @@ function DocumentPage() {
|
|||
if (selectedNodeKey !== ROOT_FOLDER_KEY) {
|
||||
selectRootFolder({ syncUrl: false })
|
||||
}
|
||||
return
|
||||
return
|
||||
}
|
||||
const targetNode = findNodeByKey(fileTree, selectedParam)
|
||||
if (targetNode && !targetNode.isLeaf && selectedParam !== selectedNodeKey) {
|
||||
|
|
@ -363,7 +398,7 @@ function DocumentPage() {
|
|||
}, [searchParams, fileTree])
|
||||
|
||||
// 处理搜索
|
||||
const handleSearch = async (value) => {
|
||||
const handleSearch = async (value: string) => {
|
||||
// 先更新搜索状态,任何清理逻辑失败都不能阻断搜索
|
||||
setSearchKeyword(value)
|
||||
setHighlightKeyword('')
|
||||
|
|
@ -383,22 +418,25 @@ function DocumentPage() {
|
|||
}
|
||||
if (!value.trim()) {
|
||||
setMatchedFilePaths(new Set())
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
setIsSearching(true)
|
||||
try {
|
||||
const res = await searchDocuments(value, projectId)
|
||||
const paths = new Set(res.data.map(item => item.file_path))
|
||||
setMatchedFilePaths(paths)
|
||||
// 全局搜索也会返回项目级结果(没有 file_path),这里只取文件命中的路径
|
||||
const filePaths = res.data
|
||||
.map((item) => item.file_path)
|
||||
.filter((filePath): filePath is string => Boolean(filePath))
|
||||
setMatchedFilePaths(new Set(filePaths))
|
||||
|
||||
// 自动展开匹配的节点
|
||||
const keysToExpand = new Set(openKeys)
|
||||
res.data.forEach(item => {
|
||||
const parts = item.file_path.split('/')
|
||||
const keysToExpand = new Set<string>(openKeys)
|
||||
filePaths.forEach((filePath) => {
|
||||
const parts = filePath.split('/')
|
||||
let currentPath = ''
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i]
|
||||
currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i]
|
||||
keysToExpand.add(currentPath)
|
||||
}
|
||||
})
|
||||
|
|
@ -414,8 +452,8 @@ function DocumentPage() {
|
|||
const filteredTreeData = useMemo(() => {
|
||||
if (!searchKeyword.trim()) return fileTree
|
||||
|
||||
const loop = (data) => {
|
||||
const result = []
|
||||
const loop = (data: FileTreeNode[]): FileTreeNode[] => {
|
||||
const result: FileTreeNode[] = []
|
||||
for (const node of data) {
|
||||
const titleMatch = node.title.toLowerCase().includes(searchKeyword.toLowerCase())
|
||||
const contentMatch = matchedFilePaths.has(node.key)
|
||||
|
|
@ -468,7 +506,7 @@ function DocumentPage() {
|
|||
}
|
||||
|
||||
// 加载 markdown 文件
|
||||
const loadMarkdown = async (filePath) => {
|
||||
const loadMarkdown = async (filePath: string) => {
|
||||
setLoading(true)
|
||||
setTocItems([]) // 清空旧的目录数据
|
||||
try {
|
||||
|
|
@ -504,7 +542,7 @@ function DocumentPage() {
|
|||
})
|
||||
|
||||
return () => {
|
||||
canceled = true
|
||||
canceled = true
|
||||
cancel(taskId)
|
||||
}
|
||||
}, [markdownContent, isLargeMarkdown])
|
||||
|
|
@ -522,7 +560,7 @@ function DocumentPage() {
|
|||
} catch (error) {
|
||||
console.warn('清理搜索高亮失败:', error)
|
||||
}
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
let canceled = false
|
||||
|
|
@ -550,7 +588,7 @@ function DocumentPage() {
|
|||
}, 260)
|
||||
|
||||
return () => {
|
||||
canceled = true
|
||||
canceled = true
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
}, [loading, markdownContent, searchKeyword, viewMode, isLargeMarkdown])
|
||||
|
|
@ -568,13 +606,13 @@ function DocumentPage() {
|
|||
console.warn('清理引用高亮失败:', error)
|
||||
}
|
||||
}
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
// 超大文档走虚拟滚动,定位到包含关键词的文档块
|
||||
if (isLargeMarkdown) {
|
||||
largeMarkdownRef.current?.scrollToKeyword?.(highlightKeyword)
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
const container = contentRef.current
|
||||
|
|
@ -605,19 +643,19 @@ function DocumentPage() {
|
|||
}, 260)
|
||||
|
||||
return () => {
|
||||
canceled = true
|
||||
canceled = true
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
}, [loading, highlightKeyword, markdownContent, viewMode, isLargeMarkdown])
|
||||
|
||||
// 处理菜单点击
|
||||
const handleMenuClick = ({ key }) => {
|
||||
const handleMenuClick = ({ key }: { key: string }) => {
|
||||
const node = findNodeByKey(fileTree, key)
|
||||
if (!node) return
|
||||
|
||||
if (!node.isLeaf) {
|
||||
selectFolder(key, { syncUrl: true })
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
openDocumentPath(key, { syncUrl: true })
|
||||
|
|
@ -626,7 +664,7 @@ function DocumentPage() {
|
|||
const scrollContentToTop = () => {
|
||||
if (isLargeMarkdown) {
|
||||
largeMarkdownRef.current?.scrollToTop()
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
if (contentRef.current) {
|
||||
|
|
@ -645,7 +683,7 @@ function DocumentPage() {
|
|||
}
|
||||
|
||||
// 解析相对路径
|
||||
const resolveRelativePath = (currentPath, relativePath) => {
|
||||
const resolveRelativePath = (currentPath: string, relativePath: string) => {
|
||||
// 获取当前文件所在目录
|
||||
const currentDir = currentPath.substring(0, currentPath.lastIndexOf('/'))
|
||||
|
||||
|
|
@ -665,18 +703,18 @@ function DocumentPage() {
|
|||
return dirParts.join('/')
|
||||
}
|
||||
|
||||
const normalizeMarkdownHref = (href) => {
|
||||
if (!href) return href
|
||||
const normalizeMarkdownHref = (href?: string | null): string | undefined => {
|
||||
if (!href) return undefined
|
||||
|
||||
const [pathPart, hashPart = ''] = href.split('#')
|
||||
const [rawPath, searchPart = ''] = pathPart.split('?')
|
||||
|
||||
const decodedPath = rawPath
|
||||
const decodedPath: string = rawPath
|
||||
.split('/')
|
||||
.map((part) => {
|
||||
try {
|
||||
return decodeURIComponent(part)
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return part
|
||||
}
|
||||
})
|
||||
|
|
@ -686,12 +724,12 @@ function DocumentPage() {
|
|||
return hashPart ? `${rebuilt}#${hashPart}` : rebuilt
|
||||
}
|
||||
|
||||
const isExternalHref = (href) => {
|
||||
const isExternalHref = (href?: string | null): boolean => {
|
||||
return Boolean(href && (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith('//')))
|
||||
}
|
||||
|
||||
// 处理markdown内部链接点击
|
||||
const handleMarkdownLink = (e, href) => {
|
||||
const handleMarkdownLink = (e: MouseEvent<HTMLElement>, href?: string | null) => {
|
||||
const normalizedHref = normalizeMarkdownHref(href)
|
||||
|
||||
// 检查是否是外部链接
|
||||
|
|
@ -720,10 +758,10 @@ function DocumentPage() {
|
|||
let targetPath
|
||||
if (pathOnly.startsWith('.') || pathOnly.startsWith('..')) {
|
||||
// 真正的相对路径,相对于当前文件
|
||||
targetPath = resolveRelativePath(selectedFile, pathOnly)
|
||||
targetPath = resolveRelativePath(selectedFile, pathOnly)
|
||||
} else {
|
||||
// 项目内绝对路径(由编辑器生成),相对于项目根目录
|
||||
targetPath = pathOnly.startsWith('/') ? pathOnly.substring(1) : pathOnly
|
||||
targetPath = pathOnly.startsWith('/') ? pathOnly.substring(1) : pathOnly
|
||||
}
|
||||
|
||||
// 自动展开父目录
|
||||
|
|
@ -736,7 +774,7 @@ function DocumentPage() {
|
|||
const allParentPaths = []
|
||||
let currentPath = ''
|
||||
for (const part of pathParts) {
|
||||
currentPath = currentPath ? `${currentPath}/${part}` : part
|
||||
currentPath = currentPath ? `${currentPath}/${part}` : part
|
||||
allParentPaths.push(currentPath)
|
||||
}
|
||||
setOpenKeys([...new Set([...openKeys, ...allParentPaths])])
|
||||
|
|
@ -751,7 +789,7 @@ function DocumentPage() {
|
|||
if (isPdf) {
|
||||
// PDF文件:切换到PDF模式
|
||||
setPdfUrl(buildDocumentUrl(targetPath))
|
||||
setPdfFilename(targetPath.split('/').pop())
|
||||
setPdfFilename(targetPath.split('/').pop() ?? '')
|
||||
setViewMode('pdf')
|
||||
} else {
|
||||
// Markdown文件:加载内容
|
||||
|
|
@ -760,7 +798,7 @@ function DocumentPage() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleMarkdownContentClick = (event) => {
|
||||
const handleMarkdownContentClick = (event: MouseEvent<HTMLDivElement>) => {
|
||||
const target = event.target
|
||||
const anchor = target instanceof Element ? target.closest('a') : null
|
||||
if (!anchor) return
|
||||
|
|
@ -771,13 +809,18 @@ function DocumentPage() {
|
|||
if (isExternalHref(href)) {
|
||||
event.preventDefault()
|
||||
window.open(href, '_blank', 'noopener,noreferrer')
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
handleMarkdownLink(event, href)
|
||||
}
|
||||
|
||||
const handleGitPull = async (repoId = null, force = false, syncScope = null, subPath = '') => {
|
||||
const handleGitPull = async (
|
||||
repoId: number | null = null,
|
||||
force = false,
|
||||
syncScope: GitSyncScope | null = null,
|
||||
subPath = '',
|
||||
) => {
|
||||
if (gitRepos.length === 0) {
|
||||
Toast.warning('未配置Git仓库')
|
||||
return false
|
||||
|
|
@ -802,7 +845,7 @@ function DocumentPage() {
|
|||
return true
|
||||
} catch (error) {
|
||||
console.error('Git Pull error:', error)
|
||||
const errorMsg = error.response?.data?.detail || 'Git Pull 失败'
|
||||
const errorMsg = getApiErrorDetail(error) || 'Git Pull 失败'
|
||||
|
||||
// 目录级同步不提供强制重置(强制重置作用于整个仓库,与目录同步语义冲突)
|
||||
if (!force && !subPath) {
|
||||
|
|
@ -832,7 +875,12 @@ function DocumentPage() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleGitPush = async (repoId = null, force = false, syncScope = null, subPath = '') => {
|
||||
const handleGitPush = async (
|
||||
repoId: number | null = null,
|
||||
force = false,
|
||||
syncScope: GitSyncScope | null = null,
|
||||
subPath = '',
|
||||
) => {
|
||||
if (gitRepos.length === 0) {
|
||||
Toast.warning('未配置Git仓库')
|
||||
return false
|
||||
|
|
@ -851,7 +899,7 @@ function DocumentPage() {
|
|||
return true
|
||||
} catch (error) {
|
||||
console.error('Git Push error:', error)
|
||||
const errorMsg = error.response?.data?.detail || 'Git Push 失败'
|
||||
const errorMsg = getApiErrorDetail(error) || 'Git Push 失败'
|
||||
|
||||
if (!force && !subPath) {
|
||||
Toast.confirm({
|
||||
|
|
@ -882,9 +930,9 @@ function DocumentPage() {
|
|||
|
||||
// 构建项目目录树选项(仅文件夹,用于选择同步目录)
|
||||
const gitDirTreeData = useMemo(() => {
|
||||
const build = (nodes) => (nodes || [])
|
||||
.filter(n => !n.isLeaf)
|
||||
.map(n => ({
|
||||
const build = (nodes: FileTreeNode[] | undefined): GitDirectoryNode[] => (nodes || [])
|
||||
.filter((n) => !n.isLeaf)
|
||||
.map((n) => ({
|
||||
title: n.title,
|
||||
value: n.key,
|
||||
children: n.children ? build(n.children) : [],
|
||||
|
|
@ -893,14 +941,14 @@ function DocumentPage() {
|
|||
}, [fileTree])
|
||||
|
||||
// 加载指定仓库的远端目录结构(用于选择同步目录)
|
||||
const loadGitRemoteDirs = (repoId = null) => {
|
||||
const loadGitRemoteDirs = (repoId: number | null = null) => {
|
||||
getGitRepoDirectories(projectId, repoId)
|
||||
.then((res) => setGitRemoteDirOptions(res.data?.directories || []))
|
||||
.catch(() => setGitRemoteDirOptions([]))
|
||||
}
|
||||
|
||||
// 打开 Git 同步范围弹窗
|
||||
const openGitSyncModal = (action, repoId = null) => {
|
||||
const openGitSyncModal = (action: 'pull' | 'push', repoId: number | null = null) => {
|
||||
const targetRepo = repoId
|
||||
? gitRepos.find(r => r.id === repoId)
|
||||
: (gitRepos.find(r => r.is_default === 1) || gitRepos[0])
|
||||
|
|
@ -910,7 +958,7 @@ function DocumentPage() {
|
|||
setGitSyncSubPath(targetRepo?.sync_path || '')
|
||||
setGitSyncModalVisible(true)
|
||||
// 加载该仓库远端目录结构(覆盖本地未拉取时的空树)
|
||||
loadGitRemoteDirs(targetRepo?.id)
|
||||
loadGitRemoteDirs(targetRepo?.id ?? null)
|
||||
}
|
||||
|
||||
// 确认执行同步
|
||||
|
|
@ -920,8 +968,8 @@ function DocumentPage() {
|
|||
try {
|
||||
const syncScope = gitSyncScope === 'dir' ? 'path' : 'all'
|
||||
const success = gitSyncAction === 'pull'
|
||||
? await handleGitPull(gitSyncRepoId || undefined, false, syncScope, subPath)
|
||||
: await handleGitPush(gitSyncRepoId || undefined, false, syncScope, subPath)
|
||||
? await handleGitPull(gitSyncRepoId, false, syncScope, subPath)
|
||||
: await handleGitPush(gitSyncRepoId, false, syncScope, subPath)
|
||||
if (success) {
|
||||
setGitSyncModalVisible(false)
|
||||
}
|
||||
|
|
@ -935,9 +983,10 @@ function DocumentPage() {
|
|||
<Tooltip title="Git Pull(可选择同步目录)">
|
||||
<Button
|
||||
size="middle"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={() => openGitSyncModal('pull')}
|
||||
disabled={disabled}
|
||||
aria-label="Git Pull(可选择同步目录)"
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
|
|
@ -946,9 +995,10 @@ function DocumentPage() {
|
|||
<Tooltip title="Git Push(可选择同步目录)">
|
||||
<Button
|
||||
size="middle"
|
||||
icon={<CloudUploadOutlined />}
|
||||
icon={<CloudUploadOutlined aria-hidden />}
|
||||
onClick={() => openGitSyncModal('push')}
|
||||
disabled={disabled}
|
||||
aria-label="Git Push(可选择同步目录)"
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
|
|
@ -1018,7 +1068,7 @@ function DocumentPage() {
|
|||
const selectedNode = selectedNodeKey ? findNodeByKey(fileTree, selectedNodeKey) : null
|
||||
if (!selectedNode || !selectedNode.isLeaf) {
|
||||
Toast.warning('提示', '请先选择一个文件再分享')
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -1068,7 +1118,7 @@ function DocumentPage() {
|
|||
}
|
||||
|
||||
// 切换密码保护
|
||||
const handlePasswordToggle = async (checked) => {
|
||||
const handlePasswordToggle = async (checked: boolean) => {
|
||||
if (!selectedNodeKey) return
|
||||
|
||||
if (!checked) {
|
||||
|
|
@ -1097,12 +1147,12 @@ function DocumentPage() {
|
|||
const handleSavePassword = async () => {
|
||||
if (!selectedNodeKey) {
|
||||
Toast.warning('请先选择文件')
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
if (!password.trim()) {
|
||||
Toast.warning('请输入访问密码')
|
||||
return
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res = await createOrUpdateFileShare(projectId, {
|
||||
|
|
@ -1124,7 +1174,7 @@ function DocumentPage() {
|
|||
const handleCreateShare = async () => {
|
||||
if (!selectedNodeKey) {
|
||||
Toast.warning('请先选择文件')
|
||||
return
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -1164,10 +1214,10 @@ function DocumentPage() {
|
|||
// 使用 components 替换文本节点,但这只对直接文本子节点有效
|
||||
// 对于深层嵌套,我们需要递归或使用 rehype 插件
|
||||
// 这里使用简单组件替换
|
||||
const markdownComponents = useMemo(() => {
|
||||
const markdownComponents = useMemo<Components>(() => {
|
||||
if (!searchKeyword) {
|
||||
return {
|
||||
a: ({ node, href, children, ...props }) => {
|
||||
a: ({ node, href, children, ...props }: ComponentProps<'a'> & ExtraProps) => {
|
||||
const isExternal = isExternalHref(href);
|
||||
return (
|
||||
<a
|
||||
|
|
@ -1186,14 +1236,22 @@ function DocumentPage() {
|
|||
|
||||
// 搜索模式下,尝试高亮
|
||||
// 注意:这可能不完美,但比没有好
|
||||
const highlightRenderer = (Tag) => function HighlightedText({ node, children, ...props }) {
|
||||
type HighlightTag = 'p' | 'li' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'span' | 'td' | 'th' | 'div'
|
||||
|
||||
// 这些标签只需要通用 HTML 属性;用联合标签渲染可避免逐标签穷举 props
|
||||
const highlightRenderer = (Tag: HighlightTag) =>
|
||||
function HighlightedText({
|
||||
node,
|
||||
children,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLElement> & ExtraProps) {
|
||||
// 如果 children 是字符串,高亮
|
||||
if (typeof children === 'string') {
|
||||
return <Tag {...props}><HighlightText text={children} keyword={searchKeyword} /></Tag>
|
||||
}
|
||||
// 如果是数组,遍历
|
||||
if (Array.isArray(children)) {
|
||||
const newChildren = children.map((child, idx) => {
|
||||
const newChildren = (children as ReactNode[]).map((child, idx) => {
|
||||
if (typeof child === 'string') {
|
||||
return <HighlightText key={idx} text={child} keyword={searchKeyword} />
|
||||
}
|
||||
|
|
@ -1205,7 +1263,7 @@ function DocumentPage() {
|
|||
}
|
||||
|
||||
return {
|
||||
a: ({ node, href, children, ...props }) => {
|
||||
a: ({ node, href, children, ...props }: ComponentProps<'a'> & ExtraProps) => {
|
||||
const isExternal = isExternalHref(href);
|
||||
return (
|
||||
<a
|
||||
|
|
@ -1247,7 +1305,7 @@ function DocumentPage() {
|
|||
onClick={handleClose}
|
||||
aria-label="返回项目列表"
|
||||
>
|
||||
<ArrowLeftOutlined />
|
||||
<ArrowLeftOutlined aria-hidden />
|
||||
</button>
|
||||
<h2 title={projectName || '项目浏览'}>{projectName || '项目浏览'}</h2>
|
||||
</div>
|
||||
|
|
@ -1273,17 +1331,19 @@ function DocumentPage() {
|
|||
<Tooltip title="分享">
|
||||
<Button
|
||||
size="middle"
|
||||
icon={<ShareAltOutlined />}
|
||||
icon={<ShareAltOutlined aria-hidden />}
|
||||
onClick={handleShare}
|
||||
disabled={isViewer}
|
||||
aria-label="分享"
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title="刷新">
|
||||
<Button
|
||||
size="middle"
|
||||
icon={<ReloadOutlined spin={refreshing} />}
|
||||
icon={<ReloadOutlined aria-hidden spin={refreshing} />}
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing}
|
||||
aria-label="刷新"
|
||||
/>
|
||||
</Tooltip>
|
||||
</Space.Compact>
|
||||
|
|
@ -1295,12 +1355,12 @@ function DocumentPage() {
|
|||
<div style={{ padding: '12px 16px 4px' }}>
|
||||
<Input.Search
|
||||
placeholder="搜索文档内容..."
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
value={searchKeyword}
|
||||
onChange={(e) => setSearchKeyword(e.target.value)}
|
||||
onSearch={handleSearch}
|
||||
loading={isSearching}
|
||||
enterButton
|
||||
enterButton={searchEnterButton({ primary: true, loading: isSearching })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -1325,14 +1385,14 @@ function DocumentPage() {
|
|||
{viewMode === 'markdown' && (
|
||||
<Space className="docs-header-actions">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollContentToTop}
|
||||
size="small"
|
||||
>
|
||||
回到顶部
|
||||
</Button>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleExportMarkdownPDF}
|
||||
size="small"
|
||||
>
|
||||
|
|
@ -1360,7 +1420,7 @@ function DocumentPage() {
|
|||
if (!node || node.isLeaf) {
|
||||
return (
|
||||
<div className="docs-folder-placeholder">
|
||||
<FolderOpenOutlined />
|
||||
<FolderOpenOutlined aria-hidden />
|
||||
<span>已选择文件夹,请从左侧选择 Markdown 或 PDF 文件查看。</span>
|
||||
</div>
|
||||
)
|
||||
|
|
@ -1381,9 +1441,11 @@ function DocumentPage() {
|
|||
key={sub.key}
|
||||
className="docs-folder-item"
|
||||
onClick={() => selectFolder(sub.key, { syncUrl: true, expandSelf: true })}
|
||||
{...keyboardActivation(() => selectFolder(sub.key, { syncUrl: true, expandSelf: true }))}
|
||||
aria-label={`打开文件夹:${sub.title}`}
|
||||
title={sub.title}
|
||||
>
|
||||
<FolderOutlined className="docs-folder-item-icon" />
|
||||
<FolderOutlined aria-hidden className="docs-folder-item-icon" />
|
||||
<span className="docs-folder-item-name">{sub.title}</span>
|
||||
<span className="docs-folder-item-count">{sub.children?.length || 0} 项</span>
|
||||
</div>
|
||||
|
|
@ -1396,14 +1458,16 @@ function DocumentPage() {
|
|||
key={file.key}
|
||||
className="docs-folder-item docs-file-item"
|
||||
onClick={() => openDocumentPath(file.key, { syncUrl: true })}
|
||||
{...keyboardActivation(() => openDocumentPath(file.key, { syncUrl: true }))}
|
||||
aria-label={`打开文档:${file.title}`}
|
||||
title={file.title}
|
||||
>
|
||||
{isPdf
|
||||
? <FilePdfOutlined className="docs-folder-item-icon pdf" />
|
||||
: <FileTextOutlined className="docs-folder-item-icon md" />}
|
||||
? <FilePdfOutlined aria-hidden className="docs-folder-item-icon pdf" />
|
||||
: <FileTextOutlined aria-hidden className="docs-folder-item-icon md" />}
|
||||
<span className="docs-folder-item-name">
|
||||
{displayName}
|
||||
{file.is_shared && <ShareAltOutlined className="docs-folder-item-share" title="已分享" />}
|
||||
{file.is_shared && <ShareAltOutlined aria-hidden className="docs-folder-item-share" title="已分享" />}
|
||||
</span>
|
||||
<span className="docs-folder-item-count">{isPdf ? 'PDF 文档' : 'Markdown 文档'}</span>
|
||||
</div>
|
||||
|
|
@ -1472,7 +1536,12 @@ function DocumentPage() {
|
|||
value={`${window.location.origin}${shareInfo.share_url}`}
|
||||
readOnly
|
||||
addonAfter={
|
||||
<CopyOutlined onClick={handleCopyLink} style={{ cursor: 'pointer' }} />
|
||||
<CopyOutlined
|
||||
aria-label="复制分享链接"
|
||||
onClick={handleCopyLink}
|
||||
{...keyboardActivation(() => handleCopyLink())}
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -1487,6 +1556,7 @@ function DocumentPage() {
|
|||
{hasPassword && (
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input.Password
|
||||
iconRender={passwordVisibilityIcon}
|
||||
placeholder="请输入访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
|
|
@ -1527,7 +1597,7 @@ function DocumentPage() {
|
|||
<Button
|
||||
key="pull"
|
||||
type="primary"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
loading={gitSyncing}
|
||||
disabled={gitSyncAction !== 'pull'}
|
||||
onClick={confirmGitSync}
|
||||
|
|
@ -1537,7 +1607,7 @@ function DocumentPage() {
|
|||
<Button
|
||||
key="push"
|
||||
type="primary"
|
||||
icon={<CloudUploadOutlined />}
|
||||
icon={<CloudUploadOutlined aria-hidden />}
|
||||
loading={gitSyncing}
|
||||
disabled={gitSyncAction !== 'push'}
|
||||
onClick={confirmGitSync}
|
||||
|
|
@ -1553,6 +1623,7 @@ function DocumentPage() {
|
|||
<Select
|
||||
style={{ width: '100%' }}
|
||||
value={gitSyncRepoId}
|
||||
aria-label="Git 仓库"
|
||||
onChange={(id) => {
|
||||
setGitSyncRepoId(id)
|
||||
const repo = gitRepos.find(r => r.id === id)
|
||||
|
|
@ -1588,8 +1659,10 @@ function DocumentPage() {
|
|||
仅将所选目录与远程仓库同步(其他目录不受影响)
|
||||
</div>
|
||||
<TreeSelect
|
||||
switcherIcon={decorativeSwitcherIcon}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择要同步的项目目录"
|
||||
aria-label="选择要同步的项目目录"
|
||||
value={gitSyncSubPath || undefined}
|
||||
onChange={setGitSyncSubPath}
|
||||
treeData={gitRemoteDirOptions.length ? gitRemoteDirOptions : gitDirTreeData}
|
||||
|
|
@ -1608,6 +1681,7 @@ function DocumentPage() {
|
|||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
icon={decorativeAlertIcon('info')}
|
||||
message="目录级推送仅提交并推送所选目录的变更,不支持强制推送;若提示历史不一致,请先执行「整个仓库」拉取后再推送。"
|
||||
/>
|
||||
)}
|
||||
|
|
@ -5,29 +5,33 @@
|
|||
* 单独成模块,便于编辑页与测试复用同一份判定逻辑。
|
||||
*/
|
||||
|
||||
export const EDITOR_VIEW_MODES = ['edit', 'split', 'preview']
|
||||
export const EDITOR_VIEW_MODES = ['edit', 'split', 'preview'] as const
|
||||
|
||||
export type EditorViewMode = (typeof EDITOR_VIEW_MODES)[number]
|
||||
|
||||
export const EDITOR_VIEW_MODE_STORAGE_KEY = 'nexdocus.editor.viewMode'
|
||||
|
||||
export const DEFAULT_EDITOR_VIEW_MODE = 'edit'
|
||||
|
||||
export const EDITOR_VIEW_MODE_LABELS = {
|
||||
export const EDITOR_VIEW_MODE_LABELS: Record<EditorViewMode, string> = {
|
||||
edit: '编辑',
|
||||
split: '分栏',
|
||||
preview: '预览',
|
||||
}
|
||||
|
||||
// 工具栏里只放图标,悬浮提示补全含义,避免与同行图标风格不一致,也避免窄屏时工具栏被挤到换行
|
||||
export const EDITOR_VIEW_MODE_HINTS = {
|
||||
export const EDITOR_VIEW_MODE_HINTS: Record<EditorViewMode, string> = {
|
||||
edit: '仅编辑区',
|
||||
split: '编辑区 + 预览区',
|
||||
preview: '仅预览区',
|
||||
}
|
||||
|
||||
export function readEditorViewMode(storage) {
|
||||
export function readEditorViewMode(storage?: Pick<Storage, 'getItem'> | null): EditorViewMode {
|
||||
try {
|
||||
const saved = (storage || window.localStorage).getItem(EDITOR_VIEW_MODE_STORAGE_KEY)
|
||||
return EDITOR_VIEW_MODES.includes(saved) ? saved : DEFAULT_EDITOR_VIEW_MODE
|
||||
return EDITOR_VIEW_MODES.includes(saved as EditorViewMode)
|
||||
? (saved as EditorViewMode)
|
||||
: DEFAULT_EDITOR_VIEW_MODE
|
||||
} catch (error) {
|
||||
return DEFAULT_EDITOR_VIEW_MODE
|
||||
}
|
||||
|
|
@ -2,29 +2,31 @@ import { useState } from 'react'
|
|||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { Form, Input, Button, Tabs } from 'antd'
|
||||
import { UserOutlined, LockOutlined, MailOutlined, ArrowRightOutlined } from '@ant-design/icons'
|
||||
import { login, register } from '@/api/auth'
|
||||
import { login, register, type LoginPayload, type RegisterPayload } from '@/api/auth'
|
||||
import { getUserMenus } from '@/api/menu'
|
||||
import useUserStore from '@/stores/userStore'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { setAuthStorage } from '@/utils/authStorage'
|
||||
import { getApiErrorMessage } from '@/utils/apiError'
|
||||
import './Login.css'
|
||||
import { passwordVisibilityIcon } from '@/utils/antdA11y'
|
||||
|
||||
function Login() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [activeTab, setActiveTab] = useState('login')
|
||||
const [loginForm] = Form.useForm()
|
||||
const [loginForm] = Form.useForm<LoginPayload>()
|
||||
const navigate = useNavigate()
|
||||
const [searchParams] = useSearchParams()
|
||||
const { setUser, setToken } = useUserStore()
|
||||
|
||||
const handleLogin = async (values) => {
|
||||
const handleLogin = async (values: LoginPayload) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await login(values)
|
||||
Toast.success('登录成功')
|
||||
|
||||
// 保存 token 和用户信息
|
||||
localStorage.setItem('access_token', res.data.access_token)
|
||||
localStorage.setItem('user_info', JSON.stringify(res.data.user))
|
||||
setAuthStorage(res.data.access_token, res.data.user)
|
||||
setToken(res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
|
||||
|
|
@ -40,8 +42,9 @@ function Login() {
|
|||
if (menuRes.data && menuRes.data.length > 0) {
|
||||
const firstMenu = menuRes.data[0]
|
||||
// 如果第一个菜单有子菜单,跳转到第一个子菜单
|
||||
if (firstMenu.children && firstMenu.children.length > 0) {
|
||||
navigate(firstMenu.children[0].path)
|
||||
const firstChildPath = firstMenu.children?.[0]?.path
|
||||
if (firstChildPath) {
|
||||
navigate(firstChildPath)
|
||||
} else if (firstMenu.path) {
|
||||
navigate(firstMenu.path)
|
||||
} else {
|
||||
|
|
@ -59,14 +62,14 @@ function Login() {
|
|||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '登录失败,请检查用户名和密码'
|
||||
const errorMsg = getApiErrorMessage(error, '登录失败,请检查用户名和密码')
|
||||
Toast.error('登录失败', errorMsg)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRegister = async (values) => {
|
||||
const handleRegister = async (values: RegisterPayload) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
await register(values)
|
||||
|
|
@ -74,7 +77,7 @@ function Login() {
|
|||
setActiveTab('login')
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '注册失败'
|
||||
const errorMsg = getApiErrorMessage(error, '注册失败')
|
||||
Toast.error('注册失败', errorMsg)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
|
|
@ -139,7 +142,7 @@ function Login() {
|
|||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
|
||||
prefix={<UserOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="请输入用户名"
|
||||
size="large"
|
||||
/>
|
||||
|
|
@ -151,7 +154,8 @@ function Login() {
|
|||
rules={[{ required: true, message: '请输入密码' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
|
||||
iconRender={passwordVisibilityIcon}
|
||||
prefix={<LockOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="请输入密码"
|
||||
size="large"
|
||||
visibilityToggle
|
||||
|
|
@ -165,7 +169,7 @@ function Login() {
|
|||
loading={loading}
|
||||
block
|
||||
size="large"
|
||||
icon={<ArrowRightOutlined />}
|
||||
icon={<ArrowRightOutlined aria-hidden />}
|
||||
iconPosition="end"
|
||||
>
|
||||
立即登录
|
||||
|
|
@ -197,7 +201,7 @@ function Login() {
|
|||
]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
|
||||
prefix={<UserOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="用户名"
|
||||
size="large"
|
||||
/>
|
||||
|
|
@ -211,7 +215,7 @@ function Login() {
|
|||
]}
|
||||
>
|
||||
<Input
|
||||
prefix={<MailOutlined style={{ color: '#bfbfbf' }} />}
|
||||
prefix={<MailOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="邮箱(选填)"
|
||||
size="large"
|
||||
/>
|
||||
|
|
@ -226,7 +230,8 @@ function Login() {
|
|||
]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
|
||||
iconRender={passwordVisibilityIcon}
|
||||
prefix={<LockOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="密码"
|
||||
size="large"
|
||||
/>
|
||||
|
|
@ -249,7 +254,8 @@ function Login() {
|
|||
]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
|
||||
iconRender={passwordVisibilityIcon}
|
||||
prefix={<LockOutlined aria-hidden style={{ color: 'var(--border-color-strong)' }} />}
|
||||
placeholder="确认密码"
|
||||
size="large"
|
||||
/>
|
||||
|
|
@ -9,6 +9,8 @@ import {
|
|||
} from '@ant-design/icons'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { getNotifications, markAsRead, markAllAsRead } from '@/api/notification'
|
||||
import { namePageItem } from '@/utils/antdA11y'
|
||||
import type { NotificationItem } from '@/types/api'
|
||||
import useNotificationStore from '@/stores/notificationStore'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
|
|
@ -17,7 +19,7 @@ const { Content } = Layout
|
|||
const { Text } = Typography
|
||||
|
||||
function NotificationList() {
|
||||
const [notifications, setNotifications] = useState([])
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
|
|
@ -39,7 +41,7 @@ function NotificationList() {
|
|||
unread_only: activeTab === 'unread'
|
||||
})
|
||||
setNotifications(res.data || [])
|
||||
setTotal(res.meta?.total || 0)
|
||||
setTotal(res.total || 0)
|
||||
} catch (error) {
|
||||
console.error('Fetch notifications error:', error)
|
||||
Toast.error('加载失败', '无法获取通知列表')
|
||||
|
|
@ -48,7 +50,7 @@ function NotificationList() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleMarkRead = async (id) => {
|
||||
const handleMarkRead = async (id: string | number) => {
|
||||
try {
|
||||
await markAsRead(id)
|
||||
setNotifications(notifications.map(n => n.id === id ? { ...n, is_read: true } : n))
|
||||
|
|
@ -69,7 +71,7 @@ function NotificationList() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleNotificationClick = (n) => {
|
||||
const handleNotificationClick = (n: NotificationItem) => {
|
||||
if (!n.is_read) {
|
||||
handleMarkRead(n.id)
|
||||
}
|
||||
|
|
@ -78,11 +80,11 @@ function NotificationList() {
|
|||
}
|
||||
}
|
||||
|
||||
const getCategoryIcon = (category) => {
|
||||
const getCategoryIcon = (category: string) => {
|
||||
switch (category) {
|
||||
case 'project': return <ProjectOutlined style={{ color: 'var(--color-primary)' }} />
|
||||
case 'collaboration': return <TeamOutlined style={{ color: 'var(--color-success)' }} />
|
||||
default: return <NotificationOutlined style={{ color: 'var(--color-warning)' }} />
|
||||
case 'project': return <ProjectOutlined aria-hidden style={{ color: 'var(--color-primary)' }} />
|
||||
case 'collaboration': return <TeamOutlined aria-hidden style={{ color: 'var(--color-success)' }} />
|
||||
default: return <NotificationOutlined aria-hidden style={{ color: 'var(--color-warning)' }} />
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -92,9 +94,9 @@ function NotificationList() {
|
|||
<div className="notification-list-page">
|
||||
<PageHeader
|
||||
title="消息中心"
|
||||
icon={<BellOutlined />}
|
||||
icon={<BellOutlined aria-hidden />}
|
||||
extra={
|
||||
<Button icon={<CheckOutlined />} onClick={handleMarkAllRead}>
|
||||
<Button icon={<CheckOutlined aria-hidden />} onClick={handleMarkAllRead}>
|
||||
全部标记为已读
|
||||
</Button>
|
||||
}
|
||||
|
|
@ -147,7 +149,7 @@ function NotificationList() {
|
|||
<div style={{ display: 'flex', gap: '16px' }}>
|
||||
<Avatar
|
||||
icon={getCategoryIcon(item.category)}
|
||||
style={{ background: 'var(--bg-color-secondary)' }}
|
||||
style={{ background: 'var(--bg-color-secondary)' }} aria-hidden
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
|
||||
|
|
@ -175,6 +177,7 @@ function NotificationList() {
|
|||
pageSize={pageSize}
|
||||
onChange={setPage}
|
||||
showSizeChanger={false}
|
||||
itemRender={namePageItem}
|
||||
/>
|
||||
</div>
|
||||
</Content>
|
||||
|
|
@ -1,16 +1,19 @@
|
|||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useState, useEffect, useRef, type MouseEvent } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { Layout, Modal, Input, Spin, Button, Space, Tooltip } from 'antd'
|
||||
import { LockOutlined, FileTextOutlined, FilePdfOutlined, VerticalAlignTopOutlined, CloudDownloadOutlined, MenuOutlined, CloseOutlined } from '@ant-design/icons'
|
||||
import { Viewer } from '@bytemd/react'
|
||||
import type { Components } from 'react-markdown'
|
||||
import 'bytemd/dist/index.css'
|
||||
import 'highlight.js/styles/github.css'
|
||||
import GithubSlugger from 'github-slugger'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import FloatingToc, { TocDrawer } from '@/components/FloatingToc/FloatingToc'
|
||||
import FloatingToc, { TocDrawer, type TocItem } from '@/components/FloatingToc/FloatingToc'
|
||||
import VirtualPDFViewer from '@/components/PDFViewer/VirtualPDFViewer'
|
||||
import LargeMarkdownViewer, { isLargeMarkdownContent } from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import { MARKDOWN_VIEWER_PLUGINS } from '@/utils/markdownViewer'
|
||||
import type { FileShareContent, FileSharePublicInfo } from '@/types/api'
|
||||
import type { LargeMarkdownViewerHandle } from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import {
|
||||
getFileSharePublicInfo,
|
||||
verifyFileSharePassword,
|
||||
|
|
@ -18,26 +21,27 @@ import {
|
|||
exportFileSharePDF,
|
||||
} from '@/api/share'
|
||||
import './PreviewPage.css'
|
||||
import { passwordVisibilityIcon } from '@/utils/antdA11y'
|
||||
|
||||
const { Content } = Layout
|
||||
|
||||
// 查找内容区实际可滚动的容器(普通 MD:主内容区;PDF/大文档:内部滚动容器)
|
||||
const findScrollableEl = (root) => {
|
||||
const findScrollableEl = (root: HTMLElement | null): HTMLElement | null => {
|
||||
if (!root) return null
|
||||
if (root.scrollHeight > root.clientHeight + 1) return root
|
||||
const inner = root.querySelector('.pdf-content, .markdown-virtual-list')
|
||||
const inner = root.querySelector<HTMLElement>('.pdf-content, .markdown-virtual-list')
|
||||
if (inner && inner.scrollHeight > inner.clientHeight + 1) return inner
|
||||
return null
|
||||
}
|
||||
|
||||
function FileSharePage() {
|
||||
const { shareCode } = useParams()
|
||||
const { shareCode = '' } = useParams<{ shareCode: string }>()
|
||||
const navigate = useNavigate()
|
||||
const contentRef = useRef(null)
|
||||
const largeMarkdownRef = useRef(null)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
const largeMarkdownRef = useRef<LargeMarkdownViewerHandle>(null)
|
||||
const [headerVisible, setHeaderVisible] = useState(false)
|
||||
const headerHoveringRef = useRef(false)
|
||||
const headerHideTimerRef = useRef(null)
|
||||
const headerHideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const clearHeaderHideTimer = () => {
|
||||
if (headerHideTimerRef.current) {
|
||||
clearTimeout(headerHideTimerRef.current)
|
||||
|
|
@ -62,12 +66,12 @@ function FileSharePage() {
|
|||
const target = root ? findScrollableEl(root) : null
|
||||
if (target && target.scrollTop > 8) scheduleHeaderHide()
|
||||
}
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState(null)
|
||||
const [, setShareInfo] = useState(null)
|
||||
const [contentInfo, setContentInfo] = useState(null)
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState<HTMLDivElement | null>(null)
|
||||
const [, setShareInfo] = useState<FileSharePublicInfo | null>(null)
|
||||
const [contentInfo, setContentInfo] = useState<FileShareContent | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [isMobile, setIsMobile] = useState(false)
|
||||
const [tocItems, setTocItems] = useState([])
|
||||
const [tocItems, setTocItems] = useState<TocItem[]>([])
|
||||
const [tocDrawerVisible, setTocDrawerVisible] = useState(false)
|
||||
const [passwordModalVisible, setPasswordModalVisible] = useState(false)
|
||||
const [password, setPassword] = useState('')
|
||||
|
|
@ -89,8 +93,8 @@ function FileSharePage() {
|
|||
useEffect(() => {
|
||||
const root = contentRef.current
|
||||
if (!root) return
|
||||
const sync = (scrollEl = null) => {
|
||||
const target = scrollEl || findScrollableEl(root)
|
||||
const sync = (scrollEl: HTMLElement | EventTarget | null = null) => {
|
||||
const target = (scrollEl as HTMLElement | null) || findScrollableEl(root)
|
||||
if (!target) {
|
||||
clearHeaderHideTimer()
|
||||
setHeaderVisible(true)
|
||||
|
|
@ -104,7 +108,7 @@ function FileSharePage() {
|
|||
setHeaderVisible(false)
|
||||
}
|
||||
}
|
||||
const onScroll = (e) => sync(e.target)
|
||||
const onScroll = (e: Event) => sync(e.target)
|
||||
root.addEventListener('scroll', onScroll, true)
|
||||
sync()
|
||||
return () => {
|
||||
|
|
@ -120,8 +124,8 @@ function FileSharePage() {
|
|||
}
|
||||
|
||||
const slugger = new GithubSlugger()
|
||||
const headings = []
|
||||
markdownContent.split('\n').forEach((line) => {
|
||||
const headings: TocItem[] = []
|
||||
markdownContent.split('\n').forEach((line: string) => {
|
||||
const match = line.match(/^(#{1,6})\s+(.+)$/)
|
||||
if (!match) return
|
||||
const level = match[1].length
|
||||
|
|
@ -195,11 +199,11 @@ function FileSharePage() {
|
|||
}
|
||||
}
|
||||
|
||||
const isExternalHref = (href) => {
|
||||
const isExternalHref = (href?: string | null): boolean => {
|
||||
return Boolean(href && (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith('//')))
|
||||
}
|
||||
|
||||
const isInternalFileHref = (href) => {
|
||||
const isInternalFileHref = (href?: string | null): boolean => {
|
||||
if (!href) return false
|
||||
if (href.startsWith('#')) return false
|
||||
if (isExternalHref(href)) return false
|
||||
|
|
@ -207,13 +211,13 @@ function FileSharePage() {
|
|||
return pathOnly.endsWith('.md') || pathOnly.toLowerCase().endsWith('.pdf')
|
||||
}
|
||||
|
||||
const handleMarkdownLink = (e, href) => {
|
||||
const handleMarkdownLink = (e: MouseEvent<HTMLElement>, href?: string | null) => {
|
||||
if (!isInternalFileHref(href)) return
|
||||
e.preventDefault()
|
||||
Toast.error('无法打开内部文件链接', '单文件分享模式不支持跳转到其他内部文件')
|
||||
}
|
||||
|
||||
const handleMarkdownContentClick = (event) => {
|
||||
const handleMarkdownContentClick = (event: MouseEvent<HTMLDivElement>) => {
|
||||
const target = event.target
|
||||
const anchor = target instanceof Element ? target.closest('a') : null
|
||||
if (!anchor) return
|
||||
|
|
@ -230,7 +234,7 @@ function FileSharePage() {
|
|||
handleMarkdownLink(event, href)
|
||||
}
|
||||
|
||||
const markdownComponents = {
|
||||
const markdownComponents: Components = {
|
||||
a: ({ node, href, children, ...props }) => {
|
||||
const isExternal = isExternalHref(href)
|
||||
return (
|
||||
|
|
@ -266,10 +270,10 @@ function FileSharePage() {
|
|||
onClick={handleClose}
|
||||
aria-label="关闭"
|
||||
>
|
||||
<CloseOutlined />
|
||||
<CloseOutlined aria-hidden />
|
||||
</button>
|
||||
<h3 className="preview-header-title">
|
||||
<HeaderIcon className="preview-header-icon" style={isHeaderPdf ? { color: '#f5222d' } : undefined} />
|
||||
<HeaderIcon className="preview-header-icon" style={isHeaderPdf ? { color: 'var(--color-pdf)' } : undefined} />
|
||||
<span className="preview-header-text">{headerLabel}</span>
|
||||
</h3>
|
||||
{contentInfo?.type === 'markdown' && (
|
||||
|
|
@ -277,7 +281,7 @@ function FileSharePage() {
|
|||
<Space className="preview-header-actions preview-compact-actions" size={4}>
|
||||
<Tooltip title="回到顶部">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollContentToTop}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -286,7 +290,7 @@ function FileSharePage() {
|
|||
</Tooltip>
|
||||
<Tooltip title="下载PDF">
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleExportPDF}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -296,7 +300,7 @@ function FileSharePage() {
|
|||
{!isLargeMarkdown && (
|
||||
<Tooltip title="文档索引">
|
||||
<Button
|
||||
icon={<MenuOutlined />}
|
||||
icon={<MenuOutlined aria-hidden />}
|
||||
onClick={() => setTocDrawerVisible(true)}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -308,14 +312,14 @@ function FileSharePage() {
|
|||
) : (
|
||||
<Space className="preview-header-actions">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollContentToTop}
|
||||
size="small"
|
||||
>
|
||||
回到顶部
|
||||
</Button>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleExportPDF}
|
||||
size="small"
|
||||
>
|
||||
|
|
@ -377,7 +381,7 @@ function FileSharePage() {
|
|||
/>
|
||||
|
||||
<Modal
|
||||
title={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><LockOutlined /><span>访问验证</span></div>}
|
||||
title={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><LockOutlined aria-hidden /><span>访问验证</span></div>}
|
||||
open={passwordModalVisible}
|
||||
onOk={handleVerifyPassword}
|
||||
onCancel={() => setPasswordModalVisible(false)}
|
||||
|
|
@ -388,11 +392,12 @@ function FileSharePage() {
|
|||
<div style={{ marginTop: 16 }}>
|
||||
<p>该文件分享需要访问密码,请输入密码后继续浏览。</p>
|
||||
<Input.Password
|
||||
iconRender={passwordVisibilityIcon}
|
||||
placeholder="请输入访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onPressEnter={handleVerifyPassword}
|
||||
prefix={<LockOutlined />}
|
||||
prefix={<LockOutlined aria-hidden />}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
|
|
@ -390,7 +390,7 @@
|
|||
}
|
||||
|
||||
.preview-folder-item-icon.pdf {
|
||||
color: #f5222d;
|
||||
color: var(--color-pdf);
|
||||
}
|
||||
|
||||
.preview-folder-item-name {
|
||||
|
|
|
|||
|
|
@ -1,19 +1,27 @@
|
|||
import { useState, useEffect, useRef, useMemo } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import { useParams, useSearchParams, useNavigate } from 'react-router-dom'
|
||||
import { Layout, Spin, Button, Modal, Input, Drawer, Empty, Tooltip, Space } from 'antd'
|
||||
import { FileTextOutlined, FolderOutlined, FolderOpenOutlined, FilePdfOutlined, LockOutlined, MenuOutlined, VerticalAlignTopOutlined, CloudDownloadOutlined, UnorderedListOutlined, CloseOutlined } from '@ant-design/icons'
|
||||
import { Viewer } from '@bytemd/react'
|
||||
import type { Components } from 'react-markdown'
|
||||
import 'bytemd/dist/index.css'
|
||||
import 'highlight.js/styles/github.css'
|
||||
import Mark from 'mark.js'
|
||||
import Highlighter from 'react-highlight-words'
|
||||
import GithubSlugger from 'github-slugger'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import FloatingToc, { TocDrawer } from '@/components/FloatingToc/FloatingToc'
|
||||
import FloatingToc, { TocDrawer, type TocItem } from '@/components/FloatingToc/FloatingToc'
|
||||
import VirtualPDFViewer from '@/components/PDFViewer/VirtualPDFViewer'
|
||||
import ProjectFileTree from '@/components/ProjectFileTree/ProjectFileTree'
|
||||
import LargeMarkdownViewer, { isLargeMarkdownContent } from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import { keyboardActivation } from '@/utils/a11yActivation'
|
||||
import LargeMarkdownViewer, {
|
||||
isLargeMarkdownContent,
|
||||
type LargeMarkdownViewerHandle,
|
||||
} from '@/components/LargeMarkdownViewer/LargeMarkdownViewer'
|
||||
import { MARKDOWN_VIEWER_PLUGINS } from '@/utils/markdownViewer'
|
||||
import { findNodeByKey, findRootReadme, mergeParentKeys } from '@/utils/treeUtils'
|
||||
import { getApiErrorStatus } from '@/utils/apiError'
|
||||
import type { FileTreeNode, ProjectSharePublicInfo } from '@/types/api'
|
||||
import {
|
||||
getProjectSharePublicInfo,
|
||||
getProjectShareTree,
|
||||
|
|
@ -24,21 +32,22 @@ import {
|
|||
exportProjectSharePDF,
|
||||
} from '@/api/share'
|
||||
import './PreviewPage.css'
|
||||
import { clearInputIcon, passwordVisibilityIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Sider, Content } = Layout
|
||||
const ROOT_FOLDER_KEY = '__root__'
|
||||
|
||||
// 查找内容区实际可滚动的容器(普通 MD:主内容区;PDF/大文档:内部滚动容器)
|
||||
const findScrollableEl = (root) => {
|
||||
const findScrollableEl = (root: HTMLElement | null): HTMLElement | null => {
|
||||
if (!root) return null
|
||||
if (root.scrollHeight > root.clientHeight + 1) return root
|
||||
const inner = root.querySelector('.pdf-content, .markdown-virtual-list')
|
||||
const inner = root.querySelector<HTMLElement>('.pdf-content, .markdown-virtual-list')
|
||||
if (inner && inner.scrollHeight > inner.clientHeight + 1) return inner
|
||||
return null
|
||||
}
|
||||
|
||||
const HighlightText = ({ text, keyword }) => {
|
||||
if (!keyword || !text) return text
|
||||
const HighlightText = ({ text, keyword }: { text?: string | null; keyword?: string }) => {
|
||||
if (!keyword || !text) return <>{text}</>
|
||||
return (
|
||||
<Highlighter
|
||||
highlightClassName="search-highlight"
|
||||
|
|
@ -50,17 +59,17 @@ const HighlightText = ({ text, keyword }) => {
|
|||
}
|
||||
|
||||
function ProjectSharePage() {
|
||||
const { shareCode } = useParams()
|
||||
const { shareCode = '' } = useParams<{ shareCode: string }>()
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [projectInfo, setProjectInfo] = useState(null)
|
||||
const [fileTree, setFileTree] = useState([])
|
||||
const [projectInfo, setProjectInfo] = useState<ProjectSharePublicInfo | null>(null)
|
||||
const [fileTree, setFileTree] = useState<FileTreeNode[]>([])
|
||||
const [selectedFile, setSelectedFile] = useState('')
|
||||
const [selectedNodeKey, setSelectedNodeKey] = useState('')
|
||||
const [markdownContent, setMarkdownContent] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [openKeys, setOpenKeys] = useState([])
|
||||
const [tocItems, setTocItems] = useState([])
|
||||
const [openKeys, setOpenKeys] = useState<string[]>([])
|
||||
const [tocItems, setTocItems] = useState<TocItem[]>([])
|
||||
const [passwordModalVisible, setPasswordModalVisible] = useState(false)
|
||||
const [password, setPassword] = useState('')
|
||||
const [siderCollapsed] = useState(false)
|
||||
|
|
@ -71,13 +80,13 @@ function ProjectSharePage() {
|
|||
const [pdfFilename, setPdfFilename] = useState('')
|
||||
const [viewMode, setViewMode] = useState('markdown')
|
||||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
const [matchedFilePaths, setMatchedFilePaths] = useState(new Set())
|
||||
const [matchedFilePaths, setMatchedFilePaths] = useState<Set<string>>(new Set())
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const contentRef = useRef(null)
|
||||
const viewerRef = useRef(null)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
const viewerRef = useRef<HTMLDivElement>(null)
|
||||
const [headerVisible, setHeaderVisible] = useState(false)
|
||||
const headerHoveringRef = useRef(false)
|
||||
const headerHideTimerRef = useRef(null)
|
||||
const headerHideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const clearHeaderHideTimer = () => {
|
||||
if (headerHideTimerRef.current) {
|
||||
clearTimeout(headerHideTimerRef.current)
|
||||
|
|
@ -102,8 +111,8 @@ function ProjectSharePage() {
|
|||
const target = root ? findScrollableEl(root) : null
|
||||
if (target && target.scrollTop > 8) scheduleHeaderHide()
|
||||
}
|
||||
const largeMarkdownRef = useRef(null)
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState(null)
|
||||
const largeMarkdownRef = useRef<LargeMarkdownViewerHandle>(null)
|
||||
const [pdfToolbarTarget, setPdfToolbarTarget] = useState<HTMLDivElement | null>(null)
|
||||
const isLargeMarkdown = isLargeMarkdownContent(markdownContent)
|
||||
|
||||
const handleClose = () => {
|
||||
|
|
@ -125,8 +134,8 @@ function ProjectSharePage() {
|
|||
useEffect(() => {
|
||||
const root = contentRef.current
|
||||
if (!root) return
|
||||
const sync = (scrollEl = null) => {
|
||||
const target = scrollEl || findScrollableEl(root)
|
||||
const sync = (scrollEl: HTMLElement | EventTarget | null = null) => {
|
||||
const target = (scrollEl as HTMLElement | null) || findScrollableEl(root)
|
||||
if (!target) {
|
||||
clearHeaderHideTimer()
|
||||
setHeaderVisible(true)
|
||||
|
|
@ -140,7 +149,7 @@ function ProjectSharePage() {
|
|||
setHeaderVisible(false)
|
||||
}
|
||||
}
|
||||
const onScroll = (e) => sync(e.target)
|
||||
const onScroll = (e: Event) => sync(e.target)
|
||||
root.addEventListener('scroll', onScroll, true)
|
||||
sync()
|
||||
return () => {
|
||||
|
|
@ -181,12 +190,12 @@ function ProjectSharePage() {
|
|||
}
|
||||
return
|
||||
}
|
||||
const targetNode = findNodeByKey(fileTree, selectedParam)
|
||||
const targetNode = findNodeByKey<FileTreeNode>(fileTree, selectedParam)
|
||||
if (targetNode && !targetNode.isLeaf && selectedParam !== selectedNodeKey) {
|
||||
selectFolder(selectedParam)
|
||||
}
|
||||
} else if (fileParam) {
|
||||
const targetNode = findNodeByKey(fileTree, fileParam)
|
||||
const targetNode = findNodeByKey<FileTreeNode>(fileTree, fileParam)
|
||||
if (targetNode && !targetNode.isLeaf) {
|
||||
selectFolder(fileParam, { syncUrl: true })
|
||||
} else if (fileParam !== selectedFile) {
|
||||
|
|
@ -195,7 +204,7 @@ function ProjectSharePage() {
|
|||
} else {
|
||||
// 没有指定文件时,默认打开根目录 README.md
|
||||
if (!selectedFile && !selectedNodeKey) {
|
||||
const readmeNode = findReadme(fileTree)
|
||||
const readmeNode = findRootReadme(fileTree)
|
||||
if (readmeNode) {
|
||||
openSharedFile(readmeNode.key, { syncUrl: true })
|
||||
}
|
||||
|
|
@ -234,13 +243,13 @@ function ProjectSharePage() {
|
|||
}
|
||||
}
|
||||
|
||||
const loadFileTree = async (pwd = null) => {
|
||||
const loadFileTree = async (pwd: string | null = null) => {
|
||||
try {
|
||||
const res = await getProjectShareTree(shareCode, pwd)
|
||||
setFileTree(res.data || [])
|
||||
} catch (error) {
|
||||
console.error('Load share tree error:', error)
|
||||
if (error.response?.status === 403) {
|
||||
if (getApiErrorStatus(error) === 403) {
|
||||
setPasswordModalVisible(true)
|
||||
} else {
|
||||
Toast.error('加载失败', '目录加载失败')
|
||||
|
|
@ -248,7 +257,7 @@ function ProjectSharePage() {
|
|||
}
|
||||
}
|
||||
|
||||
const loadMarkdown = async (filePath, pwd = null) => {
|
||||
const loadMarkdown = async (filePath: string, pwd: string | null = null) => {
|
||||
setLoading(true)
|
||||
setTocItems([])
|
||||
try {
|
||||
|
|
@ -259,7 +268,7 @@ function ProjectSharePage() {
|
|||
}
|
||||
} catch (error) {
|
||||
console.error('Load share markdown error:', error)
|
||||
if (error.response?.status === 403) {
|
||||
if (getApiErrorStatus(error) === 403) {
|
||||
setPasswordModalVisible(true)
|
||||
} else {
|
||||
Toast.error('加载失败', '文档加载失败')
|
||||
|
|
@ -269,18 +278,18 @@ function ProjectSharePage() {
|
|||
}
|
||||
}
|
||||
|
||||
const normalizeMarkdownHref = (href) => {
|
||||
if (!href) return href
|
||||
const normalizeMarkdownHref = (href?: string | null): string | undefined => {
|
||||
if (!href) return undefined
|
||||
|
||||
const [pathPart, hashPart = ''] = href.split('#')
|
||||
const [rawPath, searchPart = ''] = pathPart.split('?')
|
||||
|
||||
const decodedPath = rawPath
|
||||
const decodedPath: string = rawPath
|
||||
.split('/')
|
||||
.map((part) => {
|
||||
try {
|
||||
return decodeURIComponent(part)
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return part
|
||||
}
|
||||
})
|
||||
|
|
@ -290,11 +299,11 @@ function ProjectSharePage() {
|
|||
return hashPart ? `${rebuilt}#${hashPart}` : rebuilt
|
||||
}
|
||||
|
||||
const isExternalHref = (href) => {
|
||||
const isExternalHref = (href?: string | null): boolean => {
|
||||
return Boolean(href && (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith('//')))
|
||||
}
|
||||
|
||||
const handleSearch = async (value) => {
|
||||
const handleSearch = async (value: string) => {
|
||||
const keyword = value || ''
|
||||
setSearchKeyword(keyword)
|
||||
|
||||
|
|
@ -306,10 +315,10 @@ function ProjectSharePage() {
|
|||
setIsSearching(true)
|
||||
try {
|
||||
const res = await searchProjectShareDocuments(shareCode, keyword)
|
||||
const paths = new Set((res.data || []).map((item) => item.file_path))
|
||||
const paths = new Set<string>((res.data || []).map((item) => item.file_path))
|
||||
setMatchedFilePaths(paths)
|
||||
|
||||
const keysToExpand = new Set(openKeys)
|
||||
const keysToExpand = new Set<string>(openKeys)
|
||||
;(res.data || []).forEach((item) => {
|
||||
const parents = item.parent_paths || []
|
||||
parents.forEach((parentPath) => keysToExpand.add(parentPath))
|
||||
|
|
@ -330,7 +339,7 @@ function ProjectSharePage() {
|
|||
}
|
||||
|
||||
const slugger = new GithubSlugger()
|
||||
const headings = []
|
||||
const headings: TocItem[] = []
|
||||
markdownContent.split('\n').forEach((line) => {
|
||||
const match = line.match(/^(#{1,6})\s+(.+)$/)
|
||||
if (!match) return
|
||||
|
|
@ -342,25 +351,7 @@ function ProjectSharePage() {
|
|||
setTocItems(headings)
|
||||
}, [markdownContent, isLargeMarkdown])
|
||||
|
||||
const findReadme = (nodes) => {
|
||||
for (const node of nodes) {
|
||||
if (node.title === 'README.md' && node.isLeaf) return node
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const findNodeByKey = (nodes, key) => {
|
||||
for (const node of nodes) {
|
||||
if (node.key === key) return node
|
||||
if (node.children?.length) {
|
||||
const found = findNodeByKey(node.children, key)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const updateSelectedParam = (path, isFile = true) => {
|
||||
const updateSelectedParam = (path: string, isFile = true) => {
|
||||
const nextParams = new URLSearchParams(searchParams)
|
||||
nextParams.delete('file')
|
||||
nextParams.delete('selected')
|
||||
|
|
@ -370,24 +361,18 @@ function ProjectSharePage() {
|
|||
setSearchParams(nextParams, { replace: true })
|
||||
}
|
||||
|
||||
const updateFileParam = (filePath) => {
|
||||
const updateFileParam = (filePath: string) => {
|
||||
updateSelectedParam(filePath, true)
|
||||
}
|
||||
|
||||
const expandParentFolders = (path) => {
|
||||
const parts = path.split('/')
|
||||
const allParentPaths = []
|
||||
let currentPath = ''
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i]
|
||||
allParentPaths.push(currentPath)
|
||||
}
|
||||
if (allParentPaths.length > 0) {
|
||||
setOpenKeys(prev => [...new Set([...prev, ...allParentPaths])])
|
||||
}
|
||||
const expandParentFolders = (path: string) => {
|
||||
setOpenKeys((prev) => mergeParentKeys(prev, path))
|
||||
}
|
||||
|
||||
const selectFolder = (folderPath, { syncUrl = false, expandSelf = false } = {}) => {
|
||||
const selectFolder = (
|
||||
folderPath: string,
|
||||
{ syncUrl = false, expandSelf = false }: { syncUrl?: boolean; expandSelf?: boolean } = {},
|
||||
) => {
|
||||
setSelectedFile('')
|
||||
setSelectedNodeKey(folderPath)
|
||||
setMarkdownContent('')
|
||||
|
|
@ -422,9 +407,15 @@ function ProjectSharePage() {
|
|||
}
|
||||
|
||||
// 获取文件夹内的子节点(与左侧文件树保持一致:文件夹 + md/pdf 文档)
|
||||
const getFolderChildren = (folderPath) => {
|
||||
const getFolderChildren = (folderPath: string) => {
|
||||
const rootNode: FileTreeNode = {
|
||||
key: ROOT_FOLDER_KEY,
|
||||
title: projectInfo?.name || '项目分享',
|
||||
isLeaf: false,
|
||||
children: fileTree,
|
||||
}
|
||||
const node = folderPath === ROOT_FOLDER_KEY
|
||||
? { key: ROOT_FOLDER_KEY, title: projectInfo?.name || '项目分享', isLeaf: false, children: fileTree }
|
||||
? rootNode
|
||||
: folderPath ? findNodeByKey(fileTree, folderPath) : null
|
||||
if (!node || node.isLeaf) return { folders: [], files: [], node }
|
||||
const children = node.children || []
|
||||
|
|
@ -449,10 +440,10 @@ function ProjectSharePage() {
|
|||
const folderParts = folderPath && folderPath !== ROOT_FOLDER_KEY
|
||||
? folderPath.split('/').filter(Boolean)
|
||||
: []
|
||||
const items = [{
|
||||
const items: Array<{ key: string; label: ReactNode; icon: ReactNode; onClick?: () => void }> = [{
|
||||
key: ROOT_FOLDER_KEY,
|
||||
label: projectInfo?.name || '项目分享',
|
||||
icon: <FolderOutlined />,
|
||||
icon: <FolderOutlined aria-hidden />,
|
||||
onClick: () => selectRootFolder(),
|
||||
}]
|
||||
|
||||
|
|
@ -463,18 +454,18 @@ function ProjectSharePage() {
|
|||
items.push({
|
||||
key: path,
|
||||
label: part,
|
||||
icon: <FolderOutlined />,
|
||||
icon: <FolderOutlined aria-hidden />,
|
||||
onClick: () => selectFolder(path, { syncUrl: true }),
|
||||
})
|
||||
})
|
||||
|
||||
if (viewMode !== 'folder' && selectedFile) {
|
||||
const fileName = selectedFile.split('/').filter(Boolean).pop()
|
||||
const fileName = selectedFile.split('/').filter(Boolean).pop() ?? ''
|
||||
const isPdf = fileName.toLowerCase().endsWith('.pdf')
|
||||
items.push({
|
||||
key: selectedFile,
|
||||
label: isPdf ? fileName : fileName.replace(/\.md$/i, ''),
|
||||
icon: isPdf ? <FilePdfOutlined /> : <FileTextOutlined />,
|
||||
icon: isPdf ? <FilePdfOutlined aria-hidden /> : <FileTextOutlined aria-hidden />,
|
||||
})
|
||||
}
|
||||
return items
|
||||
|
|
@ -521,7 +512,7 @@ function ProjectSharePage() {
|
|||
}
|
||||
|
||||
// 菜单点击:文件夹进入文件夹视图,文件打开文档
|
||||
const handleMenuClick = ({ key }) => {
|
||||
const handleMenuClick = ({ key }: { key: string }) => {
|
||||
const node = findNodeByKey(fileTree, key)
|
||||
if (!node) return
|
||||
if (!node.isLeaf) {
|
||||
|
|
@ -534,8 +525,8 @@ function ProjectSharePage() {
|
|||
const filteredTreeData = useMemo(() => {
|
||||
if (!searchKeyword.trim()) return fileTree
|
||||
|
||||
const loop = (nodes) => {
|
||||
const result = []
|
||||
const loop = (nodes: FileTreeNode[]): FileTreeNode[] => {
|
||||
const result: FileTreeNode[] = []
|
||||
for (const node of nodes) {
|
||||
const titleMatch = node.title.toLowerCase().includes(searchKeyword.toLowerCase())
|
||||
const contentMatch = matchedFilePaths.has(node.key)
|
||||
|
|
@ -555,7 +546,7 @@ function ProjectSharePage() {
|
|||
return loop(fileTree)
|
||||
}, [fileTree, searchKeyword, matchedFilePaths])
|
||||
|
||||
const resolveRelativePath = (currentPath, relativePath) => {
|
||||
const resolveRelativePath = (currentPath: string, relativePath: string) => {
|
||||
if (relativePath.startsWith('/')) return relativePath.substring(1)
|
||||
const lastSlashIndex = currentPath.lastIndexOf('/')
|
||||
const currentDir = lastSlashIndex !== -1 ? currentPath.substring(0, lastSlashIndex) : ''
|
||||
|
|
@ -568,7 +559,7 @@ function ProjectSharePage() {
|
|||
return dirParts.join('/')
|
||||
}
|
||||
|
||||
const resolveMarkdownTarget = (relativePath) => {
|
||||
const resolveMarkdownTarget = (relativePath: string) => {
|
||||
if (!relativePath) return relativePath
|
||||
if (relativePath.startsWith('.')) {
|
||||
return resolveRelativePath(selectedFile, relativePath)
|
||||
|
|
@ -576,7 +567,7 @@ function ProjectSharePage() {
|
|||
return relativePath.startsWith('/') ? relativePath.substring(1) : relativePath
|
||||
}
|
||||
|
||||
const openSharedFile = (key, { syncUrl = true } = {}) => {
|
||||
const openSharedFile = (key: string, { syncUrl = true }: { syncUrl?: boolean } = {}) => {
|
||||
setSelectedFile(key)
|
||||
setSelectedNodeKey(key)
|
||||
expandParentFolders(key)
|
||||
|
|
@ -587,7 +578,7 @@ function ProjectSharePage() {
|
|||
|
||||
if (key.toLowerCase().endsWith('.pdf')) {
|
||||
setPdfUrl(getProjectShareDocumentUrl(shareCode, key))
|
||||
setPdfFilename(key.split('/').pop())
|
||||
setPdfFilename(key.split('/').pop() ?? '')
|
||||
setViewMode('pdf')
|
||||
return
|
||||
}
|
||||
|
|
@ -596,7 +587,7 @@ function ProjectSharePage() {
|
|||
loadMarkdown(key)
|
||||
}
|
||||
|
||||
const handleMarkdownLink = (e, href) => {
|
||||
const handleMarkdownLink = (e: MouseEvent<HTMLElement>, href?: string | null) => {
|
||||
const normalizedHref = normalizeMarkdownHref(href)
|
||||
if (!normalizedHref || isExternalHref(normalizedHref) || normalizedHref.startsWith('#')) return
|
||||
const pathOnly = normalizedHref.split(/[?#]/)[0]
|
||||
|
|
@ -607,7 +598,7 @@ function ProjectSharePage() {
|
|||
openSharedFile(resolveMarkdownTarget(pathOnly))
|
||||
}
|
||||
|
||||
const handleMarkdownContentClick = (event) => {
|
||||
const handleMarkdownContentClick = (event: MouseEvent<HTMLDivElement>) => {
|
||||
if (event.defaultPrevented) return
|
||||
const target = event.target
|
||||
const anchor = target instanceof Element ? target.closest('a') : null
|
||||
|
|
@ -650,7 +641,7 @@ function ProjectSharePage() {
|
|||
}
|
||||
}
|
||||
|
||||
const markdownComponents = {
|
||||
const markdownComponents: Components = {
|
||||
a: ({ node, href, children, ...props }) => {
|
||||
const isExternal = isExternalHref(href)
|
||||
return (
|
||||
|
|
@ -682,12 +673,12 @@ function ProjectSharePage() {
|
|||
<div className="preview-search">
|
||||
<Input.Search
|
||||
placeholder="搜索文档内容..."
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
value={searchKeyword}
|
||||
onChange={(e) => setSearchKeyword(e.target.value)}
|
||||
onSearch={handleSearch}
|
||||
loading={isSearching}
|
||||
enterButton
|
||||
enterButton={searchEnterButton({ primary: true, loading: isSearching })}
|
||||
/>
|
||||
</div>
|
||||
<ProjectFileTree
|
||||
|
|
@ -717,7 +708,7 @@ function ProjectSharePage() {
|
|||
onClick={handleClose}
|
||||
aria-label="关闭"
|
||||
>
|
||||
<CloseOutlined />
|
||||
<CloseOutlined aria-hidden />
|
||||
</button>
|
||||
<h2>{projectInfo?.name || '项目分享'}</h2>
|
||||
</div>
|
||||
|
|
@ -725,12 +716,12 @@ function ProjectSharePage() {
|
|||
<div className="preview-search">
|
||||
<Input.Search
|
||||
placeholder="搜索文档内容..."
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
value={searchKeyword}
|
||||
onChange={(e) => setSearchKeyword(e.target.value)}
|
||||
onSearch={handleSearch}
|
||||
loading={isSearching}
|
||||
enterButton
|
||||
enterButton={searchEnterButton({ primary: true, loading: isSearching })}
|
||||
/>
|
||||
</div>
|
||||
<ProjectFileTree
|
||||
|
|
@ -756,7 +747,7 @@ function ProjectSharePage() {
|
|||
<Tooltip title="关闭">
|
||||
<Button
|
||||
type="text"
|
||||
icon={<CloseOutlined />}
|
||||
icon={<CloseOutlined aria-hidden />}
|
||||
onClick={handleClose}
|
||||
size="small"
|
||||
aria-label="关闭"
|
||||
|
|
@ -765,7 +756,7 @@ function ProjectSharePage() {
|
|||
<Tooltip title="目录索引">
|
||||
<Button
|
||||
type="text"
|
||||
icon={<UnorderedListOutlined />}
|
||||
icon={<UnorderedListOutlined aria-hidden />}
|
||||
onClick={() => setMobileDrawerVisible(true)}
|
||||
size="small"
|
||||
aria-label="目录索引"
|
||||
|
|
@ -779,7 +770,7 @@ function ProjectSharePage() {
|
|||
<Space className="preview-header-actions preview-compact-actions" size={4}>
|
||||
<Tooltip title="回到顶部">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollContentToTop}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -788,7 +779,7 @@ function ProjectSharePage() {
|
|||
</Tooltip>
|
||||
<Tooltip title="下载PDF">
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleExportPDF}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -798,7 +789,7 @@ function ProjectSharePage() {
|
|||
{!isLargeMarkdown && (
|
||||
<Tooltip title="文档索引">
|
||||
<Button
|
||||
icon={<MenuOutlined />}
|
||||
icon={<MenuOutlined aria-hidden />}
|
||||
onClick={() => setTocDrawerVisible(true)}
|
||||
size="small"
|
||||
type="text"
|
||||
|
|
@ -810,14 +801,14 @@ function ProjectSharePage() {
|
|||
) : (
|
||||
<Space className="preview-header-actions">
|
||||
<Button
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
icon={<VerticalAlignTopOutlined aria-hidden />}
|
||||
onClick={scrollContentToTop}
|
||||
size="small"
|
||||
>
|
||||
回到顶部
|
||||
</Button>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
icon={<CloudDownloadOutlined aria-hidden />}
|
||||
onClick={handleExportPDF}
|
||||
size="small"
|
||||
>
|
||||
|
|
@ -843,7 +834,7 @@ function ProjectSharePage() {
|
|||
if (!node || node.isLeaf) {
|
||||
return (
|
||||
<div className="preview-folder-placeholder">
|
||||
<FolderOpenOutlined />
|
||||
<FolderOpenOutlined aria-hidden />
|
||||
<span>已选择文件夹,请从左侧选择 Markdown 或 PDF 文件查看。</span>
|
||||
</div>
|
||||
)
|
||||
|
|
@ -864,9 +855,11 @@ function ProjectSharePage() {
|
|||
key={sub.key}
|
||||
className="preview-folder-item"
|
||||
onClick={() => selectFolder(sub.key, { syncUrl: true, expandSelf: true })}
|
||||
{...keyboardActivation(() => selectFolder(sub.key, { syncUrl: true, expandSelf: true }))}
|
||||
aria-label={`打开文件夹:${sub.title}`}
|
||||
title={sub.title}
|
||||
>
|
||||
<FolderOutlined className="preview-folder-item-icon" />
|
||||
<FolderOutlined aria-hidden className="preview-folder-item-icon" />
|
||||
<span className="preview-folder-item-name">{sub.title}</span>
|
||||
<span className="preview-folder-item-count">{sub.children?.length || 0} 项</span>
|
||||
</div>
|
||||
|
|
@ -879,11 +872,13 @@ function ProjectSharePage() {
|
|||
key={file.key}
|
||||
className="preview-folder-item preview-file-item"
|
||||
onClick={() => openSharedFile(file.key, { syncUrl: true })}
|
||||
{...keyboardActivation(() => openSharedFile(file.key, { syncUrl: true }))}
|
||||
aria-label={`打开文档:${file.title}`}
|
||||
title={file.title}
|
||||
>
|
||||
{isPdf
|
||||
? <FilePdfOutlined className="preview-folder-item-icon pdf" />
|
||||
: <FileTextOutlined className="preview-folder-item-icon md" />}
|
||||
? <FilePdfOutlined aria-hidden className="preview-folder-item-icon pdf" />
|
||||
: <FileTextOutlined aria-hidden className="preview-folder-item-icon md" />}
|
||||
<span className="preview-folder-item-name">{displayName}</span>
|
||||
<span className="preview-folder-item-count">{isPdf ? 'PDF 文档' : 'Markdown 文档'}</span>
|
||||
</div>
|
||||
|
|
@ -903,7 +898,7 @@ function ProjectSharePage() {
|
|||
renderTitle={(item, keyword) => <HighlightText text={item.title} keyword={keyword} />}
|
||||
onClick={(e) => {
|
||||
if (e.defaultPrevented) return
|
||||
const target = e.target.closest('a')
|
||||
const target = e.target instanceof Element ? e.target.closest('a') : null
|
||||
if (target) {
|
||||
const href = target.getAttribute('href')
|
||||
if (href) handleMarkdownLink(e, href)
|
||||
|
|
@ -943,7 +938,7 @@ function ProjectSharePage() {
|
|||
/>
|
||||
|
||||
<Modal
|
||||
title={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><LockOutlined /><span>访问验证</span></div>}
|
||||
title={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><LockOutlined aria-hidden /><span>访问验证</span></div>}
|
||||
open={passwordModalVisible}
|
||||
onOk={handleVerifyPassword}
|
||||
onCancel={() => setPasswordModalVisible(false)}
|
||||
|
|
@ -954,11 +949,12 @@ function ProjectSharePage() {
|
|||
<div style={{ marginTop: 16 }}>
|
||||
<p>该分享需要访问密码,请输入密码后继续浏览。</p>
|
||||
<Input.Password
|
||||
iconRender={passwordVisibilityIcon}
|
||||
placeholder="请输入访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onPressEnter={handleVerifyPassword}
|
||||
prefix={<LockOutlined />}
|
||||
prefix={<LockOutlined aria-hidden />}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
|
|
@ -2,19 +2,33 @@ import { useState, useEffect } from 'react'
|
|||
import { Card, Tabs, Form, Input, Button, Avatar, Upload, Space, Typography } from 'antd'
|
||||
import { UserOutlined, LockOutlined, UploadOutlined, ApiOutlined, CopyOutlined, ReloadOutlined } from '@ant-design/icons'
|
||||
import ImgCrop from 'antd-img-crop'
|
||||
import { getCurrentUser, updateProfile, changePassword, uploadAvatar, getMcpCredentials, rotateMcpSecret } from '@/api/auth'
|
||||
import type { RcFile } from 'antd/es/upload'
|
||||
import {
|
||||
changePassword,
|
||||
getCurrentUser,
|
||||
getMcpCredentials,
|
||||
rotateMcpSecret,
|
||||
updateProfile,
|
||||
uploadAvatar,
|
||||
type ChangePasswordPayload,
|
||||
type ProfileFormValues,
|
||||
type ProfileUpdatePayload,
|
||||
} from '@/api/auth'
|
||||
import type { McpCredential, User } from '@/types/api'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import useUserStore from '@/stores/userStore'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import './ProfilePage.css'
|
||||
import { passwordVisibilityIcon } from '@/utils/antdA11y'
|
||||
|
||||
const { Paragraph, Text } = Typography
|
||||
|
||||
function ProfilePage() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [userInfo, setUserInfo] = useState(null)
|
||||
const [mcpCredentials, setMcpCredentials] = useState(null)
|
||||
const [profileForm] = Form.useForm()
|
||||
const [passwordForm] = Form.useForm()
|
||||
const [userInfo, setUserInfo] = useState<User | null>(null)
|
||||
const [mcpCredentials, setMcpCredentials] = useState<McpCredential | null>(null)
|
||||
const [profileForm] = Form.useForm<ProfileFormValues>()
|
||||
const [passwordForm] = Form.useForm<ChangePasswordPayload>()
|
||||
const { setUser } = useUserStore()
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -50,7 +64,7 @@ function ProfilePage() {
|
|||
}
|
||||
|
||||
// 更新资料
|
||||
const handleUpdateProfile = async (values) => {
|
||||
const handleUpdateProfile = async (values: ProfileUpdatePayload) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await updateProfile({
|
||||
|
|
@ -63,14 +77,14 @@ function ProfilePage() {
|
|||
Toast.success('更新成功', '个人资料已更新')
|
||||
} catch (error) {
|
||||
console.error('Update profile error:', error)
|
||||
Toast.error(error.response?.data?.detail || '更新失败')
|
||||
Toast.error(getApiErrorDetail(error) || '更新失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const handleChangePassword = async (values) => {
|
||||
const handleChangePassword = async (values: ChangePasswordPayload) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
await changePassword({
|
||||
|
|
@ -85,14 +99,14 @@ function ProfilePage() {
|
|||
}, 2000)
|
||||
} catch (error) {
|
||||
console.error('Change password error:', error)
|
||||
Toast.error(error.response?.data?.detail || '修改密码失败')
|
||||
Toast.error(getApiErrorDetail(error) || '修改密码失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 上传头像前的验证
|
||||
const beforeAvatarUpload = (file) => {
|
||||
const beforeAvatarUpload = (file: File) => {
|
||||
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
|
||||
if (!isJpgOrPng) {
|
||||
Toast.error('格式错误', '仅支持 JPG、PNG 格式的图片')
|
||||
|
|
@ -107,9 +121,9 @@ function ProfilePage() {
|
|||
}
|
||||
|
||||
// 处理头像上传
|
||||
const handleAvatarUpload = async (info) => {
|
||||
const { file } = info
|
||||
|
||||
// beforeUpload 已校验类型/大小并返回 true,因此 customRequest 拿到的一定是 File
|
||||
// (antd 的 UploadRequestFile 还可能是 Blob/string,这里在边界处收窄)
|
||||
const handleAvatarUpload = async ({ file }: { file: RcFile }) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await uploadAvatar(file)
|
||||
|
|
@ -118,14 +132,14 @@ function ProfilePage() {
|
|||
Toast.success('上传成功', '头像已更新')
|
||||
} catch (error) {
|
||||
console.error('Upload avatar error:', error)
|
||||
Toast.error('上传失败', error.response?.data?.detail || '头像上传失败')
|
||||
Toast.error('上传失败', getApiErrorDetail(error) || '头像上传失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取头像URL
|
||||
const getAvatarUrl = () => {
|
||||
const getAvatarUrl = (): string | null => {
|
||||
if (!userInfo?.avatar) return null
|
||||
// avatar 字段存储的是相对路径,如:2/avatar/xxx.jpg
|
||||
// 需要转换为 API 端点: /api/v1/auth/avatar/{user_id}/{filename}
|
||||
|
|
@ -138,7 +152,7 @@ function ProfilePage() {
|
|||
return null
|
||||
}
|
||||
|
||||
const handleCopy = async (value, label) => {
|
||||
const handleCopy = async (value: string | undefined, label: string) => {
|
||||
if (!value) return
|
||||
|
||||
try {
|
||||
|
|
@ -165,7 +179,7 @@ function ProfilePage() {
|
|||
Toast.success('已生成', '新的 MCP Secret 已生效')
|
||||
} catch (error) {
|
||||
console.error('Rotate MCP secret error:', error)
|
||||
Toast.error('生成失败', error.response?.data?.detail || '重新生成 MCP Secret 失败')
|
||||
Toast.error('生成失败', getApiErrorDetail(error) || '重新生成 MCP Secret 失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
|
|
@ -178,7 +192,7 @@ function ProfilePage() {
|
|||
key: 'profile',
|
||||
label: (
|
||||
<span>
|
||||
<UserOutlined />
|
||||
<UserOutlined aria-hidden />
|
||||
个人资料
|
||||
</span>
|
||||
),
|
||||
|
|
@ -187,7 +201,7 @@ function ProfilePage() {
|
|||
<div className="avatar-section">
|
||||
<Avatar
|
||||
size={100}
|
||||
icon={<UserOutlined />}
|
||||
icon={<UserOutlined aria-hidden />}
|
||||
src={getAvatarUrl()}
|
||||
/>
|
||||
<ImgCrop
|
||||
|
|
@ -201,9 +215,9 @@ function ProfilePage() {
|
|||
<Upload
|
||||
showUploadList={false}
|
||||
beforeUpload={beforeAvatarUpload}
|
||||
customRequest={({ file }) => handleAvatarUpload({ file })}
|
||||
customRequest={({ file }) => handleAvatarUpload({ file: file as RcFile })}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} style={{ marginTop: 16 }} loading={loading}>
|
||||
<Button icon={<UploadOutlined aria-hidden />} style={{ marginTop: 16 }} loading={loading}>
|
||||
更换头像
|
||||
</Button>
|
||||
</Upload>
|
||||
|
|
@ -262,7 +276,7 @@ function ProfilePage() {
|
|||
key: 'password',
|
||||
label: (
|
||||
<span>
|
||||
<LockOutlined />
|
||||
<LockOutlined aria-hidden />
|
||||
修改密码
|
||||
</span>
|
||||
),
|
||||
|
|
@ -279,7 +293,7 @@ function ProfilePage() {
|
|||
name="old_password"
|
||||
rules={[{ required: true, message: '请输入当前密码' }]}
|
||||
>
|
||||
<Input.Password placeholder="请输入当前密码" />
|
||||
<Input.Password iconRender={passwordVisibilityIcon} placeholder="请输入当前密码" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
|
|
@ -291,7 +305,7 @@ function ProfilePage() {
|
|||
{ max: 50, message: '密码最多50个字符' },
|
||||
]}
|
||||
>
|
||||
<Input.Password placeholder="请输入新密码(至少6个字符)" />
|
||||
<Input.Password iconRender={passwordVisibilityIcon} placeholder="请输入新密码(至少6个字符)" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
|
|
@ -310,7 +324,7 @@ function ProfilePage() {
|
|||
}),
|
||||
]}
|
||||
>
|
||||
<Input.Password placeholder="请再次输入新密码" />
|
||||
<Input.Password iconRender={passwordVisibilityIcon} placeholder="请再次输入新密码" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
|
|
@ -342,7 +356,7 @@ function ProfilePage() {
|
|||
key: 'mcp',
|
||||
label: (
|
||||
<span>
|
||||
<ApiOutlined />
|
||||
<ApiOutlined aria-hidden />
|
||||
MCP 接入
|
||||
</span>
|
||||
),
|
||||
|
|
@ -355,7 +369,7 @@ function ProfilePage() {
|
|||
<p>用于远程 MCP Client 通过 `X-Bot-Id` 与 `X-Bot-Secret` 接入你的账号。</p>
|
||||
</div>
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
icon={<ReloadOutlined aria-hidden />}
|
||||
onClick={handleRotateSecret}
|
||||
loading={loading}
|
||||
>
|
||||
|
|
@ -370,7 +384,7 @@ function ProfilePage() {
|
|||
{mcpCredentials?.bot_id || '-'}
|
||||
</Paragraph>
|
||||
<Button
|
||||
icon={<CopyOutlined />}
|
||||
icon={<CopyOutlined aria-hidden />}
|
||||
onClick={() => handleCopy(mcpCredentials?.bot_id, 'X-Bot-Id')}
|
||||
disabled={!mcpCredentials?.bot_id}
|
||||
>
|
||||
|
|
@ -385,7 +399,7 @@ function ProfilePage() {
|
|||
</Paragraph>
|
||||
<Space>
|
||||
<Button
|
||||
icon={<CopyOutlined />}
|
||||
icon={<CopyOutlined aria-hidden />}
|
||||
onClick={() => handleCopy(mcpCredentials?.bot_secret, 'X-Bot-Secret')}
|
||||
disabled={!mcpCredentials?.bot_secret}
|
||||
>
|
||||
|
|
@ -82,7 +82,7 @@ body.dark .project-card .ant-card-actions > li:not(:last-child) {
|
|||
height: 20px;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, var(--color-danger) 0%, #f5222d 100%);
|
||||
background: linear-gradient(135deg, var(--color-danger) 0%, var(--color-danger-strong) 100%);
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
useState,
|
||||
useEffect,
|
||||
type SyntheticEvent,
|
||||
} from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Card, Empty, Modal, Form, Input, Row, Col, Space, Button, Switch, Select, Table, Tag, Pagination, Progress, Alert, Tooltip } from 'antd'
|
||||
import { PlusOutlined, FolderOutlined, TeamOutlined, CopyOutlined, DeleteOutlined, EditOutlined, FileOutlined, BranchesOutlined, GithubOutlined, GithubFilled, SwapOutlined, SettingOutlined, DatabaseOutlined, ReloadOutlined, CalendarOutlined, FileTextOutlined, SafetyOutlined, FormOutlined, ReadOutlined } from '@ant-design/icons'
|
||||
import { getMyProjects, getOwnedProjects, getSharedProjects, createProject, deleteProject, updateProject, getProjectMembers, addProjectMember, removeProjectMember, updateProjectMemberRole, getGitRepos, createGitRepo, updateGitRepo, deleteGitRepo, testGitRepoConnection, transferProject } from '@/api/project'
|
||||
import type { GitRepoPayload } from '@/api/project'
|
||||
import { getProjectShareInfo, updateProjectShareSettings } from '@/api/share'
|
||||
import { getUserList } from '@/api/users'
|
||||
import { searchDocuments } from '@/api/search'
|
||||
|
|
@ -12,25 +17,59 @@ import ListActionBar from '@/components/ListActionBar/ListActionBar'
|
|||
import Toast from '@/components/Toast/Toast'
|
||||
import useProjectKnowledge from './useProjectKnowledge'
|
||||
import useUserStore from '@/stores/userStore'
|
||||
import { getApiErrorDetail, getApiErrorMessage } from '@/utils/apiError'
|
||||
import { keyboardActivation } from '@/utils/a11yActivation'
|
||||
import { decorativeAlertIcon, namePageItem, passwordVisibilityIcon } from '@/utils/antdA11y'
|
||||
import type {
|
||||
GitRepo,
|
||||
ProjectListItem,
|
||||
ProjectMember,
|
||||
ProjectRole,
|
||||
ProjectShareInfo,
|
||||
SearchResult,
|
||||
User,
|
||||
} from '@/types/api'
|
||||
import './ProjectList.css'
|
||||
|
||||
function ProjectList({ type = 'my' }) {
|
||||
const [projects, setProjects] = useState([])
|
||||
/** 页面形态:my=我创建的,share=我参与的,其它=全部 */
|
||||
type ProjectListType = 'my' | 'share' | 'all'
|
||||
|
||||
/** 项目分享状态(/shares/projects/{id}/settings 与 info 的公共形状) */
|
||||
type ShareState = ProjectShareInfo
|
||||
|
||||
/** 创建 / 编辑项目表单 */
|
||||
interface ProjectFormValues {
|
||||
name: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
/** Git 仓库表单:is_default 由 Switch 承载,提交时再折算成后端的 0/1 */
|
||||
interface GitRepoFormValues {
|
||||
name: string
|
||||
repo_url: string
|
||||
branch?: string
|
||||
username?: string
|
||||
token?: string
|
||||
is_default?: boolean
|
||||
}
|
||||
|
||||
function ProjectList({ type = 'my' }: { type?: ProjectListType }) {
|
||||
const [projects, setProjects] = useState<ProjectListItem[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [modalVisible, setModalVisible] = useState(false)
|
||||
const [editModalVisible, setEditModalVisible] = useState(false)
|
||||
const [gitModalVisible, setGitModalVisible] = useState(false)
|
||||
const [membersModalVisible, setMembersModalVisible] = useState(false)
|
||||
const [currentProject, setCurrentProject] = useState(null)
|
||||
const [shareInfo, setShareInfo] = useState(null)
|
||||
const [currentProject, setCurrentProject] = useState<ProjectListItem | null>(null)
|
||||
const [shareInfo, setShareInfo] = useState<ShareState | null>(null)
|
||||
const [hasPassword, setHasPassword] = useState(false)
|
||||
const [password, setPassword] = useState('')
|
||||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
const [searchResults, setSearchResults] = useState([])
|
||||
const [searchResults, setSearchResults] = useState<SearchResult[]>([])
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [hasSearched, setHasSearched] = useState(false)
|
||||
const [members, setMembers] = useState([])
|
||||
const [users, setUsers] = useState([])
|
||||
const [members, setMembers] = useState<ProjectMember[]>([])
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [loadingMembers, setLoadingMembers] = useState(false)
|
||||
const [form] = Form.useForm()
|
||||
const [editForm] = Form.useForm()
|
||||
|
|
@ -40,23 +79,28 @@ function ProjectList({ type = 'my' }) {
|
|||
const navigate = useNavigate()
|
||||
const { user: currentUser } = useUserStore()
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [unreadByProject, setUnreadByProject] = useState({})
|
||||
const [unreadByProject, setUnreadByProject] = useState<Record<string, number>>({})
|
||||
const pageSize = 8
|
||||
|
||||
// 角色字段统一小写(兼容历史数据中的大小写差异)
|
||||
const normalizeRole = (role) => String(role || '').trim().toLowerCase()
|
||||
const normalizeRole = (role?: string | null) => String(role || '').trim().toLowerCase()
|
||||
|
||||
// 参与项目角色 -> 显示名称
|
||||
const projectRoleLabel = (role) => {
|
||||
const roleMap = { admin: '管理员', editor: '编辑者', viewer: '查看者' }
|
||||
const projectRoleLabel = (role?: string | null) => {
|
||||
const roleMap: Record<string, string> = { admin: '管理员', editor: '编辑者', viewer: '查看者' }
|
||||
return roleMap[normalizeRole(role)] || role || '查看者'
|
||||
}
|
||||
|
||||
// 成员管理弹窗角色显示名
|
||||
const memberRoleLabels = { admin: '管理员', editor: '编辑者', viewer: '查看者' }
|
||||
const memberRoleLabels: Record<string, string> = { admin: '管理员', editor: '编辑者', viewer: '查看者' }
|
||||
|
||||
// 成员角色可选项;历史脏数据(大小写异常/未知角色)统一按查看者展示
|
||||
const memberRoleValues: ProjectRole[] = ['admin', 'editor', 'viewer']
|
||||
const toMemberRole = (role?: string | null): ProjectRole =>
|
||||
memberRoleValues.find((item) => item === normalizeRole(role)) || 'viewer'
|
||||
|
||||
// 格式化日期
|
||||
const formatDate = (dateStr) => {
|
||||
const formatDate = (dateStr?: string | null) => {
|
||||
if (!dateStr) return ''
|
||||
try {
|
||||
const d = new Date(dateStr)
|
||||
|
|
@ -68,7 +112,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 相对时间(用于“最后更新”)
|
||||
const formatRelativeTime = (dateStr) => {
|
||||
const formatRelativeTime = (dateStr?: string | null) => {
|
||||
if (!dateStr) return ''
|
||||
const d = new Date(dateStr)
|
||||
if (Number.isNaN(d.getTime())) return ''
|
||||
|
|
@ -84,14 +128,14 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 按项目更新时间倒序排序(刚更新的项目排在前面;无更新时间时按创建时间)
|
||||
const sortByLastActivity = (list) => [...list].sort((a, b) => {
|
||||
const sortByLastActivity = (list: ProjectListItem[]) => [...list].sort((a, b) => {
|
||||
const ta = new Date(a.last_activity_at || a.created_at || 0).getTime()
|
||||
const tb = new Date(b.last_activity_at || b.created_at || 0).getTime()
|
||||
return (Number.isFinite(tb) ? tb : 0) - (Number.isFinite(ta) ? ta : 0)
|
||||
})
|
||||
|
||||
// 卡片归属用户显示名(我的项目 -> 当前用户;参与项目 -> 项目所有者)
|
||||
const cardOwnerName = (project) => {
|
||||
const cardOwnerName = (project: ProjectListItem) => {
|
||||
if (type === 'my') {
|
||||
return currentUser?.nickname || currentUser?.username || '我'
|
||||
}
|
||||
|
|
@ -99,30 +143,30 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 卡片归属用户头像首字符
|
||||
const cardOwnerInitial = (project) => {
|
||||
const cardOwnerInitial = (project: ProjectListItem) => {
|
||||
const name = cardOwnerName(project)
|
||||
return (name || '?').charAt(0).toUpperCase()
|
||||
}
|
||||
|
||||
// 卡片角色显示名(我的项目 -> 所有者;参与项目 -> 我的角色)
|
||||
const cardRoleLabel = (project) => {
|
||||
const cardRoleLabel = (project: ProjectListItem) => {
|
||||
if (type === 'my') return '所有者'
|
||||
return projectRoleLabel(project.user_role)
|
||||
}
|
||||
|
||||
// 卡片角色徽章样式类
|
||||
const cardRoleClass = (project) => {
|
||||
const cardRoleClass = (project: ProjectListItem) => {
|
||||
if (type === 'my') return 'role-owner'
|
||||
const roleMap = { admin: 'role-admin', editor: 'role-editor', viewer: 'role-viewer' }
|
||||
const roleMap: Record<string, string> = { admin: 'role-admin', editor: 'role-editor', viewer: 'role-viewer' }
|
||||
return roleMap[normalizeRole(project.user_role)] || 'role-viewer'
|
||||
}
|
||||
|
||||
// 卡片角色徽章图标
|
||||
const cardRoleIcon = (project) => {
|
||||
const cardRoleIcon = (project: ProjectListItem) => {
|
||||
const role = normalizeRole(project.user_role)
|
||||
if (type === 'my' || role === 'admin') return <SafetyOutlined />
|
||||
if (role === 'editor') return <FormOutlined />
|
||||
return <ReadOutlined />
|
||||
if (type === 'my' || role === 'admin') return <SafetyOutlined aria-hidden />
|
||||
if (role === 'editor') return <FormOutlined aria-hidden />
|
||||
return <ReadOutlined aria-hidden />
|
||||
}
|
||||
|
||||
const {
|
||||
|
|
@ -149,6 +193,7 @@ function ProjectList({ type = 'my' }) {
|
|||
// ... (fetchProjects code)
|
||||
|
||||
const handleOpenTransfer = async () => {
|
||||
if (!currentProject) return
|
||||
setLoadingMembers(true)
|
||||
setTransferModalVisible(true)
|
||||
try {
|
||||
|
|
@ -156,7 +201,7 @@ function ProjectList({ type = 'my' }) {
|
|||
const res = await getUserList({ page: 1, page_size: 100, status: 1 })
|
||||
const allUsers = res.data || []
|
||||
// 过滤掉当前所有者(也就是自己,虽然API也会校验)
|
||||
setUsers(allUsers.filter(u => u.id !== currentProject.owner_id))
|
||||
setUsers(allUsers.filter((u: User) => u.id !== currentProject.owner_id))
|
||||
} catch (error) {
|
||||
Toast.error('加载用户列表失败')
|
||||
} finally {
|
||||
|
|
@ -164,7 +209,8 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleTransfer = async (values) => {
|
||||
const handleTransfer = async (values: { new_owner_id: number }) => {
|
||||
if (!currentProject) return
|
||||
Toast.confirm({
|
||||
title: '确认转移',
|
||||
content: '确定要将项目所有权转移给该用户吗?转移后您将变为管理员,无法再删除项目或转移所有权。',
|
||||
|
|
@ -180,7 +226,7 @@ function ProjectList({ type = 'my' }) {
|
|||
fetchProjects()
|
||||
} catch (error) {
|
||||
console.error('Transfer error:', error)
|
||||
Toast.error('转移失败: ' + (error.response?.data?.detail || error.message))
|
||||
Toast.error(`转移失败: ${getApiErrorMessage(error, '请稍后重试')}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
@ -213,7 +259,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleCreateProject = async (values) => {
|
||||
const handleCreateProject = async (values: ProjectFormValues) => {
|
||||
try {
|
||||
await createProject(values)
|
||||
Toast.success('创建成功', '项目已创建')
|
||||
|
|
@ -225,7 +271,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
}
|
||||
|
||||
const handleDeleteProject = async (projectId) => {
|
||||
const handleDeleteProject = async (projectId: number) => {
|
||||
Toast.confirm({
|
||||
title: '确认删除',
|
||||
content: '确定要删除这个项目吗?如果项目中存在文件,将无法删除。删除后将无法恢复!',
|
||||
|
|
@ -239,7 +285,7 @@ function ProjectList({ type = 'my' }) {
|
|||
fetchProjects()
|
||||
} catch (error) {
|
||||
console.error('Delete project error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '删除失败'
|
||||
const errorMsg = getApiErrorMessage(error, '删除失败')
|
||||
Toast.error('删除失败', errorMsg)
|
||||
}
|
||||
},
|
||||
|
|
@ -247,7 +293,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 打开编辑项目
|
||||
const handleEdit = (e, project) => {
|
||||
const handleEdit = (e: SyntheticEvent, project: ProjectListItem) => {
|
||||
e.stopPropagation()
|
||||
setCurrentProject(project)
|
||||
editForm.setFieldsValue({
|
||||
|
|
@ -261,17 +307,16 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 切换公开/私有(立即生效)
|
||||
const handlePublicToggle = async (checked) => {
|
||||
const handlePublicToggle = async (checked: boolean) => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
const res = await updateProject(currentProject.id, {
|
||||
is_public: checked ? 1 : 0,
|
||||
})
|
||||
const updatedProject = res.data || {
|
||||
...currentProject,
|
||||
is_public: checked ? 1 : 0,
|
||||
}
|
||||
setCurrentProject(updatedProject)
|
||||
// 更新接口只回项目详情(没有列表统计字段),合并进当前列表项,避免卡片信息丢失
|
||||
setCurrentProject((prev) => (
|
||||
prev ? { ...prev, ...(res.data || {}), is_public: checked ? 1 : 0 } : prev
|
||||
))
|
||||
Toast.success(checked ? '项目已设为公开' : '项目已设为私有')
|
||||
await fetchProjects()
|
||||
|
||||
|
|
@ -292,17 +337,14 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 更新项目(仅名称和描述)
|
||||
const handleUpdateProject = async (values) => {
|
||||
const handleUpdateProject = async (values: ProjectFormValues) => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
const res = await updateProject(currentProject.id, {
|
||||
name: values.name,
|
||||
description: values.description,
|
||||
})
|
||||
const updatedProject = res.data || {
|
||||
...currentProject,
|
||||
...values,
|
||||
}
|
||||
setCurrentProject(updatedProject)
|
||||
setCurrentProject((prev) => (prev ? { ...prev, ...(res.data || {}), ...values } : prev))
|
||||
Toast.success('项目更新成功')
|
||||
await fetchProjects()
|
||||
setEditModalVisible(false)
|
||||
|
|
@ -335,15 +377,15 @@ function ProjectList({ type = 'my' }) {
|
|||
})()
|
||||
}, [editModalVisible, currentProject])
|
||||
|
||||
const [gitRepos, setGitRepos] = useState([])
|
||||
const [gitRepos, setGitRepos] = useState<GitRepo[]>([])
|
||||
const [loadingRepos, setLoadingRepos] = useState(false)
|
||||
const [gitRepoModalVisible, setGitRepoModalVisible] = useState(false)
|
||||
const [editingRepo, setEditingRepo] = useState(null)
|
||||
const [editingRepo, setEditingRepo] = useState<GitRepo | null>(null)
|
||||
const [testingGitRepo, setTestingGitRepo] = useState(false)
|
||||
const [repoForm] = Form.useForm()
|
||||
|
||||
// 打开Git设置(仓库列表)
|
||||
const handleGitSettings = (e, project) => {
|
||||
const handleGitSettings = (e: SyntheticEvent, project: ProjectListItem) => {
|
||||
e.stopPropagation()
|
||||
setCurrentProject(project)
|
||||
setGitModalVisible(true)
|
||||
|
|
@ -351,14 +393,14 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 打开知识库(向量化进度)弹窗
|
||||
const handleKnowledge = (e, project) => {
|
||||
const handleKnowledge = (e: SyntheticEvent, project: ProjectListItem) => {
|
||||
e.stopPropagation()
|
||||
setCurrentProject(project)
|
||||
openKnowledgeModal(project)
|
||||
}
|
||||
|
||||
// 加载Git仓库列表
|
||||
const fetchGitRepos = async (projectId) => {
|
||||
const fetchGitRepos = async (projectId: number) => {
|
||||
setLoadingRepos(true)
|
||||
try {
|
||||
const res = await getGitRepos(projectId)
|
||||
|
|
@ -383,7 +425,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 打开编辑仓库弹窗
|
||||
const handleEditRepo = (repo) => {
|
||||
const handleEditRepo = (repo: GitRepo) => {
|
||||
setEditingRepo(repo)
|
||||
repoForm.setFieldsValue({
|
||||
...repo,
|
||||
|
|
@ -393,6 +435,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
const handleTestRepoConnection = async () => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
const values = await repoForm.validateFields(['repo_url', 'branch', 'username', 'token'])
|
||||
setTestingGitRepo(true)
|
||||
|
|
@ -402,8 +445,9 @@ function ProjectList({ type = 'my' }) {
|
|||
})
|
||||
Toast.success('远端仓库认证成功')
|
||||
} catch (error) {
|
||||
if (error?.errorFields) return
|
||||
const errorMsg = error.response?.data?.detail || '远端仓库认证失败'
|
||||
// 表单校验失败由 antd 就地提示,不再叠加 Toast
|
||||
if (error && typeof error === 'object' && 'errorFields' in error) return
|
||||
const errorMsg = getApiErrorDetail(error) || '远端仓库认证失败'
|
||||
Toast.error(errorMsg)
|
||||
} finally {
|
||||
setTestingGitRepo(false)
|
||||
|
|
@ -411,7 +455,8 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 删除仓库
|
||||
const handleDeleteRepo = (repoId) => {
|
||||
const handleDeleteRepo = (repoId: number) => {
|
||||
if (!currentProject) return
|
||||
Toast.confirm({
|
||||
title: '确认删除',
|
||||
content: '确定要删除这个Git仓库配置吗?',
|
||||
|
|
@ -422,16 +467,17 @@ function ProjectList({ type = 'my' }) {
|
|||
fetchGitRepos(currentProject.id)
|
||||
} catch (error) {
|
||||
console.error('Delete repo error:', error)
|
||||
Toast.error(error.response?.data?.detail || '删除失败')
|
||||
Toast.error(getApiErrorDetail(error) || '删除失败')
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 保存仓库(新增/更新)
|
||||
const handleSaveRepo = async (values) => {
|
||||
const handleSaveRepo = async (values: GitRepoFormValues) => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
const data = {
|
||||
const data: GitRepoPayload = {
|
||||
...values,
|
||||
is_default: values.is_default ? 1 : 0,
|
||||
}
|
||||
|
|
@ -448,11 +494,11 @@ function ProjectList({ type = 'my' }) {
|
|||
fetchGitRepos(currentProject.id)
|
||||
} catch (error) {
|
||||
console.error('Save repo error:', error)
|
||||
Toast.error(error.response?.data?.detail || (editingRepo ? '更新失败' : '添加失败'))
|
||||
Toast.error(getApiErrorDetail(error) || (editingRepo ? '更新失败' : '添加失败'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenProject = (projectId) => {
|
||||
const handleOpenProject = (projectId: number) => {
|
||||
// 打开参与项目时,将其未读更新通知标记为已读(与消息通知联动)
|
||||
if (type === 'share' && unreadByProject[projectId]) {
|
||||
markProjectNotificationsRead(projectId)
|
||||
|
|
@ -504,7 +550,8 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 切换密码保护
|
||||
const handlePasswordToggle = async (checked) => {
|
||||
const handlePasswordToggle = async (checked: boolean) => {
|
||||
if (!currentProject) return
|
||||
if (!checked) {
|
||||
try {
|
||||
await updateProjectShareSettings(currentProject.id, { access_pass: null })
|
||||
|
|
@ -524,6 +571,7 @@ function ProjectList({ type = 'my' }) {
|
|||
|
||||
// 保存密码
|
||||
const handleSavePassword = async () => {
|
||||
if (!currentProject) return
|
||||
if (!password.trim()) {
|
||||
Toast.warning('请输入访问密码')
|
||||
return
|
||||
|
|
@ -541,7 +589,8 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 打开成员管理
|
||||
const handleMembers = async (e, project) => {
|
||||
// 卡片本身可点进入项目,这里必须阻止冒泡;鼠标与键盘两条路径共用同一处理
|
||||
const handleMembers = async (e: SyntheticEvent, project: ProjectListItem) => {
|
||||
e.stopPropagation()
|
||||
setCurrentProject(project)
|
||||
setMembersModalVisible(true)
|
||||
|
|
@ -562,15 +611,15 @@ function ProjectList({ type = 'my' }) {
|
|||
setUsers(usersData)
|
||||
} catch (error) {
|
||||
console.error('Get members error:', error)
|
||||
console.error('Error details:', error.response)
|
||||
Toast.error('获取数据失败: ' + (error.response?.data?.detail || error.message))
|
||||
Toast.error(`获取数据失败: ${getApiErrorMessage(error, '请稍后重试')}`)
|
||||
} finally {
|
||||
setLoadingMembers(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 添加成员
|
||||
const handleAddMember = async (values) => {
|
||||
const handleAddMember = async (values: { user_id: number; role: ProjectRole }) => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
await addProjectMember(currentProject.id, values)
|
||||
Toast.success('成员添加成功')
|
||||
|
|
@ -580,13 +629,14 @@ function ProjectList({ type = 'my' }) {
|
|||
setMembers(res.data || [])
|
||||
} catch (error) {
|
||||
console.error('Add member error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '添加成员失败'
|
||||
const errorMsg = getApiErrorMessage(error, '添加成员失败')
|
||||
Toast.error(errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除成员
|
||||
const handleRemoveMember = async (userId) => {
|
||||
const handleRemoveMember = async (userId: number) => {
|
||||
if (!currentProject) return
|
||||
Toast.confirm({
|
||||
title: '确认删除',
|
||||
content: '确定要删除这个成员吗?',
|
||||
|
|
@ -599,7 +649,7 @@ function ProjectList({ type = 'my' }) {
|
|||
setMembers(res.data || [])
|
||||
} catch (error) {
|
||||
console.error('Remove member error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '删除成员失败'
|
||||
const errorMsg = getApiErrorMessage(error, '删除成员失败')
|
||||
Toast.error(errorMsg)
|
||||
}
|
||||
},
|
||||
|
|
@ -607,7 +657,8 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 修改成员角色(列表内直接切换)
|
||||
const handleChangeMemberRole = async (record, role) => {
|
||||
const handleChangeMemberRole = async (record: ProjectMember, role: ProjectRole) => {
|
||||
if (!currentProject) return
|
||||
try {
|
||||
await updateProjectMemberRole(currentProject.id, record.user_id, role)
|
||||
Toast.success('成功', `${record.nickname || record.username} 的角色已更新为${memberRoleLabels[role] || role}`)
|
||||
|
|
@ -616,13 +667,13 @@ function ProjectList({ type = 'my' }) {
|
|||
setMembers(res.data || [])
|
||||
} catch (error) {
|
||||
console.error('Update member role error:', error)
|
||||
const errorMsg = error.response?.data?.detail || error.message || '更新角色失败'
|
||||
const errorMsg = getApiErrorMessage(error, '更新角色失败')
|
||||
Toast.error(errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理搜索输入变化
|
||||
const handleSearchChange = (value) => {
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchKeyword(value)
|
||||
// 如果清空了输入框,重置搜索状态
|
||||
if (!value || !value.trim()) {
|
||||
|
|
@ -632,7 +683,7 @@ function ProjectList({ type = 'my' }) {
|
|||
}
|
||||
|
||||
// 处理搜索
|
||||
const handleSearch = async (keyword) => {
|
||||
const handleSearch = async (keyword: string) => {
|
||||
setSearchKeyword(keyword)
|
||||
|
||||
if (!keyword || !keyword.trim()) {
|
||||
|
|
@ -650,14 +701,14 @@ function ProjectList({ type = 'my' }) {
|
|||
setSearchResults(res.data || [])
|
||||
} catch (error) {
|
||||
console.error('Search error:', error)
|
||||
Toast.error('搜索失败', error.response?.data?.detail || error.message)
|
||||
Toast.error('搜索失败', getApiErrorDetail(error))
|
||||
} finally {
|
||||
setSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理搜索结果点击
|
||||
const handleSearchResultClick = (item) => {
|
||||
const handleSearchResultClick = (item: SearchResult) => {
|
||||
if (item.type === 'project') {
|
||||
// 跳转到项目文档页
|
||||
navigate(`/projects/${item.project_id}/docs`)
|
||||
|
|
@ -685,7 +736,7 @@ function ProjectList({ type = 'my' }) {
|
|||
key: 'create',
|
||||
label: '创建项目',
|
||||
type: 'primary',
|
||||
icon: <PlusOutlined />,
|
||||
icon: <PlusOutlined aria-hidden />,
|
||||
onClick: () => setModalVisible(true),
|
||||
},
|
||||
] : []}
|
||||
|
|
@ -715,9 +766,9 @@ function ProjectList({ type = 'my' }) {
|
|||
>
|
||||
<div className="project-card-icon">
|
||||
{item.type === 'project' ? (
|
||||
<FolderOutlined style={{ fontSize: 48, color: 'var(--color-primary)' }} />
|
||||
<FolderOutlined style={{ fontSize: 48, color: 'var(--color-primary)' }} aria-hidden />
|
||||
) : (
|
||||
<FileOutlined style={{ fontSize: 48, color: 'var(--color-success)' }} />
|
||||
<FileOutlined style={{ fontSize: 48, color: 'var(--color-success)' }} aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
|
|
@ -759,22 +810,44 @@ function ProjectList({ type = 'my' }) {
|
|||
className={type === 'share' ? 'project-card project-card-share' : 'project-card project-card-my'}
|
||||
onClick={() => handleOpenProject(project.id)}
|
||||
actions={type === 'my' ? [
|
||||
<Tooltip key="settings" title="项目设置"><SettingOutlined onClick={(e) => handleEdit(e, project)} /></Tooltip>,
|
||||
<Tooltip key="settings" title="项目设置">
|
||||
<SettingOutlined
|
||||
aria-label="项目设置"
|
||||
onClick={(e) => handleEdit(e, project)}
|
||||
{...keyboardActivation((e) => handleEdit(e, project))}
|
||||
/>
|
||||
</Tooltip>,
|
||||
<Tooltip key="git" title={(project.git_repo_count || 0) > 0 ? 'Git 仓库(已配置)' : 'Git 仓库'}>
|
||||
{(project.git_repo_count || 0) > 0 ? (
|
||||
<GithubFilled
|
||||
className="project-card-git-action-icon configured"
|
||||
onClick={(e) => handleGitSettings(e, project)}
|
||||
aria-label="Git 仓库"
|
||||
{...keyboardActivation((e) => handleGitSettings(e, project))}
|
||||
/>
|
||||
) : (
|
||||
<BranchesOutlined
|
||||
className="project-card-git-action-icon"
|
||||
onClick={(e) => handleGitSettings(e, project)}
|
||||
aria-label="Git 仓库"
|
||||
{...keyboardActivation((e) => handleGitSettings(e, project))}
|
||||
/>
|
||||
)}
|
||||
</Tooltip>,
|
||||
<Tooltip key="kb" title="知识库向量化"><DatabaseOutlined onClick={(e) => handleKnowledge(e, project)} /></Tooltip>,
|
||||
<Tooltip key="members" title="成员管理"><TeamOutlined onClick={(e) => handleMembers(e, project)} /></Tooltip>,
|
||||
<Tooltip key="kb" title="知识库向量化">
|
||||
<DatabaseOutlined
|
||||
aria-label="知识库向量化"
|
||||
onClick={(e) => handleKnowledge(e, project)}
|
||||
{...keyboardActivation((e) => handleKnowledge(e, project))}
|
||||
/>
|
||||
</Tooltip>,
|
||||
<Tooltip key="members" title="成员管理">
|
||||
<TeamOutlined
|
||||
aria-label="成员管理"
|
||||
onClick={(e) => handleMembers(e, project)}
|
||||
{...keyboardActivation((e) => handleMembers(e, project))}
|
||||
/>
|
||||
</Tooltip>,
|
||||
] : [
|
||||
<Tooltip key="view" title={`以${cardRoleLabel(project)}身份进入项目`}>
|
||||
<span className={`project-card-view-action ${cardRoleClass(project)}`}>
|
||||
|
|
@ -787,8 +860,9 @@ function ProjectList({ type = 'my' }) {
|
|||
<span
|
||||
className="project-card-member-action"
|
||||
onClick={(e) => handleMembers(e, project)}
|
||||
{...keyboardActivation((e) => handleMembers(e, project))}
|
||||
>
|
||||
<TeamOutlined />
|
||||
<TeamOutlined aria-hidden />
|
||||
<span>成员管理</span>
|
||||
</span>
|
||||
</Tooltip>,
|
||||
|
|
@ -813,7 +887,7 @@ function ProjectList({ type = 'my' }) {
|
|||
<div className="project-card-body">
|
||||
<div className="project-card-title-row">
|
||||
<span className={`project-card-title-icon ${type === 'my' ? 'is-owner' : 'is-shared'}`}>
|
||||
{type === 'my' ? <FolderOutlined /> : <TeamOutlined />}
|
||||
{type === 'my' ? <FolderOutlined aria-hidden /> : <TeamOutlined aria-hidden />}
|
||||
</span>
|
||||
<h3 title={project.name}>{project.name}</h3>
|
||||
</div>
|
||||
|
|
@ -823,22 +897,22 @@ function ProjectList({ type = 'my' }) {
|
|||
{type === 'my' ? (
|
||||
<>
|
||||
<span className="project-stat-item" title="文档数量">
|
||||
<FileTextOutlined /> {project.doc_count || 0} 文档
|
||||
<FileTextOutlined aria-hidden /> {project.doc_count || 0} 文档
|
||||
</span>
|
||||
<span className="project-stat-item" title="最后更新时间">
|
||||
<CalendarOutlined /> {formatRelativeTime(project.last_activity_at) || formatDate(project.created_at) || '—'}
|
||||
<CalendarOutlined aria-hidden /> {formatRelativeTime(project.last_activity_at) || formatDate(project.created_at) || '—'}
|
||||
</span>
|
||||
<span className="project-stat-item" title="项目参与人数量">
|
||||
<TeamOutlined /> {project.member_count ?? 0} 人参与
|
||||
<TeamOutlined aria-hidden /> {project.member_count ?? 0} 人参与
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="project-stat-item" title="文档数量">
|
||||
<FileTextOutlined /> {project.doc_count || 0} 文档
|
||||
<FileTextOutlined aria-hidden /> {project.doc_count || 0} 文档
|
||||
</span>
|
||||
<span className="project-stat-item" title="最后更新时间">
|
||||
<CalendarOutlined /> {formatRelativeTime(project.last_activity_at) || formatDate(project.created_at) || '—'}
|
||||
<CalendarOutlined aria-hidden /> {formatRelativeTime(project.last_activity_at) || formatDate(project.created_at) || '—'}
|
||||
</span>
|
||||
<span className="project-card-owner" title={cardOwnerName(project)}>
|
||||
<span className="project-card-owner-avatar">{cardOwnerInitial(project)}</span>
|
||||
|
|
@ -867,11 +941,11 @@ function ProjectList({ type = 'my' }) {
|
|||
onChange={setCurrentPage}
|
||||
showSizeChanger={false}
|
||||
className="dot-pagination"
|
||||
itemRender={(page, type, originalElement) => {
|
||||
itemRender={(_page, type, originalElement) => {
|
||||
if (type === 'page') {
|
||||
return <span className="pagination-dot" />
|
||||
}
|
||||
return originalElement
|
||||
return namePageItem(_page, type, originalElement)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -985,7 +1059,14 @@ function ProjectList({ type = 'my' }) {
|
|||
value={shareInfo?.share_url ? `${window.location.origin}${shareInfo.share_url}` : '正在生成分享链接...'}
|
||||
readOnly
|
||||
addonAfter={
|
||||
shareInfo?.share_url ? <CopyOutlined onClick={handleCopyLink} style={{ cursor: 'pointer' }} /> : null
|
||||
shareInfo?.share_url ? (
|
||||
<CopyOutlined
|
||||
aria-label="复制分享链接"
|
||||
onClick={handleCopyLink}
|
||||
{...keyboardActivation(() => handleCopyLink())}
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<Space>
|
||||
|
|
@ -995,6 +1076,7 @@ function ProjectList({ type = 'my' }) {
|
|||
{hasPassword && (
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input.Password
|
||||
iconRender={passwordVisibilityIcon}
|
||||
placeholder="请输入访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
|
|
@ -1014,18 +1096,18 @@ function ProjectList({ type = 'my' }) {
|
|||
<Space>
|
||||
<Button
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<DeleteOutlined aria-hidden />}
|
||||
onClick={() => {
|
||||
setEditModalVisible(false)
|
||||
editForm.resetFields()
|
||||
handleDeleteProject(currentProject.id)
|
||||
if (currentProject) handleDeleteProject(currentProject.id)
|
||||
}}
|
||||
>
|
||||
删除项目
|
||||
</Button>
|
||||
<Button
|
||||
danger
|
||||
icon={<SwapOutlined />}
|
||||
icon={<SwapOutlined aria-hidden />}
|
||||
onClick={handleOpenTransfer}
|
||||
>
|
||||
转移所有权
|
||||
|
|
@ -1062,7 +1144,7 @@ function ProjectList({ type = 'my' }) {
|
|||
layout="vertical"
|
||||
onFinish={handleTransfer}
|
||||
>
|
||||
<p style={{ color: '#f5222d', marginBottom: 16 }}>
|
||||
<p style={{ color: 'var(--color-danger-strong)', marginBottom: 16 }}>
|
||||
警告:转移所有权后,您将失去该项目的所有权并变为普通管理员,且无法撤销此操作。
|
||||
</p>
|
||||
<Form.Item
|
||||
|
|
@ -1191,14 +1273,14 @@ function ProjectList({ type = 'my' }) {
|
|||
return (
|
||||
<Select
|
||||
size="small"
|
||||
value={normalizeRole(role)}
|
||||
value={toMemberRole(role)}
|
||||
style={{ width: 110 }}
|
||||
onChange={(newRole) => handleChangeMemberRole(record, newRole)}
|
||||
options={[
|
||||
{ value: 'admin', label: '管理员' },
|
||||
{ value: 'editor', label: '编辑者' },
|
||||
{ value: 'viewer', label: '查看者' },
|
||||
]}
|
||||
aria-label="成员角色"
|
||||
onChange={(newRole: ProjectRole) => handleChangeMemberRole(record, newRole)}
|
||||
options={memberRoleValues.map((value) => ({
|
||||
value,
|
||||
label: memberRoleLabels[value],
|
||||
}))}
|
||||
/>
|
||||
)
|
||||
},
|
||||
|
|
@ -1245,7 +1327,7 @@ function ProjectList({ type = 'my' }) {
|
|||
width={800}
|
||||
>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={handleAddRepo}>
|
||||
<Button type="primary" icon={<PlusOutlined aria-hidden />} onClick={handleAddRepo}>
|
||||
添加仓库
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -1296,8 +1378,8 @@ function ProjectList({ type = 'my' }) {
|
|||
width: 150,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEditRepo(record)}>编辑</Button>
|
||||
<Button type="link" danger size="small" icon={<DeleteOutlined />} onClick={() => handleDeleteRepo(record.id)}>删除</Button>
|
||||
<Button type="link" size="small" icon={<EditOutlined aria-hidden />} onClick={() => handleEditRepo(record)}>编辑</Button>
|
||||
<Button type="link" danger size="small" icon={<DeleteOutlined aria-hidden />} onClick={() => handleDeleteRepo(record.id)}>删除</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
|
|
@ -1333,7 +1415,7 @@ function ProjectList({ type = 'my' }) {
|
|||
rules={[{ required: true, message: '请输入Git仓库地址' }, { type: 'url', message: '请输入有效的URL' }]}
|
||||
extra="支持 HTTPS 协议"
|
||||
>
|
||||
<Input placeholder="https://github.com/username/repo.git" prefix={<GithubOutlined />} />
|
||||
<Input placeholder="https://github.com/username/repo.git" prefix={<GithubOutlined aria-hidden />} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
|
|
@ -1357,7 +1439,7 @@ function ProjectList({ type = 'my' }) {
|
|||
name="token"
|
||||
extra="推荐使用 Personal Access Token"
|
||||
>
|
||||
<Input.Password placeholder="Git访问令牌" />
|
||||
<Input.Password iconRender={passwordVisibilityIcon} placeholder="Git访问令牌" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
|
|
@ -1386,7 +1468,7 @@ function ProjectList({ type = 'my' }) {
|
|||
onCancel={closeKnowledgeModal}
|
||||
width={640}
|
||||
footer={[
|
||||
<Button key="refresh" icon={<ReloadOutlined />} onClick={() => refreshProgress(currentProject?.id)} disabled={vectorizing || loadingProgress}>
|
||||
<Button key="refresh" icon={<ReloadOutlined aria-hidden />} onClick={() => currentProject && refreshProgress(currentProject.id)} disabled={vectorizing || loadingProgress}>
|
||||
刷新
|
||||
</Button>,
|
||||
<Button key="close" onClick={closeKnowledgeModal}>关闭</Button>,
|
||||
|
|
@ -1395,7 +1477,7 @@ function ProjectList({ type = 'my' }) {
|
|||
type="primary"
|
||||
loading={vectorizing}
|
||||
disabled={vectorizing || !progress?.embedding_ready}
|
||||
onClick={() => runVectorize(currentProject?.id, { force: false })}
|
||||
onClick={() => currentProject && runVectorize(currentProject.id, { force: false })}
|
||||
>
|
||||
增量向量化
|
||||
</Button>,
|
||||
|
|
@ -1404,7 +1486,7 @@ function ProjectList({ type = 'my' }) {
|
|||
danger
|
||||
loading={vectorizing}
|
||||
disabled={vectorizing || !progress?.embedding_ready}
|
||||
onClick={() => runVectorize(currentProject?.id, { force: true })}
|
||||
onClick={() => currentProject && runVectorize(currentProject.id, { force: true })}
|
||||
>
|
||||
全量向量化
|
||||
</Button>,
|
||||
|
|
@ -1429,6 +1511,9 @@ function ProjectList({ type = 'my' }) {
|
|||
style={{ marginBottom: 16 }}
|
||||
type={currentTask.status === 'failed' ? 'error' : currentTask.status === 'success' ? 'success' : 'info'}
|
||||
showIcon
|
||||
icon={decorativeAlertIcon(
|
||||
currentTask.status === 'failed' ? 'error' : currentTask.status === 'success' ? 'success' : 'info',
|
||||
)}
|
||||
message={
|
||||
`最近任务:${currentTask.task_type === 'full' ? '全量向量化' : '增量向量化'} · ` +
|
||||
`${currentTask.status === 'pending' ? '等待执行' : currentTask.status === 'running' ? '后台执行中' : currentTask.status === 'success' ? '已完成' : '执行失败'}`
|
||||
|
|
@ -1,15 +1,23 @@
|
|||
import { useEffect, useRef, useState } from 'react'
|
||||
import { getLatestVectorizeTask, getVectorizeProgress, getVectorizeTask, vectorizeProject } from '@/api/knowledgeBase'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import type { Project, VectorizeProgress, VectorizeTask } from '@/types/api'
|
||||
|
||||
const RUNNING_TASK_STATUSES = ['pending', 'running']
|
||||
|
||||
function isRunningTask(task: VectorizeTask | null): boolean {
|
||||
return RUNNING_TASK_STATUSES.includes(task?.status ?? '')
|
||||
}
|
||||
|
||||
function useProjectKnowledge() {
|
||||
const [kbModalVisible, setKbModalVisible] = useState(false)
|
||||
const [kbProject, setKbProject] = useState(null)
|
||||
const [progress, setProgress] = useState(null)
|
||||
const [currentTask, setCurrentTask] = useState(null)
|
||||
const [kbProject, setKbProject] = useState<Project | null>(null)
|
||||
const [progress, setProgress] = useState<VectorizeProgress | null>(null)
|
||||
const [currentTask, setCurrentTask] = useState<VectorizeTask | null>(null)
|
||||
const [loadingProgress, setLoadingProgress] = useState(false)
|
||||
const [vectorizing, setVectorizing] = useState(false)
|
||||
const pollTimer = useRef(null)
|
||||
const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
const clearPoll = () => {
|
||||
if (pollTimer.current) {
|
||||
|
|
@ -20,7 +28,7 @@ function useProjectKnowledge() {
|
|||
|
||||
useEffect(() => () => clearPoll(), [])
|
||||
|
||||
const fetchProgress = async (projectId, { silent = false } = {}) => {
|
||||
const fetchProgress = async (projectId: number, { silent = false }: { silent?: boolean } = {}) => {
|
||||
if (!silent) setLoadingProgress(true)
|
||||
try {
|
||||
const res = await getVectorizeProgress(projectId)
|
||||
|
|
@ -35,12 +43,12 @@ function useProjectKnowledge() {
|
|||
}
|
||||
}
|
||||
|
||||
const syncLatestTask = async (projectId) => {
|
||||
const syncLatestTask = async (projectId: number) => {
|
||||
try {
|
||||
const res = await getLatestVectorizeTask(projectId)
|
||||
const task = res.data || null
|
||||
setCurrentTask(task)
|
||||
setVectorizing(['pending', 'running'].includes(task?.status))
|
||||
setVectorizing(isRunningTask(task))
|
||||
return task
|
||||
} catch (error) {
|
||||
console.error('Fetch vectorize task error:', error)
|
||||
|
|
@ -48,7 +56,7 @@ function useProjectKnowledge() {
|
|||
}
|
||||
}
|
||||
|
||||
const pollTask = (projectId, taskId) => {
|
||||
const pollTask = (projectId: number, taskId: string) => {
|
||||
clearPoll()
|
||||
pollTimer.current = setInterval(async () => {
|
||||
try {
|
||||
|
|
@ -59,7 +67,7 @@ function useProjectKnowledge() {
|
|||
const task = taskRes.data || null
|
||||
setCurrentTask(task)
|
||||
|
||||
if (!['pending', 'running'].includes(task?.status)) {
|
||||
if (!isRunningTask(task)) {
|
||||
clearPoll()
|
||||
setVectorizing(false)
|
||||
await fetchProgress(projectId, { silent: true })
|
||||
|
|
@ -81,14 +89,14 @@ function useProjectKnowledge() {
|
|||
}, 2000)
|
||||
}
|
||||
|
||||
const openKnowledgeModal = async (project) => {
|
||||
const openKnowledgeModal = async (project: Project) => {
|
||||
setKbProject(project)
|
||||
setKbModalVisible(true)
|
||||
setProgress(null)
|
||||
setCurrentTask(null)
|
||||
await fetchProgress(project.id)
|
||||
const task = await syncLatestTask(project.id)
|
||||
if (['pending', 'running'].includes(task?.status)) {
|
||||
if (task && isRunningTask(task)) {
|
||||
pollTask(project.id, task.task_id)
|
||||
}
|
||||
}
|
||||
|
|
@ -102,7 +110,7 @@ function useProjectKnowledge() {
|
|||
setVectorizing(false)
|
||||
}
|
||||
|
||||
const runVectorize = async (projectId, { force = false } = {}) => {
|
||||
const runVectorize = async (projectId: number, { force = false }: { force?: boolean } = {}) => {
|
||||
if (!projectId) return
|
||||
setVectorizing(true)
|
||||
try {
|
||||
|
|
@ -116,8 +124,7 @@ function useProjectKnowledge() {
|
|||
}
|
||||
} catch (error) {
|
||||
console.error('Vectorize project error:', error)
|
||||
const detail = error.response?.data?.detail || '向量化失败'
|
||||
Toast.error(detail)
|
||||
Toast.error(getApiErrorDetail(error) || '向量化失败')
|
||||
await fetchProgress(projectId, { silent: true })
|
||||
} finally {
|
||||
if (!pollTimer.current) {
|
||||
|
|
@ -38,12 +38,18 @@ import {
|
|||
testLLMModelConfig,
|
||||
updateLLMModelConfig,
|
||||
updateLLMModelConfigStatus,
|
||||
type LLMModelConfigPayload,
|
||||
type LLMModelConfigQuery,
|
||||
} from '@/api/llmModelConfigs'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import type { LLMModelConfig, LLMProvider, LLMTestResult, ModelType } from '@/types/api'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import ListTable from '@/components/ListTable/ListTable'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import './ModelConfigs.css'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
import { clearInputIcon, passwordVisibilityIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Search, TextArea } = Input
|
||||
|
||||
|
|
@ -56,25 +62,34 @@ const MAX_TOKENS_OPTIONS = [
|
|||
|
||||
const DEFAULT_MAX_TOKENS = 8192
|
||||
|
||||
const MODEL_TYPE_META = {
|
||||
const MODEL_TYPE_META: Record<ModelType, {
|
||||
label: string
|
||||
icon: JSX.Element
|
||||
description: string
|
||||
addText: string
|
||||
}> = {
|
||||
chat: {
|
||||
label: '对话模型',
|
||||
icon: <CommentOutlined />,
|
||||
icon: <CommentOutlined aria-hidden />,
|
||||
description: '用于知识库对话、问答生成的大语言模型。',
|
||||
addText: '新增对话模型',
|
||||
},
|
||||
embedding: {
|
||||
label: '向量模型',
|
||||
icon: <DeploymentUnitOutlined />,
|
||||
icon: <DeploymentUnitOutlined aria-hidden />,
|
||||
description: '用于文档向量化(ZVec)与语义检索的 Embedding 模型。',
|
||||
addText: '新增向量模型',
|
||||
},
|
||||
}
|
||||
|
||||
function buildModelCode(provider, llmModelName, modelType) {
|
||||
function buildModelCode(
|
||||
provider: string | undefined,
|
||||
llmModelName: string | undefined,
|
||||
modelType: ModelType,
|
||||
) {
|
||||
const providerPart = (provider || 'custom').trim().toLowerCase()
|
||||
const modelPart = (llmModelName || '').trim().toLowerCase()
|
||||
const sanitized = []
|
||||
const sanitized: string[] = []
|
||||
let previousSeparator = false
|
||||
|
||||
for (const char of modelPart) {
|
||||
|
|
@ -92,7 +107,11 @@ function buildModelCode(provider, llmModelName, modelType) {
|
|||
return modelType === 'embedding' ? `emb_${base}` : base
|
||||
}
|
||||
|
||||
function buildModelName(providerMeta, provider, llmModelName) {
|
||||
function buildModelName(
|
||||
providerMeta: LLMProvider | undefined,
|
||||
provider: string | undefined,
|
||||
llmModelName: string | undefined,
|
||||
) {
|
||||
const label = providerMeta?.label || provider || '自定义模型'
|
||||
const modelPart = (llmModelName || '').trim()
|
||||
if (!modelPart) {
|
||||
|
|
@ -101,16 +120,31 @@ function buildModelName(providerMeta, provider, llmModelName) {
|
|||
return `${label} ${modelPart}`
|
||||
}
|
||||
|
||||
function formatDateTime(value) {
|
||||
function formatDateTime(value?: string | null) {
|
||||
if (!value) return '-'
|
||||
return new Date(value).toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/编辑表单的取值形状:弹窗打开时会写入全部必填字段(含隐藏的 model_type),
|
||||
* 因此直接复用提交契约;提交时仍按当前编辑的 Tab 覆盖 model_type。
|
||||
*/
|
||||
type ModelConfigFormValues = LLMModelConfigPayload
|
||||
|
||||
/** 自动回填时只写入变化的字段 */
|
||||
type ModelConfigFormPatch = Partial<ModelConfigFormValues>
|
||||
|
||||
interface AutoFillFlags {
|
||||
endpointUrl: boolean
|
||||
modelName: boolean
|
||||
modelCode: boolean
|
||||
}
|
||||
|
||||
function ModelConfigs() {
|
||||
const [form] = Form.useForm()
|
||||
const [form] = Form.useForm<ModelConfigFormValues>()
|
||||
const screens = Grid.useBreakpoint()
|
||||
const [activeType, setActiveType] = useState('chat')
|
||||
const [editingType, setEditingType] = useState('chat')
|
||||
const [activeType, setActiveType] = useState<ModelType>('chat')
|
||||
const [editingType, setEditingType] = useState<ModelType>('chat')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [testing, setTesting] = useState(false)
|
||||
|
|
@ -118,21 +152,21 @@ function ModelConfigs() {
|
|||
const [pageSize, setPageSize] = useState(10)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const [providerFilter, setProviderFilter] = useState(undefined)
|
||||
const [statusFilter, setStatusFilter] = useState(undefined)
|
||||
const [configs, setConfigs] = useState([])
|
||||
const [providerCatalog, setProviderCatalog] = useState([])
|
||||
const [providerFilter, setProviderFilter] = useState<string | undefined>(undefined)
|
||||
const [statusFilter, setStatusFilter] = useState<boolean | undefined>(undefined)
|
||||
const [configs, setConfigs] = useState<LLMModelConfig[]>([])
|
||||
const [providerCatalog, setProviderCatalog] = useState<LLMProvider[]>([])
|
||||
const [modalVisible, setModalVisible] = useState(false)
|
||||
const [editingConfigId, setEditingConfigId] = useState(null)
|
||||
const [autoFillFlags, setAutoFillFlags] = useState({
|
||||
const [editingConfigId, setEditingConfigId] = useState<number | null>(null)
|
||||
const [autoFillFlags, setAutoFillFlags] = useState<AutoFillFlags>({
|
||||
endpointUrl: true,
|
||||
modelName: true,
|
||||
modelCode: true,
|
||||
})
|
||||
const loadRequestIdRef = useRef(0)
|
||||
const loadRequestIdRef = useRef<number>(0)
|
||||
|
||||
const providerValue = Form.useWatch('provider', form)
|
||||
const llmModelNameValue = Form.useWatch('llm_model_name', form)
|
||||
const providerValue = Form.useWatch('provider', form) as string | undefined
|
||||
const llmModelNameValue = Form.useWatch('llm_model_name', form) as string | undefined
|
||||
const isEmbedding = editingType === 'embedding'
|
||||
const isLocalProvider = providerValue === 'local'
|
||||
const localModels = providerCatalog.find((item) => item.value === 'local')?.models || []
|
||||
|
|
@ -159,7 +193,7 @@ function ModelConfigs() {
|
|||
}
|
||||
|
||||
const currentValues = form.getFieldsValue()
|
||||
const nextValues = {}
|
||||
const nextValues: ModelConfigFormPatch = {}
|
||||
|
||||
if (autoFillFlags.endpointUrl) {
|
||||
const nextEndpointUrl = providerMeta.default_endpoint_url || ''
|
||||
|
|
@ -203,7 +237,7 @@ function ModelConfigs() {
|
|||
const requestId = ++loadRequestIdRef.current
|
||||
try {
|
||||
setLoading(true)
|
||||
const params = {
|
||||
const params: LLMModelConfigQuery = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
model_type: activeType,
|
||||
|
|
@ -226,10 +260,11 @@ function ModelConfigs() {
|
|||
}
|
||||
}
|
||||
|
||||
const getProviderMeta = (provider) => providerCatalog.find((item) => item.value === provider)
|
||||
const getProviderMeta = (provider?: string | null) =>
|
||||
providerCatalog.find((item) => item.value === provider)
|
||||
|
||||
const handleTabChange = (key) => {
|
||||
setActiveType(key)
|
||||
const handleTabChange = (key: string) => {
|
||||
setActiveType(key as ModelType)
|
||||
setPage(1)
|
||||
setKeyword('')
|
||||
setProviderFilter(undefined)
|
||||
|
|
@ -276,7 +311,7 @@ function ModelConfigs() {
|
|||
setModalVisible(true)
|
||||
}
|
||||
|
||||
const openEditModal = async (record) => {
|
||||
const openEditModal = async (record: LLMModelConfig) => {
|
||||
try {
|
||||
const res = await getLLMModelConfigDetail(record.config_id)
|
||||
const detail = res.data
|
||||
|
|
@ -307,10 +342,10 @@ function ModelConfigs() {
|
|||
form.resetFields()
|
||||
}
|
||||
|
||||
const handleSubmit = async (values) => {
|
||||
const handleSubmit = async (values: ModelConfigFormValues) => {
|
||||
try {
|
||||
setSubmitting(true)
|
||||
const payload = { ...values, model_type: editingType }
|
||||
const payload: LLMModelConfigPayload = { ...values, model_type: editingType }
|
||||
if (editingConfigId) {
|
||||
await updateLLMModelConfig(editingConfigId, payload)
|
||||
Toast.success('模型配置更新成功')
|
||||
|
|
@ -321,33 +356,33 @@ function ModelConfigs() {
|
|||
closeModal()
|
||||
loadConfigs()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '保存模型配置失败')
|
||||
Toast.error(getApiErrorDetail(error) || '保存模型配置失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (record) => {
|
||||
const handleDelete = async (record: LLMModelConfig) => {
|
||||
try {
|
||||
await deleteLLMModelConfig(record.config_id)
|
||||
Toast.success('模型配置删除成功')
|
||||
loadConfigs()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除模型配置失败')
|
||||
Toast.error(getApiErrorDetail(error) || '删除模型配置失败')
|
||||
}
|
||||
}
|
||||
|
||||
const handleStatusChange = async (record, checked) => {
|
||||
const handleStatusChange = async (record: LLMModelConfig, checked: boolean) => {
|
||||
try {
|
||||
await updateLLMModelConfigStatus(record.config_id, checked)
|
||||
Toast.success(checked ? '模型已启用' : '模型已停用')
|
||||
loadConfigs()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '更新状态失败')
|
||||
Toast.error(getApiErrorDetail(error) || '更新状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
const handleSetDefault = (record) => {
|
||||
const handleSetDefault = (record: LLMModelConfig) => {
|
||||
const isVectorModel = record.model_type === 'embedding'
|
||||
Toast.confirm({
|
||||
title: isVectorModel ? '切换默认向量模型?' : '切换默认对话模型?',
|
||||
|
|
@ -368,15 +403,15 @@ function ModelConfigs() {
|
|||
Toast.success(isVectorModel ? '默认向量模型已切换,请重建已有项目向量' : '默认对话模型已切换')
|
||||
await loadConfigs()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '切换默认模型失败')
|
||||
Toast.error(getApiErrorDetail(error) || '切换默认模型失败')
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const showTestResult = (result) => {
|
||||
const showTestResult = (result: LLMTestResult) => {
|
||||
const providerLabel = getProviderMeta(result.provider)?.label || result.provider
|
||||
const lines = [
|
||||
const lines: string[] = [
|
||||
`提供方:${providerLabel}`,
|
||||
`模型:${result.llm_model_name}`,
|
||||
`延迟:${result.latency_ms} ms`,
|
||||
|
|
@ -411,8 +446,8 @@ function ModelConfigs() {
|
|||
}
|
||||
}
|
||||
|
||||
const getColumns = (type) => {
|
||||
const baseColumns = [
|
||||
const getColumns = (type: ModelType): ColumnsType<LLMModelConfig> => {
|
||||
const baseColumns: ColumnsType<LLMModelConfig> = [
|
||||
{
|
||||
title: '模型名称',
|
||||
dataIndex: 'model_name',
|
||||
|
|
@ -433,7 +468,7 @@ function ModelConfigs() {
|
|||
dataIndex: 'provider',
|
||||
key: 'provider',
|
||||
width: 140,
|
||||
render: (provider) => (
|
||||
render: (provider: string) => (
|
||||
<Tag color="blue">{getProviderMeta(provider)?.label || provider || '-'}</Tag>
|
||||
),
|
||||
},
|
||||
|
|
@ -501,7 +536,7 @@ function ModelConfigs() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<StarOutlined />}
|
||||
icon={<StarOutlined aria-hidden />}
|
||||
onClick={() => handleSetDefault(record)}
|
||||
>
|
||||
设为默认
|
||||
|
|
@ -510,7 +545,7 @@ function ModelConfigs() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
icon={<EditOutlined aria-hidden />}
|
||||
onClick={() => openEditModal(record)}
|
||||
>
|
||||
编辑
|
||||
|
|
@ -526,7 +561,7 @@ function ModelConfigs() {
|
|||
type="link"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<DeleteOutlined aria-hidden />}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
|
|
@ -539,15 +574,16 @@ function ModelConfigs() {
|
|||
return baseColumns
|
||||
}
|
||||
|
||||
const renderListPanel = (type) => (
|
||||
const renderListPanel = (type: ModelType) => (
|
||||
<>
|
||||
<div className="admin-toolbar">
|
||||
<div className="admin-toolbar-left">
|
||||
<Search
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
placeholder="搜索模型名称、编码或模型标识"
|
||||
value={keyword}
|
||||
style={{ width: 320, maxWidth: '100%' }}
|
||||
enterButton={searchEnterButton()}
|
||||
onChange={(event) => {
|
||||
setPage(1)
|
||||
setKeyword(event.target.value)
|
||||
|
|
@ -560,6 +596,7 @@ function ModelConfigs() {
|
|||
<Select
|
||||
allowClear
|
||||
placeholder="筛选提供方"
|
||||
aria-label="筛选提供方"
|
||||
style={{ width: 180 }}
|
||||
value={providerFilter}
|
||||
options={providerCatalog.map((item) => ({
|
||||
|
|
@ -574,6 +611,7 @@ function ModelConfigs() {
|
|||
<Select
|
||||
allowClear
|
||||
placeholder="筛选状态"
|
||||
aria-label="筛选状态"
|
||||
style={{ width: 140 }}
|
||||
value={statusFilter}
|
||||
options={[
|
||||
|
|
@ -590,12 +628,12 @@ function ModelConfigs() {
|
|||
<div className="admin-toolbar-right">
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
icon={<PlusOutlined aria-hidden />}
|
||||
onClick={openCreateModal}
|
||||
>
|
||||
{MODEL_TYPE_META[type].addText}
|
||||
</Button>
|
||||
<Button icon={<ReloadOutlined />} onClick={loadConfigs}>
|
||||
<Button icon={<ReloadOutlined aria-hidden />} onClick={loadConfigs}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -645,7 +683,7 @@ function ModelConfigs() {
|
|||
<PageHeader
|
||||
title="模型配置"
|
||||
description="分类管理对话模型与向量模型的提供方、接口地址、参数模板与连通性测试。"
|
||||
icon={<CloudServerOutlined />}
|
||||
icon={<CloudServerOutlined aria-hidden />}
|
||||
/>
|
||||
|
||||
<Card className="admin-card model-config-card">
|
||||
|
|
@ -681,7 +719,7 @@ function ModelConfigs() {
|
|||
<>
|
||||
<CancelBtn />
|
||||
<Button
|
||||
icon={<ExperimentOutlined />}
|
||||
icon={<ExperimentOutlined aria-hidden />}
|
||||
loading={testing}
|
||||
onClick={handleFormTest}
|
||||
>
|
||||
|
|
@ -832,6 +870,7 @@ function ModelConfigs() {
|
|||
{!isLocalProvider && (
|
||||
<Form.Item label="API Key" name="api_key">
|
||||
<Input.Password
|
||||
iconRender={passwordVisibilityIcon}
|
||||
placeholder="支持留空后稍后补齐;测试非 Ollama 模型时建议填写"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { Tree, Button, Card, Tag, Space } from 'antd'
|
||||
import type { DataNode } from 'antd/es/tree'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { Tree, Button, Card, Tag, Space, type TreeProps } from 'antd'
|
||||
import { SafetyOutlined, SaveOutlined, CheckCircleOutlined, CloseCircleOutlined, AppstoreOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
getAllRoles,
|
||||
|
|
@ -7,19 +9,22 @@ import {
|
|||
getRolePermissions,
|
||||
updateRolePermissions,
|
||||
} from '@/api/rolePermissions'
|
||||
import type { MenuPermissionNode, Role } from '@/types/api'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import ListTable from '@/components/ListTable/ListTable'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import StatCard from '@/components/StatCard/StatCard'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
import { decorativeSwitcherIcon } from '@/utils/antdA11y'
|
||||
|
||||
function Permissions() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [roles, setRoles] = useState([])
|
||||
const [menuTree, setMenuTree] = useState([])
|
||||
const [selectedRole, setSelectedRole] = useState(null)
|
||||
const [checkedKeys, setCheckedKeys] = useState([])
|
||||
const [expandedKeys, setExpandedKeys] = useState([])
|
||||
const [roles, setRoles] = useState<Role[]>([])
|
||||
const [menuTree, setMenuTree] = useState<DataNode[]>([])
|
||||
const [selectedRole, setSelectedRole] = useState<Role | null>(null)
|
||||
const [checkedKeys, setCheckedKeys] = useState<string[]>([])
|
||||
const [expandedKeys, setExpandedKeys] = useState<string[]>([])
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -58,11 +63,11 @@ function Permissions() {
|
|||
}
|
||||
}
|
||||
|
||||
const buildTreeData = (menus) => {
|
||||
const buildTreeData = (menus: MenuPermissionNode[]): DataNode[] => {
|
||||
// Backend already returns a nested tree structure
|
||||
// We just need to transform it to Ant Design Tree format
|
||||
const transformNode = (node) => {
|
||||
const treeNode = {
|
||||
const transformNode = (node: MenuPermissionNode): DataNode => {
|
||||
const treeNode: DataNode = {
|
||||
key: node.id.toString(),
|
||||
title: node.menu_name,
|
||||
}
|
||||
|
|
@ -78,7 +83,7 @@ function Permissions() {
|
|||
return menus.map(transformNode)
|
||||
}
|
||||
|
||||
const handleRoleClick = async (role) => {
|
||||
const handleRoleClick = async (role: Role) => {
|
||||
if (role.is_system === 1) {
|
||||
Toast.warning('系统角色不允许修改权限')
|
||||
return
|
||||
|
|
@ -97,8 +102,9 @@ function Permissions() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleCheck = (checkedKeysValue) => {
|
||||
setCheckedKeys(checkedKeysValue)
|
||||
const handleCheck: NonNullable<TreeProps['onCheck']> = (checkedKeysValue) => {
|
||||
const keys = Array.isArray(checkedKeysValue) ? checkedKeysValue : checkedKeysValue.checked
|
||||
setCheckedKeys(keys.map(String))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
|
|
@ -114,13 +120,13 @@ function Permissions() {
|
|||
Toast.success('权限保存成功')
|
||||
} catch (error) {
|
||||
console.error('Save permissions error:', error)
|
||||
Toast.error(error.response?.data?.detail || '保存权限失败')
|
||||
Toast.error(getApiErrorDetail(error) || '保存权限失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const columns = [
|
||||
const columns: ColumnsType<Role> = [
|
||||
{
|
||||
title: '角色名称',
|
||||
dataIndex: 'role_name',
|
||||
|
|
@ -135,13 +141,13 @@ function Permissions() {
|
|||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
render: (status) =>
|
||||
render: (status: Role['status']) =>
|
||||
status === 1 ? (
|
||||
<Tag icon={<CheckCircleOutlined />} color="success">
|
||||
<Tag icon={<CheckCircleOutlined aria-hidden />} color="success">
|
||||
启用
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag icon={<CloseCircleOutlined />} color="error">
|
||||
<Tag icon={<CloseCircleOutlined aria-hidden />} color="error">
|
||||
禁用
|
||||
</Tag>
|
||||
),
|
||||
|
|
@ -150,13 +156,13 @@ function Permissions() {
|
|||
title: '系统角色',
|
||||
dataIndex: 'is_system',
|
||||
key: 'is_system',
|
||||
render: (isSystem) => (isSystem === 1 ? <Tag color="orange">是</Tag> : <Tag>否</Tag>),
|
||||
render: (isSystem: Role['is_system']) => (isSystem === 1 ? <Tag color="orange">是</Tag> : <Tag>否</Tag>),
|
||||
},
|
||||
]
|
||||
|
||||
const editableRoles = roles.filter((role) => role.is_system !== 1).length
|
||||
const flattenTreeCount = (nodes) => nodes.reduce((count, node) => {
|
||||
const childrenCount = node.children ? flattenTreeCount(node.children) : 0
|
||||
const flattenTreeCount = (nodes: DataNode[]): number => nodes.reduce((count, node) => {
|
||||
const childrenCount = node.children ? flattenTreeCount(node.children as DataNode[]) : 0
|
||||
return count + 1 + childrenCount
|
||||
}, 0)
|
||||
const menuCount = flattenTreeCount(menuTree)
|
||||
|
|
@ -166,13 +172,13 @@ function Permissions() {
|
|||
<PageHeader
|
||||
title="权限管理"
|
||||
description="为角色配置菜单和功能权限,系统角色默认只读。"
|
||||
icon={<SafetyOutlined />}
|
||||
icon={<SafetyOutlined aria-hidden />}
|
||||
/>
|
||||
|
||||
<div className="admin-stats">
|
||||
<StatCard title="角色总数" value={roles.length} icon={<SafetyOutlined />} color="blue" />
|
||||
<StatCard title="可编辑角色" value={editableRoles} icon={<CheckCircleOutlined />} color="green" />
|
||||
<StatCard title="权限节点数" value={menuCount} icon={<AppstoreOutlined />} color="orange" />
|
||||
<StatCard title="角色总数" value={roles.length} icon={<SafetyOutlined aria-hidden />} color="blue" />
|
||||
<StatCard title="可编辑角色" value={editableRoles} icon={<CheckCircleOutlined aria-hidden />} color="green" />
|
||||
<StatCard title="权限节点数" value={menuCount} icon={<AppstoreOutlined aria-hidden />} color="orange" />
|
||||
</div>
|
||||
|
||||
<div className="admin-grid-2">
|
||||
|
|
@ -182,7 +188,7 @@ function Permissions() {
|
|||
extra={(
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
icon={<SaveOutlined aria-hidden />}
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
disabled={!selectedRole}
|
||||
|
|
@ -207,8 +213,9 @@ function Permissions() {
|
|||
|
||||
<Tree
|
||||
checkable
|
||||
switcherIcon={decorativeSwitcherIcon}
|
||||
expandedKeys={expandedKeys}
|
||||
onExpand={setExpandedKeys}
|
||||
onExpand={(keys) => setExpandedKeys(keys.map(String))}
|
||||
checkedKeys={checkedKeys}
|
||||
onCheck={handleCheck}
|
||||
treeData={menuTree}
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
Popconfirm,
|
||||
Card,
|
||||
} from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import {
|
||||
PlusOutlined,
|
||||
EditOutlined,
|
||||
|
|
@ -27,35 +28,39 @@ import {
|
|||
deleteRole,
|
||||
getRoleUsers,
|
||||
} from '@/api/roles'
|
||||
import type { Role, User } from '@/types/api'
|
||||
import type { RolePayload } from '@/api/roles'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import ListTable from '@/components/ListTable/ListTable'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import StatCard from '@/components/StatCard/StatCard'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
import { clearInputIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Search } = Input
|
||||
|
||||
function Roles() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [roles, setRoles] = useState([])
|
||||
const [roles, setRoles] = useState<Role[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState(null)
|
||||
const [statusFilter, setStatusFilter] = useState<number | null>(null)
|
||||
|
||||
const [createModalVisible, setCreateModalVisible] = useState(false)
|
||||
const [editModalVisible, setEditModalVisible] = useState(false)
|
||||
const [usersModalVisible, setUsersModalVisible] = useState(false)
|
||||
const [currentRole, setCurrentRole] = useState(null)
|
||||
const [roleUsers, setRoleUsers] = useState([])
|
||||
const [currentRole, setCurrentRole] = useState<Role | null>(null)
|
||||
const [roleUsers, setRoleUsers] = useState<User[]>([])
|
||||
const [usersLoading, setUsersLoading] = useState(false)
|
||||
const [usersPage, setUsersPage] = useState(1)
|
||||
const [usersPageSize, setUsersPageSize] = useState(10)
|
||||
const [usersTotal, setUsersTotal] = useState(0)
|
||||
|
||||
const [createForm] = Form.useForm()
|
||||
const [editForm] = Form.useForm()
|
||||
const [createForm] = Form.useForm<RolePayload>()
|
||||
const [editForm] = Form.useForm<RolePayload>()
|
||||
|
||||
useEffect(() => {
|
||||
loadRoles()
|
||||
|
|
@ -64,7 +69,7 @@ function Roles() {
|
|||
const loadRoles = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const params = {
|
||||
const params: Parameters<typeof getRoleList>[0] = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}
|
||||
|
|
@ -84,7 +89,7 @@ function Roles() {
|
|||
}
|
||||
}
|
||||
|
||||
const loadRoleUsers = async (roleId) => {
|
||||
const loadRoleUsers = async (roleId: number) => {
|
||||
try {
|
||||
setUsersLoading(true)
|
||||
const res = await getRoleUsers(roleId, {
|
||||
|
|
@ -104,7 +109,7 @@ function Roles() {
|
|||
}
|
||||
|
||||
// 创建角色
|
||||
const handleCreate = async (values) => {
|
||||
const handleCreate = async (values: RolePayload) => {
|
||||
try {
|
||||
await createRole(values)
|
||||
Toast.success('角色创建成功')
|
||||
|
|
@ -112,36 +117,37 @@ function Roles() {
|
|||
createForm.resetFields()
|
||||
loadRoles()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '创建角色失败')
|
||||
Toast.error(getApiErrorDetail(error) || '创建角色失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 编辑角色
|
||||
const handleEdit = async (values) => {
|
||||
const handleEdit = async (values: RolePayload) => {
|
||||
try {
|
||||
if (!currentRole) return
|
||||
await updateRole(currentRole.id, values)
|
||||
Toast.success('角色信息更新成功')
|
||||
setEditModalVisible(false)
|
||||
editForm.resetFields()
|
||||
loadRoles()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '更新角色失败')
|
||||
Toast.error(getApiErrorDetail(error) || '更新角色失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 删除角色
|
||||
const handleDelete = async (roleId) => {
|
||||
const handleDelete = async (roleId: number) => {
|
||||
try {
|
||||
await deleteRole(roleId)
|
||||
Toast.success('角色删除成功')
|
||||
loadRoles()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除角色失败')
|
||||
Toast.error(getApiErrorDetail(error) || '删除角色失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 查看角色下的用户
|
||||
const handleViewUsers = (role) => {
|
||||
const handleViewUsers = (role: Role) => {
|
||||
setCurrentRole(role)
|
||||
setUsersPage(1)
|
||||
setUsersModalVisible(true)
|
||||
|
|
@ -153,7 +159,7 @@ function Roles() {
|
|||
}
|
||||
}, [usersModalVisible, currentRole, usersPage, usersPageSize])
|
||||
|
||||
const columns = [
|
||||
const columns: ColumnsType<Role> = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
|
|
@ -180,19 +186,19 @@ function Roles() {
|
|||
title: '用户数',
|
||||
dataIndex: 'user_count',
|
||||
key: 'user_count',
|
||||
render: (count) => <Tag color="blue">{count}</Tag>,
|
||||
render: (count: number) => <Tag color="blue">{count}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
render: (status) =>
|
||||
render: (status: Role['status']) =>
|
||||
status === 1 ? (
|
||||
<Tag icon={<CheckCircleOutlined />} color="success">
|
||||
<Tag icon={<CheckCircleOutlined aria-hidden />} color="success">
|
||||
启用
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag icon={<CloseCircleOutlined />} color="error">
|
||||
<Tag icon={<CloseCircleOutlined aria-hidden />} color="error">
|
||||
禁用
|
||||
</Tag>
|
||||
),
|
||||
|
|
@ -201,14 +207,14 @@ function Roles() {
|
|||
title: '系统角色',
|
||||
dataIndex: 'is_system',
|
||||
key: 'is_system',
|
||||
render: (isSystem) =>
|
||||
render: (isSystem: Role['is_system']) =>
|
||||
isSystem === 1 ? <Tag color="orange">是</Tag> : <Tag>否</Tag>,
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
render: (text: string | null) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
|
|
@ -220,7 +226,7 @@ function Roles() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<TeamOutlined />}
|
||||
icon={<TeamOutlined aria-hidden />}
|
||||
onClick={() => handleViewUsers(record)}
|
||||
>
|
||||
用户列表
|
||||
|
|
@ -228,7 +234,7 @@ function Roles() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
icon={<EditOutlined aria-hidden />}
|
||||
disabled={record.is_system === 1}
|
||||
onClick={() => {
|
||||
setCurrentRole(record)
|
||||
|
|
@ -255,7 +261,7 @@ function Roles() {
|
|||
type="link"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<DeleteOutlined aria-hidden />}
|
||||
disabled={record.is_system === 1}
|
||||
>
|
||||
删除
|
||||
|
|
@ -266,7 +272,7 @@ function Roles() {
|
|||
},
|
||||
]
|
||||
|
||||
const userColumns = [
|
||||
const userColumns: ColumnsType<User> = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
|
|
@ -297,13 +303,13 @@ function Roles() {
|
|||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
render: (status) =>
|
||||
render: (status: Role['status']) =>
|
||||
status === 1 ? (
|
||||
<Tag icon={<CheckCircleOutlined />} color="success">
|
||||
<Tag icon={<CheckCircleOutlined aria-hidden />} color="success">
|
||||
启用
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag icon={<CloseCircleOutlined />} color="error">
|
||||
<Tag icon={<CloseCircleOutlined aria-hidden />} color="error">
|
||||
停用
|
||||
</Tag>
|
||||
),
|
||||
|
|
@ -312,7 +318,7 @@ function Roles() {
|
|||
title: '创建时间',
|
||||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
render: (text: string | null) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
|
||||
},
|
||||
]
|
||||
|
||||
|
|
@ -324,28 +330,29 @@ function Roles() {
|
|||
<PageHeader
|
||||
title="角色管理"
|
||||
description="维护系统角色、角色编码与用户归属关系。"
|
||||
icon={<TeamOutlined />}
|
||||
icon={<TeamOutlined aria-hidden />}
|
||||
extra={(
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
|
||||
<Button type="primary" icon={<PlusOutlined aria-hidden />} onClick={() => setCreateModalVisible(true)}>
|
||||
新增角色
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="admin-stats">
|
||||
<StatCard title="角色总数" value={total} icon={<SafetyOutlined />} color="blue" />
|
||||
<StatCard title="当前页启用" value={enabledRoles} icon={<CheckCircleOutlined />} color="green" />
|
||||
<StatCard title="系统角色数" value={systemRoles} icon={<TeamOutlined />} color="orange" />
|
||||
<StatCard title="角色总数" value={total} icon={<SafetyOutlined aria-hidden />} color="blue" />
|
||||
<StatCard title="当前页启用" value={enabledRoles} icon={<CheckCircleOutlined aria-hidden />} color="green" />
|
||||
<StatCard title="系统角色数" value={systemRoles} icon={<TeamOutlined aria-hidden />} color="orange" />
|
||||
</div>
|
||||
|
||||
<Card className="admin-card">
|
||||
<div className="admin-toolbar">
|
||||
<div className="admin-toolbar-left">
|
||||
<Search
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
placeholder="搜索角色名称、编码"
|
||||
value={keyword}
|
||||
style={{ width: 320 }}
|
||||
enterButton={searchEnterButton()}
|
||||
onChange={(event) => {
|
||||
setPage(1)
|
||||
setKeyword(event.target.value)
|
||||
|
|
@ -358,6 +365,7 @@ function Roles() {
|
|||
<Select
|
||||
allowClear
|
||||
placeholder="筛选状态"
|
||||
aria-label="筛选状态"
|
||||
style={{ width: 140 }}
|
||||
value={statusFilter}
|
||||
onChange={(value) => {
|
||||
|
|
@ -372,7 +380,7 @@ function Roles() {
|
|||
</div>
|
||||
|
||||
<div className="admin-toolbar-right">
|
||||
<Button icon={<ReloadOutlined />} onClick={loadRoles}>
|
||||
<Button icon={<ReloadOutlined aria-hidden />} onClick={loadRoles}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
UserOutlined,
|
||||
ReloadOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import {
|
||||
getUserList,
|
||||
createUser,
|
||||
|
|
@ -29,34 +30,40 @@ import {
|
|||
updateUserStatus,
|
||||
updateUserRoles,
|
||||
resetUserPassword,
|
||||
type UserCreatePayload,
|
||||
type UserQuery,
|
||||
type UserUpdatePayload,
|
||||
} from '@/api/users'
|
||||
import type { Role, User } from '@/types/api'
|
||||
import { getApiErrorDetail } from '@/utils/apiError'
|
||||
import { getAllRoles } from '@/api/rolePermissions'
|
||||
import ListTable from '@/components/ListTable/ListTable'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import StatCard from '@/components/StatCard/StatCard'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
import { clearInputIcon, searchEnterButton } from '@/utils/antdA11y'
|
||||
|
||||
const { Search } = Input
|
||||
|
||||
function Users() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [users, setUsers] = useState([])
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState(null)
|
||||
const [statusFilter, setStatusFilter] = useState<number | null>(null)
|
||||
|
||||
const [roles, setRoles] = useState([])
|
||||
const [roles, setRoles] = useState<Role[]>([])
|
||||
const [createModalVisible, setCreateModalVisible] = useState(false)
|
||||
const [editModalVisible, setEditModalVisible] = useState(false)
|
||||
const [rolesModalVisible, setRolesModalVisible] = useState(false)
|
||||
const [currentUser, setCurrentUser] = useState(null)
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null)
|
||||
|
||||
const [createForm] = Form.useForm()
|
||||
const [editForm] = Form.useForm()
|
||||
const [rolesForm] = Form.useForm()
|
||||
const [createForm] = Form.useForm<UserCreatePayload>()
|
||||
const [editForm] = Form.useForm<UserUpdatePayload>()
|
||||
const [rolesForm] = Form.useForm<{ role_ids?: number[] }>()
|
||||
|
||||
useEffect(() => {
|
||||
loadUsers()
|
||||
|
|
@ -69,7 +76,7 @@ function Users() {
|
|||
const loadUsers = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const params = {
|
||||
const params: UserQuery = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}
|
||||
|
|
@ -101,7 +108,7 @@ function Users() {
|
|||
}
|
||||
|
||||
// 创建用户
|
||||
const handleCreate = async (values) => {
|
||||
const handleCreate = async (values: UserCreatePayload) => {
|
||||
try {
|
||||
const res = await createUser(values)
|
||||
if (res.code === 200) {
|
||||
|
|
@ -111,12 +118,13 @@ function Users() {
|
|||
loadUsers()
|
||||
}
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '创建用户失败')
|
||||
Toast.error(getApiErrorDetail(error) || '创建用户失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 编辑用户
|
||||
const handleEdit = async (values) => {
|
||||
const handleEdit = async (values: UserUpdatePayload) => {
|
||||
if (!currentUser) return
|
||||
try {
|
||||
await updateUser(currentUser.id, values)
|
||||
Toast.success('用户信息更新成功')
|
||||
|
|
@ -124,35 +132,36 @@ function Users() {
|
|||
editForm.resetFields()
|
||||
loadUsers()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '更新用户失败')
|
||||
Toast.error(getApiErrorDetail(error) || '更新用户失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 删除用户
|
||||
const handleDelete = async (userId) => {
|
||||
const handleDelete = async (userId: number) => {
|
||||
try {
|
||||
await deleteUser(userId)
|
||||
Toast.success('用户删除成功')
|
||||
loadUsers()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '删除用户失败')
|
||||
Toast.error(getApiErrorDetail(error) || '删除用户失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 切换用户状态
|
||||
const handleStatusChange = async (userId, checked) => {
|
||||
const handleStatusChange = async (userId: number, checked: boolean) => {
|
||||
try {
|
||||
const status = checked ? 1 : 0
|
||||
await updateUserStatus(userId, status)
|
||||
Toast.success(checked ? '用户已启用' : '用户已停用')
|
||||
loadUsers()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '操作失败')
|
||||
Toast.error(getApiErrorDetail(error) || '操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 分配角色
|
||||
const handleAssignRoles = async (values) => {
|
||||
const handleAssignRoles = async (values: { role_ids?: number[] }) => {
|
||||
if (!currentUser) return
|
||||
try {
|
||||
await updateUserRoles(currentUser.id, values.role_ids || [])
|
||||
Toast.success('角色分配成功')
|
||||
|
|
@ -160,12 +169,12 @@ function Users() {
|
|||
rolesForm.resetFields()
|
||||
loadUsers()
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '角色分配失败')
|
||||
Toast.error(getApiErrorDetail(error) || '角色分配失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 重置密码
|
||||
const handleResetPassword = async (userId) => {
|
||||
const handleResetPassword = async (userId: number) => {
|
||||
try {
|
||||
const res = await resetUserPassword(userId)
|
||||
if (res.code === 200) {
|
||||
|
|
@ -175,11 +184,11 @@ function Users() {
|
|||
})
|
||||
}
|
||||
} catch (error) {
|
||||
Toast.error(error.response?.data?.detail || '密码重置失败')
|
||||
Toast.error(getApiErrorDetail(error) || '密码重置失败')
|
||||
}
|
||||
}
|
||||
|
||||
const columns = [
|
||||
const columns: ColumnsType<User> = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
|
|
@ -210,7 +219,7 @@ function Users() {
|
|||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
key: 'roles',
|
||||
render: (roles) => (
|
||||
render: (roles: User['roles']) => (
|
||||
<>
|
||||
{roles?.map((role) => (
|
||||
<Tag key={role.id} color="blue">
|
||||
|
|
@ -250,7 +259,7 @@ function Users() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<TeamOutlined />}
|
||||
icon={<TeamOutlined aria-hidden />}
|
||||
onClick={() => {
|
||||
setCurrentUser(record)
|
||||
rolesForm.setFieldsValue({
|
||||
|
|
@ -264,7 +273,7 @@ function Users() {
|
|||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
icon={<EditOutlined aria-hidden />}
|
||||
onClick={() => {
|
||||
setCurrentUser(record)
|
||||
editForm.setFieldsValue({
|
||||
|
|
@ -283,7 +292,7 @@ function Users() {
|
|||
okText="确定"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" size="small" icon={<KeyOutlined />}>
|
||||
<Button type="link" size="small" icon={<KeyOutlined aria-hidden />}>
|
||||
重置密码
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
|
|
@ -294,7 +303,7 @@ function Users() {
|
|||
okText="确定"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined aria-hidden />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
|
|
@ -310,28 +319,29 @@ function Users() {
|
|||
<PageHeader
|
||||
title="用户管理"
|
||||
description="统一管理系统用户、账号状态、角色分配与密码重置。"
|
||||
icon={<UserOutlined />}
|
||||
icon={<UserOutlined aria-hidden />}
|
||||
extra={(
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
|
||||
<Button type="primary" icon={<PlusOutlined aria-hidden />} onClick={() => setCreateModalVisible(true)}>
|
||||
新增用户
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="admin-stats">
|
||||
<StatCard title="用户总数" value={total} icon={<UserOutlined />} color="blue" />
|
||||
<StatCard title="当前页启用" value={activeUsers} icon={<CheckCircleOutlined />} color="green" />
|
||||
<StatCard title="可分配角色数" value={roles.length} icon={<TeamOutlined />} color="orange" />
|
||||
<StatCard title="用户总数" value={total} icon={<UserOutlined aria-hidden />} color="blue" />
|
||||
<StatCard title="当前页启用" value={activeUsers} icon={<CheckCircleOutlined aria-hidden />} color="green" />
|
||||
<StatCard title="可分配角色数" value={roles.length} icon={<TeamOutlined aria-hidden />} color="orange" />
|
||||
</div>
|
||||
|
||||
<Card className="admin-card">
|
||||
<div className="admin-toolbar">
|
||||
<div className="admin-toolbar-left">
|
||||
<Search
|
||||
allowClear
|
||||
allowClear={clearInputIcon()}
|
||||
placeholder="搜索用户名、昵称、邮箱"
|
||||
value={keyword}
|
||||
style={{ width: 320 }}
|
||||
enterButton={searchEnterButton()}
|
||||
onChange={(event) => {
|
||||
setPage(1)
|
||||
setKeyword(event.target.value)
|
||||
|
|
@ -344,6 +354,7 @@ function Users() {
|
|||
<Select
|
||||
allowClear
|
||||
placeholder="筛选状态"
|
||||
aria-label="筛选状态"
|
||||
style={{ width: 140 }}
|
||||
value={statusFilter}
|
||||
onChange={(value) => {
|
||||
|
|
@ -358,7 +369,7 @@ function Users() {
|
|||
</div>
|
||||
|
||||
<div className="admin-toolbar-right">
|
||||
<Button icon={<ReloadOutlined />} onClick={loadUsers}>
|
||||
<Button icon={<ReloadOutlined aria-hidden />} onClick={loadUsers}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -1,11 +1,15 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import type { Dayjs } from 'dayjs'
|
||||
import { Table, Card, Select, DatePicker, Button, Tag, Input } from 'antd'
|
||||
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { ReloadOutlined, SearchOutlined, FileSearchOutlined, CheckCircleOutlined, FolderOutlined, FileTextOutlined } from '@ant-design/icons'
|
||||
import { getOperationLogs, getLogStats } from '@/api/logs'
|
||||
import { ReloadOutlined, SearchOutlined, FileSearchOutlined, CheckCircleOutlined, FolderOutlined, FileTextOutlined, CalendarOutlined } from '@ant-design/icons'
|
||||
import { getOperationLogs, getLogStats, type LogQuery } from '@/api/logs'
|
||||
import type { LogStats, OperationLog, User } from '@/types/api'
|
||||
import { getUserList } from '@/api/users'
|
||||
import PageHeader from '@/components/PageHeader/PageHeader'
|
||||
import StatCard from '@/components/StatCard/StatCard'
|
||||
import { namePageItem, rangeSeparatorWithLabel } from '@/utils/antdA11y'
|
||||
import dayjs from 'dayjs'
|
||||
import './SystemLogs.css'
|
||||
import '@/pages/System/AdminPages.css'
|
||||
|
|
@ -14,7 +18,7 @@ const { RangePicker } = DatePicker
|
|||
const { Option } = Select
|
||||
|
||||
// 操作类型映射
|
||||
const operationTypeMap = {
|
||||
const operationTypeMap: Record<string, string> = {
|
||||
create_project: '创建项目',
|
||||
update_project: '更新项目',
|
||||
delete_project: '删除项目',
|
||||
|
|
@ -36,7 +40,7 @@ const operationTypeMap = {
|
|||
}
|
||||
|
||||
// 资源类型映射
|
||||
const resourceTypeMap = {
|
||||
const resourceTypeMap: Record<string, string> = {
|
||||
project: '项目',
|
||||
file: '文件',
|
||||
member: '成员',
|
||||
|
|
@ -45,7 +49,7 @@ const resourceTypeMap = {
|
|||
}
|
||||
|
||||
// 操作类型颜色
|
||||
const operationTypeColors = {
|
||||
const operationTypeColors: Record<string, string> = {
|
||||
create_project: 'green',
|
||||
update_project: 'blue',
|
||||
delete_project: 'red',
|
||||
|
|
@ -66,25 +70,36 @@ const operationTypeColors = {
|
|||
user_register: 'green',
|
||||
}
|
||||
|
||||
interface LogFilters {
|
||||
operation_type?: string
|
||||
resource_type?: string
|
||||
user_id?: number
|
||||
project_id?: string
|
||||
/** RangePicker 清空时会给出 [null, null] 或 null */
|
||||
dateRange: [Dayjs | null, Dayjs | null] | null
|
||||
}
|
||||
|
||||
const EMPTY_FILTERS: LogFilters = {
|
||||
operation_type: undefined,
|
||||
resource_type: undefined,
|
||||
user_id: undefined,
|
||||
project_id: undefined,
|
||||
dateRange: null,
|
||||
}
|
||||
|
||||
function SystemLogs() {
|
||||
const [logs, setLogs] = useState([])
|
||||
const [logs, setLogs] = useState<OperationLog[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [pagination, setPagination] = useState({
|
||||
const [pagination, setPagination] = useState<TablePaginationConfig>({
|
||||
current: 1,
|
||||
pageSize: 20,
|
||||
total: 0,
|
||||
})
|
||||
const [stats, setStats] = useState(null)
|
||||
const [users, setUsers] = useState([])
|
||||
const [stats, setStats] = useState<LogStats | null>(null)
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
|
||||
// 筛选条件
|
||||
const [filters, setFilters] = useState({
|
||||
operation_type: undefined,
|
||||
resource_type: undefined,
|
||||
user_id: undefined,
|
||||
project_id: undefined,
|
||||
dateRange: null,
|
||||
})
|
||||
const [filters, setFilters] = useState<LogFilters>(EMPTY_FILTERS)
|
||||
|
||||
useEffect(() => {
|
||||
fetchLogs()
|
||||
|
|
@ -92,10 +107,10 @@ function SystemLogs() {
|
|||
fetchUsers()
|
||||
}, [])
|
||||
|
||||
const fetchLogs = async (page = 1, pageSize = 20, nextFilters = filters) => {
|
||||
const fetchLogs = async (page = 1, pageSize = 20, nextFilters: LogFilters = filters) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const params = {
|
||||
const params: LogQuery = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}
|
||||
|
|
@ -115,9 +130,10 @@ function SystemLogs() {
|
|||
}
|
||||
|
||||
// 处理日期范围
|
||||
if (nextFilters.dateRange && nextFilters.dateRange.length === 2) {
|
||||
params.start_date = nextFilters.dateRange[0].format('YYYY-MM-DD')
|
||||
params.end_date = nextFilters.dateRange[1].format('YYYY-MM-DD')
|
||||
const [rangeStart, rangeEnd] = nextFilters.dateRange ?? []
|
||||
if (rangeStart && rangeEnd) {
|
||||
params.start_date = rangeStart.format('YYYY-MM-DD')
|
||||
params.end_date = rangeEnd.format('YYYY-MM-DD')
|
||||
}
|
||||
|
||||
const res = await getOperationLogs(params)
|
||||
|
|
@ -147,16 +163,14 @@ function SystemLogs() {
|
|||
const fetchUsers = async () => {
|
||||
try {
|
||||
const res = await getUserList({ page: 1, page_size: 100, status: 1 })
|
||||
// 后端返回格式: { code: 200: "success", data: [...], total, page, page_size }
|
||||
const usersData = Array.isArray(res.data) ? res.data : []
|
||||
setUsers(usersData)
|
||||
setUsers(res.data ?? [])
|
||||
} catch (error) {
|
||||
console.error('Fetch users error:', error)
|
||||
Toast.error('获取用户列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
const handleTableChange = (newPagination) => {
|
||||
const handleTableChange = (newPagination: TablePaginationConfig) => {
|
||||
fetchLogs(newPagination.current, newPagination.pageSize)
|
||||
}
|
||||
|
||||
|
|
@ -171,18 +185,11 @@ function SystemLogs() {
|
|||
}
|
||||
|
||||
const handleReset = () => {
|
||||
const resetFilters = {
|
||||
operation_type: undefined,
|
||||
resource_type: undefined,
|
||||
user_id: undefined,
|
||||
project_id: undefined,
|
||||
dateRange: null,
|
||||
}
|
||||
setFilters(resetFilters)
|
||||
fetchLogs(1, pagination.pageSize, resetFilters)
|
||||
setFilters(EMPTY_FILTERS)
|
||||
fetchLogs(1, pagination.pageSize, EMPTY_FILTERS)
|
||||
}
|
||||
|
||||
const columns = [
|
||||
const columns: ColumnsType<OperationLog> = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
|
|
@ -200,7 +207,7 @@ function SystemLogs() {
|
|||
dataIndex: 'operation_type',
|
||||
key: 'operation_type',
|
||||
width: 140,
|
||||
render: (type) => (
|
||||
render: (type: string) => (
|
||||
<Tag color={operationTypeColors[type] || 'default'}>
|
||||
{operationTypeMap[type] || type}
|
||||
</Tag>
|
||||
|
|
@ -211,7 +218,7 @@ function SystemLogs() {
|
|||
dataIndex: 'resource_type',
|
||||
key: 'resource_type',
|
||||
width: 100,
|
||||
render: (type) => resourceTypeMap[type] || type,
|
||||
render: (type: string) => resourceTypeMap[type] || type,
|
||||
},
|
||||
{
|
||||
title: '资源ID',
|
||||
|
|
@ -224,7 +231,7 @@ function SystemLogs() {
|
|||
dataIndex: 'detail',
|
||||
key: 'detail',
|
||||
ellipsis: true,
|
||||
render: (detail) => {
|
||||
render: (detail: string | null) => {
|
||||
if (!detail) return '-'
|
||||
try {
|
||||
const parsed = JSON.parse(detail)
|
||||
|
|
@ -253,7 +260,7 @@ function SystemLogs() {
|
|||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
width: 80,
|
||||
render: (status) => (
|
||||
render: (status: OperationLog['status']) => (
|
||||
<Tag color={status === 1 ? 'success' : 'error'}>
|
||||
{status === 1 ? '成功' : '失败'}
|
||||
</Tag>
|
||||
|
|
@ -264,7 +271,7 @@ function SystemLogs() {
|
|||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
width: 180,
|
||||
render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
|
||||
render: (time: string | null) => (time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'),
|
||||
},
|
||||
]
|
||||
|
||||
|
|
@ -285,15 +292,15 @@ function SystemLogs() {
|
|||
<PageHeader
|
||||
title="系统日志"
|
||||
description="按用户、资源、时间维度筛选系统操作日志与行为统计。"
|
||||
icon={<FileSearchOutlined />}
|
||||
icon={<FileSearchOutlined aria-hidden />}
|
||||
/>
|
||||
|
||||
{stats && (
|
||||
<div className="admin-stats admin-stats-4">
|
||||
<StatCard title="总日志数" value={stats.total_count} icon={<FileSearchOutlined />} color="blue" />
|
||||
<StatCard title="今日操作" value={stats.today_count} icon={<CheckCircleOutlined />} color="green" />
|
||||
<StatCard title="项目操作" value={projectOperationCount} icon={<FolderOutlined />} color="orange" />
|
||||
<StatCard title="文件操作" value={fileOperationCount} icon={<FileTextOutlined />} color="red" />
|
||||
<StatCard title="总日志数" value={stats.total_count} icon={<FileSearchOutlined aria-hidden />} color="blue" />
|
||||
<StatCard title="今日操作" value={stats.today_count} icon={<CheckCircleOutlined aria-hidden />} color="green" />
|
||||
<StatCard title="项目操作" value={projectOperationCount} icon={<FolderOutlined aria-hidden />} color="orange" />
|
||||
<StatCard title="文件操作" value={fileOperationCount} icon={<FileTextOutlined aria-hidden />} color="red" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -302,6 +309,7 @@ function SystemLogs() {
|
|||
<div className="admin-toolbar-left">
|
||||
<Select
|
||||
placeholder="操作类型"
|
||||
aria-label="操作类型"
|
||||
style={{ width: 160 }}
|
||||
allowClear
|
||||
value={filters.operation_type}
|
||||
|
|
@ -314,6 +322,7 @@ function SystemLogs() {
|
|||
|
||||
<Select
|
||||
placeholder="资源类型"
|
||||
aria-label="资源类型"
|
||||
style={{ width: 120 }}
|
||||
allowClear
|
||||
value={filters.resource_type}
|
||||
|
|
@ -326,11 +335,12 @@ function SystemLogs() {
|
|||
|
||||
<Select
|
||||
placeholder="操作用户"
|
||||
aria-label="操作用户"
|
||||
style={{ width: 160 }}
|
||||
allowClear
|
||||
showSearch
|
||||
filterOption={(input, option) =>
|
||||
(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
value={filters.user_id}
|
||||
onChange={(value) => setFilters({ ...filters, user_id: value })}
|
||||
|
|
@ -351,13 +361,15 @@ function SystemLogs() {
|
|||
|
||||
<RangePicker
|
||||
value={filters.dateRange}
|
||||
separator={rangeSeparatorWithLabel()}
|
||||
suffixIcon={<CalendarOutlined aria-hidden />}
|
||||
onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
|
||||
/>
|
||||
|
||||
<Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
|
||||
<Button type="primary" icon={<SearchOutlined aria-hidden />} onClick={handleSearch}>
|
||||
查询
|
||||
</Button>
|
||||
<Button icon={<ReloadOutlined />} onClick={handleReset}>
|
||||
<Button icon={<ReloadOutlined aria-hidden />} onClick={handleReset}>
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -368,7 +380,7 @@ function SystemLogs() {
|
|||
dataSource={logs}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={pagination}
|
||||
pagination={{ ...pagination, itemRender: namePageItem }}
|
||||
onChange={handleTableChange}
|
||||
scroll={{ x: 1400 }}
|
||||
/>
|
||||
|
|
@ -1,7 +1,15 @@
|
|||
import { create } from 'zustand'
|
||||
import { getUnreadCount } from '@/api/notification'
|
||||
|
||||
const useNotificationStore = create((set, get) => ({
|
||||
interface NotificationState {
|
||||
unreadCount: number
|
||||
setUnreadCount: (count: number) => void
|
||||
decrementUnreadCount: () => void
|
||||
fetchUnreadCount: () => Promise<void>
|
||||
resetUnreadCount: () => void
|
||||
}
|
||||
|
||||
const useNotificationStore = create<NotificationState>()((set) => ({
|
||||
unreadCount: 0,
|
||||
setUnreadCount: (count) => set({ unreadCount: count }),
|
||||
decrementUnreadCount: () => set((state) => ({ unreadCount: Math.max(0, state.unreadCount - 1) })),
|
||||
|
|
@ -1,7 +1,12 @@
|
|||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
|
||||
const useThemeStore = create(
|
||||
interface ThemeState {
|
||||
isDarkMode: boolean
|
||||
toggleTheme: () => void
|
||||
}
|
||||
|
||||
const useThemeStore = create<ThemeState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
isDarkMode: false,
|
||||
|
|
@ -4,10 +4,20 @@
|
|||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { clearAuthStorage } from '@/utils/authStorage'
|
||||
import type { User } from '@/types/api'
|
||||
|
||||
const useUserStore = create(
|
||||
interface UserState {
|
||||
user: User | null
|
||||
token: string | null
|
||||
setUser: (user: User | null) => void
|
||||
setToken: (token: string | null) => void
|
||||
logout: () => void
|
||||
isAuthenticated: () => boolean
|
||||
}
|
||||
|
||||
const useUserStore = create<UserState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
(set, get) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
|
||||
|
|
@ -20,7 +30,7 @@ const useUserStore = create(
|
|||
},
|
||||
|
||||
isAuthenticated: () => {
|
||||
const state = useUserStore.getState()
|
||||
const state = get()
|
||||
return !!state.token && !!state.user
|
||||
},
|
||||
}),
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
* 全站唯一的视觉变量来源:页面/组件样式只允许引用这里的变量,
|
||||
* 不要再写死颜色、圆角、阴影与层级,以保证明暗主题与后续改版的一致性。
|
||||
*
|
||||
* 与 antd 的对应关系见 src/theme/antdTheme.js(AntD 的 token 必须用 JS 传入 ConfigProvider)。
|
||||
* 与 antd 的对应关系见 src/theme/antdTheme.ts(AntD 的 token 必须用 JS 传入 ConfigProvider)。
|
||||
*/
|
||||
|
||||
:root {
|
||||
|
|
@ -24,8 +24,13 @@
|
|||
--color-danger-hover: #ff7875;
|
||||
--color-danger-active: #d4380d;
|
||||
--color-danger-bg: #fff2f0;
|
||||
--color-danger-strong: #f5222d;
|
||||
--color-pdf: var(--color-danger-strong);
|
||||
--color-info: #1677ff;
|
||||
|
||||
--color-stat-purple: #722ed1;
|
||||
--color-stat-gray: #8c8c8c;
|
||||
|
||||
/* ---------- 文本 ---------- */
|
||||
--text-color: rgba(0, 0, 0, 0.88);
|
||||
--text-color-secondary: rgba(0, 0, 0, 0.65);
|
||||
|
|
@ -134,8 +139,13 @@ body.dark {
|
|||
--color-danger-hover: #e8684a;
|
||||
--color-danger-active: #a62c2c;
|
||||
--color-danger-bg: rgba(220, 68, 70, 0.16);
|
||||
--color-danger-strong: #f5222d;
|
||||
--color-pdf: var(--color-danger-strong);
|
||||
--color-info: #177ddc;
|
||||
|
||||
--color-stat-purple: #722ed1;
|
||||
--color-stat-gray: #8c8c8c;
|
||||
|
||||
/* ---------- 文本 ---------- */
|
||||
--text-color: rgba(255, 255, 255, 0.85);
|
||||
--text-color-secondary: rgba(255, 255, 255, 0.65);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { ThemeConfig } from 'antd'
|
||||
|
||||
/**
|
||||
* Ant Design 主题配置
|
||||
*
|
||||
|
|
@ -40,7 +42,7 @@ const darkToken = {
|
|||
colorBorderSecondary: '#303030',
|
||||
}
|
||||
|
||||
const getComponents = (isDarkMode) => ({
|
||||
const getComponents = (isDarkMode: boolean): ThemeConfig['components'] => ({
|
||||
Button: {
|
||||
controlHeight: 34,
|
||||
controlHeightLG: 40,
|
||||
|
|
@ -84,12 +86,8 @@ const getComponents = (isDarkMode) => ({
|
|||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* 生成 AntD ConfigProvider 的 theme 配置
|
||||
* @param {boolean} isDarkMode 是否暗色模式
|
||||
* @returns {object} AntD ThemeConfig
|
||||
*/
|
||||
export function getAntdTheme(isDarkMode) {
|
||||
/** 生成 AntD ConfigProvider 的 theme 配置 */
|
||||
export function getAntdTheme(isDarkMode: boolean): ThemeConfig {
|
||||
return {
|
||||
token: isDarkMode ? darkToken : lightToken,
|
||||
components: getComponents(isDarkMode),
|
||||
|
|
@ -0,0 +1,624 @@
|
|||
/**
|
||||
* 后端接口契约类型
|
||||
*
|
||||
* 与 backend/app/schemas、backend/app/api/v1 的实际返回结构一一对应。
|
||||
* 统一响应体为 { code, message, data };部分列表接口把分页字段放在顶层。
|
||||
*/
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页列表响应:total / page / page_size 与 data 同级。
|
||||
* 用户、角色、通知、模型配置等列表接口采用这一形状。
|
||||
*/
|
||||
export interface ApiListResponse<T> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
/** data 内分页(操作日志把分页字段放在 data 里) */
|
||||
export interface PagedData<T> {
|
||||
items: T
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
/** 状态:0 禁用 / 1 启用 */
|
||||
export type EnabledStatus = 0 | 1
|
||||
|
||||
export interface RoleSummary {
|
||||
id: number
|
||||
role_name: string
|
||||
role_code: string
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number
|
||||
username: string
|
||||
nickname: string | null
|
||||
email: string | null
|
||||
phone: string | null
|
||||
avatar: string | null
|
||||
status: EnabledStatus
|
||||
is_superuser: 0 | 1
|
||||
last_login_at: string | null
|
||||
created_at: string
|
||||
roles?: RoleSummary[]
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
access_token: string
|
||||
token_type: string
|
||||
user: User
|
||||
}
|
||||
|
||||
export interface McpCredential {
|
||||
bot_id: string
|
||||
bot_secret: string
|
||||
status: number
|
||||
last_used_at: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
message?: string | null
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: number
|
||||
role_name: string
|
||||
role_code: string
|
||||
description: string | null
|
||||
status: EnabledStatus
|
||||
is_system: 0 | 1
|
||||
user_count?: number
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface MenuNode {
|
||||
id: number
|
||||
menu_name: string
|
||||
menu_code: string
|
||||
/** 1-目录 2-菜单 3-按钮/权限点 */
|
||||
menu_type: number
|
||||
path: string | null
|
||||
component: string | null
|
||||
icon: string | null
|
||||
sort_order: number
|
||||
visible: 0 | 1
|
||||
permission: string | null
|
||||
children?: MenuNode[]
|
||||
}
|
||||
|
||||
/**
|
||||
* /role-permissions/menu-tree 的节点比 /menu/user-menus 多返回 parent_id 与 status,
|
||||
* 权限分配页需要 parent_id 来判断根节点,因此单独建模而不是合并成同一个类型。
|
||||
*/
|
||||
export interface MenuPermissionNode extends MenuNode {
|
||||
parent_id: number
|
||||
status: number
|
||||
children?: MenuPermissionNode[]
|
||||
}
|
||||
|
||||
export interface RolePermissionDetail {
|
||||
role_id: number
|
||||
role_name: string
|
||||
role_code: string
|
||||
menu_ids: number[]
|
||||
}
|
||||
|
||||
/** 项目角色由后端归一化为小写 */
|
||||
export type ProjectRole = 'admin' | 'editor' | 'viewer'
|
||||
|
||||
export interface Project {
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
is_public: 0 | 1
|
||||
storage_key: string
|
||||
owner_id: number
|
||||
is_template: 0 | 1
|
||||
status: number
|
||||
cover_image: string | null
|
||||
visit_count: number
|
||||
doc_count?: number
|
||||
user_role?: ProjectRole | 'owner'
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 项目列表接口的元素:除了 Project 本体,后端还按文件系统与成员表补齐统计字段。
|
||||
* owner_* / user_role 只有 /projects/shared(我参与的项目)才会返回。
|
||||
*/
|
||||
export interface ProjectListItem extends Project {
|
||||
doc_count: number
|
||||
/** 项目内文档的最新修改时间;项目为空或全部为 assets 时为 null */
|
||||
last_activity_at: string | null
|
||||
member_count: number
|
||||
git_repo_count: number
|
||||
owner_name?: string
|
||||
owner_nickname?: string | null
|
||||
}
|
||||
|
||||
export interface ProjectMember {
|
||||
id: number
|
||||
project_id: number
|
||||
user_id: number
|
||||
role: ProjectRole
|
||||
joined_at: string | null
|
||||
username: string
|
||||
nickname: string | null
|
||||
}
|
||||
|
||||
export interface GitRepo {
|
||||
id: number
|
||||
project_id: number
|
||||
name: string
|
||||
repo_url: string
|
||||
branch: string
|
||||
username: string | null
|
||||
token?: string | null
|
||||
is_default: 0 | 1
|
||||
sync_path: string
|
||||
has_token?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface GitDirectoryNode {
|
||||
title: string
|
||||
value: string
|
||||
key?: string
|
||||
isLeaf?: boolean
|
||||
selectable?: boolean
|
||||
children?: GitDirectoryNode[]
|
||||
}
|
||||
|
||||
export interface GitSyncResult {
|
||||
repo_id: number
|
||||
sync_path: string | null
|
||||
}
|
||||
|
||||
export interface GitDirectoriesResult {
|
||||
directories: GitDirectoryNode[]
|
||||
repo: string
|
||||
}
|
||||
|
||||
export interface ExportTask {
|
||||
task_id: string
|
||||
project_id: number
|
||||
status: string
|
||||
message: string
|
||||
progress: number
|
||||
processed_files: number
|
||||
total_files: number
|
||||
file_count: number
|
||||
zip_filename: string | null
|
||||
error: string | null
|
||||
created_at: string | null
|
||||
completed_at: string | null
|
||||
}
|
||||
|
||||
export interface ProjectShareInfo {
|
||||
enabled: boolean
|
||||
share_url: string | null
|
||||
has_password: boolean
|
||||
access_pass: string | null
|
||||
}
|
||||
|
||||
export interface FileShareInfo {
|
||||
file_path: string
|
||||
share_url: string
|
||||
has_password: boolean
|
||||
access_pass: string | null
|
||||
}
|
||||
|
||||
export interface ProjectSharePublicInfo {
|
||||
name: string
|
||||
description: string | null
|
||||
has_password: boolean
|
||||
share_code: string
|
||||
}
|
||||
|
||||
export interface FileSharePublicInfo {
|
||||
name: string
|
||||
project_name: string
|
||||
file_path: string
|
||||
has_password: boolean
|
||||
share_code: string
|
||||
}
|
||||
|
||||
/** antd Tree 节点结构,key 为文件相对路径 */
|
||||
export interface FileTreeNode {
|
||||
title: string
|
||||
key: string
|
||||
isLeaf: boolean
|
||||
is_shared?: boolean
|
||||
children?: FileTreeNode[]
|
||||
}
|
||||
|
||||
export interface FileContent {
|
||||
path: string
|
||||
content: string
|
||||
}
|
||||
|
||||
/**
|
||||
* /files/{id}/tree 的响应:目录树之外还带回读权限角色与项目基本信息,
|
||||
* 前端据此决定编辑入口是否可用、标题显示什么。
|
||||
*/
|
||||
export interface ProjectTreeResponse {
|
||||
tree: FileTreeNode[]
|
||||
user_role: ProjectRole | 'owner'
|
||||
project_name: string
|
||||
project_description: string | null
|
||||
}
|
||||
|
||||
/** 项目分享读取单个 Markdown 文件:只回传正文,不回传 path */
|
||||
export interface ShareFileContent {
|
||||
content: string
|
||||
}
|
||||
|
||||
/** 项目分享内的文件搜索结果(与全局 /search/documents 的形状不同) */
|
||||
export interface ShareSearchResult {
|
||||
file_path: string
|
||||
file_name: string
|
||||
match_type: string
|
||||
highlights?: string | null
|
||||
parent_paths?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 单文件分享的内容:PDF 只回传可直接访问的文档地址,
|
||||
* Markdown 回传改写过去资源前缀后的正文。
|
||||
*/
|
||||
export type FileShareContent =
|
||||
| { type: 'pdf'; filename: string; document_url: string; content?: undefined }
|
||||
| { type: 'markdown'; filename: string; content: string; document_url?: undefined }
|
||||
|
||||
export interface FileUploadResult {
|
||||
filename: string
|
||||
path: string
|
||||
url: string
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface ImportDocumentsResult {
|
||||
imported_files: string[]
|
||||
}
|
||||
|
||||
export type OperationType = 'rename' | 'delete' | 'create_dir' | 'create_file' | 'move'
|
||||
|
||||
export interface FileOperatePayload {
|
||||
action: OperationType
|
||||
path: string
|
||||
new_path?: string
|
||||
content?: string
|
||||
}
|
||||
|
||||
export interface NotificationItem {
|
||||
id: string | number
|
||||
user_id: number
|
||||
type: string
|
||||
category: string
|
||||
title: string
|
||||
content: string | null
|
||||
link: string | null
|
||||
is_read: boolean
|
||||
created_at: string | number
|
||||
read_at: string | null
|
||||
}
|
||||
|
||||
export interface UnreadByProjectResult {
|
||||
unread_by_project: Record<string, number>
|
||||
}
|
||||
|
||||
export interface OperationLog {
|
||||
id: number
|
||||
user_id: number | null
|
||||
username: string | null
|
||||
operation_type: string
|
||||
resource_type: string | null
|
||||
resource_id: string | null
|
||||
detail: string | null
|
||||
ip_address: string | null
|
||||
user_agent: string | null
|
||||
status: string | number
|
||||
error_message: string | null
|
||||
created_at: string | null
|
||||
}
|
||||
|
||||
export interface LogStats {
|
||||
operation_stats: Record<string, number>
|
||||
resource_stats: Record<string, number>
|
||||
today_count: number
|
||||
total_count: number
|
||||
}
|
||||
|
||||
export interface DashboardStats {
|
||||
stats: {
|
||||
user_count: number
|
||||
project_count: number
|
||||
document_count: number
|
||||
}
|
||||
recent_users: Array<{
|
||||
id: number
|
||||
username: string
|
||||
email: string | null
|
||||
created_at: string | null
|
||||
}>
|
||||
recent_projects: Array<{
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
owner_name: string
|
||||
created_at: string | null
|
||||
}>
|
||||
}
|
||||
|
||||
export interface PersonalStats {
|
||||
user_info: {
|
||||
id: number
|
||||
username: string
|
||||
email: string | null
|
||||
created_at: string | null
|
||||
}
|
||||
stats: {
|
||||
personal_projects_count: number
|
||||
shared_projects_count: number
|
||||
document_count: number
|
||||
}
|
||||
recent_personal_projects: Array<{
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
created_at: string | null
|
||||
}>
|
||||
recent_shared_projects: Array<{
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
role: ProjectRole
|
||||
joined_at: string | null
|
||||
}>
|
||||
}
|
||||
|
||||
export interface ActivityDate {
|
||||
date: string
|
||||
count: number
|
||||
}
|
||||
|
||||
/** 桌面「最近活动」条目,由 dashboard/document-activity 聚合 */
|
||||
export interface ActivityLog {
|
||||
id: string
|
||||
operation_type: string
|
||||
operation_count: number
|
||||
project_id: number
|
||||
project_name: string
|
||||
file_path: string
|
||||
file_exists: boolean
|
||||
first_time: string | null
|
||||
last_time: string | null
|
||||
created_at: string | null
|
||||
}
|
||||
|
||||
export type ModelType = 'chat' | 'embedding'
|
||||
|
||||
export interface LLMModelConfig {
|
||||
config_id: number
|
||||
model_code: string
|
||||
model_name: string
|
||||
model_type: ModelType
|
||||
provider: string
|
||||
endpoint_url: string
|
||||
llm_model_name: string
|
||||
llm_timeout: number
|
||||
llm_temperature: number
|
||||
llm_top_p: number
|
||||
llm_max_tokens: number | null
|
||||
llm_system_prompt: string | null
|
||||
embedding_dimension: number | null
|
||||
chunk_size: number | null
|
||||
chunk_overlap: number | null
|
||||
description: string | null
|
||||
is_active: boolean
|
||||
is_default: boolean
|
||||
has_api_key: boolean
|
||||
api_key_masked: string
|
||||
api_key?: string
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
/** 本地 embedding 模型(backend/models 目录扫描结果) */
|
||||
export interface LocalEmbeddingModel {
|
||||
name: string
|
||||
/** 从 1_Pooling/config.json 读取,读不到时为 null */
|
||||
dimension: number | null
|
||||
/** 权重文件是否已就位;未就位时不可选 */
|
||||
ready: boolean
|
||||
}
|
||||
|
||||
export interface LLMProvider {
|
||||
value: string
|
||||
label: string
|
||||
default_endpoint_url: string
|
||||
protocol: string
|
||||
default_chunk_size: number
|
||||
default_chunk_overlap: number
|
||||
/** 仅本地提供方下发 */
|
||||
models?: LocalEmbeddingModel[]
|
||||
/** 仅部分提供方下发(如本地模型只支持 embedding);缺省表示不限制 */
|
||||
model_types?: ModelType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 模型连通性测试结果:对话模型返回 preview,
|
||||
* 向量模型额外返回实际生成的向量维度。
|
||||
*/
|
||||
export interface LLMTestResult {
|
||||
provider: string
|
||||
endpoint_url: string
|
||||
llm_model_name: string
|
||||
latency_ms: number
|
||||
preview: string
|
||||
dimension?: number
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
session_id: number
|
||||
project_id: number
|
||||
llm_config_id: number | null
|
||||
title: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type MessageStatus = 'pending' | 'streaming' | 'completed' | 'interrupted' | 'failed' | string
|
||||
|
||||
export interface ThinkingLogEntry {
|
||||
stage: string
|
||||
message: string
|
||||
duration_ms?: number | null
|
||||
count?: number | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** 支撑句:后端按「主张 → 原文候选」做余弦对齐后回填 */
|
||||
export interface CitationQuote {
|
||||
text: string
|
||||
score: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 引用编号在正文中第 k 次出现对应的对齐结果:
|
||||
* quote_occurrences[k] 与答案里第 k 个 [n] 上角标一一对应(后端按全文出现顺序生成)。
|
||||
*/
|
||||
export interface CitationOccurrence {
|
||||
claim: string
|
||||
quotes: CitationQuote[]
|
||||
}
|
||||
|
||||
export interface ChatReference {
|
||||
citation_id: number | string
|
||||
file_path: string
|
||||
file_name: string
|
||||
anchor_text: string
|
||||
excerpt: string
|
||||
content: string
|
||||
chunk_index: number | null
|
||||
hit_terms: string[]
|
||||
/** 该引用整体得分最高的若干条支撑句 */
|
||||
quotes: CitationQuote[]
|
||||
/** 按正文出现顺序逐一对齐的支撑句;旧数据可能为空数组 */
|
||||
quote_occurrences: CitationOccurrence[]
|
||||
project_id?: number | null
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number
|
||||
role: 'user' | 'assistant' | string
|
||||
content: string
|
||||
status?: MessageStatus
|
||||
duration_ms?: number | null
|
||||
thinking_log?: ThinkingLogEntry[]
|
||||
referenced_files?: unknown[]
|
||||
references?: ChatReference[]
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ChatSearchResult {
|
||||
result_id: number
|
||||
session_id: number
|
||||
message_id: number
|
||||
role: string
|
||||
content: string
|
||||
snippet: string
|
||||
session_title: string
|
||||
project_id: number
|
||||
project_name: string
|
||||
llm_config_id: number | null
|
||||
model_name: string | null
|
||||
created_at: string | null
|
||||
}
|
||||
|
||||
export interface StreamIdsEvent {
|
||||
session_id?: number
|
||||
user_message_id?: number
|
||||
assistant_message_id?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface StreamDoneEvent {
|
||||
session_id?: number
|
||||
user_message_id?: number
|
||||
assistant_message_id?: number
|
||||
content?: string
|
||||
references?: ChatReference[]
|
||||
status?: string
|
||||
duration_ms?: number
|
||||
thinking_log?: ThinkingLogEntry[]
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE 的 thinking 事件与落库的 thinking_log 条目由后端同一个 `_log()` 产生,
|
||||
* 字段完全一致,因此共用 ThinkingLogEntry,不再维护两份定义。
|
||||
*/
|
||||
export type StreamThinkingEvent = ThinkingLogEntry
|
||||
|
||||
export interface VectorizeProgress {
|
||||
total: number
|
||||
success: number
|
||||
failed: number
|
||||
pending: number
|
||||
percent: number
|
||||
failed_items: Array<{ file_path: string; error: string }>
|
||||
pending_items: string[]
|
||||
embedding_ready: boolean
|
||||
}
|
||||
|
||||
export interface VectorizeTask {
|
||||
task_id: string
|
||||
project_id: number
|
||||
task_type: 'full' | 'incremental' | string
|
||||
status: 'pending' | 'running' | 'success' | 'partial' | 'failed' | string
|
||||
total: number
|
||||
processed: number
|
||||
skipped: number
|
||||
failed: number
|
||||
error_message: string | null
|
||||
created_at: string | null
|
||||
started_at: string | null
|
||||
finished_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export type SearchResult =
|
||||
| {
|
||||
type: 'project'
|
||||
project_id: number
|
||||
project_name: string
|
||||
project_description: string
|
||||
match_type: string
|
||||
file_path?: undefined
|
||||
file_name?: undefined
|
||||
highlights?: undefined
|
||||
}
|
||||
| {
|
||||
type: 'file'
|
||||
project_id: number
|
||||
project_name: string
|
||||
file_path: string
|
||||
file_name: string
|
||||
match_type: string
|
||||
highlights?: string | null
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
|
||||
|
||||
/**
|
||||
* 给「用 div/span 承载点击」的自定义控件补齐键盘语义。
|
||||
*
|
||||
* NEX §5.11:自定义交互必须支持键盘、可见焦点与可访问名称。
|
||||
* 这些控件沿用 div 是为了保住既有视觉与鼠标行为,因此不换成原生 button,
|
||||
* 而是补 role/tabIndex/onKeyDown,让键盘用户能完成同一动作。
|
||||
* 空格键需阻止默认行为,否则页面会滚动而不是触发控件。
|
||||
*/
|
||||
export interface ActivationProps {
|
||||
role: 'button'
|
||||
tabIndex: number
|
||||
onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void
|
||||
}
|
||||
|
||||
export function keyboardActivation(
|
||||
activate: (event: ReactKeyboardEvent<HTMLElement>) => void,
|
||||
): ActivationProps {
|
||||
return {
|
||||
role: 'button',
|
||||
tabIndex: 0,
|
||||
onKeyDown: (event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return
|
||||
event.preventDefault()
|
||||
activate(event)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** aria-label 只接受字符串;文案取不到时宁可留空,也不编造业务名称 */
|
||||
export function textForAriaLabel(node: unknown): string | undefined {
|
||||
if (typeof node === 'string') return node
|
||||
if (typeof node === 'number') return String(node)
|
||||
return undefined
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
import type { ReactElement, ReactNode } from 'react'
|
||||
import { Children, cloneElement, isValidElement } from 'react'
|
||||
import { Button } from 'antd'
|
||||
import {
|
||||
CaretDownFilled,
|
||||
CheckCircleFilled,
|
||||
CloseCircleFilled,
|
||||
ExclamationCircleFilled,
|
||||
EyeInvisibleOutlined,
|
||||
EyeOutlined,
|
||||
InfoCircleFilled,
|
||||
SearchOutlined,
|
||||
SwapRightOutlined,
|
||||
} from '@ant-design/icons'
|
||||
|
||||
/**
|
||||
* antd 内置控件的可访问名称补丁。
|
||||
*
|
||||
* `@ant-design/icons` 会在外层 `<span>` 上输出 `role="img" aria-label="<字形名>"`
|
||||
* (`AntdIcon.js:57-58`)。当图标是控件唯一的名称来源时,内部字形名就会变成
|
||||
* 读屏念出的业务名称,违反 NEX §5.16。这里只处理 antd 自己渲染、我们无法直接
|
||||
* 加属性的图标,统一走官方逃生口,不覆盖第三方 DOM(§5.13)。
|
||||
*/
|
||||
|
||||
/** 输入框清空按钮:`allowClear` 的官方逃生口是 `allowClear={{ clearIcon }}` */
|
||||
export function clearInputIcon(label = '清空'): { clearIcon: ReactNode } {
|
||||
return { clearIcon: <CloseCircleFilled aria-label={label} /> }
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页的上/下页按钮:rc-pagination 只把 `title="上一页"` 放在外层 `<li>` 上,
|
||||
* 按钮本身没有名称,于是 `left`/`right` 字形名成了计算名。
|
||||
* `itemRender` 是官方钩子,克隆原始节点补 `aria-label`,DOM 结构与样式不变。
|
||||
*/
|
||||
const PAGE_ITEM_LABELS: Record<string, string> = {
|
||||
prev: '上一页',
|
||||
next: '下一页',
|
||||
'jump-prev': '向前 5 页',
|
||||
'jump-next': '向后 5 页',
|
||||
}
|
||||
|
||||
/**
|
||||
* 把节点内的 antd 图标标记为装饰性,避免 `left`/`right` 这类字形名进入可访问性树。
|
||||
* antd 图标是 forwardRef 组件,类名在组件内部计算,因此按 `displayName` 识别。
|
||||
*/
|
||||
function isAntdIcon(el: ReactElement): boolean {
|
||||
const type = el.type as { displayName?: string }
|
||||
return /(?:Outlined|Filled|TwoTone)$/.test(type?.displayName ?? '')
|
||||
}
|
||||
|
||||
function hideDecorativeIcons(children: ReactNode): ReactNode {
|
||||
return Children.map(children, (child) => {
|
||||
if (!isValidElement(child)) return child
|
||||
const el = child as ReactElement<{ children?: ReactNode }>
|
||||
if (isAntdIcon(el)) return cloneElement(el, { 'aria-hidden': true } as never)
|
||||
if (el.props.children === undefined) return el
|
||||
return cloneElement(el, {} as never, hideDecorativeIcons(el.props.children))
|
||||
})
|
||||
}
|
||||
|
||||
export function namePageItem(_page: number, type: string, originalElement: ReactNode): ReactNode {
|
||||
const label = PAGE_ITEM_LABELS[type]
|
||||
if (!label || !isValidElement(originalElement)) return originalElement
|
||||
const el = originalElement as ReactElement<{ children?: ReactNode }>
|
||||
return cloneElement(el, { 'aria-label': label } as never, hideDecorativeIcons(el.props.children))
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索框的搜索按钮:`enterButton` 默认只放 `<SearchOutlined />`,
|
||||
* 按钮没有文本,于是字形名 `search` 成了计算名。传入自定义 Button 是官方写法,
|
||||
* antd 仍会克隆它并加上 `ant-input-search-button` 与尺寸,外观不变。
|
||||
*/
|
||||
export function searchEnterButton({
|
||||
label = '搜索',
|
||||
primary = false,
|
||||
loading = false,
|
||||
}: { label?: string; primary?: boolean; loading?: boolean } = {}) {
|
||||
return (
|
||||
<Button
|
||||
color={primary ? 'primary' : 'default'}
|
||||
variant={primary ? 'solid' : 'outlined'}
|
||||
loading={loading}
|
||||
aria-label={label}
|
||||
icon={<SearchOutlined aria-hidden />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tree / TreeSelect 的展开箭头。antd 默认给 `CaretDownFilled`,它会输出
|
||||
* `aria-label="caret-down"`,而展开状态已经由 `treeitem` 的 `aria-expanded` 表达,
|
||||
* 图标纯属装饰。`switcherIcon` 是官方钩子,antd 会克隆它并补上
|
||||
* `ant-tree-switcher-icon`(含 `-90deg` 旋转动画),因此外观与动效不变。
|
||||
*/
|
||||
export const decorativeSwitcherIcon = <CaretDownFilled aria-hidden />
|
||||
|
||||
/**
|
||||
* 日期范围选择器中间的 `→`。antd 默认渲染的是
|
||||
* `<span class="ant-picker-separator" aria-label="to"><SwapRightOutlined /></span>`,
|
||||
* 其中 `ant-picker-separator` 这个 class 承载 `fontSizeLG` 与颜色,直接换成裸图标会让
|
||||
* 图标小一圈;而图标自身又会把 `swap-right` 暴露成可访问名称。
|
||||
* 这里沿用 antd 自己的结构,只把装饰图标排除出名称计算,并把英文 `to` 本地化为 `至`。
|
||||
* class 前缀取 antd 默认值,项目未自定义 `prefixCls`(已核对 `App.tsx` 无 `prefixCls`)。
|
||||
*/
|
||||
export function rangeSeparatorWithLabel(label = '至') {
|
||||
return (
|
||||
<span className="ant-picker-separator" aria-label={label}>
|
||||
<SwapRightOutlined aria-hidden />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* `Alert showIcon` 的图标。antd 按 `type` 自动挑 `*Filled` 图标,同样会输出
|
||||
* `aria-label="exclamation-circle"` 这类字形名;而 Alert 的语义已经由 `message`
|
||||
* 文本表达(§5.10 状态不得只靠颜色/图标),图标纯属装饰。
|
||||
* 传自定义 `icon` 时 antd 会用 `replaceElement` 把 `ant-alert-icon` 类合并到该图标上
|
||||
* (`antd/lib/alert/Alert.js:46-51`),因此大小、颜色、间距都不变。
|
||||
* 这里按 type 复刻 antd 自己的图标映射,只额外加 `aria-hidden`。
|
||||
*/
|
||||
const ALERT_ICONS = {
|
||||
success: CheckCircleFilled,
|
||||
info: InfoCircleFilled,
|
||||
warning: ExclamationCircleFilled,
|
||||
error: CloseCircleFilled,
|
||||
} as const
|
||||
|
||||
export function decorativeAlertIcon(type: keyof typeof ALERT_ICONS = 'info') {
|
||||
const Icon = ALERT_ICONS[type] || InfoCircleFilled
|
||||
return <Icon aria-hidden />
|
||||
}
|
||||
|
||||
/**
|
||||
* `Input.Password` 的可见性切换图标。它是一个 `role="img"` 的可点控件,
|
||||
* antd 默认让它暴露成 `eye-invisible` / `eye` 这类字形名(`Password.js:29`),
|
||||
* 而它没有兄弟文案可以补足名称,因此必须给业务语义 `aria-label`。
|
||||
* `iconRender` 是官方钩子;这里沿用 antd 原本的图标映射
|
||||
* (明文态给 `EyeOutlined`、密文态给 `EyeInvisibleOutlined`)与 `ant-input-password-icon` 类,
|
||||
* 外观、点击与 `preventDefault` 行为都不变。
|
||||
*/
|
||||
export function passwordVisibilityIcon(visible: boolean) {
|
||||
return visible ? <EyeOutlined aria-label="隐藏密码" /> : <EyeInvisibleOutlined aria-label="显示密码" />
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import axios from 'axios'
|
||||
|
||||
/**
|
||||
* 读取接口错误的可读信息。
|
||||
*
|
||||
* 后端错误有两类形状:
|
||||
* - HTTPException:{ detail: "..." }(HTTP 状态码非 2xx,走 axios 错误分支)
|
||||
* - 业务码错误:{ code: 401, message: "..." }(HTTP 200,由拦截器抛 Error)
|
||||
* catch 到的值在 strict 模式下是 unknown,这里统一收口,避免各页面重复写
|
||||
* `error.response?.data?.detail` 这种不安全取值。
|
||||
*/
|
||||
|
||||
interface ApiErrorBody {
|
||||
detail?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** 取 HTTP 状态码(网络错误 / 业务码错误时为 undefined) */
|
||||
export function getApiErrorStatus(error: unknown): number | undefined {
|
||||
return axios.isAxiosError(error) ? error.response?.status : undefined
|
||||
}
|
||||
|
||||
/** 取后端返回的 detail(没有则 undefined),不回落到 Error.message */
|
||||
export function getApiErrorDetail(error: unknown): string | undefined {
|
||||
if (axios.isAxiosError<ApiErrorBody>(error)) {
|
||||
const detail = error.response?.data?.detail
|
||||
return typeof detail === 'string' && detail ? detail : undefined
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 取可读错误信息:后端 detail → Error.message → 调用方兜底文案 */
|
||||
export function getApiErrorMessage(error: unknown, fallback: string): string {
|
||||
const detail = getApiErrorDetail(error)
|
||||
if (detail) return detail
|
||||
if (error instanceof Error && error.message) return error.message
|
||||
return fallback
|
||||
}
|
||||
|
|
@ -1,16 +1,23 @@
|
|||
const ACCESS_TOKEN_KEY = 'access_token'
|
||||
const USER_INFO_KEY = 'user_info'
|
||||
|
||||
export function getAccessToken() {
|
||||
export function getAccessToken(): string | null {
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function setAuthStorage(accessToken: string, userInfo: unknown) {
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken)
|
||||
localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
|
||||
}
|
||||
|
||||
export function clearAuthStorage() {
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
}
|
||||
|
||||
export function buildAuthorizedUrl(url, extraParams = {}) {
|
||||
type UrlParamValue = string | number | boolean | null | undefined
|
||||
|
||||
export function buildAuthorizedUrl(url: string, extraParams: Record<string, UrlParamValue> = {}): string {
|
||||
const params = new URLSearchParams()
|
||||
const token = getAccessToken()
|
||||
|
||||
|
|
@ -20,7 +27,7 @@ export function buildAuthorizedUrl(url, extraParams = {}) {
|
|||
|
||||
Object.entries(extraParams).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
params.set(key, value)
|
||||
params.set(key, String(value))
|
||||
}
|
||||
})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue