diff --git a/src/app/(routes)/blog/posts/[postSlug]/body.tsx b/src/app/(routes)/blog/posts/[postSlug]/body.tsx new file mode 100644 index 0000000..4f75dcc --- /dev/null +++ b/src/app/(routes)/blog/posts/[postSlug]/body.tsx @@ -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 ( +

+ {block.text} +

+ ); + case "h2": + return ( +

+ {block.text} +

+ ); + case "list": + return ( + + ); + default: + return ( +

+ {block.text} +

+ ); + } + }); + } + + const fallbackText = asText(fallback).trim(); + + return ( +

+ {fallbackText === "" ? EMPTY_BODY_MESSAGE : fallbackText} +

+ ); +} diff --git a/src/app/(routes)/blog/posts/[postSlug]/coverImage.ts b/src/app/(routes)/blog/posts/[postSlug]/coverImage.ts new file mode 100644 index 0000000..4d9631a --- /dev/null +++ b/src/app/(routes)/blog/posts/[postSlug]/coverImage.ts @@ -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; +} diff --git a/src/app/(routes)/blog/posts/[postSlug]/page.tsx b/src/app/(routes)/blog/posts/[postSlug]/page.tsx index dfa8ead..d8cfbb3 100644 --- a/src/app/(routes)/blog/posts/[postSlug]/page.tsx +++ b/src/app/(routes)/blog/posts/[postSlug]/page.tsx @@ -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 { 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 { 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 { 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

- {postData.post.title} + {post.title}

-

- {postData.post.excerpt} -

+ {post.excerpt ? ( +

+ {post.excerpt} +

+ ) : null}
-
-

- {dict.blog.homePage.by} + {authorName ? ( +

+

+ {dict.blog.homePage.by} +

+ + {authorName} + +
+ ) : null} + {categoryName && categorySlug ? ( +
+

+ {dict.blog.homePage.in} +

+ + {categoryName} + +
+ ) : null} + {publishedDate ? ( +

+ {publishedDate}

- - {postData.post.author.name} - -
-
-

- {dict.blog.homePage.in} -

- - {postData.post.category.name} - -
+ ) : null}
  • {dict.blog.header.Home} @@ -93,7 +134,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
  • {dict.blog.header.Categories} @@ -102,20 +143,22 @@ export default async function SinglePost(props: PostSlugPagepropsType) { -
  • -
  • - - {postData.post.category.name} - - - - - -
  • + {categoryName && categorySlug ? ( +
  • + + {categoryName} + + + - + +
  • + ) : null}
  • - {params.postSlug.replaceAll(/%20|-|_/g, " ")} + {post.title}

@@ -131,120 +174,64 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
- {`${postData.post.title} -

- 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,{" "} - - WP Page Builder - - . If you’re tired of the same old page builder plugins, this is - one you should try out. -

-

- What’s Special About WP Page Builder? -

-

- 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. -

- {"post -

- Here are some of the amazing add-ons included: -

-
    -
  • - Form: 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. -
  • -
  • - Carousel: 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. -
  • -
  • - Post Grid: Display blog posts - in grids defining the number of posts and styling the look. -
  • -
  • - Media Carousel: Create a - media carousel and showcase your media files beautifully. -
  • -
  • - Testimonials: WP Page Builder - comes with an add-on to display client testimonials. -
  • -
-
-
- {"post -
-
- {"post -
+ {coverImage ? ( + {`${post.title} + ) : null} + +
+ {renderBody(post.body, post.excerpt)}
-

- “ WP Page Builder offers a lot of ready-to-use design blocks to - make your site development process a lot faster and easier “ -

-
-
- {"user - - parsa aghayi - -

- {dict.blog.postSinglePage.followMe} + + {postTags.length > 0 ? ( +

    + {postTags.map((tag) => ( +
  • + + #{tag.name} + +
  • + ))} +
+ ) : null} + + {authorName ? ( +
+
+ {"post - @parsaaghayi + {authorName} - . -

+

+ {dict.blog.postSinglePage.followMe} + + @parsaaghayi + + . +

+
-
+ ) : null}
@@ -256,7 +243,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) { alt="socials-vertical icons" />

- {postData.post.likes} + {post.likes}

@@ -267,7 +254,7 @@ export default async function SinglePost(props: PostSlugPagepropsType) { alt="socials-vertical icons" />

- {postData.post.views} + {post.views}

@@ -286,60 +273,54 @@ export default async function SinglePost(props: PostSlugPagepropsType) { */}
- {postData.related_posts.map( - (relatedPost: PostType, key: number) => { - if (key < 2) { - return ( -
( +
+ {`${relatedPost.title} +
+
+

+ {dict.blog.homePage.by} +

+ - {`${relatedPost.title} -
-
-

- {dict.blog.homePage.by} -

- - {relatedPost.author.name} - -
-
-

- {dict.blog.homePage.in} -

- - {relatedPost.category.name} - -
-
- - {relatedPost.title} - -

- {relatedPost.excerpt} -

-
- ); - } - }, - )} + {relatedPost.author.name} + +
+
+

+ {dict.blog.homePage.in} +

+ + {relatedPost.category.name} + +
+
+ + {relatedPost.title} + +

+ {relatedPost.excerpt} +

+
+ ))}