tahamajs/IE / Projects /front /src /components /blog /BlogComments.tsx
tahamajs's picture
download
raw
9.26 kB
import { useState, useEffect } from "react";
import { useAuth } from "@/context/AuthContext";
import { blogCommentApi } from "@/lib/api";
import { MessageSquare, Trash2, Send, CornerDownRight, ThumbsUp } from "lucide-react";
import { toast } from "react-toastify";
import { motion, AnimatePresence } from "framer-motion";
interface BlogComment {
id: number;
postId: number;
content: string;
parentId?: number | null;
author: {
id: number;
username: string;
avatarUrl?: string;
};
createdAt: string;
likesCount?: number;
likedByMe?: boolean;
replies?: BlogComment[];
}
interface BlogCommentsProps {
postId: number;
}
export function BlogComments({ postId }: BlogCommentsProps) {
const { user } = useAuth();
const [comments, setComments] = useState<BlogComment[]>([]);
const [loading, setLoading] = useState(true);
const [commentText, setCommentText] = useState("");
const [replyToId, setReplyToId] = useState<number | null>(null);
const [replyText, setReplyText] = useState("");
const [submitting, setSubmitting] = useState(false);
const fetchComments = async () => {
try {
setLoading(true);
const response = await blogCommentApi.getByPost(postId);
const data = response.data;
const commentList = Array.isArray(data) ? data : data?.items || [];
setComments(commentList);
} catch (err) {
console.error("Error fetching blog comments:", err);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (postId) {
fetchComments();
}
}, [postId]);
const handleAddComment = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) {
toast.error("Please login to comment");
return;
}
if (!commentText.trim()) return;
setSubmitting(true);
try {
await blogCommentApi.add({
postId,
content: commentText.trim(),
});
toast.success("Comment added!");
setCommentText("");
fetchComments();
} catch (err) {
toast.error("Failed to add comment");
} finally {
setSubmitting(false);
}
};
const handleAddReply = async (parentId: number) => {
if (!user) {
toast.error("Please login to reply");
return;
}
if (!replyText.trim()) return;
setSubmitting(true);
try {
await blogCommentApi.add({
postId,
content: replyText.trim(),
parentId,
});
toast.success("Reply added!");
setReplyText("");
setReplyToId(null);
fetchComments();
} catch (err) {
toast.error("Failed to add reply");
} finally {
setSubmitting(false);
}
};
const handleDeleteComment = async (commentId: number) => {
if (!window.confirm("Are you sure you want to delete this comment?")) return;
try {
await blogCommentApi.delete(commentId);
toast.success("Comment deleted");
fetchComments();
} catch (err) {
toast.error("Failed to delete comment");
}
};
const handleLikeToggle = async (comment: BlogComment) => {
if (!user) {
toast.error("Please login to like comments");
return;
}
try {
if (comment.likedByMe) {
await blogCommentApi.unlike(comment.id);
} else {
await blogCommentApi.like(comment.id);
}
fetchComments();
} catch (err) {
toast.error("Failed to update comment status");
}
};
const renderComment = (comment: BlogComment, isReply = false) => {
const isOwner = user && user.id === comment.author.id;
return (
<motion.div
key={comment.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`relative p-5 rounded-2xl border backdrop-blur-md transition-all ${
isReply
? "bg-slate-900/20 border-white/5 ml-8 mt-3"
: "bg-slate-950/40 border-white/10 mt-4"
}`}
>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/20 text-primary font-bold text-sm uppercase">
{comment.author.username.slice(0, 2)}
</div>
<div>
<div className="font-semibold text-gray-950 dark:text-white">
{comment.author.username}
</div>
<div className="text-xs text-gray-500">
{new Date(comment.createdAt).toLocaleDateString(undefined, {
hour: "2-digit",
minute: "2-digit",
})}
</div>
</div>
</div>
{isOwner && (
<button
onClick={() => handleDeleteComment(comment.id)}
className="text-gray-400 hover:text-red-500 transition-colors"
>
<Trash2 className="h-4.5 w-4.5" />
</button>
)}
</div>
<p className="mt-3 text-sm text-gray-700 dark:text-gray-300 leading-relaxed pl-1">
{comment.content}
</p>
<div className="mt-4 flex items-center gap-4 text-xs">
<button
onClick={() => handleLikeToggle(comment)}
className={`flex items-center gap-1.5 font-medium transition ${
comment.likedByMe
? "text-primary scale-110"
: "text-gray-500 hover:text-primary dark:text-gray-400"
}`}
>
<ThumbsUp className="h-4 w-4" />
<span>{comment.likesCount ?? 0}</span>
</button>
{!isReply && (
<button
onClick={() => setReplyToId(replyToId === comment.id ? null : comment.id)}
className="flex items-center gap-1 text-gray-500 hover:text-primary dark:text-gray-400 transition"
>
<MessageSquare className="h-4 w-4" />
<span>Reply</span>
</button>
)}
</div>
{replyToId === comment.id && (
<div className="mt-4 flex items-center gap-2 pl-2">
<CornerDownRight className="h-4 w-4 text-gray-400 flex-shrink-0" />
<input
type="text"
value={replyText}
onChange={(e) => setReplyText(e.target.value)}
placeholder="Write a reply..."
className="flex-1 bg-white/5 border border-white/10 rounded-xl px-4 py-2 text-sm text-white focus:outline-none focus:border-primary transition"
/>
<button
disabled={submitting}
onClick={() => handleAddReply(comment.id)}
className="bg-primary text-white rounded-xl p-2 hover:bg-primary/90 disabled:opacity-50 transition"
>
<Send className="h-4 w-4" />
</button>
</div>
)}
{comment.replies && comment.replies.length > 0 && (
<div className="border-l border-white/5 pl-2 mt-2">
{comment.replies.map((reply) => renderComment(reply, true))}
</div>
)}
</motion.div>
);
};
return (
<div className="mt-12 rounded-[2rem] border border-white/10 bg-slate-950/45 p-6 backdrop-blur-xl">
<h3 className="text-xl font-bold flex items-center gap-2 mb-6">
<MessageSquare className="h-5 w-5 text-primary" />
<span>Comments ({comments.length})</span>
</h3>
{user ? (
<form onSubmit={handleAddComment} className="mb-8 flex gap-3">
<input
type="text"
value={commentText}
onChange={(e) => setCommentText(e.target.value)}
placeholder="Add to the discussion..."
className="flex-1 bg-white/5 border border-white/10 rounded-2xl px-5 py-3 text-sm text-white focus:outline-none focus:border-primary transition"
/>
<button
type="submit"
disabled={submitting}
className="bg-primary hover:bg-primary/95 text-white font-semibold rounded-2xl px-6 flex items-center gap-2 disabled:opacity-50 transition shadow-lg shadow-primary/20"
>
<Send className="h-4 w-4" />
<span>Send</span>
</button>
</form>
) : (
<div className="mb-8 p-4 rounded-2xl border border-dashed border-white/10 text-center text-sm text-gray-400 bg-white/5">
Please{" "}
<a href="/login" className="text-primary hover:underline font-semibold">
login
</a>{" "}
to post a comment.
</div>
)}
{loading ? (
<div className="flex justify-center py-8">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
</div>
) : comments.length === 0 ? (
<p className="text-center py-8 text-gray-500 text-sm">
No comments yet. Be the first to start the discussion!
</p>
) : (
<div className="space-y-4">
<AnimatePresence>
{comments
.filter((c) => !c.parentId) // Only root level comments
.map((c) => renderComment(c))}
</AnimatePresence>
</div>
)}
</div>
);
}

Xet Storage Details

Size:
9.26 kB
·
Xet hash:
e36d7a5344ef0f50556f037c4951900854504ac7affe6fba2beaa7cb2f51c131

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.