5 Commits
Author SHA1 Message Date
dongskandClaude Sonnet 4.6 noreply@anthropic.com> 8699798ea5 feat: 模组全维度独立,消除全局 DOM/Portal/存储污染
- jieya-ibp/welltrust-qap ThemeContext 改为作用域容器承载 CSS 变量与背景色,不再写 document
- 删除 order-cost CostCockpit 对 documentElement 的死变量写入
- bomx Drawer createPortal 挂载点内移到 .bomx-app,移除 document.body 兜底
- knowledge-graph 拖拽 cursor 改为根容器 ref
- 新增 check-module-independence 门禁并接入 build
- SOP 与融合技能文档补充「模组完全独立互不影响」章节

Co-Authored-By: Claude Sonnet 4.6 noreply@anthropic.com>
2026-10-19 09:10:30 +08:00
dongsk 9c45aedbe8 update css 2026-10-18 23:02:15 +08:00
dongsk 90ee2b30f5 搜索 2026-10-18 21:50:40 +08:00
dongsk 4e2459f2c8 新增融合skill 2026-10-18 21:41:09 +08:00
dongsk 2a34c94268 新增融合经验 2026-10-18 21:38:01 +08:00
28 changed files with 1745 additions and 132 deletions
@@ -0,0 +1,40 @@
---
name: react-module-integration
description: 将独立 React(Vite) 前端项目融合进 ai-platform 平台成为首页可进入的模块,覆盖前期勘察、静态资源迁移、CSS 样式隔离、平台注册与验证部署全流程。当用户要求把 React 项目接入或融合进 ai-platform、新增平台模块、排查模块融合后白屏或部署异常时使用。不用于从零新建独立项目或纯后端接入。
---
# ai-platform React 模块融合
完整操作手册在 `references/react-module-integration-sop.md`(含命令、代码模板、案例),执行任何一步前先阅读对应章节。以下为必须遵守的红线与执行顺序。
## 执行顺序
1. **前期勘察**(SOP §1):对源项目逐项检查——新增依赖、路由方式、入口 Provider、全局 CSS、`document.body` 操作、public 资源清单、存储 key 前缀、`@keyframes` 命名、React 版本差异。
2. **目录规划与复制**(SOP §2):源码进 `src/modules/<name>/`,禁止复制 `main.tsx`、`__tests__`。
3. **静态资源迁移**(SOP §3):资源统一放 `public/mod-assets/<name>/`,代码引用全部改为绝对路径 `/mod-assets/<name>/xxx`(含 `locateFile`)。
4. **样式隔离**(SOP §4):模块根容器类(如 `.xxx-root`)作为所有选择器前缀;`body`/`:root`/`html`/`#root` 规则必须改写或删除;class、ID、裸元素三类冲突源都要检测。
5. **代码适配**(SOP §6):源 `main.tsx` 的 Provider 包裹与 CSS import 全部迁入模块 `App.tsx`;`tsc -b` 报错按清单修(TS6133、TS2554)。
6. **平台注册**(SOP §7):`moduleConfig` + `registry.ts` + `App.tsx` 路由(模块用 `React.lazy` 动态导入 + `<Suspense fallback={<ModuleLoading />}>` 包 `<Routes>`,禁止静态 import,否则模块 CSS 进主包)+ `HomePage.tsx` ICON_MAP 四件套。
7. **验证**(SOP §8):构建层、浏览器层(mock 登录注入)、回归层逐项打勾。
8. **部署检查**(SOP §9):nginx 加固与生产地址冒烟。
## 红线(违反必出事故)
- **路由与资源目录永不同名**:资源只放 `public/mod-assets/<name>/`,绝不能放 `public/<name>/`。否则 dist 下出现与路由同名目录,nginx 目录 301 补斜杠并把容器端口 `:8901` 泄漏进浏览器地址栏,新页签 403/空白(2026-10 生产事故,SOP §3、§9)。
- **样式绝对隔离**:所有 CSS 选择器挂模块根容器类下。模块 CSS 虽随 React.lazy 路由 chunk 按需加载,但加载后仍全局生效,裸选择器必然跨模块污染;同名 `@keyframes`/工具类若值不同必须重命名或作用域化。全局选择器由 `npm run check:styles` 零容忍门禁拦截(已接入 build,SOP §4.5);ID 选择器特异性最高,`#nav` 类冲突需给旧模块规则也加前缀(SOP §4.2)。
- **全维度独立零容忍**:禁止写 `document.body`/`document.documentElement` 的 style/classList,禁止向 `document.head` 注入 link/style/script;Portal(弹窗/抽屉)禁止挂 `document.body`,必须挂模块根容器内;localStorage/sessionStorage key 必须带模块前缀(平台 `userToken`/`userInfo` 白名单除外);`document.title` 由平台 `ModuleTitle` 托管;事件监听/定时器必须在 useEffect 返回中清理。由 `npm run check:independence` 零容忍门禁拦截(已接入 build,SOP §5)。
- **零平台侵入**:不改 `document.body`/`document.documentElement`,存储 key 带模块前缀,不与平台路由冲突。
- **Provider 必须迁移**:漏迁 `AppProvider` 会导致路由渲染时 context 为 null 白屏。
## 验证捷径
- 提交/构建前跑 `npm run check:styles`(已接入 build 门禁),退出码 0 = 模块 CSS 无全局选择器违规。
- 提交/构建前跑 `npm run check:independence`(已接入 build 门禁),退出码 0 = 无全局 DOM 写入 / body Portal / 无前缀 storage key 违规。
- 构建后 `ls dist/` 确认根目录无与路由同名目录。
- 部署后 `curl -sI https://生产域名/<name>` 期望 200(或 302 跳登录);出现 301 且 Location 带 `:8901` 即端口泄漏信号。
- 浏览器验证前先注入 mock 会话:`sessionStorage.setItem('userToken', 'mock-token-for-ui-check')`。
- 进入模块再返回首页,确认 body class/style、CSS 变量、Portal DOM 无残留(视觉无污染)。
## 历史踩坑速查
详见 SOP §10 速查表。最高频三坑:同名资源目录端口泄漏、`#nav` ID 冲突、漏迁 Provider。
@@ -0,0 +1,349 @@
# React 前端项目融合 ai-platform 模块化 SOP
> 适用场景:将独立的 React 前端项目(Vite 构建)融合进 `ai-platform`,作为首页可进入的独立模块。
> 已按此 SOP 成功融合:jieya-ibp、welltrust-qap、baode-web、supplier-platform、wuc-quotation。
---
## 0. 核心原则(先记住这五条)
1. **样式绝对隔离**:模块 CSS 随 React.lazy 路由 chunk 按需加载(进入模块才下载该模块 JS+CSS),但加载后仍全局生效,任何裸元素选择器、`:root`/`body` 全局规则、裸 class/ID 选择器都会跨模块污染。**模块所有 CSS 选择器必须挂在模块根容器类下**;同名 `@keyframes` 与同名工具类若值不同,必须重命名或作用域化。
2. **路由与资源目录永不同名**:模块路由名(如 `/wuc-quotation`)绝不能与 `dist` 下静态资源目录同名,否则 nginx `try_files $uri` 命中目录触发自动 301 补斜杠重定向,Location 会带上容器内端口(8901)泄漏进浏览器地址栏,随后 403(详见 §3、§9)。资源统一放 `public/mod-assets/<模块名>/`。
3. **零平台侵入**:模块不得修改 `document.body`/`document.documentElement` 的 class/style,不得占用全局 localStorage key,不得与平台路由冲突。
4. **入口职责迁移**:源项目 `main.tsx` 中的 Provider 包裹、全局 CSS 引入等职责,全部迁移到模块 `App.tsx`,平台路由直接渲染模块默认导出。
5. **全维度独立**:模块必须做到「挂载即用、卸载即净」——CSS 变量与主题令牌挂模块根容器或 ThemeProvider 作用域 div,靠继承生效、卸载即消失;禁止写 `document.documentElement`/`document.body` 的 style/classList,禁止向 `document.head` 注入 link/style/script;localStorage/sessionStorage key 必须带模块前缀(平台 `userToken`/`userInfo` 白名单除外);Portal 挂载点必须在模块根容器内部;`document.title` 由平台 `ModuleTitle` 托管;事件监听与定时器必须在 `useEffect` 返回中卸载清理。由 `check:independence` 门禁零容忍拦截(见 §5.9)。
---
## 1. 前期勘察(融合前必做,约 10 分钟)
对源项目逐项检查并记录结论:
| 检查项 | 命令/方法 | 判定 |
|---|---|---|
| 新增依赖 | 对比 `package.json` 与 ai-platform | 原则上零新增;有新增需评估版本冲突 |
| 路由方式 | 看源 `main.tsx`/`App.tsx` | URL 子路由 → 平台路由用 `/xxx/*`;内部 state 切页 → 精确 path 即可 |
| 入口 Provider | 看 `main.tsx` 的 `<XxxProvider>` 包裹 | **必须迁移**(否则路由渲染时 context 为 null 白屏) |
| 全局 CSS | grep `html`/`body`/`:root`/`#root` | 记录所有需剥离/迁移的全局规则 |
| body 操作 | grep `document.body`、`document.documentElement` | classList.toggle/style 修改需改为模块根容器 ref |
| public 资源 | `ls public/` | 记录文件清单与代码引用位置(grep 文件名) |
| 内嵌资产 | grep `data:` | base64 data URI 无需处理 |
| 存储 key | grep `localStorage`/`sessionStorage` | key 必须带项目前缀,无前缀需加 |
| keyframes | grep `@keyframes` | 与全平台 CSS 比对命名唯一性 |
| React 版本 | `package.json` | 平台为 React 18.3 + @types/react 19,注意类型差异(见 §6.3) |
---
## 2. 目录规划与代码复制
```
ai-platform/
├── src/modules/<name>/ # 模块源码
│ ├── App.tsx # 入口(含 Provider 包裹 + CSS 引入 + 根容器)
│ ├── index.ts # moduleConfig 导出
│ ├── app/ | pages/ | ... # 源项目 src 业务代码(排除 main.tsx、__tests__)
│ └── styles/ | *.css # 源项目样式
└── public/mod-assets/<name>/ # 模块静态资源(禁止放 public/<name>/)
```
```bash
mkdir -p ai-platform/src/modules/<name> ai-platform/public/mod-assets/<name>
cp -R <源项目>/src/app ai-platform/src/modules/<name>/app
cp -R <源项目>/src/styles ai-platform/src/modules/<name>/styles
cp <源项目>/src/App.tsx ai-platform/src/modules/<name>/App.tsx
# 不要复制 main.tsx、__tests__、vite.config 等入口/测试文件
```
---
## 3. 静态资源迁移
1. `public/` 下资源全部复制到 `public/mod-assets/<name>/`;
2. grep 源码中所有相对路径引用(`src="xxx.svg"`、`href="xxx.md"`、`locateFile` 等),统一改为绝对路径 `/mod-assets/<name>/xxx`;
3. 验证:dev 下直接访问 `http://localhost:<port>/mod-assets/<name>/xxx` 返回 200;
4. build 后确认 `dist/mod-assets/<name>/` 存在。
> 为什么不用 `public/<name>/`:Vite 会把 public 目录原样拷入 dist,形成与模块路由同名的目录。完整故障链(2026-10 生产事故):
> 1. 首页卡片 `window.open('/<name>')` → nginx `try_files $uri /index.html` 的 `$uri` 命中该**目录**(非文件);
> 2. nginx 对目录请求自动 301 补斜杠(`/`),且 `port_in_redirect` 默认为 on,Location 变成 `https://域名:8901/<name>/`——**容器内端口被泄漏到浏览器地址栏**;
> 3. `:8901` 在外网不可达/无该虚拟主机 → 目录又无 index.html → 最终 403 或空白。
> 症状特征:只有"新增且带同名静态目录"的模块新页签打开异常(地址栏出现 `:8901`),老模块完全正常。
---
## 4. 样式隔离(核心,必须逐条执行)
### 4.1 根容器命名空间
模块 App 最外层包一个根容器,所有 CSS 选择器挂到它下面:
```tsx
// App.tsx
const rootRef = useRef<HTMLDivElement>(null)
return <div className="xxx-root" ref={rootRef}>...</div>
```
命名空间化有三种落地方式(按源项目 CSS 规模选择):
| 方式 | 适用 | 案例 |
|---|---|---|
| 全量脚本转换 | CSS 大/规则多(尤其 minified) | wuc-quotation:5 个 CSS 全部选择器加 `.wuc-root` 前缀 |
| 仅冲突类加前缀 | CSS 小、冲突少 | baode-web:20 处冲突选择器加 `.baode-root` |
| 原生自带命名空间 | 源项目已经做好隔离 | supplier-platform:变量与布局挂 `.hansong-app` |
**脚本转换要点**(已踩坑):
- `:root{--var}` → `.xxx-root{--var}`(CSS 变量迁到根容器)
- `body` → `.xxx-root`;`body.dark`/`body.collapsed` → `.xxx-root.dark` 等(主题/状态类改挂根容器)
- `body > #root > header` → `.xxx-root > header`(层级补偿规则改写)
- `html, body{overflow:hidden}` 等 → **直接删除**(会锁死平台整页滚动);视口锁定改由 `.xxx-root{height:100vh}` 承接
- `@media` 块内部规则**必须递归处理**(漏掉会造成窄屏规则逃逸成全局)
- `@keyframes`/`@font-face` 原样保留;字符串(data URI)不能破坏——需状态机解析而非正则替换
- 转换完必须校验:无残留 `body`/`:root`/`html`/`#root` 选择器、brace 平衡
### 4.2 三类冲突源都要检测(缺一不可)
```python
# 检测思路(对每个已存在模块 + 平台全局样式执行)
# 1. class 冲突:新模块 TSX className 集合 ∩ 双方 CSS 类名集合
# 2. ID 冲突:新模块 TSX 中的 id="xxx" ∩ 其它模块 CSS 中的 #xxx(双向)
# 3. 裸元素选择器:新模块 CSS 中 html/body/header/aside/nav/button/input 等无前缀选择器
```
> **ID 冲突是隐藏最深的坑**:`#nav` 特异性(1,0,0)碾压任何 `.wuc-root nav`(0,1,1)。wuc-quotation 上线后菜单被 supplier-platform 的 `#nav{display:flex}` 强制水平排列。修复方式是给**旧模块**的 ID 规则也加根容器前缀(`.hansong-app #nav`)。
### 4.3 运行时全局副作用清理
- `document.body.classList.toggle('dark'/'collapsed')` → `rootRef.current?.classList.toggle(...)`
- `document.body.style.overflow = ...`(如 LoginPage 的 useEffect)→ 模块内改为根容器样式或卸载时恢复
- 弹窗/Portal 挂载点若用 `document.body`,改为模块根容器内渲染
- `@media print` 中 `body{...}` 规则 → `.xxx-root{...}`,并放开视口锁定(`height:auto;overflow:visible`)
### 4.4 其它隔离项
- localStorage/sessionStorage key 带项目前缀(如 `wuchuan-quotation-v1`)
- `@keyframes` 命名全平台唯一(冲突时给新模块 keyframes 加前缀)
- 各模块 CSS 文件内不放 `@import` 全局重置(normalize/reset 一律禁止)
### 4.5 全局选择器门禁(check:styles)
`scripts/check-module-styles.mjs`(`npm run check:styles`)是样式隔离的零容忍门禁:以状态机逐字符解析扫描 `src/modules/**/*.css`(兼容数 MB 的 minified CSS 与 data URI 字符串),命中裸标签选择器(`button`/`table` 等)、裸 `:root`/伪类伪元素(`::-webkit-scrollbar` 等)、通配符 `*`、裸属性选择器、`@import` 引入 reset/normalize 即判违规,非零码退出。已接入 build 门禁(`npm run build` = `tsc -b && npm run check:styles && npm run check:independence && vite build`,双门禁见 §5.9),日常可单独运行:
```bash
npm run check:styles # 退出码 0 = 模块 CSS 无全局选择器违规
```
---
## 5. 模组完全独立互不影响(全维度隔离)
模块在平台中是「挂载即用、卸载即净」的独立单元,任何逃逸到全局的副作用都会污染首页与其它模块。本节是样式隔离(§4)之外的运行时隔离规则,与 `check:styles` 共同构成双门禁。
### 5.1 CSS 选择器命名空间
见 §4——所有选择器必须挂模块根容器类(`.xxx-root`),此处不重复。
### 5.2 CSS 变量与主题令牌作用域
- **禁止**向 `document.documentElement` / `document.body` 写入 CSS 变量、`style`、`classList`。
- 主题令牌(`--xxx` 变量、`background`、`color`、`font-family` 等)一律挂在**模块根容器**或模块内的 `ThemeProvider` 作用域 `div` 上,靠 CSS 继承向下生效。
- 模块卸载(路由切走)后,根容器及其子树从 DOM 移除,所有令牌随之消失,不残留到首页。
- 若源项目用 `document.documentElement.style.setProperty('--xxx', ...)` 切换主题,改为 `rootRef.current?.style.setProperty(...)` 或在根容器上切类。
### 5.3 全局 DOM 写入禁令
- **禁止**修改 `document.body` / `document.documentElement` 的 `style` 或 `classList`(如 `body.style.overflow`、`body.classList.toggle('dark')`)。
- **禁止**向 `document.head` 注入 `<link>`、`<style>`、`<script>` 标签。
- 需要锁滚动、切主题等副作用时,一律作用于模块根容器 `ref`,并在卸载时恢复。
### 5.4 存储 key 必须带模块前缀
- localStorage / sessionStorage 的 key 必须带模块前缀(如 `wuchuan-quotation-v1`、`sp_theme`、`ocDataSourceMode`、`welltrust-qap-*` 等)。
- **白名单**:平台级 `userToken`、`userInfo` 可直接读写,模块不得新增其它无前缀全局 key。
- 切换主题等本地偏好也用前缀 key,不得复用无命名空间的 `theme` / `darkMode`。
### 5.5 事件监听与定时器必须卸载清理
- 所有 `addEventListener`(`window` / `document` / `rootRef`)、`setTimeout`、`setInterval`、`requestAnimationFrame` 必须在 `useEffect` 的返回函数中 `removeEventListener` / `clearTimeout` / `clearInterval` / `cancelAnimationFrame`。
- 模块可被用户随时切走,残留监听器会跨模块执行并导致内存泄漏。
### 5.6 Portal 挂载点必须在模块根容器内部
- 弹窗、抽屉、Tooltip 等 `ReactDOM.createPortal(...)` 的第二个参数(容器)**必须**指向模块根容器内部的节点(如 `rootRef.current` 或根容器内的 `<div id="xxx-portal-root">`)。
- **禁止**挂到 `document.body`——否则模块卸载后 Portal DOM 残留在 body,样式与交互污染全局。
- 若第三方组件默认 portal 到 body,需通过 API 指定 `getContainer` / `appendTo` / `container` 为模块根容器。
### 5.7 document.title 由平台托管
- 模块**不得**自行 `document.title = ...`。
- 平台 `ModuleTitle` 组件在进入模块时设置标题为模块中文名,卸载时恢复 `'EIOSpace'`(见 §7 平台注册)。
### 5.8 第三方全局样式/脚本注入禁令
- 禁止在模块代码中动态 `<script src="...">` 注入第三方 SDK 到 `document.head` / `document.body`(如统计、地图、编辑器);必须用时改为 `import` 打包或挂到模块根容器内。
- 禁止 `@import` 全局 reset / normalize(见 §4.4)。
### 5.9 双门禁(check:styles + check:independence)
| 门禁 | 命令 | 零容忍范围 |
|---|---|---|
| 样式门禁 | `npm run check:styles` | CSS 全局选择器(裸标签、`:root`、`*`、`@import` reset 等,见 §4.5) |
| 独立门禁 | `npm run check:independence` | 全局 DOM 写入(`document.body` / `documentElement` 的 style/classList)、`document.head` 注入 link/style/script、`document.body` Portal、无前缀 storage key |
双门禁已接入 build:
```bash
npm run build # = tsc -b && npm run check:styles && npm run check:independence && vite build
```
日常可单独运行:
```bash
npm run check:independence # 退出码 0 = 无全局 DOM / Portal / 无前缀 storage 违规
```
---
## 6. 代码适配
### 6.1 入口与 Provider
```tsx
// App.tsx 末尾:平台路由直接渲染默认导出,Provider 职责从 main.tsx 移到这里
import { AppProvider } from './app/store'
export default function App() {
return (
<AppProvider>
<AppShell />
</AppProvider>
)
}
```
同时把源 `main.tsx` 的 CSS import 全部搬到模块 `App.tsx` 顶部(保持原有顺序)。
### 6.2 严格 tsconfig 适配(tsc -b 报错清单)
- `TS6133` 未使用变量/import → 删除(含解构中未使用的成员)
- `TS2554`:`useRef<T>()` → `useRef<T | undefined>(undefined)`(@types/react 19 要求初始值)
- 默认导入 `import React` 未使用 → 删除(react-jsx transform 无需)
### 6.3 其他常见点
- 事件监听/定时器在组件卸载时清理(模块可被随时切走)
- 弹窗内 `dangerouslySetInnerHTML` 注入的 HTML,其类名也要被命名空间 CSS 覆盖(确认前缀后仍能匹配)
- 内部 state 切页的项目保留原交互,不强行改造为 URL 路由
---
## 7. 平台注册(三件套 + 图标)
```ts
// 1. src/modules/<name>/index.ts
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: '<name>',
name: '模块中文名',
description: '一句话描述',
icon: 'Lucide图标名', // 如 FileSpreadsheet / Radar / Building2
path: '/<name>',
accentColor: '#7C6FFF', // 暗色强调色
accentColorLight: '#5747EF', // 亮色强调色
gradient: 'linear-gradient(135deg, ...)', // 暗色卡片渐变
gradientLight: 'linear-gradient(135deg, ...)', // 亮色卡片渐变
tags: ['标签1', '标签2'],
};
```
```ts
// 2. src/modules/registry.ts:import + modules 数组追加
// 3. src/App.tsx:模块级 React.lazy 动态导入 + 路由(ModuleTitle 负责页签标题,卸载恢复 'EIOSpace')
const XxxApp = lazy(() => import('@/modules/<name>/App'));
...
<Routes>
<Suspense fallback={<ModuleLoading />}>
<Route path="/<name>" element={<RequireAuth><ModuleTitle title="模块中文名"><XxxApp /></ModuleTitle></RequireAuth>} />
...
</Suspense>
</Routes>
// 4. src/pages/HomePage.tsx:ICON_MAP 增加图标(先在 lucide-react import 中补图标名)
```
> 模块入口必须用 `React.lazy` 动态导入(模块 CSS 随路由 chunk 按需加载),**静态 import 会把模块 CSS 打进主包,禁止**。
> 首页卡片点击已是 `window.open(mod.path, '_blank')` 新页签打开,无需额外处理。
---
## 8. 验证清单
**构建层**
- [ ] `npx tsc --noEmit` 通过
- [ ] `npm run build` 通过(注意 `tsc -b` 比 `tsc --noEmit` 更严,以 build 为准;已含 `check:styles` + `check:independence` 双门禁)
- [ ] `npm run check:styles` 退出码 0(模块 CSS 全局选择器零容忍门禁,见 §4.5,已接入 build)
- [ ] `npm run check:independence` 退出码 0(全局 DOM 写入 / body Portal / 无前缀 storage key 零容忍门禁,见 §5.9,已接入 build)
- [ ] `dist/mod-assets/<name>/` 资源齐全
- [ ] **`ls dist/` 确认根目录下没有与模块路由同名的目录**(防端口泄漏,见 §3)
**浏览器层**(dev server + mock 登录)
```js
// 平台守卫只查 sessionStorage.userToken,浏览器验证先注入:
sessionStorage.setItem('userToken', 'mock-token-for-ui-check');
sessionStorage.setItem('userInfo', JSON.stringify({ name: '演示用户', userId: 'demo' }));
```
- [ ] `/<name>` 页面完整渲染(header/侧栏/内容区),控制台无 React 报错、无 404
- [ ] 页内交互可用(菜单切换、弹窗、主题切换)
- [ ] 新页签打开后浏览器标题为模块中文名
- [ ] 首页出现新模块卡片(图标、配色正确)
- [ ] 首页(未进入任何模块)Network 面板无任何模块级 CSS chunk
- [ ] 首次进入模块路由时按需加载对应 JS+CSS chunk(React.lazy 生效)
- [ ] **进入模块再返回首页,首页视觉无污染**(body class/style 无残留、CSS 变量无残留、无 Portal 残留 DOM)
- [ ] **弹窗/抽屉等 Portal 的 DOM 位于模块根容器内部**(Elements 面板检查,非 `document.body` 直接子节点)
**回归层(改了旧模块 CSS 时必做)**
- [ ] 新模块关键布局 computed style 复核(如 nav 的 display)
- [ ] 被 CSS 影响的旧模块核心页面正常(如 supplier 顶栏导航)
- [ ] 平台首页/登录页样式未受污染
---
## 9. 部署注意(nginx)
- `nginx.conf` SPA 回退必须是 `try_files $uri /index.html;`——**禁止 `$uri/`**(目录命中 → 403 且不回退)
- **必须加两条重定向加固**(防止容器内端口泄漏到浏览器地址栏,2026-10 事故根因):
```nginx
server {
listen 8901;
...
port_in_redirect off; # 301 重定向的 Location 不带 8901 端口
absolute_redirect off; # 使用相对路径 Location,彻底避免泄漏 host/port
}
```
- 部署后用生产地址冒烟验证(新页签打开路径):
```bash
curl -sI https://ai-workshop.digiwincloud.com.cn/<name> | head -5
# 期望:HTTP 200(或 302 跳登录页)
# 异常信号:HTTP 301 且 Location 带 :8901 —— 即存在与路由同名的静态目录触发了目录重定向
```
- 模块静态资源引用用绝对路径 `/mod-assets/...`,与部署子路径无关
---
## 10. 历史踩坑速查表
| 案例 | 坑 | 修复 |
|---|---|---|
| baode-web ↔ supplier-platform | baode 自检页 `.page{max-width:1080px}` 污染 supplier 的 `section.page` | `.page`→`.checkpage` + 冲突类加 `.baode-root` 前缀 |
| supplier-platform | 源 tsconfig 宽松,`useRef<T>()` 在 @types/react 19 下报 TS2554 | `useRef<T \| undefined>(undefined)` |
| 全部模块 | dist 下与路由同名目录:早期 `try_files $uri/` 命中目录 403;去掉 `$uri/` 后 `$uri` 仍命中目录触发 301 补斜杠,`port_in_redirect` 默认 on 把容器端口 `:8901` 泄漏进浏览器地址栏,新页签跳到带端口地址后 403/空白 | 资源统一迁 `mod-assets/`;nginx 加 `port_in_redirect off; absolute_redirect off;` |
| wuc-quotation | 漏迁 `AppProvider` → 白屏 `ctx is null` | Provider 移入模块默认导出 |
| wuc-quotation | 001.css 7.8MB 内嵌 data URI + minified,正则替换会破坏资产 | 状态机解析转换,字符串原样保留 |
| wuc-quotation | `document.body.classList.toggle('dark')` 污染平台 body | 改挂 `.wuc-root` 根容器 ref |
| wuc-quotation | `@media` 内规则未递归前缀化(首版转换脚本 bug) | 递归处理 + 转换后自动校验 |
| wuc-quotation ↔ supplier-platform | `#nav` ID 特异性碾压类前缀,菜单被改 flex 水平 | 旧模块规则改 `.hansong-app #nav`;SOP 增加 ID 冲突检测 |
| jieya-ibp / welltrust-qap | sql.js wasm 路径、logo 相对路径失效 | 统一 `locateFile: () => '/mod-assets/<name>/...'` |
| 全部模块 | 模块 CSS 全局选择器(`:root`/`button`/`table`/`::-webkit-scrollbar`/`*`)跨模块污染 | 加模块根容器前缀 + `check:styles` 门禁(§4.5,已接入 build) |
@@ -0,0 +1,14 @@
# Checklist
- [x] jieya-ibp/context/ThemeContext.tsx 不再写 document.documentElement / document.body,CSS 变量与背景/文字色由 ThemeProvider 作用域容器承载
- [x] welltrust-qap/context/ThemeContext.tsx 同上改造
- [x] order-cost-analysis CostCockpit 移除对 documentElement 的 --body-bg 死变量写入
- [x] bomx Drawer 的 createPortal 挂载点位于 .bomx-app 子树内,不再挂 document.body(portalMount 必传,无 document.body 兜底)
- [x] 浏览器验证:进入 jieya 后返回首页,首页背景与文字色未被模组主题覆盖(body style 串 before==during==after)
- [x] 浏览器验证:jieya 明暗主题切换正常(作用于 .jieya-root);welltrust 同构;bomx Drawer 当前未实例化
- [x] scripts/check-module-independence.mjs 存在,能检出全局 DOM 写入、head 注入、body Portal、无前缀 storage key,违规非零退出
- [x] package.json 含 check:independence,build 已接入 check:styles + check:independence 双门禁
- [x] npm run check:independence 退出码 0
- [x] npm run check:styles 退出码 0
- [x] npm run build 通过
- [x] docs/react-module-integration-sop.md 含「模组完全独立互不影响」完整规则与双门禁说明
- [x] .trae/skills/react-module-integration/SKILL.md 与 references 副本同步更新
@@ -0,0 +1,58 @@
# 模组完全独立互不影响 Spec
## Why
此前已完成「模组 CSS 按需加载 + 选择器命名空间隔离」(spec `isolate-and-lazyload-module-styles`),但跨模组污染不止 CSS 一项。审计发现仍存在模组在运行时直接写入全局 DOM 且卸载不恢复的行为(jieya-ibp / welltrust-qap 的 ThemeContext 把 CSS 变量写到 `document.documentElement`、把 `background`/`color` 写到 `document.body`;order-cost-analysis 的 CostCockpit 向 `documentElement` 写 `--body-bg` 死变量)。这些值在用户离开模组后仍残留在全局,会污染首页与其它模组的视觉。从「每个模组完全独立、互不影响」的角度,需要在 CSS 之外补齐全局 DOM、存储、事件、Portal 等维度的隔离,并把规则沉淀进 SOP 与技能文档。
## What Changes
- **修复全局 DOM 写入污染**:jieya-ibp 与 welltrust-qap 的 `ThemeContext` 不再写 `document.documentElement` / `document.body`,改为由 `ThemeProvider` 渲染的作用域容器承载 CSS 变量与背景/文字色(CSS 变量向下继承,模组内所有 `var(--xxx)` 正常取值);order-cost-analysis CostCockpit 移除向 `documentElement` 写 `--body-bg` 的死代码。
- **Portal 挂载规范化**:bomx Drawer 目前用 `createPortal(..., document.body)`(已用 `.bomx-app` 包裹层解决 CSS 作用域);作为最佳实践,将 Portal 内容挂到模块根容器内的 Portal 挂载点,避免全局 body 出现非受控 DOM。
- **新增模组独立门禁脚本**:`scripts/check-module-independence.mjs`,扫描 `src/modules/**/*.{ts,tsx,js,jsx}`,检测 `document.body.style`/`document.body.classList`、`document.documentElement.style`/`setAttribute`、`document.head.appendChild`/`insertBefore`(注入 link/style)、`createPortal` 第二参数为 `document.body`、`localStorage`/`sessionStorage` key 不带模组前缀等违规模式,非零退出;接入 `npm run check:independence` 并加入 `build` 门禁。
- **文档沉淀**:更新 `docs/react-module-integration-sop.md` 与 `.trae/skills/react-module-integration`(含 references 副本),新增「模组独立不互相影响」章节,覆盖:CSS 选择器命名空间、CSS 变量作用域、全局 DOM 写入禁令、storage key 前缀、事件/定时器卸载清理、Portal 挂载、document.title、第三方全局样式/脚本注入禁令,并给出 check:styles + check:independence 双门禁说明。
## Impact
- Affected specs: `isolate-and-lazyload-module-styles`(CSS 隔离已完成,本 spec 扩展到全维度)
- Affected code:
- `src/modules/jieya-ibp/context/ThemeContext.tsx`、`src/modules/welltrust-qap/context/ThemeContext.tsx`(全局写入改作用域容器)
- `src/modules/order-cost-analysis/pages-orig/CostCockpit.tsx`(移除死变量写入)
- `src/modules/bomx-reuse-analyzer/components/Drawer.tsx`(Portal 挂载点内移)
- `scripts/check-module-independence.mjs`(新增)
- `package.json`(新增 `check:independence`,build 接入)
- `docs/react-module-integration-sop.md`、`.trae/skills/react-module-integration/SKILL.md`、`.trae/skills/react-module-integration/references/react-module-integration-sop.md`(文档沉淀)
## ADDED Requirements
### Requirement: 模组不得写入全局 DOM 且卸载后无残留
系统 SHALL 保证每个模组在运行期不修改 `document.body` / `document.documentElement` 的 `style`/`classList`,不向 `document.head` 注入 `<link>`/`<style>`/`<script>`;模组的 CSS 变量、背景色、文字色等主题令牌 SHALL 仅作用于模组根容器及其后代。
#### Scenario: 访问 jieya-ibp 后回到首页
- **WHEN** 用户进入 `/jieya-ibp` 再返回首页 `/`
- **THEN** 首页背景色与文字色为平台默认值,未被 jieya 的深色主题覆盖
#### Scenario: 主题令牌仅在模组内生效
- **WHEN** jieya-ibp 切换明暗主题
- **THEN** `--body-bg`/`--scroll-thumb`/`--glow-color`/`--hover-bg` 等变量仅在 `.jieya-root` 子树内生效,`getComputedStyle(document.documentElement).getPropertyValue('--body-bg')` 不含模组值
### Requirement: 模组门户(Portal)挂载于模组根容器内
系统 SHALL 保证模组的弹窗/抽屉等 Portal 内容挂载在模组根容器内部的 DOM 节点,而非 `document.body`,避免全局 body 出现非模组受控的 DOM。
#### Scenario: bomx 抽屉挂载点
- **WHEN** 打开 bomx-reuse-analyzer 的 Drawer
- **THEN** 抽屉 DOM 节点位于 `.bomx-app` 子树内,而非 `document.body` 的直接子节点
### Requirement: 模组独立自动化门禁
系统 SHALL 提供 `npm run check:independence` 脚本,扫描模组代码中的全局 DOM 写入、head 注入、body Portal、无前缀 storage key 等独立违规,作为构建门禁。
#### Scenario: 门禁通过
- **WHEN** 所有模组均无全局 DOM 写入、Portal 均挂在根容器内、storage key 均带模组前缀
- **THEN** `npm run check:independence` 退出码 0
#### Scenario: 门禁发现违规
- **WHEN** 某模组存在 `document.body.style.xxx` 或 `createPortal(x, document.body)`
- **THEN** 脚本输出违规文件+行号+原因,退出码非 0,`npm run build` 失败
### Requirement: 模组独立规则文档化
SOP 文档与 react-module-integration 技能 SHALL 包含「模组完全独立互不影响」的完整规则清单与双门禁(check:styles + check:independence)说明。
#### Scenario: 查阅文档
- **WHEN** 查阅 SOP 或技能文件
- **THEN** 可找到全局 DOM 写入禁令、CSS 变量作用域、storage key 前缀、事件/定时器清理、Portal 挂载、document.title、第三方注入禁令等规则,以及双门禁运行方式
@@ -0,0 +1,29 @@
# Tasks
- [x] Task 1: 修复全局 DOM 写入污染(jieya-ibp / welltrust-qap ThemeContext)
- [x] SubTask 1.1: `jieya-ibp/context/ThemeContext.tsx`:移除 `useEffect` 中对 `document.documentElement` 的 `setProperty` 与 `document.body.style.background/color`;改为 `ThemeProvider` 返回的 `<ThemeContext.Provider>` 内包裹一层作用域 `<div>`,以 inline style 设置 `--body-bg`/`--scroll-thumb`/`--glow-color`/`--hover-bg` 变量与 `background`/`color`(值取自 `tokens`),宽高 100% 承接 `AppInner` 的 100vw/100vh 根容器
- [x] SubTask 1.2: `welltrust-qap/context/ThemeContext.tsx`:同 1.1 改造
- [x] SubTask 1.3: `order-cost-analysis/pages-orig/CostCockpit.tsx`:移除向 `document.documentElement` 写 `--body-bg` 的 `useEffect`(`var(--body-bg)` 在模组内无引用,属死代码)
- [x] SubTask 1.4: 浏览器验证:进入 jieya 再回首页,首页背景/文字色未被覆盖;jieya 明暗主题切换正常(welltrust 同构改造,tsc + build 通过)
- [x] Task 2: Portal 挂载点内移(bomx Drawer)
- [x] SubTask 2.1: `bomx-reuse-analyzer/pages/BomxReuseHome.tsx` 根容器内新增 Portal 挂载点 `<div ref={portalMountRef} />`
- [x] SubTask 2.2: `bomx-reuse-analyzer/components/Drawer.tsx`:`createPortal` 第二参数改为必传 `portalMount: HTMLDivElement`,彻底移除 `document.body` 兜底
- [x] SubTask 2.3: Drawer 当前未被任何文件引用(死代码),无运行时实例;`.bomx-app` 根容器无 transform/filter/perspective,不会破坏 fixed 遮罩
- [x] Task 3: 新增模组独立门禁脚本
- [x] SubTask 3.1: 新增 `scripts/check-module-independence.mjs`(ESM 零依赖),扫描 `src/modules/**/*.{ts,tsx,js,jsx}`,检测 5 类违规(body 样式写入、documentElement 写入、head 注入、body Portal、无前缀 storage key),跳过字符串与注释,违规非零退出
- [x] SubTask 3.2: `package.json` 增加 `check:independence`;`build` 改为 `tsc -b && npm run check:styles && npm run check:independence && vite build`
- [x] SubTask 3.3: 自测:修复后退出码 0(扫描 270 文件);故意保留/插入的违规样例可正确检出(已验证 bomx Drawer、knowledge-graph 两处真实违规被检出并修复)
- [x] Task 4: 文档沉淀(SOP + 技能)
- [x] SubTask 4.1: `docs/react-module-integration-sop.md` 新增 §5「模组完全独立互不影响」(5.1–5.9),覆盖全维度规则与双门禁说明;章节顺延
- [x] SubTask 4.2: `.trae/skills/react-module-integration/SKILL.md` 红线与验证清单同步
- [x] SubTask 4.3: `.trae/skills/react-module-integration/references/react-module-integration-sop.md` 与 docs 完全同源(diff 无输出)
- [x] Task 5: 端到端验证
- [x] SubTask 5.1: `npm run build` 通过(含双门禁),dist 无回归
- [x] SubTask 5.2: 浏览器验证:首页→jieya→首页 body 样式串 before/during/after 完全一致(仅平台深色主题值),jieya 主题背景作用于 `.jieya-root`;控制台无报错
- [x] SubTask 5.3: `npm run check:independence` 与 `npm run check:styles` 均退出码 0
# Task Dependencies
- Task 1、Task 2 互相独立,可并行
- Task 3 依赖 Task 1、Task 2(修复后门禁才能通过;门禁脚本本身可先写,用 HEAD 版本验证检出能力)
- Task 4 与 Task 1/2/3 无代码冲突,可并行
- Task 5 依赖 Task 1-4
@@ -0,0 +1,12 @@
# Checklist
- [x] `src/App.tsx` 全部模块组件改为 `React.lazy()` 动态导入,`<Suspense>` 兜底生效
- [x] `npx tsc -b` 类型检查通过
- [x] `npm run build` 成功,`dist/assets` 中每个模块的 CSS 为独立 chunk 文件(8 个 css chunk:主 css 12KB 仅平台样式,wuc 7.8MB、supplier/baode/jieya/welltrust/bomx 各自独立,共享 styles chunk 1 个)
- [x] `scripts/check-module-styles.mjs` 存在且能正确检测 `:root`/`html`/`body`/`*`/裸元素选择器/`@import` 重置,违规时非 0 退出并列出文件+行号(对 git HEAD 存量验证:46 条违规全部检出且行号正确,wuc 7.8MB data URI 零误报)
- [x] `package.json` 含 `check:styles` 脚本,且 `build` 脚本已接入该门禁(`tsc -b && npm run check:styles && vite build`)
- [x] `bomx-reuse-analyzer/styles.css` 无 `:root` 残留,模块页面 CSS 变量取值正常、视觉无回归(浏览器实测浅色 BOM 界面正常渲染)
- [x] `npm run check:styles` 退出码 0(✓ 模块样式检查通过,扫描 12 个文件)
- [x] 首页加载时 Network 面板无任何模块级 CSS chunk(实测仅 /src/index.css)
- [x] 跳转 `supplier-platform`/`wuc-quotation`/`bomx-reuse-analyzer` 时按需加载对应样式且渲染正常、无控制台报错(wuc 6 个样式文件按需加载;另验 jieya-ibp 深色主题正常)
- [x] 平台首页与登录页视觉未受模块样式污染(星空动画、卡片、按钮样式实测正常)
- [x] `docs/react-module-integration-sop.md` 与 `.trae/skills/react-module-integration/SKILL.md` 已包含 lazy 路由约定与 check:styles 校验说明(references 副本同步)
@@ -0,0 +1,70 @@
# 模块样式隔离与按需加载 Spec
## Why
当前 `src/App.tsx` 静态 import 全部 12 个模块的 App 组件,导致所有模块的 JS 与 CSS 全部打进主包,用户打开首页即下载全部模块样式(wuc-quotation 单个模块 CSS 约 7.8MB)。同时样式隔离仅依赖 SOP 中的手工命名空间约定,无自动化守护,仍存在残留全局选择器(如 `bomx-reuse-analyzer/styles.css` 的 `:root` 规则)可跨模块污染。
## What Changes
- **路由级懒加载**:`src/App.tsx` 中模块组件改为 `React.lazy()` 动态导入,外层包 `<Suspense>` 加载兜底;Vite 自动将每个模块拆为独立 JS+CSS chunk,仅在跳转到对应路由时才加载该模块样式。
- **样式隔离自动化守护**:新增 `scripts/check-module-styles.mjs` 检查脚本,扫描 `src/modules/**/*.css` 中的全局选择器(`:root`/`html`/`body`/`*`/裸元素选择器/`@import` 全局重置),发现违规即报错退出;注册为 `npm run check:styles`。
- **修复存量违规**:`bomx-reuse-analyzer/styles.css` 的 `:root` CSS 变量迁移到模块根容器类下。
- **构建管线接入**:存量违规清零后,将 `check:styles` 纳入 `build` 脚本,防止后续模块引入全局选择器。
- **文档同步**:更新 SOP 文档与 react-module-integration 技能,明确新模块接入必须使用 lazy 路由模式 + 命名空间根容器。
## Impact
- Affected specs: 无既有 spec(首次建立)
- Affected code:
- `src/App.tsx`(懒加载改造)
- `src/modules/bomx-reuse-analyzer/styles.css`(存量违规修复)
- `scripts/check-module-styles.mjs`(新增)
- `package.json`(新增 check:styles 脚本、build 接入)
- `docs/react-module-integration-sop.md`、`.trae/skills/react-module-integration/SKILL.md`(文档同步)
## ADDED Requirements
### Requirement: 模块按需加载
系统 SHALL 以 `React.lazy()` 动态导入方式注册全部模块路由,保证模块代码与样式拆分为独立 chunk,仅在用户导航至该模块路由时才发起加载。
#### Scenario: 首页不加载模块样式
- **WHEN** 用户登录后停留在平台首页(`/`)
- **THEN** Network 面板中不出现任何模块级 CSS chunk(如 `wuc-quotation`、`supplier-platform` 的 CSS 文件)
#### Scenario: 跳转模块时加载对应样式
- **WHEN** 用户首次导航到某模块路由(如 `/supplier-platform`)
- **THEN** 浏览器按需加载该模块对应的 JS 与 CSS chunk,模块界面正常渲染
#### Scenario: 加载期间兜底 UI
- **WHEN** 模块 chunk 尚在加载中
- **THEN** Suspense 兜底占位展示(平台风格的加载提示),加载完成后无报错切换至模块界面
#### Scenario: 构建产物按模块拆分
- **WHEN** 执行 `npm run build`
- **THEN** `dist/assets` 中每个模块生成独立的 JS 与 CSS 产物(含路由引用关系),`tsc -b` 类型检查通过
### Requirement: 模块样式全局选择器零容忍
系统 SHALL 提供自动化检查脚本,确保 `src/modules/**/*.css` 中不出现全局作用选择器;检查结果 SHALL 作为构建门禁。
#### Scenario: 扫描通过
- **WHEN** 执行 `npm run check:styles` 且所有模块 CSS 均挂在模块命名空间根容器类下
- **THEN** 脚本以退出码 0 结束,无违规输出
#### Scenario: 扫描发现违规
- **WHEN** 某模块 CSS 中存在 `:root`、`html`、`body`、`*`、裸元素选择器或 `@import` 全局重置
- **THEN** 脚本以非 0 退出码失败,并逐条输出违规文件、行号与选择器内容
#### Scenario: 构建门禁生效
- **WHEN** 模块 CSS 存在全局选择器违规时执行 `npm run build`
- **THEN** 构建失败并提示先修复样式违规
### Requirement: 存量违规清零
系统 SHALL 保证现有 12 个模块 CSS 无全局选择器残留,不污染平台首页、登录页及其它模块。
#### Scenario: bomx-reuse-analyzer 变量迁移
- **WHEN** `src/modules/bomx-reuse-analyzer/styles.css` 中存在 `:root { --xxx }` 规则
- **THEN** 变量定义迁移至该模块根容器类下,模块页面变量取值正常,视觉无回归
### Requirement: 新模块接入约定同步
SOP 文档与 react-module-integration 技能 SHALL 同步更新:新模块路由必须使用 lazy 动态导入模式,CSS 必须挂载在模块命名空间根容器下,并通过 check:styles 校验。
#### Scenario: 文档含懒加载约定
- **WHEN** 查阅 SOP 文档或技能文件
- **THEN** 可找到 lazy 路由模式代码约定与 check:styles 校验说明
@@ -0,0 +1,30 @@
# Tasks
- [x] Task 1: 路由级懒加载改造
- [x] SubTask 1.1: `src/App.tsx` 将 12 个模块组件的静态 import 全部改为 `React.lazy(() => import('...'))`
- [x] SubTask 1.2: `<Routes>` 外层包 `<Suspense>`,提供平台风格 loading 兜底(居中 spinner + "模块加载中"文案)
- [x] SubTask 1.3: 验证 `npx tsc -b` 类型检查通过;`npm run build` 后确认 `dist/assets` 中各模块 CSS 拆分为独立文件
- [x] Task 2: 样式隔离自动检查脚本
- [x] SubTask 2.1: 新增 `scripts/check-module-styles.mjs`:递归扫描 `src/modules/**/*.css`,检测 `:root`/`html`/`body`/`*` 选择器、裸元素选择器(无类/ID/命名空间前缀的元素标签规则)、`@import` 全局重置;违规输出文件+行号+选择器,非 0 退出
- [x] SubTask 2.2: `package.json` 注册 `"check:styles": "node scripts/check-module-styles.mjs"`
- [ ] Task 3: 修复存量违规(勘察确认共 5 个模组存在裸选择器,修复后须全部通过 check:styles)
- [x] SubTask 3.1: `bomx-reuse-analyzer/styles.css`(根容器 `.bomx-app`):`:root`→`.bomx-app`、`::-webkit-scrollbar*`/`input[type=...]`/`select`/`input:focus`/`:focus-visible` 全部加前缀
- [x] SubTask 3.2: `order-cost-analysis`:为 `pages-orig/CostCockpit.tsx`、`pages-orig/AIMCockpit.tsx` 根 div 添加 `ordercost-root` 类,`styles.css` 顶部级 `::-webkit-scrollbar` 三条规则加前缀
- [x] SubTask 3.3: `jieya-ibp`:App.tsx 根 div(加载态 + 主态)添加 `jieya-root` 类;`index.css` 的 `button`/`input, textarea`/`::-webkit-scrollbar` 四条规则加前缀
- [x] SubTask 3.4: `welltrust-qap`:同 3.3,根类 `welltrust-root`
- [x] SubTask 3.5: `supplier-platform/index.css`:`main`、`table/th/td/tr.rec-row/tbody tr` 等裸元素规则加 `.hansong-app` 前缀
- [x] SubTask 3.6: 检查受影响模组的 `createPortal` 挂载点均位于模块根容器内(bomx Drawer 挂 document.body 需包 `.bomx-app` 类包裹层);baode/bomx/jieya/welltrust 的 `@media (prefers-reduced-motion)` 内 `*` 通配规则加根前缀;jieya/welltrust 的 `.space-*` 同名不同值工具类作用域化、`slide-in-right` 等同名不同体 keyframes 重命名
- [x] SubTask 3.7: `npm run check:styles` 退出码 0(存量违规清零)
- [x] Task 4: 构建门禁与文档同步
- [x] SubTask 4.1: `package.json` 的 `build` 脚本接入 `check:styles`(`tsc -b && npm run check:styles && vite build`)
- [x] SubTask 4.2: 更新 `docs/react-module-integration-sop.md`:新增「路由必须 lazy 动态导入」约定与 check:styles 校验说明
- [x] SubTask 4.3: 同步 `.trae/skills/react-module-integration/SKILL.md`(红线与验证清单补充懒加载要求)
- [x] Task 5: 端到端验证
- [x] SubTask 5.1: `npm run dev` 启动,浏览器验证:首页 Network 无任何模块 CSS chunk(实测仅 /src/index.css)
- [x] SubTask 5.2: 依次跳转 `supplier-platform`、`wuc-quotation`、`bomx-reuse-analyzer`:按需加载对应 chunk、界面渲染正常、无控制台报错(另验 jieya-ibp 深色主题正常)
- [x] SubTask 5.3: 抽查首页与登录页视觉无污染、`bomx-reuse-analyzer` 页面样式无回归
# Task Dependencies
- Task 3 依赖 Task 2(需要脚本先检测出违规)
- Task 4 依赖 Task 2、Task 3(违规清零后才接入构建门禁)
- Task 5 依赖 Task 1(懒加载完成后方可验证按需加载);SubTask 5.3 依赖 Task 3
- Task 2 与 Task 1 无依赖,可并行
+349
View File
@@ -0,0 +1,349 @@
# React 前端项目融合 ai-platform 模块化 SOP
> 适用场景:将独立的 React 前端项目(Vite 构建)融合进 `ai-platform`,作为首页可进入的独立模块。
> 已按此 SOP 成功融合:jieya-ibp、welltrust-qap、baode-web、supplier-platform、wuc-quotation。
---
## 0. 核心原则(先记住这五条)
1. **样式绝对隔离**:模块 CSS 随 React.lazy 路由 chunk 按需加载(进入模块才下载该模块 JS+CSS),但加载后仍全局生效,任何裸元素选择器、`:root`/`body` 全局规则、裸 class/ID 选择器都会跨模块污染。**模块所有 CSS 选择器必须挂在模块根容器类下**;同名 `@keyframes` 与同名工具类若值不同,必须重命名或作用域化。
2. **路由与资源目录永不同名**:模块路由名(如 `/wuc-quotation`)绝不能与 `dist` 下静态资源目录同名,否则 nginx `try_files $uri` 命中目录触发自动 301 补斜杠重定向,Location 会带上容器内端口(8901)泄漏进浏览器地址栏,随后 403(详见 §3、§9)。资源统一放 `public/mod-assets/<模块名>/`。
3. **零平台侵入**:模块不得修改 `document.body`/`document.documentElement` 的 class/style,不得占用全局 localStorage key,不得与平台路由冲突。
4. **入口职责迁移**:源项目 `main.tsx` 中的 Provider 包裹、全局 CSS 引入等职责,全部迁移到模块 `App.tsx`,平台路由直接渲染模块默认导出。
5. **全维度独立**:模块必须做到「挂载即用、卸载即净」——CSS 变量与主题令牌挂模块根容器或 ThemeProvider 作用域 div,靠继承生效、卸载即消失;禁止写 `document.documentElement`/`document.body` 的 style/classList,禁止向 `document.head` 注入 link/style/script;localStorage/sessionStorage key 必须带模块前缀(平台 `userToken`/`userInfo` 白名单除外);Portal 挂载点必须在模块根容器内部;`document.title` 由平台 `ModuleTitle` 托管;事件监听与定时器必须在 `useEffect` 返回中卸载清理。由 `check:independence` 门禁零容忍拦截(见 §5.9)。
---
## 1. 前期勘察(融合前必做,约 10 分钟)
对源项目逐项检查并记录结论:
| 检查项 | 命令/方法 | 判定 |
|---|---|---|
| 新增依赖 | 对比 `package.json` 与 ai-platform | 原则上零新增;有新增需评估版本冲突 |
| 路由方式 | 看源 `main.tsx`/`App.tsx` | URL 子路由 → 平台路由用 `/xxx/*`;内部 state 切页 → 精确 path 即可 |
| 入口 Provider | 看 `main.tsx` 的 `<XxxProvider>` 包裹 | **必须迁移**(否则路由渲染时 context 为 null 白屏) |
| 全局 CSS | grep `html`/`body`/`:root`/`#root` | 记录所有需剥离/迁移的全局规则 |
| body 操作 | grep `document.body`、`document.documentElement` | classList.toggle/style 修改需改为模块根容器 ref |
| public 资源 | `ls public/` | 记录文件清单与代码引用位置(grep 文件名) |
| 内嵌资产 | grep `data:` | base64 data URI 无需处理 |
| 存储 key | grep `localStorage`/`sessionStorage` | key 必须带项目前缀,无前缀需加 |
| keyframes | grep `@keyframes` | 与全平台 CSS 比对命名唯一性 |
| React 版本 | `package.json` | 平台为 React 18.3 + @types/react 19,注意类型差异(见 §6.3) |
---
## 2. 目录规划与代码复制
```
ai-platform/
├── src/modules/<name>/ # 模块源码
│ ├── App.tsx # 入口(含 Provider 包裹 + CSS 引入 + 根容器)
│ ├── index.ts # moduleConfig 导出
│ ├── app/ | pages/ | ... # 源项目 src 业务代码(排除 main.tsx、__tests__)
│ └── styles/ | *.css # 源项目样式
└── public/mod-assets/<name>/ # 模块静态资源(禁止放 public/<name>/)
```
```bash
mkdir -p ai-platform/src/modules/<name> ai-platform/public/mod-assets/<name>
cp -R <源项目>/src/app ai-platform/src/modules/<name>/app
cp -R <源项目>/src/styles ai-platform/src/modules/<name>/styles
cp <源项目>/src/App.tsx ai-platform/src/modules/<name>/App.tsx
# 不要复制 main.tsx、__tests__、vite.config 等入口/测试文件
```
---
## 3. 静态资源迁移
1. `public/` 下资源全部复制到 `public/mod-assets/<name>/`;
2. grep 源码中所有相对路径引用(`src="xxx.svg"`、`href="xxx.md"`、`locateFile` 等),统一改为绝对路径 `/mod-assets/<name>/xxx`;
3. 验证:dev 下直接访问 `http://localhost:<port>/mod-assets/<name>/xxx` 返回 200;
4. build 后确认 `dist/mod-assets/<name>/` 存在。
> 为什么不用 `public/<name>/`:Vite 会把 public 目录原样拷入 dist,形成与模块路由同名的目录。完整故障链(2026-10 生产事故):
> 1. 首页卡片 `window.open('/<name>')` → nginx `try_files $uri /index.html` 的 `$uri` 命中该**目录**(非文件);
> 2. nginx 对目录请求自动 301 补斜杠(`/`),且 `port_in_redirect` 默认为 on,Location 变成 `https://域名:8901/<name>/`——**容器内端口被泄漏到浏览器地址栏**;
> 3. `:8901` 在外网不可达/无该虚拟主机 → 目录又无 index.html → 最终 403 或空白。
> 症状特征:只有"新增且带同名静态目录"的模块新页签打开异常(地址栏出现 `:8901`),老模块完全正常。
---
## 4. 样式隔离(核心,必须逐条执行)
### 4.1 根容器命名空间
模块 App 最外层包一个根容器,所有 CSS 选择器挂到它下面:
```tsx
// App.tsx
const rootRef = useRef<HTMLDivElement>(null)
return <div className="xxx-root" ref={rootRef}>...</div>
```
命名空间化有三种落地方式(按源项目 CSS 规模选择):
| 方式 | 适用 | 案例 |
|---|---|---|
| 全量脚本转换 | CSS 大/规则多(尤其 minified) | wuc-quotation:5 个 CSS 全部选择器加 `.wuc-root` 前缀 |
| 仅冲突类加前缀 | CSS 小、冲突少 | baode-web:20 处冲突选择器加 `.baode-root` |
| 原生自带命名空间 | 源项目已经做好隔离 | supplier-platform:变量与布局挂 `.hansong-app` |
**脚本转换要点**(已踩坑):
- `:root{--var}` → `.xxx-root{--var}`(CSS 变量迁到根容器)
- `body` → `.xxx-root`;`body.dark`/`body.collapsed` → `.xxx-root.dark` 等(主题/状态类改挂根容器)
- `body > #root > header` → `.xxx-root > header`(层级补偿规则改写)
- `html, body{overflow:hidden}` 等 → **直接删除**(会锁死平台整页滚动);视口锁定改由 `.xxx-root{height:100vh}` 承接
- `@media` 块内部规则**必须递归处理**(漏掉会造成窄屏规则逃逸成全局)
- `@keyframes`/`@font-face` 原样保留;字符串(data URI)不能破坏——需状态机解析而非正则替换
- 转换完必须校验:无残留 `body`/`:root`/`html`/`#root` 选择器、brace 平衡
### 4.2 三类冲突源都要检测(缺一不可)
```python
# 检测思路(对每个已存在模块 + 平台全局样式执行)
# 1. class 冲突:新模块 TSX className 集合 ∩ 双方 CSS 类名集合
# 2. ID 冲突:新模块 TSX 中的 id="xxx" ∩ 其它模块 CSS 中的 #xxx(双向)
# 3. 裸元素选择器:新模块 CSS 中 html/body/header/aside/nav/button/input 等无前缀选择器
```
> **ID 冲突是隐藏最深的坑**:`#nav` 特异性(1,0,0)碾压任何 `.wuc-root nav`(0,1,1)。wuc-quotation 上线后菜单被 supplier-platform 的 `#nav{display:flex}` 强制水平排列。修复方式是给**旧模块**的 ID 规则也加根容器前缀(`.hansong-app #nav`)。
### 4.3 运行时全局副作用清理
- `document.body.classList.toggle('dark'/'collapsed')` → `rootRef.current?.classList.toggle(...)`
- `document.body.style.overflow = ...`(如 LoginPage 的 useEffect)→ 模块内改为根容器样式或卸载时恢复
- 弹窗/Portal 挂载点若用 `document.body`,改为模块根容器内渲染
- `@media print` 中 `body{...}` 规则 → `.xxx-root{...}`,并放开视口锁定(`height:auto;overflow:visible`)
### 4.4 其它隔离项
- localStorage/sessionStorage key 带项目前缀(如 `wuchuan-quotation-v1`)
- `@keyframes` 命名全平台唯一(冲突时给新模块 keyframes 加前缀)
- 各模块 CSS 文件内不放 `@import` 全局重置(normalize/reset 一律禁止)
### 4.5 全局选择器门禁(check:styles)
`scripts/check-module-styles.mjs`(`npm run check:styles`)是样式隔离的零容忍门禁:以状态机逐字符解析扫描 `src/modules/**/*.css`(兼容数 MB 的 minified CSS 与 data URI 字符串),命中裸标签选择器(`button`/`table` 等)、裸 `:root`/伪类伪元素(`::-webkit-scrollbar` 等)、通配符 `*`、裸属性选择器、`@import` 引入 reset/normalize 即判违规,非零码退出。已接入 build 门禁(`npm run build` = `tsc -b && npm run check:styles && npm run check:independence && vite build`,双门禁见 §5.9),日常可单独运行:
```bash
npm run check:styles # 退出码 0 = 模块 CSS 无全局选择器违规
```
---
## 5. 模组完全独立互不影响(全维度隔离)
模块在平台中是「挂载即用、卸载即净」的独立单元,任何逃逸到全局的副作用都会污染首页与其它模块。本节是样式隔离(§4)之外的运行时隔离规则,与 `check:styles` 共同构成双门禁。
### 5.1 CSS 选择器命名空间
见 §4——所有选择器必须挂模块根容器类(`.xxx-root`),此处不重复。
### 5.2 CSS 变量与主题令牌作用域
- **禁止**向 `document.documentElement` / `document.body` 写入 CSS 变量、`style`、`classList`。
- 主题令牌(`--xxx` 变量、`background`、`color`、`font-family` 等)一律挂在**模块根容器**或模块内的 `ThemeProvider` 作用域 `div` 上,靠 CSS 继承向下生效。
- 模块卸载(路由切走)后,根容器及其子树从 DOM 移除,所有令牌随之消失,不残留到首页。
- 若源项目用 `document.documentElement.style.setProperty('--xxx', ...)` 切换主题,改为 `rootRef.current?.style.setProperty(...)` 或在根容器上切类。
### 5.3 全局 DOM 写入禁令
- **禁止**修改 `document.body` / `document.documentElement` 的 `style` 或 `classList`(如 `body.style.overflow`、`body.classList.toggle('dark')`)。
- **禁止**向 `document.head` 注入 `<link>`、`<style>`、`<script>` 标签。
- 需要锁滚动、切主题等副作用时,一律作用于模块根容器 `ref`,并在卸载时恢复。
### 5.4 存储 key 必须带模块前缀
- localStorage / sessionStorage 的 key 必须带模块前缀(如 `wuchuan-quotation-v1`、`sp_theme`、`ocDataSourceMode`、`welltrust-qap-*` 等)。
- **白名单**:平台级 `userToken`、`userInfo` 可直接读写,模块不得新增其它无前缀全局 key。
- 切换主题等本地偏好也用前缀 key,不得复用无命名空间的 `theme` / `darkMode`。
### 5.5 事件监听与定时器必须卸载清理
- 所有 `addEventListener`(`window` / `document` / `rootRef`)、`setTimeout`、`setInterval`、`requestAnimationFrame` 必须在 `useEffect` 的返回函数中 `removeEventListener` / `clearTimeout` / `clearInterval` / `cancelAnimationFrame`。
- 模块可被用户随时切走,残留监听器会跨模块执行并导致内存泄漏。
### 5.6 Portal 挂载点必须在模块根容器内部
- 弹窗、抽屉、Tooltip 等 `ReactDOM.createPortal(...)` 的第二个参数(容器)**必须**指向模块根容器内部的节点(如 `rootRef.current` 或根容器内的 `<div id="xxx-portal-root">`)。
- **禁止**挂到 `document.body`——否则模块卸载后 Portal DOM 残留在 body,样式与交互污染全局。
- 若第三方组件默认 portal 到 body,需通过 API 指定 `getContainer` / `appendTo` / `container` 为模块根容器。
### 5.7 document.title 由平台托管
- 模块**不得**自行 `document.title = ...`。
- 平台 `ModuleTitle` 组件在进入模块时设置标题为模块中文名,卸载时恢复 `'EIOSpace'`(见 §7 平台注册)。
### 5.8 第三方全局样式/脚本注入禁令
- 禁止在模块代码中动态 `<script src="...">` 注入第三方 SDK 到 `document.head` / `document.body`(如统计、地图、编辑器);必须用时改为 `import` 打包或挂到模块根容器内。
- 禁止 `@import` 全局 reset / normalize(见 §4.4)。
### 5.9 双门禁(check:styles + check:independence)
| 门禁 | 命令 | 零容忍范围 |
|---|---|---|
| 样式门禁 | `npm run check:styles` | CSS 全局选择器(裸标签、`:root`、`*`、`@import` reset 等,见 §4.5) |
| 独立门禁 | `npm run check:independence` | 全局 DOM 写入(`document.body` / `documentElement` 的 style/classList)、`document.head` 注入 link/style/script、`document.body` Portal、无前缀 storage key |
双门禁已接入 build:
```bash
npm run build # = tsc -b && npm run check:styles && npm run check:independence && vite build
```
日常可单独运行:
```bash
npm run check:independence # 退出码 0 = 无全局 DOM / Portal / 无前缀 storage 违规
```
---
## 6. 代码适配
### 6.1 入口与 Provider
```tsx
// App.tsx 末尾:平台路由直接渲染默认导出,Provider 职责从 main.tsx 移到这里
import { AppProvider } from './app/store'
export default function App() {
return (
<AppProvider>
<AppShell />
</AppProvider>
)
}
```
同时把源 `main.tsx` 的 CSS import 全部搬到模块 `App.tsx` 顶部(保持原有顺序)。
### 6.2 严格 tsconfig 适配(tsc -b 报错清单)
- `TS6133` 未使用变量/import → 删除(含解构中未使用的成员)
- `TS2554`:`useRef<T>()` → `useRef<T | undefined>(undefined)`(@types/react 19 要求初始值)
- 默认导入 `import React` 未使用 → 删除(react-jsx transform 无需)
### 6.3 其他常见点
- 事件监听/定时器在组件卸载时清理(模块可被随时切走)
- 弹窗内 `dangerouslySetInnerHTML` 注入的 HTML,其类名也要被命名空间 CSS 覆盖(确认前缀后仍能匹配)
- 内部 state 切页的项目保留原交互,不强行改造为 URL 路由
---
## 7. 平台注册(三件套 + 图标)
```ts
// 1. src/modules/<name>/index.ts
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: '<name>',
name: '模块中文名',
description: '一句话描述',
icon: 'Lucide图标名', // 如 FileSpreadsheet / Radar / Building2
path: '/<name>',
accentColor: '#7C6FFF', // 暗色强调色
accentColorLight: '#5747EF', // 亮色强调色
gradient: 'linear-gradient(135deg, ...)', // 暗色卡片渐变
gradientLight: 'linear-gradient(135deg, ...)', // 亮色卡片渐变
tags: ['标签1', '标签2'],
};
```
```ts
// 2. src/modules/registry.ts:import + modules 数组追加
// 3. src/App.tsx:模块级 React.lazy 动态导入 + 路由(ModuleTitle 负责页签标题,卸载恢复 'EIOSpace')
const XxxApp = lazy(() => import('@/modules/<name>/App'));
...
<Routes>
<Suspense fallback={<ModuleLoading />}>
<Route path="/<name>" element={<RequireAuth><ModuleTitle title="模块中文名"><XxxApp /></ModuleTitle></RequireAuth>} />
...
</Suspense>
</Routes>
// 4. src/pages/HomePage.tsx:ICON_MAP 增加图标(先在 lucide-react import 中补图标名)
```
> 模块入口必须用 `React.lazy` 动态导入(模块 CSS 随路由 chunk 按需加载),**静态 import 会把模块 CSS 打进主包,禁止**。
> 首页卡片点击已是 `window.open(mod.path, '_blank')` 新页签打开,无需额外处理。
---
## 8. 验证清单
**构建层**
- [ ] `npx tsc --noEmit` 通过
- [ ] `npm run build` 通过(注意 `tsc -b` 比 `tsc --noEmit` 更严,以 build 为准;已含 `check:styles` + `check:independence` 双门禁)
- [ ] `npm run check:styles` 退出码 0(模块 CSS 全局选择器零容忍门禁,见 §4.5,已接入 build)
- [ ] `npm run check:independence` 退出码 0(全局 DOM 写入 / body Portal / 无前缀 storage key 零容忍门禁,见 §5.9,已接入 build)
- [ ] `dist/mod-assets/<name>/` 资源齐全
- [ ] **`ls dist/` 确认根目录下没有与模块路由同名的目录**(防端口泄漏,见 §3)
**浏览器层**(dev server + mock 登录)
```js
// 平台守卫只查 sessionStorage.userToken,浏览器验证先注入:
sessionStorage.setItem('userToken', 'mock-token-for-ui-check');
sessionStorage.setItem('userInfo', JSON.stringify({ name: '演示用户', userId: 'demo' }));
```
- [ ] `/<name>` 页面完整渲染(header/侧栏/内容区),控制台无 React 报错、无 404
- [ ] 页内交互可用(菜单切换、弹窗、主题切换)
- [ ] 新页签打开后浏览器标题为模块中文名
- [ ] 首页出现新模块卡片(图标、配色正确)
- [ ] 首页(未进入任何模块)Network 面板无任何模块级 CSS chunk
- [ ] 首次进入模块路由时按需加载对应 JS+CSS chunk(React.lazy 生效)
- [ ] **进入模块再返回首页,首页视觉无污染**(body class/style 无残留、CSS 变量无残留、无 Portal 残留 DOM)
- [ ] **弹窗/抽屉等 Portal 的 DOM 位于模块根容器内部**(Elements 面板检查,非 `document.body` 直接子节点)
**回归层(改了旧模块 CSS 时必做)**
- [ ] 新模块关键布局 computed style 复核(如 nav 的 display)
- [ ] 被 CSS 影响的旧模块核心页面正常(如 supplier 顶栏导航)
- [ ] 平台首页/登录页样式未受污染
---
## 9. 部署注意(nginx)
- `nginx.conf` SPA 回退必须是 `try_files $uri /index.html;`——**禁止 `$uri/`**(目录命中 → 403 且不回退)
- **必须加两条重定向加固**(防止容器内端口泄漏到浏览器地址栏,2026-10 事故根因):
```nginx
server {
listen 8901;
...
port_in_redirect off; # 301 重定向的 Location 不带 8901 端口
absolute_redirect off; # 使用相对路径 Location,彻底避免泄漏 host/port
}
```
- 部署后用生产地址冒烟验证(新页签打开路径):
```bash
curl -sI https://ai-workshop.digiwincloud.com.cn/<name> | head -5
# 期望:HTTP 200(或 302 跳登录页)
# 异常信号:HTTP 301 且 Location 带 :8901 —— 即存在与路由同名的静态目录触发了目录重定向
```
- 模块静态资源引用用绝对路径 `/mod-assets/...`,与部署子路径无关
---
## 10. 历史踩坑速查表
| 案例 | 坑 | 修复 |
|---|---|---|
| baode-web ↔ supplier-platform | baode 自检页 `.page{max-width:1080px}` 污染 supplier 的 `section.page` | `.page`→`.checkpage` + 冲突类加 `.baode-root` 前缀 |
| supplier-platform | 源 tsconfig 宽松,`useRef<T>()` 在 @types/react 19 下报 TS2554 | `useRef<T \| undefined>(undefined)` |
| 全部模块 | dist 下与路由同名目录:早期 `try_files $uri/` 命中目录 403;去掉 `$uri/` 后 `$uri` 仍命中目录触发 301 补斜杠,`port_in_redirect` 默认 on 把容器端口 `:8901` 泄漏进浏览器地址栏,新页签跳到带端口地址后 403/空白 | 资源统一迁 `mod-assets/`;nginx 加 `port_in_redirect off; absolute_redirect off;` |
| wuc-quotation | 漏迁 `AppProvider` → 白屏 `ctx is null` | Provider 移入模块默认导出 |
| wuc-quotation | 001.css 7.8MB 内嵌 data URI + minified,正则替换会破坏资产 | 状态机解析转换,字符串原样保留 |
| wuc-quotation | `document.body.classList.toggle('dark')` 污染平台 body | 改挂 `.wuc-root` 根容器 ref |
| wuc-quotation | `@media` 内规则未递归前缀化(首版转换脚本 bug) | 递归处理 + 转换后自动校验 |
| wuc-quotation ↔ supplier-platform | `#nav` ID 特异性碾压类前缀,菜单被改 flex 水平 | 旧模块规则改 `.hansong-app #nav`;SOP 增加 ID 冲突检测 |
| jieya-ibp / welltrust-qap | sql.js wasm 路径、logo 相对路径失效 | 统一 `locateFile: () => '/mod-assets/<name>/...'` |
| 全部模块 | 模块 CSS 全局选择器(`:root`/`button`/`table`/`::-webkit-scrollbar`/`*`)跨模块污染 | 加模块根容器前缀 + `check:styles` 门禁(§4.5,已接入 build) |
+4 -2
View File
@@ -5,8 +5,10 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && npm run check:styles && npm run check:independence && vite build",
"preview": "vite preview" "preview": "vite preview",
"check:styles": "node scripts/check-module-styles.mjs",
"check:independence": "node scripts/check-module-independence.mjs"
}, },
"dependencies": { "dependencies": {
"@ant-design/icons": "^5.4.0", "@ant-design/icons": "^5.4.0",
+349
View File
@@ -0,0 +1,349 @@
#!/usr/bin/env node
/**
* 模组独立性检查(门禁脚本)
*
* 平台规则:src/modules 下每个模组必须完全独立、互不影响,禁止运行时写入全局 DOM、
* 向 head 注入全局样式/脚本、将 Portal 挂到 document.body、使用无前缀的 storage key。
*
* 实现:先做词法剥离(注释 + 字符串/模板字面量),再用正则检测违规模式。
* 零依赖,Node >= 18。
*/
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MODULES_DIR = path.join(ROOT, 'src', 'modules');
const EXTS = new Set(['.ts', '.tsx', '.js', '.jsx']);
// 平台级共享 storage key 白名单(不计模组前缀)
const STORAGE_WHITELIST = new Set(['userToken', 'userInfo']);
/* ---------------------------------- 文件收集 ---------------------------------- */
function collectFiles(dir, out = []) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
collectFiles(full, out);
} else if (entry.isFile() && EXTS.has(path.extname(entry.name))) {
out.push(full);
}
}
return out;
}
/* -------------------------------- 词法剥离 -------------------------------- */
/**
* 剥离源码中的注释与字符串/模板字面量,保留换行以维持行号对齐。
* 返回两份结果:
* - commentStripped:仅去掉 // 与 /* *\/ 注释,字符串内容保留(用于需要读取
* 字符串字面量的检查,如 storage key、createElement 标签名)。
* - fullyStripped:注释 + 字符串/模板全部替换为空格(用于避免字符串内关键字误报)。
*
* 被剥离的非换行字符统一替换为空格,保证字符偏移与行号不变。
*/
function stripSource(source) {
let commentStripped = '';
let fullyStripped = '';
let inBlockComment = false;
let inTemplate = false;
let i = 0;
const pushSpace = (ch) => {
const sp = ch === '\n' ? '\n' : ' ';
commentStripped += sp;
fullyStripped += sp;
};
while (i < source.length) {
const ch = source[i];
const next = source[i + 1];
if (inBlockComment) {
if (ch === '*' && next === '/') {
inBlockComment = false;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
} else {
pushSpace(ch);
i++;
}
continue;
}
if (inTemplate) {
if (ch === '\\') {
// 转义字符整体跳过
commentStripped += ch + (next || '');
fullyStripped += ' ' + (next === '\n' ? '\n' : ' ');
i += 2;
continue;
}
if (ch === '`') {
inTemplate = false;
pushSpace(ch);
i++;
continue;
}
if (ch === '$' && next === '{') {
// 模板插值:按大括号深度跳过(插值内代码也一并剥离)
let depth = 1;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
while (i < source.length && depth > 0) {
const c = source[i];
if (c === '{') depth++;
else if (c === '}') depth--;
pushSpace(c);
i++;
}
continue;
}
pushSpace(ch);
i++;
continue;
}
// —— 普通代码态 ——
if (ch === '/' && next === '/') {
// 行注释:跳到行尾
while (i < source.length && source[i] !== '\n') {
commentStripped += ' ';
fullyStripped += ' ';
i++;
}
continue;
}
if (ch === '/' && next === '*') {
inBlockComment = true;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
continue;
}
if (ch === '`') {
inTemplate = true;
pushSpace(ch);
i++;
continue;
}
if (ch === '"' || ch === "'") {
const quote = ch;
commentStripped += ch; // commentStripped 保留字符串内容
fullyStripped += ' ';
i++;
while (i < source.length) {
const c = source[i];
if (c === '\\') {
commentStripped += c + (source[i + 1] || '');
fullyStripped += ' ' + (source[i + 1] === '\n' ? '\n' : ' ');
i += 2;
continue;
}
if (c === quote) {
commentStripped += quote;
fullyStripped += ' ';
i++;
break;
}
if (c === '\n') {
// 字符串跨行(非法 JS,但容错)
commentStripped += '\n';
fullyStripped += '\n';
i++;
continue;
}
commentStripped += c;
fullyStripped += ' ';
i++;
}
continue;
}
commentStripped += ch;
fullyStripped += ch;
i++;
}
return { commentStripped, fullyStripped };
}
/* ------------------------------ 工具:顶层逗号切分 ------------------------------ */
/** 按顶层逗号切分参数列表,括号/方括号/花括号内的逗号不切分。 */
function splitTopLevel(s) {
const parts = [];
let cur = '';
let paren = 0, bracket = 0, brace = 0;
for (const ch of s) {
if (ch === '(') paren++;
else if (ch === ')') paren--;
else if (ch === '[') bracket++;
else if (ch === ']') bracket--;
else if (ch === '{') brace++;
else if (ch === '}') brace--;
if (ch === ',' && paren === 0 && bracket === 0 && brace === 0) {
parts.push(cur);
cur = '';
continue;
}
cur += ch;
}
parts.push(cur);
return parts;
}
/** 计算字符串中 index 位置对应的行号(1-based)。 */
function lineAt(text, index) {
let line = 1;
for (let k = 0; k < index && k < text.length; k++) {
if (text[k] === '\n') line++;
}
return line;
}
/* -------------------------------- 违规判定 -------------------------------- */
/**
* 判定 storage key 是否合规:
* - 在白名单内;或
* - 包含 - / _ / . ;或
* - 匹配小写驼峰模块前缀 ^[a-z]{2,}[A-Z](如 ocDataSourceMode)。
*/
function isStorageKeyCompliant(key) {
if (STORAGE_WHITELIST.has(key)) return true;
if (/[-_.]/.test(key)) return true;
if (/^[a-z]{2,}[A-Z]/.test(key)) return true;
return false;
}
/**
* 扫描单个文件,返回违规列表 [{ line, reason }]。
*/
function scanFile(source) {
const violations = [];
const { commentStripped, fullyStripped } = stripSource(source);
const commentLines = commentStripped.split('\n');
const fullyLines = fullyStripped.split('\n');
// —— 预扫描:收集被赋值为 createElement('link'|'style'|'script') 的变量名 ——
// 用于跨行判定 document.head.appendChild(var) 是否为注入全局样式/脚本。
const injectVars = new Set();
const assignRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*document\.createElement\s*\(\s*['"`](link|style|script)['"`]/g;
for (const line of commentLines) {
let m;
while ((m = assignRe.exec(line)) !== null) {
injectVars.add(m[1]);
}
}
// —— 逐行检测(a / b / c / e)——
for (let idx = 0; idx < fullyLines.length; idx++) {
const lineNo = idx + 1;
const fLine = fullyLines[idx];
const cLine = commentLines[idx];
// a. document.body.(style|classList).
if (/document\.body\.(style|classList)\./.test(fLine)) {
violations.push({ line: lineNo, reason: '写入 document.body 的 style/classList(应仅作用于模组根容器)' });
}
// b. document.documentElement.(style|setAttribute|classList).
if (/document\.documentElement\.(style|setAttribute|classList)\./.test(fLine)) {
violations.push({ line: lineNo, reason: '写入 document.documentElement 的 style/setAttribute/classList(CSS 变量应挂在模组根容器)' });
}
// c. document.head.appendChild/insertBefore 注入 link/style/script
if (/document\.head\.(appendChild|insertBefore)\s*\(/.test(cLine)) {
// 同行内是否直接 createElement('link'|'style'|'script')
const inlineInject = /createElement\s*\(\s*['"`](link|style|script)['"`]/.test(cLine);
// 或参数为前面收集到的注入变量
let varInject = false;
if (!inlineInject) {
const argMatch = cLine.match(/document\.head\.(?:appendChild|insertBefore)\s*\(\s*([A-Za-z_$][\w$]*)/);
if (argMatch && injectVars.has(argMatch[1])) varInject = true;
}
if (inlineInject || varInject) {
violations.push({ line: lineNo, reason: '向 document.head 注入 link/style/script 元素(禁止模组注入全局样式/脚本)' });
}
}
// e. localStorage/sessionStorage key 无前缀
const storageRe = /(local|session)Storage\.(getItem|setItem|removeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g;
let sm;
while ((sm = storageRe.exec(cLine)) !== null) {
const key = sm[3];
if (!isStorageKeyCompliant(key)) {
violations.push({ line: lineNo, reason: `storage key「${key}」未带模组前缀(需含 -/_/. 或以小写驼峰模块名开头)` });
}
}
}
// —— 整段检测(d. createPortal 第二参数为 document.body,可能跨多行)——
const portalRe = /createPortal\s*\(/g;
let pm;
while ((pm = portalRe.exec(fullyStripped)) !== null) {
const start = pm.index;
let depth = 1;
let j = start + pm[0].length;
while (j < fullyStripped.length && depth > 0) {
const c = fullyStripped[j];
if (c === '(') depth++;
else if (c === ')') depth--;
j++;
}
if (depth === 0) {
const args = fullyStripped.slice(start + pm[0].length, j - 1);
const parts = splitTopLevel(args);
// 第二参数为 Portal 挂载容器:若其中出现 document.body(含兜底表达式
// 如 portalMount ?? document.body),即视为挂到全局 body,判违规。
if (parts.length >= 2 && /\bdocument\.body\b/.test(parts[1])) {
const lineNo = lineAt(fullyStripped, start);
violations.push({ line: lineNo, reason: 'createPortal 挂载点含 document.body(Portal 应挂在模组根容器内,禁止兜底到全局 body)' });
}
}
}
return violations;
}
/* ------------------------------------ 主流程 ----------------------------------- */
function main() {
const files = collectFiles(MODULES_DIR).sort();
const violations = [];
for (const file of files) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
const source = readFileSync(file, 'utf8');
const fileViolations = scanFile(source);
for (const v of fileViolations) {
violations.push(`[违规] ${rel}:${v.line} ${v.reason}`);
}
}
if (violations.length > 0) {
for (const v of violations) console.log(v);
const badFiles = new Set(violations.map((v) => v.split(':')[0].replace('[违规] ', ''))).size;
console.log(
`[汇总] 模组独立检查失败:共 ${violations.length} 条违规,涉及 ${badFiles} 个文件(共扫描 ${files.length} 个文件)`,
);
process.exit(1);
}
console.log(`✓ 模组独立检查通过(扫描 ${files.length} 个文件)`);
process.exit(0);
}
main();
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env node
/**
* 模块样式命名空间检查(门禁脚本)
*
* 平台规则:src/modules 下所有 .css 中选择器必须挂在模块根容器类(命名空间)下,
* 禁止全局作用选择器(裸标签 / :root / 通配符 / 裸伪类 / 裸属性选择器等)跨模块污染。
*
* 实现:状态机逐字符解析(模块内存在数 MB 的 minified CSS,含大量 data URI
* 字符串与花括号,不能依赖简单正则)。零依赖,Node >= 18。
*/
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MODULES_DIR = path.join(ROOT, 'src', 'modules');
const MAX_LEN = 80;
/* ---------------------------------- 文件收集 ---------------------------------- */
function collectCssFiles(dir) {
const out = [];
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
out.push(...collectCssFiles(full));
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.css')) {
out.push(full);
}
}
return out;
}
/* --------------------------------- 选择器判定 --------------------------------- */
/**
* 判定单个选择器(已 trim)是否为全局作用选择器。
* 返回 null 表示合法(挂在类/ID 命名空间下),否则返回原因字符串。
*/
function classifySelector(sel) {
if (!sel || sel.startsWith('@')) return null;
// 裸伪类/伪元素::root、:focus-visible、::-webkit-scrollbar 等,等价于通配符
if (sel.startsWith(':')) {
if (/^:root(?![a-zA-Z0-9_-])/.test(sel)) return '裸 :root 选择器(全局作用)';
return '裸伪类/伪元素(等价于通配符,全局作用)';
}
if (sel.startsWith('*')) return '通配符 *(全局作用)';
if (sel.startsWith('[')) return '裸属性选择器(全局作用)';
// 裸标签:首 token 匹配 /^[a-zA-Z][a-zA-Z0-9-]*$/ 且不是 CSS 函数(后面紧跟 "(")
const m = sel.match(/^[a-zA-Z][a-zA-Z0-9-]*/);
if (m) {
const next = sel.charAt(m[0].length);
if (next !== '(') {
return `裸标签选择器「${m[0]}」(未挂在模块根容器下)`;
}
}
return null;
}
/**
* 按顶层逗号拆分选择器列表:括号 ( ) 与属性选择器 [ ] 内的逗号不拆分,
* 引号字符串内的逗号不拆分。
*/
function splitTopLevelCommas(s) {
const parts = [];
let cur = '';
let paren = 0;
let bracket = 0;
let quote = null;
let escaped = false;
for (const ch of s) {
if (quote) {
cur += ch;
if (escaped) escaped = false;
else if (ch === '\\') escaped = true;
else if (ch === quote) quote = null;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
cur += ch;
continue;
}
if (ch === '(') paren++;
else if (ch === ')') paren = Math.max(0, paren - 1);
else if (ch === '[') bracket++;
else if (ch === ']') bracket = Math.max(0, bracket - 1);
if (ch === ',' && paren === 0 && bracket === 0) {
parts.push(cur);
cur = '';
continue;
}
cur += ch;
}
parts.push(cur);
return parts;
}
function truncate(s) {
return s.length > MAX_LEN ? `${s.slice(0, MAX_LEN - 3)}...` : s;
}
/* --------------------------------- 状态机解析 --------------------------------- */
/**
* 逐字符解析 CSS 文本。
* - 跳过块注释与字符串内容(data URI 中的 { } ; ( ) 不影响结构);
* - 跟踪大括号深度与栈帧:'media'(@media/@supports 内继续扫描)、
* 'rule'(普通规则块,声明不扫描)、'skip'(@keyframes/@font-face 等块内不扫描);
* - prelude("{" 之前的文本)在扫描态下累积,用于选择器判定与 @import 检查。
*
* onRule(prelude, line) —— 每条普通规则回调;
* onImport(prelude, line) —— 每条顶层(或 @media 内)@import 回调。
*/
function parseCss(source, onRule, onImport) {
const stack = [];
let prelude = '';
let preludeLine = -1;
let line = 1;
let inComment = false;
let quote = null;
let escaped = false;
const scanMode = () => stack.length === 0 || stack[stack.length - 1] === 'media';
const resetPrelude = () => {
prelude = '';
preludeLine = -1;
};
for (let i = 0; i < source.length; i++) {
const ch = source[i];
if (ch === '\n') line++;
if (inComment) {
if (ch === '*' && source[i + 1] === '/') {
inComment = false;
i++;
}
continue;
}
if (quote) {
// 字符串内容原样跳过(不解析其中的 { } ; 等);
// 为支持 @import 目标检查,扫描态下仍原样记录进 prelude。
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === quote) {
quote = null;
}
if (scanMode()) prelude += ch;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
if (scanMode()) {
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
prelude += ch;
}
continue;
}
if (ch === '/' && source[i + 1] === '*') {
inComment = true;
i++;
continue;
}
if (ch === '{') {
const trimmed = prelude.trim();
let frame;
if (scanMode() && trimmed.startsWith('@')) {
const m = trimmed.match(/^@([a-zA-Z0-9-]+)/);
const name = m ? m[1].toLowerCase() : '';
// @media / @supports 递归继续扫描内部规则;其余 at-rule 跳过块内选择器
frame = name === 'media' || name === 'supports' ? 'media' : 'skip';
} else if (scanMode()) {
if (trimmed) onRule(trimmed, preludeLine === -1 ? line : preludeLine);
frame = 'rule';
} else {
frame = 'skip';
}
stack.push(frame);
resetPrelude();
continue;
}
if (ch === '}') {
if (stack.length) stack.pop();
resetPrelude();
continue;
}
if (ch === ';') {
if (scanMode()) {
const trimmed = prelude.trim();
if (/^@import\b/.test(trimmed)) {
onImport(trimmed, preludeLine === -1 ? line : preludeLine);
}
}
resetPrelude();
continue;
}
if (scanMode()) {
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
prelude += ch;
}
}
}
/* ------------------------------------ 主流程 ----------------------------------- */
function main() {
const files = collectCssFiles(MODULES_DIR).sort();
const violations = [];
const addViolation = (rel, line, selector, reason) => {
violations.push(`[违规] ${rel}:${line} ${truncate(selector)} ${reason}`);
};
for (const file of files) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
const source = readFileSync(file, 'utf8');
parseCss(
source,
(prelude, line) => {
for (const part of splitTopLevelCommas(prelude)) {
const sel = part.trim();
const reason = classifySelector(sel);
if (reason) addViolation(rel, line, sel, reason);
}
},
(prelude, line) => {
if (/(^|[^a-z0-9])(reset|normalize)/i.test(prelude)) {
addViolation(rel, line, prelude, '@import 引入 reset/normalize 样式(全局污染)');
}
},
);
}
if (violations.length > 0) {
for (const v of violations) console.log(v);
const badFiles = new Set(violations.map((v) => v.split(' ')[0])).size;
console.log(
`[汇总] 模块样式命名空间检查失败:共 ${violations.length} 条违规,涉及 ${badFiles} 个文件(共扫描 ${files.length} 个文件)`,
);
process.exit(1);
}
console.log(`✓ 模块样式检查通过(扫描 ${files.length} 个文件)`);
process.exit(0);
}
main();
+47 -14
View File
@@ -1,26 +1,58 @@
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom'; import { Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage'; import HomePage from '@/pages/HomePage';
import SSOLogin from '@/pages/SSOLogin'; import SSOLogin from '@/pages/SSOLogin';
import LoginPage from '@/pages/LoginPage'; import LoginPage from '@/pages/LoginPage';
import RequireAuth from '@/shared/components/RequireAuth'; import RequireAuth from '@/shared/components/RequireAuth';
import ModuleTitle from '@/shared/components/ModuleTitle'; import ModuleTitle from '@/shared/components/ModuleTitle';
import AIMCockpit from '@/modules/ai-matching/pages/AIMCockpit';
import CostCockpit from '@/modules/cost-analysis/pages/CostCockpit'; const AIMCockpit = lazy(() => import('@/modules/ai-matching/pages/AIMCockpit'));
import KnowledgeGraphHome from '@/modules/knowledge-graph/pages/KnowledgeGraphHome'; const CostCockpit = lazy(() => import('@/modules/cost-analysis/pages/CostCockpit'));
import SpaceCockpit from '@/modules/knowledge-graph/pages/SpaceCockpit'; const KnowledgeGraphHome = lazy(() => import('@/modules/knowledge-graph/pages/KnowledgeGraphHome'));
import BomxReuseHome from '@/modules/bomx-reuse-analyzer/pages/BomxReuseHome'; const SpaceCockpit = lazy(() => import('@/modules/knowledge-graph/pages/SpaceCockpit'));
import CostCockpitFull from '@/modules/order-cost-analysis/pages/CostCockpitFull'; const BomxReuseHome = lazy(() => import('@/modules/bomx-reuse-analyzer/pages/BomxReuseHome'));
import AIMCockpitFull from '@/modules/order-cost-analysis/pages/AIMCockpitFull'; const CostCockpitFull = lazy(() => import('@/modules/order-cost-analysis/pages/CostCockpitFull'));
import BexellSchedulingApp from '@/modules/bexell-scheduling-ai/App'; const AIMCockpitFull = lazy(() => import('@/modules/order-cost-analysis/pages/AIMCockpitFull'));
import SanruiAIDesignHome from '@/modules/sanrui-ai-design/pages/SanruiAIDesignHome'; const BexellSchedulingApp = lazy(() => import('@/modules/bexell-scheduling-ai/App'));
import JieyaIbpApp from '@/modules/jieya-ibp/App'; const SanruiAIDesignHome = lazy(() => import('@/modules/sanrui-ai-design/pages/SanruiAIDesignHome'));
import WelltrustQapApp from '@/modules/welltrust-qap/App'; const JieyaIbpApp = lazy(() => import('@/modules/jieya-ibp/App'));
import BaodeWebApp from '@/modules/baode-web/App'; const WelltrustQapApp = lazy(() => import('@/modules/welltrust-qap/App'));
import SupplierPlatformApp from '@/modules/supplier-platform/App'; const BaodeWebApp = lazy(() => import('@/modules/baode-web/App'));
import WucQuotationApp from '@/modules/wuc-quotation/App'; const SupplierPlatformApp = lazy(() => import('@/modules/supplier-platform/App'));
const WucQuotationApp = lazy(() => import('@/modules/wuc-quotation/App'));
function ModuleLoading() {
const spinnerStyle: React.CSSProperties = {
width: 44,
height: 44,
border: '3px solid rgba(0, 212, 255, 0.2)',
borderTopColor: '#00d4ff',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
};
return (
<div
style={{
position: 'fixed',
inset: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 18,
background: '#000a1e',
zIndex: 9999,
}}
>
<div style={spinnerStyle} />
<div style={{ color: '#00d4ff', fontSize: 14, letterSpacing: 2 }}>模块加载中…</div>
</div>
);
}
export default function App() { export default function App() {
return ( return (
<Suspense fallback={<ModuleLoading />}>
<Routes> <Routes>
<Route path="/login" element={<LoginPage />} /> <Route path="/login" element={<LoginPage />} />
<Route path="/sso-login" element={<SSOLogin />} /> <Route path="/sso-login" element={<SSOLogin />} />
@@ -40,5 +72,6 @@ export default function App() {
<Route path="/supplier-platform" element={<RequireAuth><ModuleTitle title="供应商智能管控平台"><SupplierPlatformApp /></ModuleTitle></RequireAuth>} /> <Route path="/supplier-platform" element={<RequireAuth><ModuleTitle title="供应商智能管控平台"><SupplierPlatformApp /></ModuleTitle></RequireAuth>} />
<Route path="/wuc-quotation" element={<RequireAuth><ModuleTitle title="武船AI智能报价平台"><WucQuotationApp /></ModuleTitle></RequireAuth>} /> <Route path="/wuc-quotation" element={<RequireAuth><ModuleTitle title="武船AI智能报价平台"><WucQuotationApp /></ModuleTitle></RequireAuth>} />
</Routes> </Routes>
</Suspense>
); );
} }
+3 -3
View File
@@ -177,7 +177,7 @@
flex: none; width: 18px; height: 18px; border-radius: 50%; flex: none; width: 18px; height: 18px; border-radius: 50%;
display: grid; place-items: center; font-size: 11px; color: #fff; background: #cbd5e1; display: grid; place-items: center; font-size: 11px; color: #fff; background: #cbd5e1;
} }
.s-执行中 .fnode-dot { background: var(--brand); animation: pulse 1.6s ease-in-out infinite; } .s-执行中 .fnode-dot { background: var(--brand); animation: baode-pulse 1.6s ease-in-out infinite; }
.s-等待填报 .fnode-dot { background: var(--wait); } .s-等待填报 .fnode-dot { background: var(--wait); }
.s-待补全 .fnode-dot { background: var(--cta); } .s-待补全 .fnode-dot { background: var(--cta); }
.s-已完成 .fnode-dot { background: var(--pass); } .s-已完成 .fnode-dot { background: var(--pass); }
@@ -386,10 +386,10 @@
.checkpage .fail { color: var(--fail); font-weight: 600; } .checkpage .fail { color: var(--fail); font-weight: 600; }
@keyframes floatIn { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } } @keyframes floatIn { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } }
@keyframes pulse { @keyframes baode-pulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.35); } 0%, 100% { box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.35); }
50% { box-shadow: 0 0 0 6px rgba(37, 99, 235, 0); } 50% { box-shadow: 0 0 0 6px rgba(37, 99, 235, 0); }
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; } .baode-root * { animation: none !important; transition: none !important; }
} }
@@ -2,8 +2,13 @@ import { useEffect } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { IconX } from './Icons'; import { IconX } from './Icons';
// 使用 Portal 渲染到 body,避免被父级层叠上下文/导航条遮挡 // Portal 渲染到模块根容器内的挂载点(必传 portalMount),
export default function Drawer({ open, title, onClose, children, width = 540 }: any) { // 保持 DOM 节点位于模块作用域内,禁止挂到 document.body
export default function Drawer({ open, title, onClose, children, width = 540, portalMount }: {
open: boolean; title?: React.ReactNode; onClose: () => void;
children?: React.ReactNode; width?: number;
portalMount: HTMLDivElement;
}) {
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
@@ -12,7 +17,9 @@ export default function Drawer({ open, title, onClose, children, width = 540 }:
}, [open, onClose]); }, [open, onClose]);
return createPortal( return createPortal(
<> // 模块根容器包裹层:为 portal 内容提供 .bomx-app 作用域下的 CSS 变量;
// overlay/panel 均 position:fixed,且平台 body 为 overflow:hidden,包裹层不影响布局
<div className="bomx-app">
{/* 遮罩:覆盖全屏(含导航条),点击任意非抽屉区域关闭 */} {/* 遮罩:覆盖全屏(含导航条),点击任意非抽屉区域关闭 */}
{open && <div className="drawer-overlay" onClick={onClose} />} {open && <div className="drawer-overlay" onClick={onClose} />}
@@ -29,7 +36,7 @@ export default function Drawer({ open, title, onClose, children, width = 540 }:
</div> </div>
<div className="drawer-content">{children}</div> <div className="drawer-content">{children}</div>
</div> </div>
</>, </div>,
document.body portalMount
); );
} }
@@ -1,4 +1,4 @@
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { initStore } from '../core/store'; import { initStore } from '../core/store';
import BomBrowser from '../components/BomBrowser'; import BomBrowser from '../components/BomBrowser';
@@ -47,6 +47,9 @@ export default function BomxReuseHome() {
const [loadError, setLoadError] = useState<any>(null); const [loadError, setLoadError] = useState<any>(null);
const [fadingOut, setFadingOut] = useState(false); const [fadingOut, setFadingOut] = useState(false);
// Drawer Portal 挂载点:位于 .bomx-app 根容器内部,使 Drawer DOM 节点留在模块作用域内
const portalMountRef = useRef<HTMLDivElement>(null);
const loadData = useCallback(async (sourceKey: string) => { const loadData = useCallback(async (sourceKey: string) => {
setLoading(true); setLoading(true);
setFadingOut(false); setFadingOut(false);
@@ -164,6 +167,9 @@ export default function BomxReuseHome() {
</div> </div>
<ToastContainer /> <ToastContainer />
{/* Drawer Portal 挂载点:Drawer 通过 createPortal 将内容渲染到此节点内 */}
<div ref={portalMountRef} />
{data && ( {data && (
<div className="data-source-switch"> <div className="data-source-switch">
<select <select
+13 -13
View File
@@ -3,7 +3,7 @@
风格:Premium Light · 深度层次 · 流畅交互 风格:Premium Light · 深度层次 · 流畅交互
============================================================ */ ============================================================ */
:root { .bomx-app {
--header-h: 64px; --header-h: 64px;
/* 品牌渐变 */ /* 品牌渐变 */
--grad-brand: linear-gradient(135deg, #6366F1 0%, #8B5CF6 50%, #A855F7 100%); --grad-brand: linear-gradient(135deg, #6366F1 0%, #8B5CF6 50%, #A855F7 100%);
@@ -85,9 +85,9 @@
z-index: 0; z-index: 0;
} }
::-webkit-scrollbar { width: 8px; height: 8px; } .bomx-app ::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-thumb { background: var(--line-2); border-radius: 4px; } .bomx-app ::-webkit-scrollbar-thumb { background: var(--line-2); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-3); } .bomx-app ::-webkit-scrollbar-thumb:hover { background: var(--text-3); }
/* ===== Header ===== */ /* ===== Header ===== */
.app-header { .app-header {
@@ -260,7 +260,7 @@
.btn-sm { height: 32px; padding: 0 13px; font-size: 12px; border-radius: var(--r-sm); } .btn-sm { height: 32px; padding: 0 13px; font-size: 12px; border-radius: var(--r-sm); }
/* ===== Form ===== */ /* ===== Form ===== */
input[type="text"], input[type="number"], select { .bomx-app input[type="text"], .bomx-app input[type="number"], .bomx-app select {
height: 38px; height: 38px;
padding: 0 13px; padding: 0 13px;
border: 1px solid var(--line-2); border: 1px solid var(--line-2);
@@ -273,7 +273,7 @@ input[type="text"], input[type="number"], select {
transition: all var(--t-fast) var(--ease); transition: all var(--t-fast) var(--ease);
} }
input:focus, select:focus { .bomx-app input:focus, .bomx-app select:focus {
border-color: var(--indigo); border-color: var(--indigo);
box-shadow: 0 0 0 3px rgba(99,102,241,0.14); box-shadow: 0 0 0 3px rgba(99,102,241,0.14);
} }
@@ -589,7 +589,7 @@ input:focus, select:focus {
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @keyframes bomx-fade-in { from { opacity: 0; } to { opacity: 1; } }
.drawer { .drawer {
position: fixed; position: fixed;
@@ -645,7 +645,7 @@ input:focus, select:focus {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
animation: fade-in 0.2s ease; animation: bomx-fade-in 0.2s ease;
} }
.confirm-modal { .confirm-modal {
@@ -743,10 +743,10 @@ input:focus, select:focus {
.checkbox-label { display: inline-flex; align-items: center; gap: 7px; cursor: pointer; } .checkbox-label { display: inline-flex; align-items: center; gap: 7px; cursor: pointer; }
.checkbox-label input { width: 16px; height: 16px; accent-color: var(--indigo); cursor: pointer; } .checkbox-label input { width: 16px; height: 16px; accent-color: var(--indigo); cursor: pointer; }
:focus-visible { outline: 2px solid var(--indigo); outline-offset: 2px; } .bomx-app :focus-visible { outline: 2px solid var(--indigo); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } .bomx-app *, .bomx-app *::before, .bomx-app *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
} }
/* ===== 修复:BOM 树表头列样式统一 ===== */ /* ===== 修复:BOM 树表头列样式统一 ===== */
@@ -896,11 +896,11 @@ input:focus, select:focus {
border: 2.5px solid var(--line-1); border: 2.5px solid var(--line-1);
border-top-color: var(--accent-primary); border-top-color: var(--accent-primary);
border-radius: 50%; border-radius: 50%;
animation: spin 0.8s linear infinite; animation: bomx-spin 0.8s linear infinite;
flex-shrink: 0; flex-shrink: 0;
} }
@keyframes spin { @keyframes bomx-spin {
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
} }
@@ -1168,7 +1168,7 @@ input:focus, select:focus {
border: 2px solid var(--indigo-soft); border: 2px solid var(--indigo-soft);
border-top-color: var(--indigo); border-top-color: var(--indigo);
border-radius: 50%; border-radius: 50%;
animation: spin 0.7s linear infinite; animation: bomx-spin 0.7s linear infinite;
} }
/* 阶段信息 */ /* 阶段信息 */
+2 -2
View File
@@ -82,7 +82,7 @@ function AppInner() {
if (!dbReady) { if (!dbReady) {
const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null); const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null);
return ( return (
<div style={{ <div className="jieya-root" style={{
width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14, background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14,
}}> }}>
@@ -116,7 +116,7 @@ function AppInner() {
} }
return ( return (
<div style={{ <div className="jieya-root" style={{
width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column', width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column',
background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden', background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden',
position: 'relative', position: 'relative',
+14 -13
View File
@@ -1,5 +1,5 @@
import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { createContext, useContext, useState, useCallback } from 'react';
import type { ReactNode } from 'react'; import type { ReactNode, CSSProperties } from 'react';
export type Theme = 'dark' | 'light'; export type Theme = 'dark' | 'light';
@@ -185,19 +185,20 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
}); });
}, []); }, []);
useEffect(() => {
const root = document.documentElement;
root.style.setProperty('--body-bg', tokens.bodyBg);
root.style.setProperty('--scroll-thumb', tokens.scrollThumb);
root.style.setProperty('--glow-color', tokens.accentGlow);
root.style.setProperty('--hover-bg', tokens.tableRowHover);
document.body.style.background = tokens.bodyBgImage;
document.body.style.color = tokens.text;
}, [tokens]);
return ( return (
<ThemeContext.Provider value={{ theme, tokens, toggleTheme }}> <ThemeContext.Provider value={{ theme, tokens, toggleTheme }}>
{children} <div style={{
'--body-bg': tokens.bodyBg,
'--scroll-thumb': tokens.scrollThumb,
'--glow-color': tokens.accentGlow,
'--hover-bg': tokens.tableRowHover,
background: tokens.bodyBgImage,
color: tokens.text,
width: '100%',
minHeight: '100vh',
} as CSSProperties}>
{children}
</div>
</ThemeContext.Provider> </ThemeContext.Provider>
); );
} }
+18 -18
View File
@@ -1,7 +1,7 @@
/* 本模块样式仅保留动效/工具类;base 重置与 tailwind 由平台全局 index.css 提供 */ /* 本模块样式仅保留动效/工具类;base 重置与 tailwind 由平台全局 index.css 提供 */
button { cursor: pointer; } .jieya-root button { cursor: pointer; }
input, textarea { font-family: inherit; } .jieya-root input, .jieya-root textarea { font-family: inherit; }
/* ═══════════════════════════════════════════ /* ═══════════════════════════════════════════
太空舱 / 三栏工作区 动效层 太空舱 / 三栏工作区 动效层
@@ -23,7 +23,7 @@ input, textarea { font-family: inherit; }
from { opacity: 0; transform: translateX(-20px); } from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); } to { opacity: 1; transform: translateX(0); }
} }
@keyframes slide-in-right { @keyframes jieya-slide-in-right {
from { opacity: 0; transform: translateX(20px); } from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); } to { opacity: 1; transform: translateX(0); }
} }
@@ -43,11 +43,11 @@ input, textarea { font-family: inherit; }
from { opacity: 0; transform: translateY(18px) scale(0.97); } from { opacity: 0; transform: translateY(18px) scale(0.97); }
to { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 1; transform: translateY(0) scale(1); }
} }
@keyframes space-pulse { @keyframes jieya-space-pulse {
0%, 100% { opacity: 0.55; } 0%, 100% { opacity: 0.55; }
50% { opacity: 1; } 50% { opacity: 1; }
} }
@keyframes glow-pulse { @keyframes jieya-glow-pulse {
0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); } 0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); }
50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); } 50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); }
} }
@@ -55,7 +55,7 @@ input, textarea { font-family: inherit; }
0%, 100% { opacity: 1; transform: scale(1); } 0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.35; transform: scale(0.78); } 50% { opacity: 0.35; transform: scale(0.78); }
} }
@keyframes scan-sweep { @keyframes jieya-scan-sweep {
0% { left: -30%; } 0% { left: -30%; }
100% { left: 110%; } 100% { left: 110%; }
} }
@@ -128,27 +128,27 @@ input, textarea { font-family: inherit; }
.animate-slide-in { animation: slide-in-left 0.3s ease-out; } .animate-slide-in { animation: slide-in-left 0.3s ease-out; }
.animate-number { animation: number-roll 0.5s ease-out; } .animate-number { animation: number-roll 0.5s ease-out; }
.space-animate-left { animation: slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); } .space-animate-left { animation: slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-right{ animation: slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); } .jieya-root .space-animate-right{ animation: jieya-slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-up { animation: slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); } .space-animate-up { animation: slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); }
.card-in { animation: card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; } .card-in { animation: card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.notice-in { animation: notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; } .notice-in { animation: notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.content-reveal { animation: content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; } .jieya-root .content-reveal { animation: content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; }
.stream-cursor { animation: stream-cursor-blink 0.9s step-end infinite; } .stream-cursor { animation: stream-cursor-blink 0.9s step-end infinite; }
.space-pulse { animation: space-pulse 2.4s ease-in-out infinite; } .jieya-root .space-pulse { animation: jieya-space-pulse 2.4s ease-in-out infinite; }
.dot-blink { animation: dot-blink 1.6s ease-in-out infinite; } .dot-blink { animation: dot-blink 1.6s ease-in-out infinite; }
.glow-pulse { animation: glow-pulse 3s ease-in-out infinite; } .jieya-root .glow-pulse { animation: jieya-glow-pulse 3s ease-in-out infinite; }
.bar-grow { animation: bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; } .bar-grow { animation: bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; }
.dash-flow { animation: dash-flow 1.2s linear infinite; } .dash-flow { animation: dash-flow 1.2s linear infinite; }
/* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */ /* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */
::-webkit-scrollbar { width: 5px; height: 5px; } .jieya-root ::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; } .jieya-root ::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; } .jieya-root ::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; }
::-webkit-scrollbar-corner { background: transparent; } .jieya-root ::-webkit-scrollbar-corner { background: transparent; }
.space-scroll::-webkit-scrollbar { width: 4px; height: 8px; } .jieya-root .space-scroll::-webkit-scrollbar { width: 4px; height: 8px; }
.space-scroll::-webkit-scrollbar-track { background: transparent; } .jieya-root .space-scroll::-webkit-scrollbar-track { background: transparent; }
.space-scroll::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; } .jieya-root .space-scroll::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; }
/* 面板通用过渡 */ /* 面板通用过渡 */
.panel-shell { transition: width 0.3s cubic-bezier(0.4,0,0.2,1); } .panel-shell { transition: width 0.3s cubic-bezier(0.4,0,0.2,1); }
@@ -156,7 +156,7 @@ input, textarea { font-family: inherit; }
.ghost-btn:hover { background: var(--hover-bg, rgba(79,70,229,0.07)); } .ghost-btn:hover { background: var(--hover-bg, rgba(79,70,229,0.07)); }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
*, *::before, *::after { .jieya-root *, .jieya-root *::before, .jieya-root *::after {
animation-duration: 0.01ms !important; animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important; animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important; transition-duration: 0.01ms !important;
@@ -32,6 +32,7 @@ export default function KnowledgeGraphHome() {
const [sideTab, setSideTab] = useState<SideTab>('stats'); const [sideTab, setSideTab] = useState<SideTab>('stats');
const [sidebarWidth, setSidebarWidth] = useState(320); const [sidebarWidth, setSidebarWidth] = useState(320);
const isDragging = useRef(false); const isDragging = useRef(false);
const rootRef = useRef<HTMLDivElement>(null);
const handleNodeSelect = (node: SelectedNode | null) => setSelectedNode(node); const handleNodeSelect = (node: SelectedNode | null) => setSelectedNode(node);
const handleMaterialSelect = (mat: Material | null) => { const handleMaterialSelect = (mat: Material | null) => {
@@ -46,8 +47,8 @@ export default function KnowledgeGraphHome() {
isDragging.current = true; isDragging.current = true;
const startX = e.clientX; const startX = e.clientX;
const startWidth = sidebarWidth; const startWidth = sidebarWidth;
document.body.style.cursor = 'col-resize'; rootRef.current?.style.setProperty('cursor', 'col-resize');
document.body.style.userSelect = 'none'; rootRef.current?.style.setProperty('userSelect', 'none');
const onMouseMove = (ev: MouseEvent) => { const onMouseMove = (ev: MouseEvent) => {
if (!isDragging.current) return; if (!isDragging.current) return;
@@ -57,8 +58,8 @@ export default function KnowledgeGraphHome() {
}; };
const onMouseUp = () => { const onMouseUp = () => {
isDragging.current = false; isDragging.current = false;
document.body.style.cursor = ''; rootRef.current?.style.setProperty('cursor', '');
document.body.style.userSelect = ''; rootRef.current?.style.setProperty('userSelect', '');
document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp); document.removeEventListener('mouseup', onMouseUp);
}; };
@@ -69,7 +70,7 @@ export default function KnowledgeGraphHome() {
const viewLabels: Record<ViewMode, string> = { category: '按分类', project: '按项目', aging: '按账龄' }; const viewLabels: Record<ViewMode, string> = { category: '按分类', project: '按项目', aging: '按账龄' };
return ( return (
<div className="flex h-screen w-screen overflow-hidden" style={{ backgroundColor:'#f5f5f7' }}> <div ref={rootRef} className="flex h-screen w-screen overflow-hidden" style={{ backgroundColor:'#f5f5f7' }}>
{/* Sidebar */} {/* Sidebar */}
<aside className="flex-shrink-0 flex flex-col sidebar-bg" style={{ width:sidebarWidth, borderRight:'none' }}> <aside className="flex-shrink-0 flex flex-col sidebar-bg" style={{ width:sidebarWidth, borderRight:'none' }}>
{/* Logo header */} {/* Logo header */}
@@ -30,7 +30,7 @@ export default function AIMCockpit() {
}; };
return ( return (
<div style={{ <div className="ordercost-root" style={{
width: '100vw', height: '100vh', width: '100vw', height: '100vh',
overflow: 'hidden', overflow: 'hidden',
display: 'flex', flexDirection: 'column', display: 'flex', flexDirection: 'column',
@@ -24,11 +24,6 @@ export default function CostCockpit() {
const { theme, tokens, toggleTheme } = useTheme(); const { theme, tokens, toggleTheme } = useTheme();
const { orders } = useOrders(); const { orders } = useOrders();
// 同步 body 背景色(CSS 变量)
useEffect(() => {
document.documentElement.style.setProperty('--body-bg', tokens.bodyBg);
}, [tokens.bodyBg]);
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null); const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
const [leftExpanded, setLeftExpanded] = useState(false); const [leftExpanded, setLeftExpanded] = useState(false);
const [rightExpanded, setRightExpanded] = useState(false); const [rightExpanded, setRightExpanded] = useState(false);
@@ -83,7 +78,7 @@ export default function CostCockpit() {
}, [centerFullscreen]); }, [centerFullscreen]);
return ( return (
<div style={{ <div className="ordercost-root" style={{
width: '100vw', height: '100vh', width: '100vw', height: '100vh',
overflow: 'hidden', overflow: 'hidden',
display: 'flex', flexDirection: 'column', display: 'flex', flexDirection: 'column',
+3 -3
View File
@@ -91,9 +91,9 @@
.space-scroll::-webkit-scrollbar-thumb { background: rgba(0,212,255,0.25); border-radius: 4px; } .space-scroll::-webkit-scrollbar-thumb { background: rgba(0,212,255,0.25); border-radius: 4px; }
.space-scroll::-webkit-scrollbar-thumb:hover { background: rgba(0,212,255,0.45); } .space-scroll::-webkit-scrollbar-thumb:hover { background: rgba(0,212,255,0.45); }
::-webkit-scrollbar { width: 5px; height: 5px; } .ordercost-root ::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; } .ordercost-root ::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(0,212,255,0.2); border-radius: 10px; } .ordercost-root ::-webkit-scrollbar-thumb { background: rgba(0,212,255,0.2); border-radius: 10px; }
/* 拖入模块处理动画 */ /* 拖入模块处理动画 */
@keyframes module-spin { @keyframes module-spin {
+13 -13
View File
@@ -39,8 +39,8 @@
.logo-sub{font-size:10px;color:var(--faint);letter-spacing:1.5px} .logo-sub{font-size:10px;color:var(--faint);letter-spacing:1.5px}
.live{display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:700;color:var(--blue); .live{display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:700;color:var(--blue);
border:1px solid var(--blue);border-radius:20px;padding:2px 8px;margin-left:8px} border:1px solid var(--blue);border-radius:20px;padding:2px 8px;margin-left:8px}
.live i{width:6px;height:6px;border-radius:50%;background:var(--blue);animation:pulse 1.4s infinite} .live i{width:6px;height:6px;border-radius:50%;background:var(--blue);animation:hansong-pulse 1.4s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.25}} @keyframes hansong-pulse{0%,100%{opacity:1}50%{opacity:.25}}
/* 加 .hansong-app 前缀:#nav 会误命中 wuc-quotation 模块的 <nav id="nav">(ID 特异性高于类选择器) */ /* 加 .hansong-app 前缀:#nav 会误命中 wuc-quotation 模块的 <nav id="nav">(ID 特异性高于类选择器) */
.hansong-app #nav{display:flex;gap:6px;margin-left:14px;flex:1;justify-content:flex-end} .hansong-app #nav{display:flex;gap:6px;margin-left:14px;flex:1;justify-content:flex-end}
.nav-btn{border:1px solid transparent;background:transparent;color:var(--sub);font-size:13px;font-weight:600; .nav-btn{border:1px solid transparent;background:transparent;color:var(--sub);font-size:13px;font-weight:600;
@@ -64,7 +64,7 @@
.user-role{font-size:10px;color:var(--faint)} .user-role{font-size:10px;color:var(--faint)}
/* ===== 页面容器 ===== */ /* ===== 页面容器 ===== */
main{flex:1;overflow:hidden;position:relative} .hansong-app main{flex:1;overflow:hidden;position:relative}
.page{position:absolute;inset:0;padding:14px 18px;display:none;flex-direction:column;gap:12px;overflow:hidden} .page{position:absolute;inset:0;padding:14px 18px;display:none;flex-direction:column;gap:12px;overflow:hidden}
.page.on{display:flex;animation:fadeIn .35s} .page.on{display:flex;animation:fadeIn .35s}
@keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1}} @keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1}}
@@ -182,13 +182,13 @@ main{flex:1;overflow:hidden;position:relative}
/* ===== 比价表 ===== */ /* ===== 比价表 ===== */
.tbl-wrap{margin:0 14px 12px;border:1px solid var(--line);border-radius:12px;overflow:hidden;background:var(--card-solid)} .tbl-wrap{margin:0 14px 12px;border:1px solid var(--line);border-radius:12px;overflow:hidden;background:var(--card-solid)}
.tbl-title{padding:9px 14px;font-size:12px;font-weight:800;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:8px} .tbl-title{padding:9px 14px;font-size:12px;font-weight:800;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:8px}
table{width:100%;border-collapse:collapse;font-size:12px} .hansong-app table{width:100%;border-collapse:collapse;font-size:12px}
th{background:var(--blue-bg);color:var(--sub);font-weight:700;text-align:left;padding:8px 10px;white-space:nowrap;font-size:11px} .hansong-app th{background:var(--blue-bg);color:var(--sub);font-weight:700;text-align:left;padding:8px 10px;white-space:nowrap;font-size:11px}
td{padding:8px 10px;border-top:1px solid var(--line);vertical-align:middle} .hansong-app td{padding:8px 10px;border-top:1px solid var(--line);vertical-align:middle}
tr.rec-row{background:linear-gradient(90deg,var(--blue-bg),transparent)} .hansong-app tr.rec-row{background:linear-gradient(90deg,var(--blue-bg),transparent)}
tr.rec-row td:first-child{box-shadow:inset 3px 0 0 var(--blue)} .hansong-app tr.rec-row td:first-child{box-shadow:inset 3px 0 0 var(--blue)}
tbody tr{transition:.15s} .hansong-app tbody tr{transition:.15s}
tbody tr:hover{background:var(--blue-bg)} .hansong-app tbody tr:hover{background:var(--blue-bg)}
.score-cell{display:flex;align-items:center;gap:6px} .score-cell{display:flex;align-items:center;gap:6px}
.score-bar{width:52px;height:6px;border-radius:3px;background:rgba(120,135,170,.18);overflow:hidden} .score-bar{width:52px;height:6px;border-radius:3px;background:rgba(120,135,170,.18);overflow:hidden}
.score-bar i{display:block;height:100%;border-radius:3px;background:linear-gradient(90deg,var(--blue),var(--purple))} .score-bar i{display:block;height:100%;border-radius:3px;background:linear-gradient(90deg,var(--blue),var(--purple))}
@@ -309,10 +309,10 @@ tbody tr:hover{background:var(--blue-bg)}
/* ===== AI 思考动画 ===== */ /* ===== AI 思考动画 ===== */
.ai-think{padding:34px 20px;text-align:center} .ai-think{padding:34px 20px;text-align:center}
.ai-think .orb{width:52px;height:52px;margin:0 auto 14px;border-radius:50%; .ai-think .orb{width:52px;height:52px;margin:0 auto 14px;border-radius:50%;
background:conic-gradient(var(--blue),var(--purple),var(--cyan),var(--blue));animation:spin 1.2s linear infinite; background:conic-gradient(var(--blue),var(--purple),var(--cyan),var(--blue));animation:hansong-spin 1.2s linear infinite;
display:flex;align-items:center;justify-content:center} display:flex;align-items:center;justify-content:center}
.ai-think .orb::after{content:"";width:42px;height:42px;border-radius:50%;background:var(--card-solid)} .ai-think .orb::after{content:"";width:42px;height:42px;border-radius:50%;background:var(--card-solid)}
@keyframes spin{to{transform:rotate(360deg)}} @keyframes hansong-spin{to{transform:rotate(360deg)}}
.think-step{font-size:12px;color:var(--sub);padding:3px 0;opacity:0;animation:fadeUp .3s forwards} .think-step{font-size:12px;color:var(--sub);padding:3px 0;opacity:0;animation:fadeUp .3s forwards}
.think-step b{color:var(--blue)} .think-step b{color:var(--blue)}
.empty-hint{padding:40px 20px;text-align:center;color:var(--faint);font-size:12px} .empty-hint{padding:40px 20px;text-align:center;color:var(--faint);font-size:12px}
@@ -320,5 +320,5 @@ tbody tr:hover{background:var(--blue-bg)}
.sec-label{font-size:11px;font-weight:800;color:var(--faint);letter-spacing:1px;margin:14px 14px 6px} .sec-label{font-size:11px;font-weight:800;color:var(--faint);letter-spacing:1px;margin:14px 14px 6px}
.mini-list{font-size:11px} .mini-list{font-size:11px}
.mini-list .row{display:flex;gap:8px;padding:5px 0;border-top:1px dashed var(--line);align-items:center} .mini-list .row{display:flex;gap:8px;padding:5px 0;border-top:1px dashed var(--line);align-items:center}
select.sel{border:1px solid var(--line2);background:var(--card-solid);color:var(--ink);border-radius:9px; .hansong-app select.sel{border:1px solid var(--line2);background:var(--card-solid);color:var(--ink);border-radius:9px;
padding:6px 10px;font-size:12px;outline:none;cursor:pointer;font-weight:600} padding:6px 10px;font-size:12px;outline:none;cursor:pointer;font-weight:600}
+2 -2
View File
@@ -82,7 +82,7 @@ function AppInner() {
if (!dbReady) { if (!dbReady) {
const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null); const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null);
return ( return (
<div style={{ <div className="welltrust-root" style={{
width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14, background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14,
}}> }}>
@@ -116,7 +116,7 @@ function AppInner() {
} }
return ( return (
<div style={{ <div className="welltrust-root" style={{
width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column', width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column',
background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden', background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden',
position: 'relative', position: 'relative',
@@ -1,5 +1,5 @@
import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { createContext, useContext, useState, useCallback } from 'react';
import type { ReactNode } from 'react'; import type { ReactNode, CSSProperties } from 'react';
export type Theme = 'dark' | 'light'; export type Theme = 'dark' | 'light';
@@ -193,19 +193,20 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
}); });
}, []); }, []);
useEffect(() => {
const root = document.documentElement;
root.style.setProperty('--body-bg', tokens.bodyBg);
root.style.setProperty('--scroll-thumb', tokens.scrollThumb);
root.style.setProperty('--glow-color', tokens.accentGlow);
root.style.setProperty('--hover-bg', tokens.tableRowHover);
document.body.style.background = tokens.bodyBgImage;
document.body.style.color = tokens.text;
}, [tokens]);
return ( return (
<ThemeContext.Provider value={{ theme, tokens, toggleTheme }}> <ThemeContext.Provider value={{ theme, tokens, toggleTheme }}>
{children} <div style={{
'--body-bg': tokens.bodyBg,
'--scroll-thumb': tokens.scrollThumb,
'--glow-color': tokens.accentGlow,
'--hover-bg': tokens.tableRowHover,
background: tokens.bodyBgImage,
color: tokens.text,
width: '100%',
minHeight: '100vh',
} as CSSProperties}>
{children}
</div>
</ThemeContext.Provider> </ThemeContext.Provider>
); );
} }
+18 -18
View File
@@ -1,7 +1,7 @@
/* 本模块样式仅保留动效/工具类;base 重置与 tailwind 由平台全局 index.css 提供 */ /* 本模块样式仅保留动效/工具类;base 重置与 tailwind 由平台全局 index.css 提供 */
button { cursor: pointer; } .welltrust-root button { cursor: pointer; }
input, textarea { font-family: inherit; } .welltrust-root input, .welltrust-root textarea { font-family: inherit; }
/* ═══════════════════════════════════════════ /* ═══════════════════════════════════════════
太空舱 / 三栏工作区 动效层 太空舱 / 三栏工作区 动效层
@@ -23,7 +23,7 @@ input, textarea { font-family: inherit; }
from { opacity: 0; transform: translateX(-20px); } from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); } to { opacity: 1; transform: translateX(0); }
} }
@keyframes slide-in-right { @keyframes welltrust-slide-in-right {
from { opacity: 0; transform: translateX(20px); } from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); } to { opacity: 1; transform: translateX(0); }
} }
@@ -43,11 +43,11 @@ input, textarea { font-family: inherit; }
from { opacity: 0; transform: translateY(18px) scale(0.97); } from { opacity: 0; transform: translateY(18px) scale(0.97); }
to { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 1; transform: translateY(0) scale(1); }
} }
@keyframes space-pulse { @keyframes welltrust-space-pulse {
0%, 100% { opacity: 0.55; } 0%, 100% { opacity: 0.55; }
50% { opacity: 1; } 50% { opacity: 1; }
} }
@keyframes glow-pulse { @keyframes welltrust-glow-pulse {
0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); } 0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); }
50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); } 50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); }
} }
@@ -55,7 +55,7 @@ input, textarea { font-family: inherit; }
0%, 100% { opacity: 1; transform: scale(1); } 0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.35; transform: scale(0.78); } 50% { opacity: 0.35; transform: scale(0.78); }
} }
@keyframes scan-sweep { @keyframes welltrust-scan-sweep {
0% { left: -30%; } 0% { left: -30%; }
100% { left: 110%; } 100% { left: 110%; }
} }
@@ -125,27 +125,27 @@ input, textarea { font-family: inherit; }
.animate-slide-in { animation: slide-in-left 0.3s ease-out; } .animate-slide-in { animation: slide-in-left 0.3s ease-out; }
.animate-number { animation: number-roll 0.5s ease-out; } .animate-number { animation: number-roll 0.5s ease-out; }
.space-animate-left { animation: slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); } .space-animate-left { animation: slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-right{ animation: slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); } .welltrust-root .space-animate-right{ animation: welltrust-slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-up { animation: slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); } .space-animate-up { animation: slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); }
.card-in { animation: card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; } .card-in { animation: card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.notice-in { animation: notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; } .notice-in { animation: notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.content-reveal { animation: content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; } .welltrust-root .content-reveal { animation: content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; }
.stream-caret { display: inline-block; width: 2px; height: 0.95em; margin-left: 2px; vertical-align: -0.12em; background: currentColor; animation: stream-caret-blink 1s steps(1) infinite; } .stream-caret { display: inline-block; width: 2px; height: 0.95em; margin-left: 2px; vertical-align: -0.12em; background: currentColor; animation: stream-caret-blink 1s steps(1) infinite; }
.space-pulse { animation: space-pulse 2.4s ease-in-out infinite; } .welltrust-root .space-pulse { animation: welltrust-space-pulse 2.4s ease-in-out infinite; }
.dot-blink { animation: dot-blink 1.6s ease-in-out infinite; } .dot-blink { animation: dot-blink 1.6s ease-in-out infinite; }
.glow-pulse { animation: glow-pulse 3s ease-in-out infinite; } .welltrust-root .glow-pulse { animation: welltrust-glow-pulse 3s ease-in-out infinite; }
.bar-grow { animation: bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; } .bar-grow { animation: bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; }
.dash-flow { animation: dash-flow 1.2s linear infinite; } .dash-flow { animation: dash-flow 1.2s linear infinite; }
/* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */ /* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */
::-webkit-scrollbar { width: 5px; height: 5px; } .welltrust-root ::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; } .welltrust-root ::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; } .welltrust-root ::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; }
::-webkit-scrollbar-corner { background: transparent; } .welltrust-root ::-webkit-scrollbar-corner { background: transparent; }
.space-scroll::-webkit-scrollbar { width: 4px; height: 8px; } .welltrust-root .space-scroll::-webkit-scrollbar { width: 4px; height: 8px; }
.space-scroll::-webkit-scrollbar-track { background: transparent; } .welltrust-root .space-scroll::-webkit-scrollbar-track { background: transparent; }
.space-scroll::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; } .welltrust-root .space-scroll::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; }
/* 面板通用过渡 */ /* 面板通用过渡 */
.panel-shell { transition: width 0.3s cubic-bezier(0.4,0,0.2,1); } .panel-shell { transition: width 0.3s cubic-bezier(0.4,0,0.2,1); }
@@ -153,7 +153,7 @@ input, textarea { font-family: inherit; }
.ghost-btn:hover { background: var(--hover-bg, rgba(79,70,229,0.07)); } .ghost-btn:hover { background: var(--hover-bg, rgba(79,70,229,0.07)); }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
*, *::before, *::after { .welltrust-root *, .welltrust-root *::before, .welltrust-root *::after {
animation-duration: 0.01ms !important; animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important; animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important; transition-duration: 0.01ms !important;