Files
juwan-frontend/components/post-comments.tsx
T

100 lines
3.3 KiB
TypeScript

"use client"
import { Heart } from "lucide-react"
import { useState } from "react"
import { generateId } from "@/lib/id"
import type { Comment } from "@/lib/types"
import { useRequireAuth } from "@/lib/use-require-auth"
import { useAuthStore } from "@/store/auth"
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
import { Button } from "./ui/button"
import { Textarea } from "./ui/textarea"
interface PostCommentsProps {
initialComments: Comment[]
postId: string
}
export function PostComments({ initialComments, postId }: PostCommentsProps) {
const [comments, setComments] = useState(initialComments)
const [content, setContent] = useState("")
const { requireAuth } = useRequireAuth()
const user = useAuthStore((s) => s.user)
return (
<div className="space-y-4">
<h2 className="font-semibold"> ({comments.length})</h2>
<form
className="flex gap-3"
onSubmit={(event) => {
event.preventDefault()
requireAuth(() => {
const nextContent = content.trim()
if (!nextContent) return
if (!user) return
const createdAt = new Date().toISOString()
setComments((prev) => [
...prev,
{
id: generateId(`comment-${postId}`),
postId,
author: user,
content: nextContent,
likeCount: 0,
liked: false,
createdAt,
},
])
setContent("")
})
}}
>
<Textarea
placeholder="写下你的评论..."
className="flex-1"
rows={2}
value={content}
onChange={(event) => setContent(event.target.value)}
/>
<Button className="self-end" disabled={!content.trim()}>
</Button>
</form>
{comments.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8"></p>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id} className="flex gap-3">
<Avatar className="h-8 w-8">
<AvatarImage src={comment.author.avatar} />
<AvatarFallback>{comment.author.nickname[0]}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-0.5">
<span className="text-sm font-medium">{comment.author.nickname}</span>
<span className="text-xs text-muted-foreground">
{new Date(comment.createdAt).toLocaleString("zh-CN")}
</span>
</div>
<p className="text-sm">{comment.content}</p>
<button
type="button"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground mt-1 transition-colors"
>
<Heart
className={`h-3 w-3 ${comment.liked ? "fill-red-500 text-red-500" : ""}`}
/>
{comment.likeCount}
</button>
</div>
</div>
))}
</div>
)}
</div>
)
}