Compare commits
97 Commits
ae7f773627
...
weiyuan
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a0d9e15cd | |||
| 04cf3324a3 | |||
| a811793825 | |||
| 9576ba674a | |||
| 870b51d054 | |||
| ed693a450a | |||
| 49515f4ef3 | |||
| f896495048 | |||
| a532b860c8 | |||
| dd4da99f1d | |||
| 437a0345e8 | |||
| 9b9e98a6b4 | |||
| 574b6efa1e | |||
| 45979985fe | |||
| 4cd894b7ae | |||
| 09e1d7cf7f | |||
| 2ae4a625b5 | |||
| 031e22ee49 | |||
| ef67244aea | |||
| 436195a229 | |||
| 46aaa44a77 | |||
| ab79dfd357 | |||
| 461f0c577a | |||
| 72e7fe1072 | |||
| d90319f43a | |||
| 9145ed5834 | |||
| 94ac3db60c | |||
| 2aa9d73325 | |||
| 605cff1d58 | |||
| 04cc45bbb7 | |||
| 7908ed53a3 | |||
| 9b6eb1c7c4 | |||
| f88a404fab | |||
| 074c4422f9 | |||
| f8c451b7b8 | |||
| ff93660768 | |||
| b6a859bcad | |||
| 5610fdc273 | |||
| db3dba1e96 | |||
| 737c353d84 | |||
| d878f0db21 | |||
| 67969a041d | |||
| ef3f405190 | |||
| e154b31b99 | |||
| 3dc2624e00 | |||
| 822d26c0dd | |||
| 923e27de08 | |||
| 19fd943660 | |||
| 28b71237df | |||
| 0fe6151153 | |||
| 7b7616b3fa | |||
| 7802020982 | |||
| 2889fee300 | |||
| cb74c2b310 | |||
| d40d88d292 | |||
| 67719540ba | |||
| c604a8ff9c | |||
| 4ffe9dadbf | |||
| ed9820e6a6 | |||
| 5463a0c772 | |||
| 85214b308a | |||
| cfb9f85c90 | |||
| 635351f539 | |||
| 5c0849e82b | |||
| 54b3e0cc21 | |||
| d3404996fd | |||
| b0860467d5 | |||
| a075732cb4 | |||
| fc09e2307a | |||
| 43048626a6 | |||
| 15192c433b | |||
| 1fd4e084b6 | |||
| 29bf03b770 | |||
| 0ac883ea62 | |||
| 87d2c2894b | |||
| 399a3d7907 | |||
| d14a517fdc | |||
| 2e6fe73939 | |||
| b8659d0a9a | |||
| f9dd9297b8 | |||
| 3ffba4ac6c | |||
| 7b9cc0ba40 | |||
| 26c9b367a5 | |||
| 5f48bfda12 | |||
| 67d08b69c2 | |||
| ae190663f0 | |||
| de1c1de1ab | |||
| edb74f1223 | |||
| df17f5791a | |||
| da350cb1cb | |||
| e395b6e4ed | |||
| dbdb60cd98 | |||
| f9c5321ac1 | |||
| dd85c25997 | |||
| 3b195704bf | |||
| 9a22d7eeec | |||
| de6673c91a |
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": ["Bash(go build:*)"]
|
||||||
|
},
|
||||||
|
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||||
|
"promptCacheTtl": "1h"
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Loaded by npm run dev. Override locally in .env.development.local.
|
||||||
|
# Public configuration only; VITE_* values are exposed to the browser.
|
||||||
|
VITE_REACT_APP_SERVER_URL=
|
||||||
|
VITE_CLOUD_BRAIN_UI_ENABLED=true
|
||||||
|
|
||||||
|
# Vite development proxy only. Keep the browser URL empty to use this proxy.
|
||||||
|
DEV_PROXY_TARGET=http://134.175.227.134:13000
|
||||||
|
|
||||||
|
# Optional analytics. Empty IDs disable script injection.
|
||||||
|
VITE_UMAMI_WEBSITE_ID=
|
||||||
|
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
|
||||||
|
VITE_GOOGLE_ANALYTICS_ID=
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# Frontend build-time feature flags. Rebuild the frontend after changing them.
|
|
||||||
# Missing or false keeps the Cloud Brain suite hidden and blocks direct routes.
|
|
||||||
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
UI_ORG_NAME=测试企业1
|
||||||
|
UI_ORG_USER=test111
|
||||||
|
UI_ORG_PASS=2uT7anlhzR5w
|
||||||
|
UI_PERSONAL_USER=test222
|
||||||
|
UI_PERSONAL_PASS=12345678
|
||||||
|
UI_VISUAL_OFFSCREEN=1
|
||||||
|
UI_ADMIN_USER=ltadmin
|
||||||
|
UI_ADMIN_PASS=DoWtIMTli7njHYQeCNaR
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Loaded by npm run build. Override locally in .env.production.local or in CI.
|
||||||
|
# Public configuration only; VITE_* values are exposed to the browser.
|
||||||
|
# Empty URL uses same-origin requests; configure your production reverse proxy.
|
||||||
|
# Set a backend root URL for cross-origin requests, then rebuild and redeploy.
|
||||||
|
VITE_REACT_APP_SERVER_URL=
|
||||||
|
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||||
|
|
||||||
|
# Optional analytics. Empty IDs disable script injection.
|
||||||
|
VITE_UMAMI_WEBSITE_ID=
|
||||||
|
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
|
||||||
|
VITE_GOOGLE_ANALYTICS_ID=
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: { browser: true, es2021: true, node: true },
|
|
||||||
parserOptions: {
|
|
||||||
ecmaVersion: 2022,
|
|
||||||
sourceType: 'module',
|
|
||||||
ecmaFeatures: { jsx: true },
|
|
||||||
},
|
|
||||||
settings: {
|
|
||||||
react: { version: 'detect' },
|
|
||||||
},
|
|
||||||
plugins: ['header', 'react-hooks', 'react', 'unused-imports'],
|
|
||||||
// src/docs 是随文档页一起服务的纯静态脚本(非 ES 模块、用 CDN 全局如 hljs),
|
|
||||||
// 不属于 React 应用的模块图,排除出 lint。
|
|
||||||
ignorePatterns: ['dist/**', 'node_modules/**', 'src/docs/**'],
|
|
||||||
overrides: [
|
|
||||||
{
|
|
||||||
files: ['**/*.{js,jsx}'],
|
|
||||||
rules: {
|
|
||||||
'header/header': [
|
|
||||||
2,
|
|
||||||
'block',
|
|
||||||
[
|
|
||||||
'',
|
|
||||||
'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',
|
|
||||||
'',
|
|
||||||
],
|
|
||||||
],
|
|
||||||
'no-multiple-empty-lines': ['error', { max: 1 }],
|
|
||||||
|
|
||||||
// ===== 防线:杜绝“用了未定义/未导入标识符”导致的运行时崩溃(本次线上事故根因)=====
|
|
||||||
// 让规则识别 JSX 中使用到的组件/React,避免误报。
|
|
||||||
'react/jsx-uses-vars': 'error',
|
|
||||||
'react/jsx-uses-react': 'error',
|
|
||||||
// 未定义标识符 = 直接报错(构建/CI 即拦截)。
|
|
||||||
'no-undef': 'error',
|
|
||||||
// 未使用的 import = error 且可 --fix 自动移除(含 JSX/副作用识别);
|
|
||||||
// 未使用的变量 = warn(不阻断,下划线前缀豁免)。
|
|
||||||
'no-unused-vars': 'off',
|
|
||||||
'unused-imports/no-unused-imports': 'error',
|
|
||||||
'unused-imports/no-unused-vars': [
|
|
||||||
'warn',
|
|
||||||
{
|
|
||||||
vars: 'all',
|
|
||||||
varsIgnorePattern: '^_',
|
|
||||||
args: 'none',
|
|
||||||
argsIgnorePattern: '^_',
|
|
||||||
ignoreRestSiblings: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
// React Hooks 规则。
|
|
||||||
'react-hooks/rules-of-hooks': 'error',
|
|
||||||
'react-hooks/exhaustive-deps': 'warn',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -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
|
||||||
+45
-6
@@ -1,29 +1,68 @@
|
|||||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
# dependencies
|
# dependencies
|
||||||
/node_modules
|
node_modules/
|
||||||
/.pnp
|
/.pnp
|
||||||
.pnp.js
|
.pnp.js
|
||||||
|
bun.lock
|
||||||
|
bun.lockb
|
||||||
|
|
||||||
# testing
|
# testing
|
||||||
/coverage
|
/coverage
|
||||||
|
/.nyc_output/
|
||||||
|
*.lcov
|
||||||
|
|
||||||
|
# Local acceptance tests, browser sessions, and reports
|
||||||
|
/e2e/
|
||||||
|
/.e2e/
|
||||||
|
/tests/
|
||||||
|
/playwright/.auth/
|
||||||
|
/playwright-report/
|
||||||
|
/test-results/
|
||||||
|
/blob-report/
|
||||||
|
/report/
|
||||||
|
/scripts/seed-demo-requests.mjs
|
||||||
|
|
||||||
# production
|
# production
|
||||||
/build
|
/build
|
||||||
|
/dist/
|
||||||
|
/dist-ssr/
|
||||||
|
vercel.json
|
||||||
|
|
||||||
|
# tool caches and temporary files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
.claude/settings.local.json
|
||||||
|
.vite/
|
||||||
|
.cache/
|
||||||
|
.eslintcache
|
||||||
|
.stylelintcache
|
||||||
|
*.tsbuildinfo
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
*.log.*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
# misc
|
# misc
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.env.local
|
Thumbs.db
|
||||||
.env.development.local
|
Desktop.ini
|
||||||
.env.test.local
|
|
||||||
.env.production.local
|
|
||||||
|
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
.idea
|
.idea
|
||||||
package-lock.json
|
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
|
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
|
||||||
scripts/kt_batches/
|
scripts/kt_batches/
|
||||||
scripts/kt_out/
|
scripts/kt_out/
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated build output and tool caches are not source files.
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
dist-ssr/
|
||||||
|
build/
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
.vite/
|
||||||
|
.cache/
|
||||||
|
|
||||||
|
# Generated browser evidence is not source code.
|
||||||
|
logs/
|
||||||
|
report/
|
||||||
|
playwright-report/
|
||||||
|
test-results/
|
||||||
|
blob-report/
|
||||||
|
playwright/.auth/
|
||||||
|
e2e/*-snapshots/
|
||||||
+12
-1
@@ -1 +1,12 @@
|
|||||||
module.exports = require('@so1ve/prettier-config');
|
export default {
|
||||||
|
singleQuote: true,
|
||||||
|
jsxSingleQuote: true,
|
||||||
|
overrides: [
|
||||||
|
{
|
||||||
|
// 规范文档使用紧凑表格(不按列宽补空格),减少体积与 AI 代理读取的 token。
|
||||||
|
// 路径以 ./ 开头只匹配仓库根目录文件,不影响 src/ 下的 README。
|
||||||
|
files: ['./AGENTS.md', './CLAUDE.md', './README.md', 'docs/**/*.md'],
|
||||||
|
options: { proseWrap: 'never' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# 项目协作规范(AGENTS.md · Codex 默认入口)
|
||||||
|
|
||||||
|
> 第 0–9 节为公共规则,第 10 节保留工具差异。
|
||||||
|
|
||||||
|
## 0. 最高优先级:资源、扫描、Git、安全与授权(不得删减或弱化)
|
||||||
|
|
||||||
|
1. **扫描排除**:文件枚举、全文搜索、递归扫描默认排除 `node_modules`、`.git`、`dist`、`build`、`coverage`,以及生成目录 `report`、`logs`、`test-results`、`playwright-report`、`blob-report`、`.vite`、`.cache`。
|
||||||
|
2. **定向优先**:先搜索与任务相关的源码、配置、`package.json`、`package-lock.json`,搜索时限定目录(如 `src/`、`docs/`);不做无目的全项目扫描。
|
||||||
|
3. **依赖定向读**:确认依赖版本、类型定义、组件实现或兼容性时,只读 `node_modules/<包>/package.json` 或具体文件,禁止扫描整个 `node_modules`。
|
||||||
|
4. **Git 边界**:正常使用 `git status`、`git diff`、`git log`;仅在排查 Git 本身问题时查看 `.git` 内部文件。只在用户要求时 commit / push。
|
||||||
|
5. **不妨碍必要操作**:上述限制不影响依赖安装、升级、构建、测试等必要操作。
|
||||||
|
6. **读取量控制**:大文件或批量文件先摘要后细节,定向、分段读取(单次约 300 行内);并发读取文件数不超过 4;控制单次输出量。
|
||||||
|
7. **范围与敏感信息**:禁止扫描项目根目录之外的无关目录、用户目录、磁盘根目录或其他仓库;不读取无关敏感文件;不输出 `.env*`、密钥、令牌、密码、Cookie、storageState 的值,确需确认配置时只列键名和用途。
|
||||||
|
8. **不阻塞**:默认连续执行只读分析和非破坏性产出;关键路径缺失、权限不足、破坏性操作或高风险删除列入“待确认项”,继续完成可执行部分,不编造。
|
||||||
|
9. **破坏性操作**:删除、覆盖、重命名文件必须有依据、清单、影响说明和回滚方案;默认先输出清单不执行,获得明确授权后按清单操作并记录结果。
|
||||||
|
10. **授权边界**:文档类授权只覆盖只读分析、规范 / PRD / 文档产出和治理清单;不覆盖未经清单确认的删除、覆盖、重命名,也不覆盖业务代码修改。业务代码只在用户任务或 PRD 明确要求时修改。
|
||||||
|
11. **资源与并发**:执行中关注内存与 CPU,避免 OOM;浏览器、构建、全量测试串行;启动前可用物理内存 ≥ 2GB、可用提交 ≥ 2.5GB,运行中低于 700MB 立即停止本任务进程;不结束他人进程。
|
||||||
|
|
||||||
|
## 1. 按需加载
|
||||||
|
|
||||||
|
- 已由会话加载的入口不再重读;不为获取公共规则再加载另一入口。细节按第 6 节索引直达目标文档摘要卡、目标章节与相关源码,不复制 `docs/` 全文。
|
||||||
|
- 仅首次接手、不确定规范归属或维护文档目录时读 `docs/README.md`;已定位目标时不重复经过索引。
|
||||||
|
- 记录已读路径与章节;未变内容不重读,文件变化只补读相关差异。上下文压缩 / 交接时保留目标、授权边界、已读索引、已改文件、验证结果与待办,恢复后定向续作。
|
||||||
|
- 保持标题、章节顺序与措辞稳定,局部修改;版本与日期只在第 9 节维护。任务状态、临时地址、日志和验证报告写入忽略目录,不追加到入口前缀。
|
||||||
|
- 所有面向用户的说明、提问与交付使用简体中文;代码、命令、路径与报错保持原样并按需解释,引用用路径与行号,不粘贴大段原文。
|
||||||
|
|
||||||
|
## 2. 项目速览
|
||||||
|
|
||||||
|
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
||||||
|
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
||||||
|
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发服务按全局基线第 7.1 节结合项目目录、启动日志和监听进程发现,优先复用已有服务。
|
||||||
|
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
||||||
|
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
||||||
|
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
||||||
|
- **主题**:唯一入口 `src/components/ui/UiThemeProvider.jsx`;`src/components/ui/*` 是存量页面的契约封装层。
|
||||||
|
|
||||||
|
| 命令 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm ci` | 按 lock 安装依赖;会重建 `node_modules`,已有可用依赖时无需为文档检查重装 |
|
||||||
|
| `npm run dev` | 开发服务;脚本不自动写日志,启动方须按基线第 6 节将输出写入 `dev.log` |
|
||||||
|
| `npm run eslint` / `npm run lint` | ESLint(零警告)/ Prettier 检查 |
|
||||||
|
| `npm test -- --test-concurrency=1` | 串行单测(`src/`、`tests/`、`test/unit/`) |
|
||||||
|
| `npm run check:ui` | UI 依赖、lock 图、品牌图标 hash 审计 |
|
||||||
|
| `npm run test:e2e -- --list` / `npm run test:e2e` | 配置与用例发现 / Playwright 执行;用例在本地忽略目录 `e2e/`,执行前见第 7 节 |
|
||||||
|
| `npm run i18n:status` / `npm run i18n:lint` | 语言包检查 |
|
||||||
|
| `npm run build` | 生产构建(验收构建见第 7 节) |
|
||||||
|
| `npm run check` | 依次执行 UI 审计、ESLint、串行单测、构建;不含 Prettier,默认写入 `dist/`,不能替代临时目录验收流程 |
|
||||||
|
|
||||||
|
Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd` / `npx.cmd` 避免执行策略拦截,不修改安全设置。
|
||||||
|
|
||||||
|
## 3. 规则优先级
|
||||||
|
|
||||||
|
用户当前指令 > 本文件第 0 节 > 页面规范 `docs/ui/*_SPEC.md`(限其范围)> `docs/ui/GLOBAL_UI_BASELINE.md` > `docs/standards/UI_COMPONENT_STANDARDS.md` > `docs/standards/DEV_STANDARDS.md` > Ant Design 默认行为。同级冲突取“最后更新”较新者,并在同一次改动中修订两处。`docs/CHANGELOG.md` 只记录历史,不作为规则依据。
|
||||||
|
|
||||||
|
## 4. 开发约束(细节见 `docs/standards/DEV_STANDARDS.md`)
|
||||||
|
|
||||||
|
- **任务边界**:纯 UI 任务不新增功能,不改请求、载荷、状态、路由、权限、计费、登录与业务触发条件;非阻塞 Bug 只记风险。改前先读相关代码,保留用户已有修改。
|
||||||
|
- **组件**:通用 UI 只用 `antd`,新代码用原生 API;存量页面经 `@/components/ui` 保留旧契约(适配 Modal / SideSheet 用 `visible` + `onCancel`,适配 Input 的 `onChange` 收值);分页列表统一用适配层 `Table`。
|
||||||
|
- **外壳**:控制台用 `ConsolePrimitives`;企业中心用 `OrgPageHeader` / `OrgFilterCard` / `OrgListCard` / `OrgModal` / `OrgSideSheet`;用户中心用 `UserCenterPageHeader` + `.uc-page`。
|
||||||
|
- **样式**:不新增 ConfigProvider、主题状态或存储 key;颜色只来自 token 或页面变量,JSX 不写十六进制,不用全局 `!important`。
|
||||||
|
- **图标与依赖**:按钮图标从 `src/components/common/icons/ActionIcons.js` 导入,装饰图标用 `lucide-react`;禁止引入 Semi、Radix UI、Floating UI、`@lobehub/*`、MUI、Chakra、Headless UI、leva、antd-style、react-layout-kit。
|
||||||
|
- **请求**:只用 `API`,参数用 `params`,先判 `success`;分页 `p` 从 1 开始、`page_size` ≤ 100;`catch` 不重复提示 AxiosError;`finally` 回收 loading。
|
||||||
|
- **命名与文件**:状态用 `items`、`total`、`page`、`pageSize`、`loading`、`submitting`、`editingRecord`、`drawerOpen`;不重复添加通用长版权文件头;入库单测放 `test/unit/`;新文案用 `t('中文原文')` 并补齐 9 个语言包。
|
||||||
|
- **可访问性**:交互元素可键盘操作且焦点可见;纯图标按钮加 `aria-label`;状态不只靠颜色表达;动效遵守 `prefers-reduced-motion`。
|
||||||
|
|
||||||
|
## 5. 目录规则
|
||||||
|
|
||||||
|
| 路径 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| `src/hooks`、`src/context`、`src/helpers/api*`、`src/services`、`src/App.jsx` | 业务数据流与路由,UI 任务不改语义 |
|
||||||
|
| `src/components/ui/` | 契约封装层,只做视图映射,不放请求、权限、业务状态 |
|
||||||
|
| `src/components/console/` | 控制台外壳与原语;新页面登记 `consoleRoutes.js` |
|
||||||
|
| `src/pages/Organization/` | 企业中心;新页面登记 `OrgBreadcrumb` 的 `orgPageGroups` |
|
||||||
|
| `src/pages/{UserCenter,KeyManagement,ServiceDashboard,Recharge}/` | 用户中心;新页面登记 `UserCenterBreadcrumb` 的 `pageTitles` |
|
||||||
|
| `src/styles/`、页面 CSS | 页面作用域;颜色只写在变量定义中,深色写在 `html.dark` |
|
||||||
|
| `src/assets/brand-icons/` | 脚本生成,禁止手改(`npm run vendor:icons` + `npm run check:ui`) |
|
||||||
|
| `src/i18n/locales/` | 9 个语言包同步更新 |
|
||||||
|
| `e2e/`、`report/`、`logs/`、`test-results/`、`playwright-report/` | 本地验收与证据,Git 忽略,不提交、不全量扫描 |
|
||||||
|
|
||||||
|
## 6. 规范索引(按任务读取)
|
||||||
|
|
||||||
|
| 任务 | 先读 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新增或重构 CRUD、请求、状态、权限、i18n | `docs/standards/DEV_STANDARDS.md` |
|
||||||
|
| 主题变量与组件样式(卡片、筛选栏、表格、分页、表单、弹窗、抽屉、页签、标签、按钮、图标、可访问性) | `docs/standards/UI_COMPONENT_STANDARDS.md` |
|
||||||
|
| 外壳(顶栏、侧栏、公告、页头、登录页)、页面布局、UI 验收 | `docs/ui/GLOBAL_UI_BASELINE.md` |
|
||||||
|
| 用户中心:看板、使用记录、充值、个人设置 | `docs/ui/USER_CENTER_SPEC.md` |
|
||||||
|
| 密钥管理 / 服务监控 | `docs/ui/KEY_MANAGEMENT_SPEC.md` / `docs/ui/SERVICE_DASHBOARD_SPEC.md` |
|
||||||
|
| 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` |
|
||||||
|
| 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` |
|
||||||
|
| 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` |
|
||||||
|
| UI 审查清单 | `docs/ui-review-checklist.md` |
|
||||||
|
| 历史改动与回滚 | `docs/CHANGELOG.md` |
|
||||||
|
| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 |
|
||||||
|
|
||||||
|
无需读文档即可遵守的长期状态:
|
||||||
|
|
||||||
|
- 技能超市默认真实接口(`LiveSkillMarket.jsx`),仅 `VITE_SKILL_MARKET_MOCK=true` 进入演示;收到“恢复成真实 api 请求”类指令时只核验状态。
|
||||||
|
- 密钥管理路由为 `/user-center/key-management`,旧 `/key-management` 重定向。
|
||||||
|
- 暗色主色 `#d1963a`(由种子 `#f2ad41` 推导),侧栏选中项保留 `#f2ad41`。
|
||||||
|
- 带侧栏页面:内容边距桌面 30 / 36 / 36px、移动 16 / 16 / 24px;面包屑距顶 30px、与标题 24px;标题 28 / 32px / 650。
|
||||||
|
|
||||||
|
## 7. 开发、验收与交付
|
||||||
|
|
||||||
|
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
||||||
|
2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。
|
||||||
|
3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851 与 360×800(最小必测视口);正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。
|
||||||
|
4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。
|
||||||
|
5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。
|
||||||
|
6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。
|
||||||
|
|
||||||
|
## 8. 禁止事项
|
||||||
|
|
||||||
|
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
||||||
|
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
||||||
|
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
||||||
|
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git(仅 `.env.playwright.local` 中的测试账号按用户约定允许入库);本地脱敏报告按第 7 节交付。
|
||||||
|
|
||||||
|
## 9. 维护
|
||||||
|
|
||||||
|
- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致;标题与第 10 节分别维护,不整文件覆盖另一份。维护时执行开发规范第 12.4 节的一致性校验。
|
||||||
|
|
||||||
|
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
||||||
|
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
||||||
|
|
||||||
|
> 规范版本:v3.8 · 更新:2026-11-24
|
||||||
|
|
||||||
|
## 10. 工具差异(本节允许不同)
|
||||||
|
|
||||||
|
- 本文件供通用 Agent / Codex 使用;已加载时按第 1 节续作。
|
||||||
|
- 网页操作优先使用项目 Playwright;computer-use 不作为默认工具,失败排查见 UI 基线第 7.1 节。
|
||||||
|
- 代码检索优先 `rg` 并限定目录(如 `rg <词> src docs`),遵守第 0 节扫描边界。
|
||||||
|
- 按当前 Codex 会话实际提供的工具执行;沙箱、审批、技能和可用浏览器能力以运行环境为准,本文件不授予额外权限。遇到更深目录的 `AGENTS.md` 时,先读取适用范围内的补充约束。
|
||||||
|
- 仅在用户明确要求时使用子代理,并传递任务范围、第 0 节规则与验收要求。
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# 项目协作规范(CLAUDE.md · Claude Code 默认入口)
|
||||||
|
|
||||||
|
> 第 0–9 节为公共规则,第 10 节保留工具差异。
|
||||||
|
|
||||||
|
## 0. 最高优先级:资源、扫描、Git、安全与授权(不得删减或弱化)
|
||||||
|
|
||||||
|
1. **扫描排除**:文件枚举、全文搜索、递归扫描默认排除 `node_modules`、`.git`、`dist`、`build`、`coverage`,以及生成目录 `report`、`logs`、`test-results`、`playwright-report`、`blob-report`、`.vite`、`.cache`。
|
||||||
|
2. **定向优先**:先搜索与任务相关的源码、配置、`package.json`、`package-lock.json`,搜索时限定目录(如 `src/`、`docs/`);不做无目的全项目扫描。
|
||||||
|
3. **依赖定向读**:确认依赖版本、类型定义、组件实现或兼容性时,只读 `node_modules/<包>/package.json` 或具体文件,禁止扫描整个 `node_modules`。
|
||||||
|
4. **Git 边界**:正常使用 `git status`、`git diff`、`git log`;仅在排查 Git 本身问题时查看 `.git` 内部文件。只在用户要求时 commit / push。
|
||||||
|
5. **不妨碍必要操作**:上述限制不影响依赖安装、升级、构建、测试等必要操作。
|
||||||
|
6. **读取量控制**:大文件或批量文件先摘要后细节,定向、分段读取(单次约 300 行内);并发读取文件数不超过 4;控制单次输出量。
|
||||||
|
7. **范围与敏感信息**:禁止扫描项目根目录之外的无关目录、用户目录、磁盘根目录或其他仓库;不读取无关敏感文件;不输出 `.env*`、密钥、令牌、密码、Cookie、storageState 的值,确需确认配置时只列键名和用途。
|
||||||
|
8. **不阻塞**:默认连续执行只读分析和非破坏性产出;关键路径缺失、权限不足、破坏性操作或高风险删除列入“待确认项”,继续完成可执行部分,不编造。
|
||||||
|
9. **破坏性操作**:删除、覆盖、重命名文件必须有依据、清单、影响说明和回滚方案;默认先输出清单不执行,获得明确授权后按清单操作并记录结果。
|
||||||
|
10. **授权边界**:文档类授权只覆盖只读分析、规范 / PRD / 文档产出和治理清单;不覆盖未经清单确认的删除、覆盖、重命名,也不覆盖业务代码修改。业务代码只在用户任务或 PRD 明确要求时修改。
|
||||||
|
11. **资源与并发**:执行中关注内存与 CPU,避免 OOM;浏览器、构建、全量测试串行;启动前可用物理内存 ≥ 2GB、可用提交 ≥ 2.5GB,运行中低于 700MB 立即停止本任务进程;不结束他人进程。
|
||||||
|
|
||||||
|
## 1. 按需加载
|
||||||
|
|
||||||
|
- 已由会话加载的入口不再重读;不为获取公共规则再加载另一入口。细节按第 6 节索引直达目标文档摘要卡、目标章节与相关源码,不复制 `docs/` 全文。
|
||||||
|
- 仅首次接手、不确定规范归属或维护文档目录时读 `docs/README.md`;已定位目标时不重复经过索引。
|
||||||
|
- 记录已读路径与章节;未变内容不重读,文件变化只补读相关差异。上下文压缩 / 交接时保留目标、授权边界、已读索引、已改文件、验证结果与待办,恢复后定向续作。
|
||||||
|
- 保持标题、章节顺序与措辞稳定,局部修改;版本与日期只在第 9 节维护。任务状态、临时地址、日志和验证报告写入忽略目录,不追加到入口前缀。
|
||||||
|
- 所有面向用户的说明、提问与交付使用简体中文;代码、命令、路径与报错保持原样并按需解释,引用用路径与行号,不粘贴大段原文。
|
||||||
|
|
||||||
|
## 2. 项目速览
|
||||||
|
|
||||||
|
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
||||||
|
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
||||||
|
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发服务按全局基线第 7.1 节结合项目目录、启动日志和监听进程发现,优先复用已有服务。
|
||||||
|
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
||||||
|
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
||||||
|
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
||||||
|
- **主题**:唯一入口 `src/components/ui/UiThemeProvider.jsx`;`src/components/ui/*` 是存量页面的契约封装层。
|
||||||
|
|
||||||
|
| 命令 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm ci` | 按 lock 安装依赖;会重建 `node_modules`,已有可用依赖时无需为文档检查重装 |
|
||||||
|
| `npm run dev` | 开发服务;脚本不自动写日志,启动方须按基线第 6 节将输出写入 `dev.log` |
|
||||||
|
| `npm run eslint` / `npm run lint` | ESLint(零警告)/ Prettier 检查 |
|
||||||
|
| `npm test -- --test-concurrency=1` | 串行单测(`src/`、`tests/`、`test/unit/`) |
|
||||||
|
| `npm run check:ui` | UI 依赖、lock 图、品牌图标 hash 审计 |
|
||||||
|
| `npm run test:e2e -- --list` / `npm run test:e2e` | 配置与用例发现 / Playwright 执行;用例在本地忽略目录 `e2e/`,执行前见第 7 节 |
|
||||||
|
| `npm run i18n:status` / `npm run i18n:lint` | 语言包检查 |
|
||||||
|
| `npm run build` | 生产构建(验收构建见第 7 节) |
|
||||||
|
| `npm run check` | 依次执行 UI 审计、ESLint、串行单测、构建;不含 Prettier,默认写入 `dist/`,不能替代临时目录验收流程 |
|
||||||
|
|
||||||
|
Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd` / `npx.cmd` 避免执行策略拦截,不修改安全设置。
|
||||||
|
|
||||||
|
## 3. 规则优先级
|
||||||
|
|
||||||
|
用户当前指令 > 本文件第 0 节 > 页面规范 `docs/ui/*_SPEC.md`(限其范围)> `docs/ui/GLOBAL_UI_BASELINE.md` > `docs/standards/UI_COMPONENT_STANDARDS.md` > `docs/standards/DEV_STANDARDS.md` > Ant Design 默认行为。同级冲突取“最后更新”较新者,并在同一次改动中修订两处。`docs/CHANGELOG.md` 只记录历史,不作为规则依据。
|
||||||
|
|
||||||
|
## 4. 开发约束(细节见 `docs/standards/DEV_STANDARDS.md`)
|
||||||
|
|
||||||
|
- **任务边界**:纯 UI 任务不新增功能,不改请求、载荷、状态、路由、权限、计费、登录与业务触发条件;非阻塞 Bug 只记风险。改前先读相关代码,保留用户已有修改。
|
||||||
|
- **组件**:通用 UI 只用 `antd`,新代码用原生 API;存量页面经 `@/components/ui` 保留旧契约(适配 Modal / SideSheet 用 `visible` + `onCancel`,适配 Input 的 `onChange` 收值);分页列表统一用适配层 `Table`。
|
||||||
|
- **外壳**:控制台用 `ConsolePrimitives`;企业中心用 `OrgPageHeader` / `OrgFilterCard` / `OrgListCard` / `OrgModal` / `OrgSideSheet`;用户中心用 `UserCenterPageHeader` + `.uc-page`。
|
||||||
|
- **样式**:不新增 ConfigProvider、主题状态或存储 key;颜色只来自 token 或页面变量,JSX 不写十六进制,不用全局 `!important`。
|
||||||
|
- **图标与依赖**:按钮图标从 `src/components/common/icons/ActionIcons.js` 导入,装饰图标用 `lucide-react`;禁止引入 Semi、Radix UI、Floating UI、`@lobehub/*`、MUI、Chakra、Headless UI、leva、antd-style、react-layout-kit。
|
||||||
|
- **请求**:只用 `API`,参数用 `params`,先判 `success`;分页 `p` 从 1 开始、`page_size` ≤ 100;`catch` 不重复提示 AxiosError;`finally` 回收 loading。
|
||||||
|
- **命名与文件**:状态用 `items`、`total`、`page`、`pageSize`、`loading`、`submitting`、`editingRecord`、`drawerOpen`;不重复添加通用长版权文件头;入库单测放 `test/unit/`;新文案用 `t('中文原文')` 并补齐 9 个语言包。
|
||||||
|
- **可访问性**:交互元素可键盘操作且焦点可见;纯图标按钮加 `aria-label`;状态不只靠颜色表达;动效遵守 `prefers-reduced-motion`。
|
||||||
|
|
||||||
|
## 5. 目录规则
|
||||||
|
|
||||||
|
| 路径 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| `src/hooks`、`src/context`、`src/helpers/api*`、`src/services`、`src/App.jsx` | 业务数据流与路由,UI 任务不改语义 |
|
||||||
|
| `src/components/ui/` | 契约封装层,只做视图映射,不放请求、权限、业务状态 |
|
||||||
|
| `src/components/console/` | 控制台外壳与原语;新页面登记 `consoleRoutes.js` |
|
||||||
|
| `src/pages/Organization/` | 企业中心;新页面登记 `OrgBreadcrumb` 的 `orgPageGroups` |
|
||||||
|
| `src/pages/{UserCenter,KeyManagement,ServiceDashboard,Recharge}/` | 用户中心;新页面登记 `UserCenterBreadcrumb` 的 `pageTitles` |
|
||||||
|
| `src/styles/`、页面 CSS | 页面作用域;颜色只写在变量定义中,深色写在 `html.dark` |
|
||||||
|
| `src/assets/brand-icons/` | 脚本生成,禁止手改(`npm run vendor:icons` + `npm run check:ui`) |
|
||||||
|
| `src/i18n/locales/` | 9 个语言包同步更新 |
|
||||||
|
| `e2e/`、`report/`、`logs/`、`test-results/`、`playwright-report/` | 本地验收与证据,Git 忽略,不提交、不全量扫描 |
|
||||||
|
|
||||||
|
## 6. 规范索引(按任务读取)
|
||||||
|
|
||||||
|
| 任务 | 先读 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新增或重构 CRUD、请求、状态、权限、i18n | `docs/standards/DEV_STANDARDS.md` |
|
||||||
|
| 主题变量与组件样式(卡片、筛选栏、表格、分页、表单、弹窗、抽屉、页签、标签、按钮、图标、可访问性) | `docs/standards/UI_COMPONENT_STANDARDS.md` |
|
||||||
|
| 外壳(顶栏、侧栏、公告、页头、登录页)、页面布局、UI 验收 | `docs/ui/GLOBAL_UI_BASELINE.md` |
|
||||||
|
| 用户中心:看板、使用记录、充值、个人设置 | `docs/ui/USER_CENTER_SPEC.md` |
|
||||||
|
| 密钥管理 / 服务监控 | `docs/ui/KEY_MANAGEMENT_SPEC.md` / `docs/ui/SERVICE_DASHBOARD_SPEC.md` |
|
||||||
|
| 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` |
|
||||||
|
| 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` |
|
||||||
|
| 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` |
|
||||||
|
| UI 审查清单 | `docs/ui-review-checklist.md` |
|
||||||
|
| 历史改动与回滚 | `docs/CHANGELOG.md` |
|
||||||
|
| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 |
|
||||||
|
|
||||||
|
无需读文档即可遵守的长期状态:
|
||||||
|
|
||||||
|
- 技能超市默认真实接口(`LiveSkillMarket.jsx`),仅 `VITE_SKILL_MARKET_MOCK=true` 进入演示;收到“恢复成真实 api 请求”类指令时只核验状态。
|
||||||
|
- 密钥管理路由为 `/user-center/key-management`,旧 `/key-management` 重定向。
|
||||||
|
- 暗色主色 `#d1963a`(由种子 `#f2ad41` 推导),侧栏选中项保留 `#f2ad41`。
|
||||||
|
- 带侧栏页面:内容边距桌面 30 / 36 / 36px、移动 16 / 16 / 24px;面包屑距顶 30px、与标题 24px;标题 28 / 32px / 650。
|
||||||
|
|
||||||
|
## 7. 开发、验收与交付
|
||||||
|
|
||||||
|
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
||||||
|
2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。
|
||||||
|
3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851 与 360×800(最小必测视口);正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。
|
||||||
|
4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。
|
||||||
|
5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。
|
||||||
|
6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。
|
||||||
|
|
||||||
|
## 8. 禁止事项
|
||||||
|
|
||||||
|
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
||||||
|
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
||||||
|
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
||||||
|
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git(仅 `.env.playwright.local` 中的测试账号按用户约定允许入库);本地脱敏报告按第 7 节交付。
|
||||||
|
|
||||||
|
## 9. 维护
|
||||||
|
|
||||||
|
- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致;标题与第 10 节分别维护,不整文件覆盖另一份。维护时执行开发规范第 12.4 节的一致性校验。
|
||||||
|
|
||||||
|
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
||||||
|
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
||||||
|
|
||||||
|
> 规范版本:v3.8 · 更新:2026-11-24
|
||||||
|
|
||||||
|
## 10. 工具差异(本节允许不同)
|
||||||
|
|
||||||
|
- 本文件是 Claude Code 项目记忆入口;已加载时按第 1 节续作,进入子目录时留意适用的 `CLAUDE.md`。
|
||||||
|
- 文件检索优先 Glob / Grep 并限定路径,用 Read 分段读取;Bash 同样遵守第 0 节扫描边界。
|
||||||
|
- 用户级记忆、项目 / 本地设置、权限、hooks、MCP 与技能以当前 Claude Code 实际加载项为准;不假定他人机器存在相同的 `~/.claude/CLAUDE.md` 或插件,不把本机授权写成团队默认权限,不提交本地凭据或放宽权限来绕过失败。
|
||||||
|
- 子代理与工作流只在用户明确要求时使用;委派时传递任务范围、第 0 节规则与验收要求。
|
||||||
@@ -1,228 +0,0 @@
|
|||||||
# 前端性能优化报告 - Weelink Monkey AI
|
|
||||||
|
|
||||||
## ✅ 已完成的性能优化 (2026-02-12 更新)
|
|
||||||
|
|
||||||
### 🎉 主要成就
|
|
||||||
|
|
||||||
#### 1. **react-icons (83MB) - ✅ 已完全移除**
|
|
||||||
|
|
||||||
- **优化方案**: 创建自定义内联 SVG 图标组件 ([BrandIcons.jsx](src/components/common/icons/BrandIcons.jsx))
|
|
||||||
- **替换的文件**: 全部7个文件已完成替换
|
|
||||||
- ✅ `components/settings/personal/sections/AccountBindingSection.jsx`
|
|
||||||
- ✅ `components/topup/modals/PaymentConfirmModal.jsx`
|
|
||||||
- ✅ `pages/Recharge/RechargePanel.jsx`
|
|
||||||
- ✅ `components/topup/RechargeCard.jsx`
|
|
||||||
- ✅ `components/table/channels/ChannelsColumnDefs.jsx`
|
|
||||||
- ✅ `components/settings/personal/cards/AccountManagement.jsx`
|
|
||||||
- ✅ `components/settings/personal/modals/WeChatBindModal.jsx`
|
|
||||||
- **从 package.json 移除**: ✅ 完成
|
|
||||||
- **节省空间**: **~83MB → 0MB** (100% 优化)
|
|
||||||
- **实际效果**: 构建产物减少约 2-3MB (gzip后)
|
|
||||||
|
|
||||||
#### 2. **@lobehub/icons - 保留使用**
|
|
||||||
|
|
||||||
- **使用文件**: 2个
|
|
||||||
- `pages/Home/index.jsx`
|
|
||||||
- `helpers/render.jsx`
|
|
||||||
- **原因**: 这些是 AI 模型品牌图标(OpenAI, Claude, Gemini等),是项目核心功能
|
|
||||||
- **优化**: 通过 tree-shaking 和具名导入已优化加载
|
|
||||||
- **实际打包**: ~5MB → ~500KB (通过 tree-shaking)
|
|
||||||
|
|
||||||
### 🟡 现有依赖(已优化)
|
|
||||||
|
|
||||||
#### 3. **lucide-react**
|
|
||||||
|
|
||||||
- **状态**: ✅ 正在使用,已通过 tree-shaking 优化
|
|
||||||
- **导入方式**: 具名导入确保仅打包使用的图标
|
|
||||||
- **用途**: 通用 UI 图标 (替代了大部分 react-icons)
|
|
||||||
- **实际打包**: ~40MB → ~50-100KB (通过 tree-shaking)
|
|
||||||
|
|
||||||
#### 4. **mermaid (图表库)**
|
|
||||||
|
|
||||||
- **状态**: ✅ 已懒加载
|
|
||||||
- **文件**: `components/common/markdown/MarkdownRenderer.jsx`
|
|
||||||
- **优化**: 仅在需要时动态加载
|
|
||||||
|
|
||||||
#### 5. **katex (数学公式渲染)**
|
|
||||||
|
|
||||||
- **状态**: ✅ 已通过 Vite chunk 分离
|
|
||||||
- **优化**: 独立chunk,按需加载
|
|
||||||
|
|
||||||
#### 6. **@visactor (图表可视化)**
|
|
||||||
|
|
||||||
- **状态**: ✅ 已通过 Vite chunk 分离
|
|
||||||
- **包含**: react-vchart, vchart, vchart-semi-theme
|
|
||||||
- **优化**: 独立chunk,按需加载
|
|
||||||
|
|
||||||
### 🎯 新增优化项
|
|
||||||
|
|
||||||
✅ **Vite 构建配置优化**
|
|
||||||
|
|
||||||
- 启用 esbuild 压缩
|
|
||||||
- 移除生产环境的 console 和 debugger
|
|
||||||
- 优化 tree-shaking 配置
|
|
||||||
- 细粒度的代码分割 (12+ chunks)
|
|
||||||
- Target ES2015 减少polyfill
|
|
||||||
|
|
||||||
✅ **已完成的优化项目**
|
|
||||||
|
|
||||||
- Google Fonts 依赖已移除
|
|
||||||
- Telegram 登录组件已懒加载
|
|
||||||
- MapleBackground 动画已优化
|
|
||||||
- 首屏 loading 动画已优化
|
|
||||||
- Mermaid 已懒加载
|
|
||||||
- **react-icons 已完全移除** ⭐ NEW
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📊 优化前后对比
|
|
||||||
|
|
||||||
| 库名 | 优化前 | 优化后 | 节省 | 状态 |
|
|
||||||
| -------------- | ---------- | --------------------- | ----------- | ------------- |
|
|
||||||
| react-icons | 83MB | 0MB | **-83MB** | ✅ **已移除** |
|
|
||||||
| lucide-react | 40MB | ~100KB (tree-shaking) | **-39.9MB** | ✅ **已优化** |
|
|
||||||
| @lobehub/icons | 5MB | ~500KB (tree-shaking) | **-4.5MB** | ✅ **已优化** |
|
|
||||||
| @visactor | 10MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
|
||||||
| mermaid | 3MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
|
||||||
| katex | 2MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
|
||||||
| **依赖总计** | **~143MB** | **~600KB + 懒加载** | **~99% ⬇️** | ✅ **完成** |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🎯 优化技术细节
|
|
||||||
|
|
||||||
### ✅ 已实施的优化
|
|
||||||
|
|
||||||
1. **移除 react-icons (83MB)**
|
|
||||||
- 创建自定义 SVG 组件库 `BrandIcons.jsx`
|
|
||||||
- 包含品牌图标: Wechat, Alipay, Stripe, Telegram, Discord, Linux, Shuffle
|
|
||||||
- 所有7个文件已完成迁移
|
|
||||||
- 从 package.json 移除依赖
|
|
||||||
|
|
||||||
2. **优化图标库使用**
|
|
||||||
- lucide-react: 使用具名导入 ✅
|
|
||||||
- @lobehub/icons: 保留(AI模型图标必需) ✅
|
|
||||||
- 自定义SVG: 零依赖,体积最小 ✅
|
|
||||||
|
|
||||||
3. **Vite 构建优化**
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// 压缩配置
|
|
||||||
- esbuild 压缩 (速度+体积优化)
|
|
||||||
- 移除 console/debugger
|
|
||||||
- tree-shaking 优化
|
|
||||||
|
|
||||||
// 代码分割 (12+ chunks)
|
|
||||||
- react-core
|
|
||||||
- semi-ui / semi-icons
|
|
||||||
- vchart (图表)
|
|
||||||
- mermaid (流程图)
|
|
||||||
- markdown / katex
|
|
||||||
- lobe-icons / lucide-icons
|
|
||||||
- i18n / utils
|
|
||||||
- react-components
|
|
||||||
```
|
|
||||||
|
|
||||||
### 📋 下一步可选优化
|
|
||||||
|
|
||||||
1. **CDN 加速 (可选)**
|
|
||||||
- 考虑使用国内CDN加速 Semi UI
|
|
||||||
- 使用CDN加速大型依赖(mermaid, vchart)
|
|
||||||
|
|
||||||
2. **图片优化 (可选)**
|
|
||||||
- WebP 格式转换
|
|
||||||
- 图片懒加载
|
|
||||||
- 响应式图片
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🚀 实际优化效果
|
|
||||||
|
|
||||||
### 打包体积对比
|
|
||||||
|
|
||||||
| 指标 | 优化前 | 优化后 | 提升 |
|
|
||||||
| --------------------- | ------ | ------- | ------------- |
|
|
||||||
| 初始JS依赖 | ~143MB | ~10MB\* | **93%** ⬇️ |
|
|
||||||
| 主chunk (预估) | ~2.5MB | ~800KB | **68%** ⬇️ |
|
|
||||||
| gzip 后 (预估) | ~8MB | ~2-3MB | **62-75%** ⬇️ |
|
|
||||||
| 首屏加载时间 (中国4G) | 4-8秒 | 1.5-3秒 | **50-75%** ⬇️ |
|
|
||||||
|
|
||||||
\*通过 tree-shaking + 代码分割 + 懒加载实现
|
|
||||||
|
|
||||||
### 📈 预期用户体验提升
|
|
||||||
|
|
||||||
| 场景 | 优化前 | 优化后 | 改善 |
|
|
||||||
| ------------- | --------- | ----------- | ---------- |
|
|
||||||
| 🇨🇳 中国4G网络 | 6-8秒白屏 | 2-3秒可交互 | ⭐⭐⭐⭐⭐ |
|
|
||||||
| 🌐 国际网络 | 3-5秒 | 1-2秒 | ⭐⭐⭐⭐ |
|
|
||||||
| 📱 移动端 | 较慢 | 流畅 | ⭐⭐⭐⭐⭐ |
|
|
||||||
| 🔄 页面切换 | 卡顿 | 即时响应 | ⭐⭐⭐⭐⭐ |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## ✅ 优化完成清单
|
|
||||||
|
|
||||||
### 🎉 已完成 (2026-02-12)
|
|
||||||
|
|
||||||
- [x] 移除 react-icons (83MB → 0MB)
|
|
||||||
- [x] 创建自定义 SVG 图标组件
|
|
||||||
- [x] 替换所有7个使用文件
|
|
||||||
- [x] 从 package.json 移除
|
|
||||||
- [x] 优化 Vite 构建配置
|
|
||||||
- [x] 启用 esbuild 压缩
|
|
||||||
- [x] 优化 tree-shaking
|
|
||||||
- [x] 细粒度代码分割 (12+ chunks)
|
|
||||||
- [x] 移除生产环境 console
|
|
||||||
- [x] 懒加载大型依赖
|
|
||||||
- [x] Telegram 登录组件
|
|
||||||
- [x] Mermaid 图表
|
|
||||||
- [x] @visactor 图表库
|
|
||||||
- [x] katex 数学公式
|
|
||||||
- [x] 优化图标库
|
|
||||||
- [x] lucide-react 具名导入
|
|
||||||
- [x] @lobehub/icons tree-shaking
|
|
||||||
|
|
||||||
### 📋 可选后续优化
|
|
||||||
|
|
||||||
- [ ] 配置 CDN 加速(Semi UI, 大型依赖)
|
|
||||||
- [ ] 图片优化 (WebP, 懒加载)
|
|
||||||
- [ ] 启用 Brotli 压缩
|
|
||||||
- [ ] 添加性能监控
|
|
||||||
|
|
||||||
### 🧪 验证步骤
|
|
||||||
|
|
||||||
运行以下命令验证优化效果:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd web
|
|
||||||
npm install # 安装依赖(已移除 react-icons)
|
|
||||||
npm run build # 构建生产版本
|
|
||||||
```
|
|
||||||
|
|
||||||
查看构建产物:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ls -lh dist/assets/ # 查看打包后的文件大小
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📝 变更记录
|
|
||||||
|
|
||||||
**2026-02-12 (本次优化)**
|
|
||||||
|
|
||||||
- ✅ 完全移除 react-icons (83MB)
|
|
||||||
- ✅ 创建自定义品牌图标组件
|
|
||||||
- ✅ 优化 Vite 构建配置
|
|
||||||
- ✅ 实现细粒度代码分割
|
|
||||||
- ✅ 优化图标库 tree-shaking
|
|
||||||
|
|
||||||
**预期收益**:
|
|
||||||
|
|
||||||
- 依赖体积减少 ~93%
|
|
||||||
- 首屏加载时间减少 50-75%
|
|
||||||
- 中国用户体验显著提升
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
最后更新: 2026-02-12
|
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
# Monkey AI Web 前端
|
||||||
|
|
||||||
|
Monkey AI Web 是从总仓库 `weiyuan` 分支独立出来的前端工程,包含 AI 体验中心、模型与技能超市、用户中心、企业中心和管理控制台。本文面向接手开发、联调与部署的前端工程师。
|
||||||
|
|
||||||
|
- 仓库地址:`https://git.weytoken.com/qiubs/monkey-ai-web.git`(SSH:`ssh://git@git.weytoken.com:2222/qiubs/monkey-ai-web.git`)
|
||||||
|
- 集成分支:`weiyuan`,新功能分支从此创建。
|
||||||
|
- 本仓库只含前端,所有命令在仓库根目录执行。登录、模型调用、充值、企业管理等业务需要配套后端,仓库不提供默认测试账号或离线 Mock 服务。
|
||||||
|
|
||||||
|
## 1. 技术栈
|
||||||
|
|
||||||
|
| 用途 | 方案 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页面开发 | React 18、JavaScript / JSX、ES Modules(未启用 TypeScript) |
|
||||||
|
| 构建与开发服务 | Vite 5,npm 锁文件 `package-lock.json` |
|
||||||
|
| 路由 | React Router 6(BrowserRouter) |
|
||||||
|
| UI 与样式 | Ant Design 6(`antd` 6.7.0、`@ant-design/icons` 6.3.4)、Tailwind CSS 3、CSS 变量;装饰图标 `lucide-react` |
|
||||||
|
| 请求与流式响应 | Axios、Fetch、`sse.js` |
|
||||||
|
| 状态管理 | React Context 与按业务拆分的 Hooks |
|
||||||
|
| 国际化 | i18next、react-i18next |
|
||||||
|
| 内容与可视化 | React Markdown、KaTeX、Mermaid、VChart、`@xyflow/react`、Quill |
|
||||||
|
| 测试与检查 | Node.js 内置测试运行器、Playwright、ESLint 8、Prettier 3 |
|
||||||
|
|
||||||
|
依赖版本以 [package.json](./package.json) 与 [package-lock.json](./package-lock.json) 为准。
|
||||||
|
|
||||||
|
## 2. 本地启动
|
||||||
|
|
||||||
|
环境要求:Node.js ≥ 22.13.0,npm ≥ 10(`packageManager` 为 npm 10.9.9)。统一使用 npm,不要用 Bun 或 Yarn 生成其他锁文件。
|
||||||
|
|
||||||
|
仓库仅维护 `package-lock.json`,并忽略 `bun.lock` / `bun.lockb`。本地与 CI 使用 `npm ci` 安装依赖、`npm run dev` 启动开发服务、`npm run build` 构建。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git
|
||||||
|
cd monkey-ai-web
|
||||||
|
npm ci
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
开发服务默认监听 `0.0.0.0`,端口为 5174,支持访问本机地址和局域网 IP。端口被占用时 Vite 自动顺延,以终端输出的 `Local:` 和 `Network:` 地址为准。开发服务禁用项目未使用的 `import.meta.glob` 转换,普通动态导入和热更新照常使用。需要供验收脚本读取地址时,把输出重定向到 `dev.log`(如 `nohup npm run dev > dev.log 2>&1 &`)。
|
||||||
|
|
||||||
|
| 命令 | 模式 | 自动加载的配置文件 |
|
||||||
|
| ----------------- | ----------- | ---------------------------------- |
|
||||||
|
| `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`。修改后需重启开发服务或重新构建。
|
||||||
|
|
||||||
|
## 3. 后端联调与环境变量
|
||||||
|
|
||||||
|
### 推荐:同源请求,经 Vite 代理
|
||||||
|
|
||||||
|
`VITE_REACT_APP_SERVER_URL` 留空时,接口使用当前网页域名。[vite.config.js](./vite.config.js) 把以下前缀转发到 `DEV_PROXY_TARGET` 指定的后端(`/v1` 同时代理 WebSocket):
|
||||||
|
|
||||||
|
```text
|
||||||
|
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
|
||||||
|
```
|
||||||
|
|
||||||
|
切换联调后端时修改 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启服务;该变量只供 Vite 代理使用,不会暴露给浏览器。生产环境需由 Nginx 或网关配置同源反向代理,Vite 开发代理不会进入生产产物。
|
||||||
|
|
||||||
|
### 可选:直接访问独立后端域名
|
||||||
|
|
||||||
|
设置 `VITE_REACT_APP_SERVER_URL=https://api.example.com`(填后端根地址,不加 `/api`)。接口根地址由 [src/helpers/config.js](./src/helpers/config.js) 读取:非空时使用该值并开启 `withCredentials`,为空时走同源。直连时请求不经过 Vite 代理,后端需正确配置 CORS、凭证与 Cookie 策略;地址写入构建产物,切换需重新构建并发布。
|
||||||
|
|
||||||
|
### 环境变量
|
||||||
|
|
||||||
|
| 变量 | 作用 |
|
||||||
|
| --- | --- |
|
||||||
|
| `DEV_PROXY_TARGET` | 开发代理的后端地址(仅 Vite 使用) |
|
||||||
|
| `VITE_REACT_APP_SERVER_URL` | 浏览器直连的后端根地址,留空为同源 |
|
||||||
|
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑入口与路由开关,开发环境默认开启,生产环境默认关闭 |
|
||||||
|
| `VITE_SKILL_MARKET_MOCK` | 设为 `true` 时技能超市进入本地演示模式;默认不设置 |
|
||||||
|
| `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL` | Umami 统计,ID 留空则不注入脚本 |
|
||||||
|
| `VITE_GOOGLE_ANALYTICS_ID` | Google Analytics,留空则不注入 |
|
||||||
|
|
||||||
|
`VITE_` 开头的变量会进入浏览器产物,只能放公开配置,不能放模型密钥或后端机密。
|
||||||
|
|
||||||
|
## 4. 目录与代码入口
|
||||||
|
|
||||||
|
```text
|
||||||
|
monkey-ai-web/
|
||||||
|
├── docs/ # 开发与组件规范、页面 UI 规范、变更记录(入口 docs/README.md)
|
||||||
|
├── public/ # 原样复制到产物的静态资源
|
||||||
|
├── scripts/ # 开发启动、单测发现、UI 依赖审计、品牌图标生成、i18n 辅助脚本
|
||||||
|
│ └── vite/ # 自定义 Vite 插件:legacy-css-layers.js 提供旧浏览器 @layer 样式兜底
|
||||||
|
├── src/
|
||||||
|
│ ├── index.jsx # React 挂载、语言初始化、全局 Provider
|
||||||
|
│ ├── App.jsx # 路由、懒加载、访问守卫
|
||||||
|
│ ├── index.css # 全局样式与滚动条
|
||||||
|
│ ├── assets/ # 原型提取资源、品牌图标(脚本生成)
|
||||||
|
│ ├── components/ # 通用与业务组件:ui(Ant Design 适配层与主题入口)、console、common、layout 等
|
||||||
|
│ ├── pages/ # 页面与业务模块
|
||||||
|
│ ├── hooks/ # 按业务拆分的数据与交互逻辑
|
||||||
|
│ ├── context/ # User、Status、Theme、Org、Playground
|
||||||
|
│ ├── helpers/ # API 实例、鉴权、配置、主题、通用工具
|
||||||
|
│ ├── services/ # 会话、安全验证等服务
|
||||||
|
│ ├── constants/ # 业务常量
|
||||||
|
│ ├── config/ # 前端功能开关
|
||||||
|
│ ├── i18n/ # 语言目录、初始化、语言包
|
||||||
|
│ └── styles/ # 主题 token、中心外壳与页面样式
|
||||||
|
├── test/unit/ # 可入库的单元测试
|
||||||
|
├── tests/ # 历史 Node 测试
|
||||||
|
├── index.html # HTML 入口与启动占位画面
|
||||||
|
├── vite.config.js # 代理、别名、构建配置
|
||||||
|
├── playwright.config.js # 浏览器验收配置(用例放在本地忽略目录 e2e/)
|
||||||
|
├── package.json
|
||||||
|
└── package-lock.json
|
||||||
|
```
|
||||||
|
|
||||||
|
启动链路:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `App.jsx` → 业务页面。`PageLayout` 拉取 `/api/status`、校验用户会话并组织全局布局。别名 `@/` 指向 `src/`,`~/` 指向 `node_modules/`;`src/` 下的 `.js` 文件也按 JSX 编译,新增组件使用 `.jsx`。
|
||||||
|
|
||||||
|
### 常用业务入口
|
||||||
|
|
||||||
|
| 功能 | 路由 | 代码位置 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 首页 | `/`、`/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/` |
|
||||||
|
| 模型超市 | `/market`(`/pricing` 重定向) | `src/components/table/model-pricing/` |
|
||||||
|
| 技能超市 | `/skill-market` | `src/pages/SkillMarket/` |
|
||||||
|
| 用户中心 | `/user-center/{dashboard,usage-record,topup,settings,service-dashboard,invite,invoice,weyai-download}` | `src/pages/UserCenter/`、`src/pages/Recharge/` |
|
||||||
|
| 密钥管理 | `/user-center/key-management`(`/key-management` 重定向) | `src/pages/KeyManagement/` |
|
||||||
|
| 充值 | `/recharge` | `src/pages/Recharge/` |
|
||||||
|
| 企业中心 | `/org/*` | `src/pages/Organization/`、`src/hooks/org/` |
|
||||||
|
| 管理控制台 | `/console/*` | `src/components/console/` 与各页面目录 |
|
||||||
|
| 客户端与下载 | `/client/authorize`、`/weyai/download` | `src/pages/ClientAuthorize/`、`src/pages/WeyAiDownload/` |
|
||||||
|
|
||||||
|
页面是否可访问还受用户角色、后端模块配置与前端功能开关影响,以 `App.jsx` 与对应页面为准。
|
||||||
|
|
||||||
|
## 5. 开发约定
|
||||||
|
|
||||||
|
编码规范见 [docs/standards/DEV_STANDARDS.md](./docs/standards/DEV_STANDARDS.md),组件样式见 [docs/standards/UI_COMPONENT_STANDARDS.md](./docs/standards/UI_COMPONENT_STANDARDS.md),外壳与验收见 [docs/ui/GLOBAL_UI_BASELINE.md](./docs/ui/GLOBAL_UI_BASELINE.md)。要点:
|
||||||
|
|
||||||
|
- **请求**:只用 `src/helpers/api.js` 导出的 `API`。实例已处理接口根地址、凭证、统一错误提示(`skipErrorHandler: true` 跳过)、并发 GET 去重(`disableDuplicate: true` 关闭)、`New-API-User` 请求头,以及 `/api/org/*` 的 `X-Org-Id`。接口返回 `{ success, message, data }`,HTTP 200 不等于业务成功。流式对话见 `src/hooks/playground/useApiRequest.jsx`。
|
||||||
|
- **路由与权限**:在 `src/App.jsx` 注册路由,用 `PrivateRoute`、`AdminRoute`(role ≥ 10)、`RootRoute`(role ≥ 100)守卫;企业中心子路由在 `src/pages/Organization/index.jsx`。部分模块的可见性来自 `/api/status`,不能只靠隐藏菜单控制权限。
|
||||||
|
- **UI**:通用组件用 Ant Design;存量页面经 `src/components/ui` 适配层保留原契约;主题只由 `UiThemeProvider` 提供,不新增 ConfigProvider;按钮图标从 `src/components/common/icons/ActionIcons.js` 导入。页面改动需检查浅色、深色与窄屏。
|
||||||
|
- **国际化**:文案写 `t('中文原文')`,新 key 补齐 `src/i18n/locales/` 下 9 个语言包;运行时开放语言以 `src/i18n/catalog.js` 为准(简中、繁中、英、日、韩、越、泰),`fr.json`、`ru.json` 尚未登记。
|
||||||
|
|
||||||
|
## 6. 常用命令与提交检查
|
||||||
|
|
||||||
|
| 命令 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm run dev` | 启动开发服务 |
|
||||||
|
| `npm run build` | 生产构建,输出 `dist/` |
|
||||||
|
| `npm run verify:build -- <产物目录> --startup` | 校验静态入口、首屏 JS gzip 预算和按需加载边界;产物须用 `--manifest` 生成 |
|
||||||
|
| `npm run preview` | 本地预览构建结果(默认端口 4173) |
|
||||||
|
| `npm test -- --test-concurrency=1` | 串行运行单测(扫描 `src/`、`tests/`、`test/unit/`;新增共享单测放 `test/unit/`) |
|
||||||
|
| `npm run eslint` / `npm run eslint:fix` | ESLint 检查(零警告门禁)/ 自动修复 |
|
||||||
|
| `npm run lint` / `npm run lint:fix` | Prettier 检查 / 全仓格式化 |
|
||||||
|
| `npm run check:ui` | 审计应用源码、脚本、单测和根目录 JS 配置中的旧 UI 库引用,以及依赖声明、锁文件和品牌图标资产 SHA-256 |
|
||||||
|
| `npm run check` | 依次执行 `check:ui`、ESLint、单测与生产构建,任一步失败即停止 |
|
||||||
|
| `npm run vendor:icons` | 重新生成品牌图标资产 |
|
||||||
|
| `npm run test:e2e` / `test:e2e:headed` / `test:e2e:report` | Playwright 验收 / 有头运行 / 查看报告 |
|
||||||
|
| `npm run i18n:extract` / `i18n:status` / `i18n:sync` / `i18n:lint` | 语言包提取、统计、同步、检查 |
|
||||||
|
|
||||||
|
提交前至少运行 `npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1` 与 `git diff --check`;涉及依赖或图标时加跑 `npm run check:ui`。`npm run build` 只执行构建,不包含检查与测试。i18n 提取与同步会修改语言包,提交前核对 diff。
|
||||||
|
|
||||||
|
纯文档改动只检查变更文件的 Prettier、`git diff --check` 与相关链接 / 命令。`npm run check` 不包含 Prettier,且会构建到 `dist/`;Agent 验收构建须先获授权并输出到临时目录。Windows PowerShell 可用 `npm.cmd` / `npx.cmd` 避免执行策略拦截;终端编码、Web 请求和提交格式见 `docs/standards/DEV_STANDARDS.md` 第 12 节。`npm run dev` 本身不生成 `dev.log`,启动方须重定向输出,详见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。
|
||||||
|
|
||||||
|
### 本地 Playwright 登录配置
|
||||||
|
|
||||||
|
全流程 UI 审查使用 [UI 审查清单](docs/ui-review-checklist.md)。`e2e/` 保存本地用例,`.e2e/` 保存分阶段状态、截图、验收报告与会话缓存;均由 Git 忽略。会话缓存不上传、不提交。
|
||||||
|
|
||||||
|
本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`。该文件只保存测试账号,按用户约定不作 Git 忽略,允许提交;不得把值写入脚本、日志、截图注释或报告。其他凭据与 storageState 仍不入库。运行时由 Node 加载到环境变量:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --env-file=.env.playwright.local e2e/auth-login/run.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
收到通用测试指令时,代理按 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节自动判断受影响页面与账号类型,选择登录流程和脚本参数,无需用户重复说明个人或企业登录。手工运行脚本时,超管个人登录单独使用 `UI_ADMIN_USER` / `UI_ADMIN_PASS`,添加 `--admin` 选择超管账号,默认使用普通个人账号。仅执行个人端阶段可添加 `--personal-only`,例如 `node --env-file=.env.playwright.local e2e/auth-login/run.mjs --personal-only --admin`。超管同样通过 `/login` 的真实 UI 登录,不绕过权限校验。
|
||||||
|
|
||||||
|
测试先通过项目目录、启动日志与监听进程查找并验证已有开发服务;历史日志中的失效地址不能作为新启服务的依据。仅确认本项目服务不存在时才启动,结束时只清理本次启动的进程。项目 Playwright 配置和专项验收通过 `scripts/dev-service.mjs` 自动发现并复用服务(验证 Vite 源码映射属于当前项目,兼容 UTF-8 / UTF-16LE 日志);显式目标仍按调用方配置执行。本地登录脚本同样先发现已有服务,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。
|
||||||
|
|
||||||
|
Playwright 默认运行桌面及两个移动项目:`chrome-mobile`(最小视口 360×800)与 `chrome-mobile-393`(393×851)。通用用例继承项目视口,专项用例可覆盖视口测试指定场景。Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 优先复用已核验的现有开发服务,仅确认不存在时才使用 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。
|
||||||
|
|
||||||
|
| 命令 / 参数 | 用途与默认值 |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm run test:e2e:headless` | 无头运行;本地默认有头离屏,CI 强制无头 |
|
||||||
|
| `npm run test:e2e -- --project=chrome-mobile` | 运行默认配置中的 360×800 手机项目。专项 UI 验收也须覆盖此最小视口 |
|
||||||
|
| `npm run test:e2e:extended` | 全部 8 视口;也可设置 `PW_EXTENDED_LAYOUT=1` |
|
||||||
|
| `npm run test:e2e:dist` | 验证已有静态产物并严格启动 4176;不自动构建 |
|
||||||
|
| `npm run test:acceptance -- <参数>` | 串行单测、临时目录构建、产物校验、强制 local-dist/4176 测试 |
|
||||||
|
| `npm run test:e2e:environment` | 隔离验证 8 视口、手机 UA/触摸/DPR、CSS 截图;不代表业务验收 |
|
||||||
|
| `npm run test:e2e:report` | 打开最新完整 HTML 报告;仅人工使用 |
|
||||||
|
| `PW_WORKERS` | 默认 1,只接受正安全整数;保留串行优先策略 |
|
||||||
|
| `PW_TARGET` / `PW_BASE_URL` | 未指定时优先自动发现并复用开发服务,确认不存在后默认 local-dev / `http://127.0.0.1:4176/`;remote 必填 URL |
|
||||||
|
| `PW_VIDEO` / `PW_REQUIRE_ALL` | 默认 0;开启失败保留视频 / 全部通过约束 |
|
||||||
|
|
||||||
|
`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。
|
||||||
|
|
||||||
|
Trace、失败截图、CI JUnit 在 `test-results/<runId>/`,HTML 在 `playwright-report/<runId>/`,历史产物不自动清理。`PW_*` 不自动读取 Vite `.env*`;终端赋值只传递给当前会话的子进程。静态截图可使用 `scripts/browser-capture.mjs` 的 `captureStatic()`;已有视觉基线保留,不自动更新。
|
||||||
|
|
||||||
|
## 7. 构建与部署
|
||||||
|
|
||||||
|
- **首屏分包**:React 运行时独立缓存,公告和协议预览保留在按需 chunk;首页仅在收到非空 Markdown 时下载解析器。首屏启动 JS 预算为 820 KiB gzip,不含路由按需包和 CSS;验收构建使用 `npm run build -- --manifest --outDir <临时目录>`,再执行 `npm run verify:build -- <临时目录> --startup`。
|
||||||
|
- **开发预热**:只预热应用入口、布局和路由,不预热所有页面或禁用依赖发现。没有全量 `vendor` 分组,也没有将图表、文档等浏览器依赖外置。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
npm run preview
|
||||||
|
```
|
||||||
|
|
||||||
|
将 `dist/` 作为静态站点发布,部署环境需处理:
|
||||||
|
|
||||||
|
- **共享测试环境**:局域网沿用现有域名或 IP 与端口。由网关提供构建后的静态文件和 SPA 路由回退,并继续转发测试后端接口。Vite 的源码转换与 HMR 只用于独立的开发服务。自动发布时,先完成构建与检查,再切换站点目录,避免访问到构建中的文件。
|
||||||
|
- **路由回退**:使用 BrowserRouter,直接访问 `/org/...` 等页面时静态服务器需回退到 `index.html`,否则刷新返回 404。
|
||||||
|
- **接口转发**:生产环境配置反向代理或独立后端地址;Vite 开发代理不会进入产物,`preview` 不能代替生产网关。
|
||||||
|
- **流式与长连接**:SSE 接口需关闭响应缓冲并设置合理超时;WebSocket 需配置连接升级。
|
||||||
|
- **缓存**:`index.html` 应及时更新,带哈希的静态资源可长缓存;后端地址写在产物中,切换需重新构建并发布。
|
||||||
|
- **部署路径**:当前按域名根路径部署;部署到子目录需检查 Vite `base`、路由与静态资源地址。
|
||||||
|
|
||||||
|
## 8. 常见问题
|
||||||
|
|
||||||
|
| 现象 | 优先检查 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页面能打开但提示状态或接口加载失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;代理配置 |
|
||||||
|
| 共享测试站出现 Vite 红色遮罩 | 检查站点网关的前端上游。共享测试站应由网关提供构建后的静态文件,Vite 开发服务仅用于联调。开发服务对 `.npmrc` 请求直接返回 404。 |
|
||||||
|
| 登录后又回到登录页 | `/api/user/self` 响应、Cookie 是否发送、跨域凭证策略、账号状态 |
|
||||||
|
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求头 `X-Org-Id` |
|
||||||
|
| 修改环境变量后无变化 | 是否重启开发服务或重新构建发布;HTML 与静态资源缓存 |
|
||||||
|
| 找不到云脑入口 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关与账号权限 |
|
||||||
|
| 技能超市显示演示数据 | 是否设置了 `VITE_SKILL_MARKET_MOCK=true` |
|
||||||
|
| 线上子页面刷新 404 | 静态服务器是否配置 SPA 回退,接口路径是否被误回退到 HTML |
|
||||||
|
| 对话内容结束后才一次性显示 | SSE 响应、反向代理缓冲与超时 |
|
||||||
|
| 格式检查失败 | 对改动文件执行 `npx prettier --write <文件>` |
|
||||||
|
| 修改品牌后仍显示旧 Logo 或颜色 | 后台品牌设置、主题本地缓存、HTML 与静态资源缓存 |
|
||||||
|
|
||||||
|
首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 用已配置的测试模型验证对话。
|
||||||
|
|
||||||
|
## 9. 文档导航
|
||||||
|
|
||||||
|
| 文档 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| [AGENTS.md](./AGENTS.md) / [CLAUDE.md](./CLAUDE.md) | AI 代理协作入口:资源与安全规则、规范索引 |
|
||||||
|
| [docs/README.md](./docs/README.md) | 文档索引与规则优先级 |
|
||||||
|
| [docs/standards/DEV_STANDARDS.md](./docs/standards/DEV_STANDARDS.md) | 开发规范与 CRUD 模板 |
|
||||||
|
| [docs/standards/UI_COMPONENT_STANDARDS.md](./docs/standards/UI_COMPONENT_STANDARDS.md) | 主题变量与公共组件样式 |
|
||||||
|
| [docs/ui/GLOBAL_UI_BASELINE.md](./docs/ui/GLOBAL_UI_BASELINE.md) | 外壳、布局与验收流程 |
|
||||||
|
| [docs/CHANGELOG.md](./docs/CHANGELOG.md) | 变更记录与回滚方式 |
|
||||||
+1298
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
|||||||
|
# 文档索引
|
||||||
|
|
||||||
|
> 状态:有效 · 更新:2026-11-17 · 版本:v4.1
|
||||||
|
|
||||||
|
本项目前端规范的入口。规范分三层:开发与组件规范(`standards/`)、外壳与页面规范(`ui/`)、变更记录(`CHANGELOG.md`)。通用样式只写在 `UI_COMPONENT_STANDARDS.md`,页面规范只记录差异。
|
||||||
|
|
||||||
|
**何时阅读**:第一次接手项目、不确定该读哪份文档,或新增、调整文档时。
|
||||||
|
|
||||||
|
## 速查:按任务找文档
|
||||||
|
|
||||||
|
| 我要做的事 | 先读 | 再读 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 新增一个增删改查页面 | `standards/DEV_STANDARDS.md` 第 11 节参考实现 | `standards/UI_COMPONENT_STANDARDS.md` 第 3–9 节 |
|
||||||
|
| 调整颜色、卡片、表格、分页、表单、弹窗、抽屉 | `standards/UI_COMPONENT_STANDARDS.md` | 对应页面规范 |
|
||||||
|
| 修改顶栏、侧栏、页头、登录页或页面边距 | `ui/GLOBAL_UI_BASELINE.md` | — |
|
||||||
|
| 修改用户中心(看板、使用记录、充值、个人设置) | `ui/USER_CENTER_SPEC.md` | — |
|
||||||
|
| 修改密钥管理 / 服务监控 | `ui/KEY_MANAGEMENT_SPEC.md` / `ui/SERVICE_DASHBOARD_SPEC.md` | `ui/USER_CENTER_SPEC.md` 第 3 节 |
|
||||||
|
| 修改企业中心 / 控制台 | `ui/ORG_CENTER_SPEC.md` / `ui/CONSOLE_SPEC.md` | — |
|
||||||
|
| 修改模型超市 / 技能超市 | `ui/MODEL_MARKET_SPEC.md` / `ui/SKILL_MARKET_SPEC.md` | — |
|
||||||
|
| 修改任一表格的列设置 | `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | — |
|
||||||
|
| 做 UI 验收 | `ui/GLOBAL_UI_BASELINE.md` 第 6、7 节 | `ui-review-checklist.md`、对应页面规范的“验收要点” |
|
||||||
|
| 查改动范围或回滚方式 | `CHANGELOG.md` | — |
|
||||||
|
|
||||||
|
每份规范开头都有“何时阅读”和“速查”表,先看速查,需要细节再按章节号读取。
|
||||||
|
|
||||||
|
## 文档清单
|
||||||
|
|
||||||
|
| 文档 | 内容 | 大小 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `standards/DEV_STANDARDS.md` | 目录命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n、参考实现、提交前自检 | 约 23KB |
|
||||||
|
| `standards/UI_COMPONENT_STANDARDS.md` | 主题与变量、尺寸、卡片、筛选栏、表格、分页、表单、弹窗、抽屉、页签、标签、按钮与图标、可访问性与性能 | 约 20KB |
|
||||||
|
| `ui/GLOBAL_UI_BASELINE.md` | 外壳、带侧栏页面规格、布局规则、登录关卡、验收流程 | 约 15KB |
|
||||||
|
| `ui/USER_CENTER_SPEC.md` | 用户中心各页面 | 约 8KB |
|
||||||
|
| `ui/KEY_MANAGEMENT_SPEC.md` | 密钥管理 | 约 4KB |
|
||||||
|
| `ui/SERVICE_DASHBOARD_SPEC.md` | 服务监控 | 约 2KB |
|
||||||
|
| `ui/ORG_CENTER_SPEC.md` | 企业中心 12 个目标页 | 约 10KB |
|
||||||
|
| `ui/CONSOLE_SPEC.md` | 控制台 | 约 6KB |
|
||||||
|
| `ui/MODEL_MARKET_SPEC.md` | 模型超市 | 约 8KB |
|
||||||
|
| `ui/SKILL_MARKET_SPEC.md` | 技能超市与数据模式 | 约 8KB |
|
||||||
|
| `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | 表格列设置 | 约 4KB |
|
||||||
|
| `ui-review-checklist.md` | 双端 UI 审查、交互与证据记录清单 | 约 3KB |
|
||||||
|
| `CHANGELOG.md` | 对现状仍有影响的功能与修复记录 | 约 6KB |
|
||||||
|
|
||||||
|
## 规则优先级
|
||||||
|
|
||||||
|
用户当前指令 > `AGENTS.md` / `CLAUDE.md` 第 0 节 > 页面规范 `ui/*_SPEC.md`(限其范围)> `ui/GLOBAL_UI_BASELINE.md` > `standards/UI_COMPONENT_STANDARDS.md` > `standards/DEV_STANDARDS.md` > Ant Design 默认行为。同级冲突以“更新”日期较新者为准,并在同一次改动中修订两处。`CHANGELOG.md` 只记录历史,不作为规则依据。
|
||||||
|
|
||||||
|
## 阅读与维护
|
||||||
|
|
||||||
|
- 同一会话已读过的文档不重复全文加载,变化时仅补读相关差异;已知规范归属时按入口第 6 节直达目标章节,无需重复读取本索引。上下文交接保留已读路径与章节;单次读取超过约 300 行时分段读,并发读取不超过 4 个文件;用“路径 + 章节号”引用,不复制全文。
|
||||||
|
- 新文档按下列模板编写:开发与组件规范放 `standards/`,页面规范放 `ui/` 并命名为 `<范围>_SPEC.md`;同时登记本文“速查”和“文档清单”,并在 `AGENTS.md` / `CLAUDE.md` 第 6 节加一行索引。
|
||||||
|
- 同一组件规则被两个以上页面使用时,写进 `UI_COMPONENT_STANDARDS.md`,页面规范只保留差异。
|
||||||
|
- 改造、迁移、优化与回归的过程记录、截图与报告不建文档,只放 Git 忽略的 `report/`、`logs/`;`CHANGELOG.md` 只记录对现状仍有影响的功能与修复。
|
||||||
|
- 修改规范只动相关段落,并更新状态行的日期与版本(Agent 入口放在第 9 节,保持前缀稳定);每季度检查一次过期内容、失效路径与 `UI_COMPONENT_STANDARDS.md` 第 16 节的收敛进度。
|
||||||
|
- 规范类文档的表格由 Prettier 按紧凑格式输出(`.prettierrc.mjs` 的 overrides),提交前运行 `npx prettier --check <文件>`。
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# 标题
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:… · 更新:YYYY-MM-DD · 版本:vX.Y
|
||||||
|
|
||||||
|
一段话说明本文范围,以及与其他规范的关系。
|
||||||
|
|
||||||
|
**何时阅读**:哪些任务需要读本文。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| ------ | ---- |
|
||||||
|
| … | … |
|
||||||
|
|
||||||
|
**相关代码**:相关源码路径。
|
||||||
|
|
||||||
|
## 1. 范围与依据
|
||||||
|
|
||||||
|
(编号章节:只写可执行的规则;页面规范只写与公共规范不同的部分;必要时给出正例 / 反例。)
|
||||||
|
```
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
# 统一开发与 Ant Design CRUD 规范
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-26 · 版本:v2.6
|
||||||
|
|
||||||
|
新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。
|
||||||
|
|
||||||
|
**何时阅读**:新增或重构 CRUD 页面,编写请求、Hook、表单、弹层、权限、i18n 时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 落地顺序 | 常量 → 数据 Hook → 视图 → 路由 / 菜单 / 面包屑 → i18n → 单测(参考实现见第 11 节) |
|
||||||
|
| 组件选择 | 按所在中心选外壳(2.2 节);分页列表用适配层 `Table`;其余用 antd 原生 API |
|
||||||
|
| 适配层 | Modal / SideSheet 用 `visible` + `onCancel`;适配 Input 的 `onChange` 收值(2.3 节) |
|
||||||
|
| 请求 | 只用 `API` + `params`;先判 `success`;`p` 从 1 开始,`page_size` ≤ 100(第 3 节) |
|
||||||
|
| 错误 | HTTP 错误由拦截器提示,`catch` 不重复弹出;`finally` 回收 loading |
|
||||||
|
| React | 函数组件 + Hooks;派生值在渲染中计算;记忆化只用于测量过的问题(第 4 节) |
|
||||||
|
| 状态命名 | `items`、`total`、`page`、`pageSize`、`filters`、`loading`、`submitting`、`editingRecord`、`drawerOpen` |
|
||||||
|
| 表单 | `Form.useForm` + `rules`;失败不关闭弹层;提交按钮 `loading` 防重复(第 6 节) |
|
||||||
|
| 文件 | 不重复添加通用长版权文件头;单测放 `test/unit/`;文案补齐 9 个语言包 |
|
||||||
|
|
||||||
|
**相关代码**:`src/helpers/api.js`、`src/helpers/utils.jsx`、`src/helpers/paging.js`、`src/helpers/auth.jsx`、`src/components/ui/`、`src/components/console/`、`src/pages/Organization/components/`
|
||||||
|
|
||||||
|
## 0. 适用边界
|
||||||
|
|
||||||
|
- 本规范约束**新增 CRUD** 与**经授权的重构**。存量页面做纯 UI 任务时,请求、载荷、回调签名、状态、路由、权限保持原样,不为“符合规范”改写。
|
||||||
|
- 与页面规范冲突时按 `docs/README.md` 的“规则优先级”处理。
|
||||||
|
|
||||||
|
## 1. 目录与命名
|
||||||
|
|
||||||
|
### 1.1 一个 CRUD 模块的文件
|
||||||
|
|
||||||
|
| 层 | 路径 | 职责 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 常量与类型 | `src/constants/<module>.constants.js` | 接口前缀、状态/动作枚举、JSDoc 记录类型 |
|
||||||
|
| 数据 Hook | `src/hooks/<module>/use<Module>Data.js` | 唯一请求入口:列表、查询、分页、增删改 |
|
||||||
|
| 视图(控制台) | `src/components/table/<module>/index.jsx`、`<Module>Filters.jsx`、`<Module>ColumnDefs.jsx`、`modals/*.jsx` | 编排、筛选、列定义、编辑弹层 |
|
||||||
|
| 视图(企业中心) | `src/pages/Organization/Org<Module>.jsx`,Hook 放 `src/hooks/org/` | 同上;单文件过大时拆到 `components/` |
|
||||||
|
| 视图(用户中心) | `src/pages/UserCenter/<Module>.jsx` + 同名 `.css` | 同上 |
|
||||||
|
| 控制台路由入口 | `src/pages/<Module>/index.jsx` | 由 `App.jsx` 以 `React.lazy` 加载 |
|
||||||
|
| 单元测试 | `test/unit/<module>-*.test.js` | `.gitignore` 不再按测试扩展名全局忽略;保留已跟踪的存量测试 |
|
||||||
|
|
||||||
|
### 1.2 命名
|
||||||
|
|
||||||
|
| 对象 | 规则 | 示例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 组件文件 | PascalCase + `.jsx` | `EditRedemptionModal.jsx` |
|
||||||
|
| Hook | `use` + PascalCase;含 JSX 才用 `.jsx` | `useTaskLogsData.js` |
|
||||||
|
| 常量 | UPPER_SNAKE | `REDEMPTION_STATUS` |
|
||||||
|
| 事件 | 组件内 `handleXxx`,props 回调 `onXxx` | `handlePageChange`、`onSubmit` |
|
||||||
|
| 布尔 | `xxxOpen`、`isXxx`、`hasXxx` | `isMobile`、`isEdit` |
|
||||||
|
| 样式 | 页面根类 + 局部变量族 `--<前缀>-*`;文件 kebab-case | `.km-page`、`--km-card-border`、`key-management.css` |
|
||||||
|
| 后端字段 | 保持 snake_case 原样,不在前端改名 | `created_time`、`page_size` |
|
||||||
|
|
||||||
|
### 1.3 版权声明
|
||||||
|
|
||||||
|
源码不重复添加通用长版权文件头,保留独立的第三方声明。
|
||||||
|
|
||||||
|
## 2. Ant Design 组件边界
|
||||||
|
|
||||||
|
### 2.1 分层
|
||||||
|
|
||||||
|
| 层 | 何时用 | 入口 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| antd 原生 | 新代码默认 | `import { Button, Form, Input, Drawer } from 'antd'` |
|
||||||
|
| 中心外壳 | 页头、筛选卡、列表卡、弹层作用域样式 | 见 2.2 |
|
||||||
|
| 适配层 | 分页列表的 `Table` / `Pagination`;存量页 | `import { Table } from '@/components/ui'` |
|
||||||
|
| 专用组件 | 图表、流程画布、富文本、新手引导 | VChart、XYFlow、Quill、Joyride,不用通用控件替换 |
|
||||||
|
|
||||||
|
- 唯一主题入口为 `src/components/ui/UiThemeProvider.jsx`;禁止再包 `ConfigProvider`、新增主题状态或存储 key。组件内读 token 用 `const { token } = theme.useToken()`。
|
||||||
|
- 静态方法(`message`、`Modal.confirm`、`notification`)已由 `ConfigProvider.config` 注入主题,可直接使用。
|
||||||
|
|
||||||
|
### 2.2 按中心选组件
|
||||||
|
|
||||||
|
| 位置 | `/console/*` | `/org/*` | `/user-center/*` |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 页头 | `ConsolePageContainer` 自动渲染,登记 `consoleRoutes.js` | `OrgPageHeader`(`title`、`subtitle`、`actions`)+ 登记面包屑 | `UserCenterPageHeader`(`title`、`subtitle`、`extra`) |
|
||||||
|
| 页面根类 | 由外壳提供 | `uc-page oc-page` | `uc-page` |
|
||||||
|
| 筛选区 | `ConsoleSearchBar` + `ConsoleSearchActions` | `OrgFilterCard`(三列网格,`actions` 放重置/搜索) | antd `Card` + `Form` |
|
||||||
|
| 列表容器 | `ConsoleCard`,存量用 `CardPro` | `OrgListCard`(`title`、`tools`) | antd `Card`(`title`、`extra`) |
|
||||||
|
| 行操作 | `Button type='link' size='small'` | `OrgRowActions` 包裹无图标 link 按钮 | `Button type='link' size='small'` |
|
||||||
|
| 弹窗 | `ConsoleModal`(原生 `open`,默认 560) | `OrgModal`(适配契约:`visible`、`onCancel`) | antd `Modal` |
|
||||||
|
| 抽屉 | `ConsoleDrawer`(原生 `open`,默认 560) | `OrgSideSheet`(`visible`、`onCancel`、`width={560}`) | antd `Drawer`(`size={560}`) |
|
||||||
|
| 分页表格 | `@/components/ui` `Table`(自动套 `ConsoleTable` 与统一分页) | `@/components/ui` `Table`(自动统一分页) | `@/components/ui` `Table` + 显式分页选项(见 5.3) |
|
||||||
|
|
||||||
|
组件来源:`src/components/console/ConsolePrimitives.jsx`、`src/pages/Organization/components/{OrgPageHeader,OrgListCard,OrgModal,OrgSideSheet}.jsx`、`src/components/common/UserCenterPageHeader.jsx`。
|
||||||
|
|
||||||
|
### 2.3 适配层契约(踩坑清单)
|
||||||
|
|
||||||
|
| 组件 | 正确写法 | 常见错误与后果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `Modal` / `OrgModal` | `visible`、`onCancel`、`onOk`、`confirmLoading`;预渲染用 `lazyRender={false}` | 传 `open` 或 `forceRender` 会被内部 `visible`/`lazyRender` 覆盖,弹窗不显示或不预渲染 |
|
||||||
|
| `SideSheet` / `OrgSideSheet` | `visible`、`onCancel`、`width` | 传 `open`、`onClose` 无效 |
|
||||||
|
| `Input` | `onChange(value)` | 当作事件读 `e.target.value` |
|
||||||
|
| `Form` | `getFormApi`、`initValues`、`Form.Input` 等字段组件 | 与原生 `Form.useForm` 混在同一张表单 |
|
||||||
|
| `Form.RadioGroup` / `RadioGroup` | 前者首参为值,后者首参为事件 | 统一成一种契约 |
|
||||||
|
| `Table` / `Pagination` | `currentPage`、`pageSize`、`total`、`onPageChange(page)`、`onPageSizeChange(size)` | 换参,或一次改页容量触发两次请求 |
|
||||||
|
| `Button` | 存量 `theme='solid'` → primary,`type='danger'` → danger | 新代码继续写 `theme`;新代码用原生 `type='primary'`、`danger` |
|
||||||
|
| `Tag` | 旧 `white` / `grey` → antd `default` | 用白底自定义样式模拟普通标签 |
|
||||||
|
| `Dropdown` | 桌面默认 hover、触屏默认 click,显式 `trigger` 优先 | 强行统一触发方式 |
|
||||||
|
| `Card` | 存量 `bordered` 由适配层映射为 `variant` | 新代码继续写 `bordered` |
|
||||||
|
| `DatePicker` / `TimePicker` | 与 Semi 一致:`onChange(Date \| Date[] \| null, 文本 \| 文本[])`,`Form.DatePicker` 字段值为 `Date`;`format` 可写 date-fns 记法(自动转 dayjs);新代码直接用 antd + dayjs | 把首参当文本或对文本调用 `.getTime()`;需要文本时取第二个参数 |
|
||||||
|
| `Upload` | 手动上传在 `beforeUpload` 返回 `false`,保留文件实例、校验与列表 | 手动上传时自动发请求;`autoRemove` 的文件仍显示 |
|
||||||
|
| `Layout` | 侧栏布局显式控制 `hasSider` | 自动 `hasSider` 把内容列压成零宽 |
|
||||||
|
| `CardPro` | 多行筛选区完整显示,正文独立滚动 | 筛选区被收缩或截断、与正文重叠 |
|
||||||
|
| `Chat` | 输入框聚焦只聚焦 | 聚焦时触发发送 |
|
||||||
|
|
||||||
|
### 2.4 图标与样式
|
||||||
|
|
||||||
|
- 外观取值(颜色、间距、圆角、字号、各组件样式)以 `docs/standards/UI_COMPONENT_STANDARDS.md` 为准,本文只写编码约束。
|
||||||
|
- 按钮与操作图标:`import { Plus, Pencil, Trash2, RefreshCw, Search } from '@/components/common/icons/ActionIcons'`,按钮内传 `size={16}`;装饰图标用 `lucide-react`。
|
||||||
|
- 禁止导入 `@lobehub/*`、Radix UI、Floating UI、Semi、MUI(含旧 `@material-ui/*`)、Chakra、Headless UI、leva、antd-style、react-layout-kit。ESLint 的 `ui-dependencies/no-legacy-ui` 与 `npm run check:ui` 共用 `scripts/ui-dependency-policy.cjs`,不要在入口重复维护包名。
|
||||||
|
- JSX 不写十六进制颜色;不用全局 `!important`;新视图不用 Tailwind 颜色类(如 `text-gray-500`),改用 token 或页面变量。
|
||||||
|
|
||||||
|
## 3. 请求封装与错误处理
|
||||||
|
|
||||||
|
### 3.1 规则
|
||||||
|
|
||||||
|
- 只用 `import { API } from '@/helpers'`;禁止新建 axios 实例或用 `fetch` 调 `/api`(流式对话 `src/hooks/playground/useApiRequest.jsx` 除外)。
|
||||||
|
- `API` 已提供:`New-API-User` 请求头;`/api/org/*` 自动注入 `X-Org-Id`(显式传入优先);并发相同 GET 去重(`disableDuplicate: true` 关闭,带取消信号或请求组的 GET 不共享);HTTP 错误统一提示(`skipErrorHandler: true` 跳过并由页面自行处理)。受会话约束的接口首次返回 401 时取消该会话未完成的只读请求,阻止该会话继续发请求,并仅清理、跳转 `/org/login?expired=true` 一次。公开接口或显式 `sessionBound: false` 的请求不参与会话联动。
|
||||||
|
- 同一批必须全部成功的只读请求,可传入同一个 `requestGroup: new AbortController()`;首次拒绝的 HTTP 4xx/5xx 取消同组剩余读取。普通失败不取消无关请求,正常并发不限流;已发送的写入不由请求组批量取消。调用方仍须处理 Promise 拒绝,并在 `finally` 清理加载状态。
|
||||||
|
- 查询参数用 `params` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。
|
||||||
|
- `API` 的 GET、HEAD、OPTIONS 默认在 60 秒后超时,调用方可以通过 `timeout` 覆盖。保持在 `finally` 回收加载状态,并让过期请求与当前请求的状态互不干扰。
|
||||||
|
- 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。
|
||||||
|
- 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。
|
||||||
|
|
||||||
|
### 3.2 正反例
|
||||||
|
|
||||||
|
以兑换码搜索为例。反例摘自 `src/hooks/redemptions/useRedemptionsData.jsx` 的 `searchRedemptions`(第 104–121 行,有删节),新代码按正例编写:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// ❌ 存量写法
|
||||||
|
setSearching(true);
|
||||||
|
try {
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/redemption/search?keyword=${searchKeyword}&p=1&page_size=${pageSize}`, // keyword 未编码
|
||||||
|
);
|
||||||
|
// ...
|
||||||
|
} catch (error) {
|
||||||
|
showError(error.message); // 拦截器已提示,同一错误弹两次
|
||||||
|
}
|
||||||
|
setSearching(false); // 不在 finally 中
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
// ✅ 新代码
|
||||||
|
const reportUnexpected = (error) => {
|
||||||
|
// AxiosError 已由 API 拦截器提示,这里只提示代码异常
|
||||||
|
if (error?.name !== 'AxiosError') showError(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
setSearching(true);
|
||||||
|
try {
|
||||||
|
const res = await API.get('/api/redemption/search', {
|
||||||
|
params: { keyword, p: 1, page_size: pageSize },
|
||||||
|
});
|
||||||
|
const { success, message, data } = res.data;
|
||||||
|
if (!success) {
|
||||||
|
showError(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setItems(data.items || []);
|
||||||
|
setTotal(data.total || 0);
|
||||||
|
} catch (error) {
|
||||||
|
reportUnexpected(error);
|
||||||
|
} finally {
|
||||||
|
setSearching(false);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. React 组件、Hooks 与状态
|
||||||
|
|
||||||
|
- 新组件写函数组件 + Hooks;错误边界因 React 限制仍用类组件(如 `src/components/common/ChunkErrorBoundary.jsx`);路由页面与重型组件用 `React.lazy` + `Suspense` 拆包(`App.jsx` 已有模式)。
|
||||||
|
- 自定义 Hook 以 `use` 开头,一个 Hook 只负责一件事,返回结构稳定的对象。
|
||||||
|
- 派生值在渲染时计算,不复制进 `useState` 再用 `useEffect` 同步。
|
||||||
|
- `useMemo` / `useCallback` / `React.memo` 只用于测量过的昂贵计算或稳定传给记忆化子组件的引用,不默认添加。
|
||||||
|
- 状态就近放置,只提升到最近的共同使用方;属性透传超过 2–3 层时改用 Context。Context 只放低频变化的全局状态,输入框文本等高频值不放进 Context。
|
||||||
|
- 页面状态放在模块 hook 的 `useState` 中;跨页面只用既有 Context:`src/context/{User,Status,Theme,Org,Playground}`。项目未使用 Redux、Zustand、React Query,不引入新状态库。
|
||||||
|
- 生命周期加载用 `useEffectEvent`(`src/hooks/common/useEffectEvent.js`)包装加载函数,`useEffect` 依赖只放真正的触发条件;不得禁用 `react-hooks/exhaustive-deps`(ESLint `--max-warnings=0`)。
|
||||||
|
- 不可变更新:用 `setItems((list) => list.map(...))`,不直接改 `record`。
|
||||||
|
- 打开弹层时重置表单,不用 `setTimeout` 延迟清空编辑态。
|
||||||
|
- 不新增 localStorage / sessionStorage key;确需新增时在 PRD 中声明。
|
||||||
|
|
||||||
|
| 含义 | ✅ 命名 | ❌ 存量反例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 当前页数据 | `items` | `redemptions` 同时承担多种语义 |
|
||||||
|
| 总数 | `total` | 兑换码页用 `tokenCount` 表示总数 |
|
||||||
|
| 页码 / 页容量 | `page` / `pageSize` | `activePage` 与 `currentPage` 混用 |
|
||||||
|
| 查询条件 | `filters` | 每次从 `formApi.getValues()` 临时拼 |
|
||||||
|
| 列表加载 | `loading` | `loading` 与 `searching` 并存且不同步 |
|
||||||
|
| 提交中 | `submitting` | 复用列表 `loading` |
|
||||||
|
| 编辑对象 | `editingRecord`(`null` = 新建) | `{ id: undefined }` 表示新建 |
|
||||||
|
| 弹层开关 | `drawerOpen` / `modalOpen` | `showEdit`、拼写错误的 `visiable` |
|
||||||
|
| 勾选行 | `selectedRowKeys` | `selectedKeys` 存整行对象 |
|
||||||
|
|
||||||
|
## 5. 列表页编码要点
|
||||||
|
|
||||||
|
筛选栏、表格、分页的外观与交互规格见 `UI_COMPONENT_STANDARDS.md` 第 4–6 节。编码时注意:
|
||||||
|
|
||||||
|
- 筛选表单的 `onFinish` 调用 hook 的 `search(values)`;“重置”先 `form.resetFields()` 再调用 `reset()`。
|
||||||
|
- 列定义在组件内用 `t()` 生成;状态渲染引用常量枚举,不写魔法数字;`rowKey` 用稳定业务 id。
|
||||||
|
- 批量操作:`rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}`。
|
||||||
|
- 删除后的页码回退、筛选后的页码重置放在 hook 中处理(不要散落在组件中)。
|
||||||
|
- 列设置只用于已有该功能的表格(`docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。
|
||||||
|
- 所有路由的分页表格用适配层 `Table` / `Pagination`。完整数据交给 `Table` 本地分页,不传 `total`;已由页面筛选切片或由接口返回单页数据时传 `total`,表格不会再次切片。未开启分页的表格保持原样。受控分页按下例传入,条数回调自行回到第 1 页,不再触发翻页回调:
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
pagination={{
|
||||||
|
currentPage: page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
onPageChange: handlePageChange,
|
||||||
|
onPageSizeChange: handlePageSizeChange,
|
||||||
|
}}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 表单与弹层编码要点
|
||||||
|
|
||||||
|
表单项、弹窗、抽屉的外观与选型见 `UI_COMPONENT_STANDARDS.md` 第 7–9 节。编码时注意:
|
||||||
|
|
||||||
|
- 新表单用 `Form.useForm()` + `rules`;页脚按钮调用 `form.submit()`,逻辑写在 `onFinish`,校验失败由 Form 展示错误。
|
||||||
|
- 防重复:提交中按钮 `loading` 或 `confirmLoading`;hook 内 `submitting` 为真时直接返回。
|
||||||
|
- 成功:`showSuccess` → 关闭 → 刷新当前页;失败:保留弹层与已填内容。
|
||||||
|
- 打开时重置:弹层加 `forceRender`,在 `useEffect([open, record])` 中先 `resetFields()` 再 `setFieldsValue(record)`。
|
||||||
|
- 删除:确认回调返回 Promise 以显示加载;确认形态、危险按钮、失败保留与键盘交互见组件规范第 8 节。
|
||||||
|
- 日期提交前转换为后端格式(多为 Unix 秒);有未保存内容时沿用页面已有的关闭确认流程。
|
||||||
|
|
||||||
|
## 7. 加载、空态与错误态
|
||||||
|
|
||||||
|
组件写法见 `UI_COMPONENT_STANDARDS.md` 第 13 节。编码时注意:列表加载用 hook 的 `loading` 驱动 `Table loading`;校验错误只由 `Form.Item rules` 展示,不再弹 toast;页面级异常用 `Alert` 并保留重试入口。
|
||||||
|
|
||||||
|
## 8. 权限与路由
|
||||||
|
|
||||||
|
- 控制台:在 `src/App.jsx` 注册 `/console/<key>`,用 `AdminRoute`(role ≥ 10,可加 `permission` 做委派管理员校验)或 `RootRoute`(role ≥ 100)包裹;在 `src/components/console/consoleRoutes.js` 的 `consolePages` 增加 `{ key, title, description }`,描述文案键为 `consoleUi.descriptions.<description>`;侧栏菜单路径来自同文件。
|
||||||
|
- 企业中心:在 `src/pages/Organization/index.jsx` 增加子路由,元素按角色与模块可见性返回页面或 `<Navigate to={hiddenOrgTarget} replace />`;在 `components/OrgBreadcrumb.jsx` 的 `orgPageGroups` 登记分组;侧栏入口在 `OrgSidebar.jsx`。
|
||||||
|
- 用户中心:在 `src/components/common/UserCenterBreadcrumb.jsx` 的 `pageTitles` 登记 `路径 → 标题`。
|
||||||
|
- 组件内判断用 `isAdmin()` / `isRoot()`(`@/helpers`)、`useUserPermissions()`、企业 `orgRole` 与功能开关;隐藏按钮不等于鉴权,后端必须校验,前端不伪造权限。
|
||||||
|
- 新增路由、权限、菜单属于业务改动,纯 UI 任务禁止。
|
||||||
|
|
||||||
|
## 9. 类型定义
|
||||||
|
|
||||||
|
- 项目为 JS/JSX,未启用 TypeScript;新增文件只用 `.js` / `.jsx`,不引入 TS 类型体系。记录结构用 JSDoc `@typedef` 写在常量文件;组件公共 props 用 JSDoc(参考 `OrgListCard.jsx`)或 `prop-types`。
|
||||||
|
- 枚举值集中定义,禁止在组件中散落魔法数字(如 `status === 1`)。
|
||||||
|
|
||||||
|
## 10. 国际化
|
||||||
|
|
||||||
|
- `const { t } = useTranslation()`;key 为中文原文;插值写 `t('共 {{total}} 条', { total })`,不拼接翻译片段。
|
||||||
|
- 新 key 补齐 `src/i18n/locales/` 下 9 个文件(zh、zh-TW、en、ja、ko、vi、th、fr、ru);运行时开放语言以 `src/i18n/catalog.js` 为准。
|
||||||
|
- 用 `npm run i18n:status`、`npm run i18n:lint` 检查;`i18n:extract` / `i18n:sync` 会改语言包,提交前核对 diff。
|
||||||
|
|
||||||
|
## 11. 参考实现与落地步骤
|
||||||
|
|
||||||
|
仓库中没有专门的模板模块。新增 CRUD 时,复制同一中心里结构最接近的真实页面,再按本文规则修正已知问题。
|
||||||
|
|
||||||
|
### 11.1 参考实现
|
||||||
|
|
||||||
|
| 中心 | 参考文件 | 可复用的结构 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 控制台(列表 + 编辑弹窗) | `src/components/table/redemptions/`(`index.jsx`、`RedemptionsFilters.jsx`、`RedemptionsColumnDefs.jsx`、`RedemptionsTable.jsx`、`modals/EditRedemptionModal.jsx`)、`src/hooks/redemptions/useRedemptionsData.jsx`,路由入口 `src/pages/Redemption/index.jsx` | 数据 Hook 与筛选、列定义、表格、弹窗分文件;`CardPro` 编排筛选、操作、表格与分页 |
|
||||||
|
| 控制台(原语写法) | `src/pages/AdminInvoice/index.jsx` | `ConsoleSearchBar` + `ConsoleSearchActions` + `ConsoleCard` + 适配层 `Table` / `Modal` |
|
||||||
|
| 企业中心 | `src/pages/Organization/OrgProjects.jsx`;筛选卡见 `OrgAudit.jsx` | `OrgPageHeader` + `OrgListCard` + 适配层 `Table` 分页 + `OrgRowActions` + `OrgModal` + `Switch` 启停 + `Popconfirm` |
|
||||||
|
| 用户中心 | `src/pages/KeyManagement/index.jsx`、`src/hooks/tokens/useTokensData.jsx` | `UserCenterPageHeader` + 查询 `Card` + 列表 `Card` + `Table` + 适配层 `Pagination` + `Drawer` |
|
||||||
|
|
||||||
|
### 11.2 复制时必须修正的问题
|
||||||
|
|
||||||
|
参考实现是存量代码,复制后按本文规则修正。以兑换码模块为例(其他存量模块有同类写法):
|
||||||
|
|
||||||
|
| 位置 | 问题 | 改为 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `useRedemptionsData.jsx:107` | 查询串手工拼接,`keyword` 未编码 | `API.get(url, { params })`(3.2 节) |
|
||||||
|
| `useRedemptionsData.jsx:91`、`:119`、`:160` | `catch` 中 `showError(error.message)`,与拦截器重复提示 | 只提示非 AxiosError(3.2 节) |
|
||||||
|
| `useRedemptionsData.jsx:93`、`:162` | `setLoading(false)` 不在 `finally` 中 | 放进 `finally` |
|
||||||
|
| `useRedemptionsData.jsx:153` | 直接修改 `record.status` | 不可变更新(第 4 节) |
|
||||||
|
| `useRedemptionsData.jsx:41` | 用 `tokenCount` 表示总数 | `total` |
|
||||||
|
| `useRedemptionsData.jsx:279` | `setTimeout` 延迟清空编辑态 | 打开弹层时重置表单(第 6 节) |
|
||||||
|
| `redemptions/index.jsx:69` | 属性名拼写为 `visiable` | 原生组件用 `open`,适配层用 `visible` |
|
||||||
|
|
||||||
|
### 11.3 落地步骤
|
||||||
|
|
||||||
|
1. **常量**:`src/constants/<module>.constants.js` 定义接口前缀、状态枚举与 JSDoc 记录类型,需要时在 `src/constants/index.js` 导出。
|
||||||
|
2. **数据 Hook**:`src/hooks/<module>/use<Module>Data.js`,请求按第 3 节,状态命名按第 4 节。
|
||||||
|
3. **视图**:按 11.1 选同中心的参考实现拆分文件;外壳组件按 2.2 节选择,样式按 `UI_COMPONENT_STANDARDS.md`。
|
||||||
|
4. **路由、菜单与面包屑**:按第 8 节登记。
|
||||||
|
5. **文案**:新 key 补齐 9 个语言包(第 10 节)。
|
||||||
|
6. **单测**:在 `test/unit/` 下补 Hook 或列定义的测试,可参考 `test/unit/pagination.test.js`。
|
||||||
|
7. **检查**:运行第 12 节的命令并完成自检。
|
||||||
|
|
||||||
|
## 12. 代码风格与提交前检查
|
||||||
|
|
||||||
|
### 12.1 检查与构建
|
||||||
|
|
||||||
|
- Prettier:`singleQuote`、`jsxSingleQuote`,换行 LF;规范类文档使用紧凑表格(`.prettierrc.mjs` 的 overrides)。
|
||||||
|
- ESLint:`no-undef`、未使用 import 报错、Hooks 规则、禁用 UI 库导入,`--max-warnings=0`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run eslint # 0 错误 0 警告
|
||||||
|
npm run lint # Prettier 检查;修复用 npx prettier --write <文件>
|
||||||
|
npm test -- --test-concurrency=1 # 串行单测
|
||||||
|
npm run check:ui # 改依赖、图标或 UI 库导入时
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
构建验证需用户同意,输出到临时目录且不覆盖 `dist/`(见当前 Agent 入口第 7 节,无需加载另一入口)。
|
||||||
|
|
||||||
|
纯文档改动只需检查变更文件的 Prettier、`git diff --check` 与涉及的链接、命令、公共规则一致性;上述全量代码检查适用于代码变更。`npm run check` 不含 Prettier,且最后执行默认输出到 `dist/` 的构建,不直接用于临时目录验收。
|
||||||
|
|
||||||
|
### 12.2 提交与暂存
|
||||||
|
|
||||||
|
- 只在用户要求时 commit / push;提交前检查 `git status --short`、`git diff` 与 `git diff --cached`,只暂存当前任务文件,不使用 `git add .` 混入其他修改。
|
||||||
|
- 新提交使用 `type(scope): 中文说明`,scope 可省略;type 选 `feat`、`fix`、`docs`、`refactor`、`test`、`chore`、`perf`、`build`、`ci`、`revert`,例如 `docs(agent): 对齐公共规范与工具差异`。这是协作约定,`package.json` 未配置 commitlint;不假定本机另有 Git hook 强制校验。
|
||||||
|
- 提交说明写变更原因与实际验证结果;不写未完成的验证。默认不 amend、不强推、不重置工作区,提交后核对提交内容与剩余改动。
|
||||||
|
|
||||||
|
### 12.3 Windows 执行约定
|
||||||
|
|
||||||
|
- 每条 PowerShell 命令开头显式设置 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;`,包括 `-NoProfile` 子进程;读取 UTF-8 文件用 `Get-Content -Encoding UTF8`。通过 Bash 调用 PowerShell 同样处理;cmd 命令先运行 `chcp 65001 >nul`。Python 使用 `python -X utf8`,隔离模式使用 `python -I -X utf8`。
|
||||||
|
- PowerShell 若拦截 `npm.ps1` / `npx.ps1`,改用 `npm.cmd` / `npx.cmd`;不修改执行策略或 Windows 安全设置,不自动确认或抑制脚本安全警告。
|
||||||
|
- Windows PowerShell 5.1 的每个 `Invoke-WebRequest`(含别名)必须显式包含 `-UseBasicParsing -TimeoutSec 30`;优先使用完整命令名。原生 curl 仅用 `curl.exe --connect-timeout 10 --max-time 30`。执行已有下载脚本前检查调用,补齐参数;依赖旧 HTML DOM 的调用方应先迁移到合适的解析器,不擅自删除 DOM 依赖。不为验证下载而运行下载脚本,检查状态、内容或预期哈希。
|
||||||
|
- CPU / 内存用 `Get-CimInstance Win32_Processor` / `Win32_OperatingSystem`,避免依赖本地化名称的 `Get-Counter`;提交内存不足或无法确认资源门槛时不启动重型任务。任务结束只清理本任务启动的进程,保留已运行服务和他人进程。
|
||||||
|
- 调用 `reg.exe`、`netsh` 等原生程序前同样设置 UTF-8;使用 PowerShell 的 `&` 调用,不用 `cmd /c` 嵌套引号。内联 Node 脚本含引号时优先用 here-string 管道传入 `node`,避免 PowerShell 5.1 参数转义丢失。
|
||||||
|
|
||||||
|
### 12.4 Agent 入口一致性校验
|
||||||
|
|
||||||
|
PowerShell 校验成功输出 `公共规则一致`;不一致或缺少章节边界时退出码为 1:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;
|
||||||
|
@'
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const common = (p) => {
|
||||||
|
const s = fs.readFileSync(p, 'utf8').replace(/\r\n/g, '\n');
|
||||||
|
const a = s.indexOf('\n## 0.');
|
||||||
|
const b = s.indexOf('\n## 10.');
|
||||||
|
if (a < 0 || b <= a) throw Error(p + ': missing section boundary');
|
||||||
|
return s.slice(a, b);
|
||||||
|
};
|
||||||
|
if (common('AGENTS.md') !== common('CLAUDE.md')) throw Error('Common rules differ');
|
||||||
|
console.log('公共规则一致');
|
||||||
|
'@ | node
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12.5 提交前自检
|
||||||
|
|
||||||
|
- [ ] 改动的流程可只用键盘完成,焦点始终可见,纯图标按钮有 `aria-label`。
|
||||||
|
- [ ] 新的异步界面同时实现了加载、空数据、失败三种状态。
|
||||||
|
- [ ] 没有硬编码已有 token 能表达的颜色、间距、圆角;同一逻辑或结构出现 3 次以上已抽取复用。
|
||||||
|
- [ ] 请求参数、载荷、回调签名与改动前一致(纯 UI 任务)。
|
||||||
|
- [ ] 新文案已补齐 9 个语言包;改了脚本、环境变量或目录约定时已更新 `README.md`。
|
||||||
|
- [ ] 上述检查命令全部通过,并在 `docs/CHANGELOG.md` 追加了条目(如适用)。
|
||||||
|
|
||||||
|
## 13. 正反例速查
|
||||||
|
|
||||||
|
| 维度 | ✅ 正例 | ❌ 反例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 导入 | `import { Form } from 'antd'`;分页表格 `import { Table } from '@/components/ui'` | `import { Form } from '@douyinfe/semi-ui'`;同一表单混用两种 Form |
|
||||||
|
| 组件组合 | `OrgListCard` + 适配 `Table` + `OrgSideSheet visible` | 企业页直接用原生 `Drawer`,丢失 `.org-sidesheet` 遮罩样式 |
|
||||||
|
| 弹层开关 | `<OrgModal visible={modalOpen} onCancel={close} />` | `<OrgModal open={modalOpen} />`(被 `visible` 覆盖,不显示) |
|
||||||
|
| 状态命名 | `items`、`total`、`page`、`editingRecord`、`drawerOpen` | `tokenCount`、`visiable`、`{ id: undefined }` |
|
||||||
|
| 分页参数 | `params: { p: page, page_size: pageSize }`,`page_size ≤ 100` | `?page=0&size=1000` 期望一次取全 |
|
||||||
|
| 错误处理 | `if (!success) showError(message)`;`catch` 只提示非 Axios 异常;`finally` 回收 | `catch` 内 `showError(error.message)`;无 `finally` |
|
||||||
|
| 图标 | `<Button icon={<Plus size={16} />}>`(ActionIcons) | 按钮内新引入 lucide 图标或自绘 SVG |
|
||||||
|
| 样式 | `style={{ '--dm-surface': token.colorBgContainer }}` + 页面 CSS 引用变量 | `style={{ color: '#b96508' }}`、全局 `!important` |
|
||||||
|
| 文案 | `t('共 {{total}} 条', { total })` | `'共 ' + total + ' 条'`、只补中文语言包 |
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
# UI 公共组件与样式规范
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-20 · 版本:v2.6
|
||||||
|
|
||||||
|
所有后台页面共用的主题与组件标准。页面规范只记录与本文不同的部分;编码约定见 `DEV_STANDARDS.md`,外壳与布局见 `GLOBAL_UI_BASELINE.md`。
|
||||||
|
|
||||||
|
**何时阅读**:新增或调整任何页面的颜色、卡片、筛选栏、表格、分页、表单、弹窗、抽屉、页签、标签、按钮与图标,或检查可访问性时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 主题 | 只用 `UiThemeProvider` 的 token;局部颜色写在带前缀的页面变量族(第 2 节) |
|
||||||
|
| 尺寸 | 间距 8 / 16 / 24px(区块 18px);控件高 34px;圆角 8 / 10 / 12px |
|
||||||
|
| 卡片 | 筛选卡 + 列表卡,内边距 24px,卡头标题 15px / 600(第 3 节) |
|
||||||
|
| 筛选栏 | 字段竖排,3–5 列,间距 16px,“重置 / 搜索”在右下(第 4 节) |
|
||||||
|
| 表格 | `size='middle'`,表头 46px / 500,`scroll.x`,操作列为 link 按钮(第 5 节) |
|
||||||
|
| 分页 | 右对齐、小尺寸、每页 10 / 20 / 50 / 100 条、“共 N 条”(第 6 节) |
|
||||||
|
| 弹窗 / 抽屉 | 弹窗 520 / 560 / 720–800px,抽屉 440 / 560 / 620–820px,次操作在前(第 8、9 节) |
|
||||||
|
| 标签 | 状态用语义色,分类用调色板色(第 11 节) |
|
||||||
|
| 图标 | 按钮图标从 `ActionIcons.js` 导入,按钮内 16px(第 12 节) |
|
||||||
|
| 可访问性 | 键盘可达、焦点可见、图标按钮有 `aria-label`、状态不只靠颜色(第 15 节) |
|
||||||
|
|
||||||
|
**相关代码**:`src/components/ui/UiThemeProvider.jsx`、`src/styles/tokens.css`、`src/components/ui/`、`src/components/common/`
|
||||||
|
|
||||||
|
## 1. 适用范围与分层
|
||||||
|
|
||||||
|
| 层级 | 内容 | 文档 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 公共层 | 主题、尺寸刻度、通用组件样式与交互 | 本文 |
|
||||||
|
| 外壳层 | 顶栏、侧栏、公告、页头、内容边距、登录页 | `docs/ui/GLOBAL_UI_BASELINE.md` |
|
||||||
|
| 中心与页面 | 控制台、企业中心、用户中心及各页面的差异部分 | `docs/ui/*_SPEC.md` |
|
||||||
|
| 编码约定 | 请求、状态、CRUD 结构、适配层契约 | `docs/standards/DEV_STANDARDS.md` |
|
||||||
|
|
||||||
|
页面规范与本文冲突时,以页面规范为准(仅限其声明范围);本文未定义的部分使用 antd 默认样式与全局 token。
|
||||||
|
|
||||||
|
## 2. 主题与变量
|
||||||
|
|
||||||
|
### 2.1 全局 token
|
||||||
|
|
||||||
|
唯一定义处为 `prototypeTheme(dark)`(`src/components/ui/UiThemeProvider.jsx`),由 `useActualTheme` 选择浅色或暗色算法。
|
||||||
|
|
||||||
|
| token | 浅色 | 深色 | 对应 CSS 变量 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `colorPrimary` / `colorInfo` | `#b96508` | `#d1963a` | `--brand-primary` |
|
||||||
|
| `colorBgLayout` | `#f4f6f9` | `#11151c` | `--surface-bg-base` |
|
||||||
|
| `colorBgContainer` | `#ffffff` | `#1b212b` | `--surface-card` |
|
||||||
|
| `colorText` | `#263247` | `#e6ebf3` | `--text-primary` |
|
||||||
|
| `colorTextSecondary` | `#7e8998` | `#8e9aaa` | `--text-secondary` |
|
||||||
|
| `colorBorderSecondary` | `#e9edf2` | `#2b333f` | `--border-subtle` |
|
||||||
|
| `borderRadius` / `controlHeight` | 8 / 34 | 8 / 34 | — |
|
||||||
|
| `fontFamily` | Segoe UI、PingFang SC、Microsoft YaHei、sans-serif | 同左 | — |
|
||||||
|
|
||||||
|
品牌主题预设在 `src/styles/presets.js`,主题配置与持久化在 `src/helpers/theme.js` 与 `src/context/Theme`;预设 key 不改名。
|
||||||
|
|
||||||
|
组件级配置:`Menu` 项高 42px,原型选中底 `#fff3df` / `#382b1b`,选中文字 `#a45a07` / `#f2ad41`;`Card` 标题 15px;`Modal` 圆角 12px;`Tag` 默认描边样式;弹窗与抽屉遮罩默认不模糊。
|
||||||
|
|
||||||
|
暗色原型:antd 暗色算法由种子 `#f2ad41` 推导出 `#d1963a`;保留该全局主色及原型选中态。系统配置的主题色保留为原始种子,交互色根据当前明暗模式派生:选中背景低浓度着色,选中文字与强调色保证可读;实底按钮的默认、悬停和按压态共享同一前景色。页面复用 `--brand-accent`、`--brand-selection-bg`、`--brand-selection-text`,不自行写固定品牌色;成功、警告、错误继续独立于主色。
|
||||||
|
|
||||||
|
### 2.2 取色方式
|
||||||
|
|
||||||
|
| 场景 | 用法 |
|
||||||
|
| --- | --- |
|
||||||
|
| React 组件内 | `const { token } = theme.useToken()`,读 `token.colorPrimary` 等 |
|
||||||
|
| 组件把 token 传给局部 CSS | `style={{ '--xx-surface': token.colorBgContainer }}`,CSS 中引用变量 |
|
||||||
|
| 普通样式 | 语义变量:`--surface-*`、`--text-*`、`--border-subtle`、`--brand-*`、`--elevation-*`、`--motion-*`(`src/styles/tokens.css`) |
|
||||||
|
| 存量页面 | `--ui-*` 兼容变量(由 `UiThemeProvider` 的 TokenBridge 生成),新代码不再新增引用 |
|
||||||
|
|
||||||
|
禁止:新增 ConfigProvider、主题状态或存储 key;在 JSX 中写十六进制颜色;用全局 `!important` 覆盖 antd;只改页面底色来实现深色模式。
|
||||||
|
|
||||||
|
### 2.3 页面变量族
|
||||||
|
|
||||||
|
token 与语义变量没有对应值时,才在页面作用域内定义变量族:
|
||||||
|
|
||||||
|
1. 前缀为两个字母加连字符(如 `--uc-*`、`--oc-*`),只在页面根类与 `html.dark` 下的同一选择器中定义。
|
||||||
|
2. 浅色值取设计实测;深色值只引用 `--surface-*`、`--text-*`、`--border-subtle`、`--ui-color-*` 或它们的 `color-mix`;装饰阴影在深色下为 `none`。
|
||||||
|
3. 样式规则只引用变量,不直接写颜色。
|
||||||
|
|
||||||
|
以密钥管理为例(摘自 `src/pages/KeyManagement/key-management.css`):
|
||||||
|
|
||||||
|
```css
|
||||||
|
.km-page {
|
||||||
|
--km-card-border: #e6e9ef;
|
||||||
|
--km-card-shadow: 0 4px 24px rgba(15, 23, 42, 0.02);
|
||||||
|
}
|
||||||
|
html.dark .km-page {
|
||||||
|
--km-card-border: var(--border-subtle);
|
||||||
|
--km-card-shadow: none;
|
||||||
|
}
|
||||||
|
.km-page .km-list-card.ant-card {
|
||||||
|
border-color: var(--km-card-border);
|
||||||
|
box-shadow: var(--km-card-shadow);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 前缀 | 作用范围 | 前缀 | 作用范围 |
|
||||||
|
| ------------- | ---------------------- | ------------- | -------------- |
|
||||||
|
| `--uc-*` | 用户中心外壳 | `--oc-*` | 企业中心目标页 |
|
||||||
|
| `--ur-*` | 使用记录 | `--console-*` | 控制台 |
|
||||||
|
| `--rc-*` | 在线充值 | `--mm-*` | 模型超市 |
|
||||||
|
| `--ps-*` | 个人设置 | `--sm-*` | 技能超市 |
|
||||||
|
| `--km-*` | 密钥管理 | `--nm-*` | 系统公告弹窗 |
|
||||||
|
| `--service-*` | 服务监控(token 注入) | | |
|
||||||
|
|
||||||
|
### 2.4 尺寸刻度
|
||||||
|
|
||||||
|
| 类别 | 取值 |
|
||||||
|
| --- | --- |
|
||||||
|
| 间距 | 4 / 8 / 16 / 24px;页面区块之间 18px(`--uc-layout-gap`) |
|
||||||
|
| 圆角 | 控件 8px;小标签与选项 6px;卡片 10px;弹窗 12px |
|
||||||
|
| 控件高度 | 34px(按钮、输入框、选择器);表格行操作按钮使用 `small` |
|
||||||
|
| 字号 | 正文 14 / 22px;表格与辅助信息 13px;标签与说明 12px;卡片标题 15px / 600;弹层标题 16px / 600;页面标题 28 / 32px / 650 |
|
||||||
|
|
||||||
|
## 3. 卡片
|
||||||
|
|
||||||
|
| 项目 | 标准 |
|
||||||
|
| --- | --- |
|
||||||
|
| 结构 | antd `Card`;列表页拆为“筛选卡”与“列表卡”两张,间距 18px |
|
||||||
|
| 外观 | 圆角 10px;描边取页面变量或 `--border-subtle`;阴影只用极浅投影,深色为 `none` |
|
||||||
|
| 内边距 | 24px;移动端 16px |
|
||||||
|
| 列表卡头 | 左侧标题(15px / 600,行高 24px),右侧工具区(间距 8px,窄屏换行);最小高 34px;与表格间距 18px |
|
||||||
|
| 工具区顺序 | 次要操作(导出、刷新)在前,主操作(新建 / 创建)居后,列设置齿轮固定在最右 |
|
||||||
|
|
||||||
|
统计卡、信息卡等组合区块使用 `Card` + `Typography` + `Space` / `Grid`,数据与处理函数由页面提供。
|
||||||
|
|
||||||
|
## 4. 表格搜索栏(筛选卡)
|
||||||
|
|
||||||
|
- **筛选卡与列表卡间距**:从筛选卡底边到下方列表卡顶边统一为 18px,复用 `--uc-layout-gap`。同一对相邻区块只设置一次间距,优先由共同容器的 `gap` 控制。企业端以 `/org/logs` 为对齐基准,审计日志若在页签与筛选卡之间插入说明条,说明条上下也各留 18px。
|
||||||
|
- 背景:使用不透明的卡片纯色;浅色为白色,深色沿用主题卡片色,不使用渐变背景。
|
||||||
|
- 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。
|
||||||
|
- 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。
|
||||||
|
- 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。
|
||||||
|
- 搜索保留当前页码、每页条数、排序、勾选和展开等表格操作状态。点击“重置”时取消待执行搜索及在途筛选请求,恢复本页的默认筛选条件,回到第 1 页并初始化本页的表格操作状态。只切换筛选的页签放在筛选卡上方。
|
||||||
|
- 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。
|
||||||
|
- 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心常规筛选使用 `OrgFilterCard`。消耗明细及提示词记录复用个人消费记录的筛选布局和移动端折叠。
|
||||||
|
- 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。
|
||||||
|
- 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。移动端统一通过“显示/隐藏操作项”切换。
|
||||||
|
- 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。
|
||||||
|
|
||||||
|
### 4.1 时间范围及自动搜索
|
||||||
|
|
||||||
|
- 表格筛选的范围控件使用 `DatePicker` 或 `Form.DatePicker` 的 `tableFilter`,开始和结束输入框共用一个控件,支持清除。仅日期使用 `YYYY-MM-DD`,含时间使用 `YYYY-MM-DD HH:mm:ss`。日期弹层使用当前主题;桌面快捷周期位于日历左侧,窄屏可换行。
|
||||||
|
- 快捷周期依次为今天、近 7 天、本周、近 30 天、本月,复用 `DATE_RANGE_PRESETS`。相对周期按选择时的本地日期计算,匹配已提交范围时显示选中态。页面沿用自身初始日期或空值。选择完整范围、确认时间、选择快捷周期或清除后,通过同一个值变更入口提交;临时选择、悬浮预览和下拉搜索词不触发列表查询。
|
||||||
|
- `useFilterSearch` 将字段变更合并为一次 300ms 防抖查询。兼容表单用 `onValueChange={scheduleSearch}`,原生 Ant Design Form 用 `onValuesChange` 传最终值;独立受控字段可用 `changeFilter(setValue)`。输入框、数字组件、选择器、开关、复选和异步选择组件均在实际筛选值变化时接入。搜索按钮和回车共用 `submitSearch`,立即执行待查询条件。
|
||||||
|
- 后端分页沿用现有查询接口,传当前页及条件,同时将 `AbortSignal` 传到 `API`。字段变化、重置和卸载取消在途查询,忽略过期响应。以页码或已应用条件驱动请求的页面可用 `useTableFilterQuery` 将取消操作传给 `useFilterSearch`。
|
||||||
|
- 本地分页先按条件处理完整数据集再切页。独立控件可用 `useLocalTableFilters` 分开显示值与已应用值,再用 `useFilteredTableRows` 计算结果。大数组过滤复用 `filterTableRows`,超出 500 行时分片让出主线程,并在每批检查取消状态。
|
||||||
|
|
||||||
|
## 5. 表格
|
||||||
|
|
||||||
|
### 5.1 表头与行
|
||||||
|
|
||||||
|
| 项目 | 标准 |
|
||||||
|
| ---- | --------------------------------------------------------------------- |
|
||||||
|
| 尺寸 | `size='middle'`;表头高 46px |
|
||||||
|
| 表头 | 浅底(页面变量或 `colorFillAlter`)、次文字色、字重 500、不换行 |
|
||||||
|
| 行 | 行线取页面变量或 `--border-subtle`;正文 14px(紧凑列表可用 13px) |
|
||||||
|
| 滚动 | `scroll={{ x: 'max-content' }}`,在卡片内横向滚动;不固定表头纵向滚动 |
|
||||||
|
| 行键 | `rowKey` 用稳定业务 id;后端可能返回重复行时拼接序号 |
|
||||||
|
|
||||||
|
### 5.2 列
|
||||||
|
|
||||||
|
- 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。
|
||||||
|
- 状态列用只读 `Tag` 或 `TableStatusSwitch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。
|
||||||
|
- 调用、计费和访问权限分组列使用 `TableGroupTags`,单组与多组按同一套颜色渲染(见第 11 节)。
|
||||||
|
- 操作列放在最后,标题固定为“操作”,按钮为 `type='link' size='small'`,同一行操作间距 8px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`。`/console/user` 的用户列表、`/console/subscription` 的会员列表和 `/console/commission?view=partners` 的合作伙伴列表使用 `TableRowActions`:直出高频动作,其余放进带下箭头的文字“更多”菜单。其他列表沿用既有操作呈现方式,不批量套用此菜单。菜单点击打开、右对齐,无有效菜单项时不渲染入口;危险项置末、标记 `danger` 并保留业务确认。现有权限、状态限制、禁用项和回调不得因收纳而改变,方向键、Enter、Escape 可操作菜单。
|
||||||
|
- 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。
|
||||||
|
- 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。
|
||||||
|
- 三中心表头背景统一由 `center-table.css` 绘制:页面通过 `--center-table-head-bg` 提供色调,公共层在不透明的容器底色上叠加同色填充,普通列与固定列保持一致;页面不再直接覆盖表头 `background`。固定列使用 antd 6 的 `.ant-table-cell-fix` 与原生动态层级,不写死 `z-index`,不使用旧版 `fix-left` / `fix-right` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。
|
||||||
|
- 操作列在异步数据或列变化后重新测量可见行的按钮宽度,取最大值;列宽不超过表格容器,按钮组在空间不足时换行。左右固定区总宽超过容器时,保留右侧操作列,其余固定列参与横向滚动;容器恢复足够宽度后恢复原固定配置,避免窄屏相互遮挡。
|
||||||
|
- 操作列的删除入口置末并用 `danger`;点击仅打开确认,确认后的提交与刷新按第 8 节执行。无权删除或当前状态不允许删除时,沿用业务的隐藏或禁用规则。
|
||||||
|
|
||||||
|
### 5.3 状态
|
||||||
|
|
||||||
|
| 状态 | 写法 |
|
||||||
|
| --- | --- |
|
||||||
|
| 加载 | `Table loading` |
|
||||||
|
| 空数据 | 标准列表使用 `TableEmpty`(`ConsoleListTable` 默认接入):保留表头,简单插图 + “暂无数据”在当前可见宽度内居中;加载中不把空态当作查询结果,失败继续走错误提示 |
|
||||||
|
| 批量操作 | `rowSelection={{ selectedRowKeys, onChange }}`,未选中时批量按钮禁用 |
|
||||||
|
|
||||||
|
## 6. 分页
|
||||||
|
|
||||||
|
- 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。
|
||||||
|
- 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。
|
||||||
|
- 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。
|
||||||
|
- 删除当前页最后一条后回到上一页;筛选和搜索沿用当前页,重置回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。
|
||||||
|
- 受控分页须实现条数回调(或兼容的统一变更回调)才显示条数选择,不用客户端切片模拟固定条数的服务端接口;分页启用且有结果时单页也显示分页栏。
|
||||||
|
- 接入自动搜索的表格使用 `preservePage`。筛选后当前页没有结果时仍保留页码,分页栏显示实际结果总数并允许手动返回。删除后的页码调整由对应删除流程处理。
|
||||||
|
|
||||||
|
## 7. 表单项
|
||||||
|
|
||||||
|
- 布局:`layout='vertical'`;标签 14 / 22px、与控件间距 8px;控件高 34px、宽度 100%(筛选与弹层内)。
|
||||||
|
- 必填:用 `rules` 校验;弹层表单可设 `requiredMark={false}`,但校验规则不变;字段说明用 `Form.Item extra`。
|
||||||
|
- 错误:为错误提示预留高度,避免校验出现时相邻字段位移;提交失败保留已填内容。
|
||||||
|
- 输入:`Input allowClear` 并设 `maxLength`;数字用 `InputNumber`;日期用 `DatePicker`(值为 dayjs,提交前转换为后端格式)。
|
||||||
|
- 分组:长表单用 `Collapse`(设 `forceRender`,确保字段始终注册)或 `Divider` + 小标题(14px / 700,下距 18px)分组。
|
||||||
|
- 存量页面的适配层表单(`getFormApi`、`Form.Input` 等)不与原生 `Form.useForm` 混用。
|
||||||
|
|
||||||
|
## 8. 弹窗
|
||||||
|
|
||||||
|
| 项目 | 标准 |
|
||||||
|
| --- | --- |
|
||||||
|
| 选用 | 确认类或不超过 4 个简单字段;字段更多或含分组设置时用抽屉 |
|
||||||
|
| 宽度 | 520px(确认、简单表单)、560px(标准表单,控制台默认)、720–800px(含表格或富内容);窄屏左右各留 16px |
|
||||||
|
| 外观 | 圆角 12px;标题 16px / 600;正文与页脚使用 antd 默认间距 |
|
||||||
|
| 页脚 | 次操作(取消)在前、主操作(确定 / 保存)在后,按钮高 34px、间距 8px;危险确认用 `okButtonProps={{ danger: true }}` |
|
||||||
|
| 行为 | 提交中 `confirmLoading`;校验或请求失败不关闭;X、取消、Esc、遮罩关闭行为一致 |
|
||||||
|
| 表格操作列危险确认 | 删除、注销和冻结使用小尺寸危险链接,更多菜单使用危险菜单项。普通单条操作用 `TableActionPopconfirm`,注销、企业冻结等影响较大的操作用确认弹窗。取消在前,危险确认在后;优先聚焦取消 |
|
||||||
|
|
||||||
|
- 保留业务定制的标题、正文和按钮文案,并接入国际化。确认信息明确操作对象和影响。
|
||||||
|
- 只有明确确认才发送请求;取消、Esc 或关闭不修改数据。确认回调返回 Promise,提交中显示加载并防止重复请求,失败保留确认及上下文并提示原因。成功后关闭确认并刷新列表,删除当前页最后一条时按分页规范回退。
|
||||||
|
- 表格危险操作的回调在 API 明确失败时返回 `false`。确认框保持打开,业务回调保留原有错误提示。受控弹窗由业务在成功后关闭。
|
||||||
|
|
||||||
|
## 9. 抽屉
|
||||||
|
|
||||||
|
| 项目 | 标准 |
|
||||||
|
| --- | --- |
|
||||||
|
| 宽度 | 440px(列表、信息查看)、560px(创建 / 编辑表单)、620–820px(详情与宽内容);移动端 100% |
|
||||||
|
| 外观 | 标题 16 / 24px / 600;正文内边距 24px,`scrollbar-gutter: stable`;页脚贴底、按钮右对齐、间距 8px |
|
||||||
|
| 表单 | 设 `forceRender` 保持表单挂载,打开时 `resetFields()` 后回填,避免残留上次内容 |
|
||||||
|
|
||||||
|
### 遮罩
|
||||||
|
|
||||||
|
- 默认使用 antd 遮罩(不模糊)。
|
||||||
|
- “原型风格遮罩” `rgba(0,0,0,.3)` + `blur(4px)` 用于企业中心目标页弹层、列设置弹框、模型超市与技能超市详情抽屉;新页面如需使用,应在页面作用域通过变量定义,不修改全局默认。
|
||||||
|
|
||||||
|
## 10. 选项卡
|
||||||
|
|
||||||
|
| 类型 | 用法 |
|
||||||
|
| --- | --- |
|
||||||
|
| 列表页签 | antd `Tabs`;导航与下方内容间距 20px(控制台 16px);页签间距 28px;文字 14 / 22px;选中与悬停为品牌色,2px 下划线 |
|
||||||
|
| 卡片首部页签 | 控制台卡片主体以 `Tabs` 开始、页签上方没有标题或提示时,主体顶部内边距 8px,参考 `/console/website-setting`、`/console/smart-router`;保留页签默认上下内边距 12px、导航高 46px、与下方内容间距 16px,不叠加空白占位或顶部外边距。卡片其余内边距不变;页签前有错误提示或说明块时按对应容器规则处理。浅深主题、桌面与移动端一致。 |
|
||||||
|
| 筛选页签 | 只切换筛选条件时隐藏内容区(企业中心 `.oc-tabs-nav-only`),筛选结果由下方列表卡展示 |
|
||||||
|
| 分段控件 | 2–4 个互斥选项(如趋势维度、充值类型、头像类型)用 `Segmented`,`onChange(value)` 直接接值处理函数 |
|
||||||
|
| 预渲染 | 原先预渲染全部页签的页面保留 `forceRender`,不改变请求时机 |
|
||||||
|
|
||||||
|
## 11. 标签与状态
|
||||||
|
|
||||||
|
- **状态**用语义色:成功 `success`、失败 `error`、进行中 `processing`、等待 / 警告 `warning`、中性 `default`。
|
||||||
|
- **分类**(分组、类型、模型标签等)用调色板色(`blue`、`green`、`purple`、`gold`、`cyan` 等 antd 预设),不用非预设色名。
|
||||||
|
- 全局默认描边;卡片内的分类标签与企业中心表格标签用无边框样式,新代码写 `variant='filled'`(antd 6 已弃用 `bordered={false}`,二者视觉等价;存量写法可在修改时顺带收敛)。标签间距 8px,表格内标签不留右外边距。
|
||||||
|
- **表格启停开关**以 `/user-center/key-management` 为准,复用 `TableStatusSwitch`:小尺寸、开启显示「启用」并使用系统主题主色,关闭显示「禁用」并使用组件中性色。其他既有布尔含义可自定义两态文字。保留键盘焦点、可访问名称、原有确认和权限;关闭状态不等于控件不可操作。只读状态仍用 `Tag`,过期、耗尽等非二元状态的说明保留,表单与筛选区开关不套用本规则。
|
||||||
|
- **表格分组颜色与布局**以 `/console/organizations` 分组列为准,复用 `TableGroupTags`(单个标签也可用 `TableGroupTag`)。三种分组的标签文字固定为 `default`、`vip`、`svip`,颜色分别为蓝、黄、红。分组列禁止追加「(默认)」等说明,默认分组设置继续在表单中体现。`premium`、`pro` 沿用原名及红、黄配色,自定义分组用中性色。使用 antd 浅底描边标签并适配明暗主题。标签逐个着色、去重,按 4px 间距单行排列。纯分组列复用 `TABLE_GROUP_COLUMN_WIDTH`(148px),以完整容纳三枚标准标签为准。超出单元格的分组可横向滚动,已有的「+N」展开仍可使用。空值继承、智能熔断和非调用分组沿用各自的业务展示。
|
||||||
|
|
||||||
|
## 12. 按钮与图标
|
||||||
|
|
||||||
|
- 按钮:主操作 `type='primary'`,次操作默认按钮,行内操作 `type='link' size='small'`,危险操作 `danger`;高 34px,按钮组间距 8px。
|
||||||
|
- 按钮与操作图标统一从 `src/components/common/icons/ActionIcons.js` 导入(名称与 lucide 一致,如 `Plus`、`Pencil`、`Trash2`、`RefreshCw`、`Search`)。按钮内传 `size={16}`;未传尺寸时默认 24px(兼容入口 `components/ui/icons.jsx` 默认 16px);字体大小不影响图标占位。图标与文字整体居中,规则在 `src/styles/action-icons.css`。
|
||||||
|
- 非按钮装饰图标使用 `lucide-react`;无准确对应项的专业图形保留原实现。
|
||||||
|
- 模型品牌图标使用 `src/assets/brand-icons/`:首页与 `helpers/render.jsx` 只导入 `primitives`,完整变体经 `LobeHubIcon` 懒加载,头像容器用 antd `Avatar`。资产由 `npm run vendor:icons` 生成,保留 MIT 许可证、来源清单与 SHA-256,禁止手改;维护说明见 `src/assets/brand-icons/README.md`。
|
||||||
|
|
||||||
|
## 13. 提示、空态与加载
|
||||||
|
|
||||||
|
| 场景 | 写法 |
|
||||||
|
| --- | --- |
|
||||||
|
| 操作反馈 | `showSuccess` / `showError` / `showWarning`(`@/helpers`),已统一主题 |
|
||||||
|
| 页面级说明 | `Alert`(控制台用 `ConsoleAlert`:内边距 12px 16px、正文 14 / 22px、图标 16px) |
|
||||||
|
| 首屏加载 | `Card loading` 或 `Skeleton`;局部等待用 `Spin` |
|
||||||
|
| 空数据 | `Empty.PRESENTED_IMAGE_SIMPLE` |
|
||||||
|
|
||||||
|
原型未定义且 antd 没有对应组件的场景,按 `GLOBAL_UI_BASELINE.md` 第 5 节处理。
|
||||||
|
|
||||||
|
## 14. 组件分层与依赖
|
||||||
|
|
||||||
|
组件分层(antd 原生、中心封装、契约封装、专用组件)及选用方式见 `DEV_STANDARDS.md` 2.1、2.2 节。`src/components/ui/*` 只做视图映射,不放请求、权限与业务状态。
|
||||||
|
|
||||||
|
- 禁用范围见开发规范第 2.4 节;ESLint 与 `npm run check:ui` 共用一份规则,本地品牌图标不是运行时 UI 依赖。
|
||||||
|
- `npm run check:ui` 审计根目录 JS 配置、应用源码、脚本和单测的包引用,并检查依赖声明、锁文件中的传递包和别名,以及品牌图标资产 SHA-256。命令已包含在 `npm run check` 中。
|
||||||
|
- `antd` 与 `@ant-design/icons` 精确锁定版本;`src/components/ui/antd-v5-compat.css` 统一标签间距、分页选择器宽度与必填标记字体,页面样式可以覆盖。
|
||||||
|
- 当前版本 API 约定:Card 用 `variant`,Drawer 用 `size`,弹层遮罩用 `mask` 配置,Alert 标题用 `title`;样式选择器使用 `.ant-modal-container`、`.ant-alert-title`、`.ant-collapse-body`。聊天消息列表使用 `List`(antd 已标记弃用),替换前需先建立该区域的视觉基线。
|
||||||
|
|
||||||
|
## 15. 可访问性与性能
|
||||||
|
|
||||||
|
可访问性要求写在封装组件内部(如 `ConsoleModal`、`OrgListCard`),调用处无需重复。
|
||||||
|
|
||||||
|
### 15.1 可访问性
|
||||||
|
|
||||||
|
- **键盘**:所有交互元素可用 Tab 聚焦、Enter / Space 触发,焦点样式可见;不要只写 `outline: none` 而不提供 `:focus-visible` 替代。可点击的卡片使用 `role='button'` + `tabIndex={0}` 并响应 Enter / Space(模型超市、技能超市卡片已采用)。
|
||||||
|
- **名称**:纯图标按钮必须有 `aria-label`(可同时配 `Tooltip`);装饰图标加 `aria-hidden`;图片写有意义的 `alt`,装饰图片用 `alt=''`。
|
||||||
|
- **表单**:每个字段用 `Form.Item label` 关联标签,不只依赖 placeholder;错误信息由 `rules` 产生,antd 会自动关联到字段。
|
||||||
|
- **弹层**:使用 antd `Modal` / `Drawer`(自带焦点约束、Esc 关闭、关闭后焦点返回),不要用 `div` 自制弹层。
|
||||||
|
- **颜色**:状态不能只靠颜色表达,标签必须带文字;正文对比度 ≥ 4.5:1,大字 ≥ 3:1。
|
||||||
|
- **导航与动效**:当前菜单项标记 `aria-current`;非必要动效遵守 `prefers-reduced-motion`。
|
||||||
|
|
||||||
|
纯图标按钮的写法以密钥管理的复制按钮为准(摘自 `src/pages/KeyManagement/index.jsx`):
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
<Tooltip title={t('复制密钥')}>
|
||||||
|
<Button
|
||||||
|
type='text'
|
||||||
|
size='small'
|
||||||
|
aria-label={t('复制密钥')}
|
||||||
|
icon={<ActionCopy size={16} />}
|
||||||
|
onClick={() => onCopy('sk-' + token.key)}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
```
|
||||||
|
|
||||||
|
反例:只传 `icon` 不传 `aria-label`(读屏软件无法读出按钮用途);状态标签只有颜色没有文字。
|
||||||
|
|
||||||
|
### 15.2 性能
|
||||||
|
|
||||||
|
- 路由页面与重型组件(图表、编辑器、流程画布)按需加载;新增依赖前评估构建体积,避免扩大现有的大 chunk。
|
||||||
|
- 列表一律分页(服务端分页为主,已加载数据可前端分页),不一次渲染全部数据。
|
||||||
|
- 搜索输入、滚动、窗口缩放等高频事件做防抖或节流(如模型超市搜索 300ms 防抖)。
|
||||||
|
- 图片与嵌入内容设置宽高或 `aspect-ratio`,加载态占住最终布局的位置,避免布局跳动。
|
||||||
|
- 交互后立即给出反馈(按钮 `loading`、骨架屏),耗时操作不阻塞输入。
|
||||||
|
|
||||||
|
## 16. 现状偏差与收敛
|
||||||
|
|
||||||
|
以下差异已存在于代码中,新增页面按本文标准实现;修改相关页面时顺带收敛,不单独发起改动。
|
||||||
|
|
||||||
|
| 项目 | 现状 | 收敛方向 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 卡片描边与阴影 | 用户中心与密钥管理:`#e6e9ef` + `0 4px 24px rgba(15,23,42,.02)`;企业中心:`--border-subtle` + `0 3px 18px #25354a03`;控制台:token 描边无阴影 | 统一为一组公共变量,各中心引用 |
|
||||||
|
| 重复变量 | `--ur-*` 与 `--km-*` 的卡片、表头、行线、标签取值完全相同 | 提取为用户中心公共变量,两页引用 |
|
||||||
|
| 表头 | 用户中心与密钥管理字重 400;企业中心表头 12px、正文 13px、行内边距 17px;控制台未固定表头高度 | 统一为 46px、500 字重;企业中心紧凑表格保留为“紧凑”变体 |
|
||||||
|
| 列表卡头 | 用户中心与密钥管理 `margin: -6px 0 18px`;企业中心下距 20px;控制台卡头 56px / 16px | 标题 15px / 600、与表格间距 18px |
|
||||||
|
| 筛选操作间距 | 使用记录 10px,其余 8px | 8px |
|
||||||
|
| 状态标签 | 大量状态使用 `blue` / `green` / `red` / `orange` 等调色板色 | 状态改为语义色,分类保留调色板色 |
|
||||||
|
| 弹层宽度 | 弹窗出现 600 / 640 / 760 / 950 等非刻度值 | 收敛到第 8、9 节刻度 |
|
||||||
|
| 遮罩 | 默认遮罩与“原型风格遮罩”并存 | 保持现状,新页面默认使用 antd 遮罩 |
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# UI 审查清单
|
||||||
|
|
||||||
|
> 状态:有效 · 更新:2026-11-19 · 版本:v1.0
|
||||||
|
|
||||||
|
**何时阅读**:执行双端 UI 审查、视觉回归与真实操作验收时。项目设置、全局基线与对应页面规范优先,本清单不定义新增功能。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
- 环境、登录、视口与像素阈值:`ui/GLOBAL_UI_BASELINE.md` 第 6、7 节。
|
||||||
|
- 组件与主题判定:`standards/UI_COMPONENT_STANDARDS.md` 与对应页面规范。
|
||||||
|
- 只勾选实际验证项;无此控件写“不适用”,权限、数据或环境不足写“未覆盖”并留证,不视为通过。
|
||||||
|
|
||||||
|
## 检查顺序
|
||||||
|
|
||||||
|
- [ ] **导航布局**:侧栏展开、折叠、层级、悬停、选中与图标;顶栏 Logo、搜索、通知、头像、主题、语言、环境标识;面包屑;多页签关闭、固定、右键、滚动与回到顶部。
|
||||||
|
- [ ] **全局视觉**:背景、渐变、蒙层与其他叠加;边距、栅格、对齐、响应折行;主题与语义色、透明度、深浅映射;字号、字重、行高、截断、等宽数字和脱敏;SVG 基线、线面、尺寸、间距、圆角、边框、分割线与阴影。
|
||||||
|
- [ ] **容器**:卡片头、主体与分区,标签页的选中态、下划线、胶囊与位置,折叠面板与分隔线。
|
||||||
|
- [ ] **数据区**:表头、单元格、固定列、斑马纹、空态、虚拟滚动、列设置、密度、批量、编辑和拖拽;分页条数、位置、跳转、总数;操作对齐、权限、折叠和危险态;下拉菜单分组、图标及禁用态;标签、徽标、头像、进度、描述、统计、时间线、步骤、结果、JSON、高亮、复制与二维码。
|
||||||
|
- [ ] **输入与筛选**:文本、数字、自动补全、搜索、富文本、代码、单复选、组合框、开关、分段、日期时间、级联、树、穿梭、上传、滑块和评分;尺寸、前后缀、清除、计数、下拉空态、多选标签、远程搜索及错误、只读、禁用;标签、必填、校验、栅格、查询重置、展开收起和条件计数。
|
||||||
|
- [ ] **操作按钮**:主、次、默认、虚线、文本、链接、图标、危险、幽灵、下拉、分裂;大小、形状、块级、图标间距、点击热区、加载和禁用;按钮组、长文案与多语言折行、工具栏及弹层主操作、权限隐藏和禁用提示;危险二次确认、防重入、键盘焦点、语义色及深浅映射。复用组件和 token。
|
||||||
|
- [ ] **浮层与反馈**:弹窗和抽屉的尺寸、位置、结构、遮罩、关闭与二次确认;提示与气泡的定位、箭头、背景、阴影和触发;警告、消息、通知、无权占位及关闭反馈。
|
||||||
|
- [ ] **图形**:图表、拓扑、流程的 Canvas、WebGL 或 SVG;容器、DPR、清晰度、坐标轴、网格、图例、标注、配色、提示和动画终态。
|
||||||
|
- [ ] **状态**:骨架、加载、空态、失败、禁用、校验、选中;文字与图标能传达状态,空态操作不越权。
|
||||||
|
- [ ] **交互**:悬停、键盘焦点、按压、展开收起、表单、弹层、搜索分页、主题语言、导航与多页签;过渡时长、缓动、关键帧、进出场与减少动态效果。真实 CRUD 按基线、创建、复查、编辑、复查、删除、复查执行。
|
||||||
|
|
||||||
|
## 记录口径
|
||||||
|
|
||||||
|
- 每项差异记录页面、组件、属性、期望、实际、严重级、截图与建议;只读、真实写入与模拟场景分别记账。
|
||||||
|
- 视觉证据注明主题、视口、DPR、语言、字体和数据模式;跨主题像素变化不等于缺陷,只有同条件基线比较可按视觉阈值判定。
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# 控制台 UI 规范(/console/\*)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.7
|
||||||
|
|
||||||
|
管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。
|
||||||
|
|
||||||
|
**何时阅读**:修改控制台页面、页头、路由元信息或控制台原语时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页头 | `ConsolePageContainer` 统一挂载;元信息登记在 `consoleRoutes.js`;页面自带随子视图变化的标题时设 `hideHeading`,外壳只保留面包屑 |
|
||||||
|
| 原语 | `ConsolePrimitives.jsx`:Alert、Card、SearchBar、SearchActions、Form、Table、Tabs、Modal、Drawer |
|
||||||
|
| 样式差异 | 卡头 56px / 16px;筛选 4 列;表头底色 `colorFillAlter`;弹层默认 560px |
|
||||||
|
| 系统设置 | 统一纵向表单;控制台不显示紧凑模式切换 |
|
||||||
|
| 业务 | 路由、鉴权、接口、hook 与回调保持原契约 |
|
||||||
|
|
||||||
|
**相关代码**:`src/components/console/`、`src/components/common/ui/CardPro.jsx`、`src/pages/Setting/Setting.css`
|
||||||
|
|
||||||
|
## 1. 页面清单
|
||||||
|
|
||||||
|
| 页面 | 路径末段 | 规则 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 数据看板、监控中心 | `analytics`、`monitor` | 日期与刷新操作进入公共页头;保留时间筛选与监控页签 |
|
||||||
|
| 渠道、密钥、模型、用户、兑换码 | `channel`、`token`、`models`、`user`、`redemption` | 搜索卡、列表卡、表格与分页统一 |
|
||||||
|
| 使用日志、绘图日志、任务日志 | `log`、`midjourney`、`task` | 统一查询、统计、列表、分页;保留列设置与详情入口 |
|
||||||
|
| 企业、订单、发票、会员卡 | `organizations`、`order`、`invoice`、`subscription` | 统一容器、页头、搜索、卡片;保留编辑与审批流程 |
|
||||||
|
| 钱包、个人设置、提成、合作伙伴 | `topup`、`personal`、`my-commission`、`partner` | 共用视图在控制台上下文嵌入,其他入口保留原样 |
|
||||||
|
| 系统设置、官网设置、预约演示 | `setting`、`website-setting`、`demo-reservations` | 统一标题、Tabs、表单与列表;保留委派权限与配置保存 |
|
||||||
|
| 技能平台、专家平台 | `skill-platform`、`expert-platform` | 不使用装饰标题区;保留页级操作、指引与管理功能 |
|
||||||
|
| 在线调试、聊天 | `playground`、`chat/:id?` | 使用公共标题,画布嵌入工作区;保留会话与 iframe 行为 |
|
||||||
|
| 兼容入口 | `/console`、`experience-center-audit` | 保留原重定向 |
|
||||||
|
|
||||||
|
页面内不再自行渲染图标标题、渐变标题底座或补偿顶栏高度,标题与描述统一来自公共页头。
|
||||||
|
|
||||||
|
## 2. 文件与职责
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `ConsolePageContainer.jsx` | 唯一页头:面包屑、标题、描述、页级操作插槽;页面操作经 `ConsolePageActions` 保留原回调 |
|
||||||
|
| `consoleRoutes.js` | `consolePages` 元信息(`key`、`title`、`description`、可选 `hideHeading`)、菜单路径;最长父路由匹配、动态详情与未知路径兜底 |
|
||||||
|
| `ConsoleContext.jsx` | 页面上下文、搜索控件尺寸上下文、主题 token 到 `--console-*` 的映射;不新增 ConfigProvider 或存储 key |
|
||||||
|
| `ConsolePrimitives.jsx` | `ConsoleAlert`、`ConsoleCard`、`ConsoleSearchBar`、`ConsoleSearchActions`、`ConsoleForm`、`ConsoleTable`、`ConsoleTabs`、`ConsoleModal`、`ConsoleDrawer` |
|
||||||
|
| `ConsoleCollection.jsx` | 把 `CardPro` 的统计、查询、操作、表格、分页插槽编排为标准卡片;移动端查询可展开 / 收起 |
|
||||||
|
| `consoleTableAdapter.js` | 在旧 Table 适配边界转换 antd 排序参数,保持服务器排序处理函数契约 |
|
||||||
|
| `console.css` | 页头、容器、栅格、卡片、表单、表格、页签、弹层与响应式样式,限定在控制台上下文 |
|
||||||
|
|
||||||
|
新增控制台页面:在 `App.jsx` 注册路由并用 `AdminRoute` / `RootRoute` 包裹,在 `consolePages` 登记,补充 `consoleUi.descriptions.<description>` 文案。
|
||||||
|
|
||||||
|
## 3. 公共规则
|
||||||
|
|
||||||
|
- 页头:动态面包屑(首项为一级导航,末项为当前页,未知子路径保留已匹配父级),28 / 32px / 650 无图标标题,14 / 22px 描述(上距 6px),可选操作区;页头与工作区 18px。
|
||||||
|
- 顶部导航按路径段匹配,`/console` 及其任意后代路径激活“控制台”。
|
||||||
|
- 颜色由 `colorBgContainer`、`colorBgLayout`、`colorTextHeading`、`colorText`、`colorTextSecondary`、`colorBorderSecondary`、`colorFillAlter`、`colorPrimary` 映射到 `--console-*`;间距 8 / 16 / 24px;抽屉与弹窗 Portal 继承同一映射。
|
||||||
|
- 通用卡片、筛选栏、表格、分页、弹层样式按 `UI_COMPONENT_STANDARDS.md`;控制台差异:卡头最小高 56px、标题 16px / 600,筛选栏 4 列,表头底色为 `colorFillAlter`,列表页签与下方间距 16px。
|
||||||
|
- 弹窗与抽屉经 `ConsoleModal` / `ConsoleDrawer` 默认 560px,并按“次操作在前、主操作在后”重排纯按钮页脚;表单补齐 `scrollToError` 与校验失败回调,字段、规则与提交函数不变。
|
||||||
|
- 提示栏:控制台内的 `Banner` / `Alert` 统一走 `ConsoleAlert`,内边距 12px 16px、正文 14 / 22px、图标 16px,颜色取对应语义 token。
|
||||||
|
- 系统设置(`page.key === 'setting'`):表单统一纵向布局、8px 标签间距、24px 栅格、控件等宽,校验信息预留高度;弹窗页脚按钮高 34px、间距 8px、右对齐。规则限定在 `.settings-page` / `.settings-form-dialog`。
|
||||||
|
- 控制台上下文中 `CompactModeToggle` 不渲染,表格密度状态保留;其他模块仍可使用紧凑模式。
|
||||||
|
- 兑换码列表沿用渠道列表的行内链接按钮、右侧固定操作列和底部分页。「查看、复制、编辑、禁用/启用、删除」在同一行直接显示,保留既有权限和状态限制,删除仍需确认。窄屏横向滚动时操作列不换行。批量复制在选中兑换码后可用,清除失效兑换码由独立的危险操作确认承载。
|
||||||
|
- 添加兑换码与编辑兑换码信息共用右侧侧栏窗、表单样式及页脚。查看详情使用弹窗,优先展示兑换码和状态,再列出额度、时间与兑换人信息。
|
||||||
|
- 平台 Skill 中心的分类标签区域与搜索工具栏同宽、左对齐,不保留独立的最大宽度和自动居中;窄屏按原间距自然换行。
|
||||||
|
- 平台 Skill 详情的审核工作台仅由抽屉正文纵向滚动,技能原文不设置独立滚动区;审核操作进入抽屉固定页脚,按钮右对齐、间距 8px,仅在审核页签展示。
|
||||||
|
- 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。
|
||||||
|
|
||||||
|
## 4. 验收要点
|
||||||
|
|
||||||
|
- 浅深主题 × 桌面 / 移动:导航、面包屑、标题、容器、搜索与重置、分页、排序、表单校验、Tabs、弹窗与抽屉打开 / 取消。
|
||||||
|
- 搜索、分页、排序使用真实 GET;空数据与延迟加载用模拟接口并标注;所有非 GET `/api/` 请求拦截计数,不执行真实写操作。
|
||||||
|
- 监控页的演示数据只验收视图与交互,不作为监控后端验收。
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
# 后台 UI 全局基线
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-23 · 版本:v3.14
|
||||||
|
|
||||||
|
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
|
||||||
|
|
||||||
|
**何时阅读**:修改外壳或页面布局,或执行 UI 验收之前。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 视觉依据 | 在线原型 `http://192.168.0.161:8888`,只作视觉参考;页面规范优先 |
|
||||||
|
| 带侧栏页面 | 边距桌面 30 / 36 / 36px、移动 16 / 16 / 24px;面包屑距顶 30px、与标题 24px;标题 28 / 32px / 650(4.4 节) |
|
||||||
|
| 外壳尺寸 | 顶栏 72px;公告栏 35px;侧栏 216 / 64px;菜单项 42px |
|
||||||
|
| 滚动条 | 全站 6px,`#8b8b8b`,悬停 `#636363`,页面不得单独设置 |
|
||||||
|
| 装饰 | 无设计依据不加渐变、玻璃、发光、浮起与动效 |
|
||||||
|
| 登录关卡 | 真实 UI 登录,企业先于个人,凭据只经环境变量(第 6 节) |
|
||||||
|
| 验收 | 浅深主题 × 1920×1000 / 393×851 / 360×800,有头离屏串行,唯一页面不抢焦点,模拟与真实分开记录(第 7 节) |
|
||||||
|
|
||||||
|
**相关代码**:`src/styles/{user-center,center-layout,org-page,prototype}.css`、`src/index.css`、`src/components/layout/`
|
||||||
|
|
||||||
|
## 1. 依据与范围
|
||||||
|
|
||||||
|
- 原型定义的颜色、尺寸、样式、状态与视觉交互优先;原型只作视觉依据,不作业务、数据、状态、接口、路由依据。
|
||||||
|
- 专项规范见 `docs/README.md` 索引;专项未覆盖的部分按本文执行。
|
||||||
|
- 不重做:WeyAI 外部页与第三方 SDK 的内部视觉;本站托管的 `/weyai/download` 属于系统页面,沿用统一主题、顶栏与浮层 token。体验中心只检查宿主布局。图表、流程画布、编辑器与新手引导保留专用组件。
|
||||||
|
- 改造前先列出已覆盖、未覆盖、排除的页面;配置隐藏、权限重定向和原型失效入口单独列出。
|
||||||
|
|
||||||
|
## 2. 目录职责
|
||||||
|
|
||||||
|
| 目录 / 文件 | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `src/components/layout/` | 页面布局(`PageLayout`)、顶栏、公告栏、系统公告弹窗 |
|
||||||
|
| `src/styles/{user-center,center-layout,org-page}.css` | 用户中心与企业中心的外壳、侧栏、页头、内容边距 |
|
||||||
|
| `src/styles/prototype.css` | 有原型依据的布局与页面作用域样式 |
|
||||||
|
| `src/index.css` | 全局样式与滚动条 |
|
||||||
|
| `src/components/common/{UserCenterPageHeader,UserCenterBreadcrumb}.jsx` | 用户中心页头与面包屑 |
|
||||||
|
| `src/pages/Organization/components/{OrgPageHeader,OrgBreadcrumb}.jsx` | 企业中心页头与面包屑 |
|
||||||
|
| `src/assets/prototype/` | 原型提取的背景与插画资源(注明来源) |
|
||||||
|
|
||||||
|
主题、组件与图标相关文件见 `UI_COMPONENT_STANDARDS.md` 第 2、14 节。
|
||||||
|
|
||||||
|
## 3. 主题与组件
|
||||||
|
|
||||||
|
主题 token、页面变量族、尺寸刻度,以及卡片、筛选栏、表格、分页、表单、弹窗、抽屉、页签、标签、按钮与图标的统一样式,见 `docs/standards/UI_COMPONENT_STANDARDS.md`。本文只约束外壳与布局。
|
||||||
|
|
||||||
|
## 4. 全局外壳
|
||||||
|
|
||||||
|
### 4.1 顶栏
|
||||||
|
|
||||||
|
- 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。
|
||||||
|
- 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。
|
||||||
|
- 右侧按钮:主题、公告、语言等图标 16px,按钮高度与工具按钮点击区 34px、文字行高 20px,账户头像 32px、下拉箭头 10px;`.ui-header-actions` 内链接、徽标和图标容器为 inline-flex,图标、文字、头像与分隔线垂直居中;桌面专属操作在 768px 以下隐藏。
|
||||||
|
- 全站共享顶栏不展示未登录用户的“登录 / 注册”按钮,桌面与移动端一致;已登录用户保留头像与账户菜单,登录 / 注册页面及受保护导航的原有鉴权跳转保持不变。
|
||||||
|
- 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。
|
||||||
|
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。
|
||||||
|
|
||||||
|
### 4.2 公告栏与系统公告弹窗
|
||||||
|
|
||||||
|
- 公告栏总高 35px,浅金 / 深棕配色,图标无圆形底色与阴影;保留滚动、循环与悬停暂停。
|
||||||
|
- 系统公告弹窗用 antd `Modal` + `Segmented` + `Checkbox` + `Button`:桌面宽 860px、顶部 100px,长内容区最大 470px、空态区 300px;`notice-modal.css` 的 `--nm-*` 来自 `theme.useToken`;移动端左右留 16px,正文按视口限高滚动。
|
||||||
|
- 复用 `/api/notice`、`StatusContext.announcements`、未读回调与 `notice_close_date`;默认勾选“今日不再提示”,仅勾选并确认时记录日期,X / 遮罩 / Esc 只关闭。
|
||||||
|
|
||||||
|
### 4.3 侧栏
|
||||||
|
|
||||||
|
- 控制台侧栏显示、路由选中项变化或滚动区尺寸变化后,当前菜单超出可视范围时,仅滚动菜单区域使其完整可见;已可见时不移动,不滚动正文、不抢焦点,也不强制展开用户手动收起的分组。
|
||||||
|
- 企业中心与用户中心共用 `src/styles/center-layout.css`:展开 216px、收起 64px;菜单行高 42px、行距 6px,图标 16px / 1.5px 线宽;折叠入口文案“收起导航”。
|
||||||
|
- 企业信息区为无底框网格图标(24px / 1.65 线宽),内边距 28px 16px 26px,图文间距 10px;企业名与身份 12px / 20px 行高,身份上距 2px。
|
||||||
|
- 个人侧栏只保留容器外侧分隔线,内层 Menu 不叠加 `border-inline-end`;企业侧栏不提供菜单搜索。
|
||||||
|
- 内容外壳设 `min-width: 0`,防止宽表格挤压;桌面滚动区保留稳定槽位并补足 16px 留白,移动端不补。
|
||||||
|
|
||||||
|
### 4.4 带侧栏页面统一规格
|
||||||
|
|
||||||
|
适用于所有带侧栏的 `/user-center/*` 与 `/org/*` 页面,覆盖各页的旧数值;新增此类页面必须遵守,不得自写标题区或内容边距。
|
||||||
|
|
||||||
|
1. **内容边距**:读取 `user-center.css` 的 `--uc-page-pad-top/x/bottom`(桌面 30 / 36 / 36px,≤ 768px 为 16 / 16 / 24px)。普通页面根节点用 `.uc-page`;数据看板 `.uc-dashboard`、服务监控 `.user-center-service-page`(`calc(64px + 顶距)`,抵消宿主 `-mt-[64px]`)、下载页 `.weyai-download--embedded` 直接引用这些变量。企业功能页(`.org-*-page`、`.knowledge-page`、`.org-workbench`)走 `org-page.css`。禁止写死页面级边距或使用 `p-4 sm:p-6 lg:p-8`。工作区块间距 `--uc-layout-gap: 18px`。
|
||||||
|
2. **页头**:用户中心用 `<UserCenterPageHeader title subtitle extra />`,企业中心用 `OrgPageHeader`(内部复用前者)。面包屑 12 / 18px,距内容区顶 30px,父级 `--text-secondary`、当前项 `--text-primary`,分隔符左右 10px,与标题 24px;标题 28 / 32px / 650 / 字距 -0.6px(`--uc-heading`);副标题 14 / 22px、上距 6px(`--uc-subtitle`);页头与首块 18px;右侧操作放 `extra`(间距 8px,窄屏换行)。页面不得覆盖这些数值,数据看板只保留 hero 装饰层。
|
||||||
|
3. **面包屑登记**:用户中心在 `UserCenterBreadcrumb.jsx` 的 `pageTitles` 登记,显示“用户中心 / 当前页面”;企业中心在 `OrgBreadcrumb` 的 `orgPageGroups` 登记,分组页显示“分组 / 当前页面”,其他为“企业中心 / 当前页面”,未登记页面以标题兜底;体验中心(云端大脑 / 图片生成 / 视频生成)用 `ExperiencePageHeader`(内部复用 `UserCenterPageHeader`),显示“体验中心 / 当前页面”,企业中心宿主的云端大脑保留原卡片页头。带 hero 的企业功能页在 hero 内首个元素顶部放 `<OrgBreadcrumb />`。不在原本没有面包屑的页面新增导航;没有副标题文案时只传 `title`。
|
||||||
|
4. **滚动条**:全站滑块 `#8b8b8b`、悬停 `#636363`、宽高 6px、圆角 3px、轨道透明,值来自 `tokens.css` 的 `--brand-scroll` / `--brand-scroll-hover`,规则集中在 `src/index.css`。页面 CSS 与内联样式禁止设置 `scrollbar-width` / `scrollbar-color`(Chrome 121+ 设置后会忽略 `::-webkit-scrollbar`),标准属性只在 `@supports not selector(::-webkit-scrollbar)` 中给 Firefox。三中心操作表格沿用 Ant Design 固定列表格的横向滚动行为,不隐藏滚动条。
|
||||||
|
5. **验证**:逐页核对左右边距、面包屑顶距、标题与副标题字号间距、滚动条静止与悬停颜色(桌面 / 移动 × 浅 / 深)。
|
||||||
|
|
||||||
|
### 4.5 登录页与认证顶栏
|
||||||
|
|
||||||
|
- 认证页(`/login`、`/org/login`、`/org/:slug/login`、`/register`、`/org/register`、`/reset`、`/user/reset`)统一使用登录顶栏 `.login-layout-header` 与局部布局 `.auth-login-page`,顶栏采用后台标准样式,无品牌条、玻璃渐变与反光层;仅客户端授权页 `/client/authorize` 保留 `.auth-layout-header` 透出背景。
|
||||||
|
- 登录卡片无顶部装饰线、反光、外发光、角落光晕与 Logo 光环 / 星标;企业 / 个人切换用 antd `Button`;输入框、下拉、整行按钮与认证弹窗(`.auth-login-modal`)控件统一 36px 高、8px 圆角(`--auth-control-height`),必填标识经 `Form.Item` 呈现;表单项无下边距,label 12px、与输入框间距 7px,输入框下方固定预留 22px 报错位(`--auth-error-line`),必填与非必填项间距一致,正常、报错、修正三态布局稳定。第三方登录用描边整行按钮,无位移与扫光;分隔线用 `AuthDivider`。规则集中在 `src/styles/prototype.css` 的 `.auth-login-page` 段。
|
||||||
|
- 副标题、“记住登录名”、管理员重置提示与“忘记密码”使用加深 20% 的次文字色,无悬停底色,“忘记密码”悬停再加深;“切换企业”与“登录”同为主按钮样式。认证表单必填项显示 `*` 并就地提示:输入框“请输入 + label”,选择框“请选择 + label”;邮箱等格式校验沿用原判断与文案;校验用 `rules` / `validate`,通过后调用原处理函数,页面自管的受控输入(企业登录第 1 步)失焦为空时提示且不改按钮禁用条件。样式与校验调整不得改变登录校验、回调与载荷。
|
||||||
|
|
||||||
|
### 4.6 导航入口
|
||||||
|
|
||||||
|
- 密钥管理位于个人侧栏“使用记录”下方,路由 `/user-center/key-management`(旧 `/key-management` 重定向);侧栏、头像菜单、移动底栏入口指向同一路径,顶栏不再展示该入口。
|
||||||
|
|
||||||
|
## 5. 布局、背景与未定义场景
|
||||||
|
|
||||||
|
- 带侧栏页面按 4.4;控制台按 `CONSOLE_SPEC.md`;其余页面内容默认 24px 30px、移动 16px。筛选区自然换行,表格在自身容器横向滚动;不通过隐藏正文、裁剪校验信息或固定整页宽度迎合截图。
|
||||||
|
- 模型超市与技能超市的工作区居中,含内边距的最大宽度为 1760px;横向内边距为 `clamp(20px, 4vw, 80px)`,Hero 搜索区域沿用同一横向留白,600px 及以下为 20px。覆盖 3840 / 2560 / 1920 至 360px 宽度,目录按实际可用宽度减少列数,保留卡片正文和控件正常字号,不通过整体缩放压缩内容。
|
||||||
|
- WeyAi 两个下载路由共用页头、安装卡、工作台示意、平台安装包、功能和使用步骤。公开页的居中容器含内边距最大宽度为 1464px。首屏在页面可用宽度 960px 及以下上下排列,安装包分组在 1024px 及以上显示三列,在 768–1023px 显示两列,其余宽度显示一列,文件名可换行。用户中心内嵌页沿用第 4.4 节的面包屑和内容边距,下载页背景从面包屑区域开始覆盖内容区,面包屑与首屏标题区间隔 24px。
|
||||||
|
- 背景图优先复用原型的原始 SVG / 图片,放入 `src/assets/prototype` 并注明来源;原型用 CSS 绘制的背景按测量值在页面作用域复现,不用生成插画替代。
|
||||||
|
- 企业工作台横幅 `.ew-hero` 的浅金 / 深棕背景与三层轮廓只用于 `.org-workbench`,不扩散到其他页面。
|
||||||
|
- 原型未定义、antd 有组件:用当前版本默认样式与主题 token。antd 无对应部件:语义背景 / 文字 / 边框,无装饰背景、阴影与动画,间距 8 / 16 / 24px,窄屏堆叠且操作可达;新增此类统一规则先写入本文。
|
||||||
|
- 组合统计区用 `Card` + `Typography` + `Space` / `Grid`,数据、条件与处理函数由原页面提供。
|
||||||
|
- 无数据源的原型元素不虚构,只读占位或不渲染,并记入风险。
|
||||||
|
|
||||||
|
## 6. 登录前置关卡
|
||||||
|
|
||||||
|
1. UI 改动与验收前先通过真实浏览器 UI 登录,确认后台主体已渲染;仅接口成功或 URL 变化不算进入。涉及企业与个人两端时企业先于个人;禁止 API 登录、伪造鉴权或换入口绕过。收到“开发完成后测试一下”“修完后验收”等指令,自动依据任务目标、改动文件、实际路由和权限守卫确定范围与账号,不要求用户重复指定登录类型:
|
||||||
|
- `/org/*` 企业中心:企业账号,经 `/org/login` 登录,保留 A/B 判定。
|
||||||
|
- `/user-center/*` 及普通个人页面:普通个人账号,经 `/login` 登录。
|
||||||
|
- `/console/*` 控制台:超管账号,经 `/login` 登录;不先用普通账号试探控制台权限。
|
||||||
|
- 共享组件或跨中心改动:追踪实际引用,在受影响的中心分别验收;不同账号使用独立 Context,避免企业、个人与超管会话混用。不因一句泛化测试指令执行无关页面的全量验收。
|
||||||
|
- 执行前用简短进度说明告知已判断的范围与账号类型,直接继续。先使用现有本地配置;仅在范围经代码分析仍不明确、必要凭据缺失或实际权限不足时询问。用户明确“无需测试”“无需生产测试”等限制优先,普通测试指令不自动授权生产构建或生产环境操作。
|
||||||
|
2. Base URL 按第 7.1 节通过项目目录、启动日志与监听进程查找并核验,服务可用即复用;日志中的失效地址不能作为新启服务的依据。仅确认不存在时,Windows 用 `Start-Process -WindowStyle Hidden` 启动并写入 `dev.log`,支持 nohup 的 shell 用 `nohup npm run dev > dev.log 2>&1 &`。
|
||||||
|
3. 企业入口 `{Base URL}/org/login`,`waitForLoadState('networkidle')` 后检查可见非隐藏、非复选框输入框的数量、placeholder / 标签与按钮,打印不含输入值的判定并截图。
|
||||||
|
- 状态 A:一个企业输入框 +“下一步”。先填企业名称,点击“下一步”,等“企业内登录名”“密码”“登录”出现后再填凭据;不得把登录名当企业名,不得跳过企业查询。
|
||||||
|
- 状态 B:已出现登录名、密码与“登录”。直接填写凭据,保留已解析的企业上下文。
|
||||||
|
4. 个人端:新建无企业 Cookies / Storage 的 Context,进入 `{Base URL}/login`,按页面原有协议勾选与登录,确认用户中心侧栏与主体渲染后保存 storageState。
|
||||||
|
5. 凭据只经环境变量传入:企业 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`,普通个人 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS`,超管 `UI_ADMIN_USER` / `UI_ADMIN_PASS`。本机通过 `.env.playwright.local` 加载,不要求用户每次重新提供;该文件仅保存测试账号,按用户约定不作 Git 忽略,允许入库。值仍不得回显或写入脚本、日志、截图注释、报告;登录阶段不录 trace / HAR,其他凭据与 storageState 不入库。本地入口和账号选择参数见 `README.md` 的“本地 Playwright 登录配置”。
|
||||||
|
6. 失败时截图,记录 `dev.log` 尾部与失败请求(密码、Cookie、token、ticket 脱敏),写入风险;不盲目重试,不改登录业务代码。
|
||||||
|
7. 结束时通过顶栏用户菜单“退出登录”,确认回到登录页(当前为 `/org/login`)且受保护路由不再渲染。
|
||||||
|
|
||||||
|
## 7. 验收流程
|
||||||
|
|
||||||
|
### 7.1 工具
|
||||||
|
|
||||||
|
- 优先使用项目 Playwright 配置(`playwright.config.js`:`testDir: ./e2e`、`workers` 默认 1,可由正整数 `PW_WORKERS` 覆盖)与本机 Chrome(`channel: 'chrome'`)。默认离屏,保留 `UI_VISUAL_OFFSCREEN=1`(只降低可见干扰,不保证没有瞬时焦点激活);要求不启动有头窗口时可用无头模式并在报告注明。
|
||||||
|
- 测试优先复用用户已启动的本项目开发服务:结合项目目录、启动日志(优先 `dev.log`,兼容 UTF-8 / UTF-16LE)、进程和监听端口查找候选地址,验证响应属于当前项目。历史日志地址失效时继续查找,不得直接启动新服务;仅确认本项目服务不存在时才启动,并记录、清理本次进程,不结束用户进程。项目 Playwright 配置通过 `scripts/dev-service.mjs` 自动发现服务并以 `PW_TARGET=remote` + `PW_BASE_URL` 复用;显式指定目标时保留调用方配置。专项脚本是否接收 `PLAYWRIGHT_BASE_URL` 以其实现为准,不能用它替代 runner 的 `PW_BASE_URL`。Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。
|
||||||
|
- 默认 runner 为浅色、1920×1080 / 360×800,本地有头、CI 无头,`webServer.reuseExistingServer=false`;默认执行不等于完成第 7.3 节浅深主题与规范视口矩阵,须在用例或专项脚本补足。严格有头焦点约束见第 7.1.1 节。
|
||||||
|
- `e2e/` 为本地忽略目录,验收脚本不随仓库分发;新增脚本同样放在该目录。
|
||||||
|
|
||||||
|
#### 7.1.1 浏览器焦点约束(有头 Chrome)
|
||||||
|
|
||||||
|
目标是不干扰用户桌面焦点。脚本统一通过 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()` 启动,它已内置以下约束:
|
||||||
|
|
||||||
|
| 约束 | 要求与实现 |
|
||||||
|
| --- | --- |
|
||||||
|
| 唯一页面 | 全程只用启动时已有的一个标签页,访问新地址用 `page.goto` / `browser_navigate`;`context.newPage()` 被拦截并抛错 |
|
||||||
|
| 禁止新建 / 切换 | 不调用 `browser_tabs new` / `select`、`context.newPage()`、`page.bringToFront()`;标签页管理只允许 `browser_tabs list` / `close`。应用自开的 `window.open` 与 `target="_blank"` 链接在页内拦截并记录;仍出现的额外页面立即关闭,不切换 |
|
||||||
|
| 禁止系统级输入 | 只用页面级操作(`click`、`fill`、`type`、`goto`、`evaluate`),不用系统级鼠标键盘模拟、窗口激活或最小化 |
|
||||||
|
| 后台建页 | 启动后若没有现成页面,只能用 CDP `Target.createTarget` 并传 `{ background: true, newWindow: false }` |
|
||||||
|
| 换账号 / 视口 / 主题 | 同一页面内用 `resetSession(origins)` 清 Cookie 与存储;视口用 `setViewportSize`,主题用 `emulateMedia`;需要 `isMobile` / `hasTouch` 时关闭后重启(计为新的启动) |
|
||||||
|
| 启动激活 | 启动时窗口若获得前台,记录“启动焦点激活事件”后继续,不做任何再次激活的操作 |
|
||||||
|
| 状态断言 | 关键步骤后调用 `checkpoint(label)`:以 Windows 前台窗口所属进程比对本次 profile 的 `chrome.exe`;`document.hasFocus()` 受 Playwright 焦点模拟影响恒为 true,只记录不判定。后台 → 前台记录“二次焦点激活”并暂停;无法确认时记录“无法确认后台状态”并暂停,不得宣称“已保证后台运行” |
|
||||||
|
|
||||||
|
- runner 用例从 `scripts/playwright-test.mjs` 导入 `test` / `expect`,公共 fixture 以 CDP `Target.createTarget({ background: true })` 创建当前 Context 的唯一页面,禁止 `browser.newContext` / `browser.newPage` / `context.newPage` / `page.bringToFront`,意外新页面立即关闭并判失败。页面创建后和用例结束后探测焦点;前台激活或状态未确认会记录并停止。独立脚本仍通过 `launchFocusSafe()`,在关键步骤调用 `checkpoint()`。
|
||||||
|
- 交付说明写明焦点日志结论(是否出现启动激活、二次激活、无法确认),不把未检测的运行写成“后台运行”。
|
||||||
|
|
||||||
|
#### 7.1.2 runner 环境与产物约定
|
||||||
|
|
||||||
|
`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。
|
||||||
|
|
||||||
|
| 配置 | 约定 |
|
||||||
|
| --- | --- |
|
||||||
|
| 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 |
|
||||||
|
| 视口 | 默认 1920×1080、360×800、393×851;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 |
|
||||||
|
| 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;默认项目覆盖 360×800(`chrome-mobile`)和 393×851(`chrome-mobile-393`),screen 沿用模板;平板仅为桌面设备的平板尺寸 |
|
||||||
|
| 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `http://127.0.0.1:4176/`;开发和预览均严格占用指定端口,禁止静默回退 |
|
||||||
|
| 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 |
|
||||||
|
| 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 |
|
||||||
|
| 并发 | 默认单 worker、文件内不拆分;`PW_WORKERS` 只接受正安全整数,不代表动态内存调度 |
|
||||||
|
| 布尔变量 | `PW_HEADLESS`、`PW_EXTENDED_LAYOUT`、`PW_VIDEO`、`PW_REQUIRE_ALL`、`UI_VISUAL_OFFSCREEN` 仅接受 `0` / `1`,未设采用默认值 |
|
||||||
|
| 产物 | `test-results/<runId>/` 保存 Trace、CSS 像素失败截图、CI JUnit;`playwright-report/<runId>/` 保存 HTML,均不自动清理 |
|
||||||
|
| 运行编号 | 自动生成并由 worker 继承;手设 `PW_RUN_ID` 须为唯一的安全目录名,字母/数字/短横线/下划线,最长 100 字符 |
|
||||||
|
| 静态截图 | 新采集使用 `captureStatic()`:等待字体与可见图片、CSS 像素、禁用动画/过渡、隐藏光标;行为测试不全局关闭动画 |
|
||||||
|
| 视觉基线 | 保留已有 `toHaveScreenshot()` 断言和用例级阈值;不会自动更新基线。既有截图、坐标及历史报告不缩放重写,环境变化后新比较须重采 |
|
||||||
|
| 专项覆盖 | 现有用例可以显式覆盖 viewport、主题和 DPR,执行结果须标明实际环境;默认 runner 不替代第 7.3 节的规范矩阵 |
|
||||||
|
|
||||||
|
`PW_*` 来自启动进程环境,不自动加载 Vite `.env*`;凭据仍按第 6 节与 README 单独加载。环境指纹第 2 版包含共享上下文、公共启动参数和 CSS 截图口径,不等于锁定系统字体与 Chrome 版本。Service Worker 仍由各流程决定:runner 沿用默认允许,独立守卫流程保留阻止。
|
||||||
|
|
||||||
|
常用入口:`npm run test:e2e:headless`、`test:e2e:extended`、`test:e2e:dist`、`test:e2e:environment`。`test:e2e:report` 自动找到最新完整报告,也可传指定目录。`npm run test:acceptance -- <Playwright 参数>` 先串行单测,再构建到系统临时目录、校验产物、强制 local-dist/4176 测试,结束后清理本次临时构建,不覆盖工作区 dist;已有依赖真实后端或登录态的用例仍需配置好环境,不等于自动完成真实业务验收。
|
||||||
|
|
||||||
|
### 7.2 分阶段
|
||||||
|
|
||||||
|
1. 企业端:真实 UI 登录 → 逐菜单双主题 → 表格、筛选、分页、弹窗、抽屉、表单的正常与失败状态 → UI 退出。
|
||||||
|
2. 个人端:全新 Context → 真实 UI 登录 → 可见菜单与关键操作、双主题、桌面 / 移动;配置隐藏或权限重定向单列。
|
||||||
|
3. 全局:主题切换与刷新保持、Portal、控制台错误、空数据、校验、失败提示、重复提交、滚动与窄屏溢出;验证受影响共享控件的原回调与请求载荷。
|
||||||
|
|
||||||
|
### 7.3 采集与判定
|
||||||
|
|
||||||
|
- 固定视口(桌面 1920×1000,移动 393×851 和 360×800。360×800 是必测的最小移动视口,专项可增加其他尺寸)、DPR 1、`zh-CN`、`Asia/Shanghai`、`reducedMotion: reduce`、相同数据与状态;用角色、标签、测试标识定位,用条件等待,不依赖固定延时与坐标。
|
||||||
|
- 等待懒加载、骨架屏、提交中状态结束;检查错误消息、控制台、实际路由与无效数值,不能只凭无 pageerror 判定通过。
|
||||||
|
- 只读验收记录所有非 GET `/api/` 请求(应为 0);模拟响应按接口真实结构提供并标注;真实写入只用可清理的测试数据;支付未启用不得写成支付通过。
|
||||||
|
- 定位双字按钮允许 antd 默认字间距,如 `getByRole('button', { name: /^(?:loadings+)?保s*存$/ })`;虚拟 Select 用可见选项或组合框键盘操作,不点击隐藏的辅助选项。
|
||||||
|
- 像素比较阈值:整页 ≤ 0.5%、组件 ≤ 0.2%(P3 ≤ 2%、P2 ≤ 10%、P1 > 10%),不放宽。`toHaveScreenshot()` 本地基线生成后须不带 update 复跑一次,它不是原型对比证据。
|
||||||
|
|
||||||
|
### 7.4 资源与证据
|
||||||
|
|
||||||
|
- 启动浏览器或构建前检查内存(可用物理 ≥ 2GB、可用提交 ≥ 2.5GB);浏览器同时只开一个,重任务串行;运行中可用内存低于 700MB 立即停止本任务进程;不结束他人进程。
|
||||||
|
- 构建输出到系统临时目录,不覆盖 `dist/`,Node 堆约 2944MB。esbuild 预构建内存不足时可设 `GOMAXPROCS=2`、`GOGC=25`、`GOMEMLIMIT=1200MiB`。
|
||||||
|
- 截图、trace、video、storageState、报告只写 Git 忽略目录(`report/`、`logs/`、`e2e/`、`test-results/`、`playwright-report/`)。
|
||||||
|
|
||||||
|
### 7.5 交付说明
|
||||||
|
|
||||||
|
包含 UI 范围、组件映射、差异清单(规范例外 / 业务差异 / 回归)、真实与模拟验证结果、未覆盖状态、风险;同步 `docs/CHANGELOG.md` 与受影响规范。未验证的真实保存与像素对齐不得写成通过。
|
||||||
|
|
||||||
|
## 8. 禁止事项
|
||||||
|
|
||||||
|
通用禁止事项见 `AGENTS.md` 第 8 节。外壳与验收另外禁止:
|
||||||
|
|
||||||
|
- 用浏览器遍历页面猜测原型,或把其他页面截图当作本页参考。
|
||||||
|
- 为匹配截图删除宿主导航、隐藏正文、裁剪校验信息或固定整页宽度。
|
||||||
|
- 在原本没有面包屑的页面新增导航,或在页面中自写标题区与内容边距。
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 密钥管理 UI 规范(/user-center/key-management)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.2
|
||||||
|
|
||||||
|
个人密钥管理页的规范:列表、模型抽屉、创建 / 编辑抽屉。通用样式按公共规范,卡片与表格取值与用户中心共用。
|
||||||
|
|
||||||
|
**何时阅读**:修改密钥列表、模型抽屉、创建 / 编辑抽屉时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 路由 | `/user-center/key-management`,旧 `/key-management` 重定向 |
|
||||||
|
| 视图 | `KeyManagement/index.jsx` + `key-management.css`;编辑抽屉由 `EditTokenModal presentation='drawer'` 渲染 |
|
||||||
|
| 业务 | `useTokensData` 负责后端查询与分页;`buildTokenPayload`、启停与删除确认不变 |
|
||||||
|
| 列表 | 固定列宽,默认每页 10 条;列设置不持久化 |
|
||||||
|
| 抽屉 | 模型列表 440px;创建 / 编辑 560px(移动 100%) |
|
||||||
|
| 外壳 | 页头与边距按 `GLOBAL_UI_BASELINE.md` 4.4 |
|
||||||
|
|
||||||
|
**相关代码**:`src/pages/KeyManagement/`、`src/components/table/tokens/modals/`、`src/hooks/tokens/useTokensData.jsx`
|
||||||
|
|
||||||
|
## 1. 文件与职责
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `src/pages/KeyManagement/index.jsx` | 页头、查询、列表、模型抽屉 |
|
||||||
|
| `src/pages/KeyManagement/key-management.css` | 页面作用域样式与 `--km-*` 变量 |
|
||||||
|
| `src/components/table/tokens/modals/EditTokenDrawer.jsx` | 创建 / 编辑抽屉视图 |
|
||||||
|
| `src/components/table/tokens/modals/EditTokenModal.jsx` | 状态、`formApi`、`submit`、`buildTokenPayload`;`presentation='drawer'` 时渲染抽屉 |
|
||||||
|
| `src/hooks/tokens/useTokensData.jsx` | 列表、搜索、分页、启停、删除 |
|
||||||
|
|
||||||
|
独立路由形态(`.km-page-standalone`)只补顶栏偏移(桌面 100px、移动 80px)。
|
||||||
|
|
||||||
|
## 2. 页面规则
|
||||||
|
|
||||||
|
| 区域 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页头 | `UserCenterPageHeader`;“新手教程 / 查看操作指引”图标按钮保留在右侧 |
|
||||||
|
| 查询卡 | 保留单输入框,匹配密钥名称、Key 或分组。输入防抖,点击搜索或按回车立即提交,重置取消待提交条件并回到普通列表第 1 页 |
|
||||||
|
| 列表 | `Table size='middle' tableLayout='fixed'`,列宽 150 / 300 / 150 / 100 / 180 / 100 / 100 / 130;默认每页 10 条;列设置用 `ColumnSettings`,不持久化 |
|
||||||
|
| 状态 | `TableStatusSwitch`(`onChange` 仍走原 `Modal.confirm` → `manageToken`);已过期 / 已耗尽另显示语义 `Tag` |
|
||||||
|
| 分组 | `TableGroupTags` + `Tooltip`,颜色按组件公共规范;额度为 `Tag color='success'` |
|
||||||
|
| 密钥 | `<code>` 密钥框(底 `#f4f6f9`、描边 `#e4e9ee`,深色引用 `--surface-bg-base` / `--border-subtle`)+ 显示、隐藏、复制图标按钮 + `Tooltip`;脱敏提示 `Alert type='success'` |
|
||||||
|
| 模型抽屉 | 440px;正文 20px;卡片间 18px;信息卡 16px(标签 12 / 18px);分类头 45px(底 `#f6f8fa`);模型名高 28px(等宽 12px、底 `#fafafa`);行距 9.5px、列距 8px;面板描边 `#e4e9ef` |
|
||||||
|
| 编辑抽屉 | 560px(移动 100%);适配 `Form requiredMark={false}`;过期快捷 `Button` 组(间距 5px、描边 `#d9dfe6`、无按钮阴影,`aria-pressed`);仅“自定义”显示 `DatePicker showTime`;高级设置 `Collapse`(`forceRender`)+ `Switch` + `Divider`;页脚按钮间距 10px |
|
||||||
|
|
||||||
|
日期面板语言由 `UiThemeProvider` 同步 dayjs locale。
|
||||||
|
|
||||||
|
## 3. 保留功能与已知差异
|
||||||
|
|
||||||
|
- 默认名称 `claudeNN`、过去日期禁用为业务默认。
|
||||||
|
- 普通列表通过 `/api/token/` 服务端分页。个人搜索接口当前不支持单条件同时匹配名称、Key 和分组,也不提供分页结果;为保持原有条件,搜索复用个人列表接口取全后本地匹配和分页,不调用控制台管理接口。未取全时不展示部分搜索结果。
|
||||||
|
- 技能注入关闭时“绑定技能”字段仅隐藏,仍注册在表单中,载荷不变。
|
||||||
|
- 模型抽屉不显示来源说明行;“自定义”过期选项选中时仅文字变主色。
|
||||||
|
- 第三方新手引导(Joyride)沿用其自身配色配置。
|
||||||
|
|
||||||
|
## 4. 验收要点
|
||||||
|
|
||||||
|
- 浅深主题 × 桌面 / 移动:列表启用与禁用、密钥显隐与复制、模型抽屉、创建与编辑抽屉、模型限制下拉、过期时间面板。
|
||||||
|
- 改动前后请求序列(加载 → 模型抽屉 → 编辑 → 创建)一致;真实增删改只使用可清理的测试密钥。
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# 模型超市 UI 规范(/market)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.5
|
||||||
|
|
||||||
|
个人端模型超市 `/market` 的规范。本页为独立视觉页面,组件映射优先于公共规范。
|
||||||
|
|
||||||
|
**何时阅读**:修改模型超市页面、筛选、卡片或详情抽屉时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 范围 | `/market` 与详情抽屉;`/pricing` 重定向到此 |
|
||||||
|
| 代码 | 视图在 `model-pricing/{market,filter,modal}/`;数据与计价只来自 hooks / helpers |
|
||||||
|
| 主题 | `useMarketThemeStyle()` 注入 `--mm-*`;原型色只写在 `.mm-theme` 变量块 |
|
||||||
|
| 布局 | Hero 235px、顶部横向筛选卡、整页滚动、按可用宽度自适应 1–4 列 |
|
||||||
|
| 业务 | `/api/pricing`、筛选、计价、懒渲染、详情与复制回调不变;搜索防抖 300ms |
|
||||||
|
|
||||||
|
**相关代码**:`src/components/table/model-pricing/`、`src/hooks/model-pricing/`
|
||||||
|
|
||||||
|
## 1. 范围与依据
|
||||||
|
|
||||||
|
- 视觉依据:2026-11-13 本地原型 `微元算力-MaaS平台原型付-20261113/index.html` 顶栏“模型超市”与用户提供的筛选展开截图;新版横向筛选和整页滚动替代旧在线原型的侧栏布局。只作视觉依据,不作业务、数据、接口、路由依据。
|
||||||
|
- 仅覆盖个人端;企业端登录流程不在本页范围。
|
||||||
|
- 开发地址取 `dev.log` 最后一个 `Local:` 拼接 `/market`,不写死 IP 或端口。
|
||||||
|
|
||||||
|
## 2. 文件与职责
|
||||||
|
|
||||||
|
| 文件(相对 `src/components/table/model-pricing/`) | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `layout/PricingPage.jsx` | 路由入口(不改) |
|
||||||
|
| `market/ModelMarketPage.jsx` | 页面编排:调用 `useModelPricingData`、`usePricingFilterCounts`,组合 Hero、顶部筛选卡、目录、详情 |
|
||||||
|
| `market/MarketHero.jsx` | 标题、副标题、搜索条(300ms 防抖;搜索按钮与回车立即写入;重置)、线路背景 |
|
||||||
|
| `market/MarketFilterSidebar.jsx`、`MarketFilterGroup.jsx` | 顶部筛选 `Card` 与可换行 `Button` 组;保留原组件文件名,厂商常驻,其余条件通过“展开更多 / 收起筛选”控制 |
|
||||||
|
| `filter/Pricing{Groups,Vendors,QuotaTypes,Tags,EndpointTypes}.jsx` | 各筛选组的选项、计数与禁用规则 |
|
||||||
|
| `market/MarketCatalog.jsx`、`MarketModelCard.jsx` | 结果栏、按厂商分区、懒渲染、卡片、空态、加载、企业作用域提示 |
|
||||||
|
| `market/MarketLogo.jsx` | 图标框(模型图标 → 厂商图标 → 名称缩写) |
|
||||||
|
| `modal/ModelDetailSideSheet.jsx`、`modal/components/*` | 详情抽屉:头部、基本信息、API 端点、分组价格表 |
|
||||||
|
| `market/market.css`、`market/marketTheme.js` | 页面作用域样式与 `--mm-*` 变量 |
|
||||||
|
|
||||||
|
`src/assets/prototype/market-hero-art.svg` 为原型提取的 Hero 线路图,文件头注明来源。
|
||||||
|
|
||||||
|
## 3. 组件映射
|
||||||
|
|
||||||
|
本页为独立视觉页面,以下映射优先于公共规范;未列出的组件按 `UI_COMPONENT_STANDARDS.md` 执行。
|
||||||
|
|
||||||
|
| 区域 | 写法 |
|
||||||
|
| --- | --- |
|
||||||
|
| 搜索 | `Input`(`allowClear`、前缀图标)+ `Button`(重置 / 搜索 primary) |
|
||||||
|
| 筛选 | `Card` 位于结果栏下方、厂商分区上方;仅展示厂商、计费、端点三组可换行 `Button`(`aria-pressed`),隐藏用户分组与模型标签筛选行;不显示计数;“disabled 或计数为 0”时禁用 |
|
||||||
|
| 筛选展开 | 默认仅显示厂商行;卡头保留重置与“展开更多 / 收起筛选”`Button`,同步 `aria-expanded` / `aria-controls`,收起不清空条件;装饰品牌图标设 `aria-hidden` |
|
||||||
|
| 分区标题 | `.mm-section-title`:图标框 + h2 + “N 款模型” |
|
||||||
|
| 卡片 | `Card`(`role=button`,Enter / Space 打开);价格格、缓存行、页脚分组与折扣 `Tag`、复制 `Button` + `Tooltip` |
|
||||||
|
| 加载 | `Card loading` |
|
||||||
|
| 空态 | `.mm-empty`:标题 + 说明 +“重置筛选”`Button` |
|
||||||
|
| 企业作用域 | `Alert type='warning'` |
|
||||||
|
| 详情 | `Drawer`(820px,窄屏 100%,标题“模型详情”,页脚 primary“关闭”);`Typography.Title copyable`,复制提示沿用原文案 |
|
||||||
|
| 端点 | `.mm-detail-endpoint` + `Tag` |
|
||||||
|
| 价格表 | `Table size='small'`、`pagination={false}`、`scroll={{ x: 'max-content' }}`,列宽 180 / 135 |
|
||||||
|
| 图片预览 | `Image` 受控预览(保留 `modalImageUrl` / `isModalOpenurl`) |
|
||||||
|
|
||||||
|
“重置”“重置筛选”复用原 `resetPricingFilters`,只传搜索与五类筛选 setter,不传货币、单位、视图 setter;全部断点的更多条件展开复用原 `showSettings`;厂商选项只列有模型的厂商,按名称排序。
|
||||||
|
|
||||||
|
## 4. 主题变量
|
||||||
|
|
||||||
|
抽屉 Portal 用 `rootClassName='mm-detail-drawer mm-theme'` + `rootStyle` 使用同一组变量。`--mm-*` 只在 `.mm-theme` 与 `html.dark .mm-theme` 中定义:
|
||||||
|
|
||||||
|
| 变量 | 浅色 | 深色 | 用途 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `--mm-page-bg` | `#f4f6f9` | `#111720` | 页面底色 |
|
||||||
|
| `--mm-surface` | `#ffffff` | `#1b232e` | 筛选卡、模型卡片、空态 |
|
||||||
|
| `--mm-muted` | `#616e80` | `#acb6c5` | 次要文字 |
|
||||||
|
| `--mm-tint` | `#fff3dc` | `#3c2e1d` | 选中筛选、折扣标签底 |
|
||||||
|
| `--mm-soft` | `#fafbfc` | `#202732` | 端点卡底 |
|
||||||
|
| `--mm-title` | `#302c24` | `#f3e6ce` | Hero 标题 |
|
||||||
|
| `--mm-subtitle` | `#68685f` | `#beb7ac` | Hero 副标题 |
|
||||||
|
| `--mm-art` | `#a7722d` | `#deb572` | 线路背景网格色 |
|
||||||
|
| `--mm-card-hover-*` | 边框 `#cb923b` + 暖色阴影 | 同边框 + 深色阴影 | 卡片悬停 / 聚焦 |
|
||||||
|
| `--mm-price-extra` | `#3778b8` | `#8cb9e6` | 详情表缓存类价格 |
|
||||||
|
| `--mm-mask` | `rgba(0,0,0,.3)` + 4px 模糊 | 同左 | 详情抽屉遮罩 |
|
||||||
|
|
||||||
|
筛选卡使用 `--mm-filter-shadow`,深色为 `none`;搜索条改为不透明背景与实线边框;背景通过 `--mm-art-mask` 渐隐。仅在原型同样使用 `!important` 的四条规则中保留(选中筛选项、搜索框阴影、卡片悬停边框、详情表格内边距)。
|
||||||
|
|
||||||
|
## 5. 布局与尺寸(1920×1000 / 393×851)
|
||||||
|
|
||||||
|
- 应用壳:`.mm-page` 最小高为视口减公告占位,顶部内边距等于顶栏高度;由宿主页面整页滚动,`.mm-scroll` 不再建立独立滚动区;厂商分区以浏览器视口 + 200px 余量保持懒渲染。
|
||||||
|
- Hero:最小高 235px,上下内边距 28px(≤ 600 为 22px),横向遵循 `GLOBAL_UI_BASELINE.md` 第 5 节;间距 24px(≤ 600 为 18px);线路背景固定在顶栏与公告下方、高 250px、底部遮罩渐隐;标题 34px / 650 / 字距 1px(≤ 850 为 30px,≤ 600 为 24px),副标题 14px。
|
||||||
|
- 搜索条:宽 `min(720px, 100%)`,内边距 8px,圆角 12px,不透明底、无背景模糊;输入框与按钮高 40px(≤ 600 为 36px),按钮横向内边距 18px。
|
||||||
|
- 工作区:横向内边距与最大宽度遵循 `GLOBAL_UI_BASELINE.md` 第 5 节;上下内边距 18px / 24px,≤ 1180 为 18px / 20px,≤ 600 为 10px / 14px。
|
||||||
|
- 筛选卡:满内容宽度、底部间距 14px,内边距 14px 18px 10px;卡头标题 15px、副标题 12px,底部 11px + 分隔线;≤ 600 内边距 12px 12px 8px,卡头允许换行,副标题 11px。
|
||||||
|
- 筛选组:两列网格 `72px minmax(0, 1fr)`、间距 12px、内边距 10px 0 5px;标签 12px / 500 / 行高 30px;按钮最小高 28px、内边距 3px 9px、12px、圆角 6px、间距 6px;选中为主色边框 + `--mm-tint` 底 + 600 字重。≤ 600 标签列 66px、间距 7px、按钮最小高 29px、11px。
|
||||||
|
- 结果栏:最小高 45px、底距 10px,标题 18px,计数与价格单位 13px;≤ 850 隐藏价格单位,≤ 600 最小高 38px、底距 6px。
|
||||||
|
- 网格:`repeat(auto-fill, minmax(min(100%, 320px), 1fr))`,按目录实际宽度形成 1–4 列;不足 320px 时单列填满可用宽度,保留正常字号;筛选后只有少量结果时保留空列,避免卡片横向拉伸。间距 16px(≤ 850 为 12px,≤ 600 为 14px);分区标题 20px / 650,分区间距 25px。
|
||||||
|
- 卡片:圆角 12px,内边距 18px 18px 0;图标框 36px,模型名 16px / 600;价格 21px(≤ 850 为 19,≤ 600 为 24),划线官方价 12px;缓存区最小高 57px;页脚 12px。
|
||||||
|
- 详情抽屉:正文内边距 24px;模型图标 46px、名称 21px;分区上分隔线、上下 24px;端点卡内边距 14px 16px;表格单元 13px 12px。
|
||||||
|
|
||||||
|
## 6. 动效与未定义项
|
||||||
|
|
||||||
|
- 卡片悬停 / 聚焦上浮 3px、暖色阴影、指针光晕、一次扫光;`:focus-visible` 2px 主色内描边。Hero 信号线 14s 流动、核心图形 8s 呼吸。`prefers-reduced-motion: reduce` 时取消位移与动画,信号线降为 25% 静态。
|
||||||
|
- 筛选条件与目录共用宿主滚动区,不再显示侧栏或目录内部滚动条。
|
||||||
|
- 原型未定义的状态(加载、失败、空目录、隐藏价格、企业作用域、等级锁定)按 `GLOBAL_UI_BASELINE.md` 第 5 节处理。
|
||||||
|
- 不虚构原型元素:详情表“操作”列、未上架厂商、示例额外分组不渲染。
|
||||||
|
- 保留差异:控件正文色沿用全局 `colorText`;按钮图标走 `ActionIcons`,装饰图标用 `lucide-react`。
|
||||||
|
|
||||||
|
## 7. 禁止事项
|
||||||
|
|
||||||
|
- 修改 `/api/pricing` 请求、载荷、筛选与计价、懒渲染、详情开关、复制提示、路由与权限。
|
||||||
|
- 新增排序、分页、导出等原型业务;恢复旧版渐变标题、光斑、点阵、水印、色条或玻璃吸顶栏。
|
||||||
|
|
||||||
|
## 8. 验收要点
|
||||||
|
|
||||||
|
- 搜索仅对 `model_name` 做不区分大小写的子串匹配,忽略关键词首尾空格;描述、标签、厂商名称不参与关键词匹配,其他筛选条件仍取交集;保留原前端防抖,不新增搜索请求。
|
||||||
|
- 视口 1920×1000 与 393×851,浅深主题;交互序列:默认厂商行 → 展开三组条件,确认用户分组与模型标签不显示 → 选择计费或端点 → 收起仍保持筛选与价格 → 重置 → 悬停卡片 → 键盘聚焦卡片 → 关键词搜索 → 选择厂商 → 空结果 → 整页滚动到底与厂商懒渲染 → 打开详情。
|
||||||
|
- 响应式补充 3840×2160、2560×1440、1920×1080、中屏及断点两侧、360×800;检查两侧留白、卡片宽度、正文换行、无横向溢出,以及筛选展开和详情在窄屏上的可达性。
|
||||||
|
- 与原型比较时使用同构模拟目录并标注;真实后端另行验证;整页 ≤ 0.5%、组件 ≤ 0.2%。
|
||||||
|
- 本地截图回归断言非 GET `/api/` 请求为 0。
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# 企业中心 UI 规范(/org/\*)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
|
||||||
|
|
||||||
|
企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。
|
||||||
|
|
||||||
|
**何时阅读**:修改企业中心目标页、Org 通用组件或 `org-center.css` 时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 范围 | 工作台、数据看板、员工管理、项目管理、预算中心、审批中心、令牌管理(原“密钥管理”)、企业充值、消耗明细、审计日志、个人设置、企业设置;“我的 AI 能力”不改;“组织架构”页面名称统一为“部门管理”(与权限目录一致,2026-11-23);“角色管理”为统一权限体系新增页面(2026-11-23) |
|
||||||
|
| 样式 | `org-center.css`,作用域 `.org-center .oc-page`,颜色只写 `--oc-*`(第 2 节) |
|
||||||
|
| 组件变体 | 紧凑表格、3 列筛选、无图标行操作、`.oc-list-tabs`、无边框标签(第 3 节) |
|
||||||
|
| 弹层 | `OrgModal` / `OrgSideSheet`,原型风格遮罩;密钥抽屉 560px |
|
||||||
|
| 面包屑 | 分组登记在 `OrgBreadcrumb` 的 `orgPageGroups` |
|
||||||
|
| 消耗明细 | 绘图与视频、预览视频、成员排行规则见第 5 节 |
|
||||||
|
|
||||||
|
**相关代码**:`src/pages/Organization/`、`src/styles/org-center.css`、`src/styles/org-page.css`
|
||||||
|
|
||||||
|
## 1. 范围与依据
|
||||||
|
|
||||||
|
- 视觉依据:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(深色用“切换至暗色主题”),只作视觉依据,不作业务、路由、数据依据。
|
||||||
|
- 只对齐背景、字体、图标、表格、表单、卡片、页签、搜索条件、操作列、弹窗、按钮、颜色、文字、间距与已有交互反馈;不改请求、载荷、状态、路由、权限与触发条件。
|
||||||
|
- 原型有而系统无的功能不补建:CSV 导出、在职 / 离职页签、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。
|
||||||
|
|
||||||
|
## 2. 作用域与变量
|
||||||
|
|
||||||
|
- 目标页根节点同时带 `.uc-page` 与 `.oc-page`;页面类 `.oc-workbench`、`.oc-dashboard`、`.oc-recharge`、`.oc-personal-settings`、`.oc-company-settings`、`.oc-expenses`;Portal 弹层用 `.oc-dialog`、`.oc-key-drawer`。
|
||||||
|
- 颜色只写在变量中,规则只引用变量;浅色为原型实测,深色写在 `html.dark` 下。
|
||||||
|
|
||||||
|
| 变量 | 浅色 | 深色 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `--oc-text` | `--text-primary` | `--text-primary` | 正文 |
|
||||||
|
| `--oc-muted` | `--text-secondary` | `--text-secondary` | 次文字 |
|
||||||
|
| `--oc-border` | `--border-subtle` | `--border-subtle` | 分隔线 |
|
||||||
|
| `--oc-soft` | `#fafbfc` | `#202732` | 浅底 |
|
||||||
|
| `--oc-brand` | `#b96508` | `#f2ad41` | 页签、强调(antd 主色仍由 `UiThemeProvider` 决定) |
|
||||||
|
| `--oc-page-bg` | `#f8fafc` | `--surface-bg-base` | 页面底 |
|
||||||
|
| `--oc-card-shadow` | `0 3px 18px #25354a03` | 同左 | 列表卡阴影 |
|
||||||
|
|
||||||
|
- 标签统一无边框(新代码 `variant='filled'`,等价于已弃用的 `bordered={false}`);非 antd 预设色(如 `amber`、`violet`)改用 `gold` / `purple`。
|
||||||
|
- 消耗明细页根节点由 `useOrgLogsThemeStyle()` 注入 `--oc-brand`(浅色与自定义主色跟随 `colorPrimary`,默认暗色为 `#f2ad41`)、`--oc-stat-brand-bg`(品牌色 6.3% `color-mix`)与 `--ur-progress-done`。
|
||||||
|
- 新增样式用 `:where()` 包裹作用域祖先,不使用 `!important`。
|
||||||
|
|
||||||
|
## 3. 页头与通用块
|
||||||
|
|
||||||
|
通用卡片、筛选栏、表格、分页、弹层、页签、标签样式按 `UI_COMPONENT_STANDARDS.md`;企业中心的差异如下。
|
||||||
|
|
||||||
|
- **页头**:`OrgPageHeader`(内部复用 `UserCenterPageHeader`),规格见 `GLOBAL_UI_BASELINE.md` 4.4;页头不放操作按钮,操作移入列表卡头。面包屑分组见 4.4 第 3 条。
|
||||||
|
- **列表卡 `OrgListCard`**:卡头与表格间距 20px;表格为紧凑变体(正文 13px,表头 12px / 500、底色 `--oc-soft`,行上下内边距 17px);分页按公共组件规范,覆盖页签及表格明细。
|
||||||
|
- **筛选卡 `OrgFilterCard`**:默认 3 列。提示词记录和消耗明细的筛选区沿用个人消费记录的布局。筛选取值与生效时机沿用原页面(审计日志为“选择即筛选”,“搜索”以当前条件重新查询)。
|
||||||
|
- **行操作 `OrgRowActions`**:link 按钮 13 / 24px、无内边距、间距 10px,不带图标。
|
||||||
|
- **列表页签 `.oc-list-tabs`**:导航高 44px,页签内边距 12px 0,选中与悬停色为 `--oc-brand`;只切换筛选时加 `.oc-tabs-nav-only`。
|
||||||
|
- **标签**:表格与卡片内标签统一无边框(`variant='filled'`);非 antd 预设色改用 `gold` / `purple`。
|
||||||
|
- **启停开关**:密钥、员工调原处理函数;项目禁用沿用确认 + DELETE、启用复用编辑 PUT;预算复用编辑 PUT 并透传主体、原始额度、周期、自定义天数与超限动作,主体已删除时禁用开关。
|
||||||
|
- **弹层**:`OrgModal` / `OrgSideSheet` 使用原型风格遮罩(`--oc-mask-bg` `rgba(0,0,0,.3)` + `--oc-mask-blur` 4px),只作用于企业中心目标页;表单竖排、`requiredMark={false}`,字段说明用 `extra`。
|
||||||
|
- **企业密钥抽屉 `OrgKeyForm`**:560px;字段为名称、归属项目、密钥分组、过期时间(`Radio.Group.oc-key-expiry`:间距 6px、圆角 6px、描边 `#d9dfe6`,仅“自定义”显示日期选择)与 `Collapse` 高级设置(额度设置 + `Divider` + 访问限制);`expiryPreset` 只用于视图,取值仍走 `setExpiredTime`。
|
||||||
|
|
||||||
|
## 4. 页面规则
|
||||||
|
|
||||||
|
| 页面 | 系统实现 | 保留差异 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 工作台 | `OrgHero` 标签化身份与 `oc-wb-*` 卡片(额度、密钥、用量、最近申请);横幅 `.ew-hero` 背景只在 `.org-workbench` 作用域 | 额度周期标签放在重置卡;最近申请无分页 |
|
||||||
|
| 数据看板 | `oc-dash-*` hero(健康提示“企业运行正常”、企业名、企业额度、组织概况)+ `OrgAnalyticsPanel`(汇总条、趋势 `Segmented`、分布、明细页签) | 时间范围 7 / 30 / 90 天;企业名来自 `orgInfo.name`,无值时隐藏 |
|
||||||
|
| 员工管理 | 筛选卡(关键字、分组、组织、状态,服务端筛选)+ 单张列表卡,不分页签;备注独立列;状态 `Switch`;新建 / 编辑用抽屉 | 无在职 / 离职页签 |
|
||||||
|
| 项目管理 | `OrgListCard` + link 操作(模型 / 分组 / 成员 / 密钥 / 编辑);状态开关 | 操作列不再显示“停用” |
|
||||||
|
| 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 已加载数据前端分页 |
|
||||||
|
| 审批中心 | 状态页签(回调 `setStatusFilter`)+ 申请列表卡;拒绝弹窗竖排表单项 | — |
|
||||||
|
| Agent 任务审计 | 保留页头状态筛选、任务元数据 / 待对账 / 安全策略三个页签。记录按卡片排列,任务状态和计费状态使用独立标签,弹窗使用 `OrgModal` | 正文必须填写有效审计原因并经二次确认。页签计数、操作和焦点使用系统品牌色,状态标签使用语义色。窄屏按单列排列卡片,长编号换行 |
|
||||||
|
| 密钥管理 | 密钥框 + 显隐 / 复制、可用模型 link、分组列、状态开关、绝对时间;列设置用共享组件;创建 / 编辑为 560px `OrgSideSheet` | 列设置只在当前页面生效;非操作列整体横向滚动,仅在可见列宽度超过容器时显示滚动条 |
|
||||||
|
| 企业充值 | 企业钱包 + 充值工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录;订单“立即充值”与支付方式点击同为 `handlePreTopUp` | 档位与折扣来自后台配置;无订单号搜索与发票入口 |
|
||||||
|
| 消耗明细 | 统计卡 + 页签(明细日志 / 成员排行 / 绘图与视频)+ 消费记录样式筛选卡 + 列表卡;查询按钮为“搜索”(`handleSearch`) | 见第 5 节 |
|
||||||
|
| 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡;“提示词记录”页签沿用原显隐,筛选区参考消费记录;说明条上下与筛选卡至列表卡均间隔 18px | — |
|
||||||
|
| 个人设置 | 复用用户中心 `ui-personal-*`、`AvatarSection`、`SectionHeader`;三页签:头像设置 / 个人资料 / 通知设置;企业身份并入资料头 | 昵称在弹窗中修改 |
|
||||||
|
| 企业设置 | 设置卡内页签 + 区块头(刷新 / 保存设置);复制为 14px 无内边距图标按钮 | 保留“数据安全”“危险区域”页签 |
|
||||||
|
|
||||||
|
数据看板补充:
|
||||||
|
|
||||||
|
- 剩余额度提示按未取整占比判定:> 20% 为“可用额度充足”(`#438568`),0 < 占比 ≤ 20% 为“可用额度偏低”(`#9c6b25`),≤ 0 为“可用额度已用尽”(`#b34c4c`);数据无效时隐藏,仅作提示,不影响计费或拦截。
|
||||||
|
- 多维用量分析工具组用原生 `Select` / `Button`:维度 132px、时间 86px、刷新 34px,高 34px、间距 8px。
|
||||||
|
- 模型明细使用已加载数据做前端分页(默认每页 10 条),翻页不请求接口,维度、时间或数据变化时回到第一页;表格随页面自然展开,仅窄屏横向滚动。
|
||||||
|
|
||||||
|
## 5. 消耗明细(/org/logs)
|
||||||
|
|
||||||
|
- 三个页签和审计日志下的提示词记录共用个人消费记录的筛选布局:桌面五列,时间范围跨两列;窄屏三列,移动端单列并默认收起。操作区位于右下,“重置”在前,“搜索”在后,点击和回车共用提交入口。
|
||||||
|
- 绘图与视频由 `components/OrgTaskRecords.jsx` 呈现,复用 `useTaskLogsData({ organizationMode: true })`、`TaskLogsFilters`、`getTaskLogsColumns`、`exportTaskLogsPageCsv`、`ColumnSelectorModal`、`ContentModal`;结构为筛选卡 + “任务记录”列表卡(导出本页 / 刷新 / 列设置),不渲染“本页统计”区块。
|
||||||
|
- 任务表列宽 185 / 185 / 110 / 110 / 250 / 330 / 110 / 155 / 145 / 150;模型为行内胶囊,费用主色右对齐;分页沿用公共规范。“刷新”与“搜索”调用同一 `refresh`。
|
||||||
|
- 时间范围为本页签自有的可编辑字段(默认最近 7 天,含快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示。
|
||||||
|
- 末列“操作”不固定:视频任务显示“点击预览视频”,失败任务保留失败原因查看,其余显示“-”。
|
||||||
|
- 预览视频沿用 `ContentModal`:标题栏“视频预览”与关闭按钮、16:9 播放区、加载态、播放失败或无地址时 `Empty` 空态、页脚复制链接 / 新标签页打开 / 关闭;关闭时暂停视频,重开同一视频不残留加载指示。
|
||||||
|
- 只有具备排行权限并打开「成员排行」时才查询榜单。首次打开使用已生效的成员、模型和时间范围,默认每页 10 人。翻页和更改每页人数均携带服务端返回的 `snapshot`。搜索、重置、刷新及切换企业会重新查询当前条件下的榜单。快照过期时自动按原筛选和页容量回到第 1 页重取一次。
|
||||||
|
- 服务端按成员汇总后按消耗额度降序排列,同额按成员 ID 升序。行键使用 `user_id`,名次按返回页码、页容量和行号连续计算。前三名使用当前主题的强调色及三档底色,其余名次使用中性色。
|
||||||
|
- 明细日志查询不写 URL;绘图与视频筛选沿用原有 URL 同步。
|
||||||
|
- 保留差异:明细日志无列设置、分组列、操作列;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。
|
||||||
|
|
||||||
|
## 6. 验收要点
|
||||||
|
|
||||||
|
- 登录走真实 UI:状态 A(企业名 +“下一步”)与状态 B(记忆企业后的登录名 + 密码),凭据经 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS` 传入,结束时 UI 退出。
|
||||||
|
- 1920×1080 与移动 393×851、浅深主题;只读验收非 GET `/api/` 请求为 0;未开放的接口以同构模拟数据验证并标注。
|
||||||
|
- 像素比较阈值见 `GLOBAL_UI_BASELINE.md` 7.3;整页因真实数据不同只作参考,组件按两侧对应类名裁剪比较。
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# 服务监控 UI 规范(/user-center/service-dashboard)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-19 · 版本:v2.3
|
||||||
|
|
||||||
|
服务监控页的规范:分组可用性、历史条与详情弹窗。
|
||||||
|
|
||||||
|
**何时阅读**:修改服务监控页面、分组卡、历史条或详情弹窗时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 路由 | `/user-center/service-dashboard`,旧 `/service-dashboard` 重定向;桌面侧栏、移动底栏和页面访问统一受超管“运营设置 → 左侧边栏模块管理 → 用户中心 → 服务监控”开关(`SidebarModulesAdmin.userCenter.serviceDashboard`)及区域 / 功能可见分组控制;关闭或无分组权限时不挂载页面,回到首个可见页面,无可用页面时回到首页;未配置时沿用默认开启 |
|
||||||
|
| 组件 | `Card`、`Button`、详情 `Modal` + `Statistic` + `Table`、`Tooltip`、`Spin` / `Empty` |
|
||||||
|
| 主题 | `theme.useToken()` 注入 `--service-*`;正常态跟随 `colorPrimary`,告警 / 异常用 `colorWarning` / `colorError` |
|
||||||
|
| 业务 | 60 秒自动刷新、逐秒倒计时、分组权限、模型测试与请求不变 |
|
||||||
|
| 外壳 | 页头与边距按 `GLOBAL_UI_BASELINE.md` 4.4 |
|
||||||
|
|
||||||
|
**相关代码**:`src/pages/ServiceDashboard/`
|
||||||
|
|
||||||
|
## 1. 范围与依据
|
||||||
|
|
||||||
|
- 在线原型没有服务监控页面,视觉依据为已确认的浅色设计稿,不以其他页面截图为参考,不做深色像素验收。
|
||||||
|
- 背景由用户中心宿主提供,页面不使用背景图片。
|
||||||
|
|
||||||
|
## 2. 视觉规则
|
||||||
|
|
||||||
|
- 页头:标题 28px / 650 / 32px,副标题 14px 次文字色,文案“实时查看各分组服务可用性与模型状态”;标题区无图标、星光、绿色渐变与装饰阴影。
|
||||||
|
- 状态色:正常分组色条、图标、可用率、正常历史条、监控状态点与倒计时跟随 `token.colorPrimary`;图标、可用率与监控标记的底色用 `colorPrimaryBg`,边线用 `colorPrimaryBorder`;告警与异常沿用 `colorWarning`、`colorError` 及其背景色。
|
||||||
|
- 历史条:无对应 antd 组件,保留 60 点、6px 条宽、2px 间距;深色缺失点用 `token.colorFillSecondary`,文字用 `token.colorTextSecondary`,容器用 `token.colorBgContainer` 与 `token.colorBorderSecondary`。
|
||||||
|
- 详情弹窗、表格与测试按钮按 `UI_COMPONENT_STANDARDS.md` 执行,Portal 直接继承现有主题。
|
||||||
|
- 桌面状态标记靠右;窄屏历史条在行内横向滚动,刷新信息允许换行。不新增装饰与动效。
|
||||||
|
|
||||||
|
## 3. 验收要点
|
||||||
|
|
||||||
|
- 浅深主题 × 桌面 / 移动:真实页面、倒计时变化、手动刷新、主题切换保持。
|
||||||
|
- 空数据、请求失败、重复点击、告警与异常态使用模拟接口验证,并与真实页面结果分开记录。
|
||||||
|
- 完整截图保留顶栏,不为匹配设计稿删除宿主导航。
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# 技能超市 UI 规范(/skill-market)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.3
|
||||||
|
|
||||||
|
个人端技能超市 `/skill-market` 的规范,含真实接口与本地演示两种数据模式。本页为独立视觉页面。
|
||||||
|
|
||||||
|
**何时阅读**:修改技能超市页面、筛选、卡片、详情抽屉,或切换数据模式时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 数据模式 | 默认真实接口;`VITE_SKILL_MARKET_MOCK=true` 才进入演示(第 1 节) |
|
||||||
|
| 视图 | `SkillMarket/view/*` + `skill-market.css`(`.sm-*`),两种模式共用 |
|
||||||
|
| 筛选 | 范围、多标签“任一匹配”、搜索、分页均在前端完成,先完整加载目录 |
|
||||||
|
| 主题 | `useSkillMarketThemeStyle()` 注入 `--sm-*` |
|
||||||
|
| 布局 | Hero 235px、搜索条 720×58、宽屏侧栏 264px、自适应 1–4 列;≤ 1024 可折叠筛选 |
|
||||||
|
|
||||||
|
**相关代码**:`src/pages/SkillMarket/`
|
||||||
|
|
||||||
|
## 1. 数据模式
|
||||||
|
|
||||||
|
| 模式 | 入口 | 开启方式 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 真实接口 | `LiveSkillMarket.jsx` | 默认,或 `VITE_SKILL_MARKET_MOCK` 不为 `true` | 当前开发与生产环境均为此模式 |
|
||||||
|
| 本地演示 | `MockSkillMarket.jsx` | `VITE_SKILL_MARKET_MOCK=true` 并重启服务 | 数据在 `mockStore.js`,存储键 `skill-market-mock-v1`,只在当前浏览器,与真实账号无关 |
|
||||||
|
|
||||||
|
- 真实模式:`loadMarketCatalog()` 顺序读取 `/api/skills/market` 全部分页(`page_size: 24` + `offset`,不发送 `tag` / `keyword`),由 `queryCatalog()` 本地组合范围、标签与搜索并分页;部分分页失败时显示加载失败,不把不完整目录当全量。
|
||||||
|
- “我的技能”:个人身份取 `/api/user/skills/mine` 中 `enabled === true` 的技能,加入 / 移除调用 `PUT /api/user/skills/mine/:id`(载荷 `{ enabled: boolean }`);企业员工取 `/api/org/skills/mine` 中实际启用的技能,未启用技能的 `POST / DELETE /api/org/skills/requests/:id` 仍是诉求操作,不计入“我的技能”。
|
||||||
|
- 本地演示的新增、编辑、删除、“加入我的技能 / 移除”只在浏览器内完成,不调用技能或企业技能接口;`MockSkillMarket.jsx` 与 `mockStore.js` 可整体移除,不影响真实模式。
|
||||||
|
- 收到“恢复成真实 api 请求”类指令时,只核验当前为真实模式,不回退现有 UI 或其他页面。
|
||||||
|
|
||||||
|
## 2. 组件映射
|
||||||
|
|
||||||
|
本页为独立视觉页面,以下映射优先于公共规范;未列出的组件按 `UI_COMPONENT_STANDARDS.md` 执行。
|
||||||
|
|
||||||
|
| 区域 | 文件 | 写法 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 页面骨架 | `Live/MockSkillMarket.jsx` | `.sm-page.sm-theme` 整屏应用壳:外层不滚动,侧栏与卡片列表各自滚动 |
|
||||||
|
| Hero | `view/SkillMarketHero.jsx` | 线路、点阵、轨道与四个模块装饰(图表 / 文档 / 齿轮为原型 SVG,钥匙为 `skill-market-hero-key.png` 遮罩);`Input allowClear` +“重置”+“搜索”(primary,`htmlType='submit'`) |
|
||||||
|
| 筛选侧栏 | `view/SkillFilterSidebar.jsx` | “筛选 / 重置”;技能范围(全部 / 我的)`Button` + 数量;“标签筛选” `Select mode='multiple'`(可搜索、可清空);“匹配任一已选标签”说明;已选标签可关闭 `Tag` 与“清空标签” |
|
||||||
|
| 结果栏 | `view/SkillCatalog.jsx` | “全部技能 / 我的技能”+ 筛选后数量与已选标签数;页面已有操作放右侧 |
|
||||||
|
| 卡片 | `view/SkillCard.jsx` | `Card`(`role=button`,Enter / Space 打开,指针光晕)、分类图标框、`Tag bordered={false}`、页脚 `v{n}` + 已有操作 |
|
||||||
|
| 状态徽标 | 两种模式 | `Tag` 语义色:`disabled → default`、`inactive → warning`、`enabled → success` |
|
||||||
|
| 加载 | 真实模式 | `Card loading`(8 张) |
|
||||||
|
| 空态 | `view/SkillCatalog.jsx` | `.sm-empty`:标题“没有符合条件的技能”、说明、“重置筛选”;“我的技能”为空时显示专用空态与“浏览全部技能” |
|
||||||
|
| 分页 | 两种模式 | 列表底部居中(`.sm-pager`) |
|
||||||
|
| 详情 | `view/SkillDetailDrawer.jsx` | `Drawer size={620}`(窄屏 100vw),`rootClassName='sm-detail-drawer sm-theme'`;分节:来源 / 企业启用参考 / 标签 / 适用场景 / 触发词 / 更新时间;页脚“关闭”+ 已有操作 |
|
||||||
|
| 企业提示 | 真实模式 | `Alert type='info'`(`.sm-notice`),文案与条件不变 |
|
||||||
|
|
||||||
|
`SkillDetailSideSheet` 仍供技能平台使用,本页不使用。
|
||||||
|
|
||||||
|
## 3. 筛选行为
|
||||||
|
|
||||||
|
- 搜索在点击“搜索”或回车后生效;清空输入立即清除已提交关键词,保留范围与标签。
|
||||||
|
- “重置”“重置筛选”清空搜索与已选标签并回到全部技能;“清空标签”只清标签,保留范围与已提交搜索。
|
||||||
|
- 侧栏“全部 / 我的”数量取未过滤目录,结果数量取当前组合筛选;筛选或翻页后列表回到顶部,页码超出时夹取到有效页。
|
||||||
|
- 本地演示与真实模式行为一致,切换筛选不发请求。
|
||||||
|
|
||||||
|
## 4. 主题与样式
|
||||||
|
|
||||||
|
- 不新增 ConfigProvider、主题状态或存储 key;`--sm-brand = colorPrimary`、`--sm-text = colorText`,页面根与详情 Portal(`rootStyle`)共用。
|
||||||
|
- 许可证徽标使用 antd 预设调色板色:待审核 / 未知决策用 `gold`、通过用 `green`、阻止用 `red`;背景与描边使用默认预设,文字取对应主题调色板第 9 档 token,提高小字号可读性;不使用非预设色名 `amber` 或固定浅色背景。卡片与详情复用同一 `LicenseBadge`。
|
||||||
|
- `.sm-theme` / `html.dark .sm-theme` 变量(浅 / 深):页面底 `#f4f6f9` / `#111720`,面板 `#fff` / `#1b232e`,次要字 `#626f80` / `#aab6c5`,边线 `#e0e5ec` / `#344151`,浅金底 `#fff2dc` / `#3c2f1f`,卡片悬停边 `#c39343`;深色文字型主色 `--sm-accent: #f2ad41`。样式规则只引用变量,无 `!important`。
|
||||||
|
- 侧栏滚动条 6px,悬停或聚焦时显示;卡片列表隐藏滚动条,不写 `scrollbar-width` / `scrollbar-color`。
|
||||||
|
- 动效:卡片悬停上浮 3px + 光晕;Hero 线路 15s 线性循环,模块 10s 漂浮 7px(延时 0 / -5 / -3 / -7s);仅精确指针设备悬停生效,`prefers-reduced-motion` 时全部停用。
|
||||||
|
|
||||||
|
## 5. 布局与尺寸(1920×1080)
|
||||||
|
|
||||||
|
- 页面:上内边距取 `--app-header-height`(桌面 72 / 移动 56),高为视口减公告占位。
|
||||||
|
- Hero:最小高 235px,上下内边距 28px(≤ 600 为 22px),横向遵循 `GLOBAL_UI_BASELINE.md` 第 5 节;间距 24px;标题 34px / 1.4 / 650 / 字距 0.5px;副标题 14px / 1.8、上距 10px;搜索条 720×58、内边距 8px、间距 10px、圆角 12px;输入框与按钮高 40px,按钮左右 18px。
|
||||||
|
- 工作区:横向内边距与最大宽度遵循 `GLOBAL_UI_BASELINE.md` 第 5 节;上下内边距 20px / 24px、间距 22px;侧栏 264px、内边距 12px 22px 12px 18px、圆角 12px;结果栏最小高 45px、下距 12px。
|
||||||
|
- 网格:`repeat(auto-fill, minmax(min(100%, 300px), 1fr))`,按扣除侧栏后的可用宽度形成 1–4 列;不足 300px 时单列填满可用宽度;筛选结果少时保留空列,不将单张卡片拉满整行;间距 16px,≤ 850 为 12px、≤ 600 为 14px。长标题和连续英文描述按词或必要时按字符换行,保留标题两行、描述三行摘要与完整详情。
|
||||||
|
- 卡片:圆角 12px,正文内边距 20px 18px 0;图标框 40px + 12px 间距;标题 16px / 1.35 / 600,来源 12 / 16px;描述 13px / 1.9、3 行、最小高 74px;标签 11 / 22px、圆角 5px;页脚按钮高 32px、字号 12px。
|
||||||
|
- 详情抽屉:正文内边距 24px,页脚 8px 16px;描述 14px / 1.95;分节上边线 + 22px;小标题 15px / 700;标签 12 / 20px;遮罩 `rgba(0,0,0,.3)` + `blur(4px)`。
|
||||||
|
- 断点:1540(侧栏 248)、1180(侧栏 230、上下内边距 18px / 20px、间距 18px)、1024(“筛选 / 收起筛选”控制整行侧栏,展开后最大高为工作区 45%,目录保持可滚动)、850(上下内边距 16px、卡片紧凑、隐藏两个小模块)、600(上下内边距 10px / 14px、移动端控件和卡片排版)。筛选展开状态与已选条件沿用原逻辑。
|
||||||
|
|
||||||
|
## 6. 已知差异
|
||||||
|
|
||||||
|
- 控件与卡片正文色沿用全局 `colorText`;侧栏滚动条槽 6px(原型 10px),以内边距补偿内容宽度。
|
||||||
|
- 分类显示名沿用 `constants/skillCategories.js`;本地演示每页 24 条。
|
||||||
|
- 本地演示卡片保留“企业状态”徽标与“编辑 / 删除”;真实模式不新增这两类操作,管理员“管理”与企业治理按钮条件不变。
|
||||||
|
|
||||||
|
## 7. 验收要点
|
||||||
|
|
||||||
|
- 1920×1080 与移动端、浅深主题:默认、悬停卡片、搜索框聚焦、标签选择、重置、空结果、详情、列表底部;本地演示另验证分页、加入 / 移除、新增校验、编辑与删除确认。
|
||||||
|
- 响应式补充 3840×2160、2560×1440、中屏及 1024px 断点两侧、360×800;检查两侧留白、卡片最小宽度、长内容换行、无横向溢出,以及折叠筛选和详情的可达性。真实目录为空时,满列表与分页使用明确标注的模拟 HTTP 数据单独验证。
|
||||||
|
- 真实模式验证:完整目录超过一页时能筛到末页;个人加入 / 移除的接口与载荷;企业诉求不增加“我的技能”数量;游客与管理员按钮权限;筛选不产生额外请求。
|
||||||
|
- 模拟数据与真实后端结果分开记录。新增文案补齐 9 个语言包。
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# 表格列设置规范(三中心通用)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.1
|
||||||
|
|
||||||
|
三中心已有列设置的统一组件与交互规范。
|
||||||
|
|
||||||
|
**何时阅读**:修改任一表格的列设置入口、弹框或列显隐逻辑时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| ------ | -------------------------------------------------- |
|
||||||
|
| 范围 | 9 个已有入口;没有列设置的表格不新增 |
|
||||||
|
| 组件 | `ColumnSettings.jsx` + `column-settings.css` |
|
||||||
|
| 入口 | 齿轮在表格卡片工具栏最右,不混入搜索表单 |
|
||||||
|
| 弹框 | 宽 520px、两列选项、全选、“重置 / 取消 / 确定” |
|
||||||
|
| 交互 | 先改草稿,确定后一次应用,至少保留一列;取消即放弃 |
|
||||||
|
| 持久化 | 原存储键不变;个人 / 企业密钥不持久化 |
|
||||||
|
|
||||||
|
**相关代码**:`src/components/common/table/`
|
||||||
|
|
||||||
|
## 1. 入口清单
|
||||||
|
|
||||||
|
| 中心 | 页面 / 页签 | 路由 | 位置 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 用户中心 | 使用记录 / 消费记录 | `/user-center/usage-record` | 调用明细卡片右上角,位于导出之后 |
|
||||||
|
| 用户中心 | 使用记录 / 绘图与视频 | `/user-center/usage-record?tab=task` | 任务记录卡片右上角,位于导出之后 |
|
||||||
|
| 用户中心 | 密钥管理 | `/user-center/key-management` | 密钥列表卡片右上角,位于创建之后 |
|
||||||
|
| 控制台 | 使用日志 | `/console/log` | 列表卡片右上角,位于导出之后 |
|
||||||
|
| 控制台 | 异步任务 | `/console/task` | 列表卡片右上角 |
|
||||||
|
| 控制台 | 绘图日志 | `/console/midjourney` | 列表卡片右上角 |
|
||||||
|
| 控制台 | 渠道管理 | `/console/channel` | 列表工具栏最右侧 |
|
||||||
|
| 企业中心 | 密钥管理 | `/org/tokens` | 列表卡片右上角,位于刷新 / 创建之后 |
|
||||||
|
| 企业中心 | 消耗明细 / 绘图与视频 | `/org/logs` | 任务记录卡片右上角,位于导出 / 刷新之后 |
|
||||||
|
|
||||||
|
管理员密钥 `/console/token`、企业明细日志、成员排行等没有列设置的表格不补建入口。
|
||||||
|
|
||||||
|
## 2. 组件
|
||||||
|
|
||||||
|
| 导出 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `ColumnSettingsButton` | `Button type='text'` + `Tooltip`,34px,16px 设置图标,带可访问标签与展开状态 |
|
||||||
|
| `ColumnSettingsModal` | `Modal` + `Checkbox.Group` + `Checkbox` + `Button` + 校验 `Alert`;列选项由调用方提供 |
|
||||||
|
| `ColumnVisibilitySettings` | 把布尔列显隐映射接入弹框,确认时一次提交,保留当前角色不可配置的键值 |
|
||||||
|
| `TableColumnSettings`(默认导出) | 个人与企业密钥页的数组列显隐适配 |
|
||||||
|
|
||||||
|
- 各日志与渠道模块原有的 `ColumnSelectorModal` 保留列生成与权限过滤,内部委托公共弹框。
|
||||||
|
- 列选项名称来自实际表格列定义(如企业任务的“任务 ID”“操作”),表头中的帮助图标不复制到选项。
|
||||||
|
|
||||||
|
## 3. 外观
|
||||||
|
|
||||||
|
- 弹框宽 520px、顶部 100px,视口不足时左右各留 16px;内容内边距 20px / 24px,圆角 12px;标题 16 / 24px、600。
|
||||||
|
- 正文顶部 20px;全选区上下 14px,下方 1px 分隔线,下距 18px。
|
||||||
|
- 选项两列,行距 16px、列距 20px,网格内边距 4px 0 12px;窄屏改为 14px / 10px 间距、12px 文字。复选框 17px、圆角 6px。
|
||||||
|
- 底部按钮依次为“重置”“取消”“确定”(primary),高 34px、间距 8px。
|
||||||
|
- 遮罩 `rgba(0,0,0,.3)` + `blur(4px)`;主色跟随主题,深色读取现有 token;不新增 ConfigProvider、主题状态或存储键。
|
||||||
|
|
||||||
|
## 4. 交互与状态
|
||||||
|
|
||||||
|
1. 打开时复制当前可见列为独立草稿,后台刷新与轮询不覆盖正在编辑的草稿。
|
||||||
|
2. 单列勾选、全选与重置只修改草稿;全选与半选按当前角色可配置的列计算。
|
||||||
|
3. 重置恢复本表原有默认列(渠道“自动封禁”仍默认隐藏)。
|
||||||
|
4. 确定时至少保留一列;全部取消后确定会显示校验提示,弹框保持打开。
|
||||||
|
5. 确定后一次应用;日志与渠道沿用原 localStorage 规则,个人与企业密钥只在页面内保留。
|
||||||
|
6. 取消、关闭按钮、Esc、遮罩均放弃草稿,不改变表格或存储;关闭后焦点返回入口。
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# 用户中心 UI 规范(/user-center/\*)
|
||||||
|
|
||||||
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
|
||||||
|
|
||||||
|
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
|
||||||
|
|
||||||
|
**何时阅读**:修改数据看板、使用记录、在线充值、个人设置,或共享的使用记录表格分支时。
|
||||||
|
|
||||||
|
## 速查
|
||||||
|
|
||||||
|
| 关注点 | 规则 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页面 | 数据看板、使用记录、在线充值、个人设置(第 1 节) |
|
||||||
|
| 外壳 | `.uc-page` + `UserCenterPageHeader`,边距与页头按 `GLOBAL_UI_BASELINE.md` 4.4 |
|
||||||
|
| 变量族 | `--uc-*` / `--ur-*` / `--rc-*` / `--ps-*`;卡片与表格取值与密钥管理共用(第 3 节) |
|
||||||
|
| 筛选栏 | 5 列,时间范围跨 2 列;移动端默认收起 |
|
||||||
|
| 业务边界 | 只消费原有状态与处理函数;不点击真实支付类确认按钮 |
|
||||||
|
|
||||||
|
**相关代码**:`src/pages/UserCenter/`、`src/pages/Recharge/`、`src/components/settings/personal/`、`src/components/table/{usage-logs,task-logs}/`
|
||||||
|
|
||||||
|
## 1. 范围与依据
|
||||||
|
|
||||||
|
| 页面 | 路由 | 主要文件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 数据看板 | `/user-center/dashboard` | `src/pages/UserCenter/UserDashboard.jsx` |
|
||||||
|
| 使用记录 | `/user-center/usage-record`(`?tab=task` 为绘图与视频) | `src/pages/UserCenter/UsageRecord.jsx` / `.css`;`src/components/table/{usage-logs,task-logs}/*` |
|
||||||
|
| 在线充值 | `/user-center/topup` | `src/pages/Recharge/*`(`recharge.css`、`WalletCard.jsx`) |
|
||||||
|
| 个人设置 | `/user-center/settings` | `src/components/settings/PersonalSetting.jsx`、`src/components/settings/personal/*` |
|
||||||
|
|
||||||
|
- 视觉依据:在线原型 `http://192.168.0.161:8888` 侧栏对应页面,只作视觉依据;深色由主题推导,不做深色像素验收。
|
||||||
|
- 不在范围:企业中心、控制台、认证页、WeyAI 外部页、体验中心、模型超市、技能超市。
|
||||||
|
|
||||||
|
## 2. 文件与职责
|
||||||
|
|
||||||
|
| 文件 | 职责 | 边界 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `src/styles/user-center.css` | 外壳:页面底色、内容边距、页头、移动底部导航 | 只写外壳;页面内部样式放各自 CSS |
|
||||||
|
| `src/pages/UserCenter/UsageRecord.jsx` / `.css` | 使用记录页签宿主与 `--ur-*` 变量 | 页签沿用 `handleTabChange`、URL `?tab=` 与懒挂载 |
|
||||||
|
| `src/components/table/usage-logs/*`、`task-logs/*` | 记录筛选、列定义、表格、弹窗 | 个人端走 `usageRecordMode` 分支,`/console/log`、`/console/task` 不受影响 |
|
||||||
|
| `src/pages/Recharge/*` | 钱包、金额、支付方式、订单、会员与记录 | 只消费原有状态与处理函数(`preTopUp`、`topUp`、`handlePlanClick` 等) |
|
||||||
|
| `src/components/membership/MembershipHistoryModal.jsx` | 会员购买记录(内嵌页签与弹窗共用) | 同一请求、分页与列定义 |
|
||||||
|
| `src/components/topup/modals/PaymentConfirmModal.jsx` | 充值确认弹窗 | `onOk`、禁用条件、确认文案不变 |
|
||||||
|
| `src/components/settings/PersonalSetting.jsx`、`personal/*` | 资料头、页签与各设置区块 | 表单 `getFormApi`、`rules`、提交与保存条件不变 |
|
||||||
|
| `src/pages/UserCenter/UserDashboard.jsx` | 指标、图表、会员权益 | 图表数据与刷新逻辑不变 |
|
||||||
|
|
||||||
|
## 3. 变量族
|
||||||
|
|
||||||
|
| 变量族 | 作用域 | 文件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `--uc-*` | `body[data-ui-scope='admin']`、`.user-center` | `src/styles/user-center.css` |
|
||||||
|
| `--ur-*` | `.usage-record-page` | `src/pages/UserCenter/UsageRecord.css` |
|
||||||
|
| `--rc-*` | `.ui-recharge-page` | `src/pages/Recharge/recharge.css` |
|
||||||
|
| `--ps-*` | `.ui-personal-settings` | `src/components/settings/personal/personal-settings.css` |
|
||||||
|
|
||||||
|
用户中心卡片与表格的浅色取值(使用记录、密钥管理共用;深色引用主题变量):
|
||||||
|
|
||||||
|
| 用途 | 浅色 | 深色 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 页面底 | `#f8fafc`(`--uc-page-bg`) | `--surface-bg-base` |
|
||||||
|
| 卡片描边 | `#e6e9ef` | `--border-subtle` |
|
||||||
|
| 卡片阴影 | `0 4px 24px rgba(15,23,42,.02)` | `none` |
|
||||||
|
| 筛选标签 | `#6b7789` | `--text-secondary` |
|
||||||
|
| 表头底 / 文字 | `#f8f9fc` / `#687589` | `--ui-color-fill-0` / `--text-secondary` |
|
||||||
|
| 行线 | `#f0f0f0` | `--border-subtle` |
|
||||||
|
| 页签选中 | 主色 | `#f2ad41`(`--ur-tab-accent`) |
|
||||||
|
|
||||||
|
使用记录的状态胶囊另有成功、失败、进行中三组底色 / 描边 / 文字变量(`--ur-success-*`、`--ur-failure-*`、`--ur-pending-*`),深色由语义色与卡片色混合得到。
|
||||||
|
|
||||||
|
## 4. 页面规则
|
||||||
|
|
||||||
|
### 4.1 数据看板
|
||||||
|
|
||||||
|
- 底色用 `--surface-bg-base`;保留 `.uc-dashboard-hero` 装饰层:高 315px(移动 460px),插画 630×310、`right: 4%`、`top: 17px`,浅色不透明度 .82、深色 .64 并降低亮度与饱和度;移动端插画 330×210、`right: -65px`、`top: 10px`、不透明度 .18。
|
||||||
|
- 时间粒度为 `Select`(92×34),新值在下一次刷新或筛选时生效。
|
||||||
|
|
||||||
|
### 4.2 使用记录
|
||||||
|
|
||||||
|
- 页签:纯文字页签(公共列表页签样式),与下方 20px,URL `?tab=` 同步并懒挂载。
|
||||||
|
- 筛选卡:5 列栅格,时间范围跨 2 列;背景使用 `--surface-card` 纯色(浅色为白色、深色为主题卡片色);操作“重置 / 搜索”右下。
|
||||||
|
- 列表卡:标题 15px / 600,导出、列设置位于卡头右侧;表头字重 400(公共标准为 500,待收敛)。
|
||||||
|
- 消费记录调用明细为固定列宽宽表,横向滚动时“时间”列固定在左侧,“操作”列显示时固定在右侧,中间列可滚动。时间分两行(日期 11px、时间 15px / 600),固定列兼容规则遵循公共规范第 5.2 节。
|
||||||
|
- 消费记录“用时 / 首字”列宽 190px,总用时、首字耗时与流式状态分别用 antd 默认带描边 `Tag` 展示,保留主题算法生成的浅底 / 文字 / 边框。总用时对 `use_time` 取整数秒,`<101s` 用 `green`、`101–299s` 用 `gold`、`≥300s` 用 `magenta`;首字耗时取 `other.frt / 1000`,先保留一位小数再判色,`<3s` 用 `cyan`、`3–<10s` 用 `orange`、`≥10s` 用 `red`。流式显示三枚标签(状态为蓝色“流”),非流式仅显示总用时与中性“非流”;零值正常展示,缺失、非数值或负耗时显示中性破折号。
|
||||||
|
- 绘图与视频:三张统计卡(高 70px、间距 15px)+ 任务记录表。
|
||||||
|
- Webhook 示例为 `<pre class='ui-notify-code'>` +“复制”链接,复制提示沿用原文案。
|
||||||
|
|
||||||
|
### 4.3 在线充值
|
||||||
|
|
||||||
|
- 左栏钱包 230px + 主区,间距 22px;金额 4 列(间距 12px × 13px)。
|
||||||
|
- 余额充值 / 会员订阅用 `Segmented`,记录区用 `Tabs`(页签间距 32px)。
|
||||||
|
- 支付方式为选择块(高 42px、最小宽 133px,选中描边 + 勾),点击调用 `preTopUp(method.type)`;订单卡应付区 240px、主按钮高 44px,“立即充值”调用 `preTopUp(payWay)`。
|
||||||
|
- 钱包卡与订单卡的浅暖色渐变只在 `.ui-recharge-page` 作用域。
|
||||||
|
|
||||||
|
### 4.4 个人设置
|
||||||
|
|
||||||
|
- 资料头内边距 21px 26px 23px,带浅色渐变(仅 `.ui-personal-settings`);设置卡最小高 480px。
|
||||||
|
- 头像区:215px 预览 + 表单(输入宽 600px);头像类型用 `Segmented`,`onChange(value)` 接 `handleAvatarSettingChange('avatarType', value)`。
|
||||||
|
- 行卡内边距 22px;通知面板内边距 20px,代码块 12px / 21.5px。
|
||||||
|
|
||||||
|
### 4.5 移动端
|
||||||
|
|
||||||
|
内容边距 16px;筛选默认收起(“显示 / 隐藏操作项”);表格在卡片内横向滚动;钱包、订单、方案卡单列;底部导航 `.uc-mobile-nav`(`aria-current` 标记当前项)。
|
||||||
|
|
||||||
|
## 5. 保留功能与已知差异
|
||||||
|
|
||||||
|
- 无数据源的原型元素(PayPal 说明行、“查看 10 元示例”、头像“显示文字”独立字段)不渲染。
|
||||||
|
- 普通用户无“渠道 ID / 用户 ID”筛选及管理员列;后端未启用在线支付时,充值页不渲染金额、支付方式与订单卡;资料头比原型多“调用次数”;日期面板禁用过去日期。
|
||||||
|
- 正文色沿用全局 `colorText`;支付品牌图标保留品牌色。
|
||||||
|
- 不点击真实的“确认支付”“确认购买”“确认升级”“删除账户”等确认按钮。
|
||||||
|
|
||||||
|
## 6. 验收要点
|
||||||
|
|
||||||
|
- 浅深主题 × 桌面 1920×1000 / 移动 393×851,覆盖每个页面与页签。
|
||||||
|
- 交互:悬停、焦点、禁用、加载、弹窗打开 / 取消、日期面板、校验失败、复制提示、主题切换后刷新保持。
|
||||||
|
- 只读验收的非 GET `/api/` 请求为 0;模拟数据只拦截列表与报价接口并标注。新增文案补齐 9 个语言包。
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
const globals = require('globals');
|
||||||
|
const react = require('eslint-plugin-react');
|
||||||
|
const reactHooks = require('eslint-plugin-react-hooks');
|
||||||
|
const unusedImports = require('eslint-plugin-unused-imports');
|
||||||
|
const { uiDependencyConfig } = require('./scripts/ui-dependency-policy.cjs');
|
||||||
|
|
||||||
|
module.exports = [
|
||||||
|
{
|
||||||
|
ignores: [
|
||||||
|
'**/.*',
|
||||||
|
'dist/**',
|
||||||
|
'node_modules/**',
|
||||||
|
'logs/**',
|
||||||
|
'report/**',
|
||||||
|
'playwright-report/**',
|
||||||
|
'test-results/**',
|
||||||
|
'blob-report/**',
|
||||||
|
'src/assets/brand-icons/*.js',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
uiDependencyConfig,
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,jsx}'],
|
||||||
|
linterOptions: { reportUnusedDisableDirectives: 'off' },
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
sourceType: 'module',
|
||||||
|
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||||
|
globals: { ...globals.browser, ...globals.node, ...globals.es2021 },
|
||||||
|
},
|
||||||
|
settings: { react: { version: 'detect' } },
|
||||||
|
plugins: {
|
||||||
|
react,
|
||||||
|
'react-hooks': reactHooks,
|
||||||
|
'unused-imports': unusedImports,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'no-multiple-empty-lines': ['error', { max: 1 }],
|
||||||
|
|
||||||
|
// ===== 防线:杜绝“用了未定义/未导入标识符”导致的运行时崩溃(本次线上事故根因)=====
|
||||||
|
// 让规则识别 JSX 中使用到的组件/React,避免误报。
|
||||||
|
'react/jsx-uses-vars': 'error',
|
||||||
|
'react/jsx-uses-react': 'error',
|
||||||
|
// 未定义标识符 = 直接报错(构建/CI 即拦截)。
|
||||||
|
'no-undef': 'error',
|
||||||
|
// 未使用的 import = error 且可 --fix 自动移除(含 JSX/副作用识别);
|
||||||
|
// 未使用的变量 = warn(不阻断,下划线前缀豁免)。
|
||||||
|
'no-unused-vars': 'off',
|
||||||
|
'unused-imports/no-unused-imports': 'error',
|
||||||
|
'unused-imports/no-unused-vars': [
|
||||||
|
'warn',
|
||||||
|
{
|
||||||
|
vars: 'all',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
args: 'none',
|
||||||
|
caughtErrors: 'none',
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
ignoreRestSiblings: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
// React Hooks 规则。
|
||||||
|
'react-hooks/rules-of-hooks': 'error',
|
||||||
|
'react-hooks/exhaustive-deps': 'warn',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -1,22 +1,3 @@
|
|||||||
/*
|
|
||||||
Copyright (C) 2025 QuantumNous
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as
|
|
||||||
published by the Free Software Foundation, either version 3 of the
|
|
||||||
License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
For commercial licensing, please contact support@quantumnous.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { defineConfig } from 'i18next-cli';
|
import { defineConfig } from 'i18next-cli';
|
||||||
|
|
||||||
/** @type {import('i18next-cli').I18nextToolkitConfig} */
|
/** @type {import('i18next-cli').I18nextToolkitConfig} */
|
||||||
|
|||||||
+111
-7
@@ -2,6 +2,104 @@
|
|||||||
<html lang="zh">
|
<html lang="zh">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
|
<script id="wl-legacy-polyfills">
|
||||||
|
// 旧内核补丁,针对 Chromium 88~98(停更的 Edge、Win10 LTSC 自带 Edge、国产壳浏览器)。
|
||||||
|
// 打包产物里用到、而这批内核缺失的 JS API 只有下面三个;其中 mermaid 分包在加载时
|
||||||
|
// 就调用 structuredClone,登录/注册等页面静态依赖它,缺了整页报错。
|
||||||
|
// 88 以下不在兜底范围:那些内核连 :is() 选择器都不认,暗色变体等样式本身就会失效。
|
||||||
|
// 每项都只在缺失时才定义,对新浏览器没有任何影响。内联脚本不经过转译,语法须停留在
|
||||||
|
// ES5;且必须排在所有脚本之前。
|
||||||
|
// 样式侧对应的兜底见 vite-plugin-legacy-css-layers.js。
|
||||||
|
(function () {
|
||||||
|
var define = function (target, name, value) {
|
||||||
|
if (typeof target[name] === 'function') return;
|
||||||
|
Object.defineProperty(target, name, {
|
||||||
|
value: value,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Chromium 92
|
||||||
|
var at = function (index) {
|
||||||
|
var i = Math.trunc(index) || 0;
|
||||||
|
if (i < 0) i += this.length;
|
||||||
|
return i < 0 || i >= this.length ? undefined : this[i];
|
||||||
|
};
|
||||||
|
define(Array.prototype, 'at', at);
|
||||||
|
define(String.prototype, 'at', at);
|
||||||
|
define(Object.getPrototypeOf(Int8Array).prototype, 'at', at);
|
||||||
|
|
||||||
|
// Chromium 93
|
||||||
|
define(Object, 'hasOwn', function (object, key) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(object, key);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Chromium 98。按调用方实际传入的数据形态实现:普通对象/数组/Date/RegExp/Map/Set/
|
||||||
|
// 二进制缓冲,循环引用与共享引用在克隆结果里保持原有关系;函数与 symbol 按规范抛
|
||||||
|
// DataCloneError。Error、Blob 等宿主对象和 transfer 参数未实现(会被当成普通对象)。
|
||||||
|
define(window, 'structuredClone', function (value) {
|
||||||
|
var seen = new Map();
|
||||||
|
var Shared = window.SharedArrayBuffer;
|
||||||
|
var remember = function (source, copy) {
|
||||||
|
seen.set(source, copy);
|
||||||
|
return copy;
|
||||||
|
};
|
||||||
|
var clone = function (v) {
|
||||||
|
if (typeof v === 'function' || typeof v === 'symbol') {
|
||||||
|
throw new DOMException('uncloneable value', 'DataCloneError');
|
||||||
|
}
|
||||||
|
if (v === null || typeof v !== 'object') return v;
|
||||||
|
if (seen.has(v)) return seen.get(v);
|
||||||
|
if (v instanceof Date) return remember(v, new Date(v.getTime()));
|
||||||
|
if (v instanceof RegExp) {
|
||||||
|
return remember(v, new RegExp(v.source, v.flags));
|
||||||
|
}
|
||||||
|
if (v instanceof ArrayBuffer) return remember(v, v.slice(0));
|
||||||
|
// 共享内存按规范是共享而非复制;不单列的话它会落进普通对象分支变成 {}
|
||||||
|
if (Shared && v instanceof Shared) return v;
|
||||||
|
if (ArrayBuffer.isView(v)) {
|
||||||
|
// 缓冲区也走 clone:多个视图共享的缓冲区克隆后仍是同一份
|
||||||
|
var buf = clone(v.buffer);
|
||||||
|
var size = v instanceof DataView ? v.byteLength : v.length;
|
||||||
|
return remember(v, new v.constructor(buf, v.byteOffset, size));
|
||||||
|
}
|
||||||
|
var out;
|
||||||
|
if (v instanceof Map) {
|
||||||
|
out = remember(v, new Map());
|
||||||
|
v.forEach(function (item, key) {
|
||||||
|
out.set(clone(key), clone(item));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (v instanceof Set) {
|
||||||
|
out = remember(v, new Set());
|
||||||
|
v.forEach(function (item) {
|
||||||
|
out.add(clone(item));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
out = remember(v, Array.isArray(v) ? new Array(v.length) : {});
|
||||||
|
Object.keys(v).forEach(function (key) {
|
||||||
|
var copy = clone(v[key]);
|
||||||
|
if (key !== '__proto__') {
|
||||||
|
out[key] = copy;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 唯独这个键不能赋值:赋值改写的是原型,而不是落成自有属性
|
||||||
|
Object.defineProperty(out, key, {
|
||||||
|
value: copy,
|
||||||
|
writable: true,
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
return clone(value);
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<!-- favicon: 后端启动时把 __WL_BRAND_FAVICON__ 替换为 common.Logo(未配置时为 /logo.svg);
|
<!-- favicon: 后端启动时把 __WL_BRAND_FAVICON__ 替换为 common.Logo(未配置时为 /logo.svg);
|
||||||
dev 模式占位符未替换时,下面的内联脚本会重写 href 为 /logo.svg。 -->
|
dev 模式占位符未替换时,下面的内联脚本会重写 href 为 /logo.svg。 -->
|
||||||
<link id="wl-favicon" rel="icon" href="__WL_BRAND_FAVICON__" />
|
<link id="wl-favicon" rel="icon" href="__WL_BRAND_FAVICON__" />
|
||||||
@@ -92,7 +190,7 @@
|
|||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
background: radial-gradient(
|
background: radial-gradient(
|
||||||
circle,
|
circle,
|
||||||
var(--brand-primary-soft, rgba(22, 104, 220, 0.10)),
|
var(--brand-primary-soft, rgba(22, 104, 220, 0.1)),
|
||||||
transparent 70%
|
transparent 70%
|
||||||
);
|
);
|
||||||
filter: blur(24px);
|
filter: blur(24px);
|
||||||
@@ -280,13 +378,19 @@
|
|||||||
var el = document.getElementById('wl-splash');
|
var el = document.getElementById('wl-splash');
|
||||||
var rawBrand = el ? el.getAttribute('data-brand') : null;
|
var rawBrand = el ? el.getAttribute('data-brand') : null;
|
||||||
var rawLogo = el ? el.getAttribute('data-logo') : null;
|
var rawLogo = el ? el.getAttribute('data-logo') : null;
|
||||||
var brandIsDevPH = !!(rawBrand && rawBrand.indexOf(PLACEHOLDER_PREFIX) === 0);
|
var brandIsDevPH = !!(
|
||||||
var logoIsDevPH = !!(rawLogo && rawLogo.indexOf(PLACEHOLDER_PREFIX) === 0);
|
rawBrand && rawBrand.indexOf(PLACEHOLDER_PREFIX) === 0
|
||||||
|
);
|
||||||
|
var logoIsDevPH = !!(
|
||||||
|
rawLogo && rawLogo.indexOf(PLACEHOLDER_PREFIX) === 0
|
||||||
|
);
|
||||||
var name = brandIsDevPH ? '' : clean(rawBrand);
|
var name = brandIsDevPH ? '' : clean(rawBrand);
|
||||||
var logo = logoIsDevPH ? '' : clean(rawLogo);
|
var logo = logoIsDevPH ? '' : clean(rawLogo);
|
||||||
try {
|
try {
|
||||||
if ((!el || brandIsDevPH) && !name) name = clean(localStorage.getItem('system_name'));
|
if ((!el || brandIsDevPH) && !name)
|
||||||
if ((!el || logoIsDevPH) && !logo) logo = clean(localStorage.getItem('logo'));
|
name = clean(localStorage.getItem('system_name'));
|
||||||
|
if ((!el || logoIsDevPH) && !logo)
|
||||||
|
logo = clean(localStorage.getItem('logo'));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
/* 隐私模式 localStorage 不可用:name/logo 保持空,React 端走终极兜底 */
|
/* 隐私模式 localStorage 不可用:name/logo 保持空,React 端走终极兜底 */
|
||||||
}
|
}
|
||||||
@@ -305,7 +409,8 @@
|
|||||||
try {
|
try {
|
||||||
// ---- 文案:navigator.language 判定 zh / en ----
|
// ---- 文案:navigator.language 判定 zh / en ----
|
||||||
var lang = (navigator.language || 'zh').toLowerCase();
|
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');
|
var textEl = el.querySelector('.wl-text');
|
||||||
if (textEl) textEl.textContent = loadingText;
|
if (textEl) textEl.textContent = loadingText;
|
||||||
|
|
||||||
@@ -356,7 +461,6 @@
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<script src="/config.js"></script>
|
|
||||||
<script type="module" src="/src/index.jsx"></script>
|
<script type="module" src="/src/index.jsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-2
@@ -1,8 +1,7 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "./",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["src/*"]
|
"@/*": ["./src/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"]
|
"include": ["src/**/*"]
|
||||||
|
|||||||
Generated
+12761
File diff suppressed because it is too large
Load Diff
+35
-27
@@ -1,28 +1,25 @@
|
|||||||
{
|
{
|
||||||
"name": "react-template",
|
"name": "monkey-ai-web",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ant-design/icons": "6.3.4",
|
||||||
"@dagrejs/dagre": "^1.1.4",
|
"@dagrejs/dagre": "^1.1.4",
|
||||||
"@douyinfe/semi-icons": "^2.63.1",
|
|
||||||
"@douyinfe/semi-ui": "^2.69.1",
|
|
||||||
"@lobehub/icons": "^2.0.0",
|
|
||||||
"@visactor/react-vchart": "~1.8.8",
|
"@visactor/react-vchart": "~1.8.8",
|
||||||
"@visactor/vchart": "~1.8.8",
|
"@visactor/vchart": "~1.8.8",
|
||||||
"@visactor/vchart-semi-theme": "~1.8.8",
|
|
||||||
"@xyflow/react": "^12.6.0",
|
"@xyflow/react": "^12.6.0",
|
||||||
"antd": "^6.3.0",
|
"antd": "6.7.0",
|
||||||
"axios": "^1.19.0",
|
"axios": "^1.19.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"colord": "^2.9.3",
|
"colord": "^2.9.3",
|
||||||
"country-flag-icons": "^1.5.19",
|
"country-flag-icons": "^1.5.19",
|
||||||
"dayjs": "^1.11.11",
|
"dayjs": "^1.11.11",
|
||||||
"docx": "^9.6.1",
|
"docx": "^9.6.1",
|
||||||
|
"entities": "^6.0.1",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
"history": "^5.3.0",
|
"history": "^5.3.0",
|
||||||
"i18next": "^23.16.8",
|
"i18next": "^23.16.8",
|
||||||
"i18next-browser-languagedetector": "^7.2.0",
|
|
||||||
"katex": "^0.16.22",
|
"katex": "^0.16.22",
|
||||||
"lucide-react": "^0.511.0",
|
"lucide-react": "^0.511.0",
|
||||||
"marked": "^4.1.1",
|
"marked": "^4.1.1",
|
||||||
@@ -30,6 +27,7 @@
|
|||||||
"prop-types": "^15.8.1",
|
"prop-types": "^15.8.1",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"qrcode.react": "^4.2.0",
|
"qrcode.react": "^4.2.0",
|
||||||
|
"quill": "^2.0.3",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"react-fireworks": "^1.0.4",
|
"react-fireworks": "^1.0.4",
|
||||||
@@ -38,7 +36,6 @@
|
|||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-router-dom": "^6.3.0",
|
"react-router-dom": "^6.3.0",
|
||||||
"react-telegram-login": "^1.1.2",
|
"react-telegram-login": "^1.1.2",
|
||||||
"react-toastify": "^9.0.8",
|
|
||||||
"react-turnstile": "^1.0.5",
|
"react-turnstile": "^1.0.5",
|
||||||
"rehype-highlight": "^7.0.2",
|
"rehype-highlight": "^7.0.2",
|
||||||
"rehype-katex": "^7.0.1",
|
"rehype-katex": "^7.0.1",
|
||||||
@@ -51,18 +48,30 @@
|
|||||||
"xlsx": "^0.18.5"
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "node scripts/dev.mjs",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"test": "node --test",
|
"test": "node scripts/test.mjs",
|
||||||
|
"test:e2e": "playwright test",
|
||||||
|
"test:e2e:headed": "playwright test --headed",
|
||||||
|
"test:e2e:report": "node scripts/run-playwright.mjs report",
|
||||||
"lint": "prettier . --check",
|
"lint": "prettier . --check",
|
||||||
"lint:fix": "prettier . --write",
|
"lint:fix": "prettier . --write",
|
||||||
"eslint": "bunx eslint \"**/*.{js,jsx}\" --cache",
|
"check": "npm run check:ui && npm run eslint && npm test -- --test-concurrency=1 && npm run build",
|
||||||
"eslint:fix": "bunx eslint \"**/*.{js,jsx}\" --fix --cache",
|
"eslint": "eslint \"**/*.{js,jsx}\" --cache --max-warnings=0",
|
||||||
|
"eslint:fix": "eslint \"**/*.{js,jsx}\" --fix --cache",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"i18n:extract": "bunx i18next-cli extract",
|
"i18n:extract": "i18next-cli extract",
|
||||||
"i18n:status": "bunx i18next-cli status",
|
"i18n:status": "i18next-cli status",
|
||||||
"i18n:sync": "bunx i18next-cli sync",
|
"i18n:sync": "i18next-cli sync",
|
||||||
"i18n:lint": "bunx i18next-cli lint"
|
"i18n:lint": "i18next-cli lint",
|
||||||
|
"check:ui": "node scripts/check-ui-dependencies.mjs",
|
||||||
|
"vendor:icons": "node scripts/vendor-brand-icons.mjs",
|
||||||
|
"test:e2e:headless": "node scripts/run-playwright.mjs headless",
|
||||||
|
"test:e2e:extended": "node scripts/run-playwright.mjs extended",
|
||||||
|
"test:e2e:dist": "node scripts/run-playwright.mjs dist",
|
||||||
|
"verify:build": "node scripts/verify-build.mjs",
|
||||||
|
"test:acceptance": "npm test -- --test-concurrency=1 && node scripts/run-acceptance.mjs",
|
||||||
|
"test:e2e:environment": "node scripts/test-playwright-environment.mjs"
|
||||||
},
|
},
|
||||||
"browserslist": {
|
"browserslist": {
|
||||||
"production": [
|
"production": [
|
||||||
@@ -77,25 +86,24 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@douyinfe/vite-plugin-semi": "^2.74.0-alpha.6",
|
"@playwright/test": "1.64.1",
|
||||||
"@so1ve/prettier-config": "^3.1.0",
|
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
"autoprefixer": "^10.4.21",
|
"autoprefixer": "^10.4.21",
|
||||||
"eslint": "8.57.0",
|
"esbuild": "0.25.12",
|
||||||
"eslint-plugin-header": "^3.1.1",
|
"eslint": "9.39.5",
|
||||||
"eslint-plugin-react": "^7.37.5",
|
"eslint-plugin-react": "^7.37.5",
|
||||||
"eslint-plugin-react-hooks": "^5.2.0",
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
"eslint-plugin-unused-imports": "^3.2.0",
|
"eslint-plugin-unused-imports": "4.4.1",
|
||||||
|
"globals": "16.5.0",
|
||||||
"i18next-cli": "^1.10.3",
|
"i18next-cli": "^1.10.3",
|
||||||
"postcss": "^8.5.3",
|
"postcss": "^8.5.3",
|
||||||
"prettier": "^3.0.0",
|
"prettier": "^3.0.0",
|
||||||
"tailwindcss": "^3",
|
"tailwindcss": "^3",
|
||||||
"typescript": "4.4.2",
|
"vite": "6.4.6"
|
||||||
"vite": "^5.2.0"
|
|
||||||
},
|
},
|
||||||
"prettier": {
|
"engines": {
|
||||||
"singleQuote": true,
|
"node": ">=22.13.0",
|
||||||
"jsxSingleQuote": true
|
"npm": ">=10"
|
||||||
},
|
},
|
||||||
"proxy": "http://localhost:3000"
|
"packageManager": "npm@10.9.9"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { defineConfig } from '@playwright/test';
|
||||||
|
import {
|
||||||
|
browserChannel,
|
||||||
|
contextOptions,
|
||||||
|
defaultProjectViewports,
|
||||||
|
projectViewports,
|
||||||
|
} from './scripts/browser-environment.mjs';
|
||||||
|
import { runtimeOptions } from './scripts/playwright-runtime.mjs';
|
||||||
|
import { findDevService } from './scripts/dev-service.mjs';
|
||||||
|
|
||||||
|
if (
|
||||||
|
!process.argv.includes('--list') &&
|
||||||
|
!process.env.PW_TARGET &&
|
||||||
|
!process.env.PW_BASE_URL
|
||||||
|
) {
|
||||||
|
const existing = await findDevService();
|
||||||
|
if (existing) {
|
||||||
|
process.env.PW_TARGET = 'remote';
|
||||||
|
process.env.PW_BASE_URL = existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const runtime = runtimeOptions({ defaultPort: 4176, defaultWorkers: 1 });
|
||||||
|
const { target, baseURL, isCI, headless, workers, outputDir, reportDir } =
|
||||||
|
runtime;
|
||||||
|
if (
|
||||||
|
isCI &&
|
||||||
|
process.argv.some((argument) =>
|
||||||
|
['--headed', '--debug', '--ui'].includes(argument),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error('CI requires headless non-interactive tests');
|
||||||
|
const viewports = runtime.extended ? projectViewports : defaultProjectViewports;
|
||||||
|
|
||||||
|
// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。
|
||||||
|
// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式
|
||||||
|
// (或 UI_VISUAL_OFFSCREEN=1),避免弹出 UI 或依赖显示环境。
|
||||||
|
// 离屏不能保证系统启动时不激活窗口;公共 fixture 探测到前台或状态不明时停止。
|
||||||
|
const listOnly = process.argv.includes('--list');
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './e2e',
|
||||||
|
testMatch: '**/*.spec.js',
|
||||||
|
outputDir,
|
||||||
|
fullyParallel: false,
|
||||||
|
workers,
|
||||||
|
forbidOnly: isCI || runtime.requireAll,
|
||||||
|
failOnFlakyTests: isCI,
|
||||||
|
retries: isCI ? 1 : 0,
|
||||||
|
timeout: 30000,
|
||||||
|
expect: { timeout: 5000 },
|
||||||
|
reporter: listOnly
|
||||||
|
? [['list']]
|
||||||
|
: [
|
||||||
|
['list'],
|
||||||
|
['html', { outputFolder: reportDir, open: 'never' }],
|
||||||
|
...(isCI ? [['junit', { outputFile: `${outputDir}/junit.xml` }]] : []),
|
||||||
|
['./scripts/playwright-reporter.mjs'],
|
||||||
|
],
|
||||||
|
metadata: {
|
||||||
|
platform: process.platform,
|
||||||
|
node: process.version,
|
||||||
|
target,
|
||||||
|
baseURL: baseURL.href,
|
||||||
|
runId: runtime.runId,
|
||||||
|
},
|
||||||
|
use: {
|
||||||
|
baseURL: baseURL.href,
|
||||||
|
headless,
|
||||||
|
launchOptions: { args: runtime.launchArgs },
|
||||||
|
...contextOptions('desktop'),
|
||||||
|
screenshot: { mode: 'only-on-failure', scale: 'css' },
|
||||||
|
trace: 'retain-on-failure',
|
||||||
|
video: runtime.video ? 'retain-on-failure' : 'off',
|
||||||
|
},
|
||||||
|
projects: viewports.map((name) => ({
|
||||||
|
name: `chrome-${name}`,
|
||||||
|
use: { ...contextOptions(name), channel: browserChannel },
|
||||||
|
})),
|
||||||
|
webServer:
|
||||||
|
target === 'remote'
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
command:
|
||||||
|
target === 'local-dist'
|
||||||
|
? `node scripts/preview-dist.mjs --port ${baseURL.port || 80}`
|
||||||
|
: `npm run dev -- --host 127.0.0.1 --port ${baseURL.port || 80} --strictPort`,
|
||||||
|
url: baseURL.href,
|
||||||
|
reuseExistingServer: false,
|
||||||
|
timeout: 30000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,22 +1,3 @@
|
|||||||
/*
|
|
||||||
Copyright (C) 2025 QuantumNous
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as
|
|
||||||
published by the Free Software Foundation, either version 3 of the
|
|
||||||
License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
For commercial licensing, please contact support@quantumnous.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
plugins: {
|
plugins: {
|
||||||
tailwindcss: {},
|
tailwindcss: {},
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
// Runtime configuration - modify per deployment environment.
|
|
||||||
// Monolith mode: leave SERVER_URL empty.
|
|
||||||
// Separated mode: set to backend URL, e.g. 'https://api.example.com'
|
|
||||||
window.__APP_CONFIG__ = {
|
|
||||||
SERVER_URL: '',
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。
|
||||||
|
// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。
|
||||||
|
|
||||||
|
// Use this for static review captures, not for interaction/animation tests.
|
||||||
|
export async function prepareStaticCapture(page) {
|
||||||
|
await page.evaluate(async () => {
|
||||||
|
await Promise.race([
|
||||||
|
Promise.all([
|
||||||
|
document.fonts.ready,
|
||||||
|
...[...document.images]
|
||||||
|
.filter((image) => image.currentSrc && image.checkVisibility())
|
||||||
|
.map((image) => image.decode().catch(() => {})),
|
||||||
|
]),
|
||||||
|
new Promise((_, reject) =>
|
||||||
|
setTimeout(
|
||||||
|
() =>
|
||||||
|
reject(
|
||||||
|
new Error(
|
||||||
|
'Static capture fonts/images did not settle within 10s',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
10000,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const staticScreenshotOptions = {
|
||||||
|
scale: 'css',
|
||||||
|
animations: 'disabled',
|
||||||
|
caret: 'hide',
|
||||||
|
style:
|
||||||
|
'*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }',
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function captureStatic(page, options = {}) {
|
||||||
|
await prepareStaticCapture(page);
|
||||||
|
return page.screenshot({ ...options, ...staticScreenshotOptions });
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { devices } from '@playwright/test';
|
||||||
|
import { browserStabilityArgs } from './playwright-runtime.mjs';
|
||||||
|
|
||||||
|
// The review JSON is also read by Python; keep dimensions and device choices there.
|
||||||
|
const config = JSON.parse(
|
||||||
|
readFileSync(new URL('./ui-review/config.json', import.meta.url), 'utf8'),
|
||||||
|
);
|
||||||
|
const aliases = {
|
||||||
|
'desktop-boundary': 'laptop',
|
||||||
|
'laptop-hd': 'hd',
|
||||||
|
'laptop-wxga': 'wxga',
|
||||||
|
};
|
||||||
|
export const browserChannel = config.browser.channel;
|
||||||
|
export const defaultProjectViewports = ['desktop', 'mobile', 'mobile-393'];
|
||||||
|
export const projectViewports = [
|
||||||
|
...defaultProjectViewports,
|
||||||
|
'tablet',
|
||||||
|
'desktop-boundary',
|
||||||
|
'laptop-hd',
|
||||||
|
'laptop-wxga',
|
||||||
|
'qhd',
|
||||||
|
'uhd',
|
||||||
|
];
|
||||||
|
|
||||||
|
export function deviceOptions(name) {
|
||||||
|
const key = aliases[name] || name;
|
||||||
|
const size = config.viewports[key];
|
||||||
|
if (!size) throw new Error(`Unknown viewport: ${name}`);
|
||||||
|
const descriptor =
|
||||||
|
devices[
|
||||||
|
config.browser[
|
||||||
|
key.startsWith('mobile') ? 'mobileDevice' : 'desktopDevice'
|
||||||
|
]
|
||||||
|
];
|
||||||
|
if (!descriptor) throw new Error(`Unknown device profile for ${name}`);
|
||||||
|
const { defaultBrowserType, ...context } = descriptor;
|
||||||
|
return { ...context, viewport: { width: size[0], height: size[1] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function contextOptions(name, reducedMotion = 'reduce') {
|
||||||
|
return {
|
||||||
|
...deviceOptions(name),
|
||||||
|
locale: config.browser.locale,
|
||||||
|
timezoneId: config.browser.timezone,
|
||||||
|
colorScheme: 'light',
|
||||||
|
reducedMotion,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function environmentFingerprint(name, reducedMotion = 'reduce') {
|
||||||
|
return createHash('sha256')
|
||||||
|
.update(
|
||||||
|
JSON.stringify({
|
||||||
|
version: 2,
|
||||||
|
channel: browserChannel,
|
||||||
|
options: contextOptions(name, reducedMotion),
|
||||||
|
launchArgs: browserStabilityArgs,
|
||||||
|
screenshotScale: 'css',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
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';
|
||||||
|
import policy from './ui-dependency-policy.cjs';
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
const { isForbiddenUiDependency, uiDependencyConfig } = policy;
|
||||||
|
const linter = new Linter({ cwd: root });
|
||||||
|
const sourceConfig = [uiDependencyConfig];
|
||||||
|
const sourceDirectories = new Set(['src', 'scripts', 'test', 'tests']);
|
||||||
|
const excludedDirectories = new Set([
|
||||||
|
'node_modules',
|
||||||
|
'dist',
|
||||||
|
'dist-ssr',
|
||||||
|
'build',
|
||||||
|
'coverage',
|
||||||
|
'report',
|
||||||
|
'logs',
|
||||||
|
'test-results',
|
||||||
|
'playwright-report',
|
||||||
|
'blob-report',
|
||||||
|
'kt_batches',
|
||||||
|
'kt_out',
|
||||||
|
]);
|
||||||
|
export { isForbiddenUiDependency };
|
||||||
|
|
||||||
|
export function auditManifest(manifest, lock) {
|
||||||
|
const issues = [];
|
||||||
|
for (const section of [
|
||||||
|
'dependencies',
|
||||||
|
'devDependencies',
|
||||||
|
'optionalDependencies',
|
||||||
|
'peerDependencies',
|
||||||
|
]) {
|
||||||
|
for (const [name, specifier] of Object.entries(manifest[section] || {})) {
|
||||||
|
const alias = /^npm:((?:@[^/]+\/)?[^@/]+)(?:@|$)/.exec(specifier)?.[1];
|
||||||
|
if (isForbiddenUiDependency(name)) {
|
||||||
|
issues.push(`package.json ${section}: ${name}`);
|
||||||
|
} else if (isForbiddenUiDependency(alias)) {
|
||||||
|
issues.push(`package.json ${section}: ${name} -> ${alias}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [location, entry] of Object.entries(lock.packages || {})) {
|
||||||
|
const names = location.split(/(?:^|\/)node_modules\//);
|
||||||
|
if (names.length === 1) continue;
|
||||||
|
if (isForbiddenUiDependency(names.at(-1))) {
|
||||||
|
issues.push(`package-lock.json: ${location}`);
|
||||||
|
} else if (isForbiddenUiDependency(entry.name)) {
|
||||||
|
issues.push(`package-lock.json: ${location} -> ${entry.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lock.packages || lock.lockfileVersion < 2)
|
||||||
|
issues.push('Expected an npm lockfile with a packages graph.');
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function auditSource(source, filename) {
|
||||||
|
return linter
|
||||||
|
.verify(source, sourceConfig, { filename, allowInlineConfig: false })
|
||||||
|
.map((issue) => `${filename}:${issue.line}: ${issue.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sourceFiles(dir, isRoot = true) {
|
||||||
|
const files = [];
|
||||||
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||||
|
const name = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (
|
||||||
|
isRoot
|
||||||
|
? sourceDirectories.has(entry.name)
|
||||||
|
: !entry.name.startsWith('.') && !excludedDirectories.has(entry.name)
|
||||||
|
) {
|
||||||
|
files.push(...(await sourceFiles(name, false)));
|
||||||
|
}
|
||||||
|
} else if (entry.isFile() && /\.(?:js|jsx|cjs|mjs)$/.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(directory);
|
||||||
|
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: Math.max(0, 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.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,941 @@
|
|||||||
|
/** Actual commission UI regression, isolated API fixtures and no remote traffic.
|
||||||
|
* PLAYWRIGHT_MODULE: existing playwright/index.mjs; COMMISSION_QA_OUTPUT: artifacts.
|
||||||
|
* Browser plugin is unavailable; uses existing Playwright/Chromium, no installation.
|
||||||
|
*/
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
const webRoot = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
'..',
|
||||||
|
);
|
||||||
|
process.chdir(webRoot);
|
||||||
|
const out =
|
||||||
|
process.env.COMMISSION_QA_OUTPUT ||
|
||||||
|
fs.mkdtempSync(path.join(os.tmpdir(), 'commission-qa-'));
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
const { chromium } = await import(
|
||||||
|
process.env.PLAYWRIGHT_MODULE
|
||||||
|
? pathToFileURL(path.resolve(process.env.PLAYWRIGHT_MODULE)).href
|
||||||
|
: 'playwright'
|
||||||
|
);
|
||||||
|
const { createServer, loadConfigFromFile } = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/vite/dist/node/index.js')).href
|
||||||
|
);
|
||||||
|
const { config: base } = await loadConfigFromFile(
|
||||||
|
{ command: 'serve', mode: 'development' },
|
||||||
|
path.join(webRoot, 'vite.config.js'),
|
||||||
|
);
|
||||||
|
const entry = path
|
||||||
|
.join(webRoot, 'src/__commission-qa.jsx')
|
||||||
|
.replaceAll('\\', '/');
|
||||||
|
const server = await createServer({
|
||||||
|
...base,
|
||||||
|
configFile: false,
|
||||||
|
root: webRoot,
|
||||||
|
cacheDir: path.join(out, 'vite-cache'),
|
||||||
|
optimizeDeps: { ...base.optimizeDeps, force: false },
|
||||||
|
server: { host: '127.0.0.1', port: 0, strictPort: false, proxy: {} },
|
||||||
|
plugins: [
|
||||||
|
...base.plugins,
|
||||||
|
{
|
||||||
|
name: 'commission-adjustment-qa',
|
||||||
|
configureServer(vite) {
|
||||||
|
vite.middlewares.use('/api/', (_req, res) => {
|
||||||
|
res.statusCode = 503;
|
||||||
|
res.end('QA requires intercepted API');
|
||||||
|
});
|
||||||
|
vite.middlewares.use('/__commission-qa.html', async (_req, res) => {
|
||||||
|
res.setHeader('Content-Type', 'text/html');
|
||||||
|
res.end(
|
||||||
|
await vite.transformIndexHtml(
|
||||||
|
'/__commission-qa.html',
|
||||||
|
'<html><head><title>Commission adjustment QA</title></head><body><div id="root"></div><script type="module" src="/__commission-qa.jsx"></script></body></html>',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
resolveId(id) {
|
||||||
|
if (id === '/__commission-qa.jsx') return entry;
|
||||||
|
},
|
||||||
|
load(id) {
|
||||||
|
if (id === entry)
|
||||||
|
return `
|
||||||
|
import '/src/styles/tokens.css';import '/src/index.css';import '/src/styles/org.css';
|
||||||
|
import React from 'react';import {createRoot} from 'react-dom/client';
|
||||||
|
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';
|
||||||
|
import {MemoryRouter, Routes, Route, useLocation, useNavigate} from 'react-router-dom';
|
||||||
|
import {StatusContext} from '/src/context/Status/index.jsx';import {UserContext} from '/src/context/User/index.jsx';
|
||||||
|
import CommissionV2 from '/src/pages/CommissionV2/index.jsx';
|
||||||
|
import Organization from '/src/pages/Organization/index.jsx';
|
||||||
|
import {OrgProvider} from '/src/context/Org/index.jsx';
|
||||||
|
import {SettlementDialog} from '/src/pages/CommissionV2/operations.jsx';
|
||||||
|
i18n.use(initReactI18next).init({lng:'zh',fallbackLng:'zh',resources:{zh:{translation:{}}},interpolation:{escapeValue:false}});
|
||||||
|
const user={id:1,role:100,username:'qa'};
|
||||||
|
const view=new URLSearchParams(location.search).get('view');
|
||||||
|
const section=new URLSearchParams(location.search).get('section');
|
||||||
|
function RouteProbe(){const route=useLocation();window.__qaNavigate=useNavigate();return <output hidden data-qa-route={route.pathname+route.search}/>;}
|
||||||
|
function SettlementTest(){const [operation,setOperation]=React.useState(null);return <><button onClick={()=>setOperation({kind:'fee'})}>打开测试结算</button><SettlementDialog operation={operation} statement={{id:1,fee_uyuan:0}} items={[]} mutateJSON={async()=>{}} onClose={()=>setOperation(null)} onSaved={()=>{}}/></>}
|
||||||
|
createRoot(document.getElementById('root')).render(<MemoryRouter initialEntries={[view==='org'?'/org/commission'+(section?'?view='+section:''):view==='personal'?'/console/my-commission':'/console/commission'+location.search]}><RouteProbe/><StatusContext.Provider value={[{status:{commission_partner_portal_enabled:true}},()=>{}]}><UserContext.Provider value={[{user,authChecking:false},()=>{}]}><OrgProvider>{view==='org'?<Routes><Route path='/org/*' element={<Organization/>}/></Routes>:view==='settlement'?<SettlementTest/>:<CommissionV2/>}</OrgProvider></UserContext.Provider></StatusContext.Provider></MemoryRouter>);
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
|
||||||
|
console.log('QA origin:', origin, 'Artifacts:', out);
|
||||||
|
let browser;
|
||||||
|
try {
|
||||||
|
browser = await chromium.launch({ headless: true });
|
||||||
|
} catch (error) {
|
||||||
|
await server.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const results = [];
|
||||||
|
let activeState;
|
||||||
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise((done) => {
|
||||||
|
resolve = done;
|
||||||
|
});
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
async function until(check, message) {
|
||||||
|
const end = Date.now() + 12000;
|
||||||
|
while (!(await check())) {
|
||||||
|
if (Date.now() > end) throw new Error(message || 'Timed out');
|
||||||
|
await sleep(30);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const tiers = [
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
config_id: 1,
|
||||||
|
name: '企业专用最新档',
|
||||||
|
source_type: 'channel',
|
||||||
|
source_id: 10,
|
||||||
|
channel_ids: [10],
|
||||||
|
model_names: [],
|
||||||
|
tier_key: 'G1',
|
||||||
|
rate_bps: 1000,
|
||||||
|
effective_from: now - 30,
|
||||||
|
effective_to: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
config_id: 3,
|
||||||
|
name: '真正停用档',
|
||||||
|
source_type: 'channel',
|
||||||
|
source_id: 11,
|
||||||
|
channel_ids: [11],
|
||||||
|
model_names: [],
|
||||||
|
tier_key: 'G2',
|
||||||
|
rate_bps: 500,
|
||||||
|
effective_from: now - 100,
|
||||||
|
effective_to: now - 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
config_id: 4,
|
||||||
|
name: '明日生效档',
|
||||||
|
source_type: 'model',
|
||||||
|
source_id: 0,
|
||||||
|
channel_ids: [],
|
||||||
|
model_names: ['future-model'],
|
||||||
|
tier_key: 'G3',
|
||||||
|
rate_bps: 700,
|
||||||
|
effective_from: now + 86400,
|
||||||
|
effective_to: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const oldTier = {
|
||||||
|
...tiers[0],
|
||||||
|
id: 1,
|
||||||
|
name: '不应显示的历史档',
|
||||||
|
effective_from: now - 200,
|
||||||
|
effective_to: now - 30,
|
||||||
|
};
|
||||||
|
async function setup(view = 'partners', width = 1500, section = '') {
|
||||||
|
const context = await browser.newContext({
|
||||||
|
viewport: { width, height: 1050 },
|
||||||
|
});
|
||||||
|
await context.addInitScript(() => {
|
||||||
|
localStorage.setItem('current_org_id', '101');
|
||||||
|
localStorage.setItem(
|
||||||
|
'user',
|
||||||
|
JSON.stringify({ id: 1, role: 100, username: 'qa' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.setDefaultTimeout(12000);
|
||||||
|
page.setDefaultNavigationTimeout(120000);
|
||||||
|
const state = {
|
||||||
|
context,
|
||||||
|
page,
|
||||||
|
requests: [],
|
||||||
|
writes: [],
|
||||||
|
errors: [],
|
||||||
|
mode: '',
|
||||||
|
delays: {},
|
||||||
|
orgDelays: {},
|
||||||
|
};
|
||||||
|
activeState = state;
|
||||||
|
page.on('pageerror', (error) => state.errors.push(error.message));
|
||||||
|
page.on('dialog', (dialog) => dialog.accept());
|
||||||
|
await page.route('**/*', async (route) => {
|
||||||
|
const req = route.request();
|
||||||
|
const url = new URL(req.url());
|
||||||
|
if (url.origin !== origin) {
|
||||||
|
await route.abort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!url.pathname.startsWith('/api/')) {
|
||||||
|
await route.continue();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.requests.push({
|
||||||
|
path: url.pathname,
|
||||||
|
query: Object.fromEntries(url.searchParams),
|
||||||
|
method: req.method(),
|
||||||
|
headers: req.headers(),
|
||||||
|
});
|
||||||
|
let data = [];
|
||||||
|
if (req.method() !== 'GET') {
|
||||||
|
state.writes.push({
|
||||||
|
path: url.pathname,
|
||||||
|
body: req.postDataJSON(),
|
||||||
|
headers: req.headers(),
|
||||||
|
});
|
||||||
|
data = { id: 91 };
|
||||||
|
} else if (url.pathname.startsWith('/api/org/commission/')) {
|
||||||
|
const id = Number(req.headers()['x-org-id']);
|
||||||
|
if (state.orgDelays[id]) await state.orgDelays[id];
|
||||||
|
if (/\/statements\/\d+$/.test(url.pathname) && state.detailDelay)
|
||||||
|
await state.detailDelay;
|
||||||
|
const statement = {
|
||||||
|
id: id * 10,
|
||||||
|
partner_id: id,
|
||||||
|
statement_month: '2026-11',
|
||||||
|
status: 'pending_confirmation',
|
||||||
|
payable_uyuan: 1000000,
|
||||||
|
commission_uyuan: 1000000,
|
||||||
|
};
|
||||||
|
if (url.pathname.endsWith('/summary'))
|
||||||
|
data = {
|
||||||
|
partner_status: 'active',
|
||||||
|
agreement_expires_at: now + 86400 * 60,
|
||||||
|
};
|
||||||
|
else if (url.pathname.endsWith('/statements')) data = [statement];
|
||||||
|
else if (/\/statements\/\d+$/.test(url.pathname)) data = statement;
|
||||||
|
else if (url.pathname.endsWith('/assignments'))
|
||||||
|
data = [
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
status: 'formal',
|
||||||
|
customer_name: `企业${id}客户`,
|
||||||
|
subject_type: 'organization',
|
||||||
|
subject_id: id,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
} else if (url.pathname === '/api/org/info') {
|
||||||
|
const id = Number(req.headers()['x-org-id']);
|
||||||
|
if (state.pendingOrg === id) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
code: 'org_pending_activation',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
organization: { id, name: `企业${id}`, status: 1, feature_flags: {} },
|
||||||
|
member: { role: 'admin', is_member_actor: true },
|
||||||
|
};
|
||||||
|
} else if (url.pathname === '/api/org/list') {
|
||||||
|
data = [101, 102].map((id) => ({
|
||||||
|
id,
|
||||||
|
name: `企业${id}`,
|
||||||
|
status: 1,
|
||||||
|
role: 'admin',
|
||||||
|
}));
|
||||||
|
} else if (
|
||||||
|
url.pathname.endsWith('/options/users') ||
|
||||||
|
url.pathname.endsWith('/options/organizations')
|
||||||
|
) {
|
||||||
|
const q = url.searchParams.get('q') || '';
|
||||||
|
if (state.delays[q]) await state.delays[q];
|
||||||
|
if (state.mode === 'search-error' && q) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 503,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ success: false, message: '选项查询暂不可用' }),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const user = {
|
||||||
|
id: 7,
|
||||||
|
username: 'redstar',
|
||||||
|
display_name: '红星',
|
||||||
|
disabled: false,
|
||||||
|
disabled_reason: '',
|
||||||
|
};
|
||||||
|
const org = {
|
||||||
|
id: 8,
|
||||||
|
name: '测试企业',
|
||||||
|
code: 'qa-company',
|
||||||
|
disabled: false,
|
||||||
|
disabled_reason: '',
|
||||||
|
};
|
||||||
|
const isUser = url.pathname.endsWith('/users');
|
||||||
|
const items = isUser
|
||||||
|
? ['7', '#7', '红星', 'redstar', 'slow'].includes(q)
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
...user,
|
||||||
|
...(q === 'slow'
|
||||||
|
? { id: 99, display_name: '迟到的旧结果' }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []
|
||||||
|
: [org];
|
||||||
|
data = { items, total: items.length, p: 1, page_size: 20 };
|
||||||
|
} else if (url.pathname.endsWith('/options')) {
|
||||||
|
data = {
|
||||||
|
users: [{ id: 900, username: 'recent-only', display_name: '最近用户' }],
|
||||||
|
organizations: [],
|
||||||
|
channels: [
|
||||||
|
{ id: 10, name: '测试渠道' },
|
||||||
|
{ id: 11, name: '旧渠道' },
|
||||||
|
],
|
||||||
|
models: [{ id: 'future-model', name: 'future-model' }],
|
||||||
|
levels: [],
|
||||||
|
};
|
||||||
|
} else if (url.pathname.endsWith('/tiers')) {
|
||||||
|
if (url.searchParams.get('view') === 'latest') {
|
||||||
|
let items = state.tierRows || tiers;
|
||||||
|
const pageNumber = Number(url.searchParams.get('p') || 1);
|
||||||
|
const pageSize = Number(url.searchParams.get('page_size') || 20);
|
||||||
|
if (state.exportConflict && pageNumber > 1) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
message: '档位配置已变化,请重新加载或重新导出',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const q = url.searchParams.get('q');
|
||||||
|
const source = url.searchParams.get('source_type');
|
||||||
|
const status = url.searchParams.get('status');
|
||||||
|
if (q) items = items.filter((row) => row.name.includes(q));
|
||||||
|
if (source) items = items.filter((row) => row.source_type === source);
|
||||||
|
const stateOf = (row) =>
|
||||||
|
row.effective_to
|
||||||
|
? 'disabled'
|
||||||
|
: row.effective_from > now
|
||||||
|
? 'pending'
|
||||||
|
: 'active';
|
||||||
|
const counts = {
|
||||||
|
all: items.length,
|
||||||
|
active: items.filter((r) => stateOf(r) === 'active').length,
|
||||||
|
pending: items.filter((r) => stateOf(r) === 'pending').length,
|
||||||
|
disabled: items.filter((r) => stateOf(r) === 'disabled').length,
|
||||||
|
};
|
||||||
|
if (status && status !== 'all')
|
||||||
|
items = items.filter((row) => stateOf(row) === status);
|
||||||
|
data = {
|
||||||
|
items: items.slice(
|
||||||
|
(pageNumber - 1) * pageSize,
|
||||||
|
pageNumber * pageSize,
|
||||||
|
),
|
||||||
|
total: items.length,
|
||||||
|
counts,
|
||||||
|
p: Number(url.searchParams.get('p') || 1),
|
||||||
|
page_size: Number(url.searchParams.get('page_size') || 20),
|
||||||
|
as_of: now,
|
||||||
|
revision: 3,
|
||||||
|
};
|
||||||
|
} else data = [...tiers, oldTier];
|
||||||
|
}
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ success: true, data }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.goto(
|
||||||
|
`${origin}/__commission-qa.html?view=${view}§ion=${section}`,
|
||||||
|
);
|
||||||
|
if (view === 'org')
|
||||||
|
await page.locator('[data-partner-scope="1:101"]').waitFor();
|
||||||
|
else if (view === 'personal')
|
||||||
|
await page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
else if (view === 'settlement')
|
||||||
|
await page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
else
|
||||||
|
await page
|
||||||
|
.getByText(
|
||||||
|
view === 'tiers'
|
||||||
|
? '维护统一分佣比例与状态,支持按等级、模型及渠道关联档位'
|
||||||
|
: '已完成线下准入和协议签署的外部合作伙伴档案',
|
||||||
|
{ exact: true },
|
||||||
|
)
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await page.title(), 'Commission adjustment QA');
|
||||||
|
assert.equal(await page.locator('vite-error-overlay').count(), 0);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
const field = (page, label) =>
|
||||||
|
page
|
||||||
|
.locator('.commission-form-field')
|
||||||
|
.filter({ has: page.locator('span').filter({ hasText: label }) });
|
||||||
|
async function openPartner(s) {
|
||||||
|
await s.page.getByRole('button', { name: /新建伙伴档案/ }).click();
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).waitFor();
|
||||||
|
}
|
||||||
|
async function searchUser(s, q) {
|
||||||
|
const control = field(s.page, '关联个人用户');
|
||||||
|
await control.locator('.semi-select').click();
|
||||||
|
await control.locator('input').fill(q);
|
||||||
|
}
|
||||||
|
async function test(name, run) {
|
||||||
|
if (process.env.QA_FILTER && !name.includes(process.env.QA_FILTER)) return;
|
||||||
|
let s;
|
||||||
|
try {
|
||||||
|
s = await run();
|
||||||
|
assert.deepEqual(s.errors, []);
|
||||||
|
await s.page.screenshot({
|
||||||
|
path: path.join(out, `${name}.png`),
|
||||||
|
fullPage: false,
|
||||||
|
animations: 'disabled',
|
||||||
|
});
|
||||||
|
results.push({ name, passed: true });
|
||||||
|
console.log('PASS', name);
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ name, passed: false, error: error.stack });
|
||||||
|
console.log('FAIL', name, error.message);
|
||||||
|
if (activeState) {
|
||||||
|
await activeState.page.screenshot({
|
||||||
|
path: path.join(out, `${name}-failed.png`),
|
||||||
|
});
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(out, `${name}-failed.txt`),
|
||||||
|
await activeState.page.locator('body').innerText(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (s || activeState) await (s || activeState).context.close();
|
||||||
|
activeState = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await test('organization-secondary-history-and-details', async () => {
|
||||||
|
const s = await setup('org', 1500, 'customers');
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
await s.page.reload();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('link', { name: '分佣概览', exact: true }).click();
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '提成账单详情', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的提成', exact: true })
|
||||||
|
.getAttribute('aria-current'),
|
||||||
|
'page',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('button', { name: '确认账单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor();
|
||||||
|
// Browser back dismisses an unsubmitted confirmation and invalidates detail loads.
|
||||||
|
await s.page.evaluate(() => window.__qaNavigate(-1));
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor({ state: 'hidden' });
|
||||||
|
await s.page.evaluate(() => window.__qaNavigate(1));
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的提成', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.evaluate(() =>
|
||||||
|
window.__qaNavigate('/org/commission?view=invalid'),
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-collapse-and-search', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const menu = s.page.getByRole('button', { name: '企业分佣', exact: true });
|
||||||
|
await menu.click();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'false');
|
||||||
|
await s.page
|
||||||
|
.getByRole('textbox', { name: '搜索菜单', exact: true })
|
||||||
|
.fill('提成');
|
||||||
|
await s.page.getByRole('link', { name: '我的提成', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的提成', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '清空搜索', exact: true }).click();
|
||||||
|
await s.page.getByRole('button', { name: '收起', exact: true }).click();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'false');
|
||||||
|
await menu.click();
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-mobile', async () => {
|
||||||
|
const s = await setup('org', 390);
|
||||||
|
await s.page.getByRole('button', { name: '打开菜单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await until(
|
||||||
|
async () => !(await s.page.locator('.semi-sidesheet').isVisible()),
|
||||||
|
'Mobile drawer did not close',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('.partner-portal .commission-v2-sider').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
await s.page.evaluate(
|
||||||
|
() => document.documentElement.scrollWidth <= innerWidth + 1,
|
||||||
|
),
|
||||||
|
'Page overflowed mobile viewport',
|
||||||
|
);
|
||||||
|
await s.page.screenshot({
|
||||||
|
path: path.join(out, 'organization-mobile-content.png'),
|
||||||
|
});
|
||||||
|
await s.page.getByRole('button', { name: '打开菜单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-navigation', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const menu = s.page.getByRole('button', { name: '企业分佣', exact: true });
|
||||||
|
await menu.waitFor();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'true');
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('.partner-portal .commission-v2-sider').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.getAttribute('aria-current'),
|
||||||
|
'page',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '本月预估', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '本月预估', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.getByRole('link', { name: '分佣规则', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣规则', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('personal-navigation-preserved', async () => {
|
||||||
|
const s = await setup('personal');
|
||||||
|
await s.page.getByRole('navigation', { name: '伙伴分佣导航' }).waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.ok(
|
||||||
|
!s.requests.some((r) => r.path.startsWith('/api/org/commission/')),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('user-id-remote-search', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, '7');
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/options/users') && r.query.q === '7',
|
||||||
|
),
|
||||||
|
'No remote user-ID search request',
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('红星伙伴');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(() => s.writes.length === 1, 'Partner was not saved');
|
||||||
|
assert.equal(s.writes[0].body.user_id, 7);
|
||||||
|
assert.equal(s.writes[0].body.type, 'individual');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('company-without-user', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await openPartner(s);
|
||||||
|
await s.page.getByText('企业伙伴', { exact: true }).click();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业管理员登录身份', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const org = field(s.page, '关联企业');
|
||||||
|
await org.locator('.semi-select').click();
|
||||||
|
await s.page
|
||||||
|
.getByText(/测试企业.*#8/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('企业伙伴测试');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(
|
||||||
|
() => s.writes.length === 1,
|
||||||
|
'Company requires an obsolete user identity',
|
||||||
|
);
|
||||||
|
assert.equal(s.writes[0].body.organization_id, 8);
|
||||||
|
assert.ok(!s.writes[0].body.user_id);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('search-race-keeps-new-results', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(
|
||||||
|
() => s.requests.some((r) => r.query.q === 'slow'),
|
||||||
|
'Slow request not sent',
|
||||||
|
);
|
||||||
|
await field(s.page, '关联个人用户').locator('input').fill('红星');
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('保留选择');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(() => s.writes.length === 1);
|
||||||
|
assert.equal(s.writes[0].body.user_id, 7);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('type-switch-discards-pending-user', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(() => s.requests.some((r) => r.query.q === 'slow'));
|
||||||
|
await s.page.getByText('企业伙伴', { exact: true }).click();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('关联个人用户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await field(s.page, '关联企业').locator('.semi-select').click();
|
||||||
|
await s.page
|
||||||
|
.getByText(/测试企业.*#8/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('close-reopen-discards-old-search', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(() => s.requests.some((r) => r.query.q === 'slow'));
|
||||||
|
await s.page.getByRole('button', { name: '取消', exact: true }).click();
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, '7');
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-tiers-only', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
await s.page.getByText('企业专用最新档', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('不应显示的历史档', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/tiers') && r.query.view === 'latest',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await s.page.getByText('真正停用档', { exact: true }).waitFor();
|
||||||
|
const future = s.page.locator('tr').filter({ hasText: '明日生效档' });
|
||||||
|
assert.equal(
|
||||||
|
await future.getByRole('button', { name: '停用', exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(await s.page.locator('.semi-datepicker').count(), 0);
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '绑定历史', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-status-filter-is-server-side', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
await s.page.getByText('企业专用最新档', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('tab', { name: /已停用/ }).click();
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/tiers') && r.query.status === 'disabled',
|
||||||
|
),
|
||||||
|
'Status filter only ran locally',
|
||||||
|
);
|
||||||
|
await s.page.getByText('真正停用档', { exact: true }).waitFor();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
(await s.page.getByText('企业专用最新档', { exact: true }).count()) ===
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('不应显示的历史档', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('settlement-cancel-and-close', async () => {
|
||||||
|
const s = await setup('settlement');
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.click();
|
||||||
|
await s.page.getByText('录入手续费', { exact: true }).waitFor();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '取消' })
|
||||||
|
.click();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
!(await s.page.getByText('录入手续费', { exact: true }).isVisible()),
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.click();
|
||||||
|
await s.page.getByText('录入手续费', { exact: true }).waitFor();
|
||||||
|
await s.page.locator('.semi-modal-close').click();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
!(await s.page.getByText('录入手续费', { exact: true }).isVisible()),
|
||||||
|
);
|
||||||
|
assert.equal(s.page.isClosed(), false);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-export-fetches-all-pages', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
s.tierRows = Array.from({ length: 105 }, (_, index) => ({
|
||||||
|
...tiers[0],
|
||||||
|
id: 1000 + index,
|
||||||
|
config_id: 1000 + index,
|
||||||
|
name: `导出配置${index}`,
|
||||||
|
}));
|
||||||
|
await s.page.getByRole('button', { name: /刷新/ }).click();
|
||||||
|
await s.page.getByText('导出配置0', { exact: true }).waitFor();
|
||||||
|
const download = s.page.waitForEvent('download');
|
||||||
|
await s.page.getByRole('button', { name: '导出', exact: true }).click();
|
||||||
|
const file = await download;
|
||||||
|
const exportPath = path.join(out, 'latest-all-pages.xlsx');
|
||||||
|
await file.saveAs(exportPath);
|
||||||
|
const XLSX = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/xlsx/xlsx.mjs')).href
|
||||||
|
);
|
||||||
|
const workbook = XLSX.read(fs.readFileSync(exportPath), { type: 'buffer' });
|
||||||
|
const rows = XLSX.utils.sheet_to_json(
|
||||||
|
workbook.Sheets[workbook.SheetNames[0]],
|
||||||
|
);
|
||||||
|
assert.equal(rows.length, 105);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path.endsWith('/tiers') &&
|
||||||
|
r.query.p === '2' &&
|
||||||
|
r.query.revision === '3' &&
|
||||||
|
r.query.as_of === String(now),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-export-refuses-changed-revision', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
s.tierRows = Array.from({ length: 105 }, (_, index) => ({
|
||||||
|
...tiers[0],
|
||||||
|
id: 1000 + index,
|
||||||
|
config_id: 1000 + index,
|
||||||
|
name: `变更配置${index}`,
|
||||||
|
}));
|
||||||
|
s.exportConflict = true;
|
||||||
|
let downloads = 0;
|
||||||
|
s.page.on('download', () => downloads++);
|
||||||
|
await s.page.getByRole('button', { name: /刷新/ }).click();
|
||||||
|
await s.page.getByText('变更配置0', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '导出', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-banner')
|
||||||
|
.filter({ hasText: '档位配置已变化,请重新加载或重新导出' })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(downloads, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-navigation-discards-slow-detail', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const delayed = deferred();
|
||||||
|
s.detailDelay = delayed.promise;
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await until(
|
||||||
|
() => s.requests.some((r) => /\/statements\/\d+$/.test(r.path)),
|
||||||
|
'No detail request',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
const response = s.page.waitForResponse((r) =>
|
||||||
|
/\/statements\/\d+$/.test(new URL(r.url()).pathname),
|
||||||
|
);
|
||||||
|
delayed.resolve();
|
||||||
|
await (await response).finished();
|
||||||
|
await s.page.evaluate(
|
||||||
|
() =>
|
||||||
|
new Promise((done) =>
|
||||||
|
requestAnimationFrame(() => requestAnimationFrame(done)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '提成账单详情', exact: true })
|
||||||
|
.count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.count(),
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-pending-activation-switch', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
s.pendingOrg = 102;
|
||||||
|
await s.page
|
||||||
|
.locator('select[aria-label="切换企业"]')
|
||||||
|
.first()
|
||||||
|
.selectOption('102');
|
||||||
|
await s.page.getByText('企业待激活', { exact: true }).waitFor();
|
||||||
|
assert.equal(await s.page.locator('[data-partner-scope]').count(), 0);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.evaluate(() => localStorage.getItem('current_org_id')),
|
||||||
|
'102',
|
||||||
|
);
|
||||||
|
s.pendingOrg = null;
|
||||||
|
await s.page.getByRole('button', { name: '刷新状态', exact: true }).click();
|
||||||
|
await s.page.getByText('企业102客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-switch-clears-confirmation', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await s.page.getByRole('button', { name: '确认账单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor();
|
||||||
|
// The real sidebar switch must unmount the old confirmation and pin all subsequent requests.
|
||||||
|
await s.page
|
||||||
|
.locator('select[aria-label="切换企业"]')
|
||||||
|
.first()
|
||||||
|
.selectOption('102');
|
||||||
|
await s.page.locator('[data-partner-scope="1:102"]').waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('[data-partner-scope="1:101"]').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path === '/api/org/commission/statements' &&
|
||||||
|
r.headers['x-org-id'] === '102',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert.ok(!s.requests.some((r) => r.path.startsWith('/api/partner/v2/')));
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业102客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
await server.close();
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(out, 'results.json'),
|
||||||
|
JSON.stringify(results, null, 2),
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`${results.filter((r) => r.passed).length}/${results.length} passed`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (results.some((r) => !r.passed)) process.exitCode = 1;
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { readFile, readdir } from 'node:fs/promises';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const exec = promisify(execFile);
|
||||||
|
const projectRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
|
||||||
|
export function logAddresses(bytes, encoding) {
|
||||||
|
const text = bytes.toString(
|
||||||
|
encoding || (bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8'),
|
||||||
|
);
|
||||||
|
return [
|
||||||
|
...text
|
||||||
|
.replace(/\x1b\[[0-9;]*m/g, '')
|
||||||
|
.matchAll(/(?:Local:|Network:)\s*(https?:\/\/[^\s]+)/g),
|
||||||
|
]
|
||||||
|
.map((match) => match[1])
|
||||||
|
.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function matchesProject(address, root) {
|
||||||
|
try {
|
||||||
|
const url = new URL(address);
|
||||||
|
if (
|
||||||
|
!['http:', 'https:'].includes(url.protocol) ||
|
||||||
|
url.username ||
|
||||||
|
url.password
|
||||||
|
)
|
||||||
|
return false;
|
||||||
|
const source = await readFile(path.join(root, 'src/index.jsx'), 'utf8');
|
||||||
|
const response = await fetch(new URL('src/index.jsx', url), {
|
||||||
|
signal: AbortSignal.timeout(2500),
|
||||||
|
});
|
||||||
|
if (!response.ok) return false;
|
||||||
|
const text = await response.text();
|
||||||
|
const map = text.match(
|
||||||
|
/sourceMappingURL=data:application\/json;base64,([^\s]+)/,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
!!map &&
|
||||||
|
JSON.parse(
|
||||||
|
Buffer.from(map[1], 'base64').toString(),
|
||||||
|
).sourcesContent?.includes(source)
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function nodePorts() {
|
||||||
|
if (process.platform !== 'win32') return [];
|
||||||
|
const command =
|
||||||
|
'[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; ' +
|
||||||
|
'$ids = @(Get-CimInstance Win32_Process -Filter "Name=\'node.exe\'" | Select-Object -ExpandProperty ProcessId); ' +
|
||||||
|
'Get-NetTCPConnection -State Listen -ErrorAction Stop | Where-Object { $_.OwningProcess -in $ids } | Select-Object -ExpandProperty LocalPort -Unique | ConvertTo-Json -Compress';
|
||||||
|
const { stdout } = await exec(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-Command', command],
|
||||||
|
{ timeout: 15000, windowsHide: true },
|
||||||
|
);
|
||||||
|
const parsed = JSON.parse(stdout.trim() || '[]');
|
||||||
|
return [parsed].flat().filter((port) => Number.isInteger(port) && port > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findDevService({
|
||||||
|
root = projectRoot,
|
||||||
|
getPorts = nodePorts,
|
||||||
|
} = {}) {
|
||||||
|
const candidates = [];
|
||||||
|
const entries = await readdir(root, { withFileTypes: true });
|
||||||
|
const logs = entries.filter(
|
||||||
|
(entry) => entry.isFile() && /\.log$/i.test(entry.name),
|
||||||
|
);
|
||||||
|
logs.sort(
|
||||||
|
(a, b) => Number(b.name === 'dev.log') - Number(a.name === 'dev.log'),
|
||||||
|
);
|
||||||
|
for (const entry of logs.slice(0, 8)) {
|
||||||
|
const bytes = await readFile(path.join(root, entry.name));
|
||||||
|
candidates.push(
|
||||||
|
...logAddresses(
|
||||||
|
bytes.subarray(Math.max(0, bytes.length - 262144)),
|
||||||
|
bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Only Node listeners are probed; the source map must match this checkout.
|
||||||
|
for (const address of new Set(candidates)) {
|
||||||
|
if (await matchesProject(address, root))
|
||||||
|
return new URL(address).origin + '/';
|
||||||
|
}
|
||||||
|
const ports = await getPorts();
|
||||||
|
for (const address of new Set(
|
||||||
|
ports.map((port) => 'http://127.0.0.1:' + port + '/'),
|
||||||
|
)) {
|
||||||
|
if (await matchesProject(address, root))
|
||||||
|
return new URL(address).origin + '/';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// esbuild runs in Go, so NODE_OPTIONS cannot control its heap or parallelism.
|
||||||
|
process.env.GOMEMLIMIT ||= '512MiB';
|
||||||
|
process.env.GOMAXPROCS ||= '2';
|
||||||
|
|
||||||
|
// Set Go's environment before Vite starts its esbuild service.
|
||||||
|
await import('../node_modules/vite/bin/vite.js');
|
||||||
@@ -18,7 +18,12 @@ function walk(dir, files = []) {
|
|||||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
const full = path.join(dir, entry.name);
|
const full = path.join(dir, entry.name);
|
||||||
if (entry.isDirectory()) {
|
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);
|
walk(full, files);
|
||||||
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
||||||
files.push(full);
|
files.push(full);
|
||||||
@@ -93,13 +98,13 @@ function main() {
|
|||||||
totalKeysUsedInSource: allKeys.size,
|
totalKeysUsedInSource: allKeys.size,
|
||||||
missingByLocale: missing,
|
missingByLocale: missing,
|
||||||
keyToFiles: Object.fromEntries(
|
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(
|
fs.writeFileSync(
|
||||||
path.join(__dirname, 'missing_i18n.json'),
|
path.join(__dirname, 'missing_i18n.json'),
|
||||||
JSON.stringify(out, null, 2),
|
JSON.stringify(out, null, 2),
|
||||||
'utf8'
|
'utf8',
|
||||||
);
|
);
|
||||||
console.log(`\nWrote ${path.join(__dirname, 'missing_i18n.json')}`);
|
console.log(`\nWrote ${path.join(__dirname, 'missing_i18n.json')}`);
|
||||||
|
|
||||||
|
|||||||
+174
-21
@@ -23,27 +23,136 @@ const MAX_COUNT = 300;
|
|||||||
|
|
||||||
// 优先级分层:数字越小越先翻译。一个 key 被多个区域引用时取最小值(最高优先级)。
|
// 优先级分层:数字越小越先翻译。一个 key 被多个区域引用时取最小值(最高优先级)。
|
||||||
const TIERS = [
|
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: 1,
|
||||||
{ tier: 3, name: '个人高频主链路', areas: ['pages/UserCenter', 'pages/KeyManagement', 'pages/Token', 'pages/Recharge', 'pages/TopUp', 'components/topup', 'pages/Home', 'pages/Dashboard', 'pages/Pricing'] },
|
name: '入口/认证',
|
||||||
{ 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'] },
|
areas: [
|
||||||
{ 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'] },
|
'components/auth',
|
||||||
{ tier: 6, name: '企业侧', areas: ['pages/Organization', 'pages/ExpertPlatform', 'pages/SkillPlatform', 'pages/ExperienceCenterAudit'] },
|
'pages/OrgLogin',
|
||||||
{ 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'] },
|
'pages/OrgRegister',
|
||||||
{ tier: 8, name: '分佣/合作伙伴', areas: ['pages/CommissionConsole', 'pages/MyCommission', 'pages/PartnerPortal', 'components/promotion'] },
|
'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_OTHER = 9; // 源码中有引用但未归入上表的区域
|
||||||
const TIER_DEAD = 99; // 源码已无引用的历史 key(en.json 里还在,为「一一对应」保留)
|
const TIER_DEAD = 99; // 源码已无引用的历史 key(en.json 里还在,为「一一对应」保留)
|
||||||
|
|
||||||
const AREA_TIER = new Map();
|
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) {
|
for (const { tier, name, areas } of TIERS) {
|
||||||
TIER_NAME.set(tier, name);
|
TIER_NAME.set(tier, name);
|
||||||
for (const a of areas) AREA_TIER.set(a, tier);
|
for (const a of areas) AREA_TIER.set(a, tier);
|
||||||
}
|
}
|
||||||
|
|
||||||
const load = (n) =>
|
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 本身;不另存快照文件,避免两份
|
// 已译状态唯一事实源就是 locales/{ko,th}.json 本身;不另存快照文件,避免两份
|
||||||
// 数据漂移(快照落后时会把已译 key 重新切进批次,覆盖掉已有译文)。
|
// 数据漂移(快照落后时会把已译 key 重新切进批次,覆盖掉已有译文)。
|
||||||
const loadDone = (l) => {
|
const loadDone = (l) => {
|
||||||
@@ -62,7 +171,11 @@ function walk(dir, files = []) {
|
|||||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
const full = path.join(dir, entry.name);
|
const full = path.join(dir, entry.name);
|
||||||
if (entry.isDirectory()) {
|
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);
|
walk(full, files);
|
||||||
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
||||||
files.push(full);
|
files.push(full);
|
||||||
@@ -72,15 +185,24 @@ function walk(dir, files = []) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unescape = (raw) =>
|
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 -> 最高优先级 + 代表区域
|
// 1) 建立 key -> 最高优先级 + 代表区域
|
||||||
const keyTier = new Map();
|
const keyTier = new Map();
|
||||||
const keyArea = 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 content = fs.readFileSync(file, 'utf8');
|
||||||
const rel = path.relative(SRC_DIR, file).split(path.sep);
|
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;
|
const tier = AREA_TIER.get(area) ?? TIER_OTHER;
|
||||||
let m;
|
let m;
|
||||||
T_CALL_RE.lastIndex = 0;
|
T_CALL_RE.lastIndex = 0;
|
||||||
@@ -117,7 +239,11 @@ const flush = () => {
|
|||||||
if (!batch.length) return;
|
if (!batch.length) return;
|
||||||
n += 1;
|
n += 1;
|
||||||
const name = `batch_${String(n).padStart(3, '0')}.json`;
|
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))];
|
const areas = [...new Set(batch.map((x) => x.area))];
|
||||||
manifest.push({
|
manifest.push({
|
||||||
file: name,
|
file: name,
|
||||||
@@ -134,29 +260,56 @@ const flush = () => {
|
|||||||
for (const { k, tier } of pending) {
|
for (const { k, tier } of pending) {
|
||||||
const zhText = k in zh ? zh[k] || k : k;
|
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();
|
flush();
|
||||||
}
|
}
|
||||||
curTier = tier;
|
curTier = tier;
|
||||||
// cur:各语种已有译文。批次按「任一语种未译」切,已译的那一侧回填 "" 即保留原值
|
// cur:各语种已有译文。批次按「任一语种未译」切,已译的那一侧回填 "" 即保留原值
|
||||||
const cur = Object.fromEntries(LANGS.map((l) => [l, done[l][k] || '']));
|
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;
|
used += zhText.length;
|
||||||
}
|
}
|
||||||
flush();
|
flush();
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
path.join(OUT_DIR, '_manifest.json'),
|
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',
|
'utf8',
|
||||||
);
|
);
|
||||||
|
|
||||||
const perTier = new Map();
|
const perTier = new Map();
|
||||||
for (const { tier } of pending) perTier.set(tier, (perTier.get(tier) || 0) + 1);
|
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(' / ');
|
const doneSummary = LANGS.map(
|
||||||
console.log(`en 全集 ${enKeys.length} | ${doneSummary} | 待译(任一语种缺) ${pending.length} | 切成 ${n} 批`);
|
(l) => `${l}已译 ${enKeys.filter((k) => done[l][k]).length}`,
|
||||||
|
).join(' / ');
|
||||||
|
console.log(
|
||||||
|
`en 全集 ${enKeys.length} | ${doneSummary} | 待译(任一语种缺) ${pending.length} | 切成 ${n} 批`,
|
||||||
|
);
|
||||||
console.log('待译量按优先级:');
|
console.log('待译量按优先级:');
|
||||||
for (const [tier, cnt] of [...perTier.entries()].sort((a, b) => a[0] - b[0])) {
|
for (const [tier, cnt] of [...perTier.entries()].sort((a, b) => a[0] - b[0])) {
|
||||||
const bs = manifest.filter((b) => b.tier === tier).length;
|
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)} 批`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ const BATCH_DIR = path.join(__dirname, 'kt_batches');
|
|||||||
const OUT_DIR = path.join(__dirname, 'kt_out');
|
const OUT_DIR = path.join(__dirname, 'kt_out');
|
||||||
const LANGS = require('./i18n_langs.cjs');
|
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 仍留在目录里,
|
// kt_out/ 按批次号对位,换一组语种重切批次后,旧语种的 {lng}_NNN.json 仍留在目录里,
|
||||||
// 却对应的是上一轮的批次内容;若靠长度校验兜底,同长批次会被静默错位回填。
|
// 却对应的是上一轮的批次内容;若靠长度校验兜底,同长批次会被静默错位回填。
|
||||||
// 这里要求本次语种必须属于当前批次清单的语种(旧清单无 langs 字段时按 ko,th)。
|
// 这里要求本次语种必须属于当前批次清单的语种(旧清单无 langs 字段时按 ko,th)。
|
||||||
@@ -33,11 +35,13 @@ if (foreign.length) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const enKeys = Object.keys(
|
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 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;
|
let hardFail = false;
|
||||||
|
|
||||||
@@ -54,7 +58,9 @@ for (const lng of LANGS) {
|
|||||||
|
|
||||||
for (const b of manifest.batches) {
|
for (const b of manifest.batches) {
|
||||||
const idx = b.file.match(/batch_(\d+)\.json/)[1];
|
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`);
|
const outFile = path.join(OUT_DIR, `${lng}_${idx}.json`);
|
||||||
if (!fs.existsSync(outFile)) continue;
|
if (!fs.existsSync(outFile)) continue;
|
||||||
|
|
||||||
@@ -69,7 +75,10 @@ for (const lng of LANGS) {
|
|||||||
batch.forEach((item, i) => {
|
batch.forEach((item, i) => {
|
||||||
const v = typeof vals[i] === 'string' ? vals[i] : '';
|
const v = typeof vals[i] === 'string' ? vals[i] : '';
|
||||||
if (!v) return;
|
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));
|
const unknown = [...placeholders(v)].filter((x) => !allowed.has(x));
|
||||||
if (unknown.length) {
|
if (unknown.length) {
|
||||||
problems.push(
|
problems.push(
|
||||||
@@ -92,7 +101,9 @@ for (const lng of LANGS) {
|
|||||||
if (!v) continue;
|
if (!v) continue;
|
||||||
if (k.startsWith('_')) continue; // "_" 前缀留给文件内注释
|
if (k.startsWith('_')) continue; // "_" 前缀留给文件内注释
|
||||||
if (!enKeys.includes(k)) {
|
if (!enKeys.includes(k)) {
|
||||||
console.error(`[${lng}] 覆盖项 ${JSON.stringify(k)} 不在 en.json 中,已跳过`);
|
console.error(
|
||||||
|
`[${lng}] 覆盖项 ${JSON.stringify(k)} 不在 en.json 中,已跳过`,
|
||||||
|
);
|
||||||
hardFail = true;
|
hardFail = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -110,7 +121,11 @@ for (const lng of LANGS) {
|
|||||||
Object.keys(ordered).length === enKeys.length &&
|
Object.keys(ordered).length === enKeys.length &&
|
||||||
Object.keys(ordered).every((k, i) => k === enKeys[i]);
|
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(
|
console.log(
|
||||||
`[${lng}] keys=${enKeys.length} 已译=${filled} (原有${baseCount} + 新增${added} + 覆盖${overridden}) 待译=${enKeys.length - filled} key与en一一对应=${okKeys ? 'YES' : 'NO'}`,
|
`[${lng}] keys=${enKeys.length} 已译=${filled} (原有${baseCount} + 新增${added} + 覆盖${overridden}) 待译=${enKeys.length - filled} key与en一一对应=${okKeys ? 'YES' : 'NO'}`,
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ const SRC_DIR = path.join(__dirname, '..', 'src');
|
|||||||
const LANGS = require('./i18n_langs.cjs');
|
const LANGS = require('./i18n_langs.cjs');
|
||||||
|
|
||||||
const load = (n) =>
|
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 T_CALL_RE = /\bt\(\s*(['"`])((?:\\.|(?!\1).)*?)\1/g;
|
||||||
const CJK_RE = /[一-鿿]/;
|
const CJK_RE = /[一-鿿]/;
|
||||||
@@ -19,7 +20,11 @@ function walk(dir, files = []) {
|
|||||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
const full = path.join(dir, entry.name);
|
const full = path.join(dir, entry.name);
|
||||||
if (entry.isDirectory()) {
|
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);
|
walk(full, files);
|
||||||
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) {
|
||||||
files.push(full);
|
files.push(full);
|
||||||
@@ -38,7 +43,9 @@ function unescape(raw) {
|
|||||||
|
|
||||||
const dicts = Object.fromEntries(LANGS.map((l) => [l, load(l)]));
|
const dicts = Object.fromEntries(LANGS.map((l) => [l, load(l)]));
|
||||||
const primary = dicts[LANGS[0]];
|
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 byArea = new Map();
|
||||||
const allUsed = new Set();
|
const allUsed = new Set();
|
||||||
@@ -49,7 +56,9 @@ for (const file of files) {
|
|||||||
// 粒度必须与 i18n_kt_batches.cjs 的分层一致:components 也要拆到子目录,
|
// 粒度必须与 i18n_kt_batches.cjs 的分层一致:components 也要拆到子目录,
|
||||||
// 否则 2800 多个 key 全折叠成一个 'components',看不出各子区域是否打满。
|
// 否则 2800 多个 key 全折叠成一个 'components',看不出各子区域是否打满。
|
||||||
const area =
|
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;
|
let m;
|
||||||
T_CALL_RE.lastIndex = 0;
|
T_CALL_RE.lastIndex = 0;
|
||||||
while ((m = T_CALL_RE.exec(content)) !== null) {
|
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)}%)`);
|
console.log(` ${l} 已译:${d} (${Math.round((d / used.length) * 100)}%)`);
|
||||||
}
|
}
|
||||||
const absent = used.filter((k) => !(k in primary)).length;
|
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()]
|
const stats = [...byArea.entries()]
|
||||||
.map(([area, set]) => {
|
.map(([area, set]) => {
|
||||||
const arr = [...set];
|
const arr = [...set];
|
||||||
const done = arr.filter((k) => primary[k]).length;
|
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)
|
.filter((r) => r.total >= 25)
|
||||||
.sort((a, b) => a.pct - b.pct);
|
.sort((a, b) => a.pct - b.pct);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// 找出会溢出的具体位置。控制台是围绕中文两字标签设计的,泰语平均膨胀 3.16x,
|
// 找出会溢出的具体位置。控制台是围绕中文两字标签设计的,泰语平均膨胀 3.16x,
|
||||||
// 短标签最高 9x,密集表格首当其冲。
|
// 短标签最高 9x,密集表格首当其冲。
|
||||||
//
|
//
|
||||||
// 判据:Semi 的 Table column `width: N`(px)在 14px 字号下大致可容
|
// 判据:表格列的 `width: N`(px)在 14px 字号下大致可容
|
||||||
// 中文 ≈ N/14 字,拉丁/泰文 ≈ N/7.5 字符(泰文含上下叠加符号,按拉丁估更保守)。
|
// 中文 ≈ N/14 字,拉丁/泰文 ≈ N/7.5 字符(泰文含上下叠加符号,按拉丁估更保守)。
|
||||||
// 超出即报,按超出比例排序。这是静态估算,不替代真机目视走查。
|
// 超出即报,按超出比例排序。这是静态估算,不替代真机目视走查。
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
@@ -12,20 +12,25 @@ const path = require('path');
|
|||||||
const SRC_DIR = path.join(__dirname, '..', 'src');
|
const SRC_DIR = path.join(__dirname, '..', 'src');
|
||||||
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
|
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
|
||||||
const load = (n) =>
|
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 LANGS = require('./i18n_langs.cjs');
|
||||||
const DICTS = LANGS.map((l) => [l, load(l)]);
|
const DICTS = LANGS.map((l) => [l, load(l)]);
|
||||||
|
|
||||||
const PX_PER_CHAR = 7.5; // 拼音文字/韩/泰在 14px 下的保守平均字宽
|
const PX_PER_CHAR = 7.5; // 拼音文字/韩/泰在 14px 下的保守平均字宽
|
||||||
// 日文假名与汉字、繁体中文都是全角,按字号整宽计
|
// 日文假名与汉字、繁体中文都是全角,按字号整宽计
|
||||||
const PX_PER_CHAR_BY_LANG = { ja: 14, 'zh-TW': 14 };
|
const PX_PER_CHAR_BY_LANG = { ja: 14, 'zh-TW': 14 };
|
||||||
const PADDING = 24; // Semi 表头左右内边距 + 排序图标余量
|
const PADDING = 24; // 表头左右内边距及排序图标的估算余量
|
||||||
|
|
||||||
function walk(dir, files = []) {
|
function walk(dir, files = []) {
|
||||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
const full = path.join(dir, entry.name);
|
const full = path.join(dir, entry.name);
|
||||||
if (entry.isDirectory()) {
|
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);
|
walk(full, files);
|
||||||
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) files.push(full);
|
} else if (/\.(jsx?|tsx?)$/.test(entry.name)) files.push(full);
|
||||||
}
|
}
|
||||||
@@ -43,7 +48,9 @@ const COL_RE2 =
|
|||||||
const CJK = /[一-鿿]/;
|
const CJK = /[一-鿿]/;
|
||||||
const rows = [];
|
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 c = fs.readFileSync(file, 'utf8');
|
||||||
const rel = path.relative(SRC_DIR, file);
|
const rel = path.relative(SRC_DIR, file);
|
||||||
const push = (key, width) => {
|
const push = (key, width) => {
|
||||||
@@ -83,7 +90,9 @@ const uniq = rows.filter((r) => {
|
|||||||
return true;
|
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`);
|
console.log(`固定列宽装不下译文的位置:${uniq.length} 处(${perLang})\n`);
|
||||||
const LIMIT = Number(process.argv[2]) || 30; // 可传参查看全部
|
const LIMIT = Number(process.argv[2]) || 30; // 可传参查看全部
|
||||||
for (const r of uniq.slice(0, LIMIT)) {
|
for (const r of uniq.slice(0, LIMIT)) {
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
// 不传时保持历史行为(ko,th)。同一轮 batches → 回填 → build 必须用同一组语种,
|
// 不传时保持历史行为(ko,th)。同一轮 batches → 回填 → build 必须用同一组语种,
|
||||||
// 因为 kt_batches/ 按这组语种的「任一未译」切批。
|
// 因为 kt_batches/ 按这组语种的「任一未译」切批。
|
||||||
const arg = process.argv.find((a) => a.startsWith('--langs='));
|
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
|
module.exports = raw
|
||||||
.split(',')
|
.split(',')
|
||||||
|
|||||||
@@ -17,13 +17,16 @@ let OpenCC;
|
|||||||
try {
|
try {
|
||||||
OpenCC = require(process.env.OPENCC_JS || 'opencc-js');
|
OpenCC = require(process.env.OPENCC_JS || 'opencc-js');
|
||||||
} catch (e) {
|
} 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);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
|
const LOCALES_DIR = path.join(__dirname, '..', 'src', 'i18n', 'locales');
|
||||||
const load = (n) =>
|
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 会把 审核 与 审计 都转成「稽核」,
|
||||||
// 转换后已无法区分,只能在源文本上先把 审核 定成繁体「審核」(OpenCC 不再改动繁体字)。
|
// 转换后已无法区分,只能在源文本上先把 审核 定成繁体「審核」(OpenCC 不再改动繁体字)。
|
||||||
@@ -71,14 +74,17 @@ for (const k of enKeys) {
|
|||||||
const src = zh[k] || k.replace(/_(zero|one|two|few|many|other)$/, '');
|
const src = zh[k] || k.replace(/_(zero|one|two|few|many|other)$/, '');
|
||||||
const v = convert(src);
|
const v = convert(src);
|
||||||
// 占位符是 ASCII,转换不应动到;这里兜底校验,防止词典误伤插值名
|
// 占位符是 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;
|
out[k] = v;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ovPath = path.join(__dirname, 'zhtw_overrides.json');
|
const ovPath = path.join(__dirname, 'zhtw_overrides.json');
|
||||||
let overridden = 0;
|
let overridden = 0;
|
||||||
if (fs.existsSync(ovPath)) {
|
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.startsWith('_') || !v) continue;
|
||||||
if (!(k in out)) {
|
if (!(k in out)) {
|
||||||
problems.push(`覆盖项 ${JSON.stringify(k)} 不在 en.json 中`);
|
problems.push(`覆盖项 ${JSON.stringify(k)} 不在 en.json 中`);
|
||||||
@@ -95,7 +101,9 @@ fs.writeFileSync(
|
|||||||
'utf8',
|
'utf8',
|
||||||
);
|
);
|
||||||
const changed = enKeys.filter((k) => out[k] !== (zh[k] || k)).length;
|
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) {
|
if (problems.length) {
|
||||||
console.error(`[zh-TW] 异常 ${problems.length} 条:`);
|
console.error(`[zh-TW] 异常 ${problems.length} 条:`);
|
||||||
problems.slice(0, 30).forEach((p) => console.error(' ' + p));
|
problems.slice(0, 30).forEach((p) => console.error(' ' + p));
|
||||||
|
|||||||
+1945
-5835
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,724 @@
|
|||||||
|
/**
|
||||||
|
* Isolated browser regression for the real model-cost settings components.
|
||||||
|
* No backend is started: every /api/ request is mocked; off-origin traffic is blocked.
|
||||||
|
* Requires existing web/node_modules and an externally available Playwright + Chromium.
|
||||||
|
* PowerShell example:
|
||||||
|
* $env:PLAYWRIGHT_MODULE='C:/path/to/node_modules/playwright/index.mjs'
|
||||||
|
* node web/scripts/model-cost-qa.mjs
|
||||||
|
* Optional: COST_QA_OUTPUT (artifact directory), QA_FILTER (case-name substring).
|
||||||
|
* Browser plugin not available in the authoring environment; regular Playwright used.
|
||||||
|
*/
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
const webRoot = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
'..',
|
||||||
|
);
|
||||||
|
const out =
|
||||||
|
process.env.COST_QA_OUTPUT ||
|
||||||
|
fs.mkdtempSync(path.join(os.tmpdir(), 'model-cost-qa-'));
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
const playwrightModule = process.env.PLAYWRIGHT_MODULE;
|
||||||
|
const { chromium } = await import(
|
||||||
|
playwrightModule
|
||||||
|
? pathToFileURL(path.resolve(playwrightModule)).href
|
||||||
|
: 'playwright'
|
||||||
|
);
|
||||||
|
const { createServer, loadConfigFromFile } = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/vite/dist/node/index.js')).href
|
||||||
|
);
|
||||||
|
const loadedConfig = await loadConfigFromFile(
|
||||||
|
{ command: 'serve', mode: 'development' },
|
||||||
|
path.join(webRoot, 'vite.config.js'),
|
||||||
|
);
|
||||||
|
const base = loadedConfig.config;
|
||||||
|
const entry = path.join(webRoot, 'src/__cost-test.jsx').replaceAll('\\', '/');
|
||||||
|
const server = await createServer({
|
||||||
|
...base,
|
||||||
|
configFile: false,
|
||||||
|
root: webRoot,
|
||||||
|
cacheDir: path.join(out, 'vite-cache'),
|
||||||
|
optimizeDeps: { ...base.optimizeDeps, force: false },
|
||||||
|
server: { host: '127.0.0.1', port: 0, strictPort: false, proxy: {} },
|
||||||
|
plugins: [
|
||||||
|
...base.plugins,
|
||||||
|
{
|
||||||
|
name: 'isolated-model-cost-qa',
|
||||||
|
configureServer(vite) {
|
||||||
|
vite.middlewares.use('/api/', (_req, res) => {
|
||||||
|
res.statusCode = 503;
|
||||||
|
res.end('QA requires browser request interception');
|
||||||
|
});
|
||||||
|
vite.middlewares.use('/__cost-test.html', async (_req, res) => {
|
||||||
|
res.setHeader('Content-Type', 'text/html');
|
||||||
|
res.end(
|
||||||
|
await vite.transformIndexHtml(
|
||||||
|
'/__cost-test.html',
|
||||||
|
'<html><head><title>Cost settings QA</title></head><body><div id="root"></div><script type="module" src="/__cost-test.jsx"></script></body></html>',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
resolveId(id) {
|
||||||
|
if (id === '/__cost-test.jsx') return entry;
|
||||||
|
},
|
||||||
|
load(id) {
|
||||||
|
if (id === entry)
|
||||||
|
return `
|
||||||
|
import '/src/styles/tokens.css';import '/src/index.css';import '/src/styles/org.css';
|
||||||
|
import React from 'react';import {createRoot} from 'react-dom/client';
|
||||||
|
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';
|
||||||
|
import {MemoryRouter} from 'react-router-dom';
|
||||||
|
import {StatusProvider} from '/src/context/Status/index.jsx';import {UserProvider} from '/src/context/User/index.jsx';
|
||||||
|
import RatioSetting from '/src/components/settings/RatioSetting.jsx';
|
||||||
|
import ModelCostSettings from '/src/pages/Setting/Ratio/ModelCostSettings.jsx';
|
||||||
|
i18n.use(initReactI18next).init({lng:'zh',fallbackLng:'zh',resources:{zh:{translation:{}}},interpolation:{escapeValue:false}});
|
||||||
|
createRoot(document.getElementById('root')).render(<MemoryRouter><StatusProvider><UserProvider><div style={{padding:20}}>{location.search.includes('direct')?<ModelCostSettings/>:<RatioSetting/>}</div></UserProvider></StatusProvider></MemoryRouter>);
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const origin = 'http://127.0.0.1:' + server.httpServer.address().port;
|
||||||
|
console.log('QA origin:', origin, 'Artifacts:', out);
|
||||||
|
let browser;
|
||||||
|
try {
|
||||||
|
browser = await chromium.launch({ headless: true });
|
||||||
|
} catch (error) {
|
||||||
|
await server.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const results = [];
|
||||||
|
const allRequests = [];
|
||||||
|
const allErrors = [];
|
||||||
|
let active;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
async function until(predicate) {
|
||||||
|
const deadline = Date.now() + 12000;
|
||||||
|
while (!predicate()) {
|
||||||
|
if (Date.now() > deadline)
|
||||||
|
throw new Error('Timed out waiting for intercepted request');
|
||||||
|
await sleep(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise((r) => (resolve = r));
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
async function setup({
|
||||||
|
direct = true,
|
||||||
|
role = 100,
|
||||||
|
channels = true,
|
||||||
|
viewport = { width: 1500, height: 1000 },
|
||||||
|
} = {}) {
|
||||||
|
const ctx = await browser.newContext({ viewport });
|
||||||
|
await ctx.addInitScript(
|
||||||
|
(role) =>
|
||||||
|
localStorage.setItem(
|
||||||
|
'user',
|
||||||
|
JSON.stringify({ id: 1, role, username: 'qa' }),
|
||||||
|
),
|
||||||
|
role,
|
||||||
|
);
|
||||||
|
const p = await ctx.newPage();
|
||||||
|
p.setDefaultTimeout(12000);
|
||||||
|
p.setDefaultNavigationTimeout(120000);
|
||||||
|
p.on('dialog', (d) => d.accept());
|
||||||
|
const s = {
|
||||||
|
p,
|
||||||
|
ctx,
|
||||||
|
requests: [],
|
||||||
|
writes: [],
|
||||||
|
errors: [],
|
||||||
|
readMode: 'normal',
|
||||||
|
writeMode: 'normal',
|
||||||
|
readGates: {},
|
||||||
|
writeGate: null,
|
||||||
|
channels,
|
||||||
|
};
|
||||||
|
active = s;
|
||||||
|
p.on('pageerror', (e) => s.errors.push(e.message));
|
||||||
|
p.on('console', (m) => {
|
||||||
|
if (m.type() === 'error' && !m.text().startsWith('Warning:'))
|
||||||
|
allErrors.push(m.text());
|
||||||
|
});
|
||||||
|
await p.route('**/*', async (route) => {
|
||||||
|
const r = route.request(),
|
||||||
|
u = new URL(r.url());
|
||||||
|
if (u.origin !== origin) {
|
||||||
|
await route.abort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!u.pathname.startsWith('/api/')) return route.continue();
|
||||||
|
const event = {
|
||||||
|
method: r.method(),
|
||||||
|
path: u.pathname,
|
||||||
|
key: u.searchParams.get('scope_key'),
|
||||||
|
body: r.postDataJSON(),
|
||||||
|
};
|
||||||
|
s.requests.push(event);
|
||||||
|
allRequests.push(event);
|
||||||
|
const ok = (data) => route.fulfill({ json: { success: true, data } });
|
||||||
|
const path = u.pathname,
|
||||||
|
k = event.key || '1';
|
||||||
|
if (r.method() !== 'GET') {
|
||||||
|
s.writes.push(event);
|
||||||
|
if (s.writeGate) await s.writeGate.promise;
|
||||||
|
if (s.writeMode === 'network') return route.abort('failed');
|
||||||
|
if (s.writeMode === 'business-reject')
|
||||||
|
return route.fulfill({
|
||||||
|
json: { success: false, message: 'mock rejected write' },
|
||||||
|
});
|
||||||
|
if (s.writeMode === 'reject')
|
||||||
|
return route.fulfill({
|
||||||
|
status: 500,
|
||||||
|
json: { success: false, message: 'mock write failure' },
|
||||||
|
});
|
||||||
|
return ok({ created: 1, updated: 1, closed: 1, deleted: 1 });
|
||||||
|
}
|
||||||
|
if (path === '/api/channel/')
|
||||||
|
return ok({
|
||||||
|
items: channels
|
||||||
|
? [
|
||||||
|
{ id: 1, name: 'Channel A', status: 1 },
|
||||||
|
{ id: 2, name: 'Channel B', status: 1 },
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
total: channels ? 2 : 0,
|
||||||
|
});
|
||||||
|
if (path === '/api/option/') return ok([]);
|
||||||
|
if (path.endsWith('/uncovered')) return ok({ total: 0, items: [] });
|
||||||
|
if (path.includes('/commission/costs/')) {
|
||||||
|
const capturedMode = s.readMode;
|
||||||
|
const gate = s.readGates[k];
|
||||||
|
if (gate) await gate.promise;
|
||||||
|
if (capturedMode === 'network') return route.abort('failed');
|
||||||
|
if (capturedMode === '500' || (capturedMode === 'failB' && k === '2'))
|
||||||
|
return route.fulfill({
|
||||||
|
status: 500,
|
||||||
|
json: { message: 'internal stack not for display' },
|
||||||
|
});
|
||||||
|
if (capturedMode.startsWith('410'))
|
||||||
|
return route.fulfill({
|
||||||
|
status: 410,
|
||||||
|
json: {
|
||||||
|
success: false,
|
||||||
|
message:
|
||||||
|
capturedMode === '410-valid'
|
||||||
|
? '旧版分佣已停用:测试说明'
|
||||||
|
: capturedMode === '410-object'
|
||||||
|
? { bad: true }
|
||||||
|
: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (path.endsWith('scope_models'))
|
||||||
|
return ok({
|
||||||
|
models: [
|
||||||
|
{
|
||||||
|
model_name: `model-${k === '1' ? 'A' : 'B'}`,
|
||||||
|
units: [{ unit: 'input_1m', tier_key: '' }],
|
||||||
|
enabled_channels: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
official: { [`model-${k === '1' ? 'A' : 'B'}`]: { input: 10 } },
|
||||||
|
});
|
||||||
|
return ok([
|
||||||
|
{
|
||||||
|
id: Number(k) * 100 + 1,
|
||||||
|
scope: 'channel',
|
||||||
|
scope_key: k,
|
||||||
|
model_name: `model-${k === '1' ? 'A' : 'B'}`,
|
||||||
|
unit: 'input_1m',
|
||||||
|
tier_key: '',
|
||||||
|
cost_uyuan_per_unit: Number(k) * 1000000,
|
||||||
|
effective_from: 1,
|
||||||
|
effective_to: 0,
|
||||||
|
note: 'original',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return ok([]);
|
||||||
|
});
|
||||||
|
s.goto = async () => {
|
||||||
|
await p.goto(origin + '/__cost-test.html' + (direct ? '?direct' : ''), {
|
||||||
|
waitUntil: 'domcontentloaded',
|
||||||
|
});
|
||||||
|
await p
|
||||||
|
.getByText(direct ? '渠道' : '模型倍率设置', { exact: true })
|
||||||
|
.first()
|
||||||
|
.waitFor();
|
||||||
|
};
|
||||||
|
s.close = async () => {
|
||||||
|
assert.deepEqual(s.errors, [], 'no page runtime errors');
|
||||||
|
await ctx.close();
|
||||||
|
};
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
async function loaded(s, model = 'A') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').first().waitFor();
|
||||||
|
await s.p
|
||||||
|
.getByText('model-' + model, { exact: true })
|
||||||
|
.first()
|
||||||
|
.waitFor();
|
||||||
|
}
|
||||||
|
const button = (p, name) =>
|
||||||
|
p
|
||||||
|
.locator('button')
|
||||||
|
.filter({ hasText: new RegExp('^' + name + '$') })
|
||||||
|
.first();
|
||||||
|
const modal = (p) =>
|
||||||
|
p.locator('.semi-modal-content').filter({ visible: true }).last();
|
||||||
|
async function confirm(p, label) {
|
||||||
|
await p.getByText(label, { exact: true }).last().click();
|
||||||
|
}
|
||||||
|
async function choose(s, id) {
|
||||||
|
await s.p.locator('.semi-select').first().click();
|
||||||
|
await s.p
|
||||||
|
.getByText(`#${id} Channel ${id === 1 ? 'A' : 'B'}`, { exact: true })
|
||||||
|
.click();
|
||||||
|
}
|
||||||
|
async function refresh(s) {
|
||||||
|
await button(s.p, '刷新').click();
|
||||||
|
}
|
||||||
|
async function noWrites(s) {
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
}
|
||||||
|
async function history(s) {
|
||||||
|
await button(s.p, '版本(1)').click();
|
||||||
|
}
|
||||||
|
async function advanced(s) {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '编辑').click();
|
||||||
|
await s.p.getByText('编辑价格版本', { exact: true }).waitFor();
|
||||||
|
}
|
||||||
|
async function modalOk(s) {
|
||||||
|
await modal(s.p).locator('.semi-modal-footer button').last().click();
|
||||||
|
}
|
||||||
|
async function test(name, fn) {
|
||||||
|
if (process.env.QA_FILTER && !name.includes(process.env.QA_FILTER)) return;
|
||||||
|
let s;
|
||||||
|
try {
|
||||||
|
s = await fn();
|
||||||
|
if (s) await s.close();
|
||||||
|
results.push({ name, pass: true });
|
||||||
|
console.log('PASS', name);
|
||||||
|
} catch (e) {
|
||||||
|
results.push({ name, pass: false, error: e.stack });
|
||||||
|
console.error('FAIL', name, e.message);
|
||||||
|
console.error('BODY', await active.p.locator('body').innerText());
|
||||||
|
await active.p.screenshot({
|
||||||
|
path: out + '/failure-' + results.length + '.png',
|
||||||
|
});
|
||||||
|
await active.ctx.close();
|
||||||
|
}
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-results.json',
|
||||||
|
JSON.stringify(results, null, 2),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await test('lazy mounting, first cost load, tab draft persistence', async () => {
|
||||||
|
const s = await setup({ direct: false });
|
||||||
|
await s.goto();
|
||||||
|
await sleep(300);
|
||||||
|
assert.equal(
|
||||||
|
s.requests.filter((r) => r.path.includes('/commission/costs')).length,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).click();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await s.p.getByText('模型倍率设置', { exact: true }).first().click();
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).click();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-tabs.png' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('non Root has no cost tab', async () => {
|
||||||
|
const s = await setup({ direct: false, role: 10 });
|
||||||
|
await s.goto();
|
||||||
|
assert.equal(
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('A dirty -> B 500 clears A and prevents all writes', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
s.readMode = 'failB';
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await s.p
|
||||||
|
.getByText('错误:加载成本配置失败,请重试', { exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-cross-channel.png' });
|
||||||
|
await noWrites(s);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('A slow B fast keeps B snapshot after A completes', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const gate = deferred();
|
||||||
|
s.readGates['1'] = gate;
|
||||||
|
await s.goto();
|
||||||
|
await choose(s, 2);
|
||||||
|
await loaded(s, 'B');
|
||||||
|
gate.resolve();
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
|
||||||
|
assert.equal(await s.p.getByText('model-A', { exact: true }).count(), 0);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('8');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(s.writes[0].body.scope_key, '2');
|
||||||
|
assert.equal(s.writes[0].body.items[0].model_name, 'model-B');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('old failed request cannot toast or unlock newer B pending read', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const a = deferred(),
|
||||||
|
b = deferred();
|
||||||
|
s.readMode = '500';
|
||||||
|
s.readGates['1'] = a;
|
||||||
|
await s.goto();
|
||||||
|
await sleep(100);
|
||||||
|
s.readMode = 'normal';
|
||||||
|
s.readGates['2'] = b;
|
||||||
|
await choose(s, 2);
|
||||||
|
await until(() => s.requests.filter((r) => r.key === '2').length === 2);
|
||||||
|
a.resolve();
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(await s.p.locator('.semi-toast-content').count(), 0);
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
b.resolve();
|
||||||
|
await loaded(s, 'B');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('invalid draft switch cancel preserves; confirm discards', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('-2');
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '留在当前渠道');
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '-2');
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await loaded(s, 'B');
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('same-channel failed refresh retains readonly draft then confirms recovery', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
s.readMode = '500';
|
||||||
|
await refresh(s);
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
await s.p
|
||||||
|
.getByText('错误:加载成本配置失败,请重试', { exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
assert(await s.p.getByPlaceholder('成本单价').isDisabled());
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
s.readMode = 'normal';
|
||||||
|
await refresh(s);
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '1');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('clear selection confirms dirty draft, disables writes, no empty scope GET', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await s.p.locator('.semi-select').first().hover();
|
||||||
|
await s.p.locator('.semi-select-clear').first().click();
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
assert(
|
||||||
|
!s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path.includes('/commission/costs/') &&
|
||||||
|
!r.path.endsWith('uncovered') &&
|
||||||
|
r.key === '',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('no channel defaults has no scoped requests or writes', async () => {
|
||||||
|
const s = await setup({ channels: false });
|
||||||
|
await s.goto();
|
||||||
|
await sleep(100);
|
||||||
|
assert(!s.requests.some((r) => r.path.endsWith('scope_models')));
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const mode of ['410-valid', '410-empty', '410-object', '500', 'network'])
|
||||||
|
await test('error presentation ' + mode, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
s.readMode = mode;
|
||||||
|
await s.goto();
|
||||||
|
const expected =
|
||||||
|
mode === '410-valid'
|
||||||
|
? '错误:旧版分佣已停用:测试说明'
|
||||||
|
: '错误:加载成本配置失败,请重试';
|
||||||
|
await s.p.getByText(expected, { exact: true }).waitFor();
|
||||||
|
assert.equal(await s.p.locator('.semi-toast-content').count(), 1);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
await noWrites(s);
|
||||||
|
if (mode === '410-valid') await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-410.png' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const kind of ['save', 'save-delete', 'discount', 'advanced', 'delete'])
|
||||||
|
await test('write lock and payload ' + kind, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
s.writeGate = deferred();
|
||||||
|
let submit;
|
||||||
|
if (kind === 'save') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
submit = button(s.p, '保存成本价');
|
||||||
|
}
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
submit = s.p.getByText('确认保存', { exact: true });
|
||||||
|
}
|
||||||
|
if (kind === 'discount') {
|
||||||
|
await button(s.p, '按官方价折扣批量定价').click();
|
||||||
|
await s.p.getByText('覆盖(新开一版价格)', { exact: true }).click();
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
if (kind === 'advanced') {
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
if (kind === 'delete') {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
await submit.evaluate((el) => {
|
||||||
|
el.click();
|
||||||
|
el.click();
|
||||||
|
});
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
assert(await button(s.p, '刷新').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
assert(
|
||||||
|
await s.p
|
||||||
|
.locator('.semi-select')
|
||||||
|
.first()
|
||||||
|
.getAttribute('class')
|
||||||
|
.then((v) => v.includes('disabled')),
|
||||||
|
);
|
||||||
|
const w = s.writes[0];
|
||||||
|
if (['save', 'discount'].includes(kind)) {
|
||||||
|
assert.equal(w.body.scope, 'channel');
|
||||||
|
assert.equal(w.body.scope_key, '1');
|
||||||
|
if (kind === 'save') {
|
||||||
|
assert.equal(w.body.items[0].model_name, 'model-A');
|
||||||
|
assert.equal(w.body.items[0].cost_uyuan_per_unit, 7000000);
|
||||||
|
} else {
|
||||||
|
assert.deepEqual(w.body.model_names, ['model-A']);
|
||||||
|
assert.equal(w.body.discount, 0.2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (kind === 'advanced') {
|
||||||
|
assert.equal(w.body[0].scope_key, '1');
|
||||||
|
assert.equal(w.body[0].model_name, 'model-A');
|
||||||
|
assert.equal(w.body[0].id, 101);
|
||||||
|
assert.equal(w.body[0].cost_uyuan_per_unit, 9000000);
|
||||||
|
}
|
||||||
|
if (kind === 'save-delete') assert.deepEqual(w.body.ids, [101]);
|
||||||
|
if (kind === 'delete') assert(w.path.endsWith('/101'));
|
||||||
|
s.writeGate.resolve();
|
||||||
|
await sleep(250);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const mode of ['reject', 'business-reject', 'network'])
|
||||||
|
await test('failed delete retains inline draft ' + mode, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
s.writeMode = mode;
|
||||||
|
await modalOk(s);
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.filter(
|
||||||
|
(r) => r.method === 'GET' && r.path.endsWith('scope_models'),
|
||||||
|
).length === 2,
|
||||||
|
);
|
||||||
|
await s.p.waitForFunction(() => {
|
||||||
|
const input = document.querySelector('input[placeholder="成本单价"]');
|
||||||
|
return input && !input.disabled;
|
||||||
|
});
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
assert.equal(await button(s.p, '保存成本价').isEnabled(), true);
|
||||||
|
assert.equal(s.writes.length, 1, 'failed deletion must not auto-retry');
|
||||||
|
assert.equal(s.writes[0].method, 'DELETE');
|
||||||
|
assert.equal(s.writes[0].path, '/api/commission/costs/101');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const failRead of [false, true])
|
||||||
|
await test(
|
||||||
|
'failed advanced write retains draft, read ' +
|
||||||
|
(failRead ? 'fails' : 'succeeds'),
|
||||||
|
async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
await modal(s.p).locator('input').last().fill('keep draft');
|
||||||
|
s.writeMode = 'reject';
|
||||||
|
if (failRead) s.readMode = '500';
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(350);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').first().inputValue(),
|
||||||
|
'9',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').last().inputValue(),
|
||||||
|
'keep draft',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p)
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.last()
|
||||||
|
.isDisabled(),
|
||||||
|
failRead,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
if (!failRead) {
|
||||||
|
s.writeMode = 'normal';
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(s.writes.length, 2);
|
||||||
|
assert.equal(s.writes[1].body[0].cost_uyuan_per_unit, 9000000);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
for (const kind of ['save-delete', 'discount', 'advanced', 'delete'])
|
||||||
|
await test('stale confirmation after reload rejects ' + kind, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
}
|
||||||
|
if (kind === 'discount')
|
||||||
|
await button(s.p, '按官方价折扣批量定价').click();
|
||||||
|
if (kind === 'advanced') await advanced(s);
|
||||||
|
if (kind === 'delete') {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
}
|
||||||
|
// Native DOM click exercises the underlying refresh handler while an old modal remains mounted.
|
||||||
|
await button(s.p, '刷新').evaluate((el) => el.click());
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
}
|
||||||
|
await sleep(150);
|
||||||
|
const old =
|
||||||
|
kind === 'save-delete'
|
||||||
|
? s.p.getByText('确认保存', { exact: true })
|
||||||
|
: kind === 'delete'
|
||||||
|
? modal(s.p).locator('.semi-modal-footer button').last()
|
||||||
|
: modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
// The refresh may unmount the dialog between count and click; inspect
|
||||||
|
// and click any surviving controls atomically without locator retries.
|
||||||
|
await old.evaluateAll((elements) => elements.forEach((el) => el.click()));
|
||||||
|
await noWrites(s);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const action of ['edit', 'cancel'])
|
||||||
|
await test('pending failed advanced PUT ' + action, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
s.writeMode = 'reject';
|
||||||
|
s.writeGate = deferred();
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(100);
|
||||||
|
if (action === 'edit')
|
||||||
|
await modal(s.p).locator('input').last().fill('typed while pending');
|
||||||
|
else
|
||||||
|
await modal(s.p).locator('.semi-modal-footer button').first().click();
|
||||||
|
s.writeGate.resolve();
|
||||||
|
await sleep(300);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
if (action === 'edit')
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').last().inputValue(),
|
||||||
|
'typed while pending',
|
||||||
|
);
|
||||||
|
else
|
||||||
|
await s.p
|
||||||
|
.getByText('编辑价格版本', { exact: true })
|
||||||
|
.waitFor({ state: 'detached' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('mobile meaningful cost view', async () => {
|
||||||
|
const s = await setup({ viewport: { width: 390, height: 844 } });
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-mobile.png' });
|
||||||
|
assert.equal(await s.p.locator('vite-error-overlay').count(), 0);
|
||||||
|
assert.equal(await s.p.title(), 'Cost settings QA');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-requests.json',
|
||||||
|
JSON.stringify(allRequests, null, 2),
|
||||||
|
);
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-console.json',
|
||||||
|
JSON.stringify(allErrors, null, 2),
|
||||||
|
);
|
||||||
|
await browser.close();
|
||||||
|
await server.close();
|
||||||
|
console.log(
|
||||||
|
JSON.stringify({
|
||||||
|
passed: results.filter((r) => r.pass).length,
|
||||||
|
total: results.length,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
if (results.some((r) => !r.pass)) process.exitCode = 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。
|
||||||
|
// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。
|
||||||
|
|
||||||
|
import { contextOptions as sharedContextOptions } from './browser-environment.mjs';
|
||||||
|
import { prepareStaticCapture } from './browser-capture.mjs';
|
||||||
|
import { browserRuntime, browserStabilityArgs } from './playwright-runtime.mjs';
|
||||||
|
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export const FOCUS_SAFE_ARGS = Object.freeze([
|
||||||
|
...browserStabilityArgs,
|
||||||
|
'--window-position=-32000,-32000',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const FOCUS_EVENTS = Object.freeze({
|
||||||
|
STARTUP: '启动焦点激活事件',
|
||||||
|
STARTUP_PERSIST: '启动焦点仍保持',
|
||||||
|
REACTIVATED: '二次焦点激活',
|
||||||
|
UNKNOWN: '无法确认后台状态',
|
||||||
|
EXTRA_PAGE: '意外新页面',
|
||||||
|
FORBIDDEN: '禁止的焦点操作',
|
||||||
|
BACKGROUND_TARGET: '后台创建页面',
|
||||||
|
});
|
||||||
|
|
||||||
|
export class FocusGuardError extends Error {
|
||||||
|
constructor(message) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'FocusGuardError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createFocusLog(sink = console.log) {
|
||||||
|
const entries = [];
|
||||||
|
return {
|
||||||
|
entries,
|
||||||
|
record(type, detail = {}) {
|
||||||
|
const entry = { time: new Date().toISOString(), type, ...detail };
|
||||||
|
entries.push(entry);
|
||||||
|
sink(`[focus] ${type} ${JSON.stringify(detail)}`);
|
||||||
|
return entry;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 在页面内拦截 window.open 与 target 非 _self 的链接,避免应用自行打开新标签页。
|
||||||
|
export const BLOCK_POPUP_SCRIPT = `(() => {
|
||||||
|
if (window.__focusGuardBlockedOpens) return;
|
||||||
|
const blocked = [];
|
||||||
|
Object.defineProperty(window, '__focusGuardBlockedOpens', { value: blocked });
|
||||||
|
window.open = function (url) {
|
||||||
|
blocked.push(String(url ?? ''));
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
const intercept = (event) => {
|
||||||
|
const anchor = event.target && event.target.closest && event.target.closest('a[target]');
|
||||||
|
if (!anchor) return;
|
||||||
|
const target = String(anchor.getAttribute('target') || '').toLowerCase();
|
||||||
|
if (!target || target === '_self' || target === '_top' || target === '_parent') return;
|
||||||
|
event.preventDefault();
|
||||||
|
blocked.push(anchor.href);
|
||||||
|
};
|
||||||
|
document.addEventListener('click', intercept, true);
|
||||||
|
document.addEventListener('auxclick', intercept, true);
|
||||||
|
})();`;
|
||||||
|
|
||||||
|
export function installFocusGuards(context, page, log) {
|
||||||
|
const browser = context.browser?.();
|
||||||
|
const forbid = (api) => async () => {
|
||||||
|
log.record(FOCUS_EVENTS.FORBIDDEN, { api });
|
||||||
|
throw new FocusGuardError(
|
||||||
|
`${api} 被焦点约束禁止:只能在唯一页面内用 goto 导航`,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const original = {
|
||||||
|
newPage: context.newPage,
|
||||||
|
bringToFront: page.bringToFront,
|
||||||
|
browserNewPage: browser?.newPage,
|
||||||
|
browserNewContext: browser?.newContext,
|
||||||
|
};
|
||||||
|
context.newPage = forbid('context.newPage');
|
||||||
|
page.bringToFront = forbid('page.bringToFront');
|
||||||
|
if (browser) {
|
||||||
|
browser.newPage = forbid('browser.newPage');
|
||||||
|
browser.newContext = forbid('browser.newContext');
|
||||||
|
}
|
||||||
|
const onPage = async (extra) => {
|
||||||
|
if (extra === page) return;
|
||||||
|
log.record(FOCUS_EVENTS.EXTRA_PAGE, { url: extra.url() });
|
||||||
|
await extra.close().catch(() => {});
|
||||||
|
};
|
||||||
|
context.on('page', onPage);
|
||||||
|
return () => {
|
||||||
|
context.off('page', onPage);
|
||||||
|
context.newPage = original.newPage;
|
||||||
|
page.bringToFront = original.bringToFront;
|
||||||
|
if (browser) {
|
||||||
|
browser.newPage = original.browserNewPage;
|
||||||
|
browser.newContext = original.browserNewContext;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 状态迁移:启动阶段的激活只记录;之后仅“后台 → 前台”视为二次激活。
|
||||||
|
export function classifyFocus({ phase, previous, current }) {
|
||||||
|
if (current === 'unknown')
|
||||||
|
return { event: FOCUS_EVENTS.UNKNOWN, fatal: true };
|
||||||
|
if (current !== 'foreground') return { event: null, fatal: false };
|
||||||
|
if (phase === 'startup') return { event: FOCUS_EVENTS.STARTUP, fatal: false };
|
||||||
|
if (previous === 'foreground')
|
||||||
|
return { event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false };
|
||||||
|
return { event: FOCUS_EVENTS.REACTIVATED, fatal: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const FOREGROUND_PS = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;
|
||||||
|
Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '[DllImport("user32.dll")] public static extern System.IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p);'
|
||||||
|
$fg = 0; [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fg)
|
||||||
|
$dir = $env:FOCUS_GUARD_PROFILE
|
||||||
|
$ids = @()
|
||||||
|
if ($dir) { $ids = @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($dir) } | ForEach-Object { $_.ProcessId }) }
|
||||||
|
Write-Output ("$fg|" + ($ids -join ','))`;
|
||||||
|
|
||||||
|
export function parseForegroundOutput(output) {
|
||||||
|
const match = /^(\d+)\|([\d,]*)$/.exec(String(output).trim());
|
||||||
|
if (!match) return { state: 'unknown', reason: 'unparsable' };
|
||||||
|
const pids = match[2] ? match[2].split(',').map(Number) : [];
|
||||||
|
if (!pids.length) return { state: 'unknown', reason: 'no-browser-process' };
|
||||||
|
return {
|
||||||
|
state: pids.includes(Number(match[1])) ? 'foreground' : 'background',
|
||||||
|
foregroundPid: Number(match[1]),
|
||||||
|
browserPids: pids,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只读查询系统前台窗口所属进程,并与本次 profile 启动的 chrome.exe 比对;不调用任何激活 API。
|
||||||
|
export function probeOsForeground(profileDir) {
|
||||||
|
if (process.platform !== 'win32')
|
||||||
|
return Promise.resolve({
|
||||||
|
state: 'unknown',
|
||||||
|
reason: 'unsupported-platform',
|
||||||
|
});
|
||||||
|
const encoded = Buffer.from(FOREGROUND_PS, 'utf16le').toString('base64');
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
execFile(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
||||||
|
{
|
||||||
|
windowsHide: true,
|
||||||
|
timeout: 15000,
|
||||||
|
env: { ...process.env, FOCUS_GUARD_PROFILE: profileDir },
|
||||||
|
},
|
||||||
|
(error, stdout) =>
|
||||||
|
resolve(
|
||||||
|
error
|
||||||
|
? { state: 'unknown', reason: 'probe-failed' }
|
||||||
|
: parseForegroundOutput(stdout),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createBackgroundPage(context, log) {
|
||||||
|
const browser = context.browser();
|
||||||
|
if (!browser)
|
||||||
|
throw new FocusGuardError('无法获取 Browser,不能用 CDP 后台创建页面');
|
||||||
|
const session = await browser.newBrowserCDPSession();
|
||||||
|
try {
|
||||||
|
const pagePromise = context.waitForEvent('page', { timeout: 10000 });
|
||||||
|
await session.send('Target.createTarget', {
|
||||||
|
url: 'about:blank',
|
||||||
|
background: true,
|
||||||
|
newWindow: false,
|
||||||
|
});
|
||||||
|
const page = await pagePromise;
|
||||||
|
log.record(FOCUS_EVENTS.BACKGROUND_TARGET, { via: 'Target.createTarget' });
|
||||||
|
return page;
|
||||||
|
} finally {
|
||||||
|
await session.detach().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动唯一页面的有头 Chrome。切换桌面 / 移动需关闭后重新启动(计为新的启动阶段)。
|
||||||
|
* 返回 { context, page, log, checkpoint, resetSession, blockedPopups, close }。
|
||||||
|
*/
|
||||||
|
export async function launchFocusSafe(options = {}) {
|
||||||
|
const runtime = browserRuntime({
|
||||||
|
...process.env,
|
||||||
|
...(options.headless === undefined
|
||||||
|
? {}
|
||||||
|
: { PW_HEADLESS: options.headless ? '1' : '0' }),
|
||||||
|
});
|
||||||
|
const {
|
||||||
|
chromium = (await import('@playwright/test')).chromium,
|
||||||
|
device = 'desktop',
|
||||||
|
colorScheme = 'light',
|
||||||
|
headless = runtime.headless,
|
||||||
|
blockPopups = true,
|
||||||
|
extraArgs = [],
|
||||||
|
contextOptions = {},
|
||||||
|
log = createFocusLog(),
|
||||||
|
} = options;
|
||||||
|
const deviceEnvironment = sharedContextOptions(device);
|
||||||
|
const profileDir = await mkdtemp(path.join(os.tmpdir(), 'monkey-pw-focus-'));
|
||||||
|
let context;
|
||||||
|
try {
|
||||||
|
context = await chromium.launchPersistentContext(profileDir, {
|
||||||
|
...deviceEnvironment,
|
||||||
|
locale: 'zh-CN',
|
||||||
|
timezoneId: 'Asia/Shanghai',
|
||||||
|
colorScheme,
|
||||||
|
reducedMotion: 'reduce',
|
||||||
|
serviceWorkers: 'block',
|
||||||
|
...contextOptions,
|
||||||
|
channel: 'chrome',
|
||||||
|
headless,
|
||||||
|
args: [...extraArgs, ...runtime.launchArgs],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
if (blockPopups) await context.addInitScript(BLOCK_POPUP_SCRIPT);
|
||||||
|
const page = context.pages()[0] ?? (await createBackgroundPage(context, log));
|
||||||
|
const removeGuards = installFocusGuards(context, page, log);
|
||||||
|
const screenshot = page.screenshot.bind(page);
|
||||||
|
page.screenshot = async (options = {}) => {
|
||||||
|
await prepareStaticCapture(page);
|
||||||
|
return screenshot({ scale: 'css', ...options });
|
||||||
|
};
|
||||||
|
|
||||||
|
let previous = 'background';
|
||||||
|
let phase = 'startup';
|
||||||
|
async function checkpoint(label, { pauseOnUnknown = true } = {}) {
|
||||||
|
if (
|
||||||
|
log.entries.some((entry) =>
|
||||||
|
[FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE].includes(entry.type),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new FocusGuardError(
|
||||||
|
`焦点守护发现禁止操作或意外新页面(${label}),已停止`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let state;
|
||||||
|
let detail = {};
|
||||||
|
if (headless) state = 'background';
|
||||||
|
else {
|
||||||
|
const osProbe = await probeOsForeground(profileDir);
|
||||||
|
// Playwright 默认开启焦点模拟,document.hasFocus() 恒为 true,只作记录;以系统前台进程为准。
|
||||||
|
const pageFocus = await page
|
||||||
|
.evaluate(() => document.hasFocus())
|
||||||
|
.catch(() => null);
|
||||||
|
detail = {
|
||||||
|
os: osProbe.state,
|
||||||
|
reason: osProbe.reason,
|
||||||
|
foregroundPid: osProbe.foregroundPid,
|
||||||
|
documentHasFocus: pageFocus,
|
||||||
|
};
|
||||||
|
state = osProbe.state;
|
||||||
|
}
|
||||||
|
const verdict = classifyFocus({ phase, previous, current: state });
|
||||||
|
if (verdict.event) log.record(verdict.event, { label, ...detail });
|
||||||
|
phase = 'running';
|
||||||
|
if (state !== 'unknown') previous = state;
|
||||||
|
if (verdict.fatal && (state !== 'unknown' || pauseOnUnknown))
|
||||||
|
throw new FocusGuardError(`${verdict.event}(${label}),已暂停`);
|
||||||
|
return { state, ...detail };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resetSession(origins = []) {
|
||||||
|
await context.clearCookies();
|
||||||
|
const session = await context.newCDPSession(page);
|
||||||
|
try {
|
||||||
|
for (const origin of origins)
|
||||||
|
await session.send('Storage.clearDataForOrigin', {
|
||||||
|
origin,
|
||||||
|
storageTypes: 'all',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await session.detach().catch(() => {});
|
||||||
|
}
|
||||||
|
await page.goto('about:blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
const blockedPopups = () =>
|
||||||
|
page.evaluate(() => [...(window.__focusGuardBlockedOpens || [])]);
|
||||||
|
|
||||||
|
async function close() {
|
||||||
|
removeGuards();
|
||||||
|
await context.close().catch(() => {});
|
||||||
|
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await checkpoint('launch');
|
||||||
|
} catch (error) {
|
||||||
|
await close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return { context, page, log, checkpoint, resetSession, blockedPopups, close };
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
const FOCUS_ANNOTATION = 'focus-guard';
|
||||||
|
|
||||||
|
export default class AcceptanceReporter {
|
||||||
|
onBegin(config, suite) {
|
||||||
|
this.suite = suite;
|
||||||
|
this.focusEvents = new Set();
|
||||||
|
this.focusChecks = new Set();
|
||||||
|
this.headed = config.projects.some(
|
||||||
|
(project) => project.use?.headless === false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
onTestEnd(test, result) {
|
||||||
|
for (const note of [...(result.annotations || []), ...test.annotations]) {
|
||||||
|
if (note.type === FOCUS_ANNOTATION)
|
||||||
|
this.focusEvents.add(
|
||||||
|
`${test.titlePath().slice(1).join(' > ')}:${note.description}`,
|
||||||
|
);
|
||||||
|
if (note.type === 'focus-guard-checked')
|
||||||
|
this.focusChecks.add(`${test.id}:${note.description}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onEnd(result) {
|
||||||
|
// 焦点守护汇总:有事件时如实列出,不能宣称已保证后台运行
|
||||||
|
if (this.focusEvents.size) {
|
||||||
|
console.warn(
|
||||||
|
`\n[focus-guard] 记录到 ${this.focusEvents.size} 条焦点事件,本次运行不能宣称已保证后台运行:`,
|
||||||
|
);
|
||||||
|
for (const entry of this.focusEvents) console.warn(`- ${entry}`);
|
||||||
|
} else if (this.headed && this.focusChecks.size) {
|
||||||
|
console.log(
|
||||||
|
'\n[focus-guard] 各采样点(页面创建后、用例结束后)未检测到 Playwright Chrome 处于前台;采样点之间的瞬时激活无法排除',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (process.env.PW_REQUIRE_ALL !== '1') return;
|
||||||
|
const incomplete = this.suite
|
||||||
|
.allTests()
|
||||||
|
.filter(
|
||||||
|
(test) =>
|
||||||
|
test.expectedStatus !== 'passed' ||
|
||||||
|
test.results.length === 0 ||
|
||||||
|
test.results.some((run) => run.status === 'skipped') ||
|
||||||
|
test.outcome() === 'flaky',
|
||||||
|
);
|
||||||
|
if (incomplete.length) {
|
||||||
|
console.error(
|
||||||
|
'Full acceptance requires every test to pass without skips, expected failures or flaky retries:',
|
||||||
|
);
|
||||||
|
for (const test of incomplete)
|
||||||
|
console.error(`- ${test.titlePath().join(' > ')}`);
|
||||||
|
return { status: 'failed' };
|
||||||
|
}
|
||||||
|
return { status: result.status };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
// 浏览器焦点守护:有头真实 Chrome 运行时尽最大可能不抢占用户桌面焦点。
|
||||||
|
// - 唯一页面:每个用例只有一个页面,由 CDP Target.createTarget({ background: true }) 后台创建,
|
||||||
|
// 不走 context.newPage()(Playwright 内部创建时不带 background,会以前台方式打开窗口)。
|
||||||
|
// - 禁止新建/切换标签页:context.newPage、browser.newPage、browser.newContext、page.bringToFront 调用即报错;
|
||||||
|
// 页面隐式打开的新标签页(target=_blank、window.open)立即关闭并判定用例失败。
|
||||||
|
// - 焦点探测:页面创建后与用例结束后各查一次前台窗口,若属于本 worker 启动的 Chrome,
|
||||||
|
// 记录「启动焦点激活事件」/「运行中焦点激活事件」;探测失败记为「焦点状态未确认」。只记录,不做任何激活操作。
|
||||||
|
// CI(无头)不创建窗口,跳过探测;页面仍按同样规程创建。
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createInterface } from 'node:readline';
|
||||||
|
|
||||||
|
export const FOCUS_ANNOTATION = 'focus-guard';
|
||||||
|
|
||||||
|
const PROBE_SCRIPT = [
|
||||||
|
'[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;',
|
||||||
|
"Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '",
|
||||||
|
'[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();',
|
||||||
|
'[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);',
|
||||||
|
"';",
|
||||||
|
// 预热 CIM(首次查询需数秒),就绪后才应答查询
|
||||||
|
'[void](Get-CimInstance Win32_Process -Filter "ProcessId=$PID")',
|
||||||
|
'[Console]::Out.WriteLine("ready"); [Console]::Out.Flush()',
|
||||||
|
'while ($null -ne ($line = [Console]::In.ReadLine())) {',
|
||||||
|
' try {',
|
||||||
|
' $fgPid = [uint32]0',
|
||||||
|
' [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fgPid)',
|
||||||
|
' $parent = (Get-CimInstance Win32_Process -Filter "ProcessId=$fgPid").ParentProcessId',
|
||||||
|
' [Console]::Out.WriteLine("$fgPid $parent")',
|
||||||
|
' } catch { [Console]::Out.WriteLine("error") }',
|
||||||
|
' [Console]::Out.Flush()',
|
||||||
|
'}',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
// 每个 worker 一个常驻 PowerShell 只读探测进程(Add-Type 编译只发生一次),按行应答「前台窗口进程号 父进程号」
|
||||||
|
export function createFocusProbe() {
|
||||||
|
if (process.platform !== 'win32') return null;
|
||||||
|
const child = spawn(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-NonInteractive', '-Command', PROBE_SCRIPT],
|
||||||
|
{
|
||||||
|
stdio: ['pipe', 'pipe', 'ignore'],
|
||||||
|
windowsHide: true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
child.on('error', () => {});
|
||||||
|
const lines = createInterface({ input: child.stdout });
|
||||||
|
const waiting = [];
|
||||||
|
let markReady;
|
||||||
|
const ready = new Promise((resolve) => {
|
||||||
|
markReady = resolve;
|
||||||
|
});
|
||||||
|
lines.on('line', (line) => {
|
||||||
|
if (line.trim() === 'ready') markReady(true);
|
||||||
|
else waiting.shift()?.(line.trim());
|
||||||
|
});
|
||||||
|
child.on('exit', () => {
|
||||||
|
markReady(false);
|
||||||
|
while (waiting.length) waiting.shift()(null);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
// 返回 { foregroundPid, parentPid };探测失败或超时返回 null
|
||||||
|
async query(timeout = 8000) {
|
||||||
|
const started = await Promise.race([
|
||||||
|
ready,
|
||||||
|
new Promise((resolve) => {
|
||||||
|
setTimeout(resolve, 15000, false).unref();
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
if (!started || child.exitCode !== null || !child.stdin.writable)
|
||||||
|
return null;
|
||||||
|
const answer = await new Promise((resolve) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
resolve(null);
|
||||||
|
}, timeout);
|
||||||
|
waiting.push((line) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve(line);
|
||||||
|
});
|
||||||
|
child.stdin.write('q\n');
|
||||||
|
});
|
||||||
|
const match = /^(\d+) (\d+)$/.exec(answer || '');
|
||||||
|
return match
|
||||||
|
? { foregroundPid: Number(match[1]), parentPid: Number(match[2]) }
|
||||||
|
: null;
|
||||||
|
},
|
||||||
|
dispose() {
|
||||||
|
child.stdin.end();
|
||||||
|
if (child.exitCode === null)
|
||||||
|
setTimeout(() => {
|
||||||
|
if (child.exitCode === null) child.kill();
|
||||||
|
}, 2000).unref();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 前台窗口是否属于本 worker 启动的 Chrome(Chrome 主进程由 worker 进程直接启动并持有窗口)
|
||||||
|
export async function checkFocus(probe, stage, testInfo) {
|
||||||
|
if (!probe) return;
|
||||||
|
const state = await probe.query();
|
||||||
|
let description;
|
||||||
|
if (!state) {
|
||||||
|
description = `焦点状态未确认(${stage}):前台窗口探测失败,不能宣称已保证后台运行`;
|
||||||
|
} else if (state.parentPid === process.pid) {
|
||||||
|
description = `${stage === '页面创建后' ? '启动焦点激活事件' : '运行中焦点激活事件'}:${stage}前台窗口属于 Playwright Chrome(pid ${state.foregroundPid})`;
|
||||||
|
} else {
|
||||||
|
testInfo.annotations.push({
|
||||||
|
type: 'focus-guard-checked',
|
||||||
|
description: stage,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
testInfo.annotations.push({ type: FOCUS_ANNOTATION, description });
|
||||||
|
console.warn(
|
||||||
|
`[${FOCUS_ANNOTATION}] ${new Date().toISOString()} ${testInfo.titlePath.join(' > ')}:${description}`,
|
||||||
|
);
|
||||||
|
throw new Error(description);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 本用例上下文的 CDP browserContextId:每个 worker 独占一个浏览器且用例串行,同一时刻只应有一个上下文
|
||||||
|
async function contextIdOf(cdp) {
|
||||||
|
const { browserContextIds } = await cdp.send('Target.getBrowserContexts');
|
||||||
|
if (browserContextIds.length !== 1) {
|
||||||
|
throw new Error(
|
||||||
|
`焦点守护:无法唯一确定当前浏览器上下文(共 ${browserContextIds.length} 个),拒绝以前台方式创建页面`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return browserContextIds[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 唯一页面:通过 CDP Target.createTarget({ background: true }) 后台创建,由 Playwright 自动接管为 context 的页面
|
||||||
|
export async function openBackgroundPage(browser, context) {
|
||||||
|
const cdp = await browser.newBrowserCDPSession();
|
||||||
|
try {
|
||||||
|
const browserContextId = await contextIdOf(cdp);
|
||||||
|
const pageEvent = context.waitForEvent('page', { timeout: 15000 });
|
||||||
|
await cdp.send('Target.createTarget', {
|
||||||
|
url: 'about:blank',
|
||||||
|
browserContextId,
|
||||||
|
background: true,
|
||||||
|
});
|
||||||
|
return await pageEvent;
|
||||||
|
} finally {
|
||||||
|
await cdp.detach().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const forbid = (name, violations) => () => {
|
||||||
|
violations.push(`禁止调用 ${name}`);
|
||||||
|
throw new Error(
|
||||||
|
`焦点守护:禁止调用 ${name}(唯一页面原则,不得新建或切换标签页/窗口;访问新地址请在当前页 page.goto)`,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 安装禁止项,返回 { violations, restore };restore 在用例结束时调用,恢复 worker 共享的 browser 方法
|
||||||
|
export function installGuards(browser, context, page) {
|
||||||
|
const violations = [];
|
||||||
|
const saved = { newPage: browser.newPage, newContext: browser.newContext };
|
||||||
|
context.newPage = forbid('context.newPage()', violations);
|
||||||
|
page.bringToFront = forbid('page.bringToFront()', violations);
|
||||||
|
browser.newPage = forbid('browser.newPage()', violations);
|
||||||
|
browser.newContext = forbid('browser.newContext()', violations);
|
||||||
|
const onPage = (extra) => {
|
||||||
|
if (extra === page) return;
|
||||||
|
violations.push(
|
||||||
|
`页面隐式打开了新标签页/窗口:${extra.url() || 'about:blank'}(已立即关闭)`,
|
||||||
|
);
|
||||||
|
extra.close().catch(() => {});
|
||||||
|
};
|
||||||
|
context.on('page', onPage);
|
||||||
|
return {
|
||||||
|
violations,
|
||||||
|
restore() {
|
||||||
|
context.off('page', onPage);
|
||||||
|
browser.newPage = saved.newPage;
|
||||||
|
browser.newContext = saved.newContext;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
export const browserStabilityArgs = Object.freeze([
|
||||||
|
'--hide-scrollbars',
|
||||||
|
'--disable-backgrounding-occluded-windows',
|
||||||
|
'--disable-renderer-backgrounding',
|
||||||
|
'--disable-background-timer-throttling',
|
||||||
|
'--disable-features=CalculateNativeWinOcclusion',
|
||||||
|
'--no-first-run',
|
||||||
|
'--no-default-browser-check',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function positiveInteger(value, name) {
|
||||||
|
const text = String(value);
|
||||||
|
if (
|
||||||
|
!['number', 'string'].includes(typeof value) ||
|
||||||
|
text !== text.trim() ||
|
||||||
|
!/^[1-9]\d*$/.test(text) ||
|
||||||
|
!Number.isSafeInteger(Number(value))
|
||||||
|
) {
|
||||||
|
throw new Error(`${name} must be a positive safe integer (1, 2, 3, ...)`);
|
||||||
|
}
|
||||||
|
return Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function flag(env, name, fallback) {
|
||||||
|
if (env[name] === undefined) return fallback;
|
||||||
|
if (!['0', '1'].includes(env[name]))
|
||||||
|
throw new Error(`${name} must be 0 or 1`);
|
||||||
|
return env[name] === '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function browserRuntime(env = process.env) {
|
||||||
|
const isCI = Boolean(env.CI && env.CI !== 'false' && env.CI !== '0');
|
||||||
|
const headless = flag(env, 'PW_HEADLESS', isCI);
|
||||||
|
if (isCI && !headless)
|
||||||
|
throw new Error(
|
||||||
|
'CI requires headless Chrome; PW_HEADLESS=0 is not allowed',
|
||||||
|
);
|
||||||
|
// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。
|
||||||
|
// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式
|
||||||
|
// (或 UI_VISUAL_OFFSCREEN=1),避免弹出 UI 或依赖显示环境。
|
||||||
|
const offscreen = flag(env, 'UI_VISUAL_OFFSCREEN', true);
|
||||||
|
const knownAgent = Boolean(
|
||||||
|
env.CODEX_THREAD_ID || env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT,
|
||||||
|
);
|
||||||
|
if (!offscreen && (isCI || headless || knownAgent))
|
||||||
|
throw new Error(
|
||||||
|
'UI_VISUAL_OFFSCREEN=0 is only allowed for manual local headed debugging',
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
isCI,
|
||||||
|
headless,
|
||||||
|
offscreen,
|
||||||
|
launchArgs: [
|
||||||
|
...browserStabilityArgs,
|
||||||
|
...(offscreen ? ['--window-position=-32000,-32000'] : []),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runtimeOptions({
|
||||||
|
defaultPort,
|
||||||
|
defaultWorkers,
|
||||||
|
env = process.env,
|
||||||
|
}) {
|
||||||
|
const target = env.PW_TARGET || 'local-dev';
|
||||||
|
if (!['local-dev', 'local-dist', 'remote'].includes(target))
|
||||||
|
throw new Error('PW_TARGET must be local-dist, local-dev or remote');
|
||||||
|
if (target === 'remote' && !env.PW_BASE_URL)
|
||||||
|
throw new Error('PW_BASE_URL is required for remote tests');
|
||||||
|
const baseURL = new URL(
|
||||||
|
env.PW_BASE_URL || `http://127.0.0.1:${defaultPort}/`,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!['http:', 'https:'].includes(baseURL.protocol) ||
|
||||||
|
baseURL.username ||
|
||||||
|
baseURL.password ||
|
||||||
|
baseURL.search ||
|
||||||
|
baseURL.hash
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'PW_BASE_URL must be an HTTP(S) URL without credentials, query or hash',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!baseURL.pathname.endsWith('/'))
|
||||||
|
throw new Error('PW_BASE_URL directory path must end with /');
|
||||||
|
if (
|
||||||
|
target !== 'remote' &&
|
||||||
|
(baseURL.hostname !== '127.0.0.1' ||
|
||||||
|
baseURL.protocol !== 'http:' ||
|
||||||
|
baseURL.pathname !== '/')
|
||||||
|
) {
|
||||||
|
throw new Error('Local targets require http://127.0.0.1:<port>/');
|
||||||
|
}
|
||||||
|
const browser = browserRuntime(env);
|
||||||
|
const { isCI } = browser;
|
||||||
|
const workers =
|
||||||
|
env.PW_WORKERS === undefined
|
||||||
|
? isCI
|
||||||
|
? 1
|
||||||
|
: positiveInteger(defaultWorkers, 'resources.concurrency')
|
||||||
|
: positiveInteger(env.PW_WORKERS, 'PW_WORKERS');
|
||||||
|
const extended = flag(env, 'PW_EXTENDED_LAYOUT', false);
|
||||||
|
const video = flag(env, 'PW_VIDEO', false);
|
||||||
|
const requireAll = flag(env, 'PW_REQUIRE_ALL', false);
|
||||||
|
const runId = env.PW_RUN_ID ?? `${target}-${Date.now()}-${randomUUID()}`;
|
||||||
|
if (
|
||||||
|
typeof runId !== 'string' ||
|
||||||
|
runId !== runId.trim() ||
|
||||||
|
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/.test(runId)
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
'PW_RUN_ID must be a safe directory name of 1-100 letters, digits, underscores or hyphens',
|
||||||
|
);
|
||||||
|
// Workers inherit this ID; every run keeps its traces and reports together.
|
||||||
|
env.PW_RUN_ID = runId;
|
||||||
|
return {
|
||||||
|
target,
|
||||||
|
baseURL,
|
||||||
|
...browser,
|
||||||
|
workers,
|
||||||
|
extended,
|
||||||
|
video,
|
||||||
|
requireAll,
|
||||||
|
runId,
|
||||||
|
outputDir: `test-results/${runId}`,
|
||||||
|
reportDir: `playwright-report/${runId}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { test as base, expect } from '@playwright/test';
|
||||||
|
import {
|
||||||
|
checkFocus,
|
||||||
|
createFocusProbe,
|
||||||
|
installGuards,
|
||||||
|
openBackgroundPage,
|
||||||
|
} from './playwright-runner-focus.mjs';
|
||||||
|
import { prepareStaticCapture } from './browser-capture.mjs';
|
||||||
|
|
||||||
|
export const test = base.extend({
|
||||||
|
focusProbe: [
|
||||||
|
async ({ headless }, use) => {
|
||||||
|
const probe = headless ? null : createFocusProbe();
|
||||||
|
if (!headless && !probe)
|
||||||
|
throw new Error(
|
||||||
|
'焦点状态未确认:当前系统不支持前台窗口探测,请使用 PW_HEADLESS=1',
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
await use(probe);
|
||||||
|
} finally {
|
||||||
|
probe?.dispose();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ scope: 'worker' },
|
||||||
|
],
|
||||||
|
page: async ({ browser, context, focusProbe, headless }, use, testInfo) => {
|
||||||
|
if (!headless && process.env.CI && !['0', 'false'].includes(process.env.CI))
|
||||||
|
throw new Error('CI requires headless Chrome');
|
||||||
|
const page = await openBackgroundPage(browser, context);
|
||||||
|
const guards = installGuards(browser, context, page);
|
||||||
|
const screenshot = page.screenshot.bind(page);
|
||||||
|
page.screenshot = async (options = {}) => {
|
||||||
|
await prepareStaticCapture(page);
|
||||||
|
return screenshot({ scale: 'css', ...options });
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await checkFocus(focusProbe, '页面创建后', testInfo);
|
||||||
|
await use(page);
|
||||||
|
await checkFocus(focusProbe, '用例结束后', testInfo);
|
||||||
|
} finally {
|
||||||
|
guards.restore();
|
||||||
|
expect(
|
||||||
|
guards.violations,
|
||||||
|
'焦点守护:用例不得新建或切换标签页/窗口',
|
||||||
|
).toEqual([]);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export { expect };
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { preview } from 'vite';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { positiveInteger } from './playwright-runtime.mjs';
|
||||||
|
import { verifyBuild } from './verify-build.mjs';
|
||||||
|
|
||||||
|
const directory =
|
||||||
|
process.env.PW_DIST_DIR ||
|
||||||
|
fileURLToPath(new URL('../dist/', import.meta.url));
|
||||||
|
const portIndex = process.argv.indexOf('--port');
|
||||||
|
const port = positiveInteger(
|
||||||
|
portIndex === -1 ? 4176 : process.argv[portIndex + 1],
|
||||||
|
'port',
|
||||||
|
);
|
||||||
|
if (port > 65535) throw new Error('port must be <= 65535');
|
||||||
|
await verifyBuild(directory);
|
||||||
|
const server = await preview({
|
||||||
|
build: { outDir: directory },
|
||||||
|
preview: { host: '127.0.0.1', port, strictPort: true },
|
||||||
|
});
|
||||||
|
server.printUrls();
|
||||||
|
for (const signal of ['SIGTERM', 'SIGINT'])
|
||||||
|
process.on(signal, () => server.httpServer.close());
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { mkdtemp, rm } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { verifyBuild } from './verify-build.mjs';
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-build-'));
|
||||||
|
const env = {
|
||||||
|
...process.env,
|
||||||
|
PW_TARGET: 'local-dist',
|
||||||
|
PW_BASE_URL: 'http://127.0.0.1:4176/',
|
||||||
|
PW_REQUIRE_ALL: '1',
|
||||||
|
PW_DIST_DIR: directory,
|
||||||
|
};
|
||||||
|
function run(script, args) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(process.execPath, [script, ...args], {
|
||||||
|
cwd: root,
|
||||||
|
stdio: 'inherit',
|
||||||
|
env,
|
||||||
|
});
|
||||||
|
child.on('error', reject);
|
||||||
|
child.on('exit', (code) =>
|
||||||
|
code === 0
|
||||||
|
? resolve()
|
||||||
|
: reject(new Error(`${path.basename(script)} failed (${code})`)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await run(path.join(root, 'node_modules/vite/bin/vite.js'), [
|
||||||
|
'build',
|
||||||
|
'--outDir',
|
||||||
|
directory,
|
||||||
|
'--emptyOutDir',
|
||||||
|
]);
|
||||||
|
await verifyBuild(directory);
|
||||||
|
await run(path.join(root, 'node_modules/@playwright/test/cli.js'), [
|
||||||
|
'test',
|
||||||
|
...process.argv.slice(2),
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { readdir, stat, access } from 'node:fs/promises';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export async function latestReport(directory) {
|
||||||
|
const reports = [];
|
||||||
|
try {
|
||||||
|
const legacy = await stat(path.join(directory, 'index.html'));
|
||||||
|
reports.push({ candidate: directory, modified: legacy.mtimeMs });
|
||||||
|
} catch {
|
||||||
|
/* Older runners wrote index.html directly in this directory. */
|
||||||
|
}
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
const candidate = path.join(directory, entry.name);
|
||||||
|
try {
|
||||||
|
const info = await stat(path.join(candidate, 'index.html'));
|
||||||
|
reports.push({ candidate, modified: info.mtimeMs });
|
||||||
|
} catch {
|
||||||
|
/* Incomplete runs have no report to open. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reports.sort((a, b) => b.modified - a.modified);
|
||||||
|
if (!reports.length) throw new Error('No completed HTML report found');
|
||||||
|
return reports[0].candidate;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
process.argv[1] &&
|
||||||
|
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||||
|
) {
|
||||||
|
const [mode, ...args] = process.argv.slice(2);
|
||||||
|
const env = { ...process.env };
|
||||||
|
const cli = fileURLToPath(
|
||||||
|
new URL('../node_modules/@playwright/test/cli.js', import.meta.url),
|
||||||
|
);
|
||||||
|
let command = ['test', ...args];
|
||||||
|
if (mode === 'headless') env.PW_HEADLESS = '1';
|
||||||
|
else if (mode === 'extended') env.PW_EXTENDED_LAYOUT = '1';
|
||||||
|
else if (mode === 'dist') {
|
||||||
|
env.PW_TARGET = 'local-dist';
|
||||||
|
env.PW_BASE_URL = 'http://127.0.0.1:4176/';
|
||||||
|
const root =
|
||||||
|
env.PW_DIST_DIR || fileURLToPath(new URL('../dist/', import.meta.url));
|
||||||
|
await access(path.join(root, 'index.html'));
|
||||||
|
} else if (mode === 'report') {
|
||||||
|
const explicitDirectory = args[0] && !args[0].startsWith('-');
|
||||||
|
const directory = explicitDirectory
|
||||||
|
? args[0]
|
||||||
|
: await latestReport(
|
||||||
|
fileURLToPath(new URL('../playwright-report/', import.meta.url)),
|
||||||
|
);
|
||||||
|
command = [
|
||||||
|
'show-report',
|
||||||
|
directory,
|
||||||
|
...(explicitDirectory ? args.slice(1) : args),
|
||||||
|
];
|
||||||
|
} else throw new Error('Expected headless, extended, dist or report');
|
||||||
|
const child = spawn(process.execPath, [cli, ...command], {
|
||||||
|
cwd: fileURLToPath(new URL('../', import.meta.url)),
|
||||||
|
stdio: 'inherit',
|
||||||
|
env,
|
||||||
|
});
|
||||||
|
child.on('error', (error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
child.on('exit', (code) => {
|
||||||
|
process.exitCode = code ?? 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ for (const lng of Object.keys(data.missingByLocale)) {
|
|||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
path.join(OUT_DIR, `missing_keys_${lng}.json`),
|
path.join(OUT_DIR, `missing_keys_${lng}.json`),
|
||||||
JSON.stringify(keys, null, 2),
|
JSON.stringify(keys, null, 2),
|
||||||
'utf8'
|
'utf8',
|
||||||
);
|
);
|
||||||
console.log(`Wrote missing_keys_${lng}.json (${keys.length} keys)`);
|
console.log(`Wrote missing_keys_${lng}.json (${keys.length} keys)`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
const directory = await mkdtemp(path.join(tmpdir(), 'pw-environment-'));
|
||||||
|
const url = (name) => pathToFileURL(path.join(root, name)).href;
|
||||||
|
try {
|
||||||
|
await writeFile(
|
||||||
|
path.join(directory, 'playwright.config.mjs'),
|
||||||
|
`
|
||||||
|
import config from ${JSON.stringify(url('playwright.config.js'))}
|
||||||
|
export default { ...config, testDir: ${JSON.stringify(directory)}, testMatch: '**/*.spec.mjs', fullyParallel: false, workers: 1,
|
||||||
|
outputDir: ${JSON.stringify(root)} + config.outputDir,
|
||||||
|
reporter: config.reporter.map(([name, options]) => [name.startsWith('.') ? ${JSON.stringify(root)} + name : name, name === 'html' ? { ...options, outputFolder: ${JSON.stringify(root)} + options.outputFolder } : options]),
|
||||||
|
webServer: config.webServer ? { ...config.webServer, cwd: ${JSON.stringify(root)} } : undefined }
|
||||||
|
`,
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
path.join(directory, 'environment.spec.mjs'),
|
||||||
|
`
|
||||||
|
import { test, expect } from ${JSON.stringify(url('scripts/playwright-test.mjs'))}
|
||||||
|
import { contextOptions } from ${JSON.stringify(url('scripts/browser-environment.mjs'))}
|
||||||
|
import { captureStatic } from ${JSON.stringify(url('scripts/browser-capture.mjs'))}
|
||||||
|
test('设备上下文、触摸、DPR、CSS 截图与稳定字体', async ({ page, baseURL }, info) => {
|
||||||
|
const expected = contextOptions(info.project.name.replace('chrome-', ''))
|
||||||
|
await page.route('**/__pw_environment__', route => route.fulfill({ contentType: 'text/html', body: '<meta name="viewport" content="width=device-width, initial-scale=1"><style>body{margin:0} div{width:100px;height:50px;background:orange;animation:move 3s infinite}@keyframes move{to{transform:translateX(100px)}}</style><div>环境验证</div>' }))
|
||||||
|
await page.goto(new URL('__pw_environment__', baseURL).href)
|
||||||
|
const actual = await page.evaluate(() => ({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio, ua: navigator.userAgent, touch: navigator.maxTouchPoints > 0, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, reduced: matchMedia('(prefers-reduced-motion: reduce)').matches }))
|
||||||
|
expect(actual).toMatchObject({ width: expected.viewport.width, height: expected.viewport.height, dpr: expected.deviceScaleFactor, touch: expected.hasTouch, language: expected.locale, timezone: expected.timezoneId, reduced: true })
|
||||||
|
expect(actual.ua).toBe(expected.userAgent)
|
||||||
|
const image = await captureStatic(page)
|
||||||
|
expect(image.readUInt32BE(16)).toBe(expected.viewport.width)
|
||||||
|
expect(image.readUInt32BE(20)).toBe(expected.viewport.height)
|
||||||
|
expect((await captureStatic(page)).equals(image)).toBe(true)
|
||||||
|
})
|
||||||
|
`,
|
||||||
|
);
|
||||||
|
const env = {
|
||||||
|
...process.env,
|
||||||
|
PW_HEADLESS: '1',
|
||||||
|
UI_VISUAL_OFFSCREEN: '1',
|
||||||
|
PW_EXTENDED_LAYOUT: '1',
|
||||||
|
PW_WORKERS: '1',
|
||||||
|
};
|
||||||
|
delete env.PW_RUN_ID;
|
||||||
|
delete env.PLAYWRIGHT_HTML_OUTPUT_DIR;
|
||||||
|
const code = await new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(
|
||||||
|
process.execPath,
|
||||||
|
[
|
||||||
|
path.join(root, 'node_modules/@playwright/test/cli.js'),
|
||||||
|
'test',
|
||||||
|
'--config',
|
||||||
|
path.join(directory, 'playwright.config.mjs'),
|
||||||
|
],
|
||||||
|
{ cwd: root, env, stdio: 'inherit' },
|
||||||
|
);
|
||||||
|
child.on('error', reject);
|
||||||
|
child.on('exit', (code) => resolve(code ?? 1));
|
||||||
|
});
|
||||||
|
process.exitCode = code;
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
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;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -497,3 +497,4 @@
|
|||||||
"自定义对话参数": "対話パラメータをカスタマイズ",
|
"自定义对话参数": "対話パラメータをカスタマイズ",
|
||||||
"选择 AI 模型": "AI モデルを選択",
|
"选择 AI 模型": "AI モデルを選択",
|
||||||
"实时显示AI回复内容": "AIの返信内容をリアルタイム表示"
|
"实时显示AI回复内容": "AIの返信内容をリアルタイム表示"
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
const forbiddenPackages = [
|
||||||
|
/^@(?:radix-ui|floating-ui|lobehub|headlessui|mui|material-ui|chakra-ui)\//,
|
||||||
|
/^@douyinfe\/semi-/,
|
||||||
|
/^(?:leva|antd-style|react-layout-kit)(?:[/?#]|$)/,
|
||||||
|
];
|
||||||
|
|
||||||
|
function isForbiddenUiDependency(specifier) {
|
||||||
|
return (
|
||||||
|
typeof specifier === 'string' &&
|
||||||
|
forbiddenPackages.some((pattern) => pattern.test(specifier))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rule = {
|
||||||
|
meta: {
|
||||||
|
schema: [],
|
||||||
|
messages: {
|
||||||
|
forbidden:
|
||||||
|
'Use Ant Design or the audited local brand assets instead of {{specifier}}.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create(context) {
|
||||||
|
const inspect = (node) => {
|
||||||
|
const specifier =
|
||||||
|
node?.type === 'Literal'
|
||||||
|
? node.value
|
||||||
|
: node?.type === 'TemplateLiteral' && node.expressions.length === 0
|
||||||
|
? node.quasis[0].value.cooked
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (isForbiddenUiDependency(specifier)) {
|
||||||
|
context.report({ node, messageId: 'forbidden', data: { specifier } });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
ImportDeclaration: (node) => inspect(node.source),
|
||||||
|
ExportNamedDeclaration: (node) => inspect(node.source),
|
||||||
|
ExportAllDeclaration: (node) => inspect(node.source),
|
||||||
|
ImportExpression: (node) => inspect(node.source),
|
||||||
|
CallExpression: (node) => {
|
||||||
|
const { callee } = node;
|
||||||
|
const isRequire =
|
||||||
|
callee.type === 'Identifier' && callee.name === 'require';
|
||||||
|
const isRequireResolve =
|
||||||
|
callee.type === 'MemberExpression' &&
|
||||||
|
!callee.computed &&
|
||||||
|
callee.object.type === 'Identifier' &&
|
||||||
|
callee.object.name === 'require' &&
|
||||||
|
callee.property.name === 'resolve';
|
||||||
|
if (isRequire || isRequireResolve) inspect(node.arguments[0]);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const uiDependencyConfig = {
|
||||||
|
files: ['**/*.{js,jsx,cjs,mjs}'],
|
||||||
|
languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },
|
||||||
|
plugins: { 'ui-dependencies': { rules: { 'no-legacy-ui': rule } } },
|
||||||
|
rules: { 'ui-dependencies/no-legacy-ui': 'error' },
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = { isForbiddenUiDependency, uiDependencyConfig };
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"browser": {
|
||||||
|
"channel": "chrome",
|
||||||
|
"desktopDevice": "Desktop Chrome",
|
||||||
|
"mobileDevice": "Pixel 5",
|
||||||
|
"locale": "zh-CN",
|
||||||
|
"timezone": "Asia/Shanghai"
|
||||||
|
},
|
||||||
|
"viewports": {
|
||||||
|
"desktop": [1920, 1080],
|
||||||
|
"mobile": [360, 800],
|
||||||
|
"mobile-393": [393, 851],
|
||||||
|
"tablet": [768, 1024],
|
||||||
|
"laptop": [1024, 768],
|
||||||
|
"hd": [1366, 768],
|
||||||
|
"wxga": [1440, 900],
|
||||||
|
"qhd": [2560, 1440],
|
||||||
|
"uhd": [3840, 2160]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { readFile, access } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { gzipSync } from 'node:zlib';
|
||||||
|
|
||||||
|
const BOOTSTRAP_GZIP_LIMIT = 820 * 1024;
|
||||||
|
const NOTICE = 'src/components/layout/NoticeModal.jsx';
|
||||||
|
const AGREEMENT = 'src/components/common/DocumentRenderer/AgreementModal.jsx';
|
||||||
|
const HEADER = 'src/components/layout/headerbar/index.jsx';
|
||||||
|
const HOME = 'src/pages/Home/index.jsx';
|
||||||
|
const MARKED = 'node_modules/marked/lib/marked.esm.js';
|
||||||
|
|
||||||
|
function resolveAsset(root, asset) {
|
||||||
|
const filename = path.resolve(root, asset.replace(/^\//, ''));
|
||||||
|
if (!filename.startsWith(root + path.sep))
|
||||||
|
throw new Error(`Build asset escapes output directory: ${asset}`);
|
||||||
|
return filename;
|
||||||
|
}
|
||||||
|
|
||||||
|
function staticChunks(manifest, roots) {
|
||||||
|
const seen = new Set();
|
||||||
|
const visit = (key) => {
|
||||||
|
if (seen.has(key)) return;
|
||||||
|
const chunk = manifest[key];
|
||||||
|
if (!chunk) throw new Error(`Missing build manifest chunk: ${key}`);
|
||||||
|
seen.add(key);
|
||||||
|
for (const dependency of chunk.imports || []) visit(dependency);
|
||||||
|
};
|
||||||
|
roots.forEach(visit);
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyStartup(root) {
|
||||||
|
const manifest = JSON.parse(
|
||||||
|
await readFile(path.join(root, '.vite', 'manifest.json'), 'utf8'),
|
||||||
|
);
|
||||||
|
const entry = 'index.html';
|
||||||
|
for (const [routes, deferred] of [
|
||||||
|
[
|
||||||
|
[entry, HOME, HEADER],
|
||||||
|
[NOTICE, MARKED],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
[entry, 'src/components/auth/LoginForm.jsx', HEADER],
|
||||||
|
[AGREEMENT, NOTICE],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
[entry, 'src/components/auth/RegisterForm.jsx', HEADER],
|
||||||
|
[AGREEMENT, NOTICE],
|
||||||
|
],
|
||||||
|
]) {
|
||||||
|
const eager = staticChunks(manifest, routes);
|
||||||
|
for (const feature of deferred) {
|
||||||
|
if (!manifest[feature]?.isDynamicEntry || eager.has(feature))
|
||||||
|
throw new Error(`Expected an independent lazy chunk: ${feature}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = new Set(
|
||||||
|
[...staticChunks(manifest, [entry])].map((key) => manifest[key].file),
|
||||||
|
);
|
||||||
|
let bootstrapGzipBytes = 0;
|
||||||
|
for (const file of files) {
|
||||||
|
const source = await readFile(resolveAsset(root, file));
|
||||||
|
bootstrapGzipBytes += gzipSync(source).length;
|
||||||
|
}
|
||||||
|
if (bootstrapGzipBytes > BOOTSTRAP_GZIP_LIMIT)
|
||||||
|
throw new Error(
|
||||||
|
`Bootstrap JS exceeds 820 KiB gzip: ${bootstrapGzipBytes} B`,
|
||||||
|
);
|
||||||
|
return { bootstrapGzipBytes, bootstrapChunks: files.size };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyBuild(directory, { startup = false } = {}) {
|
||||||
|
const root = path.resolve(directory);
|
||||||
|
const html = await readFile(path.join(root, 'index.html'), 'utf8');
|
||||||
|
// Inspect actual resource tags, not URLs embedded in comments or inline scripts.
|
||||||
|
const markup = html
|
||||||
|
.replace(/<!--[\s\S]*?-->/g, '')
|
||||||
|
.replace(/(<script\b[^>]*>)[\s\S]*?<\/script\s*>/gi, '$1</script>');
|
||||||
|
const tags = [
|
||||||
|
...markup.matchAll(/<(?:script|link|img|source)\b[^>]*>/gi),
|
||||||
|
].map((match) => match[0]);
|
||||||
|
const assets = tags
|
||||||
|
.flatMap((tag) => [...tag.matchAll(/\s(?:src|href)\s*=["']([^"']+)["']/g)])
|
||||||
|
.map((match) => match[1].split(/[?#]/)[0])
|
||||||
|
// The inline brand bootstrap resolves this server placeholder to /logo.svg.
|
||||||
|
.map((value) => (value === '__WL_BRAND_FAVICON__' ? '/logo.svg' : value))
|
||||||
|
.filter((value) => value && !/^(?:[a-z]+:|\/\/|#)/i.test(value));
|
||||||
|
if (!assets.some((value) => /\.js$/.test(value)))
|
||||||
|
throw new Error('Build has no JavaScript entry');
|
||||||
|
for (const asset of assets) {
|
||||||
|
await access(resolveAsset(root, asset));
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
root,
|
||||||
|
assets: assets.length,
|
||||||
|
...(startup ? await verifyStartup(root) : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
process.argv[1] &&
|
||||||
|
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||||
|
) {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const directory = args.find((argument) => argument !== '--startup') || 'dist';
|
||||||
|
console.log(
|
||||||
|
await verifyBuild(directory, { startup: args.includes('--startup') }),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import postcss from 'postcss';
|
||||||
|
|
||||||
|
// 旧浏览器的级联层(@layer)兜底。
|
||||||
|
//
|
||||||
|
// index.css 把 Tailwind 的 base / components / utilities 整体包在原生 @layer 里,
|
||||||
|
// @layer 自 Chromium 99 / Firefox 97 / Safari 15.4 才支持;更老的内核(停更的
|
||||||
|
// Edge、Win10 LTSC 自带 Edge、各类国产壳浏览器)把它当未知 at-rule 连同块内
|
||||||
|
// 全部规则一起丢弃 —— Tailwind 整体失效,页面只剩无尺寸约束的原图 logo。
|
||||||
|
//
|
||||||
|
// 这里在构建期把入口样式表里各层的内容按层序压平成一份不含 @layer 的样式表,
|
||||||
|
// index.html 里的内联探测脚本只在浏览器不认识 @layer 时才加载它。支持 @layer 的
|
||||||
|
// 浏览器不会请求这个文件,原有样式与层叠关系一个字节都不变。
|
||||||
|
//
|
||||||
|
// 压平只是近似,目标是页面可用而非像素一致。兜底表排在所有入口样式表之前,
|
||||||
|
// 因此「同特异性的普通声明,层外胜」得以保持;以下两点与原生级联层不同,
|
||||||
|
// 旧浏览器里会表现为局部外观差异(07 号文档 §95 有实例):
|
||||||
|
// - 层内 !important 本应无条件压过层外 !important,压平后改按特异性与先后;
|
||||||
|
// - 层内选择器特异性高于层外时会反超,原生层叠里层外恒胜。
|
||||||
|
|
||||||
|
// at 关键字大小写不敏感(@LAYER 也是合法写法),PostCSS 保留原始大小写,比较前统一
|
||||||
|
const isAtRule = (node, name) =>
|
||||||
|
node.type === 'atrule' && node.name.toLowerCase() === name;
|
||||||
|
const isLayer = (node) => isAtRule(node, 'layer');
|
||||||
|
|
||||||
|
// 文本里出现 @layer 不等于真有层规则(注释、字符串里也可能有这几个字),
|
||||||
|
// 先粗筛再解析确认,免得把没分层的样式表算进「必须兜底」的名单
|
||||||
|
const hasLayerRule = (css) => {
|
||||||
|
if (!/@layer/i.test(css)) return false;
|
||||||
|
let found = false;
|
||||||
|
postcss.parse(css).walkAtRules(/^layer$/i, () => {
|
||||||
|
found = true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
return found;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 只认「顶层的具名/匿名层块 + 层序声明」这一种形态(当前产物仅此一种)。
|
||||||
|
// 嵌套层、点号层名、条件块里的层、@import layer() 的优先级规则各不相同,
|
||||||
|
// 近似处理会悄悄排错顺序或漏收样式,而这类错误在新浏览器上完全看不出来 ——
|
||||||
|
// 所以遇到就让构建失败,由人来决定怎么扩展。
|
||||||
|
const assertSupportedShape = (root) => {
|
||||||
|
const reject = (what) => {
|
||||||
|
throw new Error(
|
||||||
|
`[legacy-css-layers] 入口样式表出现了 ${what},旧浏览器兜底尚不支持这种写法。` +
|
||||||
|
'请先扩展 scripts/vite/legacy-css-layers.js 的 flattenCssLayers 再构建。',
|
||||||
|
);
|
||||||
|
};
|
||||||
|
root.walkAtRules((rule) => {
|
||||||
|
if (isLayer(rule) && rule.parent !== root) {
|
||||||
|
reject(`非顶层的 @layer ${rule.params}`);
|
||||||
|
}
|
||||||
|
if (isLayer(rule) && rule.params.includes('.')) {
|
||||||
|
reject(`带点号的层名 @layer ${rule.params}`);
|
||||||
|
}
|
||||||
|
if (isAtRule(rule, 'import')) {
|
||||||
|
// 先去掉 url() 与字符串,免得文件名里的 layer 字样被当成关键字
|
||||||
|
const flags = rule.params.replace(/url\([^)]*\)|"[^"]*"|'[^']*'/gi, '');
|
||||||
|
if (/\blayer\b/i.test(flags)) reject(`@import ${rule.params}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从一组按文档顺序排列的 CSS 源码中取出所有级联层,按层序拼成不含 @layer 的 CSS。
|
||||||
|
* 层序与浏览器一致:按层名首次出现的先后(`@layer a, b;` 声明与 `@layer a {}` 块
|
||||||
|
* 都算出现),先出现的优先级低,因此排在前面。不在任何层里的规则不收录 ——
|
||||||
|
* 它们在旧浏览器里本来就生效。
|
||||||
|
*/
|
||||||
|
export function flattenCssLayers(sources) {
|
||||||
|
const roots = sources.map((css) => postcss.parse(css));
|
||||||
|
roots.forEach(assertSupportedShape);
|
||||||
|
|
||||||
|
// 层外已有逐字相同的规则时,层内那份不必收:选择器与声明都一样、层外的又加载
|
||||||
|
// 在后,它在旧浏览器里必然被覆盖。
|
||||||
|
const unlayered = new Set();
|
||||||
|
for (const root of roots) {
|
||||||
|
root.each((node) => {
|
||||||
|
if (!isLayer(node) && node.type !== 'comment') {
|
||||||
|
unlayered.add(node.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const layers = new Map();
|
||||||
|
const layerOf = (name) => {
|
||||||
|
if (!layers.has(name)) layers.set(name, []);
|
||||||
|
return layers.get(name);
|
||||||
|
};
|
||||||
|
for (const root of roots) {
|
||||||
|
root.each((node) => {
|
||||||
|
if (!isLayer(node)) return;
|
||||||
|
if (!node.nodes) {
|
||||||
|
postcss.list.comma(node.params).forEach(layerOf);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 匿名层各自独立,用块对象本身当 key 避免互相合并
|
||||||
|
layerOf(node.params.trim() || node).push(
|
||||||
|
node.nodes.filter((child) => !unlayered.has(child.toString())),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const flattened = postcss.root();
|
||||||
|
for (const blocks of layers.values()) {
|
||||||
|
for (const nodes of blocks) flattened.append(nodes);
|
||||||
|
}
|
||||||
|
return flattened.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 内联探测脚本:不经过转译,语法须停留在 ES5,且同步执行。
|
||||||
|
// 用 document.write 而非 createElement 插入 <link>:解析器创建的样式表与其余
|
||||||
|
// 入口样式表一样阻塞首帧,不会先闪一下无样式页面。
|
||||||
|
const buildLoader = (href) =>
|
||||||
|
`<script>
|
||||||
|
(function () {
|
||||||
|
try {
|
||||||
|
var probe = document.createElement('style');
|
||||||
|
probe.textContent = '@layer wl-probe{}';
|
||||||
|
document.head.appendChild(probe);
|
||||||
|
var supported = probe.sheet.cssRules.length > 0;
|
||||||
|
document.head.removeChild(probe);
|
||||||
|
if (supported) return;
|
||||||
|
} catch (e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
document.write('<link rel="stylesheet" href="${href}">');
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const STYLESHEET_LINK = /<link\b[^>]*\brel="stylesheet"[^>]*>/g;
|
||||||
|
const CONDITIONAL_LINK = /\s(?:media|disabled)(?=[\s=>/])/i;
|
||||||
|
|
||||||
|
// Rollup 的 asset.source 可能是 string 或 Uint8Array
|
||||||
|
const sourceText = (asset) =>
|
||||||
|
typeof asset.source === 'string'
|
||||||
|
? asset.source
|
||||||
|
: Buffer.from(asset.source).toString('utf8');
|
||||||
|
|
||||||
|
export default function legacyCssLayers() {
|
||||||
|
let base = '/';
|
||||||
|
return {
|
||||||
|
name: 'legacy-css-layers',
|
||||||
|
apply: 'build',
|
||||||
|
// 排在 vite:build-html 之后:此时 index.html 已带上最终的样式表 <link>
|
||||||
|
enforce: 'post',
|
||||||
|
configResolved(config) {
|
||||||
|
base = config.base;
|
||||||
|
},
|
||||||
|
generateBundle(_, bundle) {
|
||||||
|
const layered = Object.keys(bundle).filter(
|
||||||
|
(name) =>
|
||||||
|
name.endsWith('.css') &&
|
||||||
|
bundle[name].type === 'asset' &&
|
||||||
|
hasLayerRule(sourceText(bundle[name])),
|
||||||
|
);
|
||||||
|
if (!layered.length) return;
|
||||||
|
|
||||||
|
// 走到这里说明产物确实依赖 @layer。注入所依赖的 index.html 或入口 <link>
|
||||||
|
// 找不到时,旧浏览器拿不到兜底而新浏览器上毫无征兆 —— 让构建失败,不静默跳过。
|
||||||
|
const page = bundle['index.html'];
|
||||||
|
if (page?.type !== 'asset') {
|
||||||
|
this.error('样式表用到了 @layer,但产物里没有 index.html 可供注入兜底');
|
||||||
|
}
|
||||||
|
const html = sourceText(page);
|
||||||
|
|
||||||
|
// 入口样式表:能对应到产物文件、且无条件加载的 <link>,按文档顺序(层序取决于它)。
|
||||||
|
// 只认解析得出产物文件的标签,注释或脚本字符串里的同形文本不会被当成锚点;
|
||||||
|
// 带 media / disabled 的标签只在特定条件下生效,它的规则既不能无条件收进兜底表,
|
||||||
|
// 也不能拿来给别的样式表剔重,所以不算入口。
|
||||||
|
const entry = [...html.matchAll(STYLESHEET_LINK)]
|
||||||
|
.filter(([tag]) => !CONDITIONAL_LINK.test(tag))
|
||||||
|
.map((match) => ({
|
||||||
|
at: match.index,
|
||||||
|
href: /\bhref="([^"]+)"/.exec(match[0])?.[1],
|
||||||
|
}))
|
||||||
|
.filter(({ href }) => href?.startsWith(base))
|
||||||
|
.map(({ at, href }) => ({ at, name: href.slice(base.length) }))
|
||||||
|
.filter(({ name }) => bundle[name]?.type === 'asset');
|
||||||
|
if (!entry.length) {
|
||||||
|
this.error(
|
||||||
|
'样式表用到了 @layer,但没能从 index.html 里解析出任何入口样式表 <link>,无法注入兜底',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const entryNames = entry.map(({ name }) => name);
|
||||||
|
|
||||||
|
// 不经过入口 <link> 的样式表(懒加载分包、条件加载的表)兜底覆盖不到:
|
||||||
|
// 旧浏览器会丢掉它们层内的那部分样式。
|
||||||
|
for (const name of layered) {
|
||||||
|
if (entryNames.includes(name)) continue;
|
||||||
|
this.warn(`${name} 含 @layer 但不是入口样式表,旧浏览器兜底覆盖不到它`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const css = flattenCssLayers(
|
||||||
|
entryNames.map((name) => sourceText(bundle[name])),
|
||||||
|
);
|
||||||
|
// 层内规则在层外全都有逐字副本:旧浏览器什么也不缺
|
||||||
|
if (!css) return;
|
||||||
|
|
||||||
|
const fileName = this.getFileName(
|
||||||
|
this.emitFile({
|
||||||
|
type: 'asset',
|
||||||
|
name: 'legacy-layers.css',
|
||||||
|
source: css,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// 插在第一个入口样式表之前,兜底表才排在所有入口样式表前面
|
||||||
|
const { at } = entry[0];
|
||||||
|
page.source =
|
||||||
|
html.slice(0, at) + buildLoader(base + fileName) + html.slice(at);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+201
-94
@@ -1,22 +1,3 @@
|
|||||||
/*
|
|
||||||
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, { lazy, Suspense, useContext, useMemo } from 'react';
|
import React, { lazy, Suspense, useContext, useMemo } from 'react';
|
||||||
import { Route, Routes, Navigate, useLocation } from 'react-router-dom';
|
import { Route, Routes, Navigate, useLocation } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
@@ -24,7 +5,13 @@ import {
|
|||||||
isMiniProgramWebView,
|
isMiniProgramWebView,
|
||||||
} from './helpers/miniProgram';
|
} from './helpers/miniProgram';
|
||||||
import Loading from './components/common/ui/Loading';
|
import Loading from './components/common/ui/Loading';
|
||||||
import { AuthRedirect, PrivateRoute, AdminRoute, RootRoute } from './helpers';
|
import {
|
||||||
|
AuthRedirect,
|
||||||
|
PrivateRoute,
|
||||||
|
AdminRoute,
|
||||||
|
RootRoute,
|
||||||
|
} from './helpers/auth';
|
||||||
|
import { PermRoute, ConsoleRoute, ConsoleIndexRoute } from './authz';
|
||||||
import NotFound from './pages/NotFound';
|
import NotFound from './pages/NotFound';
|
||||||
import Forbidden from './pages/Forbidden';
|
import Forbidden from './pages/Forbidden';
|
||||||
import { StatusContext } from './context/Status';
|
import { StatusContext } from './context/Status';
|
||||||
@@ -49,7 +36,6 @@ const About = lazy(() => import('./pages/About'));
|
|||||||
const UserAgreement = lazy(() => import('./pages/UserAgreement'));
|
const UserAgreement = lazy(() => import('./pages/UserAgreement'));
|
||||||
const PrivacyPolicy = lazy(() => import('./pages/PrivacyPolicy'));
|
const PrivacyPolicy = lazy(() => import('./pages/PrivacyPolicy'));
|
||||||
const ExperienceCenter = lazy(() => import('./pages/ExperienceCenter'));
|
const ExperienceCenter = lazy(() => import('./pages/ExperienceCenter'));
|
||||||
const KeyManagement = lazy(() => import('./pages/KeyManagement'));
|
|
||||||
const UserCenter = lazy(() => import('./pages/UserCenter'));
|
const UserCenter = lazy(() => import('./pages/UserCenter'));
|
||||||
const Recharge = lazy(() => import('./pages/Recharge'));
|
const Recharge = lazy(() => import('./pages/Recharge'));
|
||||||
const Tutorial = lazy(() => import('./pages/Tutorial'));
|
const Tutorial = lazy(() => import('./pages/Tutorial'));
|
||||||
@@ -59,9 +45,7 @@ const Docs = lazy(() => import('./pages/Docs'));
|
|||||||
const LoginForm = lazy(() => import('./components/auth/LoginForm'));
|
const LoginForm = lazy(() => import('./components/auth/LoginForm'));
|
||||||
const OrgLogin = lazy(() => import('./pages/OrgLogin'));
|
const OrgLogin = lazy(() => import('./pages/OrgLogin'));
|
||||||
const PartnerPortal = lazy(() => import('./pages/PartnerPortal'));
|
const PartnerPortal = lazy(() => import('./pages/PartnerPortal'));
|
||||||
const PartnerConsole = lazy(() => import('./pages/PartnerPortal/Console'));
|
const CommissionV2 = lazy(() => import('./pages/CommissionV2'));
|
||||||
const CommissionConsole = lazy(() => import('./pages/CommissionConsole'));
|
|
||||||
const MyCommission = lazy(() => import('./pages/MyCommission'));
|
|
||||||
const OrgRegister = lazy(() => import('./pages/OrgRegister'));
|
const OrgRegister = lazy(() => import('./pages/OrgRegister'));
|
||||||
const RegisterForm = lazy(() => import('./components/auth/RegisterForm'));
|
const RegisterForm = lazy(() => import('./components/auth/RegisterForm'));
|
||||||
const PasswordResetForm = lazy(
|
const PasswordResetForm = lazy(
|
||||||
@@ -75,6 +59,8 @@ const OAuth2Callback = lazy(() => import('./components/auth/OAuth2Callback'));
|
|||||||
// 控制台页面懒加载
|
// 控制台页面懒加载
|
||||||
const User = lazy(() => import('./pages/User'));
|
const User = lazy(() => import('./pages/User'));
|
||||||
const Setting = lazy(() => import('./pages/Setting'));
|
const Setting = lazy(() => import('./pages/Setting'));
|
||||||
|
const WebsiteSettings = lazy(() => import('./pages/WebsiteSettings'));
|
||||||
|
const DemoReservations = lazy(() => import('./pages/DemoReservations'));
|
||||||
const Channel = lazy(() => import('./pages/Channel'));
|
const Channel = lazy(() => import('./pages/Channel'));
|
||||||
const Token = lazy(() => import('./pages/Token'));
|
const Token = lazy(() => import('./pages/Token'));
|
||||||
const Redemption = lazy(() => import('./pages/Redemption'));
|
const Redemption = lazy(() => import('./pages/Redemption'));
|
||||||
@@ -94,8 +80,17 @@ const PersonalSetting = lazy(
|
|||||||
);
|
);
|
||||||
const Setup = lazy(() => import('./pages/Setup'));
|
const Setup = lazy(() => import('./pages/Setup'));
|
||||||
const Analytics = lazy(() => import('./pages/Analytics'));
|
const Analytics = lazy(() => import('./pages/Analytics'));
|
||||||
|
const SmartRouter = lazy(() => import('./pages/SmartRouter'));
|
||||||
const Organization = lazy(() => import('./pages/Organization'));
|
const Organization = lazy(() => import('./pages/Organization'));
|
||||||
const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations'));
|
const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations'));
|
||||||
|
// 平台侧权限管理(菜单管理 / 平台角色 / 功能套餐 / 角色模板 / 运行模式)
|
||||||
|
const AuthzMenuManage = lazy(() => import('./pages/Permission/MenuManage'));
|
||||||
|
const AuthzPlatformRoles = lazy(
|
||||||
|
() => import('./pages/Permission/PlatformRoles'),
|
||||||
|
);
|
||||||
|
const AuthzPackages = lazy(() => import('./pages/Permission/Packages'));
|
||||||
|
const AuthzTemplates = lazy(() => import('./pages/Permission/Templates'));
|
||||||
|
const AuthzRunMode = lazy(() => import('./pages/Permission/RunMode'));
|
||||||
const AdminOrder = lazy(() => import('./pages/AdminOrder'));
|
const AdminOrder = lazy(() => import('./pages/AdminOrder'));
|
||||||
const AdminInvoice = lazy(() => import('./pages/AdminInvoice'));
|
const AdminInvoice = lazy(() => import('./pages/AdminInvoice'));
|
||||||
const Subscription = lazy(() => import('./pages/Subscription'));
|
const Subscription = lazy(() => import('./pages/Subscription'));
|
||||||
@@ -127,12 +122,14 @@ const ORG_USER_NAV_PATHS = {
|
|||||||
skillMarket: ['/skill-market'],
|
skillMarket: ['/skill-market'],
|
||||||
docs: ['/docs'],
|
docs: ['/docs'],
|
||||||
experienceCenter: ['/experience-center'],
|
experienceCenter: ['/experience-center'],
|
||||||
keyManagement: ['/key-management'],
|
keyManagement: ['/key-management', '/user-center/key-management'],
|
||||||
userCenter: ['/user-center'],
|
userCenter: ['/user-center'],
|
||||||
};
|
};
|
||||||
|
const matchesPathPrefix = (pathname, prefix) =>
|
||||||
|
pathname === prefix || pathname.startsWith(`${prefix}/`);
|
||||||
const isOrgAllowedPath = (pathname, extraPrefixes = []) =>
|
const isOrgAllowedPath = (pathname, extraPrefixes = []) =>
|
||||||
[...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some(
|
[...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some((prefix) =>
|
||||||
(p) => pathname === p || pathname.startsWith(p + '/'),
|
matchesPathPrefix(pathname, prefix),
|
||||||
);
|
);
|
||||||
|
|
||||||
// 模型超市旧路径 /pricing → /market。用组件而非静态 <Navigate>,
|
// 模型超市旧路径 /pricing → /market。用组件而非静态 <Navigate>,
|
||||||
@@ -147,6 +144,22 @@ const PricingLegacyRedirect = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 密钥管理旧路径 /key-management → /user-center/key-management,同样保留 query/hash
|
||||||
|
// (如创作台 ?from=creation_studio 埋点来源、旧书签与登录回跳带参)
|
||||||
|
const KeyManagementLegacyRedirect = () => {
|
||||||
|
const location = useLocation();
|
||||||
|
return (
|
||||||
|
<Navigate
|
||||||
|
to={{
|
||||||
|
pathname: '/user-center/key-management',
|
||||||
|
search: location.search,
|
||||||
|
hash: location.hash,
|
||||||
|
}}
|
||||||
|
replace
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [statusState] = useContext(StatusContext);
|
const [statusState] = useContext(StatusContext);
|
||||||
@@ -204,27 +217,38 @@ function App() {
|
|||||||
// /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。
|
// /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。
|
||||||
// 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对
|
// 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对
|
||||||
// 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。
|
// 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。
|
||||||
if (isOrgAdmin && !prefixes.includes('/skill-market')) {
|
if (
|
||||||
|
orgMembershipLoaded &&
|
||||||
|
isOrgAdmin &&
|
||||||
|
!prefixes.includes('/skill-market')
|
||||||
|
) {
|
||||||
prefixes.push('/skill-market');
|
prefixes.push('/skill-market');
|
||||||
}
|
}
|
||||||
return prefixes;
|
return prefixes;
|
||||||
}, [statusState?.status?.HeaderNavModulesOrgUser, isOrgAdmin]);
|
}, [
|
||||||
|
statusState?.status?.HeaderNavModulesOrgUser,
|
||||||
|
orgMembershipLoaded,
|
||||||
|
isOrgAdmin,
|
||||||
|
]);
|
||||||
|
|
||||||
// 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。
|
// 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。
|
||||||
// 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。
|
// 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。
|
||||||
// 企业列表未到位前不做封锁判定:isOrgAdmin 首帧恒 false,此时若直接重定向,
|
// 只有技能超市的企业管理员特例需要等待企业列表;等待时也不挂载受限页面。
|
||||||
// 硬刷新/收藏夹直达 /skill-market 的 org_only 管理员会在放行判据还没算出来时
|
const routePath = location.pathname.toLowerCase();
|
||||||
// 就被弹回 /org,而重定向不可逆——之后 isOrgAdmin 变 true 也回不去。
|
|
||||||
const orgConfined =
|
const orgConfined =
|
||||||
userState?.user?.org_only_mode === true &&
|
userState?.user?.org_only_mode === true &&
|
||||||
orgMembershipLoaded &&
|
|
||||||
isOrgCenterAvailable &&
|
isOrgCenterAvailable &&
|
||||||
!isOrgAllowedPath(location.pathname, orgUserAllowedPrefixes);
|
!isOrgAllowedPath(routePath, orgUserAllowedPrefixes);
|
||||||
|
|
||||||
if (orgConfined) {
|
if (orgConfined) {
|
||||||
return (
|
return (
|
||||||
<SetupCheck>
|
<SetupCheck>
|
||||||
<Navigate to='/org' replace />
|
{!orgMembershipLoaded &&
|
||||||
|
matchesPathPrefix(routePath, '/skill-market') ? (
|
||||||
|
<Loading />
|
||||||
|
) : (
|
||||||
|
<Navigate to='/org' replace />
|
||||||
|
)}
|
||||||
</SetupCheck>
|
</SetupCheck>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -265,61 +289,71 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/models'
|
path='/console/models'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.model'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<ModelPage />
|
<ModelPage />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/channel'
|
path='/console/channel'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.channel'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Channel />
|
<Channel />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/token'
|
path='/console/token'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.admin_token'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Token />
|
<Token />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/playground'
|
path='/console/playground'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.playground'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Playground />
|
<Playground />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/monitor'
|
path='/console/monitor'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.monitor'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<MonitorCenter />
|
<MonitorCenter />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/smart-router'
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<SmartRouter />
|
||||||
|
</Suspense>
|
||||||
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/analytics'
|
path='/console/analytics'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.analytics'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Analytics />
|
<Analytics />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
@@ -327,7 +361,7 @@ function App() {
|
|||||||
element={
|
element={
|
||||||
<PrivateRoute>
|
<PrivateRoute>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<MyCommission />
|
<CommissionV2 />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
@@ -336,9 +370,7 @@ function App() {
|
|||||||
path='/console/partner'
|
path='/console/partner'
|
||||||
element={
|
element={
|
||||||
<PrivateRoute>
|
<PrivateRoute>
|
||||||
<Suspense fallback={<Loading />}>
|
<Navigate to='/console/my-commission' replace />
|
||||||
<PartnerConsole />
|
|
||||||
</Suspense>
|
|
||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -348,40 +380,91 @@ function App() {
|
|||||||
/* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/
|
/* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/
|
||||||
伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接
|
伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接
|
||||||
输 URL 进到一个读得到、写按钮全 403 的半残页面。 */
|
输 URL 进到一个读得到、写按钮全 403 的半残页面。 */
|
||||||
<RootRoute>
|
<ConsoleRoute code='platform.commission' legacy='root'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<CommissionConsole />
|
<CommissionV2 />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</RootRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/experience-center-audit'
|
path='/console/experience-center-audit'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.analytics'>
|
||||||
<Navigate to='/console/analytics?tab=audit' replace />
|
<Navigate to='/console/analytics?tab=audit' replace />
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/organizations'
|
path='/console/organizations'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.org'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<AdminOrganizations />
|
<AdminOrganizations />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{/* 平台侧权限管理:路由按与侧边栏相同的权限点守卫(PermRoute),接口权限由后端校验;运行模式仅 root */}
|
||||||
|
<Route
|
||||||
|
path='/console/authz/menus'
|
||||||
|
element={
|
||||||
|
<PermRoute code='platform.authz.menu.query'>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<AuthzMenuManage />
|
||||||
|
</Suspense>
|
||||||
|
</PermRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/authz/roles'
|
||||||
|
element={
|
||||||
|
<PermRoute code='platform.authz.role.query'>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<AuthzPlatformRoles />
|
||||||
|
</Suspense>
|
||||||
|
</PermRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/authz/packages'
|
||||||
|
element={
|
||||||
|
<PermRoute code='platform.authz.package.query'>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<AuthzPackages />
|
||||||
|
</Suspense>
|
||||||
|
</PermRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/authz/templates'
|
||||||
|
element={
|
||||||
|
<PermRoute code='platform.authz.template.query'>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<AuthzTemplates />
|
||||||
|
</Suspense>
|
||||||
|
</PermRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/authz/mode'
|
||||||
|
element={
|
||||||
|
<RootRoute>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<AuthzRunMode />
|
||||||
|
</Suspense>
|
||||||
|
</RootRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/skill-platform'
|
path='/console/skill-platform'
|
||||||
element={
|
element={
|
||||||
CLOUD_BRAIN_UI_ENABLED ? (
|
CLOUD_BRAIN_UI_ENABLED ? (
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.skill'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<SkillPlatform />
|
<SkillPlatform />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
) : (
|
) : (
|
||||||
<Navigate to='/console' replace />
|
<Navigate to='/console' replace />
|
||||||
)
|
)
|
||||||
@@ -391,11 +474,11 @@ function App() {
|
|||||||
path='/console/expert-platform'
|
path='/console/expert-platform'
|
||||||
element={
|
element={
|
||||||
CLOUD_BRAIN_UI_ENABLED ? (
|
CLOUD_BRAIN_UI_ENABLED ? (
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.expert'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<ExpertPlatform />
|
<ExpertPlatform />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
) : (
|
) : (
|
||||||
<Navigate to='/console' replace />
|
<Navigate to='/console' replace />
|
||||||
)
|
)
|
||||||
@@ -404,21 +487,21 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/order'
|
path='/console/order'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.order'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<AdminOrder />
|
<AdminOrder />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/invoice'
|
path='/console/invoice'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.invoice'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<AdminInvoice />
|
<AdminInvoice />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 旧路由重定向到用户中心内的服务监控 */}
|
{/* 旧路由重定向到用户中心内的服务监控 */}
|
||||||
@@ -462,31 +545,31 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/redemption'
|
path='/console/redemption'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.redemption'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Redemption />
|
<Redemption />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/user'
|
path='/console/user'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.user'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<User />
|
<User />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/subscription'
|
path='/console/subscription'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.subscription'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Subscription />
|
<Subscription />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
@@ -608,11 +691,37 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/setting'
|
path='/console/setting'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.setting'>
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<Setting />
|
<Setting />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/website-setting'
|
||||||
|
element={
|
||||||
|
<ConsoleRoute
|
||||||
|
code='platform.setting.website_setting'
|
||||||
|
permission='website-setting'
|
||||||
|
>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<WebsiteSettings />
|
||||||
|
</Suspense>
|
||||||
|
</ConsoleRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/demo-reservations'
|
||||||
|
element={
|
||||||
|
<ConsoleRoute
|
||||||
|
code='platform.setting.demo_reservations'
|
||||||
|
permission='demo-reservations'
|
||||||
|
>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<DemoReservations />
|
||||||
|
</Suspense>
|
||||||
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
@@ -628,49 +737,42 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/topup'
|
path='/console/topup'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.topup'>
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<TopUp />
|
<TopUp />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/log'
|
path='/console/log'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.log'>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<Log />
|
<Log />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path='/console'
|
|
||||||
element={
|
|
||||||
<AdminRoute>
|
|
||||||
<Navigate to='/console/analytics' replace />
|
|
||||||
</AdminRoute>
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route path='/console' element={<ConsoleIndexRoute />} />
|
||||||
<Route
|
<Route
|
||||||
path='/console/midjourney'
|
path='/console/midjourney'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.drawing_log'>
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<Midjourney />
|
<Midjourney />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/task'
|
path='/console/task'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.task_log'>
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<Task />
|
<Task />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
@@ -716,8 +818,13 @@ function App() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{/* 密钥管理归入用户中心路径;旧地址保留为重定向(旧链接、登录回跳、书签) */}
|
||||||
<Route
|
<Route
|
||||||
path='/key-management'
|
path='/key-management'
|
||||||
|
element={<KeyManagementLegacyRedirect />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path='/user-center/key-management'
|
||||||
element={
|
element={
|
||||||
moduleAuthConfig.keyManagement ? (
|
moduleAuthConfig.keyManagement ? (
|
||||||
<PrivateRoute>
|
<PrivateRoute>
|
||||||
@@ -725,12 +832,12 @@ function App() {
|
|||||||
fallback={<Loading></Loading>}
|
fallback={<Loading></Loading>}
|
||||||
key={location.pathname}
|
key={location.pathname}
|
||||||
>
|
>
|
||||||
<KeyManagement />
|
<UserCenter keyManagementMode />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
) : (
|
) : (
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<KeyManagement />
|
<UserCenter keyManagementMode />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -817,11 +924,11 @@ function App() {
|
|||||||
<Route
|
<Route
|
||||||
path='/console/chat/:id?'
|
path='/console/chat/:id?'
|
||||||
element={
|
element={
|
||||||
<AdminRoute>
|
<ConsoleRoute code='platform.chat'>
|
||||||
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
|
||||||
<Chat />
|
<Chat />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AdminRoute>
|
</ConsoleRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 方便使用chat2link直接跳转聊天... */}
|
{/* 方便使用chat2link直接跳转聊天... */}
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 310" fill="none" aria-hidden="true"><defs><linearGradient id="platform-top" x1="180" y1="80" x2="550" y2="300" gradientUnits="userSpaceOnUse"><stop stop-color="#fff9e8"></stop><stop offset="1" stop-color="#e8b363"></stop></linearGradient><linearGradient id="chip-top" x1="290" y1="55" x2="420" y2="210" gradientUnits="userSpaceOnUse"><stop stop-color="#fffdf5"></stop><stop offset="1" stop-color="#f5cb80"></stop></linearGradient><linearGradient id="chip-front" x1="310" y1="140" x2="420" y2="230"><stop stop-color="#eaa849"></stop><stop offset="1" stop-color="#ba6b1b"></stop></linearGradient><linearGradient id="glass" x1="150" y1="55" x2="290" y2="215"><stop stop-color="#fff" stop-opacity=".92"></stop><stop offset="1" stop-color="#fff4db" stop-opacity=".6"></stop></linearGradient><radialGradient id="aura"><stop stop-color="#ffd997" stop-opacity=".65"></stop><stop offset="1" stop-color="#ffd997" stop-opacity="0"></stop></radialGradient><filter id="shadow" x="-40%" y="-40%" width="180%" height="200%"><feGaussianBlur stdDeviation="10"></feGaussianBlur></filter></defs><ellipse cx="404" cy="220" rx="245" ry="78" fill="url(#aura)"></ellipse><ellipse cx="392" cy="244" rx="176" ry="30" fill="#b47536" opacity=".14" filter="url(#shadow)"></ellipse><path d="M172 210L382 91L610 210L395 295Z" fill="#dd9b47" opacity=".17"></path><path d="M172 194L382 75L610 194L395 279Z" fill="url(#platform-top)" stroke="#fff5dd" stroke-width="2"></path><path d="M172 194v16l223 85v-16z" fill="#dbac65" opacity=".7"></path><path d="M395 279l215-85v16l-215 85z" fill="#c99148" opacity=".6"></path><path d="M226 206l89-48 124 49 104-55 M254 232l95-53 119 49 70-34 M394 253v-22" stroke="#c89550" stroke-width="1.5" opacity=".65"></path><g fill="#fff8e4" stroke="#d09b51"><circle cx="226" cy="206" r="4"></circle><circle cx="254" cy="232" r="4"></circle><circle cx="543" cy="152" r="4"></circle><circle cx="538" cy="194" r="4"></circle><circle cx="394" cy="253" r="4"></circle></g><g><path d="M314 151l89-49 108 51-90 49z" fill="url(#chip-top)" stroke="#fff7e6" stroke-width="2"></path><path d="M314 151v23l107 52v-24z" fill="url(#chip-front)"></path><path d="M421 202l90-49v23l-90 50z" fill="#d99c45"></path><path d="M314 121l89-49 108 51-90 49z" fill="url(#chip-top)" stroke="#fff9ea" stroke-width="2"></path><path d="M314 121v20l107 51v-20z" fill="url(#chip-front)"></path><path d="M421 172l90-49v20l-90 49z" fill="#e0aa58"></path><path d="M314 91l89-49 108 51-90 49z" fill="url(#chip-top)" stroke="#fffdf5" stroke-width="2"></path><path d="M314 91v20l107 51v-20z" fill="url(#chip-front)"></path><path d="M421 142l90-49v20l-90 49z" fill="#e5b369"></path><path d="M365 89l36-20 48 23-36 20z" fill="#fff8e7" stroke="#d99d49"></path><path d="M385 88l15-8 25 12-15 8z" fill="#d49338"></path><g stroke="#fff3cc" stroke-width="3" stroke-linecap="round"><path d="M331 113l9 4 M350 122l9 4 M369 131l9 4 M331 143l9 4 M350 152l9 4 M369 161l9 4 M331 175l9 4 M350 184l9 4 M369 193l9 4"></path></g></g><g><path d="M164 85l127 26v112l-127-28z" fill="url(#glass)" stroke="#fff" stroke-width="2"></path><path d="M174 98l106 22v85l-106-23z" fill="#f5d59c" fill-opacity=".42"></path><path d="M187 174v-21 M206 178v-37 M225 182v-27 M244 186v-54 M263 190v-40" stroke="#cc8f39" stroke-width="8"></path><path d="M184 132l24-9 22 14 31-11" stroke="#dda74e" stroke-width="2"></path><circle cx="184" cy="132" r="3" fill="#c48730"></circle></g><g stroke="#f0c47a" stroke-width="1.4"><path d="M503 58l32-18 31 17-32 19z" fill="#fff1d6"></path><path d="M503 58v28l31 18V76z" fill="#e9b66a"></path><path d="M534 76l32-19v29l-32 18z" fill="#f5d59b"></path><path d="M571 139l20-12 22 12-21 12z" fill="#fff6e3"></path><path d="M571 139v20l21 12v-20z" fill="#dfab60"></path><path d="M592 151l21-12v20l-21 12z" fill="#f2ce8f"></path></g><path d="M282 74l13-8 14 8-13 8z M222 64l8-5 9 5-8 5z M548 235l10-6 10 6-10 6z" fill="#ecc589"></path><path d="M479 28v14 M472 35h14 M607 88v10 M602 93h10" stroke="#dfb66d" stroke-width="2" stroke-linecap="round"></path><ellipse cx="391" cy="185" rx="235" ry="91" stroke="#d7a558" stroke-opacity=".28" stroke-width="1.5" stroke-dasharray="4 8"></ellipse></svg>
|
||||||
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
<!-- 来源:原型 http://192.168.0.161:8888 模型超市 .mm-hero .mm-art 内联 SVG(2026-11-04 采集,原样保留路径与配色;动画与深浅主题颜色由 market.css 控制) -->
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 250" preserveAspectRatio="xMidYMid slice"><defs><linearGradient id="mm-trace"><stop stop-color="#c78426" stop-opacity="0"></stop><stop offset=".55" stop-color="#e3ad53"></stop><stop offset="1" stop-color="#ce8729" stop-opacity="0"></stop></linearGradient><radialGradient id="mm-halo"><stop stop-color="#f3bc59" stop-opacity=".35"></stop><stop offset="1" stop-color="#f3bc59" stop-opacity="0"></stop></radialGradient><pattern id="mm-grid" width="44" height="44" patternUnits="userSpaceOnUse"><path d="M44 0H0V44" fill="none" stroke="currentColor" stroke-opacity=".08"></path></pattern></defs><rect width="1440" height="250" fill="url(#mm-grid)"></rect><ellipse cx="1170" cy="135" rx="400" ry="240" fill="url(#mm-halo)"></ellipse><g fill="none" stroke="url(#mm-trace)" stroke-width="1"><path d="M-100 220 180 60h230l110 65h360l120-70h320"></path><path d="M-100 240 180 80h230l110 65h360l120-70h320"></path><path d="M0 200h190l120-70h160M880 180h200l160-95h200"></path><path d="M0 60h200l140 80M1040 250l160-95h240"></path><ellipse cx="1170" cy="133" rx="190" ry="75" transform="rotate(-20 1170 133)"></ellipse><ellipse cx="1170" cy="133" rx="220" ry="90" transform="rotate(-20 1170 133)"></ellipse></g><g class="mm-signals" fill="none" stroke="#e8b04e" stroke-width="2"><path d="M-100 220 180 60h230l110 65h360l120-70h320"></path><path d="M0 200h190l120-70h160M880 180h200l160-95h200"></path></g><g fill="#c5852c"><circle cx="180" cy="60" r="3"></circle><circle cx="410" cy="60" r="3"></circle><circle cx="1000" cy="55" r="3"></circle><circle cx="1080" cy="180" r="3"></circle></g></svg>
|
||||||
|
After Width: | Height: | Size: 1.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 927 B |
@@ -0,0 +1,393 @@
|
|||||||
|
/*
|
||||||
|
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, {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
|
import { useLocation } from 'react-router-dom';
|
||||||
|
import { Modal } from 'antd';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { API } from '../helpers/api';
|
||||||
|
import {
|
||||||
|
clearUserData,
|
||||||
|
isOrgLoginSession,
|
||||||
|
ORG_LOGIN_SESSION_KEY,
|
||||||
|
USER_STORAGE_KEY,
|
||||||
|
} from '../helpers/data';
|
||||||
|
import {
|
||||||
|
clearProxyExpired,
|
||||||
|
getCurrentOrgId,
|
||||||
|
getProxySession,
|
||||||
|
} from '../helpers/orgContext';
|
||||||
|
import { UserContext } from '../context/User';
|
||||||
|
import { normalizeView } from './permLogic';
|
||||||
|
|
||||||
|
// 权限上下文(权限重构 §9 GET /api/authz/me):同时持有平台视图与当前企业视图。
|
||||||
|
// 企业视图随当前企业(或代理会话)切换重新加载。有已切换模块、处于代理会话或上一次加载失败时,页面重新获得焦点
|
||||||
|
// (10 秒内不重复)、或每 60 秒刷新一次;否则(未切换,视图只用于判断是否已切换)每 10 分钟刷新一次、获得焦点时
|
||||||
|
// 2 分钟内不重复,不挤占按 IP 计数的全局限流,同时切换后用户切回窗口即可较快跟上。
|
||||||
|
// 当前视图的有效内容(权限点、菜单、数据范围)发生变化且涉及已切换模块时,按 Q12 要求重新登录。
|
||||||
|
|
||||||
|
export const AuthzContext = createContext({
|
||||||
|
platform: null,
|
||||||
|
org: null,
|
||||||
|
orgLoadedKey: null,
|
||||||
|
platformLoadedFor: 0,
|
||||||
|
platformLoadFailed: false,
|
||||||
|
reload: () => {},
|
||||||
|
});
|
||||||
|
|
||||||
|
const REFRESH_MS = 60 * 1000;
|
||||||
|
// 未切换时的刷新间隔
|
||||||
|
const IDLE_REFRESH_MS = 10 * 60 * 1000;
|
||||||
|
// 窗口 focus 触发刷新的节流间隔:频繁切换窗口时不重复拉取
|
||||||
|
const FOCUS_THROTTLE_MS = 10 * 1000;
|
||||||
|
// 未切换时 focus 触发刷新的节流间隔
|
||||||
|
const IDLE_FOCUS_THROTTLE_MS = 2 * 60 * 1000;
|
||||||
|
|
||||||
|
// 未登录(会话失效、其他标签页已登出):不算"加载失败",不因此转入高频刷新
|
||||||
|
const UNAUTHORIZED = Symbol('unauthorized');
|
||||||
|
|
||||||
|
// 拉取视图;接口 success:false 或网络错误返回 null(调用方按"加载失败"处理),401 返回 UNAUTHORIZED
|
||||||
|
const fetchView = async (headers) => {
|
||||||
|
try {
|
||||||
|
const res = await API.get('/api/authz/me', {
|
||||||
|
headers,
|
||||||
|
skipErrorHandler: true,
|
||||||
|
disableDuplicate: true,
|
||||||
|
});
|
||||||
|
return res.data?.success ? normalizeView(res.data.data) : null;
|
||||||
|
} catch (e) {
|
||||||
|
return e?.response?.status === 401 ? UNAUTHORIZED : null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 当前企业视图的标识(企业 ID + 代理会话):企业中心据此判断企业视图是否已按当前企业加载过
|
||||||
|
export const currentOrgViewKey = () =>
|
||||||
|
`${getCurrentOrgId()}:${getProxySession()?.id || ''}`;
|
||||||
|
|
||||||
|
const orgHeaders = () => {
|
||||||
|
const proxy = getProxySession();
|
||||||
|
const orgId = getCurrentOrgId();
|
||||||
|
if (!orgId) return null;
|
||||||
|
const h = { 'X-Org-Id': String(orgId) };
|
||||||
|
if (proxy) h['X-Proxy-Session'] = proxy.id;
|
||||||
|
return h;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 视图有效内容的指纹:只取已切换模块(前后两次 enforced_modules 的并集)内的权限点、
|
||||||
|
// 菜单(code 与 visible)与数据范围类型(全部 / 部门 / 本人);未切换模块的变化不影响页面行为,不纳入。
|
||||||
|
// 部门个数不纳入:它是按部门树展开后的个数,新增子部门就会变化,而页面行为不变。
|
||||||
|
// 已切换模块列表本身不纳入:模块切换(或回退)只是把页面从旧判断改为按权限点判断,界面就地更新,
|
||||||
|
// 不属于 Q12 所说的撤权,不要求重新登录;切换前后权限点本身的变化仍会按上面的并集比较提示。
|
||||||
|
// 不用 version:它包含目录与企业版本,改任意菜单名、角色名都会变化,会误弹重新登录。
|
||||||
|
const viewSignature = (v, inScope) =>
|
||||||
|
JSON.stringify([
|
||||||
|
(v.perms || []).filter(inScope).sort(),
|
||||||
|
(v.menus || [])
|
||||||
|
.filter((m) => inScope(m.code))
|
||||||
|
.map((m) => `${m.code}:${m.visible ? 1 : 0}`)
|
||||||
|
.sort(),
|
||||||
|
Object.entries(v.scopes || {})
|
||||||
|
.filter(([code]) => inScope(code))
|
||||||
|
.map(
|
||||||
|
([code, sc]) =>
|
||||||
|
`${code}:${sc?.all ? 1 : 0}:${sc?.depts ? 1 : 0}:${sc?.self ? 1 : 0}`,
|
||||||
|
)
|
||||||
|
.sort(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 有效内容变化且涉及已切换模块:权限确实影响到页面行为,需要重新登录
|
||||||
|
const changedUnderEnforce = (prev, next) => {
|
||||||
|
if (!prev || !next) return false;
|
||||||
|
// 用户、企业或登录域不同都是换了会话(如个人会话改用企业入口登录),不是权限变更
|
||||||
|
if (
|
||||||
|
prev.user_id !== next.user_id ||
|
||||||
|
prev.org_id !== next.org_id ||
|
||||||
|
prev.domain !== next.domain ||
|
||||||
|
(prev.session_domain || '') !== (next.session_domain || '')
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const modules = new Set([
|
||||||
|
...(prev.enforced_modules || []),
|
||||||
|
...(next.enforced_modules || []),
|
||||||
|
]);
|
||||||
|
if (modules.size === 0) return false;
|
||||||
|
const moduleOf = { ...(prev.module_of || {}), ...(next.module_of || {}) };
|
||||||
|
const inScope = (code) => modules.has(moduleOf[code]);
|
||||||
|
return viewSignature(prev, inScope) !== viewSignature(next, inScope);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 视图是否涉及已切换模块(需要高频刷新以及时发现权限变更;代理会话另由调用方判断)
|
||||||
|
const isActiveView = (v) => !!v && (v.enforced_modules || []).length > 0;
|
||||||
|
|
||||||
|
// 内容相同的视图不重新写入状态,避免每次刷新都让订阅方(企业中心等)重渲染
|
||||||
|
const sameView = (a, b) => {
|
||||||
|
if (a === b) return true;
|
||||||
|
if (!a || !b) return false;
|
||||||
|
try {
|
||||||
|
return JSON.stringify(a) === JSON.stringify(b);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AuthzProvider = ({ children }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [userState, userDispatch] = useContext(UserContext);
|
||||||
|
const userId = userState?.user?.id || 0;
|
||||||
|
const location = useLocation();
|
||||||
|
const [platform, setPlatform] = useState(null);
|
||||||
|
const [org, setOrg] = useState(null);
|
||||||
|
// 最近一次企业视图加载(无论成败)对应的 currentOrgViewKey;未加载过为 null
|
||||||
|
const [orgLoadedKey, setOrgLoadedKey] = useState(null);
|
||||||
|
// 平台视图已为哪个用户加载过(成败均算);路由守卫据此等待视图到达,避免先按旧判断误拦
|
||||||
|
const [platformLoadedFor, setPlatformLoadedFor] = useState(0);
|
||||||
|
// 最近一次平台视图加载是否失败(配合 platformLoadedFor 使用):路由守卫据此显示可重试提示
|
||||||
|
const [platformLoadFailed, setPlatformLoadFailed] = useState(false);
|
||||||
|
const prevRef = useRef({ platform: null, org: null });
|
||||||
|
const promptedRef = useRef(false);
|
||||||
|
// 已弹出的"权限已变更"提示实例:其他标签页换了会话时关闭它
|
||||||
|
const modalRef = useRef(null);
|
||||||
|
// 最近一次开始拉取视图的时间,用于 focus 刷新节流
|
||||||
|
const lastFetchRef = useRef(0);
|
||||||
|
// 最近一次加载是否有视图失败:失败后按高频刷新重试,否则已切换企业首次加载失败时会按旧判断渲染最长 10 分钟
|
||||||
|
const failedRef = useRef(false);
|
||||||
|
// 最新的 reload:storage 事件处理里主动重新加载(事件处理只注册一次)
|
||||||
|
const reloadRef = useRef(null);
|
||||||
|
// 企业会话(企业域登录、或仅企业资源账号)重新登录回 /org/login,否则回 /login
|
||||||
|
const orgOnlyRef = useRef(false);
|
||||||
|
orgOnlyRef.current = userState?.user?.org_only_mode === true;
|
||||||
|
const onOrgPage = location.pathname.startsWith('/org');
|
||||||
|
const orgKey = onOrgPage ? currentOrgViewKey() : '';
|
||||||
|
|
||||||
|
const promptRelogin = useCallback(() => {
|
||||||
|
if (promptedRef.current) return;
|
||||||
|
promptedRef.current = true;
|
||||||
|
// 只能点"重新登录":不提供关闭按钮,点遮罩与按 Esc 都不关闭
|
||||||
|
modalRef.current = Modal.warning({
|
||||||
|
title: t('权限已变更'),
|
||||||
|
content: t('你的权限已变更,请重新登录。'),
|
||||||
|
okText: t('重新登录'),
|
||||||
|
centered: true,
|
||||||
|
closable: false,
|
||||||
|
keyboard: false,
|
||||||
|
mask: { closable: false },
|
||||||
|
onOk: async () => {
|
||||||
|
modalRef.current = null;
|
||||||
|
// 先判断会话域,再登出清理(清理会移除企业登录标记)
|
||||||
|
// 以后端返回的登录域为准;老版本后端没有该字段时退回本地标记
|
||||||
|
const view = prevRef.current.org || prevRef.current.platform;
|
||||||
|
const orgSession = view?.session_domain
|
||||||
|
? view.session_domain === 'org'
|
||||||
|
: isOrgLoginSession() || orgOnlyRef.current;
|
||||||
|
const target = orgSession ? '/org/login' : '/login';
|
||||||
|
try {
|
||||||
|
await API.get('/api/user/logout', {
|
||||||
|
skipErrorHandler: true,
|
||||||
|
disableDuplicate: true,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// 登出失败也继续清理本地数据并跳转登录页
|
||||||
|
}
|
||||||
|
clearUserData();
|
||||||
|
userDispatch({ type: 'logout' });
|
||||||
|
window.location.href = target;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}, [t, userDispatch]);
|
||||||
|
|
||||||
|
const reload = useCallback(async () => {
|
||||||
|
lastFetchRef.current = Date.now();
|
||||||
|
const loadingKey = currentOrgViewKey();
|
||||||
|
if (!userId) {
|
||||||
|
setPlatform(null);
|
||||||
|
setOrg(null);
|
||||||
|
prevRef.current = { platform: null, org: null };
|
||||||
|
setOrgLoadedKey(loadingKey);
|
||||||
|
setPlatformLoadedFor(0);
|
||||||
|
setPlatformLoadFailed(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const headers = onOrgPage ? orgHeaders() : null;
|
||||||
|
const [pr, or] = await Promise.all([
|
||||||
|
fetchView(undefined),
|
||||||
|
headers ? fetchView(headers) : Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
const unauthorized = pr === UNAUTHORIZED || or === UNAUTHORIZED;
|
||||||
|
const p = pr === UNAUTHORIZED ? null : pr;
|
||||||
|
const o = or === UNAUTHORIZED ? null : or;
|
||||||
|
if (p) {
|
||||||
|
if (changedUnderEnforce(prevRef.current.platform, p)) promptRelogin();
|
||||||
|
const same = sameView(prevRef.current.platform, p);
|
||||||
|
prevRef.current.platform = p;
|
||||||
|
if (!same) setPlatform(p);
|
||||||
|
} else {
|
||||||
|
// 加载失败:保留上一份视图作比较基准;不属于当前用户的旧视图不能再用
|
||||||
|
const kept = prevRef.current.platform;
|
||||||
|
if (kept && kept.user_id !== userId) {
|
||||||
|
prevRef.current.platform = null;
|
||||||
|
setPlatform(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setPlatformLoadFailed(!p);
|
||||||
|
setPlatformLoadedFor(userId);
|
||||||
|
failedRef.current = !unauthorized && (!p || (!!headers && !o));
|
||||||
|
if (!headers) {
|
||||||
|
prevRef.current.org = null;
|
||||||
|
setOrg(null);
|
||||||
|
// 不在企业页时并未加载企业视图,不能标记为已就绪(否则进入企业中心时会按旧判断先行守卫)
|
||||||
|
setOrgLoadedKey(onOrgPage ? loadingKey : null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (o) {
|
||||||
|
if (changedUnderEnforce(prevRef.current.org, o)) promptRelogin();
|
||||||
|
const same = sameView(prevRef.current.org, o);
|
||||||
|
prevRef.current.org = o;
|
||||||
|
if (!same) setOrg(o);
|
||||||
|
} else {
|
||||||
|
// 加载失败:保留上一份视图作比较基准;只有仍属于当前用户与当前企业时才继续使用
|
||||||
|
const kept = prevRef.current.org;
|
||||||
|
if (
|
||||||
|
kept &&
|
||||||
|
(kept.user_id !== userId || kept.org_id !== getCurrentOrgId())
|
||||||
|
) {
|
||||||
|
prevRef.current.org = null;
|
||||||
|
setOrg(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setOrgLoadedKey(loadingKey);
|
||||||
|
}, [userId, onOrgPage, promptRelogin]);
|
||||||
|
|
||||||
|
// 换账号、换企业(含进入 / 退出代理)都要重新加载:企业键不参与 reload 本身的计算,单独作为触发条件
|
||||||
|
useEffect(() => {
|
||||||
|
reloadRef.current = reload;
|
||||||
|
}, [reload]);
|
||||||
|
useEffect(() => {
|
||||||
|
reload();
|
||||||
|
}, [reload, orgKey]);
|
||||||
|
|
||||||
|
// 换账号(含登出):允许对新账号重新提示
|
||||||
|
useEffect(() => {
|
||||||
|
promptedRef.current = false;
|
||||||
|
}, [userId]);
|
||||||
|
|
||||||
|
// 离开企业中心:清除本标签页的"代理已失效"标记,之后再进入 /org 按正常企业上下文解析
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onOrgPage) clearProxyExpired();
|
||||||
|
}, [onOrgPage]);
|
||||||
|
|
||||||
|
// 多标签页:其他标签页重新登录或登出(localStorage 用户数据变化)时,关闭本页已弹出的提示,
|
||||||
|
// 避免在旧标签页点"重新登录"把新会话注销;同时丢弃旧的比较基准,下一次加载按新会话重新建立
|
||||||
|
useEffect(() => {
|
||||||
|
// 只看用户身份:登出(键被删)或换成另一个用户才算换会话;额度等字段刷新不算,
|
||||||
|
// 否则会关掉仍然有效的提示并丢弃比较基准,本标签页就再也不会提示了
|
||||||
|
const userIdOf = (raw) => {
|
||||||
|
try {
|
||||||
|
return raw ? JSON.parse(raw)?.id || 0 : 0;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onStorage = (e) => {
|
||||||
|
if (
|
||||||
|
e.key !== USER_STORAGE_KEY &&
|
||||||
|
e.key !== ORG_LOGIN_SESSION_KEY &&
|
||||||
|
e.key !== null
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 企业登录标记变化:同一用户在其他标签页改用企业入口(或个人入口)登录,登录域变了,按换会话处理
|
||||||
|
if (
|
||||||
|
e.key === USER_STORAGE_KEY &&
|
||||||
|
e.newValue !== null &&
|
||||||
|
userIdOf(e.oldValue) === userIdOf(e.newValue)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (modalRef.current) {
|
||||||
|
modalRef.current.destroy();
|
||||||
|
modalRef.current = null;
|
||||||
|
}
|
||||||
|
promptedRef.current = false;
|
||||||
|
prevRef.current = { platform: null, org: null };
|
||||||
|
// 立即按新会话重新加载:本标签页的 UserContext 不跨标签同步,不会自己触发加载;
|
||||||
|
// 清空基准后也不再算"有已切换模块",不主动加载就要等最长 10 分钟
|
||||||
|
if (reloadRef.current) reloadRef.current();
|
||||||
|
};
|
||||||
|
window.addEventListener('storage', onStorage);
|
||||||
|
return () => window.removeEventListener('storage', onStorage);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!userId) return undefined;
|
||||||
|
const active = () =>
|
||||||
|
failedRef.current ||
|
||||||
|
isActiveView(prevRef.current.platform) ||
|
||||||
|
isActiveView(prevRef.current.org) ||
|
||||||
|
!!getProxySession();
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (
|
||||||
|
active() ||
|
||||||
|
Date.now() - lastFetchRef.current >= IDLE_REFRESH_MS - 1000
|
||||||
|
) {
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
}, REFRESH_MS);
|
||||||
|
const onFocus = () => {
|
||||||
|
const throttle = active() ? FOCUS_THROTTLE_MS : IDLE_FOCUS_THROTTLE_MS;
|
||||||
|
if (Date.now() - lastFetchRef.current < throttle) return;
|
||||||
|
reload();
|
||||||
|
};
|
||||||
|
window.addEventListener('focus', onFocus);
|
||||||
|
return () => {
|
||||||
|
clearInterval(timer);
|
||||||
|
window.removeEventListener('focus', onFocus);
|
||||||
|
};
|
||||||
|
}, [userId, reload]);
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({
|
||||||
|
platform,
|
||||||
|
org,
|
||||||
|
orgLoadedKey,
|
||||||
|
platformLoadedFor,
|
||||||
|
platformLoadFailed,
|
||||||
|
reload,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
platform,
|
||||||
|
org,
|
||||||
|
orgLoadedKey,
|
||||||
|
platformLoadedFor,
|
||||||
|
platformLoadFailed,
|
||||||
|
reload,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<AuthzContext.Provider value={value}>{children}</AuthzContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
+6
-9
@@ -18,15 +18,12 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import PricingTable from '../../view/table/PricingTable';
|
import { usePerm } from './usePerm';
|
||||||
import PricingCardView from '../../view/card/PricingCardView';
|
|
||||||
|
|
||||||
const PricingView = ({ viewMode = 'table', ...props }) => {
|
// <Perm code='org.member.edit' legacy={isAdmin} fallback={null}>…</Perm>
|
||||||
return viewMode === 'card' ? (
|
const Perm = ({ code, legacy, fallback = null, children }) => {
|
||||||
<PricingCardView {...props} />
|
const allowed = usePerm(code, legacy);
|
||||||
) : (
|
return <>{allowed ? children : fallback}</>;
|
||||||
<PricingTable {...props} />
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default PricingView;
|
export default Perm;
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
/*
|
||||||
|
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, { useContext, useState } from 'react';
|
||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button, Result } from 'antd';
|
||||||
|
import Loading from '../components/common/ui/Loading';
|
||||||
|
import { AdminRoute, PrivateRoute, RootRoute } from '../helpers/auth';
|
||||||
|
import { isRoot } from '../helpers/utils';
|
||||||
|
import { UserContext } from '../context/User';
|
||||||
|
import { AuthzContext } from './AuthzProvider';
|
||||||
|
import { usePerm } from './usePerm';
|
||||||
|
|
||||||
|
// 平台视图加载失败:给出可重试的提示,而不是按旧判断直接跳 /forbidden
|
||||||
|
const LoadFailed = ({ reload }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [retrying, setRetrying] = useState(false);
|
||||||
|
const retry = async () => {
|
||||||
|
setRetrying(true);
|
||||||
|
try {
|
||||||
|
await reload();
|
||||||
|
} finally {
|
||||||
|
setRetrying(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Result
|
||||||
|
status='warning'
|
||||||
|
title={t('权限信息加载失败')}
|
||||||
|
subTitle={t('请检查网络后重试')}
|
||||||
|
extra={
|
||||||
|
<Button type='primary' loading={retrying} onClick={retry}>
|
||||||
|
{t('重试')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 会话已在其他标签页变更:刷新页面按新会话重新加载
|
||||||
|
const SessionChanged = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Result
|
||||||
|
status='info'
|
||||||
|
title={t('登录状态已变化')}
|
||||||
|
subTitle={t('你已在其他页面切换了账号,请刷新页面')}
|
||||||
|
extra={
|
||||||
|
<Button type='primary' onClick={() => window.location.reload()}>
|
||||||
|
{t('刷新页面')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 平台视图是否已就绪。返回 null 表示就绪,否则返回等待期间应显示的内容。
|
||||||
|
// 就绪:已有属于当前用户的平台视图(之后的刷新失败不影响);否则本用户的加载已结束且失败时提示重试。
|
||||||
|
const useViewPending = () => {
|
||||||
|
const [userState] = useContext(UserContext);
|
||||||
|
const { platform, platformLoadedFor, platformLoadFailed, reload } =
|
||||||
|
useContext(AuthzContext);
|
||||||
|
const userId = userState?.user?.id || 0;
|
||||||
|
const viewReady = !!platform && platform.user_id === userId;
|
||||||
|
if (!userId || viewReady) return { pending: null, failed: false };
|
||||||
|
if (platformLoadedFor === userId && platformLoadFailed) {
|
||||||
|
return { pending: <LoadFailed reload={reload} />, failed: true };
|
||||||
|
}
|
||||||
|
// 视图已加载但属于另一个用户:其他标签页换了账号,本页的用户信息已过期,提示刷新而不是一直转圈
|
||||||
|
if (platformLoadedFor === userId && platform) {
|
||||||
|
return { pending: <SessionChanged />, failed: false };
|
||||||
|
}
|
||||||
|
return { pending: <Loading />, failed: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
// 按平台权限点守卫的路由:判断与侧边栏一致(usePerm(code, isRoot())),
|
||||||
|
// 平台视图到达前显示加载中,加载失败显示可重试提示,无权限时与其它守卫一样跳 /forbidden。
|
||||||
|
const PermGate = ({ code, children }) => {
|
||||||
|
const allowed = usePerm(code, isRoot());
|
||||||
|
const { pending } = useViewPending();
|
||||||
|
if (pending) return pending;
|
||||||
|
if (!allowed) return <Navigate to='/forbidden' replace />;
|
||||||
|
return children;
|
||||||
|
};
|
||||||
|
|
||||||
|
const PermRoute = ({ code, children }) => (
|
||||||
|
<PrivateRoute>
|
||||||
|
<PermGate code={code}>{children}</PermGate>
|
||||||
|
</PrivateRoute>
|
||||||
|
);
|
||||||
|
|
||||||
|
// 原有守卫:legacy='root' 为 RootRoute,否则为 AdminRoute(permission 为系统设置页签委派校验)
|
||||||
|
const LegacyRoute = ({ legacy, permission, children }) =>
|
||||||
|
legacy === 'root' ? (
|
||||||
|
<RootRoute>{children}</RootRoute>
|
||||||
|
) : (
|
||||||
|
<AdminRoute permission={permission}>{children}</AdminRoute>
|
||||||
|
);
|
||||||
|
|
||||||
|
// 控制台路由守卫(新旧双路径):code 所属模块已切到新体系时按权限点判断(持有权限点的非管理员也能进入,
|
||||||
|
// 没有权限点的管理员进不去);未切换时完全沿用原有守卫(AdminRoute / RootRoute)。
|
||||||
|
// 用法:<ConsoleRoute code='platform.channel'>、<ConsoleRoute code='platform.commission' legacy='root'>、
|
||||||
|
// <ConsoleRoute code='platform.setting.website_setting' permission='website-setting'>
|
||||||
|
export const ConsoleRoute = ({
|
||||||
|
code,
|
||||||
|
legacy = 'admin',
|
||||||
|
permission,
|
||||||
|
children,
|
||||||
|
}) => {
|
||||||
|
const [userState] = useContext(UserContext);
|
||||||
|
const { platform } = useContext(AuthzContext);
|
||||||
|
const { pending, failed } = useViewPending();
|
||||||
|
const user = userState?.user;
|
||||||
|
const legacyRoute = (
|
||||||
|
<LegacyRoute legacy={legacy} permission={permission}>
|
||||||
|
{children}
|
||||||
|
</LegacyRoute>
|
||||||
|
);
|
||||||
|
// 未登录或登录态校验中:交给原有守卫(跳登录页或显示加载中)
|
||||||
|
if (!user) return legacyRoute;
|
||||||
|
if (pending) {
|
||||||
|
// 视图加载失败时无从得知模块是否已切换:原判断会放行的人仍按原有守卫进入(接口权限由后端校验),
|
||||||
|
// 避免权限接口故障把管理员挡在控制台外;其余人显示可重试提示
|
||||||
|
const legacyRole = legacy === 'root' ? 100 : 10;
|
||||||
|
if (failed && typeof user.role === 'number' && user.role >= legacyRole) {
|
||||||
|
return legacyRoute;
|
||||||
|
}
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
const mod = platform.moduleOf[code];
|
||||||
|
if (!mod || !platform.enforcedSet.has(mod)) return legacyRoute;
|
||||||
|
if (!platform.permSet.has(code)) return <Navigate to='/forbidden' replace />;
|
||||||
|
return children;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 控制台入口 /console:原行为是管理员进运营看板。运营看板模块已切换且当前用户没有该菜单时
|
||||||
|
// (含持有其他平台菜单的非管理员),改进第一个已切换且持有的控制台菜单;都没有时按原有守卫处理。
|
||||||
|
export const ConsoleIndexRoute = () => {
|
||||||
|
const [userState] = useContext(UserContext);
|
||||||
|
const { platform } = useContext(AuthzContext);
|
||||||
|
const { pending, failed } = useViewPending();
|
||||||
|
const user = userState?.user;
|
||||||
|
const legacyRoute = (
|
||||||
|
<AdminRoute>
|
||||||
|
<Navigate to='/console/analytics' replace />
|
||||||
|
</AdminRoute>
|
||||||
|
);
|
||||||
|
if (!user) return legacyRoute;
|
||||||
|
if (pending) {
|
||||||
|
if (failed && typeof user.role === 'number' && user.role >= 10) {
|
||||||
|
return legacyRoute;
|
||||||
|
}
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
const enforced = (code) => platform.enforcedSet.has(platform.moduleOf[code]);
|
||||||
|
const analyticsEnforced = enforced('platform.analytics');
|
||||||
|
const canAnalytics = analyticsEnforced
|
||||||
|
? platform.permSet.has('platform.analytics')
|
||||||
|
: typeof user.role === 'number' && user.role >= 10;
|
||||||
|
if (canAnalytics) return <Navigate to='/console/analytics' replace />;
|
||||||
|
// view.menus 已按 sort 排好,且只含当前用户持有的节点
|
||||||
|
const first = (platform.menus || []).find(
|
||||||
|
(m) =>
|
||||||
|
m.type === 'menu' &&
|
||||||
|
m.visible &&
|
||||||
|
typeof m.route === 'string' &&
|
||||||
|
m.route.startsWith('/console/') &&
|
||||||
|
enforced(m.code),
|
||||||
|
);
|
||||||
|
if (first) return <Navigate to={first.route} replace />;
|
||||||
|
return legacyRoute;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PermRoute;
|
||||||
+15
-17
@@ -17,20 +17,18 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||||||
For commercial licensing, please contact support@quantumnous.com
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React from 'react';
|
export { AuthzContext, AuthzProvider } from './AuthzProvider';
|
||||||
import { Button } from '@douyinfe/semi-ui';
|
export {
|
||||||
|
usePerm,
|
||||||
const FilterModalFooter = ({ onReset, onConfirm, t }) => {
|
useAnyPerm,
|
||||||
return (
|
useAuthzView,
|
||||||
<div className='flex justify-end'>
|
useAuthzReload,
|
||||||
<Button theme='outline' type='tertiary' onClick={onReset}>
|
useOrgViewReady,
|
||||||
{t('重置')}
|
} from './usePerm';
|
||||||
</Button>
|
export { default as Perm } from './Perm';
|
||||||
<Button theme='solid' type='primary' onClick={onConfirm}>
|
export {
|
||||||
{t('确定')}
|
default as PermRoute,
|
||||||
</Button>
|
ConsoleRoute,
|
||||||
</div>
|
ConsoleIndexRoute,
|
||||||
);
|
} from './PermRoute';
|
||||||
};
|
export { checkPerm, checkAnyPerm, buildMenuTree } from './permLogic';
|
||||||
|
|
||||||
export default FilterModalFooter;
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/*
|
||||||
|
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
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 权限判断的纯逻辑(权限重构 §7.1 新旧双路径),与 React 无关,便于单测。
|
||||||
|
// view 为 /api/authz/me 的返回;legacy 为旧判断(布尔或返回布尔的函数)。
|
||||||
|
|
||||||
|
export function normalizeView(data) {
|
||||||
|
if (!data) return null;
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
permSet: new Set(data.perms || []),
|
||||||
|
enforcedSet: new Set(data.enforced_modules || []),
|
||||||
|
moduleOf: data.module_of || {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const evalLegacy = (legacy) =>
|
||||||
|
typeof legacy === 'function' ? !!legacy() : !!legacy;
|
||||||
|
|
||||||
|
// 模块已切到新体系(enforced):以权限点为准;否则走旧判断。未提供旧判断时按权限点判断。
|
||||||
|
// view 尚未加载:有旧判断走旧判断,否则不放行。
|
||||||
|
export function checkPerm(view, code, legacy) {
|
||||||
|
if (!view) return legacy === undefined ? false : evalLegacy(legacy);
|
||||||
|
const mod = view.moduleOf[code];
|
||||||
|
if (mod && view.enforcedSet.has(mod)) return view.permSet.has(code);
|
||||||
|
if (legacy === undefined) return view.permSet.has(code);
|
||||||
|
return evalLegacy(legacy);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 是否持有任一权限点(同样按模块逐个走新旧路径)。
|
||||||
|
export function checkAnyPerm(view, codes, legacy) {
|
||||||
|
return codes.some((c) => checkPerm(view, c, legacy));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 视图对应的域:org.* 权限点看企业视图,其余看平台视图。
|
||||||
|
export function viewForCode(views, code) {
|
||||||
|
return code.startsWith('org.') ? views.org : views.platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 菜单树:按 parent 组装,同级按 sort;只保留 visible 的节点。
|
||||||
|
export function buildMenuTree(menus) {
|
||||||
|
const byParent = new Map();
|
||||||
|
for (const m of menus || []) {
|
||||||
|
if (!m.visible) continue;
|
||||||
|
const list = byParent.get(m.parent || '') || [];
|
||||||
|
list.push(m);
|
||||||
|
byParent.set(m.parent || '', list);
|
||||||
|
}
|
||||||
|
const build = (parent) =>
|
||||||
|
(byParent.get(parent) || [])
|
||||||
|
.sort((a, b) => a.sort - b.sort || a.code.localeCompare(b.code))
|
||||||
|
.map((m) => ({ ...m, children: build(m.code) }));
|
||||||
|
return build('');
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
|
import {
|
||||||
|
normalizeView,
|
||||||
|
checkPerm,
|
||||||
|
checkAnyPerm,
|
||||||
|
buildMenuTree,
|
||||||
|
} from './permLogic.js';
|
||||||
|
|
||||||
|
const view = normalizeView({
|
||||||
|
perms: ['org.member', 'org.member.query'],
|
||||||
|
enforced_modules: ['member'],
|
||||||
|
module_of: {
|
||||||
|
'org.member': 'member',
|
||||||
|
'org.member.query': 'member',
|
||||||
|
'org.member.edit': 'member',
|
||||||
|
'org.dept.query': 'dept',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enforced module follows perms, ignoring the legacy check', () => {
|
||||||
|
assert.equal(checkPerm(view, 'org.member.query', false), true);
|
||||||
|
assert.equal(checkPerm(view, 'org.member.edit', true), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('non-enforced module follows the legacy check', () => {
|
||||||
|
assert.equal(checkPerm(view, 'org.dept.query', true), true);
|
||||||
|
assert.equal(
|
||||||
|
checkPerm(view, 'org.dept.query', () => false),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.equal(checkPerm(view, 'org.dept.query'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('view not loaded yet', () => {
|
||||||
|
assert.equal(checkPerm(null, 'org.member.query'), false);
|
||||||
|
assert.equal(checkPerm(null, 'org.member.query', true), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('any of several perms', () => {
|
||||||
|
assert.equal(
|
||||||
|
checkAnyPerm(view, ['org.member.edit', 'org.member.query']),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(checkAnyPerm(view, ['org.member.edit']), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('menu tree keeps visible nodes ordered by sort', () => {
|
||||||
|
const tree = buildMenuTree([
|
||||||
|
{ code: 'b', parent: '', sort: 20, visible: true },
|
||||||
|
{ code: 'a', parent: '', sort: 10, visible: true },
|
||||||
|
{ code: 'a.x', parent: 'a', sort: 10, visible: true },
|
||||||
|
{ code: 'a.h', parent: 'a', sort: 5, visible: false },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(
|
||||||
|
tree.map((n) => n.code),
|
||||||
|
['a', 'b'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
tree[0].children.map((n) => n.code),
|
||||||
|
['a.x'],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useContext, useEffect } from 'react';
|
||||||
|
import { AuthzContext, currentOrgViewKey } from './AuthzProvider';
|
||||||
|
import { checkPerm, checkAnyPerm, viewForCode } from './permLogic';
|
||||||
|
|
||||||
|
// usePerm(code, legacy):模块已切到新体系时按权限点判断,否则按 legacy(旧判断)判断。
|
||||||
|
export function usePerm(code, legacy) {
|
||||||
|
const ctx = useContext(AuthzContext);
|
||||||
|
return checkPerm(viewForCode(ctx, code), code, legacy);
|
||||||
|
}
|
||||||
|
|
||||||
|
// useAnyPerm(codes, legacy):持有其中任一权限点。
|
||||||
|
export function useAnyPerm(codes, legacy) {
|
||||||
|
const ctx = useContext(AuthzContext);
|
||||||
|
if (!codes.length) return false;
|
||||||
|
return checkAnyPerm(viewForCode(ctx, codes[0]), codes, legacy);
|
||||||
|
}
|
||||||
|
|
||||||
|
// useAuthzView(domain):'platform' | 'org' 的原始视图(菜单树渲染等)。
|
||||||
|
export function useAuthzView(domain) {
|
||||||
|
const ctx = useContext(AuthzContext);
|
||||||
|
return domain === 'org' ? ctx.org : ctx.platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuthzReload() {
|
||||||
|
return useContext(AuthzContext).reload;
|
||||||
|
}
|
||||||
|
|
||||||
|
// useOrgViewReady():企业视图是否已按当前企业(含代理会话)加载过(成败均算)。
|
||||||
|
// 企业中心在它就绪前不做路由守卫,避免新体系下持有菜单的人在视图到达前被旧判断重定向走。
|
||||||
|
// 当前企业刚由解析器写入、Provider 尚未感知时主动触发一次加载。
|
||||||
|
export function useOrgViewReady() {
|
||||||
|
const ctx = useContext(AuthzContext);
|
||||||
|
const key = currentOrgViewKey();
|
||||||
|
const ready = ctx.orgLoadedKey === key;
|
||||||
|
const { reload } = ctx;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ready) reload();
|
||||||
|
}, [ready, key, reload]);
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
@@ -1,41 +1,27 @@
|
|||||||
/*
|
import { formatPercent } from '../../helpers/safeDisplay';
|
||||||
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 { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Card, Table, Progress } from '@douyinfe/semi-ui';
|
import { Card, Table, Progress } from '@/components/ui';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
|
||||||
const ChannelConsumption = ({ data, title, icon, t }) => {
|
const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => {
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
||||||
if (!data || data.length === 0) {
|
if (!data || data.length === 0) {
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className='shadow-sm hover:shadow-md transition-shadow'
|
className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
|
||||||
title={
|
title={
|
||||||
<div className='flex items-center gap-2'>
|
embedded ? undefined : (
|
||||||
<span className='text-brand'>{icon}</span>
|
<div className='flex items-center gap-2'>
|
||||||
<span className='font-semibold'>{title}</span>
|
<span className='text-brand'>{icon}</span>
|
||||||
</div>
|
<span className='font-semibold'>{title}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
<div className='h-[300px] flex items-center justify-center text-gray-400'>
|
<div className='h-[300px] flex items-center justify-center text-gray-400'>
|
||||||
{t('暂无数据')}
|
{t('暂无数据')}
|
||||||
@@ -115,26 +101,33 @@ const ChannelConsumption = ({ data, title, icon, t }) => {
|
|||||||
width: 80,
|
width: 80,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
render: (val) => (
|
render: (val) => (
|
||||||
<span className='text-gray-500'>{(val || 0).toFixed(1)}%</span>
|
<span className='text-gray-500'>{formatPercent(val || 0, 1)}</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className='shadow-sm hover:shadow-md transition-shadow'
|
className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
|
||||||
title={
|
title={
|
||||||
<div className='flex items-center gap-2'>
|
embedded ? undefined : (
|
||||||
<span className='text-brand'>{icon}</span>
|
<div className='flex items-center gap-2'>
|
||||||
<span className='font-semibold'>{title}</span>
|
<span className='text-brand'>{icon}</span>
|
||||||
<span className='text-xs text-gray-400 ml-2'>TOP {data.length}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
</div>
|
<span className='text-xs text-gray-400 ml-2'>
|
||||||
|
{I18N_TECHNICAL_TEXT.TOP} {data.length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '0' }}
|
styles={{ body: { padding: '0' } }}
|
||||||
>
|
>
|
||||||
<Table
|
<Table
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data}
|
dataSource={data.map((record, index) => ({
|
||||||
|
...record,
|
||||||
|
key: `${record.channel_name}-${index}`,
|
||||||
|
}))}
|
||||||
pagination={{
|
pagination={{
|
||||||
currentPage,
|
currentPage,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -148,7 +141,7 @@ const ChannelConsumption = ({ data, title, icon, t }) => {
|
|||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
size='small'
|
size='small'
|
||||||
rowKey={(record, index) => `${record.channel_name}-${index}`}
|
rowKey='key'
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { ChevronDown as ActionChevronDown } from '@/components/common/icons/ActionIcons';
|
||||||
|
import React from 'react';
|
||||||
|
import './collapsible-panel.css';
|
||||||
|
|
||||||
|
const CollapsibleHeader = ({ icon, title, isOpen, onToggle, extra }) => (
|
||||||
|
<button
|
||||||
|
type='button'
|
||||||
|
aria-expanded={isOpen}
|
||||||
|
className='app-action-button w-full text-left flex items-center justify-between gap-2 cursor-pointer select-none px-5 py-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm hover:shadow-md transition-all border border-gray-100 dark:border-gray-700'
|
||||||
|
onClick={onToggle}
|
||||||
|
>
|
||||||
|
<span className='flex items-center gap-2 min-w-0 flex-wrap'>
|
||||||
|
<span className='text-brand flex-shrink-0'>{icon}</span>
|
||||||
|
<span className='font-semibold text-gray-800 dark:text-gray-100'>
|
||||||
|
{title}
|
||||||
|
</span>
|
||||||
|
{extra}
|
||||||
|
</span>
|
||||||
|
<ActionChevronDown
|
||||||
|
aria-hidden='true'
|
||||||
|
className={`w-5 h-5 flex-shrink-0 text-gray-400 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default CollapsibleHeader;
|
||||||
@@ -1,28 +1,10 @@
|
|||||||
/*
|
|
||||||
Copyright (C) 2025 QuantumNous
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as
|
|
||||||
published by the Free Software Foundation, either version 3 of the
|
|
||||||
License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
For commercial licensing, please contact support@quantumnous.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Card, Table, Button } from '@douyinfe/semi-ui';
|
import { Card, Table, Button } from '@/components/ui';
|
||||||
import { IconDownload } from '@douyinfe/semi-icons';
|
import { IconDownload } from '@/components/ui/icons';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay';
|
||||||
|
|
||||||
const DailyStatsTable = ({ data, title, icon, t }) => {
|
const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
|
||||||
const columns = [
|
const columns = [
|
||||||
{
|
{
|
||||||
title: t('日期'),
|
title: t('日期'),
|
||||||
@@ -68,7 +50,7 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
|
|||||||
align: 'right',
|
align: 'right',
|
||||||
render: (val) => (
|
render: (val) => (
|
||||||
<span className='text-yellow-600 font-medium'>
|
<span className='text-yellow-600 font-medium'>
|
||||||
¥{(val || 0).toFixed(2)}
|
¥{formatNumber(val, 2, '0.00')}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -99,7 +81,7 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
|
|||||||
width: 120,
|
width: 120,
|
||||||
align: 'right',
|
align: 'right',
|
||||||
render: (val) => {
|
render: (val) => {
|
||||||
const tokens = val || 0;
|
const tokens = toFiniteNumber(val) ?? 0;
|
||||||
if (tokens >= 1000000) {
|
if (tokens >= 1000000) {
|
||||||
return <span>{(tokens / 1000000).toFixed(2)}M</span>;
|
return <span>{(tokens / 1000000).toFixed(2)}M</span>;
|
||||||
} else if (tokens >= 1000) {
|
} else if (tokens >= 1000) {
|
||||||
@@ -161,13 +143,29 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className='shadow-sm hover:shadow-md transition-shadow'
|
className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
|
||||||
title={
|
title={
|
||||||
<div className='flex items-center justify-between w-full'>
|
embedded ? undefined : (
|
||||||
<div className='flex items-center gap-2'>
|
<div className='flex items-center justify-between w-full'>
|
||||||
<span className='text-brand'>{icon}</span>
|
<div className='flex items-center gap-2'>
|
||||||
<span className='font-semibold'>{title}</span>
|
<span className='text-brand'>{icon}</span>
|
||||||
|
<span className='font-semibold'>{title}</span>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
icon={<IconDownload />}
|
||||||
|
size='small'
|
||||||
|
onClick={handleExport}
|
||||||
|
disabled={!data || data.length === 0}
|
||||||
|
>
|
||||||
|
{t('导出CSV')}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
styles={{ body: { padding: '0' } }}
|
||||||
|
>
|
||||||
|
{embedded && (
|
||||||
|
<div className='flex justify-end p-4'>
|
||||||
<Button
|
<Button
|
||||||
icon={<IconDownload />}
|
icon={<IconDownload />}
|
||||||
size='small'
|
size='small'
|
||||||
@@ -177,13 +175,12 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
|
|||||||
{t('导出CSV')}
|
{t('导出CSV')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
}
|
)}
|
||||||
bodyStyle={{ padding: '0' }}
|
|
||||||
>
|
|
||||||
<Table
|
<Table
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data || []}
|
dataSource={data || []}
|
||||||
pagination={{
|
pagination={{
|
||||||
|
preservePage: true,
|
||||||
pageSize: 10,
|
pageSize: 10,
|
||||||
showSizeChanger: true,
|
showSizeChanger: true,
|
||||||
showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
|
showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
|
||||||
|
|||||||
@@ -1,21 +1,4 @@
|
|||||||
/*
|
import { formatUserReference } from '../../helpers/safeDisplay';
|
||||||
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, { useMemo, useState } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
@@ -29,12 +12,12 @@ import {
|
|||||||
Modal,
|
Modal,
|
||||||
Input,
|
Input,
|
||||||
Typography,
|
Typography,
|
||||||
} from '@douyinfe/semi-ui';
|
} from '@/components/ui';
|
||||||
import {
|
import {
|
||||||
IconRefresh,
|
IconRefresh,
|
||||||
IconAlertTriangle,
|
IconAlertTriangle,
|
||||||
IconShieldStroked,
|
IconShieldStroked,
|
||||||
} from '@douyinfe/semi-icons';
|
} from '@/components/ui/icons';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -113,7 +96,9 @@ const HighFreqLowCostUsers = ({
|
|||||||
width: 160,
|
width: 160,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
<div className='flex flex-col'>
|
<div className='flex flex-col'>
|
||||||
<Text strong>{v || row.username || `user_${row.user_id}`}</Text>
|
<Text strong>
|
||||||
|
{formatUserReference(v || row.username, row.user_id, t('未知用户'))}
|
||||||
|
</Text>
|
||||||
{row.username && v && row.username !== v && (
|
{row.username && v && row.username !== v && (
|
||||||
<Text type='tertiary' size='small'>
|
<Text type='tertiary' size='small'>
|
||||||
@{row.username}
|
@{row.username}
|
||||||
@@ -251,7 +236,7 @@ const HighFreqLowCostUsers = ({
|
|||||||
</Space>
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
{/* 筛选区 */}
|
{/* 筛选区 */}
|
||||||
<div className='mb-4 grid grid-cols-2 sm:grid-cols-4 gap-3 items-end'>
|
<div className='mb-4 grid grid-cols-2 sm:grid-cols-4 gap-3 items-end'>
|
||||||
|
|||||||
@@ -1,26 +1,8 @@
|
|||||||
/*
|
|
||||||
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, { useMemo } from 'react';
|
import React, { useMemo } from 'react';
|
||||||
import { Card } from '@douyinfe/semi-ui';
|
import { Card } from '@/components/ui';
|
||||||
import { VChart } from '@visactor/react-vchart';
|
import { VChart } from '@visactor/react-vchart';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
import { formatPercent } from '../../helpers/safeDisplay';
|
||||||
|
|
||||||
const ModelDistribution = ({ data, title, icon, t }) => {
|
const ModelDistribution = ({ data, title, icon, t }) => {
|
||||||
const pieSpec = useMemo(() => {
|
const pieSpec = useMemo(() => {
|
||||||
@@ -104,7 +86,7 @@ const ModelDistribution = ({ data, title, icon, t }) => {
|
|||||||
<span className='font-semibold'>{title}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
{pieSpec ? (
|
{pieSpec ? (
|
||||||
<div>
|
<div>
|
||||||
@@ -119,12 +101,12 @@ const ModelDistribution = ({ data, title, icon, t }) => {
|
|||||||
<span className='text-xs text-gray-500 w-4'>{index + 1}</span>
|
<span className='text-xs text-gray-500 w-4'>{index + 1}</span>
|
||||||
<span
|
<span
|
||||||
className='text-sm flex-1 truncate'
|
className='text-sm flex-1 truncate'
|
||||||
title={item.model_name}
|
title={item.model_name || t('未知')}
|
||||||
>
|
>
|
||||||
{item.model_name}
|
{item.model_name || t('未知')}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-xs text-gray-500'>
|
<span className='text-xs text-gray-500'>
|
||||||
{item.percent?.toFixed(1)}%
|
{formatPercent(item.percent, 1)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,362 @@
|
|||||||
|
import React, { useMemo, useState, useEffect } from 'react';
|
||||||
|
import { Button, Empty, Segmented, Skeleton, theme } from 'antd';
|
||||||
|
import { VChart } from '@visactor/react-vchart';
|
||||||
|
import { Info } from 'lucide-react';
|
||||||
|
import { RefreshCw } from '@/components/common/icons/ActionIcons';
|
||||||
|
import { ConsoleDrawer } from '@/components/console/ConsolePrimitives';
|
||||||
|
import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly';
|
||||||
|
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||||
|
import { formatIdReference, formatPercent } from '../../helpers/safeDisplay';
|
||||||
|
|
||||||
|
// 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。
|
||||||
|
// 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。
|
||||||
|
const abbr = (n) => {
|
||||||
|
const v = Number(n) || 0;
|
||||||
|
const abs = Math.abs(v);
|
||||||
|
if (abs >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
|
||||||
|
if (abs >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
|
||||||
|
if (abs >= 1e3) return `${(v / 1e3).toFixed(2)}K`;
|
||||||
|
return `${v}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const money = (n) => {
|
||||||
|
const v = Number(n) || 0;
|
||||||
|
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(2)}K`;
|
||||||
|
return `$${v.toFixed(2)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// unix 秒 → 本地「MM-DD HH:00」。后端返回的是小时桶起点,整点整分,不做四舍五入。
|
||||||
|
const hourLabel = (unixSec) => {
|
||||||
|
const d = new Date((Number(unixSec) || 0) * 1000);
|
||||||
|
const p = (x) => String(x).padStart(2, '0');
|
||||||
|
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:00`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SERIES_COLORS = {
|
||||||
|
input: '#3b82f6',
|
||||||
|
output: '#10b981',
|
||||||
|
cacheCreation: '#f59e0b',
|
||||||
|
cacheRead: '#8b5cf6',
|
||||||
|
hitRate: '#ef4444',
|
||||||
|
};
|
||||||
|
|
||||||
|
const StatBlock = ({ label, value, sub, color }) => (
|
||||||
|
<div className='flex-1 min-w-[110px]'>
|
||||||
|
<div className='text-xs text-[var(--text-secondary)] mb-1'>{label}</div>
|
||||||
|
<div
|
||||||
|
className='text-lg font-semibold'
|
||||||
|
style={color ? { color } : undefined}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</div>
|
||||||
|
{sub ? (
|
||||||
|
<div className='text-xs text-[var(--text-secondary)] mt-0.5'>{sub}</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单企业逐小时缓存命中率报表抽屉。
|
||||||
|
*
|
||||||
|
* 数据源是企业小时聚合表,不是 logs —— 口径与成本理由见
|
||||||
|
* model/analytics_org_cache.go 顶部注释。
|
||||||
|
*/
|
||||||
|
const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { token } = theme.useToken();
|
||||||
|
const [hours, setHours] = useState(24);
|
||||||
|
// 关闭后重开默认回到 24h:上次选了 7d 不该粘到下一家企业上。
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible) setHours(24);
|
||||||
|
}, [visible]);
|
||||||
|
|
||||||
|
const orgId = visible ? org?.org_id : null;
|
||||||
|
const { data, loading, error, refresh } = useOrgCacheHourly(orgId, hours);
|
||||||
|
|
||||||
|
const points = useMemo(() => data?.points || [], [data]);
|
||||||
|
const totals = data?.totals || null;
|
||||||
|
// 全窗口零流量:补出来的点都是 0,画出来是一条贴底的直线,不如直接给空态。
|
||||||
|
const hasTraffic = points.some((p) => (p.requests || 0) > 0);
|
||||||
|
|
||||||
|
const spec = useMemo(() => {
|
||||||
|
if (!points.length || !hasTraffic) return null;
|
||||||
|
|
||||||
|
const inputKey = t('输入');
|
||||||
|
const outputKey = t('输出');
|
||||||
|
const creationKey = t('写缓存');
|
||||||
|
const readKey = t('读缓存');
|
||||||
|
|
||||||
|
const stacked = [];
|
||||||
|
const rateRows = [];
|
||||||
|
points.forEach((p) => {
|
||||||
|
const label = hourLabel(p.hour);
|
||||||
|
stacked.push(
|
||||||
|
{ hour: label, kind: inputKey, value: p.input || 0 },
|
||||||
|
{ hour: label, kind: outputKey, value: p.output || 0 },
|
||||||
|
{ hour: label, kind: creationKey, value: p.cache_creation || 0 },
|
||||||
|
{ hour: label, kind: readKey, value: p.cache_read || 0 },
|
||||||
|
);
|
||||||
|
rateRows.push({
|
||||||
|
hour: label,
|
||||||
|
// 该小时无流量时后端给 null;这里原样传下去并让序列 invalidType='break',
|
||||||
|
// 折线在空洞处断开,而不是掉到 0% 被误读成命中率暴跌。
|
||||||
|
hit_rate:
|
||||||
|
p.hit_rate === null || p.hit_rate === undefined ? null : p.hit_rate,
|
||||||
|
actual_cost: p.actual_cost || 0,
|
||||||
|
requests: p.requests || 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const rateKey = t('缓存命中率');
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'common',
|
||||||
|
data: [
|
||||||
|
{ id: 'tokens', values: stacked },
|
||||||
|
{ id: 'rate', values: rateRows },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'bar',
|
||||||
|
id: 'tokens',
|
||||||
|
dataIndex: 0,
|
||||||
|
xField: 'hour',
|
||||||
|
yField: 'value',
|
||||||
|
seriesField: 'kind',
|
||||||
|
stack: true,
|
||||||
|
bar: { style: { cornerRadius: [0, 0, 0, 0] } },
|
||||||
|
tooltip: {
|
||||||
|
visible: true,
|
||||||
|
mark: {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
key: (datum) => datum?.kind,
|
||||||
|
value: (datum) => `${abbr(datum?.value)} tokens`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'line',
|
||||||
|
id: 'rate',
|
||||||
|
name: rateKey,
|
||||||
|
dataIndex: 1,
|
||||||
|
xField: 'hour',
|
||||||
|
yField: 'hit_rate',
|
||||||
|
// 空洞断线,不要 connectNulls 把两段无关的曲线连起来
|
||||||
|
invalidType: 'break',
|
||||||
|
point: {
|
||||||
|
visible: true,
|
||||||
|
size: 3,
|
||||||
|
style: { fill: SERIES_COLORS.hitRate },
|
||||||
|
},
|
||||||
|
line: { style: { stroke: SERIES_COLORS.hitRate, lineWidth: 2 } },
|
||||||
|
tooltip: {
|
||||||
|
visible: true,
|
||||||
|
mark: {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
key: () => rateKey,
|
||||||
|
value: (datum) =>
|
||||||
|
datum?.hit_rate === null || datum?.hit_rate === undefined
|
||||||
|
? t('无流量')
|
||||||
|
: formatPercent(datum.hit_rate, 1),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: () => t('实际消费'),
|
||||||
|
value: (datum) => money(datum?.actual_cost),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: () => t('请求数'),
|
||||||
|
value: (datum) => (datum?.requests || 0).toLocaleString(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
color: [
|
||||||
|
SERIES_COLORS.input,
|
||||||
|
SERIES_COLORS.output,
|
||||||
|
SERIES_COLORS.cacheCreation,
|
||||||
|
SERIES_COLORS.cacheRead,
|
||||||
|
],
|
||||||
|
legends: {
|
||||||
|
visible: true,
|
||||||
|
orient: 'top',
|
||||||
|
position: 'middle',
|
||||||
|
padding: { top: 0, bottom: 12, left: 0, right: 0 },
|
||||||
|
layoutType: 'normal',
|
||||||
|
},
|
||||||
|
tooltip: { visible: true, dimension: { visible: true } },
|
||||||
|
crosshair: { xField: { visible: true, line: { visible: true } } },
|
||||||
|
axes: [
|
||||||
|
{
|
||||||
|
orient: 'bottom',
|
||||||
|
// 7d = 168 个桶,标签必须自动抽稀,否则重叠成黑条
|
||||||
|
label: { style: { angle: -45 }, autoLimit: true, autoHide: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
orient: 'left',
|
||||||
|
title: { visible: true, text: t('Token 数') },
|
||||||
|
label: { formatMethod: (v) => abbr(v) },
|
||||||
|
seriesIndex: [0],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
orient: 'right',
|
||||||
|
title: { visible: true, text: t('命中率 (%)') },
|
||||||
|
// 固定 0~100:让曲线的高低在不同企业、不同窗口之间可比。
|
||||||
|
// 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。
|
||||||
|
min: 0,
|
||||||
|
max: 100,
|
||||||
|
label: { formatMethod: (v) => formatPercent(v, 0) },
|
||||||
|
seriesIndex: [1],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}, [points, hasTraffic, t]);
|
||||||
|
|
||||||
|
const orgReference = formatIdReference(org?.org_id);
|
||||||
|
const orgTitle = org?.org_name || (org ? `${t('企业')} ${orgReference}` : '');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConsoleDrawer
|
||||||
|
open={visible}
|
||||||
|
onClose={onClose}
|
||||||
|
size={isMobile ? '100%' : 820}
|
||||||
|
title={
|
||||||
|
<div className='flex items-center gap-2 flex-wrap'>
|
||||||
|
<span className='font-semibold'>{t('缓存命中率明细')}</span>
|
||||||
|
<span className='text-sm font-normal text-[var(--text-secondary)]'>
|
||||||
|
{orgTitle}
|
||||||
|
</span>
|
||||||
|
{org?.org_id ? (
|
||||||
|
<span className='text-xs font-normal text-[var(--text-secondary)]'>
|
||||||
|
{orgReference}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className='flex items-center justify-between gap-3 flex-wrap mb-4'>
|
||||||
|
<Segmented
|
||||||
|
value={hours}
|
||||||
|
onChange={setHours}
|
||||||
|
options={[
|
||||||
|
{ label: t('近 24 小时'), value: 24 },
|
||||||
|
{ label: t('近 7 天'), value: 24 * 7 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
icon={<RefreshCw size={16} />}
|
||||||
|
onClick={refresh}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
{t('刷新')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{totals ? (
|
||||||
|
<div
|
||||||
|
className='flex flex-wrap gap-4 px-4 py-3 mb-4 rounded-lg'
|
||||||
|
style={{ background: token.colorFillAlter }}
|
||||||
|
>
|
||||||
|
<StatBlock
|
||||||
|
label={t('缓存命中率')}
|
||||||
|
value={
|
||||||
|
totals.hit_rate === null || totals.hit_rate === undefined
|
||||||
|
? '--'
|
||||||
|
: formatPercent(totals.hit_rate, 2)
|
||||||
|
}
|
||||||
|
sub={t('按 token 加权')}
|
||||||
|
color={SERIES_COLORS.hitRate}
|
||||||
|
/>
|
||||||
|
<StatBlock label={t('输入')} value={abbr(totals.input)} />
|
||||||
|
<StatBlock label={t('输出')} value={abbr(totals.output)} />
|
||||||
|
<StatBlock
|
||||||
|
label={t('写缓存')}
|
||||||
|
value={abbr(totals.cache_creation)}
|
||||||
|
color={SERIES_COLORS.cacheCreation}
|
||||||
|
/>
|
||||||
|
<StatBlock
|
||||||
|
label={t('读缓存')}
|
||||||
|
value={abbr(totals.cache_read)}
|
||||||
|
color={SERIES_COLORS.cacheRead}
|
||||||
|
/>
|
||||||
|
<StatBlock
|
||||||
|
label={t('实际消费')}
|
||||||
|
value={money(totals.actual_cost)}
|
||||||
|
sub={t('{{n}} 次请求', {
|
||||||
|
n: (totals.requests || 0).toLocaleString(),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{loading && !points.length ? (
|
||||||
|
<Skeleton active title={false} paragraph={{ rows: 8 }} />
|
||||||
|
) : error ? (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
className='py-12'
|
||||||
|
description={
|
||||||
|
<>
|
||||||
|
<div className='text-[var(--text-primary)]'>{t('加载失败')}</div>
|
||||||
|
<div>{error}</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : spec ? (
|
||||||
|
<VChart
|
||||||
|
spec={spec}
|
||||||
|
option={{ mode: 'desktop-browser' }}
|
||||||
|
style={{ height: 360 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
className='py-12'
|
||||||
|
description={
|
||||||
|
<>
|
||||||
|
<div className='text-[var(--text-primary)]'>
|
||||||
|
{t('该时间段内没有流量')}
|
||||||
|
</div>
|
||||||
|
<div>{t('所选窗口内这家企业没有产生可统计的请求')}</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 口径脚注:不写清楚的话,运营会拿这张图去对账单,然后发现对不上。 */}
|
||||||
|
<div
|
||||||
|
className='mt-4 px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed rounded-md'
|
||||||
|
style={{ background: token.colorFillAlter }}
|
||||||
|
>
|
||||||
|
<div className='flex items-start gap-1.5'>
|
||||||
|
<Info aria-hidden className='w-3.5 h-3.5 mt-0.5 flex-shrink-0' />
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。输出 token 与缓存无关,不计入分母。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'数据来自企业小时聚合表,按自然小时切桶;最后一个小时尚未走完,数字仍在累加。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'「实际消费」为本平台实际计费金额;标准价对比待官方价目表配置完成后再上。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ConsoleDrawer>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { abbr as formatTokenAbbr, money as formatUsd, hourLabel };
|
||||||
|
export default OrgCacheHourlySheet;
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
import { formatIdReference, formatPercent } from '../../helpers/safeDisplay';
|
||||||
|
import React, { useState, useCallback } from 'react';
|
||||||
|
import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd';
|
||||||
|
import { ArrowDown } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
ConsoleCard,
|
||||||
|
ConsoleTable,
|
||||||
|
} from '@/components/console/ConsolePrimitives';
|
||||||
|
import OrgCacheHourlySheet from './OrgCacheHourlySheet';
|
||||||
|
|
||||||
|
// 并发占用比对应的色阶:接近上限提前变黄,打满变红。
|
||||||
|
const WARN_RATIO = 0.8;
|
||||||
|
|
||||||
|
// 缓存命中率色阶。90% 是与客户约定的 KPI 线(严格口径),所以绿/黄的分界放在这里;
|
||||||
|
// 70% 以下基本意味着会话结构出了问题(深轮首触、子代理扇出),标红提示排查。
|
||||||
|
const CACHE_GOOD = 90;
|
||||||
|
const CACHE_WARN = 70;
|
||||||
|
|
||||||
|
// 色阶取主题语义 token(成功 / 警告 / 错误 / 主色),阈值不变
|
||||||
|
const cacheRateColor = (rate, token) => {
|
||||||
|
if (rate >= CACHE_GOOD) return token.colorSuccess;
|
||||||
|
if (rate >= CACHE_WARN) return token.colorWarning;
|
||||||
|
return token.colorError;
|
||||||
|
};
|
||||||
|
|
||||||
|
const concurrencyColor = (ratio, token) => {
|
||||||
|
if (ratio >= 1) return token.colorError;
|
||||||
|
if (ratio >= WARN_RATIO) return token.colorWarning;
|
||||||
|
return token.colorPrimary;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可点击的表头:点一下换排序维度,始终降序(后端只支持降序 TOP-N)。
|
||||||
|
const SortableTitle = ({ label, field, sortBy, onSort }) => {
|
||||||
|
const active = sortBy === field;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role='button'
|
||||||
|
tabIndex={0}
|
||||||
|
aria-pressed={active}
|
||||||
|
className={`inline-flex items-center gap-1 cursor-pointer select-none transition-colors ${
|
||||||
|
active
|
||||||
|
? 'text-brand font-semibold'
|
||||||
|
: 'text-[var(--text-secondary)] hover:text-brand'
|
||||||
|
}`}
|
||||||
|
onClick={() => onSort(field)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
onSort(field);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
<ArrowDown
|
||||||
|
aria-hidden
|
||||||
|
className={`w-3 h-3 ${active ? 'opacity-100' : 'opacity-25'}`}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const OrgRealtimeUsage = ({
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
sortBy,
|
||||||
|
onSortChange,
|
||||||
|
limit = 10,
|
||||||
|
title,
|
||||||
|
icon,
|
||||||
|
t,
|
||||||
|
}) => {
|
||||||
|
const { token } = theme.useToken();
|
||||||
|
const items = data?.items || [];
|
||||||
|
const windowSeconds = data?.window_seconds || 60;
|
||||||
|
|
||||||
|
// 抽屉状态放在这里而不是提到页面级:它完全由本表的行点击驱动,
|
||||||
|
// 页面不需要知道它的存在。
|
||||||
|
const [detailOrg, setDetailOrg] = useState(null);
|
||||||
|
const closeDetail = useCallback(() => setDetailOrg(null), []);
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: t('企业'),
|
||||||
|
dataIndex: 'org_name',
|
||||||
|
key: 'org_name',
|
||||||
|
width: 220,
|
||||||
|
fixed: 'left',
|
||||||
|
render: (text, record) => {
|
||||||
|
const orgReference = formatIdReference(record.org_id);
|
||||||
|
return (
|
||||||
|
<div className='flex items-center gap-2 min-w-0'>
|
||||||
|
<span className='text-sm font-medium truncate' title={text || ''}>
|
||||||
|
{text || `${t('企业')} ${orgReference}`}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
|
||||||
|
{orgReference}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label={t('并发占用')}
|
||||||
|
field='concurrency'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'concurrency',
|
||||||
|
key: 'concurrency',
|
||||||
|
width: 220,
|
||||||
|
render: (val, record) => {
|
||||||
|
const current = val || 0;
|
||||||
|
const limit = record.max_concurrency || 0;
|
||||||
|
// 0 表示未配置上限:不画进度条(没有分母,画出来就是误导)。
|
||||||
|
if (limit <= 0) {
|
||||||
|
return (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||||
|
{current.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)]'>
|
||||||
|
/ {t('不限制')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const ratio = current / limit;
|
||||||
|
const color = concurrencyColor(ratio, token);
|
||||||
|
return (
|
||||||
|
<div className='min-w-0'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-sm font-semibold' style={{ color }}>
|
||||||
|
{current.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)]'>
|
||||||
|
/ {limit.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
{record.rejected > 0 && (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'近 {{seconds}} 秒内有 {{times}} 次请求因超过并发上限被限流(429)',
|
||||||
|
{
|
||||||
|
seconds: windowSeconds,
|
||||||
|
times: record.rejected,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Tag color='error' variant='filled'>
|
||||||
|
{t('限流中')}
|
||||||
|
</Tag>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Progress
|
||||||
|
percent={Math.min(ratio * 100, 100)}
|
||||||
|
showInfo={false}
|
||||||
|
size='small'
|
||||||
|
className='mt-1'
|
||||||
|
strokeColor={color}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label='RPM'
|
||||||
|
field='rpm'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'rpm',
|
||||||
|
key: 'rpm',
|
||||||
|
width: 140,
|
||||||
|
align: 'right',
|
||||||
|
render: (val) => (
|
||||||
|
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||||
|
{(val || 0).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label='TPM'
|
||||||
|
field='tpm'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'tpm',
|
||||||
|
key: 'tpm',
|
||||||
|
width: 180,
|
||||||
|
align: 'right',
|
||||||
|
render: (val) => (
|
||||||
|
<span className='text-sm font-semibold text-brand-deep'>
|
||||||
|
{(val || 0).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 这一列不可排序:后端的 TOP-N 是按内存计数器(并发/RPM/TPM)排的,
|
||||||
|
// 命中率是取完 TOP-N 之后再补的落库数据,没有「按命中率取前 N 名」这回事。
|
||||||
|
title: (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'近 1 小时的缓存命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。与左侧 RPM/TPM 的 60 秒窗口不同:命中率在分钟级噪声很大,按 60 秒算每次刷新都会跳。点击数字查看逐小时明细。',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className='inline-flex items-center gap-1 text-[var(--text-secondary)] border-b border-dashed border-[var(--border-subtle)]'>
|
||||||
|
{t('1h 缓存命中率')}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
dataIndex: 'cache_hit_rate',
|
||||||
|
key: 'cache_hit_rate',
|
||||||
|
width: 170,
|
||||||
|
align: 'right',
|
||||||
|
render: (val, record) => {
|
||||||
|
// 分母为 0 = 这一小时没有可统计的 token,不是「命中率 0%」。
|
||||||
|
// 两者混为一谈会让刚接入的企业看起来像缓存全丢。
|
||||||
|
if (!record.cache_tokens) {
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
title={
|
||||||
|
data?.cache_degraded
|
||||||
|
? t('缓存数据暂时不可用(小时聚合表查询失败)')
|
||||||
|
: t('近 1 小时没有可统计的 token')
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className='text-sm'
|
||||||
|
style={{ color: token.colorTextQuaternary }}
|
||||||
|
>
|
||||||
|
--
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const rate = val || 0;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role='button'
|
||||||
|
tabIndex={0}
|
||||||
|
className='inline-flex items-center justify-end gap-1 cursor-pointer select-none group'
|
||||||
|
onClick={() => setDetailOrg(record)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
setDetailOrg(record);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className='text-sm font-semibold group-hover:underline'
|
||||||
|
style={{ color: cacheRateColor(rate, token) }}
|
||||||
|
>
|
||||||
|
{formatPercent(rate, 1)}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className='text-xs text-[var(--text-secondary)] group-hover:text-brand'
|
||||||
|
>
|
||||||
|
›
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConsoleCard
|
||||||
|
title={
|
||||||
|
<div className='flex items-center justify-between w-full flex-wrap gap-2'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-brand'>{icon}</span>
|
||||||
|
<span className='font-semibold'>{title}</span>
|
||||||
|
<span className='text-xs font-normal text-[var(--text-secondary)] ml-2'>
|
||||||
|
{t('取前 {{limit}} 名', { limit })}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-3'>
|
||||||
|
{data && data.enforced === false && (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'当前只计量不拦截(ORG_CONCURRENCY_LIMIT_ENABLED=false):即使占满上限也不会返回 429',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Tag color='default' variant='filled'>
|
||||||
|
{t('仅观测')}
|
||||||
|
</Tag>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
{data?.degraded ? (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'未启用 Redis 或心跳异常,当前仅统计本实例的数据,多节点部署时会偏小',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
status='warning'
|
||||||
|
text={
|
||||||
|
<span className='text-xs font-normal'>
|
||||||
|
{t('单实例口径')}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
) : (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'统计 {{instances}} 个实例,窗口为近 {{seconds}} 秒滚动',
|
||||||
|
{
|
||||||
|
instances: data?.instances || 1,
|
||||||
|
seconds: windowSeconds,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
status='processing'
|
||||||
|
color={token.colorSuccess}
|
||||||
|
text={
|
||||||
|
<span className='text-xs font-normal'>
|
||||||
|
{t('实时 · 近 {{seconds}} 秒滚动', {
|
||||||
|
seconds: windowSeconds,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
styles={{ body: { padding: 0 } }}
|
||||||
|
>
|
||||||
|
{loading && items.length === 0 ? (
|
||||||
|
<div className='px-4 py-6'>
|
||||||
|
<Skeleton active title={false} paragraph={{ rows: 5 }} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ConsoleTable
|
||||||
|
columns={columns}
|
||||||
|
dataSource={items}
|
||||||
|
pagination={false}
|
||||||
|
scroll={{ x: 930 }}
|
||||||
|
size='small'
|
||||||
|
rowKey='org_id'
|
||||||
|
locale={{
|
||||||
|
emptyText: (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={t('近 {{seconds}} 秒内没有企业产生请求', {
|
||||||
|
seconds: windowSeconds,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{/* 口径脚注:并发/RPM 只盖同步转发,TPM 还滞后一个请求时长。
|
||||||
|
不写出来的话,运营会拿这张表去对账单,然后发现对不上。 */}
|
||||||
|
<div className='px-4 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed border-t border-[var(--border-subtle)]'>
|
||||||
|
{t(
|
||||||
|
'口径:仅统计 /v1、/v1beta 同步转发接口;Midjourney、Suno、视频与异步图片任务提交后在后台执行,不计入本表。',
|
||||||
|
)}{' '}
|
||||||
|
{t(
|
||||||
|
'RPM 含被限流拒绝的请求;TPM 在请求结束时才计入,长流式请求会在结束的那一秒形成毛刺。',
|
||||||
|
)}{' '}
|
||||||
|
{t(
|
||||||
|
'缓存命中率的窗口是近 1 小时(读企业小时聚合表),与左侧 60 秒窗口的指标不同步。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<OrgCacheHourlySheet
|
||||||
|
visible={!!detailOrg}
|
||||||
|
org={detailOrg}
|
||||||
|
onClose={closeDetail}
|
||||||
|
t={t}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ConsoleCard>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default OrgRealtimeUsage;
|
||||||
@@ -1,24 +1,7 @@
|
|||||||
/*
|
import { formatNumber, formatPercent } from '../../helpers/safeDisplay';
|
||||||
Copyright (C) 2025 QuantumNous
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as
|
|
||||||
published by the Free Software Foundation, either version 3 of the
|
|
||||||
License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
For commercial licensing, please contact support@quantumnous.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Card } from '@douyinfe/semi-ui';
|
import { Card } from '@/components/ui';
|
||||||
import {
|
import {
|
||||||
Users,
|
Users,
|
||||||
UserPlus,
|
UserPlus,
|
||||||
@@ -34,7 +17,7 @@ import { renderQuota, timestamp2string } from '../../helpers';
|
|||||||
const OverviewCards = ({ overview, loading = false, t }) => {
|
const OverviewCards = ({ overview, loading = false, t }) => {
|
||||||
if (!overview) {
|
if (!overview) {
|
||||||
return (
|
return (
|
||||||
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6'>
|
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
|
||||||
{[...Array(6)].map((_, i) => (
|
{[...Array(6)].map((_, i) => (
|
||||||
<Card key={i} className='animate-pulse'>
|
<Card key={i} className='animate-pulse'>
|
||||||
<div className='h-20 bg-gray-200 dark:bg-gray-700 rounded'></div>
|
<div className='h-20 bg-gray-200 dark:bg-gray-700 rounded'></div>
|
||||||
@@ -65,7 +48,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: t('今日充值'),
|
title: t('今日充值'),
|
||||||
value: `¥${overview.today_topup?.toFixed(2) || '0.00'}`,
|
value: `¥${formatNumber(overview.today_topup, 2, '0.00')}`,
|
||||||
change: overview.today_topup_change,
|
change: overview.today_topup_change,
|
||||||
icon: <DollarSign className='w-5 h-5' />,
|
icon: <DollarSign className='w-5 h-5' />,
|
||||||
color: 'yellow',
|
color: 'yellow',
|
||||||
@@ -92,7 +75,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: t('付费率'),
|
title: t('付费率'),
|
||||||
value: `${overview.pay_rate?.toFixed(1) || '0.0'}%`,
|
value: formatPercent(overview.pay_rate, 1, '0.0%'),
|
||||||
change: null,
|
change: null,
|
||||||
icon: <Percent className='w-5 h-5' />,
|
icon: <Percent className='w-5 h-5' />,
|
||||||
color: 'pink',
|
color: 'pink',
|
||||||
@@ -117,14 +100,14 @@ const OverviewCards = ({ overview, loading = false, t }) => {
|
|||||||
)}
|
)}
|
||||||
<span>
|
<span>
|
||||||
{isPositive ? '+' : ''}
|
{isPositive ? '+' : ''}
|
||||||
{change.toFixed(1)}%
|
{formatPercent(change, 1)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='mb-6'>
|
<div>
|
||||||
<div
|
<div
|
||||||
className={`grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 transition-opacity ${
|
className={`grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 transition-opacity ${
|
||||||
loading ? 'opacity-50' : ''
|
loading ? 'opacity-50' : ''
|
||||||
@@ -134,7 +117,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
|
|||||||
<Card
|
<Card
|
||||||
key={index}
|
key={index}
|
||||||
className={`${card.bgColor} border-none shadow-sm hover:shadow-md transition-shadow`}
|
className={`${card.bgColor} border-none shadow-sm hover:shadow-md transition-shadow`}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
<div className='flex items-start justify-between'>
|
<div className='flex items-start justify-between'>
|
||||||
<div className='flex-1'>
|
<div className='flex-1'>
|
||||||
|
|||||||
@@ -1,22 +1,6 @@
|
|||||||
/*
|
import { formatUserReference } from '../../helpers/safeDisplay';
|
||||||
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 { Trans } from 'react-i18next';
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
@@ -27,8 +11,8 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
Space,
|
Space,
|
||||||
Select,
|
Select,
|
||||||
} from '@douyinfe/semi-ui';
|
} from '@/components/ui';
|
||||||
import { IconRefresh } from '@douyinfe/semi-icons';
|
import { IconRefresh } from '@/components/ui/icons';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -54,6 +38,7 @@ const RiskControlBanLogs = ({
|
|||||||
banLogStatus,
|
banLogStatus,
|
||||||
setBanLogStatus,
|
setBanLogStatus,
|
||||||
banLogPage,
|
banLogPage,
|
||||||
|
banLogPageSize,
|
||||||
fetchBanLogs,
|
fetchBanLogs,
|
||||||
unbanUser,
|
unbanUser,
|
||||||
t,
|
t,
|
||||||
@@ -175,7 +160,11 @@ const RiskControlBanLogs = ({
|
|||||||
<div className='mb-3 flex items-center justify-between flex-wrap gap-2'>
|
<div className='mb-3 flex items-center justify-between flex-wrap gap-2'>
|
||||||
<Space>
|
<Space>
|
||||||
<Text type='tertiary' size='small'>
|
<Text type='tertiary' size='small'>
|
||||||
{t('共')} {banLogTotal || 0} {t('条')}
|
<Trans
|
||||||
|
t={t}
|
||||||
|
i18nKey='共 {{value}} 条'
|
||||||
|
values={{ value: banLogTotal || 0 }}
|
||||||
|
/>
|
||||||
</Text>
|
</Text>
|
||||||
<Select
|
<Select
|
||||||
value={banLogStatus}
|
value={banLogStatus}
|
||||||
@@ -204,12 +193,13 @@ const RiskControlBanLogs = ({
|
|||||||
rowKey='id'
|
rowKey='id'
|
||||||
loading={loading}
|
loading={loading}
|
||||||
pagination={{
|
pagination={{
|
||||||
pageSize: 20,
|
pageSize: banLogPageSize,
|
||||||
showTotal: true,
|
showTotal: true,
|
||||||
total: banLogTotal,
|
total: banLogTotal,
|
||||||
// 受控分页:避免切换状态筛选后 Semi 内部页码与 hook 不同步
|
// 受控分页:避免切换状态筛选后 Semi 内部页码与 hook 不同步
|
||||||
currentPage: banLogPage,
|
currentPage: banLogPage,
|
||||||
onPageChange: (page) => fetchBanLogs({ page }),
|
onPageChange: (page) => fetchBanLogs({ page }),
|
||||||
|
onPageSizeChange: (pageSize) => fetchBanLogs({ page: 1, pageSize }),
|
||||||
}}
|
}}
|
||||||
empty={t('暂无封号记录')}
|
empty={t('暂无封号记录')}
|
||||||
scroll={{ x: 1400 }}
|
scroll={{ x: 1400 }}
|
||||||
@@ -239,7 +229,9 @@ const RiskControlBanLogs = ({
|
|||||||
<div>
|
<div>
|
||||||
<Text type='tertiary'>{t('用户:')}</Text>
|
<Text type='tertiary'>{t('用户:')}</Text>
|
||||||
<Text strong>
|
<Text strong>
|
||||||
{unbanRow.user_snapshot || `user_${unbanRow.user_id}`}(ID:
|
{unbanRow.user_snapshot ||
|
||||||
|
formatUserReference('', unbanRow.user_id, t('未知用户'))}
|
||||||
|
(ID:
|
||||||
{unbanRow.user_id})
|
{unbanRow.user_id})
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,22 +1,4 @@
|
|||||||
/*
|
import { Trans } from 'react-i18next';
|
||||||
Copyright (C) 2025 QuantumNous
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as
|
|
||||||
published by the Free Software Foundation, either version 3 of the
|
|
||||||
License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
For commercial licensing, please contact support@quantumnous.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
import React, { useEffect, useRef, useState } from 'react';
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
@@ -28,7 +10,7 @@ import {
|
|||||||
Banner,
|
Banner,
|
||||||
Button,
|
Button,
|
||||||
Space,
|
Space,
|
||||||
} from '@douyinfe/semi-ui';
|
} from '@/components/ui';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -267,8 +249,11 @@ const RiskControlRulesModal = ({
|
|||||||
<span>
|
<span>
|
||||||
{t('总消耗 ≤')}{' '}
|
{t('总消耗 ≤')}{' '}
|
||||||
<Text type='tertiary' size='small'>
|
<Text type='tertiary' size='small'>
|
||||||
({t('quota')}, ≈ {renderQuota(form.ban_max_total_quota, 4)},{' '}
|
<Trans
|
||||||
{t('防误伤大客户')})
|
t={t}
|
||||||
|
i18nKey='(quota, ≈ {{value}}, 防误伤大客户)'
|
||||||
|
values={{ value: renderQuota(form.ban_max_total_quota, 4) }}
|
||||||
|
/>
|
||||||
</Text>
|
</Text>
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,11 @@
|
|||||||
/*
|
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
|
||||||
Copyright (C) 2025 QuantumNous
|
import {
|
||||||
|
formatNumber,
|
||||||
This program is free software: you can redistribute it and/or modify
|
formatPercent,
|
||||||
it under the terms of the GNU Affero General Public License as
|
toFiniteNumber,
|
||||||
published by the Free Software Foundation, either version 3 of the
|
} from '../../helpers/safeDisplay';
|
||||||
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, { useMemo } from 'react';
|
import React, { useMemo } from 'react';
|
||||||
import { Card } from '@douyinfe/semi-ui';
|
import { Card } from '@/components/ui';
|
||||||
import { VChart } from '@visactor/react-vchart';
|
import { VChart } from '@visactor/react-vchart';
|
||||||
|
|
||||||
// 支付渠道颜色映射:支付宝蓝色、微信绿色
|
// 支付渠道颜色映射:支付宝蓝色、微信绿色
|
||||||
@@ -47,8 +34,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
|
|||||||
const chartData = data.map((item) => ({
|
const chartData = data.map((item) => ({
|
||||||
name: item.payment_method ? t(item.payment_method) : t('未知'),
|
name: item.payment_method ? t(item.payment_method) : t('未知'),
|
||||||
rawName: item.payment_method,
|
rawName: item.payment_method,
|
||||||
value: item.amount || 0,
|
value: toFiniteNumber(item.amount) ?? 0,
|
||||||
count: item.count || 0,
|
count: toFiniteNumber(item.count) ?? 0,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// 根据支付渠道名称生成颜色数组
|
// 根据支付渠道名称生成颜色数组
|
||||||
@@ -77,11 +64,15 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
key: (datum) => datum?.name,
|
key: (datum) => datum?.name,
|
||||||
value: (datum) => `¥${(datum?.value || 0).toFixed(2)}`,
|
value: (datum) => `¥${formatNumber(datum?.value, 2, '0.00')}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: () => t('笔数'),
|
key: () => t('笔数'),
|
||||||
value: (datum) => t('{{n}} 笔', { n: datum?.count || 0, count: datum?.count || 0 }),
|
value: (datum) =>
|
||||||
|
t('{{n}} 笔', {
|
||||||
|
n: datum?.count || 0,
|
||||||
|
count: datum?.count || 0,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -103,7 +94,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
|
|||||||
// 统计列表
|
// 统计列表
|
||||||
const channelList = data || [];
|
const channelList = data || [];
|
||||||
const totalAmount = channelList.reduce(
|
const totalAmount = channelList.reduce(
|
||||||
(sum, item) => sum + (item.amount || 0),
|
(sum, item) => sum + (toFiniteNumber(item.amount) ?? 0),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -116,7 +107,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
|
|||||||
<span className='font-semibold'>{title}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
{pieSpec ? (
|
{pieSpec ? (
|
||||||
<div>
|
<div>
|
||||||
@@ -136,17 +127,18 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
|
|||||||
</span>
|
</span>
|
||||||
<div className='text-right'>
|
<div className='text-right'>
|
||||||
<span className='font-medium'>
|
<span className='font-medium'>
|
||||||
¥{(item.amount || 0).toFixed(2)}
|
¥{formatNumber(item.amount, 2, '0.00')}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-gray-400 text-xs ml-2'>
|
<span className='text-gray-400 text-xs ml-2'>
|
||||||
({item.percent?.toFixed(1)}%)
|
({formatPercent(item.percent, 1).replace('%', '')}
|
||||||
|
{I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div className='flex items-center justify-between text-sm pt-2 font-semibold'>
|
<div className='flex items-center justify-between text-sm pt-2 font-semibold'>
|
||||||
<span>{t('合计')}</span>
|
<span>{t('合计')}</span>
|
||||||
<span>¥{totalAmount.toFixed(2)}</span>
|
<span>¥{formatNumber(totalAmount, 2, '0.00')}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,25 +1,7 @@
|
|||||||
/*
|
|
||||||
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, { useMemo } from 'react';
|
import React, { useMemo } from 'react';
|
||||||
import { Card } from '@douyinfe/semi-ui';
|
import { Card } from '@/components/ui';
|
||||||
import { VChart } from '@visactor/react-vchart';
|
import { VChart } from '@visactor/react-vchart';
|
||||||
|
import { formatCurrency } from '@/helpers/safeDisplay';
|
||||||
|
|
||||||
const TrendCharts = ({ title, icon, data, type, t }) => {
|
const TrendCharts = ({ title, icon, data, type, t }) => {
|
||||||
const spec = useMemo(() => {
|
const spec = useMemo(() => {
|
||||||
@@ -65,7 +47,10 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
|
|||||||
{
|
{
|
||||||
key: (datum) => datum?.type,
|
key: (datum) => datum?.type,
|
||||||
value: (datum) =>
|
value: (datum) =>
|
||||||
t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }),
|
t('{{n}} 人', {
|
||||||
|
n: (datum?.value || 0).toLocaleString(),
|
||||||
|
count: datum?.value || 0,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -75,7 +60,10 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
|
|||||||
{
|
{
|
||||||
key: (datum) => datum?.type,
|
key: (datum) => datum?.type,
|
||||||
value: (datum) =>
|
value: (datum) =>
|
||||||
t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }),
|
t('{{n}} 人', {
|
||||||
|
n: (datum?.value || 0).toLocaleString(),
|
||||||
|
count: datum?.value || 0,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -136,7 +124,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
key: () => topupKey,
|
key: () => topupKey,
|
||||||
value: (datum) => `¥${(datum?.[topupKey] || 0).toFixed(2)}`,
|
value: (datum) => formatCurrency(datum?.[topupKey]),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -168,8 +156,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
key: () => consumeKey,
|
key: () => consumeKey,
|
||||||
value: (datum) =>
|
value: (datum) => formatCurrency(datum?.[consumeKey]),
|
||||||
`¥${(datum?.[consumeKey] || 0).toFixed(2)}`,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -231,7 +218,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
|
|||||||
<span className='font-semibold'>{title}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
{spec ? (
|
{spec ? (
|
||||||
<VChart
|
<VChart
|
||||||
|
|||||||
@@ -1,24 +1,12 @@
|
|||||||
/*
|
import {
|
||||||
Copyright (C) 2025 QuantumNous
|
formatIdReference,
|
||||||
|
formatUserReference,
|
||||||
This program is free software: you can redistribute it and/or modify
|
} from '../../helpers/safeDisplay';
|
||||||
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 { Trans } from 'react-i18next';
|
||||||
|
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Card, Avatar, Progress } from '@douyinfe/semi-ui';
|
import { Card, Avatar, Progress } from '@/components/ui';
|
||||||
import { renderQuota } from '../../helpers';
|
import { renderQuota } from '../../helpers';
|
||||||
|
|
||||||
const UserRanking = ({ data, title, icon, t }) => {
|
const UserRanking = ({ data, title, icon, t }) => {
|
||||||
@@ -32,7 +20,7 @@ const UserRanking = ({ data, title, icon, t }) => {
|
|||||||
<span className='font-semibold'>{title}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
<div className='h-[300px] flex items-center justify-center text-gray-400'>
|
<div className='h-[300px] flex items-center justify-center text-gray-400'>
|
||||||
{t('暂无数据')}
|
{t('暂无数据')}
|
||||||
@@ -71,11 +59,15 @@ const UserRanking = ({ data, title, icon, t }) => {
|
|||||||
<span className='text-brand'>{icon}</span>
|
<span className='text-brand'>{icon}</span>
|
||||||
<span className='font-semibold'>{title}</span>
|
<span className='font-semibold'>{title}</span>
|
||||||
<span className='text-xs text-gray-400 ml-2'>
|
<span className='text-xs text-gray-400 ml-2'>
|
||||||
{t('共')} {data.length} {t('人')}
|
<Trans
|
||||||
|
t={t}
|
||||||
|
i18nKey='共 {{length}} 人'
|
||||||
|
values={{ length: data.length }}
|
||||||
|
/>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
bodyStyle={{ padding: '16px' }}
|
styles={{ body: { padding: '16px' } }}
|
||||||
>
|
>
|
||||||
<div className='space-y-2 max-h-[450px] overflow-y-auto pr-1'>
|
<div className='space-y-2 max-h-[450px] overflow-y-auto pr-1'>
|
||||||
{data.map((item, index) => (
|
{data.map((item, index) => (
|
||||||
@@ -98,11 +90,15 @@ const UserRanking = ({ data, title, icon, t }) => {
|
|||||||
<div className='flex items-center justify-between'>
|
<div className='flex items-center justify-between'>
|
||||||
<span
|
<span
|
||||||
className='text-sm font-medium truncate'
|
className='text-sm font-medium truncate'
|
||||||
title={`${item.display_name || item.username || 'User'} (ID: ${item.user_id})`}
|
title={`${formatUserReference(item.display_name || item.username, item.user_id, t('未知用户'))}`}
|
||||||
>
|
>
|
||||||
{item.display_name || item.username || `User ${item.user_id}`}
|
{formatUserReference(
|
||||||
|
item.display_name || item.username,
|
||||||
|
item.user_id,
|
||||||
|
t('未知用户'),
|
||||||
|
)}
|
||||||
<span className='text-xs text-gray-400 ml-1'>
|
<span className='text-xs text-gray-400 ml-1'>
|
||||||
#{item.user_id}
|
{formatIdReference(item.user_id)}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
<span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'>
|
<span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'>
|
||||||
@@ -120,7 +116,10 @@ const UserRanking = ({ data, title, icon, t }) => {
|
|||||||
<span>
|
<span>
|
||||||
{item.requests?.toLocaleString()} {t('次请求')}
|
{item.requests?.toLocaleString()} {t('次请求')}
|
||||||
</span>
|
</span>
|
||||||
<span>{(item.tokens || 0).toLocaleString()} tokens</span>
|
<span>
|
||||||
|
{(item.tokens || 0).toLocaleString()}{' '}
|
||||||
|
{I18N_TECHNICAL_TEXT.TOKENS}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex justify-between text-xs mt-1'>
|
<div className='flex justify-between text-xs mt-1'>
|
||||||
<span className='text-gray-500'>{t('余额')}:</span>
|
<span className='text-gray-500'>{t('余额')}:</span>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user