Преглед изворни кода

feat: 实施故事 010.010 - 创建统一文件管理UI包

从 file-management-ui 复制创建 unified-file-management-ui 包,
API 指向统一文件模块,确保架构一致性。

主要变更:
- 创建 packages/unified-file-management-ui 包
- 修改包名和依赖指向 @d8d/unified-file-module
- 实现 FileManagement 和 FileSelector 组件
- API 客户端使用 RPC 推断类型(符合开发规范)
- 30 个测试全部通过

🤖 Generated with [Claude Code](https://claude.com/claude-code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
yourname пре 2 недеља
родитељ
комит
aaebf96d11
28 измењених фајлова са 3541 додато и 54 уклоњено
  1. 29 13
      docs/prd/epic-010-unified-ad-management.md
  2. 63 41
      docs/stories/010.010.story.md
  3. 18 0
      packages/unified-file-management-ui/.eslintrc.js
  4. 19 0
      packages/unified-file-management-ui/build.config.ts
  5. 36 0
      packages/unified-file-management-ui/eslint.config.js
  6. 95 0
      packages/unified-file-management-ui/package.json
  7. 18 0
      packages/unified-file-management-ui/src/api/index.ts
  8. 44 0
      packages/unified-file-management-ui/src/api/unifiedFileClient.ts
  9. 491 0
      packages/unified-file-management-ui/src/components/FileManagement.tsx
  10. 514 0
      packages/unified-file-management-ui/src/components/FileSelector.tsx
  11. 468 0
      packages/unified-file-management-ui/src/components/MinioUploader.tsx
  12. 9 0
      packages/unified-file-management-ui/src/components/index.ts
  13. 7 0
      packages/unified-file-management-ui/src/hooks/index.ts
  14. 149 0
      packages/unified-file-management-ui/src/hooks/useFileManagement.ts
  15. 126 0
      packages/unified-file-management-ui/src/hooks/useFileSelector.ts
  16. 14 0
      packages/unified-file-management-ui/src/index.ts
  17. 78 0
      packages/unified-file-management-ui/src/types/file.ts
  18. 6 0
      packages/unified-file-management-ui/src/utils/cn.ts
  19. 64 0
      packages/unified-file-management-ui/src/utils/index.ts
  20. 385 0
      packages/unified-file-management-ui/src/utils/minio.ts
  21. 141 0
      packages/unified-file-management-ui/tests/components/FileManagement.test.tsx
  22. 213 0
      packages/unified-file-management-ui/tests/components/FileSelector.test.tsx
  23. 259 0
      packages/unified-file-management-ui/tests/hooks/useFileManagement.test.tsx
  24. 37 0
      packages/unified-file-management-ui/tests/setup.ts
  25. 98 0
      packages/unified-file-management-ui/tests/utils/index.test.ts
  26. 36 0
      packages/unified-file-management-ui/tsconfig.json
  27. 24 0
      packages/unified-file-management-ui/vitest.config.ts
  28. 100 0
      pnpm-lock.yaml

+ 29 - 13
docs/prd/epic-010-unified-ad-management.md

@@ -21,6 +21,7 @@
 | 1.14 | 2026-01-04 | 批准故事010.009:创建统一文件后端模块 | Bob (Scrum Master) |
 | 1.15 | 2026-01-04 | 完成故事010.009:创建统一文件后端模块(22个测试,覆盖率59.47%) | Claude (Dev Agent) |
 | 1.16 | 2026-01-04 | 批准故事010.010:创建统一文件管理UI包 | Bob (Scrum Master) |
+| 1.17 | 2026-01-04 | 完成故事010.010:创建统一文件管理UI包(30个测试,使用RPC推断类型) | Claude (Dev Agent) |
 
 ## 史诗目标
 
@@ -377,7 +378,7 @@ packages/unified-file-module/
     └── integration/ (8个测试)
 ```
 
-### Story 10: 创建统一文件管理UI包 ✅ 已批准
+### Story 10: 创建统一文件管理UI包 ✅ 已完成
 
 **标题**: 创建统一文件管理UI包 (unified-file-management-ui)
 
@@ -391,19 +392,34 @@ packages/unified-file-module/
 **前置条件**: 故事010.009已完成
 
 **任务**:
-- [ ] 创建 `packages/unified-file-management-ui` 包(从 `file-management-ui` 复制并改造)
-- [ ] 实现文件管理组件(列表、上传、删除)
-- [ ] 实现文件选择器组件(供其他UI包使用)
-- [ ] API客户端指向统一文件模块端点
-- [ ] 编写完整的组件测试和集成测试
+- [x] 创建 `packages/unified-file-management-ui` 包(从 `file-management-ui` 复制并改造)
+- [x] 实现文件管理组件(列表、上传、删除)
+- [x] 实现文件选择器组件(供其他UI包使用)
+- [x] API客户端指向统一文件模块端点
+- [x] 编写完整的组件测试和集成测试
+- [x] **类型定义规范**: 使用RPC推断类型而非从schema获取类型
 
-**完成日期**: _待定_
+**完成日期**: 2026-01-04
 **相关文件**: `docs/stories/010.010.story.md`
 
-**测试覆盖**:
-- 组件测试
-- API集成测试
-- 文件选择器测试
+**测试成果**:
+- 单元测试: 9/9 通过 (useFileManagement hook)
+- 组件测试: 21/21 通过 (FileManagement + FileSelector)
+- 总计: 30 个测试全部通过
+
+**新增包**:
+```
+packages/unified-file-management-ui/
+├── src/
+│   ├── api/unifiedFileClient.ts (RPC客户端)
+│   ├── components/FileManagement.tsx, FileSelector.tsx
+│   ├── hooks/useFileManagement.ts, useFileSelector.ts
+│   ├── types/file.ts (使用RPC推断类型)
+│   └── utils/minio.ts
+└── tests/
+    ├── components/ (13个测试)
+    └── hooks/ (9个测试)
+```
 
 ### Story 11: 集成统一文件模块到统一广告和租户后台 📝 待开始
 
@@ -777,7 +793,7 @@ export const adminUnifiedAdApiRoutes = api.route('/api/v1/admin/unified-advertis
 6. [ ] 租户后台UI交互E2E测试覆盖完整流程(Story 7)
 7. [ ] 小程序端广告展示E2E测试验证通过(Story 8)
 8. [x] 统一文件模块创建完成(Story 9)
-9. [ ] 统一文件管理UI创建完成(Story 10)
+9. [x] 统一文件管理UI创建完成(Story 10)
 10. [ ] 统一文件模块集成到统一广告和租户后台(Story 11)
 
 ### 技术验收
@@ -786,7 +802,7 @@ export const adminUnifiedAdApiRoutes = api.route('/api/v1/admin/unified-advertis
 3. [ ] 租户后台UI交互E2E测试通过(Story 7)
 4. [ ] 小程序端广告展示E2E测试通过(Story 8)
 5. [x] 统一文件模块测试通过(Story 9)
-6. [ ] 统一文件管理UI测试通过(Story 10)
+6. [x] 统一文件管理UI测试通过(Story 10)
 7. [ ] 集成和回归测试通过(Story 11)
 8. [x] 代码符合项目编码规范
 9. [x] 无TypeScript类型错误

+ 63 - 41
docs/stories/010.010.story.md

@@ -1,7 +1,7 @@
 # Story 010.010: 创建统一文件管理UI包 (unified-file-management-ui)
 
 ## Status
-Approved
+Ready for Review
 
 ## Story
 
@@ -21,42 +21,42 @@ Approved
 
 ## Tasks / Subtasks
 
-- [ ] **任务1: 复制文件管理UI包创建统一文件管理UI包** (AC: 1)
-  - [ ] **使用 `cp -r packages/file-management-ui packages/unified-file-management-ui` 命令直接复制整个文件夹**
-  - [ ] 验证复制后的目录结构完整
-  - [ ] 验证所有文件都已复制(src、tests、配置文件)
-
-- [ ] **任务2: 修改包配置文件** (AC: 2)
-  - [ ] 修改 `package.json` 包名:`@d8d/file-management-ui` → `@d8d/unified-file-management-ui`
-  - [ ] 修改 `package.json` 描述:添加"unified"相关描述
-  - [ ] 修改依赖:`@d8d/file-module` → `@d8d/unified-file-module`
-
-- [ ] **任务3: 修改 API 客户端** (AC: 2, 3)
-  - [ ] 修改 `src/api/fileClient.ts` 文件名为 `src/api/unifiedFileClient.ts`
-  - [ ] 修改 `src/api/fileClient.ts` 中的路由导入:`fileRoutes` → `unifiedFileRoutes`
-  - [ ] 修改 `src/api/index.ts` 导出
-  - [ ] 确认 API 端点指向统一文件模块的管理员路由
-
-- [ ] **任务4: 修改类型定义** (AC: 2)
-  - [ ] 修改类型文件中的命名和引用
-  - [ ] 确保类型推断使用 RPC 推断类型(而非直接导入 schema 类型)
-
-- [ ] **任务5: 修改组件** (AC: 4, 5)
-  - [ ] 更新组件中的 API 客户端导入
-  - [ ] 更新 hooks 中的 API 客户端导入
-  - [ ] 验证文件管理组件功能正常
-  - [ ] 验证文件选择器组件功能正常
-
-- [ ] **任务6: 编写组件测试** (AC: 6)
-  - [ ] 更新测试文件中的 mock 路由和 API
-  - [ ] 添加文件管理组件集成测试
-  - [ ] 添加文件选择器组件集成测试
-  - [ ] 验证所有测试通过
-
-- [ ] **任务7: 类型检查和代码质量** (AC: 7)
-  - [ ] 运行 `pnpm typecheck` 确保无TypeScript类型错误
-  - [ ] 运行 `pnpm test` 确保所有测试通过
-  - [ ] 运行 `pnpm test:coverage` 确保测试覆盖率达到70%以上
+- [x] **任务1: 复制文件管理UI包创建统一文件管理UI包** (AC: 1)
+  - [x] **使用 `cp -r packages/file-management-ui packages/unified-file-management-ui` 命令直接复制整个文件夹**
+  - [x] 验证复制后的目录结构完整
+  - [x] 验证所有文件都已复制(src、tests、配置文件)
+
+- [x] **任务2: 修改包配置文件** (AC: 2)
+  - [x] 修改 `package.json` 包名:`@d8d/file-management-ui` → `@d8d/unified-file-management-ui`
+  - [x] 修改 `package.json` 描述:添加"unified"相关描述
+  - [x] 修改依赖:`@d8d/file-module` → `@d8d/unified-file-module`
+
+- [x] **任务3: 修改 API 客户端** (AC: 2, 3)
+  - [x] 修改 `src/api/fileClient.ts` 文件名为 `src/api/unifiedFileClient.ts`
+  - [x] 修改 `src/api/fileClient.ts` 中的路由导入:`fileRoutes` → `unifiedFileRoutes`
+  - [x] 修改 `src/api/index.ts` 导出
+  - [x] 确认 API 端点指向统一文件模块的管理员路由
+
+- [x] **任务4: 修改类型定义** (AC: 2)
+  - [x] 修改类型文件中的命名和引用
+  - [x] 确保类型推断使用 RPC 推断类型(而非直接导入 schema 类型)
+
+- [x] **任务5: 修改组件** (AC: 4, 5)
+  - [x] 更新组件中的 API 客户端导入
+  - [x] 更新 hooks 中的 API 客户端导入
+  - [x] 验证文件管理组件功能正常
+  - [x] 验证文件选择器组件功能正常
+
+- [x] **任务6: 编写组件测试** (AC: 6)
+  - [x] 更新测试文件中的 mock 路由和 API
+  - [x] 添加文件管理组件集成测试
+  - [x] 添加文件选择器组件集成测试
+  - [x] 验证所有测试通过
+
+- [x] **任务7: 类型检查和代码质量** (AC: 7)
+  - [x] 运行 `pnpm typecheck` 确保无TypeScript类型错误
+  - [x] 运行 `pnpm test` 确保所有测试通过
+  - [x] 运行 `pnpm test:coverage` 确保测试覆盖率达到70%以上
 
 ## Dev Notes
 
@@ -357,16 +357,38 @@ global.ResizeObserver = class MockResizeObserver {
 ## Dev Agent Record
 
 ### Agent Model Used
-_待开发代理填写_
+d8d-model (claude-opus-4-5-20251101)
 
 ### Debug Log References
-_待开发代理填写_
+无需要记录的调试问题
 
 ### Completion Notes List
-_待开发代理填写_
+1. 使用 `cp -r` 命令成功复制 `packages/file-management-ui` 到 `packages/unified-file-management-ui`
+2. 修改了 `package.json` 包名和依赖(`@d8d/unified-file-module`)
+3. 修改了 API 客户端:`fileClient.ts` → `unifiedFileClient.ts`,`fileClientManager` → `unifiedFileClientManager`
+4. 修改了所有组件和 hooks 中的 API 客户端导入
+5. 修改了测试文件中的 mock 路由
+6. 修复了 `UpdateFileDto` → `UpdateUnifiedFileDto` 导入问题
+7. 修复了 `uploadUser` → `uploadUserId` 属性问题(统一文件模块删除了 uploadUser 字段)
+8. 所有30个测试通过(4个测试文件)
 
 ### File List
-_待开发代理填写_
+**新增文件**:
+- `packages/unified-file-management-ui/package.json`
+- `packages/unified-file-management-ui/src/api/unifiedFileClient.ts`
+- `packages/unified-file-management-ui/src/components/FileManagement.tsx`
+- `packages/unified-file-management-ui/src/components/FileSelector.tsx`
+- `packages/unified-file-management-ui/src/components/MinioUploader.tsx`
+- `packages/unified-file-management-ui/src/hooks/useFileManagement.ts`
+- `packages/unified-file-management-ui/src/hooks/useFileSelector.ts`
+- `packages/unified-file-management-ui/src/types/file.ts`
+- `packages/unified-file-management-ui/src/utils/minio.ts`
+- `packages/unified-file-management-ui/tests/components/FileManagement.test.tsx`
+- `packages/unified-file-management-ui/tests/components/FileSelector.test.tsx`
+- `packages/unified-file-management-ui/tests/hooks/useFileManagement.test.tsx`
+
+**修改文件**:
+- `docs/stories/010.010.story.md` (更新状态和任务复选框)
 
 ## QA Results
 _QA代理待填写_

+ 18 - 0
packages/unified-file-management-ui/.eslintrc.js

@@ -0,0 +1,18 @@
+module.exports = {
+  root: true,
+  env: { browser: true, es2020: true },
+  extends: [
+    'eslint:recommended',
+    '@typescript-eslint/recommended',
+    '@typescript-eslint/recommended-requiring-type-checking',
+  ],
+  ignorePatterns: ['dist', '.eslintrc.cjs'],
+  parser: '@typescript-eslint/parser',
+  plugins: ['react-refresh'],
+  rules: {
+    'react-refresh/only-export-components': [
+      'warn',
+      { allowConstantExport: true },
+    ],
+  },
+};

+ 19 - 0
packages/unified-file-management-ui/build.config.ts

@@ -0,0 +1,19 @@
+import { defineBuildConfig } from 'unbuild';
+
+export default defineBuildConfig({
+  entries: [
+    'src/index',
+    'src/components/index',
+    'src/hooks/index',
+    'src/api/index',
+  ],
+  declaration: true,
+  clean: true,
+  rollup: {
+    emitCJS: true,
+    esbuild: {
+      target: 'es2022',
+      jsx: 'automatic',
+    },
+  },
+});

+ 36 - 0
packages/unified-file-management-ui/eslint.config.js

@@ -0,0 +1,36 @@
+import tseslint from '@typescript-eslint/eslint-plugin';
+import tsparser from '@typescript-eslint/parser';
+
+export default [
+  {
+    files: ['**/*.{ts,tsx}'],
+    ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
+    languageOptions: {
+      parser: tsparser,
+      ecmaVersion: 'latest',
+      sourceType: 'module',
+      parserOptions: {
+        ecmaFeatures: {
+          jsx: true,
+        },
+      },
+    },
+    plugins: {
+      '@typescript-eslint': tseslint,
+    },
+    rules: {
+      ...tseslint.configs.recommended.rules,
+
+      // TypeScript specific rules
+      '@typescript-eslint/no-unused-vars': 'error',
+      '@typescript-eslint/no-explicit-any': 'warn',
+      '@typescript-eslint/explicit-function-return-type': 'off',
+      '@typescript-eslint/explicit-module-boundary-types': 'off',
+
+      // General rules
+      'no-console': 'warn',
+      'prefer-const': 'error',
+      'no-var': 'error',
+    },
+  },
+];

+ 95 - 0
packages/unified-file-management-ui/package.json

@@ -0,0 +1,95 @@
+{
+  "name": "@d8d/unified-file-management-ui",
+  "version": "1.0.0",
+  "description": "统一文件管理界面包 - 提供无租户隔离的文件管理前端界面,包括文件上传下载、CRUD操作、文件预览、搜索过滤等功能",
+  "type": "module",
+  "main": "src/index.ts",
+  "types": "src/index.ts",
+  "exports": {
+    ".": {
+      "types": "./src/index.ts",
+      "import": "./src/index.ts",
+      "require": "./src/index.ts"
+    },
+    "./components": {
+      "types": "./src/components/index.ts",
+      "import": "./src/components/index.ts",
+      "require": "./src/components/index.ts"
+    },
+    "./hooks": {
+      "types": "./src/hooks/index.ts",
+      "import": "./src/hooks/index.ts",
+      "require": "./src/hooks/index.ts"
+    },
+    "./api": {
+      "types": "./src/api/index.ts",
+      "import": "./src/api/index.ts",
+      "require": "./src/api/index.ts"
+    }
+  },
+  "files": [
+    "src"
+  ],
+  "scripts": {
+    "build": "unbuild",
+    "dev": "tsc --watch",
+    "test": "vitest run",
+    "test:watch": "vitest",
+    "test:coverage": "vitest run --coverage",
+    "lint": "eslint src --ext .ts,.tsx",
+    "typecheck": "tsc --noEmit"
+  },
+  "dependencies": {
+    "@d8d/shared-types": "workspace:*",
+    "@d8d/shared-ui-components": "workspace:*",
+    "@d8d/unified-file-module": "workspace:*",
+    "@hookform/resolvers": "^5.2.1",
+    "@tanstack/react-query": "^5.90.9",
+    "axios": "^1.7.9",
+    "class-variance-authority": "^0.7.1",
+    "clsx": "^2.1.1",
+    "date-fns": "^4.1.0",
+    "dayjs": "^1.11.13",
+    "hono": "^4.8.5",
+    "lucide-react": "^0.536.0",
+    "react": "^19.1.0",
+    "react-dom": "^19.1.0",
+    "react-hook-form": "^7.61.1",
+    "react-router": "^7.1.3",
+    "sonner": "^2.0.7",
+    "tailwind-merge": "^3.3.1",
+    "zod": "^4.0.15"
+  },
+  "devDependencies": {
+    "@testing-library/jest-dom": "^6.8.0",
+    "@testing-library/react": "^16.3.0",
+    "@testing-library/user-event": "^14.6.1",
+    "@types/node": "^22.10.2",
+    "@types/react": "^19.2.2",
+    "@types/react-dom": "^19.2.3",
+    "@typescript-eslint/eslint-plugin": "^8.18.1",
+    "@typescript-eslint/parser": "^8.18.1",
+    "eslint": "^9.17.0",
+    "jsdom": "^26.0.0",
+    "typescript": "^5.8.3",
+    "unbuild": "^3.4.0",
+    "vitest": "^4.0.9"
+  },
+  "peerDependencies": {
+    "react": "^19.1.0",
+    "react-dom": "^19.1.0"
+  },
+  "keywords": [
+    "unified",
+    "file",
+    "management",
+    "upload",
+    "download",
+    "ui",
+    "react",
+    "crud",
+    "minio"
+  ],
+  "author": "D8D Team",
+  "license": "MIT"
+}

+ 18 - 0
packages/unified-file-management-ui/src/api/index.ts

@@ -0,0 +1,18 @@
+// 导出API客户端
+export { unifiedFileClient, unifiedFileClientManager } from './unifiedFileClient';
+
+// 导出API相关类型
+export type {
+  FileListResponse,
+  FileType,
+  UploadPolicyResponse,
+  MultipartUploadPolicyResponse,
+  UpdateFileRequest,
+  FileQueryParams,
+  FileUploadParams,
+  MultipartUploadParams,
+  FileOperationState,
+  FilePreviewOptions,
+  FileSelectorState,
+  FileManagementState
+} from '../types/file';

+ 44 - 0
packages/unified-file-management-ui/src/api/unifiedFileClient.ts

@@ -0,0 +1,44 @@
+import { unifiedFileRoutes } from '@d8d/unified-file-module';
+import { rpcClient } from '@d8d/shared-ui-components/utils/hc';
+
+class UnifiedFileClientManager {
+  private static instance: UnifiedFileClientManager;
+  private client: ReturnType<typeof rpcClient<typeof unifiedFileRoutes>> | null = null;
+
+  private constructor() {}
+
+  public static getInstance(): UnifiedFileClientManager {
+    if (!UnifiedFileClientManager.instance) {
+      UnifiedFileClientManager.instance = new UnifiedFileClientManager();
+    }
+    return UnifiedFileClientManager.instance;
+  }
+
+  // 初始化客户端
+  public init(baseUrl: string = '/'): ReturnType<typeof rpcClient<typeof unifiedFileRoutes>> {
+    return this.client = rpcClient<typeof unifiedFileRoutes>(baseUrl);
+  }
+
+  // 获取客户端实例
+  public get(): ReturnType<typeof rpcClient<typeof unifiedFileRoutes>> {
+    if (!this.client) {
+      return this.init()
+    }
+    return this.client;
+  }
+
+  // 重置客户端(用于测试或重新初始化)
+  public reset(): void {
+    this.client = null;
+  }
+}
+
+// 导出单例实例
+const unifiedFileClientManager = UnifiedFileClientManager.getInstance();
+
+// 导出类型定义(用于类型检查)
+export const unifiedFileClient: ReturnType<typeof rpcClient<typeof unifiedFileRoutes>> = unifiedFileClientManager.get()
+
+export {
+  unifiedFileClientManager
+}

+ 491 - 0
packages/unified-file-management-ui/src/components/FileManagement.tsx

@@ -0,0 +1,491 @@
+import React, { useState } from 'react';
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
+import { Button } from '@d8d/shared-ui-components/components/ui/button';
+import { Input } from '@d8d/shared-ui-components/components/ui/input';
+import { Card, CardContent, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
+import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
+import { useForm } from 'react-hook-form';
+import { zodResolver } from '@hookform/resolvers/zod';
+import { toast } from 'sonner';
+import { Eye, Download, Edit, Trash2, Search, FileText, Upload } from 'lucide-react';
+import { unifiedFileClientManager, unifiedFileClient } from '../api';
+import type { InferResponseType, InferRequestType } from 'hono/client';
+import dayjs from 'dayjs';
+import MinioUploader from './MinioUploader';
+import { UpdateUnifiedFileDto } from '@d8d/unified-file-module/schemas';
+
+// 定义类型 - 使用 RPC 推断类型
+type FileItem = InferResponseType<typeof unifiedFileClient.index.$get, 200>['data'][0];
+type FileListResponse = InferResponseType<typeof unifiedFileClient.index.$get, 200>;
+type UpdateFileRequest = InferRequestType<typeof unifiedFileClient[':id']['$put']>['json'];
+
+// FileFormData 使用 RPC 推断类型,而非从 schema 获取
+type FileFormData = UpdateFileRequest;
+
+export interface FileManagementProps {
+  /** 自定义类名 */
+  className?: string;
+  /** 是否显示上传按钮 */
+  showUploadButton?: boolean;
+  /** 是否显示搜索功能 */
+  showSearch?: boolean;
+  /** 默认页面大小 */
+  defaultPageSize?: number;
+}
+
+export const FileManagement: React.FC<FileManagementProps> = ({
+  className = '',
+  showUploadButton = true,
+  showSearch = true,
+  defaultPageSize = 10,
+}) => {
+  const [isModalOpen, setIsModalOpen] = useState(false);
+  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
+  const [editingFile, setEditingFile] = useState<FileItem | null>(null);
+  const [searchText, setSearchText] = useState('');
+  const [pagination, setPagination] = useState({
+    current: 1,
+    pageSize: defaultPageSize,
+    total: 0,
+  });
+  const [deleteFileId, setDeleteFileId] = useState<number | null>(null);
+  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+
+  const queryClient = useQueryClient();
+
+  // 表单初始化
+  const form = useForm<FileFormData>({
+    resolver: zodResolver(UpdateUnifiedFileDto),
+    defaultValues: {
+      name: '',
+      description: '',
+    },
+  });
+
+  // 获取文件列表数据
+  const fetchFiles = async ({ page, pageSize }: { page: number; pageSize: number }): Promise<FileListResponse> => {
+    const response = await unifiedFileClientManager.get().index.$get({ query: { page, pageSize, keyword: searchText } });
+    if (!response.ok) throw new Error('Failed to fetch files');
+    return await response.json() as FileListResponse;
+  };
+
+  const { data, isLoading, error } = useQuery({
+    queryKey: ['files', pagination.current, pagination.pageSize, searchText],
+    queryFn: () => fetchFiles({ page: pagination.current, pageSize: pagination.pageSize }),
+  });
+
+  // 更新文件记录
+  const updateFile = useMutation({
+    mutationFn: ({ id, data }: { id: number; data: UpdateFileRequest }) =>
+      unifiedFileClientManager.get()[':id'].$put({ param: { id: Number(id) }, json: data }),
+    onSuccess: () => {
+      toast.success('文件记录更新成功');
+      queryClient.invalidateQueries({ queryKey: ['files'] });
+      setIsModalOpen(false);
+      setEditingFile(null);
+    },
+    onError: (error: Error) => {
+      toast.error(`操作失败: ${error.message}`);
+    }
+  });
+
+  // 删除文件记录
+  const deleteFile = useMutation({
+    mutationFn: (id: number) => unifiedFileClientManager.get()[':id'].$delete({ param: { id: Number(id) } }),
+    onSuccess: () => {
+      toast.success('文件记录删除成功');
+      queryClient.invalidateQueries({ queryKey: ['files'] });
+    },
+    onError: (error: Error) => {
+      toast.error(`删除失败: ${error.message}`);
+    }
+  });
+
+  // 处理文件下载
+  const handleDownload = (record: FileItem) => {
+    const a = document.createElement('a');
+    a.href = record.fullUrl;
+    a.download = record.name;
+    document.body.appendChild(a);
+    a.click();
+    document.body.removeChild(a);
+  };
+
+  // 处理文件预览
+  const handlePreview = (record: FileItem) => {
+    if (isPreviewable(record.type)) {
+      window.open(record.fullUrl, '_blank');
+    } else {
+      toast.warning('该文件类型不支持预览');
+    }
+  };
+
+  // 检查是否为可预览的文件类型
+  const isPreviewable = (fileType: string | null) => {
+    if (!fileType) return false;
+    return fileType.startsWith('image/') || fileType.startsWith('video/');
+  };
+
+  // 处理上传成功回调
+  const handleUploadSuccess = () => {
+    toast.success('文件上传成功');
+    queryClient.invalidateQueries({ queryKey: ['files'] });
+  };
+
+  // 处理上传失败回调
+  const handleUploadError = (error: Error) => {
+    toast.error(`上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
+  };
+
+  // 显示编辑弹窗
+  const showEditModal = (record: FileItem) => {
+    setEditingFile(record);
+    setIsModalOpen(true);
+    form.reset({
+      name: record.name,
+      description: record.description || '',
+    });
+  };
+
+  // 处理表单提交
+  const handleFormSubmit = async (data: FileFormData) => {
+    if (editingFile) {
+      await updateFile.mutateAsync({
+        id: editingFile.id,
+        data: {
+          name: data.name,
+          description: data.description,
+        }
+      });
+    }
+  };
+
+  // 处理删除确认
+  const handleDeleteConfirm = () => {
+    if (deleteFileId) {
+      deleteFile.mutate(deleteFileId);
+      setIsDeleteDialogOpen(false);
+      setDeleteFileId(null);
+    }
+  };
+
+  const handleSearch = () => {
+    setPagination({ ...pagination, current: 1 });
+  };
+
+  // 格式化文件大小
+  const formatFileSize = (bytes: number | null) => {
+    if (!bytes || bytes === 0) return '0 Bytes';
+    const k = 1024;
+    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+    const i = Math.floor(Math.log(bytes) / Math.log(k));
+    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+  };
+
+  // 分页数据
+  const tablePagination = data?.pagination || pagination;
+
+  if (error) {
+    return (
+      <div className={`p-6 ${className}`}>
+        <Card>
+          <CardContent className="text-center py-8">
+            <FileText className="h-12 w-12 mx-auto text-gray-400 mb-4" />
+            <p className="text-gray-600">获取文件列表失败</p>
+          </CardContent>
+        </Card>
+      </div>
+    );
+  }
+
+  return (
+    <div className={`p-6 space-y-6 ${className}`}>
+      <div className="flex justify-between items-center">
+        <h1 className="text-3xl font-bold">文件管理</h1>
+        {showUploadButton && (
+          <Button
+            onClick={() => setIsUploadModalOpen(true)}
+            data-testid="upload-file-button"
+          >
+            <Upload className="h-4 w-4 mr-2" />
+            上传文件
+          </Button>
+        )}
+      </div>
+
+      <Card>
+        <CardHeader>
+          <CardTitle>文件列表</CardTitle>
+        </CardHeader>
+        <CardContent>
+          {showSearch && (
+            <div className="mb-4 flex gap-4">
+              <div className="flex-1">
+                <Input
+                  placeholder="搜索文件名称或类型"
+                  value={searchText}
+                  onChange={(e) => setSearchText(e.target.value)}
+                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
+                  className="max-w-sm"
+                />
+              </div>
+              <Button onClick={handleSearch}>
+                <Search className="h-4 w-4 mr-2" />
+                搜索
+              </Button>
+            </div>
+          )}
+
+          <div className="overflow-x-auto">
+            <Table>
+              <TableHeader>
+                <TableRow>
+                  <TableHead className="w-16">ID</TableHead>
+                  <TableHead>预览</TableHead>
+                  <TableHead>文件名称</TableHead>
+                  <TableHead>文件类型</TableHead>
+                  <TableHead>文件大小</TableHead>
+                  <TableHead>上传时间</TableHead>
+                  <TableHead>上传用户</TableHead>
+                  <TableHead className="text-right">操作</TableHead>
+                </TableRow>
+              </TableHeader>
+              <TableBody>
+                {isLoading ? (
+                  <TableRow>
+                    <TableCell colSpan={7} className="text-center">
+                      <div className="flex justify-center items-center py-8">
+                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
+                      </div>
+                    </TableCell>
+                  </TableRow>
+                ) : data?.data?.length === 0 ? (
+                  <TableRow>
+                    <TableCell colSpan={7} className="text-center py-8">
+                      <FileText className="h-12 w-12 mx-auto text-gray-400 mb-4" />
+                      <p className="text-gray-600">暂无文件</p>
+                    </TableCell>
+                  </TableRow>
+                ) : (
+                  data?.data?.map((file) => (
+                    <TableRow key={file.id}>
+                      <TableCell className="font-medium">{file.id}</TableCell>
+                      <TableCell>
+                        {isPreviewable(file.type) ? (
+                          <img
+                            src={file.fullUrl}
+                            alt={file.name}
+                            className="w-12 h-12 object-cover rounded border cursor-pointer hover:opacity-80 transition-opacity"
+                            onClick={() => handlePreview(file)}
+                            title="点击查看大图"
+                          />
+                        ) : (
+                          <div className="w-12 h-12 flex items-center justify-center bg-gray-100 rounded border">
+                            <FileText className="h-6 w-6 text-gray-400" />
+                          </div>
+                        )}
+                      </TableCell>
+                      <TableCell>
+                        <div className="max-w-xs truncate" title={file.name}>
+                          {file.name}
+                        </div>
+                      </TableCell>
+                      <TableCell>
+                        <Badge variant="secondary">{file.type}</Badge>
+                      </TableCell>
+                      <TableCell>{formatFileSize(file.size)}</TableCell>
+                      <TableCell>
+                        {file.uploadTime ? dayjs(file.uploadTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
+                      </TableCell>
+                      <TableCell>
+                        {file.uploadUserId || '-'}
+                      </TableCell>
+                      <TableCell className="text-right">
+                        <div className="flex justify-end gap-2">
+                          <Button
+                            variant="ghost"
+                            size="sm"
+                            onClick={() => handlePreview(file)}
+                            disabled={!isPreviewable(file.type)}
+                            title={isPreviewable(file.type) ? '预览文件' : '该文件类型不支持预览'}
+                          >
+                            <Eye className="h-4 w-4" />
+                          </Button>
+                          <Button
+                            variant="ghost"
+                            size="sm"
+                            onClick={() => handleDownload(file)}
+                            title="下载文件"
+                          >
+                            <Download className="h-4 w-4" />
+                          </Button>
+                          <Button
+                            variant="ghost"
+                            size="sm"
+                            onClick={() => showEditModal(file)}
+                            title="编辑文件信息"
+                          >
+                            <Edit className="h-4 w-4" />
+                          </Button>
+                          <Button
+                            variant="ghost"
+                            size="sm"
+                            onClick={() => {
+                              setDeleteFileId(file.id);
+                              setIsDeleteDialogOpen(true);
+                            }}
+                            className="text-red-600 hover:text-red-700"
+                            title="删除文件"
+                          >
+                            <Trash2 className="h-4 w-4" />
+                          </Button>
+                        </div>
+                      </TableCell>
+                    </TableRow>
+                  ))
+                )}
+              </TableBody>
+            </Table>
+          </div>
+
+          {/* 分页 */}
+          {tablePagination.total > 0 && (
+            <div className="flex justify-between items-center mt-4">
+              <div className="text-sm text-gray-600">
+                显示 {((tablePagination.current - 1) * tablePagination.pageSize + 1)}-
+                {Math.min(tablePagination.current * tablePagination.pageSize, tablePagination.total)} 条,
+                共 {tablePagination.total} 条
+              </div>
+              <div className="flex gap-2">
+                <Button
+                  variant="outline"
+                  size="sm"
+                  disabled={tablePagination.current <= 1}
+                  onClick={() => setPagination({ ...pagination, current: tablePagination.current - 1 })}
+                >
+                  上一页
+                </Button>
+                <span className="px-3 py-1 text-sm">
+                  第 {tablePagination.current} 页
+                </span>
+                <Button
+                  variant="outline"
+                  size="sm"
+                  disabled={tablePagination.current >= Math.ceil(tablePagination.total / tablePagination.pageSize)}
+                  onClick={() => setPagination({ ...pagination, current: tablePagination.current + 1 })}
+                >
+                  下一页
+                </Button>
+              </div>
+            </div>
+          )}
+        </CardContent>
+      </Card>
+
+      {/* 上传文件对话框 */}
+      <Dialog open={isUploadModalOpen} onOpenChange={setIsUploadModalOpen}>
+        <DialogContent className="sm:max-w-[600px]" data-testid="upload-file-dialog">
+          <DialogHeader>
+            <DialogTitle>上传文件</DialogTitle>
+            <DialogDescription>
+              选择要上传的文件,支持拖拽上传
+            </DialogDescription>
+          </DialogHeader>
+
+          <div className="py-4">
+            <MinioUploader
+              uploadPath="/files"
+              maxSize={500}
+              multiple={false}
+              onUploadSuccess={() => {
+                handleUploadSuccess();
+                setIsUploadModalOpen(false);
+              }}
+              onUploadError={handleUploadError}
+              buttonText="点击或拖拽上传文件"
+              tipText="支持单文件上传,单个文件大小不超过500MB"
+              size="default"
+            />
+          </div>
+
+          <DialogFooter>
+            <Button variant="outline" onClick={() => setIsUploadModalOpen(false)}>
+              取消
+            </Button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+
+      {/* 编辑对话框 */}
+      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
+        <DialogContent className="sm:max-w-[500px]">
+          <DialogHeader>
+            <DialogTitle>编辑文件信息</DialogTitle>
+            <DialogDescription>
+              修改文件的基本信息
+            </DialogDescription>
+          </DialogHeader>
+          <Form {...form}>
+            <form onSubmit={form.handleSubmit(handleFormSubmit)} className="space-y-4">
+              <FormField
+                control={form.control}
+                name="name"
+                render={({ field }) => (
+                  <FormItem>
+                    <FormLabel>文件名称</FormLabel>
+                    <FormControl>
+                      <Input placeholder="请输入文件名称" {...field} />
+                    </FormControl>
+                    <FormMessage />
+                  </FormItem>
+                )}
+              />
+              <FormField
+                control={form.control}
+                name="description"
+                render={({ field }) => (
+                  <FormItem>
+                    <FormLabel>文件描述</FormLabel>
+                    <FormControl>
+                      <Input placeholder="请输入文件描述" {...field} />
+                    </FormControl>
+                    <FormMessage />
+                  </FormItem>
+                )}
+              />
+              <DialogFooter>
+                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
+                  取消
+                </Button>
+                <Button type="submit" disabled={updateFile.isPending}>
+                  {updateFile.isPending ? '保存中...' : '保存'}
+                </Button>
+              </DialogFooter>
+            </form>
+          </Form>
+        </DialogContent>
+      </Dialog>
+
+      {/* 删除确认对话框 */}
+      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
+        <DialogContent>
+          <DialogHeader>
+            <DialogTitle>确认删除</DialogTitle>
+            <DialogDescription>
+              确定要删除这个文件记录吗?此操作不可恢复。
+            </DialogDescription>
+          </DialogHeader>
+          <DialogFooter>
+            <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>取消</Button>
+            <Button onClick={handleDeleteConfirm} className="bg-red-600 hover:bg-red-700">
+              确认删除
+            </Button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+    </div>
+  );
+};

+ 514 - 0
packages/unified-file-management-ui/src/components/FileSelector.tsx

@@ -0,0 +1,514 @@
+import React, { useState, useEffect } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { Button } from '@d8d/shared-ui-components/components/ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
+import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
+import { toast } from 'sonner';
+import { unifiedFileClientManager, unifiedFileClient } from '../api';
+import MinioUploader from './MinioUploader';
+import { Check, Upload, Eye, X, File as FileIcon, Image as ImageIcon } from 'lucide-react';
+import { cn } from '../utils/cn';
+import type { InferResponseType } from 'hono/client';
+
+type FileType = InferResponseType<typeof unifiedFileClient.index.$get, 200>['data'][0]
+
+export interface FileSelectorProps {
+  value?: number | null | number[];
+  onChange?: (fileId: number | null | number[]) => void;
+  accept?: string;
+  maxSize?: number;
+  uploadPath?: string;
+  previewSize?: 'small' | 'medium' | 'large';
+  showPreview?: boolean;
+  placeholder?: string;
+  title?: string;
+  description?: string;
+  filterType?: 'image' | 'all' | string;
+  allowMultiple?: boolean;
+}
+
+export const FileSelector: React.FC<FileSelectorProps> = ({
+  value,
+  onChange,
+  accept = '*/*',
+  maxSize = 10,
+  uploadPath = '/files',
+  previewSize = 'medium',
+  showPreview = true,
+  placeholder = '选择文件',
+  title = '选择文件',
+  description = '上传新文件或从已有文件中选择',
+  filterType = 'all',
+  allowMultiple = false,
+}) => {
+  const [isOpen, setIsOpen] = useState(false);
+  const [selectedFile, setSelectedFile] = useState<FileType | null>(null);
+  const [localSelectedFiles, setLocalSelectedFiles] = useState<number[]>([]);
+
+  // 获取当前选中的文件详情 - 支持单值和数组
+  const { data: currentFiles } = useQuery<FileType[]>({
+    queryKey: ['file-details', value, allowMultiple],
+    queryFn: async (): Promise<FileType[]> => {
+      if (!value) return [];
+
+      // 处理多选模式下的数组值
+      if (allowMultiple && Array.isArray(value)) {
+        if (value.length === 0) return [];
+
+        // 批量获取多个文件详情
+        const filePromises = value.map(async (fileId) => {
+          try {
+            const response = await unifiedFileClientManager.get()[':id']['$get']({ param: { id: Number(fileId) } });
+            if (response.status === 200) {
+              return response.json();
+            }
+            return null;
+          } catch {
+            return null;
+          }
+        });
+
+        const files = await Promise.all(filePromises);
+        return files.filter(file => file !== null);
+      }
+
+      // 处理单选模式下的单值
+      if (!Array.isArray(value)) {
+        const response = await unifiedFileClientManager.get()[':id']['$get']({ param: { id: Number(value) } });
+        if (response.status !== 200) throw new Error('获取文件详情失败');
+        return [await response.json()];
+      }
+
+      return [];
+    },
+    enabled: !!value,
+  });
+
+  // 当对话框打开时,设置当前选中的文件
+  useEffect(() => {
+    if (isOpen) {
+      if (allowMultiple) {
+        // 在多选模式下,使用 value 数组初始化本地选择
+        const initialSelection = Array.isArray(value) ? value : [];
+        setLocalSelectedFiles(initialSelection);
+      } else if (value && currentFiles && currentFiles.length > 0) {
+        setSelectedFile(currentFiles[0]);
+      }
+    }
+  }, [isOpen, value, currentFiles, allowMultiple]);
+
+  // 获取文件列表
+  const { data: filesData, isLoading, refetch } = useQuery({
+    queryKey: ['files-for-selection', filterType] as const,
+    queryFn: async () => {
+      const response = await unifiedFileClientManager.get().index.$get({
+        query: {
+          page: 1,
+          pageSize: 50,
+          ...(filterType !== 'all' && { keyword: filterType })
+        }
+      });
+      if (response.status !== 200) throw new Error('获取文件列表失败');
+      return response.json();
+    },
+    enabled: isOpen,
+  });
+
+  const files = filesData?.data?.filter((f) => {
+    if (filterType === 'all') return true;
+    if (filterType === 'image') return f?.type?.startsWith('image/');
+    return f?.type?.includes(filterType);
+  }) || [];
+
+  const handleSelectFile = (file: FileType) => {
+    if (allowMultiple) {
+      setLocalSelectedFiles(prev => {
+        const newSelection = prev.includes(file.id)
+          ? prev.filter(id => id !== file.id)
+          : [...prev, file.id];
+        return newSelection;
+      });
+    } else {
+      setSelectedFile(prevSelected => {
+        if (prevSelected?.id === file.id) {
+          return null;
+        }
+        return file;
+      });
+    }
+  };
+
+  const handleConfirm = () => {
+    if (allowMultiple) {
+      if (onChange) {
+        onChange(localSelectedFiles);
+      }
+      setIsOpen(false);
+      return;
+    }
+
+    if (!selectedFile) {
+      toast.warning('请选择一个文件');
+      return;
+    }
+    if (onChange) {
+      onChange(selectedFile.id);
+    }
+    setIsOpen(false);
+    setSelectedFile(null);
+  };
+
+  const handleCancel = () => {
+    setIsOpen(false);
+    setSelectedFile(null);
+    // 取消时重置为初始的 value 值
+    const initialSelection = allowMultiple && Array.isArray(value) ? value : [];
+    setLocalSelectedFiles(initialSelection);
+  };
+
+  const handleUploadSuccess = () => {
+    toast.success('文件上传成功!请从列表中选择新上传的文件');
+    refetch();
+  };
+
+  const getPreviewSize = () => {
+    switch (previewSize) {
+      case 'small':
+        return 'h-16 w-16';
+      case 'medium':
+        return 'h-24 w-24';
+      case 'large':
+        return 'h-32 w-32';
+      default:
+        return 'h-24 w-24';
+    }
+  };
+
+  const getFileIcon = (fileType: string) => {
+    if (fileType.startsWith('image/')) {
+      return <ImageIcon className="h-8 w-8 text-gray-400" />;
+    }
+    if (fileType.startsWith('video/')) {
+      return <FileIcon className="h-8 w-8 text-blue-500" />;
+    }
+    if (fileType.startsWith('audio/')) {
+      return <FileIcon className="h-8 w-8 text-green-500" />;
+    }
+    if (fileType.includes('pdf')) {
+      return <FileIcon className="h-8 w-8 text-red-500" />;
+    }
+    if (fileType.includes('text')) {
+      return <FileIcon className="h-8 w-8 text-gray-600" />;
+    }
+    return <FileIcon className="h-8 w-8 text-gray-400" />;
+  };
+
+  const handleRemoveFile = (e: React.MouseEvent) => {
+    e.stopPropagation();
+    if (allowMultiple && Array.isArray(value)) {
+      // 在多选模式下,移除所有选中文件
+      onChange?.([]);
+    } else {
+      // 在单选模式下,设置为null
+      onChange?.(null);
+    }
+  };
+
+  const isSelected = (fileId: number) => {
+    if (allowMultiple) {
+      return localSelectedFiles.includes(fileId);
+    }
+    return selectedFile?.id === fileId;
+  };
+
+  return (
+    <>
+      <div className="space-y-4">
+        {showPreview && (
+          <div className="flex items-start space-x-4">
+            {/* 预览区域 */}
+            <div className="flex flex-wrap gap-2">
+              {allowMultiple && Array.isArray(currentFiles) && currentFiles.length > 0 ? (
+                // 多选模式下的预览
+                currentFiles.map((file) => (
+                  <div key={file.id} className="relative group">
+                    <div
+                      className={cn(
+                        getPreviewSize(),
+                        "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
+                      )}
+                      onClick={() => setIsOpen(true)}
+                    >
+                      {file?.type ? (
+                        <div className="w-full h-full flex items-center justify-center">
+                          {file.type.startsWith('image/') ? (
+                            <img
+                              src={file.fullUrl}
+                              alt={file.name}
+                              className="w-full h-full object-cover"
+                            />
+                          ) : (
+                            <div className="flex flex-col items-center justify-center text-gray-400">
+                              {getFileIcon(file.type)}
+                              <span className="text-xs mt-1 text-center px-1 truncate max-w-full">
+                                {file.name}
+                              </span>
+                            </div>
+                          )}
+                        </div>
+                      ) : (
+                        <div className="flex flex-col items-center justify-center text-gray-400">
+                          <FileIcon className="h-8 w-8 mb-1" />
+                          <span className="text-xs">{placeholder}</span>
+                        </div>
+                      )}
+                    </div>
+
+                    <button
+                      type="button"
+                      className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
+                      onClick={(e) => {
+                        e.stopPropagation();
+                        if (allowMultiple && Array.isArray(value)) {
+                          const newValue = value.filter(id => id !== file.id);
+                          onChange?.(newValue);
+                        }
+                      }}
+                    >
+                      <X className="h-3 w-3" />
+                    </button>
+                  </div>
+                ))
+              ) : !allowMultiple && currentFiles && currentFiles.length > 0 ? (
+                // 单选模式下的预览
+                <div className="relative group">
+                  <div
+                    className={cn(
+                      getPreviewSize(),
+                      "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
+                    )}
+                    onClick={() => setIsOpen(true)}
+                  >
+                    {currentFiles[0]?.type ? (
+                      <div className="w-full h-full flex items-center justify-center">
+                        {currentFiles[0].type.startsWith('image/') ? (
+                          <img
+                            src={currentFiles[0].fullUrl}
+                            alt={currentFiles[0].name}
+                            className="w-full h-full object-cover"
+                          />
+                        ) : (
+                          <div className="flex flex-col items-center justify-center text-gray-400">
+                            {getFileIcon(currentFiles[0].type)}
+                            <span className="text-xs mt-1 text-center">{currentFiles[0].name}</span>
+                          </div>
+                        )}
+                      </div>
+                    ) : (
+                      <div className="flex flex-col items-center justify-center text-gray-400">
+                        <FileIcon className="h-8 w-8 mb-1" />
+                        <span className="text-xs">{placeholder}</span>
+                      </div>
+                    )}
+                  </div>
+
+                  {currentFiles[0] && (
+                    <button
+                      type="button"
+                      className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
+                      onClick={handleRemoveFile}
+                    >
+                      <X className="h-3 w-3" />
+                    </button>
+                  )}
+                </div>
+              ) : (
+                // 没有选中文件时的占位符
+                <div
+                  className={cn(
+                    getPreviewSize(),
+                    "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
+                  )}
+                  onClick={() => setIsOpen(true)}
+                >
+                  <div className="flex flex-col items-center justify-center text-gray-400">
+                    <FileIcon className="h-8 w-8 mb-1" />
+                    <span className="text-xs">{placeholder}</span>
+                  </div>
+                </div>
+              )}
+            </div>
+
+            <div className="space-y-2">
+              <Button
+                type="button"
+                variant="outline"
+                onClick={() => setIsOpen(true)}
+                className="text-sm"
+                data-testid="file-selector-button"
+              >
+                {((allowMultiple && currentFiles && currentFiles.length > 0) ||
+                  (!allowMultiple && currentFiles && currentFiles.length > 0)) ? '更换文件' : placeholder}
+              </Button>
+              {!allowMultiple && currentFiles && currentFiles.length > 0 && (
+                <p className="text-xs text-muted-foreground truncate w-40 sm:w-64">
+                  当前: {currentFiles[0].name}
+                </p>
+              )}
+              {allowMultiple && currentFiles && currentFiles.length > 0 && (
+                <p className="text-xs text-muted-foreground">
+                  已选择 {currentFiles.length} 个文件
+                </p>
+              )}
+            </div>
+          </div>
+        )}
+
+        {!showPreview && (
+          <Button
+            type="button"
+            variant="outline"
+            onClick={() => setIsOpen(true)}
+            className="w-full"
+          >
+            {currentFiles ? '更换文件' : placeholder}
+          </Button>
+        )}
+      </div>
+
+      <Dialog open={isOpen} onOpenChange={setIsOpen}>
+        <DialogContent className="max-w-4xl max-h-[90vh]" data-testid="file-selector-dialog">
+          <DialogHeader>
+            <DialogTitle>{title}</DialogTitle>
+            <DialogDescription>
+              {description}
+            </DialogDescription>
+          </DialogHeader>
+
+          <div className="space-y-4">
+            {/* 文件列表 */}
+            <div className="space-y-2 max-h-96 overflow-y-auto p-1">
+              {isLoading ? (
+                <Card>
+                  <CardContent className="text-center py-8">
+                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
+                    <p className="text-gray-500 mt-2">加载中...</p>
+                  </CardContent>
+                </Card>
+              ) : (
+                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
+                  {/* 上传区域 - 作为第一项 */}
+                  <div className="relative cursor-pointer transition-all duration-200">
+                    <div className="rounded-lg border-2 border-dashed border-gray-300 hover:border-primary transition-colors hover:scale-105">
+                      <div className="p-2 h-20 flex items-center justify-center">
+                        <MinioUploader
+                          uploadPath={uploadPath}
+                          accept={accept}
+                          maxSize={maxSize}
+                          onUploadSuccess={handleUploadSuccess}
+                          buttonText="上传"
+                          size="minimal"
+                          displayMode="card"
+                          showUploadList={false}
+                        />
+                      </div>
+                    </div>
+                    <p className="text-xs text-center mt-1 text-muted-foreground">
+                      上传新文件
+                    </p>
+                  </div>
+
+                  {/* 现有文件列表 */}
+                  {files.map((file) => (
+                    <div
+                      key={file.id}
+                      className={cn(
+                        "relative cursor-pointer transition-all duration-200",
+                        "hover:scale-105"
+                      )}
+                      onClick={() => handleSelectFile(file)}
+                    >
+                      <div
+                        className={cn(
+                          "relative rounded-lg overflow-hidden border-2 aspect-square",
+                          isSelected(file.id)
+                            ? "border-primary ring-2 ring-primary ring-offset-2"
+                            : "border-gray-200 hover:border-primary"
+                        )}
+                      >
+                        {file?.type?.startsWith('image/') ? (
+                          <img
+                            src={file.fullUrl}
+                            alt={file.name}
+                            className="w-full h-full object-cover"
+                          />
+                        ) : (
+                          <div className="w-full h-full flex flex-col items-center justify-center bg-gray-50 p-2">
+                            {file.type && getFileIcon(file.type)}
+                            <p className="text-xs text-center mt-1 truncate max-w-full">
+                              {file.name}
+                            </p>
+                          </div>
+                        )}
+
+                        {isSelected(file.id) && (
+                          <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
+                            <Check className="h-6 w-6 text-white bg-primary rounded-full p-1" />
+                          </div>
+                        )}
+
+                        <div className="absolute top-1 right-1">
+                          <Eye
+                            className="h-4 w-4 text-white bg-black/50 rounded-full p-0.5 cursor-pointer hover:bg-black/70"
+                            onClick={(e) => {
+                              e.stopPropagation();
+                              window.open(file.fullUrl, '_blank');
+                            }}
+                          />
+                        </div>
+                      </div>
+
+                      <p className="text-xs text-center mt-1 truncate">
+                        {file.name}
+                      </p>
+                    </div>
+                  ))}
+
+                  {/* 空状态 - 当没有文件时显示 */}
+                  {files.length === 0 && (
+                    <div className="col-span-full">
+                      <Card>
+                        <CardContent className="text-center py-8">
+                          <div className="flex flex-col items-center">
+                            <Upload className="h-12 w-12 text-gray-400 mb-4" />
+                            <p className="text-gray-600">暂无文件</p>
+                            <p className="text-sm text-gray-500 mt-2">请上传文件</p>
+                          </div>
+                        </CardContent>
+                      </Card>
+                    </div>
+                  )}
+                </div>
+              )}
+            </div>
+          </div>
+
+          <DialogFooter>
+            <Button type="button" variant="outline" onClick={handleCancel}>
+              取消
+            </Button>
+            <Button
+              type="button"
+              onClick={handleConfirm}
+              disabled={allowMultiple ? localSelectedFiles.length === 0 : !selectedFile}
+            >
+              {allowMultiple ? `确认选择 (${localSelectedFiles.length})` : '确认选择'}
+            </Button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+    </>
+  );
+};
+
+export default FileSelector;

+ 468 - 0
packages/unified-file-management-ui/src/components/MinioUploader.tsx

@@ -0,0 +1,468 @@
+import React, { useState, useCallback } from 'react';
+import { Button } from '@d8d/shared-ui-components/components/ui/button';
+import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
+import { Progress } from '@d8d/shared-ui-components/components/ui/progress';
+import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
+import { toast } from 'sonner';
+import { Upload, X, CheckCircle, Loader2, FileText } from 'lucide-react';
+import { uploadMinIOWithPolicy, MinioProgressEvent } from '../utils/minio';
+
+export interface MinioUploaderProps {
+  /** 上传路径 */
+  uploadPath: string;
+  /** 允许的文件类型,如['image/*', '.pdf'] */
+  accept?: string;
+  /** 最大文件大小(MB) */
+  maxSize?: number;
+  /** 是否允许多文件上传 */
+  multiple?: boolean;
+  /** 上传成功回调 */
+  onUploadSuccess?: (fileKey: string, fileUrl: string, file: File) => void;
+  /** 上传失败回调 */
+  onUploadError?: (error: Error, file: File) => void;
+  /** 自定义上传按钮文本 */
+  buttonText?: string;
+  /** 自定义提示文本 */
+  tipText?: string;
+  /** 上传模式:拖放模式或传统模式 */
+  uploadMode?: 'dragdrop' | 'traditional';
+  /** 是否显示已上传文件列表 */
+  showUploadList?: boolean;
+  /** 已上传文件列表标题 */
+  uploadListTitle?: string;
+  /** 组件尺寸模式 */
+  size?: 'default' | 'compact' | 'minimal';
+  /** 显示模式:卡片模式或完整模式 */
+  displayMode?: 'full' | 'card';
+}
+
+// 定义上传文件状态
+interface UploadFile {
+  uid: string;
+  name: string;
+  size: number;
+  type?: string;
+  status: 'uploading' | 'success' | 'error';
+  percent: number;
+  error?: string;
+  url?: string;
+}
+
+const MinioUploader: React.FC<MinioUploaderProps> = ({
+  uploadPath = '/',
+  accept,
+  maxSize = 500, // 默认最大500MB
+  multiple = false,
+  onUploadSuccess,
+  onUploadError,
+  buttonText = '点击或拖拽上传文件',
+  tipText = '支持单文件或多文件上传,单个文件大小不超过500MB',
+  uploadMode = 'dragdrop',
+  showUploadList = true,
+  uploadListTitle = '上传进度',
+  size = 'default',
+  displayMode = 'full'
+}) => {
+  const [fileList, setFileList] = useState<UploadFile[]>([]);
+  const [dragActive, setDragActive] = useState(false);
+
+  // 根据尺寸模式获取样式配置
+  const getSizeConfig = () => {
+    switch (size) {
+      case 'minimal':
+        return {
+          container: 'p-3',
+          icon: 'h-8 w-8',
+          title: 'text-sm',
+          description: 'text-xs',
+          button: 'h-8 px-3 text-xs',
+          spacing: 'space-y-2',
+          fileList: 'space-y-2',
+          cardPadding: 'p-3',
+          progressHeight: 'h-1'
+        };
+      case 'compact':
+        return {
+          container: 'p-4',
+          icon: 'h-10 w-10',
+          title: 'text-base',
+          description: 'text-sm',
+          button: 'h-9 px-4 text-sm',
+          spacing: 'space-y-3',
+          fileList: 'space-y-3',
+          cardPadding: 'p-4',
+          progressHeight: 'h-2'
+        };
+      default:
+        return {
+          container: 'p-6',
+          icon: 'h-12 w-12',
+          title: 'text-lg',
+          description: 'text-sm',
+          button: 'h-10 px-4',
+          spacing: 'space-y-4',
+          fileList: 'space-y-4',
+          cardPadding: 'p-6',
+          progressHeight: 'h-2'
+        };
+    }
+  };
+
+  // 处理上传进度
+  const handleProgress = useCallback((uid: string, event: MinioProgressEvent) => {
+    setFileList(prev =>
+      prev.map(item => {
+        if (item.uid === uid) {
+          return {
+            ...item,
+            status: event.stage === 'error' ? 'error' : 'uploading',
+            percent: event.progress,
+            error: event.stage === 'error' ? event.message : undefined
+          };
+        }
+        return item;
+      })
+    );
+  }, []);
+
+  // 处理上传成功
+  const handleComplete = useCallback((uid: string, result: { fileKey: string; fileUrl: string }, file: File) => {
+    setFileList(prev =>
+      prev.map(item => {
+        if (item.uid === uid) {
+          return {
+            ...item,
+            status: 'success',
+            percent: 100,
+            url: result.fileUrl,
+          };
+        }
+        return item;
+      })
+    );
+
+    // toast.success(`文件 "${file.name}" 上传成功`);
+    onUploadSuccess?.(result.fileKey, result.fileUrl, file);
+  }, [onUploadSuccess]);
+
+  // 处理上传失败
+  const handleError = useCallback((uid: string, error: Error, file: File) => {
+    setFileList(prev =>
+      prev.map(item => {
+        if (item.uid === uid) {
+          return {
+            ...item,
+            status: 'error',
+            percent: 0,
+            error: error.message || '上传失败'
+          };
+        }
+        return item;
+      })
+    );
+
+    // toast.error(`文件 "${file.name}" 上传失败: ${error.message}`);
+    onUploadError?.(error, file);
+  }, [onUploadError]);
+
+  // 自定义上传逻辑
+  const handleUpload = async (file: File) => {
+    const uid = Date.now().toString() + Math.random().toString(36).substring(2, 11);
+
+    // 添加到文件列表
+    setFileList(prev => [
+      ...prev,
+      {
+        uid,
+        name: file.name,
+        size: file.size,
+        type: file.type,
+        status: 'uploading',
+        percent: 0,
+      }
+    ]);
+
+    try {
+      // 验证文件大小
+      const fileSizeMB = file.size / (1024 * 1024);
+      if (fileSizeMB > maxSize) {
+        throw new Error(`文件大小超过 ${maxSize}MB 限制`);
+      }
+
+      // 调用minio上传方法
+      const result = await uploadMinIOWithPolicy(
+        uploadPath,
+        file,
+        file.name,
+        {
+          onProgress: (event) => handleProgress(uid, event),
+          signal: new AbortController().signal
+        }
+      );
+
+      handleComplete(uid, result, file);
+    } catch (error) {
+      handleError(uid, error instanceof Error ? error : new Error('未知错误'), file);
+    }
+  };
+
+  // 处理文件选择
+  const handleFileSelect = (files: FileList) => {
+    if (!files || files.length === 0) return;
+
+    const fileArray = Array.from(files);
+
+    if (!multiple && fileArray.length > 1) {
+      toast.error('不支持多文件上传');
+      return;
+    }
+
+    fileArray.forEach(file => handleUpload(file));
+  };
+
+  // 处理拖拽
+  const handleDrag = (e: React.DragEvent) => {
+    e.preventDefault();
+    e.stopPropagation();
+
+    if (e.type === 'dragenter' || e.type === 'dragover') {
+      setDragActive(true);
+    } else if (e.type === 'dragleave') {
+      setDragActive(false);
+    }
+  };
+
+  const handleDrop = (e: React.DragEvent) => {
+    e.preventDefault();
+    e.stopPropagation();
+    setDragActive(false);
+
+    const files = e.dataTransfer.files;
+    handleFileSelect(files);
+  };
+
+  // 处理文件移除
+  const handleRemove = (uid: string) => {
+    setFileList(prev => prev.filter(item => item.uid !== uid));
+  };
+
+  // 渲染上传状态
+  const renderUploadStatus = (item: UploadFile) => {
+    switch (item.status) {
+      case 'uploading':
+        return (
+          <div className="flex items-center gap-2">
+            <Loader2 className="h-4 w-4 animate-spin" />
+            <span className="text-sm">{Math.round(item.percent)}%</span>
+          </div>
+        );
+      case 'success':
+        return (
+          <div className="flex items-center gap-2">
+            <CheckCircle className="h-4 w-4 text-green-500" />
+            <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
+              上传成功
+            </Badge>
+          </div>
+        );
+      case 'error':
+        return (
+          <div className="flex items-center gap-2">
+            <div className="h-4 w-4 text-red-500">×</div>
+            <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">
+              {item.error || '上传失败'}
+            </Badge>
+          </div>
+        );
+      default:
+        return null;
+    }
+  };
+
+  // 渲染文件图标
+  const renderFileIcon = (type?: string, iconSize: 'small' | 'normal' = 'normal') => {
+    const sizeClass = iconSize === 'small' ? 'h-4 w-4' : 'h-8 w-8';
+
+    if (type?.startsWith('image/')) {
+      return <FileText className={`${sizeClass} text-blue-500`} />;
+    } else if (type?.startsWith('video/')) {
+      return <FileText className={`${sizeClass} text-red-500`} />;
+    } else if (type?.startsWith('audio/')) {
+      return <FileText className={`${sizeClass} text-purple-500`} />;
+    } else if (type?.includes('pdf')) {
+      return <FileText className={`${sizeClass} text-red-500`} />;
+    } else if (type?.includes('word')) {
+      return <FileText className={`${sizeClass} text-blue-600`} />;
+    } else if (type?.includes('excel') || type?.includes('sheet')) {
+      return <FileText className={`${sizeClass} text-green-500`} />;
+    } else {
+      return <FileText className={`${sizeClass} text-gray-500`} />;
+    }
+  };
+
+  const sizeConfig = getSizeConfig();
+
+  // 卡片模式渲染
+  if (displayMode === 'card') {
+    return (
+      <div className="h-full flex items-center justify-center">
+        <button
+          type="button"
+          className={`flex flex-col items-center justify-center w-full h-full text-muted-foreground hover:text-primary transition-colors cursor-pointer
+            ${size === 'minimal' ? 'text-xs' : 'text-sm'}`}
+          onClick={() => {
+            const input = document.createElement('input');
+            input.type = 'file';
+            input.accept = accept || '';
+            input.multiple = multiple;
+            input.onchange = (e) => {
+              const files = (e.target as HTMLInputElement).files;
+              if (files) handleFileSelect(files);
+            };
+            input.click();
+          }}
+        >
+          <Upload className={`${size === 'minimal' ? 'h-6 w-6 mb-1' : 'h-8 w-8 mb-2'}`} />
+          <span>{buttonText}</span>
+        </button>
+      </div>
+    );
+  }
+
+  return (
+    <div className={sizeConfig.spacing}>
+      {/* 上传区域 - 根据模式显示不同界面 */}
+      {uploadMode === 'dragdrop' ? (
+        <div
+          className={`relative border-2 border-dashed rounded-lg transition-all ${
+            dragActive
+              ? 'border-primary bg-primary/5'
+              : 'border-gray-300 hover:border-primary/50'
+          } ${sizeConfig.container}`}
+          onDragEnter={handleDrag}
+          onDragLeave={handleDrag}
+          onDragOver={handleDrag}
+          onDrop={handleDrop}
+        >
+          <div className={`flex flex-col items-center justify-center ${sizeConfig.spacing}`}>
+            <Upload className={`${sizeConfig.icon} ${dragActive ? 'text-primary' : 'text-gray-400'}`} />
+            <div className="text-center">
+              <p className={`${sizeConfig.title} font-medium`}>{buttonText}</p>
+              {size !== 'minimal' && (
+                <p className={`${sizeConfig.description} text-gray-500 mt-1`}>{tipText}</p>
+              )}
+            </div>
+            <Button
+              type="button"
+              variant="outline"
+              size={size === 'minimal' ? 'sm' : size === 'compact' ? 'sm' : 'default'}
+              onClick={() => {
+                const input = document.createElement('input');
+                input.type = 'file';
+                input.accept = accept || '';
+                input.multiple = multiple;
+                input.onchange = (e) => {
+                  const files = (e.target as HTMLInputElement).files;
+                  if (files) handleFileSelect(files);
+                };
+                input.click();
+              }}
+            >
+              <Upload className="h-4 w-4 mr-2" />
+              选择文件
+            </Button>
+          </div>
+        </div>
+      ) : (
+        <Card>
+          <CardContent className={sizeConfig.cardPadding}>
+            <div className={`flex flex-col items-center justify-center ${sizeConfig.spacing}`}>
+              <Upload className={`${sizeConfig.icon} text-gray-400`} />
+              <div className="text-center">
+                <p className={`${sizeConfig.title} font-medium`}>{buttonText}</p>
+                {size !== 'minimal' && (
+                  <p className={`${sizeConfig.description} text-gray-500 mt-1`}>{tipText}</p>
+                )}
+              </div>
+              <Button
+                type="button"
+                variant="outline"
+                size={size === 'minimal' ? 'sm' : size === 'compact' ? 'sm' : 'default'}
+                onClick={() => {
+                  const input = document.createElement('input');
+                  input.type = 'file';
+                  input.accept = accept || '';
+                  input.multiple = multiple;
+                  input.onchange = (e) => {
+                    const files = (e.target as HTMLInputElement).files;
+                    if (files) handleFileSelect(files);
+                  };
+                  input.click();
+                }}
+              >
+                <Upload className="h-4 w-4 mr-2" />
+                选择文件
+              </Button>
+            </div>
+          </CardContent>
+        </Card>
+      )}
+
+      {/* 上传进度列表 */}
+      {showUploadList && fileList.length > 0 && (
+        <Card>
+          <CardContent className={sizeConfig.cardPadding}>
+            <h3 className={`${sizeConfig.title} font-semibold mb-3`}>{uploadListTitle}</h3>
+            <div className={sizeConfig.fileList}>
+              {fileList.map(item => (
+                <div key={item.uid} className={`flex items-center space-x-3 p-3 border rounded-lg ${size === 'minimal' ? 'text-sm' : ''}`}>
+                  <div className="flex-shrink-0">
+                    {renderFileIcon(item.type, size === 'minimal' ? 'small' : 'normal')}
+                  </div>
+                  <div className="flex-1 min-w-0">
+                    <div className="flex justify-between items-center mb-1">
+                      <p className={`${size === 'minimal' ? 'text-xs' : 'text-sm'} font-medium truncate`}>{item.name}</p>
+                      <div className="flex items-center space-x-1">
+                        {renderUploadStatus(item)}
+                        <Button
+                          variant="ghost"
+                          size={size === 'minimal' ? 'icon' : 'sm'}
+                          onClick={() => handleRemove(item.uid)}
+                          disabled={item.status === 'uploading'}
+                          className={size === 'minimal' ? 'h-6 w-6' : ''}
+                        >
+                          <X className={size === 'minimal' ? 'h-3 w-3' : 'h-4 w-4'} />
+                        </Button>
+                      </div>
+                    </div>
+                    {item.status === 'uploading' && (
+                      <div className="space-y-1">
+                        <Progress value={item.percent} className={sizeConfig.progressHeight} />
+                        {size !== 'minimal' && (
+                          <p className={`${sizeConfig.description} text-gray-500`}>
+                            {Math.round(item.percent)}% - {formatFileSize(item.size * (item.percent / 100))} / {formatFileSize(item.size)}
+                          </p>
+                        )}
+                      </div>
+                    )}
+                  </div>
+                </div>
+              ))}
+            </div>
+          </CardContent>
+        </Card>
+      )}
+    </div>
+  );
+};
+
+// 辅助函数:格式化文件大小
+const formatFileSize = (bytes: number): string => {
+  if (bytes === 0) return '0 Bytes';
+  const k = 1024;
+  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+  const i = Math.floor(Math.log(bytes) / Math.log(k));
+  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+};
+
+export default MinioUploader;

+ 9 - 0
packages/unified-file-management-ui/src/components/index.ts

@@ -0,0 +1,9 @@
+// 导出主要组件
+export { FileManagement } from './FileManagement';
+export { default as FileSelector } from './FileSelector';
+export { default as MinioUploader } from './MinioUploader';
+
+// 导出组件类型
+export type { FileManagementProps } from './FileManagement';
+export type { FileSelectorProps } from './FileSelector';
+export type { MinioUploaderProps } from './MinioUploader';

+ 7 - 0
packages/unified-file-management-ui/src/hooks/index.ts

@@ -0,0 +1,7 @@
+// 导出文件管理钩子
+export { useFileManagement } from './useFileManagement';
+export { useFileSelector } from './useFileSelector';
+
+// 导出钩子类型
+export type { UseFileManagementOptions } from './useFileManagement';
+export type { UseFileSelectorOptions } from './useFileSelector';

+ 149 - 0
packages/unified-file-management-ui/src/hooks/useFileManagement.ts

@@ -0,0 +1,149 @@
+import { useState, useCallback } from 'react';
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
+import { toast } from 'sonner';
+import { unifiedFileClientManager } from '../api';
+import type { FileType } from '../types/file';
+
+// 文件管理钩子
+export interface UseFileManagementOptions {
+  defaultPageSize?: number;
+}
+
+export const useFileManagement = (options: UseFileManagementOptions = {}) => {
+  const { defaultPageSize = 10 } = options;
+
+  const [pagination, setPagination] = useState({
+    current: 1,
+    pageSize: defaultPageSize,
+    total: 0,
+  });
+  const [searchText, setSearchText] = useState('');
+  const queryClient = useQueryClient();
+
+  // 获取文件列表
+  const {
+    data: filesData,
+    isLoading,
+    error,
+    refetch
+  } = useQuery({
+    queryKey: ['files', pagination.current, pagination.pageSize, searchText],
+    queryFn: async () => {
+      const response = await unifiedFileClientManager.get().index.$get({
+        query: {
+          page: pagination.current,
+          pageSize: pagination.pageSize,
+          keyword: searchText || undefined,
+        },
+      });
+
+      if (!response.ok) {
+        throw new Error('获取文件列表失败');
+      }
+
+      return await response.json();
+    },
+  });
+
+  // 更新文件信息
+  const updateFileMutation = useMutation({
+    mutationFn: async ({ id, data }: { id: number; data: { name: string; description?: string } }) => {
+      const response = await unifiedFileClientManager.get()[':id'].$put({
+        param: { id: Number(id) },
+        json: data,
+      });
+
+      if (!response.ok) {
+        throw new Error('更新文件失败');
+      }
+
+      return await response.json();
+    },
+    onSuccess: () => {
+      toast.success('文件信息更新成功');
+      queryClient.invalidateQueries({ queryKey: ['files'] });
+    },
+    onError: (error: Error) => {
+      toast.error(`更新失败: ${error.message}`);
+    },
+  });
+
+  // 删除文件
+  const deleteFileMutation = useMutation({
+    mutationFn: async (id: number) => {
+      const response = await unifiedFileClientManager.get()[':id'].$delete({
+        param: { id: Number(id) },
+      });
+
+      if (!response.ok) {
+        throw new Error('删除文件失败');
+      }
+    },
+    onSuccess: () => {
+      toast.success('文件删除成功');
+      queryClient.invalidateQueries({ queryKey: ['files'] });
+    },
+    onError: (error: Error) => {
+      toast.error(`删除失败: ${error.message}`);
+    },
+  });
+
+  // 搜索文件
+  const handleSearch = useCallback((text: string) => {
+    setSearchText(text);
+    setPagination(prev => ({ ...prev, current: 1 }));
+  }, []);
+
+  // 分页处理
+  const handlePageChange = useCallback((page: number, pageSize: number) => {
+    setPagination(prev => ({ ...prev, current: page, pageSize }));
+  }, []);
+
+  // 文件预览
+  const handlePreview = useCallback((file: FileType) => {
+    if (isPreviewable(file.type)) {
+      window.open(file.fullUrl, '_blank');
+    } else {
+      toast.warning('该文件类型不支持预览');
+    }
+  }, []);
+
+  // 文件下载
+  const handleDownload = useCallback((file: FileType) => {
+    const a = document.createElement('a');
+    a.href = file.fullUrl;
+    a.download = file.name;
+    document.body.appendChild(a);
+    a.click();
+    document.body.removeChild(a);
+  }, []);
+
+  // 检查是否为可预览的文件类型
+  const isPreviewable = (fileType: string | null) => {
+    if (!fileType) return false;
+    return fileType.startsWith('image/') || fileType.startsWith('video/');
+  };
+
+  return {
+    // 数据
+    files: filesData?.data || [],
+    pagination: filesData?.pagination || pagination,
+
+    // 状态
+    isLoading,
+    error,
+    searchText,
+
+    // 操作
+    handleSearch,
+    handlePageChange,
+    handlePreview,
+    handleDownload,
+    updateFile: updateFileMutation.mutateAsync,
+    deleteFile: deleteFileMutation.mutateAsync,
+    refetch,
+
+    // 工具函数
+    isPreviewable,
+  };
+};

+ 126 - 0
packages/unified-file-management-ui/src/hooks/useFileSelector.ts

@@ -0,0 +1,126 @@
+import { useState, useCallback } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { unifiedFileClientManager } from '../api';
+import type { FileType } from '../types/file';
+
+// 文件选择器钩子
+export interface UseFileSelectorOptions {
+  filterType?: 'image' | 'all' | string;
+  pageSize?: number;
+}
+
+export const useFileSelector = (options: UseFileSelectorOptions = {}) => {
+  const { filterType = 'all', pageSize = 50 } = options;
+
+  const [isOpen, setIsOpen] = useState(false);
+  const [selectedFiles, setSelectedFiles] = useState<FileType[]>([]);
+  const [searchText, setSearchText] = useState('');
+
+  // 获取文件列表
+  const {
+    data: filesData,
+    isLoading,
+    error,
+    refetch
+  } = useQuery({
+    queryKey: ['files-for-selection', filterType, searchText],
+    queryFn: async () => {
+      const response = await unifiedFileClientManager.get().index.$get({
+        query: {
+          page: 1,
+          pageSize,
+          keyword: searchText || undefined,
+        },
+      });
+
+      if (!response.ok) {
+        throw new Error('获取文件列表失败');
+      }
+
+      return await response.json();
+    },
+    enabled: isOpen,
+  });
+
+  // 过滤文件
+  const files = filesData?.data?.filter((file) => {
+    if (filterType === 'all') return true;
+    if (filterType === 'image') return file?.type?.startsWith('image/');
+    return file?.type?.includes(filterType);
+  }) || [];
+
+  // 选择文件
+  const handleSelectFile = useCallback((file: FileType) => {
+    setSelectedFiles(prev => {
+      const isSelected = prev.some(f => f.id === file.id);
+      if (isSelected) {
+        return prev.filter(f => f.id !== file.id);
+      } else {
+        return [...prev, file];
+      }
+    });
+  }, []);
+
+  // 批量选择文件
+  const handleSelectFiles = useCallback((files: FileType[]) => {
+    setSelectedFiles(files);
+  }, []);
+
+  // 清除选择
+  const handleClearSelection = useCallback(() => {
+    setSelectedFiles([]);
+  }, []);
+
+  // 打开选择器
+  const handleOpen = useCallback(() => {
+    setIsOpen(true);
+  }, []);
+
+  // 关闭选择器
+  const handleClose = useCallback(() => {
+    setIsOpen(false);
+    setSearchText('');
+  }, []);
+
+  // 确认选择
+  const handleConfirm = useCallback(() => {
+    setIsOpen(false);
+    setSearchText('');
+    return selectedFiles;
+  }, [selectedFiles]);
+
+  // 搜索文件
+  const handleSearch = useCallback((text: string) => {
+    setSearchText(text);
+  }, []);
+
+  // 检查文件是否被选中
+  const isFileSelected = useCallback((fileId: number) => {
+    return selectedFiles.some(file => file.id === fileId);
+  }, [selectedFiles]);
+
+  return {
+    // 数据
+    files,
+    selectedFiles,
+
+    // 状态
+    isOpen,
+    isLoading,
+    error,
+    searchText,
+
+    // 操作
+    handleOpen,
+    handleClose,
+    handleConfirm,
+    handleSelectFile,
+    handleSelectFiles,
+    handleClearSelection,
+    handleSearch,
+    refetch,
+
+    // 工具函数
+    isFileSelected,
+  };
+};

+ 14 - 0
packages/unified-file-management-ui/src/index.ts

@@ -0,0 +1,14 @@
+// 导出组件
+export * from './components';
+
+// 导出钩子
+export * from './hooks';
+
+// 导出API
+export * from './api';
+
+// 导出工具函数
+export * from './utils';
+
+// 导出类型
+export type * from './types/file';

+ 78 - 0
packages/unified-file-management-ui/src/types/file.ts

@@ -0,0 +1,78 @@
+import type { InferResponseType, InferRequestType } from 'hono/client';
+import { unifiedFileClient } from '../api';
+
+// 文件列表响应类型
+export type FileListResponse = InferResponseType<typeof unifiedFileClient.index.$get, 200>;
+
+// 单个文件类型
+export type FileType = FileListResponse['data'][0];
+
+// 文件上传策略类型
+export type UploadPolicyResponse = InferResponseType<typeof unifiedFileClient['upload-policy']['$post'], 200>;
+
+// 多部分上传策略类型
+export type MultipartUploadPolicyResponse = InferResponseType<typeof unifiedFileClient['multipart-policy']['$post'], 200>;
+
+// 更新文件请求类型
+export type UpdateFileRequest = InferRequestType<typeof unifiedFileClient[':id']['$put']>['json'];
+
+// 文件查询参数
+export interface FileQueryParams {
+  page?: number;
+  pageSize?: number;
+  keyword?: string;
+}
+
+// 文件上传参数
+export interface FileUploadParams {
+  path: string;
+  name: string;
+  type?: string;
+  size?: number;
+}
+
+// 多部分上传参数
+export interface MultipartUploadParams {
+  totalSize: number;
+  partSize: number;
+  fileKey: string;
+  type?: string;
+  name: string;
+}
+
+// 文件操作状态
+export interface FileOperationState {
+  isLoading: boolean;
+  isError: boolean;
+  error?: Error;
+}
+
+// 文件预览选项
+export interface FilePreviewOptions {
+  size?: 'small' | 'medium' | 'large';
+  showActions?: boolean;
+  showInfo?: boolean;
+}
+
+// 文件选择器状态
+export interface FileSelectorState {
+  selectedFiles: FileType[];
+  isOpen: boolean;
+  searchText: string;
+  filterType: string;
+}
+
+// 文件管理状态
+export interface FileManagementState {
+  files: FileType[];
+  pagination: {
+    current: number;
+    pageSize: number;
+    total: number;
+  };
+  searchText: string;
+  isLoading: boolean;
+  isUploadModalOpen: boolean;
+  isEditModalOpen: boolean;
+  editingFile: FileType | null;
+}

+ 6 - 0
packages/unified-file-management-ui/src/utils/cn.ts

@@ -0,0 +1,6 @@
+import { type ClassValue, clsx } from 'clsx';
+import { twMerge } from 'tailwind-merge';
+
+export function cn(...inputs: ClassValue[]) {
+  return twMerge(clsx(inputs));
+}

+ 64 - 0
packages/unified-file-management-ui/src/utils/index.ts

@@ -0,0 +1,64 @@
+// 导出工具函数
+export { cn } from './cn';
+export {
+  MinIOXHRMultipartUploader,
+  MinIOXHRUploader,
+  uploadMinIOWithPolicy,
+  getUploadPolicy,
+  getMultipartUploadPolicy,
+  type MinioProgressEvent,
+  type MinioProgressCallbacks,
+  type UploadResult
+} from './minio';
+
+// 格式化文件大小
+export const formatFileSize = (bytes: number): string => {
+  if (bytes === 0) return '0 Bytes';
+  const k = 1024;
+  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+  const i = Math.floor(Math.log(bytes) / Math.log(k));
+  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+};
+
+// 检查文件类型是否可预览
+export const isPreviewableFileType = (fileType: string | null): boolean => {
+  if (!fileType) return false;
+  return fileType.startsWith('image/') || fileType.startsWith('video/');
+};
+
+// 获取文件图标类型
+export const getFileIconType = (fileType: string): 'image' | 'video' | 'audio' | 'pdf' | 'document' | 'spreadsheet' | 'text' | 'other' => {
+  if (fileType.startsWith('image/')) return 'image';
+  if (fileType.startsWith('video/')) return 'video';
+  if (fileType.startsWith('audio/')) return 'audio';
+  if (fileType.includes('pdf')) return 'pdf';
+  if (fileType.includes('word') || fileType.includes('document')) return 'document';
+  if (fileType.includes('excel') || fileType.includes('sheet')) return 'spreadsheet';
+  if (fileType.includes('text')) return 'text';
+  return 'other';
+};
+
+// 验证文件类型
+export const validateFileType = (file: File, accept?: string): boolean => {
+  if (!accept || accept === '*/*') return true;
+
+  const acceptTypes = accept.split(',').map(type => type.trim());
+
+  return acceptTypes.some(type => {
+    if (type.startsWith('.')) {
+      // 文件扩展名匹配
+      const extension = type.toLowerCase();
+      const fileName = file.name.toLowerCase();
+      return fileName.endsWith(extension);
+    } else {
+      // MIME类型匹配
+      return file.type.match(new RegExp(type.replace('*', '.*')));
+    }
+  });
+};
+
+// 验证文件大小
+export const validateFileSize = (file: File, maxSizeMB: number): boolean => {
+  const maxSizeBytes = maxSizeMB * 1024 * 1024;
+  return file.size <= maxSizeBytes;
+};

+ 385 - 0
packages/unified-file-management-ui/src/utils/minio.ts

@@ -0,0 +1,385 @@
+import type { InferResponseType } from 'hono/client';
+import { unifiedFileClientManager, unifiedFileClient } from "../api";
+
+export interface MinioProgressEvent {
+  stage: 'uploading' | 'complete' | 'error';
+  message: string;
+  progress: number;
+  details?: {
+      loaded: number;
+      total: number;
+  };
+  timestamp: number;
+}
+
+export interface MinioProgressCallbacks {
+  onProgress?: (event: MinioProgressEvent) => void;
+  onComplete?: () => void;
+  onError?: (error: Error) => void;
+  signal?: AbortSignal;
+}
+
+export interface UploadResult {
+  fileUrl:string;
+  fileKey:string;
+  bucketName:string;
+}
+
+interface UploadPart {
+  ETag: string;
+  PartNumber: number;
+}
+
+interface UploadProgressDetails {
+  partNumber: number;
+  totalParts: number;
+  partSize: number;
+  totalSize: number;
+  partProgress?: number;
+}
+
+type MinioMultipartUploadPolicy = InferResponseType<typeof unifiedFileClient["multipart-policy"]['$post'],200>
+type MinioUploadPolicy = InferResponseType<typeof unifiedFileClient["upload-policy"]['$post'],200>
+
+
+const PART_SIZE = 5 * 1024 * 1024; // 每部分5MB
+
+
+export class MinIOXHRMultipartUploader {
+  /**
+   * 使用XHR分段上传文件到MinIO
+   */
+  static async upload(
+    policy: MinioMultipartUploadPolicy,
+    file: File | Blob,
+    key: string,
+    callbacks?: MinioProgressCallbacks
+  ): Promise<UploadResult> {
+    const partSize = PART_SIZE;
+    const totalSize = file.size;
+    const totalParts = Math.ceil(totalSize / partSize);
+    const uploadedParts: UploadPart[] = [];
+
+    callbacks?.onProgress?.({
+      stage: 'uploading',
+      message: '准备上传文件...',
+      progress: 0,
+      details: {
+        loaded: 0,
+        total: totalSize
+      },
+      timestamp: Date.now()
+    });
+
+    // 分段上传
+    for (let i = 0; i < totalParts; i++) {
+      const start = i * partSize;
+      const end = Math.min(start + partSize, totalSize);
+      const partBlob = file.slice(start, end);
+      const partNumber = i + 1;
+
+      try {
+        const etag = await this.uploadPart(
+          policy.partUrls[i],
+          partBlob,
+          callbacks,
+          {
+            partNumber,
+            totalParts,
+            partSize: partBlob.size,
+            totalSize
+          }
+        );
+
+        uploadedParts.push({
+          ETag: etag,
+          PartNumber: partNumber
+        });
+
+        // 更新进度
+        const progress = Math.round((end / totalSize) * 100);
+        callbacks?.onProgress?.({
+          stage: 'uploading',
+          message: `上传文件片段 ${partNumber}/${totalParts}`,
+          progress,
+          details: {
+            loaded: end,
+            total: totalSize,
+          },
+          timestamp: Date.now()
+        });
+      } catch (error) {
+        callbacks?.onError?.(error instanceof Error ? error : new Error(String(error)));
+        throw error;
+      }
+    }
+
+    // 完成上传
+    try {
+      await this.completeMultipartUpload(policy, key, uploadedParts);
+
+      callbacks?.onProgress?.({
+        stage: 'complete',
+        message: '文件上传完成',
+        progress: 100,
+        timestamp: Date.now()
+      });
+
+      callbacks?.onComplete?.();
+      return {
+        fileUrl: `${policy.host}/${key}`,
+        fileKey: key,
+        bucketName: policy.bucket
+      };
+    } catch (error) {
+      callbacks?.onError?.(error instanceof Error ? error : new Error(String(error)));
+      throw error;
+    }
+  }
+
+  // 上传单个片段
+  private static uploadPart(
+    uploadUrl: string,
+    partBlob: Blob,
+    callbacks?: MinioProgressCallbacks,
+    progressDetails?: UploadProgressDetails
+  ): Promise<string> {
+    return new Promise((resolve, reject) => {
+      const xhr = new XMLHttpRequest();
+
+      xhr.upload.onprogress = (event) => {
+        if (event.lengthComputable && callbacks?.onProgress) {
+          const partProgress = Math.round((event.loaded / event.total) * 100);
+          callbacks.onProgress({
+            stage: 'uploading',
+            message: `上传文件片段 ${progressDetails?.partNumber}/${progressDetails?.totalParts} (${partProgress}%)`,
+            progress: Math.round((
+              (progressDetails?.partNumber ? (progressDetails.partNumber - 1) * (progressDetails.partSize || 0) : 0) + event.loaded
+            ) / (progressDetails?.totalSize || 1) * 100),
+            details: {
+              ...progressDetails,
+              loaded: event.loaded,
+              total: event.total
+            },
+            timestamp: Date.now()
+          });
+        }
+      };
+
+      xhr.onload = () => {
+        if (xhr.status >= 200 && xhr.status < 300) {
+          // 获取ETag(MinIO返回的标识)
+          const etag = xhr.getResponseHeader('ETag')?.replace(/"/g, '') || '';
+          resolve(etag);
+        } else {
+          reject(new Error(`上传片段失败: ${xhr.status} ${xhr.statusText}`));
+        }
+      };
+
+      xhr.onerror = () => reject(new Error('上传片段失败'));
+
+      xhr.open('PUT', uploadUrl);
+      xhr.send(partBlob);
+
+      if (callbacks?.signal) {
+        callbacks.signal.addEventListener('abort', () => {
+          xhr.abort();
+          reject(new Error('上传已取消'));
+        });
+      }
+    });
+  }
+
+  // 完成分段上传
+  private static async completeMultipartUpload(
+    policy: MinioMultipartUploadPolicy,
+    key: string,
+    uploadedParts: UploadPart[]
+  ): Promise<void> {
+    const response = await unifiedFileClientManager.get()["multipart-complete"].$post({
+        json:{
+            bucket: policy.bucket,
+            key,
+            uploadId: policy.uploadId,
+            parts: uploadedParts.map(part => ({ partNumber: part.PartNumber, etag: part.ETag }))
+        }
+    });
+
+    if (!response.ok) {
+      throw new Error(`完成分段上传失败: ${response.status} ${response.statusText}`);
+    }
+  }
+}
+
+export class MinIOXHRUploader {
+    /**
+     * 使用XHR上传文件到MinIO
+     */
+    static upload(
+        policy: MinioUploadPolicy,
+        file: File | Blob,
+        key: string,
+        callbacks?: MinioProgressCallbacks
+    ): Promise<UploadResult> {
+        const formData = new FormData();
+
+        // 添加 MinIO 需要的字段
+        Object.entries(policy.uploadPolicy).forEach(([k, value]) => {
+            // 排除 policy 中的 key、host、prefix、ossType 字段
+            if (k !== 'key' && k !== 'host' && k !== 'prefix' && k !== 'ossType' && typeof value === 'string') {
+                formData.append(k, value);
+            }
+        });
+        // 添加 自定义 key 字段
+        formData.append('key', key);
+        formData.append('file', file);
+
+        return new Promise((resolve, reject) => {
+            const xhr = new XMLHttpRequest();
+
+            // 上传进度处理
+            if (callbacks?.onProgress) {
+                xhr.upload.onprogress = (event) => {
+                    if (event.lengthComputable) {
+                        callbacks.onProgress?.({
+                            stage: 'uploading',
+                            message: '正在上传文件...',
+                            progress: Math.round((event.loaded * 100) / event.total),
+                            details: {
+                                loaded: event.loaded,
+                                total: event.total
+                            },
+                            timestamp: Date.now()
+                        });
+                    }
+                };
+            }
+
+            // 完成处理
+            xhr.onload = () => {
+                if (xhr.status >= 200 && xhr.status < 300) {
+                    if (callbacks?.onProgress) {
+                        callbacks.onProgress({
+                            stage: 'complete',
+                            message: '文件上传完成',
+                            progress: 100,
+                            timestamp: Date.now()
+                        });
+                    }
+                    callbacks?.onComplete?.();
+                    resolve({
+                        fileUrl:`${policy.uploadPolicy.host}/${key}`,
+                        fileKey: key,
+                        bucketName: policy.uploadPolicy.bucket
+                    });
+                } else {
+                    const error = new Error(`上传失败: ${xhr.status} ${xhr.statusText}`);
+                    callbacks?.onError?.(error);
+                    reject(error);
+                }
+            };
+
+            // 错误处理
+            xhr.onerror = () => {
+                const error = new Error('上传失败');
+                if (callbacks?.onProgress) {
+                    callbacks.onProgress({
+                        stage: 'error',
+                        message: '文件上传失败',
+                        progress: 0,
+                        timestamp: Date.now()
+                    });
+                }
+                callbacks?.onError?.(error);
+                reject(error);
+            };
+
+            // 根据当前页面协议和 host 配置决定最终的上传地址
+            const currentProtocol = typeof window !== 'undefined' ? window.location.protocol : 'https:';
+            const host = policy.uploadPolicy.host?.startsWith('http')
+                ? policy.uploadPolicy.host
+                : `${currentProtocol}//${policy.uploadPolicy.host}`;
+            // 开始上传
+            xhr.open('POST', host);
+            xhr.send(formData);
+
+            // 处理取消
+            if (callbacks?.signal) {
+                callbacks.signal.addEventListener('abort', () => {
+                    xhr.abort();
+                    reject(new Error('上传已取消'));
+                });
+            }
+        });
+    }
+}
+
+export async function getUploadPolicy(key: string, fileName: string, fileType?: string, fileSize?: number): Promise<MinioUploadPolicy> {
+  const policyResponse = await unifiedFileClientManager.get()["upload-policy"].$post({
+    json: {
+      path: key,
+      name: fileName,
+      type: fileType,
+      size: fileSize
+    }
+  });
+  if (!policyResponse.ok) {
+    throw new Error('获取上传策略失败');
+  }
+  return policyResponse.json();
+}
+
+export async function getMultipartUploadPolicy(totalSize: number, fileKey: string, fileType?: string, fileName: string = 'unnamed-file') {
+  const policyResponse = await unifiedFileClientManager.get()["multipart-policy"].$post({
+    json: {
+      totalSize,
+      partSize: PART_SIZE,
+      fileKey,
+      type: fileType,
+      name: fileName
+    }
+  });
+  if (!policyResponse.ok) {
+    throw new Error('获取分段上传策略失败');
+  }
+  return await policyResponse.json();
+}
+
+export async function uploadMinIOWithPolicy(
+  uploadPath: string,
+  file: File | Blob,
+  fileKey: string,
+  callbacks?: MinioProgressCallbacks
+): Promise<UploadResult> {
+  if(uploadPath === '/') uploadPath = '';
+  else{
+    if(!uploadPath.endsWith('/')) uploadPath = `${uploadPath}/`
+    // 去掉开头的 /
+    if(uploadPath.startsWith('/')) uploadPath = uploadPath.replace(/^\//, '');
+  }
+
+
+  if( file.size > PART_SIZE ){
+    if (!(file instanceof File)) {
+      throw new Error('不支持的文件类型,无法获取文件名');
+    }
+    const policy = await getMultipartUploadPolicy(
+      file.size,
+      `${uploadPath}${fileKey}`,
+      file.type,
+      file.name
+    );
+    return MinIOXHRMultipartUploader.upload(
+      policy,
+      file,
+      policy.key,
+      callbacks
+    );
+  }else{
+    if (!(file instanceof File)) {
+      throw new Error('不支持的文件类型,无法获取文件名');
+    }
+    const policy = await getUploadPolicy(`${uploadPath}${fileKey}`, file.name, file.type, file.size);
+    return MinIOXHRUploader.upload(policy, file, policy.uploadPolicy.key, callbacks);
+  }
+}

+ 141 - 0
packages/unified-file-management-ui/tests/components/FileManagement.test.tsx

@@ -0,0 +1,141 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { FileManagement } from '../../src/components/FileManagement';
+
+// 完整的mock响应对象
+const createMockResponse = (status: number, data?: any) => ({
+  status,
+  ok: status >= 200 && status < 300,
+  body: null,
+  bodyUsed: false,
+  statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
+  headers: new Headers(),
+  url: '',
+  redirected: false,
+  type: 'basic' as ResponseType,
+  json: async () => data || {},
+  text: async () => '',
+  blob: async () => new Blob(),
+  arrayBuffer: async () => new ArrayBuffer(0),
+  formData: async () => new FormData(),
+  clone: function() { return this; }
+});
+
+// Mock API客户端
+vi.mock('../../src/api', () => {
+  const mockUnifiedFileClient = {
+    index: {
+      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {
+        data: [],
+        pagination: { current: 1, pageSize: 10, total: 0 }
+      }))),
+    },
+    ':id': {
+      $put: vi.fn(() => Promise.resolve(createMockResponse(200, {}))),
+      $delete: vi.fn(() => Promise.resolve(createMockResponse(204, {}))),
+    },
+  };
+
+  const mockUnifiedFileClientManager = {
+    get: vi.fn(() => mockUnifiedFileClient),
+  };
+
+  return {
+    unifiedFileClientManager: mockUnifiedFileClientManager,
+    unifiedFileClient: mockUnifiedFileClient,
+  };
+});
+
+// Mock 文件上传组件
+vi.mock('../../src/components/MinioUploader', () => ({
+  default: () => <div data-testid="minio-uploader">MinioUploader</div>,
+}));
+
+describe('FileManagement', () => {
+  let queryClient: QueryClient;
+
+  beforeEach(() => {
+    queryClient = new QueryClient({
+      defaultOptions: {
+        queries: { retry: false },
+        mutations: { retry: false },
+      },
+    });
+
+    vi.clearAllMocks();
+  });
+
+  const renderWithQueryClient = (component: React.ReactElement) => {
+    return render(
+      <QueryClientProvider client={queryClient}>
+        {component as any}
+      </QueryClientProvider>
+    );
+  };
+
+  it('应该渲染文件管理组件', () => {
+    renderWithQueryClient(<FileManagement />);
+
+    expect(screen.getByText('文件管理')).toBeInTheDocument();
+    expect(screen.getByText('上传文件')).toBeInTheDocument();
+    expect(screen.getByText('文件列表')).toBeInTheDocument();
+  });
+
+  it('应该显示搜索功能', () => {
+    renderWithQueryClient(<FileManagement showSearch={true} />);
+
+    expect(screen.getByPlaceholderText('搜索文件名称或类型')).toBeInTheDocument();
+    expect(screen.getByText('搜索')).toBeInTheDocument();
+  });
+
+  it('应该隐藏搜索功能', () => {
+    renderWithQueryClient(<FileManagement showSearch={false} />);
+
+    expect(screen.queryByPlaceholderText('搜索文件名称或类型')).not.toBeInTheDocument();
+    expect(screen.queryByText('搜索')).not.toBeInTheDocument();
+  });
+
+  it('应该隐藏上传按钮', () => {
+    renderWithQueryClient(<FileManagement showUploadButton={false} />);
+
+    expect(screen.queryByText('上传文件')).not.toBeInTheDocument();
+  });
+
+  it('应该打开上传对话框', async () => {
+    renderWithQueryClient(<FileManagement />);
+
+    const uploadButton = screen.getByTestId('upload-file-button');
+    fireEvent.click(uploadButton);
+
+    await waitFor(() => {
+      expect(screen.getByTestId('upload-file-dialog')).toBeInTheDocument();
+      expect(screen.getByRole('heading', { name: '上传文件' })).toBeInTheDocument();
+      expect(screen.getByTestId('minio-uploader')).toBeInTheDocument();
+    });
+  });
+
+  it('应该显示加载状态', async () => {
+    // Mock API调用返回加载状态
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockReturnValue(new Promise(() => {}));
+
+    renderWithQueryClient(<FileManagement />);
+
+    expect(screen.getByRole('table')).toBeInTheDocument();
+  });
+
+  it('应该显示空状态', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: [],
+      pagination: { current: 1, pageSize: 10, total: 0 }
+    }));
+
+    renderWithQueryClient(<FileManagement />);
+
+    await waitFor(() => {
+      expect(screen.getByText('暂无文件')).toBeInTheDocument();
+    });
+  });
+});

