feat: Refactor blog components and add pagination

This commit is contained in:
Wini_Fy
2026-02-03 17:05:09 +07:00
parent bf652a64b6
commit 29cc0bf2cd
27 changed files with 2051 additions and 429 deletions

View File

@@ -0,0 +1,123 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
interface CommentFormProps {
slug: string;
parentId?: string | null;
replyToName?: string | null;
initialContent?: string;
onSubmitted?: () => void;
}
export default function CommentForm({
slug,
parentId = null,
replyToName = null,
initialContent = "",
onSubmitted,
}: CommentFormProps) {
const router = useRouter();
const [isPending, setIsPending] = useState(false);
const [authorName, setAuthorName] = useState("");
const [content, setContent] = useState(initialContent);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
if (!authorName.trim() || !content.trim()) {
setError("Please enter your name and comment.");
return;
}
try {
setIsPending(true);
const res = await fetch(`${apiUrl}/api/blog/${slug}/comments`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
authorName: authorName.trim(),
content: content.trim(),
...(parentId ? { parentId } : {}),
}),
});
const data = await res.json();
if (!res.ok || !data?.success) {
throw new Error(data?.message || "Failed to submit comment");
}
setAuthorName("");
setContent("");
setSuccess("Comment submitted.");
// Re-fetch server data (blog detail is no-store) to show new comment immediately
router.refresh();
onSubmitted?.();
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to submit comment");
} finally {
setIsPending(false);
}
};
return (
<div>
<h3 className="mb-3">
{parentId ? (replyToName ? `Reply to @${replyToName}` : "Reply") : "Leave A Comment"}
</h3>
{error && <p className="text-danger mb-3">{error}</p>}
{success && <p className="text-success mb-3">{success}</p>}
<form onSubmit={onSubmit} className="contact-form-items">
<div className="row g-4">
<div className="col-lg-6">
<div className="form-clt">
<span>Your Name</span>
<input
type="text"
name="authorName"
placeholder="Your name"
value={authorName}
onChange={(e) => setAuthorName(e.target.value)}
disabled={isPending}
/>
</div>
</div>
<div className="col-lg-12">
<div className="form-clt">
<textarea
name="content"
placeholder="Type your comment"
value={content}
onChange={(e) => setContent(e.target.value)}
disabled={isPending}
></textarea>
</div>
</div>
<div className="col-lg-12 wow fadeInUp" data-wow-delay=".3s">
<button type="submit" className="theme-btn" disabled={isPending}>
{isPending ? "Sending..." : "Send Comment"}
<i className="fa-solid fa-arrow-right"></i>
</button>
</div>
</div>
</form>
</div>
);
}

View File

