Functional like/view counters and comment section on blog posts
Deploy Frontend / deploy (push) Successful in 1m7s

- PostStats: optimistic like toggle (localStorage per post) and one view per
  browser session (sessionStorage) against the new public endpoints
- CommentSection: lists approved reader comments, submits new ones into
  moderation with a pending-confirmation state
- Both wired into the single-post page sidebar and after the prev/next cards;
  new en/fa dictionary labels
This commit is contained in:
Parsa Aghayi committed 2026-10-02 11:13:31 -04:00
1 parent 2d2371da9d
commit ea0401b1ff
6 files changed
+363 -24

No files matched your search

@@ -0,0 +1,189 @@
"use client";
import { useEffect, useState } from "react";
type CommentItem = {
id: number;
name: string;
body: string;
created_at: string;
};
type CommentLabels = {
title: string;
leave: string;
name: string;
email: string;
body: string;
submit: string;
pending: string;
none: string;
error: string;
};
type CommentSectionProps = {
slug: string;
labels: CommentLabels;
};
const API_URL = process.env.NEXT_PUBLIC_BLOG_API_URL;
export default function CommentSection({ slug, labels }: CommentSectionProps) {
const [comments, setComments] = useState<CommentItem[]>([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [body, setBody] = useState("");
const [status, setStatus] = useState<"loading" | "idle" | "submitting" | "submitted" | "error">("loading");
useEffect(() => {
let cancelled = false;
fetch(`${API_URL}/posts/${slug}/comments`)
.then((res) => (res.ok ? res.json() : { comments: [] }))
.then((data) => {
if (!cancelled && Array.isArray(data.comments)) {
setComments(data.comments);
setStatus("idle");
}
})
.catch(() => {
if (!cancelled) {
setStatus("idle");
}
});
return () => {
cancelled = true;
};
}, [slug]);
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setStatus("submitting");
try {
const res = await fetch(`${API_URL}/posts/${slug}/comments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, email, body }),
});
if (res.status === 201) {
setBody("");
setStatus("submitted");
} else {
setStatus("error");
}
} catch {
setStatus("error");
}
};
return (
<section className="my-10 flex w-full flex-col gap-6" aria-label={labels.title}>
<h2 className="text-[22px] font-[600] capitalize text-blog-text-default">
{labels.title} ({comments.length})
</h2>
{comments.length > 0 ? (
<ul className="flex w-full flex-col gap-5">
{comments.map((comment) => (
<li
key={comment.id}
className="flex w-full flex-col gap-2 rounded-md border border-blog-text-passive p-5"
>
<div className="flex w-full items-center justify-between gap-3">
<p className="text-[15px] font-[700] text-blog-text-default">
{comment.name}
</p>
<p className="whitespace-nowrap text-[12px] font-[400] text-blog-text-passive">
{formatDate(comment.created_at)}
</p>
</div>
<p className="text-[15px] font-[400] leading-relaxed text-blog-text-default">
{comment.body}
</p>
</li>
))}
</ul>
) : (
status === "idle" && (
<p className="text-[15px] font-[400] text-blog-text-passive">
{labels.none}
</p>
)
)}
{status === "submitted" ? (
<p className="rounded-md bg-blog-purple/10 p-4 text-[15px] font-[500] text-blog-purple">
{labels.pending}
</p>
) : (
<form
onSubmit={submit}
className="flex w-full max-w-[600px] flex-col gap-4 rounded-md border border-blog-text-passive p-5"
>
<p className="text-[18px] font-[600] capitalize text-blog-text-default">
{labels.leave}
</p>
<label className="flex flex-col gap-1">
<span className="text-[13px] font-[600] text-blog-text-passive">
{labels.name}
</span>
<input
type="text"
required
value={name}
onChange={(event) => setName(event.target.value)}
className="rounded-md border border-blog-text-passive bg-transparent px-3 py-2 text-[15px] text-blog-text-default outline-none focus:border-blog-purple"
/>
</label>
<label className="flex flex-col gap-1">
<span className="text-[13px] font-[600] text-blog-text-passive">
{labels.email}
</span>
<input
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
className="rounded-md border border-blog-text-passive bg-transparent px-3 py-2 text-[15px] text-blog-text-default outline-none focus:border-blog-purple"
/>
</label>
<label className="flex flex-col gap-1">
<span className="text-[13px] font-[600] text-blog-text-passive">
{labels.body}
</span>
<textarea
required
rows={5}
value={body}
onChange={(event) => setBody(event.target.value)}
className="rounded-md border border-blog-text-passive bg-transparent px-3 py-2 text-[15px] text-blog-text-default outline-none focus:border-blog-purple"
/>
</label>
{status === "error" ? (
<p className="text-[14px] font-[500] text-red-500">{labels.error}</p>
) : null}
<button
type="submit"
disabled={status === "submitting"}
className="w-fit rounded-full bg-blog-purple px-6 py-2 text-[15px] font-[700] capitalize text-white transition-transform hover:scale-105 disabled:cursor-not-allowed disabled:opacity-60"
>
{labels.submit}
</button>
</form>
)}
</section>
);
}
function formatDate(value: string): string {
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
return value;
}
return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(parsed);
}
+23 -22
View File
@@ -15,6 +15,8 @@ import { redirect } from "next/navigation";
import { getHeadings, renderBody } from "./body";
import { estimateReadingTime } from "./readingTime";
import ShareButtons from "../../components/share/shareButtons";
import CommentSection from "./comments";
import PostStats from "./postStats";
import { getCoverImageSrc } from "./coverImage";
import { AUTHOR_PROFILE_URL } from "@/app/lib/social-links";
import { SITE_NAME, SITE_NAME_EN, SITE_URL } from "@/app/lib/site-config";
@@ -390,28 +392,12 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
</div>
<div className="sticky top-[150px] flex flex-col items-end gap-5">
<div className="flex cursor-pointer flex-col gap-1">
<Image
src={"/images/blog/icons/like.svg"}
width={35}
height={35}
alt="socials-vertical icons"
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{post.likes}
</p>
</div>
<div className="flex cursor-pointer flex-col gap-1">
<Image
src={"/images/blog/icons/eye.svg"}
width={35}
height={35}
alt="socials-vertical icons"
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{post.views}
</p>
</div>
<PostStats
slug={post.slug ?? params.postSlug}
initialViews={post.views}
initialLikes={post.likes}
likeAriaLabel={dict.blog.postSinglePage.likeButton}
/>
</div>
</div>
@@ -511,6 +497,21 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
) : null}
</div>
) : null}
<CommentSection
slug={post.slug ?? params.postSlug}
labels={{
title: dict.blog.postSinglePage.commentsTitle,
leave: dict.blog.postSinglePage.leaveComment,
name: dict.blog.postSinglePage.commentName,
email: dict.blog.postSinglePage.commentEmail,
body: dict.blog.postSinglePage.commentBody,
submit: dict.blog.postSinglePage.commentSubmit,
pending: dict.blog.postSinglePage.commentPending,
none: dict.blog.postSinglePage.noComments,
error: dict.blog.postSinglePage.commentError,
}}
/>
</div>
</div>
);
@@ -0,0 +1,121 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
type PostStatsProps = {
slug: string;
initialViews: number;
initialLikes: number;
likeAriaLabel?: string;
};
const API_URL = process.env.NEXT_PUBLIC_BLOG_API_URL;
/**
* Live like/view counters for the sticky post sidebar. One view is recorded per
* browser session (sessionStorage), and like state persists per post in
* localStorage so refreshing does not re-like. Both are optimistic so the UI
* never blocks on the network.
*/
export default function PostStats({
slug,
initialViews,
initialLikes,
likeAriaLabel,
}: PostStatsProps) {
const [views, setViews] = useState(initialViews);
const [likes, setLikes] = useState(initialLikes);
const [liked, setLiked] = useState(() => {
try {
return localStorage.getItem(`blogLike:${slug}`) === "1";
} catch {
return false;
}
});
useEffect(() => {
if (sessionStorage.getItem(`blogViewed:${slug}`) === "1") {
return;
}
let cancelled = false;
fetch(`${API_URL}/posts/${slug}/view`, { method: "POST" })
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!cancelled && data && typeof data.views === "number") {
setViews(data.views);
try {
sessionStorage.setItem(`blogViewed:${slug}`, "1");
} catch {
/* storage unavailable */
}
}
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [slug]);
const toggleLike = () => {
const nextLiked = !liked;
setLiked(nextLiked);
setLikes((current) => Math.max(0, current + (nextLiked ? 1 : -1)));
try {
localStorage.setItem(`blogLike:${slug}`, nextLiked ? "1" : "0");
} catch {
/* storage unavailable */
}
fetch(`${API_URL}/posts/${slug}/like`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ liked: nextLiked }),
})
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data && typeof data.likes === "number") {
setLikes(Math.max(0, data.likes));
}
})
.catch(() => undefined);
};
return (
<>
<button
type="button"
onClick={toggleLike}
aria-label={likeAriaLabel ?? "Like this post"}
aria-pressed={liked}
className="flex cursor-pointer flex-col gap-1 transition-transform hover:scale-110"
>
<Image
src={"/images/blog/icons/like.svg"}
width={35}
height={35}
alt="like post"
className={liked ? "drop-shadow-[0_0_6px_rgba(255,84,128,0.9)]" : "opacity-80"}
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{likes}
</p>
</button>
<div className="flex flex-col gap-1">
<Image
src={"/images/blog/icons/eye.svg"}
width={35}
height={35}
alt="post views"
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{views}
</p>
</div>
</>
);
}
+10 -1
View File
@@ -138,7 +138,16 @@
"linkCopied": "Link copied",
"newerPost": "Newer post",
"olderPost": "Older post",
"home": "Home"
"commentsTitle": "Comments",
"leaveComment": "Leave a comment",
"commentName": "Name",
"commentEmail": "Email (optional)",
"commentBody": "Your comment",
"commentSubmit": "Post comment",
"commentPending": "Thanks! Your comment is awaiting approval.",
"noComments": "No comments yet — be the first.",
"commentError": "Something went wrong. Please try again.",
"likeButton": "Like this post"
},
"header": {
"Home": "Home",
+10 -1
View File
@@ -138,7 +138,16 @@
"linkCopied": "لینک کپی شد",
"newerPost": "پست جدیدتر",
"olderPost": "پست قدیمی‌تر",
"home": "خانه"
"commentsTitle": "دیدگاه‌ها",
"leaveComment": "ثبت دیدگاه",
"commentName": "نام",
"commentEmail": "ایمیل (اختیاری)",
"commentBody": "متن دیدگاه",
"commentSubmit": "ارسال دیدگاه",
"commentPending": "ممنون! دیدگاه شما پس از تأیید نمایش داده می‌شود.",
"noComments": "هنوز دیدگاهی ثبت نشده است. شما اولین نفر باشید.",
"commentError": "خطایی رخ داد. لطفاً دوباره تلاش کنید.",
"likeButton": "لایک کردن این پست"
},
"header": {
"Home": "خانه",
+10
View File
@@ -240,6 +240,16 @@ export type Dictionary = {
linkCopied: string;
newerPost: string;
olderPost: string;
commentsTitle: string;
leaveComment: string;
commentName: string;
commentEmail: string;
commentBody: string;
commentSubmit: string;
commentPending: string;
noComments: string;
commentError: string;
likeButton: string;
};
header: {
Home: string;