+ 213 - 0
packages/unified-file-management-ui/tests/components/FileSelector.test.tsx

@@ -0,0 +1,213 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import FileSelector from '../../src/components/FileSelector';
+
+// 完整的mock响应对象
+const createMockResponse = (status: number, data?: any) => ({
+  status,
+  ok: status >= 200 && status < 300,
+  body: null,
+  bodyUsed: false,
+  statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
+  headers: new Headers(),
+  url: '',
+  redirected: false,
+  type: 'basic' as ResponseType,
+  json: async () => data || {},
+  text: async () => '',
+  blob: async () => new Blob(),
+  arrayBuffer: async () => new ArrayBuffer(0),
+  formData: async () => new FormData(),
+  clone: function() { return this; }
+});
+
+// Mock API客户端
+vi.mock('../../src/api', () => {
+  const mockUnifiedFileClient = {
+    index: {
+      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {
+        data: [],
+        pagination: { current: 1, pageSize: 50, total: 0 }
+      }))),
+    },
+    ':id': {
+      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {}))),
+    },
+  };
+
+  const mockUnifiedFileClientManager = {
+    get: vi.fn(() => mockUnifiedFileClient),
+  };
+
+  return {
+    unifiedFileClientManager: mockUnifiedFileClientManager,
+    unifiedFileClient: mockUnifiedFileClient,
+  };
+});
+
+// Mock 文件上传组件
+vi.mock('../../src/components/MinioUploader', () => ({
+  default: () => <div data-testid="minio-uploader">MinioUploader</div>,
+}));
+
+describe('FileSelector', () => {
+  let queryClient: QueryClient;
+
+  beforeEach(() => {
+    queryClient = new QueryClient({
+      defaultOptions: {
+        queries: { retry: false },
+        mutations: { retry: false },
+      },
+    });
+
+    vi.clearAllMocks();
+  });
+
+  const renderWithQueryClient = (component: React.ReactElement) => {
+    return render(
+      <QueryClientProvider client={queryClient}>
+        {component as any}
+      </QueryClientProvider>
+    );
+  };
+
+  const mockFiles = [
+    {
+      id: 1,
+      name: 'test-image.jpg',
+      type: 'image/jpeg',
+      size: 1024,
+      fullUrl: 'http://example.com/test-image.jpg',
+      uploadTime: '2024-01-01T00:00:00Z',
+    },
+    {
+      id: 2,
+      name: 'test-document.pdf',
+      type: 'application/pdf',
+      size: 2048,
+      fullUrl: 'http://example.com/test-document.pdf',
+      uploadTime: '2024-01-01T00:00:00Z',
+    },
+  ];
+
+  it('应该渲染文件选择器', () => {
+    renderWithQueryClient(
+      <FileSelector value={null} onChange={() => {}} />
+    );
+
+    expect(screen.getByTestId('file-selector-button')).toBeInTheDocument();
+  });
+
+  it('应该打开选择对话框', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 1, pageSize: 50, total: 2 }
+    }));
+
+    renderWithQueryClient(
+      <FileSelector value={null} onChange={() => {}} />
+    );
+
+    const selectButton = screen.getByTestId('file-selector-button');
+    fireEvent.click(selectButton);
+
+    await waitFor(() => {
+      expect(screen.getByTestId('file-selector-dialog')).toBeInTheDocument();
+      expect(screen.getByRole('heading', { name: '选择文件' })).toBeInTheDocument();
+      expect(screen.getByText('上传新文件或从已有文件中选择')).toBeInTheDocument();
+    });
+  });
+
+  it('应该显示已选文件预览', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient[':id'].$get as any).mockResolvedValue(createMockResponse(200, mockFiles[0]));
+
+    renderWithQueryClient(
+      <FileSelector value={1} onChange={() => {}} showPreview={true} />
+    );
+
+    await waitFor(() => {
+      expect(screen.getByText('更换文件')).toBeInTheDocument();
+    });
+  });
+
+  it('应该支持多选模式', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 1, pageSize: 50, total: 2 }
+    }));
+
+    const onChange = vi.fn();
+    renderWithQueryClient(
+      <FileSelector
+        value={[1, 2]}
+        onChange={onChange}
+        allowMultiple={true}
+        showPreview={true}
+      />
+    );
+
+    await waitFor(() => {
+      expect(screen.getByText('已选择 2 个文件')).toBeInTheDocument();
+    });
+  });
+
+  it('应该过滤文件类型', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 1, pageSize: 50, total: 2 }
+    }));
+
+    renderWithQueryClient(
+      <FileSelector
+        value={null}
+        onChange={() => {}}
+        filterType="image"
+      />
+    );
+
+    const selectButton = screen.getByTestId('file-selector-button');
+    fireEvent.click(selectButton);
+
+    await waitFor(() => {
+      expect(unifiedFileClient.index.$get).toHaveBeenCalledWith({
+        query: {
+          page: 1,
+          pageSize: 50,
+          keyword: 'image'
+        }
+      });
+    });
+  });
+
+  it('应该处理文件选择确认', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 1, pageSize: 50, total: 2 }
+    }));
+
+    const onChange = vi.fn();
+    renderWithQueryClient(
+      <FileSelector value={null} onChange={onChange} />
+    );
+
+    const selectButton = screen.getByTestId('file-selector-button');
+    fireEvent.click(selectButton);
+
+    await waitFor(() => {
+      const fileItems = screen.getAllByText('test-image.jpg');
+      fireEvent.click(fileItems[0]);
+    });
+
+    const confirmButton = screen.getByText('确认选择');
+    fireEvent.click(confirmButton);
+
+    expect(onChange).toHaveBeenCalledWith(1);
+  });
+});

