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

94 lines
3.1 KiB
TypeScript

"use client"
import { Heart } from "lucide-react"
import { useMemo, useState } from "react"
import { addComment, toggleCommentLike } from "@/lib/api/comments"
import { useRequireAuth } from "@/lib/use-require-auth"
import { useCommentStore } from "@/store/comments"
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
import { Button } from "./ui/button"
import { Textarea } from "./ui/textarea"
interface PostCommentsProps {
postId: string
}
export function PostComments({ postId }: PostCommentsProps) {
const allComments = useCommentStore((state) => state.comments)
const comments = useMemo(
() => allComments.filter((comment) => comment.postId === postId),
[allComments, postId],
)
const [content, setContent] = useState("")
const { requireAuth } = useRequireAuth()
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
const decision = addComment(postId, nextContent)
if (!decision.ok) return
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"
onClick={() =>
requireAuth(() => {
toggleCommentLike(comment.id)
})
}
>
<Heart
className={`h-3 w-3 ${comment.liked ? "fill-red-500 text-red-500" : ""}`}
/>
{comment.likeCount}
</button>
</div>
</div>
))}
</div>
)}
</div>
)
}