|
1 | 1 | import { AvatarImage, AvatarFallback, Avatar } from "@/components/ui/avatar"; |
2 | 2 | import { Product, Review as ReviewType } from "@/lib/types"; |
3 | | -import ms from "ms"; |
4 | 3 | import { FiveStarRating } from "./five-star-rating"; |
5 | 4 | import { AIReviewSummary } from "./ai-review-summary"; |
6 | 5 |
|
7 | 6 | export async function Reviews({ product }: { product: Product }) { |
| 7 | + // Sort reviews by date descending (newest first) |
| 8 | + const sortedReviews = [...product.reviews].sort( |
| 9 | + (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime() |
| 10 | + ); |
8 | 11 | return ( |
9 | 12 | <div className="mx-auto px-4 md:px-6 max-w-2xl grid gap-12"> |
10 | 13 | <AIReviewSummary product={product} /> |
11 | | - {product.reviews.map((review) => ( |
| 14 | + {sortedReviews.map((review) => ( |
12 | 15 | <div key={review.review}> |
13 | 16 | <Review key={review.review} review={review} /> |
14 | 17 | </div> |
@@ -52,10 +55,24 @@ export function Review({ review }: { review: ReviewType }) { |
52 | 55 | * You probably want to wrap the parent element of this component with `suppressHydrationWarning` |
53 | 56 | */ |
54 | 57 | const timeAgo = (date: Date, suffix = true) => { |
55 | | - if (Date.now() - date.getTime() < 1000) { |
56 | | - return "Just now"; |
57 | | - } |
58 | | - return `${ms(Date.now() - date.getTime(), { long: true })}${ |
59 | | - suffix ? " ago" : "" |
60 | | - }`; |
| 58 | + const now = new Date(); |
| 59 | + const seconds = Math.floor((now.getTime() - date.getTime()) / 1000); |
| 60 | + |
| 61 | + if (seconds < 60) return "Just now"; |
| 62 | + const minutes = Math.floor(seconds / 60); |
| 63 | + if (minutes < 60) |
| 64 | + return `${minutes} minute${ |
| 65 | + minutes !== 1 ? "s" : "" |
| 66 | + }${suffix ? " ago" : ""}`; |
| 67 | + const hours = Math.floor(minutes / 60); |
| 68 | + if (hours < 24) |
| 69 | + return `${hours} hour${hours !== 1 ? "s" : ""}${suffix ? " ago" : ""}`; |
| 70 | + const days = Math.floor(hours / 24); |
| 71 | + if (days < 30) |
| 72 | + return `${days} day${days !== 1 ? "s" : ""}${suffix ? " ago" : ""}`; |
| 73 | + const months = Math.floor(days / 30); |
| 74 | + if (months < 12) |
| 75 | + return `${months} month${months !== 1 ? "s" : ""}${suffix ? " ago" : ""}`; |
| 76 | + const years = Math.floor(months / 12); |
| 77 | + return `${years} year${years !== 1 ? "s" : ""}${suffix ? " ago" : ""}`; |
61 | 78 | }; |
0 commit comments