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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 15x 15x 15x 13x 2x 2x 15x 15x 15x 15x 15x 15x 1x 1x 15x 15x 15x 15x 1x 1x 14x 14x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 26x 26x 26x 26x 26x 26x 26x 26x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 13x 13x 13x 13x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 20x 20x 20x 20x 20x 20x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 4x 4x 4x 4x 4x | 'use client';
import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { clientLogger } from '@/lib/logging/clientLogger';
import { StarRating } from '@/components/ui/StarRating';
import { Icon } from '@/components/ui/icons';
import { Button } from '@/components/ui/Button';
import { ReviewCard, ReviewCardSkeleton, ReviewData } from './ReviewCard';
import { cn } from '@/lib/core';
export interface ReviewStats {
averageRating: number;
totalReviews: number;
distribution: Record<number, number>;
}
export interface ReviewListProps {
productId: number;
initialReviews?: ReviewData[];
initialStats?: ReviewStats;
showForm?: boolean;
className?: string;
}
type SortOption = 'recent' | 'helpful' | 'rating_high' | 'rating_low';
/**
* ReviewList - Displays product reviews with stats and filtering
*
* Features:
* - Rating summary with distribution chart
* - Sortable reviews list
* - Pagination
* - Helpful voting
* - Loading states
*
* @example
* ```tsx
* <ReviewList productId={123} />
* ```
*/
export function ReviewList({
productId,
initialReviews,
initialStats,
className}: ReviewListProps) {
const { data: session } = useSession();
const [reviews, setReviews] = useState<ReviewData[]>(initialReviews || []);
const [stats, setStats] = useState<ReviewStats | null>(initialStats || null);
const [loading, setLoading] = useState(!initialReviews);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [sortBy, setSortBy] = useState<SortOption>('recent');
const [userVotes, setUserVotes] = useState<Record<number, boolean | null>>({});
const [votingId, setVotingId] = useState<number | null>(null);
const fetchReviews = useCallback(async () => {
try {
setLoading(true);
const response = await fetch(
`/api/products/${productId}/reviews?page=${page}&limit=10&sortBy=${sortBy}`
);
const data = await response.json();
if (data.success) {
setReviews(data.data.reviews);
setStats(data.data.stats);
setTotalPages(data.data.pagination.pages);
}
} catch (error) {
clientLogger.error('Failed to fetch reviews', error instanceof Error ? error : new Error(String(error)), {
productId,
page,
sortBy
});
} finally {
setLoading(false);
}
}, [productId, page, sortBy]);
useEffect(() => {
if (!initialReviews || page > 1 || sortBy !== 'recent') {
fetchReviews();
}
}, [fetchReviews, initialReviews, page, sortBy]);
const handleHelpful = async (reviewId: number, helpful: boolean) => {
if (!session) {
return;
}
setVotingId(reviewId);
try {
const response = await fetch(`/api/reviews/${reviewId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'helpful', helpful })});
const data = await response.json();
if (data.success) {
setUserVotes((prev) => ({ ...prev, [reviewId]: helpful }));
setReviews((prev) =>
prev.map((r) =>
r.id === reviewId
? {
...r,
helpfulCount: data.data.helpfulCount,
notHelpfulCount: data.data.notHelpfulCount}
: r
)
);
}
} catch (error) {
clientLogger.error('Failed to mark review helpful', error instanceof Error ? error : new Error(String(error)), {
reviewId,
helpful
});
} finally {
setVotingId(null);
}
};
const handleSortChange = (newSort: SortOption) => {
setSortBy(newSort);
setPage(1);
};
// Loading state
if (loading && !reviews.length) {
return <ReviewListSkeleton />;
}
// Empty state
if (!stats?.totalReviews) {
return (
<div className={cn('text-center py-12', className)}>
<Icon name="star" size={48} className="text-gray-300 mx-auto mb-4" />
<p className="text-gray-600 dark:text-gray-400 text-lg">No reviews yet</p>
<p className="text-gray-500 dark:text-gray-500 text-sm mt-1">
Be the first to share your experience with this product!
</p>
</div>
);
}
return (
<div className={cn('space-y-8 min-h-[600px]', className)}>
{/* Summary Section */}
<div className="flex flex-col md:flex-row gap-8 p-6 bg-gray-50 rounded-lg">
{/* Average Rating */}
<div className="text-center md:text-left">
<div className="text-5xl font-bold text-gray-900">
{stats.averageRating.toFixed(1)}
</div>
<div className="mt-2">
<StarRating rating={stats.averageRating} size="lg" showCount={false} />
</div>
<div className="text-sm text-gray-600 dark:text-gray-400 mt-2">
Based on {stats.totalReviews} review{stats.totalReviews !== 1 ? 's' : ''}
</div>
</div>
{/* Rating Distribution */}
<div className="flex-1">
<RatingDistribution
distribution={stats.distribution}
totalReviews={stats.totalReviews}
/>
</div>
</div>
{/* Sort Controls */}
<div className="flex justify-between items-center">
<h3 className="font-semibold text-lg">Customer Reviews</h3>
<div className="flex items-center gap-2">
<label htmlFor="sort-reviews" className="text-sm text-gray-600 dark:text-gray-400">
Sort by:
</label>
<select
id="sort-reviews"
value={sortBy}
onChange={(e) => handleSortChange(e.target.value as SortOption)}
className="border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="recent">Most Recent</option>
<option value="helpful">Most Helpful</option>
<option value="rating_high">Highest Rated</option>
<option value="rating_low">Lowest Rated</option>
</select>
</div>
</div>
{/* Reviews List */}
<div className="space-y-6">
{reviews.map((review) => (
<ReviewCard
key={review.id}
review={review}
onHelpful={session ? handleHelpful : undefined}
userVote={userVotes[review.id]}
isLoading={votingId === review.id}
showActions={!!session}
/>
))}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex justify-center items-center gap-2 pt-4">
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1 || loading}
>
<Icon name="chevron-left" size={16} />
Previous
</Button>
<span className="text-sm text-gray-600 px-4">
Page {page} of {totalPages}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={page === totalPages || loading}
>
Next
<Icon name="chevron-right" size={16} />
</Button>
</div>
)}
</div>
);
}
/**
* Rating Distribution Bar Chart
*/
function RatingDistribution({
distribution,
totalReviews}: {
distribution: Record<number, number>;
totalReviews: number;
}) {
return (
<div className="space-y-2">
{[5, 4, 3, 2, 1].map((rating) => {
const count = distribution[rating] || 0;
const percentage = totalReviews > 0 ? (count / totalReviews) * 100 : 0;
return (
<div key={rating} className="flex items-center gap-2">
<span className="w-3 text-sm text-gray-600">{rating}</span>
<Icon name="star" size={14} className="text-yellow-400" />
<div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
<div
className="h-full bg-yellow-400 rounded-full transition-all duration-300"
style={{ width: `${percentage}%` }}
/>
</div>
<span className="w-8 text-sm text-gray-600 dark:text-gray-400 text-right">{count}</span>
</div>
);
})}
</div>
);
}
/**
* ReviewList Loading Skeleton
*/
export function ReviewListSkeleton() {
return (
<div className="space-y-8 min-h-[600px] animate-pulse">
{/* Stats Skeleton */}
<div className="flex flex-col md:flex-row gap-8 p-6 bg-gray-50 rounded-lg">
<div className="text-center md:text-left">
<div className="h-12 w-20 bg-gray-200 rounded mx-auto md:mx-0" />
<div className="h-5 w-32 bg-gray-200 rounded mt-2 mx-auto md:mx-0" />
<div className="h-4 w-24 bg-gray-200 rounded mt-2 mx-auto md:mx-0" />
</div>
<div className="flex-1 space-y-2">
{[5, 4, 3, 2, 1].map((i) => (
<div key={i} className="flex items-center gap-2">
<div className="w-3 h-4 bg-gray-200 rounded" />
<div className="w-4 h-4 bg-gray-200 rounded" />
<div className="flex-1 h-2 bg-gray-200 rounded-full" />
<div className="w-8 h-4 bg-gray-200 rounded" />
</div>
))}
</div>
</div>
{/* Sort Controls Skeleton */}
<div className="flex justify-between items-center">
<div className="h-6 w-40 bg-gray-200 rounded" />
<div className="h-8 w-32 bg-gray-200 rounded" />
</div>
{/* Reviews Skeleton */}
<div className="space-y-6">
{[1, 2, 3].map((i) => (
<ReviewCardSkeleton key={i} />
))}
</div>
</div>
);
}
|