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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 1x 5x 5x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 4x 5x 5x 5x 5x 25x 25x | import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Pressable } from 'react-native';
import { Text, TextArea, XStack, YStack } from 'tamagui';
import { Button } from '@/src/design-system/components';
import { IconSymbol } from '@/src/components/ui/IconSymbol';
import { useResponsiveLayout } from '@/src/hooks/useResponsiveLayout';
import { supabaseCatfoodService, supabaseCommentService } from '@/src/lib/supabase';
import { useCatFoodStore } from '@/src/store/catFoodStore';
import { warningScale, neutralScale, successScale, errorScale } from '@/src/design-system/tokens';
import { showAlert, toast } from '@/src/components/dialogs';
interface RatingSectionProps {
catfoodId: number;
}
export function RatingSection({ catfoodId }: RatingSectionProps) {
const [myRating, setMyRating] = useState<number>(0);
const [myComment, setMyComment] = useState<string>('');
const [myRatingId, setMyRatingId] = useState<number | null>(null);
const [hoverRating, setHoverRating] = useState<number>(0);
const [loading, setLoading] = useState(false);
const [hasRated, setHasRated] = useState(false);
const updateCatFood = useCatFoodStore((state) => state.updateCatFood);
const getCatFoodById = useCatFoodStore((state) => state.getCatFoodById);
const { width, isExtraSmallScreen } = useResponsiveLayout();
// 响应式计算星星尺寸和间距
const starConfig = useMemo(() => {
// 计算可用宽度(减去卡片内边距和其他元素)
const cardPadding = 32; // $4 的像素值
const ratingDisplayWidth = myRating > 0 ? 60 : 0; // 评分显示的宽度
const availableWidth = width - cardPadding * 2 - ratingDisplayWidth - 40; // 40px 留作余量
// 计算每个星星的最大宽度
const minStarSize = 36; // 最小星星尺寸
const maxStarSize = 48; // 最大星星尺寸
const starCount = 5;
const minGap = 4; // 最小间距
const maxGap = 8; // 最大间距
// 根据可用宽度动态计算
let starSize = maxStarSize;
let gap = maxGap;
// 如果空间不够,逐步缩小
while (
starSize >= minStarSize &&
starSize * starCount + gap * (starCount - 1) > availableWidth
) {
starSize -= 2;
if (starSize < 40) {
gap = minGap;
}
}
return {
size: Math.max(minStarSize, starSize),
iconSize: Math.max(20, Math.floor(starSize * 0.58)),
gap: gap,
};
}, [width, myRating]);
// 加载用户的评分
useEffect(() => {
const loadMyRating = async () => {
try {
console.log('🔍 开始加载用户评分...');
const { data: rating, error } = await supabaseCatfoodService.getUserRating(
String(catfoodId)
);
Iif (error) {
console.log('ℹ️ 用户尚未评分(正常)');
return;
}
if (rating) {
console.log('✅ 加载到已有评分:', rating);
setMyRating(rating.score);
setMyComment(rating.comment || '');
setMyRatingId(rating.id);
setHasRated(true);
} else {
console.log('ℹ️ 用户尚未评分');
}
} catch (error: any) {
console.error('⚠️ 加载评分时出错:', error);
}
};
loadMyRating();
}, [catfoodId]);
// 处理评分(无弹窗,静默更新)
const handleRate = useCallback(
async (score: number) => {
console.log('🌟 点击评分:', score);
if (loading) {
console.log('⏳ 正在加载中,忽略点击');
return;
}
// 保存旧评分用于回滚和计算
const oldScore = myRating;
const wasRated = hasRated;
try {
setLoading(true);
// 立即更新UI(乐观更新)
setMyRating(score);
setHasRated(true);
console.log('📡 开始提交评分...');
const { error } = await supabaseCatfoodService.createRating(
String(catfoodId),
score,
myComment
);
if (error) {
throw new Error(error.message);
}
console.log('✅ 评分提交成功');
// 🚀 乐观更新:立即更新评分统计,无需刷新整个页面
const currentCatFood = getCatFoodById(catfoodId);
if (currentCatFood) {
let newScore: number;
let newCountNum: number;
if (wasRated) {
// 更新评分:替换旧评分
newCountNum = currentCatFood.countNum;
newScore =
(currentCatFood.score * currentCatFood.countNum - oldScore + score) / newCountNum;
} else {
// 首次评分:增加计数
newCountNum = currentCatFood.countNum + 1;
newScore = (currentCatFood.score * currentCatFood.countNum + score) / newCountNum;
}
updateCatFood(catfoodId, {
score: Number(newScore.toFixed(2)),
countNum: newCountNum,
});
console.log('✨ 乐观更新完成:', {
type: wasRated ? '更新评分' : '首次评分',
newScore: newScore.toFixed(2),
newCountNum,
});
}
// Realtime 订阅会自动同步服务器的最终数据
} catch (error: any) {
console.error('❌ 评分失败:', error);
// 回滚UI
setMyRating(oldScore);
setHasRated(wasRated);
// 只在出错时才弹窗提示
let errorMessage = '评分失败,请稍后重试';
if (error.message?.includes('未登录')) {
errorMessage = '请先登录后再评分';
} else if (error.message) {
errorMessage = error.message;
}
showAlert({
title: '评分失败',
message: errorMessage,
buttons: [{ text: '确定' }],
});
} finally {
setLoading(false);
}
},
[catfoodId, myComment, myRating, hasRated, loading, updateCatFood, getCatFoodById]
);
// 处理评论提交
const handleSubmit = useCallback(async () => {
if (myRating === 0) {
toast.warning('请先选择评分');
return;
}
if (loading) return;
try {
setLoading(true);
// 提交评分
const { error: ratingError } = await supabaseCatfoodService.createRating(
String(catfoodId),
myRating,
myComment
);
if (ratingError) {
throw new Error(ratingError.message);
}
// 如果有评论内容,同时创建评论记录(显示在评论区)
if (myComment.trim()) {
try {
const { error: commentError } = await supabaseCommentService.createComment({
targetType: 'catfood',
targetId: catfoodId,
content: `⭐ ${myRating}星评价:${myComment}`,
});
if (commentError) {
console.warn('创建评论失败,但评分已成功:', commentError);
}
} catch (commentError) {
console.warn('创建评论失败,但评分已成功:', commentError);
// 评论创建失败不影响评分成功
}
}
setHasRated(true);
// 🚀 乐观更新:不刷新页面,Realtime 会自动同步最终数据
// 如果是首次评分,需要手动更新统计
if (!hasRated) {
const currentCatFood = getCatFoodById(catfoodId);
if (currentCatFood) {
const newCountNum = currentCatFood.countNum + 1;
const newScore =
(currentCatFood.score * currentCatFood.countNum + myRating) / newCountNum;
updateCatFood(catfoodId, {
score: Number(newScore.toFixed(2)),
countNum: newCountNum,
});
console.log('✨ 乐观更新完成 (handleSubmit)');
}
}
// 只有首次评分或提交评论时才提示
if (!hasRated || myComment.trim()) {
toast.success(myComment.trim() ? '评分和评论已发布!' : '评分成功!');
}
// 否则静默更新,不弹窗
} catch (error: any) {
console.error('提交评分失败:', error);
toast.error('提交失败,请稍后重试');
} finally {
setLoading(false);
}
}, [catfoodId, myRating, myComment, loading, hasRated, updateCatFood, getCatFoodById]);
// 处理删除评分
const handleDelete = useCallback(async () => {
if (!myRatingId) {
toast.warning('没有可删除的评分');
return;
}
showAlert({
title: '确认删除',
message: '确定要删除您的评分吗?删除后猫粮的平均分会重新计算。',
buttons: [
{ text: '取消', style: 'cancel' },
{
text: '删除',
style: 'destructive',
onPress: async () => {
try {
setLoading(true);
console.log('🗑️ 开始删除评分,ID:', myRatingId);
// 删除评分
const { error } = await supabaseCatfoodService.deleteRating(String(catfoodId));
if (error) {
throw new Error(error.message);
}
console.log('✅ 评分删除成功');
// 重置状态
setMyRating(0);
setMyComment('');
setMyRatingId(null);
setHasRated(false);
// 🚀 乐观更新:立即更新评分统计
const currentCatFood = getCatFoodById(catfoodId);
if (currentCatFood && currentCatFood.countNum > 0) {
const newCountNum = currentCatFood.countNum - 1;
const newScore =
newCountNum > 0
? (currentCatFood.score * currentCatFood.countNum - myRating) / newCountNum
: 0;
updateCatFood(catfoodId, {
score: Number(newScore.toFixed(2)),
countNum: newCountNum,
});
console.log('✨ 乐观更新完成 (删除评分)');
}
// Realtime 订阅会自动同步服务器的最终数据
// 静默删除,不弹窗提示
} catch (error: any) {
console.error('❌ 删除评分失败:', error);
toast.error(error.message || '删除评分失败,请稍后重试');
} finally {
setLoading(false);
}
},
},
],
});
}, [myRatingId, catfoodId, myRating, updateCatFood, getCatFoodById]);
return (
<YStack
marginHorizontal="$3"
marginBottom="$3"
borderRadius={20}
backgroundColor="white"
overflow="hidden"
borderWidth={1}
borderColor={neutralScale.neutral3}
>
{/* 标题栏 */}
<XStack
padding="$4"
alignItems="center"
gap="$3"
borderBottomWidth={1}
borderBottomColor={neutralScale.neutral2}
>
<YStack
width={44}
height={44}
borderRadius={22}
backgroundColor={warningScale.warning2}
alignItems="center"
justifyContent="center"
>
<IconSymbol name="star.fill" size={22} color={warningScale.warning6} />
</YStack>
<YStack flex={1}>
<Text fontSize="$5" fontWeight="700" color={neutralScale.neutral12}>
{hasRated ? '我的评分' : '给这款猫粮打分'}
</Text>
<Text fontSize={11} color={neutralScale.neutral8} marginTop={2}>
{hasRated ? 'My Rating' : 'Rate This Product'}
</Text>
</YStack>
</XStack>
<YStack padding="$4" gap="$4">
{/* 星星评分 */}
<YStack gap="$3">
<Text fontSize="$3" color={neutralScale.neutral10} fontWeight="600">
选择评分
</Text>
<XStack
gap={starConfig.gap}
alignItems="center"
flexWrap="nowrap"
justifyContent="flex-start"
>
{[1, 2, 3, 4, 5].map((star) => {
const isActive = star <= (hoverRating || myRating);
return (
<Pressable
key={star}
onPress={() => {
console.log('🎯 Pressable onPress 触发,星级:', star);
handleRate(star);
}}
onPressIn={() => {
console.log('👆 onPressIn:', star);
setHoverRating(star);
}}
onPressOut={() => {
console.log('👇 onPressOut');
setHoverRating(0);
}}
disabled={loading}
style={{ zIndex: 10 }}
>
<YStack
width={starConfig.size}
height={starConfig.size}
alignItems="center"
justifyContent="center"
backgroundColor={isActive ? warningScale.warning2 : neutralScale.neutral2}
borderRadius={starConfig.size / 2}
borderWidth={2}
borderColor={isActive ? warningScale.warning5 : neutralScale.neutral4}
pressStyle={{ scale: 0.9 }}
pointerEvents="none"
>
<IconSymbol
name={isActive ? 'star.fill' : 'star'}
size={starConfig.iconSize}
color={isActive ? warningScale.warning6 : neutralScale.neutral6}
/>
</YStack>
</Pressable>
);
})}
{myRating > 0 && (
<YStack
paddingHorizontal={isExtraSmallScreen ? '$2.5' : '$3'}
paddingVertical="$2"
backgroundColor={warningScale.warning6}
borderRadius={16}
marginLeft="$2"
>
<Text color="white" fontSize={isExtraSmallScreen ? '$3' : '$4'} fontWeight="800">
{myRating}.0
</Text>
</YStack>
)}
</XStack>
{myRating === 0 && (
<Text fontSize="$2" color={neutralScale.neutral7}>
点击星星进行评分
</Text>
)}
</YStack>
{/* 评论输入 */}
{myRating > 0 && (
<>
<YStack gap="$2">
<Text fontSize="$3" color={neutralScale.neutral10} fontWeight="600">
评价内容(选填)
</Text>
<TextArea
placeholder="说说你的使用感受吧..."
value={myComment}
onChangeText={setMyComment}
numberOfLines={4}
backgroundColor={neutralScale.neutral1}
borderColor={neutralScale.neutral4}
borderRadius={12}
padding="$3"
fontSize="$3"
maxLength={500}
/>
<Text fontSize="$1" color={neutralScale.neutral7} textAlign="right">
{myComment.length}/500
</Text>
</YStack>
{/* 提交按钮 */}
<Button
size="$4"
height={48}
fontSize={16}
backgroundColor={warningScale.warning6}
borderWidth={0}
borderRadius={12}
onPress={handleSubmit}
disabled={loading}
pressStyle={{
scale: 0.98,
backgroundColor: warningScale.warning7,
}}
icon={
<IconSymbol
name={hasRated ? 'checkmark.circle.fill' : 'paperplane.fill'}
size={20}
color="white"
/>
}
>
<Text color="white" fontSize="$4" fontWeight="700">
{loading ? '提交中...' : hasRated ? '更新评分' : '提交评分'}
</Text>
</Button>
</>
)}
{/* 提示信息 */}
{hasRated && (
<YStack gap="$3">
<YStack
padding="$3"
backgroundColor={successScale.success1}
borderRadius={12}
borderWidth={1}
borderColor={successScale.success4}
>
<XStack alignItems="center" gap="$2">
<IconSymbol name="checkmark.circle.fill" size={18} color={successScale.success7} />
<Text fontSize="$2" color={successScale.success9} fontWeight="500">
您已评分,可以随时修改或删除
</Text>
</XStack>
</YStack>
{/* 删除评分按钮 */}
<Button
size="$3"
height={40}
fontSize={14}
backgroundColor="transparent"
borderWidth={1.5}
borderColor={errorScale.error5}
borderRadius={10}
onPress={handleDelete}
disabled={loading}
pressStyle={{
scale: 0.98,
backgroundColor: errorScale.error1,
}}
icon={<IconSymbol name="trash" size={16} color={errorScale.error7} />}
>
<Text color={errorScale.error7} fontSize="$3" fontWeight="600">
删除我的评分
</Text>
</Button>
</YStack>
)}
</YStack>
</YStack>
);
}
|