修复:集成聊天图片预览与真实尺寸发送

This commit is contained in:
Christ committed 2026-08-18 15:08:37 +08:00
1 parent 9eb6be2875
commit ee228381cf
36 files changed
+331 -83

No files matched your search

+69
View File
@@ -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 {
+63 -5
View File
@@ -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<void>;
/** 发送图片消息。 */
handleImage: (file?: File) => Promise<void>;
/** 从剪贴板候选文件中选择首张图片进入预览。 */
handlePastedImages: (files: File[]) => Promise<void>;
/** 确认发送当前预览图片。 */
confirmSendImage: () => Promise<void>;
/** 取消当前图片预览并释放临时地址。 */
closeImagePreview: () => void;
/** 重试最近一次失败发送。 */
retrySend: () => Promise<void>;
/** 是否存在可重试的发送动作。 */
@@ -76,6 +92,8 @@ export const useChat = (): UseChatResult => {
const [unreadOnly, setUnreadOnly] = useState(false);
// draft 保存待发送文本。
const [draft, setDraft] = useState('');
// pendingImage 保存等待用户确认的本地图片和临时预览地址。
const [pendingImage, setPendingImage] = useState<PendingImagePreview | null>(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<void> => {
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<void> => {
/** 处理图片选择并进入确认预览,不直接触发平台发送。 */
const handleImage = useCallback(/* 当前回调接收文件选择结果并创建图片预览。 */ async (file?: File): Promise<void> => {
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<void> => {
// 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<void> => {
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<void> => {
@@ -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,
};
};
+48 -6
View File
@@ -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 <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
return (
@@ -153,9 +166,9 @@ const Chat: React.FC = () => {
<div className={`max-w-[72%] ${outgoing ? 'items-end' : 'items-start'} flex flex-col`}>
<div className="mb-1 px-1 text-[10px] font-semibold text-slate-400">{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
{message.message_type === 'image' ? (
<a href={message.content} target="_blank" rel="noreferrer" className={`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
<button type="button" title="点击预览大图" onClick={openLightbox.bind(null, message.message_key)} className={`block cursor-zoom-in overflow-hidden rounded-2xl border bg-white p-1 text-left shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
<img src={message.content} alt="聊天图片" className="max-h-80 max-w-full rounded-xl object-contain" />
</a>
</button>
) : message.message_type === 'video' ? (
<video src={message.content} controls preload="metadata" className="max-h-80 max-w-full rounded-2xl bg-black" />
) : (
@@ -192,7 +205,17 @@ const Chat: React.FC = () => {
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
<textarea value={draft} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
onPaste={/* 当前回调识别剪贴板中的图片并进入预览流程。 */ event => {
// files 保存剪贴板提供的文件候选列表。
const files = Array.from(event.clipboardData?.files || []);
// image 保存候选列表中的首张图片。
const image = files.find(/* 当前回调判断剪贴板文件是否为图片。 */ file => file.type.startsWith('image/'));
if (image) {
event.preventDefault();
void handlePastedImages(files);
}
}}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行,Ctrl + V 粘贴图片' : '账号离线,暂时无法发送'}
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
@@ -210,6 +233,25 @@ const Chat: React.FC = () => {
</main>
</div>
)}
{pendingImage && <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-4" onClick={/* 当前回调点击遮罩取消图片预览。 */ closeImagePreview}>
<div className="flex max-h-full w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl" onClick={/* 当前回调阻止预览内容点击冒泡到遮罩。 */ event => event.stopPropagation()}>
<div className="flex shrink-0 items-center justify-between border-b border-slate-200 px-5 py-3">
<div className="text-sm font-black text-slate-900">发送图片预览</div>
<button type="button" title="取消" onClick={/* 当前回调关闭图片预览。 */ closeImagePreview} className="rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700"><X className="h-5 w-5" /></button>
</div>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-slate-100 p-4"><img src={pendingImage.url} alt="待发送图片预览" className="max-h-[55vh] max-w-full rounded-xl object-contain" /></div>
<div className="flex shrink-0 items-center justify-between gap-3 border-t border-slate-200 px-5 py-3">
<div className="min-w-0 truncate text-xs text-slate-500">{pendingImage.file.name || '粘贴的图片'} · {(pendingImage.file.size / 1024).toFixed(0)} KB</div>
<div className="flex shrink-0 items-center gap-2">
<button type="button" onClick={/* 当前回调取消图片发送。 */ closeImagePreview} className="rounded-xl px-4 py-2 text-sm font-bold text-slate-600 transition hover:bg-slate-100">取消</button>
<button type="button" onClick={/* 当前回调确认发送预览图片。 */ () => void confirmSendImage()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="flex items-center gap-2 rounded-xl bg-sky-500 px-4 py-2 text-sm font-bold text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:opacity-50">{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}发送</button>
</div>
</div>
</div>
</div>}
<Lightbox open={lightboxIndex >= 0} index={Math.max(lightboxIndex, 0)} close={/* 当前回调关闭图片灯箱。 */ () => setLightboxIndex(-1)} slides={imageSlides} />
</section>
);
};