Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 | 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 2x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 2x 7x 7x 3x 7x 3x 3x 7x 3x 7x 3x 3x 3x 3x 7x 7x 2x 5x 7x 5x 1x | /**
* 聊天对话界面
*
* 功能:
* - 显示聊天消息
* - 发送消息
* - 实时接收新消息
* - 自动标记已读
*/
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TextInput,
TouchableOpacity,
Image,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
Dimensions,
} from 'react-native';
import { Stack, useRouter, useLocalSearchParams } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';
import { ChevronLeft, Send, User } from '@tamagui/lucide-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { useThemeColors, useIsDarkMode } from '@/src/hooks/useThemeColors';
import {
supabaseChatService,
supabaseProfileService,
type Message,
type Profile,
} from '@/src/lib/supabase';
const { width: SCREEN_WIDTH } = Dimensions.get('window');
export default function ChatScreen() {
const router = useRouter();
const insets = useSafeAreaInsets();
const colors = useThemeColors();
const isDark = useIsDarkMode();
const params = useLocalSearchParams();
const conversationId = Number(params.conversationId);
const otherUserId = params.userId as string;
const [messages, setMessages] = useState<Message[]>([]);
const [otherUser, setOtherUser] = useState<Profile | null>(null);
const [inputText, setInputText] = useState('');
const [loading, setLoading] = useState(false);
const [sending, setSending] = useState(false);
const flatListRef = useRef<FlatList>(null);
const inputRef = useRef<TextInput>(null);
useEffect(() => {
loadData();
// 订阅实时消息
const unsubscribe = supabaseChatService.subscribeToMessages(conversationId, (newMessage) => {
setMessages((prev) => {
// 避免重复添加(发送消息时已手动添加)
const exists = prev.some((msg) => msg.id === newMessage.id);
if (exists) return prev;
return [...prev, newMessage];
});
scrollToBottom();
// 如果不是自己发送的消息,标记为已读
if (newMessage.senderId !== otherUserId) {
supabaseChatService.markMessagesAsRead(conversationId);
}
});
// 标记消息为已读
supabaseChatService.markMessagesAsRead(conversationId);
return () => {
unsubscribe();
};
}, [conversationId]);
const loadData = async () => {
setLoading(true);
try {
// 加载对方用户信息
Eif (otherUserId) {
const userResponse = await supabaseProfileService.getProfileById(otherUserId);
Eif (userResponse.success && userResponse.data) {
setOtherUser(userResponse.data);
}
}
// 加载消息
const messagesResponse = await supabaseChatService.getMessages(conversationId);
Eif (messagesResponse.success && messagesResponse.data) {
setMessages(messagesResponse.data);
setTimeout(() => scrollToBottom(), 100);
}
} finally {
setLoading(false);
}
};
const scrollToBottom = () => {
Iif (flatListRef.current && messages.length > 0) {
flatListRef.current.scrollToEnd({ animated: true });
}
};
const handleSend = async () => {
if (!inputText.trim() || sending) return;
const content = inputText.trim();
setInputText('');
setSending(true);
try {
const response = await supabaseChatService.sendMessage(conversationId, content);
if (response.success && response.data) {
// 立即添加消息到本地列表(不依赖实时订阅延迟)
setMessages((prev) => {
// 检查消息是否已存在(避免实时订阅重复添加)
const exists = prev.some((msg) => msg.id === response.data!.id);
if (exists) return prev;
return [...prev, response.data!];
});
scrollToBottom();
}
} catch (error) {
console.error('Failed to send message:', error);
setInputText(content); // 恢复输入内容
} finally {
setSending(false);
}
};
const isMyMessage = useCallback(
(message: Message) => {
return message.senderId !== otherUserId;
},
[otherUserId]
);
const formatTime = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};
const shouldShowTimestamp = (currentMessage: Message, previousMessage?: Message) => {
Eif (!previousMessage) return true;
const currentTime = new Date(currentMessage.createdAt).getTime();
const previousTime = new Date(previousMessage.createdAt).getTime();
// 超过5分钟显示时间戳
return currentTime - previousTime > 5 * 60 * 1000;
};
const renderMessage = ({ item, index }: { item: Message; index: number }) => {
const isMine = isMyMessage(item);
const previousMessage = index > 0 ? messages[index - 1] : undefined;
const showTimestamp = shouldShowTimestamp(item, previousMessage);
return (
<Animated.View
entering={FadeInDown.duration(300).delay(index * 50)}
style={styles.messageContainer}
>
{showTimestamp && (
<View style={styles.timestampContainer}>
<Text
style={[
styles.timestampText,
{ backgroundColor: colors.backgroundMuted, color: colors.textTertiary },
]}
>
{formatTime(item.createdAt)}
</Text>
</View>
)}
<View style={[styles.messageRow, isMine && styles.messageRowMine]}>
{!isMine && (
<View style={styles.avatarContainer}>
{otherUser?.avatarUrl ? (
<Image source={{ uri: otherUser.avatarUrl }} style={styles.avatar} />
) : (
<View style={[styles.avatarPlaceholder, { backgroundColor: colors.border }]}>
<User size={16} color="#FFFFFF" strokeWidth={2} />
</View>
)}
</View>
)}
<View
style={[
styles.messageBubble,
isMine
? [styles.messageBubbleMine, { backgroundColor: colors.primary }]
: [
styles.messageBubbleOther,
{ backgroundColor: colors.cardBackground, borderColor: colors.borderMuted },
],
]}
>
<Text style={[styles.messageText, { color: isMine ? 'white' : colors.text }]}>
{item.content}
</Text>
</View>
</View>
</Animated.View>
);
};
const renderHeader = () => {
if (loading && messages.length === 0) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={colors.primary} />
</View>
);
}
return null;
};
return (
<View
testID="chat-screen"
style={[styles.container, { paddingTop: insets.top, backgroundColor: colors.background }]}
>
<Stack.Screen options={{ headerShown: false }} />
{/* 自定义头部 */}
<LinearGradient
colors={isDark ? ['#3D2A1F', '#2D1F1A'] : ['#FEBE98', '#FFCCBC']}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
style={styles.header}
>
<TouchableOpacity
style={styles.backButton}
onPress={() => {
// 返回到消息列表
if (router.canGoBack()) {
router.back();
} else {
router.replace('/(tabs)/profile/messages');
}
}}
activeOpacity={0.8}
>
<ChevronLeft size={28} color="#FFFFFF" strokeWidth={2.5} />
</TouchableOpacity>
<View style={styles.headerCenter}>
{otherUser?.avatarUrl ? (
<Image source={{ uri: otherUser.avatarUrl }} style={styles.headerAvatar} />
) : (
<View style={styles.headerAvatarPlaceholder}>
<User size={18} color="#FFFFFF" strokeWidth={2} />
</View>
)}
<Text style={styles.headerTitle}>{otherUser?.username || '加载中...'}</Text>
</View>
<View style={styles.backButton} />
</LinearGradient>
{/* 消息列表 */}
<KeyboardAvoidingView
style={styles.flex1}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
>
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessage}
keyExtractor={(item) => item.id.toString()}
contentContainerStyle={styles.messagesList}
showsVerticalScrollIndicator={false}
ListHeaderComponent={renderHeader}
onContentSizeChange={scrollToBottom}
onLayout={scrollToBottom}
/>
{/* 输入框 */}
<View
style={[
styles.inputContainer,
{
paddingBottom: insets.bottom || 8,
backgroundColor: colors.cardBackground,
borderTopColor: colors.borderMuted,
},
]}
>
<View style={[styles.inputWrapper, { backgroundColor: colors.backgroundMuted }]}>
<TextInput
ref={inputRef}
style={[styles.input, { color: colors.text }]}
value={inputText}
onChangeText={setInputText}
placeholder="输入消息..."
placeholderTextColor={colors.textTertiary}
multiline
maxLength={1000}
returnKeyType="send"
onSubmitEditing={handleSend}
/>
<TouchableOpacity
style={[
styles.sendButton,
{ backgroundColor: colors.primary },
!inputText.trim() && [
styles.sendButtonDisabled,
{ backgroundColor: colors.border },
],
]}
onPress={handleSend}
disabled={!inputText.trim() || sending}
activeOpacity={0.8}
>
{sending ? (
<ActivityIndicator size="small" color="#FFFFFF" />
) : (
<Send size={20} color="#FFFFFF" strokeWidth={2} />
)}
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F9FAFB',
},
flex1: {
flex: 1,
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 12,
elevation: 4,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 8,
},
backButton: {
width: 40,
height: 40,
alignItems: 'center',
justifyContent: 'center',
},
headerCenter: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 12,
},
headerAvatar: {
width: 36,
height: 36,
borderRadius: 18,
borderWidth: 2,
borderColor: '#FFFFFF',
},
headerAvatarPlaceholder: {
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: 'rgba(255, 255, 255, 0.3)',
alignItems: 'center',
justifyContent: 'center',
borderWidth: 2,
borderColor: '#FFFFFF',
},
headerTitle: {
fontSize: 18,
fontWeight: '700',
color: '#FFFFFF',
},
loadingContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 100,
},
messagesList: {
paddingHorizontal: 16,
paddingVertical: 16,
flexGrow: 1,
},
messageContainer: {
marginBottom: 4,
},
timestampContainer: {
alignItems: 'center',
marginVertical: 16,
},
timestampText: {
fontSize: 12,
color: '#9CA3AF',
backgroundColor: '#F3F4F6',
paddingHorizontal: 12,
paddingVertical: 4,
borderRadius: 12,
},
messageRow: {
flexDirection: 'row',
alignItems: 'flex-end',
marginBottom: 8,
},
messageRowMine: {
justifyContent: 'flex-end',
},
avatarContainer: {
marginRight: 8,
marginBottom: 2,
},
avatar: {
width: 32,
height: 32,
borderRadius: 16,
},
avatarPlaceholder: {
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: '#D1D5DB',
alignItems: 'center',
justifyContent: 'center',
},
messageBubble: {
maxWidth: SCREEN_WIDTH * 0.7,
paddingHorizontal: 16,
paddingVertical: 10,
borderRadius: 20,
},
messageBubbleOther: {
backgroundColor: '#FFFFFF',
borderBottomLeftRadius: 4,
elevation: 1,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 2,
},
messageBubbleMine: {
borderBottomRightRadius: 4,
},
messageText: {
fontSize: 15,
lineHeight: 20,
color: '#111827',
},
messageTextMine: {
color: '#FFFFFF',
},
inputContainer: {
backgroundColor: '#FFFFFF',
borderTopWidth: 1,
borderTopColor: '#E5E7EB',
paddingHorizontal: 16,
paddingTop: 12,
},
inputWrapper: {
flexDirection: 'row',
alignItems: 'flex-end',
backgroundColor: '#F3F4F6',
borderRadius: 24,
paddingHorizontal: 16,
paddingVertical: 8,
minHeight: 48,
},
input: {
flex: 1,
fontSize: 15,
lineHeight: 20,
color: '#111827',
maxHeight: 100,
paddingVertical: 8,
},
sendButton: {
width: 36,
height: 36,
borderRadius: 18,
alignItems: 'center',
justifyContent: 'center',
marginLeft: 8,
},
sendButtonDisabled: {
backgroundColor: '#D1D5DB',
},
});
|