Richer blog reading experience: TOC, reading time, share, prev/next, newsletter CTA
Deploy Frontend / deploy (push) Successful in 1m8s

- Single post: sticky table of contents from h2 headings (anchored ids),
  estimated reading time badge, working share buttons (X/LinkedIn/Telegram/
  copy link), and same-language previous/next navigation cards
- Home: featured hero gains tag chips, reading time and a read CTA; new
  newsletter subscribe band linking to the site's contact address
- Both en/fa dictionaries updated for the new UI labels
This commit is contained in:
Parsa Aghayi committed 2026-10-02 09:49:36 -04:00
1 parent 2ef4d41588
commit 2d2371da9d
10 files changed
+339 -23

No files matched your search

@@ -3,6 +3,7 @@ import { getDefaultLocale } from "@/app/lib/functions/utils";
import { PostType } from "@/app/types/types";
import Image from "next/image";
import Link from "next/link";
import { estimateReadingTime } from "../../../posts/[postSlug]/readingTime";
interface NewProps {
data: PostType[];
@@ -10,12 +11,15 @@ interface NewProps {
export default async function New({ data }: NewProps) {
const dict = await getDictionary(await getDefaultLocale());
const featured = data[0];
const readingTime = estimateReadingTime(featured.body, await getDefaultLocale());
const featuredTags = Array.isArray(featured.tags) ? featured.tags.slice(0, 2) : [];
return (
<div className="flex w-full max-w-[95%] flex-wrap justify-between gap-5">
<div className="relative flex h-[300px] w-full flex-col justify-center overflow-hidden rounded-md border sm:h-[400px] md:h-auto md:w-[60%]">
<div className="relative flex h-[340px] w-full flex-col justify-center overflow-hidden rounded-md border sm:h-[420px] md:h-auto md:w-[60%]">
<Image
src={data[0].featured_image}
alt={`${data[0].title} featured image`}
src={featured.featured_image}
alt={`${featured.title} featured image`}
fill={true}
priority
/>
@@ -31,7 +35,7 @@ export default async function New({ data }: NewProps) {
href={"/"}
className="text-[15px] font-[400] capitalize text-white underline md:text-[16px]"
>
{data[0].author.name}
{featured.author.name}
</Link>
</div>
<div className="flex">
@@ -39,24 +43,50 @@ export default async function New({ data }: NewProps) {
{dict.blog.homePage.in}
</p>
<Link
href={`/blog/categories/${data[0].category.slug}`}
href={`/blog/categories/${featured.category.slug}`}
className="text-[15px] font-[400] text-white underline sm:text-[16px]"
>
{data[0].category.name}
{featured.category.name}
</Link>
</div>
</div>
<Link
href={`/blog/posts/${data[0].slug}`}
href={`/blog/posts/${featured.slug}`}
className="z-10 w-full text-[18px] font-[600] text-white hover:underline sm:text-[28px]"
>
{data[0].title}
{featured.title}
</Link>
<p className="z-10 w-full text-[14px] font-[400] text-white sm:text-[16px]">
{data[0].excerpt}
{featured.excerpt}
</p>
<div className="z-10 flex w-full flex-wrap items-center justify-start gap-3">
{featuredTags.length > 0 ? (
<div className="flex flex-wrap gap-2">
{featuredTags.map((tag) => (
<Link
key={tag.id}
href={`/blog/tags/${tag.slug}`}
className="rounded-full bg-white/20 px-3 py-1 text-[13px] font-[600] text-white hover:bg-white/30"
>
#{tag.name}
</Link>
))}
</div>
) : null}
<p className="text-[13px] font-[400] text-white/90">
{readingTime} {dict.blog.homePage.readTime}
</p>
</div>
<Link
href={`/blog/posts/${featured.slug}`}
className="z-10 rounded-full bg-white px-6 py-2 text-[15px] font-[700] capitalize text-blog-purple transition-transform hover:scale-105"
>
{dict.blog.homePage.readArticle}
</Link>
</div>
</div>
@@ -0,0 +1,30 @@
import { getDictionary } from "@/app/lib/functions/dictionaries";
import { getDefaultLocale } from "@/app/lib/functions/utils";
const NEWSLETTER_EMAIL = `mailto:ceo@parsaaghayi.ir?subject=${encodeURIComponent(
"Blog newsletter subscription",
)}`;
export default async function NewsletterCta() {
const dict = await getDictionary(await getDefaultLocale());
return (
<section
id="newsletter"
className="flex w-full max-w-[95%] flex-col items-center gap-5 rounded-md bg-blog-purple px-6 py-10 text-center sm:py-14"
>
<h2 className="text-[26px] font-[700] text-white sm:text-[34px]">
{dict.blog.homePage.newsletterTitle}
</h2>
<p className="max-w-[560px] text-[16px] font-[400] text-white/90">
{dict.blog.homePage.newsletterText}
</p>
<a
href={NEWSLETTER_EMAIL}
className="rounded-full bg-white px-8 py-3 text-[16px] font-[700] capitalize text-blog-purple transition-transform hover:scale-105"
>
{dict.blog.homePage.subscribe}
</a>
</section>
);
}
@@ -0,0 +1,82 @@
"use client";
import { useState } from "react";
type ShareButtonsProps = {
title: string;
url: string;
dict: {
share?: string;
copyLink?: string;
linkCopied?: string;
};
vertical?: boolean;
};
const SHARE_TARGETS = [
{
key: "twitter",
label: "X",
buildUrl: (title: string, url: string) =>
`https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`,
},
{
key: "linkedin",
label: "in",
buildUrl: (title: string, url: string) =>
`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
},
{
key: "telegram",
label: "TG",
buildUrl: (title: string, url: string) =>
`https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`,
},
];
export default function ShareButtons({
title,
url,
dict,
vertical = false,
}: ShareButtonsProps) {
const [copied, setCopied] = useState(false);
const copyLink = async () => {
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
setCopied(false);
}
};
const stackClass = vertical ? "flex-col items-center gap-4" : "flex-row items-center gap-4";
return (
<div className={`flex ${stackClass}`} aria-label={dict.share}>
{SHARE_TARGETS.map((target) => (
<a
key={target.key}
href={target.buildUrl(title, url)}
target="_blank"
rel="noopener noreferrer"
aria-label={`Share on ${target.label}`}
className="flex h-10 w-10 items-center justify-center rounded-full border border-blog-text-passive text-[16px] font-[600] text-blog-text-passive transition-colors hover:border-blog-purple hover:text-blog-purple"
>
{target.label}
</a>
))}
<button
type="button"
onClick={copyLink}
aria-label={dict.copyLink}
title={dict.copyLink}
className="flex h-10 items-center justify-center rounded-full border border-blog-text-passive px-3 text-[12px] font-[600] text-blog-text-passive transition-colors hover:border-blog-purple hover:text-blog-purple"
>
{copied ? dict.linkCopied : dict.copyLink}
</button>
</div>
);
}
+2
View File
@@ -2,6 +2,7 @@ import FilteredPosts from "./components/home/filtered-posts/filteredPosts";
import New from "./components/home/new/new";
import Random from "./components/home/random/random";
import Categories from "./components/home/Categories/Categories";
import NewsletterCta from "./components/home/newsletter/newsletterCta";
import { getDefaultLocale } from "@/app/lib/functions/utils";
export default async function Blog() {
@@ -22,6 +23,7 @@ export default async function Blog() {
<New data={homePageData.latest_posts} />
<Categories data={homePageData.latest_categories} />
<FilteredPosts data={homePageData.most_viewed_posts} />
<NewsletterCta />
<Random data={homePageData.random_posts} />
</div>
);
@@ -6,6 +6,11 @@ export type BodyBlock =
| { kind: "paragraph"; text: string }
| { kind: "list"; items: string[] };
export type HeadingItem = {
id: string;
text: string;
};
const H1_LINE = /^#\s+(.*)$/;
const H2_LINE = /^##\s+(.*)$/;
const LIST_ITEM_LINE = /^-\s+(.*)$/;
@@ -104,6 +109,21 @@ export function parseBody(body: unknown): BodyBlock[] {
);
}
/**
* Section list for the table of contents. Heading anchors are `heading-N`
* matching the `id` values renderBody attaches to each h2, so TOC links and
* article headings stay in sync no matter how the body changes.
*/
export function getHeadings(body: unknown): HeadingItem[] {
return parseBody(body)
.filter((block) => block.kind === "h2")
.map((block, index) =>
block.kind === "h2"
? { id: `heading-${index}`, text: block.text }
: { id: "", text: "" },
);
}
/**
* 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
@@ -113,6 +133,22 @@ export function renderBody(body: unknown, fallback?: unknown): ReactNode {
const blocks = parseBody(body);
if (blocks.length > 0) {
const h2Ordinal = (blocks: BodyBlock[]) => {
let count = 0;
const ordinalAt: { [index: number]: number } = {};
blocks.forEach((block, index) => {
if (block.kind === "h2") {
ordinalAt[index] = count;
count += 1;
}
});
return ordinalAt;
};
const ordinals = h2Ordinal(blocks);
return blocks.map((block, index) => {
const key = `${block.kind}-${index}`;
@@ -125,7 +161,11 @@ export function renderBody(body: unknown, fallback?: unknown): ReactNode {
);
case "h2":
return (
<h2 key={key} className={H2_CLASS}>
<h2
key={key}
id={`heading-${ordinals[index]}`}
className={H2_CLASS}
>
{block.text}
</h2>
);
@@ -12,7 +12,9 @@ import { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import { renderBody } from "./body";
import { getHeadings, renderBody } from "./body";
import { estimateReadingTime } from "./readingTime";
import ShareButtons from "../../components/share/shareButtons";
import { getCoverImageSrc } from "./coverImage";
import { AUTHOR_PROFILE_URL } from "@/app/lib/social-links";
import { SITE_NAME, SITE_NAME_EN, SITE_URL } from "@/app/lib/site-config";
@@ -133,6 +135,10 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
const relatedPosts = Array.isArray(postData.related_posts)
? postData.related_posts
: [];
const previousPost = postData.previous_post ?? null;
const nextPost = postData.next_post ?? null;
const readingTime = estimateReadingTime(post.body, locale);
const headings = getHeadings(post.body);
const pageUrl = `${SITE_URL}/blog/posts/${post.slug ?? params.postSlug}`;
const articleJsonLd: Record<string, unknown> = {
@@ -240,6 +246,11 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
{publishedDate}
</p>
) : null}
{readingTime > 0 ? (
<p className="whitespace-nowrap rounded-full border border-blog-text-passive px-3 py-1 text-[13px] font-[600] text-blog-text-passive">
{readingTime} {dict.blog.postSinglePage.readTime}
</p>
) : null}
</div>
</div>
<div className="my-10 flex w-full max-w-[90%] flex-wrap justify-center gap-5">
@@ -287,12 +298,31 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
</ul>
<div className="relative flex w-full items-start justify-center gap-3 sm:gap-4 md:gap-5">
<div className="sticky top-[150px] flex flex-col items-start">
<Image
src={"/images/blog/icons/socials-vertical.svg"}
width={35}
height={200}
alt="socials-vertical icons"
<div className="sticky top-[150px] flex flex-col items-start gap-8">
{headings.length > 0 ? (
<nav
aria-label={dict.blog.postSinglePage.onThisPage}
className="hidden max-h-[60vh] w-[210px] flex-col gap-2 overflow-y-auto border-s-2 border-blog-text-passive ps-3 motion-safe:scroll-smooth lg:flex"
>
<p className="text-[14px] font-[700] capitalize text-blog-text-default">
{dict.blog.postSinglePage.onThisPage}
</p>
{headings.map((heading) => (
<a
key={heading.id}
href={`#${heading.id}`}
className="text-[13px] font-[400] leading-snug text-blog-text-passive hover:text-blog-purple hover:underline"
>
{heading.text}
</a>
))}
</nav>
) : null}
<ShareButtons
vertical
title={post.title}
url={pageUrl}
dict={dict.blog.postSinglePage}
/>
</div>
@@ -448,6 +478,39 @@ export default async function SinglePost(props: PostSlugPagepropsType) {
))}
</div>
</div>
{previousPost || nextPost ? (
<div className="my-10 flex w-full flex-wrap justify-between gap-5">
{previousPost ? (
<Link
href={`/blog/posts/${previousPost.slug}`}
className="group flex w-full flex-col gap-2 rounded-md border border-blog-text-passive p-5 transition-colors hover:border-blog-purple sm:w-[48%]"
>
<p className="text-[13px] font-[600] capitalize text-blog-text-passive">
{dict.blog.postSinglePage.newerPost}
</p>
<p className="text-[18px] font-[600] text-blog-text-default group-hover:text-blog-purple">
{previousPost.title}
</p>
</Link>
) : (
<span className="hidden sm:block sm:w-[48%]" />
)}
{nextPost ? (
<Link
href={`/blog/posts/${nextPost.slug}`}
className="group flex w-full flex-col gap-2 rounded-md border border-blog-text-passive p-5 text-end transition-colors hover:border-blog-purple sm:w-[48%]"
>
<p className="text-[13px] font-[600] capitalize text-blog-text-passive">
{dict.blog.postSinglePage.olderPost}
</p>
<p className="text-[18px] font-[600] text-blog-text-default group-hover:text-blog-purple">
{nextPost.title}
</p>
</Link>
) : null}
</div>
) : null}
</div>
</div>
);
@@ -0,0 +1,29 @@
import { parseBody } from "./body";
const WORDS_PER_MINUTE_EN = 210;
const WORDS_PER_MINUTE_FA = 150;
/**
* Estimates how long a post takes to read, in whole minutes. Persian text is
* denser per character than Latin text, so the two languages use different
* reading rates. A post always reports at least one minute.
*/
export function estimateReadingTime(body: unknown, locale: string): number {
const blocks = parseBody(body);
const wordCount = blocks.reduce((total, block) => {
if (block.kind === "list") {
return total + block.items.join(" ").split(/\s+/).filter(Boolean).length;
}
if (block.kind === "paragraph" || block.kind === "h1" || block.kind === "h2") {
return total + block.text.split(/\s+/).filter(Boolean).length;
}
return total;
}, 0);
const rate = locale === "fa" ? WORDS_PER_MINUTE_FA : WORDS_PER_MINUTE_EN;
return Math.max(1, Math.round(wordCount / rate));
}
+16 -3
View File
@@ -107,7 +107,12 @@
"popular": "popular",
"random": "random",
"by": "BY",
"in": "IN"
"in": "IN",
"readArticle": "Read article",
"newsletterTitle": "Get fresh articles in your inbox",
"newsletterText": "One useful engineering post per week. No spam, unsubscribe anytime.",
"subscribe": "Subscribe",
"readTime": "min read"
},
"filteredPostsPage": {
"newTitle": "new",
@@ -125,7 +130,15 @@
},
"postSinglePage": {
"followMe": "follow me",
"YouMightLike": "you might also like..."
"YouMightLike": "you might also like...",
"readTime": "min read",
"onThisPage": "On this page",
"share": "Share",
"copyLink": "Copy link",
"linkCopied": "Link copied",
"newerPost": "Newer post",
"olderPost": "Older post",
"home": "Home"
},
"header": {
"Home": "Home",
@@ -144,4 +157,4 @@
"last": "last"
}
}
}
}
+16 -3
View File
@@ -107,7 +107,12 @@
"popular": "محبوب‌ترین‌ها",
"random": "تصادفی",
"by": "توسط",
"in": "در"
"in": "در",
"readArticle": "مطالعه مقاله",
"newsletterTitle": "مقاله‌های تازه را در ایمیل خود دریافت کنید",
"newsletterText": "هر هفته یک مقاله مفید درباره مهندسی نرم‌افزار. بدون اسپم، لغو اشتراک در هر زمان.",
"subscribe": "عضویت",
"readTime": "دقیقه مطالعه"
},
"filteredPostsPage": {
"newTitle": "جدیدترین‌ها",
@@ -125,7 +130,15 @@
},
"postSinglePage": {
"followMe": "من را دنبال کنید",
"YouMightLike": "شاید این‌ها را هم بپسندید..."
"YouMightLike": "شاید این‌ها را هم بپسندید...",
"readTime": "دقیقه مطالعه",
"onThisPage": "فهرست مطالب",
"share": "اشتراک‌گذاری",
"copyLink": "کپی لینک",
"linkCopied": "لینک کپی شد",
"newerPost": "پست جدیدتر",
"olderPost": "پست قدیمی‌تر",
"home": "خانه"
},
"header": {
"Home": "خانه",
@@ -144,4 +157,4 @@
"last": "آخرین"
}
}
}
}
+14
View File
@@ -107,6 +107,8 @@ export type PostSlugPagepropsType = {
export type PostSlugPagePostType = {
post: PostType;
related_posts: PostType[];
previous_post: PostType | null;
next_post: PostType | null;
};
export type MetaType = {
@@ -208,6 +210,11 @@ export type Dictionary = {
random: string;
by: string;
in: string;
readArticle: string;
readTime: string;
newsletterTitle: string;
newsletterText: string;
subscribe: string;
};
filteredPostsPage: {
newTitle: string;
@@ -226,6 +233,13 @@ export type Dictionary = {
postSinglePage: {
followMe: string;
YouMightLike: string;
readTime: string;
onThisPage: string;
share: string;
copyLink: string;
linkCopied: string;
newerPost: string;
olderPost: string;
};
header: {
Home: string;