All files / app/(tabs)/profile/components/tabs CommentsTab.tsx

0% Statements 0/62
0% Branches 0/41
0% Functions 0/10
0% Lines 0/58

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { memo, useEffect, useState } from 'react';
import { Alert, RefreshControl, ScrollView, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router';
import { Card, Spinner, Text, XStack, YStack } from 'tamagui';
import { IconSymbol } from '@/src/components/ui/IconSymbol';
import { Colors } from '@/src/constants/theme';
import { useThemeAwareColorScheme } from '@/src/hooks/useThemeAwareColorScheme';
import { supabaseCommentService, type Comment } from '@/src/lib/supabase';
import { useUserStore } from '@/src/store/userStore';
 
/**
 * 评论 Tab 组件
 *
 * 功能:
 * - 显示用户的所有评论
 * - 支持下拉刷新
 * - 显示评论内容和时间
 *
 * @component
 */
export const CommentsTab = memo(function CommentsTab() {
  const colorScheme = useThemeAwareColorScheme();
  const colors = Colors[colorScheme];
  const router = useRouter();
  const { _hasHydrated, isAuthenticated } = useUserStore();
  const [comments, setComments] = useState<Comment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
 
  /**
   * 加载评论列表
   */
  const loadComments = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setIsRefreshing(true);
      } else {
        setIsLoading(true);
      }
 
      const { data, error } = await supabaseCommentService.getMyComments();
      if (error) {
        throw new Error(error.message);
      }
      setComments(data || []);
    } catch (error: any) {
      console.error('加载评论失败:', error);
      Alert.alert('错误', '加载评论失败,请稍后重试');
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };
 
  useEffect(() => {
    // 等待 Zustand 状态恢复完成后再加载评论
    if (_hasHydrated && isAuthenticated) {
      loadComments();
    } else if (_hasHydrated && !isAuthenticated) {
      // 如果已经恢复但未认证,停止加载
      setIsLoading(false);
    }
  }, [_hasHydrated, isAuthenticated]);
 
  /**
   * 跳转到评论所在的内容详情页
   */
  const handleNavigateToComment = (comment: Comment) => {
    console.log('[CommentsTab] 点击评论,跳转到:', comment.targetType, comment.targetId);
 
    if (comment.targetType === 'post') {
      // 跳转到帖子详情页面(独立全屏页面,返回时会正确回到 profile)
      router.push({
        pathname: '/post-detail',
        params: {
          postId: comment.targetId.toString(),
          commentId: comment.id.toString(),
        },
      });
    } else if (comment.targetType === 'catfood') {
      // 跳转到猫粮详情
      router.push({
        pathname: '/detail',
        params: { id: comment.targetId },
      });
    } else if (comment.targetType === 'report') {
      // 跳转到报告详情
      router.push({
        pathname: '/detail',
        params: { id: comment.targetId },
      });
    }
  };
 
  /**
   * 格式化时间
   */
  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
 
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 30) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
  };
 
  /**
   * 获取评论目标类型的显示文字
   */
  const getTargetTypeLabel = (targetType: string) => {
    const labels: Record<string, string> = {
      post: '帖子',
      catfood: '猫粮',
      report: '报告',
    };
    return labels[targetType] || '内容';
  };
 
  if (isLoading) {
    return (
      <YStack flex={1} alignItems="center" justifyContent="center" padding="$6">
        <Spinner size="large" color="#FEBE98" />
        <Text fontSize={14} color={colors.icon} marginTop="$3">
          加载中...
        </Text>
      </YStack>
    );
  }
 
  if (comments.length === 0) {
    return (
      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{ flex: 1 }}
        refreshControl={
          <RefreshControl refreshing={isRefreshing} onRefresh={() => loadComments(true)} />
        }
      >
        <YStack flex={1} alignItems="center" justifyContent="center" padding="$6" gap="$4">
          <YStack
            width={100}
            height={100}
            borderRadius="$12"
            backgroundColor="$gray2"
            alignItems="center"
            justifyContent="center"
          >
            <IconSymbol
              name="bubble.left.and.bubble.right.fill"
              size={50}
              color={colors.icon + '60'}
            />
          </YStack>
          <Text fontSize={16} fontWeight="600" color={colors.text}>
            还没有评论
          </Text>
          <Text fontSize={14} color={colors.icon} textAlign="center">
            去猫粮详情页发表你的第一条评论吧
          </Text>
        </YStack>
      </ScrollView>
    );
  }
 
  return (
    <ScrollView
      style={{ flex: 1 }}
      showsVerticalScrollIndicator={false}
      refreshControl={
        <RefreshControl refreshing={isRefreshing} onRefresh={() => loadComments(true)} />
      }
    >
      <YStack width="100%" alignItems="center" paddingVertical="$4" gap="$3">
        {comments.map((comment) => (
          <TouchableOpacity
            key={comment.id}
            onPress={() => handleNavigateToComment(comment)}
            activeOpacity={0.8}
            style={{ width: '90%' }}
          >
            <Card
              padding="$4"
              backgroundColor={colors.background}
              borderWidth={1}
              style={{ borderColor: colors.icon + '15' }}
              borderRadius="$4"
            >
              <YStack gap="$3">
                {/* 评论目标类型标签 */}
                <XStack alignItems="center" gap="$2">
                  <YStack
                    backgroundColor="$orange10"
                    paddingHorizontal="$2"
                    paddingVertical="$1"
                    borderRadius="$2"
                  >
                    <Text fontSize={11} fontWeight="600" color="white">
                      {getTargetTypeLabel(comment.targetType)}
                    </Text>
                  </YStack>
                  <Text fontSize={12} color="$color" opacity={0.5}>
                    点击查看
                  </Text>
                </XStack>
 
                {/* 评论内容 */}
                <Text fontSize={15} color={colors.text} lineHeight={22}>
                  {comment.content}
                </Text>
 
                {/* 评论信息 */}
                <XStack justifyContent="space-between" alignItems="center">
                  <XStack gap="$2" alignItems="center">
                    <IconSymbol name="clock" size={14} color={colors.icon} />
                    <Text fontSize={12} color={colors.icon}>
                      {formatTime(comment.createdAt)}
                    </Text>
                  </XStack>
                  <XStack gap="$1" alignItems="center">
                    <IconSymbol
                      name={comment.isLiked ? 'heart.fill' : 'heart.fill'}
                      size={14}
                      color={comment.isLiked ? '#FEBE98' : colors.icon}
                    />
                    <Text fontSize={12} color={colors.icon}>
                      {comment.likes || 0}
                    </Text>
                  </XStack>
                </XStack>
              </YStack>
            </Card>
          </TouchableOpacity>
        ))}
      </YStack>
    </ScrollView>
  );
});