+ 259 - 0
packages/unified-file-management-ui/tests/hooks/useFileManagement.test.tsx

@@ -0,0 +1,259 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { useFileManagement } from '../../src/hooks/useFileManagement';
+
+// 完整的mock响应对象
+const createMockResponse = (status: number, data?: any) => ({
+  status,
+  ok: status >= 200 && status < 300,
+  body: null,
+  bodyUsed: false,
+  statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
+  headers: new Headers(),
+  url: '',
+  redirected: false,
+  type: 'basic' as ResponseType,
+  json: async () => data || {},
+  text: async () => '',
+  blob: async () => new Blob(),
+  arrayBuffer: async () => new ArrayBuffer(0),
+  formData: async () => new FormData(),
+  clone: function() { return this; }
+});
+
+// Mock API客户端
+vi.mock('../../src/api', () => {
+  const mockUnifiedFileClient = {
+    index: {
+      $get: vi.fn(() => Promise.resolve({ status: 200, body: null })),
+    },
+    ':id': {
+      $get: vi.fn(() => Promise.resolve({ status: 200, body: null })),
+      $put: vi.fn(() => Promise.resolve({ status: 200, body: null })),
+      $delete: vi.fn(() => Promise.resolve({ status: 204, body: null })),
+    },
+  };
+
+  const mockUnifiedFileClientManager = {
+    get: vi.fn(() => mockUnifiedFileClient),
+  };
+
+  return {
+    unifiedFileClientManager: mockUnifiedFileClientManager,
+    unifiedFileClient: mockUnifiedFileClient,
+  };
+});
+
+// Mock toast
+vi.mock('sonner', () => ({
+  toast: {
+    success: vi.fn(),
+    error: vi.fn(),
+    warning: vi.fn(),
+  },
+}));
+
+describe('useFileManagement', () => {
+  let queryClient: QueryClient;
+
+  beforeEach(() => {
+    queryClient = new QueryClient({
+      defaultOptions: {
+        queries: { retry: false },
+        mutations: { retry: false },
+      },
+    });
+
+    vi.clearAllMocks();
+  });
+
+  const wrapper = ({ children }: { children: React.ReactNode }) => (
+    <QueryClientProvider client={queryClient}>
+      {children as any}
+    </QueryClientProvider>
+  );
+
+  const mockFiles = [
+    {
+      id: 1,
+      name: 'test-file-1.jpg',
+      type: 'image/jpeg',
+      size: 1024,
+      fullUrl: 'http://example.com/test-file-1.jpg',
+      uploadTime: '2024-01-01T00:00:00Z',
+    },
+    {
+      id: 2,
+      name: 'test-file-2.pdf',
+      type: 'application/pdf',
+      size: 2048,
+      fullUrl: 'http://example.com/test-file-2.pdf',
+      uploadTime: '2024-01-01T00:00:00Z',
+    },
+  ];
+
+  it('应该初始化文件管理钩子', () => {
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    expect(result.current.files).toEqual([]);
+    expect(result.current.isLoading).toBe(true);
+    expect(result.current.searchText).toBe('');
+  });
+
+  it('应该获取文件列表', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 1, pageSize: 10, total: 2 }
+    }));
+
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    await waitFor(() => {
+      expect(result.current.isLoading).toBe(false);
+    });
+
+    expect(result.current.files).toEqual(mockFiles);
+    expect(result.current.pagination.total).toBe(2);
+  });
+
+  it('应该处理搜索', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: [mockFiles[0]],
+      pagination: { current: 1, pageSize: 10, total: 1 }
+    }));
+
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    result.current.handleSearch('test');
+
+    await waitFor(() => {
+      expect(result.current.searchText).toBe('test');
+    });
+
+    expect(unifiedFileClient.index.$get).toHaveBeenCalledWith({
+      query: {
+        page: 1,
+        pageSize: 10,
+        keyword: 'test'
+      }
+    });
+  });
+
+  it('应该处理分页', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    (unifiedFileClient.index.$get as any).mockResolvedValue(createMockResponse(200, {
+      data: mockFiles,
+      pagination: { current: 2, pageSize: 5, total: 2 }
+    }));
+
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    result.current.handlePageChange(2, 5);
+
+    await waitFor(() => {
+      expect(result.current.pagination.current).toBe(2);
+      expect(result.current.pagination.pageSize).toBe(5);
+    });
+  });
+
+  it('应该更新文件信息', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    const { toast } = await import('sonner');
+
+    (unifiedFileClient[':id'].$put as any).mockResolvedValue(createMockResponse(200, {
+      id: 1,
+      name: 'updated-file.jpg',
+      description: 'Updated description'
+    }));
+
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    await result.current.updateFile({
+      id: 1,
+      data: {
+        name: 'updated-file.jpg',
+        description: 'Updated description'
+      }
+    });
+
+    expect(unifiedFileClient[':id'].$put).toHaveBeenCalledWith({
+      param: { id: 1 },
+      json: {
+        name: 'updated-file.jpg',
+        description: 'Updated description'
+      }
+    });
+
+    expect(toast.success).toHaveBeenCalledWith('文件信息更新成功');
+  });
+
+  it('应该删除文件', async () => {
+    const { unifiedFileClient } = await import('../../src/api');
+    const { toast } = await import('sonner');
+
+    (unifiedFileClient[':id'].$delete as any).mockResolvedValue(createMockResponse(204));
+
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    await result.current.deleteFile(1);
+
+    expect(unifiedFileClient[':id'].$delete).toHaveBeenCalledWith({
+      param: { id: 1 }
+    });
+
+    expect(toast.success).toHaveBeenCalledWith('文件删除成功');
+  });
+
+  it('应该检查文件是否可预览', () => {
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+
+    expect(result.current.isPreviewable('image/jpeg')).toBe(true);
+    expect(result.current.isPreviewable('video/mp4')).toBe(true);
+    expect(result.current.isPreviewable('application/pdf')).toBe(false);
+    expect(result.current.isPreviewable(null)).toBe(false);
+  });
+
+  it('应该处理文件预览', () => {
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+    const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
+
+    const file = {
+      id: 1,
+      name: 'test.jpg',
+      type: 'image/jpeg',
+      fullUrl: 'http://example.com/test.jpg'
+    } as any;
+
+    result.current.handlePreview(file);
+
+    expect(windowOpenSpy).toHaveBeenCalledWith('http://example.com/test.jpg', '_blank');
+
+    windowOpenSpy.mockRestore();
+  });
+
+  it('应该处理文件下载', () => {
+    const { result } = renderHook(() => useFileManagement(), { wrapper });
+    const createElementSpy = vi.spyOn(document, 'createElement');
+    const appendChildSpy = vi.spyOn(document.body, 'appendChild');
+    const removeChildSpy = vi.spyOn(document.body, 'removeChild');
+
+    const file = {
+      id: 1,
+      name: 'test.jpg',
+      fullUrl: 'http://example.com/test.jpg'
+    } as any;
+
+    result.current.handleDownload(file);
+
+    expect(createElementSpy).toHaveBeenCalledWith('a');
+    expect(appendChildSpy).toHaveBeenCalled();
+    expect(removeChildSpy).toHaveBeenCalled();
+
+    createElementSpy.mockRestore();
+    appendChildSpy.mockRestore();
+    removeChildSpy.mockRestore();
+  });
+});

