双端适配,web端的修改父容器和接口

This commit is contained in:
2026-03-29 02:34:13 +08:00
parent 3c071957ce
commit ebb0c003e3
16 changed files with 1419 additions and 226 deletions

View File

@@ -23,6 +23,8 @@ import { spacing, fontSizes, shadows, useAppColors, type AppColors } from '../..
import { ConversationResponse, MessageResponse, MessageSegment, GroupMemberResponse, ImageSegmentData } from '../../../types/dto';
import { Avatar, Text, ImageGallery, AppBackButton } from '../../../components/common';
import { useAuthStore, messageManager, MessageEvent, MessageSubscriber } from '../../../stores';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { extractTextFromSegments } from '../../../types/dto';
import { useBreakpointGTE } from '../../../hooks/useResponsive';
import { useMarkAsRead } from '../../../stores/messageManagerHooks';
@@ -30,15 +32,20 @@ import { messageService } from '../../../services';
import * as hrefs from '../../../navigation/hrefs';
import { GroupInfoPanel } from './ChatScreen/GroupInfoPanel';
import { LongPressMenu, MenuPosition, GroupMessage } from './ChatScreen';
import { EmojiPanel } from './ChatScreen/EmojiPanel';
import { MorePanel } from './ChatScreen/MorePanel';
const { width: screenWidth } = Dimensions.get('window');
const PANEL_WIDTH = 360;
// 时间分隔间隔(毫秒)- 5分钟
const TIME_SEPARATOR_INTERVAL = 5 * 60 * 1000;
function createEmbeddedChatStyles(colors: AppColors) {
return StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.chat.screen,
backgroundColor: colors.background.default,
},
header: {
flexDirection: 'row',
@@ -78,7 +85,7 @@ function createEmbeddedChatStyles(colors: AppColors) {
},
messageList: {
flex: 1,
backgroundColor: colors.chat.screen,
backgroundColor: colors.background.default,
},
centerContainer: {
flex: 1,
@@ -102,7 +109,7 @@ function createEmbeddedChatStyles(colors: AppColors) {
},
messageRow: {
flexDirection: 'row',
alignItems: 'flex-end',
alignItems: 'flex-start',
marginBottom: spacing.md,
maxWidth: screenWidth * 0.7,
},
@@ -112,6 +119,15 @@ function createEmbeddedChatStyles(colors: AppColors) {
messageRowRight: {
alignSelf: 'flex-end',
justifyContent: 'flex-end',
alignItems: 'flex-end',
},
avatarWrapper: {
marginHorizontal: 2,
},
messageContent: {
maxWidth: screenWidth * 0.5,
marginHorizontal: spacing.xs,
alignItems: 'flex-start',
},
messageBubble: {
maxWidth: screenWidth * 0.5,
@@ -122,11 +138,11 @@ function createEmbeddedChatStyles(colors: AppColors) {
},
messageBubbleMe: {
backgroundColor: colors.chat.replyTint,
borderBottomRightRadius: 4,
borderTopRightRadius: 4,
},
messageBubbleOther: {
backgroundColor: colors.chat.bubbleIncoming,
borderBottomLeftRadius: 4,
borderTopLeftRadius: 4,
shadowColor: colors.chat.shadow,
shadowOffset: { width: 0, height: 0.5 },
shadowOpacity: 0.04,
@@ -134,9 +150,11 @@ function createEmbeddedChatStyles(colors: AppColors) {
elevation: 1,
},
senderName: {
fontSize: 12,
fontSize: 14,
color: colors.text.secondary,
marginBottom: 2,
marginBottom: 4,
marginLeft: 4,
fontWeight: '600',
},
messageText: {
fontSize: 15,
@@ -149,7 +167,7 @@ function createEmbeddedChatStyles(colors: AppColors) {
color: colors.chat.textPrimary,
},
inputArea: {
backgroundColor: colors.chat.screen,
backgroundColor: colors.background.paper,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: colors.divider,
paddingHorizontal: spacing.md,
@@ -227,6 +245,43 @@ function createEmbeddedChatStyles(colors: AppColors) {
fontSize: 12,
marginTop: 4,
},
// 时间分隔样式
timeContainer: {
alignItems: 'center',
marginVertical: spacing.md,
},
timeText: {
color: 'rgba(142, 142, 147, 0.95)',
fontSize: 11,
backgroundColor: 'rgba(142, 142, 147, 0.1)',
paddingHorizontal: spacing.sm + 4,
paddingVertical: 5,
borderRadius: 12,
fontWeight: '500',
overflow: 'hidden',
letterSpacing: 0.2,
},
// 系统通知样式(如"某某加入了群聊"
systemNoticeContainer: {
alignItems: 'center',
marginVertical: spacing.sm,
paddingHorizontal: spacing.md,
},
systemNoticeText: {
fontSize: 12,
color: colors.chat.textSecondary,
backgroundColor: 'rgba(142, 142, 147, 0.12)',
paddingHorizontal: spacing.md,
paddingVertical: spacing.xs,
borderRadius: 12,
overflow: 'hidden',
},
// 面板容器样式
panelContainer: {
backgroundColor: colors.background.paper,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: colors.divider,
},
});
}
@@ -268,6 +323,81 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
// 回复状态
const [replyingToMessage, setReplyingToMessage] = useState<GroupMessage | null>(null);
// 面板显示状态
const [showEmojiPanel, setShowEmojiPanel] = useState(false);
const [showMorePanel, setShowMorePanel] = useState(false);
// 切换表情面板
const toggleEmojiPanel = useCallback(() => {
setShowEmojiPanel(prev => !prev);
setShowMorePanel(false);
if (!showEmojiPanel) {
inputRef.current?.blur();
}
}, [showEmojiPanel]);
// 切换更多功能面板
const toggleMorePanel = useCallback(() => {
setShowMorePanel(prev => !prev);
setShowEmojiPanel(false);
if (!showMorePanel) {
inputRef.current?.blur();
}
}, [showMorePanel]);
// 关闭所有面板
const closePanels = useCallback(() => {
setShowEmojiPanel(false);
setShowMorePanel(false);
}, []);
// 插入表情
const handleInsertEmoji = useCallback((emoji: string) => {
setInputText(prev => prev + emoji);
}, []);
// 发送自定义表情
const handleSendSticker = useCallback(async (stickerUrl: string) => {
if (!conversation.id) return;
try {
setSending(true);
const segments: MessageSegment[] = [{
type: 'image',
data: { url: stickerUrl, thumbnail_url: stickerUrl }
}];
await messageManager.sendMessage(String(conversation.id), segments);
closePanels();
} catch (error) {
console.error('[EmbeddedChat] 发送表情失败:', error);
} finally {
setSending(false);
}
}, [conversation.id, closePanels]);
// 处理更多功能
const handleMoreAction = useCallback((actionId: string) => {
switch (actionId) {
case 'image':
// TODO: 实现选择图片功能
console.log('选择图片');
break;
case 'camera':
// TODO: 实现相机功能
console.log('相机');
break;
case 'file':
// TODO: 实现文件功能
console.log('文件');
break;
case 'location':
// TODO: 实现位置功能
console.log('位置');
break;
}
closePanels();
}, [closePanels]);
// 群信息面板动画
const slideAnim = useRef(new Animated.Value(PANEL_WIDTH)).current;
const fadeAnim = useRef(new Animated.Value(0)).current;
@@ -276,6 +406,42 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
// 群成员列表
const [groupMembers, setGroupMembers] = useState<GroupMemberResponse[]>([]);
// 格式化时间
const formatTime = useCallback((dateString: string): string => {
try {
const date = new Date(dateString);
const now = new Date();
const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60);
if (diffInHours < 24 && date.getDate() === now.getDate()) {
// 当天消息显示 "上午/下午 HH:mm" 格式
const hours = date.getHours();
const period = hours < 12 ? '上午' : '下午';
const displayHours = hours % 12 || 12;
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${period} ${displayHours}:${minutes}`;
}
return formatDistanceToNow(date, {
addSuffix: true,
locale: zhCN,
});
} catch {
return '';
}
}, []);
// 检查是否需要显示时间分隔
const shouldShowTime = useCallback((index: number): boolean => {
if (index === 0) return true;
const currentMsg = messages[index];
const prevMsg = messages[index - 1];
if (!currentMsg || !prevMsg) return false;
const currentTime = new Date(currentMsg.created_at).getTime();
const prevTime = new Date(prevMsg.created_at).getTime();
return (currentTime - prevTime) > TIME_SEPARATOR_INTERVAL;
}, [messages]);
// 打开/关闭群信息面板
const toggleGroupInfoPanel = useCallback(() => {
if (showGroupInfoPanel) {
@@ -325,8 +491,21 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
setLoading(true);
await messageManager.fetchMessages(String(conversation.id));
setMessages(messageManager.getMessages(String(conversation.id)));
} catch (error) {
console.error('[EmbeddedChat] 加载消息失败:', error);
} catch (error: any) {
// 检查是否是权限错误或会话不存在错误
const errorMessage = error?.message || String(error);
if (
errorMessage.includes('not found') ||
errorMessage.includes('no permission') ||
error?.code === 'NOT_FOUND' ||
error?.code === 'FORBIDDEN'
) {
console.warn('[EmbeddedChat] 会话不存在或无权限访问:', conversation.id);
// 设置空消息列表,让 UI 显示"暂无消息"而不是崩溃
setMessages([]);
} else {
console.error('[EmbeddedChat] 加载消息失败:', error);
}
} finally {
setLoading(false);
}
@@ -558,9 +737,36 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
};
// 渲染消息
const renderMessage = ({ item }: { item: MessageResponse }) => {
const renderMessage = ({ item, index }: { item: MessageResponse; index: number }) => {
const isMe = String(item.sender_id) === String(currentUser?.id);
const showTime = shouldShowTime(index);
// 系统通知消息特殊处理
// 1. is_system_notice 字段WebSocket 推送时设置)
// 2. category === 'notification'(从数据库加载时使用)
// 3. sender_id === '10000'(系统发送者兜底)
const isSystemNotice = (item as any).is_system_notice || item.category === 'notification' || item.sender_id === '10000';
// 系统通知消息渲染(如"某某加入了群聊"
if (isSystemNotice) {
return (
<View>
{showTime && (
<View style={styles.timeContainer}>
<Text style={styles.timeText}>
{formatTime(item.created_at)}
</Text>
</View>
)}
<View style={styles.systemNoticeContainer}>
<Text style={styles.systemNoticeText}>
{(item as any).notice_content || extractTextFromSegments(item.segments)}
</Text>
</View>
</View>
);
}
// 处理指针事件(鼠标右键)- 使用 onPointerDown 检测鼠标右键
const handlePointerDown = (e: any) => {
// e.nativeEvent.button: 0=左键, 1=中键, 2=右键
@@ -572,33 +778,55 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
handleMessageRightPress(item, e);
}
};
return (
<View
style={[styles.messageRow, isMe ? styles.messageRowRight : styles.messageRowLeft]}
// @ts-ignore - React Native for Web 支持 pointer events
onPointerDown={handlePointerDown}
>
{!isMe && (
<Avatar
source={item.sender?.avatar}
size={36}
name={item.sender?.nickname || item.sender?.username}
/>
<View>
{/* 时间分隔 */}
{showTime && (
<View style={styles.timeContainer}>
<Text style={styles.timeText}>
{formatTime(item.created_at)}
</Text>
</View>
)}
<View style={[styles.messageBubble, isMe ? styles.messageBubbleMe : styles.messageBubbleOther]}>
{isGroupChat && !isMe && (
<Text style={styles.senderName}>{item.sender?.nickname || item.sender?.username}</Text>
<View
style={[styles.messageRow, isMe ? styles.messageRowRight : styles.messageRowLeft]}
// @ts-ignore - React Native for Web 支持 pointer events
onPointerDown={handlePointerDown}
>
{/* 对方头像(左侧) */}
{!isMe && (
<View style={styles.avatarWrapper}>
<Avatar
source={item.sender?.avatar}
size={36}
name={item.sender?.nickname || item.sender?.username}
/>
</View>
)}
{/* 消息内容区域 */}
<View style={styles.messageContent}>
{/* 群聊模式:显示发送者昵称(在气泡上方,与头像顶部对齐) */}
{isGroupChat && !isMe && (
<Text style={styles.senderName}>{item.sender?.nickname || item.sender?.username}</Text>
)}
<View style={[styles.messageBubble, isMe ? styles.messageBubbleMe : styles.messageBubbleOther]}>
{renderMessageContent(item)}
</View>
</View>
{/* 自己的头像(右侧) */}
{isMe && (
<View style={styles.avatarWrapper}>
<Avatar
source={currentUser?.avatar}
size={36}
name={currentUser?.nickname || currentUser?.username}
/>
</View>
)}
{renderMessageContent(item)}
</View>
{isMe && (
<Avatar
source={currentUser?.avatar}
size={36}
name={currentUser?.nickname || currentUser?.username}
/>
)}
</View>
);
};
@@ -669,8 +897,12 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
>
<View style={styles.inputArea}>
<View style={styles.inputRow}>
<TouchableOpacity style={styles.iconButton}>
<MaterialCommunityIcons name="plus-circle-outline" size={28} color={colors.text.secondary} />
<TouchableOpacity style={styles.iconButton} onPress={toggleMorePanel}>
<MaterialCommunityIcons
name={showMorePanel ? "close-circle-outline" : "plus-circle-outline"}
size={28}
color={showMorePanel ? colors.primary.main : colors.text.secondary}
/>
</TouchableOpacity>
<View style={styles.inputContainer}>
@@ -691,8 +923,12 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
/>
</View>
<TouchableOpacity style={styles.iconButton}>
<MaterialCommunityIcons name="emoticon-outline" size={28} color={colors.text.secondary} />
<TouchableOpacity style={styles.iconButton} onPress={toggleEmojiPanel}>
<MaterialCommunityIcons
name={showEmojiPanel ? "emoticon-happy" : "emoticon-outline"}
size={28}
color={showEmojiPanel ? colors.primary.main : colors.text.secondary}
/>
</TouchableOpacity>
<TouchableOpacity
@@ -708,6 +944,26 @@ export const EmbeddedChat: React.FC<EmbeddedChatProps> = ({ conversation, onBack
</TouchableOpacity>
</View>
</View>
{/* 表情面板 */}
{showEmojiPanel && (
<View style={{ height: 350, backgroundColor: colors.background.paper }}>
<EmojiPanel
onInsertEmoji={handleInsertEmoji}
onInsertSticker={handleSendSticker}
onClose={closePanels}
/>
</View>
)}
{/* 更多功能面板 */}
{showMorePanel && (
<View style={{ height: 350, backgroundColor: colors.background.paper }}>
<MorePanel
onAction={handleMoreAction}
/>
</View>
)}
</KeyboardAvoidingView>
{/* 群信息侧边栏面板 - 仅大屏幕显示 */}