diff --git a/frontend/app/features/chat/hooks.test.tsx b/frontend/app/features/chat/hooks.test.tsx index 8ee725b..3c0423b 100644 --- a/frontend/app/features/chat/hooks.test.tsx +++ b/frontend/app/features/chat/hooks.test.tsx @@ -76,6 +76,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 vi.stubGlobal('WebSocket', websocketFactory); // localStorageStub 是聊天 Hook 记忆账号选择所需的浏览器存储替身。 Object.defineProperty(window, 'localStorage', { configurable: true, value: { getItem: vi.fn().mockReturnValue(''), setItem: vi.fn(), removeItem: vi.fn() } }); + // createObjectURLMock 和 revokeObjectURLMock 模拟浏览器图片预览地址的创建与释放。 + Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(/* 当前回调为测试图片生成稳定的临时地址。 */ (file: File) => `blob:${file.name}`) }); + Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() }); }); test('加载账号、会话和消息后可以发送文字与图片', /* 当前回调验证聊天 Hook 成功加载和发送路径。 */ async () => { @@ -123,6 +126,11 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 // imageAction 提交图片消息。 async () => hook.result.current.handleImage(new File(['image'], 'image.png', { type: 'image/png' })), ); + expect(hook.result.current.pendingImage?.url).toBe('blob:image.png'); + await act( + // confirmImageAction 确认预览后提交图片消息。 + async () => hook.result.current.confirmSendImage(), + ); expect(sendImageMock).toHaveBeenCalledWith(expect.objectContaining({ chat_id: 'chat-1', image: expect.any(File) }), expect.objectContaining({ signal: expect.any(AbortSignal) })); // imageInput 是图片发送成功后需要清空的输入框替身。 const imageInput = { value: 'selected-file' } as HTMLInputElement; @@ -131,6 +139,10 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 // secondImageAction 再次发送图片以验证输入框清理。 async () => hook.result.current.handleImage(new File(['image'], 'second.png', { type: 'image/png' })), ); + await act( + // confirmSecondImageAction 确认第二张图片并验证发送后的输入清理。 + async () => hook.result.current.confirmSendImage(), + ); expect(imageInput.value).toBe(''); await act( // emptyImageAction 在没有图片文件时阻止发送。 @@ -335,6 +347,10 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 // imageErrorAction 触发图片发送错误。 async () => hook.result.current.handleImage(new File(['image'], 'error.png', { type: 'image/png' })), ); + await act( + // confirmImageErrorAction 确认预览并进入图片发送错误分支。 + async () => hook.result.current.confirmSendImage(), + ); expect(hook.result.current.error).toBe('图片发送失败'); expect(hook.result.current.retryAvailable).toBe(true); sendImageMock.mockResolvedValueOnce({ message: sentMessageFixture }); @@ -361,6 +377,59 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 hook.unmount(); }); + test('图片预览取消和卸载都会释放临时对象地址', /* 当前回调验证图片预览资源不会跨会话泄漏。 */ async () => { + // hook 是图片预览资源生命周期测试使用的聊天 Hook。 + const hook = renderHook( + // chatHookFactory 创建图片预览测试 Hook。 + () => useChat(), + ); + await waitFor( + // loadingAssertion 等待图片预览测试完成初始加载。 + () => expect(hook.result.current.activeChatID).toBe('chat-1'), + ); + await act( + // previewAction 创建第一张图片预览。 + async () => hook.result.current.handleImage(new File(['image'], 'cancel.png', { type: 'image/png' })), + ); + await act( + // closeAction 取消预览并释放第一张图片地址。 + () => hook.result.current.closeImagePreview(), + ); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:cancel.png'); + await act( + // secondPreviewAction 通过剪贴板入口创建第二张图片预览。 + async () => hook.result.current.handlePastedImages([new File(['image'], 'unmount.png', { type: 'image/png' })]), + ); + hook.unmount(); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:unmount.png'); + }); + + test('切换会话会使旧图片预览失效', /* 当前回调验证旧会话图片不能误发到新会话。 */ async () => { + // hook 是会话切换预览隔离测试使用的聊天 Hook。 + const hook = renderHook( + // chatHookFactory 创建会话切换测试 Hook。 + () => useChat(), + ); + await waitFor( + // chatAssertion 等待默认会话准备完成。 + () => expect(hook.result.current.activeChatID).toBe('chat-1'), + ); + await act( + // previewAction 在原会话创建图片预览。 + async () => hook.result.current.handleImage(new File(['image'], 'switch.png', { type: 'image/png' })), + ); + await act( + // switchAction 切换到另一个会话,使原预览不可再发送。 + () => hook.result.current.setActiveChatID('chat-2'), + ); + await waitFor( + // previewAssertion 等待旧会话预览被清理。 + () => expect(hook.result.current.pendingImage).toBeNull(), + ); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:switch.png'); + hook.unmount(); + }); + test('运行状态轮询失败后仍继续调度下一次轮询', /* 当前回调验证运行状态轮询失败的容错与重试。 */ async () => { vi.useFakeTimers(); try { diff --git a/frontend/app/features/chat/hooks.ts b/frontend/app/features/chat/hooks.ts index 551d6a0..575a0c4 100644 --- a/frontend/app/features/chat/hooks.ts +++ b/frontend/app/features/chat/hooks.ts @@ -6,8 +6,18 @@ import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getCh import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types'; +/** PendingImagePreview 描述等待用户确认的本地图片预览及其资源所有权。 */ +type PendingImagePreview = { + /** file 保存当前预览会话待发送的图片文件。 */ + file: File; + /** url 保存由浏览器创建、仅在当前预览会话有效的临时地址。 */ + url: string; +}; + /** Chat Hook 对外暴露的状态、引用和交互动作。 */ export type UseChatResult = ChatFeatureState & { + /** 待确认发送的图片预览;URL 仅在当前预览会话内有效。 */ + pendingImage: PendingImagePreview | null; /** 当前选中的会话 ID。 */ activeChatID: string; /** 当前账号过滤后的会话。 */ @@ -40,6 +50,12 @@ export type UseChatResult = ChatFeatureState & { handleSend: () => Promise; /** 发送图片消息。 */ handleImage: (file?: File) => Promise; + /** 从剪贴板候选文件中选择首张图片进入预览。 */ + handlePastedImages: (files: File[]) => Promise; + /** 确认发送当前预览图片。 */ + confirmSendImage: () => Promise; + /** 取消当前图片预览并释放临时地址。 */ + closeImagePreview: () => void; /** 重试最近一次失败发送。 */ retrySend: () => Promise; /** 是否存在可重试的发送动作。 */ @@ -76,6 +92,8 @@ export const useChat = (): UseChatResult => { const [unreadOnly, setUnreadOnly] = useState(false); // draft 保存待发送文本。 const [draft, setDraft] = useState(''); + // pendingImage 保存等待用户确认的本地图片和临时预览地址。 + const [pendingImage, setPendingImage] = useState(null); // loading 表示聊天初始数据加载状态。 const [loading, setLoading] = useState(true); // messagesLoading 表示当前会话消息加载状态。 @@ -305,6 +323,11 @@ export const useChat = (): UseChatResult => { sendSequence.current += 1; }, [activeAccountID, activeChatID]); + useEffect(/* 当前回调使会话切换前创建的图片预览失效。 */ () => { + // 会话或账号切换后不得把旧预览发送到新会话。 + setPendingImage(null); + }, [activeAccountID, activeChatID]); + useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { // 会话切换时取消历史分页;新的消息加载拥有独立控制器,不能复用这个低优先级请求。 olderSequence.current += 1; @@ -321,6 +344,14 @@ export const useChat = (): UseChatResult => { sendController.current?.abort(); }, []); + useEffect(/* 当前回调负责图片预览临时地址的生命周期清理。 */ () => { + // preview 保存本次渲染仍然拥有的图片预览;状态替换或组件卸载时释放地址。 + const preview = pendingImage; + return /* 当前回调释放已不再使用的图片对象地址。 */ () => { + if (preview) URL.revokeObjectURL(preview.url); + }; + }, [pendingImage]); + /** 加载当前会话更早消息并保持滚动位置。 */ const loadOlderMessages = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise => { if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return; @@ -561,11 +592,38 @@ export const useChat = (): UseChatResult => { await sendText(text, true); }, [activeAccountID, draft, selectedSession, sendText, sending]); - /** 处理图片选择并发送。 */ - const handleImage = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (file?: File): Promise => { + /** 处理图片选择并进入确认预览,不直接触发平台发送。 */ + const handleImage = useCallback(/* 当前回调接收文件选择结果并创建图片预览。 */ async (file?: File): Promise => { if (!file || !selectedSession || !activeAccountID || sending) return; + if (!file.type.startsWith('image/')) { + setError('仅支持粘贴/发送图片文件'); + return; + } + setError(''); + setPendingImage({ file, url: URL.createObjectURL(file) }); + }, [activeAccountID, selectedSession, sending]); + + /** 从剪贴板文件中选择首张图片,其余文件仍由原生文本粘贴流程处理。 */ + const handlePastedImages = useCallback(/* 当前回调从剪贴板候选文件中筛选图片。 */ async (files: File[]): Promise => { + // image 保存剪贴板中的首张图片,只有图片才会阻止原生文本粘贴。 + const image = files.find(/* 当前回调判断文件是否为图片。 */ file => file.type.startsWith('image/')); + if (image) await handleImage(image); + }, [handleImage]); + + /** 关闭图片预览并清空文件输入,使同一文件可以再次触发选择事件。 */ + const closeImagePreview = useCallback(/* 当前回调关闭预览并清理文件输入。 */ (): void => { + setPendingImage(null); + if (imageInputRef.current) imageInputRef.current.value = ''; + }, []); + + /** 确认发送当前预览图片,发送流程沿用已有请求代次和失败重试保护。 */ + const confirmSendImage = useCallback(/* 当前回调提交用户确认的图片预览。 */ async (): Promise => { + if (!pendingImage || !selectedSession || !activeAccountID || sending) return; + // file 保存用户确认后要提交的平台图片文件。 + const file = pendingImage.file; + setPendingImage(null); await sendImage(file, true); - }, [activeAccountID, selectedSession, sendImage, sending]); + }, [activeAccountID, pendingImage, selectedSession, sendImage, sending]); /** 重试最近一次失败的文本或图片发送。 */ const retrySend = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise => { @@ -574,9 +632,9 @@ export const useChat = (): UseChatResult => { }, [retryImage, retryText, sendImage, sendText]); return { - accounts, activeAccountID, activeSessions, selectedSession, activeAccount, messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading, hasMoreContacts: hasMoreContacts[activeAccountID] === true, emojiOpen, sending, error, liveState, + accounts, activeAccountID, activeSessions, selectedSession, activeAccount, messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading, hasMoreContacts: hasMoreContacts[activeAccountID] === true, emojiOpen, sending, error, liveState, pendingImage, activeChatID, filteredSessions, scrollRef, imageInputRef, setActiveAccountID, setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen, - reloadSessions, loadMoreContacts, loadOlderMessages, handleMessageScroll, handleSend, handleImage, retrySend, retryAvailable: Boolean(retryText || retryImage), unreadForAccount, + reloadSessions, loadMoreContacts, loadOlderMessages, handleMessageScroll, handleSend, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable: Boolean(retryText || retryImage), unreadForAccount, emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime, }; }; diff --git a/frontend/app/features/chat/pages/Chat.tsx b/frontend/app/features/chat/pages/Chat.tsx index b4855cc..d577ab7 100644 --- a/frontend/app/features/chat/pages/Chat.tsx +++ b/frontend/app/features/chat/pages/Chat.tsx @@ -1,8 +1,10 @@ import React from 'react'; import { AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw, - Search, Send, Smile, UserRound, Wifi, WifiOff, + Search, Send, Smile, UserRound, Wifi, WifiOff, X, } from 'lucide-react'; +import Lightbox from 'yet-another-react-lightbox'; +import 'yet-another-react-lightbox/styles.css'; import { useChat } from '../hooks'; import { unreadBadgeClassName, unreadBadgeLabel } from '../state'; @@ -12,12 +14,23 @@ const Chat: React.FC = () => { const { accounts, activeAccountID, activeChatID, activeAccount, selectedSession, filteredSessions, messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading, - hasMoreContacts, emojiOpen, sending, error, liveState, scrollRef, imageInputRef, setActiveAccountID, + hasMoreContacts, emojiOpen, sending, error, liveState, pendingImage, scrollRef, imageInputRef, setActiveAccountID, setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen, reloadSessions, loadMoreContacts, - loadOlderMessages, handleMessageScroll, handleSend, handleImage, retrySend, retryAvailable, + loadOlderMessages, handleMessageScroll, handleSend, handleImage, handlePastedImages, confirmSendImage, closeImagePreview, retrySend, retryAvailable, unreadForAccount, emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime, } = useChat(); + // imageMessages 保存当前会话中的图片消息,供灯箱按消息顺序浏览。 + const imageMessages = React.useMemo(/* 当前回调筛选当前会话中的图片消息。 */ () => messages.filter(/* 当前回调判断消息是否为图片类型。 */ message => message.message_type === 'image'), [messages]); + // imageSlides 将聊天图片转换为灯箱组件所需的展示模型。 + const imageSlides = React.useMemo(/* 当前回调构造灯箱图片展示数据。 */ () => imageMessages.map(/* 当前回调转换单条图片消息。 */ message => ({ src: message.content, alt: '聊天图片' })), [imageMessages]); + // lightboxIndex 保存当前灯箱图片下标;负值表示灯箱关闭。 + const [lightboxIndex, setLightboxIndex] = React.useState(-1); + // openLightbox 根据消息键打开对应的图片灯箱。 + const openLightbox = React.useCallback(/* 当前回调定位并打开指定聊天图片。 */ (messageKey: string): void => { + setLightboxIndex(imageMessages.findIndex(/* 当前回调匹配图片消息键。 */ item => item.message_key === messageKey)); + }, [imageMessages]); + if (loading) return
; return ( @@ -153,9 +166,9 @@ const Chat: React.FC = () => {
{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}
{message.message_type === 'image' ? ( - + ) : message.message_type === 'video' ? (