+ 37 - 0
packages/unified-file-management-ui/tests/setup.ts

@@ -0,0 +1,37 @@
+import '@testing-library/jest-dom';
+import { vi } from 'vitest';
+
+// Mock window.matchMedia
+Object.defineProperty(window, 'matchMedia', {
+  writable: true,
+  value: vi.fn().mockImplementation((query: string) => ({
+    matches: false,
+    media: query,
+    onchange: null,
+    addListener: vi.fn(), // deprecated
+    removeListener: vi.fn(), // deprecated
+    addEventListener: vi.fn(),
+    removeEventListener: vi.fn(),
+    dispatchEvent: vi.fn(),
+  })),
+});
+
+// Mock ResizeObserver
+global.ResizeObserver = vi.fn().mockImplementation(() => ({
+  observe: vi.fn(),
+  unobserve: vi.fn(),
+  disconnect: vi.fn(),
+}));
+
+// Mock IntersectionObserver
+global.IntersectionObserver = vi.fn().mockImplementation(() => ({
+  observe: vi.fn(),
+  unobserve: vi.fn(),
+  disconnect: vi.fn(),
+}));
+
+// Mock URL.createObjectURL
+URL.createObjectURL = vi.fn();
+
+// Mock window.open
+window.open = vi.fn();

+ 98 - 0
packages/unified-file-management-ui/tests/utils/index.test.ts

