Parcourir la source

✨ feat(file-management-ui): 新增文件管理界面包

- 创建完整的文件管理界面包 `@d8d/file-management-ui`
- 实现文件管理组件 `FileManagement`,支持文件列表展示、搜索、分页、预览、下载、编辑和删除功能
- 实现文件选择器组件 `FileSelector`,支持单选和多选模式,提供文件预览和上传功能
- 实现MinIO上传组件 `MinioUploader`,支持拖拽上传、进度显示和多部分上传
- 提供完整的API客户端架构,基于Hono RPC实现类型安全的文件操作
- 实现自定义React Hooks:`useFileManagement` 和 `useFileSelector`,提供状态管理和业务逻辑封装
- 配置完整的构建系统、TypeScript配置、ESLint规则和测试环境
- 提供完整的类型定义和工具函数,支持文件大小格式化、类型验证等功能
- 实现单元测试覆盖主要组件功能
yourname il y a 1 mois
Parent
commit
f47be10fb7

+ 184 - 0
docs/stories/007.037.area-management-ui-package.story.md

@@ -0,0 +1,184 @@
+# 故事007.037: 单租户区域管理界面独立包实现
+
+## 状态
+
+Draft
+
+## 故事
+
+**作为** 系统管理员,
+**我想要** 有一个独立的单租户区域管理界面包,
+**以便** 可以在单租户系统中独立管理省市区树形结构,而不影响现有的多租户系统。
+
+## 验收标准
+
+1. **AC 1**: 成功创建单租户区域管理界面包 `@d8d/area-management-ui`,包含正确的包配置和依赖管理
+2. **AC 2**: 复制前端区域管理界面 `web/src/client/admin/pages/AreasTreePage.tsx` 为单租户区域管理界面包
+3. **AC 3**: 实现完整的区域CRUD操作和树形结构管理
+4. **AC 4**: 基于React + TypeScript + TanStack Query + React Hook Form技术栈
+5. **AC 5**: 依赖共享UI组件包 `@d8d/shared-ui-components`
+6. **AC 6**: 依赖区域模块包 `@d8d/geo-areas`
+7. **AC 7**: 提供workspace包依赖复用机制
+8. **AC 8**: 支持独立测试和部署
+9. **AC 9**: 验证现有功能无回归
+
+## 任务 / 子任务
+
+- [ ] 任务 1 (AC: 1, 7): 创建单租户区域管理界面包结构
+  - [ ] 创建包目录:`packages/area-management-ui/`
+  - [ ] 创建基础包结构:`src/`、`tests/`、`package.json`
+  - [ ] 配置包依赖和构建脚本
+
+- [ ] 任务 2 (AC: 1): 配置包依赖和构建
+  - [ ] 创建 `packages/area-management-ui/package.json` 包配置
+  - [ ] 添加依赖:`@d8d/shared-ui-components`、`@d8d/geo-areas`
+  - [ ] 配置构建脚本和TypeScript配置
+
+- [ ] 任务 3 (AC: 2, 3): 复制并调整区域管理界面组件
+  - [ ] 复制 `web/src/client/admin/pages/AreasTreePage.tsx` 为 `packages/area-management-ui/src/components/AreaManagement.tsx`
+  - [ ] 更新组件导入路径,使用共享UI组件包
+  - [ ] 调整API客户端,使用区域模块包
+
+- [ ] 任务 4 (AC: 3, 6): 创建API客户端和类型定义
+  - [ ] 创建 `packages/area-management-ui/src/api/areaClient.ts` API客户端
+  - [ ] 创建 `packages/area-management-ui/src/types/area.ts` 类型定义
+  - [ ] 确保所有类型定义与区域模块包对齐
+
+- [ ] 任务 5 (AC: 3, 4): 实现完整的区域管理功能
+  - [ ] 实现区域树形结构展示和异步加载
+  - [ ] 实现区域创建、编辑、删除功能
+  - [ ] 实现区域状态管理和层级管理
+  - [ ] 实现子节点添加和树形展开功能
+
+- [ ] 任务 6 (AC: 8): 创建测试套件
+  - [ ] 创建集成测试:`packages/area-management-ui/tests/integration/area-management.integration.test.tsx`
+  - [ ] 创建测试工具:`packages/area-management-ui/tests/test-utils.tsx`
+
+- [ ] 任务 7 (AC: 1, 7): 配置包导出接口
+  - [ ] 创建 `packages/area-management-ui/src/index.ts` 包导出主入口
+  - [ ] 确保所有导出组件、hook和类型定义正确
+  - [ ] 验证导出脚本正常工作
+
+- [ ] 任务 8 (AC: 9): 验证功能无回归
+  - [ ] 运行包构建:`pnpm build`
+  - [ ] 运行所有测试:`pnpm test`
+  - [ ] 验证区域管理功能正常
+  - [ ] 验证与现有系统兼容性
+
+- [ ] 任务 9 (新增任务): 实现RPC客户端架构和最佳实践
+  - [ ] 创建单例模式的区域客户端管理器
+  - [ ] 实现延迟初始化和客户端重置功能
+  - [ ] 使用Hono的InferRequestType和InferResponseType确保类型安全
+  - [ ] 提供全局唯一的客户端实例管理
+  - [ ] 验证RPC客户端在主应用中的正确集成
+  - [ ] 实现类型安全的API调用模式
+
+- [ ] 任务 10 (新增任务): 安装和配置包依赖
+  - [ ] 在项目根目录运行 `pnpm install` 安装新包依赖
+  - [ ] 验证包依赖正确解析和安装
+  - [ ] 确保workspace依赖关系正确配置
+
+## Dev Notes
+
+### 技术栈和架构上下文
+- **技术栈**: React 19 + TypeScript + TanStack Query + React Hook Form [Source: architecture/tech-stack.md#现有技术栈维护]
+- **前端框架**: React 19.1.0 用于用户界面构建 [Source: architecture/tech-stack.md#现有技术栈维护]
+- **状态管理**: React Query 5.83.0 用于服务端状态管理 [Source: architecture/tech-stack.md#现有技术栈维护]
+- **构建工具**: Vite 7.0.0 用于开发服务器和构建 [Source: architecture/tech-stack.md#现有技术栈维护]
+
+### 项目结构
+- **包位置**: `packages/area-management-ui/` [Source: architecture/source-tree.md#实际项目结构]
+- **源码结构**:
+  - `src/components/` - React组件
+  - `src/hooks/` - 自定义React hooks
+  - `src/api/` - API客户端
+  - `src/types/` - TypeScript类型定义
+  - `tests/unit/` - 单元测试
+  - `tests/integration/` - 集成测试
+- **依赖管理**: 使用pnpm workspace依赖管理 [Source: architecture/source-tree.md#集成指南]
+
+### 依赖关系
+- **共享UI组件包**: `@d8d/shared-ui-components` - 提供基础UI组件 [Source: architecture/source-tree.md#实际项目结构]
+- **单租户区域模块**: `@d8d/geo-areas` - 提供区域管理API [Source: docs/prd/epic-007-multi-tenant-package-replication.md#区域管理界面包]
+
+### 从前一个故事吸取的经验教训
+- **useQuery测试策略**: 使用真实的QueryClientProvider而不是mock react-query,在TestWrapper中提供完整的react-query上下文 [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+- **UI组件测试策略**: 使用data-testid进行元素定位比placeholder/role更准确稳定,避免因UI变化导致测试失败 [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+- **React Hook Form处理**: 需要过滤React Hook Form的props避免React警告,改进mock策略 [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+- **Router上下文**: 需要提供BrowserRouter上下文或mock useNavigate [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+
+### 测试标准
+- **测试框架**: Vitest + Testing Library [Source: architecture/testing-strategy.md#单元测试]
+- **测试位置**: `packages/area-management-ui/tests/unit/` 和 `packages/area-management-ui/tests/integration/` [Source: architecture/testing-strategy.md#单元测试]
+- **测试覆盖率目标**: ≥ 80% 单元测试覆盖率 [Source: architecture/testing-strategy.md#各层覆盖率要求]
+- **测试执行**: 使用 `pnpm test` 运行所有测试 [Source: architecture/testing-strategy.md#本地开发测试]
+- **测试模式**: 遵循测试金字塔模型,包含单元测试、组件测试和集成测试 [Source: architecture/testing-strategy.md#测试金字塔策略]
+
+### 关键实施要点
+- **包命名**: 使用标准命名约定,不添加特殊后缀 [Source: docs/prd/epic-007-multi-tenant-package-replication.md#包命名约定]
+- **API客户端**: 使用Hono客户端调用单租户区域API [Source: docs/stories/007.015.auth-management-ui-package.story.md#任务-5]
+- **导出接口**: 提供完整的组件、hook和类型定义导出 [Source: docs/stories/007.015.auth-management-ui-package.story.md#任务-7]
+- **组件复用**: 基于现有区域管理界面实现,确保功能完整性和一致性
+
+### 区域管理功能特性
+- **树形结构**: 异步加载树形结构,支持省级数据懒加载
+- **区域CRUD**: 完整的创建、读取、更新、删除操作
+- **层级管理**: 支持省、市、区三级结构管理
+- **状态管理**: 区域启用/禁用状态控制
+- **子节点管理**: 支持在父节点下添加子节点
+- **表单验证**: 完整的表单验证和错误处理
+
+### 测试
+
+#### 测试标准和框架
+- **测试框架**: Vitest 3.2.4 + Testing Library 16.3.0 [Source: architecture/testing-strategy.md#工具版本]
+- **测试位置**:
+  - 集成测试: `packages/area-management-ui/tests/integration/**/*.test.tsx`
+  [Source: architecture/testing-strategy.md#单元测试]
+
+#### 测试模式和策略
+- **useQuery测试**: 使用真实的QueryClientProvider而不是mock react-query [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+- **元素定位**: 使用data-testid进行元素定位,比placeholder/role更准确稳定 [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试策略关键发现]
+- **Mock策略**: 使用智能mock过滤React Hook Form props [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试架构改进]
+- **测试工具**: 提供QueryClientProvider和必要的上下文 [Source: docs/stories/007.015.auth-management-ui-package.story.md#测试架构改进]
+
+#### 特定测试要求
+- **区域CRUD测试**: 验证区域创建、读取、更新、删除功能
+- **树形结构测试**: 验证树形结构展示和异步加载功能
+- **层级管理测试**: 验证省市区层级关系管理
+- **表单验证测试**: 验证表单验证和错误处理
+- **API集成测试**: 验证与区域模块的API集成
+
+#### 测试执行命令
+- 运行所有测试: `cd packages/area-management-ui && pnpm test`
+- 运行单元测试: `cd packages/area-management-ui && pnpm test:unit`
+- 运行集成测试: `cd packages/area-management-ui && pnpm test:integration`
+- 生成覆盖率报告: `cd packages/area-management-ui && pnpm test:coverage`
+
+## 变更日志
+
+| 日期 | 版本 | 描述 | 作者 |
+|------|------|------|------|
+| 2025-11-16 | 1.0 | 初始故事创建 | Bob (Scrum Master) |
+
+## Dev Agent Record
+
+### Agent Model Used
+
+*此部分将在开发过程中由开发代理填充*
+
+### Debug Log References
+
+*此部分将在开发过程中由开发代理填充*
+
+### Completion Notes List
+
+*此部分将在开发过程中由开发代理填充*
+
+### File List
+
+*此部分将在开发过程中由开发代理填充*
+
+## QA Results
+
+*此部分将在质量保证审查过程中由QA代理填充*

+ 18 - 0
packages/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/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',
+    },
+  },
+});

+ 94 - 0
packages/file-management-ui/package.json

@@ -0,0 +1,94 @@
+{
+  "name": "@d8d/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/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": [
+    "file",
+    "management",
+    "upload",
+    "download",
+    "ui",
+    "react",
+    "crud",
+    "minio"
+  ],
+  "author": "D8D Team",
+  "license": "MIT"
+}

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

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

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

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

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

@@ -0,0 +1,488 @@
+import React, { useState } from 'react';
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
+import { Button } from '@d8d/shared-ui-components';
+import { Input } from '@d8d/shared-ui-components';
+import { Card, CardContent, CardHeader, CardTitle } from '@d8d/shared-ui-components';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components';
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components';
+import { Badge } from '@d8d/shared-ui-components';
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@d8d/shared-ui-components';
+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 { fileClient } from '../api/fileClient';
+import type { InferResponseType, InferRequestType } from 'hono/client';
+import dayjs from 'dayjs';
+import MinioUploader from './MinioUploader';
+import { UpdateFileDto } from '@d8d/file-module/schemas';
+import * as z from 'zod';
+
+// 定义类型
+type FileItem = InferResponseType<typeof fileClient.$get, 200>['data'][0];
+type FileListResponse = InferResponseType<typeof fileClient.$get, 200>;
+type UpdateFileRequest = InferRequestType<typeof fileClient[':id']['$put']>['json'];
+type FileFormData = z.infer<typeof UpdateFileDto>;
+
+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(UpdateFileDto),
+    defaultValues: {
+      name: '',
+      description: '',
+    },
+  });
+
+  // 获取文件列表数据
+  const fetchFiles = async ({ page, pageSize }: { page: number; pageSize: number }): Promise<FileListResponse> => {
+    const response = await fileClient.$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 }) =>
+      fileClient[':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) => fileClient[':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)}>
+            <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.uploadUser ? (file.uploadUser.nickname || file.uploadUser.username) : '-'}
+                      </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]">
+          <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>
+
+      {/* 删除确认对话框 */}
+      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
+        <AlertDialogContent>
+          <AlertDialogHeader>
+            <AlertDialogTitle>确认删除</AlertDialogTitle>
+            <AlertDialogDescription>
+              确定要删除这个文件记录吗?此操作不可恢复。
+            </AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>取消</AlertDialogCancel>
+            <AlertDialogAction onClick={handleDeleteConfirm} className="bg-red-600 hover:bg-red-700">
+              确认删除
+            </AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
+    </div>
+  );
+};

+ 514 - 0
packages/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';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components';
+import { Card, CardContent } from '@d8d/shared-ui-components';
+import { toast } from 'sonner';
+import { fileClient } from '../api/fileClient';
+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 fileClient.$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 fileClient[':id']['$get']({ param: { id: Number(fileId) } });
+            if (response.status === 200) {
+              return response.json();
+            }
+            return null;
+          } catch (error) {
+            console.error(`获取文件 ${fileId} 详情失败:`, error);
+            return null;
+          }
+        });
+
+        const files = await Promise.all(filePromises);
+        return files.filter(file => file !== null);
+      }
+
+      // 处理单选模式下的单值
+      if (!Array.isArray(value)) {
+        const response = await fileClient[':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 fileClient.$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"
+              >
+                {((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]">
+          <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/file-management-ui/src/components/MinioUploader.tsx

@@ -0,0 +1,468 @@
+import React, { useState, useCallback } from 'react';
+import { Button } from '@d8d/shared-ui-components';
+import { Card, CardContent } from '@d8d/shared-ui-components';
+import { Progress } from '@d8d/shared-ui-components';
+import { Badge } from '@d8d/shared-ui-components';
+import { toast } from 'sonner';
+import { Upload, X, CheckCircle, Loader2, FileText } from 'lucide-react';
+import { uploadMinIOWithPolicy, MinioProgressEvent } from '../utils/minio';
+
+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/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/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/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 { fileClient } from '../api/fileClient';
+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 fileClient.$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 fileClient[':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 fileClient[':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/file-management-ui/src/hooks/useFileSelector.ts

@@ -0,0 +1,126 @@
+import { useState, useCallback } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { fileClient } from '../api/fileClient';
+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 fileClient.$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/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/file-management-ui/src/types/file.ts

@@ -0,0 +1,78 @@
+import type { InferResponseType, InferRequestType } from 'hono/client';
+import type { fileRoutes } from '@d8d/file-module';
+
+// 文件列表响应类型
+export type FileListResponse = InferResponseType<typeof fileRoutes.$get, 200>;
+
+// 单个文件类型
+export type FileType = FileListResponse['data'][0];
+
+// 文件上传策略类型
+export type UploadPolicyResponse = InferResponseType<typeof fileRoutes['upload-policy']['$post'], 200>;
+
+// 多部分上传策略类型
+export type MultipartUploadPolicyResponse = InferResponseType<typeof fileRoutes['multipart-policy']['$post'], 200>;
+
+// 更新文件请求类型
+export type UpdateFileRequest = InferRequestType<typeof fileRoutes[':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/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/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/file-management-ui/src/utils/minio.ts

@@ -0,0 +1,385 @@
+import type { InferResponseType } from 'hono/client';
+import { fileClient } from "../api/fileClient";
+
+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 fileClient["multipart-policy"]['$post'],200>
+type MinioUploadPolicy = InferResponseType<typeof fileClient["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 fileClient["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 fileClient["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 fileClient["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);
+  }
+}

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

@@ -0,0 +1,110 @@
+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 API客户端
+vi.mock('../../src/api/fileClient', () => ({
+  fileClient: {
+    $get: vi.fn(),
+    ':id': {
+      $put: vi.fn(),
+      $delete: vi.fn(),
+    },
+  },
+}));
+
+// 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}
+      </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.getByText('上传文件');
+    fireEvent.click(uploadButton);
+
+    await waitFor(() => {
+      expect(screen.getByText('上传文件')).toBeInTheDocument();
+      expect(screen.getByTestId('minio-uploader')).toBeInTheDocument();
+    });
+  });
+
+  it('应该显示加载状态', () => {
+    // Mock API调用返回加载状态
+    const { fileClient } = require('../../src/api/fileClient');
+    fileClient.$get.mockReturnValue(new Promise(() => {}));
+
+    renderWithQueryClient(<FileManagement />);
+
+    expect(screen.getByRole('table')).toBeInTheDocument();
+  });
+
+  it('应该显示空状态', async () => {
+    const { fileClient } = require('../../src/api/fileClient');
+    fileClient.$get.mockResolvedValue({
+      ok: true,
+      json: async () => ({
+        data: [],
+        pagination: { current: 1, pageSize: 10, total: 0 }
+      })
+    });
+
+    renderWithQueryClient(<FileManagement />);
+
+    await waitFor(() => {
+      expect(screen.getByText('暂无文件')).toBeInTheDocument();
+    });
+  });
+});

+ 34 - 0
packages/file-management-ui/tsconfig.json

@@ -0,0 +1,34 @@
+{
+  "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,
+    "declaration": true,
+    "declarationMap": true,
+    "sourceMap": true,
+    "outDir": "./dist",
+    "baseUrl": ".",
+    "paths": {
+      "@/*": ["./src/*"]
+    }
+  },
+  "include": [
+    "src/**/*",
+    "tests/**/*"
+  ],
+  "exclude": [
+    "node_modules",
+    "dist"
+  ]
+}

+ 24 - 0
packages/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'
+    }
+  }
+});