@@ -0,0 +1,232 @@
"use client";
import type { BlogComment } from "@/types/blog";
import { useMemo, useState } from "react";
import CommentForm from "./CommentForm";
import { formatLongDate } from "@/utils";
interface CommentsSectionProps {
slug: string;
comments: BlogComment[];
}
export default function CommentsSection({ slug, comments }: CommentsSectionProps) {
const [replyTarget, setReplyTarget] = useState<{
// Root comment id to store as parentId (keeps 1-level threading on backend)
parentId: string;
// The author we are replying to (used for @mention UI)
replyToName: string;
// Which item in the UI is showing the reply form under it
anchorId: string;
} | null>(null);
const { parents, repliesByParent } = useMemo(() => {
const parentsLocal = (comments || []).filter((c) => !c.parentId);
const replies = (comments || []).filter((c) => !!c.parentId);
const map = new Map<string, BlogComment[]>();
for (const r of replies) {
const pid = r.parentId as string;
map.set(pid, [...(map.get(pid) || []), r]);
}
return { parents: parentsLocal, repliesByParent: map };
}, [comments]);
// Collect all author names to detect full @mentions (including multi-word names)
const authorNames = useMemo(() => {
return (comments || [])
.map((c) => c.authorName)
.filter((n): n is string => !!n)
// Sort by length desc so we match the longest possible name first
.sort((a, b) => b.length - a.length);
}, [comments]);
const renderContentWithMention = (text?: string) => {
if (!text) return null;
if (!text.startsWith("@")) return text;
// Try to match an @mention that corresponds to a known author name.
// This supports multi-word names like "@Bạn Cũng Thấy Thế Hà".
const matchedName = authorNames.find((name) => {
const candidate = `@${name}`;
if (!text.startsWith(candidate)) return false;
// Ensure the match ends at string end or is followed by a space
const nextChar = text.charAt(candidate.length);
return candidate.length === text.length || nextChar === " ";
});
if (!matchedName) {
// Fallback: just return the original text if we can't confidently match a name
return text;
}
const mention = `@${matchedName}`;
const rest = text.slice(mention.length); // includes leading space if present
return (
<>
<strong>{mention}</strong>
{rest}
</>
);
};
return (
<div className="comments-area">
<div className="comments-heading">
<h3>
{(comments || []).length} {(comments || []).length === 1 ? "Comment" : "Comments"}
</h3>
</div>
{parents.map((comment, index) => {
const replies = comment._id ? repliesByParent.get(comment._id) || [] : [];
const isReplyingHere = !!comment._id && replyTarget?.anchorId === comment._id;
return (
<div key={comment._id || index}>
<div
className={`news-single-comment ${index % 2 === 1 ? "style-2" : ""
} d-flex gap-4 pt-4 pb-0`}
>
<div className="image">
<img
src={
comment.authorAvatar ||
`/assets/img/inner-page/news-details/comment-${(index % 3) + 1}.png`
}
alt={comment.authorName}
/>
</div>
<div className="content">
<div className="head d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="con">
<span>{formatLongDate(comment.createdAt)}</span>
<h4>{comment.authorName}</h4>
</div>
{comment._id && (
<button
type="button"
className="reply"
onClick={() =>
setReplyTarget({
parentId: comment._id!,
replyToName: comment.authorName,
anchorId: comment._id!,
})
}
>
Reply
</button>
)}
</div>
<p className="mt-30 mb-4">{renderContentWithMention(comment.content)}</p>
{isReplyingHere && comment._id && (
<div className="mb-4">
<div className="d-flex justify-content-end mb-2">
<button
type="button"
className="btn btn-sm btn-outline-secondary"
onClick={() => setReplyTarget(null)}
>
Cancel
</button>
</div>
<CommentForm
slug={slug}
parentId={replyTarget?.parentId || comment._id}
replyToName={replyTarget?.replyToName || comment.authorName}
initialContent={`@${replyTarget?.replyToName || comment.authorName} `}
onSubmitted={() => setReplyTarget(null)}
/>
</div>
)}
{/* Replies */}
{replies.length > 0 && (
<div className="replies">
{replies.map((reply, replyIndex) => (
<div key={reply._id || replyIndex}>
<div
className="news-single-comment d-flex gap-4 pt-4 pb-0"
>
<div className="image">
<img
src={
reply.authorAvatar ||
`/assets/img/inner-page/news-details/comment-${(replyIndex % 3) + 1}.png`
}
alt={reply.authorName}
/>
</div>
<div className="content">
<div className="head d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="con">
<span>{formatLongDate(reply.createdAt)}</span>
<h4>{reply.authorName}</h4>
</div>
{reply._id && comment._id && (
<button
type="button"
className="reply"
onClick={() =>
setReplyTarget({
// Keep backend parentId as the root comment id (comment._id)
parentId: comment._id!,
// Mention the author we clicked reply on (child comment author)
replyToName: reply.authorName,
// Show form under this child comment
anchorId: reply._id!,
})
}
>
Reply
</button>
)}
</div>
<p className="mt-30 mb-4">{renderContentWithMention(reply.content)}</p>
</div>
</div>
{/* Reply form under child comment */}
{reply._id && replyTarget?.anchorId === reply._id && (
<div className="mb-4 mt-3">
<div className="d-flex justify-content-end mb-2">
<button
type="button"
className="btn btn-sm btn-outline-secondary"
onClick={() => setReplyTarget(null)}
>
Cancel
</button>
</div>
<CommentForm
slug={slug}
parentId={replyTarget.parentId}
replyToName={replyTarget.replyToName}
initialContent={`@${replyTarget.replyToName} `}
onSubmitted={() => setReplyTarget(null)}
/>
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
</div>
);
})}
{/* New top-level comment */}
<div className="mt-5">
<CommentForm slug={slug} />
</div>
</div>
);
}

View File

@@ -1,224 +1,116 @@
import Link from "next/link";
import type { BlogPost } from "@/types/blog";
import { editorjsToHtml, getCmsImageUrl } from "@/utils";
import { toSlug } from "@/utils/slugify";
import CommentsSection from "./CommentsSection";
interface NewsDetailsContentProps {
post: BlogPost;
}
export default function NewsDetailsContent({ post }: NewsDetailsContentProps) {
// Get comments from post (already included in API response)
const postComments = post.comments || [];
// Get base URL for EditorJS images
const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
// Convert EditorJS content to HTML
const renderContent = () => {
const html = editorjsToHtml(post.content, baseUrl);
return { __html: html };
};
// Convert EditorJS contentAfterQuote to HTML
const renderContentAfterQuote = () => {
const html = editorjsToHtml(post.contentAfterQuote, baseUrl);
return { __html: html };
};
export default function NewsDetailsContent() {
return (
<div className="col-lg-8 col-12">
<div className="news-details-post">
<div className="news-details-image">
<img src="/assets/img/inner-page/news-details/details-1.jpg" alt="img" />
<img
src={getCmsImageUrl(post.featuredImage) || "/assets/img/inner-page/news-details/details-1.jpg"}
alt={post.title}
/>
</div>
<div className="details-content">
<ul className="news-list">
<li>
<i className="fa-solid fa-user"></i>
By Admin
<i className="fa-solid fa-user"></i> By {post.author}
</li>
<li>
<i className="fa-solid fa-calendar-days"></i>
11 March 2025
<i className="fa-solid fa-calendar-days"></i> {post.publishedAt}
</li>
<li>
<i className="fa-solid fa-comments"></i>
0 Comments
<i className="fa-solid fa-comments"></i> {postComments.length} Comments
</li>
</ul>
<h2>Work Visa vs. Student Visa Which is Right for You?</h2>
<p>
Choosing between a work visa and a student visa depends on your career and academic goals. A
student visa allows you to pursue higher education abroad, gain international exposure, and
sometimes work part-time while studying. On the other hand, a work visa is for professionals
seeking employment opportunities and long-term career growth in another country.
</p>
<p className="mt-4 mb-3">
Both options have unique benefits, eligibility requirements, and future pathways. Understanding
your personal ambitions, financial plans, and long-term vision will help you decide which visa
option best suits your journey.
</p>
<h3>Work Visa vs. Student Visa: Which is Right for You?</h3>
<p className="mt-2 mb-3">
Choosing between a student visa and a work visa is a major decision that shapes your future
abroad. Both visa types open unique opportunities, but the right choice depends on your goals,
priorities, and resources. A student visa is designed for individuals who wish to pursue higher
education in a foreign country.
</p>
<div className="row g-4">
<div className="col-lg-6">
<div className="thumb">
<img src="/assets/img/inner-page/news-details/details-2.jpg" alt="img" />
</div>
<h2>{post.title}</h2>
<div dangerouslySetInnerHTML={renderContent()} />
{/* Gallery Images */}
{post.galleryImages && post.galleryImages.length > 0 && (
<div className="row g-4 mt-4">
{post.galleryImages.map((image, index) => (
<div key={index} className={post.galleryImages!.length === 1 ? "col-12" : "col-lg-6"}>
<div className="thumb">
<img src={getCmsImageUrl(image)} alt={`${post.title} - Image ${index + 1}`} />
</div>
</div>
))}
</div>
<div className="col-lg-6">
<div className="thumb">
<img src="/assets/img/inner-page/news-details/details-3.jpg" alt="img" />
</div>
)}
{/* Quote/Sidebar */}
{post.quote && (
<div className="sideber mt-4 mb-3">
<h5>{post.quote}</h5>
</div>
</div>
<div className="sideber">
<h5>
This blog really helped me understand the difference between student and work visas. The
explanations were clear and practical.
</h5>
</div>
<p className="mb-3">
It provides access to world-class universities, cultural exposure, and global networking
opportunities. With a student visa, you may also get part-time work rights, which can help support
your expenses and give you valuable international work experience. However, the primary focus
remains on academics and personal growth. On the other hand, a work visa is perfect for those who
want to establish themselves in a career overseas.
</p>
<p>
It provides immediate access to job markets, stable income, and often a pathway to permanent
residency. Work visas are suitable for skilled professionals who are ready to contribute to the
global workforce and achieve long-term career goals. Ultimately, the choice comes down to your
personal aspirations. If education and exploration are your priorities, a student visa is ideal. If
career advancement and stability are your goals, a work visa is the right fit.
</p>
)}
{/* Content After Quote */}
{post.contentAfterQuote && (
<div dangerouslySetInnerHTML={renderContentAfterQuote()} />
)}
{/* Tags and Social Share */}
<div className="row tag-share-wrap mt-4 mb-5">
<div className="col-lg-8 col-12">
<div className="tagcloud">
<span>Tags:</span>
<Link href="/blog/work-visa">WorkVisa</Link>
<Link href="/blog/family-visa">FamilyVisa</Link>
<Link href="/blog/student-visa">StudentVisa</Link>
{post.tags.map((tagName) => {
// Generate slug from tag name (Vietnamese-friendly)
const tagSlug = toSlug(tagName);
return (
<Link key={tagName} href={`/blog/tag/${tagSlug}`}>
{tagName}
</Link>
);
})}
</div>
</div>
<div className="col-lg-4 col-12 mt-3 mt-lg-0 text-lg-end">
<div className="social-share">
<a href="#">
<a href="#" aria-label="Share on Twitter">
<i className="fab fa-twitter"></i>
</a>
<a href="#">
<a href="#" aria-label="Share on YouTube">
<i className="fa-brands fa-youtube"></i>
</a>
<a href="#">
<a href="#" aria-label="Share on LinkedIn">
<i className="fab fa-linkedin-in"></i>
</a>
<a href="#">
<a href="#" aria-label="Share on Facebook">
<i className="fab fa-facebook-f"></i>
</a>
</div>
</div>
</div>
<div className="comments-area">
<div className="comments-heading">
<h3>02 Comments</h3>
</div>
<div className="news-single-comment d-flex gap-4 pt-4 pb-0">
<div className="image">
<img src="/assets/img/inner-page/news-details/comment-1.png" alt="image" />
</div>
<div className="content">
<div className="head d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="con">
<span>February 10, 2024</span>
<h4>Frank Flores</h4>
</div>
<Link href="/blog/work-visa" className="reply">
Reply
</Link>
</div>
<p className="mt-30 mb-4">
Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed
efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy
</p>
</div>
</div>
<div className="news-single-comment style-2 d-flex gap-4 pt-4 pb-0">
<div className="image">
<img src="/assets/img/inner-page/news-details/comment-2.png" alt="image" />
</div>
<div className="content">
<div className="head d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="con">
<h4>Charlie Tushar</h4>
<span>February 10, 2024</span>
</div>
<Link href="/blog/work-visa" className="reply">
Reply
</Link>
</div>
<p className="mt-30 mb-4">
Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed
efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy
</p>
</div>
</div>
<div className="news-single-comment d-flex gap-4 pt-4 pb-4">
<div className="image">
<img src="/assets/img/inner-page/news-details/comment-3.png" alt="image" />
</div>
<div className="content">
<div className="head d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="con">
<span>February 10, 2024 </span>
<h4>Fatma Sariqul</h4>
</div>
<Link href="/blog/work-visa" className="reply">
Reply
</Link>
</div>
<p className="mt-30 mb-4">
Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed
efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy
</p>
</div>
</div>
</div>
<h3 className="mb-3">Leave A Comment</h3>
<form
action="contact.php"
id="contact-form1"
method="POST"
className="contact-form-items"
>
<div className="row g-4">
<div className="col-lg-4">
<div className="form-clt">
<span>Your Name</span>
<input type="text" name="name" id="name331" placeholder="Your name" />
</div>
</div>
<div className="col-lg-4">
<div className="form-clt">
<span>Your Email</span>
<input type="text" name="name" id="email11" placeholder="Your email" />
</div>
</div>
<div className="col-lg-4">
<div className="form-clt">
<span>Your Phone</span>
<input type="text" name="name" id="name22" placeholder="Phone Number" />
</div>
</div>
<div className="col-lg-6">
<div className="form-clt">
<span>Your Address</span>
<input type="text" name="name" id="name24" placeholder="Address Now" />
</div>
</div>
<div className="col-lg-6">
<div className="form-clt">
<span>Your Date</span>
<input type="text" name="name" id="name25" placeholder="Date" />
</div>
</div>
<div className="col-lg-12">
<div className="form-clt">
<textarea
name="message"
id="message1"
placeholder="Type your message"
></textarea>
</div>
</div>
<div className="col-lg-12 wow fadeInUp" data-wow-delay=".3s">
<button type="submit" className="theme-btn">
Send Message
<i className="fa-solid fa-arrow-right"></i>
</button>
</div>
</div>
</form>
<CommentsSection slug={post.slug} comments={postComments} />
</div>
</div>
</div>

View File

@@ -1,13 +1,18 @@
import NewsDetailsContent from "./NewsDetailsContent";
import Sidebar from "@/app/blog/components/Sidebar";
import type { BlogPost } from "@/types/blog";
export default function NewsDetailsSection() {
interface NewsDetailsSectionProps {
post: BlogPost;
}
export default function NewsDetailsSection({ post }: NewsDetailsSectionProps) {
return (
<section className="news-standard-section section-padding fix">
<div className="container">
<div className="news-details-wrapper">
<div className="row g-4">
<NewsDetailsContent />
<NewsDetailsContent post={post} />
<Sidebar />
</div>
</div>

View File

@@ -1,17 +1,72 @@
import Link from "next/link";
import Breadcrumb from "@/app/components/Breadcrumb";
import NewsDetailsSection from "./components/NewsDetailsSection";
import { fetchBlogList, fetchBlogDetail } from "@/api/blog";
import Sidebar from "@/app/blog/components/Sidebar";
// Generate static params for all blog posts
export async function generateStaticParams() {
try {
const blogResponse = await fetchBlogList({ page: 1, limit: 100 });
return blogResponse.data.blogs.map((post) => ({
slug: post.slug,
}));
} catch (error) {
console.error("Error generating static params:", error);
return [];
}
}
interface BlogDetailsPageProps {
params: {
params: Promise<{
slug: string;
}> | {
slug: string;
};
}
export default function BlogDetailsPage(_props: BlogDetailsPageProps) {
export default async function BlogDetailsPage({ params }: BlogDetailsPageProps) {
// Handle both Promise and direct object
const resolvedParams = params instanceof Promise ? await params : params;
const slug = resolvedParams.slug;
// Fetch blog detail from API
let blogResponse;
try {
blogResponse = await fetchBlogDetail(slug);
} catch {
return (
<>
<Breadcrumb title="Blog Details" current="Blog Details" />
<section className="news-standard-section section-padding fix">
<div className="container">
<div className="news-standard-wrapper">
<div className="row g-4">
<div className="col-lg-8 col-12">
<div className="py-5">
<h2>Post not found</h2>
<p>The blog post you are looking for does not exist.</p>
<Link href="/blog" className="theme-btn mt-3">
Back to Blog <i className="fa-solid fa-arrow-right"></i>
</Link>
</div>
</div>
{/* Sidebar on the right */}
<Sidebar />
</div>
</div>
</div>
</section>
</>
);
}
const post = blogResponse.data;
return (
<>
<Breadcrumb title="Blog Details" current="Blog Details" />
<NewsDetailsSection />
<Breadcrumb title={post.title} current="Blog Details" />
<NewsDetailsSection post={post} />
</>
);
}