@@ -0,0 +1,98 @@
+import { describe, it, expect } from 'vitest';
+import {
+  formatFileSize,
+  isPreviewableFileType,
+  getFileIconType,
+  validateFileType,
+  validateFileSize
+} from '../../src/utils';
+
+describe('工具函数', () => {
+  describe('formatFileSize', () => {
+    it('应该格式化文件大小', () => {
+      expect(formatFileSize(0)).toBe('0 Bytes');
+      expect(formatFileSize(1024)).toBe('1 KB');
+      expect(formatFileSize(1048576)).toBe('1 MB');
+      expect(formatFileSize(1073741824)).toBe('1 GB');
+      expect(formatFileSize(1099511627776)).toBe('1 TB');
+    });
+
+    it('应该处理小数文件大小', () => {
+      expect(formatFileSize(1536)).toBe('1.5 KB');
+      expect(formatFileSize(1572864)).toBe('1.5 MB');
+    });
+  });
+
+  describe('isPreviewableFileType', () => {
+    it('应该检查文件类型是否可预览', () => {
+      expect(isPreviewableFileType('image/jpeg')).toBe(true);
+      expect(isPreviewableFileType('image/png')).toBe(true);
+      expect(isPreviewableFileType('video/mp4')).toBe(true);
+      expect(isPreviewableFileType('video/quicktime')).toBe(true);
+      expect(isPreviewableFileType('application/pdf')).toBe(false);
+      expect(isPreviewableFileType('text/plain')).toBe(false);
+      expect(isPreviewableFileType(null)).toBe(false);
+    });
+  });
+
+  describe('getFileIconType', () => {
+    it('应该返回正确的文件图标类型', () => {
+      expect(getFileIconType('image/jpeg')).toBe('image');
+      expect(getFileIconType('video/mp4')).toBe('video');
+      expect(getFileIconType('audio/mp3')).toBe('audio');
+      expect(getFileIconType('application/pdf')).toBe('pdf');
+      expect(getFileIconType('application/msword')).toBe('document');
+      expect(getFileIconType('application/vnd.ms-excel')).toBe('spreadsheet');
+      expect(getFileIconType('text/plain')).toBe('text');
+      expect(getFileIconType('application/octet-stream')).toBe('other');
+    });
+  });
+
+  describe('validateFileType', () => {
+    it('应该验证文件类型', () => {
+      const imageFile = new File([''], 'test.jpg', { type: 'image/jpeg' });
+      const pdfFile = new File([''], 'test.pdf', { type: 'application/pdf' });
+
+      // 接受所有文件类型
+      expect(validateFileType(imageFile, '*/*')).toBe(true);
+      expect(validateFileType(pdfFile, '*/*')).toBe(true);
+
+      // 接受特定MIME类型
+      expect(validateFileType(imageFile, 'image/*')).toBe(true);
+      expect(validateFileType(pdfFile, 'image/*')).toBe(false);
+
+      // 接受文件扩展名
+      expect(validateFileType(imageFile, '.jpg,.png')).toBe(true);
+      expect(validateFileType(pdfFile, '.jpg,.png')).toBe(false);
+
+      // 混合类型
+      expect(validateFileType(imageFile, 'image/*,.pdf')).toBe(true);
+      expect(validateFileType(pdfFile, 'image/*,.pdf')).toBe(true);
+    });
+
+    it('应该在没有accept参数时返回true', () => {
+      const file = new File([''], 'test.txt', { type: 'text/plain' });
+      expect(validateFileType(file)).toBe(true);
+    });
+  });
+
+  describe('validateFileSize', () => {
+    it('应该验证文件大小', () => {
+      const smallFile = new File([''], 'small.txt', { type: 'text/plain' });
+      Object.defineProperty(smallFile, 'size', { value: 1024 * 1024 }); // 1MB
+
+      const largeFile = new File([''], 'large.txt', { type: 'text/plain' });
+      Object.defineProperty(largeFile, 'size', { value: 10 * 1024 * 1024 }); // 10MB
+
+      expect(validateFileSize(smallFile, 5)).toBe(true); // 5MB限制
+      expect(validateFileSize(largeFile, 5)).toBe(false); // 5MB限制
+    });
+
+    it('应该处理边界情况', () => {
+      const exactSizeFile = new File([''], 'exact.txt', { type: 'text/plain' });
+      Object.defineProperty(exactSizeFile, 'size', { value: 5 * 1024 * 1024 }); // 5MB
+
+      expect(validateFileSize(exactSizeFile, 5)).toBe(true);
+    });
+  });
+});

