feat(聊天): 增加全局未读消息提示
This commit is contained in:
1 parent
3c46dd910b
commit
9da450d940
28 files changed
+581
-142
No files matched your search
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { useChat } from './hooks';
|
||||
import { publishChatConnectionState, publishChatLiveMessage } from './liveEvents';
|
||||
|
||||
vi.mock('./api', /* chatApiMockFactory 提供聊天 Hook 的确定性 API 替身。 */ () => ({
|
||||
getAccountDetails: vi.fn(),
|
||||
@@ -39,22 +40,8 @@ const messageFixture = { id: 1, account_id: 'account-1', chat_id: 'chat-1', mess
|
||||
// sentMessageFixture 是文字发送成功后返回的消息。
|
||||
const sentMessageFixture = { ...messageFixture, id: 2, message_key: 'message-2', direction: 'outgoing', content: '回复内容' } as ChatMessage;
|
||||
|
||||
// latestSocket 保存当前测试创建的 WebSocket 替身。
|
||||
let latestSocket: {
|
||||
// close 是关闭 WebSocket 的替身方法。
|
||||
close: ReturnType<typeof vi.fn>;
|
||||
// onopen 是 WebSocket 建立连接回调。
|
||||
onopen: (() => void) | null;
|
||||
// onmessage 是 WebSocket 消息回调。
|
||||
onmessage: ((event: { /* data 是 WebSocket 事件数据。 */ data: string }) => void) | null;
|
||||
// onclose 是 WebSocket 断开回调。
|
||||
onclose: (() => void) | null;
|
||||
// onerror 是 WebSocket 错误回调。
|
||||
onerror: (() => void) | null;
|
||||
} | null = null;
|
||||
|
||||
describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时连接状态。 */ () => {
|
||||
beforeEach(/* 当前回调重置聊天 API 替身和 WebSocket。 */ () => {
|
||||
beforeEach(/* 当前回调重置聊天 API 替身和全局实时连接状态。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
getDetailsMock.mockResolvedValue([accountFixture]);
|
||||
getRuntimeMock.mockResolvedValue({ 'account-1': { state: 'online', connected: true, failures: 0, updated_at: '2026-08-15T00:00:00Z' } });
|
||||
@@ -63,17 +50,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
markReadMock.mockResolvedValue({ success: true });
|
||||
sendMessageMock.mockResolvedValue({ message: sentMessageFixture });
|
||||
sendImageMock.mockResolvedValue({ message: sentMessageFixture });
|
||||
// websocketFactory 是不连接真实服务器的 WebSocket 构造替身。
|
||||
const websocketFactory = vi.fn(
|
||||
// websocketConstructor 创建不连接真实服务器的 WebSocket 实例。
|
||||
function websocketConstructor() {
|
||||
// socket 是当前 WebSocket 连接的可控替身。
|
||||
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
|
||||
latestSocket = socket;
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
vi.stubGlobal('WebSocket', websocketFactory);
|
||||
publishChatConnectionState('connecting');
|
||||
// localStorageStub 是聊天 Hook 记忆账号选择所需的浏览器存储替身。
|
||||
Object.defineProperty(window, 'localStorage', { configurable: true, value: { getItem: vi.fn().mockReturnValue(''), setItem: vi.fn(), removeItem: vi.fn() } });
|
||||
// createObjectURLMock 和 revokeObjectURLMock 模拟浏览器图片预览地址的创建与释放。
|
||||
@@ -230,7 +207,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => {
|
||||
test('应用壳唯一实时连接发布的状态和消息会更新聊天状态', /* 当前回调验证 Chat 页面不再自行创建 WebSocket。 */ async () => {
|
||||
// secondSession 是用于覆盖实时会话排序比较器的第二条会话。
|
||||
const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 };
|
||||
getSessionPageMock.mockResolvedValue({ sessions: [sessionFixture, secondSession], has_more: true, next_cursor: 2 });
|
||||
@@ -250,17 +227,16 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
// activeChatAssertion 等待实时消息目标会话选中。
|
||||
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
|
||||
);
|
||||
expect(latestSocket).not.toBeNull();
|
||||
await act(
|
||||
// openAction 触发 WebSocket 建立连接事件。
|
||||
() => latestSocket?.onopen?.(),
|
||||
// onlineAction 触发应用壳全局连接建立成功事件。
|
||||
() => publishChatConnectionState('online'),
|
||||
);
|
||||
expect(hook.result.current.liveState).toBe('online');
|
||||
// incomingMessage 是实时 WebSocket 推送的入站消息。
|
||||
const incomingMessage = { ...messageFixture, id: 3, message_key: 'message-3', sent_at: 3, content: '实时消息' };
|
||||
await act(
|
||||
// messageAction 触发合法的实时消息事件。
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessage }) }),
|
||||
// messageAction 触发应用壳发布的合法实时消息事件。
|
||||
() => publishChatLiveMessage(incomingMessage),
|
||||
);
|
||||
expect(hook.result.current.messages).toContainEqual(incomingMessage);
|
||||
expect(hook.result.current.messages.find(/* 当前回调定位需要验证已读状态的出站消息。 */ message => message.message_key === 'outgoing-1')).toMatchObject({ read_status: 2, read_at: 3 });
|
||||
@@ -268,12 +244,8 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
{ messageId: 'message-3', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
|
||||
]);
|
||||
await act(
|
||||
// invalidMessageAction 触发非法消息帧并保持状态稳定。
|
||||
() => latestSocket?.onmessage?.({ data: '{broken' }),
|
||||
);
|
||||
await act(
|
||||
// closeAction 触发 WebSocket 断开事件。
|
||||
() => latestSocket?.onclose?.(),
|
||||
// closeAction 触发应用壳全局连接断开事件。
|
||||
() => publishChatConnectionState('offline'),
|
||||
);
|
||||
expect(hook.result.current.liveState).toBe('offline');
|
||||
hook.unmount();
|
||||
@@ -516,7 +488,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
getSessionPageMock.mockResolvedValueOnce({ sessions: [unknownSession, sessionFixture], has_more: false, next_cursor: undefined });
|
||||
await act(
|
||||
// unknownMessageAction 触发未知会话的联系人刷新。
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: unknownMessage }) }),
|
||||
() => publishChatLiveMessage(unknownMessage),
|
||||
);
|
||||
await waitFor(
|
||||
// reloadAssertion 等待未知会话触发联系人刷新。
|
||||
@@ -527,14 +499,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
() => expect(hook.result.current.activeSessions).toContainEqual(unknownSession),
|
||||
);
|
||||
await act(
|
||||
// emptyMessageAction 触发无消息载荷并保持状态稳定。
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({}) }),
|
||||
// offlineAction 触发全局连接断开状态并保持消息列表稳定。
|
||||
() => publishChatConnectionState('offline'),
|
||||
);
|
||||
await act(
|
||||
// errorAction 触发 WebSocket 错误并关闭连接。
|
||||
() => latestSocket?.onerror?.(),
|
||||
);
|
||||
expect(latestSocket?.close).toHaveBeenCalled();
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type React from 'react';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { publishChatUnreadStatus, subscribeToChatLiveEvents } from './liveEvents';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
|
||||
|
||||
@@ -272,6 +273,15 @@ export const useChat = (): UseChatResult => {
|
||||
setActiveChatID(/* 当前回调处理集合中的单个元素。 */ current => sessions.some(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
|
||||
}, [activeAccountID, sessionsByAccount]);
|
||||
|
||||
useEffect(/* 当前副作用将所有已加载账号会话的未读聚合状态回传给应用壳,红点只能在没有任何未读时消失。 */ () => {
|
||||
// loadedAccountCount 保存已成功写入会话列表状态的账号数量;初始请求尚未完成或失败时不得错误发布无未读。
|
||||
const loadedAccountCount = Object.keys(sessionsByAccount).length;
|
||||
if (loading || (accounts.length > 0 && loadedAccountCount === 0)) return;
|
||||
// hasUnreadChatMessage 保存当前所有已加载会话是否至少存在一条未读消息。
|
||||
const hasUnreadChatMessage = Object.values(sessionsByAccount).some(/* sessions 保存当前账号的会话列表。 */ sessions => sessions.some(/* session 保存当前参与未读聚合判断的会话。 */ session => session.unread_count > 0));
|
||||
publishChatUnreadStatus(hasUnreadChatMessage);
|
||||
}, [accounts.length, loading, sessionsByAccount]);
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
|
||||
refreshedAccountsRef.current.add(activeAccountID);
|
||||
@@ -392,77 +402,48 @@ export const useChat = (): UseChatResult => {
|
||||
}
|
||||
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
// disposed disposed,负责当前功能中的对应处理。
|
||||
let disposed = false;
|
||||
// reconnectTimer reconnect定时器,负责当前功能中的对应处理。
|
||||
let reconnectTimer = 0;
|
||||
// retry 重试当前操作。
|
||||
let retry = 0;
|
||||
// socket WebSocket 连接。
|
||||
let socket: WebSocket | null = null;
|
||||
// connect 连接。
|
||||
const connect = (): void => {
|
||||
if (disposed) return;
|
||||
setLiveState('connecting');
|
||||
// protocol 连接协议。
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
|
||||
socket.onopen = /* 当前回调处理用户交互或异步状态变化。 */ () => { retry = 0; setLiveState('online'); };
|
||||
socket.onmessage = /* 当前回调处理用户交互或异步状态变化。 */ event => {
|
||||
try {
|
||||
// payload 请求载荷。
|
||||
const payload = JSON.parse(event.data);
|
||||
// message 消息。
|
||||
const message = payload.message as ChatMessage | undefined;
|
||||
if (!message) return;
|
||||
// accountID 账号标识。
|
||||
const accountID = message.account_id;
|
||||
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => {
|
||||
// rows 行数据。
|
||||
const rows = current[accountID] || [];
|
||||
// found 匹配结果。
|
||||
const found = rows.some(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id);
|
||||
if (!found) {
|
||||
void reloadSessions(accountID);
|
||||
return current;
|
||||
}
|
||||
return { ...current, [accountID]: rows.map(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id ? {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
|
||||
} : row).sort(/* 当前回调处理集合中的单个元素。 */ (a, b) => b.last_message_at - a.last_message_at) };
|
||||
});
|
||||
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
|
||||
setMessages(/* 当前回调合并实时消息并同步后续入站消息确认的出站已读状态。 */ current => markOutgoingMessagesReadByIncoming(mergeLiveMessage(current, message), message));
|
||||
if (message.direction === 'incoming' && message.message_type !== 'system') {
|
||||
// readReceipts 为当前实时消息生成平台要求的会话读取回执。
|
||||
const readReceipts = collectChatReadReceipts([message], message.chat_id);
|
||||
void markChatRead(accountID, message.chat_id, readReceipts);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。
|
||||
}
|
||||
};
|
||||
socket.onclose = /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
if (disposed) return;
|
||||
setLiveState('offline');
|
||||
// delay 延迟。
|
||||
const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4));
|
||||
reconnectTimer = window.setTimeout(connect, delay);
|
||||
};
|
||||
socket.onerror = /* 当前回调处理用户交互或异步状态变化。 */ () => socket?.close();
|
||||
};
|
||||
connect();
|
||||
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
disposed = true;
|
||||
window.clearTimeout(reconnectTimer);
|
||||
socket?.close();
|
||||
};
|
||||
/** handleLiveMessage 将应用壳唯一连接发布的消息同步到当前聊天页的会话、消息和已读状态。 */
|
||||
const handleLiveMessage = useCallback(/* 当前回调只处理类型化聊天消息,不解析原始 WebSocket 帧。 */ (message: ChatMessage): void => {
|
||||
// accountID 保存当前实时消息所属账号,用于隔离不同闲鱼账号的会话状态。
|
||||
const accountID = message.account_id;
|
||||
setSessionsByAccount(/* 当前回调在对应账号会话列表中合并最新消息与未读计数。 */ current => {
|
||||
// rows 保存当前账号已有的会话行。
|
||||
const rows = current[accountID] || [];
|
||||
// found 表示推送消息是否能匹配当前已加载会话;缺失时异步刷新该账号会话。
|
||||
const found = rows.some(/* row 保存当前参与会话匹配的联系人行。 */ row => row.chat_id === message.chat_id);
|
||||
if (!found) {
|
||||
void reloadSessions(accountID);
|
||||
return current;
|
||||
}
|
||||
return { ...current, [accountID]: rows.map(/* row 保存当前待合并实时消息的联系人行。 */ row => row.chat_id === message.chat_id ? {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
|
||||
} : row).sort(/* a、b 保存参与时间倒序比较的两条会话行。 */ (a, b) => b.last_message_at - a.last_message_at) };
|
||||
});
|
||||
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
|
||||
setMessages(/* 当前回调合并实时消息并同步后续入站消息确认的出站已读状态。 */ current => markOutgoingMessagesReadByIncoming(mergeLiveMessage(current, message), message));
|
||||
if (message.direction === 'incoming' && message.message_type !== 'system') {
|
||||
// readReceipts 为当前实时消息生成平台要求的会话读取回执。
|
||||
const readReceipts = collectChatReadReceipts([message], message.chat_id);
|
||||
void markChatRead(accountID, message.chat_id, readReceipts);
|
||||
}
|
||||
}
|
||||
}, [reloadSessions]);
|
||||
|
||||
useEffect(/* 当前副作用订阅认证应用壳唯一连接发布的事件,聊天页卸载时取消订阅而不关闭全局连接。 */ () => {
|
||||
/** handleLiveEvent 根据事件类型分别同步连接状态或消息内容。 */
|
||||
const handleLiveEvent = (event: Parameters<Parameters<typeof subscribeToChatLiveEvents>[0]>[0]): void => {
|
||||
if (event.type === 'connection') {
|
||||
setLiveState(event.state);
|
||||
return;
|
||||
}
|
||||
handleLiveMessage(event.message);
|
||||
};
|
||||
return subscribeToChatLiveEvents(handleLiveEvent);
|
||||
}, [handleLiveMessage]);
|
||||
|
||||
/** 根据滚动位置决定新消息是否自动滚到底部。 */
|
||||
const handleMessageScroll = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
|
||||
// container 容器。
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import type { ChatLiveState } from './types';
|
||||
|
||||
/** ChatLiveEvent 描述全局聊天连接向已挂载聊天页面发布的最小实时事件集合。 */
|
||||
export type ChatLiveEvent =
|
||||
| { /** type 标识事件为连接状态变更。 */ type: 'connection'; /** state 保存连接的最新可展示状态。 */ state: ChatLiveState }
|
||||
| { /** type 标识事件为一条实时聊天消息。 */ type: 'message'; /** message 保存已通过服务端权限过滤的非敏感聊天消息。 */ message: ChatMessage };
|
||||
|
||||
/** ChatLiveEventListener 描述聊天页订阅全局连接事件时提供的接收回调。 */
|
||||
export type ChatLiveEventListener = (event: ChatLiveEvent) => void;
|
||||
|
||||
// listeners 保存当前已挂载聊天页面的事件订阅者;应用壳 WebSocket 是唯一发布者,订阅者自行注销。
|
||||
const listeners = new Set<ChatLiveEventListener>();
|
||||
// currentConnectionState 保存最近一次全局聊天连接状态,使晚进入聊天页能立即渲染准确状态。
|
||||
let currentConnectionState: ChatLiveState = 'connecting';
|
||||
// unreadStatusListeners 保存全局通知 owner 的未读状态监听者;Chat 页面是唯一汇总并发布未读状态的消费者。
|
||||
const unreadStatusListeners = new Set<(hasUnreadChatMessage: boolean) => void>();
|
||||
|
||||
/** subscribeToChatLiveEvents 注册聊天页实时事件监听,并立即回放当前连接状态,返回取消订阅函数。 */
|
||||
export const subscribeToChatLiveEvents = (/** listener 保存当前聊天页接收全局实时事件的回调。 */ listener: ChatLiveEventListener): (() => void) => {
|
||||
listener({ type: 'connection', state: currentConnectionState });
|
||||
listeners.add(listener);
|
||||
return /* 当前清理函数在聊天页卸载时移除订阅,避免保留失效 React 状态写入。 */ () => listeners.delete(listener);
|
||||
};
|
||||
|
||||
/** publishChatConnectionState 由认证应用壳唯一 WebSocket 所有者发布连接状态给当前聊天页。 */
|
||||
export const publishChatConnectionState = (state: ChatLiveState): void => {
|
||||
currentConnectionState = state;
|
||||
// listener 保存当前遍历到的聊天页面订阅回调。
|
||||
for (const listener /* listener 保存当前遍历到的聊天页面订阅回调。 */ of listeners) listener({ type: 'connection', state });
|
||||
};
|
||||
|
||||
/** publishChatLiveMessage 由认证应用壳唯一 WebSocket 所有者发布一条服务端聊天消息给当前聊天页。 */
|
||||
export const publishChatLiveMessage = (message: ChatMessage): void => {
|
||||
// listener 保存当前遍历到的聊天页面订阅回调。
|
||||
for (const listener /* listener 保存当前遍历到的聊天页面订阅回调。 */ of listeners) listener({ type: 'message', message });
|
||||
};
|
||||
|
||||
/** subscribeToChatUnreadStatus 注册全局未读状态监听,返回由通知 owner 卸载时调用的取消订阅函数。 */
|
||||
export const subscribeToChatUnreadStatus = (/** listener 保存接收全部聊天会话未读聚合结果的回调。 */ listener: (hasUnreadChatMessage: boolean) => void): (() => void) => {
|
||||
unreadStatusListeners.add(listener);
|
||||
return /* 当前清理函数在应用壳卸载时释放未读状态监听,避免保留失效状态 setter。 */ () => unreadStatusListeners.delete(listener);
|
||||
};
|
||||
|
||||
/** publishChatUnreadStatus 由 Chat 页面按所有已加载会话的 unread_count 聚合结果更新侧边栏红点。 */
|
||||
export const publishChatUnreadStatus = (hasUnreadChatMessage: boolean): void => {
|
||||
// listener 保存当前遍历到的未读状态监听回调。
|
||||
for (const listener /* listener 保存当前遍历到的未读状态监听回调。 */ of unreadStatusListeners) listener(hasUnreadChatMessage);
|
||||
};
|
||||
@@ -0,0 +1,205 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getChatSessionPage } from './api';
|
||||
import { publishChatUnreadStatus } from './liveEvents';
|
||||
import { formatChatNewMessageTitle, useChatTitleNotification, useChatTitleNotifier } from './titleNotification';
|
||||
|
||||
vi.mock('./api', /* chatApiMockFactory 提供标题通知初始化未读状态读取的确定性 API 替身。 */ () => ({
|
||||
getAccountDetails: vi.fn(),
|
||||
getChatSessionPage: vi.fn(),
|
||||
}));
|
||||
|
||||
// getAccountDetailsMock 是标题通知初始化账号读取的可控替身。
|
||||
const getAccountDetailsMock = vi.mocked(getAccountDetails);
|
||||
// getChatSessionPageMock 是标题通知初始化会话未读读取的可控替身。
|
||||
const getChatSessionPageMock = vi.mocked(getChatSessionPage);
|
||||
|
||||
// originalTitle 保存每个测试开始前的浏览器标题,测试结束后必须恢复以避免影响其他聊天 Hook 用例。
|
||||
let originalTitle = '';
|
||||
|
||||
// incomingMessageFixture 是触发标题提醒的普通买家入站消息。
|
||||
const incomingMessageFixture = { direction: 'incoming', message_type: 'text' } as ChatMessage;
|
||||
|
||||
// latestSocket 保存全局标题通知 Hook 创建的可控 WebSocket 替身。
|
||||
let latestSocket: {
|
||||
// close 是关闭通知连接的替身方法。
|
||||
close: ReturnType<typeof vi.fn>;
|
||||
// onopen 是通知连接建立成功回调。
|
||||
onopen: (() => void) | null;
|
||||
// onmessage 是服务端广播聊天帧的回调。
|
||||
onmessage: ((event: { /* data 保存服务端推送的 JSON 文本。 */ data: string }) => void) | null;
|
||||
// onclose 是通知连接关闭回调。
|
||||
onclose: (() => void) | null;
|
||||
// onerror 是通知连接异常回调。
|
||||
onerror: (() => void) | null;
|
||||
} | null = null;
|
||||
|
||||
describe('chat title notification', /* 当前测试组验证后台实时消息的浏览器标题提示行为。 */ () => {
|
||||
beforeEach(/* 当前回调重置标题和时间,隔离浏览器全局状态。 */ () => {
|
||||
originalTitle = document.title;
|
||||
document.title = 'Ydisks闲鱼助手';
|
||||
vi.useFakeTimers();
|
||||
latestSocket = null;
|
||||
getAccountDetailsMock.mockResolvedValue([]);
|
||||
getChatSessionPageMock.mockResolvedValue({ sessions: [], has_more: false });
|
||||
});
|
||||
|
||||
afterEach(/* 当前回调恢复真实计时器、标题和浏览器焦点方法,避免泄漏到其他前端测试。 */ () => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
document.title = originalTitle;
|
||||
});
|
||||
|
||||
test('格式化标题不会暴露新消息数量', /* 当前回调验证标题只展示固定的新消息标记。 */ () => {
|
||||
expect(formatChatNewMessageTitle('应用')).toBe('【新消息】应用');
|
||||
});
|
||||
|
||||
test('新消息会累计闪烁标题并在重新聚焦后恢复', /* 当前回调验证前后台一致的实时计数、闪烁周期与用户确认后的清除行为。 */ () => {
|
||||
// hook 是标题通知 Hook 的渲染结果。
|
||||
const hook = renderHook(
|
||||
// titleNotificationHookFactory 创建浏览器标题通知 Hook。
|
||||
() => useChatTitleNotifier(),
|
||||
);
|
||||
act(
|
||||
// firstMessageAction 模拟第一条实时消息。
|
||||
() => hook.result.current.notifyIncomingMessage(incomingMessageFixture),
|
||||
);
|
||||
act(
|
||||
// secondMessageAction 模拟同一提醒周期收到第二条消息。
|
||||
() => hook.result.current.notifyIncomingMessage(incomingMessageFixture),
|
||||
);
|
||||
expect(document.title).toBe('【新消息】Ydisks闲鱼助手');
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
|
||||
act(
|
||||
// flashAction 推进一个闪烁周期以展示原始标题相位。
|
||||
() => vi.advanceTimersByTime(1_000),
|
||||
);
|
||||
expect(document.title).toBe('Ydisks闲鱼助手');
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
|
||||
act(
|
||||
// unreadClearedAction 模拟聊天页确认所有会话均无未读消息。
|
||||
() => publishChatUnreadStatus(false),
|
||||
);
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(false);
|
||||
act(
|
||||
// focusAction 模拟用户重新聚焦浏览器窗口,确认已看到提醒。
|
||||
() => window.dispatchEvent(new Event('focus')),
|
||||
);
|
||||
expect(document.title).toBe('Ydisks闲鱼助手');
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('系统消息和本机发出的消息不会改写浏览器标题', /* 当前回调验证不属于买家新消息的事件不会触发标题提醒。 */ () => {
|
||||
// hook 是消息方向过滤场景的标题通知 Hook 渲染结果。
|
||||
const hook = renderHook(
|
||||
// messageDirectionHookFactory 创建消息方向过滤场景。
|
||||
() => useChatTitleNotifier(),
|
||||
);
|
||||
act(
|
||||
// outgoingMessageAction 模拟本机发送的消息。
|
||||
() => hook.result.current.notifyIncomingMessage({ ...incomingMessageFixture, direction: 'outgoing' }),
|
||||
);
|
||||
act(
|
||||
// systemMessageAction 模拟后台收到不应通知用户的系统消息。
|
||||
() => hook.result.current.notifyIncomingMessage({ ...incomingMessageFixture, message_type: 'system' }),
|
||||
);
|
||||
expect(document.title).toBe('Ydisks闲鱼助手');
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('认证应用壳挂载的通知连接会接收在线聊天页之外的消息', /* 当前回调验证标题提醒的 WebSocket 不依赖 Chat 页面是否已打开。 */ () => {
|
||||
// websocketFactory 创建不连接真实服务的全局通知连接替身。
|
||||
const websocketFactory = vi.fn(
|
||||
// websocketConstructor 创建可手动触发服务端消息的连接对象。
|
||||
function websocketConstructor() {
|
||||
// socket 是当前全局通知连接的可控替身。
|
||||
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
|
||||
latestSocket = socket;
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
vi.stubGlobal('WebSocket', websocketFactory);
|
||||
// hook 是认证应用壳中全局标题通知连接的渲染结果。
|
||||
const hook = renderHook(
|
||||
// globalNotificationHookFactory 挂载不依赖 Chat 页面存在的全局通知 Hook。
|
||||
() => useChatTitleNotification(),
|
||||
);
|
||||
expect(websocketFactory).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/chat\/ws$/));
|
||||
act(
|
||||
// incomingMessageAction 模拟用户停留在仪表盘等其他页面时服务端推送买家消息。
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessageFixture }) }),
|
||||
);
|
||||
expect(document.title).toBe('【新消息】Ydisks闲鱼助手');
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
|
||||
hook.unmount();
|
||||
expect(latestSocket?.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('应用壳启动时会根据已有未读会话点亮聊天红点', /* 当前回调验证红点不只依赖当前浏览器会话期间的新 WebSocket 消息。 */ async () => {
|
||||
// unreadSession 保存服务端返回的一条历史未读会话。
|
||||
const unreadSession = { account_id: 'account-1', chat_id: 'chat-1', buyer_id: 'buyer-1', buyer_name: '买家', last_message: '历史未读消息', last_message_at: 1, unread_count: 1 };
|
||||
getAccountDetailsMock.mockResolvedValue([{ id: 'account-1', enabled: true }] as never);
|
||||
getChatSessionPageMock.mockResolvedValue({ sessions: [unreadSession], has_more: false });
|
||||
// websocketFactory 创建不会连接真实服务的全局通知连接替身。
|
||||
const websocketFactory = vi.fn(
|
||||
// websocketConstructor 创建初始化未读读取测试所需的通知连接对象。
|
||||
function websocketConstructor() {
|
||||
// socket 是当前测试创建的通知连接替身。
|
||||
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
|
||||
latestSocket = socket;
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
vi.stubGlobal('WebSocket', websocketFactory);
|
||||
// hook 是应用壳初始化阶段的全局标题通知 Hook。
|
||||
const hook = renderHook(
|
||||
// initialUnreadHookFactory 创建验证历史未读状态的通知 Hook。
|
||||
() => useChatTitleNotification(),
|
||||
);
|
||||
await act(
|
||||
// initialUnreadFlushAction 显式刷新初始化账号和会话读取 Promise,避免假定时器阻塞 waitFor 轮询。
|
||||
async () => { await Promise.resolve(); await Promise.resolve(); },
|
||||
);
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
|
||||
expect(getChatSessionPageMock).toHaveBeenCalledWith('account-1', undefined, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('延迟的初始未读快照不会覆盖期间收到的实时消息', /* 当前回调验证初始查询与 WebSocket 入站消息的先后竞态。 */ async () => {
|
||||
// resolveAccounts 用于在实时消息到达后才完成初始账号快照请求。
|
||||
let resolveAccounts: ((accounts: never[]) => void) | undefined;
|
||||
getAccountDetailsMock.mockImplementationOnce(
|
||||
// delayedAccountsRequest 维持初始账号读取未完成,模拟网络慢响应。
|
||||
() => new Promise<never[]>(/* delayedAccountsExecutor 保存延迟账号快照的完成函数。 */ resolve => { resolveAccounts = resolve; }),
|
||||
);
|
||||
// websocketFactory 创建可在初始快照未完成时接收消息的全局通知连接替身。
|
||||
const websocketFactory = vi.fn(
|
||||
// websocketConstructor 创建实时竞态测试所需的通知连接对象。
|
||||
function websocketConstructor() {
|
||||
// socket 是当前测试创建的通知连接替身。
|
||||
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
|
||||
latestSocket = socket;
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
vi.stubGlobal('WebSocket', websocketFactory);
|
||||
// hook 是初始未读快照仍在加载时的全局标题通知 Hook。
|
||||
const hook = renderHook(
|
||||
// delayedSnapshotHookFactory 创建初始快照与实时消息竞态场景。
|
||||
() => useChatTitleNotification(),
|
||||
);
|
||||
act(
|
||||
// realtimeMessageAction 模拟慢快照期间先收到一条买家消息。
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessageFixture }) }),
|
||||
);
|
||||
await act(
|
||||
// staleSnapshotAction 在收到实时消息后才让旧快照返回无账号、无未读结果。
|
||||
async () => { resolveAccounts?.([]); await Promise.resolve(); },
|
||||
);
|
||||
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getChatSessionPage } from './api';
|
||||
import { publishChatConnectionState, publishChatLiveMessage, subscribeToChatUnreadStatus } from './liveEvents';
|
||||
|
||||
/** titleFlashIntervalMs 定义浏览器标题在提示文本与原始标题间切换的周期,单位为毫秒。 */
|
||||
const titleFlashIntervalMs = 1_000;
|
||||
|
||||
/** formatChatNewMessageTitle 根据原始标题生成不暴露消息数量的浏览器新消息提示文本。 */
|
||||
export const formatChatNewMessageTitle = (baseTitle: string): string => {
|
||||
return `【新消息】${baseTitle}`;
|
||||
};
|
||||
|
||||
/** ChatTitleNotifierResult 描述标题闪烁与侧边栏新消息标记的受控状态。 */
|
||||
export type ChatTitleNotifierResult = {
|
||||
/** notifyIncomingMessage 接收实时消息并决定是否产生标题和红点提醒。 */
|
||||
notifyIncomingMessage: (message: ChatMessage) => void;
|
||||
/** hasUnreadChatMessage 表示所有已知聊天会话中是否仍存在未读普通消息。 */
|
||||
hasUnreadChatMessage: boolean;
|
||||
};
|
||||
|
||||
/** useChatTitleNotifier 管理浏览器标题闪烁,并返回由实时消息连接调用的通知入口。 */
|
||||
export const useChatTitleNotifier = (): ChatTitleNotifierResult => {
|
||||
// newMessageCount 保存当前应用会话收到、尚未被浏览器重新聚焦确认的入站消息数量。
|
||||
const [newMessageCount, setNewMessageCount] = useState(0);
|
||||
// hasUnreadChatMessage 保存在线聊天入口的持久红点状态;只有所有会话未读数归零时才清除。
|
||||
const [hasUnreadChatMessage, setHasUnreadChatMessage] = useState(false);
|
||||
// baseTitleRef 保存挂载通知服务前的标题;本 Hook 卸载时必须恢复该标题,不覆盖其他页面的标题策略。
|
||||
const baseTitleRef = useRef(document.title);
|
||||
// realtimeUnreadVersionRef 记录初始未读快照开始后收到的实时消息次数,阻止旧快照覆盖新消息提醒。
|
||||
const realtimeUnreadVersionRef = useRef(0);
|
||||
|
||||
useEffect(/* 当前副作用在用户回到页面时清除标题提示,并在卸载时移除全局监听。 */ () => {
|
||||
/** clearTitleNotification 在用户重新看到聊天页面后确认所有临时标题提醒。 */
|
||||
const clearTitleNotification = (): void => setNewMessageCount(0);
|
||||
/** handleVisibilityChange 只在页面重新可见时清除提醒,后台切换不影响未读计数。 */
|
||||
const handleVisibilityChange = (): void => {
|
||||
if (document.visibilityState === 'visible') clearTitleNotification();
|
||||
};
|
||||
window.addEventListener('focus', clearTitleNotification);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return /* 当前清理函数释放浏览器事件监听,避免注销后仍修改标题状态。 */ () => {
|
||||
window.removeEventListener('focus', clearTitleNotification);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(/* 当前副作用将未确认消息数同步到浏览器标题,并负责闪烁定时器的创建和销毁。 */ () => {
|
||||
if (newMessageCount <= 0) {
|
||||
document.title = baseTitleRef.current;
|
||||
return;
|
||||
}
|
||||
// showNotificationTitle 表示本次闪烁周期是否展示带计数的提醒标题。
|
||||
let showNotificationTitle = true;
|
||||
/** updateTitle 将当前闪烁相位写入浏览器标签标题。 */
|
||||
const updateTitle = (): void => {
|
||||
document.title = showNotificationTitle
|
||||
? formatChatNewMessageTitle(baseTitleRef.current)
|
||||
: baseTitleRef.current;
|
||||
};
|
||||
updateTitle();
|
||||
// flashTimer 由此 effect 独占;计数变化或 Hook 卸载时必须清除,避免后台残留定时器。
|
||||
const flashTimer = window.setInterval(/* 当前回调切换标题相位以形成新消息闪烁提示。 */ () => {
|
||||
showNotificationTitle = !showNotificationTitle;
|
||||
updateTitle();
|
||||
}, titleFlashIntervalMs);
|
||||
return /* 当前清理函数停止旧计数对应的定时器,并将标题恢复为进入聊天页前的值。 */ () => {
|
||||
window.clearInterval(flashTimer);
|
||||
document.title = baseTitleRef.current;
|
||||
};
|
||||
}, [newMessageCount]);
|
||||
|
||||
useEffect(/* 当前副作用在认证应用壳启动时读取各启用账号的会话未读状态,取消后不写入页面状态。 */ () => {
|
||||
// controller 取消应用壳卸载后尚未完成的账号和会话读取请求。
|
||||
const controller = new AbortController();
|
||||
// snapshotVersion 保存本次未读快照启动时的实时消息版本,响应只有版本未变化时才可写入红点状态。
|
||||
const snapshotVersion = realtimeUnreadVersionRef.current;
|
||||
/** loadUnreadStatus 并行读取启用账号的会话首页,以服务端 unread_count 初始化侧边栏红点。 */
|
||||
const loadUnreadStatus = async (): Promise<void> => {
|
||||
try {
|
||||
// accounts 保存当前用户可见的账号摘要,敏感凭证不会进入前端状态。
|
||||
const accounts = await getAccountDetails({ signal: controller.signal });
|
||||
// enabledAccounts 保存需要查询会话未读数的启用账号。
|
||||
const enabledAccounts = accounts.filter(/* account 保存当前判断启用状态的账号摘要。 */ account => account.enabled);
|
||||
// pages 保存各启用账号并行读取的会话首页结果。
|
||||
const pages = await Promise.all(enabledAccounts.map(/* account 保存当前需要读取会话首页的启用账号。 */ account => getChatSessionPage(account.id, undefined, { signal: controller.signal })));
|
||||
if (controller.signal.aborted || realtimeUnreadVersionRef.current !== snapshotVersion) return;
|
||||
// hasUnread 保存所有账号会话中是否仍有服务端标记的未读消息。
|
||||
const hasUnread = pages.some(/* page 保存当前账号会话首页,用于检查其未读计数。 */ page => page.sessions.some(/* session 保存当前参与未读判断的会话。 */ session => session.unread_count > 0));
|
||||
setHasUnreadChatMessage(hasUnread);
|
||||
} catch {
|
||||
// 初始未读读取失败时保留实时消息已点亮的红点,避免网络暂态错误错误清除提醒。
|
||||
}
|
||||
};
|
||||
void loadUnreadStatus();
|
||||
return /* 当前清理函数取消初始未读读取,避免注销后响应覆盖新会话状态。 */ () => controller.abort();
|
||||
}, []);
|
||||
|
||||
useEffect(/* 当前副作用接收 Chat 页面已读确认后的会话未读聚合状态,只有为 false 才清除红点。 */ () => subscribeToChatUnreadStatus(setHasUnreadChatMessage), []);
|
||||
|
||||
/** notifyIncomingMessage 在收到普通入站消息时累加标题提示并标记全局仍有未读聊天消息。 */
|
||||
const notifyIncomingMessage = useCallback(/* 当前回调由实时 WebSocket 消息入口调用,使用户在当前浏览器窗口也能看见标题变化。 */ (message: ChatMessage): void => {
|
||||
if (message.direction !== 'incoming' || message.message_type === 'system') return;
|
||||
realtimeUnreadVersionRef.current += 1;
|
||||
setNewMessageCount(/* 当前状态更新基于上一条实时消息计数累计,避免同一批 WebSocket 帧丢失数量。 */ current => current + 1);
|
||||
setHasUnreadChatMessage(true);
|
||||
}, []);
|
||||
|
||||
return { notifyIncomingMessage, hasUnreadChatMessage };
|
||||
};
|
||||
|
||||
/** ChatTitleNotificationResult 描述应用壳向侧边栏提供的聊天新消息标记控制。 */
|
||||
export type ChatTitleNotificationResult = Pick<ChatTitleNotifierResult, 'hasUnreadChatMessage'>;
|
||||
|
||||
/** useChatTitleNotification 在认证应用壳内维持全局聊天 WebSocket,并把普通入站消息转为标题提醒。 */
|
||||
export const useChatTitleNotification = (): ChatTitleNotificationResult => {
|
||||
// titleNotifier 保存标题和侧边栏红点状态;其消息处理函数保持稳定,重连 effect 不会因计数更新而重建 WebSocket。
|
||||
const titleNotifier = useChatTitleNotifier();
|
||||
// notifyIncomingMessage 保存标题提醒的稳定入口;hasUnreadChatMessage 保存侧边栏红点应展示的全局未读状态。
|
||||
const { notifyIncomingMessage, hasUnreadChatMessage } = titleNotifier;
|
||||
|
||||
useEffect(/* 当前副作用拥有全局通知 WebSocket 的连接、退避重连和卸载清理生命周期。 */ () => {
|
||||
// disposed 标记应用壳是否已经卸载;卸载后禁止关闭回调重新创建连接。
|
||||
let disposed = false;
|
||||
// reconnectTimer 保存当前退避重连定时器;仅此 effect 可以清理它。
|
||||
let reconnectTimer = 0;
|
||||
// retryCount 保存连续断开次数,用于限制退避延迟的最大值。
|
||||
let retryCount = 0;
|
||||
// socket 保存本轮通知连接;卸载时由该 Hook 关闭。
|
||||
let socket: WebSocket | null = null;
|
||||
/** connect 建立认证 Cookie 自动携带的通知连接,并在异常关闭后安排有限退避重连。 */
|
||||
const connect = (): void => {
|
||||
if (disposed) return;
|
||||
publishChatConnectionState('connecting');
|
||||
// protocol 根据当前页面协议选择对应安全级别的 WebSocket 方案,避免 HTTPS 页面混合内容失败。
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
|
||||
socket.onopen = /* 当前回调在连接成功后重置后续异常关闭的退避次数并通知聊天页。 */ () => {
|
||||
retryCount = 0;
|
||||
publishChatConnectionState('online');
|
||||
};
|
||||
socket.onmessage = /* 当前回调只解析服务端广播的聊天消息,损坏帧不影响后续连接。 */ event => {
|
||||
try {
|
||||
// payload 保存服务端推送的 JSON 对象。
|
||||
const payload = JSON.parse(event.data) as {
|
||||
/** message 保存服务端广播的可选实时聊天消息。 */
|
||||
message?: ChatMessage;
|
||||
};
|
||||
// message 保存可能存在的实时聊天消息;其他 WebSocket 帧无需产生标题提醒。
|
||||
const message = payload.message;
|
||||
if (message) {
|
||||
notifyIncomingMessage(message);
|
||||
publishChatLiveMessage(message);
|
||||
}
|
||||
} catch {
|
||||
// 忽略非聊天格式帧,下一条合法广播仍可正常触发通知。
|
||||
}
|
||||
};
|
||||
socket.onclose = /* 当前回调在连接非主动关闭时以有限指数退避重新订阅通知。 */ () => {
|
||||
if (disposed) return;
|
||||
publishChatConnectionState('offline');
|
||||
// delayMs 保存下一次重连等待时间,单位为毫秒,最长不超过十五秒。
|
||||
const delayMs = Math.min(15_000, 1_000 * 2 ** Math.min(retryCount++, 4));
|
||||
reconnectTimer = window.setTimeout(connect, delayMs);
|
||||
};
|
||||
socket.onerror = /* 当前回调将错误统一转换为关闭事件,以复用唯一的重连策略。 */ () => socket?.close();
|
||||
};
|
||||
connect();
|
||||
return /* 当前清理函数停止待执行重连并关闭当前连接,确保应用壳注销后不保留后台通知任务。 */ () => {
|
||||
disposed = true;
|
||||
window.clearTimeout(reconnectTimer);
|
||||
socket?.close();
|
||||
publishChatConnectionState('offline');
|
||||
};
|
||||
}, [notifyIncomingMessage]);
|
||||
|
||||
return { hasUnreadChatMessage };
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { lazy, Suspense, useEffect, useState } from 'react';
|
||||
import Sidebar from '../../shared/ui/Sidebar';
|
||||
import type { Item } from '../../shared/api-contract';
|
||||
import { useChatTitleNotification } from '../features/chat/titleNotification';
|
||||
import { getHealth } from '../features/system/api';
|
||||
import type { BuildInfo } from '../features/system/types';
|
||||
|
||||
@@ -133,6 +134,8 @@ const AuthenticatedShell: React.FC<AuthenticatedShellProps> = ({
|
||||
}) => {
|
||||
// buildInfo 保存壳层加载的公开构建版本,侧边栏保持为无请求的共享展示组件。
|
||||
const [buildInfo, setBuildInfo] = useState<BuildInfo>({ version: 'dev', commit: 'unknown' });
|
||||
// hasUnreadChatMessage 保存侧边栏在线聊天入口的服务端/实时聚合未读状态,不因导航动作改变。
|
||||
const { hasUnreadChatMessage } = useChatTitleNotification();
|
||||
|
||||
useEffect(/* effect 在壳层挂载时读取版本信息,并在卸载时中止尚未完成的请求。 */ () => {
|
||||
// controller 取消壳层卸载后不再需要的健康检查请求。
|
||||
@@ -158,6 +161,7 @@ const AuthenticatedShell: React.FC<AuthenticatedShellProps> = ({
|
||||
onNavigate={onNavigate}
|
||||
onLogout={onLogout}
|
||||
buildInfo={buildInfo}
|
||||
hasUnreadChatMessage={hasUnreadChatMessage}
|
||||
/>
|
||||
|
||||
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${collapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
|
||||
|
||||
@@ -22,11 +22,14 @@ describe('online chat UI contract', () => {
|
||||
expect(chat).not.toContain('选择一个买家');
|
||||
} /* 测试回调断言用户标签不误用买家角色。 */);
|
||||
|
||||
test('frontend connects only to the application chat websocket', () => {
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
|
||||
expect(chatHook).toContain('/api/v1/chat/ws');
|
||||
expect(chatHook).not.toContain('wss-goofish.dingtalk.com');
|
||||
} /* 测试回调断言前端只连接应用层聊天 WebSocket。 */);
|
||||
test('应用壳拥有唯一应用层聊天 WebSocket,聊天页仅订阅其事件', () => {
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 保存聊天页状态 Hook 源码。 */
|
||||
const titleNotification = source('app/features/chat/titleNotification.ts'); /* titleNotification 保存认证应用壳实时连接 owner 源码。 */
|
||||
expect(titleNotification).toContain('/api/v1/chat/ws');
|
||||
expect(titleNotification).not.toContain('wss-goofish.dingtalk.com');
|
||||
expect(chatHook).toContain('subscribeToChatLiveEvents');
|
||||
expect(chatHook).not.toContain('new WebSocket(');
|
||||
} /* 测试回调断言前端唯一连接归属应用壳,Chat 页面不会重复建连。 */);
|
||||
|
||||
test('renders peer/self identity and verified media capabilities', () => {
|
||||
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// @vitest-environment jsdom
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import Sidebar from './Sidebar';
|
||||
|
||||
describe('Sidebar', /* 当前测试组验证全局聊天新消息状态在侧边栏中的可见标记。 */ () => {
|
||||
test('未查看聊天消息时仅在在线聊天入口显示红点', /* 当前回调验证红点出现与消失不依赖页面标题状态。 */ () => {
|
||||
// navigationHandler 是侧边栏导航测试使用的无副作用回调。
|
||||
const navigationHandler = vi.fn();
|
||||
// logoutHandler 是侧边栏注销测试使用的无副作用回调。
|
||||
const logoutHandler = vi.fn();
|
||||
// collapseHandler 是侧边栏折叠测试使用的无副作用回调。
|
||||
const collapseHandler = vi.fn();
|
||||
// buildInfo 是渲染侧边栏所需的最小公开构建标识。
|
||||
const buildInfo = { version: 'dev', commit: 'test' };
|
||||
// view 保存带有新消息状态的侧边栏渲染控制器。
|
||||
const view = render(
|
||||
<Sidebar
|
||||
activeTab="dashboard"
|
||||
collapsed={false}
|
||||
onToggleCollapsed={collapseHandler}
|
||||
onNavigate={navigationHandler}
|
||||
onLogout={logoutHandler}
|
||||
buildInfo={buildInfo}
|
||||
hasUnreadChatMessage
|
||||
/>,
|
||||
);
|
||||
// unreadIndicator 表示挂载在聊天图标右上角的未读提示元素。
|
||||
const unreadIndicator = screen.getByLabelText('在线聊天有未读消息');
|
||||
expect(unreadIndicator).toBeTruthy();
|
||||
expect(unreadIndicator.classList.contains('absolute')).toBe(true);
|
||||
expect(unreadIndicator.classList.contains('-right-1')).toBe(true);
|
||||
expect(unreadIndicator.classList.contains('-top-1')).toBe(true);
|
||||
expect(unreadIndicator.classList.contains('h-3')).toBe(true);
|
||||
expect(unreadIndicator.classList.contains('w-3')).toBe(true);
|
||||
view.rerender(
|
||||
<Sidebar
|
||||
activeTab="dashboard"
|
||||
collapsed={false}
|
||||
onToggleCollapsed={collapseHandler}
|
||||
onNavigate={navigationHandler}
|
||||
onLogout={logoutHandler}
|
||||
buildInfo={buildInfo}
|
||||
hasUnreadChatMessage={false}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByLabelText('在线聊天有未读消息')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -22,11 +22,12 @@ interface SidebarProps {
|
||||
/** onNavigate 表示切换主导航页面的回调。 */ onNavigate: (tab: string) => void;
|
||||
/** onLogout 表示注销当前会话的回调。 */ onLogout: () => void;
|
||||
/** buildInfo 是由应用壳加载并传入的公开构建版本信息。 */ buildInfo: SidebarBuildInfo;
|
||||
/** hasUnreadChatMessage 表示在线聊天入口是否仍有未读消息,需要展示红点。 */ hasUnreadChatMessage?: boolean;
|
||||
}
|
||||
|
||||
// Sidebar 渲染侧边栏导航组件。
|
||||
const Sidebar: React.FC<SidebarProps> = ({
|
||||
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, buildInfo,
|
||||
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, buildInfo, hasUnreadChatMessage = false,
|
||||
}) => {
|
||||
// menuItems 侧边栏菜单项。
|
||||
const menuItems = [
|
||||
@@ -77,7 +78,10 @@ const Sidebar: React.FC<SidebarProps> = ({
|
||||
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
|
||||
}`}
|
||||
>
|
||||
<Icon className={`h-[19px] w-[19px] shrink-0 ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
|
||||
<span className="relative flex h-[19px] w-[19px] shrink-0">
|
||||
<Icon className={`h-[19px] w-[19px] ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
|
||||
{item.id === 'chat' && hasUnreadChatMessage && <span className="absolute -right-1 -top-1 h-3 w-3 rounded-full border-2 border-white bg-red-500" role="status" aria-label="在线聊天有未读消息" />}
|
||||
</span>
|
||||
{!collapsed && <span className="truncate text-sm font-bold">{item.label}</span>}
|
||||
{active && !collapsed && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-white/90" />}
|
||||
</button>
|
||||
|
||||
Reference in new issue
Block a user