Files
OCR/FRONTEND_ANALYSIS.md
2025-11-12 23:55:21 +08:00

512 lines
13 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.

# Tool_OCR 前端項目結構分析
## 項目概況
- **項目名稱**: Tool_OCR Frontend
- **框架**: React 19.2.0 (TypeScript)
- **構建工具**: Vite 7.2.2
- **樣式方案**: Tailwind CSS 4.1.17
- **路由管理**: React Router v7.9.5
- **狀態管理**: Zustand 5.0.8
- **數據獲取**: TanStack React Query v5.90.7
- **國際化**: i18next 25.6.2
- **源碼行數**: ~2,700 行
- **開發語言**: TypeScript
- **運行端口**: 12011
---
## 前端技術棧詳解
### 核心框架
- **React 19.2.0**: 最新版 React用於構建用戶界面
- 使用函數式組件
- React Hooks 進行狀態和副作用管理
- 嚴格模式StrictMode開啟
### 構建與開發
- **Vite 7.2.2**: 快速的前端構建工具
- 配置路徑別名 `@``./src`
- 開發服務器代理設定API 轉發到 localhost:12010
- TypeScript 支持
- **TypeScript ~5.9.3**: 類型檢查和增強開發體驗
- **ESLint + TypeScript ESLint**: 代碼質量檢查
- React Hooks 規則檢查
- React Refresh 支持
### 樣式設計
#### Tailwind CSS 4.1.17
- **CSS 框架**: 完全採用 Tailwind CSS
- **配置文件**: `/frontend/tailwind.config.js`
**主題配置 (HSL 色彩系統)**:
```
顏色變數 (CSS 自定義屬性):
- --background / --foreground (背景/前景)
- --primary / --primary-foreground (主色/主色前景)
- --secondary / --secondary-foreground (次色)
- --muted / --muted-foreground (灰色系)
- --accent / --accent-foreground (強調色)
- --destructive / --destructive-foreground (危險操作)
- --card / --card-foreground (卡片)
- --popover / --popover-foreground (彈出框)
- --border / --input (邊框/輸入框)
- --ring (焦點環)
```
**亮色模式**:
- 白色背景 (hsl(0 0% 100%))
- 深色文字 (hsl(222.2 84% 4.9%))
- 藍色主題 (hsl(221.2 83.2% 53.3%))
**暗色模式** (.dark class):
- 深色背景 (hsl(222.2 84% 4.9%))
- 淺色文字 (hsl(210 40% 98%))
#### PostCSS
- **配置文件**: `/frontend/postcss.config.js`
- **插件**: @tailwindcss/postcss (新版本原生支持)
#### 全局樣式
- **入口**: `/frontend/src/index.css`
- @tailwind 指令導入
- CSS 變數定義
- 亮色/暗色主題切換
---
## 項目目錄結構
```
frontend/
├── src/
│ ├── assets/ # 靜態資源
│ ├── components/ # React 組件
│ │ ├── ui/ # UI 基礎組件庫
│ │ │ ├── button.tsx # 按鈕組件 (多種變體)
│ │ │ ├── card.tsx # 卡片容器
│ │ │ ├── badge.tsx # 標籤組件
│ │ │ ├── table.tsx # 表格組件
│ │ │ ├── progress.tsx # 進度條
│ │ │ └── toast.tsx # 提示通知
│ │ ├── FileUpload.tsx # 文件上傳 (拖放支持)
│ │ ├── ResultsTable.tsx # 結果表格
│ │ ├── MarkdownPreview.tsx # Markdown 預覽
│ │ └── Layout.tsx # 主佈局組件
│ │
│ ├── pages/ # 頁面組件
│ │ ├── LoginPage.tsx # 登錄頁面
│ │ ├── UploadPage.tsx # 文件上傳頁面
│ │ ├── ProcessingPage.tsx # OCR 處理頁面
│ │ ├── ResultsPage.tsx # 結果查看頁面
│ │ ├── ExportPage.tsx # 導出配置頁面
│ │ └── SettingsPage.tsx # 系統設置頁面
│ │
│ ├── store/ # 狀態管理 (Zustand)
│ │ ├── authStore.ts # 認證狀態
│ │ └── uploadStore.ts # 上傳狀態
│ │
│ ├── services/ # API 服務層
│ │ └── api.ts # API 客戶端 (Axios)
│ │
│ ├── types/ # TypeScript 類型定義
│ │ └── api.ts # API 接口類型
│ │
│ ├── lib/ # 工具函數
│ │ └── utils.ts # cn() 函數 (Tailwind 類名合併)
│ │
│ ├── hooks/ # 自定義 React Hooks
│ │ └── (待擴展)
│ │
│ ├── i18n/ # 國際化配置
│ │ ├── index.ts # i18n 初始化
│ │ └── locales/
│ │ └── zh-TW.json # 繁體中文翻譯
│ │
│ ├── App.tsx # 應用根組件 (路由定義)
│ ├── main.tsx # 應用入口
│ ├── index.css # 全局樣式
│ └── App.css # 應用樣式 (可棄用)
├── public/ # 公開靜態資源
├── vite.config.ts # Vite 配置
├── tailwind.config.js # Tailwind 配置
├── postcss.config.js # PostCSS 配置
├── tsconfig.json # TypeScript 配置
├── tsconfig.app.json # 應用 TS 配置
├── tsconfig.node.json # Node TS 配置
├── eslint.config.js # ESLint 配置
├── index.html # HTML 入口
├── package.json # 依賴管理
├── package-lock.json # 依賴鎖定
└── .env # 環境變數
```
---
## 核心頁面和功能
### 頁面概述
| 頁面 | 路由 | 功能描述 | 行數 |
|------|------|--------|------|
| LoginPage | /login | 用戶認證 | 97 |
| UploadPage | /upload | 文件上傳,支持拖放 | 140 |
| ProcessingPage | /processing | 實時監控 OCR 處理進度 | 200 |
| ResultsPage | /results | 查看和下載 OCR 結果 | 157 |
| ExportPage | /export | 導出規則管理和結果導出 | 321 |
| SettingsPage | /settings | 系統配置和用戶偏好 | 325 |
### 總 UI 頁面代碼: ~1,240 行
---
## 組件架構
### UI 基礎組件庫 (/src/components/ui/)
採用現代化的無頭 UI 組件設計,配合 Tailwind CSS
1. **Button**
- 變體: default, destructive, outline, secondary, ghost, link
- 尺寸: default, sm, lg, icon
- 使用 cn() 實現動態類名合併
2. **Card**
- CardRoot, CardHeader, CardTitle, CardContent, CardFooter
- 容器組件,使用 Tailwind 樣式
3. **Table**
- 表格組件家族
- Table, TableHeader, TableBody, TableFooter, TableRow, TableHead, TableCell
4. **Badge**
- 標籤/徽章組件
- 用於狀態指示
5. **Progress**
- 進度條組件
- 百分比顯示
6. **Toast**
- 通知系統
- useToast() Hook
- 支持多個變體
### 業務組件
1. **FileUpload**
- react-dropzone 整合
- 支持拖放和點擊選擇
- 文件驗證 (類型、大小、數量)
- 自定義 accept 配置
2. **ResultsTable**
- 結果列表展示
3. **MarkdownPreview**
- Markdown 內容預覽
4. **Layout**
- 主體佈局
- 導航欄
- 頁頭
- 頁腳
---
## 狀態管理方案
### Zustand (v5.0.8)
#### 1. authStore.ts
```typescript
interface AuthState {
user: User | null
isAuthenticated: boolean
setUser: (user: User | null) => void
logout: () => void
}
```
- **持久化**: localStorage (auth-storage)
- **用途**: 管理登錄用戶信息和認證狀態
#### 2. uploadStore.ts
```typescript
interface UploadState {
batchId: number | null
files: FileInfo[]
uploadProgress: number
setBatchId: (id: number) => void
setFiles: (files: FileInfo[]) => void
setUploadProgress: (progress: number) => void
updateFileStatus: (fileId: number, status: string) => void
clearUpload: () => void
}
```
- **持久化**: localStorage (tool-ocr-upload-store)
- 只持久化: batchId, files (不持久化進度)
- **用途**: 管理當前上傳批次和文件信息
---
## API 服務層
### API 客戶端 (services/api.ts)
基於 Axios 的單例模式實現:
**配置**:
- Base URL: http://localhost:12010 (可通過 VITE_API_BASE_URL 環境變數覆蓋)
- API 版本: /api/v1
- 超時時間: 30 秒
- Content-Type: application/json
**功能模塊**:
1. **認證模塊**
- login(username, password)
- logout()
- Token 管理 (localStorage)
2. **文件上傳模塊**
- uploadFiles(files: File[])
- FormData multipart 上傳
3. **OCR 處理模塊**
- processOCR(batchId, lang, confidenceThreshold)
- getTaskStatus(taskId)
- getOCRResult(taskId)
- getBatchStatus(batchId)
4. **導出模塊**
- exportResults(batchId, format, options)
- exportPDF(fileId, cssTemplate)
- getExportRules()
- createExportRule(rule)
- updateExportRule(ruleId, rule)
- deleteExportRule(ruleId)
- getCSSTemplates()
5. **翻譯模塊** (計劃功能)
- translateDocument() [501 Not Implemented]
- getTranslationConfigs()
- createTranslationConfig()
**攔截器**:
- 請求攔截: 自動添加 Authorization Bearer token
- 響應攔截: 401 時清除 token 並重定向到登錄頁
---
## 類型定義
### 主要類型 (types/api.ts)
#### 認證
- LoginRequest, LoginResponse, User
#### 文件上傳
- UploadResponse, FileInfo
#### OCR 處理
- ProcessRequest, ProcessResponse, TaskStatus, BatchStatus, FileResult
#### OCR 結果
- OCRResult, OCRJsonData, TextBlock, LayoutInfo
#### 導出
- ExportRequest, ExportOptions, ExportRule, CSSTemplate
#### 翻譯 (Future)
- TranslateRequest, TranslateResponse, TranslationConfig
#### 錯誤處理
- ApiError, ApiResponse
---
## 國際化配置
### i18n (i18n/index.ts)
- **庫**: react-i18next v16.3.0
- **默認語言**: 繁體中文 (zh-TW)
- **翻譯文件**: /i18n/locales/zh-TW.json
### 翻譯內容結構
```json
{
"app": { title, subtitle },
"nav": { upload, processing, results, export, settings, logout },
"auth": { login, username, password, loginButton, loginError, welcomeBack },
"upload": { title, dragAndDrop, dropFilesHere, invalidFiles, ... },
"processing": { title, status, progress, currentFile, ... },
"results": { title, filename, status, confidence, ... },
"export": { title, format, formats, options, rules, cssTemplates, ... },
"settings": { ... },
"errors": { ... },
"common": { ... }
}
```
---
## 路由結構
### React Router v7.9.5 配置 (App.tsx)
```
/login → LoginPage (公開)
/ → Layout (受保護)
├── /upload → UploadPage
├── /processing → ProcessingPage
├── /results → ResultsPage
├── /export → ExportPage
└── /settings → SettingsPage
* → 重定向到 /
```
**保護機制**: ProtectedRoute 組件基於 authStore.isAuthenticated
---
## 樣式設計工具
### Tailwind 工具函數 (lib/utils.ts)
```typescript
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
```
**功能**:
- clsx: 條件類名組合
- tailwind-merge: 解決 Tailwind 類名衝突
- 用於動態生成和合併 Tailwind 類
---
## 依賴概覽
### 主要依賴
```json
{
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.9.5",
"zustand": "^5.0.8",
"@tanstack/react-query": "^5.90.7",
"axios": "^1.13.2",
"react-i18next": "^16.3.0",
"i18next": "^25.6.2",
"react-dropzone": "^14.3.8",
"tailwindcss": "^4.1.17",
"clsx": "^2.1.1",
"tailwind-merge": "^3.4.0"
}
```
### 開發依賴
```json
{
"typescript": "~5.9.3",
"vite": "^7.2.2",
"@vitejs/plugin-react": "^5.1.0",
"eslint": "^9.39.1",
"typescript-eslint": "^8.46.3",
"@tailwindcss/postcss": "^4.1.17",
"postcss": "^8.5.6",
"autoprefixer": "^10.4.22"
}
```
---
## 開發和構建
### 可用命令
```bash
npm run dev # 啟動開發服務器 (localhost:12011)
npm run build # 生產構建 (TypeScript 編譯 + Vite 打包)
npm run lint # ESLint 檢查
npm run preview # 預覽構建結果
```
### 開發服務器配置
- **端口**: 12011
- **代理**: /api → http://localhost:12010 (後端)
---
## 代碼質量
### ESLint 配置
- JavaScript ES2020 規範
- TypeScript 類型檢查
- React Hooks 規則 (recommended-latest)
- React Refresh 支持
- 瀏覽器全局變數支持
### TypeScript 配置
- 目標: ES2020
- 模塊: ESNext
- JSX: React-JSX (自動導入)
- 嚴格模式啟用
- 路徑別名: @ → ./src
---
## 文件統計
- **總文件數**: 28 個
- **源碼總大小**: 152 KB
- **代碼行數**: ~2,702 行 (TS/TSX/JSON)
- **UI 組件**: 6 個基礎組件
- **業務組件**: 4 個
- **頁面**: 6 個
- **工具函數**: 多個
---
## 樣式實現要點
1. **Tailwind CSS 優先**: 所有樣式都使用 Tailwind 工具類
2. **CSS 變數系統**: 使用 HSL 色彩空間,支持主題切換
3. **響應式設計**: 內置 Tailwind 響應式前綴支持
4. **可訪問性**: 焦點環、禁用狀態等 UI 反饋
5. **暗色模式**: 通過 .dark 類支持主題切換
6. **組件化**: UI 組件開箱即用,無需額外 CSS
---
## 總結
Tool_OCR 前端項目採用現代化的技術棧:
- **框架**: React 19 + TypeScript
- **構建**: Vite (快速開發和構建)
- **樣式**: Tailwind CSS 4 (工具類優先)
- **狀態**: Zustand (輕量級狀態管理)
- **數據**: React Query (服務器狀態管理)
- **路由**: React Router v7 (應用導航)
- **國際化**: i18next (多語言支持)
- **質量**: ESLint + TypeScript (靜態檢查)
**核心特點**:
1. 類型安全的開發環境
2. 響應式 UI 設計
3. 模塊化組件架構
4. 完整的狀態管理
5. API 層分離
6. 國際化就位
7. 開發友好 (HMR, 快速刷新)