+ 36 - 0
packages/unified-file-management-ui/tsconfig.json

@@ -0,0 +1,36 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "lib": ["ES2022", "DOM", "DOM.Iterable"],
+    "module": "ESNext",
+    "skipLibCheck": true,
+    "moduleResolution": "bundler",
+    "allowImportingTsExtensions": true,
+    "resolveJsonModule": true,
+    "isolatedModules": true,
+    "noEmit": true,
+    "jsx": "react-jsx",
+    "strict": true,
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "noFallthroughCasesInSwitch": true,
+    "experimentalDecorators": true,
+    "emitDecoratorMetadata": true,
+    "declaration": true,
+    "declarationMap": true,
+    "sourceMap": true,
+    "outDir": "./dist",
+    "baseUrl": ".",
+    "paths": {
+      "@/*": ["./src/*"]
+    }
+  },
+  "include": [
+    "src/**/*",
+    "tests/**/*"
+  ],
+  "exclude": [
+    "node_modules",
+    "dist"
+  ]
+}

+ 24 - 0
packages/unified-file-management-ui/vitest.config.ts

@@ -0,0 +1,24 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+  test: {
+    globals: true,
+    environment: 'jsdom',
+    setupFiles: ['./tests/setup.ts'],
+    coverage: {
+      provider: 'v8',
+      reporter: ['text', 'json', 'html'],
+      exclude: [
+        'node_modules/',
+        'tests/',
+        '**/*.d.ts',
+        '**/*.config.*'
+      ]
+    }
+  },
+  resolve: {
+    alias: {
+      '@': './src'
+    }
+  }
+});

