All files / app/(tabs)/profile messages.tsx

73.91% Statements 51/69
47.61% Branches 20/42
64.7% Functions 11/17
76.92% Lines 50/65

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                                                1x         6x 6x 6x 6x 6x 6x 6x 6x   6x   2x     2x 2x 2x     2x 2x     2x         2x                             2x 2x 2x         6x   2x       6x 4x 4x 4x 4x 4x     4x       6x           6x                     6x   1x               1x 1x                         6x 1x 1x 1x   1x               6x 1x 1x   1x                                                                                                       6x 3x             6x                                                                         2x                                   1x                                                                                                                                                                                                                                                                                                            
/**
 * 消息列表页面
 * 显示所有聊天会话
 */
 
import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Image,
  ActivityIndicator,
  RefreshControl,
  Dimensions,
} from 'react-native';
import { Stack, useRouter, useFocusEffect } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';
import { MessageCircle, ChevronLeft, User } from '@tamagui/lucide-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { supabaseChatService, supabase, type Conversation } from '@/src/lib/supabase';
import { useThemeColors, useIsDarkMode } from '@/src/hooks/useThemeColors';
 
const { width: SCREEN_WIDTH } = Dimensions.get('window');
 
type TabType = 'friends' | 'requests';
 
export default function MessagesScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const colors = useThemeColors();
  const isDark = useIsDarkMode();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
 
  useEffect(() => {
    // 获取当前用户ID
    const initUser = async () => {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      Eif (user) {
        setCurrentUserId(user.id);
      }
    };
    initUser();
    loadConversations();
 
    // 订阅会话和消息变化
    const unsubscribeConversations = supabaseChatService.subscribeToConversations(() => {
      loadConversations();
    });
 
    // 订阅未读计数变化
    const unreadChannel = supabase
      .channel('unread_counts:all')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'unread_counts',
        },
        () => {
          loadConversations();
        }
      )
      .subscribe();
 
    return () => {
      unsubscribeConversations();
      supabase.removeChannel(unreadChannel);
    };
  }, []);
 
  // 当页面重新获得焦点时刷新数据(从聊天页面返回时)
  useFocusEffect(
    useCallback(() => {
      loadConversations();
    }, [])
  );
 
  const loadConversations = async () => {
    setLoading(true);
    try {
      const response = await supabaseChatService.getMyConversations();
      Eif (response.success && response.data) {
        setConversations(response.data);
      }
    } finally {
      setLoading(false);
    }
  };
 
  const handleRefresh = async () => {
    setRefreshing(true);
    await loadConversations();
    setRefreshing(false);
  };
 
  const handleOpenConversation = (conversation: Conversation) => {
    // 获取对方用户ID并传递
    const otherUserId =
      currentUserId === conversation.participant1Id
        ? conversation.participant2Id
        : conversation.participant1Id;
    router.push(
      `/(tabs)/profile/chat?conversationId=${conversation.id}&userId=${otherUserId}` as any
    );
  };
 
  const getOtherUser = (conversation: Conversation) => {
    // 根据当前用户判断对方是谁
    Iif (!currentUserId) {
      return {
        username: '未知用户',
        avatar: undefined,
      };
    }
 
    // 如果当前用户是 participant1,显示 participant2
    Eif (currentUserId === conversation.participant1Id) {
      return {
        username: conversation.participant2Username || '未知用户',
        avatar: conversation.participant2Avatar,
      };
    }
 
    // 否则显示 participant1
    return {
      username: conversation.participant1Username || '未知用户',
      avatar: conversation.participant1Avatar,
    };
  };
 
  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
 
    Eif (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
    if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`;
 
    return date.toLocaleDateString('zh-CN');
  };
 
  const renderConversationItem = ({ item }: { item: Conversation }) => {
    const otherUser = getOtherUser(item);
    const hasUnread = (item.unreadCount || 0) > 0;
 
    return (
      <TouchableOpacity
        style={[
          styles.conversationCard,
          { backgroundColor: colors.cardBackground, borderColor: colors.borderMuted },
        ]}
        onPress={() => handleOpenConversation(item)}
        activeOpacity={0.8}
      >
        <View style={styles.avatarContainer}>
          {otherUser.avatar ? (
            <Image source={{ uri: otherUser.avatar }} style={styles.avatar} />
          ) : (
            <View style={[styles.avatarPlaceholder, { backgroundColor: colors.primary }]}>
              <User size={24} color="#FFFFFF" strokeWidth={2} />
            </View>
          )}
          {hasUnread && <View style={[styles.onlineDot, { borderColor: colors.cardBackground }]} />}
        </View>
 
        <View style={styles.conversationInfo}>
          <View style={styles.conversationHeader}>
            <Text style={[styles.username, { color: colors.text }]} numberOfLines={1}>
              {otherUser.username}
            </Text>
            <Text style={[styles.time, { color: colors.textTertiary }]}>
              {formatTime(item.lastMessageAt)}
            </Text>
          </View>
 
          <View style={styles.messagePreview}>
            <Text
              style={[
                styles.lastMessage,
                { color: colors.textSecondary },
                hasUnread && [styles.lastMessageUnread, { color: colors.text }],
              ]}
              numberOfLines={1}
            >
              {item.lastMessage || '开始聊天...'}
            </Text>
            {hasUnread && (
              <View style={[styles.unreadBadge, { backgroundColor: colors.error }]}>
                <Text style={styles.unreadText}>{item.unreadCount}</Text>
              </View>
            )}
          </View>
        </View>
      </TouchableOpacity>
    );
  };
 
  const renderEmptyState = () => (
    <View style={styles.emptyState}>
      <MessageCircle size={64} color={colors.textTertiary as any} strokeWidth={1.5} />
      <Text style={[styles.emptyTitle, { color: colors.textSecondary }]}>暂无消息</Text>
      <Text style={[styles.emptyText, { color: colors.textTertiary }]}>和好友开始聊天吧!</Text>
    </View>
  );
 
  return (
    <View
      testID="messages-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={() => {
            // 返回到个人中心主页
            router.push('/(tabs)/profile');
          }}
          activeOpacity={0.8}
        >
          <ChevronLeft size={28} color="#FFFFFF" strokeWidth={2.5} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>消息</Text>
        <View style={styles.backButton} />
      </LinearGradient>
 
      {/* 会话列表 */}
      {loading && !refreshing ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={conversations}
          renderItem={renderConversationItem}
          keyExtractor={(item) => item.id.toString()}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          ListEmptyComponent={renderEmptyState}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={handleRefresh}
              tintColor={colors.primary}
              colors={[colors.primary]}
            />
          }
        />
      )}
    </View>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9FAFB',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#FFFFFF',
    flex: 1,
    textAlign: 'center',
    marginHorizontal: 16,
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  listContent: {
    padding: 16,
    flexGrow: 1,
  },
  conversationCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
  },
  avatarContainer: {
    position: 'relative',
    marginRight: 16,
  },
  avatar: {
    width: 56,
    height: 56,
    borderRadius: 28,
  },
  avatarPlaceholder: {
    width: 56,
    height: 56,
    borderRadius: 28,
    alignItems: 'center',
    justifyContent: 'center',
  },
  onlineDot: {
    position: 'absolute',
    bottom: 2,
    right: 2,
    width: 14,
    height: 14,
    borderRadius: 7,
    backgroundColor: '#10B981',
    borderWidth: 2,
    borderColor: '#FFFFFF',
  },
  conversationInfo: {
    flex: 1,
  },
  conversationHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  username: {
    fontSize: 16,
    fontWeight: '600',
    color: '#111827',
    flex: 1,
  },
  time: {
    fontSize: 12,
    color: '#9CA3AF',
    marginLeft: 8,
  },
  messagePreview: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  lastMessage: {
    fontSize: 14,
    color: '#6B7280',
    flex: 1,
  },
  lastMessageUnread: {
    color: '#111827',
    fontWeight: '600',
  },
  unreadBadge: {
    backgroundColor: '#EF4444',
    borderRadius: 10,
    minWidth: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 6,
    marginLeft: 8,
  },
  unreadText: {
    fontSize: 11,
    fontWeight: '700',
    color: '#FFFFFF',
  },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 80,
  },
  emptyTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#4B5563',
    marginTop: 24,
    marginBottom: 8,
  },
  emptyText: {
    fontSize: 14,
    color: '#9CA3AF',
    textAlign: 'center',
    paddingHorizontal: 40,
    lineHeight: 20,
  },
});