feat(frontend): add blog editor and interactions
Some checks failed
Frontend CI/CD / build (push) Has been cancelled
Frontend CI/CD / deploy (push) Has been cancelled

This commit is contained in:
2026-06-08 21:31:07 +03:30
parent f2b4cfce1a
commit 49dcb1dd1b
10 changed files with 1019 additions and 35 deletions

View File

@@ -0,0 +1,242 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Bookmark, Heart, Loader2, MessageSquare, Send, Trash2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { api } from "@/lib/api";
import type * as Types from "@/lib/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Link } from "@/lib/router";
import { formatJalali, resolveErrorMessage } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";
type Props = {
slug: string;
initialLikes: number;
initialSaves: number;
initialComments: number;
};
function displayName(author: Types.CommentSchema["author"]) {
return [author.first_name, author.last_name].filter(Boolean).join(" ") || author.username;
}
export default function BlogPostInteractions({
slug,
initialLikes,
initialSaves,
initialComments,
}: Props) {
const { user, isAuthenticated } = useAuth();
const { toast } = useToast();
const [comments, setComments] = useState<Types.CommentSchema[]>([]);
const [interaction, setInteraction] = useState<Types.BlogInteractionSchema>({
liked: false,
saved: false,
likes_count: initialLikes,
saves_count: initialSaves,
comments_count: initialComments,
});
const [content, setContent] = useState("");
const [replyTo, setReplyTo] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const canModerate = Boolean(user?.is_staff || user?.is_superuser || user?.can_review_blog_posts);
const replyTarget = useMemo(
() => comments.find((comment) => comment.id === replyTo),
[comments, replyTo],
);
const loadComments = async () => {
const data = await api.getComments(slug);
setComments(data);
setInteraction((prev) => ({ ...prev, comments_count: data.length }));
};
useEffect(() => {
let mounted = true;
Promise.all([
api.getComments(slug),
isAuthenticated ? api.getBlogInteraction(slug).catch(() => null) : Promise.resolve(null),
])
.then(([commentData, interactionData]) => {
if (!mounted) return;
setComments(commentData);
if (interactionData) {
setInteraction(interactionData);
} else {
setInteraction((prev) => ({ ...prev, comments_count: commentData.length }));
}
})
.finally(() => {
if (mounted) setLoading(false);
});
return () => {
mounted = false;
};
}, [isAuthenticated, slug]);
const toggleLike = async () => {
if (!isAuthenticated) return;
setInteraction(await api.toggleLike(slug));
};
const toggleSave = async () => {
if (!isAuthenticated) return;
setInteraction(await api.toggleSave(slug));
};
const submitComment = async () => {
const trimmed = content.trim();
if (!trimmed) return;
try {
setSubmitting(true);
await api.createComment(slug, { content: trimmed, parent_id: replyTo ?? undefined });
setContent("");
setReplyTo(null);
await loadComments();
toast({ title: "نظر ثبت شد", variant: "success" });
} catch (error) {
toast({
title: "ثبت نظر ناموفق بود",
description: resolveErrorMessage(error, "دوباره تلاش کنید"),
variant: "destructive",
});
} finally {
setSubmitting(false);
}
};
const hideComment = async (commentId: number) => {
try {
await api.hideComment(commentId);
await loadComments();
toast({ title: "نظر مخفی شد", variant: "success" });
} catch (error) {
toast({
title: "حذف نظر ناموفق بود",
description: resolveErrorMessage(error, "دوباره تلاش کنید"),
variant: "destructive",
});
}
};
const renderComment = (comment: Types.CommentSchema, nested = false) => (
<div key={comment.id} className={nested ? "mr-6 border-r pr-4" : ""}>
<div className="rounded-2xl border border-border/70 bg-background/80 p-4 text-right">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
{canModerate ? (
<Button variant="ghost" size="sm" onClick={() => hideComment(comment.id)}>
<Trash2 className="h-4 w-4" />
</Button>
) : null}
{isAuthenticated ? (
<Button variant="ghost" size="sm" onClick={() => setReplyTo(comment.id)}>
پاسخ
</Button>
) : null}
</div>
<div>
<p className="font-medium">{displayName(comment.author)}</p>
<p className="text-xs text-muted-foreground">{formatJalali(comment.created_at, false)}</p>
</div>
</div>
<p className="mt-3 whitespace-pre-wrap leading-7 text-sm">{comment.content}</p>
</div>
{comment.replies?.length ? (
<div className="mt-3 space-y-3">
{comment.replies.map((reply) => renderComment(reply, true))}
</div>
) : null}
</div>
);
return (
<Card className="mt-8 rounded-[1.75rem] border border-border/70 shadow-sm" dir="rtl">
<CardHeader className="text-right">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-2">
<Button
variant={interaction.saved ? "default" : "outline"}
onClick={toggleSave}
disabled={!isAuthenticated}
>
<Bookmark className="ml-2 h-4 w-4" />
ذخیره
<Badge className="mr-2" variant="secondary">{interaction.saves_count}</Badge>
</Button>
<Button
variant={interaction.liked ? "default" : "outline"}
onClick={toggleLike}
disabled={!isAuthenticated}
>
<Heart className="ml-2 h-4 w-4" />
پسندیدن
<Badge className="mr-2" variant="secondary">{interaction.likes_count}</Badge>
</Button>
</div>
<div>
<CardTitle className="flex items-center justify-end gap-2">
دیدگاهها
<MessageSquare className="h-5 w-5 text-primary" />
</CardTitle>
<CardDescription className="mt-2">
{interaction.comments_count} نظر برای این نوشته ثبت شده است.
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-5">
{!isAuthenticated ? (
<div className="rounded-2xl border border-dashed border-border/70 bg-muted/20 p-5 text-center text-sm text-muted-foreground">
برای پسندیدن، ذخیرهکردن یا ثبت نظر باید وارد حساب شوید.
<Button asChild className="mr-3" size="sm">
<Link to="/auth">ورود / ثبتنام</Link>
</Button>
</div>
) : (
<div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
{replyTarget ? (
<div className="mb-3 flex items-center justify-between rounded-xl bg-background px-3 py-2 text-sm">
<Button variant="ghost" size="sm" onClick={() => setReplyTo(null)}>
لغو پاسخ
</Button>
<span>پاسخ به {displayName(replyTarget.author)}</span>
</div>
) : null}
<Textarea
value={content}
onChange={(event) => setContent(event.target.value)}
placeholder="نظر خود را بنویسید..."
className="min-h-28 text-right"
/>
<div className="mt-3 flex justify-end">
<Button onClick={submitComment} disabled={submitting || !content.trim()}>
{submitting ? <Loader2 className="ml-2 h-4 w-4 animate-spin" /> : <Send className="ml-2 h-4 w-4" />}
ثبت نظر
</Button>
</div>
</div>
)}
{loading ? (
<div className="flex justify-center py-8 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
) : comments.length ? (
<div className="space-y-4">{comments.map((comment) => renderComment(comment))}</div>
) : (
<div className="rounded-2xl border border-dashed border-border/70 p-8 text-center text-sm text-muted-foreground">
هنوز نظری ثبت نشده است.
</div>
)}
</CardContent>
</Card>
);
}