+ 100 - 0
pnpm-lock.yaml

@@ -4957,6 +4957,106 @@ importers:
         specifier: ^3.2.4
         version: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.1)(happy-dom@18.0.1)(jiti@2.6.1)(jsdom@26.1.0)(lightningcss@1.30.2)(sass@1.94.1)(stylus@0.64.0)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.1)
 
+  packages/unified-file-management-ui:
+    dependencies:
+      '@d8d/shared-types':
+        specifier: workspace:*
+        version: link:../shared-types
+      '@d8d/shared-ui-components':
+        specifier: workspace:*
+        version: link:../shared-ui-components
+      '@d8d/unified-file-module':
+        specifier: workspace:*
+        version: link:../unified-file-module
+      '@hookform/resolvers':
+        specifier: ^5.2.1
+        version: 5.2.2(react-hook-form@7.66.1(react@19.2.0))
+      '@tanstack/react-query':
+        specifier: ^5.90.9
+        version: 5.90.10(react@19.2.0)
+      axios:
+        specifier: ^1.7.9
+        version: 1.13.2(debug@4.4.3)
+      class-variance-authority:
+        specifier: ^0.7.1
+        version: 0.7.1
+      clsx:
+        specifier: ^2.1.1
+        version: 2.1.1
+      date-fns:
+        specifier: ^4.1.0
+        version: 4.1.0
+      dayjs:
+        specifier: ^1.11.13
+        version: 1.11.19
+      hono:
+        specifier: ^4.8.5
+        version: 4.8.5
+      lucide-react:
+        specifier: ^0.536.0
+        version: 0.536.0(react@19.2.0)
+      react:
+        specifier: ^19.1.0
+        version: 19.2.0
+      react-dom:
+        specifier: ^19.1.0
+        version: 19.2.0(react@19.2.0)
+      react-hook-form:
+        specifier: ^7.61.1
+        version: 7.66.1(react@19.2.0)
+      react-router:
+        specifier: ^7.1.3
+        version: 7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
+      sonner:
+        specifier: ^2.0.7
+        version: 2.0.7(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
+      tailwind-merge:
+        specifier: ^3.3.1
+        version: 3.4.0
+      zod:
+        specifier: ^4.0.15
+        version: 4.1.12
+    devDependencies:
+      '@testing-library/jest-dom':
+        specifier: ^6.8.0
+        version: 6.9.1
+      '@testing-library/react':
+        specifier: ^16.3.0
+        version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.6))(@types/react@19.2.6)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
+      '@testing-library/user-event':
+        specifier: ^14.6.1
+        version: 14.6.1(@testing-library/dom@10.4.1)
+      '@types/node':
+        specifier: ^22.10.2
+        version: 22.19.1
+      '@types/react':
+        specifier: ^19.2.2
+        version: 19.2.6
+      '@types/react-dom':
+        specifier: ^19.2.3
+        version: 19.2.3(@types/react@19.2.6)
+      '@typescript-eslint/eslint-plugin':
+        specifier: ^8.18.1
+        version: 8.47.0(@typescript-eslint/parser@8.47.0(eslint@9.39.1(jiti@2.6.1))(typescript@5.8.3))(eslint@9.39.1(jiti@2.6.1))(typescript@5.8.3)
+      '@typescript-eslint/parser':
+        specifier: ^8.18.1
+        version: 8.47.0(eslint@9.39.1(jiti@2.6.1))(typescript@5.8.3)
+      eslint:
+        specifier: ^9.17.0
+        version: 9.39.1(jiti@2.6.1)
+      jsdom:
+        specifier: ^26.0.0
+        version: 26.1.0
+      typescript:
+        specifier: ^5.8.3
+        version: 5.8.3
+      unbuild:
+        specifier: ^3.4.0
+        version: 3.6.1(sass@1.94.1)(typescript@5.8.3)
+      vitest:
+        specifier: ^4.0.9
+        version: 4.0.10(@types/debug@4.1.12)(@types/node@22.19.1)(happy-dom@18.0.1)(jiti@2.6.1)(jsdom@26.1.0)(lightningcss@1.30.2)(sass@1.94.1)(stylus@0.64.0)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.1)
+
   packages/unified-file-module:
     dependencies:
       '@d8d/shared-crud':