feat: 1.统一右侧抽屉关闭按钮布局 2.统一 UI 组件为 Ant Design 移除 radix-ui、floating-ui 组件 3. 修复 ESLint 文件格式错误的问题

This commit is contained in:
zhanjunhao
2026-11-10 14:08:10 +08:00
parent 28e924e371
commit 584728590b
202 changed files with 29195 additions and 12732 deletions
+29
View File
@@ -14,14 +14,43 @@ module.exports = {
'dist/**',
'node_modules/**',
'logs/**',
'report/**',
'playwright-report/**',
'test-results/**',
'blob-report/**',
'src/assets/brand-icons/*.js',
],
overrides: [
{
files: ['**/*.{js,jsx}'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: [
'@radix-ui/*',
'@floating-ui/*',
'@lobehub/ui',
'@lobehub/ui/*',
'@lobehub/icons',
'@lobehub/icons/*',
'@douyinfe/semi-*',
'@headlessui/*',
'@mui/*',
'@chakra-ui/*',
'leva',
'leva/*',
'antd-style',
'react-layout-kit',
],
message:
'Use antd public APIs or the audited local brand SVG assets. Preserve legacy components/ui callback contracts.',
},
],
},
],
'header/header': [
2,
'block',
+7
View File
@@ -0,0 +1,7 @@
# Match Prettier's LF output even when core.autocrlf is enabled on Windows.
* text=auto eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
# Generated icon provenance hashes must survive Windows checkouts unchanged.
src/assets/brand-icons/*.js text eol=lf
+2
View File
@@ -15,6 +15,8 @@ node_modules/
/tests/
*.test.*
*.spec.*
# Maintained unit regressions are source; local acceptance suites stay ignored.
!test/unit/*.test.js
/playwright/.auth/
/playwright-report/
/test-results/
+1
View File
@@ -10,6 +10,7 @@ coverage/
# Generated browser evidence is not source code.
logs/
report/
playwright-report/
test-results/
blob-report/
+4
View File
@@ -2,6 +2,10 @@
适用于本仓库,不要重复加载全文。
## Ant Design 依赖统一(2026-11-10)
通用 UI 使用 `antd`;旧 `src/components/ui` 是 Ant Design 契约适配层,保留值回调、Form API 和分页语义。模型品牌图标使用 `src/assets/brand-icons/` 的固定版本本地 SVG:首页与 `helpers/render.jsx` 只导入 `primitives`,完整变体仍经 `LobeHubIcon` 懒加载;头像容器使用 Ant `Avatar`,主题复用现有 Theme Context。不得重装 `@lobehub/icons`、`@lobehub/ui`、Radix UI、Floating UI、leva、antd-style 或 react-layout-kit。生成资产须通过脚本维护并保留 MIT 许可证及 hash。运行 `npm run check:ui` 检查源码、完整 lock 图和资产 hash;专用图表、流程画布、编辑器与引导保留。方案、风险和验证结果见 `docs/ui/ANTD_UNIFICATION_PLAN.md`;证据仅放忽略目录 `report/ui-unification/`。
## 三中心表格列设置统一(2026-11-07)
`/user-center/*`、`/console/*`、`/org/*` 的已有列设置统一使用 `src/components/common/table/ColumnSettings.jsx` 与 `column-settings.css`,详细入口清单见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`。齿轮入口放在表格卡片工具栏最右侧(CardPro 使用 `tableActions`),不得混入搜索表单;使用原生 Ant Design Modal / Checkbox / Button,参考本地“微元优化原型”消费记录列设置:宽 520px、两列选项、全选与分隔线、底部重置 / 取消 / primary 确定、遮罩 blur(4px) 且可关闭。选项来自当前表格列及权限;单列 / 全选 / 重置先改草稿,确认后一次应用,至少保留一列;取消 / X / Esc / 遮罩均放弃草稿。默认列、角色限制和原持久化键保持原样,个人 / 企业密钥列设置仍不持久化;不为没有列设置的表格新增功能。本节覆盖旧密钥页 Popover 约定。验收产物在忽略目录 `report/column-settings/`,重任务串行并监测资源,不执行生产构建。
+4
View File
@@ -2,6 +2,10 @@
适用于本仓库,不要重复加载全文。
## Ant Design 依赖统一(2026-11-10)
通用 UI 使用 `antd`;旧 `src/components/ui` 是 Ant Design 契约适配层,保留值回调、Form API 和分页语义。模型品牌图标使用 `src/assets/brand-icons/` 的固定版本本地 SVG:首页与 `helpers/render.jsx` 只导入 `primitives`,完整变体仍经 `LobeHubIcon` 懒加载;头像容器使用 Ant `Avatar`,主题复用现有 Theme Context。不得重装 `@lobehub/icons`、`@lobehub/ui`、Radix UI、Floating UI、leva、antd-style 或 react-layout-kit。生成资产须通过脚本维护并保留 MIT 许可证及 hash。运行 `npm run check:ui` 检查源码、完整 lock 图和资产 hash;专用图表、流程画布、编辑器与引导保留。方案、风险和验证结果见 `docs/ui/ANTD_UNIFICATION_PLAN.md`;证据仅放忽略目录 `report/ui-unification/`。
## 三中心表格列设置统一(2026-11-07)
`/user-center/*`、`/console/*`、`/org/*` 的已有列设置统一使用 `src/components/common/table/ColumnSettings.jsx` 与 `column-settings.css`,详细入口清单见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`。齿轮入口放在表格卡片工具栏最右侧(CardPro 使用 `tableActions`),不得混入搜索表单;使用原生 Ant Design Modal / Checkbox / Button,参考本地“微元优化原型”消费记录列设置:宽 520px、两列选项、全选与分隔线、底部重置 / 取消 / primary 确定、遮罩 blur(4px) 且可关闭。选项来自当前表格列及权限;单列 / 全选 / 重置先改草稿,确认后一次应用,至少保留一列;取消 / X / Esc / 遮罩均放弃草稿。默认列、角色限制和原持久化键保持原样,个人 / 企业密钥列设置仍不持久化;不为没有列设置的表格新增功能。本节覆盖旧密钥页 Popover 约定。验收产物在忽略目录 `report/column-settings/`,重任务串行并监测资源,不执行生产构建。
+57 -57
View File
@@ -1,6 +1,6 @@
# Monkey AI Web 前端开发指南
本仓库是从 `weiyuan` 分支的的独立前端,用于 AI 体验中心、企业空间、用户中心和管理控制台。本文面向接手开发、联调和部署的前端工程师。
本仓库是从 `weiyuan` 分支的的独立前端,用于 AI 体验中心、企业空间、用户中心和管理控制台。本文面向接手开发、联调和部署的前端工程师。
初次接手项目,建议先阅读 [项目分析与开发上手指南](./docs/PROJECT_ANALYSIS.zh-CN.md),了解技术栈、架构、核心业务链路及开发规范。
@@ -12,17 +12,17 @@
## 1. 技术栈
| 用途 | 当前方案 |
| --- | --- |
| 页面开发 | React 18,JavaScript / JSX,ES Modules |
| 构建与开发服务 | Vite 5,npm 锁文件 `package-lock.json` |
| 路由 | React Router 6,BrowserRouter |
| UI 与样式 | Semi Design、Tailwind CSS 3、CSS 变量;清单另有 antd 5 |
| 请求与流式响应 | Axios、Fetch、`sse.js` |
| 状态管理 | React Context 和业务 Hooks |
| 国际化 | i18next、react-i18next |
| 富文本与可视化 | React Markdown、KaTeX、Mermaid、VChart、React Flow |
| 测试与检查 | Node.js 内置测试运行器、ESLint 8、Prettier 3 |
| 用途 | 当前方案 |
| -------------- | ------------------------------------------------------ |
| 页面开发 | React 18,JavaScript / JSX,ES Modules |
| 构建与开发服务 | Vite 5,npm 锁文件 `package-lock.json` |
| 路由 | React Router 6,BrowserRouter |
| UI 与样式 | Semi Design、Tailwind CSS 3、CSS 变量;清单另有 antd 5 |
| 请求与流式响应 | Axios、Fetch、`sse.js` |
| 状态管理 | React Context 和业务 Hooks |
| 国际化 | i18next、react-i18next |
| 富文本与可视化 | React Markdown、KaTeX、Mermaid、VChart、React Flow |
| 测试与检查 | Node.js 内置测试运行器、ESLint 8、Prettier 3 |
具体声明与锁定版本见 [package.json](./package.json) 和 [package-lock.json](./package-lock.json)。应用主要使用 JS / JSX,build 不包含独立类型检查。
@@ -47,10 +47,10 @@ npm run dev
项目已提供两个自动加载的环境配置,无需复制示例文件:
| 命令 | 默认模式 | 配置文件 |
| --- | --- | --- |
| `npm run dev` | development | `.env.development` |
| `npm run build` | production | `.env.production` |
| 命令 | 默认模式 | 配置文件 |
| ----------------- | ------------ | ------------------------------------------ |
| `npm run dev` | development | `.env.development` |
| `npm run build` | production | `.env.production` |
| `npm run preview` | 预览已有产物 | 使用构建时已写入的配置,不重新应用环境变量 |
个人覆盖配置可写入 `.env.development.local` 或 `.env.production.local`(Git 忽略)。同名变量优先级从高到低:启动终端/CI > `.env.[mode].local` > `.env.[mode]` > `.env.local` > `.env`。旧的 `.env.local` 仍被加载,但与模式文件重名的变量会被模式文件覆盖,请迁移到对应的 `.local` 文件。可通过 Vite 的 `--mode` 显式选择其他模式。
@@ -93,12 +93,12 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
### 其他配置
| 配置 | 作用 | 生效方式 |
| --- | --- | --- |
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 |
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 按当前 mode 加载环境文件,终端/CI 优先 |
| `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` |
| `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 |
| 配置 | 作用 | 生效方式 |
| ----------------------------- | -------------------------------- | ------------------------------------------------- |
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 |
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 按当前 mode 加载环境文件,终端/CI 优先 |
| `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` |
| `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 |
统计脚本插件与前端配置共用 Vite 环境加载规则;ID 留空时不注入脚本。生产统计 ID 通常只配置在 `.env.production` 或生产 CI 中。
@@ -139,19 +139,19 @@ monkey-ai-web/
### 常用业务入口
| 功能 | 路由示例 | 代码位置 |
| --- | --- | --- |
| 首页 | `/`、`/home` | `src/pages/Home/` |
| 登录与注册 | `/login`、`/register`、`/org/login`、`/org/register` | `src/components/auth/`、`src/pages/OrgLogin/`、`src/pages/OrgRegister/` |
| 体验中心 | `/experience-center/*` | `src/pages/ExperienceCenter/` |
| 对话能力 | `/experience-center/text-model`、`/console/playground` | `src/pages/Playground/`、`src/hooks/playground/` |
| 图片与视频 | `/experience-center/image-generation`、`/experience-center/video-generation` | `src/pages/ExperienceCenter/components/`、`src/hooks/image/`、`src/hooks/video/` |
| 模型超市 | `/market`(`/pricing` 重定向至此) | `src/pages/Pricing/` |
| 密钥管理 | `/key-management` | `src/pages/KeyManagement/` |
| 用户中心与充值 | `/user-center/*`、`/recharge` | `src/pages/UserCenter/`、`src/pages/Recharge/` |
| 企业空间 | `/org/*` | `src/pages/Organization/`、`src/hooks/org/` |
| 管理控制台 | `/console/channel`、`/console/user`、`/console/setting` 等 | `src/pages/Channel/`、`src/pages/User/`、`src/pages/Setting/` |
| 客户端授权与下载 | `/client/authorize`、`/weyai/download` | `src/pages/ClientAuthorize/`、`src/pages/WeyAiDownload/` |
| 功能 | 路由示例 | 代码位置 |
| ---------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| 首页 | `/`、`/home` | `src/pages/Home/` |
| 登录与注册 | `/login`、`/register`、`/org/login`、`/org/register` | `src/components/auth/`、`src/pages/OrgLogin/`、`src/pages/OrgRegister/` |
| 体验中心 | `/experience-center/*` | `src/pages/ExperienceCenter/` |
| 对话能力 | `/experience-center/text-model`、`/console/playground` | `src/pages/Playground/`、`src/hooks/playground/` |
| 图片与视频 | `/experience-center/image-generation`、`/experience-center/video-generation` | `src/pages/ExperienceCenter/components/`、`src/hooks/image/`、`src/hooks/video/` |
| 模型超市 | `/market`(`/pricing` 重定向至此) | `src/pages/Pricing/` |
| 密钥管理 | `/key-management` | `src/pages/KeyManagement/` |
| 用户中心与充值 | `/user-center/*`、`/recharge` | `src/pages/UserCenter/`、`src/pages/Recharge/` |
| 企业空间 | `/org/*` | `src/pages/Organization/`、`src/hooks/org/` |
| 管理控制台 | `/console/channel`、`/console/user`、`/console/setting` 等 | `src/pages/Channel/`、`src/pages/User/`、`src/pages/Setting/` |
| 客户端授权与下载 | `/client/authorize`、`/weyai/download` | `src/pages/ClientAuthorize/`、`src/pages/WeyAiDownload/` |
路由是否可访问还受用户权限、后端模块配置和前端功能开关影响,具体以 `App.jsx` 和对应页面为准。
@@ -203,18 +203,18 @@ npm run i18n:lint
## 6. 常用命令与提交检查
| 命令 | 用途 |
| --- | --- |
| `npm run dev` | 启动开发服务 |
| `npm run build` | Vite 生产构建,输出 `dist/` |
| `npm run preview` | 预览构建结果,默认端口 4173 |
| `npm run test` | 调用 `node --test` 执行现有测试 |
| `npm run check` | 依次执行 ESLint、测试和生产构建,任一步失败即停止 |
| `npm run eslint` | JS / JSX 静态检查 |
| `npm run eslint:fix` | 自动修复可修复的 ESLint 问题 |
| `npm run lint` | Prettier 格式检查,并非 ESLint |
| `npm run lint:fix` | Prettier 全项目格式化,会批量修改文件 |
| `npm run i18n:sync` | 同步语言资源结构 |
| 命令 | 用途 |
| -------------------- | ------------------------------------------------- |
| `npm run dev` | 启动开发服务 |
| `npm run build` | Vite 生产构建,输出 `dist/` |
| `npm run preview` | 预览构建结果,默认端口 4173 |
| `npm run test` | 调用 `node --test` 执行现有测试 |
| `npm run check` | 依次执行 ESLint、测试和生产构建,任一步失败即停止 |
| `npm run eslint` | JS / JSX 静态检查 |
| `npm run eslint:fix` | 自动修复可修复的 ESLint 问题 |
| `npm run lint` | Prettier 格式检查,并非 ESLint |
| `npm run lint:fix` | Prettier 全项目格式化,会批量修改文件 |
| `npm run i18n:sync` | 同步语言资源结构 |
建议开发分支从 `weiyuan` 创建。提交前执行相关测试、ESLint 和构建,检查登录、修改页面、接口错误提示与移动布局。`npm run build` 只执行 Vite 构建,不会自动执行 ESLint 或测试。
@@ -247,16 +247,16 @@ npm run preview
## 8. 常见问题
| 现象 | 优先检查 |
| --- | --- |
| 现象 | 优先检查 |
| ---------------------------------------- | -------------------------------------------------------------------------- |
| 页面可打开,但提示无法加载状态或接口失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;Vite 代理是否正确 |
| 登录后仍回到登录页 | `/api/user/self`、Cookie 是否发送、跨域凭证策略,以及测试账号状态 |
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求中的 `X-Org-Id` |
| 修改环境变量后无变化 | 是否重启开发服务或重新构建并发布;构建时的变量值;HTML 与静态资源缓存 |
| 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 |
| 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML |
| 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 |
| 格式检查提示大量 Code style issues | 全仓仍有历史格式差异;保留统一配置,只格式化本次修改文件 |
| 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 HTML / 静态资源缓存 |
| 登录后仍回到登录页 | `/api/user/self`、Cookie 是否发送、跨域凭证策略,以及测试账号状态 |
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求中的 `X-Org-Id` |
| 修改环境变量后无变化 | 是否重启开发服务或重新构建并发布;构建时的变量值;HTML 与静态资源缓存 |
| 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 |
| 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML |
| 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 |
| 格式检查提示大量 Code style issues | 全仓仍有历史格式差异;保留统一配置,只格式化本次修改文件 |
| 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 HTML / 静态资源缓存 |
首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 选择已配置的测试模型验证对话。接口字段和业务权限问题需与后端负责人共同确认。
+8
View File
@@ -1,5 +1,13 @@
# 后台 UI 改造记录
## Ant Design 依赖统一与品牌图标解耦(2026-11-10)
方案及验收明细见 `docs/ui/ANTD_UNIFICATION_PLAN.md`。源码没有直接导入 Radix / Floating UI;实际链路是 `@lobehub/icons → @lobehub/ui / leva → Radix / Floating UI`。将现有 30 个品牌、137 个标志和变体提取为保留 MIT 许可证、来源清单及生成 hash 的本地 SVG 模块,头像容器使用 Ant `Avatar`,Dify / Moonshot 主题判断复用现有 Theme Context。首页与渲染助手仅导入基础图形,完整变体仍延迟加载;配置语法、fallback、旧 Ant 适配层及业务契约保留。
移除 196 个安装依赖,保留包版本变化 0。增加 `check:ui`、ESLint 禁止导入规则及生成文件 LF 约束,检查源码、完整 lock 图和资产 hash;忽略生成验收产物的格式与源码检查。AGENTS / CLAUDE 入口已同步。图表、画布、编辑器与引导属于专门功能,保留原实现。
验证:图标及依赖检查 9/9;全量测试 453/463,失败仍为迁移前同一批 10 项;本次修改源码 ESLint 0 错误,全仓仍有 11 个既有错误,格式检查仍有 804 个问题文件。桌面 / 移动、浅深色的 SVG 对照除暗色 Dify 两个标志跟随应用主题外一致,浏览器运行错误 0。2.9GB 堆限制、临时目录构建通过,8,979 个最终模块中目标依赖 0,进程采样工作集峰值约 2.67GB。证据位于忽略目录 `report/ui-unification/`;不宣称全站真实账号联调或像素验收通过。
## 双中心侧栏与容器按附件对齐(2026-11-06)
- 本轮附件图 1 为视觉标准,图 2 红框为重点;统一 `/org/*` 与 `/user-center/*` 菜单页面的共享容器及侧栏。
+123
View File
@@ -0,0 +1,123 @@
# Ant Design 组件统一方案与执行记录
日期:2026-11-10。范围:组件依赖、品牌图标入口、架构约束及回归验证。
## 1. 源码结论
- `package.json` 已使用 `antd` 5;已安装版本为 5.29.3。业务源码没有直接导入 Radix UI、Floating UI 或 Semi UI。
- `src/components/ui/{index,controls,form,chat}.jsx` 已基于 Ant Design 实现,是旧页面 API 的兼容层,不是一套独立组件库。大量页面依赖其值回调、表单实例和分页通知顺序,不能直接全局替换 import。
- 额外依赖链为 `@lobehub/icons@1.97.2 → @lobehub/ui@1.171.0 → @floating-ui/react / @radix-ui/react-slot / leva → @radix-ui/react-tooltip`。手动删除 lock 条目或使用空包 overrides 会破坏 npm 安装一致性。
- 品牌图标直接使用点集中在 `LobeHubIcon.jsx`、`pages/Home/index.jsx`、`helpers/render.jsx`。其中动态配置支持 `.Color`、`.Avatar`、`.Combine`、`.Text` 和链式属性,必须保留。
- `UiThemeProvider` 已提供主题、语言、静态弹层和兼容 token;不需要第二个主题 Provider 或新的持久化状态。
## 2. 目标架构
| 层次 | 统一规则 | 本次处理 |
| ---------------------------- | ------------------------------------------- | --------------------------------------------------------------- |
| 新通用视图 | 直接使用 `antd` 公共 API | 通过 ESLint 和依赖审计防止引入另一套通用 UI |
| 旧页面 | 继续使用现有 `components/ui` 契约适配器 | 保留 Input 值回调、Form API、Pagination 通知及弹层语义 |
| 主题与语言 | 复用 `UiThemeProvider` 与现有 Theme Context | 品牌图标读取同一实际主题 |
| 通用图标 | 继续使用 `lucide-react` | 不替换已有图标体系 |
| 模型品牌图标 | 审计过的本地 SVG 资源及轻量容器 | 保留 30 个品牌与已支持变体;Avatar 改为 Ant Design |
| 图表、画布、富文本、新手引导 | 专门功能组件 | 保留 VChart、XYFlow、Quill、Joyride;不能用通用 UI 控件等价替换 |
## 3. 执行步骤
1. 保存现有 lock 副本并记录依赖树、测试和静态检查基线,保留工作区原有未提交修改。
2. 从固定版本 `@lobehub/icons@1.97.2` 提取实际支持的品牌及全部现有变体,生成本地 ESM。保留 MIT 许可证、来源清单、生成脚本及 SHA-256,禁止手工修改生成文件。生成器对意外外部依赖直接报错。
3. SVG 的路径、颜色、渐变、文字标志和品牌元数据沿用上游。原头像容器改为 Ant `Avatar`,组合标志改用普通 flex 容器;两处主题相关变体读取现有 Theme Context。去掉独立的 `antd-style` / `react-layout-kit` 样式运行时。
4. 修改三个实际使用入口,保持品牌名称、变体、链式参数和未知品牌 fallback;不修改请求、载荷、权限、路由、计价、登录或存储 key。
5. 从 manifest 删除 `@lobehub/icons`,交给 npm 自动剪枝 lock 与安装树。不要手工删除传递依赖;生成工具直接声明其使用的 esbuild 开发依赖。
6. 增加 `check:ui`:同时审计全部 lock 安装位置和源码依赖,禁止重新引入目标组件库;接入常规 `check`。ESLint 另限制旧 UI 包导入。
7. 执行下述验收并把实际结果写入本文件及 `docs/UI_MIGRATION.md`。本地截图、测试与资源日志仅放 Git 忽略的 `report/ui-unification/`。
## 4. 兼容与风险控制
- 不移除现有适配层,不批量把适配 Input / Form / Select 改成原生控件,避免静默改变事件参数和提交数据。
- 模型品牌 SVG 属于已有视觉资源;Ant Design 不提供这些品牌标志,不能统一替换成通用机器人图标。
- Avatar 容器由 Ant Design 渲染,其 DOM、默认边框和布局细节可能不同于原先的布局库;需要校验容器尺寸与 SVG 尺寸。品牌图形本身必须保持一致。
- Dify / Moonshot 原先使用 `antd-style` 的独立主题检测,迁移后与应用主题一致;深色变化单列核对,不冒充像素无差异。
- 750KB 左右的生成 ESM 是保留全部已支持 SVG 变体的源文件大小,不代表网络传输体积。基础 SVG 与完整变体拆为两个入口并共享图形模块,保留现有懒加载边界。删除安装依赖数量也不等于首页体积收益;未对比完整构建产物前不宣称性能提升比例。
- 工作区进入任务时 `package-lock.json` 已有大范围改动,本次以该文件为输入,只让 npm 处理目标依赖链,不覆盖成 HEAD 版本。
## 5. 验收标准与资源策略
- 依赖:manifest、lock、实际安装树均没有 Radix UI、Floating UI、Lobe UI、leva、antd-style、react-layout-kit。
- 行为:品牌基础标志、现有变体、链式参数及 fallback 保留;SVG 标志的前后浏览器结果比较,头像容器明确列出差异。
- 浏览器:单 Chrome Context、有头离屏、串行;1920×1000 / 393×851、浅深色;隔离组件夹具不访问业务 API,不能当作真实账号全站联调。
- 自动检查:全量 `npm test -- --test-concurrency=1`、`npm run eslint`、`npm run lint`、改动文件定向检查、`git diff --check`。既有失败按基线区分,不能宣称全量通过。
- 构建:输出至系统临时目录,不覆盖 dist;Node 堆 2944MB,关闭 gzip 体积统计。构建、浏览器、全量测试串行。启动前可用物理内存至少 2GB、可用提交空间至少 2.5GB;运行中低于 700MB 时停止本任务进程。记录系统可用内存及任务 CPU/工作集,不终止其他进程。
## 6. 维护与回退
图标维护说明见 `src/assets/brand-icons/README.md`。更新时必须审计固定上游版本及外部依赖,再运行生成器和浏览器比较;不可通过重新安装完整图标 UI 包绕过检查。
回退以本次差异为单位:恢复三个图标入口及原图标依赖版本,通过 npm 恢复一致的 manifest/lock,移除本次新增图标资源和检查规则。工作区已有改动应保留;不要用全仓 reset,也不要独立回退 manifest 或 lock。
## 7. 实际验证结果
| 项目 | 实际结果 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 依赖树 | lock 中包数从 1,120 降至 924,移除 196 个包;保留包版本变化为 0。npm 重新归类部分 dev / optional / peer 元数据,未覆盖任务前 lock 改动。 |
| 安装一致性 | `npm ls --depth=0` 通过;目标依赖的 `npm ls --all` 显示空树;`check:ui` 的源码、lock 和生成文件 hash 检查通过。 |
| 品牌图标 | 30 品牌、137 个已有标志/变体;桌面和移动浅色 SVG 全部一致。深色各有 Dify / Dify.Combine 两处改为跟随应用主题,其余 SVG 一致;浏览器运行错误 0。 |
| 定向测试 | 图标配置、fallback 与依赖检查测试 9/9 通过。 |
| 全量测试 | 迁移前 448/458;迁移后 453/463,新增 5 项检查通过。失败为同一批 10 项,没有新增失败;详见本地日志。 |
| ESLint | 本次源码修改 0 错误,Home 保留 1 条原有 hooks 警告。全仓仍有 11 个原有错误、167 条警告;与迁移前源码错误逐项对照,新增错误 0。生成资产与 report 目录不参与源码 lint。 |
| 格式检查 | 全仓仍有 804 个文件报告格式问题,本次改动文件单独检查;未执行全仓格式重写。 |
| 构建 | Node 堆 2944MB,输出至系统临时目录;58.48 秒完成。最终模块图 8,979 个模块,禁止依赖 0;保留大 chunk 提示,未更改构建阈值。 |
| 资源 | 串行重任务、约 2 秒采样。构建进程峰值工作集 2,673MB、CPU 时间 83.97 秒;可用物理内存最低 19,142MB,可用提交空间最低 26,204MB,未触发 700MB 停止阈值。此工作集为采样的构建进程,不冒充整个进程树峰值。 |
浏览器补充核验:30 个头像容器均为 24×24px,Ant Avatar 的 DOM ref 转发正常;实际 `LobeHubIcon` 的链式参数、square 形状、未知名称与空名称 fallback 均通过,夹具业务写请求 0。本次改动文件的 Prettier 检查及 `git diff --check` 通过。
证据包括 `svg-comparison.json`、`integration.json`、前后截图、`tests-before.log` / `tests-final.log`、`eslint-comparison.json`、`build-modules.json`、`resources.jsonl` 与 `resources-summary.json`,均在忽略目录 `report/ui-unification/`。本轮验证集中于依赖移除及组件契约,不宣称完成真实账号下所有后台页面的全站业务或像素验收。
基线失败分类:本地 `report/console-alignment/prototype-test.mjs` 被 Node 测试发现器扫描、两个旧表格源码断言、`channels-render-safety` 旧测试加载失败、六个企业密钥复制回调测试失败。全量检查的既有失败需要另行清理;本轮没有为获得绿灯而跳过断言或修改业务代码。
## 8. 全仓代码质量修复(2026-11-10 后续)
本节更新上一轮遗留的 ESLint 与格式检查结果;第 7 节保留为依赖迁移时的历史基线。
- ESLint 原有 11 个错误已全部修复:7 个验收入口或测试文件补齐仓库许可证头;4 个 Playwright fixture 将回调参数 `use` 改名为 `provide`,避免被 React Hooks 规则误判。没有关闭规则或扩大忽略范围。验收脚本中原本被 Git 忽略的文件仍只保留在本地。
- 本轮重新扫描得到 803 个待格式化文件(上一轮记录为 804 个),全部按现有 Prettier 配置处理。其中 732 个仅统一 CRLF/LF,71 个包含排版调整。`.gitattributes` 默认使用 LF,Windows 批处理文件保留 CRLF,避免 Windows 检出后再次产生大面积格式告警。
- 格式化逐文件保存原文、校验并发修改,再写入最新版本。682 个脚本的 esbuild 输出一致,30 个 JSON 解析结果一致;5 个 JSX 的静态属性差异经 CRLF 归一化后输出一致。68 个 CSS 中 64 个压缩输出一致,其余 4 个仅为 `color-mix()` 内可选空白。生成品牌资产的 hash 检查仍通过。
- 保留现有依赖统一改动及 Drawer 关闭按钮并行任务的工作区内容。格式化结果 hash 复核没有发现后续漂移;本节不代表另一个任务已完成验收。
| 检查 | 本轮结果 |
| ------------- | ---------------------------------------------------------------------------------- |
| 全仓 ESLint | 0 错误,167 条既有警告;未自动改写 Hooks 依赖以避免改变业务行为 |
| 全仓 Prettier | 通过,所有匹配文件符合现有格式规范 |
| UI 依赖审计 | `npm run check:ui` 通过,完整 lock 图及生成资产 hash 正常 |
| 全量串行测试 | 修复前 453/463,修复后 459/463;6 个企业密钥复制测试随换行符规范化恢复,无新增失败 |
| 临时目录构建 | 通过,约 78 秒;8,979 个构建模块,禁用 UI 依赖 0,保留大 chunk 提示 |
| 差异检查 | `git diff --check` 通过 |
剩余 4 个测试失败均存在于修复前基线:Node 意外发现本地原型采集脚本且其目标文件缺失、两个表格源码断言、`channels-render-safety` 测试的依赖加载断言。本轮未修改这些测试或业务实现,也没有宣称全量测试通过。
资源控制:重任务串行执行;构建使用 2,944MB Node 堆并关闭压缩体积统计,产物写系统临时目录,不覆盖 `dist/`。本轮采样中任务进程最高工作集 2,324MB,可用物理内存最低 17,808MB,可用提交空间最低 24,607MB,无 OOM 或低内存中止。后段补充 Windows `GetSystemTimes` 系统 CPU 采样,最高 99.3%;该时段不启动额外重任务,不把后段 CPU 采样冒充全程数据。未结束其他任务的进程。
本轮基线、格式化前副本、语义复核、测试及构建日志和资源采样均只放 Git 忽略目录 `report/code-quality/`。主要索引为 `eslint-before.json` / `eslint-after.json`、`format-results.json`、`format-summary.json`、`css-equivalence.json`、`tests-before.log` / `tests-after.log`、`build-modules.json` 和 `resources-summary.json`。
## 9. Hooks 警告与剩余测试修复(2026-11-10 后续)
本节继续处理第 8 节的 167 条 ESLint 警告及 4 项测试失败,保留前文的历史结果。恢复误删的依赖后,安装前后的 `package-lock.json` SHA-256 一致,`npm ls --depth=0` 通过;中途因依赖缺失而中断的测试不计作代码验收结果。
- 对真正随输入变化的计算补齐依赖,稳定空对象、请求头与能力字段,使用函数式状态更新;移除不能保持稳定或成本很低的缓存,修正过期闭包、无效依赖以及不应依赖整个对象的情况。没有新增 ESLint 禁用指令或放宽规则,`eslint` 脚本增加 `--max-warnings=0`,后续警告会使检查失败。
- 对首次加载、弹窗可见性、筛选范围变化等明确的生命周期,使用 React 18 兼容的 `useEffectEvent`,保持回调引用稳定并读取最近提交的值;原有 `useEffect` 仍明确声明触发依赖,保留清理函数。避免将草稿状态或每次渲染新建的加载函数加入依赖后,造成重复请求、循环渲染或清空输入。该工具只用于副作用及其回调,不代替正常的响应式依赖。
- 补充 AST 审计:107 个修改文件的 API 调用结构与本轮修改前一致;89 处移入 effect event 的函数体及原始触发依赖逐项匹配。审计说明请求调用和生命周期触发的保留范围,不替代真实后端的完整业务回归。
- `scripts/test.mjs` 将单测发现范围明确为 `src/`、`tests/`、`test/unit/`,避免将忽略目录中的本地原型采集脚本当成单测。原报告内有价值的分页检查迁至可入库的 `test/unit/`,不再依赖本地报告或整个 JSX 的历史快照;保留未分页表格契约,并以运行行为检查本地筛选、页大小、页码重置及无额外请求。模型测试弹窗使用完整过滤列表交给原生 Ant Table 分页,新增测试核对实际渲染行及回调,避免沿用要求手动切片的旧断言。
- 更新旧测试对迁移后组件与新 Hook 的 mock,新增 effect event、请求收敛、草稿保留、清理和测试发现范围的回归。真实 React DOM 的隔离浏览器夹具另验证设置与用户列表只加载一次、弹窗草稿保留、手动刷新、重开加载及作用域清理;UI 和 API 由本地 mock 提供,不代表真实账号全站验收。
本轮证据仅在忽略目录 `report/code-quality-followup/`:包括警告基线、源码快照、`contract-audit.json`、`trigger-audit.json`、串行测试日志、`browser-results.json`、`build-modules.json` 及资源采样。并行 Drawer 关闭按钮任务的工作区内容保留。
| 检查 | 本轮最终结果 |
| ----------------- | ------------------------------------------------------------------------ |
| 全仓 ESLint | 0 错误、0 警告;零警告门禁通过 |
| 全仓 Prettier | 所有匹配文件通过 |
| 完整串行单测 | 475/475 通过,失败、跳过和取消均为 0;约 147 秒 |
| 隔离浏览器 | 4 组真实 React DOM 行为检查通过,运行错误 0,接口为 mock |
| UI 依赖及资产审计 | 源码、完整 lock 图和生成资产 hash 检查通过 |
| 临时目录构建 | 通过,约 106 秒;8,980 个最终模块,禁用 UI 依赖 0;保留原有大 chunk 提示 |
| 差异检查 | `git diff --check` 通过 |
资源控制:重任务串行、单测并发为 1,Node 堆上限 2,944MB;开始前检查 CPU、物理内存及提交空间,CPU 高时延后启动,运行中每约 10 秒采样,低物理内存或提交空间时停止本任务。构建输出至系统临时目录,关闭压缩体积统计;构建进程采样工作集最高 2,475MB,可用物理内存最低 10,646MB,可用提交空间最低 15,944MB,未触发内存停止阈值。测试和浏览器记录的是包装进程工作集,不将其视为整个子进程树的内存峰值;未结束其他任务的进程。
+2 -2
View File
@@ -19,8 +19,8 @@
| ------------ | --------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 页面骨架 | `MockSkillMarket.jsx` / `LiveSkillMarket.jsx` | `.skill-market-page` 容器阶梯 + `PageBackground rich grid animate` | `.sm-page.sm-theme` 整屏应用壳(外层不滚动,侧栏与卡片列表各自滚动),背景 `--sm-bg`,移除 PageBackground |
| Hero | `view/SkillMarketHero.jsx` | 标题 + 副标题 + 胶囊大搜索框(玻璃 / 光环) | 原型 `.sm-hero`:线路 / 点阵 / 轨道 / 四个模块装饰(DOM 复刻,lucide 图标),`Input allowClear` + `重置` `Button` + `搜索` `Button type=primary htmlType=submit` |
| 筛选侧栏 | `view/SkillFilterSidebar.jsx` | 分类按钮列表(单选,“全部”) | `.sm-sidebar` 独立滚动:“筛选 / 重置”、技能范围 `Button` + 数量、“标签筛选 / 可多选” `Select mode=multiple showSearch allowClear`、任一匹配说明、已选可关闭 `Tag` 和清空标签 |
| 结果栏 | `view/SkillCatalog.jsx` | “共 N 个技能” + mock 工具栏(独立一行) | `h2 全部技能 / 我的技能` + 筛选后数量及已选标签数;页面已有操作放结果栏右侧(mock:`Tag 本地演示` + 说明 + `恢复样例数据` + `新增技能`) |
| 筛选侧栏 | `view/SkillFilterSidebar.jsx` | 分类按钮列表(单选,“全部”) | `.sm-sidebar` 独立滚动:“筛选 / 重置”、技能范围 `Button` + 数量、“标签筛选 / 可多选” `Select mode=multiple showSearch allowClear`、任一匹配说明、已选可关闭 `Tag` 和清空标签 |
| 结果栏 | `view/SkillCatalog.jsx` | “共 N 个技能” + mock 工具栏(独立一行) | `h2 全部技能 / 我的技能` + 筛选后数量及已选标签数;页面已有操作放结果栏右侧(mock:`Tag 本地演示` + 说明 + `恢复样例数据` + `新增技能`) |
| 卡片 | `view/SkillCard.jsx` | 自绘 article / button、渐变头像、胶囊 chip、等宽版本号 | `Card`(`role=button`、Enter/Space 打开、指针光晕)、分类图标框(`sm-symbol-code/ai/design/marketing`)、`Tag bordered={false}`、页脚 `v{n}` + 已有操作按钮 |
| 状态徽标 | mock / live | 自绘 chip、Semi 色名 `amber` | `Tag` 语义色:`disabled→default`、`inactive→warning`、`enabled→success`;live 的 `amber` 改为 `warning`(antd 无 `amber` 预设,原先白字透明底不可见) |
| 加载 | live | `Skeleton` 占位卡 | `Card loading`(8 张,`.sm-card-loading`) |
+13 -6
View File
@@ -92,7 +92,7 @@
border-radius: 50%;
background: radial-gradient(
circle,
var(--brand-primary-soft, rgba(22, 104, 220, 0.10)),
var(--brand-primary-soft, rgba(22, 104, 220, 0.1)),
transparent 70%
);
filter: blur(24px);
@@ -280,13 +280,19 @@
var el = document.getElementById('wl-splash');
var rawBrand = el ? el.getAttribute('data-brand') : null;
var rawLogo = el ? el.getAttribute('data-logo') : null;
var brandIsDevPH = !!(rawBrand && rawBrand.indexOf(PLACEHOLDER_PREFIX) === 0);
var logoIsDevPH = !!(rawLogo && rawLogo.indexOf(PLACEHOLDER_PREFIX) === 0);
var brandIsDevPH = !!(
rawBrand && rawBrand.indexOf(PLACEHOLDER_PREFIX) === 0
);
var logoIsDevPH = !!(
rawLogo && rawLogo.indexOf(PLACEHOLDER_PREFIX) === 0
);
var name = brandIsDevPH ? '' : clean(rawBrand);
var logo = logoIsDevPH ? '' : clean(rawLogo);
try {
if ((!el || brandIsDevPH) && !name) name = clean(localStorage.getItem('system_name'));
if ((!el || logoIsDevPH) && !logo) logo = clean(localStorage.getItem('logo'));
if ((!el || brandIsDevPH) && !name)
name = clean(localStorage.getItem('system_name'));
if ((!el || logoIsDevPH) && !logo)
logo = clean(localStorage.getItem('logo'));
} catch (e) {
/* 隐私模式 localStorage 不可用:name/logo 保持空,React 端走终极兜底 */
}
@@ -305,7 +311,8 @@
try {
// ---- 文案:navigator.language 判定 zh / en ----
var lang = (navigator.language || 'zh').toLowerCase();
var loadingText = lang.indexOf('zh') === 0 ? '加载中...' : 'Loading...';
var loadingText =
lang.indexOf('zh') === 0 ? '加载中...' : 'Loading...';
var textEl = el.querySelector('.wl-text');
if (textEl) textEl.textContent = loadingText;
+893 -5064
View File
File diff suppressed because it is too large Load Diff
+8 -6
View File
@@ -5,7 +5,6 @@
"type": "module",
"dependencies": {
"@dagrejs/dagre": "^1.1.4",
"@lobehub/icons": "1.97.2",
"@visactor/react-vchart": "~1.8.8",
"@visactor/vchart": "~1.8.8",
"@xyflow/react": "^12.6.0",
@@ -50,20 +49,22 @@
"scripts": {
"dev": "node scripts/dev.mjs",
"build": "vite build",
"test": "node --test",
"test": "node scripts/test.mjs",
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
"test:e2e:report": "playwright show-report",
"lint": "prettier . --check",
"lint:fix": "prettier . --write",
"check": "npm run eslint && npm test && npm run build",
"eslint": "eslint \"**/*.{js,jsx}\" --cache",
"check": "npm run check:ui && npm run eslint && npm test -- --test-concurrency=1 && npm run build",
"eslint": "eslint \"**/*.{js,jsx}\" --cache --max-warnings=0",
"eslint:fix": "eslint \"**/*.{js,jsx}\" --fix --cache",
"preview": "vite preview",
"i18n:extract": "i18next-cli extract",
"i18n:status": "i18next-cli status",
"i18n:sync": "i18next-cli sync",
"i18n:lint": "i18next-cli lint"
"i18n:lint": "i18next-cli lint",
"check:ui": "node scripts/check-ui-dependencies.mjs",
"vendor:icons": "node scripts/vendor-brand-icons.mjs"
},
"browserslist": {
"production": [
@@ -90,7 +91,8 @@
"postcss": "^8.5.3",
"prettier": "^3.0.0",
"tailwindcss": "^3",
"vite": "5.4.21"
"vite": "5.4.21",
"esbuild": "0.21.5"
},
"proxy": "http://localhost:3000",
"engines": {
+163
View File
@@ -0,0 +1,163 @@
import { readFile, readdir } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { Linter } from 'eslint';
const root = fileURLToPath(new URL('../', import.meta.url));
const forbidden = [
/^@radix-ui\//,
/^@floating-ui\//,
/^@lobehub\/(?:ui|icons)(?:\/|$)/,
/^@douyinfe\/semi-(?:ui|icons|foundation)(?:\/|$)/,
/^@headlessui\//,
/^@mui\//,
/^@chakra-ui\//,
/^(?:leva|antd-style|react-layout-kit)(?:\/|$)/,
];
export const isForbiddenUiDependency = (name) =>
forbidden.some((pattern) => pattern.test(name));
export function auditManifest(manifest, lock) {
const issues = [];
for (const section of [
'dependencies',
'devDependencies',
'optionalDependencies',
'peerDependencies',
]) {
for (const name of Object.keys(manifest[section] || {})) {
if (isForbiddenUiDependency(name))
issues.push(`package.json ${section}: ${name}`);
}
}
for (const location of Object.keys(lock.packages || {})) {
if (isForbiddenUiDependency(location.split('node_modules/').at(-1))) {
issues.push(`package-lock.json: ${location}`);
}
}
if (!lock.packages || lock.lockfileVersion < 2)
issues.push('Expected an npm lockfile with a packages graph.');
return issues;
}
export function auditSource(source, filename) {
const linter = new Linter();
linter.defineRule('ui-dependencies', {
create(context) {
const inspect = (node) => {
if (
node?.type === 'Literal' &&
typeof node.value === 'string' &&
isForbiddenUiDependency(node.value)
) {
context.report({
node,
message: `Use Ant Design or the audited local brand assets: ${node.value}`,
});
}
};
return {
ImportDeclaration: (node) => inspect(node.source),
ExportNamedDeclaration: (node) => inspect(node.source),
ExportAllDeclaration: (node) => inspect(node.source),
ImportExpression: (node) => inspect(node.source),
CallExpression: (node) => {
if (
node.callee.type === 'Identifier' &&
node.callee.name === 'require'
)
inspect(node.arguments[0]);
},
};
},
});
return linter
.verify(
source,
{
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
ecmaFeatures: { jsx: true },
},
rules: { 'ui-dependencies': 'error' },
},
{ filename, allowInlineConfig: false },
)
.map((issue) => `${filename}:${issue.line}: ${issue.message}`);
}
async function sourceFiles(dir) {
const files = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const name = path.join(dir, entry.name);
if (entry.isDirectory()) files.push(...(await sourceFiles(name)));
else if (/\.[cm]?[jt]sx?$/.test(entry.name)) files.push(name);
}
return files;
}
export async function checkUiDependencies(directory = root) {
const manifest = JSON.parse(
await readFile(path.join(directory, 'package.json'), 'utf8'),
);
const lock = JSON.parse(
await readFile(path.join(directory, 'package-lock.json'), 'utf8'),
);
const issues = auditManifest(manifest, lock);
const files = await sourceFiles(path.join(directory, 'src'));
for (const filename of files) {
issues.push(
...auditSource(
await readFile(filename, 'utf8'),
path.relative(directory, filename),
),
);
}
const assets = path.join(directory, 'src/assets/brand-icons');
const provenance = JSON.parse(
await readFile(path.join(assets, 'manifest.json'), 'utf8'),
);
const generated = (await readdir(assets))
.filter((name) => name.endsWith('.js'))
.sort();
if (
JSON.stringify(generated) !==
JSON.stringify(Object.keys(provenance.files).sort())
)
issues.push(
'Brand icon provenance must list every generated JavaScript file.',
);
for (const [name, hash] of Object.entries(provenance.files)) {
if (!/^(?:lobehub|primitives|shared-[A-Z0-9]+)\.js$/.test(name)) {
issues.push(`Invalid generated icon filename: ${name}`);
continue;
}
const icons = await readFile(path.join(assets, name));
if (createHash('sha256').update(icons).digest('hex') !== hash)
issues.push(
`Generated brand icons differ from their provenance hash: ${name}; regenerate them.`,
);
}
return {
issues,
files: files.length,
packages: Object.keys(lock.packages).length - 1,
};
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const result = await checkUiDependencies();
if (result.issues.length) {
console.error(result.issues.join('\n'));
process.exitCode = 1;
} else {
console.log(
`UI dependency audit passed: ${result.files} source files, ${result.packages} locked packages.`,
);
}
}
+8 -3
View File
@@ -18,7 +18,12 @@ function walk(dir, files = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) continue;
if (
entry.name === 'node_modules' ||
entry.name === 'dist' ||
entry.name.startsWith('.')
)
continue;
walk(full, files);
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
files.push(full);
@@ -93,13 +98,13 @@ function main() {
totalKeysUsedInSource: allKeys.size,
missingByLocale: missing,
keyToFiles: Object.fromEntries(
[...keyToFiles.entries()].map(([k, v]) => [k, v.slice(0, 3)])
[...keyToFiles.entries()].map(([k, v]) => [k, v.slice(0, 3)]),
),
};
fs.writeFileSync(
path.join(__dirname, 'missing_i18n.json'),
JSON.stringify(out, null, 2),
'utf8'
'utf8',
);
console.log(`\nWrote ${path.join(__dirname, 'missing_i18n.json')}`);
+174 -21
View File
@@ -23,27 +23,136 @@ const MAX_COUNT = 300;
// 优先级分层:数字越小越先翻译。一个 key 被多个区域引用时取最小值(最高优先级)。
const TIERS = [
{ tier: 1, name: '入口/认证', areas: ['components/auth', 'pages/OrgLogin', 'pages/OrgRegister', 'pages/Setup', 'components/setup'] },
{ tier: 2, name: '全局外壳', areas: ['components/layout', 'components/common', 'helpers', 'pages/NotFound', 'pages/Forbidden'] },
{ tier: 3, name: '个人高频主链路', areas: ['pages/UserCenter', 'pages/KeyManagement', 'pages/Token', 'pages/Recharge', 'pages/TopUp', 'components/topup', 'pages/Home', 'pages/Dashboard', 'pages/Pricing'] },
{ tier: 4, name: '核心业务', areas: ['pages/ExperienceCenter', 'pages/CloudBrain', 'pages/SkillMarket', 'pages/Chat', 'pages/Chat2Link', 'pages/Playground', 'pages/ImageGeneration', 'pages/Midjourney', 'components/playground', 'components/image', 'components/skill'] },
{ tier: 5, name: '通用交互层', areas: ['hooks', 'components/table', 'components/customer-service', 'pages/Log', 'pages/Task', 'pages/Subscription', 'components/membership', 'pages/Tutorial', 'pages/Docs', 'pages/About', 'pages/PrivacyPolicy', 'pages/UserAgreement', 'pages/Status'] },
{ tier: 6, name: '企业侧', areas: ['pages/Organization', 'pages/ExpertPlatform', 'pages/SkillPlatform', 'pages/ExperienceCenterAudit'] },
{ tier: 7, name: '管理/运营后台', areas: ['pages/Setting', 'components/settings', 'pages/AdminOrganizations', 'pages/AdminInvoice', 'pages/AdminOrder', 'pages/Channel', 'pages/Model', 'pages/Redemption', 'pages/Monitoring', 'pages/MonitorCenter', 'pages/ServiceDashboard', 'pages/Analytics', 'pages/User', 'components/analytics', 'components/dashboard'] },
{ tier: 8, name: '提成/合作伙伴', areas: ['pages/MyCommission', 'pages/PartnerPortal', 'components/promotion'] },
{
tier: 1,
name: '入口/认证',
areas: [
'components/auth',
'pages/OrgLogin',
'pages/OrgRegister',
'pages/Setup',
'components/setup',
],
},
{
tier: 2,
name: '全局外壳',
areas: [
'components/layout',
'components/common',
'helpers',
'pages/NotFound',
'pages/Forbidden',
],
},
{
tier: 3,
name: '个人高频主链路',
areas: [
'pages/UserCenter',
'pages/KeyManagement',
'pages/Token',
'pages/Recharge',
'pages/TopUp',
'components/topup',
'pages/Home',
'pages/Dashboard',
'pages/Pricing',
],
},
{
tier: 4,
name: '核心业务',
areas: [
'pages/ExperienceCenter',
'pages/CloudBrain',
'pages/SkillMarket',
'pages/Chat',
'pages/Chat2Link',
'pages/Playground',
'pages/ImageGeneration',
'pages/Midjourney',
'components/playground',
'components/image',
'components/skill',
],
},
{
tier: 5,
name: '通用交互层',
areas: [
'hooks',
'components/table',
'components/customer-service',
'pages/Log',
'pages/Task',
'pages/Subscription',
'components/membership',
'pages/Tutorial',
'pages/Docs',
'pages/About',
'pages/PrivacyPolicy',
'pages/UserAgreement',
'pages/Status',
],
},
{
tier: 6,
name: '企业侧',
areas: [
'pages/Organization',
'pages/ExpertPlatform',
'pages/SkillPlatform',
'pages/ExperienceCenterAudit',
],
},
{
tier: 7,
name: '管理/运营后台',
areas: [
'pages/Setting',
'components/settings',
'pages/AdminOrganizations',
'pages/AdminInvoice',
'pages/AdminOrder',
'pages/Channel',
'pages/Model',
'pages/Redemption',
'pages/Monitoring',
'pages/MonitorCenter',
'pages/ServiceDashboard',
'pages/Analytics',
'pages/User',
'components/analytics',
'components/dashboard',
],
},
{
tier: 8,
name: '提成/合作伙伴',
areas: [
'pages/MyCommission',
'pages/PartnerPortal',
'components/promotion',
],
},
];
const TIER_OTHER = 9; // 源码中有引用但未归入上表的区域
const TIER_DEAD = 99; // 源码已无引用的历史 key(en.json 里还在,为「一一对应」保留)
const AREA_TIER = new Map();
const TIER_NAME = new Map([[TIER_OTHER, '其他区域'], [TIER_DEAD, '无调用点(历史键)']]);
const TIER_NAME = new Map([
[TIER_OTHER, '其他区域'],
[TIER_DEAD, '无调用点(历史键)'],
]);
for (const { tier, name, areas } of TIERS) {
TIER_NAME.set(tier, name);
for (const a of areas) AREA_TIER.set(a, tier);
}
const load = (n) =>
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8')).translation;
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8'))
.translation;
// 已译状态唯一事实源就是 locales/{ko,th}.json 本身;不另存快照文件,避免两份
// 数据漂移(快照落后时会把已译 key 重新切进批次,覆盖掉已有译文)。
const loadDone = (l) => {
@@ -62,7 +171,11 @@ function walk(dir, files = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (['node_modules', 'dist'].includes(entry.name) || entry.name.startsWith('.')) continue;
if (
['node_modules', 'dist'].includes(entry.name) ||
entry.name.startsWith('.')
)
continue;
walk(full, files);
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
files.push(full);
@@ -72,15 +185,24 @@ function walk(dir, files = []) {
}
const unescape = (raw) =>
raw.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, '\\').replace(/\\n/g, '\n');
raw
.replace(/\\'/g, "'")
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\')
.replace(/\\n/g, '\n');
// 1) 建立 key -> 最高优先级 + 代表区域
const keyTier = new Map();
const keyArea = new Map();
for (const file of walk(SRC_DIR).filter((f) => !f.includes(path.join('src', 'i18n')))) {
for (const file of walk(SRC_DIR).filter(
(f) => !f.includes(path.join('src', 'i18n')),
)) {
const content = fs.readFileSync(file, 'utf8');
const rel = path.relative(SRC_DIR, file).split(path.sep);
const area = rel[0] === 'pages' || rel[0] === 'components' ? `${rel[0]}/${rel[1]}` : rel[0];
const area =
rel[0] === 'pages' || rel[0] === 'components'
? `${rel[0]}/${rel[1]}`
: rel[0];
const tier = AREA_TIER.get(area) ?? TIER_OTHER;
let m;
T_CALL_RE.lastIndex = 0;
@@ -117,7 +239,11 @@ const flush = () => {
if (!batch.length) return;
n += 1;
const name = `batch_${String(n).padStart(3, '0')}.json`;
fs.writeFileSync(path.join(OUT_DIR, name), JSON.stringify(batch, null, 2), 'utf8');
fs.writeFileSync(
path.join(OUT_DIR, name),
JSON.stringify(batch, null, 2),
'utf8',
);
const areas = [...new Set(batch.map((x) => x.area))];
manifest.push({
file: name,
@@ -134,29 +260,56 @@ const flush = () => {
for (const { k, tier } of pending) {
const zhText = k in zh ? zh[k] || k : k;
// 优先级换档必须断批:一批只属于一个层级,进度才能对应到「哪些页面已可用」
if (batch.length && (tier !== curTier || used + zhText.length > CHAR_BUDGET || batch.length >= MAX_COUNT)) {
if (
batch.length &&
(tier !== curTier ||
used + zhText.length > CHAR_BUDGET ||
batch.length >= MAX_COUNT)
) {
flush();
}
curTier = tier;
// cur:各语种已有译文。批次按「任一语种未译」切,已译的那一侧回填 "" 即保留原值
const cur = Object.fromEntries(LANGS.map((l) => [l, done[l][k] || '']));
batch.push({ key: k, zh: zhText, en: en[k], cur, area: keyArea.get(k) || '-', tier });
batch.push({
key: k,
zh: zhText,
en: en[k],
cur,
area: keyArea.get(k) || '-',
tier,
});
used += zhText.length;
}
flush();
fs.writeFileSync(
path.join(OUT_DIR, '_manifest.json'),
JSON.stringify({ langs: LANGS, totalEnKeys: enKeys.length, pending: pending.length, batches: manifest }, null, 2),
JSON.stringify(
{
langs: LANGS,
totalEnKeys: enKeys.length,
pending: pending.length,
batches: manifest,
},
null,
2,
),
'utf8',
);
const perTier = new Map();
for (const { tier } of pending) perTier.set(tier, (perTier.get(tier) || 0) + 1);
const doneSummary = LANGS.map((l) => `${l}已译 ${enKeys.filter((k) => done[l][k]).length}`).join(' / ');
console.log(`en 全集 ${enKeys.length} | ${doneSummary} | 待译(任一语种缺) ${pending.length} | 切成 ${n} 批`);
const doneSummary = LANGS.map(
(l) => `${l}已译 ${enKeys.filter((k) => done[l][k]).length}`,
).join(' / ');
console.log(
`en 全集 ${enKeys.length} | ${doneSummary} | 待译(任一语种缺) ${pending.length} | 切成 ${n} 批`,
);
console.log('待译量按优先级:');
for (const [tier, cnt] of [...perTier.entries()].sort((a, b) => a[0] - b[0])) {
const bs = manifest.filter((b) => b.tier === tier).length;
console.log(` T${String(tier).padStart(2)} ${String(TIER_NAME.get(tier)).padEnd(16)} ${String(cnt).padStart(5)} 条 / ${String(bs).padStart(2)} 批`);
console.log(
` T${String(tier).padStart(2)} ${String(TIER_NAME.get(tier)).padEnd(16)} ${String(cnt).padStart(5)} 条 / ${String(bs).padStart(2)} 批`,
);
}
+22 -7
View File
@@ -20,7 +20,9 @@ const BATCH_DIR = path.join(__dirname, 'kt_batches');
const OUT_DIR = path.join(__dirname, 'kt_out');
const LANGS = require('./i18n_langs.cjs');
const manifest = JSON.parse(fs.readFileSync(path.join(BATCH_DIR, '_manifest.json'), 'utf8'));
const manifest = JSON.parse(
fs.readFileSync(path.join(BATCH_DIR, '_manifest.json'), 'utf8'),
);
// kt_out/ 按批次号对位,换一组语种重切批次后,旧语种的 {lng}_NNN.json 仍留在目录里,
// 却对应的是上一轮的批次内容;若靠长度校验兜底,同长批次会被静默错位回填。
// 这里要求本次语种必须属于当前批次清单的语种(旧清单无 langs 字段时按 ko,th)。
@@ -33,11 +35,13 @@ if (foreign.length) {
process.exit(1);
}
const enKeys = Object.keys(
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'en.json'), 'utf8')).translation,
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'en.json'), 'utf8'))
.translation,
);
const PH = /\{\{[^}]*\}\}/g;
const placeholders = (s) => new Set((String(s).match(PH) || []).map((x) => x.replace(/\s+/g, '')));
const placeholders = (s) =>
new Set((String(s).match(PH) || []).map((x) => x.replace(/\s+/g, '')));
let hardFail = false;
@@ -54,7 +58,9 @@ for (const lng of LANGS) {
for (const b of manifest.batches) {
const idx = b.file.match(/batch_(\d+)\.json/)[1];
const batch = JSON.parse(fs.readFileSync(path.join(BATCH_DIR, b.file), 'utf8'));
const batch = JSON.parse(
fs.readFileSync(path.join(BATCH_DIR, b.file), 'utf8'),
);
const outFile = path.join(OUT_DIR, `${lng}_${idx}.json`);
if (!fs.existsSync(outFile)) continue;
@@ -69,7 +75,10 @@ for (const lng of LANGS) {
batch.forEach((item, i) => {
const v = typeof vals[i] === 'string' ? vals[i] : '';
if (!v) return;
const allowed = new Set([...placeholders(item.zh), ...placeholders(item.en)]);
const allowed = new Set([
...placeholders(item.zh),
...placeholders(item.en),
]);
const unknown = [...placeholders(v)].filter((x) => !allowed.has(x));
if (unknown.length) {
problems.push(
@@ -92,7 +101,9 @@ for (const lng of LANGS) {
if (!v) continue;
if (k.startsWith('_')) continue; // "_" 前缀留给文件内注释
if (!enKeys.includes(k)) {
console.error(`[${lng}] 覆盖项 ${JSON.stringify(k)} 不在 en.json 中,已跳过`);
console.error(
`[${lng}] 覆盖项 ${JSON.stringify(k)} 不在 en.json 中,已跳过`,
);
hardFail = true;
continue;
}
@@ -110,7 +121,11 @@ for (const lng of LANGS) {
Object.keys(ordered).length === enKeys.length &&
Object.keys(ordered).every((k, i) => k === enKeys[i]);
fs.writeFileSync(localePath, JSON.stringify({ translation: ordered }, null, 2) + '\n', 'utf8');
fs.writeFileSync(
localePath,
JSON.stringify({ translation: ordered }, null, 2) + '\n',
'utf8',
);
console.log(
`[${lng}] keys=${enKeys.length} 已译=${filled} (原有${baseCount} + 新增${added} + 覆盖${overridden}) 待译=${enKeys.length - filled} key与en一一对应=${okKeys ? 'YES' : 'NO'}`,
+22 -6
View File
@@ -10,7 +10,8 @@ const SRC_DIR = path.join(__dirname, '..', 'src');
const LANGS = require('./i18n_langs.cjs');
const load = (n) =>
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8')).translation;
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8'))
.translation;
const T_CALL_RE = /\bt\(\s*(['"`])((?:\\.|(?!\1).)*?)\1/g;
const CJK_RE = /[一-鿿]/;
@@ -19,7 +20,11 @@ function walk(dir, files = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (['node_modules', 'dist'].includes(entry.name) || entry.name.startsWith('.')) continue;
if (
['node_modules', 'dist'].includes(entry.name) ||
entry.name.startsWith('.')
)
continue;
walk(full, files);
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
files.push(full);
@@ -38,7 +43,9 @@ function unescape(raw) {
const dicts = Object.fromEntries(LANGS.map((l) => [l, load(l)]));
const primary = dicts[LANGS[0]];
const files = walk(SRC_DIR).filter((f) => !f.includes(path.join('src', 'i18n')));
const files = walk(SRC_DIR).filter(
(f) => !f.includes(path.join('src', 'i18n')),
);
const byArea = new Map();
const allUsed = new Set();
@@ -49,7 +56,9 @@ for (const file of files) {
// 粒度必须与 i18n_kt_batches.cjs 的分层一致:components 也要拆到子目录,
// 否则 2800 多个 key 全折叠成一个 'components',看不出各子区域是否打满。
const area =
rel[0] === 'pages' || rel[0] === 'components' ? `${rel[0]}/${rel[1]}` : rel[0];
rel[0] === 'pages' || rel[0] === 'components'
? `${rel[0]}/${rel[1]}`
: rel[0];
let m;
T_CALL_RE.lastIndex = 0;
while ((m = T_CALL_RE.exec(content)) !== null) {
@@ -68,13 +77,20 @@ for (const l of LANGS) {
console.log(` ${l} 已译:${d} (${Math.round((d / used.length) * 100)}%)`);
}
const absent = used.filter((k) => !(k in primary)).length;
console.log(` 不在 ${LANGS[0]}.json 中(en.json 也缺,运行时回退中文):${absent}`);
console.log(
` 不在 ${LANGS[0]}.json 中(en.json 也缺,运行时回退中文):${absent}`,
);
const stats = [...byArea.entries()]
.map(([area, set]) => {
const arr = [...set];
const done = arr.filter((k) => primary[k]).length;
return { area, total: arr.length, done, pct: Math.round((done / arr.length) * 100) };
return {
area,
total: arr.length,
done,
pct: Math.round((done / arr.length) * 100),
};
})
.filter((r) => r.total >= 25)
.sort((a, b) => a.pct - b.pct);
+13 -4
View File
@@ -12,7 +12,8 @@ const path = require('path');
const SRC_DIR = path.join(__dirname, '..', 'src');
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
const load = (n) =>
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8')).translation;
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8'))
.translation;
const LANGS = require('./i18n_langs.cjs');
const DICTS = LANGS.map((l) => [l, load(l)]);
@@ -25,7 +26,11 @@ function walk(dir, files = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (['node_modules', 'dist'].includes(entry.name) || entry.name.startsWith('.')) continue;
if (
['node_modules', 'dist'].includes(entry.name) ||
entry.name.startsWith('.')
)
continue;
walk(full, files);
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) files.push(full);
}
@@ -43,7 +48,9 @@ const COL_RE2 =
const CJK = /[一-鿿]/;
const rows = [];
for (const file of walk(SRC_DIR).filter((f) => !f.includes(path.join('src', 'i18n')))) {
for (const file of walk(SRC_DIR).filter(
(f) => !f.includes(path.join('src', 'i18n')),
)) {
const c = fs.readFileSync(file, 'utf8');
const rel = path.relative(SRC_DIR, file);
const push = (key, width) => {
@@ -83,7 +90,9 @@ const uniq = rows.filter((r) => {
return true;
});
const perLang = LANGS.map((l) => `${l} ${uniq.filter((r) => r.lng === l).length}`).join(' / ');
const perLang = LANGS.map(
(l) => `${l} ${uniq.filter((r) => r.lng === l).length}`,
).join(' / ');
console.log(`固定列宽装不下译文的位置:${uniq.length} 处(${perLang})\n`);
const LIMIT = Number(process.argv[2]) || 30; // 可传参查看全部
for (const r of uniq.slice(0, LIMIT)) {
+3 -1
View File
@@ -5,7 +5,9 @@
// 不传时保持历史行为(ko,th)。同一轮 batches → 回填 → build 必须用同一组语种,
// 因为 kt_batches/ 按这组语种的「任一未译」切批。
const arg = process.argv.find((a) => a.startsWith('--langs='));
const raw = arg ? arg.slice('--langs='.length) : process.env.I18N_LANGS || 'ko,th';
const raw = arg
? arg.slice('--langs='.length)
: process.env.I18N_LANGS || 'ko,th';
module.exports = raw
.split(',')
+13 -5
View File
@@ -17,13 +17,16 @@ let OpenCC;
try {
OpenCC = require(process.env.OPENCC_JS || 'opencc-js');
} catch (e) {
console.error('找不到 opencc-js:先 `npm i opencc-js`(可装在仓库外),再设置 OPENCC_JS 指向该包目录');
console.error(
'找不到 opencc-js:先 `npm i opencc-js`(可装在仓库外),再设置 OPENCC_JS 指向该包目录',
);
process.exit(1);
}
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
const load = (n) =>
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8')).translation;
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${n}.json`), 'utf8'))
.translation;
// 转换前先钉住(作用在简体源上):OpenCC 会把 审核 与 审计 都转成「稽核」,
// 转换后已无法区分,只能在源文本上先把 审核 定成繁体「審核」(OpenCC 不再改动繁体字)。
@@ -71,14 +74,17 @@ for (const k of enKeys) {
const src = zh[k] || k.replace(/_(zero|one|two|few|many|other)$/, '');
const v = convert(src);
// 占位符是 ASCII,转换不应动到;这里兜底校验,防止词典误伤插值名
if (phList(v) !== phList(src)) problems.push(`${JSON.stringify(k)} 占位符被改动 -> ${JSON.stringify(v)}`);
if (phList(v) !== phList(src))
problems.push(`${JSON.stringify(k)} 占位符被改动 -> ${JSON.stringify(v)}`);
out[k] = v;
}
const ovPath = path.join(__dirname, 'zhtw_overrides.json');
let overridden = 0;
if (fs.existsSync(ovPath)) {
for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(ovPath, 'utf8')))) {
for (const [k, v] of Object.entries(
JSON.parse(fs.readFileSync(ovPath, 'utf8')),
)) {
if (k.startsWith('_') || !v) continue;
if (!(k in out)) {
problems.push(`覆盖项 ${JSON.stringify(k)} 不在 en.json 中`);
@@ -95,7 +101,9 @@ fs.writeFileSync(
'utf8',
);
const changed = enKeys.filter((k) => out[k] !== (zh[k] || k)).length;
console.log(`[zh-TW] keys=${enKeys.length} 与简体不同=${changed} 人工覆盖=${overridden}`);
console.log(
`[zh-TW] keys=${enKeys.length} 与简体不同=${changed} 人工覆盖=${overridden}`,
);
if (problems.length) {
console.error(`[zh-TW] 异常 ${problems.length} 条:`);
problems.slice(0, 30).forEach((p) => console.error(' ' + p));
+1945 -5835
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -12,7 +12,7 @@ for (const lng of Object.keys(data.missingByLocale)) {
fs.writeFileSync(
path.join(OUT_DIR, `missing_keys_${lng}.json`),
JSON.stringify(keys, null, 2),
'utf8'
'utf8',
);
console.log(`Wrote missing_keys_${lng}.json (${keys.length} keys)`);
}
+64
View File
@@ -0,0 +1,64 @@
/*
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 { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
export async function findUnitTests(root) {
const files = [];
async function visit(directory) {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const filename = path.join(directory, entry.name);
if (entry.isDirectory()) await visit(filename);
else if (entry.isFile() && /\.test\.[cm]?[jt]sx?$/.test(entry.name))
files.push(filename);
}
}
// Reports contain local browser capture tools and historical snapshots, not unit suites.
for (const directory of ['src', 'tests', 'test/unit'])
await visit(path.join(root, directory));
return files.sort();
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const root = fileURLToPath(new URL('../', import.meta.url));
const files = await findUnitTests(root);
if (!files.length)
throw new Error('No unit tests found in src/, tests/, or test/unit/.');
const child = spawn(
process.execPath,
['--test', ...process.argv.slice(2), ...files],
{
cwd: root,
stdio: 'inherit',
},
);
child.on('error', (error) => {
console.error(error);
process.exitCode = 1;
});
child.on('exit', (code) => {
process.exitCode = code ?? 1;
});
}
+153
View File
@@ -0,0 +1,153 @@
import { readFile, mkdir, writeFile, copyFile, access } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { build } from 'esbuild';
import { format } from 'prettier';
const root = fileURLToPath(new URL('../', import.meta.url));
const source = path.resolve(
root,
process.argv[2] || 'node_modules/@lobehub/icons',
);
const upstream = JSON.parse(
await readFile(path.join(source, 'package.json'), 'utf8'),
);
if (upstream.name !== '@lobehub/icons' || upstream.version !== '1.97.2') {
throw new Error('Use the audited @lobehub/icons@1.97.2 source package.');
}
const brands = [
'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',
'Kling',
'Perplexity',
'Replicate',
];
const external = new Set(['react', 'react/jsx-runtime']);
const entries = [];
const primitiveEntries = [];
for (const brand of brands) {
entries.push(`export { default as ${brand} } from './es/${brand}/index.js';`);
for (const variant of ['Mono', 'Color']) {
const modulePath = `./es/${brand}/components/${variant}.js`;
try {
await access(path.join(source, modulePath));
} catch {
continue;
}
primitiveEntries.push(
`export { default as ${brand}${variant} } from '${modulePath}';`,
);
}
}
const result = await build({
absWorkingDir: source,
entryPoints: { lobehub: 'brand:variants', primitives: 'brand:primitives' },
outdir: path.join(root, 'src/assets/brand-icons'),
splitting: true,
chunkNames: 'shared-[hash]',
bundle: true,
write: false,
metafile: true,
format: 'esm',
target: 'es2015',
minifySyntax: true,
plugins: [
{
name: 'brand-primitives-only',
setup(build) {
build.onResolve({ filter: /^brand:/ }, ({ path }) => ({
path,
namespace: 'brand',
}));
build.onLoad(
{ filter: /.*/, namespace: 'brand' },
({ path: name }) => ({
contents: (name === 'brand:variants'
? entries
: primitiveEntries
).join('\n'),
resolveDir: source,
}),
);
build.onResolve(
{ filter: /features\/Icon(Avatar|Combine)$/ },
({ path: name }) => ({
path: `../../components/common/brand-icons/${path.basename(name)}.jsx`,
external: true,
}),
);
build.onResolve({ filter: /^[^./]/ }, ({ path: name }) => {
if (name === 'antd-style')
return {
path: '../../components/common/brand-icons/useThemeMode.js',
external: true,
};
if (!external.has(name))
throw new Error(`Unexpected icon dependency: ${name}`);
return { path: name, external: true };
});
},
},
],
});
const output = path.join(root, 'src/assets/brand-icons');
await mkdir(output, { recursive: true });
const files = {};
for (const file of result.outputFiles) {
const code = await format(
'// Generated from @lobehub/icons@1.97.2. See LICENSE and README.md.\n' +
file.text,
{ parser: 'babel', singleQuote: true },
);
await writeFile(file.path, code);
files[path.basename(file.path)] = createHash('sha256')
.update(code)
.digest('hex');
}
await copyFile(path.join(source, 'LICENSE'), path.join(output, 'LICENSE'));
await writeFile(
path.join(output, 'manifest.json'),
JSON.stringify(
{
source: '@lobehub/icons',
version: upstream.version,
license: upstream.license,
brands,
moduleCount: Object.keys(result.metafile.inputs).filter(
(name) => !name.startsWith('brand:'),
).length,
files,
},
null,
2,
) + '\n',
);
console.log(
`Vendored ${brands.length} brands in ${Object.keys(files).length} modules.`,
);
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 LobeHub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+28
View File
@@ -0,0 +1,28 @@
# Audited brand icons
The generated `lobehub.js` contains the 30 brands supported by `LobeHubIcon`
and their existing Mono, Color, Text, Avatar and Combine variants, where provided
upstream. SVG paths and brand metadata come from **@lobehub/icons 1.97.2**
([upstream](https://github.com/lobehub/lobe-icons)); see the original MIT `LICENSE`.
`manifest.json` records the version, brand list and each generated file's SHA-256.
`primitives.js` exposes only Mono/Color SVGs for Home and the rendering helpers;
`shared-*.js` shares their SVG implementations with the lazily loaded variants.
Do not import `lobehub.js` from those eager entry points.
This is a generated visual asset, not a second UI framework. Its only runtime
imports are React and three local adapters under `components/common/brand-icons`.
Avatar containers use Ant Design. Theme-aware variants read the existing app
theme. No Lobe UI, Radix, Floating UI, antd-style or layout-kit runtime is needed.
Do not edit generated paths or metadata manually. To reproduce:
1. Download the pinned source with `npm pack @lobehub/icons@1.97.2 --pack-destination <temporary-directory>`.
2. Extract that tarball into the temporary directory using `tar -xf <tarball> -C <temporary-directory>`.
3. Run `npm run vendor:icons -- <temporary-directory>/package` from the repository root.
4. Run `npm run check:ui`, then compare all supported variants in light and dark themes.
The generator rejects unexpected external dependencies. Updating the upstream
version requires reviewing the generator pin, license, brand APIs and output.
Keep source packages and browser evidence outside tracked source. The normal
application install and build use the checked-in assets and never download
the upstream package.
File diff suppressed because one or more lines are too long
+43
View File
@@ -0,0 +1,43 @@
{
"source": "@lobehub/icons",
"version": "1.97.2",
"license": "MIT",
"brands": [
"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",
"Kling",
"Perplexity",
"Replicate"
],
"moduleCount": 204,
"files": {
"lobehub.js": "e048c7076a0c5a3a10508aa19a946877b0b65c497f1f8635d1ad5983b4dc065d",
"primitives.js": "cbab18ff82b8613288089b0242458e44183c99aa417c906e4bc1453fb62a649b",
"shared-2YS4Y76I.js": "3a395caca1c4d9d75756a2e897a6e71333d1fde2dd75d5234edfc5c898ab7d05"
}
}
+105
View File
@@ -0,0 +1,105 @@
// Generated from @lobehub/icons@1.97.2. See LICENSE and README.md.
import {
Color_default,
Color_default10,
Color_default11,
Color_default12,
Color_default13,
Color_default14,
Color_default15,
Color_default16,
Color_default17,
Color_default18,
Color_default19,
Color_default2,
Color_default20,
Color_default3,
Color_default4,
Color_default5,
Color_default6,
Color_default7,
Color_default8,
Color_default9,
Mono_default,
Mono_default10,
Mono_default11,
Mono_default12,
Mono_default13,
Mono_default14,
Mono_default15,
Mono_default16,
Mono_default17,
Mono_default18,
Mono_default19,
Mono_default2,
Mono_default20,
Mono_default21,
Mono_default22,
Mono_default23,
Mono_default24,
Mono_default25,
Mono_default26,
Mono_default27,
Mono_default28,
Mono_default29,
Mono_default3,
Mono_default30,
Mono_default4,
Mono_default5,
Mono_default6,
Mono_default7,
Mono_default8,
Mono_default9,
} from './shared-2YS4Y76I.js';
export {
Color_default12 as Ai360Color,
Mono_default15 as Ai360Mono,
Color_default as ClaudeColor,
Mono_default2 as ClaudeMono,
Color_default11 as CloudflareColor,
Mono_default14 as CloudflareMono,
Color_default10 as CohereColor,
Mono_default13 as CohereMono,
Mono_default26 as CozeMono,
Color_default5 as DeepSeekColor,
Mono_default7 as DeepSeekMono,
Color_default17 as DifyColor,
Mono_default25 as DifyMono,
Color_default15 as DoubaoColor,
Mono_default21 as DoubaoMono,
Color_default2 as GeminiColor,
Mono_default3 as GeminiMono,
Color_default9 as HunyuanColor,
Mono_default12 as HunyuanMono,
Mono_default17 as JinaMono,
Color_default19 as KlingColor,
Mono_default28 as KlingMono,
Mono_default11 as MidjourneyMono,
Color_default6 as MinimaxColor,
Mono_default8 as MinimaxMono,
Color_default14 as MistralColor,
Mono_default18 as MistralMono,
Mono_default4 as MoonshotMono,
Mono_default20 as OllamaMono,
Mono_default as OpenAIMono,
Mono_default24 as OpenRouterMono,
Color_default20 as PerplexityColor,
Mono_default29 as PerplexityMono,
Color_default4 as QwenColor,
Mono_default6 as QwenMono,
Mono_default30 as ReplicateMono,
Color_default18 as SiliconCloudColor,
Mono_default27 as SiliconCloudMono,
Color_default8 as SparkColor,
Mono_default10 as SparkMono,
Mono_default22 as SunoMono,
Color_default7 as WenxinColor,
Mono_default9 as WenxinMono,
Mono_default19 as XAIMono,
Color_default16 as XinferenceColor,
Mono_default23 as XinferenceMono,
Color_default13 as YiColor,
Mono_default16 as YiMono,
Color_default3 as ZhipuColor,
Mono_default5 as ZhipuMono,
};
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -177,7 +177,10 @@ const LoginForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
const status = statusState?.status || {};
const status = React.useMemo(
() => statusState?.status || {},
[statusState?.status],
);
const statusLoaded = statusState?.status !== undefined;
// affCode 只需在挂载时提取一次,避免每次渲染都执行
@@ -222,7 +225,7 @@ const LoginForm = () => {
nextParams.delete('expired');
setSearchParams(nextParams, { replace: true });
}
}, []);
}, [searchParams, setSearchParams, t]);
const finishLogin = useCallback(
(data, successMessage) =>
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useContext, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -85,7 +86,7 @@ const OAuth2Callback = (props) => {
}
};
useEffect(() => {
const onMount = useEffectEvent(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
@@ -97,7 +98,8 @@ const OAuth2Callback = (props) => {
}
sendCode(code, state);
}, []);
});
useEffect(() => onMount(), [onMount]);
return <Loading />;
};
+369 -366
View File
@@ -148,7 +148,10 @@ const RegisterForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
const status = statusState?.status || {};
const status = React.useMemo(
() => statusState?.status || {},
[statusState?.status],
);
const statusLoaded = statusState?.status !== undefined;
const [showEmailVerification, setShowEmailVerification] = useState(() => {
@@ -493,136 +496,301 @@ const RegisterForm = () => {
const renderOAuthOptions = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
/>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
/>
<div className='space-y-2'>
{status.wechat_login && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
loading={wechatLoading}
>
{t('使用 微信 继续')}
</OAuthButton>
)}
{status.wechat_open_oauth && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
>
{t('使用 微信扫码 注册')}
</OAuthButton>
)}
{status.github_oauth && (
<OAuthButton
icon={<IconGithubLogo size='large' />}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
>
{githubButtonText}
</OAuthButton>
)}
{status.discord_oauth && (
<OAuthButton
icon={<DiscordIcon />}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
>
{t('使用 Discord 继续')}
</OAuthButton>
)}
{status.oidc_enabled && (
<OAuthButton
icon={<OIDCIcon />}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
>
{t('使用 OIDC 继续')}
</OAuthButton>
)}
{status.linuxdo_oauth && (
<OAuthButton
icon={<LinuxDoIcon style={{ width: '20px', height: '20px' }} />}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
>
{t('使用 LinuxDO 继续')}
</OAuthButton>
)}
{status.telegram_oauth && (
<Suspense
fallback={
<div className='flex justify-center my-2 h-10 items-center text-gray-400 text-xs'>
Loading...
</div>
}
>
<TelegramLogin
onAuth={onTelegramLoginClicked}
botName={status.telegram_bot_name}
/>
</Suspense>
)}
{/* 分隔线 */}
<div className='relative py-3'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
</div>
<div className='relative flex justify-center'>
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
{t('或')}
</span>
</div>
</div>
{/* 用户名注册按钮 */}
<button
onClick={handleEmailRegisterClick}
disabled={emailRegisterLoading}
className='group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 overflow-hidden'
<div className='space-y-2'>
{status.wechat_login && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
loading={wechatLoading}
>
{/* 闪光效果 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
{t('使用 微信 继续')}
</OAuthButton>
)}
<IconMail className='relative z-10' />
<span className='relative z-10 font-medium text-sm'>
{t('使用 用户名 注册')}
</span>
<ArrowRight
size={16}
className='relative z-10 group-hover:translate-x-1 transition-transform'
{status.wechat_open_oauth && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
>
{t('使用 微信扫码 注册')}
</OAuthButton>
)}
{status.github_oauth && (
<OAuthButton
icon={<IconGithubLogo size='large' />}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
>
{githubButtonText}
</OAuthButton>
)}
{status.discord_oauth && (
<OAuthButton
icon={<DiscordIcon />}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
>
{t('使用 Discord 继续')}
</OAuthButton>
)}
{status.oidc_enabled && (
<OAuthButton
icon={<OIDCIcon />}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
>
{t('使用 OIDC 继续')}
</OAuthButton>
)}
{status.linuxdo_oauth && (
<OAuthButton
icon={<LinuxDoIcon style={{ width: '20px', height: '20px' }} />}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
>
{t('使用 LinuxDO 继续')}
</OAuthButton>
)}
{status.telegram_oauth && (
<Suspense
fallback={
<div className='flex justify-center my-2 h-10 items-center text-gray-400 text-xs'>
Loading...
</div>
}
>
<TelegramLogin
onAuth={onTelegramLoginClicked}
botName={status.telegram_bot_name}
/>
</button>
</Suspense>
)}
{/* 分隔线 */}
<div className='relative py-3'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
</div>
<div className='relative flex justify-center'>
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
{t('或')}
</span>
</div>
</div>
{/* 用户名注册按钮 */}
<button
onClick={handleEmailRegisterClick}
disabled={emailRegisterLoading}
className='group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 overflow-hidden'
>
{/* 闪光效果 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
<IconMail className='relative z-10' />
<span className='relative z-10 font-medium text-sm'>
{t('使用 用户名 注册')}
</span>
<ArrowRight
size={16}
className='relative z-10 group-hover:translate-x-1 transition-transform'
/>
</button>
</div>
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='mt-4 flex justify-center'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text
size='small'
className='text-gray-500 dark:text-gray-400 text-xs'
>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('用户协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
<div className='mt-4 text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
</div>
{/* 安全提示 */}
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
</GlassCard>
);
};
const renderEmailRegisterForm = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
wrapperClassName='mb-4'
logoWrapperClassName='mb-2'
/>
<Form className='register-compact-form auth-glass-form'>
{/* 用户名输入框 —— 玻璃观感统一由 .auth-glass-form(GlassCard 内置样式)驱动 */}
<Form.Input
field='username'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('用户名')}
</span>
}
placeholder={t('请输入用户名')}
name='username'
size='large'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={<IconUser size='small' />}
/>
{/* 密码输入框 */}
<Form.Input
field='password'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('密码')}
</span>
}
placeholder={t('输入密码,最短 8 位,最长 20 位')}
name='password'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password', value)}
prefix={<IconLock size='small' />}
/>
{/* 确认密码输入框 */}
<Form.Input
field='password2'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('确认密码')}
</span>
}
placeholder={t('确认密码')}
name='password2'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password2', value)}
prefix={<IconLock size='small' />}
/>
{showEmailVerification && (
<>
<Form.Input
field='email'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('邮箱')}
</span>
}
placeholder={t('输入邮箱地址')}
name='email'
type='email'
size='large'
autoComplete='email'
onChange={(value) => handleChange('email', value)}
prefix={<IconMail size='small' />}
suffix={
<Button
size='small'
onClick={sendVerificationCode}
loading={verificationCodeLoading}
disabled={disableButton || verificationCodeLoading}
className='!rounded-lg'
>
{disableButton
? `${t('重新发送')} (${countdown})`
: t('获取验证码')}
</Button>
}
/>
<Form.Input
field='verification_code'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('验证码')}
</span>
}
placeholder={t('输入验证码')}
name='verification_code'
size='large'
onChange={(value) => handleChange('verification_code', value)}
prefix={<IconKey size='small' />}
/>
</>
)}
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='mt-4 flex justify-center'>
<div className='flex items-center mt-3'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text
size='small'
className='text-gray-500 dark:text-gray-400 text-xs'
>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
@@ -630,7 +798,7 @@ const RegisterForm = () => {
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('用户协议')}
</a>
@@ -642,7 +810,7 @@ const RegisterForm = () => {
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('隐私政策')}
</a>
@@ -652,248 +820,83 @@ const RegisterForm = () => {
</div>
)}
<div className='mt-4 text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
</div>
{/* 安全提示 */}
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
</GlassCard>
);
};
const renderEmailRegisterForm = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('创建您的账户')}
wrapperClassName='mb-4'
logoWrapperClassName='mb-2'
/>
<Form className='register-compact-form auth-glass-form'>
{/* 用户名输入框 —— 玻璃观感统一由 .auth-glass-form(GlassCard 内置样式)驱动 */}
<Form.Input
field='username'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('用户名')}
</span>
<div className='space-y-2 mt-3'>
{/* 注册按钮 */}
<button
type='submit'
onClick={handleSubmit}
disabled={
registerLoading ||
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
}
placeholder={t('请输入用户名')}
name='username'
size='large'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={<IconUser size='small' />}
/>
className='group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to disabled:from-gray-400 disabled:to-gray-500 text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 disabled:cursor-not-allowed disabled:hover:translate-y-0 overflow-hidden'
>
{/* 闪光效果 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
{/* 密码输入框 */}
<Form.Input
field='password'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('密码')}
</span>
}
placeholder={t('输入密码,最短 8 位,最长 20 位')}
name='password'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password', value)}
prefix={<IconLock size='small' />}
/>
{/* 确认密码输入框 */}
<Form.Input
field='password2'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('确认密码')}
</span>
}
placeholder={t('确认密码')}
name='password2'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password2', value)}
prefix={<IconLock size='small' />}
/>
{showEmailVerification && (
<>
<Form.Input
field='email'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('邮箱')}
</span>
}
placeholder={t('输入邮箱地址')}
name='email'
type='email'
size='large'
autoComplete='email'
onChange={(value) => handleChange('email', value)}
prefix={<IconMail size='small' />}
suffix={
<Button
size='small'
onClick={sendVerificationCode}
loading={verificationCodeLoading}
disabled={disableButton || verificationCodeLoading}
className='!rounded-lg'
>
{disableButton
? `${t('重新发送')} (${countdown})`
: t('获取验证码')}
</Button>
}
/>
<Form.Input
field='verification_code'
label={
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
{t('验证码')}
</span>
}
placeholder={t('输入验证码')}
name='verification_code'
size='large'
onChange={(value) => handleChange('verification_code', value)}
prefix={<IconKey size='small' />}
/>
</>
)}
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='flex items-center mt-3'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('用户协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
<div className='space-y-2 mt-3'>
{/* 注册按钮 */}
<button
type='submit'
onClick={handleSubmit}
disabled={
registerLoading ||
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
}
className='group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to disabled:from-gray-400 disabled:to-gray-500 text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 disabled:cursor-not-allowed disabled:hover:translate-y-0 overflow-hidden'
>
{/* 闪光效果 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
{registerLoading ? (
<div className='w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin' />
) : (
<>
<span className='relative z-10 font-semibold'>
{t('注 册')}
</span>
<ArrowRight
size={16}
className='relative z-10 group-hover:translate-x-1 transition-transform'
/>
</>
)}
</button>
</div>
</Form>
{(status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth) && (
<div className='mt-2'>
<div className='relative py-3'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
</div>
<div className='relative flex justify-center'>
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
{t('或')}
{registerLoading ? (
<div className='w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin' />
) : (
<>
<span className='relative z-10 font-semibold'>
{t('注 册')}
</span>
</div>
<ArrowRight
size={16}
className='relative z-10 group-hover:translate-x-1 transition-transform'
/>
</>
)}
</button>
</div>
</Form>
{(status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth) && (
<div className='mt-2'>
<div className='relative py-3'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
</div>
<div className='relative flex justify-center'>
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
{t('或')}
</span>
</div>
<button
onClick={handleOtherRegisterOptionsClick}
disabled={otherRegisterOptionsLoading}
className='w-full h-9 flex items-center justify-center gap-2 text-sm text-gray-600 dark:text-gray-300 border border-gray-200/80 dark:border-white/[0.12] rounded-lg hover:bg-gray-50 dark:hover:bg-white/[0.06] hover:border-gray-300 dark:hover:border-white/20 transition-all'
>
{t('其他注册选项')}
</button>
</div>
)}
<div className='mt-4 text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
<button
onClick={handleOtherRegisterOptionsClick}
disabled={otherRegisterOptionsLoading}
className='w-full h-9 flex items-center justify-center gap-2 text-sm text-gray-600 dark:text-gray-300 border border-gray-200/80 dark:border-white/[0.12] rounded-lg hover:bg-gray-50 dark:hover:bg-white/[0.06] hover:border-gray-300 dark:hover:border-white/20 transition-all'
>
{t('其他注册选项')}
</button>
</div>
)}
{/* 安全提示 */}
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
<div className='mt-4 text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('已有账户?')}{' '}
<Link
to='/login'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('登录')}
</Link>
</Text>
</div>
{/* 安全提示 */}
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
<Shield size={12} />
<span>{t('安全注册')}</span>
</div>
</GlassCard>
);
};
@@ -1063,16 +1066,16 @@ const RegisterForm = () => {
const renderSkeleton = () => {
return (
<GlassCard withCornerHalos={false} withAurora={false}>
<div className='flex flex-col items-center justify-center mb-5'>
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
</div>
<div className='space-y-2'>
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
</div>
<div className='flex flex-col items-center justify-center mb-5'>
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
</div>
<div className='space-y-2'>
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
</div>
</GlassCard>
);
};
+1 -7
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
*/
import { API, showError, showSuccess } from '../../helpers';
import {
Button,
Card,
Divider,
Form,
Typography,
} from '@/components/ui';
import { Button, Card, Divider, Form, Typography } from '@/components/ui';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -102,7 +102,10 @@ const AgreementModal = ({ visible, type, onClose }) => {
{/* 头部 */}
<div className='relative flex items-center justify-between px-5 sm:px-6 h-14 border-b border-gray-200/80 dark:border-gray-800/80 flex-shrink-0 bg-white/95 dark:bg-gray-900/95 backdrop-blur-md'>
{/* 头部环境光 */}
<div className='pointer-events-none absolute inset-0 overflow-hidden' aria-hidden>
<div
className='pointer-events-none absolute inset-0 overflow-hidden'
aria-hidden
>
<div className='absolute -top-12 left-8 w-48 h-24 bg-gradient-to-br from-brand-from/15 to-brand-to/10 dark:from-brand-from/15 dark:to-brand-to/10 blur-3xl rounded-full' />
</div>
@@ -126,7 +129,10 @@ const AgreementModal = ({ visible, type, onClose }) => {
className='group inline-flex items-center gap-1 px-2 py-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from hover:bg-gray-100/80 dark:hover:bg-gray-800/80 rounded-md transition-colors'
title={t('在新标签页打开')}
>
<ExternalLink size={12} className='transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5' />
<ExternalLink
size={12}
className='transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5'
/>
<span className='hidden sm:inline'>{t('完整页面')}</span>
</a>
<button
+32 -30
View File
@@ -17,39 +17,41 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
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,
Kling,
Perplexity,
Replicate,
} from '@/assets/brand-icons/lobehub';
import React from 'react';
import { Avatar } from '@/components/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,
+2 -2
View File
@@ -41,8 +41,8 @@ runInNewContext(code, {
if (name === 'react') return React;
if (name === '@/components/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 });
assert.equal(name, '@/assets/brand-icons/lobehub');
return new Proxy({}, { get: () => Object.assign(Mono, { Color, Avatar }) });
},
});
const render = module.exports.default;
+1 -8
View File
@@ -18,14 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef } from 'react';
import {
Select,
Spin,
Typography,
Empty,
Tag,
Tooltip,
} from '@/components/ui';
import { Select, Spin, Typography, Empty, Tag, Tooltip } from '@/components/ui';
import { Lock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useModelSelector } from '../../hooks/models/useModelSelector';
+77 -19
View File
@@ -50,7 +50,11 @@ import React, { useEffect, useRef } from 'react';
const hexToRgb = (hex) => {
if (!hex) return { r: 99, g: 102, b: 241 }; // brand-primary 兜底
let h = hex.replace('#', '').trim();
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
if (h.length === 3)
h = h
.split('')
.map((c) => c + c)
.join('');
if (h.length === 8) h = h.slice(0, 6); // 忽略 alpha
if (!/^[0-9a-fA-F]{6}$/.test(h)) return { r: 99, g: 102, b: 241 };
const num = parseInt(h, 16);
@@ -62,7 +66,12 @@ const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
// 三阶 Bezier 求 t 处坐标(给触手沿曲线放置吸盘用)
const bezierPoint = (p0, p1, p2, p3, t) => {
const mt = 1 - t;
return mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3;
return (
mt * mt * mt * p0 +
3 * mt * mt * t * p1 +
3 * mt * t * t * p2 +
t * t * t * p3
);
};
// ─── 粒子类 ──────────────────────────────────────────────────
@@ -74,7 +83,11 @@ class Plankton {
}
reset(randomY = false) {
this.x = Math.random() * this.w;
this.y = randomY ? Math.random() * this.h : Math.random() < 0.5 ? -10 : this.h + 10;
this.y = randomY
? Math.random() * this.h
: Math.random() < 0.5
? -10
: this.h + 10;
this.size = Math.random() * 1.5 + 0.5;
this.vx = (Math.random() - 0.5) * 0.2;
this.vy = (Math.random() - 0.5) * 0.15;
@@ -85,7 +98,13 @@ class Plankton {
this.x += this.vx;
this.y += this.vy + Math.sin(this.phase) * 0.15;
this.phase += 0.015;
if (this.x < -20 || this.x > this.w + 20 || this.y < -20 || this.y > this.h + 20) this.reset();
if (
this.x < -20 ||
this.x > this.w + 20 ||
this.y < -20 ||
this.y > this.h + 20
)
this.reset();
}
resize(w, h) {
this.w = w;
@@ -153,7 +172,13 @@ class Bubble {
ctx.stroke();
ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha * 0.5})`;
ctx.beginPath();
ctx.arc(x - this.size * 0.3, y - this.size * 0.3, this.size * 0.28, 0, Math.PI * 2);
ctx.arc(
x - this.size * 0.3,
y - this.size * 0.3,
this.size * 0.28,
0,
Math.PI * 2,
);
ctx.fill();
}
}
@@ -287,10 +312,19 @@ class LifePulse {
// 从屏幕外随机一侧触发
const side = Math.floor(Math.random() * 4);
const m = 100;
if (side === 0) { this.ox = Math.random() * this.w; this.oy = -m; }
else if (side === 1) { this.ox = this.w + m; this.oy = Math.random() * this.h; }
else if (side === 2) { this.ox = Math.random() * this.w; this.oy = this.h + m; }
else { this.ox = -m; this.oy = Math.random() * this.h; }
if (side === 0) {
this.ox = Math.random() * this.w;
this.oy = -m;
} else if (side === 1) {
this.ox = this.w + m;
this.oy = Math.random() * this.h;
} else if (side === 2) {
this.ox = Math.random() * this.w;
this.oy = this.h + m;
} else {
this.ox = -m;
this.oy = Math.random() * this.h;
}
this.active = true;
this.startT = now;
this.maxR = Math.hypot(this.w, this.h) * 0.7;
@@ -307,7 +341,14 @@ class LifePulse {
const alpha = p < 0.5 ? p * 2 * 0.35 : (1 - p) * 2 * 0.35;
const inner = Math.max(0, radius - 50);
const outer = radius + 50;
const grad = ctx.createRadialGradient(this.ox, this.oy, inner, this.ox, this.oy, outer);
const grad = ctx.createRadialGradient(
this.ox,
this.oy,
inner,
this.ox,
this.oy,
outer,
);
grad.addColorStop(0, rgba(color, 0));
grad.addColorStop(0.5, rgba(color, alpha));
grad.addColorStop(1, rgba(color, 0));
@@ -330,7 +371,8 @@ const readTheme = () => {
};
const detectDark = () => {
if (document.documentElement.classList.contains('dark')) return true;
if (document.body && document.body.getAttribute('theme-mode') === 'dark') return true;
if (document.body && document.body.getAttribute('theme-mode') === 'dark')
return true;
// ThemeContext 在浅色模式会移除上面两个标记,此时必须先看用户显式选择,
// 否则"强制浅色 + 系统深色"会被 prefers-color-scheme 兜底误判成暗色
try {
@@ -340,7 +382,10 @@ const detectDark = () => {
} catch {
// localStorage 不可用(隐私模式等)时继续走系统偏好
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
return (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
);
};
// ─── 组件 ─────────────────────────────────────────────────
@@ -359,9 +404,10 @@ const OceanBackground = () => {
const dpr = Math.min(window.devicePixelRatio || 1, 1.5); // 上限避免移动端开销
// 设备 / 偏好检测
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
const isMobile =
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
const reducedMotion =
window.matchMedia &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -393,9 +439,18 @@ const OceanBackground = () => {
};
// 实例化
const plankton = Array.from({ length: COUNT.plankton }, () => new Plankton(width, height));
const sparkles = Array.from({ length: COUNT.sparkle }, () => new Sparkle(width, height));
const bubbles = Array.from({ length: COUNT.bubble }, () => new Bubble(width, height));
const plankton = Array.from(
{ length: COUNT.plankton },
() => new Plankton(width, height),
);
const sparkles = Array.from(
{ length: COUNT.sparkle },
() => new Sparkle(width, height),
);
const bubbles = Array.from(
{ length: COUNT.bubble },
() => new Bubble(width, height),
);
const pillars = Array.from(
{ length: COUNT.pillar },
(_, i) => new LightPillar(width, i, COUNT.pillar || 1),
@@ -445,7 +500,10 @@ const OceanBackground = () => {
const r1 = Math.max(width, height) * 0.75;
const vig = ctx.createRadialGradient(cx, cy, r0, cx, cy, r1);
vig.addColorStop(0, 'rgba(0, 0, 0, 0)');
vig.addColorStop(1, isDark ? 'rgba(0, 0, 0, 0.55)' : 'rgba(0, 10, 25, 0.35)');
vig.addColorStop(
1,
isDark ? 'rgba(0, 0, 0, 0.55)' : 'rgba(0, 10, 25, 0.35)',
);
ctx.fillStyle = vig;
ctx.fillRect(0, 0, width, height);
};
@@ -14,11 +14,7 @@
var(--ui-color-primary) 14%,
transparent
);
--pg-tint-line: color-mix(
in srgb,
var(--ui-color-primary) 28%,
transparent
);
--pg-tint-line: color-mix(in srgb, var(--ui-color-primary) 28%, transparent);
--pg-ok: var(--ui-color-success);
--pg-ok-tint: color-mix(in srgb, var(--ui-color-success) 14%, transparent);
}
@@ -0,0 +1,72 @@
/*
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, { forwardRef } from 'react';
import { Avatar, theme } from 'antd';
// Keep the upstream brand sizing contract; the container uses the app's Ant theme.
export default forwardRef(function IconAvatar(
{
shape = 'circle',
color,
background,
size,
style,
iconMultiple = 0.75,
Icon,
iconStyle,
iconClassName,
...props
},
ref,
) {
const { token } = theme.useToken();
const scaled = size * iconMultiple;
const iconSize = scaled % 2 === 0 ? scaled : scaled - 1;
const foreground = color ?? token.colorWhite;
return (
<Avatar
{...props}
ref={ref}
size={size}
shape={shape}
style={{
flex: 'none',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
background,
color: foreground,
border: 0,
borderRadius: shape === 'circle' ? '50%' : Math.floor(size * 0.1),
...style,
}}
icon={
Icon && (
<Icon
className={iconClassName}
color={foreground}
size={iconSize}
style={iconStyle}
/>
)
}
/>
);
});
@@ -0,0 +1,92 @@
/*
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, { forwardRef } from 'react';
export default forwardRef(function IconCombine(
{
Icon,
Text,
color,
size = 24,
spaceMultiple = 1,
textMultiple = 1,
extra,
extraStyle,
showText = true,
showLogo = true,
extraClassName,
iconProps,
inverse,
style,
...props
},
ref,
) {
const logo = Icon && showLogo && (
<Icon
size={size}
{...iconProps}
style={{
[inverse ? 'marginLeft' : 'marginRight']: size * spaceMultiple,
...iconProps?.style,
}}
/>
);
const text = showText && Text && <Text size={size * textMultiple} />;
return (
<div
{...props}
ref={ref}
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
flex: 'none',
color,
...style,
}}
>
{inverse ? (
<>
{text}
{logo}
</>
) : (
<>
{logo}
{text}
</>
)}
{extra && (
<span
className={extraClassName}
style={{
fontSize: size * textMultiple * 0.95,
lineHeight: 1,
...extraStyle,
}}
>
{extra}
</span>
)}
</div>
);
});
@@ -0,0 +1,25 @@
/*
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 { useActualTheme } from '../../../context/Theme';
// Dify and Moonshot variants read the existing app theme without a second provider.
export function useThemeMode() {
return { isDarkMode: useActualTheme() === 'dark' };
}
+153 -30
View File
@@ -33,8 +33,14 @@ export const IllustrationNoResult = ({ style = {} }) => (
<stop offset='100%' stopColor='var(--brand-gradient-via)' />
</linearGradient>
<linearGradient id='noResultGrad2' x1='0%' y1='0%' x2='100%' y2='100%'>
<stop offset='0%' stopColor='color-mix(in srgb, var(--brand-primary) 12%, #fff)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-primary) 20%, #fff)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--brand-primary) 12%, #fff)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-primary) 20%, #fff)'
/>
</linearGradient>
<filter id='noResultShadow' x='-20%' y='-20%' width='140%' height='140%'>
<feDropShadow
@@ -99,7 +105,13 @@ export const IllustrationNoResult = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='160' cy='50' r='3' fill='var(--brand-gradient-via)' opacity='0.5'>
<circle
cx='160'
cy='50'
r='3'
fill='var(--brand-gradient-via)'
opacity='0.5'
>
<animate
attributeName='opacity'
values='0.5;1;0.5'
@@ -107,7 +119,13 @@ export const IllustrationNoResult = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='155' cy='140' r='5' fill='var(--brand-gradient-to)' opacity='0.3'>
<circle
cx='155'
cy='140'
r='5'
fill='var(--brand-gradient-to)'
opacity='0.3'
>
<animate
attributeName='opacity'
values='0.3;0.7;0.3'
@@ -143,8 +161,14 @@ export const IllustrationNoResultDark = ({ style = {} }) => (
x2='100%'
y2='100%'
>
<stop offset='0%' stopColor='color-mix(in srgb, var(--brand-primary) 25%, #000)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--brand-primary) 25%, #000)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)'
/>
</linearGradient>
</defs>
<circle
@@ -200,7 +224,13 @@ export const IllustrationNoResultDark = ({ style = {} }) => (
strokeLinecap='round'
/>
</g>
<circle cx='45' cy='60' r='4' fill='var(--brand-gradient-from)' opacity='0.5'>
<circle
cx='45'
cy='60'
r='4'
fill='var(--brand-gradient-from)'
opacity='0.5'
>
<animate
attributeName='opacity'
values='0.5;1;0.5'
@@ -208,7 +238,13 @@ export const IllustrationNoResultDark = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='160' cy='50' r='3' fill='var(--brand-gradient-to)' opacity='0.6'>
<circle
cx='160'
cy='50'
r='3'
fill='var(--brand-gradient-to)'
opacity='0.6'
>
<animate
attributeName='opacity'
values='0.6;1;0.6'
@@ -216,7 +252,13 @@ export const IllustrationNoResultDark = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='155' cy='140' r='5' fill='var(--brand-primary-hover)' opacity='0.4'>
<circle
cx='155'
cy='140'
r='5'
fill='var(--brand-primary-hover)'
opacity='0.4'
>
<animate
attributeName='opacity'
values='0.4;0.8;0.4'
@@ -241,8 +283,14 @@ export const IllustrationNotFound = ({ style = {} }) => (
<stop offset='100%' stopColor='var(--ui-color-danger)' />
</linearGradient>
<linearGradient id='notFoundGrad2' x1='0%' y1='0%' x2='100%' y2='100%'>
<stop offset='0%' stopColor='color-mix(in srgb, var(--ui-color-warning) 15%, #fff)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--ui-color-danger) 25%, #fff)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--ui-color-warning) 15%, #fff)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--ui-color-danger) 25%, #fff)'
/>
</linearGradient>
</defs>
{/* 背景 */}
@@ -330,8 +378,14 @@ export const IllustrationNotFoundDark = ({ style = {} }) => (
x2='100%'
y2='100%'
>
<stop offset='0%' stopColor='color-mix(in srgb, var(--ui-color-warning) 30%, #000)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--ui-color-danger) 30%, #000)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--ui-color-warning) 30%, #000)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--ui-color-danger) 30%, #000)'
/>
</linearGradient>
</defs>
<circle
@@ -410,7 +464,10 @@ export const IllustrationNoAccess = ({ style = {} }) => (
</linearGradient>
<linearGradient id='noAccessGrad2' x1='0%' y1='0%' x2='100%' y2='100%'>
<stop offset='0%' stopColor='#fce7f3' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-gradient-via) 10%, #fff)' />
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-gradient-via) 10%, #fff)'
/>
</linearGradient>
</defs>
{/* 背景 */}
@@ -444,7 +501,13 @@ export const IllustrationNoAccess = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='160' cy='130' r='5' fill='var(--brand-gradient-via)' opacity='0.4'>
<circle
cx='160'
cy='130'
r='5'
fill='var(--brand-gradient-via)'
opacity='0.4'
>
<animate
attributeName='r'
values='5;7;5'
@@ -480,8 +543,14 @@ export const IllustrationNoAccessDark = ({ style = {} }) => (
x2='100%'
y2='100%'
>
<stop offset='0%' stopColor='color-mix(in srgb, var(--ui-color-danger) 30%, #000)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--ui-color-danger) 30%, #000)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)'
/>
</linearGradient>
</defs>
<circle
@@ -499,8 +568,20 @@ export const IllustrationNoAccessDark = ({ style = {} }) => (
rx='8'
fill='url(#noAccessGradDark1)'
/>
<circle cx='100' cy='112' r='8' fill='color-mix(in srgb, var(--brand-primary) 15%, #000)' />
<rect x='96' y='112' width='8' height='18' rx='2' fill='color-mix(in srgb, var(--brand-primary) 15%, #000)' />
<circle
cx='100'
cy='112'
r='8'
fill='color-mix(in srgb, var(--brand-primary) 15%, #000)'
/>
<rect
x='96'
y='112'
width='8'
height='18'
rx='2'
fill='color-mix(in srgb, var(--brand-primary) 15%, #000)'
/>
<path
d='M75 90 V70 C75 55 85 45 100 45 C115 45 125 55 125 70 V90'
stroke='url(#noAccessGradDark1)'
@@ -516,7 +597,13 @@ export const IllustrationNoAccessDark = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='160' cy='130' r='5' fill='var(--brand-gradient-to)' opacity='0.5'>
<circle
cx='160'
cy='130'
r='5'
fill='var(--brand-gradient-to)'
opacity='0.5'
>
<animate
attributeName='r'
values='5;7;5'
@@ -541,8 +628,14 @@ export const IllustrationConstruction = ({ style = {} }) => (
<stop offset='100%' stopColor='var(--accent-teal)' />
</linearGradient>
<linearGradient id='constructGrad2' x1='0%' y1='0%' x2='100%' y2='100%'>
<stop offset='0%' stopColor='color-mix(in srgb, var(--ui-color-success) 15%, #fff)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--accent-teal) 15%, #fff)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--ui-color-success) 15%, #fff)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--accent-teal) 15%, #fff)'
/>
</linearGradient>
</defs>
{/* 背景 */}
@@ -670,8 +763,14 @@ export const IllustrationConstructionDark = ({ style = {} }) => (
x2='100%'
y2='100%'
>
<stop offset='0%' stopColor='color-mix(in srgb, var(--ui-color-success) 25%, #000)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--accent-teal) 25%, #000)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--ui-color-success) 25%, #000)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--accent-teal) 25%, #000)'
/>
</linearGradient>
</defs>
<circle
@@ -783,8 +882,14 @@ export const IllustrationNoContent = ({ style = {} }) => (
<stop offset='100%' stopColor='var(--brand-gradient-via)' />
</linearGradient>
<linearGradient id='noContentGrad2' x1='0%' y1='0%' x2='100%' y2='100%'>
<stop offset='0%' stopColor='color-mix(in srgb, var(--accent-blue) 12%, #fff)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-gradient-via) 10%, #fff)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--accent-blue) 12%, #fff)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-gradient-via) 10%, #fff)'
/>
</linearGradient>
</defs>
{/* 背景 */}
@@ -846,7 +951,13 @@ export const IllustrationNoContent = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='40' cy='145' r='3' fill='var(--brand-gradient-via)' opacity='0.4'>
<circle
cx='40'
cy='145'
r='3'
fill='var(--brand-gradient-via)'
opacity='0.4'
>
<animate
attributeName='opacity'
values='0.4;0.8;0.4'
@@ -882,8 +993,14 @@ export const IllustrationNoContentDark = ({ style = {} }) => (
x2='100%'
y2='100%'
>
<stop offset='0%' stopColor='color-mix(in srgb, var(--accent-blue) 25%, #000)' />
<stop offset='100%' stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)' />
<stop
offset='0%'
stopColor='color-mix(in srgb, var(--accent-blue) 25%, #000)'
/>
<stop
offset='100%'
stopColor='color-mix(in srgb, var(--brand-gradient-via) 25%, #000)'
/>
</linearGradient>
</defs>
<circle
@@ -941,7 +1058,13 @@ export const IllustrationNoContentDark = ({ style = {} }) => (
repeatCount='indefinite'
/>
</circle>
<circle cx='40' cy='145' r='3' fill='var(--brand-gradient-to)' opacity='0.5'>
<circle
cx='40'
cy='145'
r='3'
fill='var(--brand-gradient-to)'
opacity='0.5'
>
<animate
attributeName='opacity'
values='0.5;0.9;0.5'
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import ReactMarkdown from 'react-markdown';
import 'katex/dist/katex.min.css';
import 'highlight.js/styles/github.css';
@@ -26,13 +27,7 @@ import RemarkBreaks from 'remark-breaks';
import RehypeKatex from 'rehype-katex';
import RemarkGfm from 'remark-gfm';
import RehypeHighlight from 'rehype-highlight';
import {
useRef,
useState,
useEffect,
useMemo,
useId,
} from 'react';
import { useRef, useState, useEffect, useMemo, useId } from 'react';
import React from 'react';
import { useDebouncedCallback } from 'use-debounce';
import clsx from 'clsx';
@@ -199,7 +194,7 @@ export function PreCode(props) {
}, 600);
// 处理代码块的换行
useEffect(() => {
const onMount = useEffectEvent(() => {
if (ref.current) {
const codeElements = ref.current.querySelectorAll('code');
const wrapLanguages = [
@@ -221,7 +216,8 @@ export function PreCode(props) {
});
setTimeout(renderArtifacts, 1);
}
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
@@ -509,9 +505,7 @@ function MarkdownContentImpl(props) {
{...aProps}
target={target}
style={{
color: isUserMessage
? '#87CEEB'
: 'var(--ui-color-primary)',
color: isUserMessage ? '#87CEEB' : 'var(--ui-color-primary)',
textDecoration: 'none',
}}
onMouseEnter={(e) => {
@@ -18,13 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect, useContext } from 'react';
import {
Modal,
RadioGroup,
Radio,
Button,
Typography,
} from '@/components/ui';
import { Modal, RadioGroup, Radio, Button, Typography } from '@/components/ui';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
+7 -5
View File
@@ -161,16 +161,18 @@ const JSONEditor = ({
}
// 只在外部值真正改变时更新,避免循环更新
const currentObj = keyValueArrayToObject(keyValuePairs);
if (JSON.stringify(parsed) !== JSON.stringify(currentObj)) {
setKeyValuePairs(objectToKeyValueArray(parsed, keyValuePairs));
}
setKeyValuePairs((previous) => {
const currentObj = keyValueArrayToObject(previous);
return JSON.stringify(parsed) === JSON.stringify(currentObj)
? previous
: objectToKeyValueArray(parsed, previous);
});
setJsonError('');
} catch (error) {
console.log('JSON解析失败:', error.message);
setJsonError(error.message);
}
}, [value]);
}, [value, keyValueArrayToObject, objectToKeyValueArray]);
// 外部 value 变化时,若不在手动模式,则同步手动文本
useEffect(() => {
+4 -1
View File
@@ -38,7 +38,10 @@ const readBrand = (key, windowKey) => {
// 加载文案根据浏览器语言决定,避免 i18n 还没初始化时硬编码中文。
const getLoadingText = () => {
const lang = ((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase();
const lang = (
(typeof navigator !== 'undefined' && navigator.language) ||
'zh'
).toLowerCase();
return lang.startsWith('zh') ? '加载中...' : 'Loading...';
};
@@ -47,6 +47,29 @@ import { IconChevronDown, IconChevronUp } from '@/components/ui/icons';
* @param {boolean} withCheckbox 是否启用前缀 Checkbox 来控制激活状态
* @param {boolean} loading 是否处于加载状态
*/
const ConditionalTooltipText = ({ text, containerWidth }) => {
const textRef = useRef(null);
const [isOverflowing, setIsOverflowing] = useState(false);
useEffect(() => {
const el = textRef.current;
if (!el) return;
setIsOverflowing(el.scrollWidth > el.clientWidth);
}, [text, containerWidth]);
const textElement = (
<span ref={textRef} className='sbg-ellipsis'>
{text}
</span>
);
return isOverflowing ? (
<Tooltip content={text}>{textElement}</Tooltip>
) : (
textElement
);
};
const SelectableButtonGroup = ({
title,
items = [],
@@ -63,29 +86,6 @@ const SelectableButtonGroup = ({
const [skeletonCount] = useState(12);
const [containerRef, containerWidth] = useContainerWidth();
const ConditionalTooltipText = ({ text }) => {
const textRef = useRef(null);
const [isOverflowing, setIsOverflowing] = useState(false);
useEffect(() => {
const el = textRef.current;
if (!el) return;
setIsOverflowing(el.scrollWidth > el.clientWidth);
}, [text, containerWidth]);
const textElement = (
<span ref={textRef} className='sbg-ellipsis'>
{text}
</span>
);
return isOverflowing ? (
<Tooltip content={text}>{textElement}</Tooltip>
) : (
textElement
);
};
// 基于容器宽度计算响应式列数和标签显示策略
const getResponsiveConfig = () => {
if (containerWidth <= 280) return { columns: 1, showTags: true }; // 极窄:1列+标签
@@ -207,7 +207,10 @@ const SelectableButtonGroup = ({
>
<div className='sbg-content'>
{item.icon && <span className='sbg-icon'>{item.icon}</span>}
<ConditionalTooltipText text={item.label} />
<ConditionalTooltipText
text={item.label}
containerWidth={containerWidth}
/>
{item.tagCount !== undefined && shouldShowTags && (
<Tag
className='sbg-tag'
@@ -236,7 +239,10 @@ const SelectableButtonGroup = ({
>
<div className='sbg-content'>
{item.icon && <span className='sbg-icon'>{item.icon}</span>}
<ConditionalTooltipText text={item.label} />
<ConditionalTooltipText
text={item.label}
containerWidth={containerWidth}
/>
{item.tagCount !== undefined && shouldShowTags && (
<Tag
className='sbg-tag'
-7
View File
@@ -437,10 +437,3 @@
grid-column: auto;
}
}
.console-overlay .console-detail-header .ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-overlay .console-detail-header .ant-drawer-close {
margin-inline: 12px 0;
}
@@ -150,31 +150,11 @@
grid-template-columns: minmax(0, 1fr);
}
}
.console-model-drawer .prefill-management-header .ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-model-drawer .prefill-management-header .ant-drawer-close {
margin-inline: 12px 0;
}
.console-model-drawer .console-model-editor-header .ant-drawer-header-title,
.console-channel-drawer
.console-channel-editor-header
.ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-model-drawer .console-model-editor-header .ant-drawer-title,
.console-channel-drawer .console-channel-editor-header .ant-drawer-title {
text-align: start;
}
.console-model-drawer .console-model-editor-header .ant-drawer-close,
.console-channel-drawer .console-channel-editor-header .ant-drawer-close {
margin-inline: 12px 0;
}
.console-model-drawer .console-model-tag-presets {
margin-top: 10px;
}
+1 -9
View File
@@ -18,15 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Card,
Button,
Spin,
Tabs,
TabPane,
Tag,
Empty,
} from '@/components/ui';
import { Card, Button, Spin, Tabs, TabPane, Tag, Empty } from '@/components/ui';
import { Gauge, RefreshCw } from 'lucide-react';
import {
IllustrationConstruction,
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useContext, useEffect } from 'react';
import { getRelativeTime } from '../../helpers';
import { UserContext } from '../../context/User';
@@ -134,9 +135,10 @@ const Dashboard = () => {
);
// ========== Effects ==========
useEffect(() => {
const onMount = useEffectEvent(() => {
initChart();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<div className='h-full'>
+10 -2
View File
@@ -106,9 +106,17 @@ const ImageGenerationParams = ({
newParams.n = modelCapabilities.maxImages;
}
return newParams;
return newParams.size === prev.size &&
newParams.quality === prev.quality &&
newParams.n === prev.n
? prev
: newParams;
});
}, [modelInfo]);
}, [
modelCapabilities.sizes,
modelCapabilities.supportsQuality,
modelCapabilities.maxImages,
]);
// 参数更新函数
const updateParam = useCallback(
+5 -3
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { Layout } from '@/components/ui';
import App from '../../App';
import React, {
@@ -301,9 +302,9 @@ const PageLayout = () => {
setShowGiftModal(true);
}
}
}, [userState?.user?.id]);
}, [userState?.user?.id, userState?.user?.username, userState?.user?.quota]);
useEffect(() => {
const onBootstrap = useEffectEvent(() => {
if (!authBootstrappedRef.current) {
authBootstrappedRef.current = true;
loadUser();
@@ -325,7 +326,8 @@ const PageLayout = () => {
}
}
// 界面语言已由 i18n/bootstrap.js 在渲染前判定,这里不再读取语言缓存
}, [i18n]);
});
useEffect(() => onBootstrap(), [onBootstrap, i18n]);
return (
<Layout
+8 -20
View File
@@ -76,16 +76,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
const location = useLocation();
const [routerMapState, setRouterMapState] = useState(routerMap);
const dataExportFlag = localStorage.getItem('enable_data_export');
const drawingFlag = localStorage.getItem('enable_drawing');
const taskFlag = localStorage.getItem('enable_task');
const workspaceItems = useMemo(() => {
const items = [
{
text: t('数据看板'),
itemKey: 'detail',
to: '/detail',
className:
localStorage.getItem('enable_data_export') === 'true'
? ''
: 'tableHiddle',
className: dataExportFlag === 'true' ? '' : 'tableHiddle',
},
{
text: t('密钥管理'),
@@ -101,17 +101,13 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
text: t('绘图日志'),
itemKey: 'midjourney',
to: '/midjourney',
className:
localStorage.getItem('enable_drawing') === 'true'
? ''
: 'tableHiddle',
className: drawingFlag === 'true' ? '' : 'tableHiddle',
},
{
text: t('任务日志'),
itemKey: 'task',
to: '/task',
className:
localStorage.getItem('enable_task') === 'true' ? '' : 'tableHiddle',
className: taskFlag === 'true' ? '' : 'tableHiddle',
},
{
text: t('监控中心'),
@@ -127,13 +123,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
});
return filteredItems;
}, [
localStorage.getItem('enable_data_export'),
localStorage.getItem('enable_drawing'),
localStorage.getItem('enable_task'),
t,
isModuleVisible,
]);
}, [dataExportFlag, drawingFlag, taskFlag, t, isModuleVisible]);
const financeItems = useMemo(() => {
const items = [
@@ -296,8 +286,6 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
return filteredItems;
}, [
isAdmin(),
isRoot(),
t,
isModuleVisible,
canAccessSetting,
@@ -375,7 +363,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
showError(t('聊天数据解析失败'));
}
}
}, []);
}, [t]);
// 根据当前路径设置选中的菜单项
useEffect(() => {
@@ -17,13 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useState,
useEffect,
useCallback,
useRef,
useMemo,
} from 'react';
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Empty as AntEmpty, Tag as AntTag } from 'antd';
import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui';
import { API, renderQuota } from '../../helpers';
@@ -161,81 +155,78 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
};
// 表格列定义(使用 useCallback 的格式化函数作为依赖)
const columns = useMemo(
() => [
{
title: t('方案名称'),
dataIndex: 'plan_name',
key: 'plan_name',
width: 180,
render: (text, record) => (
<div>
<Text>{text || '-'}</Text>
<Text type='tertiary' size='small' className='block'>
{PLAN_TYPE_MAP[record.plan_type] || record.plan_type} ·{' '}
{TIER_MAP[record.tier] || record.tier}
</Text>
</div>
),
const columns = [
{
title: t('方案名称'),
dataIndex: 'plan_name',
key: 'plan_name',
width: 180,
render: (text, record) => (
<div>
<Text>{text || '-'}</Text>
<Text type='tertiary' size='small' className='block'>
{PLAN_TYPE_MAP[record.plan_type] || record.plan_type} ·{' '}
{TIER_MAP[record.tier] || record.tier}
</Text>
</div>
),
},
{
title: t('每日额度'),
dataIndex: 'daily_quota',
key: 'daily_quota',
width: 120,
render: (quota) => renderQuota(quota),
},
{
title: t('天数'),
key: 'duration_days',
width: 80,
align: 'center',
render: (_, record) => {
// duration_days 不在 UserMembership 模型中,需从 end_date - start_date 计算
const days =
record.end_date && record.start_date
? Math.round((record.end_date - record.start_date) / 86400)
: '-';
return `${days} ${t('天')}`;
},
{
title: t('每日额度'),
dataIndex: 'daily_quota',
key: 'daily_quota',
width: 120,
render: (quota) => renderQuota(quota),
},
{
title: t('天数'),
key: 'duration_days',
width: 80,
align: 'center',
render: (_, record) => {
// duration_days 不在 UserMembership 模型中,需从 end_date - start_date 计算
const days =
record.end_date && record.start_date
? Math.round((record.end_date - record.start_date) / 86400)
: '-';
return `${days} ${t('天')}`;
},
},
{
title: t('购买价格'),
dataIndex: 'price_paid',
key: 'price_paid',
width: 100,
render: (price) => `¥${price?.toFixed(2) || '0.00'}`,
},
{
title: t('生效日期'),
dataIndex: 'start_date',
key: 'start_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('到期日期'),
dataIndex: 'end_date',
key: 'end_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('状态'),
key: 'status',
width: 100,
render: (_, record) => renderStatusTag(record),
},
{
title: t('购买时间'),
dataIndex: 'created_at',
key: 'created_at',
width: 140,
render: (time) => formatDateTime(time),
},
],
[t, formatDate, formatDateTime],
);
},
{
title: t('购买价格'),
dataIndex: 'price_paid',
key: 'price_paid',
width: 100,
render: (price) => `¥${price?.toFixed(2) || '0.00'}`,
},
{
title: t('生效日期'),
dataIndex: 'start_date',
key: 'start_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('到期日期'),
dataIndex: 'end_date',
key: 'end_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('状态'),
key: 'status',
width: 100,
render: (_, record) => renderStatusTag(record),
},
{
title: t('购买时间'),
dataIndex: 'created_at',
key: 'created_at',
width: 140,
render: (time) => formatDateTime(time),
},
];
return (
<div className={inline ? 'rc-member-history' : 'flex flex-col h-full'}>
@@ -17,14 +17,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import {
TextArea,
Typography,
Button,
Switch,
Banner,
} from '@/components/ui';
import { TextArea, Typography, Button, Switch, Banner } from '@/components/ui';
import { Code, Edit, Check, X, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -60,12 +55,13 @@ const CustomRequestEditor = ({
]);
// 同步外部传入的customRequestBody到本地状态
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
if (customRequestBody !== localValue) {
setLocalValue(customRequestBody || '');
validateJson(customRequestBody || '');
}
}, [customRequestBody]);
});
useEffect(() => onScopeChange(), [onScopeChange, customRequestBody]);
// 验证JSON格式
const validateJson = (value) => {
+3 -1
View File
@@ -145,7 +145,9 @@ const DebugPanel = ({
<Eye size={16} />
{t('预览请求体')}
{customRequestMode && (
<span className='px-1.5 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full'>{t('自定义')}</span>
<span className='px-1.5 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full'>
{t('自定义')}
</span>
)}
</div>
}
+8 -5
View File
@@ -82,10 +82,13 @@ const MessageContent = ({
const now = new Date();
const nextDay = new Date(now);
nextDay.setHours(24, 0, 1, 0);
timerId = window.setTimeout(() => {
setCurrentDateKey(new Date().toDateString());
scheduleNextDateRefresh();
}, Math.max(1000, nextDay.getTime() - now.getTime()));
timerId = window.setTimeout(
() => {
setCurrentDateKey(new Date().toDateString());
scheduleNextDateRefresh();
},
Math.max(1000, nextDay.getTime() - now.getTime()),
);
};
scheduleNextDateRefresh();
@@ -116,7 +119,7 @@ const MessageContent = ({
const messageTimeText = React.useMemo(() => {
if (!messageTime) return '';
const now = new Date();
const now = new Date(currentDateKey);
const sameYear = messageTime.getFullYear() === now.getFullYear();
const sameDay =
sameYear &&
+5 -1
View File
@@ -29,7 +29,11 @@ import {
Zap,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { renderGroupOption, renderModelOption, selectFilter } from '../../helpers';
import {
renderGroupOption,
renderModelOption,
selectFilter,
} from '../../helpers';
import ParameterControl from './ParameterControl';
import ImageUrlInput from './ImageUrlInput';
import ConfigManager from './ConfigManager';
@@ -121,7 +121,9 @@ const ThinkingContent = ({
<Typography.Text
style={{ color: 'white' }}
className='text-xs sm:text-sm font-medium opacity-90'
>{t('思考中')}</Typography.Text>
>
{t('思考中')}
</Typography.Text>
</div>
)}
{(!isThinkingStatus || message.isThinkingComplete) && (
+2 -7
View File
@@ -8,11 +8,7 @@
--q-success: var(--ui-color-success);
--q-danger: var(--ui-color-danger);
--q-warning: var(--ui-color-warning);
--q-tint: color-mix(
in srgb,
var(--ui-color-primary) 6%,
var(--surface-card)
);
--q-tint: color-mix(in srgb, var(--ui-color-primary) 6%, var(--surface-card));
display: flex;
flex-direction: column;
gap: 16px;
@@ -184,8 +180,7 @@
var(--ui-color-warning) 10%,
var(--surface-card)
);
border: 1px solid
color-mix(in srgb, var(--ui-color-warning) 30%, transparent);
border: 1px solid color-mix(in srgb, var(--ui-color-warning) 30%, transparent);
}
.quality-notice[data-tone='info'] {
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui';
import SettingsChats from '../../pages/Setting/Chat/SettingsChats';
@@ -63,9 +64,10 @@ const ChatsSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, Spin, Modal } from '@/components/ui';
@@ -86,9 +87,10 @@ const DashboardSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
// 用于迁移检测的旧键,下个版本会删除
const hasLegacyData = useMemo(() => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
@@ -362,9 +363,10 @@ export default function DataSecuritySetting() {
loadOrgConfigs();
};
useEffect(() => {
const onMount = useEffectEvent(() => {
reloadAll();
}, []);
});
useEffect(() => onMount(), [onMount]);
const onSave = async () => {
if (!configLoaded) {
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui';
import SettingsDrawing from '../../pages/Setting/Drawing/SettingsDrawing';
@@ -65,9 +66,10 @@ const DrawingSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui';
@@ -98,9 +99,10 @@ const ModelSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { Button, Col, Form, Row, Modal, Space, Card } from '@/components/ui';
import { API, showError, showSuccess, timestamp2string } from '../../helpers';
@@ -354,9 +355,10 @@ const OtherSetting = () => {
}
};
useEffect(() => {
const onMount = useEffectEvent(() => {
getOptions();
}, []);
});
useEffect(() => onMount(), [onMount]);
// 打开官网(可配置,未配置则按钮不显示)
const officialWebsite = (statusState?.status?.official_website || '').trim();
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui';
import SettingsGeneralPayment from '../../pages/Setting/Payment/SettingsGeneralPayment';
@@ -263,9 +264,10 @@ const PaymentSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
+10 -4
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
@@ -123,7 +124,7 @@ const PersonalSetting = () => {
recordIpLog: false,
});
useEffect(() => {
const onMount = useEffectEvent(() => {
let saved = localStorage.getItem('status');
if (saved) {
const parsed = JSON.parse(saved);
@@ -161,7 +162,8 @@ const PersonalSetting = () => {
isPasskeySupported()
.then(setPasskeySupported)
.catch(() => setPasskeySupported(false));
}, []);
});
useEffect(() => onMount(), [onMount]);
useEffect(() => {
let countdownInterval = null;
@@ -176,7 +178,7 @@ const PersonalSetting = () => {
return () => clearInterval(countdownInterval);
}, [disableButton, countdown]);
useEffect(() => {
const onScopeChange2 = useEffectEvent(() => {
if (userState?.user?.setting) {
const settings = parseUserSetting(userState.user.setting);
setNotificationSettings({
@@ -214,7 +216,11 @@ const PersonalSetting = () => {
prev.avatarPreset || getDefaultAvatarPresetId(userState.user),
}));
}
}, [userState?.user?.id, userState?.user?.setting]);
});
useEffect(
() => onScopeChange2(),
[onScopeChange2, userState?.user?.id, userState?.user?.setting],
);
const handleInputChange = (name, value) => {
setInputs((inputs) => ({ ...inputs, [name]: value }));
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui';
@@ -70,9 +71,10 @@ const RateLimitSetting = () => {
}
}
useEffect(() => {
const onMount = useEffectEvent(() => {
onRefresh();
}, []);
});
useEffect(() => onMount(), [onMount]);
return (
<>
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -71,9 +72,10 @@ const TutorialVideoSetting = () => {
}
};
useEffect(() => {
const onMount = useEffectEvent(() => {
loadVideos();
}, []);
});
useEffect(() => onMount(), [onMount]);
// 格式化时长
const formatDuration = (seconds) => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import { writeClipboardText } from '../../../../helpers/clipboard';
import { API, showError, showSuccess, showWarning } from '../../../../helpers';
import {
@@ -78,9 +79,10 @@ const TwoFASetting = ({ t }) => {
}
};
useEffect(() => {
const onMount = useEffectEvent(() => {
fetchStatus();
}, []);
});
useEffect(() => onMount(), [onMount]);
// 初始化2FA设置
const handleSetup2FA = async () => {
@@ -18,14 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Avatar,
Card,
Tag,
Divider,
Typography,
Badge,
} from '@/components/ui';
import { Avatar, Card, Tag, Divider, Typography, Badge } from '@/components/ui';
import {
isRoot,
isAdmin,
+4 -2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import { Card, Divider, Steps, Form } from '@/components/ui';
import { API, showError, showNotice } from '../../helpers';
@@ -76,9 +77,10 @@ const SetupWizard = () => {
},
];
useEffect(() => {
const onMount = useEffectEvent(() => {
fetchSetupStatus();
}, []);
});
useEffect(() => onMount(), [onMount]);
const fetchSetupStatus = async () => {
try {
@@ -60,7 +60,6 @@ const ChannelsTable = (channelsData) => {
setCurrentMultiKeyChannel,
// Auto-ban exclusion
isChannelExcluded,
excludedChannels,
autoBanExclusionFilter,
// Daily quota info
dailyQuotaInfo,
@@ -127,7 +126,7 @@ const ChannelsTable = (channelsData) => {
return channel;
})
.filter(Boolean);
}, [channels, autoBanExclusionFilter, isChannelExcluded, excludedChannels]);
}, [channels, autoBanExclusionFilter, isChannelExcluded]);
// Get all columns
const allColumns = useMemo(() => {
@@ -175,7 +174,6 @@ const ChannelsTable = (channelsData) => {
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
isChannelExcluded,
excludedChannels,
dailyQuotaInfo,
]);
@@ -184,9 +182,7 @@ const ChannelsTable = (channelsData) => {
return allColumns.filter((column) => visibleColumns[column.key]);
};
const visibleColumnsList = useMemo(() => {
return getVisibleColumns();
}, [visibleColumns, allColumns]);
const visibleColumnsList = getVisibleColumns();
const tableColumns = useMemo(() => {
const sortableColumns = visibleColumnsList.map((column) =>
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import '../../../console/module-alignment.css';
import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -964,7 +965,7 @@ const EditChannelModal = (props) => {
setModelOptions(optionsWithIcon);
}, [originModelOptions, inputs.models, t]);
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
fetchModels().then();
fetchGroups().then();
if (!isEdit) {
@@ -977,7 +978,8 @@ const EditChannelModal = (props) => {
setBasicModels(localModels);
setInputs((inputs) => ({ ...inputs, models: localModels }));
}
}, [props.editingChannel.id]);
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingChannel.id]);
useEffect(() => {
if (formApiRef.current) {
@@ -985,7 +987,7 @@ const EditChannelModal = (props) => {
}
}, [inputs]);
useEffect(() => {
const onVisibilityChange2 = useEffectEvent(() => {
if (props.visible) {
if (isEdit) {
loadChannel();
@@ -1004,7 +1006,11 @@ const EditChannelModal = (props) => {
// 关闭后作废在途的兜底数据请求
fallbackLoadSeqRef.current += 1;
}
}, [props.visible, channelId]);
});
useEffect(
() => onVisibilityChange2(),
[onVisibilityChange2, props.visible, channelId],
);
useEffect(() => {
if (!isEdit) {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect, useRef } from 'react';
import {
API,
@@ -270,7 +271,7 @@ const EditTagModal = (props) => {
setModelOptions(localModelOptions);
}, [originModelOptions, inputs.models]);
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
const fetchTagModels = async () => {
if (!tag) return;
setLoading(true);
@@ -305,7 +306,8 @@ const EditTagModal = (props) => {
tag: tag,
new_tag: tag,
});
}, [visible, tag]);
});
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible, tag]);
useEffect(() => {
if (formApiRef.current) {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -288,12 +289,16 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
};
// Effect to load data when modal opens
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible && channel?.id) {
setCurrentPage(1); // Reset to first page when opening
loadKeyStatus(1, pageSize);
}
}, [visible, channel?.id]);
});
useEffect(
() => onVisibilityChange(),
[onVisibilityChange, visible, channel?.id],
);
// Reset pagination when modal closes
useEffect(() => {
@@ -130,7 +130,9 @@ function renderType(type, t) {
);
case 'UPLOAD':
return (
<Tag color='blue' shape='circle' prefixIcon={<Upload size={14} />}>{t('上传文件')}</Tag>
<Tag color='blue' shape='circle' prefixIcon={<Upload size={14} />}>
{t('上传文件')}
</Tag>
);
case 'SHORTEN':
return (
@@ -404,9 +406,7 @@ export const getMjLogsColumns = ({
{
<Progress
stroke={
record.status === 'FAILURE'
? 'var(--ui-color-warning)'
: null
record.status === 'FAILURE' ? 'var(--ui-color-warning)' : null
}
percent={text ? parseInt(text.replace('%', '')) : 0}
showInfo={true}
+1 -3
View File
@@ -58,9 +58,7 @@ const MjLogsTable = (mjLogsData) => {
return allColumns.filter((column) => visibleColumns[column.key]);
};
const visibleColumnsList = useMemo(() => {
return getVisibleColumns();
}, [visibleColumns, allColumns]);
const visibleColumnsList = getVisibleColumns();
return (
<CardTable
@@ -17,16 +17,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import {
Card,
Row,
Col,
Typography,
Tag,
Spin,
Empty,
} from '@/components/ui';
import { Card, Row, Col, Typography, Tag, Spin, Empty } from '@/components/ui';
import { API, showError } from '../../../helpers';
import { MODEL_CATEGORY_NAMES } from '../../../constants';
@@ -53,9 +46,10 @@ const ModelsCategoryStats = ({ t }) => {
setLoading(false);
};
useEffect(() => {
const onMount = useEffectEvent(() => {
loadStats();
}, []);
});
useEffect(() => onMount(), [onMount]);
const getCategoryColor = (category) => {
const colorMap = {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import { Modal, Select, Typography, Spin } from '@/components/ui';
import { API, showError } from '../../../../helpers';
@@ -66,11 +67,12 @@ const BatchCategoryModal = ({
};
// 当弹窗打开时加载分类
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible) {
loadCategories();
}
}, [visible]);
});
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]);
const handleConfirm = async () => {
if (selectedCategories.length === 0) return;
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import '../../../console/module-alignment.css';
import React, { useState, useEffect, useRef } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor';
@@ -228,7 +229,7 @@ const EditModelModal = (props) => {
setLoading(false);
};
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues({
@@ -237,9 +238,13 @@ const EditModelModal = (props) => {
});
}
}
}, [props.editingModel?.id, props.editingModel?.model_name]);
});
useEffect(
() => onScopeChange(),
[onScopeChange, props.editingModel?.id, props.editingModel?.model_name],
);
useEffect(() => {
const onVisibilityChange2 = useEffectEvent(() => {
if (props.visiable) {
if (isEdit) {
loadModel();
@@ -252,7 +257,16 @@ const EditModelModal = (props) => {
} else {
formApiRef.current?.reset();
}
}, [props.visiable, props.editingModel?.id, props.editingModel?.model_name]);
});
useEffect(
() => onVisibilityChange2(),
[
onVisibilityChange2,
props.visiable,
props.editingModel?.id,
props.editingModel?.model_name,
],
);
const submit = async (values) => {
setLoading(true);
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useRef, useEffect } from 'react';
import { Modal, Form, Col, Row } from '@/components/ui';
import { API, showError, showSuccess } from '../../../../helpers';
@@ -67,7 +68,7 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
setLoading(false);
};
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible) {
if (isEdit) {
loadVendor();
@@ -77,7 +78,11 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
} else {
formApiRef.current?.reset();
}
}, [visible, editingVendor?.id]);
});
useEffect(
() => onVisibilityChange(),
[onVisibilityChange, visible, editingVendor?.id],
);
const submit = async (values) => {
setLoading(true);
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react';
import {
Modal,
@@ -59,7 +60,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
setLoading(false);
};
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible) {
fetchMissing();
setSearchKeyword('');
@@ -67,7 +68,8 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
} else {
setMissingModels([]);
}
}, [visible]);
});
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]);
// 过滤和分页逻辑
const filteredModels = missingModels.filter((model) =>
@@ -238,14 +238,7 @@ const UpstreamConflictModal = ({
});
return [...base, ...cols.filter(Boolean)];
}, [
t,
selections,
filteredDataSource,
getHeaderState,
applyHeaderChange,
toggleField,
]);
}, [t, selections, getHeaderState, applyHeaderChange, toggleField]);
const pagedDataSource = useMemo(() => {
const start = (currentPage - 1) * paginationSize;
@@ -57,19 +57,7 @@ const RedemptionsTable = (redemptionsData) => {
};
// Get all columns
const columns = useMemo(() => {
return getRedemptionsColumns({
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal,
});
}, [
const columns = getRedemptionsColumns({
t,
manageRedemption,
copyText,
@@ -79,7 +67,7 @@ const RedemptionsTable = (redemptionsData) => {
redemptions,
activePage,
showDeleteRedemptionModal,
]);
});
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -87,7 +88,7 @@ const EditRedemptionModal = (props) => {
setLoading(false);
};
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (isEdit) {
loadRedemption();
@@ -95,7 +96,8 @@ const EditRedemptionModal = (props) => {
formApiRef.current.setValues(getInitValues());
}
}
}, [props.editingRedemption.id]);
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingRedemption.id]);
const submit = async (values) => {
let name = values.name;
@@ -72,9 +72,7 @@ const TaskLogsTable = (taskLogsData) => {
return allColumns.filter((column) => visibleColumns[column.key]);
};
const visibleColumnsList = useMemo(() => {
return getVisibleColumns();
}, [visibleColumns, allColumns]);
const visibleColumnsList = getVisibleColumns();
const tableColumns = useMemo(() => {
return compactMode
+17 -17
View File
@@ -17,14 +17,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useEffect, useRef, useState } from 'react';
import {
Notification,
Button,
Space,
Toast,
Select,
} from '@/components/ui';
import { Notification, Button, Space, Toast, Select } from '@/components/ui';
import {
API,
showError,
@@ -51,14 +46,18 @@ function TokensPage({ labelReplace } = {}) {
// Create a wrapped translation function that replaces labels if needed
const originalT = tokensData.t;
const t = labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/密钥/g, labelReplace)
: result;
}
: originalT;
const t = React.useMemo(
() =>
labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/密钥/g, labelReplace)
: result;
}
: originalT,
[originalT, labelReplace],
);
const latestRef = useRef({
tokens: [],
@@ -256,7 +255,7 @@ function TokensPage({ labelReplace } = {}) {
};
// Show notification when Fluent container is available
useEffect(() => {
const onMount = useEffectEvent(() => {
const onAppeared = () => {
openFluentNotification();
};
@@ -271,7 +270,8 @@ function TokensPage({ labelReplace } = {}) {
window.removeEventListener('fluent-container:appeared', onAppeared);
window.removeEventListener('fluent-container:removed', onRemoved);
};
}, []);
});
useEffect(() => onMount(), [onMount]);
// When modelOptions or language changes while the notice is open, refresh the content
useEffect(() => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useContext, useRef } from 'react';
import {
API,
@@ -277,7 +278,7 @@ const EditTokenModal = (props) => {
setLoading(false);
};
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues(getInitValues());
@@ -286,9 +287,10 @@ const EditTokenModal = (props) => {
loadModels();
loadGroups();
loadSkillOptions();
}, [props.editingToken.id]);
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingToken.id]);
useEffect(() => {
const onVisibilityChange2 = useEffectEvent(() => {
if (props.visiable) {
if (isEdit) {
loadToken();
@@ -308,7 +310,11 @@ const EditTokenModal = (props) => {
setNeverExpire(true);
setExpireDate(null);
}
}, [props.visiable, props.editingToken.id]);
});
useEffect(
() => onVisibilityChange2(),
[onVisibilityChange2, props.visiable, props.editingToken.id],
);
const generateRandomSuffix = () => {
const characters =
+9 -22
View File
@@ -125,31 +125,18 @@ const UsersTable = (usersData) => {
};
// Get all columns
const columns = useMemo(() => {
return getUsersColumns({
t,
setEditingUser,
setShowEditUser,
showPromoteModal: showPromoteUserModal,
showDemoteModal: showDemoteUserModal,
showEnableDisableModal: showEnableDisableUserModal,
showDeleteModal: showDeleteUserModal,
showResetPasskeyModal: showResetPasskeyUserModal,
showResetTwoFAModal: showResetTwoFAUserModal,
showInvitedUsersModal: showInvitedUsersUserModal,
});
}, [
const columns = getUsersColumns({
t,
setEditingUser,
setShowEditUser,
showPromoteUserModal,
showDemoteUserModal,
showEnableDisableUserModal,
showDeleteUserModal,
showResetPasskeyUserModal,
showResetTwoFAUserModal,
showInvitedUsersUserModal,
]);
showPromoteModal: showPromoteUserModal,
showDemoteModal: showDemoteUserModal,
showEnableDisableModal: showEnableDisableUserModal,
showDeleteModal: showDeleteUserModal,
showResetPasskeyModal: showResetPasskeyUserModal,
showResetTwoFAModal: showResetTwoFAUserModal,
showInvitedUsersModal: showInvitedUsersUserModal,
});
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess, renderQuota } from '../../../../helpers';
@@ -122,13 +123,14 @@ const EditUserModal = (props) => {
setLoading(false);
};
useEffect(() => {
const onScopeChange = useEffectEvent(() => {
loadUser();
if (userId) {
fetchGroups();
fetchLevels();
}
}, [props.editingUser.id]);
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingUser.id]);
/* ----------------------- submit ----------------------- */
const submit = async (values) => {
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
import { Modal, Table, Tag, Spin } from '@/components/ui';
import { API, renderQuota, renderNumber, showError } from '../../../../helpers';
@@ -27,11 +28,12 @@ const InvitedUsersModal = ({ visible, onCancel, user, t }) => {
const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0);
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible && user) {
fetchInvitedUsers();
}
}, [visible, user]);
});
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible, user]);
const fetchInvitedUsers = async () => {
if (!user?.id) return;
+1 -6
View File
@@ -28,12 +28,7 @@ import {
Spin,
Tooltip,
} from '@/components/ui';
import {
CreditCard,
Coins,
Wallet,
Receipt,
} from 'lucide-react';
import { CreditCard, Coins, Wallet, Receipt } from 'lucide-react';
import {
AlipayBrandIcon,
WechatBrandIcon,
+7 -4
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useContext, useRef } from 'react';
import {
API,
@@ -467,12 +468,13 @@ const TopUp = () => {
else showError(t('复制失败,请手动复制'));
};
useEffect(() => {
const onMount = useEffectEvent(() => {
if (!userState?.user?.id) {
getUserQuota().then();
}
setTransferAmount(getQuotaPerUnit());
}, []);
});
useEffect(() => onMount(), [onMount]);
useEffect(() => {
if (affFetchedRef.current) return;
@@ -481,9 +483,10 @@ const TopUp = () => {
}, []);
// 在 statusState 可用时获取充值信息
useEffect(() => {
const onMount2 = useEffectEvent(() => {
getTopupInfo().then();
}, []);
});
useEffect(() => onMount2(), [onMount2]);
useEffect(() => {
if (statusState?.status) {
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useState, useEffect, useMemo } from 'react';
import {
Modal,
@@ -112,11 +113,15 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
}
};
useEffect(() => {
const onVisibilityChange = useEffectEvent(() => {
if (visible) {
loadTopups(page, pageSize);
}
}, [visible, page, pageSize, keyword]);
});
useEffect(
() => onVisibilityChange(),
[onVisibilityChange, visible, page, pageSize, keyword],
);
const handlePageChange = (currentPage) => {
setPage(currentPage);
@@ -187,7 +192,7 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
// 检查是否为管理员
const userIsAdmin = useMemo(() => isAdmin(), []);
const columns = useMemo(() => {
const columns = (() => {
const baseColumns = [
{
title: t('订单号'),
@@ -273,7 +278,7 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
});
return baseColumns;
}, [t, userIsAdmin]);
})();
return (
<Modal

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