forked from UKSOURCE/hailearning.edu.vn
feat: create Partnership component and styles
This commit is contained in:
@@ -1,199 +0,0 @@
|
||||
"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 [authorEmail, setAuthorEmail] = useState("");
|
||||
const [authorPhone, setAuthorPhone] = useState("");
|
||||
const [authorAddress, setAuthorAddress] = useState("");
|
||||
const [authorDate, setAuthorDate] = 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;
|
||||
}
|
||||
|
||||
// Basic email validation if provided
|
||||
if (authorEmail.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(authorEmail.trim())) {
|
||||
setError("Please enter a valid email address.");
|
||||
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(),
|
||||
...(authorEmail.trim() ? { authorEmail: authorEmail.trim() } : {}),
|
||||
...(authorPhone.trim() ? { authorPhone: authorPhone.trim() } : {}),
|
||||
...(authorAddress.trim() ? { authorAddress: authorAddress.trim() } : {}),
|
||||
...(authorDate.trim() ? { authorDate: authorDate.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("");
|
||||
setAuthorEmail("");
|
||||
setAuthorPhone("");
|
||||
setAuthorAddress("");
|
||||
setAuthorDate("");
|
||||
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-4">
|
||||
<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}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<div className="form-clt">
|
||||
<span>Your Email</span>
|
||||
<input
|
||||
type="email"
|
||||
name="authorEmail"
|
||||
placeholder="Your email"
|
||||
value={authorEmail}
|
||||
onChange={(e) => setAuthorEmail(e.target.value)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<div className="form-clt">
|
||||
<span>Your Phone</span>
|
||||
<input
|
||||
type="text"
|
||||
name="authorPhone"
|
||||
placeholder="Phone Number"
|
||||
value={authorPhone}
|
||||
onChange={(e) => setAuthorPhone(e.target.value)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-6">
|
||||
<div className="form-clt">
|
||||
<span>Your Address</span>
|
||||
<input
|
||||
type="text"
|
||||
name="authorAddress"
|
||||
placeholder="Address Now"
|
||||
value={authorAddress}
|
||||
onChange={(e) => setAuthorAddress(e.target.value)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-6">
|
||||
<div className="form-clt">
|
||||
<span>Your Date</span>
|
||||
<input
|
||||
type="text"
|
||||
name="authorDate"
|
||||
placeholder="Date"
|
||||
value={authorDate}
|
||||
onChange={(e) => setAuthorDate(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}
|
||||
required
|
||||
></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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,382 +0,0 @@
|
||||
"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 [showAllComments, setShowAllComments] = useState(false);
|
||||
const [expandedCommentKeys, setExpandedCommentKeys] = useState<Set<string>>(
|
||||
() => new Set()
|
||||
);
|
||||
const [replyTarget, setReplyTarget] = useState<{
|
||||
// ID của comment gốc để lưu làm parentId (giữ thread 1 cấp trên backend)
|
||||
parentId: string;
|
||||
// Tên tác giả mà chúng ta đang reply (dùng cho UI @mention)
|
||||
replyToName: string;
|
||||
// ID của item trong UI đang hiển thị form reply bên dưới
|
||||
anchorId: string;
|
||||
} | null>(null);
|
||||
|
||||
// Helper function để lấy chữ cái đầu của tên
|
||||
const getInitials = (name?: string): string => {
|
||||
if (!name) return "?";
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length === 0) return "?";
|
||||
return trimmed.charAt(0).toUpperCase();
|
||||
};
|
||||
|
||||
const makeCommentKey = (prefix: "p" | "r", id: string | undefined, index: number) =>
|
||||
id ? `${prefix}:${id}` : `${prefix}:idx:${index}`;
|
||||
|
||||
const isExpanded = (key: string) => expandedCommentKeys.has(key);
|
||||
|
||||
const toggleExpanded = (key: string) => {
|
||||
setExpandedCommentKeys((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
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]);
|
||||
// Thu thập tất cả tên tác giả để phát hiện @mention đầy đủ (bao gồm tên nhiều từ)
|
||||
const authorNames = useMemo(() => {
|
||||
return (comments || [])
|
||||
.map((c) => c.authorName)
|
||||
.filter((n): n is string => !!n)
|
||||
// Sắp xếp theo độ dài giảm dần để khớp tên dài nhất trước
|
||||
.sort((a, b) => b.length - a.length);
|
||||
}, [comments]);
|
||||
|
||||
const renderContentWithMention = (text?: string) => {
|
||||
if (!text) return null;
|
||||
if (!text.startsWith("@")) return text;
|
||||
|
||||
// Thử khớp @mention với tên tác giả đã biết
|
||||
// Hỗ trợ tên nhiều từ như "@Bạn Cũng Thấy Thế Hà"
|
||||
const matchedName = authorNames.find((name) => {
|
||||
const candidate = `@${name}`;
|
||||
if (!text.startsWith(candidate)) return false;
|
||||
|
||||
// Đảm bảo khớp kết thúc ở cuối chuỗi hoặc theo sau bởi khoảng trắng
|
||||
const nextChar = text.charAt(candidate.length);
|
||||
return candidate.length === text.length || nextChar === " ";
|
||||
});
|
||||
|
||||
if (!matchedName) {
|
||||
// Fallback: trả về text gốc nếu không thể khớp tên một cách chắc chắn
|
||||
return text;
|
||||
}
|
||||
|
||||
const mention = `@${matchedName}`;
|
||||
const rest = text.slice(mention.length); // bao gồm khoảng trắng đầu nếu có
|
||||
|
||||
return (
|
||||
<>
|
||||
<strong>{mention}</strong>
|
||||
{rest}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const splitWords = (s: string) =>
|
||||
s
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
|
||||
const renderTruncatedContent = (text: string | undefined, key: string) => {
|
||||
if (!text) return null;
|
||||
|
||||
const maxWords = 35;
|
||||
const words = splitWords(text);
|
||||
const needsTruncate = words.length > maxWords;
|
||||
const expanded = isExpanded(key);
|
||||
|
||||
const displayText =
|
||||
!needsTruncate || expanded ? text : `${words.slice(0, maxWords).join(" ")}...`;
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderContentWithMention(displayText)}
|
||||
{needsTruncate && (
|
||||
<>
|
||||
{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpanded(key)}
|
||||
style={{
|
||||
border: "none",
|
||||
background: "transparent",
|
||||
padding: 0,
|
||||
color: "var(--primary-color, #0d6efd)",
|
||||
cursor: "pointer",
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{expanded ? "less" : "more"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Tính toán các parent comment cần hiển thị (bao gồm children) để hiển thị tối đa 5 comments tổng cộng
|
||||
const getDisplayedParents = () => {
|
||||
if (showAllComments) return { parents: parents, repliesMap: new Map() };
|
||||
|
||||
let totalCount = 0;
|
||||
const result: typeof parents = [];
|
||||
const limitedRepliesMap = new Map<string, BlogComment[]>();
|
||||
|
||||
for (const parent of parents) {
|
||||
const allReplies = parent._id ? repliesByParent.get(parent._id) || [] : [];
|
||||
const remaining = 5 - totalCount;
|
||||
|
||||
if (remaining <= 0) break;
|
||||
|
||||
// Tính toán số lượng replies có thể hiển thị
|
||||
const repliesToShow = Math.min(allReplies.length, remaining - 1); // -1 cho chính parent comment
|
||||
|
||||
if (repliesToShow >= 0) {
|
||||
result.push(parent);
|
||||
if (parent._id && repliesToShow > 0) {
|
||||
limitedRepliesMap.set(parent._id, allReplies.slice(0, repliesToShow));
|
||||
}
|
||||
totalCount += 1 + repliesToShow;
|
||||
} else {
|
||||
// Không thể hiển thị cả parent, dừng lại
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { parents: result, repliesMap: limitedRepliesMap };
|
||||
};
|
||||
|
||||
const { parents: displayedParents, repliesMap: displayedRepliesMap } = getDisplayedParents();
|
||||
|
||||
// Tính số lượng comments hiển thị ban đầu (khi thu gọn, tối đa 5)
|
||||
const initialDisplayCount = displayedParents.reduce((sum, parent) => {
|
||||
// Khi thu gọn, sử dụng replies giới hạn từ displayedRepliesMap
|
||||
const replies = parent._id ? (displayedRepliesMap.get(parent._id) || []) : [];
|
||||
return sum + 1 + replies.length;
|
||||
}, 0);
|
||||
|
||||
const hasMoreComments = (comments || []).length > initialDisplayCount;
|
||||
|
||||
return (
|
||||
<div className="comments-area">
|
||||
<div className="comments-heading">
|
||||
<h3>
|
||||
{(comments || []).length} {(comments || []).length === 1 ? "Comment" : "Comments"}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{displayedParents.map((comment, index) => {
|
||||
// Khi showAllComments là false, chỉ sử dụng replies giới hạn từ displayedRepliesMap
|
||||
// Khi showAllComments là true, sử dụng tất cả replies từ repliesByParent
|
||||
const replies = comment._id
|
||||
? (showAllComments
|
||||
? (repliesByParent.get(comment._id) || [])
|
||||
: (displayedRepliesMap.get(comment._id) || []))
|
||||
: [];
|
||||
const isReplyingHere = !!comment._id && replyTarget?.anchorId === comment._id;
|
||||
|
||||
return (
|
||||
<div key={comment._id || index}>
|
||||
<div
|
||||
className="news-single-comment d-flex pt-4 pb-0 position-relative"
|
||||
>
|
||||
<div className="image">
|
||||
<div className="comment-avatar-box">
|
||||
{getInitials(comment.authorName)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="content">
|
||||
<div className="head d-flex gap-2 gap-md-2 align-items-center">
|
||||
<div className="con">
|
||||
<span>{formatLongDate(comment.createdAt)}</span>
|
||||
<h4>{comment.authorName}</h4>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-30">
|
||||
{renderTruncatedContent(
|
||||
comment.content,
|
||||
makeCommentKey("p", comment._id, index)
|
||||
)}
|
||||
</p>
|
||||
|
||||
{comment._id && (
|
||||
<button
|
||||
type="button"
|
||||
className="reply reply-absolute"
|
||||
onClick={() =>
|
||||
setReplyTarget({
|
||||
parentId: comment._id!,
|
||||
replyToName: comment.authorName,
|
||||
anchorId: comment._id!,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reply
|
||||
</button>
|
||||
)}
|
||||
|
||||
{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>
|
||||
)}
|
||||
|
||||
{/* Các reply */}
|
||||
{replies.length > 0 && (
|
||||
<div className="replies">
|
||||
{replies.map((reply: BlogComment, replyIndex: number) => (
|
||||
<div key={reply._id || replyIndex}>
|
||||
<div
|
||||
className="news-single-comment d-flex pt-4 pb-0 position-relative"
|
||||
>
|
||||
<div className="image">
|
||||
<div className="comment-avatar-box">
|
||||
{getInitials(reply.authorName)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="content">
|
||||
<div className="head d-flex gap-2 gap-md-2 align-items-center">
|
||||
<div className="con">
|
||||
<span>{formatLongDate(reply.createdAt)}</span>
|
||||
<h4>{reply.authorName}</h4>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-30">
|
||||
{renderTruncatedContent(
|
||||
reply.content,
|
||||
makeCommentKey("r", reply._id, replyIndex)
|
||||
)}
|
||||
</p>
|
||||
|
||||
{reply._id && comment._id && (
|
||||
<button
|
||||
type="button"
|
||||
className="reply reply-absolute"
|
||||
onClick={() =>
|
||||
setReplyTarget({
|
||||
// Giữ parentId trên backend là ID của comment gốc (comment._id)
|
||||
parentId: comment._id!,
|
||||
// Mention tác giả mà chúng ta click reply (tác giả của child comment)
|
||||
replyToName: reply.authorName,
|
||||
// Hiển thị form bên dưới child comment này
|
||||
anchorId: reply._id!,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reply
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form reply bên dưới child comment */}
|
||||
{reply._id && replyTarget && 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>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Nút hiển thị thêm comments */}
|
||||
{hasMoreComments && !showAllComments && (
|
||||
<div className="text-center mt-4 mb-4">
|
||||
<button
|
||||
type="button"
|
||||
className="theme-btn"
|
||||
onClick={() => setShowAllComments(true)}
|
||||
>
|
||||
Show More Comments ({(comments || []).length - initialDisplayCount} more)
|
||||
<i className="fa-solid fa-arrow-down"></i>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Nút thu gọn */}
|
||||
{hasMoreComments && showAllComments && (
|
||||
<div className="text-center mt-4 mb-4">
|
||||
<button
|
||||
type="button"
|
||||
className="theme-btn"
|
||||
onClick={() => {
|
||||
setShowAllComments(false);
|
||||
}}
|
||||
>
|
||||
Show Less
|
||||
<i className="fa-solid fa-arrow-up"></i>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form comment mới (top-level) */}
|
||||
<div className="mt-5">
|
||||
<CommentForm slug={slug} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
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) {
|
||||
// Lấy comments từ post (đã được bao gồm trong API response)
|
||||
const postComments = post.comments || [];
|
||||
|
||||
// Lấy base URL cho EditorJS images và URL tuyệt đối của bài viết
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
||||
const postUrl = `${baseUrl}/blog/${post.slug}`;
|
||||
const encodedPostUrl = encodeURIComponent(postUrl);
|
||||
const encodedTitle = encodeURIComponent(post.title);
|
||||
|
||||
// Chuyển đổi EditorJS content sang HTML
|
||||
const renderContent = () => {
|
||||
const html = editorjsToHtml(post.content, baseUrl);
|
||||
return { __html: html };
|
||||
};
|
||||
|
||||
// Chuyển đổi EditorJS contentAfterQuote sang HTML
|
||||
const renderContentAfterQuote = () => {
|
||||
const html = editorjsToHtml(post.contentAfterQuote, baseUrl);
|
||||
return { __html: html };
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="col-lg-8 col-12">
|
||||
<div className="news-details-post">
|
||||
<div className="news-details-image">
|
||||
<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 {post.author}
|
||||
</li>
|
||||
<li>
|
||||
<i className="fa-solid fa-calendar-days"></i> {post.publishedAt}
|
||||
</li>
|
||||
<li>
|
||||
<i className="fa-solid fa-comments"></i> {postComments.length} Comments
|
||||
</li>
|
||||
</ul>
|
||||
<h2>{post.title}</h2>
|
||||
<div className="editorjs-render" dangerouslySetInnerHTML={renderContent()} />
|
||||
|
||||
{/* Hình ảnh gallery */}
|
||||
{post.galleryImages && post.galleryImages.length > 0 && (
|
||||
<div className="row g-4 gallery-images-row">
|
||||
{post.galleryImages.map((image, index) => (
|
||||
<div key={index} className={post.galleryImages!.length === 1 ? "col-12" : "col-lg-6 gallery-item"}>
|
||||
<div className="thumb">
|
||||
<img src={getCmsImageUrl(image)} alt={`${post.title} - Image ${index + 1}`} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quote/Sidebar */}
|
||||
{post.quote && (
|
||||
<div className="sideber mt-4 mb-3">
|
||||
<h5>{post.quote}</h5>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Nội dung sau Quote */}
|
||||
{post.contentAfterQuote && (
|
||||
<div
|
||||
className="editorjs-render"
|
||||
dangerouslySetInnerHTML={renderContentAfterQuote()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tags và 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>
|
||||
{post.tags.map((tagName) => {
|
||||
// Tạo slug từ tên tag (hỗ trợ tiếng Việt)
|
||||
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={`https://twitter.com/intent/tweet?url=${encodedPostUrl}&text=${encodedTitle}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Share on Twitter"
|
||||
>
|
||||
<i className="fab fa-twitter"></i>
|
||||
</a>
|
||||
<a
|
||||
href={`https://www.facebook.com/sharer/sharer.php?u=${encodedPostUrl}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Share on Facebook"
|
||||
>
|
||||
<i className="fab fa-facebook-f"></i>
|
||||
</a>
|
||||
<a
|
||||
href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodedPostUrl}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Share on LinkedIn"
|
||||
>
|
||||
<i className="fab fa-linkedin-in"></i>
|
||||
</a>
|
||||
<a
|
||||
href={postUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Open blog post"
|
||||
>
|
||||
<i className="fa-solid fa-link"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CommentsSection slug={post.slug} comments={postComments} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import NewsDetailsContent from "./NewsDetailsContent";
|
||||
import Sidebar from "@/app/blog/components/Sidebar";
|
||||
import type { BlogPost } from "@/types/blog";
|
||||
|
||||
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 post={post} />
|
||||
<Sidebar />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import type { Metadata } from "next";
|
||||
import Breadcrumb from "@/app/components/Breadcrumb";
|
||||
import NewsDetailsSection from "./components/NewsDetailsSection";
|
||||
import { fetchBlogList, fetchBlogDetail } from "@/api/blogsApi";
|
||||
import Sidebar from "@/app/blog/components/Sidebar";
|
||||
import { getCmsImageUrl } from "@/utils";
|
||||
|
||||
// Force dynamic rendering - không cache
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// 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:
|
||||
| Promise<{
|
||||
slug: string;
|
||||
}>
|
||||
| {
|
||||
slug: string;
|
||||
};
|
||||
}
|
||||
|
||||
// SEO metadata cho từng bài blog (Open Graph / thumbnail khi share)
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params:
|
||||
| Promise<{
|
||||
slug: string;
|
||||
}>
|
||||
| {
|
||||
slug: string;
|
||||
};
|
||||
}): Promise<Metadata> {
|
||||
const resolvedParams = params instanceof Promise ? await params : params;
|
||||
const slug = resolvedParams.slug;
|
||||
|
||||
try {
|
||||
const blogResponse = await fetchBlogDetail(slug);
|
||||
const post = blogResponse.data;
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
||||
const url = `${apiUrl}/blog/${post.slug}`;
|
||||
const imageUrl = post.featuredImage
|
||||
? getCmsImageUrl(post.featuredImage)
|
||||
: `${apiUrl}/assets/img/inner-page/news-details/details-1.jpg`;
|
||||
|
||||
return {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
openGraph: {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
url,
|
||||
type: "article",
|
||||
images: [
|
||||
{
|
||||
url: imageUrl,
|
||||
alt: post.title,
|
||||
},
|
||||
],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
images: [imageUrl],
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
title: "Blog Details",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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={post.title} current="Blog Details" />
|
||||
<NewsDetailsSection post={post} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
{
|
||||
"categories": [
|
||||
{
|
||||
"name": "Visa & Immigration",
|
||||
"slug": "visa-immigration",
|
||||
"description": "Tin tức và hướng dẫn về visa, định cư."
|
||||
},
|
||||
{
|
||||
"name": "Study Abroad",
|
||||
"slug": "study-abroad",
|
||||
"description": "Kinh nghiệm du học, trường học, học bổng."
|
||||
},
|
||||
{
|
||||
"name": "Travel Tips",
|
||||
"slug": "travel-tips",
|
||||
"description": "Mẹo du lịch, chuẩn bị hành lý, bảo hiểm."
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
{
|
||||
"name": "WorkVisa",
|
||||
"slug": "work-visa"
|
||||
},
|
||||
{
|
||||
"name": "StudentVisa",
|
||||
"slug": "student-visa"
|
||||
},
|
||||
{
|
||||
"name": "Canada",
|
||||
"slug": "canada"
|
||||
},
|
||||
{
|
||||
"name": "Scholarship",
|
||||
"slug": "scholarship"
|
||||
},
|
||||
{
|
||||
"name": "TravelSafety",
|
||||
"slug": "travel-safety"
|
||||
}
|
||||
],
|
||||
"posts": [
|
||||
{
|
||||
"title": "Ultimate Guide To Getting A Work Visa In Canada",
|
||||
"slug": "ultimate-guide-work-visa-canada",
|
||||
"excerpt": "Tổng hợp đầy đủ các bước xin work visa tại Canada cho người mới bắt đầu, từ điều kiện, hồ sơ đến thời gian xử lý.",
|
||||
"content": "<p>Trong bài viết này, chúng ta sẽ đi qua từng bước cụ thể để xin work visa Canada, từ việc chuẩn bị hồ sơ, chọn chương trình phù hợp đến cách theo dõi tiến độ xử lý hồ sơ. Bạn cũng sẽ tìm thấy một số mẹo thực tế để tránh những sai lầm phổ biến.</p>",
|
||||
"category": ["Visa & Immigration", "Canada"],
|
||||
"tags": ["WorkVisa", "Canada"],
|
||||
"author": "Admin",
|
||||
"status": "published",
|
||||
"publishedAt": "11 March 2025",
|
||||
"isFeatured": true,
|
||||
"featuredImage": "/assets/img/inner-page/news-details/details-1.jpg",
|
||||
"galleryImages": [
|
||||
"/assets/img/inner-page/news-details/details-2.jpg",
|
||||
"/assets/img/inner-page/news-details/details-3.jpg"
|
||||
],
|
||||
"quote": "This blog really helped me understand the difference between student and work visas. The explanations were clear and practical.",
|
||||
"contentAfterQuote": "<p class=\"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>",
|
||||
"commentsCount": 3
|
||||
},
|
||||
{
|
||||
"title": "Top 5 Scholarship Programs For International Students",
|
||||
"slug": "top-5-scholarship-programs-international-students",
|
||||
"excerpt": "Danh sách 5 chương trình học bổng nổi bật dành cho sinh viên quốc tế với mức hỗ trợ hấp dẫn.",
|
||||
"content": "<p>Nếu bạn đang tìm kiếm học bổng để giảm chi phí du học, đây là 5 chương trình bạn không nên bỏ qua. Mỗi chương trình đều có tiêu chí xét tuyển, mức hỗ trợ và thời hạn đăng ký khác nhau.</p><p class=\"mt-4 mb-3\">Học bổng là một trong những cách tốt nhất để giảm gánh nặng tài chính khi du học. Các chương trình học bổng không chỉ hỗ trợ về mặt tài chính mà còn mở ra nhiều cơ hội phát triển nghề nghiệp và mở rộng mạng lưới quan hệ quốc tế.</p>",
|
||||
"category": ["Study Abroad"],
|
||||
"tags": ["StudentVisa", "Scholarship"],
|
||||
"author": "Admin",
|
||||
"status": "published",
|
||||
"publishedAt": "20 March 2025",
|
||||
"isFeatured": false,
|
||||
"featuredImage": "/assets/img/inner-page/news-details/details-1.jpg",
|
||||
"galleryImages": [
|
||||
"/assets/img/inner-page/news-details/details-2.jpg",
|
||||
"/assets/img/inner-page/news-details/details-3.jpg"
|
||||
],
|
||||
"quote": "These scholarship programs opened doors I never thought possible. The application process was straightforward, and the support I received was incredible.",
|
||||
"contentAfterQuote": "<p class=\"mb-3\">Applying for scholarships requires careful planning and preparation. Start by researching each program's requirements, deadlines, and eligibility criteria. Make sure to prepare all necessary documents well in advance, including transcripts, recommendation letters, and personal statements. Each scholarship has its own unique focus, so tailor your application to highlight how you align with their values and goals.</p><p>Remember that scholarship applications are competitive, so it's important to stand out. Showcase your academic achievements, extracurricular activities, and community involvement. Be authentic in your personal statement and demonstrate how the scholarship will help you achieve your educational and career aspirations. With dedication and proper preparation, you can increase your chances of securing financial support for your studies abroad.</p>",
|
||||
"commentsCount": 2
|
||||
},
|
||||
{
|
||||
"title": "10 Travel Safety Tips You Should Know Before Flying",
|
||||
"slug": "10-travel-safety-tips-before-flying",
|
||||
"excerpt": "Những lưu ý quan trọng để đảm bảo an toàn cho chuyến bay và hành trình của bạn.",
|
||||
"content": "<p>An toàn luôn là ưu tiên hàng đầu khi đi du lịch. Dưới đây là 10 tips giúp bạn yên tâm hơn trên mọi chuyến đi, từ việc chuẩn bị giấy tờ, bảo hiểm đến cách bảo vệ tài sản cá nhân.</p><p class=\"mt-4 mb-3\">Du lịch là một trải nghiệm tuyệt vời, nhưng điều quan trọng là phải chuẩn bị kỹ lưỡng để đảm bảo an toàn. Những tips này được đúc kết từ kinh nghiệm thực tế của nhiều du khách và sẽ giúp bạn tránh được những rủi ro không đáng có.</p>",
|
||||
"category": ["Travel Tips"],
|
||||
"tags": ["TravelSafety"],
|
||||
"author": "Admin",
|
||||
"status": "published",
|
||||
"publishedAt": "05 April 2025",
|
||||
"isFeatured": false,
|
||||
"featuredImage": "/assets/img/inner-page/news-details/details-1.jpg",
|
||||
"galleryImages": [
|
||||
"/assets/img/inner-page/news-details/details-2.jpg",
|
||||
"/assets/img/inner-page/news-details/details-3.jpg"
|
||||
],
|
||||
"quote": "These safety tips saved me from potential problems during my trip. I especially appreciated the advice about travel insurance and document preparation.",
|
||||
"contentAfterQuote": "<p class=\"mb-3\">Before you travel, make sure to research your destination thoroughly. Understand local customs, laws, and potential safety concerns. Keep copies of important documents like your passport, visa, and travel insurance in multiple places - both physical and digital. Inform family or friends about your itinerary and check in regularly during your trip.</p><p>When packing, prioritize essential items and keep valuables secure. Use luggage locks and consider travel insurance for expensive items. Stay aware of your surroundings, especially in crowded areas, and trust your instincts if something feels off. By following these safety tips, you can focus on enjoying your journey while staying protected throughout your travels.</p>",
|
||||
"commentsCount": 1
|
||||
}
|
||||
],
|
||||
"recentPosts": [
|
||||
{
|
||||
"title": "Ultimate Guide To Getting A Work Visa In Canada",
|
||||
"slug": "ultimate-guide-work-visa-canada",
|
||||
"thumbnail": "/assets/img/inner-page/news-details/post-1.jpg",
|
||||
"publishedAt": "11 March 2025"
|
||||
},
|
||||
{
|
||||
"title": "Top 5 Scholarship Programs For International Students",
|
||||
"slug": "top-5-scholarship-programs-international-students",
|
||||
"thumbnail": "/assets/img/inner-page/news-details/post-2.jpg",
|
||||
"publishedAt": "20 March 2025"
|
||||
},
|
||||
{
|
||||
"title": "10 Travel Safety Tips You Should Know Before Flying",
|
||||
"slug": "10-travel-safety-tips-before-flying",
|
||||
"thumbnail": "/assets/img/inner-page/news-details/post-3.jpg",
|
||||
"publishedAt": "05 April 2025"
|
||||
}
|
||||
],
|
||||
"comments": [
|
||||
{
|
||||
"postSlug": "ultimate-guide-work-visa-canada",
|
||||
"authorName": "Frank Flores",
|
||||
"authorAvatar": "/assets/img/inner-page/news-details/comment-1.png",
|
||||
"content": "Bài viết rất hữu ích, cảm ơn bạn đã chia sẻ!",
|
||||
"createdAt": "February 10, 2024",
|
||||
"status": "approved",
|
||||
"parentAuthorName": null
|
||||
},
|
||||
{
|
||||
"postSlug": "ultimate-guide-work-visa-canada",
|
||||
"authorName": "Courtney Henry",
|
||||
"authorAvatar": "/assets/img/inner-page/news-details/comment-2.png",
|
||||
"content": "Mình đã làm theo hướng dẫn và hồ sơ được duyệt nhanh hơn hẳn.",
|
||||
"createdAt": "February 12, 2024",
|
||||
"status": "approved",
|
||||
"parentAuthorName": "Frank Flores"
|
||||
},
|
||||
{
|
||||
"postSlug": "top-5-scholarship-programs-international-students",
|
||||
"authorName": "Sarah Johnson",
|
||||
"authorAvatar": "/assets/img/inner-page/news-details/comment-1.png",
|
||||
"content": "Cảm ơn bạn đã chia sẻ thông tin về các chương trình học bổng này. Mình đã apply và đang chờ kết quả!",
|
||||
"createdAt": "March 15, 2025",
|
||||
"status": "approved",
|
||||
"parentAuthorName": null
|
||||
},
|
||||
{
|
||||
"postSlug": "top-5-scholarship-programs-international-students",
|
||||
"authorName": "Michael Chen",
|
||||
"authorAvatar": "/assets/img/inner-page/news-details/comment-2.png",
|
||||
"content": "Bài viết rất chi tiết và hữu ích. Mình đã tìm thấy một chương trình phù hợp với mình.",
|
||||
"createdAt": "March 18, 2025",
|
||||
"status": "approved",
|
||||
"parentAuthorName": null
|
||||
},
|
||||
{
|
||||
"postSlug": "10-travel-safety-tips-before-flying",
|
||||
"authorName": "Jenny Wilson",
|
||||
"authorAvatar": "/assets/img/inner-page/news-details/comment-3.png",
|
||||
"content": "Những tip này rất thực tế, đặc biệt là phần chuẩn bị bảo hiểm!",
|
||||
"createdAt": "March 02, 2024",
|
||||
"status": "approved",
|
||||
"parentAuthorName": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import Breadcrumb from "@/app/components/Breadcrumb";
|
||||
import NewsSection from "@/app/blog/components/NewsSection";
|
||||
import Sidebar from "@/app/blog/components/Sidebar";
|
||||
import { fetchBlogsByCategory, fetchCategoryDetail } from "@/api/blogsApi";
|
||||
|
||||
interface CategoryPageProps {
|
||||
params:
|
||||
| Promise<{
|
||||
slug: string;
|
||||
}>
|
||||
| {
|
||||
slug: string;
|
||||
};
|
||||
searchParams?: Promise<{ search?: string; page?: string }> | { search?: string; page?: string };
|
||||
}
|
||||
|
||||
export default async function CategoryPage({ params, searchParams }: CategoryPageProps) {
|
||||
// Handle both Promise and direct object
|
||||
const resolvedParams = params instanceof Promise ? await params : params;
|
||||
const slug = resolvedParams.slug;
|
||||
const resolvedSearchParams = searchParams instanceof Promise ? await searchParams : searchParams;
|
||||
const searchQuery = resolvedSearchParams?.search?.toString() || "";
|
||||
const pageParam = resolvedSearchParams?.page?.toString() || "1";
|
||||
const currentPage = Number.parseInt(pageParam, 10) || 1;
|
||||
|
||||
// Fetch category detail and blogs
|
||||
let categoryResponse, blogsResponse;
|
||||
try {
|
||||
[categoryResponse, blogsResponse] = await Promise.all([
|
||||
fetchCategoryDetail(slug),
|
||||
fetchBlogsByCategory(slug, {
|
||||
page: currentPage,
|
||||
limit: 3,
|
||||
...(searchQuery ? { search: searchQuery } : {}),
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return (
|
||||
<>
|
||||
<Breadcrumb title="Category" current="Blog Category" />
|
||||
<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>Category not found</h2>
|
||||
<p>The category you are looking for does not exist.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const category = categoryResponse.data;
|
||||
const { blogs, pagination } = blogsResponse.data;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Breadcrumb title={category.name} current="Blog Category" />
|
||||
<NewsSection blogs={blogs} categorySlug={slug} searchQuery={searchQuery} pagination={pagination} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import type { BlogPost } from "@/types/blog";
|
||||
import { getCmsImageUrl } from "@/utils";
|
||||
|
||||
interface NewsListProps {
|
||||
blogs?: BlogPost[];
|
||||
categorySlug?: string;
|
||||
tagSlug?: string;
|
||||
}
|
||||
|
||||
export default function NewsList({ blogs = [], categorySlug, tagSlug }: NewsListProps) {
|
||||
// Use blogs from props (already filtered by API)
|
||||
const posts = blogs;
|
||||
|
||||
// Additional client-side filtering if needed (though API should handle this)
|
||||
if (categorySlug || tagSlug) {
|
||||
// If filters are provided but blogs are not pre-filtered, filter here
|
||||
// This is a fallback - ideally API should handle filtering
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="col-lg-8 col-12">
|
||||
{posts.map((post, index) => (
|
||||
<div
|
||||
key={post.slug}
|
||||
className={`news-standard-post ${index === posts.length - 1 ? "mb-0" : ""}`}
|
||||
>
|
||||
<div className="news-image">
|
||||
<img
|
||||
src={
|
||||
post.featuredImage
|
||||
? getCmsImageUrl(post.featuredImage)
|
||||
: "/assets/img/inner-page/news-details/details-1.jpg"
|
||||
}
|
||||
alt={post.title}
|
||||
/>
|
||||
</div>
|
||||
<div className="news-content">
|
||||
<ul className="news-list">
|
||||
<li>
|
||||
<i className="fa-solid fa-user"></i> By {post.author}
|
||||
</li>
|
||||
<li>
|
||||
<i className="fa-solid fa-calendar-days"></i> {post.publishedAt}
|
||||
</li>
|
||||
<li>
|
||||
<i className="fa-solid fa-comments"></i> {post.commentsCount} Comments
|
||||
</li>
|
||||
</ul>
|
||||
<h3>
|
||||
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
|
||||
</h3>
|
||||
<p>{post.excerpt}</p>
|
||||
<Link href={`/blog/${post.slug}`} className="theme-btn">
|
||||
VIEW MORE <i className="fa-solid fa-arrow-right"></i>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import NewsList from "./NewsList";
|
||||
import Sidebar from "./Sidebar";
|
||||
import Pagination from "./Pagination";
|
||||
import type { BlogPost, BlogPagination } from "@/types";
|
||||
|
||||
interface NewsSectionProps {
|
||||
blogs?: BlogPost[];
|
||||
categorySlug?: string;
|
||||
tagSlug?: string;
|
||||
searchQuery?: string;
|
||||
pagination?: BlogPagination;
|
||||
}
|
||||
|
||||
export default function NewsSection({
|
||||
blogs,
|
||||
categorySlug,
|
||||
tagSlug,
|
||||
searchQuery,
|
||||
pagination,
|
||||
}: NewsSectionProps) {
|
||||
const basePath = categorySlug
|
||||
? `/blog/category/${categorySlug}`
|
||||
: tagSlug
|
||||
? `/blog/tag/${tagSlug}`
|
||||
: "/blog";
|
||||
|
||||
return (
|
||||
<section className="news-standard-section section-padding fix">
|
||||
<div className="container">
|
||||
<div className="news-standard-wrapper">
|
||||
<div className="row g-4">
|
||||
<NewsList blogs={blogs} categorySlug={categorySlug} tagSlug={tagSlug} />
|
||||
<Sidebar searchQuery={searchQuery} />
|
||||
</div>
|
||||
{pagination && pagination.total > 1 && (
|
||||
<div className="row g-4 mt-4">
|
||||
<div className="col-12">
|
||||
<Pagination basePath={basePath} pagination={pagination} searchQuery={searchQuery} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import type { BlogPagination } from "@/types";
|
||||
|
||||
interface PaginationProps {
|
||||
basePath: string;
|
||||
pagination: BlogPagination;
|
||||
searchQuery?: string;
|
||||
}
|
||||
|
||||
export default function Pagination({ basePath, pagination, searchQuery }: PaginationProps) {
|
||||
const { current, total } = pagination;
|
||||
|
||||
if (total <= 1) return null;
|
||||
|
||||
const makeHref = (page: number) => {
|
||||
const params = new URLSearchParams();
|
||||
if (page > 1) params.set("page", page.toString());
|
||||
if (searchQuery) params.set("search", searchQuery);
|
||||
const qs = params.toString();
|
||||
return qs ? `${basePath}?${qs}` : basePath;
|
||||
};
|
||||
|
||||
const pages: number[] = [];
|
||||
for (let i = 1; i <= total; i++) {
|
||||
if (i === 1 || i === total || (i >= current - 2 && i <= current + 2)) {
|
||||
pages.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
const items: (number | "...")[] = [];
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
const page = pages[i];
|
||||
items.push(page);
|
||||
if (i < pages.length - 1 && pages[i + 1] !== page + 1) {
|
||||
items.push("...");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<nav aria-label="Blog pagination" className="mt-4">
|
||||
<ul className="pagination justify-content-center hai-pagination">
|
||||
{current > 1 && (
|
||||
<li className="page-item">
|
||||
<Link className="page-link" href={makeHref(current - 1)} aria-label="Previous page">
|
||||
<i className="fa-solid fa-arrow-left" aria-hidden="true"></i>
|
||||
</Link>
|
||||
</li>
|
||||
)}
|
||||
|
||||
{items.map((item, idx) =>
|
||||
item === "..." ? (
|
||||
<li key={`ellipsis-${idx}`} className="page-item disabled">
|
||||
<span className="page-link">...</span>
|
||||
</li>
|
||||
) : (
|
||||
<li key={item} className={`page-item ${item === current ? "active" : ""}`}>
|
||||
{item === current ? (
|
||||
<span className="page-link">{item}</span>
|
||||
) : (
|
||||
<Link className="page-link" href={makeHref(item as number)}>
|
||||
{item}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
|
||||
{current < total && (
|
||||
<li className="page-item">
|
||||
<Link className="page-link" href={makeHref(current + 1)} aria-label="Next page">
|
||||
<i className="fa-solid fa-arrow-right" aria-hidden="true"></i>
|
||||
</Link>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { fetchCategories, fetchRecentBlogs, fetchPopularTags } from "@/api/blogsApi";
|
||||
import { getCmsImageUrl } from "@/utils";
|
||||
|
||||
interface SidebarProps {
|
||||
searchQuery?: string;
|
||||
}
|
||||
|
||||
export default async function Sidebar({ searchQuery }: SidebarProps) {
|
||||
// Fetch data from API
|
||||
const [categoriesResponse, recentBlogsResponse, tagsResponse] = await Promise.all([
|
||||
fetchCategories(),
|
||||
fetchRecentBlogs(5),
|
||||
fetchPopularTags(10),
|
||||
]);
|
||||
|
||||
const categories = categoriesResponse.data;
|
||||
const recentPosts = recentBlogsResponse.data;
|
||||
const tags = tagsResponse.data;
|
||||
|
||||
return (
|
||||
<div className="col-lg-4 col-12">
|
||||
<div className="main-sideber">
|
||||
{/* Search Widget */}
|
||||
<div className="news-sideber-box">
|
||||
<div className="search-widget">
|
||||
<form action="/blog" method="GET">
|
||||
<input
|
||||
type="text"
|
||||
name="search"
|
||||
placeholder="Search Blog"
|
||||
defaultValue={searchQuery || ""}
|
||||
/>
|
||||
<button type="submit">
|
||||
<i className="fa-solid fa-magnifying-glass"></i>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/* Categories */}
|
||||
<div className="news-sideber-box">
|
||||
<div className="wid-title">
|
||||
<h3>Categories</h3>
|
||||
</div>
|
||||
<div className="news-widget-categories">
|
||||
<ul>
|
||||
{categories.map((category) => {
|
||||
const postCount = category.postCount || 0;
|
||||
return (
|
||||
<li key={category.slug}>
|
||||
<Link href={`/blog/category/${category.slug}`}>
|
||||
<i className="fa-solid fa-chevrons-right"></i> {category.name}
|
||||
</Link>
|
||||
<span>({String(postCount).padStart(2, "0")})</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
{/* Recent Post */}
|
||||
<div className="news-sideber-box">
|
||||
<div className="wid-title">
|
||||
<h3>Recent Post</h3>
|
||||
</div>
|
||||
<div className="recent-post-area">
|
||||
{recentPosts.map((post) => (
|
||||
<div key={post.slug} className="recent-items">
|
||||
<div className="recent-thumb">
|
||||
<img
|
||||
src={getCmsImageUrl(post.thumbnail) || "/assets/img/inner-page/news-details/details-1.jpg"}
|
||||
alt={post.title}
|
||||
/>
|
||||
</div>
|
||||
<div className="recent-content">
|
||||
<h6>
|
||||
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
|
||||
</h6>
|
||||
<ul>
|
||||
<li>{post.publishedAt}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{/* Tag Cloud */}
|
||||
<div className="news-sideber-box mb-0">
|
||||
<div className="wid-title">
|
||||
<h3>Tag Cloud</h3>
|
||||
</div>
|
||||
<div className="news-widget-categories">
|
||||
<div className="tagcloud">
|
||||
{tags.map((tag) => (
|
||||
<Link key={tag.slug} href={`/blog/tag/${tag.slug}`}>
|
||||
{tag.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import Breadcrumb from "@/app/components/Breadcrumb";
|
||||
import NewsSection from "./components/NewsSection";
|
||||
import { fetchBlogList } from "@/api/blogsApi";
|
||||
|
||||
interface NewsPageProps {
|
||||
searchParams?: Promise<{ search?: string; page?: string }> | { search?: string; page?: string };
|
||||
}
|
||||
|
||||
export default async function NewsPage({ searchParams }: NewsPageProps) {
|
||||
const resolvedSearchParams = searchParams instanceof Promise ? await searchParams : searchParams;
|
||||
const searchQuery = resolvedSearchParams?.search?.toString() || "";
|
||||
const pageParam = resolvedSearchParams?.page?.toString() || "1";
|
||||
const currentPage = Number.parseInt(pageParam, 10) || 1;
|
||||
|
||||
// Fetch blog list from API
|
||||
const blogResponse = await fetchBlogList({
|
||||
page: currentPage,
|
||||
limit: 3,
|
||||
...(searchQuery ? { search: searchQuery } : {}),
|
||||
});
|
||||
const { blogs, pagination } = blogResponse.data;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Breadcrumb title={searchQuery ? `Search: ${searchQuery}` : "Blog Standard"} current="Blog Standard" />
|
||||
<NewsSection blogs={blogs} searchQuery={searchQuery} pagination={pagination} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import Breadcrumb from "@/app/components/Breadcrumb";
|
||||
import NewsSection from "@/app/blog/components/NewsSection";
|
||||
import Sidebar from "@/app/blog/components/Sidebar";
|
||||
import { fetchBlogsByTag, fetchTagDetail } from "@/api/blogsApi";
|
||||
|
||||
interface TagPageProps {
|
||||
params:
|
||||
| Promise<{
|
||||
slug: string;
|
||||
}>
|
||||
| {
|
||||
slug: string;
|
||||
};
|
||||
searchParams?: Promise<{ search?: string; page?: string }> | { search?: string; page?: string };
|
||||
}
|
||||
|
||||
export default async function TagPage({ params, searchParams }: TagPageProps) {
|
||||
// Handle both Promise and direct object
|
||||
const resolvedParams = params instanceof Promise ? await params : params;
|
||||
const slug = resolvedParams.slug;
|
||||
const resolvedSearchParams = searchParams instanceof Promise ? await searchParams : searchParams;
|
||||
const searchQuery = resolvedSearchParams?.search?.toString() || "";
|
||||
const pageParam = resolvedSearchParams?.page?.toString() || "1";
|
||||
const currentPage = Number.parseInt(pageParam, 10) || 1;
|
||||
|
||||
// Fetch tag detail and blogs
|
||||
let tagResponse, blogsResponse;
|
||||
try {
|
||||
[tagResponse, blogsResponse] = await Promise.all([
|
||||
fetchTagDetail(slug),
|
||||
fetchBlogsByTag(slug, {
|
||||
page: currentPage,
|
||||
limit: 3,
|
||||
...(searchQuery ? { search: searchQuery } : {}),
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return (
|
||||
<>
|
||||
<Breadcrumb title="Tag" current="Blog Tag" />
|
||||
<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>Tag not found</h2>
|
||||
<p>The tag you are looking for does not exist.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const tag = tagResponse.data;
|
||||
const { blogs, pagination } = blogsResponse.data;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Breadcrumb title={tag.name} current="Blog Tag" />
|
||||
<NewsSection blogs={blogs} tagSlug={slug} searchQuery={searchQuery} pagination={pagination} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user