Files
syops/docs/frontend_architecture_refactor.md
T
sophie 61693d014d refactor: 重构前端骨架,及admin模块子路由和懒加载
refactor: 优化多次请求,并使用pinia状态管理
2026-06-03 10:30:16 +08:00

454 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HXOPS 前端重构架构方案
> 更新时间:2026-06-02
> 适用范围:`frontend/` 目录
> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。
---
## 1. 架构选型
在现有技术栈(Vue 3 + TypeScript + Vite + Vue Router + Vue I18n + TailwindCSS)基础上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态** 的组合架构。
**选型理由:**
- 与 Vue 3 Composition API 天然契合,学习成本低
- 业务域清晰(聊天 / 管理后台 / 知识库 / 认证),适合按 feature 垂直拆分
- 相比 FSD(Feature-Sliced Design)目录层级更浅,迁移成本可控
- 相比引入 Element Plus 等 UI 库,可继续沿用现有 Tailwind 设计体系(`tokens.css`、`components-ds.css`)
**保持不变的技术栈:**
| 层级 | 选型 |
|------|------|
| 框架 | Vue 3(Composition API + `<script setup>`)+ TypeScript |
| 构建 | Vite |
| 路由 | Vue Router 4(子路由 + 懒加载) |
| 样式 | TailwindCSS + 现有 Design Tokens |
| 国际化 | Vue I18n(messages 外置并按域拆分) |
| 网络 | `fetch` + `requestJson`(`shared/api/client.ts`)+ SSE(`useChat`) |
| 状态 | **新增 Pinia**(替代 localStorage + CustomEvent 为主的跨页状态) |
---
## 2. 目标目录结构
```text
frontend/src/
├── app/ # 应用启动层
│ ├── main.ts
│ ├── App.vue
│ ├── router/
│ │ ├── index.ts # 汇总各域路由
│ │ ├── guards.ts # 认证 / 权限守卫(从 router/index.ts 抽出)
│ │ └── routes/ # 按业务域拆分路由表
│ │ ├── auth.routes.ts
│ │ ├── chat.routes.ts
│ │ ├── admin.routes.ts
│ │ └── kb.routes.ts
│ └── plugins/
│ ├── i18n.ts # 仅注册 i18n 实例,messages 外置
│ └── pinia.ts
│
├── shared/ # 跨域共享(无业务语义)
│ ├── api/
│ │ ├── client.ts # requestJson、BusinessError、响应 envelope 解析
│ │ └── types.ts # 通用 API 类型
│ ├── composables/ # useTheme、useIsMobile、useMessage 等
│ ├── components/ # 通用 UI:Dialog、DataTable、EmptyState、Pagination
│ ├── layouts/ # AppShell、ChatShell、MinimalShell、MarketingShell
│ ├── utils/ # auth、clipboard、wecom 等纯工具
│ ├── styles/ # tokens.css、components-ds.css、utilities.css
│ └── constants/
│
├── features/ # 按业务域垂直切分(核心)
│ ├── auth/
│ │ ├── api/
│ │ │ └── user.api.ts
│ │ ├── stores/
│ │ │ └── auth.store.ts
│ │ ├── composables/
│ │ │ └── useAuth.ts
│ │ ├── views/
│ │ │ ├── WorkspaceView.vue
│ │ │ └── ResetPasswordView.vue
│ │ └── components/
│ │
│ ├── chat/
│ │ ├── api/
│ │ │ └── chat.api.ts
│ │ ├── types/
│ │ │ └── chat.types.ts
│ │ ├── stores/
│ │ │ └── chat.store.ts # 会话列表、当前 agent 等
│ │ ├── composables/
│ │ │ ├── useChat.ts # SSE 流式对话(保留并增强)
│ │ │ ├── useChatSessions.ts
│ │ │ └── useSourceFiles.ts # 源文件 / 检索来源逻辑
│ │ ├── views/
│ │ │ └── ChatView.vue # 页面编排,目标 < 300 行
│ │ └── components/
│ │ ├── ChatSidebar.vue
│ │ ├── ChatMessageList.vue
│ │ ├── ChatInputBar.vue
│ │ ├── MessageBubble.vue
│ │ ├── SourceFilePanel.vue
│ │ └── AgentSwitcher.vue
│ │
│ ├── admin/
│ │ ├── api/
│ │ │ ├── admin.api.ts
│ │ │ └── schedule.api.ts
│ │ ├── stores/
│ │ │ └── admin-nav.store.ts
│ │ ├── views/
│ │ │ └── AdminLayout.vue # 壳层 + 侧边栏,子路由出口
│ │ ├── modules/ # 原 AdminView activeModule 各拆独立模块
│ │ │ ├── dashboard/
│ │ │ ├── agents/
│ │ │ ├── users/
│ │ │ ├── departments/
│ │ │ ├── permissions/
│ │ │ ├── requests/
│ │ │ ├── reports/
│ │ │ ├── approvals/
│ │ │ ├── announcements/
│ │ │ ├── questions/
│ │ │ ├── wecom/
│ │ │ ├── schedules/
│ │ │ └── knowledge-base/
│ │ └── components/
│ │ └── AdminNav.vue
│ │
│ └── kb/
│ ├── api/
│ │ └── kb.api.ts
│ ├── views/
│ │ └── KbWorkspaceView.vue
│ └── components/ # 迁移现有 components/kb/*
│
├── locales/ # i18n 按语言 + 业务域拆分
│ ├── zh-CN/
│ │ ├── common.json
│ │ ├── auth.json
│ │ ├── chat.json
│ │ ├── admin.json
│ │ ├── kb.json
│ │ └── errors.json
│ ├── zh-TW/
│ ├── en/
│ ├── th/
│ └── index.ts # 按需加载、合并 messages
│
└── config.ts # 应用级开关(loginMode、admin.modules 等)
```
### 2.1 与现有目录的映射关系
| 现有路径 | 目标路径 | 说明 |
|----------|----------|------|
| `src/main.ts`、`src/App.vue` | `app/` | 启动与全局插件注册 |
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
| `src/api/client.ts` | `shared/api/client.ts` | 保持不变,作为统一 HTTP 层 |
| `src/api/*.ts` | `features/*/api/` | 按业务域归属 |
| `src/composables/`(通用) | `shared/composables/` | useTheme、useMessage 等 |
| `src/composables/useChat.ts` | `features/chat/composables/` | 聊天域专属 |
| `src/components/`(通用 Dialog 等) | `shared/components/` | 跨域复用 UI |
| `src/components/kb/` | `features/kb/components/` | 知识库域 |
| `src/layouts/` | `shared/layouts/` | 页面壳层 |
| `src/utils/` | `shared/utils/` | 纯工具函数 |
| `src/styles/` | `shared/styles/` | 设计 token 与全局样式 |
| `src/views/AdminView.vue` | `features/admin/modules/*/` | 拆为 12+ 子模块页面 |
| `src/views/ChatView.vue` | `features/chat/` | View + 多个子组件 |
| `src/views/WorkspaceView.vue` | `features/auth/views/` | 登录 / 工作台 |
| `src/i18n.ts` | `locales/` | 按语言、域拆分 JSON |
---
## 3. 分层职责
各层职责边界如下,**上层可依赖下层,下层不得反向依赖上层**。
```mermaid
flowchart TB
subgraph Views["Views(页面编排层)"]
V1["布局组合、路由参数解析、模块装配"]
end
subgraph Components["Components(展示层)"]
C1["纯 UI:props / emits,不直接调用 API"]
end
subgraph Composables["Composables(逻辑层)"]
CO1["SSE 流、表单、分页、副作用封装"]
end
subgraph Stores["Pinia Stores(共享状态层)"]
S1["跨组件 / 跨页面需共享的可变状态"]
end
subgraph API["API Layer(数据访问层)"]
A1["requestJson 封装 + 领域 API 函数"]
end
Views --> Components
Views --> Composables
Composables --> Stores
Composables --> API
Stores --> API
Components --> Composables
```
### 3.1 Views(页面编排层)
- **职责**:路由入口、Layout 组合、将 composable / store 的数据传给子组件
- **约束**:单个 View 文件目标 **< 300 行**;不写复杂业务算法、不直接写大段 `fetch`
- **示例**:`ChatView.vue` 只负责组装 `ChatSidebar` + `ChatMessageList` + `ChatInputBar`
### 3.2 Components(展示层)
- **职责**:可复用的 UI 单元,通过 `props` / `emits` 与外部通信
- **约束**:不直接 import 领域 API;需要数据时由父组件或 composable 注入
- **划分**:
- `shared/components/`:Dialog、DataTable、EmptyState 等无业务语义组件
- `features/*/components/`:MessageBubble、AdminNav 等领域组件
### 3.3 Composables(逻辑层)
- **职责**:封装可复用的响应式逻辑、副作用(SSE、语音识别、会话管理)
- **约束**:可调用 API 与 Store;返回 ref / computed / 方法供 View / Component 使用
- **示例**:
- `useChat`:SSE 流式对话(保留现有实现,增强类型)
- `useChatSessions`:会话 CRUD
- `useSourceFiles`:从 ChatView 抽出的源文件 / 检索来源解析
### 3.4 Pinia Stores(共享状态层)
- **职责**:跨页面、跨组件需共享且需响应式更新的状态
- **约束**:Store 可调用 API;View 优先通过 composable 访问 Store,避免在模板中散落 store 调用
| Store | 文件 | 职责 |
|-------|------|------|
| `useAuthStore` | `features/auth/stores/auth.store.ts` | 当前用户、token、login / logout、角色 |
| `useChatStore` | `features/chat/stores/chat.store.ts` | 当前 agent、会话列表、侧边栏折叠状态 |
| `useAppStore` | `app/stores/app.store.ts`(可选) | 全局 locale、theme 同步 |
| `useAdminNavStore` | `features/admin/stores/admin-nav.store.ts` | 当前 admin 模块、报表 tab |
### 3.5 API Layer(数据访问层)
- **职责**:所有 HTTP 请求的统一出口;类型定义与后端契约对齐
- **约束**:
- 仅 `shared/api/client.ts` 处理 envelope 解析与 `BusinessError`
- 领域 API 文件只做 URL 组装与类型标注,不写 UI 逻辑
- **示例**:`features/chat/api/chat.api.ts` 迁移自现有 `src/api/chat.ts`
---
## 4. 各 Feature 模块说明
### 4.1 auth(认证 / 工作台)
| 项 | 说明 |
|----|------|
| 路由 | `/`、`/workspace`、`/casdoor-callback`、`/reset-password` |
| 核心 Store | `authStore`:替代 `utils/auth.ts` 的直接读写 + `hxops:logout` 事件 |
| 页面 | `WorkspaceView`(登录、Agent 列表)、`ResetPasswordView` |
| 迁移来源 | `views/WorkspaceView.vue`、`views/ResetPasswordView.vue`、`utils/auth.ts` |
### 4.2 chat(对话)
| 项 | 说明 |
|----|------|
| 路由 | `/chat/:agentId` |
| 核心 Composable | `useChat`(SSE)、`useChatSessions`、`useSourceFiles` |
| 核心 Store | `chatStore`:当前 agent、会话列表缓存 |
| 组件拆分 | Sidebar / MessageList / InputBar / MessageBubble / SourceFilePanel / AgentSwitcher |
| 迁移来源 | `views/ChatView.vue`(~3400 行)、`composables/useChat.ts` |
### 4.3 admin(管理后台)
| 项 | 说明 |
|----|------|
| 路由 | `/admin/*` 子路由(替代 `?module=xxx` query) |
| 布局 | `AdminLayout.vue`:左侧 `AdminNav` + `<router-view>` |
| 子模块 | 与 `config.admin.modules` 一一对应,每个 module 独立页面 |
| 懒加载 | 各 module 使用 `() => import(...)`,减小首屏体积 |
| 迁移来源 | `views/AdminView.vue`(~6000 行)、`api/admin.ts`、`api/schedule.ts` |
**Admin 子路由示例:**
```typescript
// app/router/routes/admin.routes.ts
{
path: '/admin',
component: () => import('@/features/admin/views/AdminLayout.vue'),
meta: { requiresAdmin: true },
children: [
{ path: '', redirect: '/admin/dashboard' },
{ path: 'dashboard', component: () => import('@/features/admin/modules/dashboard/DashboardPage.vue') },
{ path: 'agents', component: () => import('@/features/admin/modules/agents/AgentsPage.vue') },
{ path: 'users', component: () => import('@/features/admin/modules/users/UsersPage.vue') },
{ path: 'reports/:table?', component: () => import('@/features/admin/modules/reports/ReportsPage.vue') },
{ path: 'knowledge-base', component: () => import('@/features/admin/modules/knowledge-base/KbAdminPage.vue') },
// ... 其余 module
],
}
```
**兼容旧 URL:** `/admin?module=users` → redirect 至 `/admin/users`
### 4.4 kb(知识库)
| 项 | 说明 |
|----|------|
| 路由 | `/kb/workspace`;`/kb/admin` redirect 至 `/admin/knowledge-base` |
| 组件 | 迁移 `components/kb/KbAdminPanel.vue`、`DifyHealthDialog.vue` 等 |
| 迁移来源 | `views/KbWorkspaceView.vue`(~2400 行)、`api/kb.ts` |
---
## 5. 共享层(shared)沉淀清单
在重构过程中,以下组件建议优先沉淀到 `shared/components/`,供 admin、chat、kb 共用:
| 组件 | 用途 | 现状 |
|------|------|------|
| `ConfirmDialog` | 删除 / 操作确认 | 现有 `DeleteConfirmDialog.vue` |
| `LevelMessageDialog` | 全局消息弹窗 | 现有,经 `useGlobalMessageDialog` 调用 |
| `DataTable` | 管理后台表格 + 分页 | AdminView 内大量重复表格结构 |
| `FormField` | 统一表单字段样式 | 分散在各 View |
| `Pagination` | 分页控件 | 分散在 AdminView |
| `EmptyState` | 空数据占位 | 分散实现 |
| `LoadingOverlay` | 加载遮罩 | 分散实现 |
样式继续沿用 `shared/styles/tokens.css` 与 `components-ds.css`,**不引入 Element Plus / Naive UI 等重型 UI 库**。
---
## 6. 路径别名与 import 规范
建议在 `vite.config.ts` / `tsconfig.json` 中配置:
```typescript
// vite.config.ts
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
```
**import 规则:**
```text
features/chat/views/ChatView.vue
✅ import { useChat } from '../composables/useChat'
✅ import { BaseDialog } from '@/shared/components/BaseDialog.vue'
✅ import { listChatSessions } from '../api/chat.api'
❌ import { listAdminUsers } from '@/features/admin/api/admin.api' // 跨 feature 禁止
```
跨 feature 通信通过:**路由跳转**、**shared 层工具**、或 **Pinia store**(仅全局态如 auth),避免 feature 之间直接 import 页面或 API。
---
## 7. Phase 0 落地说明(已实现)
Phase 0 目标:搭好基础设施,**不迁移现有 views**,旧代码可继续运行。
### 7.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| Pinia | `pinia@^3`,`app/plugins/pinia.ts` |
| `@/` 别名 | `vite.config.ts`、`tsconfig.app.json` |
| 路由拆分 | `app/router/routes/{auth,chat,admin,kb}.routes.ts` |
| 路由守卫 | `app/router/guards.ts`(`setupRouterGuards`) |
| Auth Store | `features/auth/stores/auth.store.ts` |
| Auth Composable | `features/auth/composables/useAuth.ts` |
| Chat Store 骨架 | `features/chat/stores/chat.store.ts` |
| API 转发层 | `shared/api/client.ts` → 现有 `api/client.ts` |
| 路由常量 | `shared/constants/routes.ts` |
| 兼容入口 | `router/index.ts` re-export `app/router` |
### 7.2 启动顺序(main.ts)
```typescript
app.use(pinia);
bindAuthStoreSync(); // Store 与 utils/auth 跨标签同步
app.use(router);
app.use(i18n);
```
### 7.3 新代码用法
```typescript
// 认证(新代码优先)
import { useAuth } from '@/features/auth';
const { user, isLoggedIn, login, logout } = useAuth();
// 或直接使用 Store
import { useAuthStore } from '@/features/auth/stores/auth.store';
```
### 7.4 兼容策略
- 旧代码仍可使用 `utils/auth` 的 `getStoredAuthUser` / `saveAuthUser`
- 路由守卫在每次导航前调用 `auth.syncFromStorage()`,保证 Store 与 storage 一致
- `utils/auth` 的 `logoutAuth` 触发 `hxops:logout` 后,Store 自动清空 `user`
### 7.5 下一步
Phase 1 已完成,见 §8。
---
## 8. Phase 1 落地说明(已实现)
Phase 1 目标:管理后台嵌套子路由 + 首个独立模块 `agents`。
### 8.1 路由结构
| URL | 组件 | 说明 |
|-----|------|------|
| `/admin` | redirect → `/admin/dashboard` | |
| `/admin/agents` | `AgentsPage.vue` | **已独立拆分** |
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only) |
| `/admin/reports/:table?` | `AdminLegacyPage.vue` | 报表模块 |
| `/admin?module=xxx` | redirect | 兼容旧链接,跳转至 `/admin/xxx` |
### 8.2 新增文件(均含文件头注释)
```text
features/admin/
├── views/AdminLayout.vue # 壳层:顶栏 + AdminNav + router-view
├── views/AdminLegacyPage.vue # 未拆分模块的过渡容器
├── components/AdminNav.vue # 子路由导航
├── modules/agents/
│ ├── AgentsPage.vue
│ ├── composables/useAgentsAdmin.ts
│ └── components/{AgentTestModal,AgentPermissionModal}.vue
├── stores/admin-nav.store.ts
├── composables/useAdminNavBadges.ts
├── constants/modules.ts
└── types/{admin,agent}.types.ts
```
### 8.3 构建验证
`npm run build` 通过;`AgentsPage`、`AdminLayout`、`AdminLegacyPage` 已代码分割为独立 chunk。
### 8.4 下一步(Phase 2)
- 继续拆分 `users`、`permissions` 等 admin 模块
- 拆分 `ChatView.vue` 为 `features/chat/components/*`
---
## 9. 相关文档
- [项目上下文与技术栈](./project_context.md)
- [UI 设计系统](./ui/DESIGN_SYSTEM.md)
- [UI 编码规范](./ui/UI_CODING_GUIDELINES.md)