Compare commits
11 Commits
main
...
a2741edf01
| Author | SHA1 | Date | |
|---|---|---|---|
| a2741edf01 | |||
| ada915f298 | |||
| 0f137b21fa | |||
| 7032d1c3f2 | |||
| 952a723448 | |||
| a01b3f259c | |||
| 72ec1a5459 | |||
| a8ace232a4 | |||
| 0d3d4fcd6a | |||
| af85d31035 | |||
| 1da95eaef3 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"pid": 91784,
|
"pid": 568932,
|
||||||
"version": "0.9.9",
|
"version": "0.9.9",
|
||||||
"socketPath": "\\\\.\\pipe\\codegraph-aef859f0205bacea",
|
"socketPath": "\\\\.\\pipe\\codegraph-aef859f0205bacea",
|
||||||
"startedAt": 1780539931451
|
"startedAt": 1780880691721
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
# 渲染进程 API 地址(Vite 编译时注入,不可在主进程中使用)
|
# 渲染进程 API 地址(Vite 编译时注入,不可在主进程中使用)
|
||||||
VITE_API_BASE_URL=http://8.160.179.64:8000
|
# VITE_API_BASE_URL=http://8.160.179.64:8000
|
||||||
|
VITE_API_BASE_URL=https://www.heixiu.net
|
||||||
|
|
||||||
# 主进程 — 更新检查 API(指向本地测试服务器)
|
# 主进程 — 更新检查 API(指向本地测试服务器)
|
||||||
UPDATE_API_URL=http://127.0.0.1:8000
|
UPDATE_API_URL=http://127.0.0.1:8000
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 船长 · HeiXiu — 前端架构文档
|
# 船长 · HeiXiu — 前端架构文档
|
||||||
|
|
||||||
> 最后更新:2026-06-03
|
> 最后更新:2026-06-08
|
||||||
|
|
||||||
## 目录结构
|
## 目录结构
|
||||||
|
|
||||||
@@ -17,12 +17,21 @@ src/
|
|||||||
│ ├── use-theme.ts # 主题切换
|
│ ├── use-theme.ts # 主题切换
|
||||||
│ └── use-updater.ts # 版本更新
|
│ └── use-updater.ts # 版本更新
|
||||||
├── pages/ # 页面
|
├── pages/ # 页面
|
||||||
│ └── login/ # 登录/注册
|
│ ├── login/ # 登录/注册/忘记密码/修改密码
|
||||||
│ ├── index.tsx # LoginPage — Modal 弹层
|
│ │ ├── index.tsx # LoginPage — Modal 弹层
|
||||||
│ ├── components/ # LoginForm / RegisterForm / FormField
|
│ │ ├── components/ # LoginForm / RegisterForm / ForgotPasswordModal / ChangePasswordModal / FormField
|
||||||
│ ├── config/ # 字段配置 / 校验规则
|
│ │ ├── config/ # 字段配置 / 校验规则
|
||||||
│ ├── hooks/ # use-auth-state(记住账号偏好)
|
│ │ ├── hooks/ # use-auth-state / use-sms-cooldown
|
||||||
│ └── types.ts # LoginFormValues / RegisterFormValues
|
│ │ └── types.ts # LoginFormValues / RegisterFormValues / FieldConfig
|
||||||
|
│ └── settings/ # 设置面板(主题 / 存储 / 账号安全 / 系统信息 / 更新)
|
||||||
|
│ ├── SettingsPage.tsx # 设置 Modal 主页面
|
||||||
|
│ ├── index.ts # barrel export
|
||||||
|
│ └── blocks/ # 设置子区块组件
|
||||||
|
│ ├── ThemeSetting.tsx
|
||||||
|
│ ├── StoragePathSetting.tsx
|
||||||
|
│ ├── SystemInfoSetting.tsx
|
||||||
|
│ ├── UpdateSetting.tsx
|
||||||
|
│ └── PasswordSetting.tsx
|
||||||
├── services/ # HTTP 层 + API 模块
|
├── services/ # HTTP 层 + API 模块
|
||||||
│ ├── request.ts # Axios 封装(通用 HTTP 层,不知晓 auth)
|
│ ├── request.ts # Axios 封装(通用 HTTP 层,不知晓 auth)
|
||||||
│ ├── auth-token.ts # Token 生命周期(refresh_token 存取 + 401 刷新回调)
|
│ ├── auth-token.ts # Token 生命周期(refresh_token 存取 + 401 刷新回调)
|
||||||
@@ -156,7 +165,23 @@ NavBar / 设置页 → AppProvider.logout()
|
|||||||
|
|
||||||
- 纯发布-订阅,不依赖任何框架
|
- 纯发布-订阅,不依赖任何框架
|
||||||
- 用于跨模块解耦通信(如 axios 拦截器无法直接用 React Context)
|
- 用于跨模块解耦通信(如 axios 拦截器无法直接用 React Context)
|
||||||
- 预定义事件:`AUTH_REQUIRED` / `SHOW_LOGIN` / `LOGIN_SUCCESS` / `LOGOUT`
|
- 预定义事件:`AUTH_REQUIRED` / `SHOW_LOGIN` / `LOGIN_SUCCESS` / `LOGOUT` / `TASK_SUBMITTED` / `OPEN_SETTINGS`
|
||||||
|
|
||||||
|
### 页面叠加层模式(QT 多窗口模型映射)
|
||||||
|
|
||||||
|
本项目是 Python QT 桌面应用的 Web 重构版。QT 应用以"新开窗口"为常态,原窗口不因新窗口打开而销毁。Web 端对应原则:
|
||||||
|
|
||||||
|
| QT 原版 | Web 对应 | 实现方式 |
|
||||||
|
|---------|---------|---------|
|
||||||
|
| 新开窗口叠加在主窗口之上 | Modal / Drawer | 事件总线驱动,主页面不卸载 |
|
||||||
|
| Tab 切换 / 视图替换 | React Router | 跨页状态放 Provider 或 localStorage |
|
||||||
|
|
||||||
|
**当前叠加层**:
|
||||||
|
- LoginPage — Modal,事件总线 `SHOW_LOGIN` / `AUTH_REQUIRED` 触发
|
||||||
|
- SettingsPage — Modal,事件总线 `OPEN_SETTINGS` 触发
|
||||||
|
- AnnouncementDrawer — Drawer,NavBar 内部 state 控制
|
||||||
|
|
||||||
|
**反模式警告**:叠加层绝不应通过路由跳转实现。`navigate('/xxx')` + `useLocation` 判断显隐会导致原有页面卸载,丢失所有组件状态。
|
||||||
|
|
||||||
### API 模块规范
|
### API 模块规范
|
||||||
|
|
||||||
|
|||||||
10
CHANGELOG.md
10
CHANGELOG.md
@@ -4,6 +4,16 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 0.0.13(2026-06-07)
|
||||||
|
|
||||||
|
- 修复主题切换后首页状态重置问题:设置页去路由化,改为事件总线驱动的 Modal 叠加
|
||||||
|
- 首页三栏分隔条视觉对齐:移除右侧多余 margin,左右完全对称
|
||||||
|
- 轮播图新增关闭按钮:session 级别隐藏,每次启动重新展示
|
||||||
|
- 确立 QT 多窗口模型 → Web 架构映射原则:叠加层走 Modal/Drawer + 事件总线,不走路由
|
||||||
|
- 修复首页三栏布局溢出:拖拽分隔条增加最大宽度约束 + 视口缩小时自动收窄面板,防止右侧面板被挤出视口
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 0.0.12(2026-06-04)
|
## 0.0.12(2026-06-04)
|
||||||
|
|
||||||
- 重构更新检查流程:无更新不再抛异常,PreCheck → 直接 IPC 通知
|
- 重构更新检查流程:无更新不再抛异常,PreCheck → 直接 IPC 通知
|
||||||
|
|||||||
69
PROJECT.md
69
PROJECT.md
@@ -46,10 +46,11 @@
|
|||||||
|
|
||||||
4. 窗口间通信统一通过主进程转发(或使用 MessagePort 等 Electron 支持的机制),保持窗口独立性。
|
4. 窗口间通信统一通过主进程转发(或使用 MessagePort 等 Electron 支持的机制),保持窗口独立性。
|
||||||
|
|
||||||
- 路由与导航:主窗口为 单页应用,使用 React Router v7+ 管理页面切换,支持嵌套路由。
|
- 路由与导航:主窗口为单页应用,使用 React Router v7+ 管理页面切换。**遵循 QT 多窗口模型映射原则**:
|
||||||
|
- 叠加层(设置、公告、素材库等)→ Modal/Drawer + 事件总线驱动,主页面不卸载
|
||||||
|
- 页面跳转(真正的视图切换)→ React Router,需跨页保持的状态放 Provider 或 localStorage
|
||||||
|
|
||||||
- 辅助窗口(设置、预览、导入导出等)为独立 BrowserWindow,加载独立的 HTML 入口(可根据路由参数或 windowId 决定内部路由),不与主窗口共享
|
- 辅助窗口(设置、预览、导入导出等)以 Modal/Drawer 叠加在主窗口之上,不与主窗口共享 DOM,但保持在同一个 React 组件树中以确保状态一致性。
|
||||||
DOM。
|
|
||||||
|
|
||||||
# 目录结构
|
# 目录结构
|
||||||
|
|
||||||
@@ -78,7 +79,7 @@
|
|||||||
│ ├── pages/ # 页面组件
|
│ ├── pages/ # 页面组件
|
||||||
│ │ ├── home/ # 首页仪表盘
|
│ │ ├── home/ # 首页仪表盘
|
||||||
│ │ ├── login/ # 登录 / 注册页
|
│ │ ├── login/ # 登录 / 注册页
|
||||||
│ │ └── settings/ # 设置面板(主题 / 存储 / 更新)
|
│ │ └── settings/ # 设置面板(主题 / 存储 / 账号安全 / 系统信息 / 更新)
|
||||||
│ ├── router/index.tsx # HashRouter 路由配置
|
│ ├── router/index.tsx # HashRouter 路由配置
|
||||||
│ ├── services/ # HTTP 请求封装
|
│ ├── services/ # HTTP 请求封装
|
||||||
│ │ ├── request.ts # Axios 封装 + 拦截器 + Token 刷新
|
│ │ ├── request.ts # Axios 封装 + 拦截器 + Token 刷新
|
||||||
@@ -169,15 +170,52 @@
|
|||||||
|
|
||||||
- 错误日志:request.ts 拦截器根据错误类型自动分级记录(AUTH_EXPIRED → debug,5xx → error,其余 → warn)。
|
- 错误日志:request.ts 拦截器根据错误类型自动分级记录(AUTH_EXPIRED → debug,5xx → error,其余 → warn)。
|
||||||
|
|
||||||
|
- 401 判断策略:HTTP 401 拦截处双重校验——同时检查 HTTP 状态码和响应体中的业务码 `data.code`。
|
||||||
|
仅 `status === 401 && data?.code === 401` 才走 token 刷新流程;其他业务码(如密码错误)穿透到正常错误处理,
|
||||||
|
透传后端的 `data.message`。这确保登录接口返回的"账号或密码错误"不被 RefreshError("登录已过期") 覆盖。
|
||||||
|
|
||||||
- 脱敏:shared/utils/sanitize.ts 在日志写入前自动处理 ID(哈希)、邮箱/手机/名称/Token 等字段。
|
- 脱敏:shared/utils/sanitize.ts 在日志写入前自动处理 ID(哈希)、邮箱/手机/名称/Token 等字段。
|
||||||
|
|
||||||
|
# 安全与认证
|
||||||
|
|
||||||
|
## Token 加密存储
|
||||||
|
|
||||||
|
- `access_token` 和 `refresh_token` 通过 Electron `safeStorage` API 加密存储,不落明文:
|
||||||
|
- macOS → Keychain
|
||||||
|
- Windows → DPAPI
|
||||||
|
- Linux → libsecret
|
||||||
|
- 实现文件:
|
||||||
|
- `electron/main/safe-storage-ipc.ts` — 主进程加密/解密 IPC 处理(`BIDIRECTIONAL.SAFESTORAGE_ENCRYPT / DECRYPT`)
|
||||||
|
- `src/utils/safe-storage.ts` — 渲染进程桥接层(`initSafeStore / getSafeStore / setSafeStore / clearSafeStore`)
|
||||||
|
- `src/services/request.ts` — token 存取通过 `getSafeStore / setSafeStore`,无需感知加密细节
|
||||||
|
- `src/services/auth-token.ts` — refresh_token 同理通过 safeStorage 存取
|
||||||
|
|
||||||
|
## 双 Token 机制
|
||||||
|
|
||||||
|
- `access_token`(短效)+ `refresh_token`(长效),登录成功同时下发
|
||||||
|
- 请求拦截器自动附加 `Authorization: Bearer <access_token>`
|
||||||
|
- 401 响应 → 双重校验(HTTP `status` + 业务 `data.code`)→ 仅 `code === 401` 时触发刷新
|
||||||
|
- 刷新期间并发请求排队(`failedQueue`),刷新完成后批量重试
|
||||||
|
- refresh 接口自身 401 直接拒绝(防死循环),login 接口 401 穿透透传后端 `message`
|
||||||
|
- 启动时 `refresh_token` 静默续期(自动登录),失败仅清除标记不影响用户名回填
|
||||||
|
- 登录/退出通过事件总线解耦(`LOGIN_SUCCESS` / `LOGOUT` / `AUTH_REQUIRED`)
|
||||||
|
|
||||||
|
## 日志脱敏
|
||||||
|
|
||||||
|
- `shared/utils/sanitize.ts` 在日志写入前自动脱敏处理
|
||||||
|
- 覆盖字段:用户 ID(SHA256 哈希)、邮箱(`***@domain`)、手机号(掩码)、用户名称、Token(截断)
|
||||||
|
- 主进程 `electron/main/logger.ts` 和渲染进程 `src/utils/logger.ts` 均写入前调用 `sanitizeLogEntry()`
|
||||||
|
|
||||||
# 样式与主题
|
# 样式与主题
|
||||||
|
|
||||||
- 优先使用 Tailwind 工具类 完成布局与常规样式,自定义设计令牌应映射为 Tailwind 扩展(在 tailwind.config.ts 中配置
|
- 优先使用 Tailwind 工具类 完成布局与常规样式,自定义设计令牌应映射为 Tailwind 扩展(在 tailwind.config.ts 中配置
|
||||||
theme.extend)。
|
theme.extend)。
|
||||||
|
|
||||||
- Ant Design 组件样式通过 ConfigProvider 的 theme 属性覆盖,确保与 Tailwind 主题令牌同步。在 src/theme/adapters/ 中创建
|
- Ant Design 组件样式通过 ConfigProvider 的 theme 属性覆盖,确保与 Tailwind 主题令牌同步。
|
||||||
antd-theme.ts,导出主题配置对象,引用 tokens.ts 中的设计变量。
|
`ConfigProvider` 同时配置 `locale={zhCN}` 实现全局中文(分页器"条/页"等无需逐个组件设置)。
|
||||||
|
在 src/theme/ 中创建 antd-theme.ts,导出主题配置对象,引用 tokens.ts 中的设计变量。
|
||||||
|
组件级 token(如 Pagination.itemActiveColor / itemActiveBg)在 sharedComponents 中统一管理,
|
||||||
|
亮色/暗色主题共享,避免 CSS !important hack。
|
||||||
|
|
||||||
- 禁止在组件中硬编码颜色、字号等设计令牌,一律使用主题变量或 Tailwind 类名。
|
- 禁止在组件中硬编码颜色、字号等设计令牌,一律使用主题变量或 Tailwind 类名。
|
||||||
|
|
||||||
@@ -224,15 +262,28 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
| 模块 | 位置 | 职责 |
|
| 模块 | 位置 | 职责 |
|
||||||
|------|------|------|
|
|-------------------|-----------------------------------------------|------------------------------------------|
|
||||||
| `HeiXiuProvider` | `electron/main/updater.ts` | 自定义 Provider,调用自有 API,无更新返回 APP_VERSION |
|
| `HeiXiuProvider` | `electron/main/updater.ts` | 自定义 Provider,调用自有 API,无更新返回 APP_VERSION |
|
||||||
| `checkForUpdates` | `electron/main/updater.ts` | 预检版本 → 无更新直发 IPC / 有更新交 electron-updater |
|
| `checkForUpdates` | `electron/main/updater.ts` | 预检版本 → 无更新直发 IPC / 有更新交 electron-updater |
|
||||||
| `downloadUpdate` | `electron/main/updater.ts` | 用户确认后触发下载(从 checkForUpdates 分离) |
|
| `downloadUpdate` | `electron/main/updater.ts` | 用户确认后触发下载(从 checkForUpdates 分离) |
|
||||||
| `netRequest` | `electron/main/net-request.ts` | Electron net.request 的 axios 风格封装 |
|
| `netRequest` | `electron/main/net-request.ts` | Electron net.request 的 axios 风格封装 |
|
||||||
| `useUpdater` | `src/hooks/use-updater.ts` | 渲染进程更新状态 Hook(单例 IPC 监听) |
|
| `useUpdater` | `src/hooks/use-updater.ts` | 渲染进程更新状态 Hook(单例 IPC 监听) |
|
||||||
| `UpdateSetting` | `src/pages/settings/UpdateSetting.tsx` | 设置页更新区块(含"查看详情"弹窗) |
|
| `UpdateSetting` | `src/pages/settings/blocks/UpdateSetting.tsx` | 设置页更新区块(含"查看详情"弹窗) |
|
||||||
| `server.py` | `test-server/server.py` | 本地测试服务器,扫描 release/ 目录,语义版本排序 |
|
| `server.py` | `test-server/server.py` | 本地测试服务器,扫描 release/ 目录,语义版本排序 |
|
||||||
|
|
||||||
|
## 增量更新(差分下载)
|
||||||
|
|
||||||
|
- `package.json` 配置 `"differentialPackage": true`,electron-builder 打包时自动生成 `.exe.blockmap` 文件
|
||||||
|
- 自定义 Provider 模式:`HeiXiuNsisUpdater extends NsisUpdater` / `HeiXiuMacUpdater extends MacUpdater` /
|
||||||
|
`HeiXiuAppImageUpdater extends AppImageUpdater`
|
||||||
|
- 三平台 Updater 均覆盖 `getUpdateInfoAndProvider()` 注入 `HeiXiuProvider`(自定义 API 版本检查),差分下载由
|
||||||
|
electron-updater 父类原生处理
|
||||||
|
- blockmap 文件流程:
|
||||||
|
- `scripts/generate-update-info.mjs` — 扫描 blockmap 文件,写 `blockmap.url` + `blockmap.size` 到 `update-info.json`
|
||||||
|
- `scripts/upload-oss.mjs` — 安装包 + blockmap 文件一并上传 OSS(支持 Node.js 直传和 ossutil 两种模式)
|
||||||
|
- `scripts/publish-release.mjs` — 通过 `--blockmap-url` 参数将 blockmap 信息发布到后端 API
|
||||||
|
- 效果:日常更新仅下载变更区块,预计节省 60%~90% 流量
|
||||||
|
|
||||||
## 环境变量加载机制(主进程)
|
## 环境变量加载机制(主进程)
|
||||||
|
|
||||||
加载顺序(后者覆盖前者,OS 环境变量始终优先):
|
加载顺序(后者覆盖前者,OS 环境变量始终优先):
|
||||||
@@ -245,7 +296,7 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
| 文件 | 何时生效 | 进 git | 用途 |
|
| 文件 | 何时生效 | 进 git | 用途 |
|
||||||
|------|---------|:------:|------|
|
|--------------------|---------------------|:-----:|--------------------|
|
||||||
| `.env.development` | `npm run dev` | ✅ | 本地开发(API → 测试服务器) |
|
| `.env.development` | `npm run dev` | ✅ | 本地开发(API → 测试服务器) |
|
||||||
| `.env.production` | `npm run build:xxx` | ❌ | 构建时参考(API → 生产服务器) |
|
| `.env.production` | `npm run build:xxx` | ❌ | 构建时参考(API → 生产服务器) |
|
||||||
| `.env.local` | 始终(后加载) | ❌ | 个人特殊配置(打包后连本地测试) |
|
| `.env.local` | 始终(后加载) | ❌ | 个人特殊配置(打包后连本地测试) |
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
| 层 | 技术 |
|
| 层 | 技术 |
|
||||||
| ---- | ------------------------------ |
|
|----|--------------------------------|
|
||||||
| 框架 | Electron 42 |
|
| 框架 | Electron 42 |
|
||||||
| 前端 | React 19 + TypeScript + Vite 8 |
|
| 前端 | React 19 + TypeScript + Vite 8 |
|
||||||
| UI | Ant Design 6 + Tailwind CSS 4 |
|
| UI | Ant Design 6 + Tailwind CSS 4 |
|
||||||
@@ -68,7 +68,7 @@ node build.mjs --win --personal --clean --build
|
|||||||
```
|
```
|
||||||
|
|
||||||
| 操作 | 说明 |
|
| 操作 | 说明 |
|
||||||
| ----------- | -------------------------------------------------------------- |
|
|-------------|---------------------------------------------------------|
|
||||||
| `--build` | 构建(默认:tsc + vite + electron-builder + update-info.json) |
|
| `--build` | 构建(默认:tsc + vite + electron-builder + update-info.json) |
|
||||||
| `--clean` | 构建前清理 release/ dist/ dist-electron/ |
|
| `--clean` | 构建前清理 release/ dist/ dist-electron/ |
|
||||||
| `--sign` | 代码签名(需配合 `--cert` 或 `CSC_LINK` 环境变量) |
|
| `--sign` | 代码签名(需配合 `--cert` 或 `CSC_LINK` 环境变量) |
|
||||||
@@ -144,7 +144,7 @@ ele-heixiu/
|
|||||||
主进程加载顺序:`.env.{mode}` → `.env.local` → OS 环境变量 → 代码默认值。
|
主进程加载顺序:`.env.{mode}` → `.env.local` → OS 环境变量 → 代码默认值。
|
||||||
|
|
||||||
| 变量 | 默认值 | 用途 |
|
| 变量 | 默认值 | 用途 |
|
||||||
| ----------------------- | ------------------------------------------------------ | --------------- |
|
|-------------------------|--------------------------------------------------------|---------------|
|
||||||
| `UPDATE_API_URL` | `https://www.heixiu.com` | 版本检查 API |
|
| `UPDATE_API_URL` | `https://www.heixiu.com` | 版本检查 API |
|
||||||
| `UPDATE_API_KEY` | — | 发布 API 鉴权 |
|
| `UPDATE_API_KEY` | — | 发布 API 鉴权 |
|
||||||
| `UPDATE_DOWNLOAD_BASE` | `https://heixiu.oss-cn-hangzhou.aliyuncs.com/releases` | OSS 下载基地址 |
|
| `UPDATE_DOWNLOAD_BASE` | `https://heixiu.oss-cn-hangzhou.aliyuncs.com/releases` | OSS 下载基地址 |
|
||||||
@@ -163,7 +163,7 @@ ele-heixiu/
|
|||||||
## 相关文档
|
## 相关文档
|
||||||
|
|
||||||
| 文档 | 面向 | 内容 |
|
| 文档 | 面向 | 内容 |
|
||||||
|------|------|------|
|
|--------------------------------------------------|-------|-----------------------|
|
||||||
| [PROJECT.md](./PROJECT.md) | 开发者 | 技术架构、更新系统、环境变量架构、测试流程 |
|
| [PROJECT.md](./PROJECT.md) | 开发者 | 技术架构、更新系统、环境变量架构、测试流程 |
|
||||||
| [UpdateA.md](./UpdateA.md) | 前端发版 | 构建命令、发版流程、代码签名 |
|
| [UpdateA.md](./UpdateA.md) | 前端发版 | 构建命令、发版流程、代码签名 |
|
||||||
| [test-server/README.md](./test-server/README.md) | 后端程序员 | API 规格、数据库表结构、实现清单 |
|
| [test-server/README.md](./test-server/README.md) | 后端程序员 | API 规格、数据库表结构、实现清单 |
|
||||||
|
|||||||
105
TODO.md
105
TODO.md
@@ -1,49 +1,6 @@
|
|||||||
# TODO — 船长·HeiXiu 待办与优化清单
|
# TODO — 船长·HeiXiu 待办与优化清单
|
||||||
|
|
||||||
> 最后更新:2026-06-03
|
> 最后更新:2026-06-08
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🔴 安全加固(优先级高)
|
|
||||||
|
|
||||||
### 1. 敏感数据加密存储
|
|
||||||
|
|
||||||
当前所有敏感数据存储在 `localStorage` 明文/Base64:
|
|
||||||
|
|
||||||
| 数据 | 现状 | 目标方案 |
|
|
||||||
|------------------|-----------|----------------------------------------|
|
|
||||||
| `access_token` | 明文 | Electron `safeStorage.encryptString()` |
|
|
||||||
| `refresh_token` | 明文 | Electron `safeStorage.encryptString()` |
|
|
||||||
| `passwordBase64` | Base64 编码 | 移除密码存储,仅靠 refresh_token 自动登录 |
|
|
||||||
|
|
||||||
**方案 A(推荐)**:使用 Electron `safeStorage` API
|
|
||||||
|
|
||||||
- macOS → Keychain
|
|
||||||
- Windows → DPAPI
|
|
||||||
- Linux → libsecret
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// preload.ts 暴露安全方法
|
|
||||||
contextBridge.exposeInMainWorld('safeStorage', {
|
|
||||||
encrypt: (plain: string) => ipcRenderer.invoke('safe-storage:encrypt', plain),
|
|
||||||
decrypt: (encrypted: Buffer) => ipcRenderer.invoke('safe-storage:decrypt', encrypted),
|
|
||||||
});
|
|
||||||
|
|
||||||
// 替代现有 setToken / setStoredRefreshToken
|
|
||||||
// 渲染进程不再直接操作 localStorage
|
|
||||||
```
|
|
||||||
|
|
||||||
**方案 B**:敏感操作下沉到主进程
|
|
||||||
|
|
||||||
- `access_token` / `refresh_token` 由主进程管理
|
|
||||||
- 渲染进程通过 IPC 发起请求时由主进程追加 Token
|
|
||||||
- 渲染进程永不持有明文 Token
|
|
||||||
|
|
||||||
### 2. 密码存储策略调整
|
|
||||||
|
|
||||||
- [ ] "记住密码" → 仅回填用户名,不再存储密码(已完成)
|
|
||||||
- [ ] 清理 `StoredAuth.passwordBase64` 字段
|
|
||||||
- [ ] "自动登录" 完全依赖 `refresh_token` 静默续期
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -60,12 +17,10 @@ contextBridge.exposeInMainWorld('safeStorage', {
|
|||||||
- [ ] 合规素材库页面(`/compliance-assets`)
|
- [ ] 合规素材库页面(`/compliance-assets`)
|
||||||
- [ ] 项目管理页面(`/projects`,企业版)
|
- [ ] 项目管理页面(`/projects`,企业版)
|
||||||
- [ ] 账户/会员/充值/消费记录/订单明细页面
|
- [ ] 账户/会员/充值/消费记录/订单明细页面
|
||||||
- [ ] 忘记密码流程
|
|
||||||
- [ ] 各页面暗色主题适配
|
- [ ] 各页面暗色主题适配
|
||||||
|
|
||||||
### 导航栏
|
### 导航栏
|
||||||
|
|
||||||
- [ ] 移除调试用的 `console.log`
|
|
||||||
- [ ] 导航配置中的 `action: 'external'` 统一管理(白名单校验)
|
- [ ] 导航配置中的 `action: 'external'` 统一管理(白名单校验)
|
||||||
- [ ] 未登录点击需登录项 → 登录成功后自动跳转到目标页
|
- [ ] 未登录点击需登录项 → 登录成功后自动跳转到目标页
|
||||||
|
|
||||||
@@ -87,54 +42,6 @@ contextBridge.exposeInMainWorld('safeStorage', {
|
|||||||
- [ ] 单元测试覆盖(Vitest)
|
- [ ] 单元测试覆盖(Vitest)
|
||||||
- [ ] Bundle 体积分析优化(rollup-plugin-visualizer 已有,定期检查)
|
- [ ] Bundle 体积分析优化(rollup-plugin-visualizer 已有,定期检查)
|
||||||
|
|
||||||
### 增量更新改造
|
|
||||||
|
|
||||||
当前状态:
|
|
||||||
|
|
||||||
- `electron-builder` 已配置 `"differential": true`,打包时已生成 `.exe.blockmap` 文件 ✅
|
|
||||||
- `electron/main/updater.ts` 为**手写全量下载**(`net.request`),未使用 `electron-updater` npm 包 ❌
|
|
||||||
- blockmap 文件生成了但从未被消费,每次更新都是完整下载
|
|
||||||
|
|
||||||
目标方案 — 自定义 Provider + electron-updater:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// electron/main/updater-v2.ts
|
|
||||||
import { autoUpdater } from 'electron-updater';
|
|
||||||
import { Provider } from 'electron-updater/out/providers/Provider';
|
|
||||||
|
|
||||||
class HeiXiuProvider extends Provider<UpdateInfo> {
|
|
||||||
// 版本检查 → 走自定义 API(保留灰度/强更控制)
|
|
||||||
async getLatestVersion(): Promise<UpdateInfo> {
|
|
||||||
const res = await fetch(`${API_BASE}/api/v1/update/check?...`);
|
|
||||||
const data = await res.json();
|
|
||||||
return {
|
|
||||||
version: data.latestVersion,
|
|
||||||
files: [{
|
|
||||||
url: data.downloadUrl,
|
|
||||||
sha512: data.sha512,
|
|
||||||
size: data.fileSize,
|
|
||||||
blockMapSize: data.blockMapSize, // 后端新增字段
|
|
||||||
}],
|
|
||||||
path: data.downloadUrl,
|
|
||||||
sha512: data.sha512,
|
|
||||||
releaseDate: data.releaseDate,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
改造内容:
|
|
||||||
|
|
||||||
- [ ] 安装 `electron-updater` npm 包
|
|
||||||
- [ ] 重写 `electron/main/updater.ts` 为自定义 Provider 模式
|
|
||||||
- [ ] 发布脚本 `upload-oss.mjs` 增加 blockmap 文件上传
|
|
||||||
- [ ] `generate-update-info.mjs` 增加 blockmap 字段(`blockMapUrl`、`blockMapSize`)
|
|
||||||
- [ ] 后端 API `/api/v1/update/check` 响应增加 `blockMapUrl`、`blockMapSize` 字段
|
|
||||||
- [ ] 后端 `releases` 表增加 `blockmap_url`、`blockmap_size` 列
|
|
||||||
- [ ] OSS 上传每次版本需同时上传 `.exe` + `.exe.blockmap` 两个文件
|
|
||||||
|
|
||||||
增量效果预估:日常更新下载量从完整安装包 → 仅变化的块(预计节省 60%~90% 流量)。
|
|
||||||
|
|
||||||
### 代码质量
|
### 代码质量
|
||||||
|
|
||||||
- [ ] 移除未使用的 `shared/` 类型和常量
|
- [ ] 移除未使用的 `shared/` 类型和常量
|
||||||
@@ -153,7 +60,7 @@ class HeiXiuProvider extends Provider<UpdateInfo> {
|
|||||||
## ⚠️ 已知技术债务
|
## ⚠️ 已知技术债务
|
||||||
|
|
||||||
| 问题 | 说明 | 影响 |
|
| 问题 | 说明 | 影响 |
|
||||||
|-----------------|---------------------------------------|----------------|
|
|-----------------|----------------------------------------------------------------------------------------------------------------------|----------------|
|
||||||
| localStorage 依赖 | 所有持久化数据依赖 localStorage | 清理浏览器数据会丢失所有配置 |
|
| localStorage 依赖 | 所有持久化数据依赖 localStorage | 清理浏览器数据会丢失所有配置 |
|
||||||
| IPC 监听器 | useUpdater 已改为单例,其他 IPC hook 可能也有类似问题 | 长期运行可能内存泄漏 |
|
| IPC 监听器 | useUpdater 已改为单例,其他 IPC hook 可能也有类似问题 | 长期运行可能内存泄漏 |
|
||||||
| `test.py` | 仓库根目录残留测试文件 | 无实际作用,应清理 |
|
| `test.py` | 仓库根目录残留测试文件 | 无实际作用,应清理 |
|
||||||
@@ -163,6 +70,8 @@ class HeiXiuProvider extends Provider<UpdateInfo> {
|
|||||||
|
|
||||||
## 📋 下次开发计划
|
## 📋 下次开发计划
|
||||||
|
|
||||||
1. **safeStorage 加密改造**(安全加固 #1)
|
1. **合规素材库页面**(功能待完善 — 按 QT 原版设计,以 Modal/Drawer 叠加而非路由跳转实现)
|
||||||
2. **合规素材库页面**(功能待完善 Route 页面)
|
2. **各页面 nav 导航补齐**(后续页面优先使用叠加模式,遵循 QT 多窗口模型 → 见 WORKLOG 2026-06-07)
|
||||||
3. **各页面 nav 导航补齐**
|
3. **leftWidth / rightWidth / taskPage 加 localStorage 持久化**(UX 优化:刷新页面后保持用户偏好;已通过路由去路由化解决组件卸载问题,但 localStorage 持久层仍未实现)
|
||||||
|
4. **轮播图关闭按钮 localStorage 持久化**(关闭按钮已实现,待做:localStorage 记录关闭时间戳,超过 N 天再显示)
|
||||||
|
5. **短信发送接入人机验证**(后期优化,需后端配合:`sendSms` 接口增加 `captcha_token` 参数 + 前端滑块/图形验证组件。当前仅靠 60s 冷却按钮 + 后端限流,桌面端 ASAR 可解包 + DevTools 网络面板 + 代理抓包均能直接暴露 API,纯前端限制对脚本攻击无效)
|
||||||
|
|||||||
18
index.html
18
index.html
@@ -1,21 +1,21 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<!-- 使用项目 Logo 作为 favicon(Windows 可用 .ico) -->
|
<!-- 使用项目 Logo 作为 favicon(Windows 可用 .ico) -->
|
||||||
<link rel="icon" type="image/png" href="/src/assets/logo/HX.png" />
|
<link rel="icon" type="image/png" href="/src/assets/logo/HX.png" />
|
||||||
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0" />-->
|
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0" />-->
|
||||||
<meta http-equiv="Content-Security-Policy" content="
|
<meta http-equiv="Content-Security-Policy" content="
|
||||||
default-src 'self';
|
default-src 'self';
|
||||||
script-src 'self' 'unsafe-inline';
|
script-src 'self' 'unsafe-inline';
|
||||||
style-src 'self' 'unsafe-inline';
|
style-src 'self' 'unsafe-inline';
|
||||||
img-src 'self' data:;
|
img-src 'self' data: https://rh-images-1252422369.cos.ap-beijing.myqcloud.com https://www.heixiu.net ; ;
|
||||||
connect-src 'self' http://8.160.179.64:8000 http://localhost:5173 ws://localhost:5173 https://www.heixiu.net;
|
connect-src 'self' http://8.160.179.64:8000 http://localhost:5173 ws://localhost:5173 https://www.heixiu.net ;
|
||||||
">
|
">
|
||||||
<title>船长·HeiXiu</title>
|
<title>船长·HeiXiu</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
74
package-lock.json
generated
74
package-lock.json
generated
@@ -1,19 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "ele-heixiu",
|
"name": "ele-heixiu",
|
||||||
"version": "0.0.1",
|
"version": "0.0.13",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ele-heixiu",
|
"name": "ele-heixiu",
|
||||||
"version": "0.0.1",
|
"version": "0.0.13",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@react-buddy/ide-toolbox": "^2.5.0",
|
||||||
"antd": "^6.4.3",
|
"antd": "^6.4.3",
|
||||||
"axios": "^1.16.1",
|
"axios": "^1.16.1",
|
||||||
"electron-updater": "^6.8.3",
|
"electron-updater": "^6.8.3",
|
||||||
"react": "^19.2.7",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.7",
|
"react-dom": "^19.2.7"
|
||||||
"react-router-dom": "^7.16.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@playwright/test": "^1.60.0",
|
"@playwright/test": "^1.60.0",
|
||||||
@@ -1949,6 +1949,15 @@
|
|||||||
"react-dom": ">=18.0.0"
|
"react-dom": ">=18.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@react-buddy/ide-toolbox": {
|
||||||
|
"version": "2.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-buddy/ide-toolbox/-/ide-toolbox-2.5.0.tgz",
|
||||||
|
"integrity": "sha512-ev2BZUeCymJfKuV3M+rQzdVZYlAacid8GexD3TtP0S+UBCBbH6ZCdkbx2eJoh/X+CEWFctg+2ppxIoaK52A7Rw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/binding-android-arm64": {
|
"node_modules/@rolldown/binding-android-arm64": {
|
||||||
"version": "1.0.3",
|
"version": "1.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",
|
||||||
@@ -3932,19 +3941,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
|
||||||
"version": "1.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
|
||||||
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "opencollective",
|
|
||||||
"url": "https://opencollective.com/express"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/core-util-is": {
|
"node_modules/core-util-is": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
||||||
@@ -7094,44 +7090,6 @@
|
|||||||
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
|
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/react-router": {
|
|
||||||
"version": "7.16.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.16.0.tgz",
|
|
||||||
"integrity": "sha512-wArC8lVyJb3+jM9OpDyW6hLCizACWkvQR/sSGqSs+o5uEXEtGlqdZ4v8hENR3Jad6i+LRkK93q/+bQAcvl6V1A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"cookie": "^1.0.1",
|
|
||||||
"set-cookie-parser": "^2.6.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=18",
|
|
||||||
"react-dom": ">=18"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"react-dom": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/react-router-dom": {
|
|
||||||
"version": "7.16.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.16.0.tgz",
|
|
||||||
"integrity": "sha512-kMUAbimWB5FVbF4Bce4bJsiKJWLIUHq/mEG8+CFDnCSgltptBiG5nguducmsJeGKytlCvQud9Qhzpn49iduTlA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"react-router": "7.16.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=18",
|
|
||||||
"react-dom": ">=18"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/read-binary-file-arch": {
|
"node_modules/read-binary-file-arch": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
|
||||||
@@ -7531,12 +7489,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/set-cookie-parser": {
|
|
||||||
"version": "2.7.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
|
|
||||||
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/shebang-command": {
|
"node_modules/shebang-command": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "ele-heixiu",
|
"name": "ele-heixiu",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.12",
|
"version": "0.0.13",
|
||||||
"description": "船长·HeiXiu — 桌面效率工作台",
|
"description": "船长·HeiXiu — 桌面效率工作台",
|
||||||
"author": "HeiXiu 杨烨",
|
"author": "HeiXiu 杨烨",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -26,12 +26,12 @@
|
|||||||
"test:e2e": "playwright test.json"
|
"test:e2e": "playwright test.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@react-buddy/ide-toolbox": "^2.5.0",
|
||||||
"antd": "^6.4.3",
|
"antd": "^6.4.3",
|
||||||
"axios": "^1.16.1",
|
"axios": "^1.16.1",
|
||||||
"electron-updater": "^6.8.3",
|
"electron-updater": "^6.8.3",
|
||||||
"react": "^19.2.7",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.7",
|
"react-dom": "^19.2.7"
|
||||||
"react-router-dom": "^7.16.0"
|
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"appId": "com.heixiu.electron",
|
"appId": "com.heixiu.electron",
|
||||||
|
|||||||
42
src/App.tsx
42
src/App.tsx
@@ -1,18 +1,25 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { HashRouter } from 'react-router-dom';
|
|
||||||
|
|
||||||
import { useAppContext } from './contexts/app-context';
|
import { useAppContext } from './contexts/app-context';
|
||||||
import { LoginPage } from './pages/login';
|
import { LoginPage } from './pages/login';
|
||||||
|
import { SettingsPage } from './pages/settings';
|
||||||
import { on, off, EVENTS } from './utils/event-bus';
|
import { on, off, EVENTS } from './utils/event-bus';
|
||||||
import { AppRoutes } from './router';
|
import { Layout } from '@/components/Layout';
|
||||||
|
import { HomePage } from '@/pages/home/HomePage';
|
||||||
|
import { PageDispatcher } from '@/components/PageDispatcher';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根组件 — 主窗口
|
* 根组件 — 主窗口
|
||||||
*
|
*
|
||||||
* 层级:
|
* 层级:
|
||||||
* HashRouter
|
* Layout(Banner + NavBar)
|
||||||
* ├── LoginPage(Modal 弹层,事件总线驱动)
|
* └── HomePage(主页面,始终挂载)
|
||||||
* ├── AppRoutes(页面路由 + SettingsPage Drawer 叠加)
|
* LoginPage(Modal 弹层,事件总线驱动)
|
||||||
|
* SettingsPage(Modal 居中叠加,事件总线驱动 — 对应 QT 原版设置窗口)
|
||||||
|
*
|
||||||
|
* 设计原则(对应 QT 原版多窗口模型):
|
||||||
|
* - 叠加层(设置、公告、页面等)→ Modal/Drawer + 事件总线,主页面不卸载
|
||||||
|
* - 不再使用 React Router,所有导航由事件总线驱动
|
||||||
*/
|
*/
|
||||||
function App() {
|
function App() {
|
||||||
const { isLoggedIn } = useAppContext();
|
const { isLoggedIn } = useAppContext();
|
||||||
@@ -42,14 +49,31 @@ function App() {
|
|||||||
setLoginOpen(false);
|
setLoginOpen(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 设置 Drawer 状态
|
||||||
|
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||||
|
|
||||||
|
// 监听打开设置 Drawer
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => setSettingsOpen(true);
|
||||||
|
on(EVENTS.OPEN_SETTINGS, handler);
|
||||||
|
return () => { off(EVENTS.OPEN_SETTINGS, handler); };
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HashRouter>
|
<>
|
||||||
|
<Layout>
|
||||||
|
<HomePage />
|
||||||
|
</Layout>
|
||||||
|
|
||||||
{/* 登录 Modal — 可关闭,关闭后主页可操作 */}
|
{/* 登录 Modal — 可关闭,关闭后主页可操作 */}
|
||||||
<LoginPage open={loginOpen && !isLoggedIn} onClose={handleLoginClose} />
|
<LoginPage open={loginOpen && !isLoggedIn} onClose={handleLoginClose} />
|
||||||
|
|
||||||
{/* 页面路由 + SettingsPage Drawer 叠加 */}
|
{/* 设置 Modal — 事件驱动,居中叠加,主页面始终挂载(对应 QT 原版独立设置窗口) */}
|
||||||
<AppRoutes />
|
<SettingsPage open={settingsOpen} onClose={() => setSettingsOpen(false)} />
|
||||||
</HashRouter>
|
|
||||||
|
{/* 页面调度器 — 监听 OPEN_PAGE 事件,根据 modalType 渲染 Modal/Drawer/FloatingPanel */}
|
||||||
|
<PageDispatcher />
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,10 @@
|
|||||||
// AppProvider — 应用状态 Provider 组件
|
// AppProvider — 应用状态 Provider 组件
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { useState, useCallback, useEffect, type ReactNode } from 'react';
|
import { useState, useMemo, useCallback, useEffect, type ReactNode } from 'react';
|
||||||
import type { Platform, Edition } from '@shared/types';
|
import type { Platform, Edition } from '@shared/types';
|
||||||
|
|
||||||
import { getPlatform, isDev } from '@/utils/platform';
|
import { getPlatform, isDev } from '@/utils/platform';
|
||||||
import { parseEdition } from '@shared/constants/app';
|
|
||||||
import { safeIpcOn, safeIpcOff } from '@/utils/ipc';
|
import { safeIpcOn, safeIpcOff } from '@/utils/ipc';
|
||||||
import { AppContext } from '@/contexts/app-context';
|
import { AppContext } from '@/contexts/app-context';
|
||||||
import type { AppContextValue } from '@/contexts/app-context';
|
import type { AppContextValue } from '@/contexts/app-context';
|
||||||
@@ -30,12 +29,25 @@ interface AppProviderProps {
|
|||||||
|
|
||||||
export function AppProvider({ children }: AppProviderProps) {
|
export function AppProvider({ children }: AppProviderProps) {
|
||||||
const [platform] = useState<Platform>(getPlatform);
|
const [platform] = useState<Platform>(getPlatform);
|
||||||
const [edition] = useState<Edition>(() => {
|
|
||||||
return parseEdition(import.meta.env.VITE_EDITION);
|
|
||||||
});
|
|
||||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||||
const [user, setUser] = useState<LoginResponseBody | null>(null);
|
const [user, setUser] = useState<LoginResponseBody | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* edition 从登录用户的 account_type 派生(运行时判断,无需构建变量)
|
||||||
|
*
|
||||||
|
* 映射关系:
|
||||||
|
* "individual" → personal ← 个人用户
|
||||||
|
* "company" | "employee" → enterprise ← 企业用户
|
||||||
|
* null(未登录) → personal ← 默认最小功能集
|
||||||
|
*
|
||||||
|
* 安全性:edition 是 useMemo 派生值,不可独立赋值;
|
||||||
|
* 不写入 localStorage,重启/登出后回退默认值,必须重新登录才能确权。
|
||||||
|
*/
|
||||||
|
const edition: Edition = useMemo(() => {
|
||||||
|
if (!user) return 'personal';
|
||||||
|
return user.account_type === 'individual' ? 'personal' : 'enterprise';
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
// ---------- 登录 / 退出 ----------
|
// ---------- 登录 / 退出 ----------
|
||||||
|
|
||||||
const login = useCallback(async (auth: LoginResponseBody) => {
|
const login = useCallback(async (auth: LoginResponseBody) => {
|
||||||
|
|||||||
@@ -1,21 +1,24 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// Layout — 页面布局壳(NavBar + 页面内容 Outlet)
|
// Layout — 页面布局壳(Banner轮播 + NavBar + 页面内容)
|
||||||
|
// BannerCarousel 始终渲染(当前仅有首页,后续多面板切换时 Banner 始终保持)
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { Outlet } from 'react-router-dom';
|
import type { ReactNode } from 'react';
|
||||||
import { theme as antTheme } from 'antd';
|
import { theme as antTheme } from 'antd';
|
||||||
import { NavBar } from './navbar';
|
import { NavBar } from './navbar';
|
||||||
|
import { BannerCarousel } from '@/pages/home/components/BannerCarousel';
|
||||||
|
|
||||||
export function Layout() {
|
export function Layout({ children }: { children: ReactNode }) {
|
||||||
const { token } = antTheme.useToken();
|
const { token } = antTheme.useToken();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="min-h-screen flex flex-col transition-colors duration-300"
|
className="h-screen flex flex-col transition-colors duration-300"
|
||||||
style={{ background: token.colorBgLayout }}
|
style={{ background: token.colorBgLayout }}
|
||||||
>
|
>
|
||||||
|
<BannerCarousel />
|
||||||
<NavBar />
|
<NavBar />
|
||||||
<Outlet />
|
{children}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
154
src/components/PageDispatcher.tsx
Normal file
154
src/components/PageDispatcher.tsx
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
// ============================================================
|
||||||
|
// PageDispatcher — 页面事件调度器
|
||||||
|
//
|
||||||
|
// 监听 EVENTS.OPEN_PAGE,根据 modalType 渲染对应容器:
|
||||||
|
// - modal → antd Modal(居中模态,有遮罩阻断交互)
|
||||||
|
// - drawer → antd Drawer(侧滑抽屉)
|
||||||
|
// - floating → FloatingPanel(非模态浮动面板,可拖拽,不阻断交互)
|
||||||
|
//
|
||||||
|
// 支持多面板共存(floating 类型可同时打开多个)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import {useState, useEffect, useCallback, useRef, type ComponentType} from 'react';
|
||||||
|
import {Modal, Drawer} from 'antd';
|
||||||
|
import {on, off, EVENTS} from '@/utils/event-bus';
|
||||||
|
import {FloatingPanel} from '@/components/common/FloatingPanel';
|
||||||
|
import {ComplianceAssetsPage} from '@/pages/compliance-assets/ComplianceAssetsPage';
|
||||||
|
import {AccountPage} from '@/pages/account/AccountPage';
|
||||||
|
import {VipPage} from '@/pages/vip/VipPage';
|
||||||
|
import {RechargePage} from '@/pages/recharge/RechargePage';
|
||||||
|
import {BillingPage} from '@/pages/billing/BillingPage';
|
||||||
|
import {OrdersPage} from '@/pages/orders/OrdersPage';
|
||||||
|
import {ProjectsPage} from '@/pages/projects/ProjectsPage';
|
||||||
|
import {QuotaPage} from '@/pages/quota/QuotaPage';
|
||||||
|
import {WechatWorkPage} from '@/pages/wechat-work/WechatWorkPage';
|
||||||
|
|
||||||
|
// ---------- 类型 ----------
|
||||||
|
|
||||||
|
type ModalType = 'modal' | 'drawer' | 'floating';
|
||||||
|
|
||||||
|
interface PageEventPayload {
|
||||||
|
target: string;
|
||||||
|
modalType: ModalType;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ActivePanel {
|
||||||
|
id: string;
|
||||||
|
target: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- target → 页面组件映射 ----------
|
||||||
|
|
||||||
|
const PAGE_MAP: Record<string, ComponentType> = {
|
||||||
|
'/compliance-assets': ComplianceAssetsPage,
|
||||||
|
'/account': AccountPage,
|
||||||
|
'/vip': VipPage,
|
||||||
|
'/recharge': RechargePage,
|
||||||
|
'/billing': BillingPage,
|
||||||
|
'/orders': OrdersPage,
|
||||||
|
'/projects': ProjectsPage,
|
||||||
|
'/quota': QuotaPage,
|
||||||
|
'/wechat-work': WechatWorkPage,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function PageDispatcher() {
|
||||||
|
// 单实例(modal / drawer)—— 同一时间只有一个
|
||||||
|
const [singleton, setSingleton] = useState<PageEventPayload | null>(null);
|
||||||
|
|
||||||
|
// 浮动面板列表(支持多个同时打开)
|
||||||
|
const [floatingPanels, setFloatingPanels] = useState<ActivePanel[]>([]);
|
||||||
|
const nextIdRef = useRef(0);
|
||||||
|
|
||||||
|
// 监听 OPEN_PAGE 事件
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (payload: unknown) => {
|
||||||
|
const {target, modalType, label} = payload as PageEventPayload;
|
||||||
|
|
||||||
|
if (!target || !PAGE_MAP[target]) {
|
||||||
|
console.warn(`[PageDispatcher] 未找到页面组件: ${target}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (modalType === 'floating') {
|
||||||
|
// 浮动面板:追加到列表
|
||||||
|
const id = `fp-${nextIdRef.current++}`;
|
||||||
|
setFloatingPanels((prev) => [...prev, {id, target, label}]);
|
||||||
|
} else {
|
||||||
|
// modal / drawer:单实例,覆盖之前的
|
||||||
|
setSingleton({target, modalType, label});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
on(EVENTS.OPEN_PAGE, handler);
|
||||||
|
return () => off(EVENTS.OPEN_PAGE, handler);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 关闭单实例
|
||||||
|
const closeSingleton = useCallback(() => {
|
||||||
|
setSingleton(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 关闭指定浮动面板
|
||||||
|
const closeFloating = useCallback((id: string) => {
|
||||||
|
setFloatingPanels((prev) => prev.filter((p) => p.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 单实例对应的页面组件
|
||||||
|
const SingletonPage = singleton ? PAGE_MAP[singleton.target] : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* ======== Modal ======== */}
|
||||||
|
{singleton?.modalType === 'modal' && SingletonPage && (
|
||||||
|
<Modal
|
||||||
|
open
|
||||||
|
centered
|
||||||
|
title={singleton.label}
|
||||||
|
onCancel={closeSingleton}
|
||||||
|
footer={null}
|
||||||
|
destroyOnHidden={true}
|
||||||
|
mask={{
|
||||||
|
closable: true,
|
||||||
|
}}
|
||||||
|
width={640}
|
||||||
|
>
|
||||||
|
<SingletonPage />
|
||||||
|
</Modal>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ======== Drawer ======== */}
|
||||||
|
{singleton?.modalType === 'drawer' && SingletonPage && (
|
||||||
|
<Drawer
|
||||||
|
open
|
||||||
|
title={singleton.label}
|
||||||
|
onClose={closeSingleton}
|
||||||
|
destroyOnHidden={true}
|
||||||
|
size={480}
|
||||||
|
>
|
||||||
|
<SingletonPage />
|
||||||
|
</Drawer>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ======== Floating Panels ======== */}
|
||||||
|
{floatingPanels.map((panel) => {
|
||||||
|
const PageContent = PAGE_MAP[panel.target];
|
||||||
|
if (!PageContent) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FloatingPanel
|
||||||
|
key={panel.id}
|
||||||
|
open
|
||||||
|
title={panel.label}
|
||||||
|
onClose={() => closeFloating(panel.id)}
|
||||||
|
>
|
||||||
|
<PageContent />
|
||||||
|
</FloatingPanel>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, type ReactNode } from 'react';
|
import { useState, useEffect, useCallback, type ReactNode } from 'react';
|
||||||
import { ConfigProvider } from 'antd';
|
import { ConfigProvider } from 'antd';
|
||||||
|
import zhCN from 'antd/locale/zh_CN';
|
||||||
|
|
||||||
import { getThemeConfig } from '../theme/antd-theme';
|
import { getThemeConfig } from '../theme/antd-theme';
|
||||||
import {
|
import {
|
||||||
@@ -66,7 +67,7 @@ export function ThemeProvider({ children }: ThemeProviderProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ThemeContext.Provider value={ctx}>
|
<ThemeContext.Provider value={ctx}>
|
||||||
<ConfigProvider theme={getThemeConfig(isDark)}>{children}</ConfigProvider>
|
<ConfigProvider theme={getThemeConfig(isDark)} locale={zhCN}>{children}</ConfigProvider>
|
||||||
</ThemeContext.Provider>
|
</ThemeContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
215
src/components/common/FloatingPanel.tsx
Normal file
215
src/components/common/FloatingPanel.tsx
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
// ============================================================
|
||||||
|
// FloatingPanel — 非模态可拖拽浮动面板
|
||||||
|
//
|
||||||
|
// 特性:
|
||||||
|
// - 标题栏拖拽移动,无遮罩,不阻断主页面交互
|
||||||
|
// - 初始居中定位,支持暗色主题
|
||||||
|
// - 边界检测(不拖出视口)
|
||||||
|
// - 多个面板可同时打开(点击置顶)
|
||||||
|
// - 关闭按钮 + 最小尺寸约束
|
||||||
|
//
|
||||||
|
// 对应 QT 原版"非模态窗口"的 Web 映射
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react';
|
||||||
|
import { useTheme } from '@/hooks/use-theme';
|
||||||
|
|
||||||
|
// ---------- 类型 ----------
|
||||||
|
|
||||||
|
export interface FloatingPanelProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
title: string;
|
||||||
|
children: ReactNode;
|
||||||
|
/** 初始宽度(px),默认 480 */
|
||||||
|
width?: number;
|
||||||
|
/** 初始高度(px),默认 360 */
|
||||||
|
height?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 全局 z-index 管理 ----------
|
||||||
|
|
||||||
|
let globalZIndex = 1000;
|
||||||
|
function nextZIndex(): number {
|
||||||
|
globalZIndex += 1;
|
||||||
|
return globalZIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function FloatingPanel({ open, onClose, title, children, width = 480, height = 360 }: FloatingPanelProps) {
|
||||||
|
const { isDark } = useTheme();
|
||||||
|
|
||||||
|
// 位置与尺寸
|
||||||
|
const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
|
||||||
|
const [zIndex, setZIndex] = useState(() => nextZIndex());
|
||||||
|
const panelRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// 拖拽状态
|
||||||
|
const draggingRef = useRef(false);
|
||||||
|
const dragStartRef = useRef({ x: 0, y: 0, panelX: 0, panelY: 0 });
|
||||||
|
|
||||||
|
// 初始居中(首次 open 时计算)
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && position === null) {
|
||||||
|
const x = Math.max(0, (window.innerWidth - width) / 2);
|
||||||
|
const y = Math.max(0, (window.innerHeight - height) / 2);
|
||||||
|
setPosition({ x, y });
|
||||||
|
}
|
||||||
|
}, [open, position, width, height]);
|
||||||
|
|
||||||
|
// 拖拽启动
|
||||||
|
const handleMouseDown = useCallback(
|
||||||
|
(e: React.MouseEvent) => {
|
||||||
|
// 仅标题栏区域可拖拽
|
||||||
|
if ((e.target as HTMLElement).closest('.fp-close-btn')) return;
|
||||||
|
e.preventDefault();
|
||||||
|
draggingRef.current = true;
|
||||||
|
dragStartRef.current = {
|
||||||
|
x: e.clientX,
|
||||||
|
y: e.clientY,
|
||||||
|
panelX: position?.x ?? 0,
|
||||||
|
panelY: position?.y ?? 0,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
[position],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 全局 mousemove / mouseup
|
||||||
|
useEffect(() => {
|
||||||
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
|
if (!draggingRef.current) return;
|
||||||
|
const ds = dragStartRef.current;
|
||||||
|
const newX = ds.panelX + (e.clientX - ds.x);
|
||||||
|
const newY = ds.panelY + (e.clientY - ds.y);
|
||||||
|
|
||||||
|
// 边界约束:保留标题栏至少 40px 可见,确保用户能拖回
|
||||||
|
const minVisible = 40;
|
||||||
|
const maxX = window.innerWidth - minVisible;
|
||||||
|
const maxY = window.innerHeight - minVisible;
|
||||||
|
|
||||||
|
setPosition({
|
||||||
|
x: Math.max(-width + minVisible, Math.min(maxX, newX)),
|
||||||
|
y: Math.max(0, Math.min(maxY, newY)),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseUp = () => {
|
||||||
|
draggingRef.current = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousemove', handleMouseMove);
|
||||||
|
document.addEventListener('mouseup', handleMouseUp);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousemove', handleMouseMove);
|
||||||
|
document.removeEventListener('mouseup', handleMouseUp);
|
||||||
|
};
|
||||||
|
}, [width]);
|
||||||
|
|
||||||
|
// 点击面板 → 置顶
|
||||||
|
const bringToFront = useCallback(() => {
|
||||||
|
setZIndex(nextZIndex());
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!open || !position) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={panelRef}
|
||||||
|
onMouseDown={bringToFront}
|
||||||
|
className="fp-panel"
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
left: position.x,
|
||||||
|
top: position.y,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
zIndex,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
borderRadius: 8,
|
||||||
|
boxShadow: isDark
|
||||||
|
? '0 8px 32px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.08)'
|
||||||
|
: '0 8px 32px rgba(0,0,0,0.15), 0 0 0 1px rgba(0,0,0,0.06)',
|
||||||
|
background: isDark ? '#1E1B4B' : '#FFFFFF',
|
||||||
|
overflow: 'hidden',
|
||||||
|
userSelect: 'none',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 标题栏 — 拖拽手柄 */}
|
||||||
|
<div
|
||||||
|
onMouseDown={handleMouseDown}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
padding: '0 12px 0 16px',
|
||||||
|
height: 40,
|
||||||
|
flexShrink: 0,
|
||||||
|
cursor: 'grab',
|
||||||
|
background: isDark
|
||||||
|
? 'linear-gradient(180deg, #2E2A5A 0%, #252050 100%)'
|
||||||
|
: 'linear-gradient(180deg, #F5F3FF 0%, #EEF2FF 100%)',
|
||||||
|
borderBottom: `1px solid ${isDark ? '#3E3A6A' : '#E5E7EB'}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 13,
|
||||||
|
fontWeight: 600,
|
||||||
|
color: isDark ? '#E8E6F0' : '#1E1B4B',
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<button
|
||||||
|
className="fp-close-btn"
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
title="关闭"
|
||||||
|
style={{
|
||||||
|
width: 28,
|
||||||
|
height: 28,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 4,
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: 16,
|
||||||
|
color: isDark ? '#A5A3C0' : '#9CA3AF',
|
||||||
|
background: 'transparent',
|
||||||
|
transition: 'all 0.15s',
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
e.currentTarget.style.background = isDark ? 'rgba(239,68,68,0.2)' : 'rgba(239,68,68,0.1)';
|
||||||
|
e.currentTarget.style.color = '#EF4444';
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
e.currentTarget.style.background = 'transparent';
|
||||||
|
e.currentTarget.style.color = isDark ? '#A5A3C0' : '#9CA3AF';
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 内容区 */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
overflow: 'auto',
|
||||||
|
userSelect: 'text',
|
||||||
|
padding: 16,
|
||||||
|
color: isDark ? '#E8E6F0' : '#1E1B4B',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
// 数据来源:GET /api/v1/announcements
|
// 数据来源:GET /api/v1/announcements
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react';
|
import {useEffect, useState, useCallback} from 'react';
|
||||||
import { Drawer, Card, Typography, Empty, Tag, Spin, Modal, Tooltip } from 'antd';
|
import {Drawer, Card, Typography, Empty, Tag, Spin, Modal, Tooltip} from 'antd';
|
||||||
import { NotificationOutlined } from '@ant-design/icons';
|
import {NotificationOutlined} from '@ant-design/icons';
|
||||||
|
|
||||||
import { fetchAnnouncements, type Announcement } from '@/services/modules';
|
import {fetchAnnouncements, type Announcement, AnnouncementListResponse} from '@/services/modules';
|
||||||
|
|
||||||
const { Text, Paragraph } = Typography;
|
const {Text, Paragraph} = Typography;
|
||||||
|
|
||||||
// ---------- 辅助 ----------
|
// ---------- 辅助 ----------
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ interface AnnouncementDrawerProps {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
|
export function AnnouncementDrawer({open, onClose}: AnnouncementDrawerProps) {
|
||||||
const [list, setList] = useState<Announcement[]>([]);
|
const [list, setList] = useState<Announcement[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -64,9 +64,8 @@ export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data = await fetchAnnouncements();
|
const data: AnnouncementListResponse = await fetchAnnouncements();
|
||||||
// 仅展示有效公告
|
setList(data.filter((item: Announcement) => item.is_active));
|
||||||
setList(data.filter((item) => item.is_active));
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError((err as Error).message || '加载公告失败');
|
setError((err as Error).message || '加载公告失败');
|
||||||
setList([]);
|
setList([]);
|
||||||
@@ -96,7 +95,7 @@ export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
|
|||||||
size={380}
|
size={380}
|
||||||
open={open}
|
open={open}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
styles={{ body: { padding: 0 } }}
|
styles={{body: {padding: 0}}}
|
||||||
>
|
>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center justify-center h-64">
|
<div className="flex items-center justify-center h-64">
|
||||||
@@ -112,7 +111,7 @@ export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-3 p-3">
|
<div className="flex flex-col gap-3 p-3">
|
||||||
{list.map((item) => (
|
{list.map((item:Announcement) => (
|
||||||
<Tooltip
|
<Tooltip
|
||||||
key={item.id}
|
key={item.id}
|
||||||
title={
|
title={
|
||||||
@@ -144,7 +143,7 @@ export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
|
|||||||
<Paragraph
|
<Paragraph
|
||||||
className="mb-2! text-xs"
|
className="mb-2! text-xs"
|
||||||
type="secondary"
|
type="secondary"
|
||||||
ellipsis={{ rows: 2 }}
|
ellipsis={{rows: 2}}
|
||||||
>
|
>
|
||||||
{item.content}
|
{item.content}
|
||||||
</Paragraph>
|
</Paragraph>
|
||||||
|
|||||||
@@ -7,30 +7,28 @@
|
|||||||
// - 登录/注册 与 退出登录 仍按登录状态互斥显示
|
// - 登录/注册 与 退出登录 仍按登录状态互斥显示
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { useState, useCallback, useMemo } from 'react';
|
import {useState, useCallback, useMemo} from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import {App} from 'antd';
|
||||||
import { App } from 'antd';
|
|
||||||
|
|
||||||
import { useAppContext } from '@/contexts/app-context';
|
import {useAppContext} from '@/contexts/app-context';
|
||||||
import { useTheme } from '@/hooks/use-theme';
|
import {useTheme} from '@/hooks/use-theme';
|
||||||
import { emit, EVENTS } from '@/utils/event-bus.ts';
|
import {emit, EVENTS} from '@/utils/event-bus.ts';
|
||||||
import { NavItem } from './NavItem';
|
import {NavItem} from './NavItem';
|
||||||
import { AnnouncementDrawer } from './AnnouncementDrawer';
|
import {AnnouncementDrawer} from './AnnouncementDrawer';
|
||||||
import { personalLeft, personalRight, enterpriseLeft, enterpriseRight } from './nav-config';
|
import {personalLeft, personalRight, enterpriseLeft, enterpriseRight} from './nav-config';
|
||||||
import type { NavItemConfig } from './types';
|
import type {NavItemConfig} from './types';
|
||||||
|
|
||||||
const NAVBAR_HEIGHT = 56;
|
const NAVBAR_HEIGHT = 56;
|
||||||
|
|
||||||
export function NavBar() {
|
export function NavBar() {
|
||||||
const { platform, edition, isLoggedIn, logout } = useAppContext();
|
const {platform, edition, isLoggedIn, logout} = useAppContext();
|
||||||
const { isDark } = useTheme();
|
const {isDark} = useTheme();
|
||||||
const { message } = App.useApp();
|
const {message} = App.useApp();
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
|
||||||
// 根据版本选择导航项
|
// 根据版本选择导航项
|
||||||
const { leftItems, rightItems } = useMemo(() => {
|
const {leftItems, rightItems} = useMemo(() => {
|
||||||
const isEnterprise = edition === 'enterprise';
|
const isEnterprise = edition === 'enterprise';
|
||||||
return {
|
return {
|
||||||
leftItems: isEnterprise ? enterpriseLeft : personalLeft,
|
leftItems: isEnterprise ? enterpriseLeft : personalLeft,
|
||||||
@@ -50,7 +48,7 @@ export function NavBar() {
|
|||||||
}),
|
}),
|
||||||
[leftItems, isLoggedIn],
|
[leftItems, isLoggedIn],
|
||||||
);
|
);
|
||||||
const visibleRight = useMemo(
|
const visibleRight: NavItemConfig[] = useMemo(
|
||||||
() =>
|
() =>
|
||||||
rightItems.filter((item) => {
|
rightItems.filter((item) => {
|
||||||
if (item.requireGuest && isLoggedIn) return false;
|
if (item.requireGuest && isLoggedIn) return false;
|
||||||
@@ -79,6 +77,10 @@ export function NavBar() {
|
|||||||
case 'button':
|
case 'button':
|
||||||
if (item.key === 'logout') {
|
if (item.key === 'logout') {
|
||||||
logout();
|
logout();
|
||||||
|
} else if (item.key === 'settings') {
|
||||||
|
emit(EVENTS.OPEN_SETTINGS);
|
||||||
|
} else if (item.key === 'auth') {
|
||||||
|
emit(EVENTS.SHOW_LOGIN);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -88,12 +90,13 @@ export function NavBar() {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'navigate':
|
case 'page':
|
||||||
case 'spa':
|
if (item.target) {
|
||||||
if (item.key === 'auth') {
|
emit(EVENTS.OPEN_PAGE, {
|
||||||
emit(EVENTS.SHOW_LOGIN);
|
target: item.target,
|
||||||
} else if (item.target) {
|
modalType: item.modalType ?? 'floating',
|
||||||
navigate(item.target);
|
label: item.label,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1 @@
|
|||||||
export { NavBar } from './NavBar';
|
export { NavBar } from './NavBar';
|
||||||
export { AnnouncementDrawer } from './AnnouncementDrawer';
|
|
||||||
export type { NavItemConfig, NavBarConfig, NavAction } from './types';
|
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ const personalLeft: NavItemConfig[] = [
|
|||||||
key: 'compliance-assets',
|
key: 'compliance-assets',
|
||||||
label: '合规素材库',
|
label: '合规素材库',
|
||||||
iconSrc: complianceAssetsSvg,
|
iconSrc: complianceAssetsSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/compliance-assets',
|
target: '/compliance-assets',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'left',
|
position: 'left',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -47,8 +48,9 @@ const personalRight: NavItemConfig[] = [
|
|||||||
key: 'account',
|
key: 'account',
|
||||||
label: '查帐户',
|
label: '查帐户',
|
||||||
iconSrc: accountSvg,
|
iconSrc: accountSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/account',
|
target: '/account',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireLogin: true,
|
requireLogin: true,
|
||||||
},
|
},
|
||||||
@@ -56,16 +58,18 @@ const personalRight: NavItemConfig[] = [
|
|||||||
key: 'vip-activate',
|
key: 'vip-activate',
|
||||||
label: '开会员/激活',
|
label: '开会员/激活',
|
||||||
iconSrc: membershipSvg,
|
iconSrc: membershipSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/vip',
|
target: '/vip',
|
||||||
|
modalType: 'modal',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'recharge-points',
|
key: 'recharge-points',
|
||||||
label: '充值积分',
|
label: '充值积分',
|
||||||
iconSrc: rechargeSvg,
|
iconSrc: rechargeSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/recharge',
|
target: '/recharge',
|
||||||
|
modalType: 'modal',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireLogin: true,
|
requireLogin: true,
|
||||||
},
|
},
|
||||||
@@ -73,8 +77,9 @@ const personalRight: NavItemConfig[] = [
|
|||||||
key: 'billing-history',
|
key: 'billing-history',
|
||||||
label: '消费记录',
|
label: '消费记录',
|
||||||
iconSrc: billingSvg,
|
iconSrc: billingSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/billing',
|
target: '/billing',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireLogin: true,
|
requireLogin: true,
|
||||||
},
|
},
|
||||||
@@ -82,8 +87,9 @@ const personalRight: NavItemConfig[] = [
|
|||||||
key: 'order-details',
|
key: 'order-details',
|
||||||
label: '订单明细',
|
label: '订单明细',
|
||||||
iconSrc: orderDetailsSvg,
|
iconSrc: orderDetailsSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/orders',
|
target: '/orders',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireLogin: true,
|
requireLogin: true,
|
||||||
},
|
},
|
||||||
@@ -91,24 +97,23 @@ const personalRight: NavItemConfig[] = [
|
|||||||
key: 'wechat-work',
|
key: 'wechat-work',
|
||||||
label: '企业微信',
|
label: '企业微信',
|
||||||
iconSrc: wechatWorkSvg,
|
iconSrc: wechatWorkSvg,
|
||||||
action: 'external',
|
action: 'page',
|
||||||
target: 'https://work.weixin.qq.com/',
|
target: '/wechat-work',
|
||||||
|
modalType: 'modal',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'settings',
|
key: 'settings',
|
||||||
label: '设置',
|
label: '设置',
|
||||||
iconSrc: settingsSvg,
|
iconSrc: settingsSvg,
|
||||||
action: 'navigate',
|
action: 'button',
|
||||||
target: '/settings',
|
|
||||||
position: 'right',
|
position: 'right',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'auth',
|
key: 'auth',
|
||||||
label: '登录/注册',
|
label: '登录/注册',
|
||||||
iconSrc: accountSvg,
|
iconSrc: accountSvg,
|
||||||
action: 'navigate',
|
action: 'button',
|
||||||
target: '/login',
|
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireGuest: true,
|
requireGuest: true,
|
||||||
},
|
},
|
||||||
@@ -132,16 +137,18 @@ const enterpriseLeft: NavItemConfig[] = [
|
|||||||
key: 'compliance-assets',
|
key: 'compliance-assets',
|
||||||
label: '合规素材库',
|
label: '合规素材库',
|
||||||
iconSrc: complianceAssetsSvg,
|
iconSrc: complianceAssetsSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/compliance-assets',
|
target: '/compliance-assets',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'left',
|
position: 'left',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'project-management',
|
key: 'project-management',
|
||||||
label: '项目管理',
|
label: '项目管理',
|
||||||
iconSrc: projectManagementSvg,
|
iconSrc: projectManagementSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/projects',
|
target: '/projects',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'left',
|
position: 'left',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -159,8 +166,9 @@ const enterpriseRight: NavItemConfig[] = [
|
|||||||
key: 'quota-check',
|
key: 'quota-check',
|
||||||
label: '查配额',
|
label: '查配额',
|
||||||
iconSrc: accountSvg,
|
iconSrc: accountSvg,
|
||||||
action: 'navigate',
|
action: 'page',
|
||||||
target: '/quota',
|
target: '/quota',
|
||||||
|
modalType: 'floating',
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireLogin: false,
|
requireLogin: false,
|
||||||
},
|
},
|
||||||
@@ -168,16 +176,14 @@ const enterpriseRight: NavItemConfig[] = [
|
|||||||
key: 'settings',
|
key: 'settings',
|
||||||
label: '设置',
|
label: '设置',
|
||||||
iconSrc: settingsSvg,
|
iconSrc: settingsSvg,
|
||||||
action: 'navigate',
|
action: 'button',
|
||||||
target: '/settings',
|
|
||||||
position: 'right',
|
position: 'right',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'auth',
|
key: 'auth',
|
||||||
label: '登录/注册',
|
label: '登录/注册',
|
||||||
iconSrc: accountSvg,
|
iconSrc: accountSvg,
|
||||||
action: 'navigate',
|
action: 'button',
|
||||||
target: '/login',
|
|
||||||
position: 'right',
|
position: 'right',
|
||||||
requireGuest: true,
|
requireGuest: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,10 +6,9 @@ import type { Edition } from '@shared/types';
|
|||||||
|
|
||||||
/** 导航项的行为类型 */
|
/** 导航项的行为类型 */
|
||||||
export type NavAction =
|
export type NavAction =
|
||||||
| 'navigate' // 新开窗口
|
| 'page' // 打开页面 Modal(携带 target 路径标识符,由事件总线分发)
|
||||||
| 'spa' // 单页应用内导航(当前窗口)
|
|
||||||
| 'drawer' // 侧拉抽屉(公告等)
|
| 'drawer' // 侧拉抽屉(公告等)
|
||||||
| 'button' // 纯按钮行为(退出登录)
|
| 'button' // 纯按钮行为(退出登录等)
|
||||||
| 'external'; // 外部链接
|
| 'external'; // 外部链接
|
||||||
|
|
||||||
/** 单个导航项配置 */
|
/** 单个导航项配置 */
|
||||||
@@ -24,6 +23,8 @@ export interface NavItemConfig {
|
|||||||
action: NavAction;
|
action: NavAction;
|
||||||
/** 点击回调 / 路由路径 / 外部 URL(取决于 action) */
|
/** 点击回调 / 路由路径 / 外部 URL(取决于 action) */
|
||||||
target?: string;
|
target?: string;
|
||||||
|
/** 窗口类型(仅 action='page' 时生效):modal 居中模态 | drawer 侧滑 | floating 非模态浮动面板 */
|
||||||
|
modalType?: 'modal' | 'drawer' | 'floating';
|
||||||
/** 仅在指定版本下显示 */
|
/** 仅在指定版本下显示 */
|
||||||
edition?: Edition | Edition[];
|
edition?: Edition | Edition[];
|
||||||
/** 仅已登录时显示 */
|
/** 仅已登录时显示 */
|
||||||
|
|||||||
43
src/contexts/home-context.ts
Normal file
43
src/contexts/home-context.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
// ============================================================
|
||||||
|
// HomeContext — 首页状态管理
|
||||||
|
// 管理:选中模型、任务分页、选中任务记录、刷新信号
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { createContext, useContext } from 'react';
|
||||||
|
import type { ModelsListResponseBody } from '@/services/modules/models';
|
||||||
|
import type { TaskInfoItemResponseBody } from '@/services/modules/task';
|
||||||
|
|
||||||
|
// ---------- Context 类型 ----------
|
||||||
|
|
||||||
|
export interface HomeContextValue {
|
||||||
|
/** 当前选中的模型 */
|
||||||
|
selectedModel: ModelsListResponseBody | null;
|
||||||
|
setSelectedModel: (model: ModelsListResponseBody | null) => void;
|
||||||
|
|
||||||
|
/** 任务记录分页 — 当前页码 */
|
||||||
|
taskPage: number;
|
||||||
|
/** 任务记录分页 — 每页条数 */
|
||||||
|
taskPageSize: number;
|
||||||
|
setTaskPage: (page: number) => void;
|
||||||
|
setTaskPageSize: (size: number) => void;
|
||||||
|
|
||||||
|
/** 当前选中的任务记录(用于右侧预览) */
|
||||||
|
selectedTask: TaskInfoItemResponseBody | null;
|
||||||
|
setSelectedTask: (task: TaskInfoItemResponseBody | null) => void;
|
||||||
|
|
||||||
|
/** 侧边栏折叠状态 */
|
||||||
|
isLeftCollapsed: boolean;
|
||||||
|
toggleLeftCollapsed: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const HomeContext = createContext<HomeContextValue | null>(null);
|
||||||
|
|
||||||
|
// ---------- Consumer Hook ----------
|
||||||
|
|
||||||
|
export function useHomeContext(): HomeContextValue {
|
||||||
|
const ctx = useContext(HomeContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error('useHomeContext() 必须在 <HomeProvider> 内部调用');
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
166
src/hooks/use-api.ts
Normal file
166
src/hooks/use-api.ts
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
// ============================================================
|
||||||
|
// use-api.ts — 业务 API Hook 集合
|
||||||
|
//
|
||||||
|
// 基于 useAsyncData / useAsyncMutation 封装各模块 API,
|
||||||
|
// 组件只需调用 Hook 获取 { data, loading, error } 三元组,
|
||||||
|
// 不再需要在组件内手写 useEffect + cancelled flag + useState。
|
||||||
|
//
|
||||||
|
// 每个 Hook 自动处理:
|
||||||
|
// - 登录状态门控(enabled: isLoggedIn)
|
||||||
|
// - 竞态条件
|
||||||
|
// - 错误日志
|
||||||
|
// - 用户可读错误信息(errorMessage)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import {useMemo} from 'react';
|
||||||
|
import {useAppContext} from '@/contexts/app-context';
|
||||||
|
import {
|
||||||
|
TaskAPI,
|
||||||
|
ModelAPI,
|
||||||
|
fetchBanners,
|
||||||
|
MODEL_CATEGORY_LABELS,
|
||||||
|
type TaskListRequestParams,
|
||||||
|
type TaskInfoItemResponseBody,
|
||||||
|
type CreatTaskRequestBody,
|
||||||
|
type ModelsListResponseBody,
|
||||||
|
type Banner,
|
||||||
|
type ModelCategory,
|
||||||
|
} from '@/services/modules';
|
||||||
|
import {useAsyncData, useAsyncMutation} from './use-async';
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Banner
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 首页轮播图数据 Hook */
|
||||||
|
export function useBannerList() {
|
||||||
|
const {isLoggedIn} = useAppContext();
|
||||||
|
|
||||||
|
return useAsyncData<Banner[]>(
|
||||||
|
fetchBanners,
|
||||||
|
[],
|
||||||
|
{enabled: isLoggedIn, label: 'banner-list'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 模型
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 模型列表数据 Hook(按类别分别请求后合并) */
|
||||||
|
export function useModelList() {
|
||||||
|
const {isLoggedIn} = useAppContext();
|
||||||
|
|
||||||
|
// 使用单个 fetcher 返回合并后的结果
|
||||||
|
const result = useAsyncData<ModelsListResponseBody[]>(
|
||||||
|
async () => {
|
||||||
|
const categories: ModelCategory[] = ["image_to_image", "text_to_image", "image_to_video", "text_to_audio"];
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
categories.map((category) =>
|
||||||
|
ModelAPI.fetchModels({
|
||||||
|
provider_name: '',
|
||||||
|
category,
|
||||||
|
page: 1,
|
||||||
|
page_size: 50,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const allModels: ModelsListResponseBody[] = [];
|
||||||
|
results.forEach((r) => {
|
||||||
|
if (r.status === 'fulfilled') {
|
||||||
|
allModels.push(...r.value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// 按优先级降序排列
|
||||||
|
allModels.sort((a, b) => b.priority - a.priority);
|
||||||
|
return allModels;
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
{enabled: isLoggedIn, label: 'model-list'},
|
||||||
|
);
|
||||||
|
|
||||||
|
// 按类别分组
|
||||||
|
const groupedModels = useMemo(() => {
|
||||||
|
const groups = new Map<string, ModelsListResponseBody[]>();
|
||||||
|
result.data?.forEach((model) => {
|
||||||
|
const cat = model.category_name || 'other';
|
||||||
|
if (!groups.has(cat)) groups.set(cat, []);
|
||||||
|
groups.get(cat)!.push(model);
|
||||||
|
});
|
||||||
|
return groups;
|
||||||
|
}, [result.data]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
/** 按类别分组后的模型 */
|
||||||
|
groupedModels,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 任务列表
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export interface UseTaskListParams {
|
||||||
|
/** 完整的 API 请求参数(由调用方根据 antd Table onChange 构建) */
|
||||||
|
requestParams: TaskListRequestParams;
|
||||||
|
/** 外部传入的刷新信号(任意变化触发重新请求) */
|
||||||
|
refreshSignal?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务列表 Hook(分页 + 筛选 + 排序)
|
||||||
|
*
|
||||||
|
* 调用方负责构建 TaskListRequestParams(包括 edition-aware 的 user_ids 逻辑),
|
||||||
|
* 本 Hook 仅负责数据获取、竞态控制、错误日志。
|
||||||
|
*/
|
||||||
|
export function useTaskList(params: UseTaskListParams) {
|
||||||
|
const {isLoggedIn} = useAppContext();
|
||||||
|
const {requestParams, refreshSignal = 0} = params;
|
||||||
|
|
||||||
|
return useAsyncData(
|
||||||
|
() => TaskAPI.getTaskList(requestParams),
|
||||||
|
[requestParams, refreshSignal],
|
||||||
|
{enabled: isLoggedIn, label: 'task-list'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 任务详情
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 任务详情 Hook(taskId 为 null 时不请求) */
|
||||||
|
export function useTaskDetail(taskId: string | null | undefined) {
|
||||||
|
const {isLoggedIn} = useAppContext();
|
||||||
|
|
||||||
|
return useAsyncData<TaskInfoItemResponseBody>(
|
||||||
|
() => TaskAPI.getTaskInfo(taskId!),
|
||||||
|
[taskId],
|
||||||
|
{enabled: isLoggedIn && !!taskId, label: 'task-detail'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 提交任务
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 提交任务 Mutation Hook */
|
||||||
|
export function useSubmitTask(options?: {
|
||||||
|
onSuccess?: (data: TaskInfoItemResponseBody) => void;
|
||||||
|
onError?: (err: Error) => void;
|
||||||
|
}) {
|
||||||
|
return useAsyncMutation<TaskInfoItemResponseBody, [CreatTaskRequestBody]>(
|
||||||
|
(body) => TaskAPI.submitTask(body),
|
||||||
|
{
|
||||||
|
label: 'submit-task',
|
||||||
|
onSuccess: options?.onSuccess,
|
||||||
|
onError: options?.onError,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 重新导出类型和工具 ----------
|
||||||
|
|
||||||
|
export {MODEL_CATEGORY_LABELS};
|
||||||
|
export type {ModelCategory, ModelsListResponseBody, TaskInfoItemResponseBody, Banner};
|
||||||
254
src/hooks/use-async.ts
Normal file
254
src/hooks/use-async.ts
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
// ============================================================
|
||||||
|
// useAsyncData / useAsyncMutation — 通用异步数据 Hook
|
||||||
|
//
|
||||||
|
// 职责:
|
||||||
|
// - 自动竞态处理(仅应用最后一次请求的结果)
|
||||||
|
// - 自动错误日志记录
|
||||||
|
// - RequestErrorType → 用户可读错误信息映射
|
||||||
|
// - 为 use-api.ts 提供基础设施
|
||||||
|
//
|
||||||
|
// 用法:
|
||||||
|
// const { data, loading, error, refetch } = useAsyncData(
|
||||||
|
// () => TaskAPI.getTaskList(params),
|
||||||
|
// [page, pageSize],
|
||||||
|
// { enabled: isLoggedIn },
|
||||||
|
// );
|
||||||
|
//
|
||||||
|
// const { execute, loading, error } = useAsyncMutation(
|
||||||
|
// (body) => TaskAPI.submitTask(body),
|
||||||
|
// { onSuccess: () => refetchTasks() },
|
||||||
|
// );
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
|
import { RequestError, RequestErrorType } from '@/services/types';
|
||||||
|
import { logger } from '@/utils/logger';
|
||||||
|
|
||||||
|
// ---------- 错误信息映射 ----------
|
||||||
|
|
||||||
|
/** RequestErrorType → 用户可读的默认错误信息 */
|
||||||
|
export function getErrorMessage(err: unknown): string {
|
||||||
|
if (err instanceof RequestError) {
|
||||||
|
switch (err.type) {
|
||||||
|
case RequestErrorType.NETWORK:
|
||||||
|
return '网络连接失败,请检查网络';
|
||||||
|
case RequestErrorType.TIMEOUT:
|
||||||
|
return '请求超时,请稍后重试';
|
||||||
|
case RequestErrorType.HTTP:
|
||||||
|
return err.message || '服务器响应异常';
|
||||||
|
case RequestErrorType.BUSINESS:
|
||||||
|
return err.message || '业务处理失败';
|
||||||
|
case RequestErrorType.CANCELLED:
|
||||||
|
return '请求已取消';
|
||||||
|
case RequestErrorType.AUTH_EXPIRED:
|
||||||
|
return '登录已过期,请重新登录';
|
||||||
|
default:
|
||||||
|
return err.message || '未知错误';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (err instanceof Error) {
|
||||||
|
return err.message || '发生未知错误';
|
||||||
|
}
|
||||||
|
return '发生未知错误';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- useAsyncData — 数据获取 ----------
|
||||||
|
|
||||||
|
export interface UseAsyncDataOptions {
|
||||||
|
/** 是否启用请求(false 时不触发 fetch,常用于登录后才请求) */
|
||||||
|
enabled?: boolean;
|
||||||
|
/** 请求标识(用于日志,如 'task-list'、'models') */
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseAsyncDataReturn<T> {
|
||||||
|
/** 响应数据 */
|
||||||
|
data: T | null;
|
||||||
|
/** 是否正在加载(含首次请求和后续刷新) */
|
||||||
|
loading: boolean;
|
||||||
|
/** 错误对象(RequestError 或普通 Error) */
|
||||||
|
error: Error | null;
|
||||||
|
/** 用户可读的错误信息 */
|
||||||
|
errorMessage: string | null;
|
||||||
|
/** 手动触发重新请求 */
|
||||||
|
refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用数据获取 Hook。
|
||||||
|
*
|
||||||
|
* - 当 `deps` 变化或 `refetch()` 调用时自动重新请求
|
||||||
|
* - 自动处理竞态条件(仅最后一次请求的结果生效)
|
||||||
|
* - `enabled: false` 时不发起请求(适用于需登录后请求的场景)
|
||||||
|
*/
|
||||||
|
export function useAsyncData<T>(
|
||||||
|
fetcher: () => Promise<T>,
|
||||||
|
deps: unknown[],
|
||||||
|
options: UseAsyncDataOptions = {},
|
||||||
|
): UseAsyncDataReturn<T> {
|
||||||
|
const { enabled = true, label } = options;
|
||||||
|
|
||||||
|
const [data, setData] = useState<T | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<Error | null>(null);
|
||||||
|
|
||||||
|
// 竞态计数器
|
||||||
|
const raceRef = useRef(0);
|
||||||
|
// 手动刷新触发器
|
||||||
|
const [refreshTick, setRefreshTick] = useState(0);
|
||||||
|
// 是否已挂载(避免 setState on unmounted)
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
|
||||||
|
const refetch = useCallback(() => {
|
||||||
|
setRefreshTick((t) => t + 1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => { mountedRef.current = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) {
|
||||||
|
setData(null);
|
||||||
|
setError(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raceId = ++raceRef.current;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await fetcher();
|
||||||
|
if (!cancelled && raceId === raceRef.current && mountedRef.current) {
|
||||||
|
setData(result);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!cancelled && raceId === raceRef.current && mountedRef.current) {
|
||||||
|
const normalized = err instanceof Error ? err : new Error(String(err));
|
||||||
|
setError(normalized);
|
||||||
|
// 仅在非取消、非认证过期时记录日志(取消是预期行为,认证过期由拦截器统一处理)
|
||||||
|
if (err instanceof RequestError) {
|
||||||
|
if (err.type !== RequestErrorType.CANCELLED && err.type !== RequestErrorType.AUTH_EXPIRED) {
|
||||||
|
logger.warn('request', `${label || 'fetch'} 请求失败`, normalized);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.warn('request', `${label || 'fetch'} 请求失败`, normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!cancelled && raceId === raceRef.current && mountedRef.current) {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void run();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [enabled, refreshTick, ...deps]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
errorMessage: error ? getErrorMessage(error) : null,
|
||||||
|
refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- useAsyncMutation — 数据变更 ----------
|
||||||
|
|
||||||
|
export interface UseAsyncMutationOptions<T, Args extends unknown[]> {
|
||||||
|
/** 请求标识(用于日志) */
|
||||||
|
label?: string;
|
||||||
|
/** 成功回调 */
|
||||||
|
onSuccess?: (data: T, ...args: Args) => void;
|
||||||
|
/** 失败回调 */
|
||||||
|
onError?: (err: Error, ...args: Args) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseAsyncMutationReturn<T, Args extends unknown[]> {
|
||||||
|
/** 执行变更 */
|
||||||
|
execute: (...args: Args) => Promise<T | undefined>;
|
||||||
|
/** 是否正在执行 */
|
||||||
|
loading: boolean;
|
||||||
|
/** 最近一次错误 */
|
||||||
|
error: Error | null;
|
||||||
|
/** 用户可读的错误信息 */
|
||||||
|
errorMessage: string | null;
|
||||||
|
/** 清除错误状态 */
|
||||||
|
reset: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用数据变更 Hook(POST / PUT / DELETE 等)。
|
||||||
|
*
|
||||||
|
* - 不自动执行,需手动调用 `execute()`
|
||||||
|
* - 返回 Promise,调用方可 await 获取结果
|
||||||
|
* - 自动错误日志记录
|
||||||
|
*/
|
||||||
|
export function useAsyncMutation<T, Args extends unknown[] = []>(
|
||||||
|
mutator: (...args: Args) => Promise<T>,
|
||||||
|
options: UseAsyncMutationOptions<T, Args> = {},
|
||||||
|
): UseAsyncMutationReturn<T, Args> {
|
||||||
|
const { label, onSuccess, onError } = options;
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<Error | null>(null);
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => { mountedRef.current = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const execute = useCallback(
|
||||||
|
async (...args: Args): Promise<T | undefined> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await mutator(...args);
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
onSuccess?.(result, ...args);
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
const normalized = err instanceof Error ? err : new Error(String(err));
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setError(normalized);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
if (err instanceof RequestError) {
|
||||||
|
if (err.type !== RequestErrorType.CANCELLED && err.type !== RequestErrorType.AUTH_EXPIRED) {
|
||||||
|
logger.warn('request', `${label || 'mutation'} 执行失败`, normalized);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.warn('request', `${label || 'mutation'} 执行失败`, normalized);
|
||||||
|
}
|
||||||
|
onError?.(normalized, ...args);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[mutator, label, onSuccess, onError],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reset = useCallback(() => {
|
||||||
|
setError(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
execute,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
errorMessage: error ? getErrorMessage(error) : null,
|
||||||
|
reset,
|
||||||
|
};
|
||||||
|
}
|
||||||
10
src/main.tsx
10
src/main.tsx
@@ -1,11 +1,11 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
import { App as AntdApp } from 'antd';
|
import {App as AntdApp} from 'antd';
|
||||||
|
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import { ThemeProvider } from './components/ThemeProvider';
|
import {ThemeProvider} from './components/ThemeProvider';
|
||||||
import { AppProvider } from './components/AppProvider';
|
import {AppProvider} from './components/AppProvider';
|
||||||
import { SettingsProvider } from './components/SettingsProvider';
|
import {SettingsProvider} from './components/SettingsProvider';
|
||||||
// 全局样式(包含 Tailwind 指令 + 主题扩展 + 重置)
|
// 全局样式(包含 Tailwind 指令 + 主题扩展 + 重置)
|
||||||
import './theme/globals.css';
|
import './theme/globals.css';
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ safeIpcOn('main-process-message', (_event: unknown, message: unknown) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 渲染进程全局未捕获错误(兜底记录到日志文件)
|
// 渲染进程全局未捕获错误(兜底记录到日志文件)
|
||||||
import { logger } from './utils/logger';
|
import {logger} from './utils/logger';
|
||||||
|
|
||||||
window.addEventListener('error', (event) => {
|
window.addEventListener('error', (event) => {
|
||||||
logger.error('ui', 'Uncaught error (renderer)', event.error, {
|
logger.error('ui', 'Uncaught error (renderer)', event.error, {
|
||||||
|
|||||||
11
src/pages/account/AccountPage.tsx
Normal file
11
src/pages/account/AccountPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// AccountPage — 查帐户(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function AccountPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>查帐户 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/pages/billing/BillingPage.tsx
Normal file
11
src/pages/billing/BillingPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// BillingPage — 消费记录(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function BillingPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>消费记录 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/pages/compliance-assets/ComplianceAssetsPage.tsx
Normal file
11
src/pages/compliance-assets/ComplianceAssetsPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ComplianceAssetsPage — 合规素材库(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function ComplianceAssetsPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>合规素材库 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
325
src/pages/home/HomeContent.tsx
Normal file
325
src/pages/home/HomeContent.tsx
Normal file
@@ -0,0 +1,325 @@
|
|||||||
|
// ============================================================
|
||||||
|
// HomeContent — 首页三列正文布局 + HomeProvider
|
||||||
|
// 可拖拽调整三栏宽度,所有数据请求在登录后发送
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
|
||||||
|
import { theme as antTheme, Empty } from 'antd';
|
||||||
|
|
||||||
|
import { HomeContext } from '@/contexts/home-context';
|
||||||
|
import { useAppContext } from '@/contexts/app-context';
|
||||||
|
import type { ModelsListResponseBody, TaskInfoItemResponseBody } from '@/services/modules';
|
||||||
|
import { LeftPanel } from './components/LeftPanel';
|
||||||
|
import { CenterPanel } from './components/CenterPanel';
|
||||||
|
import { RightPanel } from './components/RightPanel';
|
||||||
|
|
||||||
|
import { Typography } from 'antd';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
// ---------- 常量 ----------
|
||||||
|
|
||||||
|
/** 左列最小/默认宽度 */
|
||||||
|
const LEFT_MIN = 400;
|
||||||
|
const LEFT_DEFAULT = 750;
|
||||||
|
/** 右列最小/默认宽度 */
|
||||||
|
const RIGHT_MIN = 300;
|
||||||
|
const RIGHT_DEFAULT = 480;
|
||||||
|
/** 中列最小宽度 */
|
||||||
|
const CENTER_MIN = 300;
|
||||||
|
/** 拖拽分隔条宽度 */
|
||||||
|
const DIVIDER_WIDTH = 6;
|
||||||
|
/** 布局固定消耗:左右 padding(12*2) + 两个分隔条(6*2) */
|
||||||
|
const LAYOUT_OVERHEAD = 36; // 24 + 12
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function HomeContent() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
const { isLoggedIn } = useAppContext();
|
||||||
|
|
||||||
|
// ======== HomeContext 状态 ========
|
||||||
|
|
||||||
|
const [selectedModel, setSelectedModel] = useState<ModelsListResponseBody | null>(null);
|
||||||
|
const [selectedTask, setSelectedTask] = useState<TaskInfoItemResponseBody | null>(null);
|
||||||
|
const [taskPage, setTaskPage] = useState(1);
|
||||||
|
const [taskPageSize, setTaskPageSize] = useState(10);
|
||||||
|
const [isLeftCollapsed, setIsLeftCollapsed] = useState(false);
|
||||||
|
|
||||||
|
const toggleLeftCollapsed = useCallback(() => {
|
||||||
|
setIsLeftCollapsed((v) => !v);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSetSelectedModel = useCallback(
|
||||||
|
(model: ModelsListResponseBody | null) => {
|
||||||
|
setSelectedModel(model);
|
||||||
|
setSelectedTask(null);
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleSetSelectedTask = useCallback(
|
||||||
|
(task: TaskInfoItemResponseBody | null) => {
|
||||||
|
setSelectedTask(task);
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const contextValue = useMemo(() => ({
|
||||||
|
selectedModel,
|
||||||
|
setSelectedModel: handleSetSelectedModel,
|
||||||
|
taskPage,
|
||||||
|
taskPageSize,
|
||||||
|
setTaskPage,
|
||||||
|
setTaskPageSize,
|
||||||
|
selectedTask,
|
||||||
|
setSelectedTask: handleSetSelectedTask,
|
||||||
|
isLeftCollapsed,
|
||||||
|
toggleLeftCollapsed,
|
||||||
|
}), [
|
||||||
|
selectedModel,
|
||||||
|
handleSetSelectedModel,
|
||||||
|
taskPage,
|
||||||
|
taskPageSize,
|
||||||
|
selectedTask,
|
||||||
|
handleSetSelectedTask,
|
||||||
|
isLeftCollapsed,
|
||||||
|
toggleLeftCollapsed,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ======== 拖拽调整列宽 ========
|
||||||
|
|
||||||
|
const [leftWidth, setLeftWidth] = useState(LEFT_DEFAULT);
|
||||||
|
const [rightWidth, setRightWidth] = useState(RIGHT_DEFAULT);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// 拖拽状态
|
||||||
|
const [dragging, setDragging] = useState<'left' | 'right' | null>(null);
|
||||||
|
// 分隔条 hover 状态
|
||||||
|
const [hoveredDivider, setHoveredDivider] = useState<'left' | 'right' | null>(null);
|
||||||
|
const dragState = useRef<{
|
||||||
|
startX: number;
|
||||||
|
startWidth: number;
|
||||||
|
}>({ startX: 0, startWidth: 0 });
|
||||||
|
|
||||||
|
// 用 ref 追踪最新列宽,避免拖拽 mousemove 闭包中读到过期值
|
||||||
|
const leftWidthRef = useRef(leftWidth);
|
||||||
|
const rightWidthRef = useRef(rightWidth);
|
||||||
|
const draggingRef = useRef(dragging);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
leftWidthRef.current = leftWidth;
|
||||||
|
rightWidthRef.current = rightWidth;
|
||||||
|
draggingRef.current = dragging;
|
||||||
|
}, [leftWidth, rightWidth, dragging]);
|
||||||
|
|
||||||
|
const handleDividerMouseDown = (side: 'left' | 'right') => (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
// eslint-disable-next-line react-hooks/refs
|
||||||
|
dragState.current = { startX: e.clientX, startWidth: side === 'left' ? leftWidth : rightWidth };
|
||||||
|
setDragging(side);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
|
if (!dragging) return;
|
||||||
|
|
||||||
|
const containerEl = containerRef.current;
|
||||||
|
if (!containerEl) return;
|
||||||
|
const containerWidth = containerEl.clientWidth;
|
||||||
|
const ds = dragState.current;
|
||||||
|
const delta = e.clientX - ds.startX;
|
||||||
|
|
||||||
|
if (dragging === 'left') {
|
||||||
|
// 左列最大宽度 = 容器宽 - 固定消耗 - 中列最小宽 - 右列当前宽
|
||||||
|
// 确保中列至少保留 CENTER_MIN、右列不被挤出视口
|
||||||
|
const maxLeft = containerWidth - LAYOUT_OVERHEAD - CENTER_MIN - rightWidthRef.current;
|
||||||
|
const newWidth = Math.max(LEFT_MIN, Math.min(maxLeft, ds.startWidth + delta));
|
||||||
|
setLeftWidth(newWidth);
|
||||||
|
} else {
|
||||||
|
// 右列最大宽度同理:不能把中列挤到 CENTER_MIN 以下
|
||||||
|
const maxRight = containerWidth - LAYOUT_OVERHEAD - CENTER_MIN - leftWidthRef.current;
|
||||||
|
const newWidth = Math.max(RIGHT_MIN, Math.min(maxRight, ds.startWidth - delta));
|
||||||
|
setRightWidth(newWidth);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseUp = () => {
|
||||||
|
setDragging(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousemove', handleMouseMove);
|
||||||
|
document.addEventListener('mouseup', handleMouseUp);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousemove', handleMouseMove);
|
||||||
|
document.removeEventListener('mouseup', handleMouseUp);
|
||||||
|
};
|
||||||
|
}, [dragging]);
|
||||||
|
|
||||||
|
// ======== 视口缩小自动收窄面板 ========
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
// 拖拽中由 mousemove handler 处理约束,避免冲突
|
||||||
|
if (draggingRef.current) return;
|
||||||
|
|
||||||
|
const containerWidth = el.clientWidth;
|
||||||
|
const currentLeft = leftWidthRef.current;
|
||||||
|
const currentRight = rightWidthRef.current;
|
||||||
|
|
||||||
|
// 检查当前总宽度是否超出容器
|
||||||
|
const totalNeeded = currentLeft + LAYOUT_OVERHEAD + CENTER_MIN + currentRight;
|
||||||
|
if (totalNeeded <= containerWidth) return;
|
||||||
|
|
||||||
|
// 超出容器 → 优先收缩右侧面板,再收左侧
|
||||||
|
const deficit = totalNeeded - containerWidth;
|
||||||
|
const rightSlack = currentRight - RIGHT_MIN;
|
||||||
|
|
||||||
|
if (rightSlack >= deficit) {
|
||||||
|
setRightWidth(currentRight - deficit);
|
||||||
|
} else {
|
||||||
|
setRightWidth(RIGHT_MIN);
|
||||||
|
const remainingDeficit = deficit - rightSlack;
|
||||||
|
setLeftWidth(Math.max(LEFT_MIN, currentLeft - remainingDeficit));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
observer.observe(el);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ======== 分隔条样式工厂 ========
|
||||||
|
|
||||||
|
const dividerStyle = (side: 'left' | 'right'): React.CSSProperties => {
|
||||||
|
const isActive = dragging === side;
|
||||||
|
const isHovered = hoveredDivider === side;
|
||||||
|
return {
|
||||||
|
width: DIVIDER_WIDTH,
|
||||||
|
flexShrink: 0,
|
||||||
|
cursor: 'col-resize',
|
||||||
|
background: isActive
|
||||||
|
? token.colorPrimary
|
||||||
|
: isHovered
|
||||||
|
? `${token.colorPrimary}60`
|
||||||
|
: token.colorBorderSecondary,
|
||||||
|
position: 'relative' as const,
|
||||||
|
zIndex: 10,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
transition: 'background 0.2s ease',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ======== 未登录提示 ========
|
||||||
|
|
||||||
|
if (!isLoggedIn) {
|
||||||
|
return (
|
||||||
|
<HomeContext.Provider value={contextValue}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
flex: 1,
|
||||||
|
background: token.colorBgLayout,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Empty
|
||||||
|
description={
|
||||||
|
<Text type="secondary">
|
||||||
|
请先登录后再使用首页功能
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</HomeContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ======== 三列布局(可拖拽) ========
|
||||||
|
|
||||||
|
return (
|
||||||
|
<HomeContext.Provider value={contextValue}>
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
padding: 12,
|
||||||
|
gap: 0,
|
||||||
|
flex: 1,
|
||||||
|
overflow: 'hidden',
|
||||||
|
background: token.colorBgLayout,
|
||||||
|
cursor: !!dragging ? 'col-resize' : undefined,
|
||||||
|
userSelect: !!dragging ? 'none' : undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 左列 */}
|
||||||
|
{!isLeftCollapsed && (
|
||||||
|
<>
|
||||||
|
<div style={{ width: leftWidth, overflow: 'hidden', flexShrink: 0 }}>
|
||||||
|
<LeftPanel />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 左分隔条 */}
|
||||||
|
<div
|
||||||
|
onMouseDown={handleDividerMouseDown('left')}
|
||||||
|
style={dividerStyle('left')}
|
||||||
|
onMouseEnter={() => setHoveredDivider('left')}
|
||||||
|
onMouseLeave={() => setHoveredDivider(null)}
|
||||||
|
>
|
||||||
|
{/* 拖拽手柄竖线 */}
|
||||||
|
<div style={{
|
||||||
|
width: 2,
|
||||||
|
height: 32,
|
||||||
|
borderRadius: 1,
|
||||||
|
background: dragging === 'left'
|
||||||
|
? '#fff'
|
||||||
|
: hoveredDivider === 'left'
|
||||||
|
? token.colorPrimary
|
||||||
|
: token.colorBorder,
|
||||||
|
transition: 'background 0.2s ease',
|
||||||
|
}} />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 中列 */}
|
||||||
|
<div style={{ flex: 1, overflow: 'hidden', minWidth: CENTER_MIN }}>
|
||||||
|
<CenterPanel />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 右分隔条 */}
|
||||||
|
<div
|
||||||
|
onMouseDown={handleDividerMouseDown('right')}
|
||||||
|
style={dividerStyle('right')}
|
||||||
|
onMouseEnter={() => setHoveredDivider('right')}
|
||||||
|
onMouseLeave={() => setHoveredDivider(null)}
|
||||||
|
>
|
||||||
|
{/* 拖拽手柄竖线 */}
|
||||||
|
<div style={{
|
||||||
|
width: 2,
|
||||||
|
height: 32,
|
||||||
|
borderRadius: 1,
|
||||||
|
background: dragging === 'right'
|
||||||
|
? '#fff'
|
||||||
|
: hoveredDivider === 'right'
|
||||||
|
? token.colorPrimary
|
||||||
|
: token.colorBorder,
|
||||||
|
transition: 'background 0.2s ease',
|
||||||
|
}} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 右列 */}
|
||||||
|
<div style={{ width: rightWidth, overflow: 'hidden', flexShrink: 0 }}>
|
||||||
|
<RightPanel />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</HomeContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,277 +1,14 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// HomePage — 首页仪表盘(从 App.tsx 提取)
|
// HomePage — 首页(业务入口)
|
||||||
|
// 组合:BannerCarousel(在 Layout 中)+ HomeContent(三列正文)
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { HomeContent } from './HomeContent';
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
Space,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
Switch as AntSwitch,
|
|
||||||
Slider,
|
|
||||||
Progress,
|
|
||||||
theme as antTheme,
|
|
||||||
} from 'antd';
|
|
||||||
import {
|
|
||||||
ApiOutlined,
|
|
||||||
ThunderboltOutlined,
|
|
||||||
BulbOutlined,
|
|
||||||
BulbFilled,
|
|
||||||
DownloadOutlined,
|
|
||||||
SyncOutlined,
|
|
||||||
CheckCircleOutlined,
|
|
||||||
ExclamationCircleOutlined,
|
|
||||||
RocketOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
|
|
||||||
import { getPlatformName, isDev } from '@/utils/platform';
|
|
||||||
import { gradientPrimary } from '@/theme/tokens';
|
|
||||||
import { useTheme } from '@/hooks/use-theme';
|
|
||||||
import { useUpdater } from '@/hooks/use-updater';
|
|
||||||
import { useAppContext } from '@/contexts/app-context';
|
|
||||||
|
|
||||||
const { Title, Text } = Typography;
|
|
||||||
|
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
const { isDark, toggleTheme } = useTheme();
|
|
||||||
const { platform, edition, isLoggedIn, logout } = useAppContext();
|
|
||||||
const { token } = antTheme.useToken();
|
|
||||||
const [progress, setProgress] = useState(65);
|
|
||||||
const {
|
|
||||||
status: updateStatus,
|
|
||||||
progress: updateProgress,
|
|
||||||
info: updateInfo,
|
|
||||||
error: updateError,
|
|
||||||
checkForUpdates,
|
|
||||||
installUpdate,
|
|
||||||
} = useUpdater();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 p-8">
|
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
|
||||||
<div className="mx-auto max-w-4xl space-y-6">
|
<HomeContent />
|
||||||
{/* ---- 标题区 + 主题开关 ---- */}
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<div className="flex items-center justify-center gap-4">
|
|
||||||
<Title level={1} className="mb-0! gradient-primary-text">
|
|
||||||
HeiXiu · 桌面工作台
|
|
||||||
</Title>
|
|
||||||
<AntSwitch
|
|
||||||
checked={isDark}
|
|
||||||
onChange={toggleTheme}
|
|
||||||
checkedChildren={<BulbFilled />}
|
|
||||||
unCheckedChildren={<BulbOutlined />}
|
|
||||||
title={isDark ? '切换亮色模式' : '切换暗色模式'}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Text type="secondary">
|
|
||||||
Electron + React 19 + TypeScript + Ant Design + Tailwind CSS
|
|
||||||
</Text>
|
|
||||||
<br />
|
|
||||||
<Space size={4}>
|
|
||||||
<Tag color={isDark ? 'blue' : 'purple'}>
|
|
||||||
{isDark ? '🌙 暗色' : '☀️ 亮色'}
|
|
||||||
</Tag>
|
|
||||||
<Tag color={edition === 'enterprise' ? 'gold' : 'green'}>
|
|
||||||
{edition === 'enterprise' ? '企业版' : '个人版'}
|
|
||||||
</Tag>
|
|
||||||
{isLoggedIn ? (
|
|
||||||
<>
|
|
||||||
<Tag color="blue">已登录</Tag>
|
|
||||||
<Button size="small" type="link" danger onClick={logout}>
|
|
||||||
退出登录
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Tag color="default">未登录</Tag>
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ---- 导航栏状态提示 ---- */}
|
|
||||||
<Card size="small" variant="borderless" className="rounded-lg">
|
|
||||||
<Text type="secondary" className="text-xs">
|
|
||||||
💡 当前使用 <Text strong>H5 自定义导航栏</Text> 替代系统菜单。
|
|
||||||
{platform === 'darwin'
|
|
||||||
? ' macOS 保留了最小 Edit 菜单以支持 Cmd+C/V 等快捷键。'
|
|
||||||
: ' Windows/Linux 已完全移除系统菜单栏。'}
|
|
||||||
</Text>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* ---- 主题色预览 ---- */}
|
|
||||||
<Card
|
|
||||||
title="🎨 蓝紫渐变主题色预览"
|
|
||||||
variant="borderless"
|
|
||||||
className="rounded-lg shadow-lg"
|
|
||||||
>
|
|
||||||
<Space orientation="vertical" size="large" className="w-full">
|
|
||||||
{/* 渐变展示 */}
|
|
||||||
<div>
|
|
||||||
<Text strong>品牌渐变</Text>
|
|
||||||
<div className="flex gap-3 mt-2">
|
|
||||||
<div
|
|
||||||
className="flex-1 h-16 rounded-lg flex items-center justify-center text-white font-medium shadow-md"
|
|
||||||
style={{ background: gradientPrimary }}
|
|
||||||
>
|
|
||||||
135° 渐变
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
className="flex-1 h-16 rounded-lg flex items-center justify-center text-white font-medium shadow-md"
|
|
||||||
style={{ background: 'linear-gradient(90deg, #4F46E5, #7C3AED)' }}
|
|
||||||
>
|
|
||||||
90° 渐变
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 组件示例 */}
|
|
||||||
<div>
|
|
||||||
<Text strong>Ant Design 组件</Text>
|
|
||||||
<Space wrap className="mt-2">
|
|
||||||
<Button type="primary" icon={<ThunderboltOutlined />}>
|
|
||||||
主按钮
|
|
||||||
</Button>
|
|
||||||
<Button>默认</Button>
|
|
||||||
<Button type="dashed">虚线</Button>
|
|
||||||
<Button type="text">文字</Button>
|
|
||||||
<Button type="link">链接</Button>
|
|
||||||
</Space>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 滑块 + 进度条 */}
|
|
||||||
<div>
|
|
||||||
<Text strong>交互组件</Text>
|
|
||||||
<div className="flex items-center gap-4 mt-2">
|
|
||||||
<span className="text-sm" style={{ color: token.colorTextSecondary }}>
|
|
||||||
进度:
|
|
||||||
</span>
|
|
||||||
<Slider
|
|
||||||
className="flex-1"
|
|
||||||
value={progress}
|
|
||||||
onChange={setProgress}
|
|
||||||
min={0}
|
|
||||||
max={100}
|
|
||||||
/>
|
|
||||||
<Progress
|
|
||||||
type="circle"
|
|
||||||
percent={progress}
|
|
||||||
size={48}
|
|
||||||
strokeColor={{ '0%': '#4F46E5', '100%': '#7C3AED' }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Space>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* ---- 平台信息 ---- */}
|
|
||||||
<Card title="🖥️ 系统信息" variant="borderless" className="rounded-lg shadow-lg">
|
|
||||||
<Space orientation="vertical" size="middle" className="w-full">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ApiOutlined style={{ color: token.colorPrimary }} />
|
|
||||||
<Text strong>运行平台:</Text>
|
|
||||||
<Tag color="purple">{getPlatformName()}</Tag>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ApiOutlined style={{ color: token.colorPrimary }} />
|
|
||||||
<Text strong>运行环境:</Text>
|
|
||||||
<Tag color={isDev() ? 'blue' : 'green'}>
|
|
||||||
{isDev() ? '开发模式' : '生产模式'}
|
|
||||||
</Tag>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ApiOutlined style={{ color: token.colorPrimary }} />
|
|
||||||
<Text strong>当前导航:</Text>
|
|
||||||
<Tag color="purple">
|
|
||||||
H5 自定义导航栏({edition === 'enterprise' ? '企业版' : '个人版'}
|
|
||||||
布局)
|
|
||||||
</Tag>
|
|
||||||
</div>
|
|
||||||
</Space>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* ---- 版本更新 ---- */}
|
|
||||||
<Card title="🔄 版本更新" variant="borderless" className="rounded-lg shadow-lg">
|
|
||||||
<Space orientation="vertical" size="middle" className="w-full">
|
|
||||||
{/* 状态提示 */}
|
|
||||||
{updateStatus === 'checking' && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<SyncOutlined spin style={{ color: token.colorPrimary }} />
|
|
||||||
<Text type="secondary">正在检查更新...</Text>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{updateStatus === 'no-update' && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<CheckCircleOutlined style={{ color: token.colorSuccess }} />
|
|
||||||
<Text type="success">已是最新版本</Text>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{updateStatus === 'error' && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ExclamationCircleOutlined style={{ color: token.colorError }} />
|
|
||||||
<Text type="danger">{updateError?.message || '检查更新失败'}</Text>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 发现新版本 */}
|
|
||||||
{(updateStatus === 'available' || updateStatus === 'downloading') && (
|
|
||||||
<>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<RocketOutlined style={{ color: token.colorPrimary }} />
|
|
||||||
<Text strong>发现新版本:{updateInfo?.version}</Text>
|
|
||||||
{updateInfo?.forceUpdate && <Tag color="red">强制更新</Tag>}
|
|
||||||
</div>
|
|
||||||
{updateInfo?.releaseNotes && (
|
|
||||||
<Text type="secondary" className="text-xs whitespace-pre-line">
|
|
||||||
{updateInfo.releaseNotes}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 下载进度 */}
|
|
||||||
{updateStatus === 'downloading' && (
|
|
||||||
<Progress
|
|
||||||
percent={updateProgress.percent}
|
|
||||||
strokeColor={{ '0%': '#4F46E5', '100%': '#7C3AED' }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 下载完成 */}
|
|
||||||
{updateStatus === 'downloaded' && (
|
|
||||||
<>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<CheckCircleOutlined style={{ color: token.colorSuccess }} />
|
|
||||||
<Text>更新已下载完毕,点击按钮安装并重启</Text>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon={<DownloadOutlined />}
|
|
||||||
onClick={installUpdate}
|
|
||||||
>
|
|
||||||
安装更新
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 操作按钮 */}
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button
|
|
||||||
icon={<SyncOutlined spin={updateStatus === 'checking'} />}
|
|
||||||
onClick={checkForUpdates}
|
|
||||||
disabled={updateStatus === 'checking'}
|
|
||||||
>
|
|
||||||
检查更新
|
|
||||||
</Button>
|
|
||||||
{isDev() && (
|
|
||||||
<Text type="secondary" className="text-xs">
|
|
||||||
(生产环境启动 5 秒后自动检查)
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Space>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
112
src/pages/home/components/BannerCarousel.tsx
Normal file
112
src/pages/home/components/BannerCarousel.tsx
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
// ============================================================
|
||||||
|
// BannerCarousel — 首页顶部轮播图
|
||||||
|
// 使用 useBannerList() Hook 获取数据,组件仅负责渲染
|
||||||
|
//
|
||||||
|
// 关闭行为:
|
||||||
|
// - 关闭后当前会话不再显示(组件内 useState 驱动)
|
||||||
|
// - 刷新/重启应用 → state 重置 → 重新展示
|
||||||
|
// - 不做 localStorage 持久化,确保每次启动都可见
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useRef, useMemo, useState } from 'react';
|
||||||
|
import { Carousel, Skeleton, Button } from 'antd';
|
||||||
|
import { CloseOutlined } from '@ant-design/icons';
|
||||||
|
import type { CarouselRef } from 'antd/es/carousel';
|
||||||
|
|
||||||
|
import { useBannerList } from '@/hooks/use-api';
|
||||||
|
import type { Banner } from '@/services/modules';
|
||||||
|
|
||||||
|
// ---------- 组件 Props ----------
|
||||||
|
|
||||||
|
interface BannerCarouselProps {
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function BannerCarousel({ className }: BannerCarouselProps) {
|
||||||
|
const carouselRef = useRef<CarouselRef>(null);
|
||||||
|
const { data: rawBanners, loading } = useBannerList();
|
||||||
|
|
||||||
|
/** 当前会话是否已关闭轮播图(组件卸载即重置,下次启动重新展示) */
|
||||||
|
const [dismissed, setDismissed] = useState(false);
|
||||||
|
|
||||||
|
// 过滤 + 排序(纯计算,无副作用)
|
||||||
|
const banners = useMemo<Banner[]>(() => {
|
||||||
|
if (!rawBanners) return [];
|
||||||
|
return rawBanners
|
||||||
|
.filter((b) => b.is_active)
|
||||||
|
.filter((b) => b.category === 'banner')
|
||||||
|
.sort((a, b) => a.sort_order - b.sort_order);
|
||||||
|
}, [rawBanners]);
|
||||||
|
|
||||||
|
// 用户已关闭或加载完成但无数据 → 不渲染
|
||||||
|
if (dismissed || (!loading && banners.length === 0)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加载态 — 适配长条比例(2280×90)
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className={className} style={{ width: '100%' }}>
|
||||||
|
<Skeleton.Input active block style={{ height: 90 }} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`banner-carousel ${className ?? ''}`}
|
||||||
|
style={{ position: 'relative', width: '100%', overflow: 'hidden', lineHeight: 0 }}
|
||||||
|
>
|
||||||
|
<Carousel
|
||||||
|
ref={carouselRef}
|
||||||
|
autoplay
|
||||||
|
autoplaySpeed={5000}
|
||||||
|
effect="fade"
|
||||||
|
pauseOnHover
|
||||||
|
adaptiveHeight={true}
|
||||||
|
dots={banners.length > 1}
|
||||||
|
>
|
||||||
|
{banners.map((banner) => (
|
||||||
|
<div key={banner.id}>
|
||||||
|
<img
|
||||||
|
src={banner.image_url}
|
||||||
|
alt={banner.title}
|
||||||
|
style={{ width: '100%', height: 'auto', display: 'block' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Carousel>
|
||||||
|
|
||||||
|
{/* 关闭按钮 — 右上角悬浮,半透明底色,hover 加深 */}
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
icon={<CloseOutlined />}
|
||||||
|
onClick={() => setDismissed(true)}
|
||||||
|
title="关闭轮播图"
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: 8,
|
||||||
|
right: 8,
|
||||||
|
zIndex: 10,
|
||||||
|
color: '#fff',
|
||||||
|
background: 'rgba(0, 0, 0, 0.35)',
|
||||||
|
borderRadius: 4,
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.background = 'rgba(0, 0, 0, 0.55)';
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.background = 'rgba(0, 0, 0, 0.35)';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
23
src/pages/home/components/CenterPanel.tsx
Normal file
23
src/pages/home/components/CenterPanel.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// ============================================================
|
||||||
|
// CenterPanel — 中列容器(模型输入表单)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { theme as antTheme } from 'antd';
|
||||||
|
import { ModelInputForm } from './ModelInputForm';
|
||||||
|
|
||||||
|
export function CenterPanel() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: '100%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
borderRadius: 8,
|
||||||
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ModelInputForm />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
179
src/pages/home/components/LeftPanel.tsx
Normal file
179
src/pages/home/components/LeftPanel.tsx
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
// ============================================================
|
||||||
|
// LeftPanel — 左列容器(模型选择 + 可拖拽分割线 + 任务搜索 + 任务记录)
|
||||||
|
// 纵向拖拽分隔线支持鼠标调整上下区域高度比例
|
||||||
|
//
|
||||||
|
// 职责:布局 + edition 分发,子组件自行管理数据和搜索状态
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||||
|
import { theme as antTheme } from 'antd';
|
||||||
|
import { ModelSelector } from './ModelSelector';
|
||||||
|
import { TaskHistory } from './TaskHistory';
|
||||||
|
|
||||||
|
// ---------- 常量 ----------
|
||||||
|
|
||||||
|
/** 模型选择区最小高度 */
|
||||||
|
const TOP_MIN = 120;
|
||||||
|
/** 任务列表区最小高度 */
|
||||||
|
const BOTTOM_MIN = 200;
|
||||||
|
/** 默认模型选择区百分比 */
|
||||||
|
const TOP_DEFAULT_PCT = 0.40;
|
||||||
|
/** 拖拽分隔条高度 */
|
||||||
|
const DIVIDER_HEIGHT = 6;
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function LeftPanel() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
|
||||||
|
// 面板容器引用
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// 模型选择区高度(像素)
|
||||||
|
const [topHeight, setTopHeight] = useState<number | null>(null);
|
||||||
|
// 拖拽状态
|
||||||
|
const [dragging, setDragging] = useState(false);
|
||||||
|
// hover 状态
|
||||||
|
const [hovered, setHovered] = useState(false);
|
||||||
|
|
||||||
|
const dragState = useRef<{
|
||||||
|
startY: number;
|
||||||
|
startHeight: number;
|
||||||
|
}>({ startY: 0, startHeight: 0 });
|
||||||
|
|
||||||
|
// 初始化:按百分比计算顶部高度
|
||||||
|
const initHeight = useCallback(() => {
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const total = el.clientHeight;
|
||||||
|
setTopHeight(Math.max(TOP_MIN, Math.round(total * TOP_DEFAULT_PCT)));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
initHeight();
|
||||||
|
}, [initHeight]);
|
||||||
|
|
||||||
|
// 响应容器 resize(窗口大小变化时重新按比例计算)
|
||||||
|
useEffect(() => {
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
if (!dragging) {
|
||||||
|
const total = el.clientHeight;
|
||||||
|
setTopHeight((prev) => {
|
||||||
|
if (prev === null) return Math.max(TOP_MIN, Math.round(total * TOP_DEFAULT_PCT));
|
||||||
|
// 保持原有比例
|
||||||
|
const ratio = prev / total;
|
||||||
|
return Math.max(TOP_MIN, Math.round(total * Math.min(ratio, 0.8)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
observer.observe(el);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [dragging]);
|
||||||
|
|
||||||
|
// 拖拽事件
|
||||||
|
const handleDividerMouseDown = (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
dragState.current = { startY: e.clientY, startHeight: topHeight ?? 200 };
|
||||||
|
setDragging(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
|
if (!dragging) return;
|
||||||
|
|
||||||
|
const el = containerRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
|
||||||
|
const total = el.clientHeight;
|
||||||
|
const ds = dragState.current;
|
||||||
|
const delta = e.clientY - ds.startY;
|
||||||
|
const newTop = Math.max(TOP_MIN, Math.min(total - BOTTOM_MIN, ds.startHeight + delta));
|
||||||
|
setTopHeight(newTop);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseUp = () => {
|
||||||
|
setDragging(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousemove', handleMouseMove);
|
||||||
|
document.addEventListener('mouseup', handleMouseUp);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousemove', handleMouseMove);
|
||||||
|
document.removeEventListener('mouseup', handleMouseUp);
|
||||||
|
};
|
||||||
|
}, [dragging]);
|
||||||
|
|
||||||
|
// 分隔条样式
|
||||||
|
const isActive = dragging;
|
||||||
|
const isHovered = hovered;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
height: '100%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
borderRadius: 8,
|
||||||
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 上方:模型选择(高度由拖拽控制) */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: topHeight ?? '40%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ModelSelector />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 纵向拖拽分隔条 */}
|
||||||
|
<div
|
||||||
|
onMouseDown={handleDividerMouseDown}
|
||||||
|
style={{
|
||||||
|
height: DIVIDER_HEIGHT,
|
||||||
|
flexShrink: 0,
|
||||||
|
cursor: 'row-resize',
|
||||||
|
background: isActive
|
||||||
|
? token.colorPrimary
|
||||||
|
: isHovered
|
||||||
|
? `${token.colorPrimary}60`
|
||||||
|
: token.colorBorderSecondary,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
transition: 'background 0.2s ease',
|
||||||
|
zIndex: 10,
|
||||||
|
}}
|
||||||
|
onMouseEnter={() => setHovered(true)}
|
||||||
|
onMouseLeave={() => setHovered(false)}
|
||||||
|
>
|
||||||
|
{/* 拖拽手柄横线 */}
|
||||||
|
<div style={{
|
||||||
|
height: 2,
|
||||||
|
width: 32,
|
||||||
|
borderRadius: 1,
|
||||||
|
background: isActive
|
||||||
|
? '#fff'
|
||||||
|
: isHovered
|
||||||
|
? token.colorPrimary
|
||||||
|
: token.colorBorder,
|
||||||
|
transition: 'background 0.2s ease',
|
||||||
|
}} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 下方:任务记录(剩余高度) */}
|
||||||
|
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
||||||
|
<TaskHistory />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
463
src/pages/home/components/ModelInputForm.tsx
Normal file
463
src/pages/home/components/ModelInputForm.tsx
Normal file
@@ -0,0 +1,463 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ModelInputForm — 动态模型输入表单
|
||||||
|
// 根据选中模型的 param_schema + ui_config 动态渲染表单控件
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Select,
|
||||||
|
Slider,
|
||||||
|
Button,
|
||||||
|
Typography,
|
||||||
|
Empty,
|
||||||
|
Upload,
|
||||||
|
Switch,
|
||||||
|
theme as antTheme,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
SendOutlined,
|
||||||
|
UploadOutlined,
|
||||||
|
InboxOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import type { UploadFile } from 'antd/es/upload';
|
||||||
|
|
||||||
|
import { useHomeContext } from '@/contexts/home-context';
|
||||||
|
import { useAppContext } from '@/contexts/app-context';
|
||||||
|
import { useSubmitTask } from '@/hooks/use-api';
|
||||||
|
import { emit, EVENTS } from '@/utils/event-bus';
|
||||||
|
import type { TaskInfoItemResponseBody } from '@/services/modules';
|
||||||
|
|
||||||
|
const { Text, Title } = Typography;
|
||||||
|
const { TextArea } = Input;
|
||||||
|
const { Dragger } = Upload;
|
||||||
|
|
||||||
|
// ---------- 参数类型映射 ----------
|
||||||
|
|
||||||
|
/** 从 ui_config 中解析的参数描述 */
|
||||||
|
interface ParamDescriptor {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
/** 控件类型 */
|
||||||
|
controlType: 'text' | 'number' | 'textarea' | 'select' | 'slider' | 'switch' | 'image-upload';
|
||||||
|
defaultValue?: unknown;
|
||||||
|
required?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
/** 数值型:最小值 */
|
||||||
|
min?: number;
|
||||||
|
/** 数值型:最大值 */
|
||||||
|
max?: number;
|
||||||
|
/** 数值型:步长 */
|
||||||
|
step?: number;
|
||||||
|
/** select 型:选项列表 */
|
||||||
|
options?: Array<{ label: string; value: string | number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从 ui_config 对象中解析控件类型 */
|
||||||
|
function inferControlType(config: Record<string, unknown>): ParamDescriptor['controlType'] {
|
||||||
|
const type = config.type as string | undefined;
|
||||||
|
if (!type) return 'text';
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case 'number':
|
||||||
|
case 'integer':
|
||||||
|
case 'float':
|
||||||
|
return 'number';
|
||||||
|
case 'textarea':
|
||||||
|
case 'text_area':
|
||||||
|
case 'prompt':
|
||||||
|
return 'textarea';
|
||||||
|
case 'select':
|
||||||
|
case 'dropdown':
|
||||||
|
case 'enum':
|
||||||
|
return 'select';
|
||||||
|
case 'slider':
|
||||||
|
case 'range':
|
||||||
|
return 'slider';
|
||||||
|
case 'switch':
|
||||||
|
case 'boolean':
|
||||||
|
case 'bool':
|
||||||
|
return 'switch';
|
||||||
|
case 'image':
|
||||||
|
case 'image-upload':
|
||||||
|
case 'file':
|
||||||
|
return 'image-upload';
|
||||||
|
default:
|
||||||
|
return 'text';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从 param_schema + ui_config 构建参数描述符列表 */
|
||||||
|
function buildParamDescriptors(
|
||||||
|
paramSchema: string[],
|
||||||
|
uiConfig: Record<string, unknown>,
|
||||||
|
): ParamDescriptor[] {
|
||||||
|
return paramSchema.map((key) => {
|
||||||
|
const config = (uiConfig[key] || {}) as Record<string, unknown>;
|
||||||
|
const controlType = inferControlType(config);
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label: (config.label as string) || key,
|
||||||
|
controlType,
|
||||||
|
defaultValue: config.default ?? config.defaultValue,
|
||||||
|
required: (config.required as boolean) || false,
|
||||||
|
placeholder: (config.placeholder as string) || `请输入${config.label || key}`,
|
||||||
|
min: config.min as number | undefined,
|
||||||
|
max: config.max as number | undefined,
|
||||||
|
step: config.step as number | undefined,
|
||||||
|
options: (config.options as ParamDescriptor['options']) || undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function ModelInputForm() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
const { isLoggedIn } = useAppContext();
|
||||||
|
const { selectedModel } = useHomeContext();
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [referenceFiles, setReferenceFiles] = useState<UploadFile[]>([]);
|
||||||
|
|
||||||
|
// 提交突变 Hook(自动处理 loading / error / 日志)
|
||||||
|
const { execute: submitTask, loading: submitting, errorMessage } = useSubmitTask({
|
||||||
|
onSuccess: useCallback(
|
||||||
|
(_data: TaskInfoItemResponseBody) => {
|
||||||
|
message.success('任务已提交');
|
||||||
|
// 通过事件总线通知 TaskHistory 刷新(替代 Context 中的 refreshTaskSignal)
|
||||||
|
emit(EVENTS.TASK_SUBMITTED);
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 选中模型时重置表单(仅当有选中模型时操作,避免 form 未连接警告)
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedModel) {
|
||||||
|
form.resetFields();
|
||||||
|
}
|
||||||
|
setReferenceFiles([]);
|
||||||
|
}, [selectedModel?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
// 参数描述符
|
||||||
|
const paramDescriptors = useMemo(() => {
|
||||||
|
if (!selectedModel) return [];
|
||||||
|
return buildParamDescriptors(
|
||||||
|
selectedModel.param_schema || [],
|
||||||
|
selectedModel.ui_config || {},
|
||||||
|
);
|
||||||
|
}, [selectedModel]);
|
||||||
|
|
||||||
|
// 提交
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!isLoggedIn) {
|
||||||
|
message.warning('请先登录后再提交任务');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!selectedModel) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
|
||||||
|
// 分离固定字段和模型动态参数
|
||||||
|
const { prompt, negative_prompt, num_outputs, ...dynamicParams } = values;
|
||||||
|
|
||||||
|
// 构建提交参数(全部转为字符串值)
|
||||||
|
const params: Record<string, string> = {
|
||||||
|
prompt: String(prompt ?? ''),
|
||||||
|
negative_prompt: String(negative_prompt ?? ''),
|
||||||
|
num_outputs: String(num_outputs ?? 1),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 动态参数统一转字符串
|
||||||
|
for (const [key, value] of Object.entries(dynamicParams)) {
|
||||||
|
if (value !== undefined && value !== null) {
|
||||||
|
params[key] = String(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 参考图
|
||||||
|
if (referenceFiles.length > 0) {
|
||||||
|
const refUrls = referenceFiles
|
||||||
|
.filter((f) => f.status === 'done')
|
||||||
|
.map((f) => f.response?.url || f.url || f.name)
|
||||||
|
.filter(Boolean) as string[];
|
||||||
|
if (refUrls.length > 0) {
|
||||||
|
params.reference_images = JSON.stringify(refUrls);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 mutation Hook 提交(自动处理 loading / error / 日志)
|
||||||
|
await submitTask({ model_id: selectedModel.id, params });
|
||||||
|
} catch (err) {
|
||||||
|
if (err && typeof err === 'object' && 'errorFields' in err) {
|
||||||
|
// 表单验证错误,antd 会自动提示
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 错误消息由 Hook 自动通过 errorMessage 提供
|
||||||
|
message.error(errorMessage || '任务提交失败,请重试');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 渲染单个参数控件
|
||||||
|
const renderParamControl = (desc: ParamDescriptor) => {
|
||||||
|
const commonProps = {
|
||||||
|
placeholder: desc.placeholder,
|
||||||
|
style: { width: '100%' },
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (desc.controlType) {
|
||||||
|
case 'number':
|
||||||
|
return (
|
||||||
|
<InputNumber
|
||||||
|
{...commonProps}
|
||||||
|
min={desc.min}
|
||||||
|
max={desc.max}
|
||||||
|
step={desc.step}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'textarea':
|
||||||
|
return <TextArea rows={3} {...commonProps} />;
|
||||||
|
|
||||||
|
case 'select':
|
||||||
|
return (
|
||||||
|
<Select
|
||||||
|
{...commonProps}
|
||||||
|
options={desc.options}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'slider':
|
||||||
|
return (
|
||||||
|
<Slider
|
||||||
|
min={desc.min ?? 1}
|
||||||
|
max={desc.max ?? 100}
|
||||||
|
step={desc.step ?? 1}
|
||||||
|
marks={
|
||||||
|
desc.min !== undefined && desc.max !== undefined
|
||||||
|
? { [desc.min]: `${desc.min}`, [desc.max]: `${desc.max}` }
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
tooltip={{ formatter: (v) => v }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'switch':
|
||||||
|
return <Switch />;
|
||||||
|
|
||||||
|
case 'image-upload':
|
||||||
|
return (
|
||||||
|
<Upload
|
||||||
|
listType="picture-card"
|
||||||
|
maxCount={1}
|
||||||
|
accept="image/png,image/jpg,image/jpeg,image/webp"
|
||||||
|
beforeUpload={(file) => {
|
||||||
|
const isImage = file.type.startsWith('image/');
|
||||||
|
const isLt10M = file.size / 1024 / 1024 < 10;
|
||||||
|
if (!isImage) {
|
||||||
|
message.error('只能上传图片文件');
|
||||||
|
return Upload.LIST_IGNORE;
|
||||||
|
}
|
||||||
|
if (!isLt10M) {
|
||||||
|
message.error('图片大小不能超过 10MB');
|
||||||
|
return Upload.LIST_IGNORE;
|
||||||
|
}
|
||||||
|
return false; // 手动上传
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<UploadOutlined />
|
||||||
|
<div style={{ marginTop: 4, fontSize: 12 }}>上传</div>
|
||||||
|
</div>
|
||||||
|
</Upload>
|
||||||
|
);
|
||||||
|
|
||||||
|
default:
|
||||||
|
return <Input {...commonProps} />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- 未选择模型 ----
|
||||||
|
if (!selectedModel) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
height: '100%',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Empty description="请在左侧选择一个模型" image={Empty.PRESENTED_IMAGE_SIMPLE} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 表单 ----
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 模型标题 */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '16px 20px',
|
||||||
|
borderBottom: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Title level={4} style={{ margin: 0, fontSize: 18 }}>
|
||||||
|
{selectedModel.name}
|
||||||
|
</Title>
|
||||||
|
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{selectedModel.provider_name} · {selectedModel.category_name}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 可滚动表单区 */}
|
||||||
|
<div style={{ flex: 1, overflow: 'auto', padding: '16px 20px' }}>
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
size="small"
|
||||||
|
initialValues={{ num_outputs: 1 }}
|
||||||
|
>
|
||||||
|
{/* ======== 固定字段 ======== */}
|
||||||
|
|
||||||
|
{/* 提示词 */}
|
||||||
|
<Form.Item
|
||||||
|
name="prompt"
|
||||||
|
label={<Text strong>提示词</Text>}
|
||||||
|
rules={[{ required: true, message: '请输入提示词' }]}
|
||||||
|
>
|
||||||
|
<TextArea
|
||||||
|
rows={4}
|
||||||
|
placeholder="描述你想要的画面、视频或音频内容..."
|
||||||
|
showCount
|
||||||
|
maxLength={2000}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{/* 负面提示词 */}
|
||||||
|
<Form.Item
|
||||||
|
name="negative_prompt"
|
||||||
|
label={<Text type="secondary">负面提示词</Text>}
|
||||||
|
>
|
||||||
|
<TextArea
|
||||||
|
rows={2}
|
||||||
|
placeholder="描述你不希望在结果中出现的内容(可选)"
|
||||||
|
maxLength={1000}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{/* 参考图 */}
|
||||||
|
<Form.Item label={<Text strong>参考图</Text>}>
|
||||||
|
<Dragger
|
||||||
|
multiple
|
||||||
|
listType="picture"
|
||||||
|
fileList={referenceFiles}
|
||||||
|
onChange={({ fileList }) => setReferenceFiles(fileList)}
|
||||||
|
accept="image/png,image/jpg,image/jpeg,image/webp"
|
||||||
|
beforeUpload={(file) => {
|
||||||
|
const isImage = file.type.startsWith('image/');
|
||||||
|
const isLt10M = file.size / 1024 / 1024 < 10;
|
||||||
|
if (!isImage) {
|
||||||
|
message.error('只能上传图片文件');
|
||||||
|
return Upload.LIST_IGNORE;
|
||||||
|
}
|
||||||
|
if (!isLt10M) {
|
||||||
|
message.error('图片大小不能超过 10MB');
|
||||||
|
return Upload.LIST_IGNORE;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}}
|
||||||
|
maxCount={5}
|
||||||
|
style={{ marginBottom: 8 }}
|
||||||
|
>
|
||||||
|
<p className="ant-upload-drag-icon">
|
||||||
|
<InboxOutlined />
|
||||||
|
</p>
|
||||||
|
<p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
|
||||||
|
<p className="ant-upload-hint">
|
||||||
|
支持 PNG / JPG / WebP,单张不超过 10MB
|
||||||
|
</p>
|
||||||
|
</Dragger>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{/* 生成数量 */}
|
||||||
|
<Form.Item
|
||||||
|
name="num_outputs"
|
||||||
|
label={<Text strong>生成数量</Text>}
|
||||||
|
>
|
||||||
|
<InputNumber min={1} max={10} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{/* ======== 模型动态参数 ======== */}
|
||||||
|
|
||||||
|
{paramDescriptors.length > 0 && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: 16,
|
||||||
|
paddingTop: 16,
|
||||||
|
borderTop: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text strong style={{ display: 'block', marginBottom: 12 }}>
|
||||||
|
模型参数
|
||||||
|
</Text>
|
||||||
|
{paramDescriptors.map((desc) => (
|
||||||
|
<Form.Item
|
||||||
|
key={desc.key}
|
||||||
|
name={desc.key}
|
||||||
|
label={desc.label}
|
||||||
|
rules={desc.required ? [{ required: true, message: `请输入${desc.label}` }] : undefined}
|
||||||
|
initialValue={desc.defaultValue}
|
||||||
|
valuePropName={desc.controlType === 'switch' ? 'checked' : 'value'}
|
||||||
|
>
|
||||||
|
{renderParamControl(desc)}
|
||||||
|
</Form.Item>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 提交按钮 */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '12px 20px',
|
||||||
|
borderTop: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<SendOutlined />}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
loading={submitting}
|
||||||
|
disabled={!isLoggedIn || !selectedModel}
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
style={{
|
||||||
|
background: token.colorPrimary,
|
||||||
|
height: 44,
|
||||||
|
fontSize: 16,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
开始生成
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
122
src/pages/home/components/ModelSelector.tsx
Normal file
122
src/pages/home/components/ModelSelector.tsx
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ModelSelector — 模型选择器(垂直单选列表,按类别分组)
|
||||||
|
// 使用 useModelList() Hook 获取数据,组件仅负责渲染
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { Menu, Spin, Empty, Tag, Typography, theme as antTheme } from 'antd';
|
||||||
|
import { AppstoreOutlined } from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { useModelList, MODEL_CATEGORY_LABELS } from '@/hooks/use-api';
|
||||||
|
import { useHomeContext } from '@/contexts/home-context';
|
||||||
|
import type { ModelCategory } from '@/services/modules';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function ModelSelector() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
const { selectedModel, setSelectedModel } = useHomeContext();
|
||||||
|
const { data: models, loading, groupedModels } = useModelList();
|
||||||
|
|
||||||
|
// 构建 Menu items:分组标题 + 模型项
|
||||||
|
const menuItems = useMemo(() => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const items: any[] = [];
|
||||||
|
|
||||||
|
groupedModels.forEach((groupModels, category) => {
|
||||||
|
const categoryLabel = MODEL_CATEGORY_LABELS[category as ModelCategory] || category;
|
||||||
|
items.push({
|
||||||
|
key: `group-${category}`,
|
||||||
|
label: (
|
||||||
|
<Text strong style={{ fontSize: 12, color: token.colorTextSecondary }}>
|
||||||
|
{categoryLabel} ({groupModels.length})
|
||||||
|
</Text>
|
||||||
|
),
|
||||||
|
type: 'group' as const,
|
||||||
|
children: groupModels.map((model) => ({
|
||||||
|
key: model.id,
|
||||||
|
label: (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
|
||||||
|
<Text
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
fontSize: 13,
|
||||||
|
}}
|
||||||
|
title={model.name}
|
||||||
|
>
|
||||||
|
{model.name}
|
||||||
|
</Text>
|
||||||
|
{model.status !== 'active' && (
|
||||||
|
<Tag
|
||||||
|
color={model.status === 'inactive' ? 'default' : 'orange'}
|
||||||
|
style={{ fontSize: 10, lineHeight: '16px', padding: '0 4px' }}
|
||||||
|
>
|
||||||
|
{model.status === 'maintenance' ? '维护' : '停用'}
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}, [groupedModels, token.colorTextSecondary]);
|
||||||
|
|
||||||
|
// 选中菜单项
|
||||||
|
const handleSelect = ({ key }: { key: string }) => {
|
||||||
|
const model = models?.find((m) => m.id === key);
|
||||||
|
if (model) {
|
||||||
|
setSelectedModel(model);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 加载态
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
|
||||||
|
<Spin size="small" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 空态
|
||||||
|
if (!models || models.length === 0) {
|
||||||
|
return <Empty description="暂无可用模型" image={Empty.PRESENTED_IMAGE_SIMPLE} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 选中 key
|
||||||
|
const selectedKeys = selectedModel ? [selectedModel.id] : [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '8px 12px',
|
||||||
|
borderBottom: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 6,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AppstoreOutlined style={{ color: token.colorPrimary, fontSize: 14 }} />
|
||||||
|
<Text strong style={{ fontSize: 13 }}>选择模型</Text>
|
||||||
|
</div>
|
||||||
|
<Menu
|
||||||
|
mode="inline"
|
||||||
|
selectedKeys={selectedKeys}
|
||||||
|
onSelect={handleSelect}
|
||||||
|
items={menuItems}
|
||||||
|
style={{
|
||||||
|
borderInlineEnd: 'none',
|
||||||
|
background: 'transparent',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
165
src/pages/home/components/OutputPreview.tsx
Normal file
165
src/pages/home/components/OutputPreview.tsx
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
// ============================================================
|
||||||
|
// OutputPreview — 任务输出预览(图片 / 视频)
|
||||||
|
// 使用 useTaskDetail() Hook 获取任务详情,组件仅负责渲染
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { Image, Empty, Spin, Typography, Button, Tag, theme as antTheme } from 'antd';
|
||||||
|
import {
|
||||||
|
EyeOutlined,
|
||||||
|
DownloadOutlined,
|
||||||
|
CloseCircleOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { useHomeContext } from '@/contexts/home-context';
|
||||||
|
import { useTaskDetail } from '@/hooks/use-api';
|
||||||
|
import type { TaskStatusString } from '@/services/modules';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
// ---------- 状态标签配置 ----------
|
||||||
|
|
||||||
|
const STATUS_CONFIG: Record<TaskStatusString, { color: string; label: string }> = {
|
||||||
|
pending: { color: 'blue', label: '排队中' },
|
||||||
|
submitted: { color: 'cyan', label: '已提交' },
|
||||||
|
processing: { color: 'orange', label: '处理中' },
|
||||||
|
success: { color: 'green', label: '已完成' },
|
||||||
|
failed: { color: 'red', label: '失败' },
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- 工具函数 ----------
|
||||||
|
|
||||||
|
function isVideoUrl(url: string): boolean {
|
||||||
|
return /\.(mp4|webm|mov|avi|mkv)(\?|$)/i.test(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitAssets(assets: Array<{ url: string }>): { images: string[]; videos: string[] } {
|
||||||
|
const images: string[] = [];
|
||||||
|
const videos: string[] = [];
|
||||||
|
assets.forEach(({ url }) => {
|
||||||
|
if (isVideoUrl(url)) videos.push(url);
|
||||||
|
else images.push(url);
|
||||||
|
});
|
||||||
|
return { images, videos };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function OutputPreview() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
const { selectedTask } = useHomeContext();
|
||||||
|
|
||||||
|
// 数据获取(Hook 自动处理:taskId 为 null 时不请求、竞态、loading/error)
|
||||||
|
const { data: detail, loading } = useTaskDetail(selectedTask?.id);
|
||||||
|
|
||||||
|
// 从 output_assets 提取图片/视频
|
||||||
|
const { images, videos } = useMemo(() => {
|
||||||
|
if (!detail?.output_assets || detail.output_assets.length === 0) {
|
||||||
|
return { images: [], videos: [] };
|
||||||
|
}
|
||||||
|
return splitAssets(detail.output_assets);
|
||||||
|
}, [detail]);
|
||||||
|
|
||||||
|
const status = selectedTask?.status as TaskStatusString | undefined;
|
||||||
|
const statusCfg = status
|
||||||
|
? (STATUS_CONFIG[status] || { color: 'default', label: status })
|
||||||
|
: { color: 'default', label: '未知' };
|
||||||
|
|
||||||
|
// ---- 无选中任务 ----
|
||||||
|
if (!selectedTask) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
|
||||||
|
<Empty description="选择任务记录查看输出" image={Empty.PRESENTED_IMAGE_SIMPLE} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 处理中 ----
|
||||||
|
if (status === 'pending' || status === 'submitted' || status === 'processing') {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 16 }}>
|
||||||
|
<Spin size="large" />
|
||||||
|
<Tag color={statusCfg.color}>{statusCfg.label}</Tag>
|
||||||
|
<Text type="secondary">任务正在处理中,请稍候...</Text>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 失败 ----
|
||||||
|
if (status === 'failed') {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 12 }}>
|
||||||
|
<CloseCircleOutlined style={{ fontSize: 48, color: '#ff4d4f' }} />
|
||||||
|
<Text type="danger" strong>任务执行失败</Text>
|
||||||
|
{detail?.error_message && (
|
||||||
|
<Text type="secondary" style={{ maxWidth: 300, textAlign: 'center', fontSize: 12 }}>
|
||||||
|
{detail.error_message}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 加载中 ----
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
|
||||||
|
<Spin size="large" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 无结果 ----
|
||||||
|
if (!detail || images.length + videos.length === 0) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
|
||||||
|
<Empty description="暂无输出结果" image={Empty.PRESENTED_IMAGE_SIMPLE} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 展示 ----
|
||||||
|
return (
|
||||||
|
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
|
||||||
|
<div style={{
|
||||||
|
padding: '12px 16px',
|
||||||
|
borderBottom: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||||
|
<EyeOutlined style={{ fontSize: 14 }} />
|
||||||
|
<Text strong style={{ fontSize: 13 }}>输出预览</Text>
|
||||||
|
<Tag color={statusCfg.color} style={{ fontSize: 11 }}>{statusCfg.label}</Tag>
|
||||||
|
</div>
|
||||||
|
{videos.length > 0 && (
|
||||||
|
<Button size="small" type="link" icon={<DownloadOutlined />} href={videos[0]} target="_blank">
|
||||||
|
下载视频
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ flex: 1, overflow: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||||
|
{videos.map((url, i) => (
|
||||||
|
<div key={i} style={{ borderRadius: 6, overflow: 'hidden', background: '#000' }}>
|
||||||
|
<video controls style={{ width: '100%', maxHeight: 360, display: 'block' }} src={url}>
|
||||||
|
您的浏览器不支持视频播放
|
||||||
|
</video>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{images.length === 1 ? (
|
||||||
|
<Image src={images[0]} alt="输出结果" style={{ borderRadius: 6, width: '100%', objectFit: 'contain' }} />
|
||||||
|
) : (
|
||||||
|
<Image.PreviewGroup>
|
||||||
|
{images.map((url, i) => (
|
||||||
|
<Image key={i} src={url} alt={`输出结果 ${i + 1}`}
|
||||||
|
style={{ borderRadius: 6, width: '100%', objectFit: 'contain', marginBottom: 8 }} />
|
||||||
|
))}
|
||||||
|
</Image.PreviewGroup>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
23
src/pages/home/components/RightPanel.tsx
Normal file
23
src/pages/home/components/RightPanel.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// ============================================================
|
||||||
|
// RightPanel — 右列容器(输出预览)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { theme as antTheme } from 'antd';
|
||||||
|
import { OutputPreview } from './OutputPreview';
|
||||||
|
|
||||||
|
export function RightPanel() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: '100%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
borderRadius: 8,
|
||||||
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<OutputPreview />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
745
src/pages/home/components/TaskHistory.tsx
Normal file
745
src/pages/home/components/TaskHistory.tsx
Normal file
@@ -0,0 +1,745 @@
|
|||||||
|
// ============================================================
|
||||||
|
// TaskHistory — 任务记录列表(分页 + 列头筛选 + 排序 + 滚动)
|
||||||
|
//
|
||||||
|
// 筛选策略(混合模式):
|
||||||
|
// - 服务端筛选(传 API):status、model_id、user_id(企业版)
|
||||||
|
// - 客户端筛选(antd onFilter):output_type、provider_name
|
||||||
|
// - 服务端不支持日期查询,时间范围筛选暂用 sorter 排序替代
|
||||||
|
// - 企业版才会在"用户"列显示筛选菜单
|
||||||
|
//
|
||||||
|
// 使用 antd Table onChange 统一管理 pagination + filters + sorter,
|
||||||
|
// 参考 table-test.tsx 示例 4 的模式。
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
|
||||||
|
import { Table, Tag, Typography, theme as antTheme, Popover, Checkbox, Button, Space } from 'antd';
|
||||||
|
import type { ColumnsType, TableProps } from 'antd/es/table';
|
||||||
|
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
|
||||||
|
import { HistoryOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { useTaskList, useModelList } from '@/hooks/use-api';
|
||||||
|
import { useAppContext } from '@/contexts/app-context';
|
||||||
|
import { useHomeContext } from '@/contexts/home-context';
|
||||||
|
import { useTheme } from '@/hooks/use-theme';
|
||||||
|
import { on, off, EVENTS } from '@/utils/event-bus';
|
||||||
|
import type {
|
||||||
|
TaskInfoItemResponseBody,
|
||||||
|
TaskListRequestParams,
|
||||||
|
TaskStatusString,
|
||||||
|
} from '@/services/modules';
|
||||||
|
import { TaskStatusMap, OutputTypeMap } from '@/services/modules';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
// ---------- 辅助类型 ----------
|
||||||
|
|
||||||
|
/** antd Table onChange 中 filters 的类型 */
|
||||||
|
type TableFilters = Record<string, FilterValue | null>;
|
||||||
|
|
||||||
|
/** antd Table onChange 中 sorter 的类型(单列排序) */
|
||||||
|
interface TableSorter {
|
||||||
|
field?: React.Key | readonly React.Key[];
|
||||||
|
order?: 'ascend' | 'descend';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 表格参数(缓存 antd onChange 的结果,用于构建 API 请求) */
|
||||||
|
interface TableParams {
|
||||||
|
pagination: { current: number; pageSize: number };
|
||||||
|
filters: TableFilters;
|
||||||
|
sorter: TableSorter;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 常量 ----------
|
||||||
|
|
||||||
|
/** 状态筛选选项(来自 API 枚举) */
|
||||||
|
const STATUS_FILTERS = Object.entries(TaskStatusMap).map(([value, label]) => ({
|
||||||
|
text: label,
|
||||||
|
value,
|
||||||
|
}));
|
||||||
|
|
||||||
|
/** 输出类型筛选选项(从 OutputTypeMap 派生) */
|
||||||
|
const OUTPUT_TYPE_FILTERS = Object.entries(OutputTypeMap).map(([value, text]) => ({
|
||||||
|
text,
|
||||||
|
value,
|
||||||
|
}));
|
||||||
|
|
||||||
|
/** 状态标签配置(渲染用,含未来未知状态的降级处理) */
|
||||||
|
const STATUS_CONFIG: Record<string, { color: string; label: string }> = {
|
||||||
|
pending: { color: 'blue', label: '排队中' },
|
||||||
|
submitted: { color: 'cyan', label: '已提交' },
|
||||||
|
processing: { color: 'orange', label: '处理中' },
|
||||||
|
success: { color: 'green', label: '已完成' },
|
||||||
|
failed: { color: 'red', label: '失败' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 未知状态降级:后端新增状态时自动回退显示 key 原文 */
|
||||||
|
function resolveStatus(s: string): { color: string; label: string } {
|
||||||
|
return STATUS_CONFIG[s] || { color: 'default', label: s };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 列可见性持久化 ----------
|
||||||
|
|
||||||
|
/** localStorage 键名(遵循 ele-heixiu-* 规范) */
|
||||||
|
const COLUMN_VISIBILITY_KEY = 'ele-heixiu-table-columns';
|
||||||
|
|
||||||
|
/** 列元数据(定义所有可用列 + 默认可见性) */
|
||||||
|
interface ColumnMeta { key: string; title: string; defaultVisible: boolean }
|
||||||
|
|
||||||
|
const ALL_COLUMNS: ColumnMeta[] = [
|
||||||
|
{ key: 'id', title: '任务 ID', defaultVisible: true },
|
||||||
|
{ key: 'created_at', title: '创建时间', defaultVisible: true },
|
||||||
|
{ key: 'model_name', title: '模型', defaultVisible: true },
|
||||||
|
{ key: 'output_type', title: '输出类型', defaultVisible: true },
|
||||||
|
{ key: 'status', title: '状态', defaultVisible: true },
|
||||||
|
{ key: 'prompt', title: '提示词', defaultVisible: true },
|
||||||
|
{ key: 'duration', title: '时长', defaultVisible: true },
|
||||||
|
{ key: 'cost_cent', title: '费用', defaultVisible: true },
|
||||||
|
{ key: 'user_display_name', title: '用户', defaultVisible: true },
|
||||||
|
{ key: 'provider_name', title: '供应商', defaultVisible: false },
|
||||||
|
{ key: 'fps', title: '帧率', defaultVisible: false },
|
||||||
|
{ key: 'file_size', title: '文件大小', defaultVisible: false },
|
||||||
|
{ key: 'tags', title: '标签', defaultVisible: false },
|
||||||
|
{ key: 'error_message', title: '错误信息', defaultVisible: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
function readStoredColumns(): Set<string> | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(COLUMN_VISIBILITY_KEY);
|
||||||
|
if (raw) {
|
||||||
|
const arr: unknown = JSON.parse(raw);
|
||||||
|
if (Array.isArray(arr) && arr.every((v) => typeof v === 'string')) return new Set(arr);
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeStoredColumns(visible: Set<string>): void {
|
||||||
|
try { localStorage.setItem(COLUMN_VISIBILITY_KEY, JSON.stringify([...visible])); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 工具函数 ----------
|
||||||
|
|
||||||
|
/** 从 filters 中提取单值筛选(如 status 单选) */
|
||||||
|
function pickOne(filters: TableFilters, key: string): string | undefined {
|
||||||
|
const v = filters[key];
|
||||||
|
if (Array.isArray(v) && v.length > 0) return v[0] as string;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从 filters 中提取多值筛选(如 model_ids、user_ids) */
|
||||||
|
function pickMany(filters: TableFilters, key: string): string[] | undefined {
|
||||||
|
const v = filters[key];
|
||||||
|
if (Array.isArray(v) && v.length > 0) return v as string[];
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 组件 ----------
|
||||||
|
|
||||||
|
export function TaskHistory() {
|
||||||
|
const { token } = antTheme.useToken();
|
||||||
|
const { edition } = useAppContext();
|
||||||
|
const {
|
||||||
|
selectedTask,
|
||||||
|
setSelectedTask,
|
||||||
|
taskPage,
|
||||||
|
taskPageSize,
|
||||||
|
setTaskPage,
|
||||||
|
setTaskPageSize,
|
||||||
|
} = useHomeContext();
|
||||||
|
|
||||||
|
const isEnterprise = edition === 'enterprise';
|
||||||
|
|
||||||
|
// -------- 列可见性 --------
|
||||||
|
|
||||||
|
const [visibleColumns, setVisibleColumns] = useState<Set<string>>(() => {
|
||||||
|
const stored = readStoredColumns();
|
||||||
|
if (stored) return stored;
|
||||||
|
return new Set(ALL_COLUMNS.filter((c) => c.defaultVisible).map((c) => c.key));
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleColumnToggle = useCallback((key: string, checked: boolean) => {
|
||||||
|
setVisibleColumns((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (checked) next.add(key); else next.delete(key);
|
||||||
|
writeStoredColumns(next);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// -------- 主题感知斑马纹 / hover / 选中行 CSS --------
|
||||||
|
|
||||||
|
const { isDark } = useTheme();
|
||||||
|
|
||||||
|
const tableCss = useMemo(() => {
|
||||||
|
const searchIconColor = token.colorPrimary;
|
||||||
|
if (isDark) {
|
||||||
|
return `
|
||||||
|
.task-table .task-row-odd > td { background: rgba(255,255,255,0.02) !important; }
|
||||||
|
.task-table .task-row-even > td { background: transparent !important; }
|
||||||
|
.task-table .task-row-selected > td { background: ${token.blue}1A !important; }
|
||||||
|
.task-table .task-row-selected.task-row-odd > td { background: ${token.blue}22 !important; }
|
||||||
|
.task-table .ant-table-row:hover > td { background: rgba(255,255,255,0.05) !important; }
|
||||||
|
.task-table .task-row-selected:hover > td { background: ${token.blue}28 !important; }
|
||||||
|
.task-table .prompt-search-icon.filtered { color: ${searchIconColor} !important; }
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
return `
|
||||||
|
.task-table .task-row-odd > td { background: #fafafa !important; }
|
||||||
|
.task-table .task-row-even > td { background: #ffffff !important; }
|
||||||
|
.task-table .task-row-selected > td { background: #e6f4ff !important; }
|
||||||
|
.task-table .task-row-selected.task-row-odd > td { background: #dceeff !important; }
|
||||||
|
.task-table .ant-table-row:hover > td { background: #f0f5ff !important; }
|
||||||
|
.task-table .task-row-selected:hover > td { background: #d6ebff !important; }
|
||||||
|
.task-table .prompt-search-icon.filtered { color: ${searchIconColor} !important; }
|
||||||
|
`;
|
||||||
|
}, [isDark, token.blue, token.colorPrimary]);
|
||||||
|
|
||||||
|
// -------- antd Table onChange 参数缓存 --------
|
||||||
|
|
||||||
|
const [tableParams, setTableParams] = useState<TableParams>({
|
||||||
|
pagination: { current: taskPage, pageSize: taskPageSize },
|
||||||
|
filters: {},
|
||||||
|
sorter: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 同步 context 分页 ↔ tableParams
|
||||||
|
useEffect(() => {
|
||||||
|
setTableParams((prev) => ({
|
||||||
|
...prev,
|
||||||
|
pagination: { current: taskPage, pageSize: taskPageSize },
|
||||||
|
}));
|
||||||
|
}, [taskPage, taskPageSize]);
|
||||||
|
|
||||||
|
// -------- 模型列表(用于模型列筛选选项 + 模型名→ID 映射)--------
|
||||||
|
|
||||||
|
// TODO: 与 ModelSelector 中的 useModelList 重复请求,后续统一缓存层
|
||||||
|
const { data: allModels } = useModelList();
|
||||||
|
const modelFilters = useMemo(() => {
|
||||||
|
if (!allModels) return [];
|
||||||
|
return allModels.map((m) => ({ text: m.name, value: m.id }));
|
||||||
|
}, [allModels]);
|
||||||
|
|
||||||
|
// -------- 供应商列表(从模型数据中提取)--------
|
||||||
|
|
||||||
|
const providerFilters = useMemo(() => {
|
||||||
|
if (!allModels) return [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
allModels.forEach((m) => {
|
||||||
|
if (m.provider_name) seen.add(m.provider_name);
|
||||||
|
});
|
||||||
|
return Array.from(seen).sort().map((name) => ({ text: name, value: name }));
|
||||||
|
}, [allModels]);
|
||||||
|
|
||||||
|
// -------- 用户列表(从当前任务数据中提取,仅企业版使用)--------
|
||||||
|
// TODO: 替换为独立的用户列表 API
|
||||||
|
|
||||||
|
const [userFilters, setUserFilters] = useState<Array<{ text: string; value: string }>>([]);
|
||||||
|
|
||||||
|
// -------- 构建 API 请求参数 --------
|
||||||
|
|
||||||
|
const requestParams = useMemo<TaskListRequestParams>(() => {
|
||||||
|
const req: TaskListRequestParams = {
|
||||||
|
page: tableParams.pagination.current,
|
||||||
|
page_size: tableParams.pagination.pageSize,
|
||||||
|
};
|
||||||
|
const { filters } = tableParams;
|
||||||
|
|
||||||
|
// 服务端筛选字段
|
||||||
|
const status = pickOne(filters, 'status');
|
||||||
|
if (status) req.status = status as TaskStatusString;
|
||||||
|
|
||||||
|
const modelIds = pickMany(filters, 'model_name');
|
||||||
|
if (modelIds) req.model_ids = modelIds;
|
||||||
|
|
||||||
|
// user_ids:仅企业版传入
|
||||||
|
if (isEnterprise) {
|
||||||
|
const userIds = pickMany(filters, 'user_id');
|
||||||
|
if (userIds) req.user_ids = userIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
return req;
|
||||||
|
}, [tableParams, isEnterprise]);
|
||||||
|
|
||||||
|
// -------- 数据获取 --------
|
||||||
|
|
||||||
|
const [refreshTick, setRefreshTick] = useState(0);
|
||||||
|
const handleTaskSubmitted = useCallback(() => {
|
||||||
|
setRefreshTick((t) => t + 1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
on(EVENTS.TASK_SUBMITTED, handleTaskSubmitted);
|
||||||
|
return () => { off(EVENTS.TASK_SUBMITTED, handleTaskSubmitted); };
|
||||||
|
}, [handleTaskSubmitted]);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: taskData,
|
||||||
|
loading,
|
||||||
|
errorMessage,
|
||||||
|
} = useTaskList({
|
||||||
|
requestParams,
|
||||||
|
refreshSignal: refreshTick,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tasks = taskData?.items ?? [];
|
||||||
|
const total = taskData?.total ?? 0;
|
||||||
|
|
||||||
|
// 从任务数据中提取用户列表(企业版筛选用)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isEnterprise || !taskData?.items) return;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
taskData.items.forEach((t) => {
|
||||||
|
if (t.user_id && t.user_display_name) {
|
||||||
|
seen.add(JSON.stringify({ text: t.user_display_name, value: t.user_id }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const newList = Array.from(seen).map((s) => JSON.parse(s) as { text: string; value: string });
|
||||||
|
setUserFilters((prev) => {
|
||||||
|
if (prev.length === newList.length) return prev; // 避免不必要的重渲染
|
||||||
|
return newList;
|
||||||
|
});
|
||||||
|
}, [isEnterprise, taskData]);
|
||||||
|
|
||||||
|
// -------- antd Table onChange --------
|
||||||
|
|
||||||
|
const handleTableChange: TableProps<TaskInfoItemResponseBody>['onChange'] = (
|
||||||
|
pagination,
|
||||||
|
filters,
|
||||||
|
sorter,
|
||||||
|
) => {
|
||||||
|
// 同步分页到 Context
|
||||||
|
if (pagination.current && pagination.current !== taskPage) setTaskPage(pagination.current);
|
||||||
|
if (pagination.pageSize && pagination.pageSize !== taskPageSize) setTaskPageSize(pagination.pageSize);
|
||||||
|
|
||||||
|
// 缓存筛选和排序参数
|
||||||
|
const s = sorter as SorterResult<TaskInfoItemResponseBody>;
|
||||||
|
setTableParams({
|
||||||
|
pagination: {
|
||||||
|
current: pagination.current || taskPage,
|
||||||
|
pageSize: pagination.pageSize || taskPageSize,
|
||||||
|
},
|
||||||
|
filters: filters as TableFilters,
|
||||||
|
sorter: !Array.isArray(s) && s.field
|
||||||
|
? { field: s.field, order: s.order as 'ascend' | 'descend' | undefined }
|
||||||
|
: {},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// -------- 表格列定义(含列头筛选/排序 + 可见性过滤)--------
|
||||||
|
//
|
||||||
|
// 列顺序:任务 ID(固定) → 创建时间 → 模型 → 输出类型 → 状态 → 提示词 →
|
||||||
|
// 时长(视频) → 费用 → 供应商 → 帧率/文件大小/标签/错误信息 → 用户(企业版)
|
||||||
|
//
|
||||||
|
// 可见性:通过标题栏齿轮图标控制,持久化到 localStorage
|
||||||
|
//
|
||||||
|
// ⚠️ 重要:columns 依赖中不出 token.colorPrimary,否则主题切换时 columns 重新生成
|
||||||
|
// 会导致 Table 内部状态重置(页码、筛选、排序等丢失)。
|
||||||
|
// 主题色通过 searchIconColorRef 传递,不触发 columns 重建。
|
||||||
|
|
||||||
|
/** 提示词搜索图标颜色(通过 CSS class 承载,避免 columns 依赖 token 导致主题切换重置状态) */
|
||||||
|
|
||||||
|
/** 提取视频时长(秒),非视频输出类型返回 null → 渲染 "-" */
|
||||||
|
function getVideoDuration(record: TaskInfoItemResponseBody): number | null {
|
||||||
|
if (record.output_type === 'video') {
|
||||||
|
return record.ui_params.duration ?? null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 格式化时长:<60s 显示秒,≥60s 显示分秒 */
|
||||||
|
function formatDuration(seconds: number): string {
|
||||||
|
if (seconds < 60) return `${seconds} 秒`;
|
||||||
|
const m = Math.floor(seconds / 60);
|
||||||
|
const s = seconds % 60;
|
||||||
|
return s > 0 ? `${m} 分 ${s} 秒` : `${m} 分钟`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allColumns = useMemo<ColumnsType<TaskInfoItemResponseBody>>(() => {
|
||||||
|
const cols: ColumnsType<TaskInfoItemResponseBody> = [
|
||||||
|
// ---- 任务 ID(固定列) ----
|
||||||
|
{
|
||||||
|
title: '任务 ID',
|
||||||
|
dataIndex: 'id',
|
||||||
|
key: 'id',
|
||||||
|
width: 140,
|
||||||
|
ellipsis: true,
|
||||||
|
fixed: 'left',
|
||||||
|
render: (id: string) => (
|
||||||
|
<Text copyable={{ text: id }} style={{ fontSize: 12, fontFamily: 'monospace' }}>
|
||||||
|
{id.slice(0, 10)}...
|
||||||
|
</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ---- 创建时间 ----
|
||||||
|
{
|
||||||
|
title: '创建时间',
|
||||||
|
dataIndex: 'created_at',
|
||||||
|
key: 'created_at',
|
||||||
|
width: 155,
|
||||||
|
sorter: (a, b) => {
|
||||||
|
const da = a.created_at ? new Date(a.created_at).getTime() : 0;
|
||||||
|
const db = b.created_at ? new Date(b.created_at).getTime() : 0;
|
||||||
|
return da - db;
|
||||||
|
},
|
||||||
|
sortOrder: tableParams.sorter.field === 'created_at' ? tableParams.sorter.order : null,
|
||||||
|
render: (v: Date) => (
|
||||||
|
<Text style={{ fontSize: 11 }}>
|
||||||
|
{v ? new Date(v).toLocaleString('zh-CN', {
|
||||||
|
month: '2-digit', day: '2-digit',
|
||||||
|
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||||||
|
}) : '-'}
|
||||||
|
</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ---- 模型 ----
|
||||||
|
{
|
||||||
|
title: '模型',
|
||||||
|
dataIndex: 'model_name',
|
||||||
|
key: 'model_name',
|
||||||
|
width: 130,
|
||||||
|
ellipsis: true,
|
||||||
|
filters: modelFilters,
|
||||||
|
filteredValue: (tableParams.filters.model_name as string[]) || null,
|
||||||
|
onFilter: () => true, // 服务端筛选
|
||||||
|
filterSearch: true,
|
||||||
|
filterMode: 'menu' as const,
|
||||||
|
},
|
||||||
|
// ---- 输出类型 ----
|
||||||
|
{
|
||||||
|
title: '输出类型',
|
||||||
|
dataIndex: 'output_type',
|
||||||
|
key: 'output_type',
|
||||||
|
width: 90,
|
||||||
|
filters: OUTPUT_TYPE_FILTERS,
|
||||||
|
filteredValue: (tableParams.filters.output_type as string[]) || null,
|
||||||
|
onFilter: (value, record) => record.output_type === value, // 客户端筛选
|
||||||
|
render: (t: string) => (
|
||||||
|
<Tag style={{ fontSize: 10 }}>
|
||||||
|
{OutputTypeMap[t as keyof typeof OutputTypeMap] || t}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ---- 状态 ----
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
key: 'status',
|
||||||
|
width: 80,
|
||||||
|
filters: STATUS_FILTERS,
|
||||||
|
filteredValue: (tableParams.filters.status as string[]) || null,
|
||||||
|
onFilter: () => true, // 服务端筛选
|
||||||
|
render: (s: string) => {
|
||||||
|
const cfg = resolveStatus(s);
|
||||||
|
return <Tag color={cfg.color} style={{ fontSize: 10 }}>{cfg.label}</Tag>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// ---- 提示词 ----
|
||||||
|
{
|
||||||
|
title: '提示词',
|
||||||
|
dataIndex: 'prompt',
|
||||||
|
key: 'prompt',
|
||||||
|
width: 160,
|
||||||
|
ellipsis: true,
|
||||||
|
filterIcon: (filtered: boolean) => (
|
||||||
|
<SearchOutlined className={`prompt-search-icon${filtered ? ' filtered' : ''}`} style={{ fontSize: 12 }} />
|
||||||
|
),
|
||||||
|
filterDropdown: undefined, // TODO: 后续加自定义搜索框
|
||||||
|
render: (p: string | undefined) => (
|
||||||
|
<Text style={{ fontSize: 11 }} title={p}>{p || '-'}</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ---- 时长(仅视频有数据,否则 "-") ----
|
||||||
|
{
|
||||||
|
title: '时长',
|
||||||
|
key: 'duration',
|
||||||
|
width: 75,
|
||||||
|
sorter: (a, b) => {
|
||||||
|
const da = getVideoDuration(a) ?? -1;
|
||||||
|
const db = getVideoDuration(b) ?? -1;
|
||||||
|
return da - db;
|
||||||
|
},
|
||||||
|
sortOrder: tableParams.sorter.field === 'duration' ? tableParams.sorter.order : null,
|
||||||
|
render: (_: unknown, record: TaskInfoItemResponseBody) => {
|
||||||
|
const sec = getVideoDuration(record);
|
||||||
|
return <Text style={{ fontSize: 11 }}>{sec !== null ? formatDuration(sec) : '-'}</Text>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// ---- 费用 ----
|
||||||
|
{
|
||||||
|
title: '费用',
|
||||||
|
dataIndex: 'cost_cent',
|
||||||
|
key: 'cost_cent',
|
||||||
|
width: 75,
|
||||||
|
sorter: (a, b) => a.cost_cent - b.cost_cent,
|
||||||
|
sortOrder: tableParams.sorter.field === 'cost_cent' ? tableParams.sorter.order : null,
|
||||||
|
render: (c: number) => (
|
||||||
|
<Text style={{ fontSize: 11 }}>¥{(c / 100).toFixed(2)}</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ---- 供应商(默认隐藏) ----
|
||||||
|
{
|
||||||
|
title: '供应商',
|
||||||
|
dataIndex: 'provider_name',
|
||||||
|
key: 'provider_name',
|
||||||
|
width: 100,
|
||||||
|
ellipsis: true,
|
||||||
|
filters: providerFilters,
|
||||||
|
filteredValue: (tableParams.filters.provider_name as string[]) || null,
|
||||||
|
onFilter: (value, record) => record.provider_name === value, // 客户端筛选
|
||||||
|
filterSearch: true,
|
||||||
|
},
|
||||||
|
// ---- 帧率(占位列,待后端支持) ----
|
||||||
|
{
|
||||||
|
title: '帧率',
|
||||||
|
key: 'fps',
|
||||||
|
width: 70,
|
||||||
|
render: () => <Text type="secondary" style={{ fontSize: 11 }}>-</Text>,
|
||||||
|
},
|
||||||
|
// ---- 文件大小(占位列,待后端支持) ----
|
||||||
|
{
|
||||||
|
title: '文件大小',
|
||||||
|
key: 'file_size',
|
||||||
|
width: 85,
|
||||||
|
render: () => <Text type="secondary" style={{ fontSize: 11 }}>-</Text>,
|
||||||
|
},
|
||||||
|
// ---- 标签 ----
|
||||||
|
{
|
||||||
|
title: '标签',
|
||||||
|
dataIndex: 'tags',
|
||||||
|
key: 'tags',
|
||||||
|
width: 100,
|
||||||
|
ellipsis: true,
|
||||||
|
render: (tags: Array<string | null>) => {
|
||||||
|
const filtered = tags?.filter((t): t is string => t !== null) ?? [];
|
||||||
|
if (filtered.length === 0) return <Text type="secondary" style={{ fontSize: 11 }}>-</Text>;
|
||||||
|
return (
|
||||||
|
<Space size={2} wrap>
|
||||||
|
{filtered.slice(0, 2).map((t) => (
|
||||||
|
<Tag key={t} style={{ fontSize: 9, lineHeight: '14px', margin: 0 }}>{t}</Tag>
|
||||||
|
))}
|
||||||
|
{filtered.length > 2 && (
|
||||||
|
<Text type="secondary" style={{ fontSize: 9 }}>+{filtered.length - 2}</Text>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// ---- 错误信息(失败任务时展示) ----
|
||||||
|
{
|
||||||
|
title: '错误信息',
|
||||||
|
dataIndex: 'error_message',
|
||||||
|
key: 'error_message',
|
||||||
|
width: 140,
|
||||||
|
ellipsis: true,
|
||||||
|
render: (msg: string) => msg
|
||||||
|
? <Text type="danger" style={{ fontSize: 11 }} title={msg}>{msg}</Text>
|
||||||
|
: <Text type="secondary" style={{ fontSize: 11 }}>-</Text>,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// 用户列:仅企业版可筛选
|
||||||
|
if (isEnterprise) {
|
||||||
|
cols.push({
|
||||||
|
title: '用户',
|
||||||
|
dataIndex: 'user_display_name',
|
||||||
|
key: 'user_id',
|
||||||
|
width: 100,
|
||||||
|
ellipsis: true,
|
||||||
|
filters: userFilters,
|
||||||
|
filteredValue: (tableParams.filters.user_id as string[]) || null,
|
||||||
|
onFilter: () => true, // 服务端筛选(传 user_ids)
|
||||||
|
render: (n: string | null) => (
|
||||||
|
<Text style={{ fontSize: 11 }}>{n || '-'}</Text>
|
||||||
|
),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
cols.push({
|
||||||
|
title: '用户',
|
||||||
|
dataIndex: 'user_display_name',
|
||||||
|
key: 'user_id',
|
||||||
|
width: 100,
|
||||||
|
ellipsis: true,
|
||||||
|
render: (n: string | null) => (
|
||||||
|
<Text style={{ fontSize: 11 }}>{n || '-'}</Text>
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return cols;
|
||||||
|
}, [
|
||||||
|
modelFilters,
|
||||||
|
providerFilters,
|
||||||
|
userFilters,
|
||||||
|
tableParams.filters,
|
||||||
|
tableParams.sorter,
|
||||||
|
isEnterprise,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 按 visibleColumns 过滤实际展示的列
|
||||||
|
const columns = useMemo(
|
||||||
|
() => allColumns.filter((c) => visibleColumns.has(c.key as string)),
|
||||||
|
[allColumns, visibleColumns],
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------- 表格高度 --------
|
||||||
|
//
|
||||||
|
// 核心策略:固定预留 pagination 区域高度,确保无论数据加载时机如何,
|
||||||
|
// 分页器始终有空间渲染,不会溢出可视区。
|
||||||
|
//
|
||||||
|
// scroll.y = wrapper高度 - thead高度 - PAGINATION_RESERVE - 水平滚动条高度
|
||||||
|
//
|
||||||
|
// 为什么固定预留 pagination 而不是动态测量?
|
||||||
|
// - 无数据/加载中时 pagination DOM 尚不存在 → offsetHeight=0 → scroll.y 偏大
|
||||||
|
// - 翻页/切换 pageSize 时 pagination 异步渲染 → 测量时机不可控
|
||||||
|
// - 固定预留值(48px 覆盖 small-size pagination + 上下间距)避免上述所有时序问题
|
||||||
|
|
||||||
|
/** 预留 pagination 高度(small-size: ~32px + 上下 padding/margin 8px × 2) */
|
||||||
|
const PAGINATION_RESERVE = 48;
|
||||||
|
|
||||||
|
const tableWrapperRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [tableBodyHeight, setTableBodyHeight] = useState(400);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const wrapper = tableWrapperRef.current;
|
||||||
|
if (!wrapper) return;
|
||||||
|
|
||||||
|
const calcHeight = () => {
|
||||||
|
const thead = wrapper.querySelector('.ant-table-thead') as HTMLElement | null;
|
||||||
|
const body = wrapper.querySelector('.ant-table-body') as HTMLElement | null;
|
||||||
|
const theadH = thead?.offsetHeight ?? 0;
|
||||||
|
|
||||||
|
// 水平滚动条占用高度(antd Table scroll.x 触发时出现)
|
||||||
|
let hScrollH = 0;
|
||||||
|
if (body && body.scrollWidth > body.clientWidth + 1) {
|
||||||
|
hScrollH = body.offsetHeight - body.clientHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
const available = wrapper.clientHeight - theadH - PAGINATION_RESERVE - hScrollH;
|
||||||
|
setTableBodyHeight(Math.max(120, available));
|
||||||
|
};
|
||||||
|
|
||||||
|
// ResizeObserver:容器尺寸变化(窗口拉伸、面板拖拽)
|
||||||
|
const resizeObserver = new ResizeObserver(calcHeight);
|
||||||
|
resizeObserver.observe(wrapper);
|
||||||
|
|
||||||
|
// MutationObserver:内部 DOM 变化(thead 高度变化如筛选菜单弹出、
|
||||||
|
// 数据加载后水平滚动条出现等)
|
||||||
|
const mutationObserver = new MutationObserver(calcHeight);
|
||||||
|
mutationObserver.observe(wrapper, { childList: true, subtree: true });
|
||||||
|
|
||||||
|
calcHeight();
|
||||||
|
return () => {
|
||||||
|
resizeObserver.disconnect();
|
||||||
|
mutationObserver.disconnect();
|
||||||
|
};
|
||||||
|
}, [taskPageSize]);
|
||||||
|
|
||||||
|
// -------- 行样式:斑马纹 + 选中行 --------
|
||||||
|
|
||||||
|
const rowClassName = (_record: TaskInfoItemResponseBody, index: number) => {
|
||||||
|
const base = index % 2 === 1 ? 'task-row-odd' : 'task-row-even';
|
||||||
|
return selectedTask?.id === _record.id ? `${base} task-row-selected` : base;
|
||||||
|
};
|
||||||
|
|
||||||
|
// -------- 是否有活跃筛选 --------
|
||||||
|
|
||||||
|
const hasActiveFilters = Object.values(tableParams.filters).some(
|
||||||
|
(v) => Array.isArray(v) && v.length > 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
// ======== 渲染 ========
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: 0 }}>
|
||||||
|
{/* 标题栏 */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '6px 12px',
|
||||||
|
borderBottom: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 6,
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<HistoryOutlined style={{ fontSize: 14 }} />
|
||||||
|
<Text strong style={{ fontSize: 13 }}>任务记录</Text>
|
||||||
|
{total > 0 && (
|
||||||
|
<Text type="secondary" style={{ fontSize: 11 }}>共 {total} 条</Text>
|
||||||
|
)}
|
||||||
|
{hasActiveFilters && (
|
||||||
|
<Tag color="blue" style={{ fontSize: 10, lineHeight: '16px', padding: '0 4px' }}>
|
||||||
|
已筛选
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
{errorMessage && (
|
||||||
|
<Text type="danger" style={{ fontSize: 11, marginLeft: 'auto' }}>{errorMessage}</Text>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 列可见性控制 — 齿轮图标 */}
|
||||||
|
<Popover
|
||||||
|
trigger="click"
|
||||||
|
placement="bottomRight"
|
||||||
|
title="显示/隐藏列"
|
||||||
|
content={
|
||||||
|
<Checkbox.Group
|
||||||
|
value={[...visibleColumns]}
|
||||||
|
style={{ display: 'flex', flexDirection: 'column', gap: 2 }}
|
||||||
|
>
|
||||||
|
{ALL_COLUMNS.map((col) => (
|
||||||
|
<Checkbox
|
||||||
|
key={col.key}
|
||||||
|
value={col.key}
|
||||||
|
disabled={col.key === 'id'}
|
||||||
|
onChange={(e) => handleColumnToggle(col.key, e.target.checked)}
|
||||||
|
>
|
||||||
|
{col.title}
|
||||||
|
</Checkbox>
|
||||||
|
))}
|
||||||
|
</Checkbox.Group>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
icon={<SettingOutlined style={{ fontSize: 13 }} />}
|
||||||
|
style={{ marginLeft: 'auto' }}
|
||||||
|
title="列设置"
|
||||||
|
/>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 表格 — 横向 + 纵向滚动,筛选/排序通过列头操作 */}
|
||||||
|
<div ref={tableWrapperRef} style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>
|
||||||
|
<style>{tableCss}</style>
|
||||||
|
<Table<TaskInfoItemResponseBody>
|
||||||
|
className="task-table"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={tasks}
|
||||||
|
rowKey="id"
|
||||||
|
size="small"
|
||||||
|
loading={loading}
|
||||||
|
showHeader={true}
|
||||||
|
scroll={{ x: isEnterprise ? 1350 : 1250, y: tableBodyHeight }}
|
||||||
|
rowClassName={rowClassName}
|
||||||
|
onRow={(record) => ({
|
||||||
|
onClick: () => setSelectedTask(record),
|
||||||
|
style: { cursor: 'pointer' },
|
||||||
|
})}
|
||||||
|
onChange={handleTableChange}
|
||||||
|
pagination={{
|
||||||
|
current: tableParams.pagination.current,
|
||||||
|
pageSize: tableParams.pagination.pageSize,
|
||||||
|
total,
|
||||||
|
size: 'small',
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: ['10', '20', '50'],
|
||||||
|
placement: ['bottomCenter'],
|
||||||
|
style: { marginBottom: 0 },
|
||||||
|
}}
|
||||||
|
locale={{ emptyText: '暂无任务记录', filterReset: '重置', filterConfirm: '确定' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
199
src/pages/login/components/ChangePasswordModal.tsx
Normal file
199
src/pages/login/components/ChangePasswordModal.tsx
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ChangePasswordModal — 修改密码弹窗(已登录用户)
|
||||||
|
//
|
||||||
|
// 场景:已登录用户通过旧密码验证后设置新密码
|
||||||
|
// 复用:可在设置页"修改密码"入口使用,也可在其他位置独立调用
|
||||||
|
//
|
||||||
|
// API:
|
||||||
|
// - AuthAPI.changePassword({ current_password, new_password })
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { Modal, Input, Button, Typography, App } from 'antd';
|
||||||
|
import { LockOutlined, KeyOutlined, SafetyOutlined } from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { useTheme } from '@/hooks/use-theme.ts';
|
||||||
|
import { AuthAPI } from '@/services/modules';
|
||||||
|
import { validatePassword, validateConfirmPassword } from '../config/validators';
|
||||||
|
|
||||||
|
const { Text, Title } = Typography;
|
||||||
|
|
||||||
|
interface ChangePasswordModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
|
||||||
|
const { isDark } = useTheme();
|
||||||
|
const { message } = App.useApp();
|
||||||
|
|
||||||
|
// ---- 表单字段 ----
|
||||||
|
const [currentPassword, setCurrentPassword] = useState('');
|
||||||
|
const [newPassword, setNewPassword] = useState('');
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
|
|
||||||
|
// ---- 错误信息 ----
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
// ---- 提交状态 ----
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
// ---- 清除单个字段错误 ----
|
||||||
|
const clearError = useCallback((name: string) => {
|
||||||
|
setErrors((p) => {
|
||||||
|
if (!(name in p)) return p;
|
||||||
|
const n = { ...p };
|
||||||
|
delete n[name];
|
||||||
|
return n;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ---- 提交 ----
|
||||||
|
const handleSubmit = useCallback(async () => {
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (!currentPassword) {
|
||||||
|
newErrors.currentPassword = '请输入当前密码';
|
||||||
|
}
|
||||||
|
const pwdErr = validatePassword(newPassword);
|
||||||
|
if (pwdErr) newErrors.newPassword = pwdErr;
|
||||||
|
const confirmErr = validateConfirmPassword(confirmPassword, newPassword);
|
||||||
|
if (confirmErr) newErrors.confirmPassword = confirmErr;
|
||||||
|
|
||||||
|
if (Object.keys(newErrors).length > 0) {
|
||||||
|
setErrors(newErrors);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors({});
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await AuthAPI.changePassword({
|
||||||
|
current_password: currentPassword,
|
||||||
|
new_password: newPassword,
|
||||||
|
});
|
||||||
|
message.success('密码修改成功');
|
||||||
|
// 重置表单
|
||||||
|
setCurrentPassword('');
|
||||||
|
setNewPassword('');
|
||||||
|
setConfirmPassword('');
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
message.error((err as Error).message || '密码修改失败');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
}, [currentPassword, newPassword, confirmPassword, onClose, message]);
|
||||||
|
|
||||||
|
// ---- 关闭时重置错误 ----
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
setErrors({});
|
||||||
|
onClose();
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onCancel={handleClose}
|
||||||
|
footer={null}
|
||||||
|
width={440}
|
||||||
|
centered
|
||||||
|
destroyOnHidden={true}
|
||||||
|
mask={{ closable: false }}
|
||||||
|
styles={{
|
||||||
|
body: {
|
||||||
|
padding: '24px 32px 16px',
|
||||||
|
background: isDark ? '#1A1730' : '#FFFFFF',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 标题 */}
|
||||||
|
<div className="text-center mb-5">
|
||||||
|
<Title level={5} className="!mb-1 gradient-primary-text">
|
||||||
|
修改密码
|
||||||
|
</Title>
|
||||||
|
<Text type="secondary" className="text-xs">
|
||||||
|
请输入当前密码并设置新密码
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 表单 */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 当前密码 */}
|
||||||
|
<div>
|
||||||
|
<Input.Password
|
||||||
|
size="large"
|
||||||
|
prefix={<SafetyOutlined className="opacity-40" />}
|
||||||
|
placeholder="当前密码"
|
||||||
|
value={currentPassword}
|
||||||
|
onChange={(e) => {
|
||||||
|
setCurrentPassword(e.target.value);
|
||||||
|
clearError('currentPassword');
|
||||||
|
}}
|
||||||
|
status={errors.currentPassword ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.currentPassword && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.currentPassword}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 新密码 */}
|
||||||
|
<div>
|
||||||
|
<Input.Password
|
||||||
|
size="large"
|
||||||
|
prefix={<LockOutlined className="opacity-40" />}
|
||||||
|
placeholder="新密码(6~128位)"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNewPassword(e.target.value);
|
||||||
|
clearError('newPassword');
|
||||||
|
}}
|
||||||
|
status={errors.newPassword ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.newPassword && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.newPassword}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 确认新密码 */}
|
||||||
|
<div>
|
||||||
|
<Input.Password
|
||||||
|
size="large"
|
||||||
|
prefix={<KeyOutlined className="opacity-40" />}
|
||||||
|
placeholder="请再次输入新密码"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => {
|
||||||
|
setConfirmPassword(e.target.value);
|
||||||
|
clearError('confirmPassword');
|
||||||
|
}}
|
||||||
|
status={errors.confirmPassword ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.confirmPassword && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.confirmPassword}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 提交按钮 */}
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
loading={submitting}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
className="h-11! text-base! font-medium! mt-2!"
|
||||||
|
>
|
||||||
|
确认修改
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
265
src/pages/login/components/ForgotPasswordModal.tsx
Normal file
265
src/pages/login/components/ForgotPasswordModal.tsx
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ForgotPasswordModal — 忘记密码弹窗
|
||||||
|
//
|
||||||
|
// 场景:未登录用户通过手机号 + 短信验证码重置密码
|
||||||
|
// 复用:可在登录页"忘记密码?"入口使用,也可在其他位置独立调用
|
||||||
|
//
|
||||||
|
// API:
|
||||||
|
// - AuthAPI.sendSms({ phone }) 发送短信验证码
|
||||||
|
// - AuthAPI.resetPassword({ phone, sms_code, new_password }) 重置密码
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { Modal, Input, Button, Typography, App } from 'antd';
|
||||||
|
import {
|
||||||
|
PhoneOutlined,
|
||||||
|
SafetyCertificateOutlined,
|
||||||
|
LockOutlined,
|
||||||
|
KeyOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { useTheme } from '@/hooks/use-theme.ts';
|
||||||
|
import { AuthAPI } from '@/services/modules';
|
||||||
|
import {
|
||||||
|
validatePhone,
|
||||||
|
validateSmsCode,
|
||||||
|
validatePassword,
|
||||||
|
validateConfirmPassword,
|
||||||
|
} from '../config/validators';
|
||||||
|
import { useSmsCooldown } from '../hooks/use-sms-cooldown';
|
||||||
|
|
||||||
|
const { Text, Title } = Typography;
|
||||||
|
|
||||||
|
interface ForgotPasswordModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ForgotPasswordModal({ open, onClose }: ForgotPasswordModalProps) {
|
||||||
|
const { isDark } = useTheme();
|
||||||
|
const { message } = App.useApp();
|
||||||
|
|
||||||
|
// ---- 表单字段 ----
|
||||||
|
const [phone, setPhone] = useState('');
|
||||||
|
const [smsCode, setSmsCode] = useState('');
|
||||||
|
const [newPassword, setNewPassword] = useState('');
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
|
|
||||||
|
// ---- 错误信息 ----
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
// ---- 提交状态 ----
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
// ---- 短信冷却 ----
|
||||||
|
const { cooldown, secondsLeft, startCooldown } = useSmsCooldown(60);
|
||||||
|
|
||||||
|
// ---- 清除单个字段错误 ----
|
||||||
|
const clearError = useCallback((name: string) => {
|
||||||
|
setErrors((p) => {
|
||||||
|
if (!(name in p)) return p;
|
||||||
|
const n = { ...p };
|
||||||
|
delete n[name];
|
||||||
|
return n;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ---- 发送验证码 ----
|
||||||
|
const handleSendSms = useCallback(() => {
|
||||||
|
const err = validatePhone(phone);
|
||||||
|
if (err) {
|
||||||
|
setErrors((p) => ({ ...p, phone: err }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearError('phone');
|
||||||
|
startCooldown();
|
||||||
|
AuthAPI.sendSms({ phone })
|
||||||
|
.then(() => message.success('验证码已发送'))
|
||||||
|
.catch((e) => message.error((e as Error).message || '验证码发送失败'));
|
||||||
|
}, [phone, startCooldown, clearError, message]);
|
||||||
|
|
||||||
|
// ---- 提交重置 ----
|
||||||
|
const handleSubmit = useCallback(async () => {
|
||||||
|
// 逐字段校验
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
const phoneErr = validatePhone(phone);
|
||||||
|
if (phoneErr) newErrors.phone = phoneErr;
|
||||||
|
const smsErr = validateSmsCode(smsCode);
|
||||||
|
if (smsErr) newErrors.smsCode = smsErr;
|
||||||
|
const pwdErr = validatePassword(newPassword);
|
||||||
|
if (pwdErr) newErrors.newPassword = pwdErr;
|
||||||
|
const confirmErr = validateConfirmPassword(confirmPassword, newPassword);
|
||||||
|
if (confirmErr) newErrors.confirmPassword = confirmErr;
|
||||||
|
|
||||||
|
if (Object.keys(newErrors).length > 0) {
|
||||||
|
setErrors(newErrors);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors({});
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await AuthAPI.resetPassword({
|
||||||
|
phone,
|
||||||
|
sms_code: smsCode,
|
||||||
|
new_password: newPassword,
|
||||||
|
});
|
||||||
|
message.success('密码重置成功,请使用新密码登录');
|
||||||
|
// 重置表单状态
|
||||||
|
setPhone('');
|
||||||
|
setSmsCode('');
|
||||||
|
setNewPassword('');
|
||||||
|
setConfirmPassword('');
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
message.error((err as Error).message || '密码重置失败');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
}, [phone, smsCode, newPassword, confirmPassword, onClose, message]);
|
||||||
|
|
||||||
|
// ---- 关闭时重置 ----
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
setErrors({});
|
||||||
|
onClose();
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onCancel={handleClose}
|
||||||
|
footer={null}
|
||||||
|
width={440}
|
||||||
|
centered
|
||||||
|
destroyOnHidden={true}
|
||||||
|
mask={{ closable: false }}
|
||||||
|
styles={{
|
||||||
|
body: {
|
||||||
|
padding: '24px 32px 16px',
|
||||||
|
background: isDark ? '#1A1730' : '#FFFFFF',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 标题 */}
|
||||||
|
<div className="text-center mb-5">
|
||||||
|
<Title level={5} className="!mb-1 gradient-primary-text">
|
||||||
|
重置密码
|
||||||
|
</Title>
|
||||||
|
<Text type="secondary" className="text-xs">
|
||||||
|
通过手机短信验证码重置您的密码
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 表单 */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 手机号 */}
|
||||||
|
<div>
|
||||||
|
<Input
|
||||||
|
size="large"
|
||||||
|
prefix={<PhoneOutlined className="opacity-40" />}
|
||||||
|
placeholder="请输入手机号"
|
||||||
|
value={phone}
|
||||||
|
onChange={(e) => {
|
||||||
|
setPhone(e.target.value);
|
||||||
|
clearError('phone');
|
||||||
|
}}
|
||||||
|
status={errors.phone ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.phone && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.phone}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 短信验证码 */}
|
||||||
|
<div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
size="large"
|
||||||
|
prefix={<SafetyCertificateOutlined className="opacity-40" />}
|
||||||
|
placeholder="请输入验证码"
|
||||||
|
value={smsCode}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSmsCode(e.target.value);
|
||||||
|
clearError('smsCode');
|
||||||
|
}}
|
||||||
|
status={errors.smsCode ? 'error' : undefined}
|
||||||
|
className="flex-1"
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
size="large"
|
||||||
|
type="primary"
|
||||||
|
disabled={cooldown}
|
||||||
|
onClick={handleSendSms}
|
||||||
|
className="text-xs! shrink-0 px-3!"
|
||||||
|
>
|
||||||
|
{cooldown ? `${secondsLeft}s` : '发送验证码'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{errors.smsCode && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.smsCode}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 新密码 */}
|
||||||
|
<div>
|
||||||
|
<Input.Password
|
||||||
|
size="large"
|
||||||
|
prefix={<LockOutlined className="opacity-40" />}
|
||||||
|
placeholder="新密码(6~128位)"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNewPassword(e.target.value);
|
||||||
|
clearError('newPassword');
|
||||||
|
}}
|
||||||
|
status={errors.newPassword ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.newPassword && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.newPassword}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 确认新密码 */}
|
||||||
|
<div>
|
||||||
|
<Input.Password
|
||||||
|
size="large"
|
||||||
|
prefix={<KeyOutlined className="opacity-40" />}
|
||||||
|
placeholder="请再次输入新密码"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => {
|
||||||
|
setConfirmPassword(e.target.value);
|
||||||
|
clearError('confirmPassword');
|
||||||
|
}}
|
||||||
|
status={errors.confirmPassword ? 'error' : undefined}
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
{errors.confirmPassword && (
|
||||||
|
<Text type="danger" className="text-xs ml-1">
|
||||||
|
{errors.confirmPassword}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 提交按钮 */}
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
loading={submitting}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
className="h-11! text-base! font-medium! mt-2!"
|
||||||
|
>
|
||||||
|
重置密码
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -22,6 +22,7 @@ interface LoginFormProps {
|
|||||||
onSubmit: (values: LoginFormValues) => void;
|
onSubmit: (values: LoginFormValues) => void;
|
||||||
onRememberChange: (checked: boolean) => void;
|
onRememberChange: (checked: boolean) => void;
|
||||||
onAutoLoginChange: (checked: boolean) => void;
|
onAutoLoginChange: (checked: boolean) => void;
|
||||||
|
onForgotPassword?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LoginForm({
|
export function LoginForm({
|
||||||
@@ -33,6 +34,7 @@ export function LoginForm({
|
|||||||
onSubmit,
|
onSubmit,
|
||||||
onRememberChange,
|
onRememberChange,
|
||||||
onAutoLoginChange,
|
onAutoLoginChange,
|
||||||
|
onForgotPassword,
|
||||||
}: LoginFormProps) {
|
}: LoginFormProps) {
|
||||||
const [username, setUsername] = useState(initialUsername || '');
|
const [username, setUsername] = useState(initialUsername || '');
|
||||||
const [password, setPassword] = useState(initialPassword || '');
|
const [password, setPassword] = useState(initialPassword || '');
|
||||||
@@ -147,12 +149,7 @@ export function LoginForm({
|
|||||||
自动登录
|
自动登录
|
||||||
</Checkbox>
|
</Checkbox>
|
||||||
</div>
|
</div>
|
||||||
<a
|
<a className="text-xs" onClick={() => onForgotPassword?.()}>
|
||||||
className="text-xs"
|
|
||||||
onClick={() => {
|
|
||||||
/* TODO: 忘记密码流程 */
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
忘记密码?
|
忘记密码?
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
57
src/pages/login/hooks/use-sms-cooldown.ts
Normal file
57
src/pages/login/hooks/use-sms-cooldown.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
// ============================================================
|
||||||
|
// useSmsCooldown — 短信验证码发送冷却 Hook
|
||||||
|
//
|
||||||
|
// 从 RegisterForm 提取,供所有需要短信验证码的场景复用:
|
||||||
|
// - 注册(RegisterForm)
|
||||||
|
// - 忘记密码(ForgotPasswordModal)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||||
|
|
||||||
|
export interface SmsCooldownState {
|
||||||
|
/** 是否在冷却中 */
|
||||||
|
cooldown: boolean;
|
||||||
|
/** 冷却剩余秒数 */
|
||||||
|
secondsLeft: number;
|
||||||
|
/** 开始冷却 */
|
||||||
|
startCooldown: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSmsCooldown(cooldownSeconds: number = 60): SmsCooldownState {
|
||||||
|
const [cooldown, setCooldown] = useState(false);
|
||||||
|
const [secondsLeft, setSecondsLeft] = useState(0);
|
||||||
|
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
|
|
||||||
|
const startCooldown = useCallback(() => {
|
||||||
|
// 清理之前的计时器(防止重复点击导致多个计时器叠加)
|
||||||
|
if (timerRef.current) {
|
||||||
|
clearInterval(timerRef.current);
|
||||||
|
}
|
||||||
|
setCooldown(true);
|
||||||
|
setSecondsLeft(cooldownSeconds);
|
||||||
|
timerRef.current = setInterval(() => {
|
||||||
|
setSecondsLeft((prev) => {
|
||||||
|
if (prev <= 1) {
|
||||||
|
if (timerRef.current) {
|
||||||
|
clearInterval(timerRef.current);
|
||||||
|
timerRef.current = null;
|
||||||
|
}
|
||||||
|
setCooldown(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return prev - 1;
|
||||||
|
});
|
||||||
|
}, 1000);
|
||||||
|
}, [cooldownSeconds]);
|
||||||
|
|
||||||
|
// 组件卸载时清理计时器
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (timerRef.current) {
|
||||||
|
clearInterval(timerRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { cooldown, secondsLeft, startCooldown };
|
||||||
|
}
|
||||||
@@ -14,8 +14,9 @@ import { useAppContext } from '@/contexts/app-context.ts';
|
|||||||
import { useTheme } from '@/hooks/use-theme.ts';
|
import { useTheme } from '@/hooks/use-theme.ts';
|
||||||
import { LoginForm } from './components/LoginForm';
|
import { LoginForm } from './components/LoginForm';
|
||||||
import { RegisterForm } from './components/RegisterForm';
|
import { RegisterForm } from './components/RegisterForm';
|
||||||
|
import { ForgotPasswordModal } from './components/ForgotPasswordModal';
|
||||||
import { useAuthState } from './hooks/use-auth-state';
|
import { useAuthState } from './hooks/use-auth-state';
|
||||||
import {AuthAPI, LoginResponseBody} from '@/services/modules';
|
import { AuthAPI, LoginResponseBody } from '@/services/modules';
|
||||||
import { getDeviceId } from '@/utils/device';
|
import { getDeviceId } from '@/utils/device';
|
||||||
import type { LoginFormValues, RegisterFormValues } from './types';
|
import type { LoginFormValues, RegisterFormValues } from './types';
|
||||||
|
|
||||||
@@ -27,13 +28,13 @@ interface LoginPageProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function LoginPage({ open, onClose }: LoginPageProps) {
|
export function LoginPage({ open, onClose }: LoginPageProps) {
|
||||||
const { edition, login } = useAppContext();
|
const { login } = useAppContext();
|
||||||
const { isDark } = useTheme();
|
const { isDark } = useTheme();
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
|
|
||||||
const isEnterprise = edition === 'enterprise';
|
|
||||||
const [activeTab, setActiveTab] = useState<string>('login');
|
const [activeTab, setActiveTab] = useState<string>('login');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [forgotOpen, setForgotOpen] = useState(false);
|
||||||
|
|
||||||
const authState = useAuthState();
|
const authState = useAuthState();
|
||||||
|
|
||||||
@@ -43,7 +44,7 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
|||||||
async (values: LoginFormValues) => {
|
async (values: LoginFormValues) => {
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const auth:LoginResponseBody = await AuthAPI.login({
|
const auth: LoginResponseBody = await AuthAPI.login({
|
||||||
username: values.username,
|
username: values.username,
|
||||||
password: values.password,
|
password: values.password,
|
||||||
device_id: getDeviceId(),
|
device_id: getDeviceId(),
|
||||||
@@ -111,13 +112,13 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
|||||||
const loginTab = (
|
const loginTab = (
|
||||||
<LoginForm
|
<LoginForm
|
||||||
initialUsername={authState.username}
|
initialUsername={authState.username}
|
||||||
|
|
||||||
initialRemember={authState.remember}
|
initialRemember={authState.remember}
|
||||||
initialAutoLogin={authState.autoLogin}
|
initialAutoLogin={authState.autoLogin}
|
||||||
submitting={submitting}
|
submitting={submitting}
|
||||||
onSubmit={handleLogin}
|
onSubmit={handleLogin}
|
||||||
onRememberChange={authState.handleRememberChange}
|
onRememberChange={authState.handleRememberChange}
|
||||||
onAutoLoginChange={authState.handleAutoLoginChange}
|
onAutoLoginChange={authState.handleAutoLoginChange}
|
||||||
|
onForgotPassword={() => setForgotOpen(true)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -126,6 +127,7 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
onCancel={onClose}
|
onCancel={onClose}
|
||||||
@@ -149,14 +151,10 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
|||||||
船长 · HeiXiu
|
船长 · HeiXiu
|
||||||
</Text>
|
</Text>
|
||||||
<Text type="secondary" className="text-xs">
|
<Text type="secondary" className="text-xs">
|
||||||
{isEnterprise ? '企业版 — 员工账号登录' : '个人版'}
|
欢迎使用船长·HeiXiu
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 个人版 Tab | 企业版仅登录 */}
|
|
||||||
{isEnterprise ? (
|
|
||||||
loginTab
|
|
||||||
) : (
|
|
||||||
<Tabs
|
<Tabs
|
||||||
activeKey={activeTab}
|
activeKey={activeTab}
|
||||||
onChange={setActiveTab}
|
onChange={setActiveTab}
|
||||||
@@ -167,7 +165,10 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
|||||||
{ key: 'register', label: '注册', children: registerTab },
|
{ key: 'register', label: '注册', children: registerTab },
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
{/* 忘记密码弹窗 */}
|
||||||
|
<ForgotPasswordModal open={forgotOpen} onClose={() => setForgotOpen(false)} />
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
11
src/pages/orders/OrdersPage.tsx
Normal file
11
src/pages/orders/OrdersPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// OrdersPage — 订单明细(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function OrdersPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>订单明细 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/pages/projects/ProjectsPage.tsx
Normal file
11
src/pages/projects/ProjectsPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ProjectsPage — 项目管理(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function ProjectsPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>项目管理 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/pages/quota/QuotaPage.tsx
Normal file
11
src/pages/quota/QuotaPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// QuotaPage — 查配额(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function QuotaPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>查配额 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/pages/recharge/RechargePage.tsx
Normal file
11
src/pages/recharge/RechargePage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// RechargePage — 充值积分(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function RechargePage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>充值积分 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,39 +1,39 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// SettingsPage — 设置页面(路由命中 /settings 时以居中 Modal 叠加展示)
|
// SettingsPage — 设置页面(Modal 居中叠加,事件驱动显隐)
|
||||||
//
|
//
|
||||||
// 核心设计:
|
// 核心设计:
|
||||||
// - 独立于 <Routes> 之外,通过 useLocation 判断是否渲染
|
// - 通过 open/onClose props 控制显隐,不使用路由(避免主页面被卸载)
|
||||||
// - 命中 /settings → Modal 居中弹出,首页内容保持在背景不动
|
// - Modal 居中弹出 + 遮罩层,首页内容始终保持挂载不动
|
||||||
// - 关闭 Modal → navigate(-1),仅可通过 X 按钮关闭
|
// - destroyOnHidden → 关闭即销毁 DOM,不堆内存
|
||||||
// - destroyOnClose → 关闭即销毁 DOM,不堆内存
|
// - 仅可通过标题栏 X 按钮关闭(mask 不可关闭、ESC 禁用)
|
||||||
|
//
|
||||||
|
// 对应 QT 原版:设置窗口为独立窗口叠加在主窗口之上,主窗口不销毁
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import {Modal} from 'antd';
|
import { Modal } from 'antd';
|
||||||
import {SettingOutlined} from '@ant-design/icons';
|
import { SettingOutlined } from '@ant-design/icons';
|
||||||
import {useLocation, useNavigate} from 'react-router-dom';
|
import { useAppContext } from '@/contexts/app-context';
|
||||||
import {useAppContext} from '@/contexts/app-context';
|
import { ThemeSetting } from './blocks/ThemeSetting';
|
||||||
import {ThemeSetting} from './ThemeSetting';
|
import { StoragePathSetting } from './blocks/StoragePathSetting';
|
||||||
import {StoragePathSetting} from './StoragePathSetting';
|
import { SystemInfoSetting } from './blocks/SystemInfoSetting';
|
||||||
import {SystemInfoSetting} from './SystemInfoSetting';
|
import { UpdateSetting } from './blocks/UpdateSetting';
|
||||||
import {UpdateSetting} from './UpdateSetting';
|
import { PasswordSetting } from './blocks/PasswordSetting';
|
||||||
|
|
||||||
export function SettingsPage() {
|
interface SettingsPageProps {
|
||||||
const location = useLocation();
|
open: boolean;
|
||||||
const navigate = useNavigate();
|
onClose: () => void;
|
||||||
const {edition} = useAppContext();
|
}
|
||||||
const open = location.pathname === '/settings';
|
|
||||||
|
export function SettingsPage({ open, onClose }: SettingsPageProps) {
|
||||||
|
const { edition } = useAppContext();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
width={480}
|
width={480}
|
||||||
onCancel={() => navigate(-1)}
|
onCancel={onClose}
|
||||||
destroyOnHidden={true}
|
destroyOnHidden={true}
|
||||||
mask={
|
mask={{ closable: false }}
|
||||||
{
|
|
||||||
closable: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
keyboard={false}
|
keyboard={false}
|
||||||
footer={null}
|
footer={null}
|
||||||
title={
|
title={
|
||||||
@@ -42,13 +42,14 @@ export function SettingsPage() {
|
|||||||
设置
|
设置
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
styles={{body: {padding: 0, maxHeight: '70vh', overflow: 'auto'}}}
|
styles={{ body: { padding: 0, maxHeight: '70vh', overflow: 'auto' } }}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col gap-4 p-4">
|
<div className="flex flex-col gap-4 p-4">
|
||||||
<ThemeSetting />
|
<ThemeSetting />
|
||||||
<StoragePathSetting edition={edition} />
|
|
||||||
<SystemInfoSetting />
|
<SystemInfoSetting />
|
||||||
<UpdateSetting />
|
<UpdateSetting />
|
||||||
|
<StoragePathSetting edition={edition} />
|
||||||
|
<PasswordSetting />
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
|||||||
52
src/pages/settings/blocks/PasswordSetting.tsx
Normal file
52
src/pages/settings/blocks/PasswordSetting.tsx
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
// ============================================================
|
||||||
|
// PasswordSetting — 账号安全区块(密码操作入口)
|
||||||
|
//
|
||||||
|
// 提供两种密码操作,用户自选:
|
||||||
|
// 1. 修改密码 — 通过当前密码验证后设置新密码
|
||||||
|
// 2. 忘记密码 — 通过手机短信验证码重置密码
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Card, Button, Typography } from 'antd';
|
||||||
|
import { LockOutlined, PhoneOutlined } from '@ant-design/icons';
|
||||||
|
|
||||||
|
import { ChangePasswordModal } from '@/pages/login/components/ChangePasswordModal';
|
||||||
|
import { ForgotPasswordModal } from '@/pages/login/components/ForgotPasswordModal';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
export function PasswordSetting() {
|
||||||
|
const [changePwdOpen, setChangePwdOpen] = useState(false);
|
||||||
|
const [forgotPwdOpen, setForgotPwdOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card size="small" title="账号安全" className="rounded-md!">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{/* 修改密码:通过旧密码 */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Text type="secondary" className="text-sm">
|
||||||
|
通过当前密码修改
|
||||||
|
</Text>
|
||||||
|
<Button icon={<LockOutlined />} onClick={() => setChangePwdOpen(true)}>
|
||||||
|
修改密码
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 忘记密码:通过手机验证码重置 */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Text type="secondary" className="text-sm">
|
||||||
|
忘记密码?通过手机验证码重置
|
||||||
|
</Text>
|
||||||
|
<Button icon={<PhoneOutlined />} onClick={() => setForgotPwdOpen(true)}>
|
||||||
|
短信验证码重置
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<ChangePasswordModal open={changePwdOpen} onClose={() => setChangePwdOpen(false)} />
|
||||||
|
<ForgotPasswordModal open={forgotPwdOpen} onClose={() => setForgotPwdOpen(false)} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -159,8 +159,14 @@ function PathRow({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function StoragePathSetting({ edition }: StoragePathSettingProps) {
|
export function StoragePathSetting({ edition }: StoragePathSettingProps) {
|
||||||
const { outputPath, teamRepoPath, setOutputPath, setTeamRepoPath, clearOutputPath, clearTeamRepoPath } =
|
const {
|
||||||
useSettings();
|
outputPath,
|
||||||
|
teamRepoPath,
|
||||||
|
setOutputPath,
|
||||||
|
setTeamRepoPath,
|
||||||
|
clearOutputPath,
|
||||||
|
clearTeamRepoPath,
|
||||||
|
} = useSettings();
|
||||||
|
|
||||||
const isEnterprise = edition === 'enterprise';
|
const isEnterprise = edition === 'enterprise';
|
||||||
|
|
||||||
@@ -46,14 +46,14 @@ export function SystemInfoSetting() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card size="small" title="系统信息" className="rounded-md!">
|
<Card size="small" title="系统信息(开发显示信息)" className="rounded-md!">
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{infoItems.map((item) => (
|
{infoItems.map((item) => (
|
||||||
<div key={item.label} className="flex items-center gap-2">
|
<div key={item.label} className="flex items-center gap-2">
|
||||||
<span style={{ color: 'var(--color-primary, #4F46E5)', fontSize: 14 }}>
|
<span style={{ color: 'var(--color-primary, #4F46E5)', fontSize: 14 }}>
|
||||||
{item.icon}
|
{item.icon}
|
||||||
</span>
|
</span>
|
||||||
<Text type="secondary" className="text-sm min-w-[64px]">
|
<Text type="secondary" className="text-sm min-w-16">
|
||||||
{item.label}:
|
{item.label}:
|
||||||
</Text>
|
</Text>
|
||||||
<Tag color={item.color}>{item.value}</Tag>
|
<Tag color={item.color}>{item.value}</Tag>
|
||||||
@@ -65,15 +65,8 @@ function renderChangelog(markdown: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function UpdateSetting() {
|
export function UpdateSetting() {
|
||||||
const {
|
const { status, info, progress, error, checkForUpdates, downloadUpdate, installUpdate } =
|
||||||
status,
|
useUpdater();
|
||||||
info,
|
|
||||||
progress,
|
|
||||||
error,
|
|
||||||
checkForUpdates,
|
|
||||||
downloadUpdate,
|
|
||||||
installUpdate,
|
|
||||||
} = useUpdater();
|
|
||||||
|
|
||||||
const [detailOpen, setDetailOpen] = useState(false);
|
const [detailOpen, setDetailOpen] = useState(false);
|
||||||
|
|
||||||
@@ -210,15 +203,15 @@ export function UpdateSetting() {
|
|||||||
title={`更新详情 — v${info?.version || ''}`}
|
title={`更新详情 — v${info?.version || ''}`}
|
||||||
open={detailOpen}
|
open={detailOpen}
|
||||||
onCancel={() => setDetailOpen(false)}
|
onCancel={() => setDetailOpen(false)}
|
||||||
footer={
|
footer={<Button onClick={() => setDetailOpen(false)}>关闭</Button>}
|
||||||
<Button onClick={() => setDetailOpen(false)}>关闭</Button>
|
|
||||||
}
|
|
||||||
width={520}
|
width={520}
|
||||||
>
|
>
|
||||||
<div className="max-h-96 overflow-y-auto py-2">
|
<div className="max-h-96 overflow-y-auto py-2">
|
||||||
{info?.releaseNotes
|
{info?.releaseNotes ? (
|
||||||
? renderChangelog(info.releaseNotes)
|
renderChangelog(info.releaseNotes)
|
||||||
: <Text type="secondary">暂无更新详情</Text>}
|
) : (
|
||||||
|
<Text type="secondary">暂无更新详情</Text>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -3,7 +3,3 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
export { SettingsPage } from './SettingsPage';
|
export { SettingsPage } from './SettingsPage';
|
||||||
export { ThemeSetting } from './ThemeSetting';
|
|
||||||
export { StoragePathSetting } from './StoragePathSetting';
|
|
||||||
export { SystemInfoSetting } from './SystemInfoSetting';
|
|
||||||
export { UpdateSetting } from './UpdateSetting';
|
|
||||||
|
|||||||
11
src/pages/vip/VipPage.tsx
Normal file
11
src/pages/vip/VipPage.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// ============================================================
|
||||||
|
// VipPage — 开会员/激活(占位组件,后续实现具体功能)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export function VipPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 8 }}>
|
||||||
|
<p style={{ color: 'inherit', opacity: 0.6, margin: 0 }}>开会员/激活 — 页面开发中</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
98
src/pages/wechat-work/WechatWorkPage.tsx
Normal file
98
src/pages/wechat-work/WechatWorkPage.tsx
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
// ============================================================
|
||||||
|
// WechatWorkPage — 企业微信二维码 Modal 内容
|
||||||
|
//
|
||||||
|
// 点击导航栏"企业微信"后以 Modal 形式展示二维码。
|
||||||
|
// 数据来源:GET /api/v1/creatives(Banner API)
|
||||||
|
//
|
||||||
|
// 识别逻辑:Banner 中 category === 'promotion' 的条目,
|
||||||
|
// 其 image_url 为企业微信二维码图片
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
|
import { Spin, Empty } from 'antd';
|
||||||
|
import { WechatOutlined } from '@ant-design/icons';
|
||||||
|
import { fetchBanners, type Banner } from '@/services/modules';
|
||||||
|
|
||||||
|
export function WechatWorkPage() {
|
||||||
|
const [banner, setBanner] = useState<Banner | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const list = await fetchBanners();
|
||||||
|
// category === 'promotion' → 企业微信二维码
|
||||||
|
const promotion = list.find(
|
||||||
|
(item) => item.is_active && item.category === 'promotion',
|
||||||
|
);
|
||||||
|
setBanner(promotion ?? null);
|
||||||
|
} catch (err) {
|
||||||
|
setError((err as Error).message || '加载失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
// 加载态
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>
|
||||||
|
<Spin description="加载中..." />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 无数据 / 错误
|
||||||
|
if (error || !banner || !banner.image_url) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>
|
||||||
|
<Empty
|
||||||
|
image={<WechatOutlined style={{ fontSize: 48, color: '#9CA3AF' }} />}
|
||||||
|
description={error || '暂未获取到企业微信二维码,请联系管理员'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: 8 }}>
|
||||||
|
{/* 二维码图片 */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: 240,
|
||||||
|
height: 240,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
borderRadius: 8,
|
||||||
|
background: '#fff',
|
||||||
|
border: '1px solid #E5E7EB',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={banner.image_url}
|
||||||
|
alt="企业微信二维码"
|
||||||
|
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 标题(如果 Banner 有标题则显示) */}
|
||||||
|
{banner.title && (
|
||||||
|
<p style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'inherit' }}>
|
||||||
|
{banner.title}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 提示文字 */}
|
||||||
|
<p style={{ margin: 0, fontSize: 13, color: 'inherit', opacity: 0.5 }}>
|
||||||
|
请使用微信扫描二维码添加企业微信
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
// ============================================================
|
|
||||||
// AppRoutes — 应用路由配置(由 App.tsx 在 HashRouter 内使用)
|
|
||||||
//
|
|
||||||
// 核心设计:
|
|
||||||
// - SettingsPage 在 <Routes> 外部,路由命中时以 Drawer 叠加首页
|
|
||||||
// - 首页始终保持挂载,不会因导航而卸载
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
import { Routes, Route } from 'react-router-dom';
|
|
||||||
import { Layout } from '@/components/Layout';
|
|
||||||
import { HomePage } from '@/pages/home/HomePage';
|
|
||||||
import { SettingsPage } from '@/pages/settings';
|
|
||||||
|
|
||||||
export function AppRoutes() {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Routes>
|
|
||||||
<Route path="/*" element={<Layout />}>
|
|
||||||
<Route index element={<HomePage />} />
|
|
||||||
</Route>
|
|
||||||
</Routes>
|
|
||||||
{/* 独立于 Routes:根据 URL /settings 自动显隐 Drawer */}
|
|
||||||
<SettingsPage />
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@ import {post, get} from '../request';
|
|||||||
const AuthUrlObj = {
|
const AuthUrlObj = {
|
||||||
login: '/api/v1/auth/login',
|
login: '/api/v1/auth/login',
|
||||||
register: '/api/v1/auth/register',
|
register: '/api/v1/auth/register',
|
||||||
sendSms: '/api/v1/auth/sms/send',
|
sendSms: '/api/v1/auth/send-sms',
|
||||||
refreshToken: '/api/v1/auth/refresh',
|
refreshToken: '/api/v1/auth/refresh',
|
||||||
userInfo: '/api/v1/auth/me',
|
userInfo: '/api/v1/auth/me',
|
||||||
changePassword: '/api/v1/auth/change-password',
|
changePassword: '/api/v1/auth/change-password',
|
||||||
@@ -149,42 +149,42 @@ export interface UsePhoneResetPasswordRequestBody {
|
|||||||
|
|
||||||
export class AuthAPI {
|
export class AuthAPI {
|
||||||
/** 登录 */
|
/** 登录 */
|
||||||
static login(data: LoginRequestBody): Promise<LoginResponseBody> {
|
static async login(data: LoginRequestBody): Promise<LoginResponseBody> {
|
||||||
return post<LoginResponseBody>(AuthUrlObj.login, data);
|
return await post<LoginResponseBody>(AuthUrlObj.login, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 注册 */
|
/** 注册 */
|
||||||
static register(data: RegisterRequestBody): Promise<RegisterResponseBody> {
|
static async register(data: RegisterRequestBody): Promise<RegisterResponseBody> {
|
||||||
return post<RegisterResponseBody>(AuthUrlObj.register, data);
|
return await post<RegisterResponseBody>(AuthUrlObj.register, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 发送短信验证码 */
|
/** 发送短信验证码 */
|
||||||
static sendSms(data: SendSMSRequestBody): Promise<void> {
|
static async sendSms(data: SendSMSRequestBody): Promise<void> {
|
||||||
return post<void>(AuthUrlObj.sendSms, data);
|
return await post<void>(AuthUrlObj.sendSms, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 刷新 Token */
|
/** 刷新 Token */
|
||||||
static refreshToken(data: RefreshTokenRequestBody): Promise<RefreshTokenResponseBody> {
|
static async refreshToken(data: RefreshTokenRequestBody): Promise<RefreshTokenResponseBody> {
|
||||||
return post<RefreshTokenResponseBody>(AuthUrlObj.refreshToken, data);
|
return await post<RefreshTokenResponseBody>(AuthUrlObj.refreshToken, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 获取当前用户信息 */
|
/** 获取当前用户信息 */
|
||||||
static getUserInfo(): Promise<UserInfoBody> {
|
static async getUserInfo(): Promise<UserInfoBody> {
|
||||||
return get<UserInfoBody>(AuthUrlObj.userInfo);
|
return await get<UserInfoBody>(AuthUrlObj.userInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 修改密码(已登录) */
|
/** 修改密码(已登录) */
|
||||||
static changePassword(data: ChangePasswordRequestBody): Promise<void> {
|
static async changePassword(data: ChangePasswordRequestBody): Promise<void> {
|
||||||
return post<void>(AuthUrlObj.changePassword, data);
|
return await post<void>(AuthUrlObj.changePassword, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 手机验证码重置密码 */
|
/** 手机验证码重置密码 */
|
||||||
static resetPassword(data: UsePhoneResetPasswordRequestBody): Promise<void> {
|
static async resetPassword(data: UsePhoneResetPasswordRequestBody): Promise<void> {
|
||||||
return post<void>(AuthUrlObj.resetPassword, data);
|
return await post<void>(AuthUrlObj.resetPassword, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 退出登录 */
|
/** 退出登录 */
|
||||||
static logout(): Promise<void> {
|
static async logout(): Promise<void> {
|
||||||
return post<void>(AuthUrlObj.logout);
|
return await post<void>(AuthUrlObj.logout);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
43
src/services/modules/banner.ts
Normal file
43
src/services/modules/banner.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
// ============================================================
|
||||||
|
// Banner 模块 — 首页轮播图 API
|
||||||
|
// GET /api/v1/banners
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import {get} from '../request';
|
||||||
|
|
||||||
|
// ---------- 路由常量 ----------
|
||||||
|
|
||||||
|
const BannerUrlObj = {
|
||||||
|
list: '/api/v1/creatives',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
// ---------- 类型 ----------
|
||||||
|
|
||||||
|
/** 单条 Banner */
|
||||||
|
export interface Banner {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
content: "真人素材提示";
|
||||||
|
image_url: string;
|
||||||
|
link_url?: string;
|
||||||
|
category: "promotion" | "banner";
|
||||||
|
vip_level_id?: number;
|
||||||
|
sort_order: number;
|
||||||
|
is_active: boolean;
|
||||||
|
created_by: string;
|
||||||
|
created_at: Date;
|
||||||
|
updated_at: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Banner 列表响应 */
|
||||||
|
export type BannerListResponse = Banner[];
|
||||||
|
|
||||||
|
// ---------- API ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 Banner 轮播图列表
|
||||||
|
* GET /api/v1/banners
|
||||||
|
*/
|
||||||
|
export function fetchBanners(): Promise<BannerListResponse> {
|
||||||
|
return get<BannerListResponse>(BannerUrlObj.list);
|
||||||
|
}
|
||||||
@@ -22,3 +22,37 @@ export {
|
|||||||
type ChangePasswordRequestBody,
|
type ChangePasswordRequestBody,
|
||||||
type UsePhoneResetPasswordRequestBody,
|
type UsePhoneResetPasswordRequestBody,
|
||||||
} from './auth';
|
} from './auth';
|
||||||
|
|
||||||
|
export {
|
||||||
|
fetchBanners,
|
||||||
|
type Banner,
|
||||||
|
type BannerListResponse,
|
||||||
|
} from './banner';
|
||||||
|
|
||||||
|
export {
|
||||||
|
ModelAPI,
|
||||||
|
MODEL_CATEGORY_LABELS,
|
||||||
|
type ModelsListReqeustParams,
|
||||||
|
type ModelsListResponseBody,
|
||||||
|
type ModelInfoRequestParams,
|
||||||
|
type ModelInfoResponseBody,
|
||||||
|
type ModelCategory,
|
||||||
|
} from './models';
|
||||||
|
|
||||||
|
export {
|
||||||
|
TaskAPI,
|
||||||
|
OutputTypeMap,
|
||||||
|
TaskStatusMap,
|
||||||
|
type OutputTypeString,
|
||||||
|
type TaskStatusString,
|
||||||
|
type TaskListRequestParams,
|
||||||
|
type CreatTaskRequestBody,
|
||||||
|
type ExportTaskCSVParams,
|
||||||
|
type ContentItem,
|
||||||
|
type ImageUiParams,
|
||||||
|
type VideoUiParams,
|
||||||
|
type AudioUiParams,
|
||||||
|
type TaskInfoItemResponseBody,
|
||||||
|
type TaskInfoDataResponseBody,
|
||||||
|
type TaskStatusResponseBody,
|
||||||
|
} from './task';
|
||||||
|
|||||||
87
src/services/modules/models.ts
Normal file
87
src/services/modules/models.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import {get} from '../request';
|
||||||
|
// 请注意后端没有关于字段category的查询
|
||||||
|
// ---------- 路由常量 ----------
|
||||||
|
|
||||||
|
const ModelsUrlObj = {
|
||||||
|
modelList: '/api/v1/models',
|
||||||
|
getModelInfo: '/api/v1/models/{model_id}',
|
||||||
|
estimateCost: '/api/v1/models/{model_id}/estimate'
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
// ---------- 类型 ----------
|
||||||
|
|
||||||
|
/** 模型类别 */
|
||||||
|
export type ModelCategory = 'image_to_image' | 'text_to_image' | 'image_to_video' | 'text_to_audio';
|
||||||
|
|
||||||
|
/** 模型类别中文映射 */
|
||||||
|
export const MODEL_CATEGORY_LABELS: Record<ModelCategory, string> = {
|
||||||
|
image_to_image: '图生图',
|
||||||
|
text_to_image: '文生图',
|
||||||
|
image_to_video: '图生视频',
|
||||||
|
text_to_audio: '文生音频',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询可用模型的请求参数
|
||||||
|
*/
|
||||||
|
export interface ModelsListReqeustParams {
|
||||||
|
provider_name?: string;
|
||||||
|
category?: ModelCategory;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询可用模型的响应体
|
||||||
|
*/
|
||||||
|
export interface ModelsListResponseBody {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
provider_name: string;
|
||||||
|
model_type: string;
|
||||||
|
category_name: string;
|
||||||
|
status: string;
|
||||||
|
priority: number;
|
||||||
|
response_mode: string;
|
||||||
|
pricing_config: Record<string, unknown>;
|
||||||
|
param_schema: string[];
|
||||||
|
quota_config: Record<string, unknown>;
|
||||||
|
ui_config: Record<string, unknown>;
|
||||||
|
meta_config: Record<string, unknown>;
|
||||||
|
constraints_config: Record<string, unknown>;
|
||||||
|
expires_at: string;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模型信息请求参数
|
||||||
|
*/
|
||||||
|
export interface ModelInfoRequestParams {
|
||||||
|
model_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 模型详情响应体(与列表项结构一致) */
|
||||||
|
export type ModelInfoResponseBody = ModelsListResponseBody;
|
||||||
|
|
||||||
|
// ---------- API ----------
|
||||||
|
|
||||||
|
|
||||||
|
export class ModelAPI {
|
||||||
|
/**
|
||||||
|
* 获取可用模型列表
|
||||||
|
* GET /api/v1/models
|
||||||
|
*/
|
||||||
|
static fetchModels(params: ModelsListReqeustParams): Promise<ModelsListResponseBody[]> {
|
||||||
|
return get<ModelsListResponseBody[]>(ModelsUrlObj.modelList, params as unknown as Record<string, unknown>);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取单个模型详情
|
||||||
|
* GET /api/v1/models/:id
|
||||||
|
*/
|
||||||
|
static fetchModelInfo(modelId: string): Promise<ModelInfoResponseBody> {
|
||||||
|
const url = ModelsUrlObj.getModelInfo.replace('{model_id}', modelId);
|
||||||
|
return get<ModelInfoResponseBody>(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
232
src/services/modules/task.ts
Normal file
232
src/services/modules/task.ts
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
// ============================================================
|
||||||
|
// 任务模块 — 任务记录 CRUD API
|
||||||
|
// GET /api/v1/tasks → 任务列表(分页/游标)
|
||||||
|
// POST /api/v1/tasks → 提交任务
|
||||||
|
// GET /api/v1/tasks/:id → 任务详情
|
||||||
|
// GET /api/v1/tasks/:id/status → 轻量轮询状态
|
||||||
|
// GET /api/v1/tasks/export → 导出 CSV
|
||||||
|
//
|
||||||
|
// TaskAPI 的静态方法直接返回 get/post 的 Promise<T>,
|
||||||
|
// 不做额外的 async/await 包装,由调用方决定是否 await。
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import {get, post} from '../request';
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 基础枚举 / 字面量类型
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 输出类型映射 */
|
||||||
|
export enum OutputTypeMap {
|
||||||
|
image = '图片',
|
||||||
|
video = '视频',
|
||||||
|
audio = '音频',
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OutputTypeString = keyof typeof OutputTypeMap;
|
||||||
|
|
||||||
|
/** 任务状态 */
|
||||||
|
export enum TaskStatusMap {
|
||||||
|
pending = '待处理',
|
||||||
|
submitted = '已提交',
|
||||||
|
processing = '处理中',
|
||||||
|
success = '成功',
|
||||||
|
failed = '失败',
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TaskStatusString = keyof typeof TaskStatusMap;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 请求体 / 参数类型
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 任务列表请求参数 */
|
||||||
|
export interface TaskListRequestParams {
|
||||||
|
status?: TaskStatusString;
|
||||||
|
user_ids?: string[];
|
||||||
|
model_ids?: string[];
|
||||||
|
/** 游标分页:上次最后一条的 created_at(ISO 8601) */
|
||||||
|
cursor?: string;
|
||||||
|
/** 页码(OFFSET 分页模式),default: 1 */
|
||||||
|
page?: number;
|
||||||
|
/** 每页条数,default: 20 */
|
||||||
|
page_size?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建任务请求体 */
|
||||||
|
export interface CreatTaskRequestBody {
|
||||||
|
model_id: string;
|
||||||
|
params: Record<string, string>;
|
||||||
|
device_id?: string;
|
||||||
|
tags?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 导出 CSV 参数 */
|
||||||
|
export interface ExportTaskCSVParams {
|
||||||
|
start_date: Date;
|
||||||
|
end_date: Date;
|
||||||
|
status?: TaskStatusString;
|
||||||
|
user_ids?: string[];
|
||||||
|
model_ids?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 内容项 — 带判别标签的联合类型
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
interface BaseContentItem {
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TextContent extends BaseContentItem {
|
||||||
|
type: 'text';
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImageUrlContent extends BaseContentItem {
|
||||||
|
type: 'image_url';
|
||||||
|
role: 'reference_image';
|
||||||
|
image_url: { url: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface VideoUrlContent extends BaseContentItem {
|
||||||
|
type: 'video_url';
|
||||||
|
role: 'reference_video';
|
||||||
|
video_url: { url: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AudioContent extends BaseContentItem {
|
||||||
|
type: 'audio_url';
|
||||||
|
role: 'reference_audio';
|
||||||
|
audio_url: { url: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ContentItem =
|
||||||
|
| TextContent
|
||||||
|
| ImageUrlContent
|
||||||
|
| VideoUrlContent
|
||||||
|
| AudioContent;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 各输出类型的 UI 参数
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export interface ImageUiParams {
|
||||||
|
imageUrls?: string[];
|
||||||
|
prompt: string;
|
||||||
|
aspectRatio: string;
|
||||||
|
resolution?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VideoUiParams {
|
||||||
|
resolution?: string;
|
||||||
|
ratio?: string;
|
||||||
|
model?: string;
|
||||||
|
generate_audio: boolean;
|
||||||
|
duration: number;
|
||||||
|
content: ContentItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AudioUiParams {
|
||||||
|
format?: string;
|
||||||
|
sampleRate?: number;
|
||||||
|
bitrate?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 响应体 — 用判别联合按 output_type 分发
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 任务条目基类(不含 output_type 特有字段) */
|
||||||
|
interface BaseTaskItemResponseBody {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
model_id: string;
|
||||||
|
model_name: string;
|
||||||
|
provider_name: string;
|
||||||
|
status: TaskStatusString;
|
||||||
|
external_task_id: string;
|
||||||
|
cost_cent: number;
|
||||||
|
estimated_cost_cent: number;
|
||||||
|
error_code: string;
|
||||||
|
poll_attempts: number;
|
||||||
|
is_favorite: boolean;
|
||||||
|
submitted_at: Date;
|
||||||
|
finished_at: Date;
|
||||||
|
created_at: Date;
|
||||||
|
updated_at: Date;
|
||||||
|
prompt?: string;
|
||||||
|
output_assets?: Array<{ url: string }>;
|
||||||
|
tags: Array<string | null>;
|
||||||
|
error_message: string;
|
||||||
|
user_display_name: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 判别联合:根据 output_type 收窄 ui_params */
|
||||||
|
export type TaskInfoItemResponseBody =
|
||||||
|
| (BaseTaskItemResponseBody & { output_type: 'image'; ui_params: ImageUiParams })
|
||||||
|
| (BaseTaskItemResponseBody & { output_type: 'video'; ui_params: VideoUiParams })
|
||||||
|
| (BaseTaskItemResponseBody & { output_type: 'audio'; ui_params: AudioUiParams });
|
||||||
|
|
||||||
|
/** 任务列表分页响应 */
|
||||||
|
export interface TaskInfoDataResponseBody {
|
||||||
|
has_more: boolean;
|
||||||
|
next_cursor: string;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
total: number;
|
||||||
|
items: TaskInfoItemResponseBody[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 轻量轮询状态响应 */
|
||||||
|
export interface TaskStatusResponseBody {
|
||||||
|
task_id: string;
|
||||||
|
status: TaskStatusString;
|
||||||
|
progress: number;
|
||||||
|
output_assets?: string[];
|
||||||
|
error_code?: string;
|
||||||
|
error_message?: string;
|
||||||
|
cost_cent?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 路由常量
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
const TaskUrlObj = {
|
||||||
|
task: '/api/v1/tasks',
|
||||||
|
taskInfo: (task_id: string) => `/api/v1/tasks/${task_id}`,
|
||||||
|
taskStatus: (task_id: string) => `/api/v1/tasks/${task_id}/status`,
|
||||||
|
tasksCSV: '/api/v1/tasks/export',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// TaskAPI — 静态方法直接返回 Promise<T>,不做二次 async 包装
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export class TaskAPI {
|
||||||
|
/** 获取任务列表(分页/游标) */
|
||||||
|
static getTaskList(params: TaskListRequestParams): Promise<TaskInfoDataResponseBody> {
|
||||||
|
return get<TaskInfoDataResponseBody>(TaskUrlObj.task, params as Record<string, unknown>);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 提交新任务 */
|
||||||
|
static submitTask(body: CreatTaskRequestBody): Promise<TaskInfoItemResponseBody> {
|
||||||
|
return post<TaskInfoItemResponseBody>(TaskUrlObj.task, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 获取任务详情 */
|
||||||
|
static getTaskInfo(task_id: string): Promise<TaskInfoItemResponseBody> {
|
||||||
|
return get<TaskInfoItemResponseBody>(TaskUrlObj.taskInfo(task_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 轻量轮询任务状态 */
|
||||||
|
static getTaskStatus(task_id: string): Promise<TaskStatusResponseBody> {
|
||||||
|
return get<TaskStatusResponseBody>(TaskUrlObj.taskStatus(task_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 导出任务 CSV */
|
||||||
|
static exportTaskCSV(params: ExportTaskCSVParams): Promise<File> {
|
||||||
|
return get<File>(TaskUrlObj.tasksCSV, params as unknown as Record<string, unknown>);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -177,7 +177,7 @@ instance.interceptors.response.use(
|
|||||||
|
|
||||||
// HTTP 200 但业务码非 0 → 业务错误
|
// HTTP 200 但业务码非 0 → 业务错误
|
||||||
if (data && data.code !== 0) {
|
if (data && data.code !== 0) {
|
||||||
// 401 → 尝试刷新 token 并重试(但 refresh 接口自身 401 必须直接拒绝,否则死循环)
|
// 业务码 401 → 尝试刷新 token 并重试(refresh 接口自身 401 直接拒绝)
|
||||||
if (data.code === 401 && response.config) {
|
if (data.code === 401 && response.config) {
|
||||||
if (isRefreshRequest(response.config)) {
|
if (isRefreshRequest(response.config)) {
|
||||||
return Promise.reject(new RefreshError());
|
return Promise.reject(new RefreshError());
|
||||||
@@ -246,8 +246,11 @@ instance.interceptors.response.use(
|
|||||||
// HTTP 状态码错误
|
// HTTP 状态码错误
|
||||||
const { status, data } = error.response;
|
const { status, data } = error.response;
|
||||||
|
|
||||||
// 401 → 尝试刷新 token 并重试(refresh 接口自身 401 直接拒绝,防死循环)
|
// 401 → 尝试刷新 token 并重试
|
||||||
if (status === 401 && error.config) {
|
// ⚠️ 同时检查响应体中的业务码 data.code:
|
||||||
|
// data.code === 401 → token 过期 → 走刷新流程
|
||||||
|
// data.code !== 401 → 其他认证错误(如密码错误)→ 透传后端 message
|
||||||
|
if (status === 401 && error.config && data?.code === 401) {
|
||||||
if (isRefreshRequest(error.config)) {
|
if (isRefreshRequest(error.config)) {
|
||||||
const refreshErr = new RefreshError();
|
const refreshErr = new RefreshError();
|
||||||
logger.debug('request', 'Refresh endpoint returned 401', {
|
logger.debug('request', 'Refresh endpoint returned 401', {
|
||||||
|
|||||||
@@ -115,6 +115,7 @@ const sharedComponents: ThemeConfig['components'] = {
|
|||||||
},
|
},
|
||||||
Pagination: {
|
Pagination: {
|
||||||
itemActiveBg: colorPrimary,
|
itemActiveBg: colorPrimary,
|
||||||
|
itemActiveColor: '#fff',
|
||||||
colorPrimary,
|
colorPrimary,
|
||||||
colorPrimaryHover: colorPrimaryLight,
|
colorPrimaryHover: colorPrimaryLight,
|
||||||
},
|
},
|
||||||
@@ -277,24 +278,24 @@ export const darkTheme: ThemeConfig = {
|
|||||||
defaultBorderColor: darkColorBorder,
|
defaultBorderColor: darkColorBorder,
|
||||||
},
|
},
|
||||||
Menu: {
|
Menu: {
|
||||||
itemSelectedBg: '#312E81',
|
itemSelectedBg: '#1E2460',
|
||||||
itemSelectedColor: colorPrimaryLight,
|
itemSelectedColor: colorPrimaryLight,
|
||||||
itemHoverBg: '#242040',
|
itemHoverBg: '#151A48',
|
||||||
itemActiveBg: '#1E1B4B',
|
itemActiveBg: '#0F1442',
|
||||||
},
|
},
|
||||||
Layout: {
|
Layout: {
|
||||||
siderBg: `linear-gradient(180deg, #0B0A15 0%, #1A1730 100%)`,
|
siderBg: `linear-gradient(180deg, #050818 0%, #0D1140 100%)`,
|
||||||
headerBg: darkColorBgContainer,
|
headerBg: darkColorBgContainer,
|
||||||
bodyBg: darkColorBgLayout,
|
bodyBg: darkColorBgLayout,
|
||||||
},
|
},
|
||||||
Table: {
|
Table: {
|
||||||
headerBg: '#1E1B4B',
|
headerBg: '#0F1340',
|
||||||
headerColor: darkColorTextBase,
|
headerColor: darkColorTextBase,
|
||||||
rowHoverBg: '#242040',
|
rowHoverBg: '#181D52',
|
||||||
borderColor: darkColorBorderSecondary,
|
borderColor: darkColorBorderSecondary,
|
||||||
},
|
},
|
||||||
Tag: {
|
Tag: {
|
||||||
defaultBg: '#1E1B4B',
|
defaultBg: '#1A1F54',
|
||||||
defaultColor: colorPrimaryLight,
|
defaultColor: colorPrimaryLight,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -94,16 +94,16 @@
|
|||||||
* ============================================================ */
|
* ============================================================ */
|
||||||
|
|
||||||
[data-theme='dark'] {
|
[data-theme='dark'] {
|
||||||
/* 中性色 — 暗色 */
|
/* 中性色 — 暗色(科技蓝紫) */
|
||||||
--color-text-base: #e8e6f0;
|
--color-text-base: #e8e8fa;
|
||||||
--color-text-secondary: #a5a0c9;
|
--color-text-secondary: #a0a8d8;
|
||||||
--color-text-tertiary: #6e6998;
|
--color-text-tertiary: #6e78b0;
|
||||||
--color-bg-base: #0f0d1a;
|
--color-bg-base: #080c24;
|
||||||
--color-bg-container: #1a1730;
|
--color-bg-container: #0f1340;
|
||||||
--color-bg-layout: #0b0a15;
|
--color-bg-layout: #050818;
|
||||||
--color-bg-elevated: #242040;
|
--color-bg-elevated: #171b52;
|
||||||
--color-border-base: #2e2a4a;
|
--color-border-base: #2a3278;
|
||||||
--color-border-secondary: #1f1c38;
|
--color-border-secondary: #1c2250;
|
||||||
|
|
||||||
/* 暗色模式下品牌色提亮以保持对比度 */
|
/* 暗色模式下品牌色提亮以保持对比度 */
|
||||||
--color-primary: #818cf8;
|
--color-primary: #818cf8;
|
||||||
|
|||||||
@@ -8,28 +8,14 @@
|
|||||||
|
|
||||||
// ---------- 品牌色(蓝紫渐变) ----------
|
// ---------- 品牌色(蓝紫渐变) ----------
|
||||||
|
|
||||||
/** 品牌主色 — Indigo-500 */
|
|
||||||
export const colorPrimary = '#6366F1';
|
export const colorPrimary = '#6366F1';
|
||||||
|
|
||||||
/** 品牌主色浅色变体 */
|
|
||||||
export const colorPrimaryLight = '#818CF8';
|
export const colorPrimaryLight = '#818CF8';
|
||||||
|
|
||||||
/** 品牌主色深色变体 */
|
|
||||||
export const colorPrimaryDark = '#4F46E5';
|
export const colorPrimaryDark = '#4F46E5';
|
||||||
|
|
||||||
/** 品牌辅助色 — Violet-500(渐变另一端) */
|
|
||||||
export const colorSecondary = '#8B5CF6';
|
export const colorSecondary = '#8B5CF6';
|
||||||
|
|
||||||
/** 品牌渐变色起始值 */
|
export const gradientStart = '#4F46E5';
|
||||||
export const gradientStart = '#4F46E5'; // Indigo-600
|
export const gradientEnd = '#7C3AED';
|
||||||
|
|
||||||
/** 品牌渐变色结束值 */
|
|
||||||
export const gradientEnd = '#7C3AED'; // Violet-600
|
|
||||||
|
|
||||||
/** 品牌渐变色(CSS 值,可直接用于 background) */
|
|
||||||
export const gradientPrimary = `linear-gradient(135deg, ${gradientStart}, ${gradientEnd})`;
|
export const gradientPrimary = `linear-gradient(135deg, ${gradientStart}, ${gradientEnd})`;
|
||||||
|
|
||||||
/** 品牌渐变悬停态 */
|
|
||||||
export const gradientPrimaryHover = `linear-gradient(135deg, ${colorPrimary}, ${colorSecondary})`;
|
export const gradientPrimaryHover = `linear-gradient(135deg, ${colorPrimary}, ${colorSecondary})`;
|
||||||
|
|
||||||
// ---------- 功能色 ----------
|
// ---------- 功能色 ----------
|
||||||
@@ -41,41 +27,43 @@ export const colorInfo = '#3B82F6';
|
|||||||
|
|
||||||
// ---------- 中性色(亮色模式) ----------
|
// ---------- 中性色(亮色模式) ----------
|
||||||
|
|
||||||
export const colorTextBase = '#1E1B4B'; // 深蓝紫黑
|
export const colorTextBase = '#1E1B4B';
|
||||||
export const colorTextSecondary = '#6B7280';
|
export const colorTextSecondary = '#6B7280';
|
||||||
export const colorTextTertiary = '#9CA3AF';
|
export const colorTextTertiary = '#9CA3AF';
|
||||||
|
|
||||||
export const colorBgBase = '#FFFFFF';
|
export const colorBgBase = '#FFFFFF';
|
||||||
export const colorBgContainer = '#F9FAFB';
|
export const colorBgContainer = '#F9FAFB';
|
||||||
export const colorBgElevated = '#FFFFFF';
|
export const colorBgElevated = '#FFFFFF';
|
||||||
export const colorBgLayout = '#F5F3FF'; // Violet-50
|
export const colorBgLayout = '#F5F3FF';
|
||||||
export const colorBgSpotlight = '#F3F4F6';
|
export const colorBgSpotlight = '#F3F4F6';
|
||||||
|
|
||||||
export const colorBorder = '#E5E7EB';
|
/** 亮色模式 — 面板边框(稍明显) */
|
||||||
export const colorBorderSecondary = '#F3F4F6';
|
export const colorBorder = '#E2E0F0';
|
||||||
|
/** 亮色模式 — 内部分隔线(可见但不强烈) */
|
||||||
|
export const colorBorderSecondary = '#EEECF6';
|
||||||
|
|
||||||
// ---------- 中性色(暗色模式) ----------
|
// ---------- 中性色(暗色模式 — 融入品牌蓝紫调) ----------
|
||||||
|
|
||||||
/** 暗色模式 — 主文字 */
|
/** 暗色模式 — 主文字 */
|
||||||
export const darkColorTextBase = '#E8E6F0';
|
export const darkColorTextBase = '#E8E8FA';
|
||||||
/** 暗色模式 — 次要文字 */
|
/** 暗色模式 — 次要文字 */
|
||||||
export const darkColorTextSecondary = '#A5A0C9';
|
export const darkColorTextSecondary = '#A0A8D8';
|
||||||
/** 暗色模式 — 辅助文字 */
|
/** 暗色模式 — 辅助文字 */
|
||||||
export const darkColorTextTertiary = '#6E6998';
|
export const darkColorTextTertiary = '#6E78B0';
|
||||||
|
|
||||||
/** 暗色模式 — 基础背景 */
|
/** 暗色模式 — 页面底色(深邃蓝黑) */
|
||||||
export const darkColorBgBase = '#0F0D1A'; // 深蓝紫黑
|
export const darkColorBgBase = '#080C24';
|
||||||
/** 暗色模式 — 容器背景 */
|
/** 暗色模式 — 卡片/面板背景(暗蓝紫) */
|
||||||
export const darkColorBgContainer = '#1A1730'; // 抬升一层
|
export const darkColorBgContainer = '#0F1340';
|
||||||
/** 暗色模式 — 悬浮背景 */
|
/** 暗色模式 — 悬浮层背景(微亮蓝紫) */
|
||||||
export const darkColorBgElevated = '#242040'; // 再抬升一层
|
export const darkColorBgElevated = '#171B52';
|
||||||
/** 暗色模式 — 布局背景 */
|
/** 暗色模式 — 页面布局底层 */
|
||||||
export const darkColorBgLayout = '#0B0A15'; // 最深背景
|
export const darkColorBgLayout = '#050818';
|
||||||
|
|
||||||
/** 暗色模式 — 边框 */
|
/** 暗色模式 — 面板外框(蓝紫边框,可见但不刺眼) */
|
||||||
export const darkColorBorder = '#2E2A4A';
|
export const darkColorBorder = '#2A3278';
|
||||||
/** 暗色模式 — 次要边框 */
|
/** 暗色模式 — 内部分隔线(柔和蓝紫,常驻可见) */
|
||||||
export const darkColorBorderSecondary = '#1F1C38';
|
export const darkColorBorderSecondary = '#1C2250';
|
||||||
|
|
||||||
// ---------- 圆角 ----------
|
// ---------- 圆角 ----------
|
||||||
|
|
||||||
|
|||||||
@@ -69,4 +69,10 @@ export const EVENTS = {
|
|||||||
LOGIN_SUCCESS: 'auth:login-success',
|
LOGIN_SUCCESS: 'auth:login-success',
|
||||||
/** 退出登录 */
|
/** 退出登录 */
|
||||||
LOGOUT: 'auth:logout',
|
LOGOUT: 'auth:logout',
|
||||||
|
/** 任务提交成功(→ 刷新任务列表) */
|
||||||
|
TASK_SUBMITTED: 'task:submitted',
|
||||||
|
/** 打开设置 Drawer(导航栏"设置"按钮点击) */
|
||||||
|
OPEN_SETTINGS: 'settings:open',
|
||||||
|
/** 打开页面 Modal(导航栏点击页面导航项触发,携带 target 路径标识符) */
|
||||||
|
OPEN_PAGE: 'page:open',
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,10 +1,10 @@
|
|||||||
import { defineConfig, loadEnv } from 'vite';
|
import {defineConfig, loadEnv} from 'vite';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import electron from 'vite-plugin-electron/simple';
|
import electron from 'vite-plugin-electron/simple';
|
||||||
import react from '@vitejs/plugin-react';
|
import react from '@vitejs/plugin-react';
|
||||||
import renderer from 'vite-plugin-electron-renderer';
|
import renderer from 'vite-plugin-electron-renderer';
|
||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import { visualizer } from 'rollup-plugin-visualizer';
|
import {visualizer} from 'rollup-plugin-visualizer';
|
||||||
|
|
||||||
const __dirname = import.meta.dirname;
|
const __dirname = import.meta.dirname;
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ const __dirname = import.meta.dirname;
|
|||||||
// 如需避免,可把仅渲染进程用的类型放到 src/types/
|
// 如需避免,可把仅渲染进程用的类型放到 src/types/
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
export default defineConfig(({ mode }) => {
|
export default defineConfig(({mode}) => {
|
||||||
// 加载 .env.development / .env.production 中的环境变量
|
// 加载 .env.development / .env.production 中的环境变量
|
||||||
const env = loadEnv(mode, __dirname, '');
|
const env = loadEnv(mode, __dirname, '');
|
||||||
|
|
||||||
@@ -67,22 +67,33 @@ export default defineConfig(({ mode }) => {
|
|||||||
server: {
|
server: {
|
||||||
port: 5173,
|
port: 5173,
|
||||||
strictPort: true,
|
strictPort: true,
|
||||||
host: 'localhost',
|
host: "0.0.0.0",
|
||||||
// 文件监听(Windows 优化)
|
|
||||||
watch: {
|
watch: {
|
||||||
// Windows 上默认的 fs.watch 有时不稳定,
|
// Windows 上默认的 fs.watch 有时不稳定,
|
||||||
// 如果文件保存后界面无反应,可临时开启 usePolling
|
// 如果文件保存后界面无反应,可临时开启 usePolling
|
||||||
// usePolling: true,
|
// usePolling: true,
|
||||||
// interval: 100,
|
// interval: 100,
|
||||||
// 忽略不需要监听的目录,减少 CPU 占用
|
// 忽略不需要监听的目录,减少 CPU 占用
|
||||||
ignored: ['**/node_modules/**', '**/dist/**', '**/dist-electron/**', '**/release/**', '**/test-server/**'],
|
ignored: ['**/node_modules/**', '**/dist/**', '**/dist-electron/**', '**/release/**', '**/test-server/**', "**/**/*.md"],
|
||||||
},
|
},
|
||||||
// HMR 配置
|
// HMR 配置
|
||||||
hmr: {
|
hmr: {
|
||||||
// 在浏览器控制台显示 HMR 覆盖层(错误/警告时)
|
// 在浏览器控制台显示 HMR 覆盖层(错误/警告时)
|
||||||
overlay: true,
|
overlay: true,
|
||||||
// 协议默认 ws://,localhost 下无需额外配置
|
|
||||||
},
|
},
|
||||||
|
proxy: mode === "development" ? {
|
||||||
|
"/api": {
|
||||||
|
target: env.VITE_API_BASE_URL || "http://192.168.110.84:8000", // 从环境变量读取,默认为本地后端
|
||||||
|
changeOrigin: true,
|
||||||
|
bypass: (req) => {
|
||||||
|
if (req.headers.accept?.includes('text/html')) return '/index.html'
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/uploads': {
|
||||||
|
target: env.VITE_API_BASE_URL ?? 'http://192.168.110.84:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
} : undefined, // 生产环境不启用代理
|
||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
|
|||||||
Reference in New Issue
Block a user