Compare commits

...

15 Commits

Author SHA1 Message Date
qiubaishen b80afd273c feat(org): expose enterprise drawing and task logs 2026-11-06 19:06:09 +08:00
zhanjunhao a9c31708c3 fix(settings): 修复运营设置首次进入无法滚动 2026-11-02 15:39:00 +08:00
zhanjunhao 21d64e43ce feat: 修复企业凭证复制并优化弹窗底部间距 2026-11-02 12:04:37 +08:00
zhanjunhao 5bd2b3405d remove: 移除不必要的文档 2026-10-31 19:12:46 +08:00
zhanjunhao 1bf13bc226 feat: 完善官网配置、预约管理与文章编辑 2026-10-31 19:02:58 +08:00
zhanjunhao 7b80c3bbb3 perf: 优化依赖与首屏加载 2026-10-28 11:37:15 +08:00
zhanjunhao 8a7a3b45ff refactor: 统一 Playground 上下文目录与引用路径 2026-10-27 17:25:25 +08:00
zhanjunhao 599966060f feat: 区分开发和生产环境配置并完善加载与回归测试 2026-10-27 15:55:20 +08:00
zhanjunhao e74008239d docs: 拆分源码导读与模块化改造方案
将渲染、路由和 API 调用链整理为面向 Vue 3 开发者的源码导读。

合并模块化选型、迁移约束和后续演进内容,精简重复说明并完善文档互链。
2026-10-27 10:54:06 +08:00
zhanjunhao 9b1e806489 docs: 1、页面渲染、路由与 API 调用链分析及模块化改造方案 2、前端模块化改造:可行性评审与渐进实施方案(暂放) 2026-10-26 19:05:16 +08:00
zhanjunhao 82a56092bc refactor: 移除运行时后端配置并统一使用构建变量
删除 public/config.js 及 HTML 加载引用,后端地址改为构建变量优先、否则同源。补充环境变量示例、配置回归测试与部署迁移说明。

验证:npm run check 通过,183 项测试通过,生产构建成功。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-22 12:50:16 +08:00
zhanjunhao d35330d530 refactor: 优化公共状态逻辑并修复用户列表分页
- 提取存储解析、通知已读、表格偏好和企业筛选参数逻辑
- 修复分页尺寸切换的旧页码、筛选丢失及 Semi 重复回调问题
- 补充 51 项回归测试,统一检查入口并修复格式配置和 JSON 语法
- 记录 179 项测试、生产构建和隔离浏览器交互验收结果
- 删除过期迁移与性能报告并同步开发文档

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-21 18:47:21 +08:00
zhanjunhao 89dfff96df feat: 将 前端性能优化报告 移动到 docs 目录 2026-10-21 12:41:37 +08:00
zhanjunhao a5215dc3fd chore(deps): 统一使用 npm,移除 Bun 依赖 2026-10-21 12:05:46 +08:00
zhanjunhao e2b96dc503 docs: 优化 Vue 开发者上手指南并修正项目分析
补充 Vue 到 React 的概念对照、学习路径和业务链路阅读指引;更新依赖、开发代理、忽略规则及测试验证记录。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 11:10:06 +08:00
111 changed files with 25407 additions and 4149 deletions
+12
View File
@@ -0,0 +1,12 @@
# Loaded by npm run dev. Override locally in .env.development.local.
# Public configuration only; VITE_* values are exposed to the browser.
VITE_REACT_APP_SERVER_URL=
VITE_CLOUD_BRAIN_UI_ENABLED=false
# Vite development proxy only. Keep the browser URL empty to use this proxy.
DEV_PROXY_TARGET=http://134.175.227.134:13000
# Optional analytics. Empty IDs disable script injection.
VITE_UMAMI_WEBSITE_ID=
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
VITE_GOOGLE_ANALYTICS_ID=
-3
View File
@@ -1,3 +0,0 @@
# Frontend build-time feature flags. Rebuild the frontend after changing them.
# Missing or false keeps the Cloud Brain suite hidden and blocks direct routes.
VITE_CLOUD_BRAIN_UI_ENABLED=false
+11
View File
@@ -0,0 +1,11 @@
# Loaded by npm run build. Override locally in .env.production.local or in CI.
# Public configuration only; VITE_* values are exposed to the browser.
# Empty URL uses same-origin requests; configure your production reverse proxy.
# Set a backend root URL for cross-origin requests, then rebuild and redeploy.
VITE_REACT_APP_SERVER_URL=
VITE_CLOUD_BRAIN_UI_ENABLED=false
# Optional analytics. Empty IDs disable script injection.
VITE_UMAMI_WEBSITE_ID=
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
VITE_GOOGLE_ANALYTICS_ID=
+14 -4
View File
@@ -10,6 +10,17 @@ node_modules/
/.nyc_output/ /.nyc_output/
*.lcov *.lcov
# Local acceptance tests, browser sessions, and reports
/e2e/
/tests/
*.test.*
*.spec.*
/playwright/.auth/
/playwright-report/
/test-results/
/blob-report/
/scripts/seed-demo-requests.mjs
# production # production
/build /build
/dist/ /dist/
@@ -44,8 +55,8 @@ Thumbs.db
Desktop.ini Desktop.ini
.env .env
.env.* .env.*
!.env.example !.env.development
!.env.*.example !.env.production
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local
@@ -55,8 +66,7 @@ npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
.idea .idea
package-lock.json
yarn.lock yarn.lock
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库) # i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
scripts/kt_batches/ scripts/kt_batches/
scripts/kt_out/ scripts/kt_out/
+9
View File
@@ -0,0 +1,9 @@
# Generated build output and tool caches are not source files.
node_modules/
dist/
dist-ssr/
build/
coverage/
.nyc_output/
.vite/
.cache/
+4 -1
View File
@@ -1 +1,4 @@
module.exports = require('@so1ve/prettier-config'); export default {
singleQuote: true,
jsxSingleQuote: true,
};
+28
View File
@@ -0,0 +1,28 @@
# Codex 项目协作规范
适用于本项目的开发、验收、测试与页面比对。
## 工具选择
- 网页操作、功能验收、截图和页面比对,优先使用项目中的 Playwright 配置与测试脚本。
- 浏览器优先使用本机 Google Chrome,通过 Playwright 的 `channel: 'chrome'` 启动独立测试会话;需要复用已有会话时,使用已授权且可连接的浏览器会话。
- 代码检索、文件编辑、接口检查和构建验证,使用对应的命令行工具或 API。
- 不将 computer-use 作为网页任务的默认工具。仅在 Playwright 无法覆盖的原生桌面操作,或用户明确要求时使用。
- Playwright 执行失败时,先排查服务地址、元素定位、等待条件、浏览器环境和登录状态;不要直接切换到 computer-use。
## 开发与验收
- 修改前阅读相关代码与接口文档,保留用户已有修改,控制变更范围。
- 完成开发后,根据变更运行必要的逻辑测试、Playwright 验收及构建检查;纯文档修改检查内容与格式即可。
- 页面交互使用稳定的角色、标签或测试标识定位元素,使用条件等待,避免依赖固定延时和屏幕坐标。
- 功能验收覆盖正常流程及相关的空数据、失败提示、校验和重复提交场景;涉及响应式布局时检查桌面端和移动端。
- 页面比对使用一致的视口、数据、主题和页面状态,结合截图与实际交互确认差异。
- 模拟接口测试与真实后端联调分别记录;模拟通过不等同于真实保存、上传或鉴权通过。
## 测试与交付
- 复用 `playwright.config.js`:`npm run test:e2e` 运行验收,`npm run test:e2e:headed` 显示浏览器,`npm run test:e2e:report` 查看报告。
- 新增测试文件、截图、报告、trace 和浏览器会话文件应加入 Git 忽略规则,不提交到仓库;已有受 Git 跟踪的文件不擅自移除。
- 不在代码、日志或报告中输出密码、Cookie、令牌等敏感信息。
- 测试失败时检查错误与报告,修复后重跑受影响用例;未执行或受环境限制的项目如实说明。
- 交付时简要说明完成内容、实际验证结果和待验收项,不将未完成验证的功能描述为验收通过。
-228
View File
@@ -1,228 +0,0 @@
# 前端性能优化报告 - Weelink Monkey AI
## ✅ 已完成的性能优化 (2026-02-12 更新)
### 🎉 主要成就
#### 1. **react-icons (83MB) - ✅ 已完全移除**
- **优化方案**: 创建自定义内联 SVG 图标组件 ([BrandIcons.jsx](src/components/common/icons/BrandIcons.jsx))
- **替换的文件**: 全部7个文件已完成替换
- ✅ `components/settings/personal/sections/AccountBindingSection.jsx`
- ✅ `components/topup/modals/PaymentConfirmModal.jsx`
- ✅ `pages/Recharge/RechargePanel.jsx`
- ✅ `components/topup/RechargeCard.jsx`
- ✅ `components/table/channels/ChannelsColumnDefs.jsx`
- ✅ `components/settings/personal/cards/AccountManagement.jsx`
- ✅ `components/settings/personal/modals/WeChatBindModal.jsx`
- **从 package.json 移除**: ✅ 完成
- **节省空间**: **~83MB → 0MB** (100% 优化)
- **实际效果**: 构建产物减少约 2-3MB (gzip后)
#### 2. **@lobehub/icons - 保留使用**
- **使用文件**: 2个
- `pages/Home/index.jsx`
- `helpers/render.jsx`
- **原因**: 这些是 AI 模型品牌图标(OpenAI, Claude, Gemini等),是项目核心功能
- **优化**: 通过 tree-shaking 和具名导入已优化加载
- **实际打包**: ~5MB → ~500KB (通过 tree-shaking)
### 🟡 现有依赖(已优化)
#### 3. **lucide-react**
- **状态**: ✅ 正在使用,已通过 tree-shaking 优化
- **导入方式**: 具名导入确保仅打包使用的图标
- **用途**: 通用 UI 图标 (替代了大部分 react-icons)
- **实际打包**: ~40MB → ~50-100KB (通过 tree-shaking)
#### 4. **mermaid (图表库)**
- **状态**: ✅ 已懒加载
- **文件**: `components/common/markdown/MarkdownRenderer.jsx`
- **优化**: 仅在需要时动态加载
#### 5. **katex (数学公式渲染)**
- **状态**: ✅ 已通过 Vite chunk 分离
- **优化**: 独立chunk,按需加载
#### 6. **@visactor (图表可视化)**
- **状态**: ✅ 已通过 Vite chunk 分离
- **包含**: react-vchart, vchart, vchart-semi-theme
- **优化**: 独立chunk,按需加载
### 🎯 新增优化项
✅ **Vite 构建配置优化**
- 启用 esbuild 压缩
- 移除生产环境的 console 和 debugger
- 优化 tree-shaking 配置
- 细粒度的代码分割 (12+ chunks)
- Target ES2015 减少polyfill
✅ **已完成的优化项目**
- Google Fonts 依赖已移除
- Telegram 登录组件已懒加载
- MapleBackground 动画已优化
- 首屏 loading 动画已优化
- Mermaid 已懒加载
- **react-icons 已完全移除** ⭐ NEW
---
## 📊 优化前后对比
| 库名 | 优化前 | 优化后 | 节省 | 状态 |
| -------------- | ---------- | --------------------- | ----------- | ------------- |
| react-icons | 83MB | 0MB | **-83MB** | ✅ **已移除** |
| lucide-react | 40MB | ~100KB (tree-shaking) | **-39.9MB** | ✅ **已优化** |
| @lobehub/icons | 5MB | ~500KB (tree-shaking) | **-4.5MB** | ✅ **已优化** |
| @visactor | 10MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
| mermaid | 3MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
| katex | 2MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
| **依赖总计** | **~143MB** | **~600KB + 懒加载** | **~99% ⬇️** | ✅ **完成** |
---
## 🎯 优化技术细节
### ✅ 已实施的优化
1. **移除 react-icons (83MB)**
- 创建自定义 SVG 组件库 `BrandIcons.jsx`
- 包含品牌图标: Wechat, Alipay, Stripe, Telegram, Discord, Linux, Shuffle
- 所有7个文件已完成迁移
- 从 package.json 移除依赖
2. **优化图标库使用**
- lucide-react: 使用具名导入 ✅
- @lobehub/icons: 保留(AI模型图标必需) ✅
- 自定义SVG: 零依赖,体积最小 ✅
3. **Vite 构建优化**
```javascript
// 压缩配置
- esbuild 压缩 (速度+体积优化)
- 移除 console/debugger
- tree-shaking 优化
// 代码分割 (12+ chunks)
- react-core
- semi-ui / semi-icons
- vchart (图表)
- mermaid (流程图)
- markdown / katex
- lobe-icons / lucide-icons
- i18n / utils
- react-components
```
### 📋 下一步可选优化
1. **CDN 加速 (可选)**
- 考虑使用国内CDN加速 Semi UI
- 使用CDN加速大型依赖(mermaid, vchart)
2. **图片优化 (可选)**
- WebP 格式转换
- 图片懒加载
- 响应式图片
---
## 🚀 实际优化效果
### 打包体积对比
| 指标 | 优化前 | 优化后 | 提升 |
| --------------------- | ------ | ------- | ------------- |
| 初始JS依赖 | ~143MB | ~10MB\* | **93%** ⬇️ |
| 主chunk (预估) | ~2.5MB | ~800KB | **68%** ⬇️ |
| gzip 后 (预估) | ~8MB | ~2-3MB | **62-75%** ⬇️ |
| 首屏加载时间 (中国4G) | 4-8秒 | 1.5-3秒 | **50-75%** ⬇️ |
\*通过 tree-shaking + 代码分割 + 懒加载实现
### 📈 预期用户体验提升
| 场景 | 优化前 | 优化后 | 改善 |
| ------------- | --------- | ----------- | ---------- |
| 🇨🇳 中国4G网络 | 6-8秒白屏 | 2-3秒可交互 | ⭐⭐⭐⭐⭐ |
| 🌐 国际网络 | 3-5秒 | 1-2秒 | ⭐⭐⭐⭐ |
| 📱 移动端 | 较慢 | 流畅 | ⭐⭐⭐⭐⭐ |
| 🔄 页面切换 | 卡顿 | 即时响应 | ⭐⭐⭐⭐⭐ |
---
## ✅ 优化完成清单
### 🎉 已完成 (2026-02-12)
- [x] 移除 react-icons (83MB → 0MB)
- [x] 创建自定义 SVG 图标组件
- [x] 替换所有7个使用文件
- [x] 从 package.json 移除
- [x] 优化 Vite 构建配置
- [x] 启用 esbuild 压缩
- [x] 优化 tree-shaking
- [x] 细粒度代码分割 (12+ chunks)
- [x] 移除生产环境 console
- [x] 懒加载大型依赖
- [x] Telegram 登录组件
- [x] Mermaid 图表
- [x] @visactor 图表库
- [x] katex 数学公式
- [x] 优化图标库
- [x] lucide-react 具名导入
- [x] @lobehub/icons tree-shaking
### 📋 可选后续优化
- [ ] 配置 CDN 加速(Semi UI, 大型依赖)
- [ ] 图片优化 (WebP, 懒加载)
- [ ] 启用 Brotli 压缩
- [ ] 添加性能监控
### 🧪 验证步骤
运行以下命令验证优化效果:
```bash
cd web
npm install # 安装依赖(已移除 react-icons)
npm run build # 构建生产版本
```
查看构建产物:
```bash
ls -lh dist/assets/ # 查看打包后的文件大小
```
---
## 📝 变更记录
**2026-02-12 (本次优化)**
- ✅ 完全移除 react-icons (83MB)
- ✅ 创建自定义品牌图标组件
- ✅ 优化 Vite 构建配置
- ✅ 实现细粒度代码分割
- ✅ 优化图标库 tree-shaking
**预期收益**:
- 依赖体积减少 ~93%
- 首屏加载时间减少 50-75%
- 中国用户体验显著提升
---
最后更新: 2026-02-12
+55 -70
View File
@@ -15,81 +15,67 @@
| 用途 | 当前方案 | | 用途 | 当前方案 |
| --- | --- | | --- | --- |
| 页面开发 | React 18,JavaScript / JSX,ES Modules | | 页面开发 | React 18,JavaScript / JSX,ES Modules |
| 构建与开发服务 | Vite 5,Bun 锁文件 `bun.lock` | | 构建与开发服务 | Vite 5,npm 锁文件 `package-lock.json` |
| 路由 | React Router 6,BrowserRouter | | 路由 | React Router 6,BrowserRouter |
| UI 与样式 | Semi Design、部分 Ant Design 6、Tailwind CSS 3、CSS 变量 | | UI 与样式 | Semi Design、Tailwind CSS 3、CSS 变量;清单另有 antd 5 |
| 请求与流式响应 | Axios、Fetch、`sse.js` | | 请求与流式响应 | Axios、Fetch、`sse.js` |
| 状态管理 | React Context 和业务 Hooks | | 状态管理 | React Context 和业务 Hooks |
| 国际化 | i18next、react-i18next | | 国际化 | i18next、react-i18next |
| 富文本与可视化 | React Markdown、KaTeX、Mermaid、VChart、React Flow | | 富文本与可视化 | React Markdown、KaTeX、Mermaid、VChart、React Flow |
| 测试与检查 | Node.js 内置测试运行器、ESLint 8、Prettier 3 | | 测试与检查 | Node.js 内置测试运行器、ESLint 8、Prettier 3 |
具体依赖版本以 [package.json](./package.json) 和 [bun.lock](./bun.lock) 为准。项目虽然包含 TypeScript 依赖,但现有应用主要使用 JS / JSX,`build` 不包含独立类型检查。 具体声明与锁定版本见 [package.json](./package.json) 和 [package-lock.json](./package-lock.json)。应用主要使用 JS / JSX,build 不包含独立类型检查。
## 2. 本地启动 ## 2. 本地启动
### 环境准备 ### 环境准备
建议使用 Node.js 22 LTS 或 24 LTS,以及支持当前 `bun.lock` 格式的 Bun 1.3.x。仓库没有通过 `engines` 或版本文件强制固定运行时;团队应统一具体版本。 使用 Node.js >=22.13.0 和 npm >=10;本次验证为 Node.js 22.23.3 / npm 10.9.9。项目通过 engines 声明要求,packageManager 记录 npm 版本。
先向后端负责人获取可用的联调地址、测试账号和权限,以及必要的模型/渠道配置。前端仓库没有默认测试账号,也没有完整的离线 Mock 服务。 先向后端负责人获取可用的联调地址、测试账号和权限,以及必要的模型/渠道配置。前端仓库没有默认测试账号,也没有完整的离线 Mock 服务。
```bash ```bash
git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git
cd monkey-ai-web cd monkey-ai-web
bun install --frozen-lockfile npm ci
bun run dev npm run dev
``` ```
已经拿到本地目录的同学,直接在该目录运行后两条命令即可。 已经拿到本地目录的同学,直接在该目录运行后两条命令即可。
默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。默认后端地址为 `http://localhost:3000`,具体代理配置见下一节。 默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。开发代理目标由 `DEV_PROXY_TARGET` 指定,具体代理配置见下一节。
需要调整功能开关时,将 `.env.example` 复制为 `.env.local`: 项目已提供两个自动加载的环境配置,无需复制示例文件:
```bash | 命令 | 默认模式 | 配置文件 |
# Git Bash / macOS / Linux | --- | --- | --- |
cp .env.example .env.local | `npm run dev` | development | `.env.development` |
``` | `npm run build` | production | `.env.production` |
| `npm run preview` | 预览已有产物 | 使用构建时已写入的配置,不重新应用环境变量 |
```powershell 个人覆盖配置可写入 `.env.development.local` 或 `.env.production.local`(Git 忽略)。同名变量优先级从高到低:启动终端/CI > `.env.[mode].local` > `.env.[mode]` > `.env.local` > `.env`。旧的 `.env.local` 仍被加载,但与模式文件重名的变量会被模式文件覆盖,请迁移到对应的 `.local` 文件。可通过 Vite 的 `--mode` 显式选择其他模式。
# PowerShell
Copy-Item .env.example .env.local
```
项目使用 Bun 锁定依赖,ESLint 和国际化脚本也调用 `bunx`,建议统一使用 Bun。修改依赖时同步提交 `package.json` 和 `bun.lock`;不要混用包管理器重新生成依赖树。 `.env.example` 原本只是示例,不会被 Vite 自动加载,现已移除。两个环境文件仅存公开默认值,修改后需重启开发服务或重新构建生产产物。
项目统一使用 npm,提交 package.json 与 package-lock.json。首次安装及 CI 使用 `npm ci`;有意更新依赖时使用 `npm install`,检查并提交锁文件变化。不要使用 Bun 或 Yarn 重新生成另一套锁文件。
## 3. 后端联调与环境配置 ## 3. 后端联调与环境配置
### 推荐:浏览器同源请求,通过 Vite 代理后端 ### 推荐:浏览器同源请求,通过 Vite 代理后端
保持 [public/config.js](./public/config.js) 中 `SERVER_URL` 为空,也不设置 `VITE_REACT_APP_SERVER_URL`: 不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用当前网页域名。
```js [vite.config.js](./vite.config.js) 将下列前缀转发到 `DEV_PROXY_TARGET` 指定的后端:
window.__APP_CONFIG__ = {
SERVER_URL: '',
};
```
[vite.config.js](./vite.config.js) 将下列前缀转发到 `http://localhost:3000`:
```text ```text
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno /api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
``` ```
其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改所需代理项的 `target`,然后重启开发服务;代理目标目前是写在配置文件中的,**没有读取专用的代理环境变量**。`package.json` 中的 `proxy` 字段不是这里的生效入口。 其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET`,然后重启开发服务。该变量仅供 Vite 代理使用,不暴露给浏览器;默认保留原联调地址 `http://134.175.227.134:13000`。生产部署需由 Nginx/网关配置同源反向代理。`package.json` 中的 `proxy` 字段不是这里的生效入口。
### 可选:浏览器直接访问独立后端域名 ### 可选:浏览器直接访问独立后端域名
可以配置运行时文件: 在 `.env.development` / `.env.production` 或对应的 `.local` 覆盖文件中配置构建变量:
```js
window.__APP_CONFIG__ = {
SERVER_URL: 'https://api.example.com',
};
```
也可以在 `.env.local` 中配置构建变量:
```dotenv ```dotenv
VITE_REACT_APP_SERVER_URL=https://api.example.com VITE_REACT_APP_SERVER_URL=https://api.example.com
@@ -98,32 +84,31 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
接口根地址由 [src/helpers/config.js](./src/helpers/config.js) 决定,优先级为: 接口根地址由 [src/helpers/config.js](./src/helpers/config.js) 决定,优先级为:
1. 非空的 `window.__APP_CONFIG__.SERVER_URL`。 1. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`(构建变量)。
2. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`。 2. 空字符串,使用当前网页域名(同源)。
3. 空字符串,使用当前网页域名。
地址填写后端根地址,不要额外添加 `/api`,业务请求会自己带上接口路径。直接连接独立域名时,请求不经过 Vite 的本地代理;后端需要正确配置 CORS、凭证和 Cookie 策略。公共 Axios 实例在根地址非空时启用 `withCredentials`。 地址填写后端根地址,不要额外添加 `/api`,业务请求会自己带上接口路径。直接连接独立域名时,请求不经过 Vite 的本地代理;后端需要正确配置 CORS、凭证和 Cookie 策略。公共 Axios 实例在根地址非空时启用 `withCredentials`。
`public/config.js` 在入口模块之前加载,构建后成为 `dist/config.js`。部署时修改这个文件并刷新页面即可切换运行时地址;环境变量则需要重启开发服务或重新构建。运行时地址为空时仍会回退到构建变量,不会强制覆盖为同源模式。 已移除 `public/config.js` 及其入口脚本,不再支持部署后直接修改 `dist/config.js` 切换后端。旧部署如依赖该能力,需迁移为构建前设置 `VITE_REACT_APP_SERVER_URL`,或清空该变量后重新构建并配置同源反向代理。开发时修改变量需重启服务,生产时需重新构建并发布;仅修改部署服务器环境变量或刷新页面不会改变已有产物中的地址。
### 其他配置 ### 其他配置
| 配置 | 作用 | 生效方式 | | 配置 | 作用 | 生效方式 |
| --- | --- | --- | | --- | --- | --- |
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 | | `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 |
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 配置读取进程环境变量 | | `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 按当前 mode 加载环境文件,终端/CI 优先 |
| `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` | | `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` |
| `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 | | `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 |
统计脚本插件使用 `process.env`,没有显式调用 Vite `loadEnv`;如果使用 Node/npm 运行 Vite,不要假定只写 `.env.local` 就能让配置文件读到这些统计变量,应由启动终端或 CI 环境注入。 统计脚本插件与前端配置共用 Vite 环境加载规则;ID 留空时不注入脚本。生产统计 ID 通常只配置在 `.env.production` 或生产 CI 中。
前端环境变量和 `config.js` 都会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。 前端构建变量会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。
## 4. 目录与代码入口 ## 4. 目录与代码入口
```text ```text
monkey-ai-web/ monkey-ai-web/
├── public/ # 原样复制到构建目录的资源、logo、运行时 config.js ├── public/ # 原样复制到构建目录的静态资源、logo
├── scripts/ # 国际化提取、翻译整理等辅助脚本 ├── scripts/ # 国际化提取、翻译整理等辅助脚本
├── src/ ├── src/
│ ├── index.jsx # React 挂载、语言初始化、全局 Provider │ ├── index.jsx # React 挂载、语言初始化、全局 Provider
@@ -132,8 +117,7 @@ monkey-ai-web/
│ ├── components/ # 通用及业务组件,含 layout、auth、settings │ ├── components/ # 通用及业务组件,含 layout、auth、settings
│ ├── pages/ # 页面和业务模块 │ ├── pages/ # 页面和业务模块
│ ├── hooks/ # 按业务拆分的数据与交互逻辑 │ ├── hooks/ # 按业务拆分的数据与交互逻辑
│ ├── context/ # User、Status、Theme、Org 等状态 │ ├── context/ # User、Status、Theme、Org、Playground 等状态
│ ├── contexts/ # PlaygroundContext;与 context/ 均为现有目录
│ ├── helpers/ # API 实例、鉴权、配置、主题、通用工具 │ ├── helpers/ # API 实例、鉴权、配置、主题、通用工具
│ ├── services/ # 会话、安全验证等服务封装 │ ├── services/ # 会话、安全验证等服务封装
│ ├── constants/ # 业务常量和接口定义 │ ├── constants/ # 业务常量和接口定义
@@ -142,11 +126,11 @@ monkey-ai-web/
│ ├── styles/ # 主题 token、企业空间等样式 │ ├── styles/ # 主题 token、企业空间等样式
│ └── docs/ # 随前端提供的静态文档内容 │ └── docs/ # 随前端提供的静态文档内容
├── tests/ # 部分 Node 测试,其他测试与源码相邻 ├── tests/ # 部分 Node 测试,其他测试与源码相邻
├── index.html # HTML 入口、启动占位画面、config.js 加载 ├── index.html # HTML 入口、启动占位画面、入口模块加载
├── vite.config.js # 代理、别名、打包拆分 ├── vite.config.js # 代理、别名、打包拆分
├── tailwind.config.js # Tailwind 与品牌色变量映射 ├── tailwind.config.js # Tailwind 与品牌色变量映射
├── package.json ├── package.json
└── bun.lock └── package-lock.json
``` ```
主要启动链路:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `App.jsx` → 业务页面。`PageLayout` 拉取 `/api/status`,校验用户会话,并组织全局布局。 主要启动链路:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `App.jsx` → 业务页面。`PageLayout` 拉取 `/api/status`,校验用户会话,并组织全局布局。
@@ -210,9 +194,9 @@ monkey-ai-web/
当前目录登记了简体中文、繁体中文、英语、日语、韩语、越南语和泰语。虽然存在 `fr.json`、`ru.json`,且提取配置包含这两种语言,但它们没有登记到运行时语言目录,不能据此判断界面已开放法语和俄语。 当前目录登记了简体中文、繁体中文、英语、日语、韩语、越南语和泰语。虽然存在 `fr.json`、`ru.json`,且提取配置包含这两种语言,但它们没有登记到运行时语言目录,不能据此判断界面已开放法语和俄语。
```bash ```bash
bun run i18n:extract npm run i18n:extract
bun run i18n:status npm run i18n:status
bun run i18n:lint npm run i18n:lint
``` ```
提取和同步可能修改语言包,提交前检查 diff。新增语言除了登记前端目录,还需与后端支持语言列表对齐。 提取和同步可能修改语言包,提交前检查 diff。新增语言除了登记前端目录,还需与后端支持语言列表对齐。
@@ -221,33 +205,34 @@ bun run i18n:lint
| 命令 | 用途 | | 命令 | 用途 |
| --- | --- | | --- | --- |
| `bun run dev` | 启动开发服务 | | `npm run dev` | 启动开发服务 |
| `bun run build` | Vite 生产构建,输出 `dist/` | | `npm run build` | Vite 生产构建,输出 `dist/` |
| `bun run preview` | 预览构建结果,默认端口 4173 | | `npm run preview` | 预览构建结果,默认端口 4173 |
| `bun run test` | 调用 `node --test` 执行现有测试 | | `npm run test` | 调用 `node --test` 执行现有测试 |
| `bun run eslint` | JS / JSX 静态检查 | | `npm run check` | 依次执行 ESLint、测试和生产构建,任一步失败即停止 |
| `bun run eslint:fix` | 自动修复可修复的 ESLint 问题 | | `npm run eslint` | JS / JSX 静态检查 |
| `bun run lint` | Prettier 格式检查,并非 ESLint | | `npm run eslint:fix` | 自动修复可修复的 ESLint 问题 |
| `bun run lint:fix` | Prettier 全项目格式化,会批量修改文件 | | `npm run lint` | Prettier 格式检查,并非 ESLint |
| `bun run i18n:sync` | 同步语言资源结构 | | `npm run lint:fix` | Prettier 全项目格式化,会批量修改文件 |
| `npm run i18n:sync` | 同步语言资源结构 |
建议开发分支从 `weiyuan` 创建。提交前执行相关测试、ESLint 和构建,检查登录、修改页面、接口错误提示与移动布局。`bun run build` 只执行 Vite 构建,不会自动执行 ESLint 或测试。 建议开发分支从 `weiyuan` 创建。提交前执行相关测试、ESLint 和构建,检查登录、修改页面、接口错误提示与移动布局。`npm run build` 只执行 Vite 构建,不会自动执行 ESLint 或测试。
当前 ESLint 对 JS / JSX 配置了版权头、未定义标识符、未使用导入和 Hooks 规则,新增文件参考相邻文件的头部格式。 当前 ESLint 对 JS / JSX 配置了版权头、未定义标识符、未使用导入和 Hooks 规则,新增文件参考相邻文件的头部格式。
### 当前交接注意点 ### 当前交接注意点
1. **格式化配置存在模块格式问题**:`.prettierrc.mjs` 使用了 `module.exports = require(...)`。按 Node ESM 加载会报 `require is not defined in ES module scope`;使用 Prettier 前需要将配置改为正确的 ESM 写法或调整为合适的 CommonJS 配置形式。本文未修改该配置。 1. **格式化配置已统一**:`.prettierrc.mjs` 使用 ESM 导出,保留原有单引号规则;`.prettierignore` 排除构建产物与工具缓存。全仓仍有历史格式差异,修改时只格式化涉及的文件,不要为修复业务问题运行全仓 `lint:fix`。
2. **构建产物尚未被仓库规则排除**:当前 `.gitignore` 忽略 `/build`,但 Vite 默认输出 `/dist`。构建后提交前检查 `git status`,避免把生成文件提交;团队可后续补充 `/dist` 忽略规则。 2. **构建产物已忽略**:`dist/` 不提交,部署时使用 `npm run build` 生成。
3. **历史说明可能落后于代码**:部分子目录 README 仍写着 `web/src/...`,或把已经实现的功能描述成占位页。当前路径应去掉原来的 `web/` 前缀,行为以源码为准。原项目的后端、运维文档和部分注释引用的外部路径不在本仓库中。 3. **历史说明可能落后于代码**:部分子目录 README 仍写着 `web/src/...`,或把已经实现的功能描述成占位页。当前路径应去掉原来的 `web/` 前缀,行为以源码为准。原项目的后端、运维文档和部分注释引用的外部路径不在本仓库中。
4. **本次交接未执行安装、构建或完整测试**:本文依据当前源码与配置整理,命令列为开发流程,不代表该版本已经完成环境验收。 4. **验证记录**:维护性优化后,179 项测试和生产构建通过,ESLint 无错误但仍有 172 个历史警告,详见 [维护性优化报告](./docs/MAINTAINABILITY_REPORT.md)。
## 7. 构建与部署 ## 7. 构建与部署
```bash ```bash
bun install --frozen-lockfile npm ci
bun run build npm run build
bun run preview npm run preview
``` ```
将 `dist/` 作为静态站点发布,部署环境需处理: 将 `dist/` 作为静态站点发布,部署环境需处理:
@@ -255,7 +240,7 @@ bun run preview
- **路由回退**:本项目使用 BrowserRouter。直接访问 `/org/...` 等页面时,静态服务器需回退到 `index.html`,否则刷新会返回 404。 - **路由回退**:本项目使用 BrowserRouter。直接访问 `/org/...` 等页面时,静态服务器需回退到 `index.html`,否则刷新会返回 404。
- **接口转发**:生产环境配置实际的反向代理或独立后端地址。Vite 的开发代理不会打包进静态文件;`preview` 仅供本地预览,不能代替生产网关。 - **接口转发**:生产环境配置实际的反向代理或独立后端地址。Vite 的开发代理不会打包进静态文件;`preview` 仅供本地预览,不能代替生产网关。
- **实时响应**:使用 SSE 的接口需要关闭响应缓冲并设置合理超时;使用 WebSocket 时配置连接升级转发。 - **实时响应**:使用 SSE 的接口需要关闭响应缓冲并设置合理超时;使用 WebSocket 时配置连接升级转发。
- **配置缓存**:`config.js`、`index.html` 应允许及时更新,带哈希的静态资源可以使用长缓存。 - **发布与缓存**:`index.html` 应允许及时更新,带哈希的静态资源可以使用长缓存。后端构建变量包含在产物中,切换地址需重新构建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存。
- **部署路径**:当前按域名根路径部署,资源和路由包含根路径引用。部署到子目录需另行检查 Vite `base`、路由和静态资源地址。 - **部署路径**:当前按域名根路径部署,资源和路由包含根路径引用。部署到子目录需另行检查 Vite `base`、路由和静态资源地址。
仓库中的 `vercel.json` 目前只有 GitHub 通知设置,没有配置 SPA 路由回退或后端代理,不能视为完整部署配置。 仓库中的 `vercel.json` 目前只有 GitHub 通知设置,没有配置 SPA 路由回退或后端代理,不能视为完整部署配置。
@@ -267,11 +252,11 @@ bun run preview
| 页面可打开,但提示无法加载状态或接口失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;Vite 代理是否正确 | | 页面可打开,但提示无法加载状态或接口失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;Vite 代理是否正确 |
| 登录后仍回到登录页 | `/api/user/self`、Cookie 是否发送、跨域凭证策略,以及测试账号状态 | | 登录后仍回到登录页 | `/api/user/self`、Cookie 是否发送、跨域凭证策略,以及测试账号状态 |
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求中的 `X-Org-Id` | | 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求中的 `X-Org-Id` |
| 修改环境变量后无变化 | 是否重启开发服务或重新构建;`config.js` 是否覆盖环境变量;浏览器缓存 | | 修改环境变量后无变化 | 是否重启开发服务或重新构建并发布;构建时的变量值;HTML 与静态资源缓存 |
| 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 | | 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 |
| 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML | | 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML |
| 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 | | 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 |
| 格式检查报 `require` / `module` 未定义 | 上述 `.prettierrc.mjs` 模块格式问题 | | 格式检查提示大量 Code style issues | 全仓仍有历史格式差异;保留统一配置,只格式化本次修改文件 |
| 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 `config.js` / 静态资源缓存 | | 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 HTML / 静态资源缓存 |
首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 选择已配置的测试模型验证对话。接口字段和业务权限问题需与后端负责人共同确认。 首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 选择已配置的测试模型验证对话。接口字段和业务权限问题需与后端负责人共同确认。
-2872
View File
File diff suppressed because it is too large Load Diff
+113
View File
@@ -0,0 +1,113 @@
# 维护性优化报告
日期:2026-10-21
## 目标与边界
在保持现有页面、路由、接口和有效持久化数据兼容的前提下,提取重复规则、降低模块耦合、修复已确认的问题,并补充可执行回归测试。未升级依赖、迁移技术栈、调整 UI 或重写核心业务流程。
“无法优化”没有可客观证明的终点。本轮以已识别的低风险优化完成、相关测试与构建通过、独立复查未发现新增正确性问题为停止条件,不把缺少业务环境验证的重构视为安全优化。
## 已完成的改动
### 1. 通用存储解析与表格紧凑模式
- 新增 `src/helpers/storageJson.js`,统一处理 JSON 解析、数组/对象形状校验和存储读取失败;每次返回独立的默认容器,不共享可变状态。
- 新增 `src/helpers/tableCompactMode.js`,将表格偏好从依赖 React/UI 的 `utils.jsx` 中分离,读取与跨标签页事件使用相同解析规则。
- `utils.jsx` 保留原有导出,旧调用方无需迁移;存储键、每个表格的独立设置和有效值的真假判断保持兼容。
- 紧凑模式写入失败仍为尽力保存,不阻止本页面切换。非法跨标签页值现在统一恢复为默认非紧凑模式,而不是保留过期状态。
### 2. 通知已读状态
- 新增 `src/helpers/notificationReadState.js`,集中公告标识、未读列表、已读合并和持久化规则。
- `useNotifications` 的未读数量来自未读列表,避免两套独立筛选逻辑;稳定空公告数组和回调依赖,消除该处 Hooks 警告。
- 保持“发布日期 + 内容前 30 字符”的既有公告标识、重复公告计数、已读历史和关闭通知的处理顺序。
- 非法或非数组存储数据按未读处理;写入失败仍向上传播,不假装持久化成功。
### 3. 日志列偏好
- 新增 `src/helpers/columnVisibility.js`,由用量日志和任务日志共同使用,复用统一存储解析器。
- 合并顺序为:当前默认列 → 已保存的合法布尔值 → 强制隐藏列。
- 新增列获得默认值,显式 `false` 保留;未知列和非法字段值被忽略,非管理员不能通过本地偏好显示管理员专属列。
- 保留两种日志各自的存储键、默认列、重置/全选行为和接口请求。
- 未扩大为通用数据 Hook,避免把不同业务表格的请求与生命周期强行统一。
### 4. 企业用量筛选参数
- 新增 `src/helpers/orgLogFilters.js`,明细、汇总、排行复用用户、时间和模型筛选字段的接口映射。
- 分页、排行数量和绕过缓存参数继续由具体接口管理,不混入共享筛选参数。
- 保留原有空值/零值省略规则;没有修改请求代次控制、组织请求头或明细 `total=-1` 时保留已知总数的行为。
### 5. 用户管理分页与错误状态
- 修复修改每页条数时已将页面设为 1、却用旧页码发请求的问题;现在统一调用 `refresh(1, size)`。
- 翻页、调整每页条数和刷新复用相同请求路径,保留当前表单筛选条件,不再在调整条数后丢失搜索。
- 用户搜索通过 Axios `params` 编码,防止 `&`、`+`、`#` 等字符改变查询含义。
- `loadUsers` / `searchUsers` 使用 `finally` 复位加载状态;翻页入口处理请求拒绝,避免一直显示加载或未处理的 Promise 拒绝。
- 保留现有导出接口、首次请求的 page=0 约定及空筛选回退行为。
- 浏览器验收发现 Semi 调整每页条数后还会自动触发页码回调,从第 3 页的 10 条改为 20 条时,会额外请求第 2 页的旧 10 条,覆盖正确结果。已在通用分页工厂增加默认关闭的 `preventPageChangeOnPageSizeChange` 选项,仅用户列表启用;由用户列表的条数处理函数负责重置第 1 页,其他表格行为不变。
### 6. 开发检查工具
- 将 `.prettierrc.mjs` 改为有效的 ESM,删除 `package.json` 中重复的 Prettier 配置,并保留原先实际生效的单引号选项。原先 package.json 配置优先命中,掩盖了 `.mjs` 的加载错误。
- 新增 `.prettierignore`,排除构建产物、覆盖率和工具缓存,不屏蔽业务源码的历史格式问题。
- 补齐 `public/config.js` 和两个既有测试文件的标准许可证头,清除 3 个 ESLint 错误,不禁用规则。
- 修复 `scripts/translated_ja.json` 缺少结束括号导致的 JSON 语法错误,没有修改翻译内容或补造缺失翻译。
- 新增 `npm run check`,依次执行 ESLint、测试和生产构建;任一步失败即停止。该命令不代表全仓格式检查、浏览器测试或类型检查通过。
- 同步 README 和项目分析中的过期说明;依赖清单版本及锁文件保持不变。
## 验证结果
环境:Windows 10 / Git Bash,Node.js 22.23.3,npm 10.9.9。
| 检查 | 优化前 | 优化后 |
| --------------------------------- | ---------------------------------------- | ------------------------------------------- |
| `npm test` | 128 通过,0 失败 | 179 通过,0 失败;新增 51 项 |
| `npm run eslint` | 3 错误,173 警告;退出 1 | 0 错误,172 警告;退出 0 |
| `npm run build` | 通过,有大 chunk 告警 | 通过,仍有大 chunk 告警 |
| `npm run check` | 无统一入口 | 通过,包含上述三项 |
| `npm run lint` | 因 JSON 语法错误退出 2,另有历史格式差异 | 不再有解析/配置错误;仍因历史格式差异退出 1 |
| 已修改的 JS/JSX/MJS/JSON 格式检查 | — | 通过 |
| 仓库已跟踪及非忽略的 JSON 解析 | — | 33 个文件全部可解析 |
| `git diff --check` | — | 通过 |
| 独立 code review | — | 未发现本次改动新增的正确性问题 |
新增测试分布:
- `src/helpers/storageJson.test.js`:18 项,覆盖存储异常、通知标识/合并、紧凑模式独立设置和失败策略。
- `src/helpers/columnVisibility.test.js`:12 项,覆盖默认值合并、非法值、角色限制及输入不变性。
- `src/helpers/orgLogFilters.test.js`:4 项,覆盖字段映射、省略规则、端点隔离和输入不变性。
- `src/hooks/users/useUsersData.test.js`:13 项,执行真实 Hook 导出的分页/搜索处理函数,并使用 Axios 实际序列化逻辑验证参数;React 状态与 effect 通过轻量测试替身驱动。
- `tests/users-pagination.test.js`:4 项,执行已安装 Semi 的真实分页 foundation,验证用户列表接线、桌面/移动端调整条数只触发一次回调、后续翻页可用,以及其他表格的默认行为保持不变。
上述 Node 测试不模拟完整 React 调度、StrictMode、DOM 或后端权限,不能替代浏览器和真实后端验收。
生产构建的 `/`、`/login`、`/org/login`、`/console/user`、`/config.js` 已通过 HTTP 冒烟:均返回 200,HTML 有 React root 和可访问的生产入口 JS。
### 提交前浏览器验收
使用 Chrome 155.0.8059.85 headless、独立浏览器上下文和生产预览的随机本地端口;桌面视口 1440×900,移动视口 390×844,DPR=1,语言 zh-CN。Playwright 工具安装在系统临时目录,不改项目依赖或锁文件。所有业务 API 由本地 fixture 拦截,外部请求阻断,没有接触真实用户会话或执行后端写入。
以下场景通过真实点击、输入和网络请求观察验收:
1. 用户管理页加载,已查看桌面及移动端截图,列表和操作区正常渲染。
2. 搜索 `alice & bob+#?=user`,翻到第 3 页后改为每页 20 条:只发出一次第 1 页、20 条的请求,搜索参数完整保留,显示 20 行。修复前实际复现了旧条数的第二次请求;修复后通过。
3. 两个标签页之间双向切换紧凑模式,当前页立即更新,另一页通过真实 storage 事件同步。
4. 非数组的通知已读存储可恢复,打开通知并点击“我知道了”后写入兼容格式的已读键。
5. 移动端列表可见,点击“显示操作项”后可操作搜索控件。
6. 分页接口主动返回 HTTP 503 后加载状态复位;恢复接口后点击查询成功。未出现未处理的 Promise 拒绝。
最终浏览器复验没有 pageerror 或非预期 console error;主动注入的 503 产生预期网络/Axios 错误日志。最初调试中的选择器不匹配、缺少 fixture 字段已在测试脚本中修正,没有为测试修改业务返回值。真实登录、权限与线上后端仍未验收。
本地浏览器验收脚本、结果和截图位于系统临时目录 `monkey-ai-acceptance-A0u9pq`,不纳入应用产物;防回归的 4 项 Semi 分页测试已纳入仓库。按用户要求删除不再保留的 npm 迁移和性能历史报告,并清理其失效引用。
## 保留的风险与后续工作
- 172 个历史 ESLint 警告仍需按具体场景处理。没有批量补 effect 依赖、禁用规则或修改告警级别,避免引入重复请求与循环渲染。
- 全仓仍有数百个文件的历史格式差异。仅格式化涉及的代码,不用大面积格式变动掩盖业务差异。
- 大 chunk 告警仍在;拆包、图标和可视化依赖优化需要浏览器加载与缓存证据,不能凭构建耗时宣称页面性能提升。
- 真实登录、企业切换、后端权限及业务接口仍需在可用测试环境验收;本地 fixture 浏览器结果不代表真实后端联调通过。
- 本轮没有实施全局异步请求竞态治理、统一所有数据 Hook、依赖升级或大型页面拆分。这些改变影响范围较大,需要明确业务契约和更完整的集成测试。
建议日常运行 `npm run check`;涉及页面改动时同时验证浏览器场景,对本次编辑的文件执行 `npx prettier <文件列表> --check`。不要将这份报告理解为整个项目已无缺陷或不存在进一步优化空间。
@@ -0,0 +1,374 @@
# 前端模块化改造:可行性评审与渐进实施方案
> 整理日期:2026-10-27。面向项目维护者、新接手开发者和技术负责人。
> 配套导读:[页面渲染、路由与 API 调用链分析](./RENDER_ROUTING_API_REFACTOR.zh-CN.md)。本文集中说明改造决策、实施步骤和验收要求;源码依据及行号基准为 `weiyuan` 分支、提交 `821577f`。
> 本次交付是源码评审与实施设计,不是已完成的重构。未修改应用代码,未执行测试、构建或浏览器验收;历史测试记录不代表本次验证结果。后端授权规则未在本次前端仓库评审中验证。
## 1. 决策摘要
**建议批准“保行为的顶层路由模块化”,有条件推进“用户查询 service 试点”;暂不批准全站目录重排、统一守卫、布局重构和 HTTP 客户端重写。**
采用沿用 React Router、保持已有 URL 与权限、按业务拆分路由、渐进建立领域接口边界的路线。实施以可核对的行为基线和分批验收为前提,不将目录调整等同于维护性提升。
| 维度 | 评估 | 决策依据 |
| ------------------ | -------------- | -------------------------------------------------------- |
| 技术可行性 | 高 | 当前 Router 可支持 RouteObject/useRoutes,无须迁移技术栈 |
| 首期维护收益 | 明确,但局部 | 路由归属和策略入口更清晰;不会自动解决大型业务页面可读性 |
| 行为回归风险 | 中高 | 企业限制、动态权限、认证时序、key、重定向相互影响 |
| 新人独立一次性交付 | 不建议 | 隐性规则需要维护者/产品确认,不能靠代码推断业务意图 |
| 后端依赖 | 首期无需改接口 | 仍需测试账号、配置样本和真实会话联调支持 |
| 性能收益 | 不承诺 | 拆文件不是性能优化,构建及请求行为需单独观察 |
**首期完成的定义:一个新人能准确找到路由、权限和用户查询入口,且原行为通过对照验证;不是 App 行数下降,也不是所有模块都有 service。**
## 2. 当前问题:不是缺少分层,而是边界不稳定
现有用户列表已经具备:
```text
App 路由 → User 页面 → UsersTable → useUsersData → API
```
因此,不需要推翻重建 MVC、引入 Redux 或把全部文件搬到 features。当前主要成本是:
| 问题 | 源码证据 | 实际维护成本 |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| 路由声明与业务访问策略混合 | [App.jsx](../src/App.jsx#L105-L231) | 新增页面前要理解企业放行、动态配置、守卫等多套规则 |
| URL 前缀不等于权限边界 | [App.jsx](../src/App.jsx#L317-L348) | `/console` 下同时存在登录、Admin、Root 三种权限 |
| 布局规则独立依赖路径字符串 | [PageLayout.jsx](../src/components/layout/PageLayout.jsx#L94-L131) | 新路由可能匹配页面却漏配滚动、侧栏和顶栏 |
| 布局承担会话与站点初始化 | [PageLayout.jsx](../src/components/layout/PageLayout.jsx#L193-L254) | 搬布局会间接改变请求时机和会话恢复 |
| 守卫等待条件并非完全相同 | [auth.jsx](../src/helpers/auth.jsx#L59-L142) | 表面相似的包装不能直接统一 |
| service 已存在但契约不一致 | [playgroundConversation.js](../src/services/playgroundConversation.js)、[secureVerification.js](../src/services/secureVerification.js) | 不能按“从零建立统一层”机械迁移 |
| 公共 API 包含业务逻辑及登录副作用 | [api.js](../src/helpers/api.js)、[loginFlow.js](../src/helpers/loginFlow.js#L41-L58) | 移动入口可能捕获旧实例或改变错误处理 |
这是一项**职责整理与行为显式化工程**,不是换框架工程。对新人而言,减少“为改一个功能必须了解全站规则”的成本,比减少文件数量更重要。
## 3. 技术选型与关键约束
### 3.1 设计原则
- 保留现有 BrowserRouter 和 Provider 层级。
- 以模块化 RouteObject + `useRoutes` 为目标,不为拆文件迁移 Data Router。
- lazy 声明放在模块顶层,不放进组件或路由工厂。
- 复用现有 PrivateRoute、AdminRoute、RootRoute,不按 URL 前缀套统一权限。
- 首期不搬 pages/components/hooks,不改变页面业务状态归属。
- 企业限制先原样提取、测试,再讨论简化。
- service 首轮保持 Axios response,不全局修改拦截器返回结构。
- 保留不同网络传输方式,不把 Fetch/SSE 强行收敛到普通 Axios 请求。
### 3.2 行为兼容约束
#### A. “等待认证完成”的描述不能一概而论
当前 `PrivateRoute` 先判断 `userState.user`,已有用户时直接渲染;`AdminRoute`、`RootRoute` 则先检查“未完成认证且有缓存”。`AuthRedirect` 同样先判断当前用户。
因此,对“Context 已有用户、authChecked=false、本地仍有缓存”这个输入,不同守卫可能表现不同。不能将其概括为“所有守卫都等待认证完成”。
**实施要求:分别锁定各守卫的判断顺序,不在模块化 PR 中统一。** 是否应调整为统一等待,是独立的会话策略决策,需要考虑公共页、已登录导航及服务端会话校验,不等同于发现了可直接修复的漏洞。
#### B. 64 条声明不等于 64 个测试用例
分析基准中的顶层声明数量可用于检查迁移遗漏,但不能覆盖动态配置、角色、认证中间态、内部子路由、旧地址与具体通配匹配关系。
应建立“路由清单 + 策略矩阵 + 关键导航序列”三类基线。不能通过检查路径数量相等就认定迁移正确。
#### C. API 重建有会话隔离用途,不只是重装配置
`loginFlow.js` 在设置登录用户后调用 `updateAPI()`。新实例拥有新的在途请求集合,避免新会话直接复用旧实例中的请求。
service 必须在函数调用时读取 `API` 的 live binding,不能模块顶层保存 `const client = API` 或绑定 `API.get`。重建实例不等于取消旧请求,也不能据此认为旧结果回写问题已经解决。
### 3.3 路由方案比较
| 方案 | 优点 | 代价与结论 |
| --------------------------------------- | -------------------------------- | ---------------------------------------------------- |
| A:按业务提取 JSX 路由片段 | 最接近现有实现,便于逐行对照 | 可以作为长期方案,但重复包装仍需维护 |
| B:RouteObject + useRoutes | 路径与元素配置集中,易按模块组合 | **本方案选择**;保留现有 BrowserRouter 与守卫 |
| C:createBrowserRouter + RouterProvider | 支持路由级 loader/action | 涉及上下文和数据生命周期迁移,不是本次拆分的必要条件 |
迁移至 B 时,用 `createRoutesFromElements` 临时承接旧声明,再逐模块替换为对象,不必先完成一次全量 JSX 拆分。不要使用 `<Routes><ConsoleRoutes /></Routes>` 注册自定义路由组件:Routes 接收的声明应为 Route 或 Fragment,而不是等待自定义组件渲染出的 Route。
本期无需升级 Router。未来若采用 Data Router,应明确最低依赖版本;当前锁定版本支持相关 API,不代表声明下界 `^6.3.0` 已保证 6.4+ 能力。
## 4. 范围与不做事项
### 首期范围
1. 顶层路由行为清单与高风险用例。
2. 企业访问策略的纯函数提取及测试。
3. 顶层路由按业务拆分,保留既有守卫、lazy、Suspense、key 和跳转。
4. 用户列表与搜索 API 的独立试点,在路由变更稳定后提交。
5. 更新新人开发指南和模块维护约定。
### 明确不做
- 不升级 Router,不引入 Data Router、查询缓存库或全仓 TypeScript。
- 不移动全站目录,不自动生成菜单,不建设通用权限 DSL。
- 不改企业内部权限、不重排 Provider、不迁移启动副作用。
- 不改分页页码、错误提示规则、取消语义和去重算法。
- 不改体验中心未知路径行为、不统一 `/` 与 `/home` 布局。
- 不声称解决所有大组件和复杂 Hook;相关问题另建治理清单。
## 5. 目标结构及依赖规则
```text
src/
App.jsx # 保留 SetupCheck、企业限制与路由出口的顺序
router/
AppRoutes.jsx # useRoutes,仅消费路由配置
createAppRoutes.jsx # 组装;不发请求、不持有业务状态
modules/
console.routes.jsx
public.routes.jsx
auth.routes.jsx
account.routes.jsx
organization.routes.jsx
experience.routes.jsx
client.routes.jsx
legacy.routes.jsx
policy/
useRoutePolicy.js # Context/现有成员 Hook 的适配
orgAccessPolicy.js # 无 React、无存储、无网络的纯判断
services/
users.js # 首批仅用户列表与搜索
pages/ # 原位置不变
hooks/ # 原位置不变
helpers/api.js # 首期保留
```
目录逐批创建,不提前铺空文件。企业认证路径归 auth,而非仅按 `/org` 前缀归企业工作区。
### 职责合同
| 层 | 可以做 | 不应做 |
| -------------- | ------------------------------------- | ------------------------------------ |
| router/modules | 声明路径、页面、原有守卫/开关/边界 | 发业务请求、维护列表状态 |
| policy Hook | 读取 Context 和现有成员状态,组织输入 | 另建一套用户缓存、改变初始化时机 |
| policy 纯函数 | 根据输入返回放行/限制结果 | 读 localStorage、调用 Hook、执行导航 |
| 页面与业务组件 | UI 组合与事件接线 | 为同一领域重复拼接口协议 |
| 业务 Hook | loading、筛选、分页、业务失败反馈 | 创建第二个 HTTP 客户端 |
| service | 方法、URL、参数、原样响应/拒绝 | toast、路由跳转、React state |
| HTTP 客户端 | 地址、凭证、拦截器、在途去重 | 感知用户表格页码等领域 UI |
新代码优先直接导入具体模块;不新增全项目聚合出口,不为了“少写 import”隐藏依赖。已有导入暂不全仓修改。
## 6. 路由迁移设计
### 6.1 先建立可比较的契约
建议建立 `docs/ROUTE_CONTRACT.zh-CN.md`,每条声明记录:
- path、所属模块、目标组件或重定向目标。
- 守卫类型及包装顺序,包含功能关闭时是否仍经过守卫。
- 动态条件与默认值来源。
- Suspense 是否存在、key 是否使用 pathname。
- replace、query/hash 保留策略、OAuth provider type。
- 是否后代 Routes 入口、具体路径与通配入口的关系。
- 当前布局规则及验证状态。
清单依据旧代码独立建立并评审,不由新路由表生成后反过来证明自己正确。运行时路由表仍只有一份,文档不参与运行时权限判断。
### 6.2 分批迁移但保持同一棵匹配树
1. 先引入 `useRoutes(createRoutesFromElements(原有声明))`,不改元素内容。
2. 保留旧声明转换出的剩余路由对象,逐批与新模块数组合并,交给同一个 useRoutes。
3. 每迁移一个 path,同一提交中删除对应旧声明;不允许新旧重复注册。
4. 每批检查 catch-all 唯一、具体路径不丢失、后代入口仍有 `/*`。
5. 全量迁移后删除临时转换层。
不创建第二个 BrowserRouter,不长期维护两个并行路由系统。工厂函数只组合元素,不调用 Hook;Hook 在稳定组件顶层调用。
App 的企业限制可继续在子组件 AppRoutes 挂载前返回 Navigate,从而保留原有“受限时不渲染路由出口”的组织方式。不要把 useRoutes 放在同一组件的条件 return 后面。
### 6.3 第一批选择控制台的三种权限代表
从 `/console/user`、`/console/my-commission`、`/console/commission` 开始,分别验证 Admin、Private、Root。试点通过后再迁移其余控制台、公共/认证、企业/体验入口、兼容路由。
迁移必须保留以下反例:
- 不能给全部 `/console` 路由加 Admin 父守卫。
- `/login` 是 Suspense 外包 AuthRedirect,不能为整齐擅自倒置。
- `/user-center/*` 没有 pathname key,不能统一加 key。
- OAuth OIDC 分支与其他回调的 key 配置有差异。
- 云脑开关关闭时部分路径直接跳转,不应无意新增鉴权步骤。
- `/pricing` 保留 query/hash,其他旧跳转不能默认照搬这个策略。
### 6.4 抽象的停止条件
首轮允许保留重复 JSX。只有多条路由经验证确实具备相同包装顺序和重挂载规则,才提取公共包装。
不以 `auth: true` 替代全部访问语义,不把复杂条件塞进万能 Guard。更短但更隐晦的代码不是本次目标。
### 6.5 企业策略提取边界
| 提取对象 | 目标位置 | 必须保留的行为 |
| ------------ | -------------------------- | ------------------------------------------------------------ |
| 模块登录配置 | useRoutePolicy | HeaderNavModules 的默认值与 requireAuth 解析 |
| 企业路径放行 | orgAccessPolicy | 精确路径或 `prefix + '/'`,不能扩大为裸 startsWith |
| orgConfined | 纯函数判断与 Hook 输入适配 | 成员未加载不提前重定向;企业中心关闭不形成跳转循环 |
| 企业顶栏例外 | 纯策略函数 | 顶栏配置入口、tutorial/recharge 开关与企业管理员技能超市例外 |
先原样提取再测试,不新增全站阻塞等待,也不改变成员查询 Hook 的调用条件。菜单显示、路由放行和后端授权是不同边界,不能相互替代。
## 7. 用户查询 API 试点
### 7.1 契约
新增 users service,仅封装列表和搜索;保持完整 Axios response。示意:
```js
import { API } from '../helpers/api';
export function listUsers({ page, pageSize }) {
return API.get(`/api/user/?p=${page}&page_size=${pageSize}`);
}
export function searchUsers({ page, pageSize, keyword, group }) {
return API.get('/api/user/search', {
params: { keyword, group, p: page, page_size: pageSize },
});
}
```
保留 URL 形式是为了不同时改变 GET 去重 key。service 不包装 AxiosError,不加 toast,不默认设置 skipErrorHandler,不捕获旧 API 实例。
Hook 继续负责:初次 `p=0`、修改页大小后回到第 1 页、空筛选回退、success 判断、数据格式化及 loading。分组接口可暂保留原调用并登记待迁移;不为两条查询强建通用 repository。
### 7.2 不扩大首批范围
新增/编辑用户弹窗、邀请列表、用户管理写操作、2FA/Passkey 重置另批迁移。完成本次试点只能说“用户查询接口已集中”,不能说“用户模块已完成 service 化”。
后续再评估统一领域返回值。若改为返回业务 data,必须说明业务失败如何表达、HTTP 错误是否保持、提示由谁负责,并一次迁移完整的一组消费者;不全局修改 Axios 拦截器。
### 7.3 既有问题单独登记
| 问题 | 处理原则 |
| ----------------------------------- | --------------------------------------------- |
| 全局拦截器与局部 catch 可能重复提示 | 单独定义错误所有权;首轮不新增提示层 |
| 不同搜索请求的旧结果可能覆盖新结果 | 独立修复请求序号/取消策略,不能声称去重已解决 |
| 去重 key 不含所有请求选项 | 不在抽 service 时擅自扩大取消和参数标准化范围 |
| Hook 格式化会修改响应对象 | 独立评估共享响应的可变性,不混入纯搬迁 |
| 部分写操作失败后的 loading 恢复 | 独立缺陷修复,避免扩成用户管理全量重写 |
这些是后续验证与治理项,不表示本次已复现线上故障。
## 8. 测试与验收门禁
### 8.1 先承认现有测试边界
当前 `npm test` 使用 Node 内置测试运行器。用户 Hook 测试通过转译和 VM/替身执行;分页测试不是浏览器测试;去重 key 测试不等于真实 Axios 并发行为测试。
抽取 service 后需同步调整 Hook harness,并增加 service 请求契约测试,不能把新 import 全部 mock 成固定成功结果,导致原参数测试失效。
路由组件测试建议补充 Vitest + React Testing Library/jsdom,作为独立脚本,不替换现有 Node 测试。引入时核对当前 Vite/React 的兼容版本,明确测试文件匹配范围,避免两个 runner 重复收集。测试设施应单独提交。
### 8.2 最低覆盖矩阵
| 测试层 | 必须验证 | 验证手段 |
| -------- | ---------------------------------------------------------------- | ----------------------------------------- |
| 纯策略 | 企业中心开/关、成员未加载/已加载、管理员例外、额外路径、前缀碰撞 | node:test,表驱动 |
| 路由匹配 | 原路径完整、重复声明、具体路径优先于通配、未知路径 | 生产路由对象及 Router 匹配测试 |
| 守卫渲染 | 游客、普通用户、role=10、role=100、非数字 role、缓存校验中 | MemoryRouter + 真实守卫 + fixture Context |
| 特殊导航 | query/hash、replace、OAuth type、开关关闭后的目标 | 组件路由测试及浏览器核对 |
| 生命周期 | 有 key 与无 key 的代表路径、参数变化、前进后退 | 挂载计数探针;真实页面观察 effect/请求 |
| service | 方法、URL、参数编码、完整响应、原样 reject、API 实例替换 | 真实 service + 可控客户端替身 |
| 用户查询 | 初始页、搜索、空搜索、页大小、刷新、业务失败、网络失败后状态复位 | 保留现有专项测试并补充 |
| 浏览器 | 深链接刷新、回跳、侧栏/滚动/抽屉、请求次数 | 可复现人工步骤或自动化浏览器测试 |
不做所有维度的笛卡尔积;覆盖每条路由基础映射,对权限/动态策略做重点组合。特别要测“Context 有用户但 authChecked=false”与“仅缓存有用户”的区别。
### 8.3 每个 PR 的退出条件
- 迁移路径有旧/新契约对照,所有差异都有明确说明。
- 修改文件格式检查、ESLint、定向测试通过。
- 合并前运行 `npm run check` 和 `git diff --check`,记录命令、提交及结果。
- 历史告警与新增告警分开记录,不能用历史通过记录替代本批测试。
- 高风险身份路径通过浏览器验证;mock 验证与真实后端验证分开标注。
- 若无真实测试账号,标记为“待联调”,不能验收权限相关发布。
`npm run lint` 在本项目中是全仓格式检查,不应误认为 ESLint。实施时以 package.json 实际脚本为准,不为了过格式门禁顺手格式化整个仓库。
## 9. 实施计划、成本和协作
以下是规划估算,不是交付承诺。假设一名实施开发者、一名熟悉业务的维护者参与评审,具备可用环境和角色账号;不含排队等待及未知缺陷修复。
| 批次 | 交付内容 | 估算人日 | 退出条件 |
| ---- | ---------------------------------------------- | -------- | ---------------------------- |
| P0 | 路由契约、账号/配置矩阵、风险清单 | 1.5~2 | 维护者确认关键访问规则 |
| P1 | 路由测试设施、关键守卫/策略特征测试 | 1.5~2.5 | 重构前测试可复现当前行为 |
| P2 | 企业策略原样提取、控制台试点、分批迁移顶层路由 | 3~4.5 | 每批契约一致,全量旧声明退出 |
| P3 | 用户查询 service + Hook/test harness 迁移 | 1~1.5 | 查询请求和分页反馈不变 |
| P4 | 联调、部署验证、文档与问题修复缓冲 | 1~2 | 发布门禁和新人演练完成 |
**合计约 8~12.5 人日。** 对刚入职且需要穿插业务需求的开发者,日历周期会更长;P0 后应依据未知规则和测试建设成本重新估算。
如果只能投入约一周,优先交付行为基线、测试设施、策略提取与控制台试点,不承诺全站迁移,更不要把布局重构塞入同一期。
建议 PR 边界:测试设施 → 行为基线测试 → 策略纯搬迁 → 路由出口适配 → 各业务路由模块 → 用户查询 service → 文档。测试和对应应用变更在可审查范围内配套提交;不把新增依赖、全仓格式化与业务行为修复混在一起。
### 协作责任
- 实施开发者:源码契约、迁移、测试与证据记录。
- 熟悉业务的维护者:确认企业放行、角色边界、历史跳转等不是无意遗留。
- 测试/产品:确认未知路径、布局差异等是否允许改变;首期默认不改变。
- 后端/环境负责人:提供最小权限测试账号和配置样本,确认接口拒绝行为。
若缺少规则确认人或账号,先完成无行为变化的准备工作,不用个人经验替代业务决策。
## 10. 发布与回滚
1. 先测试环境,验证游客、普通用户、平台管理员、Root、org_only 员工及企业管理员。
2. 发布前记录旧构建版本、源码提交和验证结果;保留可重新部署的旧产物。
3. 首期不需要数据库或后端协议迁移,回滚以对应前端发布产物/独立提交为单位。
4. 发布重点观察登录循环、错误跳转、页面加载失败、用户查询错误、会话校验与成员查询次数。
5. 发现权限误放行、核心页面不可达、重定向循环,应立即撤回该批;不要线上临时关闭守卫止血。
6. 回滚 HTML 与资源需配套,避免新 HTML 指向已删除 chunk;部署回退遵循现有静态资源保留策略。
不增加永久双路由开关。迁移中的旧声明适配仅是短期过渡,不是长期双轨系统。
## 11. 如何证明对新人真的有帮助
交付一份简短的“改功能导航”,回答:
- 新增页面到哪个路由模块?如何选择已有守卫?
- 路由开关、企业放行和菜单显示分别在哪里?
- 调整用户查询参数到哪里?哪些状态仍由 Hook 管?
- 哪个命令验证路由、哪个验证分页、哪些需要浏览器?
- 为什么本项目初次页码是 0、某些路径保留 key?
评审时做一次新人演练:给定 `/console/user`,要求开发者找到页面、权限、查询入口和专项测试;再用一个普通登录页面说明为何不能挂 Admin 父守卫。
建议验收指标:
1. 顶层旧路径迁移对照无遗漏,所有已知行为差异经显式批准。
2. 企业策略可脱离浏览器以输入输出测试验证。
3. 新增普通路由无需修改 App 的业务判断;若需特殊规则,应能定位到明确策略入口。
4. 用户查询 URL 不再由 Hook 重复组装,原分页测试仍有效。
5. 同一导航序列下,会话/成员/列表请求没有无解释的新增。
6. 新维护者能在约 10 分钟内解释上述用户列表链路。该时间是建议目标,应通过实际演练校准,不是已测结果。
## 12. 后续演进
以下工作在顶层路由稳定后按需求独立立项,不计入首期验收。
### 12.1 布局与子路由
- 先保留用户中心和企业空间的后代 Routes 及父路径 `/*`。若未来统一为嵌套路由树,父布局需通过 Outlet 渲染 children。
- 体验中心由 pathname.includes 改为明确子路由时,应单独确认默认页和未知路径行为;空内容改成 404 或重定向属于行为变更。
- 先将 PageLayout 的路径判断提取为可测试规则,再评估路由元数据。不要自动将菜单、布局、权限合成同一张表。
- 提取会话和站点初始化 Hook 时,保持挂载位置及生命周期,避免切页重复校验会话和请求配置。
- `/` 与 `/home` 当前布局判断不同,是否统一需单独确认,不随目录整理修改。
### 12.2 HTTP 工具与领域接口
逐步拆分公共 HTTP 客户端、OAuth 服务、对话 payload/模型转换和错误解析。可由旧入口兼容 re-export,并保留 API 的 live binding;消费者迁移完成后再删除旧入口。
Axios、Fetch 与 SSE 保留各自传输适配器,只共享适用的地址、身份上下文和错误解析工具。用户写接口、大型业务 Hook 及请求竞态另行治理,不与纯接口搬迁混合。
### 12.3 可选能力的引入条件
- **TanStack Query**:仅在确有缓存、失效和请求生命周期管理需求时试点;query key 必须包含用户、组织、筛选和页码,并验证退出登录、组织切换、重试与现有错误提示的关系。
- **进一步懒加载**:基于访问频率、chunk 和请求瀑布评估,不能以文件数量或代码行数证明性能提升。
- **Data Router / TypeScript**:需有独立需求、迁移成本和验收依据,不作为模块化的隐含前置条件。
本方案的目标是降低理解成本、显式表达业务规则,并建立可验证的迭代方式。实施应从小范围试点开始,以行为一致和新人可定位问题作为验收依据,而不是追求一次完成全站终态设计。
+152 -77
View File
@@ -1,10 +1,96 @@
# Monkey AI Web 项目分析与开发上手指南 # Monkey AI Web 项目分析与开发上手指南
适用读者:具备 JavaScript、HTML、CSS 基础,准备参与本项目开发的初级和中级工程师。 适用读者:熟悉 Vue 3 + TypeScript + Vue Router / Pinia,刚加入项目、React 实战较少的前端工程师。本文先帮助你完成一个局部需求,再提供全项目参考;不要求一次读完。
分析基准:2026-10-17,`weiyuan` 分支,提交 `9a22d7e`。本文依据当前仓库的配置、入口、核心模块及测试整理;版本变化后,以对应源码和接口契约为准。 分析基准:2026-10-21,`weiyuan` 分支,提交 `df17f57`。依赖声明、开发代理和测试结果已重新核对;版本变化后,以对应源码和接口契约为准。
阅读建议:首次接手先读第 1、2、7 节,跑通环境后阅读第 3~5 节;实际开发时结合第 8、9、12 节,遇到配置与验证问题再查第 10、11 节。文末提供可点击的源码索引。 阅读建议:**今天先读第 0 节和第 7 节,再沿第 5.2 节读一个实际模块。** 第 2 节依赖表、第 3 节全局启动、第 6 节性能及第 10~12 节是按需查阅材料,不是入职考试清单。
## 0. 从 Vue 3 进入这个项目:先缩小学习范围
### 0.1 原文哪里正确,哪里不适合你
原文对“React 单页应用、业务页面 + Hooks、公共请求封装、多层权限、独立的流式请求”的判断基本正确。问题在于同时展开全项目,使读者难以分清今天必须掌握什么;缺少 Vue 到 React 的思维转换,而且部分配置描述已经过时。
本次修订纠正了 Vite / antd 声明版本、TypeScript 的依赖状态、代理目标与集中配置方式、构建目录忽略规则,以及旧测试结果。保留原来的架构索引,但不把历史问题当成当前事实。
你觉得复杂是有具体原因的:
- **框架陌生**:JSX、函数组件重新执行、闭包和 Effect 依赖,与 Vue 的模板及响应式追踪不同。
- **业务较多**:个人账户、企业空间、平台管理共用一个应用;你通常只需先负责其中一条业务链。
- **历史实现不完全一致**:既有业务 Hook,也有页面直接请求接口,不存在一个能套遍所有页面的标准模板。
- **权限和环境是额外维度**:看不到页面可能是角色、企业功能或后端配置问题,不一定是 React 写错了。
你已经掌握的组件拆分、HTTP、表单、分页、CSS、调试和接口联调仍然适用。**近期目标不是理解整个仓库,而是能解释并安全修改一个页面的数据流。**
### 0.2 Vue 概念在这里怎么对应
以下是帮助定位的类比,不是 API 一一等价。
| 熟悉的 Vue 写法 | 本项目 React 写法 | 关键差别 |
| --- | --- | --- |
| `.vue` 的 template + script setup | `.jsx` 函数组件,返回 JSX | 组件会随渲染重新执行,不是只执行一次的 setup |
| `ref` / `reactive` | `useState` | 用 setter 更新,不能直接修改对象或数组后期待自动刷新 |
| 普通派生值 / `computed` | 渲染时计算,必要时 `useMemo` | 简单计算直接写;`useMemo` 是缓存优化,不是必需的响应式声明 |
| `watch` / `onMounted` | 某些场景使用 `useEffect` | Effect 用于与外部系统同步;不是生命周期的机械替换 |
| DOM ref 或不参与展示的变量 | `useRef` | 修改 `.current` 不触发重新渲染 |
| composable | 自定义 Hook,例如 `useOrgMembers` | Hook 必须在组件或其他 Hook 顶层调用,不能放进条件或循环 |
| `defineProps` / `emit` | props / 回调 props | 父组件传函数,子组件调用;没有必需的 emit 注册机制 |
| `v-model` | `value` + `onChange` | 原生 input 通常读 `event.target.value`;Semi 回调参数要看组件 API,不能照搬 |
| `v-if` / `v-for` | 条件表达式 / `array.map()` | 列表使用稳定业务 ID 作为 key;会重排的列表不要用索引 |
| `provide/inject` | Context | Context 提供共享入口,不自动等于 Pinia 的完整 store 能力 |
| Pinia action | 本项目的业务函数或 Reducer + dispatch | 不必给每个页面建全局 store;页面状态优先留在局部 |
| Vue Router 守卫 | React Router + `PrivateRoute` / `AdminRoute` 等包装组件 | 本项目靠路由元素组合限制访问,不是注册 `beforeEach` |
| vue-i18n | `useTranslation()` 返回的 `t` | 本项目多用中文原句作为 key |
### 0.3 先掌握这四个 React 差异
**① 每次渲染读取的是本次状态快照。** setter 安排下一次渲染,不会改写当前函数里的变量:
```jsx
const [count, setCount] = useState(0);
function increment() {
setCount((previous) => previous + 1);
// 此处的 count 仍是这次渲染的值,不是刚更新后的值。
}
```
依赖旧值时使用函数式更新;不要把 Vue 的 `count.value++` 直译成 React 中的普通赋值。对象和数组也要产生新引用,例如 `setFilters((previous) => ({ ...previous, keyword }))`。
**② 自定义 Hook 复用逻辑,不会自动共享状态。** 两个组件分别调用同一个 Hook,通常各自拥有一份状态。需要共享时再由共同父组件或已有 Context 协调。
**③ Effect 依赖不是“想什么时候跑就填什么”。** Effect 中使用的响应式值需要正确列入依赖;空数组不代表其中读取的 props 永远不会变化。涉及请求、订阅、计时器时要考虑清理和旧结果失效。开发环境启用 StrictMode 时可能额外执行一次 setup/cleanup,不要靠删除依赖来掩盖问题。
**④ `useCallback` 缓存函数身份,不是计算结果,也不会自动执行请求。** 在 `useOrgMembers(orgId)` 中,`fetch` 是返回给页面调用的业务函数,不是浏览器原生 `fetch`;`[orgId]` 变化时回调需要更新,才能使用新的组织 ID。`useMemo` 则缓存计算结果;不必给所有函数和变量加缓存。
### 0.4 用一条真实链路读懂代码
先看 [Channel/index.jsx](../src/pages/Channel/index.jsx),认识“函数返回 JSX”的薄页面即可,不必深入它的大型 Hook。然后以企业成员列表作为练习:
1. 打开 [OrgMembers.jsx](../src/pages/Organization/OrgMembers.jsx),找到 `useOrgMembers(orgId)` 的调用,记下页面取出了哪些数据和函数。
2. 打开 [useOrgMembers.js](../src/hooks/org/useOrgMembers.js),先只读 `members`、`total`、`loading` 和列表 `fetch`,暂时跳过删除与额度操作。
3. 看请求的 `params` 和 `headers`:分页是 `p/page_size`,组织是 `X-Org-Id`。
4. 回到页面,搜索列表加载函数在哪里被调用,跟踪页码变化如何触发加载、返回结果如何进入表格。
5. 用浏览器 Network 对照一次真实请求,确认组织、分页与响应结构。使用获授权的测试账号,不在生产数据上练习删除或额度修改。
注意:这条链路便于理解,并不代表现有代码每处都是最佳实践。比如公共错误提示、业务失败反馈和旧请求覆盖问题仍需按第 4、8 节检查,不能盲目复制。
读完能回答以下问题就足够进入小需求:**页面数据在哪里?谁发请求?谁更新状态?谁渲染列表?切换企业时请求范围如何改变?** 暂时不需要读完整个 `App.jsx` 或 Playground。
### 0.5 接下来几天怎么推进
| 顺序 | 做什么 | 完成标准 |
| --- | --- | --- |
| 先跑通 | 按第 7 节确认环境、登录及一个有权限的列表 | 能在 Network 找到该列表请求,分清网络错误与业务错误 |
| 再读懂 | 按第 0.4 节追踪页面 → Hook → API → 状态 → UI | 能用自己的话解释一遍,不必背 API |
| 做小改动 | 在实际分配模块增加展示字段、调整样式或扩展已有表单 | 确认加载、空数据、错误、主题和翻译,检查 diff |
| 再做完整需求 | 按第 8 节完成筛选、分页等需求 | 有明确接口契约、边界验证和相关测试 |
| 按任务深入 | 涉及登录才读会话恢复;涉及对话才读 SSE | 不为“读完整个项目”而提前研究所有模块 |
暂缓:全仓 TypeScript 迁移、全局状态重构、统一所有目录、重新设计打包、重写对话流程。这些不是新人完成首个业务需求的前置条件。仓库主体是 JS/JSX,可以继续利用你对类型和接口契约的习惯,通过返回结构、JSDoc(需要时)和测试降低误用,但不要在局部需求里擅自引入全仓 TS 迁移。
若卡住,先记录“页面 URL、预期、实际表现、请求与响应、已定位的文件”,再针对具体问题定位,而不是从头重读整份文档。
## 1. 先建立对项目的整体认识 ## 1. 先建立对项目的整体认识
@@ -35,14 +121,14 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
## 2. 技术栈:使用什么,分别解决什么问题 ## 2. 技术栈:使用什么,分别解决什么问题
下表列出 `package.json` 中声明的主要版本范围。它们不是安装后的精确版本,实际依赖解析以 `bun.lock` 为准。 下表列出 package.json 中声明的主要版本;精确安装版本以 package-lock.json 为准。项目统一使用 npm,当前验证结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
| 领域 | 技术与声明版本 | 在项目中的作用 | | 领域 | 技术与声明版本 | 在项目中的作用 |
| --- | --- | --- | | --- | --- | --- |
| 页面框架 | React、React DOM `^18.2.0` | 通过组件组织页面,使用 Hooks 管理交互和状态 | | 页面框架 | React、React DOM `^18.2.0` | 通过组件组织页面,使用 Hooks 管理交互和状态 |
| 开发语言 | JavaScript、JSX、ES Modules | 主体代码为 `.js` 和 `.jsx`,使用 `import/export` | | 开发语言 | JavaScript、JSX、ES Modules | 主体代码为 `.js` 和 `.jsx`,使用 `import/export` |
| 开发与构建 | Vite `^5.2.0`、React 插件 | 本地热更新、开发代理、生产打包和资源拆分 | | 开发与构建 | Vite `5.1.0`、React 插件 | 本地热更新、开发代理、生产打包和资源拆分 |
| 包管理 | Bun 锁文件 `bun.lock` | 固定依赖解析;部分脚本直接依赖 `bunx` | | 包管理 | npm / package-lock.json | npm ci 复现锁定依赖,脚本直接调用本地工具 |
| 路由 | React Router DOM `^6.3.0` | 使用 BrowserRouter 和嵌套路由组织页面 | | 路由 | React Router DOM `^6.3.0` | 使用 BrowserRouter 和嵌套路由组织页面 |
| 主 UI 组件库 | Semi UI `^2.69.1`、Semi Icons | 表格、表单、弹窗、布局、国际化组件文案等 | | 主 UI 组件库 | Semi UI `^2.69.1`、Semi Icons | 表格、表单、弹窗、布局、国际化组件文案等 |
| 样式 | Tailwind CSS `^3`、PostCSS、Autoprefixer、CSS 变量 | 工具类、兼容处理、主题和品牌色 | | 样式 | Tailwind CSS `^3`、PostCSS、Autoprefixer、CSS 变量 | 工具类、兼容处理、主题和品牌色 |
@@ -59,10 +145,10 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
### 2.1 容易产生误解的依赖 ### 2.1 容易产生误解的依赖
1. **TypeScript 是依赖,不是当前应用的主开发语言。** 仓库有 `typescript 4.4.2`,但应用主体没有采用 TS/TSX,使用的是 `jsconfig.json`;`build` 也没有独立类型检查步骤。 1. **当前应用主体是 JavaScript/JSX,不是 TypeScript。** 清单未直接声明 TypeScript,使用 jsconfig.json,build 没有独立类型检查。
2. **Semi UI 是当前代码中的主要组件库。** `antd ^6.3.0` 虽然列在依赖中,本次检索未发现 `src/` 中直接导入它的代码,不宜据此把项目描述成“双组件库全面混用”。新功能优先延续所属模块的现有组件。 2. **Semi UI 是当前代码中的主要组件库。** `antd ^5.23.0` 虽然列在依赖中,本次检索未发现 `src/` 中直接导入它的代码,不宜据此把项目描述成“双组件库全面混用”。新功能优先延续所属模块的现有组件。
3. **存在多种请求方式是业务需要。** 普通管理接口主要使用 Axios;对话生成额外使用 Fetch 和 SSE。修改 Axios 拦截器不会自动改变 Fetch/SSE 行为。 3. **存在多种请求方式是业务需要。** 普通管理接口主要使用 Axios;对话生成额外使用 Fetch 和 SSE。修改 Axios 拦截器不会自动改变 Fetch/SSE 行为。
4. **安装了语言检测依赖,不代表当前启动流程在使用它。** 当前语言选择主要由 `src/i18n/bootstrap.js` 等代码组织,不能只根据包名推断运行逻辑。 4. **语言选择由应用自身控制。** 当前清单未声明 i18next-browser-languagedetector,启动逻辑主要由 src/i18n/bootstrap.js 组织。
## 3. 架构设计:如何理解代码之间的关系 ## 3. 架构设计:如何理解代码之间的关系
@@ -72,7 +158,7 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
```mermaid ```mermaid
flowchart TD flowchart TD
A[浏览器] --> B[index.html / config.js] A[浏览器] --> B[index.html]
B --> C[index.jsx:语言初始化与全局 Provider] B --> C[index.jsx:语言初始化与全局 Provider]
C --> D[PageLayout:全局布局、站点状态、会话校验] C --> D[PageLayout:全局布局、站点状态、会话校验]
D --> E[App.jsx:顶层路由与访问控制] D --> E[App.jsx:顶层路由与访问控制]
@@ -84,7 +170,7 @@ flowchart TD
J --> G J --> G
``` ```
开发环境中,浏览器可以通过 Vite 代理访问后端;生产环境则由部署网关转发接口,或通过运行时配置连接独立后端域名。后端内部如何划分服务、使用何种数据库,不属于本仓库能够独立确认的内容。 开发环境中,浏览器可以通过 Vite 代理访问后端;生产环境则由部署网关转发接口,或通过构建变量 `VITE_REACT_APP_SERVER_URL` 连接独立后端域名;未设置或为空时使用同源地址。后端内部如何划分服务、使用何种数据库,不属于本仓库能够独立确认的内容。
### 3.2 启动链路 ### 3.2 启动链路
@@ -92,14 +178,14 @@ flowchart TD
| 顺序 | 文件 | 负责什么 | | 顺序 | 文件 | 负责什么 |
| --- | --- | --- | | --- | --- | --- |
| 1 | `index.html` | 提供 `root` 节点、启动占位画面;先加载 `/config.js`,再加载入口模块 | | 1 | `index.html` | 提供 `root` 节点、启动占位画面;直接加载入口模块,不再加载 `/config.js` |
| 2 | `src/index.jsx` | 注入缓存主题,安装资源加载失败恢复处理,初始化语言并挂载 React | | 2 | `src/index.jsx` | 注入缓存主题,安装资源加载失败恢复处理,初始化语言并挂载 React |
| 3 | `src/context/Status/`、`User/`、`Theme/` | 提供站点配置、登录状态及主题能力 | | 3 | `src/context/Status/`、`User/`、`Theme/` | 提供站点配置、登录状态及主题能力 |
| 4 | `src/components/layout/PageLayout.jsx` | 组织全局布局,加载 `/api/status`,按缓存状态决定是否校验 `/api/user/self` | | 4 | `src/components/layout/PageLayout.jsx` | 组织全局布局,加载 `/api/status`,按缓存状态决定是否校验 `/api/user/self` |
| 5 | `src/App.jsx` | 注册顶层路由,组合登录、角色、企业访问限制和懒加载 | | 5 | `src/App.jsx` | 注册顶层路由,组合登录、角色、企业访问限制和懒加载 |
| 6 | 对应业务页面 | 加载业务数据,组合组件并处理用户操作 | | 6 | 对应业务页面 | 加载业务数据,组合组件并处理用户操作 |
语言初始化在首次 React 渲染前进行:已有本地选择时优先使用缓存,部分场景请求 `/api/i18n/locale`,异常或超时则回退。这里的目的,是避免界面先显示一种语言,随后立即切换造成闪烁。 语言初始化在首次 React 渲染前进行:有有效本地语言候选时立即使用本地结果,并在后台请求 `/api/i18n/locale`;无有效本地候选时有限等待该接口,异常或超时则回退。这里的目的,是避免界面先显示一种语言,随后立即切换造成闪烁。
会话恢复也有一个重要细节:`UserContext` 初始没有用户数据。`PageLayout` 有缓存用户时调用 `/api/user/self`,有效则写入 Context;401/403 时清除登录状态;临时网络异常时保留缓存展示态,后续业务接口仍需由后端校验真实会话。**本地用户信息用于页面状态恢复,不能作为服务端授权依据。** 会话恢复也有一个重要细节:`UserContext` 初始没有用户数据。`PageLayout` 有缓存用户时调用 `/api/user/self`,有效则写入 Context;401/403 时清除登录状态;临时网络异常时保留缓存展示态,后续业务接口仍需由后端校验真实会话。**本地用户信息用于页面状态恢复,不能作为服务端授权依据。**
@@ -110,7 +196,7 @@ flowchart TD
```text ```text
monkey-ai-web/ monkey-ai-web/
├── docs/ 本项目分析等维护文档,不参与前端页面模块加载 ├── docs/ 本项目分析等维护文档,不参与前端页面模块加载
├── public/ 静态资源和运行时 config.js ├── public/ 原样复制到构建目录的静态资源
├── scripts/ 国际化提取、翻译整理等辅助脚本 ├── scripts/ 国际化提取、翻译整理等辅助脚本
├── tests/ 部分 Node 测试 ├── tests/ 部分 Node 测试
├── src/ ├── src/
@@ -119,8 +205,7 @@ monkey-ai-web/
│ ├── pages/ 业务页面;部分包含自己的组件和子路由 │ ├── pages/ 业务页面;部分包含自己的组件和子路由
│ ├── components/ 公共组件及跨页面业务组件 │ ├── components/ 公共组件及跨页面业务组件
│ ├── hooks/ 按业务分类的数据、状态与交互逻辑 │ ├── hooks/ 按业务分类的数据、状态与交互逻辑
│ ├── context/ User、Status、Theme、Org 等 Context 定义 │ ├── context/ User、Status、Theme、Org、Playground 等 Context 定义
│ ├── contexts/ PlaygroundContext,现有独立目录
│ ├── services/ 会话、安全验证等可复用服务调用 │ ├── services/ 会话、安全验证等可复用服务调用
│ ├── helpers/ API、权限、配置、主题和工具函数 │ ├── helpers/ API、权限、配置、主题和工具函数
│ ├── constants/ 接口地址、消息状态、菜单和业务常量 │ ├── constants/ 接口地址、消息状态、菜单和业务常量
@@ -129,7 +214,7 @@ monkey-ai-web/
│ ├── styles/ 设计 token、主题预设和共享样式 │ ├── styles/ 设计 token、主题预设和共享样式
│ └── docs/ 供产品文档页使用的静态内容 │ └── docs/ 供产品文档页使用的静态内容
├── package.json 依赖与开发命令 ├── package.json 依赖与开发命令
├── bun.lock 依赖锁文件 ├── package-lock.json 依赖锁文件
└── vite.config.js 代理、别名、插件和生产构建配置 └── vite.config.js 代理、别名、插件和生产构建配置
``` ```
@@ -285,9 +370,9 @@ GET 去重键考虑 URL、查询参数、组织、用户及显式授权信息,
`fr.json`、`ru.json` 虽然存在,但未登记在当前运行时目录中;不能据文件存在就判断产品已支持法语和俄语。新增语言需同时检查语言包、目录、组件语言映射以及后端支持范围。 `fr.json`、`ru.json` 虽然存在,但未登记在当前运行时目录中;不能据文件存在就判断产品已支持法语和俄语。新增语言需同时检查语言包、目录、组件语言映射以及后端支持范围。
```bash ```bash
bun run i18n:extract npm run i18n:extract
bun run i18n:status npm run i18n:status
bun run i18n:lint npm run i18n:lint
``` ```
提取、同步类命令可能修改语言文件,执行后检查 diff,避免把与本次功能无关的大批变动一起提交。 提取、同步类命令可能修改语言文件,执行后检查 diff,避免把与本次功能无关的大批变动一起提交。
@@ -300,7 +385,7 @@ bun run i18n:lint
- 语言包按需加载,普通 GET 请求具有进行中请求去重。 - 语言包按需加载,普通 GET 请求具有进行中请求去重。
- 全局有 Chunk 加载失败识别、有限重载和错误边界,处理部署更新后旧页面引用过期资源的情况。 - 全局有 Chunk 加载失败识别、有限重载和错误边界,处理部署更新后旧页面引用过期资源的情况。
顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。`PERFORMANCE_REPORT.md` 可以作为历史参考,其中的体积收益不能当作当前版本的实测结果。修改性能时应基于本次构建产物和浏览器数据判断。 顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。修改性能时应基于本次构建产物和浏览器数据判断,不把历史估算当作当前版本的实测结果。
## 7. 快速搭建本地开发环境 ## 7. 快速搭建本地开发环境
@@ -308,52 +393,44 @@ bun run i18n:lint
先获取可访问的后端地址、测试账号及权限、可用模型或渠道,以及需要联调的企业。仓库没有完整离线 Mock 和默认测试账号,前端依赖安装成功后仍需要这些条件才能验证真实业务。 先获取可访问的后端地址、测试账号及权限、可用模型或渠道,以及需要联调的企业。仓库没有完整离线 Mock 和默认测试账号,前端依赖安装成功后仍需要这些条件才能验证真实业务。
仓库没有通过 `engines` 或版本文件强制固定运行时。建议团队统一 Node.js 22 LTS 或 24 LTS,以及兼容当前锁文件的 Bun 版本;现有 README 建议 Bun 1.3.x。本文测试环境为 Node.js `v22.23.3`,未完成 Bun 安装验证。 项目通过 engines 要求 Node.js >=22.13.0、npm >=10;packageManager 记录 npm@10.9.9。本次在 Node.js 22.23.3 / npm 10.9.9 完成 npm ci、测试与生产构建。
### 7.2 最短启动流程 ### 7.2 按当前环境选择启动流程
所有命令在仓库根目录执行,本机路径为 `D:\code\monkey-ai-web`,不需要再进入 `web/`。 所有命令在仓库根目录执行,本机路径为 `D:\code\monkey-ai-web`,不需要再进入 `web/`。
```powershell ```powershell
node --version node --version
bun --version npm --version
bun install --frozen-lockfile npm ci
bun run dev npm run dev
``` ```
默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。`--frozen-lockfile` 用于要求安装遵循锁文件,避免无意改写依赖解析。 `npm ci` 按锁文件执行干净安装,会清理 node_modules;Windows 下先停止当前项目的开发服务,避免 esbuild 或 Rollup 文件被占用。
如果需要配置前端开关,再创建本地环境文件: 更新依赖使用 npm install 并提交清单与锁文件;首次安装与 CI 使用 npm ci,不混用包管理器。
```powershell 默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。npm ci 不用于更新锁文件;清单与锁不一致时先定位差异。
Copy-Item .env.example .env.local
```
`.env.local` 已被 Git 忽略。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `bun.lock`。 开发命令自动加载 `.env.development`,生产构建自动加载 `.env.production`。个人覆盖配置使用 `.env.development.local` / `.env.production.local`,这些文件已被 Git 忽略。环境变量优先级和迁移说明见 [README](../README.md#3-后端联调与环境配置)。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `package-lock.json`。
### 7.3 推荐联调方式:浏览器同源请求 ### 7.3 推荐联调方式:浏览器同源请求
保持 `public/config.js` 中的 `SERVER_URL` 为空,且不设置 `VITE_REACT_APP_SERVER_URL`: 不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用同源地址。
```js 此时前端向当前域名发请求,由 Vite 将以下路径转发到 `.env.development` 中 `DEV_PROXY_TARGET` 指定的后端(当前为远程地址 `http://134.175.227.134:13000`,不是本机 3000 端口):
window.__APP_CONFIG__ = {
SERVER_URL: '',
};
```
此时前端向当前域名发请求,由 Vite 将以下路径转发到默认后端 `http://localhost:3000`:
```text ```text
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno /api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
``` ```
远程联调时,修改 `vite.config.js` 中所需代理项的 `target` 并重启开发服务。当前没有专门读取代理目标的环境变量,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。 切换联调环境时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启开发服务;各代理前缀共享这一目标。使用前确认该环境已获授权且适合测试,不在未知或生产环境执行破坏性操作。代理变量仅供 Vite 服务使用,不注入浏览器,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。
同源代理通常可以减少本地跨域联调问题,但代理本身不能替代后端账号、会话和业务配置。 同源代理通常可以减少本地跨域联调问题,但代理本身不能替代后端账号、会话和业务配置。
### 7.4 可选联调方式:直接连接独立后端 ### 7.4 可选联调方式:直接连接独立后端
可以在 `public/config.js` 中将 `SERVER_URL` 设为后端根地址,或者在 `.env.local` 中配置: 在 `.env.development` / `.env.production` 或对应的 `.local` 文件中配置后端根地址(构建变量):
```dotenv ```dotenv
VITE_REACT_APP_SERVER_URL=https://api.example.com VITE_REACT_APP_SERVER_URL=https://api.example.com
@@ -362,15 +439,14 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
接口根地址优先级如下: 接口根地址优先级如下:
1. 非空的 `window.__APP_CONFIG__.SERVER_URL`。 1. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`(构建变量)。
2. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`。 2. 空字符串,使用当前页面域名(同源)。
3. 空字符串,使用当前页面域名。
地址填写后端根地址,不额外加 `/api`;具体请求自己包含路径。运行时地址为空时会继续回退至构建变量,不会强制覆盖为同源模式。 地址填写后端根地址,不额外加 `/api`;具体请求自己包含路径。要使用同源模式,需确保构建变量未设置或为空。
直连独立域名时,请求不经过本地 Vite 代理,后端需要支持正确的 CORS、Cookie 和凭证策略。公共 Axios、对话 Fetch 与 SSE 都有各自的凭证配置,修改请求方式时需要分别核对。 直连独立域名时,请求不经过本地 Vite 代理,后端需要支持正确的 CORS、Cookie 和凭证策略。公共 Axios、对话 Fetch 与 SSE 都有各自的凭证配置,修改请求方式时需要分别核对。
`public/config.js` 会复制为 `dist/config.js`,部署后可修改并刷新页面;Vite 环境变量在构建时处理,开发时修改应重启服务,生产时修改应重新构建。前端配置对浏览器可见,只能存公开配置。 已移除 `public/config.js` 及其入口脚本,不再支持部署后直接修改 `dist/config.js` 切换后端。旧部署如依赖它,需迁移到构建前设置 `VITE_REACT_APP_SERVER_URL`,或清空该变量后重新构建并配置同源反向代理。Vite 环境变量在构建时处理,开发时修改应重启服务,生产时修改应重新构建并发布;仅修改部署服务器环境变量或刷新页面不会改变已有产物。前端配置对浏览器可见,只能存公开配置。
### 7.5 按这个顺序确认环境可用 ### 7.5 按这个顺序确认环境可用
@@ -422,15 +498,15 @@ Vite 对 `src/` 中的 `.js` 配置了 JSX 转换,因此历史 `.js` 文件可
| 命令 | 实际作用 | 注意点 | | 命令 | 实际作用 | 注意点 |
| --- | --- | --- | | --- | --- | --- |
| `bun run dev` | 启动 Vite 开发服务 | 默认前端 5173,代理目标默认 3000 | | `npm run dev` | 启动 Vite 开发服务 | 默认前端 5173,代理目标见 `DEV_PROXY_TARGET` |
| `bun run build` | 执行 `vite build` | 生成 `dist/`,不自动运行 ESLint、测试或独立类型检查 | | `npm run build` | 执行 `vite build` | 生成 `dist/`,不自动运行 ESLint、测试或独立类型检查 |
| `bun run preview` | 预览生产构建 | 默认 4173,用于本地预览 | | `npm run preview` | 预览生产构建 | 默认 4173,用于本地预览 |
| `bun run test` | 执行 `node --test` | 测试分布于 `tests/` 和源码相邻位置 | | `npm run test` | 执行 `node --test` | 测试分布于 `tests/` 和源码相邻位置 |
| `bun run eslint` | 检查 JS/JSX | 脚本使用 `bunx eslint` | | `npm run eslint` | 检查 JS/JSX | 脚本使用本地 eslint |
| `bun run eslint:fix` | 自动修复部分静态检查问题 | 执行后检查 diff | | `npm run eslint:fix` | 自动修复部分静态检查问题 | 执行后检查 diff |
| `bun run lint` | 执行 Prettier 格式检查 | 这个命令不是 ESLint;当前配置有已知问题 | | `npm run lint` | 执行 Prettier 格式检查 | 这个命令不是 ESLint;当前配置有已知问题 |
| `bun run lint:fix` | 执行全项目格式化 | 会批量修改文件,避免无关变动 | | `npm run lint:fix` | 执行全项目格式化 | 会批量修改文件,避免无关变动 |
| `bun run i18n:sync` | 同步语言资源结构 | 可能修改多个语言包 | | `npm run i18n:sync` | 同步语言资源结构 | 可能修改多个语言包 |
现有测试使用 `node:test` 和 `node:assert`,覆盖请求去重、登录回跳、语言初始化、功能开关、会话流程、价格计算和部分 CSS 规则等。当前依赖与配置未体现完整的浏览器端到端测试方案;通过 Node 测试不能代替真实页面联调。 现有测试使用 `node:test` 和 `node:assert`,覆盖请求去重、登录回跳、语言初始化、功能开关、会话流程、价格计算和部分 CSS 规则等。当前依赖与配置未体现完整的浏览器端到端测试方案;通过 Node 测试不能代替真实页面联调。
@@ -446,9 +522,9 @@ node --test src/hooks/playground/sessionFlow.test.js
## 10. 构建与部署需要理解什么 ## 10. 构建与部署需要理解什么
```bash ```bash
bun install --frozen-lockfile npm ci
bun run build npm run build
bun run preview npm run preview
``` ```
生产交付物为 `dist/`。部署时需保证以下行为: 生产交付物为 `dist/`。部署时需保证以下行为:
@@ -460,26 +536,27 @@ bun run preview
| 正确区分页面与接口 | `/api` 等接口不能误回退到 HTML;带哈希的资源请求也应返回正确资源类型 | | 正确区分页面与接口 | `/api` 等接口不能误回退到 HTML;带哈希的资源请求也应返回正确资源类型 |
| 流式响应 | SSE 接口需要合理的超时与关闭响应缓冲,避免生成完毕才一次性显示 | | 流式响应 | SSE 接口需要合理的超时与关闭响应缓冲,避免生成完毕才一次性显示 |
| WebSocket | 使用时需配置连接升级转发;当前开发代理在 `/v1` 开启 `ws` | | WebSocket | 使用时需配置连接升级转发;当前开发代理在 `/v1` 开启 `ws` |
| 缓存策略 | `index.html`、`config.js` 应及时更新,带哈希资源可以长缓存 | | 缓存策略 | `index.html` 应及时更新,带哈希资源可以长缓存;后端地址变化需重建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存 |
| 部署根路径 | 当前资源和路由按域名根路径使用,子目录部署需检查 Vite `base`、路由及资源路径 | | 部署根路径 | 当前资源和路由按域名根路径使用,子目录部署需检查 Vite `base`、路由及资源路径 |
`vercel.json` 当前仅配置 GitHub 通知静默,没有提供完整的路由回退和后端代理。不能把它当成已经验收过的部署方案。 `vercel.json` 当前仅配置 GitHub 通知静默,没有提供完整的路由回退和后端代理。不能把它当成已经验收过的部署方案。
## 11. 当前已确认的工程注意点 ## 11. 当前已确认的工程注意点
以下事项来自本次代码检查或实际命令结果,便于接手时安排处理优先级。本文只新增分析文档与阅读入口,没有修改这些配置。 以下事项来自代码检查或实际命令结果,便于接手时安排处理优先级。后续优化结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
| 事项 | 当前证据 | 对开发的影响与建议 | | 事项 | 当前证据 | 对开发的影响与建议 |
| --- | --- | --- | | --- | --- | --- |
| Prettier 配置无法按 ESM 正常加载 | `.prettierrc.mjs` 使用 `module.exports = require(...)`;Node 导入已复现 `require is not defined in ES module scope` | 运行格式检查前需统一为正确的 ESM 或 CJS 配置,避免格式检查成为阻塞项 | | Prettier 配置已统一 | `.prettierrc.mjs` 使用 ESM 导出,移除 package.json 的重复配置;忽略构建产物和缓存 | 全仓仍有历史格式差异,按改动范围渐进处理,不做无关全仓格式化 |
| 构建目录未被当前规则排除 | `.gitignore` 忽略 `/build`,Vite 默认输出 `/dist` | 团队宜补充忽略规则;当前构建后先检查 Git 状态,避免提交产物 | | 构建目录已被忽略 | `.gitignore` 包含 `/dist/`、`/dist-ssr/` 和 `/build` | 原文“dist 未忽略”已过时;提交前仍检查 Git 状态 |
| 压缩选项位置需要复核 | `drop: ['console', 'debugger']` 写在 `build.esbuild` 中 | Vite 5 的 `esbuild` 通常是顶层配置;不能仅凭此处注释确认日志已被移除,应调整并检查产物。本次未构建验证 | | 压缩选项位置需要复核 | `drop: ['console', 'debugger']` 写在 `build.esbuild` 中 | Vite 5 的 `esbuild` 通常是顶层配置;不能仅凭此处注释确认日志已被移除,应调整并检查产物。本次未构建验证 |
| 开发代理目标硬编码 | `vite.config.js` 多个前缀固定为 `http://localhost:3000` | 切换联调环境需检查所需前缀;可后续集中配置,降低遗漏概率 | | 开发代理已集中配置 | `vite.config.js` 的 `DEV_PROXY_TARGET` 统一供多个前缀使用,当前指向远程后端 | 仍是源码常量,不是代理环境变量;切换后重启开发服务 |
| 运行时版本未锁定 | 无 `engines` 等统一约束 | 团队应记录实际验证过的 Node 与 Bun 版本,减少环境差异 | | 依赖管理已统一 | 删除旧 Bun 锁并保留匹配清单的 npm 锁 | npm ci 已验证,依赖更新须同步提交锁文件 |
| 运行时约束 | engines 与 packageManager 已声明 Node/npm 要求 | CI 应使用已验证版本 |
| 部分说明落后于源码 | 体验中心子目录 README 仍使用 `web/src` 并描述图片、视频为占位功能 | 阅读时以当前入口、Hook 和接口调用为准 | | 部分说明落后于源码 | 体验中心子目录 README 仍使用 `web/src` 并描述图片、视频为占位功能 | 阅读时以当前入口、Hook 和接口调用为准 |
| 分层与命名存在历史差异 | `context/` 与 `contexts/` 并存,部分页面直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 | | 分层与命名存在历史差异 | Context 已统一至 `context/`,部分页面仍直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 |
统计脚本也是一个配置细节:Vite 插件使用 `process.env.VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`,没有显式调用 `loadEnv`。使用 Node/npm 运行时,不要假定仅写入 `.env.local` 就一定能被配置文件读取;应由启动环境或 CI 注入并检查构建 HTML。 统计脚本由 Vite 的 `loadEnv` 按当前 mode 读取 `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`;支持开发/生产环境文件与本地覆盖文件,终端或 CI 的同名变量优先,ID 留空时禁用注入。
### 11.1 本次验证记录与结论边界 ### 11.1 本次验证记录与结论边界
@@ -487,13 +564,11 @@ bun run preview
| --- | --- | | --- | --- |
| 源码与配置分析 | 已检查依赖、入口、路由、请求、状态、企业权限、对话、国际化、主题及检查规则 | | 源码与配置分析 | 已检查依赖、入口、路由、请求、状态、企业权限、对话、国际化、主题及检查规则 |
| Node 环境 | `v22.23.3` | | Node 环境 | `v22.23.3` |
| 现有测试 `node --test` | 122 项通过,2 个测试文件加载失败,进程退出码为 1 | | 现有测试 `node --test` | 优化与验收修复后 179 项通过,0 项失败;包含偏好解析、筛选参数、用户列表控制器和 Semi 分页回调回归测试 |
| 两个失败文件 | `tests/modal-overflow.test.js`、`tests/org-prompt-records.test.js` | | Prettier 配置导入 | ESM 配置已修复;格式检查可执行,但全仓历史格式差异仍未统一 |
| 失败原因 | 当前没有 `node_modules`,上述文件导入的 `postcss` 未安装,报 `ERR_MODULE_NOT_FOUND` | | 浏览器验收 | Chrome 隔离环境下的分页、搜索、通知、跨标签页同步、移动端和错误恢复通过;接口使用测试 fixture,不代表真实后端验收 |
| Prettier 配置导入 | 已复现 ESM 加载错误 |
| 安装、构建、完整 ESLint、浏览器联调 | 未执行;当前没有 Bun 和项目依赖,也未连接配套后端 |
本次结果说明可独立执行的既有测试已通过,但**不能据此宣称完整测试通过或项目已经验收可发布**。两个失败文件属于依赖缺失导致的加载失败,安装依赖后仍需重跑确认其断言结果。 Node 测试和生产构建通过不等于后端业务或线上发布验收通过;具体结果与验证边界见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
## 12. 常见问题排查表 ## 12. 常见问题排查表
@@ -505,18 +580,18 @@ bun run preview
| 账号有权限,菜单却不显示 | 依次检查站点模块配置、企业功能、细分权限及构建开关 | | 账号有权限,菜单却不显示 | 依次检查站点模块配置、企业功能、细分权限及构建开关 |
| 菜单显示,点击后却跳回企业空间 | 检查 `org_only_mode`、`App.jsx` 的允许路径和企业页面守卫 | | 菜单显示,点击后却跳回企业空间 | 检查 `org_only_mode`、`App.jsx` 的允许路径和企业页面守卫 |
| 企业列表为空或数据范围不符 | 检查 `current_org_id`、显式 `orgId`、`X-Org-Id`、成员权限及业务响应 | | 企业列表为空或数据范围不符 | 检查 `current_org_id`、显式 `orgId`、`X-Org-Id`、成员权限及业务响应 |
| 修改环境变量未生效 | 检查运行时地址优先级、是否重启或重建、`config.js` 和浏览器缓存 | | 修改环境变量未生效 | 检查构建时的变量值、是否重启或重建并发布、HTML 与静态资源缓存 |
| 流式回复在结束时一次性出现 | 检查 SSE 事件、网关缓冲、超时和后端输出方式 | | 流式回复在结束时一次性出现 | 检查 SSE 事件、网关缓冲、超时和后端输出方式 |
| 线上刷新子页面 404 | 检查静态服务器的 SPA 路由回退 | | 线上刷新子页面 404 | 检查静态服务器的 SPA 路由回退 |
| 模块资源加载失败 | 检查旧 HTML 与新资源是否版本不一致,确认发布和缓存策略 | | 模块资源加载失败 | 检查旧 HTML 与新资源是否版本不一致,确认发布和缓存策略 |
| `lint` 报 `require` 未定义 | 检查 `.prettierrc.mjs` 的 ESM/CJS 配置冲突 | | `lint` 报 Code style issues | 历史格式差异仍存在,只格式化本次改动文件;当前 ESM 配置已修复 |
| 测试报找不到 `postcss` | 先按锁文件安装依赖,再重跑对应测试 | | 测试报找不到 `postcss` | 先按锁文件安装依赖,再重跑对应测试 |
## 13. 建议的新成员学习路径 ## 13. 建议的新成员学习路径
| 阶段 | 重点工作 | 应达到的结果 | | 阶段 | 重点工作 | 应达到的结果 |
| --- | --- | --- | | --- | --- | --- |
| 第 1 阶段:跑通环境 | 阅读本文第 1、2、7 节,完成状态、登录和一个业务接口联调 | 能分清前端启动成功与完整业务可用 | | 第 1 阶段:跑通环境 | 阅读本文第 0、1、7 节,完成状态、登录和一个业务接口联调 | 能分清前端启动成功与完整业务可用 |
| 第 2 阶段:理解骨架 | 阅读 `index.jsx`、`PageLayout.jsx`、`App.jsx`、`api.js`、`auth.jsx` | 能解释页面从加载到请求、权限判断的过程 | | 第 2 阶段:理解骨架 | 阅读 `index.jsx`、`PageLayout.jsx`、`App.jsx`、`api.js`、`auth.jsx` | 能解释页面从加载到请求、权限判断的过程 |
| 第 3 阶段:掌握一个模块 | 从渠道或企业成员列表入手,沿页面、组件、Hook 追踪数据 | 能独立完成一个范围明确的列表或表单需求 | | 第 3 阶段:掌握一个模块 | 从渠道或企业成员列表入手,沿页面、组件、Hook 追踪数据 | 能独立完成一个范围明确的列表或表单需求 |
| 第 4 阶段:处理复杂业务 | 学习 Playground 会话、SSE、任务状态和企业细分权限 | 能评估跨模块修改影响并设计回归场景 | | 第 4 阶段:处理复杂业务 | 学习 Playground 会话、SSE、任务状态和企业细分权限 | 能评估跨模块修改影响并设计回归场景 |
@@ -533,7 +608,7 @@ bun run preview
| 构建、代理与路径别名 | [vite.config.js](../vite.config.js)、[jsconfig.json](../jsconfig.json) | | 构建、代理与路径别名 | [vite.config.js](../vite.config.js)、[jsconfig.json](../jsconfig.json) |
| React 启动与布局 | [index.jsx](../src/index.jsx)、[PageLayout.jsx](../src/components/layout/PageLayout.jsx) | | React 启动与布局 | [index.jsx](../src/index.jsx)、[PageLayout.jsx](../src/components/layout/PageLayout.jsx) |
| 顶层路由与权限 | [App.jsx](../src/App.jsx)、[auth.jsx](../src/helpers/auth.jsx) | | 顶层路由与权限 | [App.jsx](../src/App.jsx)、[auth.jsx](../src/helpers/auth.jsx) |
| 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[运行时配置](../public/config.js) | | 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[开发环境](../.env.development)、[生产环境](../.env.production) |
| 请求去重 | [requestDedupe.js](../src/helpers/requestDedupe.js)、[相关测试](../src/helpers/requestDedupe.test.js) | | 请求去重 | [requestDedupe.js](../src/helpers/requestDedupe.js)、[相关测试](../src/helpers/requestDedupe.test.js) |
| 登录状态 | [User Provider](../src/context/User/index.jsx)、[User Reducer](../src/context/User/reducer.js) | | 登录状态 | [User Provider](../src/context/User/index.jsx)、[User Reducer](../src/context/User/reducer.js) |
| 企业入口与成员逻辑 | [Organization](../src/pages/Organization/index.jsx)、[useOrgMembers](../src/hooks/org/useOrgMembers.js) | | 企业入口与成员逻辑 | [Organization](../src/pages/Organization/index.jsx)、[useOrgMembers](../src/hooks/org/useOrgMembers.js) |
+299
View File
@@ -0,0 +1,299 @@
# 页面渲染、路由与 API 调用链分析
> 适用读者:熟悉 Vue 3 / Vue Router、正在接手本 React 项目的开发者。
> 源码分析基准:`weiyuan` 分支、提交 `821577f`;文档整理日期:2026-10-27。源码行号和声明统计均以该基准为准。
> 本文解释现有实现,不包含改造实施计划。目标结构、迁移步骤与验收要求统一见[前端模块化改造技术方案](./MODULAR_REFACTOR_TECHNICAL_PLAN.zh-CN.md)。
## 1. 先建立整体认识
本项目是基于 React 与 Vite 的客户端单页应用,已使用 React Router,并非自行实现路由。`react-router-dom` 的声明范围为 `^6.3.0`,分析基准的锁定版本为 **6.30.6**,二者不能混为一谈。
入口使用 `BrowserRouter`,顶层 `App` 使用 `Routes`、`Route` 和 `Navigate`;用户中心与企业空间内部还有各自的子路由。页面和业务状态已经分布在 pages、components、hooks 等目录,并非全部写在 App 中。
`App.jsx` 在分析基准中共 880 行,包含 64 个 Route、50 个 lazy 和 64 个 Suspense 声明。它主要集中管理页面懒加载、URL 映射、访问策略、功能开关和旧地址跳转。这些数字是源码声明数量,不是同时渲染的页面数量。
对 Vue 开发者而言,可先把 App 理解为“路由注册与访问策略入口”,把 PageLayout 理解为“全局布局与部分启动逻辑”。React Router 提供路由能力,但不会自动按业务拆分文件。
建议先阅读第 2 章建立启动流程,再沿第 3 章的用户列表实例跟踪一次请求;第 4、5 章用于查阅网络和权限边界。
## 2. 从浏览器打开页面到 React 渲染
### 2.1 实际入口顺序
```text
浏览器访问 /console/user
-> 开发服务器 / 生产静态服务返回 index.html
-> index.html 直接加载入口模块并执行 src/index.jsx
-> 注入缓存主题、安装 chunk 加载失败恢复处理
-> bootstrapLanguage 决定首屏语言
-> ReactDOM.createRoot(...).render(...)
-> 全局 Provider + BrowserRouter
-> PageLayout:外壳、会话恢复、站点状态、主题等
-> App:访问策略与路由匹配
-> AdminRoute:检查登录和角色
-> Suspense + lazy:加载用户页模块
-> User -> UsersTable -> useUsersData
-> 接口结果写入 state -> React 更新表格
```
这是 **Vite 构建的客户端单页应用(SPA)**。`/console/user` 是前端页面地址,`/api/user/` 是后端接口地址;二者不是同一个路由系统。
使用 `BrowserRouter` 意味着生产服务器需要对有效的前端深链接返回 `index.html`。否则“从首页点击能进,刷新 `/console/user` 却 404”。部署时应先处理真实静态资源和 API 转发,再做 SPA 回退,不能把接口请求错误地回退成 HTML。Vite 开发代理不会随构建产物自动部署到生产。
### 2.2 Provider 的实际嵌套
`src/index.jsx:83` 中的结构是:
```text
StrictMode
StatusProvider
UserProvider
BrowserRouter
ThemeProvider
SemiLocaleWrapper
ChunkErrorBoundary
PageLayout
App
```
| 层次 | 当前职责 | Vue 开发者可以怎样理解 |
| -------------------- | ------------------------------------ | ----------------------------------------- |
| `StatusProvider` | 共享站点状态、后台下发的模块配置等 | 站点配置 store / provide |
| `UserProvider` | 用户信息、认证检查状态 | 登录态 store,但 Context 不等于完整 Pinia |
| `BrowserRouter` | 浏览器 history、当前位置、导航上下文 | Vue Router 的浏览器 history 模式 |
| `ThemeProvider` | 主题能力 | 全局主题状态与操作 |
| `SemiLocaleWrapper` | 根据语言选择 Semi 组件文案 | UI 库的 locale provider |
| `ChunkErrorBoundary` | 处理资源加载等相关错误边界 | 注意与“加载中”的 Suspense 区分 |
| `PageLayout` | 全局外壳及启动副作用 | 布局组件 + 一部分应用初始化 |
| `App` | 选择应渲染的页面 | 顶层路由出口与访问策略编排 |
注意:本项目是 `PageLayout` 包着 `App`,并非“App 里面放所有布局”。名字不决定组件层次。
### 2.3 初次渲染并非等所有接口返回后再显示
启动阶段有几类不同的等待:
- **语言初始化**发生在 React 首次渲染之前。有有效本地语言候选时可先使用本地结果;无有效本地候选时有限等待语言接口并支持回退。
- **站点状态与用户校验**由 `PageLayout` 的 effect 发起,不是整个页面的一条串行阻塞流水线。
- 有缓存用户时,`loadUser()` 调用 `/api/user/self`;没有缓存时直接标记认证检查完成,不无条件请求该接口。
- `/api/user/self` 返回业务失败或 401/403 时清理用户状态;临时网络异常则保留缓存展示态。缓存不是服务端授权凭证。
- 守卫的判断顺序不同:`PrivateRoute` 在 Context 已有用户时直接渲染,否则才检查缓存与认证等待;`AdminRoute`、`RootRoute` 优先检查“有缓存且认证未完成”,再判断用户和数字角色。`AuthRedirect` 与 PrivateRoute 一样先判断当前用户。
- `SetupCheck` 在 effect 中发现 `status.setup === false` 时跳到 `/setup`,但自身直接返回 children。它**不是等待站点状态加载完成的阻塞守卫**。
- `/api/status` 失败后当前实现回退到 `{ setup: true }`,而非一直卡在初始化中。
这些等待发生在不同层次,并不存在统一的全站 ready 状态。阅读启动逻辑时,应分别跟踪语言、站点状态和会话恢复。
### 2.4 点击导航时发生什么?
典型的 `Link` 或 `navigate()` 会更新浏览器 history,React Router 根据新位置重新匹配,渲染对应路由元素。通常不需要重新下载整份 HTML,也不会重建所有全局 Provider。
但有两个区别:
1. OAuth、401 失效处理、`SetupCheck` 等代码存在 `window.location.href`,这是整页导航,不是普通 SPA 内部切换。
2. `App.jsx` 多处给 Suspense 设置 `key={location.pathname}`。路径变化会使这些边界及其子树重新挂载,影响局部 state、effect 和请求。没有设置 key 的分支又可能保留更多状态。
阅读页面状态与请求行为时,应同时检查路由的 key;同一页面组件不一定意味着相同的挂载生命周期。
## 3. 以你选中的 `/console/user` 为例读完整条链
### 3.1 文件与职责
| 顺序 | 文件位置 | 负责什么 |
| ---- | ----------------------------------------- | ------------------------------------------------- |
| 1 | `src/App.jsx:465` | 注册 `/console/user`,组合 AdminRoute 和 Suspense |
| 2 | `src/helpers/auth.jsx:98` | AdminRoute:认证等待、登录回跳、数字角色 `>= 10` |
| 3 | `src/pages/User/index.jsx:23` | 薄页面,只组织外层容器和 UsersTable |
| 4 | `src/components/table/users/index.jsx:33` | 调用 useUsersData,接线筛选、表格、分页、弹窗 |
| 5 | `src/hooks/users/useUsersData.jsx:26` | 用户列表状态、加载、搜索、分页和操作 |
| 6 | `src/helpers/api.js:32` | Axios 实例、请求头、GET 在途去重、公共错误处理 |
| 7 | `src/hooks/users/useUsersData.jsx:79` | 判断 success,读取 items/page/total,更新 state |
`User` 在 `App.jsx:72` 通过 `React.lazy(() => import('./pages/User'))` 声明。lazy 在模块顶层定义,真正渲染时才触发相关模块加载;不是每次 App 渲染都下载全部页面。
Suspense 处理懒加载等待;**它不会自动让 Hook 中普通 Axios 请求的 loading 交给 React Router 管理**。接口加载状态仍然由 `useUsersData` 管理。
### 3.2 首次加载与搜索
`useUsersData` 挂载时调用:
```text
loadUsers(0, pageSize)
-> GET /api/user/?p=0&page_size=...
-> Axios response.data = { success, message, data }
-> data.items / data.page / data.total
-> setUsers / setActivePage / setUserCount
-> 表格重新渲染
```
同时还请求 `/api/group/`,用于筛选项。注意这里**首次请求沿用 `p=0` 的现有约定**,不要在提取 service 时顺手改成统一从 1 开始。
搜索走 `GET /api/user/search`,使用 Axios `params` 传 `keyword/group/p/page_size`。两个筛选项都为空时退回普通列表接口。翻页与修改条数复用 `refresh()`;修改条数重置第 1 页并保留筛选条件。
相关分页行为已有专项回归测试,可结合测试理解初始页码与分页交互的区别。
### 3.3 这说明现有项目已经具备什么?
当前已经有:
```text
路由 -> 页面 -> 业务 UI 组件 -> 业务 Hook -> 公共 HTTP 客户端
```
领域接口封装尚不统一:业务 Hook 和部分页面直接调用 API;已有 `services/playgroundConversation.js` 等封装,但并非所有 service 都返回相同结构。跟踪请求时,应以实际调用方和返回值为准,不能假定 service 已统一解包响应。
## 4. API 调用工具链到底提供了什么
### 4.1 地址选择与开发代理
删除前,`public/config.js` 会在 React 入口之前执行,向 `window.__APP_CONFIG__.SERVER_URL` 写入运行时值;[src/helpers/config.js](../src/helpers/config.js) 再从“运行时值 → Vite 构建变量 → 同源”逐级回退。仓库默认值一直是空字符串,但部署方可以在构建完成后直接修改 `dist/config.js`。
提交 `821577f` 删除了这条运行时分支:
- 删除 `public/config.js`。
- 删除 `index.html` 中的 `<script src="/config.js"></script>`。
- `getServerURL()` 不再访问 `window.__APP_CONFIG__`,只读取构建变量并回退到同源。
- 环境配置提供后端地址(现使用 `.env.development` / `.env.production`,原 `.env.example` 已移除),`src/helpers/config.test.js` 覆盖缺省、空值、绝对地址以及 HTML 不再加载旧脚本。
现在的地址选择只有两级:
```text
非空 import.meta.env.VITE_REACT_APP_SERVER_URL(构建变量)
> ''(同源)
```
等价源码为:
```js
export function getServerURL() {
return import.meta.env.VITE_REACT_APP_SERVER_URL || '';
}
```
| 配置 | 修改后何时生效 | 注意事项 |
| -------------------------------------- | ------------------------------- | ---------------------------------------- |
| `VITE_REACT_APP_SERVER_URL` | 开发服务重启 / 生产重新构建发布 | 会进入浏览器产物,不是服务端私密变量 |
| `vite.config.js` 的 `DEV_PROXY_TARGET` | 开发服务重启 | 只服务本地 Vite 代理,不会打包成生产代理 |
现在支持两种部署方式:
1. **同源模式(推荐)**:不设置 `VITE_REACT_APP_SERVER_URL` 或设为空,浏览器请求 `/api/...`、`/pg/...` 等相对地址。本地由 Vite 代理,生产由 Nginx、网关等反向代理。
2. **跨域直连模式**:构建前设置 `VITE_REACT_APP_SERVER_URL=https://api.example.com`,业务路径拼到该根地址后。生产修改地址必须重新构建和发布,并确认 CORS、Cookie 与 credentials 策略。
旧部署如果曾在发布后修改 `dist/config.js`,升级后必须迁移到上述方式之一。仅在部署服务器上修改环境变量、创建一个新的 `config.js` 或刷新浏览器都不会改变已经构建的 JS;Vite 会在构建阶段替换 `import.meta.env.VITE_*`。
这里还有一个容易混淆的点:`src/helpers/api.js` 中的 `updateAPI()` 仍可重新创建 Axios 实例,但它只会重新读取**已经编译进当前前端产物**的构建变量,不能像旧 `config.js` 一样在不重新构建的情况下切换后端。它不是运行时环境切换机制。此外,`loginFlow.js` 在登录后调用它重建实例,使新会话使用新的在途请求集合;这不会取消旧实例已经发出的请求。
发布时让 `index.html` 及时更新,带哈希的静态资源可长缓存;后端地址变化需重新构建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存。
默认同源时,开发链路是“浏览器请求 Vite → Vite 代理 → 后端”。代理前缀包含 `/api`、`/v1`、`/v1beta`、`/mj`、`/pg`、`/dashboard`、`/kling`、`/jimeng`、`/suno`;`/v1` 启用 WebSocket 代理。
`package.json` 中虽有 `proxy` 字段,但本项目实际使用的是 `vite.config.js` 的代理配置。
### 4.2 普通请求:Axios 公共实例
核心实现位于 `src/helpers/api.js`:
| 能力 | 当前实现 | 边界 |
| -------------- | -------------------------------------- | ------------------------------------------ |
| 基础地址 | `baseURL: getServerURL()` | 实例创建时读取;`updateAPI()` 可重建 |
| 跨域凭证 | 地址非空时 `withCredentials: true` | 不等于所有部署环境的 Cookie 都自动可用 |
| 用户标识 | 请求拦截器添加 `New-API-User` | 不是 token,更不能替代后端会话鉴权 |
| 企业标识 | `/api/org/` 前缀请求注入 `X-Org-Id` | 显式头优先,否则读 `current_org_id` |
| 默认缓存请求头 | `Cache-Control: no-store` | 不等于前端实现了查询缓存 |
| GET 合并 | 相同 key 的进行中请求共享 Promise | 仅封装的 `API.get`,完成即删除 |
| 错误处理 | 拒绝响应默认调用 `showError` 再 reject | 不统一解包,也不处理所有业务 success=false |
正常响应仍是 Axios response,需要调用方读取 `res.data`。不能直接改拦截器为 `return response.data`,否则现有大量 `res.data.success` 调用会断裂。
### 4.3 两种“失败”一定要分清
**HTTP / 网络失败**:请求被拒绝、非成功 HTTP 状态等,进入 Axios 错误拦截器。`showError()` 对 Axios 401 会清理缓存、保存安全回跳地址,并整页跳转企业登录。
**业务失败**:HTTP 200,但响应为 `{ success: false, message: '...' }`。此时 Axios Promise 通常仍成功,Hook / service 需要检查 success 并决定展示方式。
`skipErrorHandler: true` 会跳过这一层全局错误处理,调用方需要承接相应责任。它不应被简单理解成“只关闭 toast”,因为当前全局错误函数还包含 401 跳转。
现有拦截器和部分 catch 都会提示错误,存在重复提示的结构性风险。排查时需要同时查看全局拦截器和调用方 catch,确认提示实际来自哪一层。
### 4.4 GET 去重不等于数据缓存,也不等于竞态治理
`src/helpers/requestDedupe.js:35` 的 key 由 URL、序列化 params、企业 ID、用户 ID、Authorization 组成。
需要知道的边界:
- 只在请求尚未结束时合并,不保留已完成结果,不提供缓存过期或写后失效。
- 不覆盖 POST / PUT / DELETE,也不覆盖 Fetch / SSE。
- `disableDuplicate: true` 的实际含义是**绕过去重,允许独立请求**,名字容易误读。
- key 没有包含所有请求选项,例如 signal、responseType、其他 header、skipErrorHandler。
- 搜索 A 和搜索 B 是不同请求,即使 GET 去重正确,A 晚返回仍可能覆盖 B;这是另一类状态竞态。
若后续给列表加入 AbortController,不能直接假设合并后的共享请求可由某个调用方随意取消。先定义取消与去重的关系,必要时对独立可取消请求绕过去重。多企业请求也应优先显式传组织 ID,避免把切换中的可变全局值当作稳定请求上下文。
### 4.5 为什么还有 Fetch / SSE?
对话接口有独立传输需求:
- `src/hooks/playground/useApiRequest.jsx:354` 使用 Fetch 发非流式请求,并管理取消与凭证。
- 同文件 `:564` 使用 `sse.js` 创建流式请求,逐步接收数据。
- `src/constants/playground.constants.js:79` 动态计算 `/pg/chat/completions` 地址。
- `src/pages/CloudBrain/index.jsx:930` 还有自己的 SSE 路径。
它们**不经过 Axios 的请求头注入、去重和错误拦截器**,需要自行处理配置、凭证、取消和错误。
因此,排查网络问题时应先识别请求使用 Axios、Fetch 还是 SSE;只检查 Axios 拦截器无法覆盖全站网络行为。
## 5. 路由组织与访问规则
### 5.1 配置、策略、UI 包装混在一起
查看一条路由时,需要同时扫描 path、权限条件、懒加载、Loading、功能开关、跳转目标。新增一个页面往往复制十几行包装代码,难以一眼看到“URL → 页面 → 权限”。
其中企业员工限制尤其不只是路由表:它读取站点配置、企业成员身份、顶栏开关和目标路径,决定是否重定向。把这套规则放在 `App` 中,导致路由入口同时承担业务策略计算。
### 5.2 不同模块组织方式不一致
| 模块 | 当前组织方式 | 影响 |
| -------- | --------------------------------------------------- | -------------------------------------- |
| 控制台 | 大量平铺在 App 的顶层 Route | 查看同一业务域要扫长文件 |
| 用户中心 | `/user-center/*` 下使用自己的 Routes | 已有模块化基础,不必推倒重来 |
| 企业空间 | `/org/*` 下使用自己的 Routes,加本地角色/模块限制 | 应保留内部权限和初始化边界 |
| 体验中心 | 通配入口后,主要靠 `pathname.includes()` 选择子页面 | 路径匹配、默认页和未知路径规则不够统一 |
| 全局布局 | PageLayout 按路径字符串决定顶栏、侧栏和滚动 | 增加路由时容易漏掉布局配套调整 |
顶层页面懒加载也不代表每个子页面都单独懒加载。企业空间、体验中心存在子页面静态导入,是否进一步拆包需要结合访问频率和构建结果判断。
### 5.3 权限不是一个简单的 admin 布尔值
至少有这些维度:
- 是否登录,以及会话是否完成恢复。
- 平台管理员 `role >= 10`、Root `role >= 100`。
- 后台配置的模块是否要求登录。
- 企业中心是否可用。
- `org_only_mode` 用户是否只能访问企业区域,以及哪些入口例外放行。
- 企业内部角色和细粒度权限。
- 云脑等构建时功能开关。
**菜单可见性、前端路由可访问性、后端接口授权是三个不同问题。** 可以复用业务规则,但不能拿“菜单不显示”代替路由保护,也不能拿路由保护代替服务端鉴权。
### 5.4 App 之外也有值得整理的边界
- `PageLayout` 同时处理会话、站点加载、主题、路径布局、移动抽屉和弹窗。
- `helpers/api.js` 除 HTTP 客户端外,还包含对话 payload、模型/分组转换、OAuth 跳转等业务函数。
- `helpers/index.js` 是宽泛的聚合导出,新代码继续全部经它导入会使依赖关系难追踪。
这些文件是理解全局行为的重要入口,不能仅凭文件名判断其职责范围。
## 6. 建议阅读顺序与源码索引
第一次熟悉项目,按以下顺序即可,不必从 App 第一行一直背到最后一行:
1. [src/index.jsx](../src/index.jsx):认清全局 Provider 与 BrowserRouter。
2. [PageLayout.jsx](../src/components/layout/PageLayout.jsx):区分应用外壳与启动请求。
3. [App.jsx](../src/App.jsx):只读 `/console/user` 的声明和关联 lazy。
4. [auth.jsx](../src/helpers/auth.jsx):理解 PrivateRoute / AdminRoute / RootRoute。
5. [User 页面](../src/pages/User/index.jsx) → [用户表格](../src/components/table/users/index.jsx) → [useUsersData](../src/hooks/users/useUsersData.jsx):跟踪一次列表与搜索。
6. [api.js](../src/helpers/api.js) → [requestDedupe.js](../src/helpers/requestDedupe.js) → [config.js](../src/helpers/config.js):对照 Network 看真实请求。
7. 按需求再看 [企业空间](../src/pages/Organization/index.jsx)、[用户中心](../src/pages/UserCenter/index.jsx)、[体验中心](../src/pages/ExperienceCenter/index.jsx)。
配套文档:[项目分析与开发上手指南](./PROJECT_ANALYSIS.zh-CN.md)、[维护性优化报告](./MAINTAINABILITY_REPORT.md)、[README](../README.md)。
-1
View File
@@ -356,7 +356,6 @@
} }
})(); })();
</script> </script>
<script src="/config.js"></script>
<script type="module" src="/src/index.jsx"></script> <script type="module" src="/src/index.jsx"></script>
</body> </body>
</html> </html>
+17867
View File
File diff suppressed because it is too large Load Diff
+24 -12
View File
@@ -19,6 +19,7 @@
"country-flag-icons": "^1.5.19", "country-flag-icons": "^1.5.19",
"dayjs": "^1.11.11", "dayjs": "^1.11.11",
"docx": "^9.6.1", "docx": "^9.6.1",
"entities": "^6.0.1",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"history": "^5.3.0", "history": "^5.3.0",
"i18next": "^23.16.8", "i18next": "^23.16.8",
@@ -29,6 +30,7 @@
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"qrcode.react": "^4.2.0", "qrcode.react": "^4.2.0",
"quill": "^2.0.3",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-fireworks": "^1.0.4", "react-fireworks": "^1.0.4",
@@ -53,15 +55,19 @@
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"test": "node --test", "test": "node --test",
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
"test:e2e:report": "playwright show-report",
"lint": "prettier . --check", "lint": "prettier . --check",
"lint:fix": "prettier . --write", "lint:fix": "prettier . --write",
"eslint": "bunx eslint \"**/*.{js,jsx}\" --cache", "check": "npm run eslint && npm test && npm run build",
"eslint:fix": "bunx eslint \"**/*.{js,jsx}\" --fix --cache", "eslint": "eslint \"**/*.{js,jsx}\" --cache",
"eslint:fix": "eslint \"**/*.{js,jsx}\" --fix --cache",
"preview": "vite preview", "preview": "vite preview",
"i18n:extract": "bunx i18next-cli extract", "i18n:extract": "i18next-cli extract",
"i18n:status": "bunx i18next-cli status", "i18n:status": "i18next-cli status",
"i18n:sync": "bunx i18next-cli sync", "i18n:sync": "i18next-cli sync",
"i18n:lint": "bunx i18next-cli lint" "i18n:lint": "i18next-cli lint"
}, },
"browserslist": { "browserslist": {
"production": [ "production": [
@@ -77,7 +83,7 @@
}, },
"devDependencies": { "devDependencies": {
"@douyinfe/vite-plugin-semi": "^2.74.0-alpha.6", "@douyinfe/vite-plugin-semi": "^2.74.0-alpha.6",
"@so1ve/prettier-config": "^3.1.0", "@playwright/test": "^1.64.1",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"eslint": "8.57.0", "eslint": "8.57.0",
@@ -89,11 +95,17 @@
"postcss": "^8.5.3", "postcss": "^8.5.3",
"prettier": "^3.0.0", "prettier": "^3.0.0",
"tailwindcss": "^3", "tailwindcss": "^3",
"vite": "5.1.0" "vite": "5.4.21"
}, },
"prettier": { "proxy": "http://localhost:3000",
"singleQuote": true, "engines": {
"jsxSingleQuote": true "node": ">=22.13.0",
"npm": ">=10"
}, },
"proxy": "http://localhost:3000" "packageManager": "npm@10.9.9",
"overrides": {
"@douyinfe/vite-plugin-semi": {
"vite": "$vite"
}
}
} }
+66
View File
@@ -0,0 +1,66 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { defineConfig, devices } from '@playwright/test';
const baseURL = process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:4175';
export default defineConfig({
testDir: './e2e',
testMatch: '**/*.spec.js',
fullyParallel: false,
forbidOnly: Boolean(process.env.CI),
retries: 0,
workers: 1,
timeout: 45000,
expect: { timeout: 10000 },
reporter: [
['list'],
['html', { outputFolder: 'playwright-report', open: 'never' }],
],
outputDir: 'test-results',
use: {
baseURL,
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'off',
serviceWorkers: 'block',
},
projects: [
{
name: 'chrome',
use: { ...devices['Desktop Chrome'], channel: 'chrome' },
},
{
name: 'mobile-chrome',
use: { ...devices['Pixel 5'], channel: 'chrome' },
},
],
webServer: process.env.PLAYWRIGHT_BASE_URL
? undefined
: {
command: 'npm run dev -- --host 127.0.0.1 --port 4175 --strictPort',
url: baseURL,
reuseExistingServer: !process.env.CI,
timeout: 120000,
env: { VITE_REACT_APP_SERVER_URL: '' },
},
});
-6
View File
@@ -1,6 +0,0 @@
// Runtime configuration - modify per deployment environment.
// Monolith mode: leave SERVER_URL empty.
// Separated mode: set to backend URL, e.g. 'https://api.example.com'
window.__APP_CONFIG__ = {
SERVER_URL: '',
};
+2 -1
View File
@@ -496,4 +496,5 @@
"更多操作": "その他の操作", "更多操作": "その他の操作",
"自定义对话参数": "対話パラメータをカスタマイズ", "自定义对话参数": "対話パラメータをカスタマイズ",
"选择 AI 模型": "AI モデルを選択", "选择 AI 模型": "AI モデルを選択",
"实时显示AI回复内容": "AIの返信内容をリアルタイム表示" "实时显示AI回复内容": "AIの返信内容をリアルタイム表示"
}
+22
View File
@@ -71,6 +71,8 @@ const OAuth2Callback = lazy(() => import('./components/auth/OAuth2Callback'));
// 控制台页面懒加载 // 控制台页面懒加载
const User = lazy(() => import('./pages/User')); const User = lazy(() => import('./pages/User'));
const Setting = lazy(() => import('./pages/Setting')); const Setting = lazy(() => import('./pages/Setting'));
const WebsiteSettings = lazy(() => import('./pages/WebsiteSettings'));
const DemoReservations = lazy(() => import('./pages/DemoReservations'));
const Channel = lazy(() => import('./pages/Channel')); const Channel = lazy(() => import('./pages/Channel'));
const Token = lazy(() => import('./pages/Token')); const Token = lazy(() => import('./pages/Token'));
const Redemption = lazy(() => import('./pages/Redemption')); const Redemption = lazy(() => import('./pages/Redemption'));
@@ -607,6 +609,26 @@ function App() {
</AdminRoute> </AdminRoute>
} }
/> />
<Route
path='/console/website-setting'
element={
<AdminRoute permission='website-setting'>
<Suspense fallback={<Loading />}>
<WebsiteSettings />
</Suspense>
</AdminRoute>
}
/>
<Route
path='/console/demo-reservations'
element={
<AdminRoute permission='demo-reservations'>
<Suspense fallback={<Loading />}>
<DemoReservations />
</Suspense>
</AdminRoute>
}
/>
<Route <Route
path='/console/personal' path='/console/personal'
element={ element={
+8 -11
View File
@@ -21,6 +21,7 @@ import React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Toast, Banner } from '@douyinfe/semi-ui'; import { Button, Toast, Banner } from '@douyinfe/semi-ui';
import { Copy } from 'lucide-react'; import { Copy } from 'lucide-react';
import { copy as copyText } from '../../helpers/utils';
/** /**
* 企业建号一次性凭证展示面板(注册自助建号 / 管理员建号复用)。 * 企业建号一次性凭证展示面板(注册自助建号 / 管理员建号复用)。
@@ -34,11 +35,12 @@ const OrgCredentialResult = ({ creds, onLogin }) => {
const isPending = creds.status === 'pending'; const isPending = creds.status === 'pending';
const copy = (val) => { const copy = async (val) => {
navigator.clipboard if (await copyText(val)) {
.writeText(val) Toast.success(t('已复制到剪贴板'));
.then(() => Toast.success(t('已复制到剪贴板'))) } else {
.catch(() => Toast.error(t('复制失败,请手动复制'))); Toast.error(t('复制失败,请手动复制'));
}
}; };
// 四项凭证拼成带标签的文本块一次复制,避免逐项复制的遗漏(如只记了密码没记企业代码) // 四项凭证拼成带标签的文本块一次复制,避免逐项复制的遗漏(如只记了密码没记企业代码)
@@ -96,12 +98,7 @@ const OrgCredentialResult = ({ creds, onLogin }) => {
<Row label={t('登录名')} value={creds.owner_login_name} mono /> <Row label={t('登录名')} value={creds.owner_login_name} mono />
<Row label={t('初始密码')} value={creds.initial_password} mono /> <Row label={t('初始密码')} value={creds.initial_password} mono />
</div> </div>
<Button <Button size='large' block icon={<Copy size={14} />} onClick={copyAll}>
size='large'
block
icon={<Copy size={14} />}
onClick={copyAll}
>
{t('复制全部凭证')} {t('复制全部凭证')}
</Button> </Button>
{onLogin && ( {onLogin && (
+164
View File
@@ -0,0 +1,164 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Avatar } from '@douyinfe/semi-ui';
import { Bot as FastGPT, Image as Jimeng } from 'lucide-react';
import OpenAI from '@lobehub/icons/es/OpenAI';
import Claude from '@lobehub/icons/es/Claude';
import Gemini from '@lobehub/icons/es/Gemini';
import Moonshot from '@lobehub/icons/es/Moonshot';
import Zhipu from '@lobehub/icons/es/Zhipu';
import Qwen from '@lobehub/icons/es/Qwen';
import DeepSeek from '@lobehub/icons/es/DeepSeek';
import Minimax from '@lobehub/icons/es/Minimax';
import Wenxin from '@lobehub/icons/es/Wenxin';
import Spark from '@lobehub/icons/es/Spark';
import Midjourney from '@lobehub/icons/es/Midjourney';
import Hunyuan from '@lobehub/icons/es/Hunyuan';
import Cohere from '@lobehub/icons/es/Cohere';
import Cloudflare from '@lobehub/icons/es/Cloudflare';
import Ai360 from '@lobehub/icons/es/Ai360';
import Yi from '@lobehub/icons/es/Yi';
import Jina from '@lobehub/icons/es/Jina';
import Mistral from '@lobehub/icons/es/Mistral';
import XAI from '@lobehub/icons/es/XAI';
import Ollama from '@lobehub/icons/es/Ollama';
import Doubao from '@lobehub/icons/es/Doubao';
import Suno from '@lobehub/icons/es/Suno';
import Xinference from '@lobehub/icons/es/Xinference';
import OpenRouter from '@lobehub/icons/es/OpenRouter';
import Dify from '@lobehub/icons/es/Dify';
import Coze from '@lobehub/icons/es/Coze';
import SiliconCloud from '@lobehub/icons/es/SiliconCloud';
import Kling from '@lobehub/icons/es/Kling';
import Perplexity from '@lobehub/icons/es/Perplexity';
import Replicate from '@lobehub/icons/es/Replicate';
const LobeIconsMap = {
OpenAI,
Claude,
Gemini,
Moonshot,
Zhipu,
Qwen,
DeepSeek,
Minimax,
Wenxin,
Spark,
Midjourney,
Hunyuan,
Cohere,
Cloudflare,
Ai360,
Yi,
Jina,
Mistral,
XAI,
Ollama,
Doubao,
Suno,
Xinference,
OpenRouter,
Dify,
Coze,
SiliconCloud,
FastGPT,
Kling,
Jimeng,
Perplexity,
Replicate,
};
export default function LobeHubIcon({ iconName, size = 14 }) {
if (typeof iconName === 'string') iconName = iconName.trim();
// 如果没有图标名称,返回 Avatar
if (!iconName) {
return <Avatar size='extra-extra-small'>?</Avatar>;
}
// 解析组件路径与点号链式属性
const segments = String(iconName).split('.');
const baseKey = segments[0];
const BaseIcon = LobeIconsMap[baseKey];
let IconComponent = undefined;
let propStartIndex = 1;
if (BaseIcon && segments.length > 1 && BaseIcon[segments[1]]) {
IconComponent = BaseIcon[segments[1]];
propStartIndex = 2;
} else {
IconComponent = LobeIconsMap[baseKey];
propStartIndex = 1;
}
// 失败兜底
if (
!IconComponent ||
(typeof IconComponent !== 'function' && typeof IconComponent !== 'object')
) {
const firstLetter = String(iconName).charAt(0).toUpperCase();
return <Avatar size='extra-extra-small'>{firstLetter}</Avatar>;
}
// 解析点号链式属性,形如:key={...}、key='...'、key="..."、key=123、key、key=true/false
const props = {};
const parseValue = (raw) => {
if (raw == null) return true;
let v = String(raw).trim();
// 去除一层花括号包裹
if (v.startsWith('{') && v.endsWith('}')) {
v = v.slice(1, -1).trim();
}
// 去除引号
if (
(v.startsWith('"') && v.endsWith('"')) ||
(v.startsWith("'") && v.endsWith("'"))
) {
return v.slice(1, -1);
}
// 布尔
if (v === 'true') return true;
if (v === 'false') return false;
// 数字
if (/^-?\d+(?:\.\d+)?$/.test(v)) return Number(v);
// 其他原样返回字符串
return v;
};
for (let i = propStartIndex; i < segments.length; i++) {
const seg = segments[i];
if (!seg) continue;
const eqIdx = seg.indexOf('=');
if (eqIdx === -1) {
props[seg.trim()] = true;
continue;
}
const key = seg.slice(0, eqIdx).trim();
const valRaw = seg.slice(eqIdx + 1).trim();
props[key] = parseValue(valRaw);
}
// 兼容第二参数 size,若字符串中未显式指定 size,则使用函数入参
if (props.size == null && size != null) props.size = size;
return <IconComponent {...props} />;
}
+85
View File
@@ -0,0 +1,85 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { runInNewContext } from 'node:vm';
import test from 'node:test';
import React from 'react';
import { transformWithEsbuild } from 'vite';
const filename = new URL('./LobeHubIcon.jsx', import.meta.url);
const { code } = await transformWithEsbuild(
await readFile(filename, 'utf8'),
filename.pathname,
{ loader: 'jsx', format: 'cjs', jsx: 'transform', target: 'node22' },
);
const Mono = () => null;
const Color = () => null;
const Avatar = () => null;
const module = { exports: {} };
runInNewContext(code, {
module,
exports: module.exports,
require(name) {
if (name === 'react') return React;
if (name === '@douyinfe/semi-ui') return { Avatar: 'avatar' };
if (name === 'lucide-react') return { Bot: Mono, Image: Mono };
assert.ok(name.startsWith('@lobehub/icons/es/'), name);
return Object.assign(Mono, { Color, Avatar });
},
});
const render = module.exports.default;
test('brand icon keeps the selected variant and configured props', () => {
const icon = render({
iconName: "OpenAI.Avatar.type={'platform'}.shape='square'.size=24",
size: 14,
});
assert.equal(icon.type, Avatar);
assert.equal(icon.props.type, 'platform');
assert.equal(icon.props.shape, 'square');
assert.equal(icon.props.size, 24);
});
test('brand icon preserves color and default size', () => {
const icon = render({ iconName: 'Claude.Color' });
assert.equal(icon.type, Color);
assert.equal(icon.props.size, 14);
});
test('empty and unknown brand names preserve the fallback avatar', () => {
for (const [iconName, letter] of [
[null, '?'],
['', '?'],
['UnknownBrand', 'U'],
]) {
const icon = render({ iconName });
assert.equal(icon.type, 'avatar');
assert.equal(icon.props.children, letter);
}
});
test('base icons and lucide compatibility brands remain supported', () => {
for (const iconName of ['OpenAI', 'FastGPT', 'Jimeng']) {
const icon = render({ iconName, size: 20 });
assert.equal(icon.type, Mono);
assert.equal(icon.props.size, 20);
}
});
+1 -1
View File
@@ -51,7 +51,7 @@ const CardPro = ({
searchArea, searchArea,
paginationArea, // 新增分页区域 paginationArea, // 新增分页区域
// 卡片属性 // 卡片属性
shadows = '', shadows,
bordered = true, bordered = true,
// 自定义样式 // 自定义样式
style, style,
+2 -3
View File
@@ -134,7 +134,7 @@ const CardTable = ({
if (!col.title) { if (!col.title) {
return ( return (
<div key={idx} className='mt-2 flex justify-end'> <div key={idx} className='mt-2 flex justify-end'>
<Skeleton.Title active style={{ width: 100, height: 24 }} /> <Skeleton.Title style={{ width: 100, height: 24 }} />
</div> </div>
); );
} }
@@ -145,9 +145,8 @@ const CardTable = ({
className='flex justify-between items-center py-1 border-b last:border-b-0 border-dashed' className='flex justify-between items-center py-1 border-b last:border-b-0 border-dashed'
style={{ borderColor: 'var(--semi-color-border)' }} style={{ borderColor: 'var(--semi-color-border)' }}
> >
<Skeleton.Title active style={{ width: 80, height: 14 }} /> <Skeleton.Title style={{ width: 80, height: 14 }} />
<Skeleton.Title <Skeleton.Title
active
style={{ style={{
width: `${50 + (idx % 3) * 10}%`, width: `${50 + (idx % 3) * 10}%`,
maxWidth: 180, maxWidth: 180,
+125
View File
@@ -0,0 +1,125 @@
.rich-text-editor {
border: 1px solid var(--semi-color-border);
border-radius: 4px;
overflow: hidden;
background: var(--semi-color-bg-2);
}
.rich-text-editor.is-invalid {
border-color: var(--semi-color-danger);
}
.rich-text-editor:focus-within {
border-color: var(--semi-color-primary);
}
.rich-text-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 8px;
border-bottom: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
}
.rich-text-toolbar button,
.rich-text-toolbar select {
display: inline-flex;
align-items: center;
justify-content: center;
height: 30px;
min-width: 30px;
padding: 4px 6px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--semi-color-text-1);
cursor: pointer;
}
.rich-text-toolbar select {
width: 112px;
margin-right: 4px;
}
.rich-text-toolbar button:hover,
.rich-text-toolbar button[aria-pressed='true'] {
background: var(--semi-color-primary-light-default);
color: var(--semi-color-primary);
}
.rich-text-toolbar button:focus-visible,
.rich-text-toolbar select:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 1px;
}
.rich-text-toolbar button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.rich-text-content .ql-editor {
min-height: 300px;
padding: 16px;
outline: none;
line-height: 1.9;
color: var(--semi-color-text-0);
overflow-wrap: anywhere;
}
.rich-text-content .ql-editor > * + * {
margin-top: 12px;
}
.rich-text-content .ql-editor.ql-blank::before {
color: var(--semi-color-text-2);
font-style: normal;
pointer-events: none;
white-space: pre-wrap;
}
.rich-text-content h2 {
font-size: 22px;
font-weight: 600;
}
.rich-text-content h3 {
font-size: 18px;
font-weight: 600;
}
.rich-text-content ul {
list-style: disc;
padding-left: 24px;
}
.rich-text-content .ql-editor ol {
padding-left: 0;
}
.rich-text-content blockquote {
border-left: 3px solid var(--semi-color-border);
padding-left: 16px;
color: var(--semi-color-text-2);
}
.rich-text-content img {
max-width: 100%;
height: auto;
}
.rich-text-count {
border-top: 1px solid var(--semi-color-border);
padding: 4px 12px;
text-align: right;
font-size: 12px;
color: var(--semi-color-text-2);
}
.rich-text-content.ql-container,
.rich-text-content .ql-container {
font-family: inherit;
font-size: 14px;
}
.rich-text-editor.is-invalid:focus-within {
border-color: var(--semi-color-danger);
}
.rich-text-toolbar select option {
background: var(--semi-color-bg-2);
color: var(--semi-color-text-0);
}
.rich-text-content .ql-editor img {
display: inline-block;
vertical-align: middle;
}
.rich-text-image-error {
padding: 8px 12px;
font-size: 12px;
color: var(--semi-color-danger);
border-top: 1px solid var(--semi-color-border);
line-height: 1.6;
}
+509
View File
@@ -0,0 +1,509 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import Quill, { Delta } from 'quill/core';
import BoldFormat from 'quill/formats/bold';
import ItalicFormat from 'quill/formats/italic';
import UnderlineFormat from 'quill/formats/underline';
import HeaderFormat from 'quill/formats/header';
import ListFormat from 'quill/formats/list';
import QuoteFormat from 'quill/formats/blockquote';
import ImageFormat from 'quill/formats/image';
import {
Bold,
Italic,
Underline,
List,
ListOrdered,
Quote,
Undo2,
Redo2,
Eraser,
ImagePlus,
} from 'lucide-react';
import {
articleImageSource,
ARTICLE_IMAGE_TYPES,
readArticleImage,
} from './richTextImages';
import { sanitizeArticleHtml } from './richTextContent';
import { countRichText, limitRichTextChange } from './richTextLength';
import 'quill/dist/quill.core.css';
import './RichTextEditor.css';
Quill.register(
{
'formats/bold': BoldFormat,
'formats/italic': ItalicFormat,
'formats/underline': UnderlineFormat,
'formats/header': HeaderFormat,
'formats/list': ListFormat,
'formats/blockquote': QuoteFormat,
'formats/image': ImageFormat,
},
true,
);
export default function RichTextEditor({
value = '',
onChange,
disabled = false,
invalid = false,
onBusyChange,
label = '富文本正文',
placeholder = '',
maxLength,
}) {
const host = useRef(null);
const picker = useRef(null);
const instance = useRef(null);
const selection = useRef({ index: 0, length: 0 });
const callbacks = useRef({
value,
onChange,
onBusyChange,
disabled,
label,
placeholder,
maxLength,
});
const insertFiles = useRef(null);
const lastHtml = useRef('');
const [format, setFormat] = useState({});
const [count, setCount] = useState(0);
const [busy, setBusy] = useState(false);
const [imageError, setImageError] = useState('');
useEffect(() => {
callbacks.current = {
value,
onChange,
onBusyChange,
disabled,
label,
placeholder,
maxLength,
};
}, [value, onChange, onBusyChange, disabled, label, placeholder, maxLength]);
useEffect(() => {
// A separate mount node keeps Quill DOM mutations outside React's tree.
const mount = document.createElement('div');
const container = host.current;
container.append(mount);
let active = true;
let processing = false;
let compositionStart = null;
const quill = new Quill(mount, {
readOnly: callbacks.current.disabled,
placeholder: callbacks.current.placeholder,
formats: [
'bold',
'italic',
'underline',
'header',
'list',
'blockquote',
'image',
],
modules: { history: { userOnly: false }, toolbar: false },
});
instance.current = quill;
const root = quill.root;
root.setAttribute('role', 'textbox');
root.setAttribute('aria-multiline', 'true');
root.setAttribute('aria-required', 'true');
root.setAttribute('aria-label', callbacks.current.label);
const update = (change, old) => {
if (compositionStart) return;
const limit = callbacks.current.maxLength;
if (Number.isFinite(limit) && old && change) {
const bounded = old.compose(
new Delta(limitRichTextChange(old, change, limit)),
);
const correction = quill.getContents().diff(bounded);
if (correction.length()) quill.updateContents(correction, 'silent');
}
const html = sanitizeArticleHtml(quill.getSemanticHTML());
const next =
!quill.getText().trim() && !root.querySelector('img') ? '' : html;
lastHtml.current = next;
setCount(countRichText(quill.getText()));
callbacks.current.onChange?.(next);
};
const updateSelection = (range) => {
if (range)
selection.current = { index: range.index, length: range.length };
setFormat(quill.getFormat(range || selection.current));
};
quill.setContents(
quill.clipboard.convert({
html: sanitizeArticleHtml(callbacks.current.value),
}),
'silent',
);
lastHtml.current = callbacks.current.value;
setCount(countRichText(quill.getText()));
quill.history.clear();
quill.on('text-change', update);
quill.on('editor-change', updateSelectionFromEditor);
function updateSelectionFromEditor(name, range) {
updateSelection(
name === 'selection-change' ? range : quill.getSelection(),
);
}
const begin = () => {
if (!active || processing || callbacks.current.disabled) return false;
processing = true;
setBusy(true);
setImageError('');
callbacks.current.onBusyChange?.(true);
quill.enable(false);
return true;
};
const finish = () => {
processing = false;
if (!active) return;
setBusy(false);
callbacks.current.onBusyChange?.(false);
quill.enable(!callbacks.current.disabled);
if (!callbacks.current.disabled) {
const range = { ...selection.current };
quill.focus();
quill.setSelection(range, 'silent');
}
};
const insert = (delta, range) => {
if (!active) return;
let change = new Delta()
.retain(range.index)
.delete(range.length)
.concat(delta);
if (Number.isFinite(callbacks.current.maxLength)) {
change = new Delta(
limitRichTextChange(
quill.getContents(),
change,
callbacks.current.maxLength,
),
);
}
quill.history.cutoff();
quill.updateContents(change, 'api');
quill.history.cutoff();
selection.current = {
index: change.transformPosition(range.index, false),
length: 0,
};
};
const readFiles = async (files) => {
const sources = [];
for (const file of files) {
try {
sources.push(await readArticleImage(file));
} catch (error) {
if (active) setImageError(error.message);
sources.push('');
}
}
return sources;
};
insertFiles.current = async (files) => {
if (!begin()) return;
const range = { ...selection.current };
try {
const sources = await readFiles(files);
const delta = sources
.filter(Boolean)
.reduce(
(result, source) => result.insert({ image: source }),
new Delta(),
);
if (delta.length()) insert(delta, range);
} finally {
finish();
}
};
const paste = async (event) => {
event.preventDefault();
event.stopImmediatePropagation();
if (!begin()) return;
const range = quill.getSelection() || selection.current;
const html = event.clipboardData?.getData('text/html') || '';
const text = event.clipboardData?.getData('text/plain') || '';
const files = Array.from(event.clipboardData?.files || []);
try {
let delta;
if (html) {
const template = document.createElement('template');
template.innerHTML = html;
let fileIndex = 0;
let sources;
for (const img of template.content.querySelectorAll('img')) {
const original = img.getAttribute('src') || '';
let source =
articleImageSource(original) ||
articleImageSource(img.getAttribute('data-src'));
if (
!source &&
/^(?:file:|blob:|cid:|$)/i.test(original) &&
files.length
) {
sources ??= await readFiles(files);
source = sources[fileIndex++];
}
if (source) img.setAttribute('src', source);
else {
img.remove();
if (active)
setImageError(
'部分图片无法粘贴,请使用可公开访问的图片地址,或粘贴不超过 2 MB 的 JPG、PNG、WebP、GIF 图片。',
);
}
}
delta = quill.clipboard.convert({
html: sanitizeArticleHtml(template.innerHTML),
text,
});
} else if (files.length) {
const sources = await readFiles(files);
delta = sources
.filter(Boolean)
.reduce(
(result, source) => result.insert({ image: source }),
new Delta(),
);
} else
delta = quill.clipboard.convert(
{ text },
quill.getFormat(range.index),
);
if (delta.length()) insert(delta, range);
} catch {
if (active) setImageError('粘贴失败,请重试或使用纯文本粘贴');
} finally {
finish();
}
};
const imageFailed = (event) => {
if (event.target.tagName === 'IMG')
setImageError(
'部分图片加载失败,请确认原图地址可公开访问,或下载图片后重新插入。',
);
};
// Capture before Quill's default clipboard/uploader to validate every image path.
root.addEventListener('paste', paste, true);
root.addEventListener('error', imageFailed, true);
const drop = (event) => {
event.preventDefault();
event.stopImmediatePropagation();
insertFiles.current?.(Array.from(event.dataTransfer?.files || []));
};
root.addEventListener('drop', drop, true);
const startComposition = () => {
compositionStart = quill.getContents();
};
const endComposition = () => {
queueMicrotask(() => {
if (!active || !compositionStart) return;
const old = compositionStart;
compositionStart = null;
quill.update();
update(old.diff(quill.getContents()), old);
});
};
root.addEventListener('compositionstart', startComposition);
root.addEventListener('compositionend', endComposition);
return () => {
active = false;
callbacks.current.onBusyChange?.(false);
quill.off('text-change', update);
quill.off('editor-change', updateSelectionFromEditor);
root.removeEventListener('paste', paste, true);
root.removeEventListener('error', imageFailed, true);
root.removeEventListener('drop', drop, true);
root.removeEventListener('compositionstart', startComposition);
root.removeEventListener('compositionend', endComposition);
quill.enable(false);
instance.current = null;
insertFiles.current = null;
mount.remove();
container.classList.remove('ql-container');
};
}, []);
useEffect(() => {
const quill = instance.current;
if (!quill) return;
quill.enable(!disabled && !busy);
quill.root.setAttribute('aria-invalid', String(invalid));
quill.root.setAttribute('aria-label', label);
// Quill renders placeholder text via CSS, keeping it outside saved HTML.
quill.root.setAttribute('data-placeholder', placeholder);
quill.root.setAttribute('aria-placeholder', placeholder);
}, [disabled, busy, invalid, label, placeholder]);
useEffect(() => {
const quill = instance.current;
if (!quill || value === lastHtml.current) return;
quill.setContents(
quill.clipboard.convert({ html: sanitizeArticleHtml(value) }),
'silent',
);
quill.history.clear();
lastHtml.current = value;
selection.current = { index: 0, length: 0 };
setCount(countRichText(quill.getText()));
setFormat({});
}, [value]);
const run = (command) => {
const quill = instance.current;
if (!quill || disabled || busy) return;
const range = { ...selection.current };
quill.focus();
quill.setSelection(range, 'silent');
command(quill);
setFormat(quill.getFormat());
};
const tools = [
['加粗', Bold, (q) => q.format('bold', !format.bold, 'user'), format.bold],
[
'斜体',
Italic,
(q) => q.format('italic', !format.italic, 'user'),
format.italic,
],
[
'下划线',
Underline,
(q) => q.format('underline', !format.underline, 'user'),
format.underline,
],
[
'项目列表',
List,
(q) =>
q.format('list', format.list === 'bullet' ? false : 'bullet', 'user'),
format.list === 'bullet',
],
[
'有序列表',
ListOrdered,
(q) =>
q.format('list', format.list === 'ordered' ? false : 'ordered', 'user'),
format.list === 'ordered',
],
[
'引用',
Quote,
(q) => q.format('blockquote', !format.blockquote, 'user'),
format.blockquote,
],
['撤销', Undo2, (q) => q.history.undo()],
['重做', Redo2, (q) => q.history.redo()],
[
'清除格式',
Eraser,
(q) =>
q.removeFormat(
selection.current.index,
selection.current.length || 1,
'user',
),
],
];
return (
<div
className={`rich-text-editor ${invalid ? 'is-invalid' : ''}`}
aria-busy={busy}
>
<div
className='rich-text-toolbar'
role='toolbar'
aria-label='富文本工具栏'
>
<select
aria-label='段落格式'
disabled={disabled || busy}
value={format.header || ''}
onChange={(event) =>
run((q) =>
q.format('header', Number(event.target.value) || false, 'user'),
)
}
>
<option value=''>正文段落</option>
<option value='2'>二级标题</option>
<option value='3'>三级标题</option>
</select>
{tools.map(([name, Icon, command, selected = false]) => (
<button
key={name}
type='button'
title={name}
aria-label={name}
aria-pressed={Boolean(selected)}
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => run(command)}
>
<Icon size={16} />
</button>
))}
<button
type='button'
title='插入正文图片(单张不超过 2 MB)'
aria-label='插入正文图片'
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
picker.current.value = '';
picker.current.click();
}}
>
<ImagePlus size={16} />
</button>
<input
ref={picker}
type='file'
accept={ARTICLE_IMAGE_TYPES.join(',')}
hidden
multiple
onChange={(event) =>
insertFiles.current?.(Array.from(event.target.files || []))
}
/>
</div>
<div ref={host} className='rich-text-content' />
{imageError && (
<div className='rich-text-image-error' role='alert'>
{imageError}
</div>
)}
<div className='rich-text-count'>
{busy
? '图片处理中…'
: `${count}${maxLength ? ` / ${maxLength}` : ''} 字`}
</div>
</div>
);
}
@@ -153,10 +153,9 @@ const SelectableButtonGroup = ({
}} }}
> >
{withCheckbox && ( {withCheckbox && (
<Skeleton.Title active style={{ width: 14, height: 14 }} /> <Skeleton.Title style={{ width: 14, height: 14 }} />
)} )}
<Skeleton.Title <Skeleton.Title
active
style={{ style={{
width: `${60 + (index % 3) * 20}px`, width: `${60 + (index % 3) * 20}px`,
height: 14, height: 14,
@@ -264,7 +263,7 @@ const SelectableButtonGroup = ({
{title && ( {title && (
<Divider margin='12px' align='left'> <Divider margin='12px' align='left'>
{showSkeleton ? ( {showSkeleton ? (
<Skeleton.Title active style={{ width: 80, height: 14 }} /> <Skeleton.Title style={{ width: 80, height: 14 }} />
) : ( ) : (
title title
)} )}
@@ -0,0 +1,86 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from './richTextImages.js';
const TAGS = new Set([
'P',
'DIV',
'H2',
'H3',
'BR',
'B',
'STRONG',
'I',
'EM',
'U',
'UL',
'OL',
'LI',
'IMG',
'SPAN',
'BLOCKQUOTE',
]);
export function sanitizeArticleHtml(html) {
const template = document.createElement('template');
template.innerHTML = String(html || '');
const clean = (node) => {
for (const child of [...node.children]) {
if (
[
'SCRIPT',
'STYLE',
'IFRAME',
'OBJECT',
'SVG',
'MATH',
'LINK',
'META',
].includes(child.tagName)
) {
child.remove();
continue;
}
clean(child);
if (!TAGS.has(child.tagName)) {
child.replaceWith(...child.childNodes);
continue;
}
const src = child.getAttribute('src');
for (const attribute of [...child.attributes])
child.removeAttribute(attribute.name);
if (child.tagName === 'IMG') {
const source = articleImageSource(src);
if (source) {
child.setAttribute('src', source);
child.setAttribute('alt', '文章配图');
} else child.remove();
}
}
};
clean(template.content);
// Quill images are inline embeds; standalone images need their own paragraph.
for (const child of [...template.content.children]) {
if (child.tagName !== 'IMG') continue;
const paragraph = document.createElement('p');
child.replaceWith(paragraph);
paragraph.append(child);
}
return template.innerHTML;
}
@@ -0,0 +1,68 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export const ARTICLE_IMAGE_LIMIT = 2 * 1024 * 1024;
export const ARTICLE_IMAGE_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
];
export function articleImageSource(value) {
const source = String(value || '').trim();
if (source.startsWith('data:')) {
const match =
/^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/i.exec(
source,
);
if (!match || match[2].length % 4) return '';
const bytes =
(match[2].length * 3) / 4 - (match[2].match(/=+$/)?.[0].length || 0);
return bytes > 0 && bytes <= ARTICLE_IMAGE_LIMIT ? source : '';
}
try {
const url = new URL(source);
return ['http:', 'https:'].includes(url.protocol) &&
!url.username &&
!url.password
? url.href
: '';
} catch {
return '';
}
}
export async function readArticleImage(file) {
if (!ARTICLE_IMAGE_TYPES.includes(file.type))
throw new Error('正文图片仅支持 JPG、PNG、WebP、GIF 格式');
if (!file.size || file.size > ARTICLE_IMAGE_LIMIT)
throw new Error('单张正文图片大小不能超过 2 MB,且不能为空');
try {
const bitmap = await createImageBitmap(file);
bitmap.close();
} catch {
throw new Error('无法读取图片,请选择有效的图片文件');
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error('图片读取失败,请重新选择或粘贴'));
reader.readAsDataURL(file);
});
}
@@ -0,0 +1,59 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { decodeHTML } from 'entities';
export const ARTICLE_BODY_LIMIT = 20000;
export const countRichText = (text) =>
Array.from(text.replace(/\s/g, '')).length;
export const countArticleHtml = (html) =>
countRichText(decodeHTML(String(html || '').replace(/<[^>]*>/g, '')));
const countDelta = (delta) =>
delta.ops.reduce(
(total, op) =>
total + (typeof op.insert === 'string' ? countRichText(op.insert) : 0),
0,
);
// Budget only newly inserted text, keeping the original text after the caret intact.
export function limitRichTextChange(old, change, limit) {
let oldIndex = 0;
let remaining = limit - countDelta(old);
for (const op of change.ops) {
if (op.delete)
remaining += countDelta(old.slice(oldIndex, oldIndex + op.delete));
oldIndex += op.retain || op.delete || 0;
}
remaining = Math.max(0, remaining);
const ops = change.ops.flatMap((op) => {
if (typeof op.insert !== 'string') return [op];
const text = Array.from(op.insert)
.filter((char) => {
if (/\s/.test(char)) return true;
if (!remaining) return false;
remaining--;
return true;
})
.join('');
return text ? [{ ...op, insert: text }] : [];
});
return ops;
}
+30 -23
View File
@@ -17,9 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import HeaderBar from './headerbar';
import { Layout } from '@douyinfe/semi-ui'; import { Layout } from '@douyinfe/semi-ui';
import SiderBar from './SiderBar';
import App from '../../App'; import App from '../../App';
import { ToastContainer } from 'react-toastify'; import { ToastContainer } from 'react-toastify';
import React, { import React, {
@@ -49,7 +47,11 @@ import { useLocation } from 'react-router-dom';
import { applyTheme, setPresetOverrides } from '../../helpers/theme'; import { applyTheme, setPresetOverrides } from '../../helpers/theme';
// 用户问卷功能已禁用 // 用户问卷功能已禁用
// import UserSurveyModal from '../common/modals/UserSurveyModal'; // import UserSurveyModal from '../common/modals/UserSurveyModal';
import NewUserGiftModal from '../common/modals/NewUserGiftModal'; const HeaderBar = lazy(() => import('./headerbar'));
const SiderBar = lazy(() => import('./SiderBar'));
const NewUserGiftModal = lazy(
() => import('../common/modals/NewUserGiftModal'),
);
// 懒加载客服浮窗组件 - 非核心功能,延迟加载 // 懒加载客服浮窗组件 - 非核心功能,延迟加载
const CustomerServiceFloat = lazy(() => import('../customer-service')); const CustomerServiceFloat = lazy(() => import('../customer-service'));
@@ -75,7 +77,6 @@ const printConsoleWelcome = (status) => {
}; };
const PageLayout = () => { const PageLayout = () => {
console.log('[PageLayout] Component rendering...');
const [userState, userDispatch] = useContext(UserContext); const [userState, userDispatch] = useContext(UserContext);
const [statusState, statusDispatch] = useContext(StatusContext); const [statusState, statusDispatch] = useContext(StatusContext);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
@@ -94,7 +95,8 @@ const PageLayout = () => {
const shouldInnerPadding = const shouldInnerPadding =
location.pathname.includes('/console') && location.pathname.includes('/console') &&
!location.pathname.startsWith('/console/chat') && !location.pathname.startsWith('/console/chat') &&
location.pathname !== '/console/playground'; location.pathname !== '/console/playground' &&
location.pathname !== '/console/website-setting';
const isConsoleRoute = location.pathname.startsWith('/console'); const isConsoleRoute = location.pathname.startsWith('/console');
const showSider = isConsoleRoute && (!isMobile || drawerOpen); const showSider = isConsoleRoute && (!isMobile || drawerOpen);
@@ -224,10 +226,8 @@ const PageLayout = () => {
}; };
const loadStatus = async () => { const loadStatus = async () => {
console.log('[PageLayout] Loading status from API...');
try { try {
const res = await API.get('/api/status'); const res = await API.get('/api/status');
console.log('[PageLayout] API response received:', res.data);
const { success, data } = res.data; const { success, data } = res.data;
if (success) { if (success) {
statusDispatch({ type: 'set', payload: data }); statusDispatch({ type: 'set', payload: data });
@@ -241,7 +241,6 @@ const PageLayout = () => {
if (data.theme_config !== undefined) { if (data.theme_config !== undefined) {
applyTheme(data.theme_config); applyTheme(data.theme_config);
} }
console.log('[PageLayout] Status loaded successfully');
} else { } else {
console.error('[PageLayout] API returned success=false'); console.error('[PageLayout] API returned success=false');
showError('Unable to connect to server'); showError('Unable to connect to server');
@@ -355,10 +354,12 @@ const PageLayout = () => {
zIndex: 100, zIndex: 100,
}} }}
> >
<HeaderBar <Suspense fallback={null}>
onMobileMenuToggle={() => setDrawerOpen((prev) => !prev)} <HeaderBar
drawerOpen={drawerOpen} onMobileMenuToggle={() => setDrawerOpen((prev) => !prev)}
/> drawerOpen={drawerOpen}
/>
</Suspense>
{/* 跑马灯公告 - 固定在导航栏正下方;认证页不展示(与 hasMarquee 的高度计算保持一致) */} {/* 跑马灯公告 - 固定在导航栏正下方;认证页不展示(与 hasMarquee 的高度计算保持一致) */}
{!isAuthPage && <Marquee />} {!isAuthPage && <Marquee />}
</Header> </Header>
@@ -406,12 +407,14 @@ const PageLayout = () => {
: undefined, : undefined,
}} }}
> >
<SiderBar <Suspense fallback={null}>
forceExpanded={siderForceExpanded} <SiderBar
onNavigate={() => { forceExpanded={siderForceExpanded}
if (isMobile) setDrawerOpen(false); onNavigate={() => {
}} if (isMobile) setDrawerOpen(false);
/> }}
/>
</Suspense>
</Sider> </Sider>
)} )}
<Layout <Layout
@@ -470,11 +473,15 @@ const PageLayout = () => {
/> */} /> */}
{/* 新用户注册赠送额度弹窗 */} {/* 新用户注册赠送额度弹窗 */}
<NewUserGiftModal {showGiftModal && (
visible={showGiftModal} <Suspense fallback={null}>
onClose={() => setShowGiftModal(false)} <NewUserGiftModal
quota={giftQuota} visible={showGiftModal}
/> onClose={() => setShowGiftModal(false)}
quota={giftQuota}
/>
</Suspense>
)}
</Layout> </Layout>
); );
}; };
+47 -13
View File
@@ -27,6 +27,11 @@ import { useSidebar } from '../../hooks/common/useSidebar';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { isAdmin, isRoot, showError } from '../../helpers'; import { isAdmin, isRoot, showError } from '../../helpers';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import {
canAccessDelegatedAdminPage,
getDelegatedSettingTabs,
} from '../../helpers/adminDelegation';
import SkeletonWrapper from './components/SkeletonWrapper'; import SkeletonWrapper from './components/SkeletonWrapper';
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi'; import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
@@ -42,6 +47,8 @@ const routerMap = {
log: '/console/log', log: '/console/log',
midjourney: '/console/midjourney', midjourney: '/console/midjourney',
setting: '/console/setting', setting: '/console/setting',
'website-setting': '/console/website-setting',
'demo-reservations': '/console/demo-reservations',
about: '/about', about: '/about',
detail: '/console', detail: '/console',
pricing: '/market', pricing: '/market',
@@ -75,16 +82,13 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
} = useSidebar(); } = useSidebar();
const [statusState] = useContext(StatusContext); const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs;
// 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口 // 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口
const delegatedSettingTabs = useMemo(() => { const delegatedSettingTabs = useMemo(
try { () => getDelegatedSettingTabs(delegatedPermissions),
const raw = statusState?.status?.AdminDelegatedSettingTabs; [delegatedPermissions],
const parsed = raw ? JSON.parse(raw) : []; );
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}, [statusState?.status?.AdminDelegatedSettingTabs]);
const canAccessSetting = const canAccessSetting =
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0); isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
@@ -284,10 +288,31 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
to: '/setting', to: '/setting',
className: canAccessSetting ? '' : 'tableHiddle', className: canAccessSetting ? '' : 'tableHiddle',
}, },
{
text: t('官网设置'),
itemKey: 'website-setting',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('预约演示'),
itemKey: 'demo-reservations',
className: isAdmin() ? '' : 'tableHiddle',
},
]; ];
// 根据配置过滤项目 // 根据配置过滤项目
const filteredItems = items.filter((item) => { const filteredItems = items.filter((item) => {
if (
(item.itemKey === 'website-setting' ||
item.itemKey === 'demo-reservations') &&
!canAccessDelegatedAdminPage(
userState?.user?.role,
delegatedPermissions,
item.itemKey,
)
) {
return false;
}
if ( if (
!CLOUD_BRAIN_UI_ENABLED && !CLOUD_BRAIN_UI_ENABLED &&
(item.itemKey === 'skill-platform' || (item.itemKey === 'skill-platform' ||
@@ -315,7 +340,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
}); });
return filteredItems; return filteredItems;
}, [isAdmin(), isRoot(), t, isModuleVisible, canAccessSetting]); }, [
isAdmin(),
isRoot(),
t,
isModuleVisible,
canAccessSetting,
delegatedSettingTabs,
delegatedPermissions,
userState?.user?.role,
]);
const chatMenuItems = useMemo(() => { const chatMenuItems = useMemo(() => {
const items = [ const items = [
@@ -597,8 +631,8 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
</> </>
)} )}
{/* 管理员区域 - 只在管理员时显示且配置允许时显示 */} {/* 管理员区域:按角色、权限下放及菜单配置过滤。 */}
{isAdmin() && hasSectionVisibleModules('admin') && ( {isAdmin() && (
<> <>
<Divider className='sidebar-divider' /> <Divider className='sidebar-divider' />
<div> <div>
@@ -637,7 +671,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
/> />
} }
onClick={toggleCollapsed} onClick={toggleCollapsed}
icononly={collapsed} aria-label={collapsed ? t('展开侧边栏') : t('收起侧边栏')}
style={ style={
collapsed collapsed
? { width: 36, height: 24, padding: 0 } ? { width: 36, height: 24, padding: 0 }
@@ -52,7 +52,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: isMobile ? 40 : width, height }} style={{ width: isMobile ? 40 : width, height }}
/> />
} }
@@ -71,7 +70,7 @@ const SkeletonWrapper = ({
loading={true} loading={true}
active active
placeholder={ placeholder={
<Skeleton.Avatar active size='extra-small' className='shadow-sm' /> <Skeleton.Avatar size='extra-small' className='shadow-sm' />
} }
/> />
<div className='ml-1.5 mr-1'> <div className='ml-1.5 mr-1'>
@@ -80,7 +79,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: isMobile ? 15 : width, height: 12 }} style={{ width: isMobile ? 15 : width, height: 12 }}
/> />
} }
@@ -98,7 +96,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Image <Skeleton.Image
active
className={`absolute inset-0 !rounded-full ${className}`} className={`absolute inset-0 !rounded-full ${className}`}
style={{ width: '100%', height: '100%' }} style={{ width: '100%', height: '100%' }}
/> />
@@ -113,7 +110,7 @@ const SkeletonWrapper = ({
<Skeleton <Skeleton
loading={true} loading={true}
active active
placeholder={<Skeleton.Title active style={{ width, height: 24 }} />} placeholder={<Skeleton.Title style={{ width, height: 24 }} />}
/> />
); );
}; };
@@ -125,7 +122,7 @@ const SkeletonWrapper = ({
<Skeleton <Skeleton
loading={true} loading={true}
active active
placeholder={<Skeleton.Title active style={{ width, height }} />} placeholder={<Skeleton.Title style={{ width, height }} />}
/> />
</div> </div>
); );
@@ -139,10 +136,7 @@ const SkeletonWrapper = ({
loading={true} loading={true}
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title style={{ width, height, borderRadius: 9999 }} />
active
style={{ width, height, borderRadius: 9999 }}
/>
} }
/> />
</div> </div>
@@ -164,7 +158,7 @@ const SkeletonWrapper = ({
loading={true} loading={true}
active active
placeholder={ placeholder={
<Skeleton.Avatar active size='extra-small' shape='square' /> <Skeleton.Avatar size='extra-small' shape='square' />
} }
/> />
</div> </div>
@@ -174,7 +168,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: width || 80, height: height || 14 }} style={{ width: width || 80, height: height || 14 }}
/> />
} }
@@ -192,7 +185,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: width || 60, height: height || 12 }} style={{ width: width || 60, height: height || 12 }}
/> />
} }
@@ -217,7 +209,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Avatar <Skeleton.Avatar
active
shape='square' shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }} style={{ width: ICON_SIZE, height: ICON_SIZE }}
/> />
@@ -230,10 +221,7 @@ const SkeletonWrapper = ({
loading={true} loading={true}
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title style={{ width: labelWidth, height: TEXT_HEIGHT }} />
active
style={{ width: labelWidth, height: TEXT_HEIGHT }}
/>
} }
/> />
); );
@@ -269,7 +257,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Avatar <Skeleton.Avatar
active
shape='square' shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }} style={{ width: ICON_SIZE, height: ICON_SIZE }}
/> />
@@ -284,22 +271,22 @@ const SkeletonWrapper = ({
{Array(2) {Array(2)
.fill(null) .fill(null)
.map((_, i) => ( .map((_, i) => (
<CollapsedRow keyPrefix='c-chat' index={i} /> <CollapsedRow key={i} keyPrefix='c-chat' index={i} />
))} ))}
{Array(5) {Array(5)
.fill(null) .fill(null)
.map((_, i) => ( .map((_, i) => (
<CollapsedRow keyPrefix='c-console' index={i} /> <CollapsedRow key={i} keyPrefix='c-console' index={i} />
))} ))}
{Array(2) {Array(2)
.fill(null) .fill(null)
.map((_, i) => ( .map((_, i) => (
<CollapsedRow keyPrefix='c-personal' index={i} /> <CollapsedRow key={i} keyPrefix='c-personal' index={i} />
))} ))}
{Array(5) {Array(5)
.fill(null) .fill(null)
.map((_, i) => ( .map((_, i) => (
<CollapsedRow keyPrefix='c-admin' index={i} /> <CollapsedRow key={i} keyPrefix='c-admin' index={i} />
))} ))}
</div> </div>
); );
@@ -329,7 +316,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }} style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/> />
} }
@@ -350,7 +336,6 @@ const SkeletonWrapper = ({
active active
placeholder={ placeholder={
<Skeleton.Title <Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }} style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/> />
} }
@@ -82,19 +82,21 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
</Dropdown.Menu> </Dropdown.Menu>
} }
> >
<Button <span className='inline-flex'>
icon={<Globe size={20} />} <Button
aria-label={t('common.changeLanguage')} icon={<Globe size={20} />}
theme='borderless' aria-label={t('common.changeLanguage')}
type='tertiary' theme='borderless'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95' type='tertiary'
style={{ className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
color: style={{
actualTheme === 'dark' color:
? 'rgba(243,244,246,0.9)' actualTheme === 'dark'
: 'rgba(75,85,99,1)', ? 'rgba(243,244,246,0.9)'
}} : 'rgba(75,85,99,1)',
/> }}
/>
</span>
</Dropdown> </Dropdown>
); );
}; };
@@ -133,19 +133,21 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
</Dropdown.Menu> </Dropdown.Menu>
} }
> >
<Button <span className='inline-flex'>
theme='borderless' <Button
type='tertiary' theme='borderless'
aria-label={t('主导航')} type='tertiary'
aria-haspopup='menu' aria-label={t('主导航')}
aria-expanded={visible} aria-haspopup='menu'
icon={<Compass size={16} />} aria-expanded={visible}
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0' icon={<Compass size={16} />}
> className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0'
<span className='ml-1 text-[13px] font-semibold truncate'> >
{activeItem ? activeItem.text : t('导航')} <span className='ml-1 text-[13px] font-semibold truncate'>
</span> {activeItem ? activeItem.text : t('导航')}
</Button> </span>
</Button>
</span>
</Dropdown> </Dropdown>
); );
}; };
+16 -13
View File
@@ -251,19 +251,22 @@ const ThemeToggle = ({ theme, onThemeToggle, t }) => {
</Dropdown.Menu> </Dropdown.Menu>
} }
> >
<Button {/* Semi can resolve a DOM trigger directly without findDOMNode. */}
icon={currentButtonIcon} <span className='inline-flex'>
aria-label={t('切换主题')} <Button
theme='borderless' icon={currentButtonIcon}
type='tertiary' aria-label={t('切换主题')}
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95' theme='borderless'
style={{ type='tertiary'
color: className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
actualTheme === 'dark' style={{
? 'rgba(243,244,246,0.9)' color:
: 'rgba(75,85,99,1)', actualTheme === 'dark'
}} ? 'rgba(243,244,246,0.9)'
/> : 'rgba(75,85,99,1)',
}}
/>
</span>
</Dropdown> </Dropdown>
); );
}; };
+35 -33
View File
@@ -300,41 +300,43 @@ const UserArea = ({
</Dropdown.Menu> </Dropdown.Menu>
} }
> >
<Button <span className='inline-flex'>
theme='borderless' <Button
type='tertiary' theme='borderless'
className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group' type='tertiary'
> className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group'
<div className='relative'> >
<Avatar <div className='relative'>
size='small' <Avatar
src={avatarUrl} size='small'
color={stringToColor(displayName)} src={avatarUrl}
className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all' color={stringToColor(displayName)}
> className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all'
{displayName[0].toUpperCase()} >
</Avatar> {displayName[0].toUpperCase()}
{/* 在线状态点 */} </Avatar>
<span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' /> {/* 在线状态点 */}
</div> <span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
<span className='hidden md:flex flex-col items-start'> </div>
<Typography.Text <span className='hidden md:flex flex-col items-start'>
className='!text-sm !font-medium !leading-none' <Typography.Text
className='!text-sm !font-medium !leading-none'
style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)',
}}
>
{displayName}
</Typography.Text>
</span>
<ChevronDown
size={14}
style={{ style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)', color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}} }}
> className='group-hover:!opacity-80 transition-colors'
{displayName} />
</Typography.Text> </Button>
</span> </span>
<ChevronDown
size={14}
style={{
color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}}
className='group-hover:!opacity-80 transition-colors'
/>
</Button>
</Dropdown> </Dropdown>
); );
} else { } else {
+1 -1
View File
@@ -61,7 +61,7 @@ import {
selectFilter, selectFilter,
countRounds, countRounds,
} from '../../helpers'; } from '../../helpers';
import { usePlayground } from '../../contexts/PlaygroundContext'; import { usePlayground } from '../../context/Playground';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
const ChatArea = ({ const ChatArea = ({
@@ -35,7 +35,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useSpeechRecognition } from '../../hooks/playground/useSpeechRecognition'; import { useSpeechRecognition } from '../../hooks/playground/useSpeechRecognition';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePlayground } from '../../contexts/PlaygroundContext'; import { usePlayground } from '../../context/Playground';
import { import {
getExperienceCenterBool, getExperienceCenterBool,
getExperienceCenterPositiveInt, getExperienceCenterPositiveInt,
+1 -1
View File
@@ -41,7 +41,7 @@ import { useTranslation } from 'react-i18next';
// 同名遮蔽在 Vite/terser 生产构建里会把两者缩成同一个变量名,触发 TDZ 错误: // 同名遮蔽在 Vite/terser 生产构建里会把两者缩成同一个变量名,触发 TDZ 错误:
// "Cannot access 'Oe' before initialization" // "Cannot access 'Oe' before initialization"
// 本地函数签名是 (content) 而非 helpers 里的 (message),调用时记得传 message.content。 // 本地函数签名是 (content) 而非 helpers 里的 (message),调用时记得传 message.content。
import { usePlayground } from '../../contexts/PlaygroundContext'; import { usePlayground } from '../../context/Playground';
import { useSpeechSynthesis } from '../../hooks/playground/useSpeechSynthesis'; import { useSpeechSynthesis } from '../../hooks/playground/useSpeechSynthesis';
const MessageContent = ({ const MessageContent = ({
+63 -9
View File
@@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Card, Spin } from '@douyinfe/semi-ui'; import { Banner, Button, Card, Spin } from '@douyinfe/semi-ui';
import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral'; import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral';
import SettingsLanguage from '../../pages/Setting/Operation/SettingsLanguage'; import SettingsLanguage from '../../pages/Setting/Operation/SettingsLanguage';
import SettingsHeaderNavModules from '../../pages/Setting/Operation/SettingsHeaderNavModules'; import SettingsHeaderNavModules from '../../pages/Setting/Operation/SettingsHeaderNavModules';
@@ -35,7 +35,34 @@ import SettingsFallback from '../../pages/Setting/Operation/SettingsFallback';
import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme'; import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme';
import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation'; import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation';
import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject'; import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject';
import { API, showError, toBoolean } from '../../helpers'; import { API, toBoolean } from '../../helpers';
const ProgressiveSettingsSections = ({ children, loading }) => {
const sections = React.Children.toArray(children);
const [visibleCount, setVisibleCount] = useState(1);
useEffect(() => {
if (visibleCount >= sections.length) return;
// Yield between sections so mounting all forms cannot block one task.
const timer = setTimeout(() => setVisibleCount((count) => count + 1), 0);
return () => clearTimeout(timer);
}, [visibleCount, sections.length]);
return (
<Spin spinning={loading} size='large'>
{sections.slice(0, visibleCount)}
{visibleCount < sections.length && (
<div
role='status'
aria-busy='true'
className='flex justify-center py-6'
>
<Spin spinning />
</div>
)}
</Spin>
);
};
const OperationSetting = () => { const OperationSetting = () => {
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
@@ -98,6 +125,13 @@ const OperationSetting = () => {
/* 提示词采集(实验性,方案 §35 一期) */ /* 提示词采集(实验性,方案 §35 一期) */
GlobalPromptArchiveEnabled: false, GlobalPromptArchiveEnabled: false,
/* Skill switches arrive as strings from the options API. */
SkillMarketRequireAuth: false,
SkillInjectEnabled: false,
SkillInjectMaxSkills: '5',
SkillInjectMaxRunes: '3000',
SkillInjectCacheTTLSeconds: '60',
/* 监控设置 */ /* 监控设置 */
ChannelDisableThreshold: 0, ChannelDisableThreshold: 0,
QuotaRemindThreshold: 0, QuotaRemindThreshold: 0,
@@ -135,13 +169,15 @@ const OperationSetting = () => {
'fallback_setting.max_attempts_per_request': 10, 'fallback_setting.max_attempts_per_request': 10,
}); });
let [loading, setLoading] = useState(false); const [loading, setLoading] = useState(true);
const [optionsLoaded, setOptionsLoaded] = useState(false);
const [loadError, setLoadError] = useState('');
const inputTypes = useRef(inputs); const inputTypes = useRef(inputs);
const getOptions = useCallback(async () => { const getOptions = useCallback(async () => {
const res = await API.get('/api/option/'); const res = await API.get('/api/option/');
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success && Array.isArray(data)) {
let newInputs = {}; let newInputs = {};
data.forEach((item) => { data.forEach((item) => {
if (typeof inputTypes.current[item.key] === 'boolean') { if (typeof inputTypes.current[item.key] === 'boolean') {
@@ -153,16 +189,17 @@ const OperationSetting = () => {
setInputs(newInputs); setInputs(newInputs);
} else { } else {
showError(message); throw new Error(message || '运营设置读取失败,请重试');
} }
}, []); }, []);
const onRefresh = useCallback(async () => { const onRefresh = useCallback(async () => {
try { try {
setLoading(true); setLoading(true);
setLoadError('');
await getOptions(); await getOptions();
// showSuccess('刷新成功'); setOptionsLoaded(true);
} catch (error) { } catch (error) {
showError('刷新失败'); setLoadError(error.message || '运营设置读取失败,请重试');
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -172,9 +209,26 @@ const OperationSetting = () => {
onRefresh(); onRefresh();
}, [onRefresh]); }, [onRefresh]);
const errorBanner = loadError && (
<Banner type='danger' closeIcon={null} description={loadError}>
<Button onClick={onRefresh} disabled={loading}>
重新加载运营设置
</Button>
</Banner>
);
// Never mount editable defaults when the initial request fails.
if (!optionsLoaded) {
if (loadError) return errorBanner;
return (
<Spin spinning size='large' style={{ minHeight: 200, width: '100%' }} />
);
}
return ( return (
<> <>
<Spin spinning={loading} size='large'> {errorBanner}
<ProgressiveSettingsSections loading={loading}>
{/* 通用设置 */} {/* 通用设置 */}
<Card style={{ marginTop: '10px' }}> <Card style={{ marginTop: '10px' }}>
<SettingsGeneral options={inputs} refresh={onRefresh} /> <SettingsGeneral options={inputs} refresh={onRefresh} />
@@ -235,7 +289,7 @@ const OperationSetting = () => {
<SettingsExperienceCenter options={inputs} refresh={onRefresh} /> <SettingsExperienceCenter options={inputs} refresh={onRefresh} />
{/* 普通管理员可见的系统设置页(权限下放) */} {/* 普通管理员可见的系统设置页(权限下放) */}
<SettingsAdminDelegation options={inputs} refresh={onRefresh} /> <SettingsAdminDelegation options={inputs} refresh={onRefresh} />
</Spin> </ProgressiveSettingsSections>
</> </>
); );
}; };
@@ -81,7 +81,6 @@ const TaskLogsActions = ({
{ key: 'channel_name', title: t('渠道名称') }, { key: 'channel_name', title: t('渠道名称') },
] ]
: []), : []),
{ key: 'platform', title: t('平台') },
{ key: 'action', title: t('类型') }, { key: 'action', title: t('类型') },
{ {
key: 'model', key: 'model',
@@ -34,7 +34,6 @@ import {
Video, Video,
Sparkles, Sparkles,
Timer, Timer,
Image as ImageIcon,
ImagePlus, ImagePlus,
Coins, Coins,
Cpu, Cpu,
@@ -47,7 +46,6 @@ import {
IMAGE_ACTION_GENERATE, IMAGE_ACTION_GENERATE,
IMAGE_ACTION_EDIT, IMAGE_ACTION_EDIT,
} from '../../../constants/common.constant'; } from '../../../constants/common.constant';
import { CHANNEL_OPTIONS } from '../../../constants/channel.constants';
import { renderQuota } from '../../../helpers'; import { renderQuota } from '../../../helpers';
// 仅保留与下方 COLOR_CONFIG 一一对应的色值,避免 amber/lime/violet/teal/indigo/light-blue // 仅保留与下方 COLOR_CONFIG 一一对应的色值,避免 amber/lime/violet/teal/indigo/light-blue
@@ -230,34 +228,6 @@ const renderType = (type, t) => {
); );
}; };
const renderPlatform = (platform, t) => {
let option = CHANNEL_OPTIONS.find(
(opt) => String(opt.value) === String(platform),
);
if (option) {
return (
<CustomTag
icon={Video}
label={option.label}
colorKey={option.color || 'cyan'}
/>
);
}
if (platform === 'suno') {
return <CustomTag icon={Music} label='Suno' colorKey='green' />;
}
if (platform === 'image') {
return <CustomTag icon={ImageIcon} label={t('图片')} colorKey='cyan' />;
}
if (platform === 'video') {
return <CustomTag icon={Video} label={t('视频')} colorKey='blue' />;
}
if (platform === 'mj') {
return <CustomTag icon={Sparkles} label='Midjourney' colorKey='purple' />;
}
return <CustomTag icon={HelpCircle} label={t('未知')} colorKey='grey' />;
};
const renderStatus = (type, t) => { const renderStatus = (type, t) => {
const statusConfig = { const statusConfig = {
SUCCESS: { icon: CheckCircle, label: t('成功'), color: 'green' }, SUCCESS: { icon: CheckCircle, label: t('成功'), color: 'green' },
@@ -292,6 +262,7 @@ export const getTaskLogsColumns = ({
copyText, copyText,
openContentModal, openContentModal,
isAdminUser, isAdminUser,
isRootUser = false,
openVideoModal, openVideoModal,
}) => { }) => {
return [ return [
@@ -344,14 +315,6 @@ export const getTaskLogsColumns = ({
); );
}, },
}, },
{
key: COLUMN_KEYS.PLATFORM,
title: t('平台'),
dataIndex: 'platform',
render: (text, record, index) => {
return <div>{renderPlatform(text, t)}</div>;
},
},
{ {
key: COLUMN_KEYS.TYPE, key: COLUMN_KEYS.TYPE,
title: t('类型'), title: t('类型'),
@@ -394,10 +357,16 @@ export const getTaskLogsColumns = ({
return ( return (
<Typography.Text <Typography.Text
ellipsis={{ showTooltip: true }} ellipsis={{ showTooltip: true }}
onClick={() => { onClick={
openContentModal(JSON.stringify(record, null, 2)); isRootUser
}} ? () => openContentModal(JSON.stringify(record, null, 2))
className='cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors font-mono text-xs' : undefined
}
className={
isRootUser
? 'cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors font-mono text-xs'
: 'font-mono text-xs'
}
> >
{text} {text}
</Typography.Text> </Typography.Text>
@@ -54,6 +54,7 @@ const TaskLogsFilters = ({
isAdminUser, isAdminUser,
getFreshInitValues, getFreshInitValues,
usageRecordMode = false, usageRecordMode = false,
hideDateRange = false,
t, t,
}) => { }) => {
const SearchIcon = usageRecordMode ? SearchCheck : Search; const SearchIcon = usageRecordMode ? SearchCheck : Search;
@@ -98,29 +99,31 @@ const TaskLogsFilters = ({
{/* 搜索字段网格 */} {/* 搜索字段网格 */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'> <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'>
{/* 时间选择器 */} {/* 时间选择器:企业页复用上方消费记录的已提交时间范围 */}
<div className='col-span-1 lg:col-span-2'> {!hideDateRange && (
<div className='relative group'> <div className='col-span-1 lg:col-span-2'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' /> <div className='relative group'>
<div className='relative'> <div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<Form.DatePicker <div className='relative'>
field='dateRange' <Form.DatePicker
className='w-full' field='dateRange'
type='dateTimeRange' className='w-full'
placeholder={[t('开始时间'), t('结束时间')]} type='dateTimeRange'
showClear placeholder={[t('开始时间'), t('结束时间')]}
pure showClear
size='small' pure
prefix={<InputPrefix icon={Calendar} />} size='small'
presets={DATE_RANGE_PRESETS.map((preset) => ({ prefix={<InputPrefix icon={Calendar} />}
text: t(preset.text), presets={DATE_RANGE_PRESETS.map((preset) => ({
start: preset.start(), text: t(preset.text),
end: preset.end(), start: preset.start(),
}))} end: preset.end(),
/> }))}
/>
</div>
</div> </div>
</div> </div>
</div> )}
{/* 任务 ID */} {/* 任务 ID */}
<div className='relative group'> <div className='relative group'>
@@ -41,6 +41,7 @@ const TaskLogsTable = (taskLogsData) => {
openContentModal, openContentModal,
openVideoModal, openVideoModal,
isAdminUser, isAdminUser,
isRootUser,
t, t,
COLUMN_KEYS, COLUMN_KEYS,
} = taskLogsData; } = taskLogsData;
@@ -54,8 +55,17 @@ const TaskLogsTable = (taskLogsData) => {
openContentModal, openContentModal,
openVideoModal, openVideoModal,
isAdminUser, isAdminUser,
isRootUser,
}); });
}, [t, COLUMN_KEYS, copyText, openContentModal, openVideoModal, isAdminUser]); }, [
t,
COLUMN_KEYS,
copyText,
openContentModal,
openVideoModal,
isAdminUser,
isRootUser,
]);
// Filter columns based on visibility settings // Filter columns based on visibility settings
const getVisibleColumns = () => { const getVisibleColumns = () => {
+14 -2
View File
@@ -28,8 +28,19 @@ import { useTaskLogsData } from '../../../hooks/task-logs/useTaskLogsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils'; import { createCardProPagination } from '../../../helpers/utils';
const TaskLogsPage = ({ usageRecordMode = false }) => { const TaskLogsPage = ({
const taskLogsData = useTaskLogsData(); usageRecordMode = false,
organizationMode = false,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision = 0,
}) => {
const taskLogsData = useTaskLogsData({
organizationMode,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision,
});
const isMobile = useIsMobile(); const isMobile = useIsMobile();
return ( return (
@@ -81,6 +92,7 @@ const TaskLogsPage = ({ usageRecordMode = false }) => {
<TaskLogsFilters <TaskLogsFilters
{...taskLogsData} {...taskLogsData}
usageRecordMode={usageRecordMode} usageRecordMode={usageRecordMode}
hideDateRange={taskLogsData.usesSharedDateRange}
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
@@ -31,6 +31,7 @@ const ColumnSelectorModal = ({
initDefaultColumns, initDefaultColumns,
COLUMN_KEYS, COLUMN_KEYS,
isAdminUser, isAdminUser,
isRootUser,
copyText, copyText,
openContentModal, openContentModal,
usageRecordMode = false, usageRecordMode = false,
@@ -43,6 +44,7 @@ const ColumnSelectorModal = ({
copyText, copyText,
openContentModal, openContentModal,
isAdminUser, isAdminUser,
isRootUser,
}); });
// 计算"全选"状态时应忽略的 key:当前角色下不可见的管理员专属列 // 计算"全选"状态时应忽略的 key:当前角色下不可见的管理员专属列
@@ -18,7 +18,6 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useEffect, useMemo, useState } from 'react'; import React, { useEffect, useMemo, useState } from 'react';
import * as XLSX from 'xlsx';
import { Modal, Button, Checkbox, Radio, RadioGroup } from '@douyinfe/semi-ui'; import { Modal, Button, Checkbox, Radio, RadioGroup } from '@douyinfe/semi-ui';
import { CheckSquare, Eraser, FileSpreadsheet, X } from 'lucide-react'; import { CheckSquare, Eraser, FileSpreadsheet, X } from 'lucide-react';
import { import {
@@ -232,7 +231,7 @@ const UsageLogsExportModal = ({
// 不用可能过期的 logCount 来禁用按钮(避免编辑筛选未查询时被误禁用) // 不用可能过期的 logCount 来禁用按钮(避免编辑筛选未查询时被误禁用)
const pageNoData = scope === 'page' && pageCount === 0; const pageNoData = scope === 'page' && pageCount === 0;
const buildSheet = (rows, fields, header) => { const buildSheet = (XLSX, rows, fields, header) => {
const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r, t)))]; const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r, t)))];
const ws = XLSX.utils.aoa_to_sheet(aoa); const ws = XLSX.utils.aoa_to_sheet(aoa);
ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 })); ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 }));
@@ -267,10 +266,11 @@ const UsageLogsExportModal = ({
return; return;
} }
const header = fields.map((f) => t(f.label)); const header = fields.map((f) => t(f.label));
const XLSX = await import('xlsx');
const wb = XLSX.utils.book_new(); const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet( XLSX.utils.book_append_sheet(
wb, wb,
buildSheet(rows, fields, header), buildSheet(XLSX, rows, fields, header),
t('消耗明细'), t('消耗明细'),
); );
XLSX.writeFile(wb, buildExportFilename()); XLSX.writeFile(wb, buildExportFilename());
+2
View File
@@ -110,6 +110,8 @@ const UsersPage = () => {
total: usersData.userCount, total: usersData.userCount,
onPageChange: usersData.handlePageChange, onPageChange: usersData.handlePageChange,
onPageSizeChange: usersData.handlePageSizeChange, onPageSizeChange: usersData.handlePageSizeChange,
// The size handler resets to page 1; skip Semi's automatic page callback.
preventPageChangeOnPageSizeChange: true,
isMobile: isMobile, isMobile: isMobile,
t: usersData.t, t: usersData.t,
})} })}
+13
View File
@@ -54,3 +54,16 @@ export const DELEGATABLE_SETTING_TABS = SETTING_TABS.filter(
!ALWAYS_ADMIN_VISIBLE_TABS.includes(t.key) && !ALWAYS_ADMIN_VISIBLE_TABS.includes(t.key) &&
!ROOT_ONLY_SETTING_TABS.includes(t.key), !ROOT_ONLY_SETTING_TABS.includes(t.key),
); );
// Standalone admin pages share delegation settings, but are not settings tabs.
export const DELEGATABLE_ADMIN_PAGES = [
{ key: 'website-setting', labelKey: '官网设置' },
{ key: 'demo-reservations', labelKey: '预约演示' },
];
export const ADMIN_DELEGATION_OPTIONS = [
...DELEGATABLE_SETTING_TABS,
...DELEGATABLE_ADMIN_PAGES,
];
export const ADMIN_DELEGATION_OPTION_KEY = 'AdminDelegatedSettingTabs';
+2
View File
@@ -67,6 +67,8 @@ export const getDefaultSidebarModulesAdmin = () => ({
order: true, order: true,
invoice: true, invoice: true,
setting: true, setting: true,
'website-setting': true,
'demo-reservations': true,
}, },
analytics: { analytics: {
enabled: true, enabled: true,
@@ -17,10 +17,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { createContext, useContext } from 'react'; import { createContext, createElement, useContext } from 'react';
/** /**
* Context for Playground component to share image handling functionality * Share Playground input, upload, search, and image generation functionality.
*/ */
const PlaygroundContext = createContext(null); const PlaygroundContext = createContext(null);
@@ -73,11 +73,7 @@ export const usePlayground = () => {
* @returns {JSX.Element} Provider component * @returns {JSX.Element} Provider component
*/ */
export const PlaygroundProvider = ({ children, value }) => { export const PlaygroundProvider = ({ children, value }) => {
return ( return createElement(PlaygroundContext.Provider, { value }, children);
<PlaygroundContext.Provider value={value}>
{children}
</PlaygroundContext.Provider>
);
}; };
export default PlaygroundContext; export default PlaygroundContext;
+50
View File
@@ -0,0 +1,50 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
DELEGATABLE_ADMIN_PAGES,
DELEGATABLE_SETTING_TABS,
} from '../constants/settingTabs.js';
export function parseAdminDelegation(raw) {
try {
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
return Array.isArray(parsed)
? [...new Set(parsed.filter((key) => typeof key === 'string'))]
: [];
} catch {
return [];
}
}
export function getDelegatedSettingTabs(raw) {
return parseAdminDelegation(raw).filter((key) =>
DELEGATABLE_SETTING_TABS.some((tab) => tab.key === key),
);
}
export function canAccessDelegatedAdminPage(role, raw, permission) {
if (typeof role !== 'number' || !Number.isFinite(role) || role < 10) {
return false;
}
if (!DELEGATABLE_ADMIN_PAGES.some((page) => page.key === permission)) {
return false;
}
return role >= 100 || parseAdminDelegation(raw).includes(permission);
}
+20 -1
View File
@@ -21,6 +21,9 @@ import React, { useContext } from 'react';
import { Navigate, useLocation } from 'react-router-dom'; import { Navigate, useLocation } from 'react-router-dom';
import { history } from './history'; import { history } from './history';
import { UserContext } from '../context/User'; import { UserContext } from '../context/User';
import { StatusContext } from '../context/Status';
import { canAccessDelegatedAdminPage } from './adminDelegation';
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
import Loading from '../components/common/ui/Loading'; import Loading from '../components/common/ui/Loading';
import { import {
DEFAULT_LOGIN_REDIRECT, DEFAULT_LOGIN_REDIRECT,
@@ -95,8 +98,9 @@ function PrivateRoute({ children }) {
); );
} }
export function AdminRoute({ children }) { export function AdminRoute({ children, permission }) {
const [userState] = useContext(UserContext); const [userState] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const location = useLocation(); const location = useLocation();
const cachedUser = getUserData(); const cachedUser = getUserData();
@@ -113,6 +117,21 @@ export function AdminRoute({ children }) {
); );
} }
if (typeof userState.user.role === 'number' && userState.user.role >= 10) { if (typeof userState.user.role === 'number' && userState.user.role >= 10) {
if (permission) {
// Wait for server permissions before deciding access for delegated admins.
if (userState.user.role < 100 && !statusState?.status) {
return <Loading />;
}
if (
!canAccessDelegatedAdminPage(
userState.user.role,
statusState?.status?.[ADMIN_DELEGATION_OPTION_KEY],
permission,
)
) {
return <Navigate to='/forbidden' replace />;
}
}
return children; return children;
} }
return <Navigate to='/forbidden' replace />; return <Navigate to='/forbidden' replace />;
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { parseStoredObject } from './storageJson.js';
// Resolve raw localStorage JSON without mutating defaults or performing I/O.
export const resolveColumnVisibility = (
defaults,
savedColumns,
hiddenKeys = [],
) => {
const resolved = { ...defaults };
const preferences = parseStoredObject(savedColumns);
for (const key of Object.keys(defaults)) {
if (
Object.prototype.hasOwnProperty.call(preferences, key) &&
typeof preferences[key] === 'boolean'
) {
resolved[key] = preferences[key];
}
}
// Role restrictions take precedence over saved preferences.
for (const key of hiddenKeys) {
resolved[key] = false;
}
return resolved;
};
+149
View File
@@ -0,0 +1,149 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { resolveColumnVisibility } from './columnVisibility.js';
const defaults = Object.freeze({ time: true, model: true, channel: false });
test('missing or malformed saved JSON falls back to a fresh copy of defaults', () => {
for (const saved of [
undefined,
null,
'',
'{',
'not-json',
'{"time":false,}',
]) {
const resolved = resolveColumnVisibility(defaults, saved);
assert.deepEqual(resolved, defaults);
assert.notStrictEqual(resolved, defaults);
}
});
test('null, arrays, and primitive JSON values are not preference maps', () => {
for (const saved of [
'null',
'[]',
'[false]',
'"text"',
'0',
'true',
'false',
]) {
assert.deepEqual(resolveColumnVisibility(defaults, saved), defaults);
}
});
test('non-string saved data is ignored without coercion or mutation', () => {
const saved = Object.freeze({ time: false });
for (const value of [saved, [false], 1, true]) {
assert.deepEqual(resolveColumnVisibility(defaults, value), defaults);
}
assert.deepEqual(saved, { time: false });
});
test('saved false and true values override defaults while new columns keep defaults', () => {
assert.deepEqual(
resolveColumnVisibility(defaults, '{"time":false,"channel":true}'),
{ time: false, model: true, channel: true },
);
assert.deepEqual(resolveColumnVisibility(defaults, '{}'), defaults);
});
test('invalid individual preferences keep defaults without discarding valid booleans', () => {
for (const value of [null, 0, 1, '', 'false', [], {}]) {
assert.deepEqual(
resolveColumnVisibility(
defaults,
JSON.stringify({ time: value, channel: value, model: false }),
),
{ time: true, model: false, channel: false },
);
}
});
test('unknown and prototype-related saved keys do not enter the result', () => {
const resolved = resolveColumnVisibility(
defaults,
'{"time":false,"removedColumn":true,"__proto__":{"polluted":true},"constructor":false,"toString":false}',
);
assert.deepEqual(resolved, { time: false, model: true, channel: false });
assert.equal(Object.getPrototypeOf(resolved), Object.prototype);
assert.equal(Object.hasOwn(resolved, '__proto__'), false);
});
for (const [table, restrictedKeys] of [
['usage logs', ['channel', 'username', 'retry']],
['task logs', ['channel']],
]) {
for (const isAdmin of [true, false]) {
test(`${table}: ${isAdmin ? 'admin' : 'non-admin'} preferences respect role restrictions`, () => {
const roleDefaults = {
model: true,
...Object.fromEntries(restrictedKeys.map((key) => [key, isAdmin])),
};
const hiddenKeys = isAdmin ? [] : restrictedKeys;
for (const checked of [true, false]) {
const preferences = {
model: false,
...Object.fromEntries(restrictedKeys.map((key) => [key, checked])),
};
const resolved = resolveColumnVisibility(
roleDefaults,
JSON.stringify(preferences),
hiddenKeys,
);
assert.equal(resolved.model, false);
for (const key of restrictedKeys) {
assert.equal(resolved[key], isAdmin && checked);
}
}
assert.deepEqual(
resolveColumnVisibility(roleDefaults, null, hiddenKeys),
roleDefaults,
);
});
}
}
test('forced-hidden keys apply even when saved preferences are missing or invalid', () => {
for (const saved of [null, '{', 'null', '[]', '{}', '{"time":true}']) {
assert.deepEqual(resolveColumnVisibility(defaults, saved, ['time']), {
time: false,
model: true,
channel: false,
});
}
});
test('resolution never mutates defaults or hidden keys and returns independent results', () => {
const hiddenKeys = Object.freeze(['channel']);
const saved = '{"time":false,"channel":true}';
const first = resolveColumnVisibility(defaults, saved, hiddenKeys);
const second = resolveColumnVisibility(defaults, saved, hiddenKeys);
assert.notStrictEqual(first, second);
first.model = false;
assert.deepEqual(second, { time: false, model: true, channel: false });
assert.deepEqual(defaults, { time: true, model: true, channel: false });
assert.deepEqual(hiddenKeys, ['channel']);
assert.equal(saved, '{"time":false,"channel":true}');
});
+1 -5
View File
@@ -18,9 +18,5 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
export function getServerURL() { export function getServerURL() {
return ( return import.meta.env.VITE_REACT_APP_SERVER_URL || '';
window.__APP_CONFIG__?.SERVER_URL ||
import.meta.env.VITE_REACT_APP_SERVER_URL ||
''
);
} }
+58
View File
@@ -0,0 +1,58 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { transformWithEsbuild } from 'vite';
const source = await readFile(new URL('./config.js', import.meta.url), 'utf8');
async function loadConfig(env) {
const { code } = await transformWithEsbuild(source, 'config.js', {
loader: 'js',
define: { 'import.meta.env': JSON.stringify(env) },
});
return import(
`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
);
}
for (const [name, env, expected] of [
['missing backend URL uses same origin', {}, ''],
['empty backend URL uses same origin', { VITE_REACT_APP_SERVER_URL: '' }, ''],
[
'configured backend URL works without a window global',
{ VITE_REACT_APP_SERVER_URL: 'https://api.example.com' },
'https://api.example.com',
],
]) {
test(name, async () => {
const { getServerURL } = await loadConfig(env);
assert.equal(getServerURL(), expected);
});
}
test('HTML no longer loads the removed runtime configuration script', async () => {
const html = await readFile(
new URL('../../index.html', import.meta.url),
'utf8',
);
assert.doesNotMatch(html, /<script\b[^>]*\bsrc=["']\/config\.js["']/i);
});
+51
View File
@@ -0,0 +1,51 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { parseStoredArray, readStorageValue } from './storageJson.js';
export const NOTICE_READ_KEYS_KEY = 'notice_read_keys';
export const getAnnouncementKey = (announcement) =>
`${announcement?.publishDate || ''}-${(announcement?.content || '').slice(0, 30)}`;
export function getUnreadAnnouncementKeys(announcements, readKeys) {
const readSet = new Set(readKeys);
return announcements
.map(getAnnouncementKey)
.filter((key) => !readSet.has(key));
}
export function mergeAnnouncementReadKeys(announcements, readKeys) {
return Array.from(
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
);
}
export function readNoticeReadKeys() {
return parseStoredArray(readStorageValue(NOTICE_READ_KEYS_KEY));
}
export function markAnnouncementsRead(announcements) {
const mergedKeys = mergeAnnouncementReadKeys(
announcements,
readNoticeReadKeys(),
);
// Let write failures propagate so callers do not report unread items as saved.
localStorage.setItem(NOTICE_READ_KEYS_KEY, JSON.stringify(mergedKeys));
}
+34
View File
@@ -0,0 +1,34 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/** Map the shared consumption filters without adding endpoint-specific options. */
export function buildOrgLogFilters({
userId,
startTimestamp,
endTimestamp,
modelName,
} = {}) {
const params = {};
// Preserve the API callers' existing omission of empty values (including zero).
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
return params;
}
+75
View File
@@ -0,0 +1,75 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildOrgLogFilters } from './orgLogFilters.js';
test('consumption filters map to the existing API field names', () => {
const filters = Object.freeze({
userId: 42,
startTimestamp: 1700000000,
endTimestamp: 1700003600,
modelName: 'example/model + preview',
});
assert.deepEqual(buildOrgLogFilters(filters), {
user_id: 42,
start_timestamp: 1700000000,
end_timestamp: 1700003600,
model_name: 'example/model + preview',
});
});
test('empty filters and existing falsy values are omitted', () => {
assert.deepEqual(buildOrgLogFilters(), {});
for (const value of [undefined, null, '', 0, false, NaN]) {
assert.deepEqual(
buildOrgLogFilters({
userId: value,
startTimestamp: value,
endTimestamp: value,
modelName: value,
}),
{},
);
}
});
test('partial filters preserve values without coercion', () => {
assert.deepEqual(buildOrgLogFilters({ userId: '0', modelName: 'a&b' }), {
user_id: '0',
model_name: 'a&b',
});
});
test('endpoint-specific parameters cannot leak into shared filters', () => {
const filters = Object.freeze({
userId: 42,
limit: 10,
nocache: 1,
p: 5,
page_size: 20,
memberId: 7,
});
const params = buildOrgLogFilters(filters);
assert.deepEqual(params, { user_id: 42 });
params.limit = 15;
assert.deepEqual(buildOrgLogFilters(filters), { user_id: 42 });
assert.equal(filters.limit, 10);
});
+86 -180
View File
@@ -17,81 +17,46 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { lazy, Suspense } from 'react';
import i18next from 'i18next'; import i18next from 'i18next';
// React 18-compatible LobeHub icons lack these brands; use generic icons. // React 18-compatible LobeHub icons lack these brands; use generic icons.
import { Lock, Bot as FastGPT, Image as Jimeng } from 'lucide-react'; import { Lock, Bot as FastGPT, Image as Jimeng } from 'lucide-react';
import { Modal, Tag, Typography, Avatar } from '@douyinfe/semi-ui'; import { Modal, Tag, Typography } from '@douyinfe/semi-ui';
import { copy, getCurrencySymbol, showSuccess } from './utils'; import { copy, getCurrencySymbol, showSuccess } from './utils';
import { visit } from 'unist-util-visit'; import { visit } from 'unist-util-visit';
import { import OpenAI from '@lobehub/icons/es/OpenAI/components/Mono';
OpenAI, import Claude from '@lobehub/icons/es/Claude/components/Color';
Claude, import Gemini from '@lobehub/icons/es/Gemini/components/Color';
Gemini, import Moonshot from '@lobehub/icons/es/Moonshot/components/Mono';
Moonshot, import Zhipu from '@lobehub/icons/es/Zhipu/components/Color';
Zhipu, import Qwen from '@lobehub/icons/es/Qwen/components/Color';
Qwen, import DeepSeek from '@lobehub/icons/es/DeepSeek/components/Color';
DeepSeek, import Minimax from '@lobehub/icons/es/Minimax/components/Color';
Minimax, import Wenxin from '@lobehub/icons/es/Wenxin/components/Color';
Wenxin, import Spark from '@lobehub/icons/es/Spark/components/Color';
Spark, import Midjourney from '@lobehub/icons/es/Midjourney/components/Mono';
Midjourney, import Hunyuan from '@lobehub/icons/es/Hunyuan/components/Color';
Hunyuan, import Cohere from '@lobehub/icons/es/Cohere/components/Color';
Cohere, import Cloudflare from '@lobehub/icons/es/Cloudflare/components/Color';
Cloudflare, import Ai360 from '@lobehub/icons/es/Ai360/components/Color';
Ai360, import Yi from '@lobehub/icons/es/Yi/components/Color';
Yi, import Jina from '@lobehub/icons/es/Jina/components/Mono';
Jina, import Mistral from '@lobehub/icons/es/Mistral/components/Color';
Mistral, import XAI from '@lobehub/icons/es/XAI/components/Mono';
XAI, import Ollama from '@lobehub/icons/es/Ollama/components/Mono';
Ollama, import Doubao from '@lobehub/icons/es/Doubao/components/Color';
Doubao, import Suno from '@lobehub/icons/es/Suno/components/Mono';
Suno, import Xinference from '@lobehub/icons/es/Xinference/components/Color';
Xinference, import OpenRouter from '@lobehub/icons/es/OpenRouter/components/Mono';
OpenRouter, import Dify from '@lobehub/icons/es/Dify/components/Color';
Dify, import Coze from '@lobehub/icons/es/Coze/components/Mono';
Coze, import SiliconCloud from '@lobehub/icons/es/SiliconCloud/components/Color';
SiliconCloud, import Kling from '@lobehub/icons/es/Kling/components/Color';
Kling, import Perplexity from '@lobehub/icons/es/Perplexity/components/Color';
Perplexity, import Replicate from '@lobehub/icons/es/Replicate/components/Mono';
Replicate,
} from '@lobehub/icons';
// 创建图标映射表,避免使用 import * 导致整个库被打包 // Full Avatar/Text/Combine variants are loaded only when configured icons render.
// 只包含实际在库中存在的图标 const LobeHubIcon = lazy(() => import('../components/common/LobeHubIcon'));
const LobeIconsMap = {
OpenAI,
Claude,
Gemini,
Moonshot,
Zhipu,
Qwen,
DeepSeek,
Minimax,
Wenxin,
Spark,
Midjourney,
Hunyuan,
Cohere,
Cloudflare,
Ai360,
Yi,
Jina,
Mistral,
XAI,
Ollama,
Doubao,
Suno,
Xinference,
OpenRouter,
Dify,
Coze,
SiliconCloud,
FastGPT,
Kling,
Jimeng,
Perplexity,
Replicate,
};
import { import {
LayoutDashboard, LayoutDashboard,
@@ -112,6 +77,8 @@ import {
PieChart, PieChart,
Building2, Building2,
Handshake, Handshake,
Globe,
CalendarDays,
} from 'lucide-react'; } from 'lucide-react';
// 获取侧边栏Lucide图标组件 // 获取侧边栏Lucide图标组件
@@ -163,6 +130,10 @@ export function getLucideIcon(key, selected = false) {
return <Handshake {...commonProps} color={iconColor} />; return <Handshake {...commonProps} color={iconColor} />;
case 'setting': case 'setting':
return <Settings {...commonProps} color={iconColor} />; return <Settings {...commonProps} color={iconColor} />;
case 'website-setting':
return <Globe {...commonProps} color={iconColor} />;
case 'demo-reservations':
return <CalendarDays {...commonProps} color={iconColor} />;
default: default:
return <CircleUser {...commonProps} color={iconColor} />; return <CircleUser {...commonProps} color={iconColor} />;
} }
@@ -205,12 +176,12 @@ export const getModelCategories = (() => {
}, },
anthropic: { anthropic: {
label: 'Anthropic', label: 'Anthropic',
icon: <Claude.Color />, icon: <Claude />,
filter: (model) => model.model_name.toLowerCase().includes('claude'), filter: (model) => model.model_name.toLowerCase().includes('claude'),
}, },
gemini: { gemini: {
label: 'Gemini', label: 'Gemini',
icon: <Gemini.Color />, icon: <Gemini />,
filter: (model) => filter: (model) =>
model.model_name.toLowerCase().includes('gemini') || model.model_name.toLowerCase().includes('gemini') ||
model.model_name.toLowerCase().includes('gemma') || model.model_name.toLowerCase().includes('gemma') ||
@@ -230,7 +201,7 @@ export const getModelCategories = (() => {
}, },
zhipu: { zhipu: {
label: t('智谱'), label: t('智谱'),
icon: <Zhipu.Color />, icon: <Zhipu />,
filter: (model) => filter: (model) =>
model.model_name.toLowerCase().includes('chatglm') || model.model_name.toLowerCase().includes('chatglm') ||
model.model_name.toLowerCase().includes('glm-') || model.model_name.toLowerCase().includes('glm-') ||
@@ -239,29 +210,29 @@ export const getModelCategories = (() => {
}, },
qwen: { qwen: {
label: t('通义千问'), label: t('通义千问'),
icon: <Qwen.Color />, icon: <Qwen />,
filter: (model) => model.model_name.toLowerCase().includes('qwen'), filter: (model) => model.model_name.toLowerCase().includes('qwen'),
}, },
deepseek: { deepseek: {
label: 'DeepSeek', label: 'DeepSeek',
icon: <DeepSeek.Color />, icon: <DeepSeek />,
filter: (model) => model.model_name.toLowerCase().includes('deepseek'), filter: (model) => model.model_name.toLowerCase().includes('deepseek'),
}, },
minimax: { minimax: {
label: 'MiniMax', label: 'MiniMax',
icon: <Minimax.Color />, icon: <Minimax />,
filter: (model) => filter: (model) =>
model.model_name.toLowerCase().includes('abab') || model.model_name.toLowerCase().includes('abab') ||
model.model_name.toLowerCase().includes('minimax'), model.model_name.toLowerCase().includes('minimax'),
}, },
baidu: { baidu: {
label: t('文心一言'), label: t('文心一言'),
icon: <Wenxin.Color />, icon: <Wenxin />,
filter: (model) => model.model_name.toLowerCase().includes('ernie'), filter: (model) => model.model_name.toLowerCase().includes('ernie'),
}, },
xunfei: { xunfei: {
label: t('讯飞星火'), label: t('讯飞星火'),
icon: <Spark.Color />, icon: <Spark />,
filter: (model) => model.model_name.toLowerCase().includes('spark'), filter: (model) => model.model_name.toLowerCase().includes('spark'),
}, },
midjourney: { midjourney: {
@@ -271,12 +242,12 @@ export const getModelCategories = (() => {
}, },
tencent: { tencent: {
label: t('腾讯混元'), label: t('腾讯混元'),
icon: <Hunyuan.Color />, icon: <Hunyuan />,
filter: (model) => model.model_name.toLowerCase().includes('hunyuan'), filter: (model) => model.model_name.toLowerCase().includes('hunyuan'),
}, },
cohere: { cohere: {
label: 'Cohere', label: 'Cohere',
icon: <Cohere.Color />, icon: <Cohere />,
filter: (model) => filter: (model) =>
model.model_name.toLowerCase().includes('command') || model.model_name.toLowerCase().includes('command') ||
model.model_name.toLowerCase().includes('c4ai-') || model.model_name.toLowerCase().includes('c4ai-') ||
@@ -284,12 +255,12 @@ export const getModelCategories = (() => {
}, },
cloudflare: { cloudflare: {
label: 'Cloudflare', label: 'Cloudflare',
icon: <Cloudflare.Color />, icon: <Cloudflare />,
filter: (model) => model.model_name.toLowerCase().includes('@cf/'), filter: (model) => model.model_name.toLowerCase().includes('@cf/'),
}, },
ai360: { ai360: {
label: t('360智脑'), label: t('360智脑'),
icon: <Ai360.Color />, icon: <Ai360 />,
filter: (model) => model.model_name.toLowerCase().includes('360'), filter: (model) => model.model_name.toLowerCase().includes('360'),
}, },
jina: { jina: {
@@ -299,7 +270,7 @@ export const getModelCategories = (() => {
}, },
mistral: { mistral: {
label: 'Mistral AI', label: 'Mistral AI',
icon: <Mistral.Color />, icon: <Mistral />,
filter: (model) => filter: (model) =>
model.model_name.toLowerCase().includes('mistral') || model.model_name.toLowerCase().includes('mistral') ||
model.model_name.toLowerCase().includes('codestral') || model.model_name.toLowerCase().includes('codestral') ||
@@ -319,12 +290,12 @@ export const getModelCategories = (() => {
}, },
doubao: { doubao: {
label: t('豆包'), label: t('豆包'),
icon: <Doubao.Color />, icon: <Doubao />,
filter: (model) => model.model_name.toLowerCase().includes('doubao'), filter: (model) => model.model_name.toLowerCase().includes('doubao'),
}, },
yi: { yi: {
label: t('零一万物'), label: t('零一万物'),
icon: <Yi.Color />, icon: <Yi />,
filter: (model) => model.model_name.toLowerCase().includes('yi'), filter: (model) => model.model_name.toLowerCase().includes('yi'),
}, },
}; };
@@ -355,64 +326,64 @@ export function getChannelIcon(channelType) {
return <Ollama size={iconSize} />; return <Ollama size={iconSize} />;
case 14: // Anthropic Claude case 14: // Anthropic Claude
case 33: // AWS Claude case 33: // AWS Claude
return <Claude.Color size={iconSize} />; return <Claude size={iconSize} />;
case 41: // Vertex AI case 41: // Vertex AI
return <Gemini.Color size={iconSize} />; return <Gemini size={iconSize} />;
case 34: // Cohere case 34: // Cohere
return <Cohere.Color size={iconSize} />; return <Cohere size={iconSize} />;
case 39: // Cloudflare case 39: // Cloudflare
return <Cloudflare.Color size={iconSize} />; return <Cloudflare size={iconSize} />;
case 43: // DeepSeek case 43: // DeepSeek
return <DeepSeek.Color size={iconSize} />; return <DeepSeek size={iconSize} />;
case 15: // 百度文心千帆 case 15: // 百度文心千帆
case 46: // 百度文心千帆V2 case 46: // 百度文心千帆V2
return <Wenxin.Color size={iconSize} />; return <Wenxin size={iconSize} />;
case 17: // 阿里通义千问 case 17: // 阿里通义千问
return <Qwen.Color size={iconSize} />; return <Qwen size={iconSize} />;
case 18: // 讯飞星火认知 case 18: // 讯飞星火认知
return <Spark.Color size={iconSize} />; return <Spark size={iconSize} />;
case 16: // 智谱 ChatGLM case 16: // 智谱 ChatGLM
case 26: // 智谱 GLM-4V case 26: // 智谱 GLM-4V
return <Zhipu.Color size={iconSize} />; return <Zhipu size={iconSize} />;
case 24: // Google Gemini case 24: // Google Gemini
case 11: // Google PaLM2 case 11: // Google PaLM2
return <Gemini.Color size={iconSize} />; return <Gemini size={iconSize} />;
case 47: // Xinference case 47: // Xinference
return <Xinference.Color size={iconSize} />; return <Xinference size={iconSize} />;
case 25: // Moonshot case 25: // Moonshot
return <Moonshot size={iconSize} />; return <Moonshot size={iconSize} />;
case 27: // Perplexity case 27: // Perplexity
return <Perplexity.Color size={iconSize} />; return <Perplexity size={iconSize} />;
case 20: // OpenRouter case 20: // OpenRouter
return <OpenRouter size={iconSize} />; return <OpenRouter size={iconSize} />;
case 19: // 360 智脑 case 19: // 360 智脑
return <Ai360.Color size={iconSize} />; return <Ai360 size={iconSize} />;
case 23: // 腾讯混元 case 23: // 腾讯混元
return <Hunyuan.Color size={iconSize} />; return <Hunyuan size={iconSize} />;
case 31: // 零一万物 case 31: // 零一万物
return <Yi.Color size={iconSize} />; return <Yi size={iconSize} />;
case 35: // MiniMax case 35: // MiniMax
return <Minimax.Color size={iconSize} />; return <Minimax size={iconSize} />;
case 37: // Dify case 37: // Dify
return <Dify.Color size={iconSize} />; return <Dify size={iconSize} />;
case 38: // Jina case 38: // Jina
return <Jina size={iconSize} />; return <Jina size={iconSize} />;
case 40: // SiliconCloud case 40: // SiliconCloud
return <SiliconCloud.Color size={iconSize} />; return <SiliconCloud size={iconSize} />;
case 42: // Mistral AI case 42: // Mistral AI
return <Mistral.Color size={iconSize} />; return <Mistral size={iconSize} />;
case 45: // 字节火山方舟、豆包通用 case 45: // 字节火山方舟、豆包通用
return <Doubao.Color size={iconSize} />; return <Doubao size={iconSize} />;
case 48: // xAI case 48: // xAI
return <XAI size={iconSize} />; return <XAI size={iconSize} />;
case 49: // Coze case 49: // Coze
return <Coze size={iconSize} />; return <Coze size={iconSize} />;
case 50: // 可灵 Kling case 50: // 可灵 Kling
return <Kling.Color size={iconSize} />; return <Kling size={iconSize} />;
case 51: // 即梦 Jimeng case 51: // 即梦 Jimeng
return <Jimeng size={iconSize} />; return <Jimeng size={iconSize} />;
case 54: // 豆包视频 Doubao Video case 54: // 豆包视频 Doubao Video
return <Doubao.Color size={iconSize} />; return <Doubao size={iconSize} />;
case 56: // Replicate case 56: // Replicate
return <Replicate size={iconSize} />; return <Replicate size={iconSize} />;
case 8: // 自定义渠道 case 8: // 自定义渠道
@@ -436,80 +407,15 @@ export function getChannelIcon(channelType) {
* @returns {JSX.Element} - 对应的图标组件或 Avatar * @returns {JSX.Element} - 对应的图标组件或 Avatar
*/ */
export function getLobeHubIcon(iconName, size = 14) { export function getLobeHubIcon(iconName, size = 14) {
if (typeof iconName === 'string') iconName = iconName.trim(); return (
// 如果没有图标名称,返回 Avatar <Suspense
if (!iconName) { fallback={
return <Avatar size='extra-extra-small'>?</Avatar>; <span style={{ display: 'inline-block', width: size, height: size }} />
} }
>
// 解析组件路径与点号链式属性 <LobeHubIcon iconName={iconName} size={size} />
const segments = String(iconName).split('.'); </Suspense>
const baseKey = segments[0]; );
const BaseIcon = LobeIconsMap[baseKey];
let IconComponent = undefined;
let propStartIndex = 1;
if (BaseIcon && segments.length > 1 && BaseIcon[segments[1]]) {
IconComponent = BaseIcon[segments[1]];
propStartIndex = 2;
} else {
IconComponent = LobeIconsMap[baseKey];
propStartIndex = 1;
}
// 失败兜底
if (
!IconComponent ||
(typeof IconComponent !== 'function' && typeof IconComponent !== 'object')
) {
const firstLetter = String(iconName).charAt(0).toUpperCase();
return <Avatar size='extra-extra-small'>{firstLetter}</Avatar>;
}
// 解析点号链式属性,形如:key={...}、key='...'、key="..."、key=123、key、key=true/false
const props = {};
const parseValue = (raw) => {
if (raw == null) return true;
let v = String(raw).trim();
// 去除一层花括号包裹
if (v.startsWith('{') && v.endsWith('}')) {
v = v.slice(1, -1).trim();
}
// 去除引号
if (
(v.startsWith('"') && v.endsWith('"')) ||
(v.startsWith("'") && v.endsWith("'"))
) {
return v.slice(1, -1);
}
// 布尔
if (v === 'true') return true;
if (v === 'false') return false;
// 数字
if (/^-?\d+(?:\.\d+)?$/.test(v)) return Number(v);
// 其他原样返回字符串
return v;
};
for (let i = propStartIndex; i < segments.length; i++) {
const seg = segments[i];
if (!seg) continue;
const eqIdx = seg.indexOf('=');
if (eqIdx === -1) {
props[seg.trim()] = true;
continue;
}
const key = seg.slice(0, eqIdx).trim();
const valRaw = seg.slice(eqIdx + 1).trim();
props[key] = parseValue(valRaw);
}
// 兼容第二参数 size,若字符串中未显式指定 size,则使用函数入参
if (props.size == null && size != null) props.size = size;
return <IconComponent {...props} />;
} }
// 颜色列表 // 颜色列表
+49
View File
@@ -0,0 +1,49 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
function parseStoredJson(json, isValid, fallback) {
if (typeof json !== 'string') return fallback;
try {
const value = JSON.parse(json);
return isValid(value) ? value : fallback;
} catch {
return fallback;
}
}
export function parseStoredArray(json) {
return parseStoredJson(json, Array.isArray, []);
}
export function parseStoredObject(json) {
return parseStoredJson(
json,
(value) =>
value !== null && typeof value === 'object' && !Array.isArray(value),
{},
);
}
export function readStorageValue(key) {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
+300
View File
@@ -0,0 +1,300 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import {
parseStoredArray,
parseStoredObject,
readStorageValue,
} from './storageJson.js';
import {
getAnnouncementKey,
getUnreadAnnouncementKeys,
markAnnouncementsRead,
mergeAnnouncementReadKeys,
NOTICE_READ_KEYS_KEY,
readNoticeReadKeys,
} from './notificationReadState.js';
import {
getTableCompactMode,
parseTableCompactMode,
setTableCompactMode,
} from './tableCompactMode.js';
import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
function mockStorage(t, storage) {
const descriptor = Object.getOwnPropertyDescriptor(
globalThis,
'localStorage',
);
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: storage,
});
t.after(() => {
if (descriptor) {
Object.defineProperty(globalThis, 'localStorage', descriptor);
} else {
delete globalThis.localStorage;
}
});
}
const invalidJson = [
null,
undefined,
'',
'{broken',
'null',
'true',
'42',
'"text"',
];
test('stored arrays reject malformed JSON and non-array values', () => {
for (const json of [...invalidJson, '{}', '{"0":"notice"}']) {
assert.deepEqual(parseStoredArray(json), [], String(json));
}
});
test('stored objects reject malformed JSON and non-object values', () => {
for (const json of [...invalidJson, '[]', '[true]']) {
assert.deepEqual(parseStoredObject(json), {}, String(json));
}
});
test('valid stored containers keep their values without coercion or filtering', () => {
const array = ['notice', 'notice', null, 1];
const object = { global: true, tokens: false, other: 'yes' };
assert.deepEqual(parseStoredArray(JSON.stringify(array)), array);
assert.deepEqual(parseStoredObject(JSON.stringify(object)), object);
});
test('fallback containers are fresh for each parse', () => {
const array = parseStoredArray(null);
const object = parseStoredObject(null);
array.push('notice');
object.global = true;
assert.deepEqual(parseStoredArray(null), []);
assert.deepEqual(parseStoredObject(null), {});
});
test('storage reads return the original stored value', (t) => {
mockStorage(t, {
getItem(key) {
assert.equal(key, 'preference');
return 'stored';
},
});
assert.equal(readStorageValue('preference'), 'stored');
});
test('storage read failures fall back to null', (t) => {
mockStorage(t, {
getItem() {
throw new Error('Storage blocked');
},
});
assert.equal(readStorageValue('preference'), null);
assert.deepEqual(readNoticeReadKeys(), []);
assert.equal(getTableCompactMode(), false);
});
test('announcement identity keeps the date and first 30 content characters', () => {
assert.equal(
getAnnouncementKey({ publishDate: '2025-01-01', content: 'a'.repeat(40) }),
`2025-01-01-${'a'.repeat(30)}`,
);
assert.equal(getAnnouncementKey({}), '-');
assert.equal(getAnnouncementKey(null), '-');
});
const first = { publishDate: '2025-01-01', content: 'First' };
const second = { publishDate: '2025-01-02', content: 'Second' };
test('unread keys preserve announcement order and duplicate counts', () => {
const notices = [first, second, second];
const readKeys = [getAnnouncementKey(first)];
assert.deepEqual(getUnreadAnnouncementKeys(notices, readKeys), [
getAnnouncementKey(second),
getAnnouncementKey(second),
]);
assert.deepEqual(
getUnreadAnnouncementKeys(notices, []),
notices.map(getAnnouncementKey),
);
assert.deepEqual(
getUnreadAnnouncementKeys(notices, notices.map(getAnnouncementKey)),
[],
);
assert.deepEqual(getUnreadAnnouncementKeys([], readKeys), []);
});
test('merging read keys retains history, deduplicates, and does not mutate inputs', () => {
const notices = [first, second, first];
const readKeys = ['old', getAnnouncementKey(first), 'old'];
assert.deepEqual(mergeAnnouncementReadKeys(notices, readKeys), [
'old',
getAnnouncementKey(first),
getAnnouncementKey(second),
]);
assert.deepEqual(readKeys, ['old', getAnnouncementKey(first), 'old']);
assert.deepEqual(notices, [first, second, first]);
});
test('notification persistence uses the existing key and merges the latest stored history', (t) => {
let stored = '["old"]';
mockStorage(t, {
getItem(key) {
assert.equal(key, 'notice_read_keys');
return stored;
},
setItem(key, value) {
assert.equal(key, NOTICE_READ_KEYS_KEY);
stored = value;
},
});
markAnnouncementsRead([first, first]);
assert.deepEqual(JSON.parse(stored), ['old', getAnnouncementKey(first)]);
stored = JSON.stringify([...JSON.parse(stored), 'another-tab']);
markAnnouncementsRead([second]);
assert.deepEqual(JSON.parse(stored), [
'old',
getAnnouncementKey(first),
'another-tab',
getAnnouncementKey(second),
]);
});
test('invalid notice storage is treated as unread and can be repaired on write', (t) => {
let stored;
mockStorage(t, {
getItem: () => stored,
setItem: (_key, value) => {
stored = value;
},
});
for (const json of [...invalidJson, '{}']) {
stored = json;
assert.deepEqual(readNoticeReadKeys(), []);
assert.deepEqual(getUnreadAnnouncementKeys([first], readNoticeReadKeys()), [
getAnnouncementKey(first),
]);
markAnnouncementsRead([first]);
assert.deepEqual(JSON.parse(stored), [getAnnouncementKey(first)]);
}
});
test('notification write failures propagate instead of reporting a saved read state', (t) => {
const failure = new Error('Quota exceeded');
mockStorage(t, {
getItem: () => '[]',
setItem() {
throw failure;
},
});
assert.throws(
() => markAnnouncementsRead([first]),
(error) => error === failure,
);
});
test('compact parsing preserves global defaults, per-table selection and truthiness', () => {
const json = '{"global":true,"tokens":false,"channels":"enabled","logs":0}';
assert.equal(parseTableCompactMode(json), true);
assert.equal(parseTableCompactMode(json, 'tokens'), false);
assert.equal(parseTableCompactMode(json, 'channels'), true);
assert.equal(parseTableCompactMode(json, 'logs'), false);
assert.equal(parseTableCompactMode(json, 'missing'), false);
});
test('compact storage-event payloads use the same fallback as initial reads', (t) => {
let stored;
mockStorage(t, { getItem: () => stored });
for (const json of [...invalidJson, '[]', '[true]', '{"global":true}']) {
stored = json;
assert.equal(parseTableCompactMode(json), getTableCompactMode());
}
assert.equal(parseTableCompactMode(null), false);
});
test('compact writes preserve other table preferences and the storage key', (t) => {
let stored = '{"channels":true,"tokens":false}';
mockStorage(t, {
getItem(key) {
assert.equal(key, 'table_compact_modes');
return stored;
},
setItem(key, value) {
assert.equal(key, TABLE_COMPACT_MODES_KEY);
stored = value;
},
});
assert.equal(setTableCompactMode(true), undefined);
setTableCompactMode(true, 'tokens');
assert.deepEqual(JSON.parse(stored), {
channels: true,
tokens: true,
global: true,
});
setTableCompactMode(false, 'channels');
assert.equal(getTableCompactMode('channels'), false);
});
test('invalid compact preferences can be replaced by a valid object on write', (t) => {
let stored;
mockStorage(t, {
getItem: () => stored,
setItem: (_key, value) => {
stored = value;
},
});
for (const json of [...invalidJson, '[]', '[true]']) {
stored = json;
assert.equal(getTableCompactMode(), false);
setTableCompactMode(true);
assert.deepEqual(JSON.parse(stored), { global: true });
}
});
test('compact write failures remain non-fatal', (t) => {
mockStorage(t, {
getItem: () => '{}',
setItem() {
throw new Error('Quota exceeded');
},
});
assert.doesNotThrow(() => setTableCompactMode(true));
});
test('blocked storage access is guarded for reads and compact writes but not notice writes', (t) => {
mockStorage(t, undefined);
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
get() {
throw new Error('Storage blocked');
},
});
assert.deepEqual(readNoticeReadKeys(), []);
assert.equal(getTableCompactMode(), false);
assert.doesNotThrow(() => setTableCompactMode(true));
assert.throws(() => markAnnouncementsRead([first]), /Storage blocked/);
});
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
import { parseStoredObject, readStorageValue } from './storageJson.js';
export function parseTableCompactMode(json, tableKey = 'global') {
const modes = parseStoredObject(json);
return !!modes[tableKey];
}
export function getTableCompactMode(tableKey = 'global') {
return parseTableCompactMode(
readStorageValue(TABLE_COMPACT_MODES_KEY),
tableKey,
);
}
export function setTableCompactMode(compact, tableKey = 'global') {
const modes = parseStoredObject(readStorageValue(TABLE_COMPACT_MODES_KEY));
modes[tableKey] = compact;
try {
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
} catch {
// Compact mode remains usable in memory when preferences cannot be saved.
}
}
+21 -38
View File
@@ -26,7 +26,6 @@ import {
THINK_TAG_REGEX, THINK_TAG_REGEX,
MESSAGE_ROLES, MESSAGE_ROLES,
} from '../constants/playground.constants'; } from '../constants/playground.constants';
import { TABLE_COMPACT_MODES_KEY } from '../constants';
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile'; import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
// 官方价折扣计算(纯函数):管理端与市场页共用 // 官方价折扣计算(纯函数):管理端与市场页共用
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice'; import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
@@ -105,28 +104,33 @@ export function getUserIdFromLocalStorage() {
} }
export async function copy(text) { export async function copy(text) {
let okay = true;
try { try {
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
} catch (e) { return true;
} catch {
let textarea;
const activeElement = document.activeElement;
try { try {
// 构建 textarea 执行复制命令,保留多行文本格式 // 构建 textarea 执行复制命令,保留多行文本格式
const textarea = window.document.createElement('textarea'); textarea = window.document.createElement('textarea');
textarea.value = text; textarea.value = text;
textarea.setAttribute('readonly', ''); textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed'; textarea.style.position = 'fixed';
textarea.style.left = '-9999px'; textarea.style.left = '-9999px';
textarea.style.top = '-9999px'; textarea.style.top = '-9999px';
window.document.body.appendChild(textarea); // Keep the selection inside a modal's focus trap when copying credentials.
const container =
activeElement?.closest('[role="dialog"]') || document.body;
container.appendChild(textarea);
textarea.select(); textarea.select();
window.document.execCommand('copy'); return window.document.execCommand('copy');
window.document.body.removeChild(textarea); } catch {
} catch (e) { return false;
okay = false; } finally {
console.error(e); textarea?.remove();
activeElement?.focus({ preventScroll: true });
} }
} }
return okay;
} }
// isMobile 函数已移除,请改用 useIsMobile Hook // isMobile 函数已移除,请改用 useIsMobile Hook
@@ -735,33 +739,10 @@ export const formatDateTimeString = (date) => {
return `${year}-${month}-${day} ${hours}:${minutes}`; return `${year}-${month}-${day} ${hours}:${minutes}`;
}; };
function readTableCompactModes() { export {
try { getTableCompactMode,
const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY); setTableCompactMode,
return json ? JSON.parse(json) : {}; } from './tableCompactMode.js';
} catch {
return {};
}
}
function writeTableCompactModes(modes) {
try {
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
} catch {
// ignore
}
}
export function getTableCompactMode(tableKey = 'global') {
const modes = readTableCompactModes();
return !!modes[tableKey];
}
export function setTableCompactMode(compact, tableKey = 'global') {
const modes = readTableCompactModes();
modes[tableKey] = compact;
writeTableCompactModes(modes);
}
// ------------------------------- // -------------------------------
// Select 组件统一过滤逻辑 // Select 组件统一过滤逻辑
@@ -1111,6 +1092,7 @@ export const createCardProPagination = ({
isMobile = false, isMobile = false,
pageSizeOpts = [10, 20, 50, 100], pageSizeOpts = [10, 20, 50, 100],
showSizeChanger = true, showSizeChanger = true,
preventPageChangeOnPageSizeChange = false,
t = (key) => key, t = (key) => key,
}) => { }) => {
if (!total || total <= 0) return null; if (!total || total <= 0) return null;
@@ -1140,6 +1122,7 @@ export const createCardProPagination = ({
showSizeChanger={showSizeChanger} showSizeChanger={showSizeChanger}
onPageSizeChange={onPageSizeChange} onPageSizeChange={onPageSizeChange}
onPageChange={onPageChange} onPageChange={onPageChange}
preventPageChangeOnPageSizeChange={preventPageChangeOnPageSizeChange}
size={isMobile ? 'small' : 'default'} size={isMobile ? 'small' : 'default'}
showQuickJumper={isMobile} showQuickJumper={isMobile}
showTotal showTotal
+48
View File
@@ -0,0 +1,48 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { API } from './api';
import { showError } from './utils';
export async function requestWebsite(
method,
url,
body,
fallback = '请求失败,请稍后重试',
) {
let response;
try {
const options = { skipErrorHandler: true, timeout: 20000 };
response =
method === 'get'
? await API.get(url, options)
: await API.post(url, body, options);
} catch (error) {
if (error.response?.status === 401) {
showError(error);
throw new Error('登录状态已失效,请重新登录');
}
if (error.response?.status === 429)
throw new Error('请求过于频繁,请稍后重试');
throw new Error(error.response?.data?.message || fallback);
}
if (response.data?.success !== true)
throw new Error(response.data?.message || fallback);
return response.data.data;
}
+16 -43
View File
@@ -17,49 +17,31 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { useState, useEffect } from 'react'; import { useState, useEffect, useCallback } from 'react';
import {
getUnreadAnnouncementKeys,
markAnnouncementsRead,
readNoticeReadKeys,
} from '../../helpers/notificationReadState.js';
const EMPTY_ANNOUNCEMENTS = [];
export const useNotifications = (statusState) => { export const useNotifications = (statusState) => {
const [noticeVisible, setNoticeVisible] = useState(false); const [noticeVisible, setNoticeVisible] = useState(false);
const [unreadCount, setUnreadCount] = useState(0); const [unreadCount, setUnreadCount] = useState(0);
const announcements = statusState?.status?.announcements || []; const announcements =
statusState?.status?.announcements || EMPTY_ANNOUNCEMENTS;
// Helper functions const getUnreadKeys = useCallback(() => {
const getAnnouncementKey = (a) =>
`${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`;
const calculateUnreadCount = () => {
if (!announcements.length) return 0;
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements.filter((a) => !readSet.has(getAnnouncementKey(a)))
.length;
};
const getUnreadKeys = () => {
if (!announcements.length) return []; if (!announcements.length) return [];
let readKeys = []; return getUnreadAnnouncementKeys(announcements, readNoticeReadKeys());
try { }, [announcements]);
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements
.filter((a) => !readSet.has(getAnnouncementKey(a)))
.map(getAnnouncementKey);
};
// Effects // Effects
useEffect(() => { useEffect(() => {
setUnreadCount(calculateUnreadCount()); setUnreadCount(getUnreadKeys().length);
}, [announcements]); }, [getUnreadKeys]);
// Actions // Actions
const handleNoticeOpen = () => { const handleNoticeOpen = () => {
@@ -69,16 +51,7 @@ export const useNotifications = (statusState) => {
const handleNoticeClose = () => { const handleNoticeClose = () => {
setNoticeVisible(false); setNoticeVisible(false);
if (announcements.length) { if (announcements.length) {
let readKeys = []; markAnnouncementsRead(announcements);
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const mergedKeys = Array.from(
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
);
localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys));
} }
setUnreadCount(0); setUnreadCount(0);
}; };
+7 -8
View File
@@ -18,8 +18,12 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { getTableCompactMode, setTableCompactMode } from '../../helpers'; import {
import { TABLE_COMPACT_MODES_KEY } from '../../constants'; getTableCompactMode,
parseTableCompactMode,
setTableCompactMode,
} from '../../helpers/tableCompactMode.js';
import { TABLE_COMPACT_MODES_KEY } from '../../constants/common.constant.js';
/** /**
* 自定义 Hook:管理表格紧凑/自适应模式 * 自定义 Hook:管理表格紧凑/自适应模式
@@ -42,12 +46,7 @@ export function useTableCompactMode(tableKey = 'global') {
useEffect(() => { useEffect(() => {
const handleStorage = (e) => { const handleStorage = (e) => {
if (e.key === TABLE_COMPACT_MODES_KEY) { if (e.key === TABLE_COMPACT_MODES_KEY) {
try { setCompactModeState(parseTableCompactMode(e.newValue, tableKey));
const modes = JSON.parse(e.newValue || '{}');
setCompactModeState(!!modes[tableKey]);
} catch {
// ignore parse error
}
} }
}; };
window.addEventListener('storage', handleStorage); window.addEventListener('storage', handleStorage);
+11 -28
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { useState, useCallback, useEffect, useRef } from 'react'; import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { showError } from '../../helpers'; import { showError } from '../../helpers';
import { buildOrgLogFilters } from '../../helpers/orgLogFilters.js';
// 获取企业X-Org-Id header // 获取企业X-Org-Id header
const getOrgHeaders = (orgId) => ({ const getOrgHeaders = (orgId) => ({
@@ -239,19 +240,15 @@ export function useOrgMemberLogs(orgId) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const fetch = useCallback( const fetch = useCallback(
async ( async (page = 1, pageSize = 20, filters = {}) => {
page = 1,
pageSize = 20,
{ userId, startTimestamp, endTimestamp, modelName } = {},
) => {
if (!orgId) return; if (!orgId) return;
setLoading(true); setLoading(true);
try { try {
const params = { p: page, page_size: pageSize }; const params = {
if (userId) params.user_id = userId; p: page,
if (startTimestamp) params.start_timestamp = startTimestamp; page_size: pageSize,
if (endTimestamp) params.end_timestamp = endTimestamp; ...buildOrgLogFilters(filters),
if (modelName) params.model_name = modelName; };
const res = await API.get('/api/org/logs', { const res = await API.get('/api/org/logs', {
headers: getOrgHeaders(orgId), headers: getOrgHeaders(orgId),
@@ -292,18 +289,11 @@ export function useOrgLogsStat(orgId) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const fetch = useCallback( const fetch = useCallback(
async ( async (filters = {}, noCache = false) => {
{ userId, startTimestamp, endTimestamp, modelName } = {},
noCache = false,
) => {
if (!orgId) return; if (!orgId) return;
setLoading(true); setLoading(true);
try { try {
const params = {}; const params = buildOrgLogFilters(filters);
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
if (noCache) params.nocache = 1; if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/stat', { const res = await API.get('/api/org/logs/stat', {
@@ -346,18 +336,11 @@ export function useOrgMemberRanking(orgId) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const fetch = useCallback( const fetch = useCallback(
async ( async ({ limit, ...filters } = {}, noCache = false) => {
{ userId, startTimestamp, endTimestamp, modelName, limit } = {},
noCache = false,
) => {
if (!orgId) return; if (!orgId) return;
setLoading(true); setLoading(true);
try { try {
const params = {}; const params = buildOrgLogFilters(filters);
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
if (limit) params.limit = limit; if (limit) params.limit = limit;
if (noCache) params.nocache = 1; if (noCache) params.nocache = 1;
+71 -41
View File
@@ -24,15 +24,35 @@ import {
API, API,
copy, copy,
isAdmin, isAdmin,
isRoot,
showError, showError,
showSuccess, showSuccess,
timestamp2string, timestamp2string,
} from '../../helpers'; } from '../../helpers';
import { EVENTS, emit } from '../../helpers/eventBus'; import { EVENTS, emit } from '../../helpers/eventBus';
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
import { ITEMS_PER_PAGE } from '../../constants'; import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode'; import { useTableCompactMode } from '../common/useTableCompactMode';
export const useTaskLogsData = () => { const DEFAULT_TASK_RANGE_DAYS = 7;
const toUnixTimestamp = (value) => {
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.floor(value);
}
if (value instanceof Date) {
return Math.floor(value.getTime() / 1000);
}
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : NaN;
};
export const useTaskLogsData = ({
organizationMode = false,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision = 0,
} = {}) => {
const { t } = useTranslation(); const { t } = useTranslation();
// Define column keys for selection // Define column keys for selection
@@ -43,7 +63,6 @@ export const useTaskLogsData = () => {
FINISH_TIME: 'finish_time', FINISH_TIME: 'finish_time',
DURATION: 'duration', DURATION: 'duration',
CHANNEL: 'channel', CHANNEL: 'channel',
PLATFORM: 'platform',
TYPE: 'type', TYPE: 'type',
MODEL: 'model', MODEL: 'model',
TASK_ID: 'task_id', TASK_ID: 'task_id',
@@ -61,11 +80,15 @@ export const useTaskLogsData = () => {
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE); const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
// User and admin // User and admin
const isAdminUser = isAdmin(); const isAdminUser = !organizationMode && isAdmin();
// 任务 ID 详情包含完整任务记录,仅系统超级管理员可查看;企业用户始终不可打开
const isRootUser = !organizationMode && isRoot();
// Role-specific storage key to prevent different roles from overwriting each other // Role-specific storage key to prevent different roles from overwriting each other
const STORAGE_KEY = isAdminUser const STORAGE_KEY = organizationMode
? 'task-logs-table-columns-admin' ? 'task-logs-table-columns-organization'
: 'task-logs-table-columns-user'; : isAdminUser
? 'task-logs-table-columns-admin'
: 'task-logs-table-columns-user';
// Modal state // Modal state
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
@@ -81,15 +104,20 @@ export const useTaskLogsData = () => {
// Form state // Form state
const [formApi, setFormApi] = useState(null); const [formApi, setFormApi] = useState(null);
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后 const usesSharedDateRange =
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug) organizationMode &&
Number.isFinite(Number(sharedStartTimestamp)) &&
Number.isFinite(Number(sharedEndTimestamp));
// 每次调用都返回"此刻"的默认时间范围,默认最近 7 天,避免任务页首屏
// 只查当天而遗漏历史任务;返回 Date 对象以便日期控件正确显示。
const getFreshDateRange = () => { const getFreshDateRange = () => {
const now = new Date(); const now = new Date();
const zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate()); now.setSeconds(0, 0);
return [ const start = new Date(
timestamp2string(zeroNow.getTime() / 1000), now.getTime() - DEFAULT_TASK_RANGE_DAYS * 24 * 60 * 60 * 1000,
timestamp2string(now.getTime() / 1000 + 3600), );
]; return [start, now];
}; };
const getFreshInitValues = () => ({ const getFreshInitValues = () => ({
@@ -136,24 +164,13 @@ export const useTaskLogsData = () => {
// Load saved column preferences from localStorage // Load saved column preferences from localStorage
useEffect(() => { useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY); const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) { setVisibleColumns(
try { resolveColumnVisibility(
const parsed = JSON.parse(savedColumns); getDefaultColumnVisibility(),
const defaults = getDefaultColumnVisibility(); savedColumns,
const merged = { ...defaults, ...parsed }; isAdminUser ? [] : [COLUMN_KEYS.CHANNEL],
),
// For non-admin users, force-hide admin-only columns (does not touch admin settings) );
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
}, []); }, []);
// Get default column visibility based on user role // Get default column visibility based on user role
@@ -163,7 +180,6 @@ export const useTaskLogsData = () => {
[COLUMN_KEYS.FINISH_TIME]: true, [COLUMN_KEYS.FINISH_TIME]: true,
[COLUMN_KEYS.DURATION]: true, [COLUMN_KEYS.DURATION]: true,
[COLUMN_KEYS.CHANNEL]: isAdminUser, [COLUMN_KEYS.CHANNEL]: isAdminUser,
[COLUMN_KEYS.PLATFORM]: true,
[COLUMN_KEYS.TYPE]: true, [COLUMN_KEYS.TYPE]: true,
[COLUMN_KEYS.MODEL]: true, [COLUMN_KEYS.MODEL]: true,
[COLUMN_KEYS.TASK_ID]: true, [COLUMN_KEYS.TASK_ID]: true,
@@ -216,12 +232,17 @@ export const useTaskLogsData = () => {
// 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤 // 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤
const formValues = formApi ? formApi.getValues() : formInitValues; const formValues = formApi ? formApi.getValues() : formInitValues;
// 处理时间范围:每次调用时取"此刻"的默认值,避免闭包陈旧 // 企业页复用上方已经提交的时间范围;个人/平台任务页使用自己的日期控件。
const [freshStart, freshEnd] = getFreshDateRange(); const [freshStart, freshEnd] = getFreshDateRange();
let start_timestamp = freshStart; let start_timestamp = usesSharedDateRange
let end_timestamp = freshEnd; ? Number(sharedStartTimestamp)
: freshStart;
let end_timestamp = usesSharedDateRange
? Number(sharedEndTimestamp)
: freshEnd;
if ( if (
!usesSharedDateRange &&
formValues.dateRange && formValues.dateRange &&
Array.isArray(formValues.dateRange) && Array.isArray(formValues.dateRange) &&
formValues.dateRange.length === 2 formValues.dateRange.length === 2
@@ -305,8 +326,8 @@ export const useTaskLogsData = () => {
start_timestamp, start_timestamp,
end_timestamp, end_timestamp,
} = getFormValues(); } = getFormValues();
let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000); let localStartTimestamp = toUnixTimestamp(start_timestamp);
let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000); let localEndTimestamp = toUnixTimestamp(end_timestamp);
// 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示 // 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示
if ( if (
Number.isFinite(localStartTimestamp) && Number.isFinite(localStartTimestamp) &&
@@ -334,9 +355,11 @@ export const useTaskLogsData = () => {
// 与使用日志对齐:管理员可按 user_id 过滤任务日志 // 与使用日志对齐:管理员可按 user_id 过滤任务日志
if (user_id) params.set('user_id', user_id); if (user_id) params.set('user_id', user_id);
} }
const url = isAdminUser const url = organizationMode
? `/api/task/?${params.toString()}` ? `/api/org/tasks?${params.toString()}`
: `/api/task/self?${params.toString()}`; : isAdminUser
? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`;
try { try {
const res = await API.get(url); const res = await API.get(url);
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出 // 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
@@ -421,7 +444,12 @@ export const useTaskLogsData = () => {
parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE; parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
setPageSize(localPageSize); setPageSize(localPageSize);
loadLogs(1, localPageSize).then(); loadLogs(1, localPageSize).then();
}, []); }, [
organizationMode,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision,
]);
// 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求 // 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求
const loadLogsRef = useRef(loadLogs); const loadLogsRef = useRef(loadLogs);
@@ -473,6 +501,8 @@ export const useTaskLogsData = () => {
logCount, logCount,
pageSize, pageSize,
isAdminUser, isAdminUser,
isRootUser,
usesSharedDateRange,
// Modal state // Modal state
isModalOpen, isModalOpen,
+10 -20
View File
@@ -34,6 +34,7 @@ import {
import { ITEMS_PER_PAGE } from '../../constants'; import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode'; import { useTableCompactMode } from '../common/useTableCompactMode';
import { EVENTS, subscribe } from '../../helpers/eventBus'; import { EVENTS, subscribe } from '../../helpers/eventBus';
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
export const useLogsData = () => { export const useLogsData = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -191,26 +192,15 @@ export const useLogsData = () => {
// Load saved column preferences from localStorage // Load saved column preferences from localStorage
useEffect(() => { useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY); const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) { setVisibleColumns(
try { resolveColumnVisibility(
const parsed = JSON.parse(savedColumns); getDefaultColumnVisibility(),
const defaults = getDefaultColumnVisibility(); savedColumns,
const merged = { ...defaults, ...parsed }; isAdminUser
? []
// For non-admin users, force-hide admin-only columns (does not touch admin settings) : [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.USERNAME, COLUMN_KEYS.RETRY],
if (!isAdminUser) { ),
merged[COLUMN_KEYS.CHANNEL] = false; );
merged[COLUMN_KEYS.USERNAME] = false;
merged[COLUMN_KEYS.RETRY] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
}, []); }, []);
// Get default column visibility based on user role // Get default column visibility based on user role
+44 -41
View File
@@ -72,17 +72,22 @@ export const useUsersData = () => {
// Load users data // Load users data
const loadUsers = async (startIdx, pageSize) => { const loadUsers = async (startIdx, pageSize) => {
setLoading(true); setLoading(true);
const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`); try {
const { success, message, data } = res.data; const res = await API.get(
if (success) { `/api/user/?p=${startIdx}&page_size=${pageSize}`,
const newPageData = data.items; );
setActivePage(data.page); const { success, message, data } = res.data;
setUserCount(data.total); if (success) {
setUserFormat(newPageData); const newPageData = data.items;
} else { setActivePage(data.page);
showError(message); setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
} finally {
setLoading(false);
} }
setLoading(false);
}; };
// Search users with keyword and group // Search users with keyword and group
@@ -100,24 +105,32 @@ export const useUsersData = () => {
} }
if (searchKeyword === '' && searchGroup === '') { if (searchKeyword === '' && searchGroup === '') {
// If keyword is blank, load files instead // If both filters are blank, load users instead
await loadUsers(startIdx, pageSize); await loadUsers(startIdx, pageSize);
return; return;
} }
setSearching(true); setSearching(true);
const res = await API.get( try {
`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`, const res = await API.get('/api/user/search', {
); params: {
const { success, message, data } = res.data; keyword: searchKeyword,
if (success) { group: searchGroup,
const newPageData = data.items; p: startIdx,
setActivePage(data.page); page_size: pageSize,
setUserCount(data.total); },
setUserFormat(newPageData); });
} else { const { success, message, data } = res.data;
showError(message); if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
} finally {
setSearching(false);
} }
setSearching(false);
}; };
// Manage user operations (promote, demote, enable, disable, delete) // Manage user operations (promote, demote, enable, disable, delete)
@@ -191,12 +204,9 @@ export const useUsersData = () => {
// Handle page change // Handle page change
const handlePageChange = (page) => { const handlePageChange = (page) => {
setActivePage(page); setActivePage(page);
const { searchKeyword, searchGroup } = getFormValues(); refresh(page).catch((reason) => {
if (searchKeyword === '' && searchGroup === '') { showError(reason);
loadUsers(page, pageSize).then(); });
} else {
searchUsers(page, pageSize, searchKeyword, searchGroup).then();
}
}; };
// Handle page size change // Handle page size change
@@ -204,11 +214,9 @@ export const useUsersData = () => {
localStorage.setItem('page-size', size + ''); localStorage.setItem('page-size', size + '');
setPageSize(size); setPageSize(size);
setActivePage(1); setActivePage(1);
loadUsers(activePage, size) await refresh(1, size).catch((reason) => {
.then() showError(reason);
.catch((reason) => { });
showError(reason);
});
}; };
// Handle table row styling for disabled/deleted users // Handle table row styling for disabled/deleted users
@@ -225,13 +233,8 @@ export const useUsersData = () => {
}; };
// Refresh data // Refresh data
const refresh = async (page = activePage) => { const refresh = async (page = activePage, size = pageSize) => {
const { searchKeyword, searchGroup } = getFormValues(); await searchUsers(page, size);
if (searchKeyword === '' && searchGroup === '') {
await loadUsers(page, pageSize);
} else {
await searchUsers(page, pageSize, searchKeyword, searchGroup);
}
}; };
// Fetch groups data // Fetch groups data
+256
View File
@@ -0,0 +1,256 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { setImmediate } from 'node:timers/promises';
import { runInNewContext } from 'node:vm';
import axios from 'axios';
import { transformWithEsbuild } from 'vite';
const filename = new URL('./useUsersData.jsx', import.meta.url);
const { code } = await transformWithEsbuild(
await readFile(filename, 'utf8'),
filename.pathname,
{ loader: 'jsx', format: 'cjs', target: 'node22' },
);
const defaultPageSize = 10;
// Execute the real exported hook with state snapshots and mount effects only.
// This controller harness does not model React scheduling, StrictMode, DOM, or HTTP.
async function createHarness() {
const states = [];
const effects = [];
const requests = [];
const errors = [];
const storage = new Map();
let cursor = 0;
let mounting = true;
let respond = (request) => {
if (request.path === '/api/group/') {
return { data: { data: ['default'] } };
}
return {
data: {
success: true,
data: {
page: Number(request.params.p),
total: 1,
items: [{ id: 42, username: 'test-user' }],
},
},
};
};
const modules = {
react: {
useState(initialValue) {
const index = cursor++;
if (mounting) {
states[index] =
typeof initialValue === 'function' ? initialValue() : initialValue;
}
return [
states[index],
(value) => {
states[index] =
typeof value === 'function' ? value(states[index]) : value;
},
];
},
useEffect(effect) {
if (mounting) effects.push(effect);
},
},
'react-i18next': { useTranslation: () => ({ t: (value) => value }) },
'../../helpers': {
API: {
async get(url, config) {
// Use Axios's actual serializer, but never send a network request.
const parsed = new URL(
axios.getUri({ ...config, url }),
'https://example.test',
);
const request = {
path: parsed.pathname,
params: Object.fromEntries(parsed.searchParams),
};
requests.push(request);
return respond(request);
},
},
showError: (error) => errors.push(error),
showSuccess: () => {},
},
'../../constants': { ITEMS_PER_PAGE: defaultPageSize },
'../common/useTableCompactMode': {
useTableCompactMode: () => [false, () => {}],
},
};
const module = { exports: {} };
runInNewContext(code, {
module,
exports: module.exports,
require(name) {
assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`);
return modules[name];
},
localStorage: { setItem: (key, value) => storage.set(key, value) },
});
const render = () => {
cursor = 0;
return module.exports.useUsersData();
};
render();
mounting = false;
effects.forEach((effect) => effect());
await setImmediate();
return {
render,
requests,
errors,
storage,
setResponder(next) {
respond = next;
},
};
}
function assertRequest(request, page, size, filters = {}) {
const keyword = filters.searchKeyword || '';
const group = filters.searchGroup || '';
assert.deepEqual(request, {
path: keyword || group ? '/api/user/search' : '/api/user/',
params: {
...(keyword || group ? { keyword, group } : {}),
p: String(page),
page_size: String(size),
},
});
}
test('mount keeps the initial page-zero fetch and formats returned users', async () => {
const harness = await createHarness();
assertRequest(harness.requests[0], 0, defaultPageSize);
assert.equal(harness.requests[1].path, '/api/group/');
const data = harness.render();
assert.equal(data.loading, false);
assert.equal(data.searching, false);
assert.equal(data.activePage, 0);
assert.equal(data.userCount, 1);
assert.equal(data.users[0].key, 42);
});
for (const [name, filters] of Object.entries({
unfiltered: { searchKeyword: '', searchGroup: '' },
keyword: { searchKeyword: 'alice', searchGroup: '' },
group: { searchKeyword: '', searchGroup: 'staff' },
'both filters with reserved characters': {
searchKeyword: 'alice & bob+#?=user',
searchGroup: 'staff&group=other +#',
},
})) {
test(`page-size change from a later page uses page 1, new size, and live form values: ${name}`, async () => {
const harness = await createHarness();
let values = { searchKeyword: '', searchGroup: '' };
harness.render().setFormApi({ getValues: () => values });
harness.render().handlePageChange(4);
await setImmediate();
assert.equal(harness.render().activePage, 4);
values = filters;
harness.requests.length = 0;
const pending = harness.render().handlePageSizeChange(25);
assert.equal(harness.render().activePage, 1);
assert.equal(harness.render().pageSize, 25);
await pending;
assert.equal(harness.requests.length, 1);
assertRequest(harness.requests[0], 1, 25, filters);
assert.equal(harness.storage.get('page-size'), '25');
assert.equal(harness.render().activePage, 1);
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
harness.render().handlePageChange(3);
await setImmediate();
assertRequest(harness.requests[1], 3, 25, filters);
await harness.render().refresh();
assertRequest(harness.requests[2], 3, 25, filters);
});
}
test('form search still reads current filters and supports explicit filters and blank fallback', async () => {
const harness = await createHarness();
let values = { searchKeyword: 'form keyword', searchGroup: 'form group' };
harness.render().setFormApi({ getValues: () => values });
harness.requests.length = 0;
await harness.render().searchUsers(1, 20);
assertRequest(harness.requests[0], 1, 20, values);
await harness.render().searchUsers(2, 20, 'explicit', 'override');
assertRequest(harness.requests[1], 2, 20, {
searchKeyword: 'explicit',
searchGroup: 'override',
});
values = {};
await harness.render().searchUsers(1, 20);
assertRequest(harness.requests[2], 1, 20);
});
for (const action of ['loadUsers', 'searchUsers', 'blank search fallback']) {
test(`${action} clears its pending flag and propagates request rejection`, async () => {
const harness = await createHarness();
const failure = new Error('request rejected');
let rejectRequest;
harness.setResponder(
() => new Promise((resolve, reject) => (rejectRequest = reject)),
);
const data = harness.render();
const pending =
action === 'loadUsers'
? data.loadUsers(2, 10)
: data.searchUsers(2, 10, action === 'searchUsers' ? 'alice' : '', '');
const flag = action === 'searchUsers' ? 'searching' : 'loading';
assert.equal(harness.render()[flag], true);
const rejected = assert.rejects(pending, (error) => error === failure);
rejectRequest(failure);
await rejected;
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
});
}
for (const handler of ['handlePageSizeChange', 'handlePageChange']) {
for (const filtered of [false, true]) {
test(`${handler} reports rejected ${filtered ? 'filtered' : 'unfiltered'} requests and clears flags`, async () => {
const harness = await createHarness();
harness.render().setFormApi({
getValues: () => ({ searchKeyword: filtered ? 'alice' : '' }),
});
const failure = new Error('pagination request rejected');
harness.setResponder(() => Promise.reject(failure));
await harness.render()[handler](25);
await setImmediate();
assert.deepEqual(harness.errors, [failure]);
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
});
}
}
+88
View File
@@ -0,0 +1,88 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Card, Input, Tag, Typography } from '@douyinfe/semi-ui';
import { CalendarDays, Globe } from 'lucide-react';
import { useTranslation } from 'react-i18next';
export default function AdminMenuPreview({ type }) {
const { t } = useTranslation();
const isWebsite = type === 'website';
const Icon = isWebsite ? Globe : CalendarDays;
const title = isWebsite ? t('官网设置') : t('预约演示');
return (
<div className='mt-[60px] px-2 pb-6 md:px-4'>
<div className='mb-6 flex flex-wrap items-center gap-3'>
<Icon size={28} className='text-blue-500' />
<Typography.Title heading={3} style={{ margin: 0 }}>
{title}
</Typography.Title>
<Tag color='blue'>{t('功能预览')}</Tag>
</div>
<Typography.Paragraph type='tertiary'>
{t('当前为示例内容,仅用于预览页面,暂未接入数据保存。')}
</Typography.Paragraph>
{isWebsite ? (
<Card title={t('官网基础信息')}>
<div className='grid max-w-3xl gap-5 md:grid-cols-2'>
{[
[t('网站名称'), t('Monkey AI 官网')],
[t('官网地址'), 'https://www.example.com'],
[t('首页标题'), t('让 AI 为业务创造更多价值')],
[t('联系邮箱'), 'contact@example.com'],
].map(([label, value]) => (
<label key={label} className='flex flex-col gap-2'>
<span>{label}</span>
<Input value={value} readOnly />
</label>
))}
</div>
</Card>
) : (
<Card title={t('预约演示列表')}>
<div className='overflow-x-auto'>
<table className='w-full min-w-[560px] text-left text-sm'>
<thead>
<tr className='border-b border-[var(--semi-color-border)]'>
{['联系人', '企业名称', '演示需求', '状态'].map((label) => (
<th key={label} className='px-3 py-3 font-medium'>
{t(label)}
</th>
))}
</tr>
</thead>
<tbody>
<tr>
<td className='px-3 py-4'>{t('示例联系人')}</td>
<td className='px-3 py-4'>{t('示例科技有限公司')}</td>
<td className='px-3 py-4'>{t('企业 AI 应用演示')}</td>
<td className='px-3 py-4'>
<Tag color='orange'>{t('待联系')}</Tag>
</td>
</tr>
</tbody>
</table>
</div>
</Card>
)}
</div>
);
}
+1
View File
@@ -1154,6 +1154,7 @@ const AdminOrganizations = () => {
confirmLoading={createLoading} confirmLoading={createLoading}
{...(createCredentialResult ? { footer: null } : {})} {...(createCredentialResult ? { footer: null } : {})}
bodyStyle={{ bodyStyle={{
...(createCredentialResult ? { paddingBottom: 24 } : {}),
maxHeight: 'calc(100vh - 200px)', maxHeight: 'calc(100vh - 200px)',
overflowY: 'auto', overflowY: 'auto',
overscrollBehavior: 'contain', overscrollBehavior: 'contain',
+26
View File
@@ -0,0 +1,26 @@
# 预约演示列表
页面复用 CardPro、CardTable、CompactModeToggle 和 createCardProPagination。
桌面端搜索栏靠左,移动端沿用系统的操作区展开和卡片展示方式。
## 已接入接口
GET /api/website/demo-requests,通过项目共享 API 实例发送 Cookie 和 New-Api-User。
不再使用本地演示列表。业务 success 必须严格为 true,否则显示后端 message 或错误提示。
筛选字段:name、contact、companyName,去除首尾空白并以 URLSearchParams 编码。
模糊搜索由后端执行,三个条件为 AND。请求分页为 p 和 page_size;
响应读取 data.items、data.total、data.page 和 data.page_size。
查询、重置和切换每页条数回到第一页;翻页保留已提交的筛选条件。
页面忽略过期请求结果,错误时清空表格并显示错误原因。
公司名称与需求分别使用 companyName 和 requirement,不使用原型字段 company/requirements。
需求列表最多显示三行,保留内部换行,不提供查看完整需求按钮或弹窗。
## 模拟提交与验收
本地脚本 scripts/seed-demo-requests.mjs 默认仅预览,添加 --submit 才真实新增三条联调测试预约。
页面初始化不会新增数据。脚本和测试文件已加入 Git 忽略规则。
运行 npm run test:e2e 验证桌面与移动端交互;npm run test:e2e:report 查看本地报告。
完整验收要求见 docs/website-api-acceptance.md,模拟接口验收与真实服务验收分别记录。
+294
View File
@@ -0,0 +1,294 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
Banner,
Button,
Empty,
Form,
Select,
Spin,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import CardPro from '../../components/common/ui/CardPro';
import CardTable from '../../components/common/ui/CardTable';
import CompactModeToggle from '../../components/common/ui/CompactModeToggle';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../components/common/illustrations';
import { createCardProPagination } from '../../helpers/utils';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useTableCompactMode } from '../../hooks/common/useTableCompactMode';
import { fetchDemoReservations } from './reservationsApi';
const EMPTY_FILTERS = { name: '', contact: '', companyName: '' };
export default function DemoReservations() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [compactMode, setCompactMode] =
useTableCompactMode('demo-reservations');
const formRef = useRef(null);
const [query, setQuery] = useState({
...EMPTY_FILTERS,
page: 1,
pageSize: 10,
});
const [result, setResult] = useState({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
let active = true;
setLoading(true);
setError('');
fetchDemoReservations(query)
.then((data) => {
if (active) setResult(data);
})
.catch((error) => {
if (active) {
setError(error.message || '预约信息加载失败,请重新查询');
setResult({ items: [], total: 0 });
}
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [query]);
const columns = useMemo(
() =>
[
['name', '姓名', 100],
['contact', '联系方式', 210],
['companyName', '公司名称', 180],
['position', '职位', 140],
['industry', '行业', 160],
['interest', '关注方向', 190],
['requirement', '需求', 360],
].map(([dataIndex, title, width]) => ({
title: t(title),
dataIndex,
key: dataIndex,
...(compactMode ? {} : { width }),
render: (value) =>
dataIndex === 'requirement' && value ? (
<div>
<span
style={{
display: '-webkit-box',
WebkitLineClamp: 3,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
overflowWrap: 'anywhere',
whiteSpace: 'pre-wrap',
}}
>
{value}
</span>
</div>
) : (
<span style={{ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' }}>
{value || '—'}
</span>
),
})),
[t, compactMode],
);
const reset = () => {
formRef.current?.reset();
setQuery((previous) => ({
...EMPTY_FILTERS,
page: 1,
pageSize: previous.pageSize,
}));
};
const changePageSize = (pageSize) =>
setQuery((previous) => ({ ...previous, page: 1, pageSize }));
const pagination = createCardProPagination({
currentPage: result.page ?? query.page,
pageSize: result.page_size ?? query.pageSize,
total: result.total,
onPageChange: (page) => setQuery((previous) => ({ ...previous, page })),
onPageSizeChange: changePageSize,
preventPageChangeOnPageSizeChange: true,
isMobile,
t,
});
return (
<div className='mt-[60px] px-2' aria-busy={loading}>
<Spin
spinning={loading}
size='large'
style={{ minHeight: 200, width: '100%' }}
data-testid='demo-reservations-loading'
>
<CardPro
type='type1'
t={t}
descriptionArea={
<div className='flex w-full flex-col items-start justify-between gap-2 md:flex-row md:items-center'>
<div>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('预约演示')}
</Typography.Title>
<Typography.Text type='tertiary' size='small'>
{t('查看官网访客提交的预约信息,支持模糊查询与分页。')}
</Typography.Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
}
actionsArea={
<div className='flex w-full justify-start'>
<Form
initValues={EMPTY_FILTERS}
getFormApi={(api) => (formRef.current = api)}
onSubmit={(values) =>
setQuery((previous) => ({
name: (values.name || '').trim(),
contact: (values.contact || '').trim(),
companyName: (values.companyName || '').trim(),
page: 1,
pageSize: previous.pageSize,
}))
}
allowEmpty
autoComplete='off'
layout='horizontal'
className='w-full md:w-auto'
>
<div className='flex w-full flex-col items-center gap-2 md:w-auto md:flex-row'>
{[
['name', '请输入姓名'],
['contact', '请输入联系方式'],
['companyName', '请输入公司名称'],
].map(([field, placeholder]) => (
<div key={field} className='w-full md:w-44'>
<Form.Input
field={field}
aria-label={t(placeholder)}
placeholder={t(placeholder)}
showClear
pure
size='small'
maxLength={254}
/>
</div>
))}
<div className='flex w-full gap-2 md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
className='flex-1 md:flex-initial'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={reset}
size='small'
className='flex-1 md:flex-initial'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
</div>
}
paginationArea={
isMobile && result.total > 0 ? (
<div className='flex w-full flex-col items-center gap-3'>
<div className='flex items-center gap-3'>
<Typography.Text type='tertiary'>
{t('共')} {result.total} {t('条')}
</Typography.Text>
<Select
aria-label={t('每页条数')}
size='small'
value={result.page_size ?? query.pageSize}
onChange={changePageSize}
optionList={[10, 20, 50, 100].map((value) => ({
value,
label: `${value} ${t('条/页')}`,
}))}
/>
</div>
{pagination}
</div>
) : (
pagination
)
}
>
{error && (
<Banner
type='danger'
closeIcon={null}
description={t(error)}
className='mb-4'
/>
)}
<CardTable
rowKey='id'
columns={columns}
dataSource={result.items}
scroll={compactMode ? undefined : { x: 'max-content' }}
hidePagination
className='overflow-hidden'
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t(
error ? '预约信息加载失败' : '暂无符合条件的预约信息',
)}
style={{ padding: 30 }}
/>
}
/>
</CardPro>
</Spin>
</div>
);
}
@@ -0,0 +1,54 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { requestWebsite } from '../../helpers/websiteApi';
export async function fetchDemoReservations({
name = '',
contact = '',
companyName = '',
page = 1,
pageSize = 10,
} = {}) {
const params = new URLSearchParams({
name: name.trim(),
contact: contact.trim(),
companyName: companyName.trim(),
p: String(page),
page_size: String(pageSize),
});
const data = await requestWebsite(
'get',
`/api/website/demo-requests?${params}`,
undefined,
'预约信息加载失败,请重新查询',
);
if (
!data ||
!Array.isArray(data.items) ||
!Number.isInteger(data.total) ||
data.total < 0 ||
!Number.isInteger(data.page) ||
data.page < 1 ||
!Number.isInteger(data.page_size) ||
data.page_size < 1
)
throw new Error('预约列表响应格式不正确,请联系管理员检查');
return data;
}
+19 -21
View File
@@ -31,18 +31,16 @@ import { useActualTheme } from '../../context/Theme';
import { marked } from 'marked'; import { marked } from 'marked';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { import Moonshot from '@lobehub/icons/es/Moonshot/components/Mono';
Moonshot, import OpenAI from '@lobehub/icons/es/OpenAI/components/Mono';
OpenAI, import Zhipu from '@lobehub/icons/es/Zhipu/components/Color';
Zhipu, import Claude from '@lobehub/icons/es/Claude/components/Color';
Claude, import Gemini from '@lobehub/icons/es/Gemini/components/Color';
Gemini, import Wenxin from '@lobehub/icons/es/Wenxin/components/Color';
Wenxin, import Spark from '@lobehub/icons/es/Spark/components/Color';
Spark, import DeepSeek from '@lobehub/icons/es/DeepSeek/components/Color';
DeepSeek, import Qwen from '@lobehub/icons/es/Qwen/components/Color';
Qwen, import Midjourney from '@lobehub/icons/es/Midjourney/components/Mono';
Midjourney,
} from '@lobehub/icons';
import { import {
Cpu, Cpu,
Server, Server,
@@ -299,15 +297,15 @@ const Home = () => {
// 模型列表 // 模型列表
const modelIcons = [ const modelIcons = [
{ Icon: OpenAI, name: 'OpenAI' }, { Icon: OpenAI, name: 'OpenAI' },
{ Icon: Claude.Color, name: 'Claude' }, { Icon: Claude, name: 'Claude' },
{ Icon: Gemini.Color, name: 'Gemini' }, { Icon: Gemini, name: 'Gemini' },
{ Icon: Midjourney, name: 'Midjourney' }, { Icon: Midjourney, name: 'Midjourney' },
{ Icon: Qwen.Color, name: 'Qwen' }, { Icon: Qwen, name: 'Qwen' },
{ Icon: DeepSeek.Color, name: 'DeepSeek' }, { Icon: DeepSeek, name: 'DeepSeek' },
{ Icon: Zhipu.Color, name: 'ChatGLM' }, { Icon: Zhipu, name: 'ChatGLM' },
{ Icon: Moonshot, name: 'Moonshot' }, { Icon: Moonshot, name: 'Moonshot' },
{ Icon: Spark.Color, name: 'Spark' }, { Icon: Spark, name: 'Spark' },
{ Icon: Wenxin.Color, name: 'Wenxin' }, { Icon: Wenxin, name: 'Wenxin' },
]; ];
// Enterprise Style CSS // Enterprise Style CSS
@@ -498,10 +496,10 @@ const Home = () => {
<OpenAI size={24} /> <OpenAI size={24} />
</div> </div>
<div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'> <div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'>
<Claude.Color size={24} /> <Claude size={24} />
</div> </div>
<div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'> <div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'>
<Gemini.Color size={24} /> <Gemini size={24} />
</div> </div>
</div> </div>
</div> </div>
+18 -4
View File
@@ -18,7 +18,6 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useEffect, useState, useMemo, useCallback } from 'react'; import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import * as XLSX from 'xlsx';
import { import {
RefreshCw, RefreshCw,
Receipt, Receipt,
@@ -48,6 +47,7 @@ import {
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import StatCard from './components/OrgStatCard'; import StatCard from './components/OrgStatCard';
import OrgModal from './components/OrgModal'; import OrgModal from './components/OrgModal';
import TaskLogsTable from '../../components/table/task-logs';
import { import {
API, API,
showError, showError,
@@ -161,7 +161,7 @@ const EXPORT_FIELDS = [
]; ];
// 将选中字段组装成一个 worksheet(含表头、列宽) // 将选中字段组装成一个 worksheet(含表头、列宽)
function buildWorksheet(rows, fields, header) { function buildWorksheet(XLSX, rows, fields, header) {
const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r)))]; const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r)))];
const ws = XLSX.utils.aoa_to_sheet(aoa); const ws = XLSX.utils.aoa_to_sheet(aoa);
ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 })); ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 }));
@@ -241,6 +241,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const pageSize = 20; const pageSize = 20;
const [activeTab, setActiveTab] = useState('logs'); const [activeTab, setActiveTab] = useState('logs');
const [taskFilterRevision, setTaskFilterRevision] = useState(0);
const isAdmin = const isAdmin =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin'; orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const canViewTeamUsage = isAdmin || isDeptManager; const canViewTeamUsage = isAdmin || isDeptManager;
@@ -352,6 +353,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
); );
} }
setPage(1); setPage(1);
setTaskFilterRevision((revision) => revision + 1);
}; };
// 重置:回到默认状态(滚动最近 7 天、不限成员/模型) // 重置:回到默认状态(滚动最近 7 天、不限成员/模型)
@@ -372,6 +374,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
}); });
} }
setPage(1); setPage(1);
setTaskFilterRevision((revision) => revision + 1);
}; };
// 导出弹窗状态(导出方式 + 字段勾选从 localStorage 恢复) // 导出弹窗状态(导出方式 + 字段勾选从 localStorage 恢复)
@@ -455,6 +458,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
} }
const header = fields.map((f) => t(f.label)); const header = fields.map((f) => t(f.label));
const XLSX = await import('xlsx');
const wb = XLSX.utils.book_new(); const wb = XLSX.utils.book_new();
if (exportMode === 'perUser') { if (exportMode === 'perUser') {
@@ -535,7 +539,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
); );
for (const { name, rows } of groups.values()) { for (const { name, rows } of groups.values()) {
const ws = buildWorksheet(rows, fields, header); const ws = buildWorksheet(XLSX, rows, fields, header);
XLSX.utils.book_append_sheet( XLSX.utils.book_append_sheet(
wb, wb,
ws, ws,
@@ -544,7 +548,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
} }
} else { } else {
// 汇总:所有记录放在一个 sheet 页 // 汇总:所有记录放在一个 sheet 页
const ws = buildWorksheet(allLogs, fields, header); const ws = buildWorksheet(XLSX, allLogs, fields, header);
XLSX.utils.book_append_sheet( XLSX.utils.book_append_sheet(
wb, wb,
ws, ws,
@@ -931,6 +935,16 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
/> />
</TabPane> </TabPane>
<TabPane tab={t('绘图与视频')} itemKey='tasks'>
<TaskLogsTable
usageRecordMode
organizationMode
sharedStartTimestamp={appliedFilters.startTimestamp}
sharedEndTimestamp={appliedFilters.endTimestamp}
sharedFilterRevision={taskFilterRevision}
/>
</TabPane>
{canViewTeamUsage && ( {canViewTeamUsage && (
<TabPane tab={t('成员排行')} itemKey='ranking'> <TabPane tab={t('成员排行')} itemKey='ranking'>
<Table <Table
+1 -1
View File
@@ -95,7 +95,7 @@ import MessageSelectableWrapper from '../../components/playground/MessageSelecta
import FloatingButtons from '../../components/playground/FloatingButtons'; import FloatingButtons from '../../components/playground/FloatingButtons';
import SessionSidebar from '../../components/playground/SessionSidebar'; import SessionSidebar from '../../components/playground/SessionSidebar';
import KeyboardShortcutsModal from '../../components/playground/KeyboardShortcutsModal'; import KeyboardShortcutsModal from '../../components/playground/KeyboardShortcutsModal';
import { PlaygroundProvider } from '../../contexts/PlaygroundContext'; import { PlaygroundProvider } from '../../context/Playground';
const Playground = ({ isExperienceMode = false }) => { const Playground = ({ isExperienceMode = false }) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -16,26 +16,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useEffect, useState, useRef } from 'react'; import React, { useContext, useEffect, useState, useRef } from 'react';
import { Banner, Button, Card, Checkbox, Form, Spin } from '@douyinfe/semi-ui'; import { Banner, Button, Card, Checkbox, Form, Spin } from '@douyinfe/semi-ui';
import { API, isRoot, showError, showSuccess } from '../../../helpers'; import { API, isRoot, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { DELEGATABLE_SETTING_TABS } from '../../../constants/settingTabs'; import {
ADMIN_DELEGATION_OPTIONS,
const OPTION_KEY = 'AdminDelegatedSettingTabs'; ADMIN_DELEGATION_OPTION_KEY as OPTION_KEY,
} from '../../../constants/settingTabs';
function parseTabs(raw) { import { parseAdminDelegation } from '../../../helpers/adminDelegation';
if (!raw) return []; import { StatusContext } from '../../../context/Status';
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}
export default function SettingsAdminDelegation(props) { export default function SettingsAdminDelegation(props) {
const { t } = useTranslation(); const { t } = useTranslation();
const [statusState, statusDispatch] = useContext(StatusContext);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]); const [selected, setSelected] = useState([]);
const [savedRaw, setSavedRaw] = useState(''); const [savedRaw, setSavedRaw] = useState('');
@@ -44,7 +38,7 @@ export default function SettingsAdminDelegation(props) {
useEffect(() => { useEffect(() => {
const raw = props.options?.[OPTION_KEY] ?? ''; const raw = props.options?.[OPTION_KEY] ?? '';
setSavedRaw(raw); setSavedRaw(raw);
const tabs = parseTabs(raw); const tabs = parseAdminDelegation(raw);
setSelected(tabs); setSelected(tabs);
refForm.current?.setValues({ [OPTION_KEY]: tabs }); refForm.current?.setValues({ [OPTION_KEY]: tabs });
}, [props.options]); }, [props.options]);
@@ -56,7 +50,7 @@ export default function SettingsAdminDelegation(props) {
function onSubmit() { function onSubmit() {
const value = JSON.stringify(selected); const value = JSON.stringify(selected);
if (value === JSON.stringify(parseTabs(savedRaw))) { if (value === JSON.stringify(parseAdminDelegation(savedRaw))) {
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
return; return;
} }
@@ -65,6 +59,11 @@ export default function SettingsAdminDelegation(props) {
.then((res) => { .then((res) => {
const { success, message } = res.data; const { success, message } = res.data;
if (success) { if (success) {
setSavedRaw(value);
statusDispatch({
type: 'set',
payload: { ...statusState?.status, [OPTION_KEY]: value },
});
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh?.(); props.refresh?.();
} else { } else {
@@ -91,7 +90,7 @@ export default function SettingsAdminDelegation(props) {
<Banner <Banner
type='warning' type='warning'
description={t( description={t(
'勾选后,普通管理员(非超级管理员)将能够看到并编辑这些系统设置 Tab。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的 Tab 仍仅超级管理员可见。', '勾选后,普通管理员(非超级管理员)将能够访问对应的系统设置 Tab 或管理页面,菜单同步按权限显示。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的项目仍仅超级管理员可访问。',
)} )}
bordered bordered
fullMode={false} fullMode={false}
@@ -102,9 +101,15 @@ export default function SettingsAdminDelegation(props) {
field={OPTION_KEY} field={OPTION_KEY}
noLabel noLabel
direction='horizontal' direction='horizontal'
onChange={(value) => setSelected(value)} onChange={(value) => {
const unknown = parseAdminDelegation(savedRaw).filter(
(key) =>
!ADMIN_DELEGATION_OPTIONS.some((item) => item.key === key),
);
setSelected([...new Set([...unknown, ...value])]);
}}
> >
{DELEGATABLE_SETTING_TABS.map((tab) => ( {ADMIN_DELEGATION_OPTIONS.map((tab) => (
<Checkbox key={tab.key} value={tab.key}> <Checkbox key={tab.key} value={tab.key}>
{t(tab.labelKey)} {t(tab.labelKey)}
</Checkbox> </Checkbox>
@@ -404,7 +404,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px', minHeight: '80px',
}} }}
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
hoverable shadows='hover'
> >
<div <div
style={{ style={{
@@ -558,7 +558,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px', minHeight: '80px',
}} }}
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
hoverable shadows='hover'
> >
<div <div
style={{ style={{
@@ -636,7 +636,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px', minHeight: '80px',
}} }}
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
hoverable shadows='hover'
> >
<div <div
style={{ style={{
@@ -168,7 +168,7 @@ export default function SettingsOrgUserNavModules(props) {
minHeight: '64px', minHeight: '64px',
}} }}
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
hoverable shadows='hover'
> >
<div <div
style={{ style={{
@@ -695,7 +695,7 @@ export default function SettingsSidebarModulesAdmin(props) {
<Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}> <Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card <Card
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
hoverable shadows='hover'
style={{ style={{
opacity: sectionConfig.enabled ? 1 : 0.5, opacity: sectionConfig.enabled ? 1 : 0.5,
transition: 'opacity 0.2s', transition: 'opacity 0.2s',
@@ -26,6 +26,7 @@ import {
showError, showError,
showSuccess, showSuccess,
showWarning, showWarning,
toBoolean,
} from '../../../helpers'; } from '../../../helpers';
// InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN, // InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN,
@@ -76,12 +77,11 @@ export default function SettingsSkillInject(props) {
useEffect(() => { useEffect(() => {
const currentInputs = {}; const currentInputs = {};
for (const key in DEFAULTS) { for (const key in DEFAULTS) {
currentInputs[key] = Object.prototype.hasOwnProperty.call( const value = Object.prototype.hasOwnProperty.call(props.options, key)
props.options,
key,
)
? props.options[key] ? props.options[key]
: DEFAULTS[key]; : DEFAULTS[key];
currentInputs[key] =
typeof DEFAULTS[key] === 'boolean' ? toBoolean(value) : value;
} }
setInputs(currentInputs); setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs)); setInputsRow(structuredClone(currentInputs));
+52 -36
View File
@@ -17,13 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { import {
Button, Button,
Card, Card,
@@ -136,7 +130,8 @@ const TOKEN_GROUPS = [
{ {
key: 'bg', key: 'bg',
labelKey: '页面背景晕染(大面积底色 / 光晕)', labelKey: '页面背景晕染(大面积底色 / 光晕)',
descKey: '影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡', descKey:
'影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
}, },
{ {
key: 'accent', key: 'accent',
@@ -286,7 +281,8 @@ export default function SettingsTheme(props) {
() => ({ ...getEffectivePreset(selectedPreset).dark, ...customDark }), () => ({ ...getEffectivePreset(selectedPreset).dark, ...customDark }),
[selectedPreset, customDark, presetOverridesState], [selectedPreset, customDark, presetOverridesState],
); );
const effectivePalette = colorMode === 'light' ? effectiveLight : effectiveDark; const effectivePalette =
colorMode === 'light' ? effectiveLight : effectiveDark;
// 任何编辑都即时前端预览(不写 cache)。 // 任何编辑都即时前端预览(不写 cache)。
// 注意:必须等首次 props 解析完成再开启预览,否则挂载瞬间会用 default state // 注意:必须等首次 props 解析完成再开启预览,否则挂载瞬间会用 default state
@@ -553,10 +549,9 @@ export default function SettingsTheme(props) {
setPresetOverrides(payload); setPresetOverrides(payload);
setPresetOverridesState(nextOverrides); setPresetOverridesState(nextOverrides);
setPresetDraft({}); setPresetDraft({});
applyTheme( applyTheme(JSON.stringify({ preset: editingPresetKey }), {
JSON.stringify({ preset: editingPresetKey }), persist: false,
{ persist: false }, });
);
statusDispatch({ statusDispatch({
type: 'set', type: 'set',
payload: { ...(statusState?.status || {}), theme_presets: payload }, payload: { ...(statusState?.status || {}), theme_presets: payload },
@@ -624,9 +619,11 @@ export default function SettingsTheme(props) {
const cleanLight = sanitizeImportedTokens(cfg.lightTokens); const cleanLight = sanitizeImportedTokens(cfg.lightTokens);
const cleanDark = sanitizeImportedTokens(cfg.darkTokens); const cleanDark = sanitizeImportedTokens(cfg.darkTokens);
const droppedLight = const droppedLight =
Object.keys(cfg.lightTokens || {}).length - Object.keys(cleanLight).length; Object.keys(cfg.lightTokens || {}).length -
Object.keys(cleanLight).length;
const droppedDark = const droppedDark =
Object.keys(cfg.darkTokens || {}).length - Object.keys(cleanDark).length; Object.keys(cfg.darkTokens || {}).length -
Object.keys(cleanDark).length;
setSelectedPreset(presetKey); setSelectedPreset(presetKey);
setCustomLight(cleanLight); setCustomLight(cleanLight);
setCustomDark(cleanDark); setCustomDark(cleanDark);
@@ -769,9 +766,7 @@ export default function SettingsTheme(props) {
colorMode={colorMode} colorMode={colorMode}
setColorMode={setColorMode} setColorMode={setColorMode}
palette={effectivePalette} palette={effectivePalette}
customOverrides={ customOverrides={colorMode === 'light' ? customLight : customDark}
colorMode === 'light' ? customLight : customDark
}
onChange={handleTokenChange} onChange={handleTokenChange}
onResetToken={handleTokenReset} onResetToken={handleTokenReset}
onCopyToOther={handleCopyToOther} onCopyToOther={handleCopyToOther}
@@ -863,7 +858,7 @@ function PresetGrid({
return ( return (
<Col key={key} xs={24} sm={12} md={8}> <Col key={key} xs={24} sm={12} md={8}>
<Card <Card
hoverable shadows='hover'
onClick={() => onSelect(key)} onClick={() => onSelect(key)}
style={{ style={{
cursor: 'pointer', cursor: 'pointer',
@@ -926,7 +921,10 @@ function PresetGrid({
)} )}
</Title> </Title>
{isSaved && ( {isSaved && (
<Text size='small' style={{ color: 'var(--semi-color-primary)' }}> <Text
size='small'
style={{ color: 'var(--semi-color-primary)' }}
>
{t('已应用')} {t('已应用')}
</Text> </Text>
)} )}
@@ -1015,19 +1013,13 @@ function PresetTemplateEditor({
/> />
</div> </div>
<div style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}> <div
<Button style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}
type='primary' >
theme='solid' <Button type='primary' theme='solid' loading={saving} onClick={onSave}>
loading={saving}
onClick={onSave}
>
{t('保存预设模板')} {t('保存预设模板')}
</Button> </Button>
<Button <Button disabled={!isEdited || saving} onClick={onRestore}>
disabled={!isEdited || saving}
onClick={onRestore}
>
{t('恢复此预设出厂')} {t('恢复此预设出厂')}
</Button> </Button>
</div> </div>
@@ -1053,7 +1045,14 @@ function CustomEditor({
return ( return (
<> <>
{/* 基础预设选择(决定未覆盖 token 的兜底值) */} {/* 基础预设选择(决定未覆盖 token 的兜底值) */}
<div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}> <div
style={{
marginBottom: 12,
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<Text type='secondary' size='small'> <Text type='secondary' size='small'>
{t('基础预设:')} {t('基础预设:')}
</Text> </Text>
@@ -1115,7 +1114,9 @@ function CustomEditor({
<Button <Button
size='small' size='small'
onClick={onDeriveToDark} onClick={onDeriveToDark}
title={t('按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致')} title={t(
'按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致',
)}
> >
{t('派生到深色(自动调亮)')} {t('派生到深色(自动调亮)')}
</Button> </Button>
@@ -1148,7 +1149,13 @@ function GroupedTokenList({ palette, isCustomOf, onChange, onReset, t }) {
}} }}
> >
<div style={{ marginBottom: 6, padding: '0 4px' }}> <div style={{ marginBottom: 6, padding: '0 4px' }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--semi-color-text-1)' }}> <div
style={{
fontSize: 12,
fontWeight: 600,
color: 'var(--semi-color-text-1)',
}}
>
{t(g.labelKey)} {t(g.labelKey)}
</div> </div>
<Text type='tertiary' size='small' style={{ fontSize: 11 }}> <Text type='tertiary' size='small' style={{ fontSize: 11 }}>
@@ -1186,7 +1193,12 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
const alphaPct = valid ? Math.round(c.alpha() * 100) : 100; const alphaPct = valid ? Math.round(c.alpha() * 100) : 100;
// colord.toHex():alpha=1 → 6 位,alpha<1 → 8 位,天然兼容存储格式 // colord.toHex():alpha=1 → 6 位,alpha<1 → 8 位,天然兼容存储格式
const emit = (hex, pct) => onChange(colord(hex).alpha(pct / 100).toHex()); const emit = (hex, pct) =>
onChange(
colord(hex)
.alpha(pct / 100)
.toHex(),
);
return ( return (
<div <div
@@ -1259,7 +1271,11 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
step={1} step={1}
value={alphaPct} value={alphaPct}
onChange={(e) => emit(rgbHex, Number(e.target.value))} onChange={(e) => emit(rgbHex, Number(e.target.value))}
style={{ flex: 1, accentColor: 'var(--brand-primary)', cursor: 'pointer' }} style={{
flex: 1,
accentColor: 'var(--brand-primary)',
cursor: 'pointer',
}}
aria-label={`${label} alpha`} aria-label={`${label} alpha`}
/> />
<span <span
+26
View File
@@ -0,0 +1,26 @@
/* Keep long settings forms scrollable while asynchronous sections mount. */
.settings-page {
/* PageLayout top padding (24px) + this page's top margin (60px). */
height: calc(100vh - 84px - var(--content-top-offset, 0px));
height: calc(100dvh - 84px - var(--content-top-offset, 0px));
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
scrollbar-gutter: stable;
}
/* Override the global full-height tab rules only for the outer settings tabs. */
.settings-page-tabs > .semi-tabs-content,
.settings-page-tabs > .semi-tabs-content > .semi-tabs-pane,
.settings-page-tabs > .semi-tabs-content > .semi-tabs-pane > div {
height: auto !important;
overflow: visible !important;
}
@media (max-width: 767px) {
.settings-page {
/* Mobile PageLayout uses 5px top padding. */
height: calc(100vh - 65px - var(--content-top-offset, 0px));
height: calc(100dvh - 65px - var(--content-top-offset, 0px));
}
}
+10 -8
View File
@@ -22,6 +22,7 @@ import { Layout, TabPane, Tabs } from '@douyinfe/semi-ui';
import { useNavigate, useLocation } from 'react-router-dom'; import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import { getDelegatedSettingTabs } from '../../helpers/adminDelegation';
import { import {
ALWAYS_ADMIN_VISIBLE_TABS, ALWAYS_ADMIN_VISIBLE_TABS,
ROOT_ONLY_SETTING_TABS, ROOT_ONLY_SETTING_TABS,
@@ -64,6 +65,7 @@ import CustomerServiceSetting from '../../components/settings/CustomerServiceSet
import TutorialVideoSetting from '../../components/settings/TutorialVideoSetting'; import TutorialVideoSetting from '../../components/settings/TutorialVideoSetting';
import AmountOptionsManager from './AmountOptionsManager'; import AmountOptionsManager from './AmountOptionsManager';
import SettingsMembership from './Payment/SettingsMembership'; import SettingsMembership from './Payment/SettingsMembership';
import './Setting.css';
const Setting = () => { const Setting = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -264,13 +266,9 @@ const Setting = () => {
} }
// 解析 root 配置的「下放给普通管理员」tab 列表 // 解析 root 配置的「下放给普通管理员」tab 列表
let delegatedTabs = []; const delegatedTabs = getDelegatedSettingTabs(
try { statusState?.status?.AdminDelegatedSettingTabs,
const raw = statusState?.status?.AdminDelegatedSettingTabs; );
if (raw) delegatedTabs = JSON.parse(raw);
} catch (e) {
delegatedTabs = [];
}
// 可见性过滤:root 看全部;普通管理员看「会员管理 + 被下放的 tab」;其余看不到。 // 可见性过滤:root 看全部;普通管理员看「会员管理 + 被下放的 tab」;其余看不到。
if (!isRoot()) { if (!isRoot()) {
@@ -311,10 +309,14 @@ const Setting = () => {
} }
}, [location.search, statusState?.status?.AdminDelegatedSettingTabs]); }, [location.search, statusState?.status?.AdminDelegatedSettingTabs]);
return ( return (
<div className='mt-[60px] px-2'> <div
className='settings-page mt-[60px] px-2 app-scrollbar'
data-testid='settings-scroll-container'
>
<Layout> <Layout>
<Layout.Content> <Layout.Content>
<Tabs <Tabs
className='settings-page-tabs'
type='card' type='card'
collapsible collapsible
activeKey={tabActiveKey} activeKey={tabActiveKey}
+297
View File
@@ -0,0 +1,297 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState } from 'react';
import {
Button,
Card,
Checkbox,
Form,
Input,
Modal,
Select,
SideSheet,
TextArea,
Typography,
} from '@douyinfe/semi-ui';
import { articleErrors } from './insightsModel';
import { articleContentInfo, sanitizeArticleHtml } from './insightsContent';
import ArticleRichEditor from './ArticleRichEditor';
export default function ArticleEditor({ initial, insights, onApply, onClose }) {
const [draft, setDraft] = useState(initial);
const [errors, setErrors] = useState({});
const [processingImage, setProcessingImage] = useState(false);
const hasDraftChanges = JSON.stringify(draft) !== JSON.stringify(initial);
useEffect(() => {
if (!hasDraftChanges && !processingImage) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasDraftChanges, processingImage]);
const change = (name, value) => {
setDraft((previous) => ({ ...previous, [name]: value }));
setErrors((previous) => ({ ...previous, [name]: '' }));
};
const close = () => {
if (JSON.stringify(draft) === JSON.stringify(initial) && !processingImage)
onClose();
else
Modal.confirm({
title: '放弃本次编辑?',
content: '当前文章的修改尚未应用,关闭后将丢失本次编辑内容。',
okText: '放弃修改',
cancelText: '继续编辑',
onOk: onClose,
});
};
const apply = () => {
if (processingImage) return;
const article = { ...draft, body: sanitizeArticleHtml(draft.body) };
for (const key of ['title', 'summary', 'subtitle', 'tag'])
article[key] = article[key].trim();
const nextErrors = articleErrors(article, insights);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) return;
onApply(article);
};
const field = (name, label, children, required = false) => (
<Form.Slot
className='website-insights-editor-field'
label={{ text: label, required }}
error={{ error: errors[name] || undefined }}
>
{children}
</Form.Slot>
);
const info = articleContentInfo(draft.body);
return (
<SideSheet
visible
title={initial.id ? '编辑文章' : '新增文章'}
width='min(1100px, 100vw)'
onCancel={close}
maskClosable={false}
footer={
<div className='website-insights-editor-footer'>
<div className='flex gap-2'>
<Button onClick={close}>取消</Button>
<Button theme='solid' disabled={processingImage} onClick={apply}>
{processingImage ? '图片处理中' : '保存'}
</Button>
</div>
</div>
}
>
<div className='website-insights-editor-layout'>
<div className='website-insights-editor-main'>
<Typography.Title
heading={5}
className='website-insights-section-title'
>
基础信息
</Typography.Title>
{field(
'title',
'文章标题',
<Input
aria-label='文章标题'
validateStatus={errors.title ? 'error' : 'default'}
aria-invalid={Boolean(errors.title)}
value={draft.title}
placeholder='请输入文章标题'
maxLength={80}
showClear
suffix={`${draft.title.length} / 80`}
onChange={(value) => change('title', value)}
/>,
true,
)}
<div className='grid grid-cols-1 gap-x-6 md:grid-cols-2'>
{field(
'category',
'所属分类',
<Select
aria-label='所属分类'
validateStatus={errors.category ? 'error' : 'default'}
aria-invalid={Boolean(errors.category)}
value={draft.category || undefined}
placeholder='请选择文章分类'
style={{ width: '100%' }}
optionList={[
{ label: '全部内容', value: 'all' },
...insights.categories.map((c) => ({
label: c.name,
value: c.id,
})),
]}
onChange={(value) => change('category', value)}
/>,
true,
)}
{field(
'date',
'发布日期',
<Input
aria-label='发布日期'
validateStatus={errors.date ? 'error' : 'default'}
aria-invalid={Boolean(errors.date)}
type='date'
value={draft.date}
onChange={(value) => change('date', value)}
/>,
true,
)}
</div>
{field(
'subtitle',
'详情副标题',
<Input
aria-label='详情副标题'
validateStatus={errors.subtitle ? 'error' : 'default'}
aria-invalid={Boolean(errors.subtitle)}
value={draft.subtitle}
maxLength={160}
placeholder='留空时使用卡片摘要作为副标题'
onChange={(value) => change('subtitle', value)}
/>,
)}
{field(
'summary',
'卡片摘要',
<TextArea
aria-label='卡片摘要'
validateStatus={errors.summary ? 'error' : 'default'}
aria-invalid={Boolean(errors.summary)}
value={draft.summary}
placeholder='请输入卡片摘要'
maxCount={200}
rows={3}
onChange={(value) => change('summary', value)}
/>,
true,
)}
{field(
'tag',
'角标标签',
<Input
aria-label='角标标签'
validateStatus={errors.tag ? 'error' : 'default'}
aria-invalid={Boolean(errors.tag)}
value={draft.tag}
maxLength={12}
placeholder='例如 NEW、推荐'
onChange={(value) => change('tag', value)}
/>,
)}
<Typography.Title
heading={5}
className='website-insights-section-title website-insights-detail-title'
>
详情内容
</Typography.Title>
{field(
'body',
'文章正文',
<ArticleRichEditor
value={draft.body}
invalid={Boolean(errors.body)}
onChange={(value) => change('body', value)}
onBusyChange={setProcessingImage}
/>,
true,
)}
</div>
<aside className='website-insights-aside'>
<Card title='文章目录'>
<Checkbox
checked={draft.toc}
onChange={(e) => change('toc', e.target.checked)}
>
根据正文标题自动生成
</Checkbox>
<div className='website-insights-toc'>
{!draft.toc ? (
<Typography.Text type='tertiary'>
已关闭目录展示
</Typography.Text>
) : info.headings.length ? (
info.headings.map((h, i) => (
<div
key={i}
style={{ paddingLeft: h.level === 'H3' ? 12 : 0 }}
>
{h.text}
</div>
))
) : (
<Typography.Text type='tertiary'>
添加 H2 / H3 标题后自动生成目录
</Typography.Text>
)}
</div>
</Card>
<Card title={`相关推荐(${draft.related.length} / 3)`}>
<div className='website-insights-related'>
{insights.articles
.filter((a) => a.id !== draft.id)
.map((a) => (
<Checkbox
key={a.id}
checked={draft.related.includes(a.id)}
disabled={
!draft.related.includes(a.id) && draft.related.length >= 3
}
onChange={(e) =>
change(
'related',
e.target.checked
? [...draft.related, a.id]
: draft.related.filter((id) => id !== a.id),
)
}
>
{a.title}
</Checkbox>
))}
</div>
{!insights.articles.some((a) => a.id !== draft.id) && (
<Typography.Text type='tertiary'>
暂无可推荐的其他文章
</Typography.Text>
)}
{errors.related && (
<Typography.Text type='danger'>{errors.related}</Typography.Text>
)}
</Card>
<Card title='展示说明'>
<Typography.Paragraph type='tertiary'>
列表页:标题、摘要、分类、日期、角标。
</Typography.Paragraph>
<Typography.Text type='tertiary'>
详情页:副标题(留空时使用摘要)、正文、目录和推荐。
</Typography.Text>
</Card>
</aside>
</div>
</SideSheet>
);
}
@@ -0,0 +1,33 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import RichTextEditor from '../../components/common/ui/RichTextEditor';
import { ARTICLE_BODY_LIMIT } from '../../components/common/ui/richTextLength';
export default function ArticleRichEditor(props) {
return (
<RichTextEditor
{...props}
maxLength={ARTICLE_BODY_LIMIT}
label='文章正文'
placeholder='请输入文章正文,支持文本、图片及复制粘贴'
/>
);
}
+417
View File
@@ -0,0 +1,417 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import {
Button,
Card,
Empty,
Input,
Modal,
Select,
Typography,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconSearch,
IconEdit,
IconClose,
} from '@douyinfe/semi-icons';
import CardTable from '../../components/common/ui/CardTable';
import { showError, showInfo } from '../../helpers';
import {
categoryError,
createContentId,
filterArticles,
newArticle,
removeArticle,
} from './insightsModel';
import ArticleEditor from './ArticleEditor';
export default function InsightsPanel({ value, onChange, disabled, error }) {
const [keyword, setKeyword] = useState('');
const [category, setCategory] = useState('all');
const [managing, setManaging] = useState(false);
const [categoryDraft, setCategoryDraft] = useState(null);
const [categoryMessage, setCategoryMessage] = useState('');
const [article, setArticle] = useState(null);
const activeCategory = value.categories.some((c) => c.id === category)
? category
: 'all';
const rows = filterArticles(value, keyword, activeCategory);
const count = (id) =>
id === 'all'
? value.articles.length
: value.articles.filter((a) => a.category === id).length;
const selectCategory = (id) => {
setCategory(id);
};
const editCategory = (item = { id: '', name: '' }) => {
setCategoryMessage('');
setCategoryDraft({ ...item });
};
const saveCategory = () => {
const message = categoryError(
categoryDraft.name,
value.categories,
categoryDraft.id,
);
if (message) {
setCategoryMessage(message);
return;
}
const item = {
id: categoryDraft.id || createContentId(),
name: categoryDraft.name.trim(),
};
onChange({
...value,
categories: categoryDraft.id
? value.categories.map((c) => (c.id === item.id ? item : c))
: [...value.categories, item],
});
setCategoryDraft(null);
};
const deleteCategory = (item) => {
if (count(item.id)) {
showError('该分类下仍有文章,请先调整文章所属分类,再删除分类。');
return;
}
Modal.confirm({
title: '删除分类',
content: `确定删除“${item.name}”分类吗?点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => {
onChange({
...value,
categories: value.categories.filter((c) => c.id !== item.id),
});
if (category === item.id) selectCategory('all');
},
});
};
const deleteArticle = (item) =>
Modal.confirm({
title: '删除文章',
content: `确定删除“${item.title}”吗?删除后将同步清理其他文章中的推荐引用。点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => onChange(removeArticle(value, item.id)),
});
const applyArticle = (draft) => {
const next = { ...draft, id: draft.id || createContentId() };
onChange({
...value,
articles: draft.id
? value.articles.map((a) => (a.id === draft.id ? next : a))
: [next, ...value.articles],
});
setArticle(null);
showInfo('文章已应用到当前配置,请点击页面底部“保存”统一提交。');
};
const columns = [
{
title: '文章标题',
dataIndex: 'title',
width: 420,
render: (_, item) => (
<div className='website-insights-article-meta'>
<button
type='button'
className='website-insights-title'
title={item.title}
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
{item.title}
</button>
<Typography.Paragraph
type='tertiary'
className='truncate'
title={item.summary}
style={{ marginBottom: 0 }}
>
{item.summary}
</Typography.Paragraph>
</div>
),
},
{
title: '所属分类',
dataIndex: 'category',
width: 140,
render: (id) =>
id === 'all'
? '全部内容'
: value.categories.find((c) => c.id === id)?.name || '未分类',
},
{ title: '发布日期', dataIndex: 'date', width: 140 },
{
title: '操作',
key: 'actions',
width: 160,
render: (_, item) => (
<div className='flex gap-2'>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteArticle(item)}
>
删除
</Button>
</div>
),
},
];
return (
<div className='website-insights'>
{error && (
<Typography.Paragraph type='danger' role='alert'>
{error}
</Typography.Paragraph>
)}
<Card
className='website-insights-categories'
title={
<Typography.Title heading={6} className='truncate' title='内容分类'>
内容分类
</Typography.Title>
}
headerExtraContent={
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setManaging(true)}
>
管理分类
</Button>
}
>
<div className='website-insights-category-list'>
{[{ id: 'all', name: '全部内容' }, ...value.categories].map((c) => (
<div
key={c.id}
className={`website-insights-category ${activeCategory === c.id ? 'is-selected' : ''}`}
>
<Button
type='tertiary'
theme='borderless'
aria-pressed={activeCategory === c.id}
onClick={() => selectCategory(c.id)}
>
<span>{c.name}</span>
<span className='website-insights-category-count'>
{count(c.id)}
</span>
</Button>
{c.id !== 'all' && (
<div className='website-insights-category-actions'>
<Button
type='tertiary'
icon={<IconEdit />}
size='small'
theme='borderless'
aria-label={`编辑${c.name}`}
disabled={disabled}
onClick={() => editCategory(c)}
/>
<Button
icon={<IconClose />}
size='small'
theme='borderless'
type='danger'
aria-label={`删除${c.name}`}
disabled={disabled}
onClick={() => deleteCategory(c)}
/>
</div>
)}
</div>
))}
<Button
type='tertiary'
icon={<IconPlus />}
theme='borderless'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
</div>
</Card>
<div className='website-insights-toolbar'>
<Input
prefix={<IconSearch />}
aria-label='搜索文章标题或摘要'
placeholder='搜索文章标题或摘要'
value={keyword}
showClear
onEnterPress={(event) => event.preventDefault()}
onChange={(text) => {
setKeyword(text);
}}
/>
<Select
aria-label='筛选文章分类'
value={activeCategory}
optionList={[
{ label: '全部分类', value: 'all' },
...value.categories.map((c) => ({ label: c.name, value: c.id })),
]}
onChange={selectCategory}
/>
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => {
setArticle(newArticle(activeCategory));
}}
>
新增文章
</Button>
</div>
<CardTable
rowKey='id'
columns={columns}
dataSource={rows}
scroll={{ x: 860 }}
empty={<Empty description='暂无匹配的文章,请调整筛选条件或新增文章' />}
hidePagination
/>
<Modal
visible={managing}
title='管理分类'
onCancel={() => setManaging(false)}
footer={
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
}
>
<Typography.Paragraph type='tertiary'>
“全部内容”为默认分类,也汇总展示全部文章;已有文章的自定义分类需先迁移文章再删除。
</Typography.Paragraph>
<div className='website-insights-manage-row'>
<span>全部内容</span>
<Typography.Text type='tertiary'>
默认分类(不可删除)
</Typography.Text>
</div>
{value.categories.map((c) => (
<div className='website-insights-manage-row' key={c.id}>
<span>
{c.name}({count(c.id)} 篇)
</span>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => editCategory(c)}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteCategory(c)}
>
删除
</Button>
</div>
))}
</Modal>
<Modal
visible={Boolean(categoryDraft)}
title={categoryDraft?.id ? '编辑分类' : '新增分类'}
onCancel={() => setCategoryDraft(null)}
onOk={saveCategory}
okText='确定'
cancelText='取消'
okButtonProps={{ disabled }}
>
<Typography.Paragraph
className='website-category-dialog-description'
type='tertiary'
>
分类名称将用于官网导航与文章分类标签。
</Typography.Paragraph>
<div className='website-category-dialog-field'>
<label
htmlFor='website-category-name'
className='website-category-dialog-label'
>
分类名称 <span aria-hidden='true'>*</span>
</label>
<Input
id='website-category-name'
aria-required='true'
aria-invalid={Boolean(categoryMessage)}
aria-describedby={
categoryMessage ? 'website-category-name-error' : undefined
}
aria-label='分类名称'
value={categoryDraft?.name || ''}
maxLength={12}
placeholder='请输入分类名称,最多 12 个字符'
validateStatus={categoryMessage ? 'error' : 'default'}
onChange={(name) => {
setCategoryDraft((previous) => ({ ...previous, name }));
setCategoryMessage('');
}}
onEnterPress={saveCategory}
/>
{categoryMessage && (
<Typography.Text
id='website-category-name-error'
type='danger'
role='alert'
>
{categoryMessage}
</Typography.Text>
)}
</div>
</Modal>
{article && (
<ArticleEditor
initial={article}
insights={value}
onApply={applyArticle}
onClose={() => setArticle(null)}
/>
)}
</div>
);
}
+138
View File
@@ -0,0 +1,138 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import { Button, Image, Typography } from '@douyinfe/semi-ui';
import { Upload } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { showError } from '../../helpers';
import { validateImageFile } from './model';
import { uploadWebsiteQrCode } from './settingsApi';
export default function QrCodeUpload({
value,
onChange,
busy,
onBusyChange,
resetVersion,
invalid,
}) {
const { t } = useTranslation();
const inputRef = useRef(null);
const requestVersion = useRef(0);
const [uploading, setUploading] = useState(false);
useEffect(() => {
requestVersion.current += 1;
setUploading(false);
onBusyChange(false);
if (inputRef.current) inputRef.current.value = '';
return () => {
requestVersion.current += 1;
onBusyChange(false);
};
}, [resetVersion, onBusyChange]);
const upload = async (event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (!file) return;
const error = validateImageFile(file);
if (error) {
showError(t(error));
return;
}
const version = ++requestVersion.current;
setUploading(true);
onBusyChange(true);
try {
// Verify the content is decodable, rather than trusting the filename or MIME alone.
try {
const bitmap = await createImageBitmap(file);
bitmap.close();
} catch {
throw new Error(
'无法读取二维码图片,请选择有效的 JPG、PNG 或 WebP 图片',
);
}
if (version !== requestVersion.current) return;
const url = await uploadWebsiteQrCode(file);
if (version === requestVersion.current) onChange(url);
} catch (err) {
if (version === requestVersion.current)
showError(t(err.message || '二维码上传失败,请选择有效图片后重试'));
} finally {
if (version === requestVersion.current) {
setUploading(false);
onBusyChange(false);
}
}
};
return (
<div
className='flex flex-wrap items-center gap-4 rounded-lg border border-dashed p-4'
style={{
borderColor: invalid
? 'var(--semi-color-danger)'
: 'var(--semi-color-border)',
background: 'var(--semi-color-fill-0)',
}}
>
{value ? (
<div className='relative inline-flex'>
<Image
src={value}
width={100}
height={100}
style={{ objectFit: 'contain' }}
alt={t('企业微信二维码')}
/>
</div>
) : (
<Upload size={28} className='m-4 text-[var(--semi-color-text-2)]' />
)}
<div className='flex flex-col gap-2'>
<input
ref={inputRef}
type='file'
accept='image/jpeg,image/png,image/webp'
onChange={upload}
hidden
/>
<Button
icon={<Upload size={14} />}
loading={uploading}
disabled={busy || uploading}
onClick={() => inputRef.current?.click()}
>
{t(value ? '重新上传' : '上传二维码')}
</Button>
<Typography.Text type='tertiary' size='small'>
{t('支持 JPG、PNG、WebP,单张不超过 2 MB')}
</Typography.Text>
{value && (
<Typography.Text type='tertiary' size='small'>
{t('点击图片可放大预览')}
</Typography.Text>
)}
</div>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
# 官网设置接入说明
二维码使用后端上传与 HTTP(S) 绝对地址校验,缩略图支持放大预览和替换。
## 单一表单数据
首页、关于微词元、预约演示、动态与洞察共用一个配置对象,切换页签保留输入。
teamMembers 在两个页签共用,不生成不同的副本。原有 11 个字段均必填。
动态与洞察绑定 insights 对象,包含 categories 和 articles,不按页签拆分保存。
model.js 定义字段、页签、初始化、标准化和校验规则。
保存按首页、关于微词元、预约演示、动态与洞察顺序校验全部字段,错误保存在各表单项内。
空输入框提示“请输入中文字段名”,选择框提示“请选择中文字段名”,二维码提示“请上传企业微信二维码”。
每个非当前页签有错误时只显示一条“请完善某页签的配置”警告,不列出全部字段,不自动切换页签。
当前页签只显示表单项错误;切换页签后,其他页签的错误状态仍会显示。
清空会清除全部字段、二维码、错误状态,同时让尚未完成的上传结果失效。
## 读取与保存接口
进入页面 GET /api/website/page-config,解析 data 字符串并回填所有页签。
data 为 null 时回填空表单。读取失败可重试,成功前禁止编辑和保存,避免覆盖原配置。
保存 POST /api/website/page-config,请求为 { config: JSON.stringify(完整配置) }。
config 内部按 home/about/demo 分组;动态与洞察保存在 insights 扩展字段。
paidCustomers/dailyTokens/costReduction 分别映射 home.payingCustomers/dailyTokenCalls/monthlyAiCostReduction。
teamMembers/researchRatio 映射 about.teamMembers/researchStaffRatio;首页和关于页共用这两个值。
其余总部、服务网络和商务字段依联调文档映射。保存保留后端返回的未知字段。
严格检查 success === true 后才提示成功,失败保留当前编辑。提交期间防止重复请求。
完整配置按 UTF-8 字节限制为 60 KiB,超限时提示精简内容。
客户数和人数支持正整数及末尾 +;Token 支持正数、万/亿单位及末尾 +。
百分比支持 0~100,最多两位小数,% 可选。上述展示值以字符串提交。
## 二维码上传
复用客服模块 POST /api/customer-service/upload,multipart 字段 file。
期望响应 { success: true, data: { url: "https://公共资源域名/图片路径" } }。
前端限制 JPG/PNG/WebP、0~2 MB(不含 0),并在上传前尝试解码图片。
上传返回 HTTP(S) 绝对 URL 后才写入表单,可预览和替换。
切换页签或清空会使旧上传回调失效。
如果接口返回 /uploads/...,配置 VITE_WEBSITE_ASSET_BASE_URL 为公开资源域名;
禁止用开发代理地址、blob: 或 data: 地址作为提交资源路径。
绝对 URL 只保证地址形式正确,后端还需要保证图片无需后台登录即可被官网访问,
并在 HTTPS 官网部署时提供 HTTPS 图片地址。需在联调时通过未登录环境验证。
清空只移除配置引用,不删除服务器文件,文件回收由后端确定。
管理接口复用项目 API 实例的登录 Cookie 和 New-Api-User,401 沿用重新登录流程。
## 验证
```sh
node --test src/pages/WebsiteSettings/*.test.js src/components/common/ui/richTextImages.test.js
```
## 动态与洞察
InsightsPanel.jsx 承载分类管理、文章列表、标题/摘要即时搜索和分类筛选。
搜索为纯前端模糊匹配,不请求后端;不设分页,展示当前筛选后的全部文章。
ArticleEditor.jsx 承载文章新增/编辑抽屉,ArticleRichEditor.jsx 复用公共 RichTextEditor。
公共组件位于 src/components/common/ui/RichTextEditor.jsx,基于 Quill 2.0.3 core 封装,按需注册所用格式。
上游项目:https://github.com/slab/quill,BSD-3-Clause 许可;直接封装核心,不额外依赖 React 适配包。
支持 H2/H3、加粗、斜体、下划线、无序/有序列表、引用、撤销/重做、清除格式和图片。
工具栏采用独立的中性样式,避免项目 primary 按钮全局渐变影响编辑工具和选中状态。
默认保留公司动态、产品更新、行业洞察三个分类,文章为空,不向官网注入原型示例文章。
单篇文章结构:
```json
{
"id": "由前端生成的 UUID,后续可替换为后端 ID",
"title": "文章标题",
"category": "all",
"date": "2026-10-31",
"subtitle": "详情副标题,空值时由官网使用 summary",
"summary": "卡片摘要",
"tag": "NEW",
"body": "<h2>章节标题</h2><p>文章正文</p>",
"toc": true,
"related": []
}
```
必填:title(最多 80 字)、category、date、summary(最多 200 字)、body。
subtitle 最多 160 字,tag 最多 12 字,推荐最多 3 篇且不能选择自己。
正文 H2/H3 自动生成目录预览;toc 为是否展示目录,官网可从 body 提取标题。
“全部内容”是内置默认归属(category 为 all),也汇总展示所有分类的文章,不存入自定义 categories 数组。
新增文章默认归属当前分类,从全部内容新增时直接归属 all;自定义分类为空时也可新增文章。
分类名称最多 12 字,禁止空白、重名和系统保留名称;已有文章的自定义分类不能直接删除,可先迁移到全部内容。
删除文章同步清理其他文章的 related 引用。列表按发布日期倒序排列。
文章抽屉“保存”、分类编辑与文章删除只更新当前内存配置,不请求后端保存接口。
页面底部“保存”统一校验四个页签后,将整个配置序列化为 JSON 字符串调用 saveWebsiteSettings。
保存成功后刷新会从后端回填;文章抽屉内保存仅更新本地,仍需点击页面底部保存。
文章抽屉必填项错误只在字段内提示,不弹出汇总错误 Toast;不提供封面字段。
正文支持复制/粘贴 HTML 图文、剪贴板图片文件,以及工具栏选择本地图片。
HTTP(S) 图片保留绝对地址;JPG/PNG/WebP/GIF 内嵌图片每张限制 2 MB,
本地文件先解码校验,编辑期间使用 Base64 data URI;页面最终保存前上传到图片接口,将 body 中的图片替换为公开 URL。
相同内嵌图片在一次保存中仅上传一次;上传失败终止配置保存并保留本地内容。
二维码仍走原后端上传接口并强制 HTTP(S) 绝对地址,与文章内嵌图片分开处理。
HTML 在粘贴、编辑输出、应用文章时均进行白名单清理,不保留事件属性、脚本或 SVG 图片。
使用 getSemanticHTML 导出标准 HTML 列表,无需官网额外依赖 Quill 的 CSS 或 Delta 数据结构。
不可访问的外链图片会在编辑器内提示,需换为可公开访问的地址或插入本地文件。
不抓取第三方图片,无法自动绕过防盗链、登录权限及浏览器的混合内容限制。
后端正式接入时仍应进行服务端 HTML 清理(允许受限的图片 data URI)与权限校验,
官网 CSP 如有 img-src 白名单,需允许 data: 和所用图片域名。
@@ -0,0 +1,63 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Form, Input } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { FIELDS } from './model';
export default function WebsiteField({
name,
value,
error,
onChange,
onBlur,
disabled,
children,
}) {
const { t } = useTranslation();
const field = FIELDS[name];
return (
<Form.Slot
label={{ text: t(field.label), required: true, name: `website-${name}` }}
error={{
error: error ? t(error) : undefined,
errorMessageId: `website-${name}-error`,
}}
>
{children || (
<Input
id={`website-${name}`}
aria-label={t(field.label)}
aria-required={true}
aria-invalid={Boolean(error)}
aria-describedby={error ? `website-${name}-error` : undefined}
value={value}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
placeholder={t(field.placeholder)}
validateStatus={error ? 'error' : 'default'}
maxLength={name === 'businessEmail' ? 254 : 200}
showClear
/>
)}
</Form.Slot>
);
}
@@ -0,0 +1,264 @@
.website-settings-page {
display: flex;
flex-direction: column;
box-sizing: border-box;
/* Match Settings: 24px layout padding + 8px page padding on each side. */
padding-inline: 32px;
min-height: calc(100vh - var(--content-top-offset, 0px));
min-height: calc(100dvh - var(--content-top-offset, 0px));
/* PageLayout already inserts the marquee spacer above this page. */
padding-top: calc(
var(--app-header-height, 64px) - var(--content-top-offset, 0px) + 20px
);
padding-bottom: 20px;
}
.website-settings-page .website-settings-card {
flex: 1;
min-height: 100%;
}
.website-settings-page .website-settings-notice .semi-banner-icon {
margin-right: 4px;
}
.website-insights {
min-width: 0;
}
.website-settings-page .website-settings-tab-description {
margin-bottom: 16px;
line-height: 22px;
}
.website-category-dialog-description {
margin: 0 0 18px;
line-height: 22px;
}
.website-category-dialog-field {
display: flex;
flex-direction: column;
gap: 8px;
padding-bottom: 8px;
}
.website-category-dialog-label {
color: var(--semi-color-text-0);
font-weight: 600;
line-height: 20px;
}
.website-category-dialog-label > span {
color: var(--semi-color-danger);
}
.website-insights-categories {
margin-bottom: 20px;
}
.website-insights-category-list,
.website-insights-category,
.website-insights-toolbar,
.website-insights-manage-row,
.website-insights-editor-footer,
.website-rich-tools {
display: flex;
align-items: center;
gap: 8px;
}
.website-insights-category-list,
.website-rich-tools,
.website-insights-editor-footer {
flex-wrap: wrap;
}
.website-insights-category {
border: 1px solid var(--semi-color-border);
border-radius: var(--semi-border-radius-small);
gap: 0;
background: var(--semi-color-fill-0);
min-height: 34px;
padding-inline: 2px;
}
.website-insights-category.is-selected {
border-color: var(--semi-color-primary-light-active);
background: var(--semi-color-primary-light-default);
}
.website-insights-category .semi-button {
background: transparent !important;
border: 0 !important;
border-radius: 3px !important;
box-shadow: none !important;
}
.website-insights-category > .semi-button .semi-button-content {
display: flex;
align-items: center;
gap: 10px;
color: var(--semi-color-text-1);
font-weight: 400;
}
.website-insights-category.is-selected > .semi-button .semi-button-content {
color: var(--semi-color-primary);
}
.website-insights-category-count {
font-size: 12px;
opacity: 0.65;
}
.website-insights-category-actions {
display: flex;
visibility: hidden;
}
.website-insights-category-actions .semi-button {
width: 24px;
height: 24px;
padding: 4px;
}
.website-insights-category .semi-button:hover {
background: var(--semi-color-fill-1) !important;
}
.website-insights-category:hover .website-insights-category-actions,
.website-insights-category:focus-within .website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar {
flex-wrap: wrap;
margin-bottom: 16px;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 290px;
max-width: 100%;
}
.website-insights-toolbar > .semi-select {
width: 160px;
}
.website-insights-toolbar > .semi-button {
margin-left: auto;
}
.website-insights-article-meta {
display: grid;
gap: 4px;
min-width: 0;
}
.website-insights .website-insights-title {
display: block;
width: 100%;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: var(--semi-color-text-0);
font-weight: 500;
line-height: 1.6;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
cursor: pointer;
}
.website-insights .website-insights-title:hover {
color: var(--semi-color-primary);
}
.website-insights .website-insights-title:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 2px;
}
.website-insights-manage-row {
padding-block: 10px;
border-bottom: 1px solid var(--semi-color-border);
}
.website-insights-manage-row > span:first-child {
flex: 1;
}
.website-insights-editor-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 250px;
gap: 24px;
}
.website-insights-editor-main {
min-width: 0;
}
.website-insights-editor-main .website-insights-section-title {
margin: 0 0 14px;
line-height: 24px;
}
.website-insights-editor-main .website-insights-detail-title {
margin-top: 10px;
}
/* SideSheet renders outside Form, so its slots need their own field spacing. */
.website-insights-editor-main .website-insights-editor-field {
min-width: 0;
margin: 0 0 18px;
padding: 0;
}
.website-insights-editor-field > .semi-form-field-label {
margin-bottom: 8px;
}
.website-insights-aside,
.website-insights-related {
display: flex;
flex-direction: column;
gap: 16px;
}
.website-insights-related {
max-height: 260px;
overflow-y: auto;
}
.website-insights-toc {
margin-top: 12px;
line-height: 1.8;
overflow-wrap: anywhere;
}
.website-insights-editor-footer {
justify-content: flex-end;
}
@media (max-width: 767px) {
.website-settings-page {
/* Match the shared mobile layout's 5px plus the page's 8px. */
padding-inline: 13px;
}
.website-insights-editor-layout {
grid-template-columns: minmax(0, 1fr);
}
.website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 100%;
}
}
+285
View File
@@ -0,0 +1,285 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Card,
Form,
Spin,
Tabs,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess, showWarning } from '../../helpers';
import {
TABS,
emptySettings,
settingsFromConfig,
serializeSettings,
validateField,
validateSettings,
} from './model';
import { getWebsiteSettings, saveWebsiteSettings } from './settingsApi';
import WebsiteField from './WebsiteField';
import QrCodeUpload from './QrCodeUpload';
import InsightsPanel from './InsightsPanel';
import './WebsiteSettings.css';
export default function WebsiteSettings() {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('home');
const [values, setValues] = useState(emptySettings);
const [errors, setErrors] = useState({});
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [resetVersion, setResetVersion] = useState(0);
const [dirty, setDirty] = useState(false);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [loadVersion, setLoadVersion] = useState(0);
const originalConfig = useRef({});
const savePending = useRef(false);
useEffect(() => {
let active = true;
setLoading(true);
setLoadError('');
getWebsiteSettings()
.then((config) => {
if (!active) return;
originalConfig.current = config ?? {};
setValues(settingsFromConfig(config));
setDirty(false);
setErrors({});
})
.catch((error) => {
if (active)
setLoadError(error.message || '官网配置读取失败,请稍后重试');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [loadVersion]);
const disabled = saving || loading || Boolean(loadError);
useEffect(() => {
if (!dirty) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty]);
const tab = TABS.find((item) => item.key === activeTab);
const change = (name, value) => {
setDirty(true);
setValues((previous) => ({ ...previous, [name]: value }));
setErrors((previous) =>
previous[name]
? { ...previous, [name]: validateField(name, value) }
: previous,
);
};
const clear = () => {
setDirty(true);
setResetVersion((version) => version + 1);
setValues(emptySettings());
setErrors({});
setUploading(false);
};
const save = async () => {
if (savePending.current || disabled || uploading) return;
const nextErrors = validateSettings(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) {
// Keep field errors for every tab; report each hidden invalid tab only once.
for (const item of TABS) {
if (
item.key !== activeTab &&
item.fields.some((name) => nextErrors[name])
) {
showWarning(t(`请完善${item.label}的配置`));
}
}
return;
}
savePending.current = true;
setSaving(true);
try {
const configurationJson = serializeSettings(
values,
originalConfig.current,
);
const result = await saveWebsiteSettings(configurationJson);
originalConfig.current = result.config ?? JSON.parse(configurationJson);
setValues(settingsFromConfig(originalConfig.current));
setDirty(false);
showSuccess(t('官网设置已保存'));
} catch (error) {
showError(t(error.message || '保存失败,请稍后重试'));
} finally {
setSaving(false);
savePending.current = false;
}
};
return (
<div className='website-settings-page' aria-busy={loading || saving}>
<Spin
spinning={loading || saving}
size='large'
style={{
minHeight: 200,
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'column',
}}
childStyle={{ flex: 1, display: 'flex', flexDirection: 'column' }}
data-testid='website-settings-loading'
>
<Card className='website-settings-card'>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('官网设置')}
</Typography.Title>
<Typography.Paragraph type='tertiary'>
{t('配置官网展示内容与商务联系信息')}
</Typography.Paragraph>
{loadError ? (
<Banner
type='danger'
closeIcon={null}
description={t(loadError)}
fullMode={false}
>
<Button onClick={() => setLoadVersion((version) => version + 1)}>
{t('重新加载')}
</Button>
</Banner>
) : null}
<Tabs type='line' activeKey={activeTab} onChange={setActiveTab}>
{TABS.map((item) => (
<Tabs.TabPane
key={item.key}
itemKey={item.key}
tab={t(item.label)}
/>
))}
</Tabs>
<Form
onSubmit={save}
className={activeTab === 'insights' ? 'py-5' : 'max-w-4xl py-5'}
autoComplete='off'
>
<Typography.Paragraph
type='tertiary'
className='website-settings-tab-description'
>
{t(tab.description)}
</Typography.Paragraph>
{activeTab === 'insights' ? (
<InsightsPanel
key={resetVersion}
value={values.insights}
onChange={(value) => change('insights', value)}
disabled={disabled}
error={errors.insights}
/>
) : (
<div className='grid grid-cols-1 gap-x-7 md:grid-cols-2'>
{tab.fields.map((name) => (
<div
key={name}
className={name === 'address' ? 'md:col-span-2' : ''}
>
<WebsiteField
name={name}
value={values[name]}
error={errors[name]}
disabled={disabled}
onChange={(value) => change(name, value)}
onBlur={() =>
setErrors((previous) => ({
...previous,
[name]: validateField(name, values[name]),
}))
}
>
{name === 'wechatQrCode' && (
<QrCodeUpload
value={values.wechatQrCode}
onChange={(url) => change(name, url)}
busy={disabled}
onBusyChange={setUploading}
resetVersion={resetVersion}
invalid={Boolean(errors[name])}
/>
)}
</WebsiteField>
{activeTab === 'home' && name === 'teamMembers' && (
<Typography.Text type='tertiary' size='small'>
{t('研发人员占比')}:
{values.researchRatio || t('未配置')}
</Typography.Text>
)}
</div>
))}
</div>
)}
<Banner
type='info'
closeIcon={null}
className='website-settings-notice !rounded-lg'
style={{
marginTop: 10,
marginBottom: 2,
paddingTop: 2,
paddingBottom: 2,
}}
description={t('四个页签共用一份配置,保存时将统一校验并提交。')}
/>
<div
className='flex justify-center gap-2'
style={{ marginTop: 18 }}
>
<Button onClick={clear} disabled={disabled}>
{t('清空')}
</Button>
<Button
theme='solid'
htmlType='submit'
loading={saving}
disabled={disabled || uploading}
>
{t('保存')}
</Button>
</div>
</Form>
</Card>
</Spin>
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More