Render the real post body instead of a hardcoded article

The blog post page ignored the API entirely and rendered a hardcoded
placeholder article, so every published post showed the same invented content
regardless of what was stored in the database. Metadata (author, category,
date, tags, counts) came from placeholders too.

post.body is plain text written from the admin panel, so parse it into
paragraphs, h1/h2 headings and lists and render the pieces as text nodes.
dangerouslySetInnerHTML is deliberately not used: there is no sanitiser in
this app, so injecting author-supplied HTML would be an XSS hole.

The body falls back to the excerpt, then to an empty-state message. The cover
image now renders only when featured_image holds a real URL; the seeded rows
point at via.placeholder.com, so they render nothing rather than a broken or
third-party image.

Also guard the about-me section: title and description are NULL in the live
database, so it now falls back to Persian text, omits the skills grid when
there are none, and degrades to a skeleton if the API fails instead of
crashing.
This commit is contained in:
root committed 2026-10-01 16:33:12 -04:00
1 parent 2b7eda656a
commit 546ee8cc22
3 files changed
+392 -205

No files matched your search

@@ -0,0 +1,161 @@
import { type ReactNode } from "react";
export type BodyBlock =
| { kind: "h1"; text: string }
| { kind: "h2"; text: string }
| { kind: "paragraph"; text: string }
| { kind: "list"; items: string[] };
const H1_LINE = /^#\s+(.*)$/;
const H2_LINE = /^##\s+(.*)$/;
const LIST_ITEM_LINE = /^-\s+(.*)$/;
const PARAGRAPH_CLASS = "text-[20px] font-[400] text-blog-text-default";
const LIST_CLASS = "my-5 flex list-disc flex-col gap-2";
const LIST_ITEM_CLASS = "ms-5 text-[20px] font-[400] text-blog-text-default";
const H1_CLASS = "mt-10 text-[28px] font-[700] text-blog-text-default";
const H2_CLASS = "mt-10 text-[28px] font-[600] text-blog-text-default";
const EMPTY_BODY_MESSAGE = "متنی برای نمایش وجود ندارد.";
function asText(value: unknown): string {
return typeof value === "string" ? value : "";
}
/**
* Splits a markdown-ish post body into renderable blocks:
* blank lines separate blocks, "## " lines become h2, "# " lines become h1,
* consecutive "- " lines become a single list, anything else is a paragraph.
* Content is returned as plain strings, never as HTML.
*/
export function parseBody(body: unknown): BodyBlock[] {
const source = asText(body);
if (source.trim() === "") {
return [];
}
const blocks: BodyBlock[] = [];
let paragraphLines: string[] = [];
let listItems: string[] = [];
const flushParagraph = () => {
const text = paragraphLines.join(" ").trim();
paragraphLines = [];
if (text !== "") {
blocks.push({ kind: "paragraph", text });
}
};
const flushList = () => {
if (listItems.length > 0) {
blocks.push({ kind: "list", items: listItems });
listItems = [];
}
};
const flushAll = () => {
flushParagraph();
flushList();
};
for (const rawLine of source.replace(/\r\n?/g, "\n").split("\n")) {
const line = rawLine.replace(/\s+$/, "");
if (line.trim() === "") {
flushAll();
continue;
}
const h2 = H2_LINE.exec(line);
if (h2) {
flushAll();
blocks.push({ kind: "h2", text: h2[1].trim() });
continue;
}
const h1 = H1_LINE.exec(line);
if (h1) {
flushAll();
blocks.push({ kind: "h1", text: h1[1].trim() });
continue;
}
const listItem = LIST_ITEM_LINE.exec(line);
if (listItem) {
flushParagraph();
listItems.push(listItem[1].trim());
continue;
}
flushList();
paragraphLines.push(line.trim());
}
flushAll();
return blocks.filter(
(block) =>
block.kind !== "list" || block.items.some((item) => item.trim() !== ""),
);
}
/**
* Renders the post body as React elements. Falls back to the post excerpt and,
* when that is empty too, to a short Persian notice. Text is always rendered as
* text nodes (no dangerouslySetInnerHTML anywhere).
*/
export function renderBody(body: unknown, fallback?: unknown): ReactNode {
const blocks = parseBody(body);
if (blocks.length > 0) {
return blocks.map((block, index) => {
const key = `${block.kind}-${index}`;
switch (block.kind) {
case "h1":
return (
<h1 key={key} className={H1_CLASS}>
{block.text}
</h1>
);
case "h2":
return (
<h2 key={key} className={H2_CLASS}>
{block.text}
</h2>
);
case "list":
return (
<ul key={key} className={LIST_CLASS}>
{block.items
.filter((item) => item.trim() !== "")
.map((item, itemIndex) => (
<li key={`${key}-${itemIndex}`} className={LIST_ITEM_CLASS}>
{item}
</li>
))}
</ul>
);
default:
return (
<p key={key} className={PARAGRAPH_CLASS}>
{block.text}
</p>
);
}
});
}
const fallbackText = asText(fallback).trim();
return (
<p className={PARAGRAPH_CLASS}>
{fallbackText === "" ? EMPTY_BODY_MESSAGE : fallbackText}
</p>
);
}
@@ -0,0 +1,45 @@
const PLACEHOLDER_IMAGE_HOSTS = ["via.placeholder.com", "placeholder.com"];
function isPlaceholderHost(hostname: string): boolean {
return PLACEHOLDER_IMAGE_HOSTS.some(
(host) => hostname === host || hostname.endsWith(`.${host}`),
);
}
/**
* Returns the src usable by next/image, or null when the value is missing,
* blank, a known placeholder host or not an http(s)/root-relative url.
*/
export function getCoverImageSrc(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const src = value.trim();
if (src === "") {
return null;
}
if (src.startsWith("/")) {
return src;
}
let url: URL;
try {
url = new URL(src);
} catch {
return null;
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
return null;
}
if (isPlaceholderHost(url.hostname.toLowerCase())) {
return null;
}
return src;
}
+186 -205
View File
@@ -9,10 +9,13 @@ import { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import { renderBody } from "./body";
import { getCoverImageSrc } from "./coverImage";
async function fetchPostData(postSlug: string): Promise<PostSlugPagePostType> {
const res = await fetch(
`${process.env.NEXT_PUBLIC_BLOG_API_URL}/posts/${postSlug}`, {
`${process.env.NEXT_PUBLIC_BLOG_API_URL}/posts/${postSlug}`,
{
cache: process.env.NEXT_PUBLIC_BLOG_CACHE ? "force-cache" : "no-store",
}
);
@@ -24,9 +27,26 @@ async function fetchPostData(postSlug: string): Promise<PostSlugPagePostType> {
return res.json();
}
function formatPostDate(value: unknown): string {
if (typeof value !== "string" || value.trim() === "") {
return "";
}
const parsed = new Date(value.trim());
if (Number.isNaN(parsed.getTime())) {
return value.trim();
}
return new Intl.DateTimeFormat("fa-IR", { dateStyle: "medium" }).format(
parsed,
);
}
export async function generateMetadata(props: PostSlugPagepropsType): Promise<Metadata> {
const params = await props.params;
const post: PostSlugPagePostType = await fetchPostData(params.postSlug);
const coverImage = getCoverImageSrc(post.post.featured_image);
return {
title: post.post.title,
@@ -34,7 +54,7 @@ export async function generateMetadata(props: PostSlugPagepropsType): Promise<Me
openGraph: {
title: post.post.title,
description: post.post.excerpt,
images: [post.post.featured_image],
...(coverImage ? { images: [coverImage] } : {}),
},
};
}
@@ -43,46 +63,67 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
const params = await props.params;
const dict = await getDictionary(await getDefaultLocale());
const postData: PostSlugPagePostType = await fetchPostData(params.postSlug);
const post = postData.post;
const coverImage = getCoverImageSrc(post.featured_image);
const authorName = post.author?.name ?? "";
const categoryName = post.category?.name ?? "";
const categorySlug = post.category?.slug ?? "";
const publishedDate = formatPostDate(post.published_at);
const postTags = Array.isArray(post.tags) ? post.tags : [];
const relatedPosts = Array.isArray(postData.related_posts)
? postData.related_posts
: [];
return (
<div className="flex w-full max-w-[1280px] flex-wrap justify-center sm:my-10">
<div className="mt-5 flex w-full max-w-[90%] flex-col gap-5">
<h1 className="text-[36px] font-[700] capitalize text-blog-text-default">
{postData.post.title}
{post.title}
</h1>
<p className="text-[18px] font-[600] text-blog-text-default">
{postData.post.excerpt}
</p>
{post.excerpt ? (
<p className="text-[18px] font-[600] text-blog-text-default">
{post.excerpt}
</p>
) : null}
<div className="flex w-full flex-wrap gap-2">
<div className="flex gap-2">
<p className="text-[14px] font-[600] text-blog-text-passive md:text-[16px]">
{dict.blog.homePage.by}
{authorName ? (
<div className="flex gap-2">
<p className="text-[14px] font-[600] text-blog-text-passive md:text-[16px]">
{dict.blog.homePage.by}
</p>
<Link
href={"/"}
className="whitespace-nowrap text-[14px] font-[400] capitalize text-blog-text-default hover:underline md:text-[16px]"
>
{authorName}
</Link>
</div>
) : null}
{categoryName && categorySlug ? (
<div className="whit flex gap-2">
<p className="text-[16px] font-[600] text-blog-text-passive">
{dict.blog.homePage.in}
</p>
<Link
href={`/blog/categories/${categorySlug}`}
className="text-[16px] font-[400] text-blog-text-default hover:underline"
>
{categoryName}
</Link>
</div>
) : null}
{publishedDate ? (
<p className="whitespace-nowrap text-[16px] font-[400] text-blog-text-passive">
{publishedDate}
</p>
<Link
href={"/"}
className="whitespace-nowrap text-[14px] font-[400] capitalize text-blog-text-default hover:underline md:text-[16px]"
>
{postData.post.author.name}
</Link>
</div>
<div className="whit flex gap-2">
<p className="text-[16px] font-[600] text-blog-text-passive">
{dict.blog.homePage.in}
</p>
<Link
href={`/blog/categories/${postData.post.category.slug}`}
className="text-[16px] font-[400] text-blog-text-default hover:underline"
>
{postData.post.category.name}
</Link>
</div>
) : null}
</div>
</div>
<div className="my-10 flex w-full max-w-[90%] flex-wrap justify-center gap-5">
<ul className="my-10 flex w-full flex-wrap gap-2">
<li className="flex items-center gap-2">
<Link
href={"/blog"}
href="/blog"
className="text-[12px] font-[400] capitalize text-blog-text-passive hover:underline"
>
{dict.blog.header.Home}
@@ -93,7 +134,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
</li>
<li className="flex items-center gap-2">
<Link
href={"/blog/categories"}
href="/blog/categories"
className="text-[12px] font-[400] capitalize text-blog-text-passive hover:underline"
>
{dict.blog.header.Categories}
@@ -102,20 +143,22 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
-
</span>
</li>
<li className="flex items-center gap-2">
<Link
href={`/blog/categories/${postData.post.category.slug}`}
className="text-[12px] font-[400] capitalize text-blog-text-passive hover:underline"
>
{postData.post.category.name}
</Link>
<span className="mt-[-2px] -rotate-45 scale-[3] select-none text-[12px] font-[400] text-blog-text-passive">
-
</span>
</li>
{categoryName && categorySlug ? (
<li className="flex items-center gap-2">
<Link
href={`/blog/categories/${categorySlug}`}
className="text-[12px] font-[400] capitalize text-blog-text-passive hover:underline"
>
{categoryName}
</Link>
<span className="mt-[-2px] -rotate-45 scale-[3] select-none text-[12px] font-[400] text-blog-text-passive">
-
</span>
</li>
) : null}
<li className="flex items-center gap-2">
<p className="text-[12px] font-[600] capitalize text-blog-text-default">
{params.postSlug.replaceAll(/%20|-|_/g, " ")}
{post.title}
</p>
</li>
</ul>
@@ -131,120 +174,64 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
</div>
<div className="relative flex w-[95%] flex-wrap gap-5">
<img
className="w-full"
src={postData.post.featured_image}
alt={`${postData.post.title} post featured image`}
/>
<p className="text-[20px] font-[400] text-blog-text-default">
People’s quest for creating websites has easily taken us to a new
era of site development. Where, with the availability of robust
page building tools, creating websites has become a lot more fun
(especially for non-developers). The multitude of tools and
plugins available to you is vast when you try building websites on
WordPress. Today we’ll explore a new one,{" "}
<span className="text-[20px] font-[400] text-blog-blue">
WP Page Builder
</span>
. If you’re tired of the same old page builder plugins, this is
one you should try out.
</p>
<h2 className="mt-20 text-[28px] font-[600] text-blog-text-default">
What’s Special About WP Page Builder?
</h2>
<p className="text-[20px] font-[400] text-blog-text-default">
Wondering what makes WP Page Builder so special? I would say, what
doesn’t? It’s developed by the team over at Themeum, who has been
creating WordPress themes since 2013. As mentioned above, the
plugin is a full pack of essential site building elements with all
modern the modern functionality you’ve come to expect from a page
builder plugin. Let’s have a look below at all of the juicy
features WP Page Builder includes.
</p>
<img
className="w-full"
src={"/images/blog/posts/post/2.png"}
alt={"post image 2"}
/>
<p className="text-[20px] font-[400] text-blog-text-default">
Here are some of the amazing add-ons included:
</p>
<ul className="flex list-disc flex-col gap-10">
<li className="ms-5 text-[20px] font-[400] text-blog-text-default">
<span className="font-bold">Form:</span> Create web forms
effortlessly. It gives you a convenient way to style your forms
as you desire. The Form add-on itself is capable of setting up
any kind of form without needing to install any plugin.
Moreover, you can manage form plugins and enable reCAPTCHA with
just a simple click. There is also an add-on for Contact Form 7
if you prefer.
</li>
<li className="ms-5 text-[20px] font-[400] text-blog-text-default">
<span className="font-bold">Carousel:</span> It’s hard to find
an advanced add-on like a carousel in a free page builder
plugin, but WP Page Builder lets you create stunning hero
sliders without having to pay for it.
</li>
<li className="ms-5 text-[20px] font-[400] text-blog-text-default">
<span className="font-bold">Post Grid:</span> Display blog posts
in grids defining the number of posts and styling the look.
</li>
<li className="ms-5 text-[20px] font-[400] text-blog-text-default">
<span className="font-bold">Media Carousel:</span> Create a
media carousel and showcase your media files beautifully.
</li>
<li className="ms-5 text-[20px] font-[400] text-blog-text-default">
<span className="font-bold">Testimonials:</span> WP Page Builder
comes with an add-on to display client testimonials.
</li>
</ul>
<div className="my-10 flex w-full justify-between">
<div className="w-[48%]">
<img
className="w-full"
src={"/images/blog/posts/post/3.png"}
alt={"post image 3"}
/>
</div>
<div className="w-[48%]">
<img
className="w-full"
src={"/images/blog/posts/post/4.png"}
alt={"post image 4"}
/>
</div>
{coverImage ? (
<Image
className="h-auto w-full"
src={coverImage}
width={1200}
height={800}
alt={`${post.title} post featured image`}
/>
) : null}
<div className="flex w-full flex-col gap-5">
{renderBody(post.body, post.excerpt)}
</div>
<p className="my-10 text-center text-[24px] font-[400] text-blog-purple">
“ WP Page Builder offers a lot of ready-to-use design blocks to
make your site development process a lot faster and easier “
</p>
<div className="flex w-full justify-center">
<div className="flex flex-col items-center">
<Image
src={"/images/blog/users/1.png"}
alt={"user 1 image"}
width={80}
height={80}
className="mb-2 rounded-full"
/>
<Link
href={"/"}
className="text-center text-[18px] font-[400] capitalize text-blog-text-default hover:underline"
>
parsa aghayi
</Link>
<p className="text-[16px] font-[400] capitalize text-blog-text-default">
{dict.blog.postSinglePage.followMe}
{postTags.length > 0 ? (
<ul className="my-5 flex w-full flex-wrap gap-2">
{postTags.map((tag) => (
<li key={tag.id}>
<Link
href={`/blog/tags/${tag.slug}`}
className="text-[14px] font-[400] text-blog-blue hover:underline"
>
#{tag.name}
</Link>
</li>
))}
</ul>
) : null}
{authorName ? (
<div className="my-10 flex w-full justify-center">
<div className="flex flex-col items-center">
<Image
src={"/images/blog/users/1.png"}
alt={"post author image"}
width={80}
height={80}
className="mb-2 rounded-full"
/>
<Link
href={"/"}
className="ms-1 text-[16px] font-[400] lowercase text-blog-blue"
href="/"
className="text-center text-[18px] font-[400] capitalize text-blog-text-default hover:underline"
>
@parsaaghayi
{authorName}
</Link>
.
</p>
<p className="text-[16px] font-[400] capitalize text-blog-text-default">
{dict.blog.postSinglePage.followMe}
<Link
href="/"
className="ms-1 text-[16px] font-[400] lowercase text-blog-blue"
>
@parsaaghayi
</Link>
.
</p>
</div>
</div>
</div>
) : null}
</div>
<div className="sticky top-[150px] flex flex-col items-end gap-5">
@@ -256,7 +243,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
alt="socials-vertical icons"
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{postData.post.likes}
{post.likes}
</p>
</div>
<div className="flex cursor-pointer flex-col gap-1">
@@ -267,7 +254,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
alt="socials-vertical icons"
/>
<p className="whitespace-nowrap text-center text-[14px] font-[600] text-blog-text-default">
{postData.post.views}
{post.views}
</p>
</div>
</div>
@@ -286,60 +273,54 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
</Link> */}
</div>
<div className="flex w-full flex-wrap justify-between gap-5">
{postData.related_posts.map(
(relatedPost: PostType, key: number) => {
if (key < 2) {
return (
<div
key={relatedPost.id}
className="flex w-full flex-col items-center justify-start gap-1 sm:w-[45%]"
{relatedPosts.slice(0, 2).map((relatedPost: PostType) => (
<div
key={relatedPost.id}
className="flex w-full flex-col items-center justify-start gap-1 sm:w-[45%]"
>
<Image
className="mb-3 rounded-md"
src={relatedPost.featured_image}
alt={`${relatedPost.title} post featured image`}
loading="lazy"
width={600}
height={500}
/>
<div className="mb-2 flex w-full flex-wrap gap-2">
<div className="flex gap-2">
<p className="text-[14px] font-[600] text-blog-text-passive md:text-[16px]">
{dict.blog.homePage.by}
</p>
<Link
href="/"
className="whitespace-nowrap text-[14px] font-[400] capitalize text-blog-text-default hover:underline md:text-[16px]"
>
<Image
className="mb-3 rounded-md"
src={relatedPost.featured_image}
alt={`${relatedPost.title} post featured image`}
loading="lazy"
width={600}
height={500}
/>
<div className="mb-2 flex w-full flex-wrap gap-2">
<div className="flex gap-2">
<p className="text-[14px] font-[600] text-blog-text-passive md:text-[16px]">
{dict.blog.homePage.by}
</p>
<Link
href={"/"}
className="whitespace-nowrap text-[14px] font-[400] capitalize text-blog-text-default hover:underline md:text-[16px]"
>
{relatedPost.author.name}
</Link>
</div>
<div className="whit flex gap-2">
<p className="text-[16px] font-[600] text-blog-text-passive">
{dict.blog.homePage.in}
</p>
<Link
className="text-[16px] font-[400] text-blog-text-default hover:underline"
href={`/blog/categories/${relatedPost.category.slug}`}
>
{relatedPost.category.name}
</Link>
</div>
</div>
<Link
href={`/blog/posts/${relatedPost.slug}`}
className="w-full text-start text-[24px] font-[600] text-blog-text-default hover:underline"
>
{relatedPost.title}
</Link>
<p className="w-full text-start text-[16px] font-[400] text-blog-text-default">
{relatedPost.excerpt}
</p>
</div>
);
}
},
)}
{relatedPost.author.name}
</Link>
</div>
<div className="whit flex gap-2">
<p className="text-[16px] font-[600] text-blog-text-passive">
{dict.blog.homePage.in}
</p>
<Link
className="text-[16px] font-[400] text-blog-text-default hover:underline"
href={`/blog/categories/${relatedPost.category.slug}`}
>
{relatedPost.category.name}
</Link>
</div>
</div>
<Link
href={`/blog/posts/${relatedPost.slug}`}
className="w-full text-start text-[24px] font-[600] text-blog-text-default hover:underline"
>
{relatedPost.title}
</Link>
<p className="w-full text-start text-[16px] font-[400] text-blog-text-default">
{relatedPost.excerpt}
</p>
</div>
))}
</div>
</div>
</div>