Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
perf: Improve the chat input box on the homepage and the chat detail page (#409)
Gaoaececd0fefe0
diff --git a/project/web/src/app/[lng]/chat/[taskId]/page.tsx b/project/web/src/app/[lng]/chat/[taskId]/page.tsxindex 2a4ffe1f..6b5ec479 100644--- a/project/web/src/app/[lng]/chat/[taskId]/page.tsx+++ b/project/web/src/app/[lng]/chat/[taskId]/page.tsx@@ -273,7 +273,7 @@ export default function ChatDetailPage() {/>{/* 底部输入区域 */}- <div className="p-4 bg-background border-t border-border shrink-0">+ <div className="w-full p-4"><ChatInputvalue={inputValue}onChange={setInputValue}diff --git a/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx b/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsxindex e5ed4831..852280d5 100644--- a/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx+++ b/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx@@ -222,25 +222,6 @@ export const PricingContent = memo(({ lng }: PricingContentProps) => {<h1 className="text-4xl md:text-5xl font-bold text-foreground tracking-tight">{t('pricing.pageTitle')}</h1>- {userStore.userInfo && (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="outline"- size="icon"- onClick={() => setSubscriptionDialogOpen(true)}- className="h-10 w-10"- >- <Settings className="h-5 w-5" />- </Button>- </TooltipTrigger>- <TooltipContent>- <p>{t('subscriptionManagement')}</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- )}</div></header>diff --git a/project/web/src/app/[lng]/tasks-history/page.tsx b/project/web/src/app/[lng]/tasks-history/page.tsxindex 60dfd8d1..96573e15 100644--- a/project/web/src/app/[lng]/tasks-history/page.tsx+++ b/project/web/src/app/[lng]/tasks-history/page.tsx@@ -6,7 +6,7 @@import { useEffect, useState, useCallback } from 'react'import { useParams, useRouter } from 'next/navigation'-import { ArrowLeft, History, Loader2, RefreshCw, Trash2 } from 'lucide-react'+import { ArrowLeft, History, RefreshCw } from 'lucide-react'import { TaskCard, TaskCardSkeleton } from '@/components/Chat'import { Button } from '@/components/ui/button'import { agentApi, type TaskListItem } from '@/api/agent'@@ -22,66 +22,60 @@ export default function TasksHistoryPage() {// 状态const [tasks, setTasks] = useState<TaskListItem[]>([])const [isLoading, setIsLoading] = useState(true)- const [isLoadingMore, setIsLoadingMore] = useState(false)const [page, setPage] = useState(1)- const [hasMore, setHasMore] = useState(true)const [total, setTotal] = useState(0)- const pageSize = 12+ // 每页 16 条+ const pageSize = 16- /** 加载任务列表 */- const loadTasks = useCallback(async (pageNum: number, append = false) => {- if (pageNum === 1) {- setIsLoading(true)- } else {- setIsLoadingMore(true)- }+ const totalPages = Math.max(1, Math.ceil(total / pageSize || 1))- try {- const result = await agentApi.getTaskList(pageNum, pageSize)- if (result && result.code === 0 && result.data) {- const newTasks = result.data.list || []- setTasks((prev) => (append ? [...prev, ...newTasks] : newTasks))- setTotal(result.data.total || 0)- setHasMore(newTasks.length === pageSize && tasks.length + newTasks.length < (result.data.total || 0))+ /** 加载任务列表(分页) */+ const loadTasks = useCallback(+ async (pageNum: number) => {+ setIsLoading(true)+ try {+ const result = await agentApi.getTaskList(pageNum, pageSize)+ if (result && result.code === 0 && result.data) {+ const newTasks = result.data.list || []+ setTasks(newTasks)+ setTotal(result.data.total || 0)+ setPage(pageNum)+ }+ } catch (error) {+ console.error('Load task list failed:', error)+ toast.error(t('message.error' as any))+ } finally {+ setIsLoading(false)}- } catch (error) {- console.error('Load task list failed:', error)- toast.error(t('message.error' as any))- } finally {- setIsLoading(false)- setIsLoadingMore(false)- }- }, [tasks.length])+ },+ [pageSize, t]+ )/** 初始加载 */useEffect(() => {loadTasks(1)- }, []) // eslint-disable-line react-hooks/exhaustive-deps-- /** 加载更多 */- const handleLoadMore = () => {- if (!isLoadingMore && hasMore) {- const nextPage = page + 1- setPage(nextPage)- loadTasks(nextPage, true)- }- }+ }, [loadTasks])- /** 刷新列表 */+ /** 刷新列表,回到第一页 */const handleRefresh = () => {- setPage(1)loadTasks(1)}- /** 处理删除任务 */+ /** 分页切换 */+ const handlePageChange = (nextPage: number) => {+ if (nextPage < 1 || nextPage > totalPages) return+ loadTasks(nextPage)+ }++ /** 处理删除任务:删除后刷新当前页 */const handleDelete = async (id: string) => {try {const result = await agentApi.deleteTask(id)if (result && result.code === 0) {- setTasks((prev) => prev.filter((task) => task.id !== id))- setTotal((prev) => prev - 1)toast.success(t('task.deleteSuccess' as any))+ // 删除成功后,重新加载当前页,避免页码错乱+ loadTasks(page)} else {toast.error(result?.message || t('task.deleteFailed' as any))}@@ -96,7 +90,7 @@ export default function TasksHistoryPage() {}return (- <div className="min-h-screen bg-background">+ <div className="flex flex-col min-h-screen bg-background">{/* 顶部导航 */}<header className="sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-card border-b border-border"><div className="flex items-center gap-3">@@ -129,64 +123,71 @@ export default function TasksHistoryPage() {</Button></header>- {/* 任务列表 */}- <div className="max-w-6xl mx-auto px-4 py-6">- {isLoading ? (- // 加载骨架屏- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">- {Array.from({ length: pageSize }).map((_, index) => (- <TaskCardSkeleton key={index} />- ))}- </div>- ) : tasks.length === 0 ? (- // 空状态- <div className="flex flex-col items-center justify-center py-16">- <History className="w-16 h-16 text-muted-foreground/30 mb-4" />- <p className="text-muted-foreground mb-4">{t('history.empty' as any)}</p>- <Button onClick={handleBack}>- {t('home.startChat' as any)}- </Button>- </div>- ) : (- // 任务卡片网格- <>+ {/* 任务列表,整体垂直 & 水平居中 */}+ <main className="flex-1 flex items-center justify-center px-4 py-6">+ <div className="w-full max-w-6xl">+ {isLoading ? (+ // 加载骨架屏<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">- {tasks.map((task) => (- <TaskCard- key={task.id}- id={task.id}- title={task.title || t('task.newChat' as any)}- createdAt={task.createdAt}- updatedAt={task.updatedAt}- onDelete={handleDelete}- />+ {Array.from({ length: pageSize }).map((_, index) => (+ <TaskCardSkeleton key={index} />))}</div>-- {/* 加载更多 */}- {hasMore && (- <div className="flex justify-center mt-8">- <Button- variant="outline"- onClick={handleLoadMore}- disabled={isLoadingMore}- className="min-w-[120px]"- >- {isLoadingMore ? (- <>- <Loader2 className="w-4 h-4 mr-2 animate-spin" />- {t('history.loading' as any)}- </>- ) : (- t('history.loadMore' as any)- )}- </Button>+ ) : tasks.length === 0 ? (+ // 空状态+ <div className="flex flex-col items-center justify-center py-16">+ <History className="w-16 h-16 text-muted-foreground/30 mb-4" />+ <p className="text-muted-foreground mb-4">{t('history.empty' as any)}</p>+ <Button onClick={handleBack}>+ {t('home.startChat' as any)}+ </Button>+ </div>+ ) : (+ // 任务卡片网格 + 分页器+ <>+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">+ {tasks.map((task) => (+ <TaskCard+ key={task.id}+ id={task.id}+ title={task.title || t('task.newChat' as any)}+ createdAt={task.createdAt}+ updatedAt={task.updatedAt}+ onDelete={handleDelete}+ />+ ))}</div>- )}- </>- )}- </div>++ {/* 分页器 */}+ {totalPages > 1 && (+ <div className="flex items-center justify-between mt-8">+ <span className="text-sm text-muted-foreground">+ {page} / {totalPages}+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ disabled={page <= 1 || isLoading}+ onClick={() => handlePageChange(page - 1)}+ >+ {t('history.prevPage' as any) || 'Prev'}+ </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={page >= totalPages || isLoading}+ onClick={() => handlePageChange(page + 1)}+ >+ {t('history.nextPage' as any) || 'Next'}+ </Button>+ </div>+ </div>+ )}+ </>+ )}+ </div>+ </main></div>)}-diff --git a/project/web/src/components/Chat/ChatInput/index.tsx b/project/web/src/components/Chat/ChatInput/index.tsxindex 4347d713..561a534f 100644--- a/project/web/src/components/Chat/ChatInput/index.tsx+++ b/project/web/src/components/Chat/ChatInput/index.tsx@@ -61,12 +61,19 @@ export function ChatInput({const textareaRef = useRef<HTMLTextAreaElement>(null)const [isFocused, setIsFocused] = useState(false)- /** 自动调整高度 */+ /** 自动调整高度+ * - large 模式:根据内容自适应高度(最多 200px)+ * - compact 模式:保持单行起步,允许根据内容适度增高+ */useEffect(() => {- if (textareaRef.current) {+ if (!textareaRef.current) return++ if (mode === 'large') {textareaRef.current.style.height = 'auto'- const maxHeight = mode === 'large' ? 200 : 120+ const maxHeight = 200textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, maxHeight)}px`+ } else {+ textareaRef.current.style.height = 'auto'}}, [value, mode])@@ -95,38 +102,29 @@ export function ChatInput({return (<divclassName={cn(- 'rounded-2xl border bg-card transition-all duration-300 border-border shadow-sm hover:border-border/80 hover:shadow-md',+ 'w-full rounded-2xl border bg-card transition-all duration-300 border-border shadow-sm hover:border-border/80 hover:shadow-md',mode === 'large' ? 'p-4' : 'p-3',+ // 详情页(compact 模式)允许输入区域根据父容器拉伸+ mode === 'compact' && 'h-full flex flex-col',className,)}>- {/* 媒体预览区域 */}- {(medias.length > 0 || mode === 'large') && (- <div className={cn('mb-3', mode === 'compact' && medias.length === 0 && 'hidden')}>+ {/* 第一层:媒体预览区域(只有有媒体时展示) */}+ {medias.length > 0 && (+ <div className="mb-3"><MediaUploadmedias={medias}isUploading={isUploading}disabled={disabled || isGenerating}onFilesChange={onMediasChange}onRemove={onMediaRemove}+ showUploadButton={false}/></div>)}- {/* 输入区域 */}- <div className="flex items-end gap-3">- {/* 上传按钮 - 仅在 compact 模式且无媒体时显示 */}- {mode === 'compact' && medias.length === 0 && (- <MediaUpload- medias={[]}- isUploading={isUploading}- disabled={disabled || isGenerating}- onFilesChange={onMediasChange}- className="shrink-0"- />- )}-- {/* 文本输入框 */}+ {/* 第二层:文本输入区域 */}+ <div className={cn('flex-1', mode === 'compact' && 'w-full')}><textarearef={textareaRef}value={value}@@ -138,13 +136,29 @@ export function ChatInput({disabled={disabled || isGenerating}rows={mode === 'large' ? 3 : 1}className={cn(- 'flex-1 resize-none border-none outline-none focus:outline-none bg-transparent text-foreground placeholder:text-muted-foreground',+ 'w-full resize-none border-none outline-none focus:outline-none bg-transparent text-foreground placeholder:text-muted-foreground','disabled:opacity-50 disabled:cursor-not-allowed',- mode === 'large' ? 'text-base min-h-[80px]' : 'text-sm min-h-[24px]',+ mode === 'large' ? 'text-base min-h-[80px]' : 'text-sm min-h-[40px]',)}/>+ </div>++ {/* 第三层:操作栏(左侧其他操作,右侧发送按钮) */}+ <div className="mt-3 flex items-center justify-between gap-2">+ {/* 左侧:其它操作(当前仅上传按钮) */}+ <div className="flex items-center gap-2">+ <MediaUpload+ medias={medias}+ isUploading={isUploading}+ disabled={disabled || isGenerating}+ onFilesChange={onMediasChange}+ onRemove={onMediaRemove}+ showList={false}+ buttonVariant="icon"+ />+ </div>- {/* 发送/停止按钮 */}+ {/* 右侧:发送/停止按钮 */}<buttononClick={handleButtonClick}disabled={!isGenerating && !canSend}diff --git a/project/web/src/components/Chat/ChatMessage/index.tsx b/project/web/src/components/Chat/ChatMessage/index.tsxindex 8c0132a7..55cef342 100644--- a/project/web/src/components/Chat/ChatMessage/index.tsx+++ b/project/web/src/components/Chat/ChatMessage/index.tsx@@ -17,6 +17,7 @@ import type { IUploadedMedia } from '../MediaUpload'import type { IMessageStep, IWorkflowStep } from '@/store/agent'import logo from '@/assets/images/logo.png'import styles from './ChatMessage.module.scss'+import { MediaPreview } from '@/components/common/MediaPreview'export type { IWorkflowStep }@@ -253,6 +254,24 @@ export function ChatMessage({const isUser = role === 'user'const isStreaming = status === 'streaming' || status === 'pending'+ // 媒体预览状态(统一使用全局 MediaPreview 组件)+ const [previewIndex, setPreviewIndex] = useState<number | null>(null)++ const previewableMedias = useMemo(+ () => medias.filter((m) => m.type === 'image' || m.type === 'video'),+ [medias],+ )++ const previewItems = useMemo(+ () =>+ previewableMedias.map((m) => ({+ type: m.type === 'video' ? 'video' as const : 'image' as const,+ src: getOssUrl(m.url),+ title: m.name || m.file?.name,+ })),+ [previewableMedias],+ )+// 处理消息步骤:如果有 steps 则使用 steps,否则从 content 生成单个步骤const displaySteps = useMemo(() => {if (steps && steps.length > 0) {@@ -334,26 +353,45 @@ export function ChatMessage({)}+ const isPreviewable = media.type === 'image' || media.type === 'video'+ const mediaUrl = getOssUrl(media.url)++ const thisPreviewIndex = isPreviewable+ ? previewableMedias.findIndex((m) => m === media)+ : -1++ const handleOpenPreview = () => {+ if (thisPreviewIndex >= 0) {+ setPreviewIndex(thisPreviewIndex)+ }+ }++ const Wrapper: React.ElementType = isPreviewable ? 'button' : 'div'+return (- <div+ <Wrapperkey={index}- className="w-24 h-24 rounded-lg overflow-hidden border border-border bg-muted"+ type={isPreviewable ? 'button' : undefined}+ onClick={isPreviewable ? handleOpenPreview : undefined}+ className={cn(+ 'w-24 h-24 rounded-lg overflow-hidden border border-border bg-muted',+ isPreviewable && 'cursor-pointer',+ )}>{media.type === 'video' ? (<video- src={getOssUrl(media.url)}+ src={mediaUrl}className="w-full h-full object-cover"muted- controls/>) : (<img- src={getOssUrl(media.url)}+ src={mediaUrl}alt={`attachment-${index}`}className="w-full h-full object-cover"/>)}- </div>+ </Wrapper>)})}</div>@@ -412,6 +450,16 @@ export function ChatMessage({</div>)}</div>++ {/* 全局媒体预览(图片 / 视频) */}+ {previewItems.length > 0 && (+ <MediaPreview+ open={previewIndex !== null}+ items={previewItems}+ initialIndex={previewIndex ?? 0}+ onClose={() => setPreviewIndex(null)}+ />+ )}</div>)}diff --git a/project/web/src/components/Chat/MediaUpload/index.tsx b/project/web/src/components/Chat/MediaUpload/index.tsxindex 7f3b8126..04a0007b 100644--- a/project/web/src/components/Chat/MediaUpload/index.tsx+++ b/project/web/src/components/Chat/MediaUpload/index.tsx@@ -5,14 +5,17 @@'use client'-import { useRef, useMemo, useEffect } from 'react'+import { useRef, useMemo, useEffect, useState } from 'react'import { Loader2, Plus, X, FileText } from 'lucide-react'import { cn } from '@/lib/utils'import { getOssUrl } from '@/utils/oss'import { useTransClient } from '@/app/i18n/client'+import { MediaPreview } from '@/components/common/MediaPreview'/** 上传的媒体文件类型 */export interface IUploadedMedia {+ /** 唯一标识(用于进度、删除等场景的精确匹配) */+ id?: stringurl: stringtype: 'image' | 'video' | 'document'/** 上传进度 0-100,undefined 表示上传完成 */@@ -23,6 +26,14 @@ export interface IUploadedMedia {name?: string}+const formatFileSize = (bytes?: number) => {+ if (!bytes || bytes <= 0) return ''+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`+}+export interface IMediaUploadProps {/** 已上传的媒体列表 */medias: IUploadedMedia[]@@ -36,6 +47,12 @@ export interface IMediaUploadProps {onRemove?: (index: number) => void/** 最大上传数量 */maxCount?: number+ /** 是否显示媒体列表(只显示上传按钮时可关闭) */+ showList?: boolean+ /** 是否显示上传按钮(只做预览时可关闭) */+ showUploadButton?: boolean+ /** 上传按钮样式:网格方块(默认)或小圆形图标按钮 */+ buttonVariant?: 'grid' | 'icon'/** 自定义类名 */className?: string}@@ -49,11 +66,15 @@ export function MediaUpload({disabled = false,onFilesChange,onRemove,- maxCount = 9,+ maxCount = 5,+ showList = true,+ showUploadButton = true,+ buttonVariant = 'grid',className,}: IMediaUploadProps) {const { t } = useTransClient('chat')const fileInputRef = useRef<HTMLInputElement>(null)+ const [previewIndex, setPreviewIndex] = useState<number | null>(null)/** 缓存的 ObjectURL 集合 */const previewUrls = useMemo(() => {@@ -80,7 +101,19 @@ export function MediaUpload({const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {const files = e.target.filesif (files && files.length > 0) {- onFilesChange?.(files)+ const remaining = Math.max(0, maxCount - medias.length)+ if (remaining <= 0) {+ // 已达到最大数量,直接忽略本次选择+ } else if (files.length > remaining) {+ // 只取前 remaining 个文件+ const dt = new DataTransfer()+ for (let i = 0; i < remaining; i++) {+ dt.items.add(files[i])+ }+ onFilesChange?.(dt.files)+ } else {+ onFilesChange?.(files)+ }}// 重置 input,允许重复选择同一文件if (fileInputRef.current) {@@ -97,82 +130,130 @@ export function MediaUpload({const canUploadMore = medias.length < maxCount+ /** 打开预览 */+ const handlePreview = (index: number) => {+ const media = medias[index]+ if (!media) return+ if (media.type === 'document') return+ setPreviewIndex(index)+ }++ const handleClosePreview = () => {+ setPreviewIndex(null)+ }+return (- <div className={cn('flex flex-wrap items-center gap-2', className)}>+ <div+ className={cn(+ 'flex items-center gap-2',+ buttonVariant === 'grid' && 'flex-wrap',+ className,+ )}+ >{/* 已上传的媒体列表 */}- {medias.map((media, index) => (+ {showList &&+ medias.map((media, index) => (<divkey={`${media.url}-${index}`}className={cn('relative group rounded-lg overflow-hidden border border-border bg-muted',- media.type === 'document' ? 'w-auto min-w-[120px] h-14 px-3' : 'w-14 h-14',+ media.type === 'document' || media.type === 'video'+ ? 'min-w-[220px] h-14'+ : 'w-14 h-14',)}>{/* 媒体预览 */}{media.type === 'document' ? (- <div className="flex items-center gap-2 h-full">- <FileText className="w-4 h-4 text-muted-foreground shrink-0" />- <span className="text-xs text-foreground truncate max-w-[80px]">- {media.name || media.file?.name || t('media.document' as any)}- </span>+ <div className="flex items-center gap-3 h-full px-3 bg-background">+ <div className="flex items-center justify-center w-7 h-7 rounded-md bg-red-500/10 text-red-500">+ <FileText className="w-4 h-4" />+ </div>+ <div className="flex flex-col justify-center min-w-0">+ <span className="text-xs font-medium text-foreground truncate max-w-[160px]">+ {media.name || media.file?.name || t('media.document' as any)}+ </span>+ {media.file && (+ <span className="text-[11px] text-muted-foreground mt-0.5">+ {formatFileSize(media.file.size)}+ </span>+ )}+ </div></div>) : media.type === 'video' ? (- <video- src={previewUrls[index]}- className="w-full h-full object-cover"- muted- />+ <button+ type="button"+ onClick={() => handlePreview(index)}+ className="flex items-center gap-3 h-full w-full px-3 bg-background text-left cursor-pointer"+ >+ <div className="flex items-center justify-center w-7 h-7 rounded-md bg-blue-500/10 text-blue-500">+ <span className="text-[11px] font-semibold">VID</span>+ </div>+ <div className="flex flex-col justify-center min-w-0">+ <span className="text-xs font-medium text-foreground truncate max-w-[160px]">+ {media.name || media.file?.name || 'video'}+ </span>+ {media.file && (+ <span className="text-[11px] text-muted-foreground mt-0.5">+ {formatFileSize(media.file.size)}+ </span>+ )}+ </div>+ </button>) : (<imgsrc={previewUrls[index]}alt={`media-${index}`}- className="w-full h-full object-cover"+ className="w-full h-full object-cover cursor-pointer"+ onClick={() => handlePreview(index)}/>)}- {/* 上传进度遮罩 */}+ {/* 上传进度遮罩:仅在进度未完成时显示,由 Hook 负责在完成时清理 progress */}{media.progress !== undefined && media.progress < 100 && (- <div className="absolute inset-0 flex items-center justify-center bg-black/50">- <div className="relative w-8 h-8">- <svg className="w-8 h-8 -rotate-90">- <circle- cx="16"- cy="16"- r="12"- stroke="rgba(255,255,255,0.3)"- strokeWidth="3"- fill="none"- />- <circle- cx="16"- cy="16"- r="12"- stroke="white"- strokeWidth="3"- fill="none"- strokeDasharray={`${media.progress * 0.75} 75`}- strokeLinecap="round"- />- </svg>- <span className="absolute inset-0 flex items-center justify-center text-white text-[10px] font-medium">- {media.progress}%- </span>- </div>- </div>- )}-- {/* 视频上传完成标记 */}- {media.type === 'video' && media.progress === undefined && (- <div className="absolute bottom-1 right-1 bg-black/60 text-white text-[10px] px-1 rounded">- Video+ <div className="absolute inset-0 flex items-center justify-center bg-black/45">+ {media.type === 'image' ? (+ <Loader2 className="w-6 h-6 text-white animate-spin" />+ ) : (+ <div className="relative w-8 h-8">+ <svg className="w-8 h-8 -rotate-90">+ <circle+ cx="16"+ cy="16"+ r="12"+ stroke="rgba(255,255,255,0.3)"+ strokeWidth="3"+ fill="none"+ />+ <circle+ cx="16"+ cy="16"+ r="12"+ stroke="white"+ strokeWidth="3"+ fill="none"+ strokeDasharray={`${(media.progress || 0) * 0.75} 75`}+ strokeLinecap="round"+ />+ </svg>+ <span className="absolute inset-0 flex items-center justify-center text-white text-[10px] font-medium">+ {media.progress}%+ </span>+ </div>+ )}</div>)}- {/* 删除按钮 */}- {!disabled && media.progress === undefined && (+ {/* 删除按钮(上传中和上传完成都可关闭) */}+ {!disabled && (<buttononClick={() => onRemove?.(index)}- className="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm hover:bg-destructive/90"+ className={cn(+ 'absolute top-1 right-1 z-10 w-4 h-4 rounded-full flex items-center justify-center cursor-pointer',+ 'bg-background/95 text-muted-foreground shadow-sm border border-border/70',+ 'hover:bg-destructive hover:text-destructive-foreground hover:border-destructive transition-colors',+ )}+ aria-label={t('media.remove' as any)}+ type="button"><X className="w-3 h-3" /></button>@@ -181,26 +262,37 @@ export function MediaUpload({))}{/* 上传按钮 */}- {canUploadMore && (+ {showUploadButton && canUploadMore && (<><inputref={fileInputRef}type="file"- accept="image/*,video/*,.pdf,.doc,.docx,.txt"+ accept="*/*"multipleonChange={handleFileChange}className="hidden"/><buttononClick={handleUploadClick}- disabled={disabled || isUploading}+ disabled={buttonVariant === 'grid' ? disabled || isUploading : disabled}className={cn(- 'w-14 h-14 rounded-lg border-2 border-dashed border-border flex items-center justify-center transition-all',- 'hover:border-primary hover:bg-primary/10',- 'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent',+ buttonVariant === 'grid'+ ? cn(+ 'w-14 h-14 rounded-lg border-2 border-dashed border-border flex items-center justify-center transition-all cursor-pointer',+ 'hover:border-primary hover:bg-primary/10',+ 'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent',+ )+ : cn(+ // 小圆形图标按钮:更精致的聊天操作样式+ 'w-8 h-8 rounded-full flex items-center justify-center text-muted-foreground transition-all cursor-pointer',+ 'bg-background border border-border/80 hover:bg-primary/5 hover:border-primary/60',+ 'shadow-sm hover:shadow disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-background disabled:hover:border-border/80',+ ),)}+ aria-label="Upload media"+ type="button">- {isUploading ? (+ {buttonVariant === 'grid' && isUploading ? (<Loader2 className="w-5 h-5 text-muted-foreground animate-spin" />) : (<Plus className="w-5 h-5 text-muted-foreground" />@@ -208,6 +300,18 @@ export function MediaUpload({</button></>)}++ {/* 预览大图 / 视频 - 使用全局 MediaPreview 组件 */}+ <MediaPreview+ open={previewIndex !== null}+ items={previewUrls.map((src, idx) => ({+ type: medias[idx]?.type === 'video' ? 'video' : 'image',+ src,+ title: medias[idx]?.name || medias[idx]?.file?.name,+ }))}+ initialIndex={previewIndex ?? 0}+ onClose={handleClosePreview}+ /></div>)}diff --git a/project/web/src/components/common/MediaPreview.tsx b/project/web/src/components/common/MediaPreview.tsxnew file mode 100644index 00000000..895d52ff--- /dev/null+++ b/project/web/src/components/common/MediaPreview.tsx@@ -0,0 +1,147 @@+'use client'++import { useEffect, useState } from 'react'+import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog'+import { cn } from '@/lib/utils'+import { X, ChevronLeft, ChevronRight } from 'lucide-react'+import { motion, AnimatePresence } from 'framer-motion'++export interface MediaPreviewItem {+ type: 'image' | 'video'+ src: string+ title?: string+}++export interface MediaPreviewProps {+ open: boolean+ items: MediaPreviewItem[]+ initialIndex?: number+ onClose: () => void+}++export const MediaPreview = ({ open, items, initialIndex = 0, onClose }: MediaPreviewProps) => {+ const [index, setIndex] = useState(initialIndex)++ useEffect(() => {+ if (open) {+ setIndex(Math.min(Math.max(initialIndex, 0), Math.max(items.length - 1, 0)))+ }+ }, [open, initialIndex, items.length])++ const hasMultiple = items.length > 1+ const current = items[index]++ const handlePrev = () => {+ if (!hasMultiple) return+ setIndex((prev) => (prev - 1 + items.length) % items.length)+ }++ const handleNext = () => {+ if (!hasMultiple) return+ setIndex((prev) => (prev + 1) % items.length)+ }++ return (+ <Dialog open={open} onOpenChange={(o) => !o && onClose()}>+ <DialogContent+ className={cn(+ 'border-none bg-transparent shadow-none p-0 max-w-[90vw] max-h-[90vh]',+ // 使用默认 overlay 做半透明背景,这里只负责居中内容+ '[&>button]:hidden flex items-center justify-center',+ )}+ >+ {/* 无障碍:为 Dialog 提供隐藏的标题和描述 */}+ <DialogTitle className="sr-only">Media preview</DialogTitle>+ <DialogDescription className="sr-only">+ Preview of uploaded image or video.+ </DialogDescription>++ <div className="relative w-full flex items-center justify-center">+ {/* 内容卡片 */}+ <div className="relative max-h-[80vh] max-w-[90vw] overflow-hidden rounded-xl bg-background shadow-2xl">+ {/* 顶部关闭按钮 */}+ <button+ type="button"+ onClick={onClose}+ className="absolute top-3 right-3 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-background/80 text-foreground shadow-md hover:bg-background cursor-pointer"+ aria-label="Close preview"+ >+ <X className="h-4 w-4" />+ </button>++ {/* 媒体内容 */}+ <div className="flex items-center justify-center bg-muted/40">+ <AnimatePresence mode="wait">+ {current && (+ <motion.div+ key={`${current.src}-${index}`}+ initial={{ opacity: 0, scale: 0.97 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 0.97 }}+ transition={{ duration: 0.18 }}+ className="max-h-[80vh] max-w-[90vw]"+ >+ {current.type === 'video' ? (+ <video+ src={current.src}+ className="max-h-[80vh] max-w-[90vw] bg-black object-contain"+ controls+ autoPlay+ />+ ) : (+ <img+ src={current.src}+ alt={current.title || 'preview'}+ className="max-h-[80vh] max-w-[90vw] object-contain"+ />+ )}+ </motion.div>+ )}+ </AnimatePresence>+ </div>++ {/* 底部索引 / 标题 */}+ <div className="flex items-center justify-between px-4 py-2 text-xs text-muted-foreground border-t border-border/60 bg-background/80">+ {hasMultiple ? (+ <span>+ {index + 1}/{items.length}+ </span>+ ) : (+ <span />+ )}+ {current?.title && (+ <span className="truncate max-w-[60%] text-right">{current.title}</span>+ )}+ </div>+ </div>++ {/* 左右切换按钮(悬浮在卡片两侧,半透明浅色) */}+ {hasMultiple && (+ <>+ <button+ type="button"+ onClick={handlePrev}+ className="absolute left-3 md:left-10 flex h-8 w-8 items-center justify-center rounded-full bg-background/80 text-foreground shadow-md hover:bg-background cursor-pointer"+ aria-label="Previous"+ >+ <ChevronLeft className="h-4 w-4" />+ </button>+ <button+ type="button"+ onClick={handleNext}+ className="absolute right-3 md:right-10 flex h-8 w-8 items-center justify-center rounded-full bg-background/80 text-foreground shadow-md hover:bg-background cursor-pointer"+ aria-label="Next"+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ </>+ )}+ </div>+ </DialogContent>+ </Dialog>+ )+}++export default MediaPreview++diff --git a/project/web/src/hooks/useMediaUpload.ts b/project/web/src/hooks/useMediaUpload.tsindex 06489390..88fe8058 100644--- a/project/web/src/hooks/useMediaUpload.ts+++ b/project/web/src/hooks/useMediaUpload.ts@@ -42,8 +42,8 @@ export function useMediaUpload(options?: IUseMediaUploadOptions): IUseMediaUploaconst [medias, setMedias] = useState<IUploadedMedia[]>([])const [isUploading, setIsUploading] = useState(false)- // AbortController 用于取消上传- const uploadAbortRef = useRef<AbortController | null>(null)+ // AbortController Map:按媒体 id 管理中断+ const uploadAbortRef = useRef<Map<string, AbortController> | null>(null)/*** 处理媒体文件上传@@ -54,44 +54,65 @@ export function useMediaUpload(options?: IUseMediaUploadOptions): IUseMediaUploaif (!files.length) returnsetIsUploading(true)- uploadAbortRef.current = new AbortController()+ if (!uploadAbortRef.current) {+ uploadAbortRef.current = new Map()+ }++ const fileArray = Array.from(files)try {- for (let i = 0; i < files.length; i++) {- const file = files[i]+ // 先批量添加占位媒体,记录每个媒体的 id+ const tempMedias: IUploadedMedia[] = fileArray.map((file) => {+ const id = `${Date.now()}-${Math.random().toString(16).slice(2)}`const isVideo = file.type.startsWith('video/')const isDocument = !file.type.startsWith('image/') && !file.type.startsWith('video/')-- // 计算当前媒体在列表中的索引- const mediaIndex = medias.length + i-- // 添加到列表,显示上传进度- const tempMedia: IUploadedMedia = {+ return {+ id,url: '',type: isDocument ? 'document' : isVideo ? 'video' : 'image',progress: 0,file,name: isDocument ? file.name : undefined,}- setMedias((prev) => [...prev, tempMedia])-- // 上传文件(uploadToOss 返回全路径 URL)- const fullUrl = await uploadToOss(file, {- onProgress: (progress) => {- setMedias((prev) =>- prev.map((m, idx) => (idx === mediaIndex ? { ...m, progress } : m)),- )- },- signal: uploadAbortRef.current?.signal,- })-- // 上传完成,更新 URL 并移除进度- setMedias((prev) =>- prev.map((m, idx) =>- idx === mediaIndex ? { ...m, url: fullUrl as string, progress: undefined } : m,- ),- )- }+ })++ setMedias((prev) => [...prev, ...tempMedias])++ // 并行上传所有文件+ await Promise.all(+ fileArray.map(async (file, i) => {+ const targetId = tempMedias[i]?.id+ if (!targetId) return++ const controller = new AbortController()+ uploadAbortRef.current?.set(targetId, controller)++ const fullUrl = await uploadToOss(file, {+ onProgress: (progress) => {+ // 兼容 0-1 或 0-100 两种进度表示,统一成 0-100+ const percent = progress > 1 ? progress : progress * 100+ setMedias((prev) =>+ prev.map((m, idx) =>+ m.id && m.id === targetId+ ? { ...m, progress: Math.min(99, Math.max(0, percent)) }+ : m,+ ),+ )+ },+ signal: controller.signal,+ })++ setMedias((prev) =>+ prev.map((m, idx) =>+ m.id && m.id === targetId+ ? { ...m, url: fullUrl as string, progress: undefined }+ : m,+ ),+ )++ uploadAbortRef.current?.delete(targetId)+ }),+ )} catch (error: any) {if (error.name !== 'AbortError') {console.error('Upload failed:', error)@@ -99,10 +120,10 @@ export function useMediaUpload(options?: IUseMediaUploadOptions): IUseMediaUploa}} finally {setIsUploading(false)- uploadAbortRef.current = null+ uploadAbortRef.current?.clear()}},- [medias.length, onError],+ [onError],)/**@@ -110,7 +131,14 @@ export function useMediaUpload(options?: IUseMediaUploadOptions): IUseMediaUploa* @param index 媒体索引*/const handleMediaRemove = useCallback((index: number) => {- setMedias((prev) => prev.filter((_, i) => i !== index))+ setMedias((prev) => {+ const target = prev[index]+ if (target?.id && uploadAbortRef.current?.has(target.id)) {+ uploadAbortRef.current.get(target.id)?.abort()+ uploadAbortRef.current.delete(target.id)+ }+ return prev.filter((_, i) => i !== index)+ })}, [])/**@@ -118,8 +146,8 @@ export function useMediaUpload(options?: IUseMediaUploadOptions): IUseMediaUploa*/const cancelUpload = useCallback(() => {if (uploadAbortRef.current) {- uploadAbortRef.current.abort()- uploadAbortRef.current = null+ uploadAbortRef.current.forEach((controller) => controller.abort())+ uploadAbortRef.current.clear()}}, [])