Compare commits

...

3 Commits

Author SHA1 Message Date
7ddc6b158d feat(blog): redesign post detail experience
Some checks failed
Frontend CI/CD / build (push) Has been cancelled
Frontend CI/CD / deploy (push) Has been cancelled
2026-06-10 11:56:21 +03:30
0d01933f9d feat(blog): redesign post list cards 2026-06-10 11:56:09 +03:30
039158e0c4 feat(blog): add copyable highlighted code blocks 2026-06-10 11:55:56 +03:30
11 changed files with 822 additions and 263 deletions

119
package-lock.json generated
View File

@@ -55,6 +55,7 @@
"react-markdown": "^9.0.3", "react-markdown": "^9.0.3",
"react-qr-code": "^2.0.11", "react-qr-code": "^2.0.11",
"react-resizable-panels": "^2.1.9", "react-resizable-panels": "^2.1.9",
"react-syntax-highlighter": "^16.1.1",
"recharts": "^2.15.4", "recharts": "^2.15.4",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
@@ -72,6 +73,7 @@
"@types/node": "^22.16.5", "@types/node": "^22.16.5",
"@types/react": "^18.3.26", "@types/react": "^18.3.26",
"@types/react-dom": "^18.3.7", "@types/react-dom": "^18.3.7",
"@types/react-syntax-highlighter": "^15.5.13",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"eslint": "^9.32.0", "eslint": "^9.32.0",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",
@@ -96,9 +98,9 @@
} }
}, },
"node_modules/@babel/runtime": { "node_modules/@babel/runtime": {
"version": "7.28.2", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.2.tgz", "resolved": "https://package-mirror.liara.ir/repository/npm/@babel/runtime/-/runtime-7.29.7.tgz",
"integrity": "sha512-KHp2IflsnGywDjBWDkR9iEqiWSpc8GIi0lgTT3mOElT0PP1tG26P4tmFI2YvAdzgq9RGyoHZQEIEdZy6Ec5xCA==", "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -2663,6 +2665,12 @@
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
}, },
"node_modules/@types/prismjs": {
"version": "1.26.6",
"resolved": "https://package-mirror.liara.ir/repository/npm/@types/prismjs/-/prismjs-1.26.6.tgz",
"integrity": "sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==",
"license": "MIT"
},
"node_modules/@types/prop-types": { "node_modules/@types/prop-types": {
"version": "15.7.13", "version": "15.7.13",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.13.tgz", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.13.tgz",
@@ -2694,6 +2702,16 @@
"@types/react": "^18.0.0" "@types/react": "^18.0.0"
} }
}, },
"node_modules/@types/react-syntax-highlighter": {
"version": "15.5.13",
"resolved": "https://package-mirror.liara.ir/repository/npm/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz",
"integrity": "sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/react": "*"
}
},
"node_modules/@types/unist": { "node_modules/@types/unist": {
"version": "3.0.3", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -4098,6 +4116,19 @@
"reusify": "^1.0.4" "reusify": "^1.0.4"
} }
}, },
"node_modules/fault": {
"version": "1.0.4",
"resolved": "https://package-mirror.liara.ir/repository/npm/fault/-/fault-1.0.4.tgz",
"integrity": "sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA==",
"license": "MIT",
"dependencies": {
"format": "^0.2.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/fflate": { "node_modules/fflate": {
"version": "0.8.2", "version": "0.8.2",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
@@ -4182,6 +4213,14 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/format": {
"version": "0.2.2",
"resolved": "https://package-mirror.liara.ir/repository/npm/format/-/format-0.2.2.tgz",
"integrity": "sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==",
"engines": {
"node": ">=0.4.x"
}
},
"node_modules/fraction.js": { "node_modules/fraction.js": {
"version": "4.3.7", "version": "4.3.7",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
@@ -4476,6 +4515,21 @@
"url": "https://opencollective.com/unified" "url": "https://opencollective.com/unified"
} }
}, },
"node_modules/highlight.js": {
"version": "10.7.3",
"resolved": "https://package-mirror.liara.ir/repository/npm/highlight.js/-/highlight.js-10.7.3.tgz",
"integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
"license": "BSD-3-Clause",
"engines": {
"node": "*"
}
},
"node_modules/highlightjs-vue": {
"version": "1.0.0",
"resolved": "https://package-mirror.liara.ir/repository/npm/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz",
"integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==",
"license": "CC0-1.0"
},
"node_modules/html-url-attributes": { "node_modules/html-url-attributes": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
@@ -4875,6 +4929,20 @@
"loose-envify": "cli.js" "loose-envify": "cli.js"
} }
}, },
"node_modules/lowlight": {
"version": "1.20.0",
"resolved": "https://package-mirror.liara.ir/repository/npm/lowlight/-/lowlight-1.20.0.tgz",
"integrity": "sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw==",
"license": "MIT",
"dependencies": {
"fault": "^1.0.0",
"highlight.js": "~10.7.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/lru-cache": { "node_modules/lru-cache": {
"version": "10.4.3", "version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
@@ -6267,6 +6335,15 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://package-mirror.liara.ir/repository/npm/prismjs/-/prismjs-1.30.0.tgz",
"integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/prop-types": { "node_modules/prop-types": {
"version": "15.8.1", "version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
@@ -6530,6 +6607,26 @@
} }
} }
}, },
"node_modules/react-syntax-highlighter": {
"version": "16.1.1",
"resolved": "https://package-mirror.liara.ir/repository/npm/react-syntax-highlighter/-/react-syntax-highlighter-16.1.1.tgz",
"integrity": "sha512-PjVawBGy80C6YbC5DDZJeUjBmC7skaoEUdvfFQediQHgCL7aKyVHe57SaJGfQsloGDac+gCpTfRdtxzWWKmCXA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.28.4",
"highlight.js": "^10.4.1",
"highlightjs-vue": "^1.0.0",
"lowlight": "^1.17.0",
"prismjs": "^1.30.0",
"refractor": "^5.0.0"
},
"engines": {
"node": ">= 16.20.2"
},
"peerDependencies": {
"react": ">= 0.14.0"
}
},
"node_modules/react-transition-group": { "node_modules/react-transition-group": {
"version": "4.4.5", "version": "4.4.5",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
@@ -6599,6 +6696,22 @@
"decimal.js-light": "^2.4.1" "decimal.js-light": "^2.4.1"
} }
}, },
"node_modules/refractor": {
"version": "5.0.0",
"resolved": "https://package-mirror.liara.ir/repository/npm/refractor/-/refractor-5.0.0.tgz",
"integrity": "sha512-QXOrHQF5jOpjjLfiNk5GFnWhRXvxjUVnlFxkeDmewR5sXkr3iM46Zo+CnRR8B+MDVqkULW4EcLVcRBNOPXHosw==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.0",
"@types/prismjs": "^1.0.0",
"hastscript": "^9.0.0",
"parse-entities": "^4.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/regenerator-runtime": { "node_modules/regenerator-runtime": {
"version": "0.13.11", "version": "0.13.11",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",

View File

@@ -57,6 +57,7 @@
"react-markdown": "^9.0.3", "react-markdown": "^9.0.3",
"react-qr-code": "^2.0.11", "react-qr-code": "^2.0.11",
"react-resizable-panels": "^2.1.9", "react-resizable-panels": "^2.1.9",
"react-syntax-highlighter": "^16.1.1",
"recharts": "^2.15.4", "recharts": "^2.15.4",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
@@ -74,6 +75,7 @@
"@types/node": "^22.16.5", "@types/node": "^22.16.5",
"@types/react": "^18.3.26", "@types/react": "^18.3.26",
"@types/react-dom": "^18.3.7", "@types/react-dom": "^18.3.7",
"@types/react-syntax-highlighter": "^15.5.13",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"eslint": "^9.32.0", "eslint": "^9.32.0",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",

View File

@@ -1,15 +1,18 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import Markdown from "@/components/Markdown"; import BlogPostActions from "@/components/BlogPostActions";
import BlogPostInteractions from "@/components/BlogPostInteractions"; import BlogPostInteractions from "@/components/BlogPostInteractions";
import BlogThumbnail from "@/components/BlogThumbnail";
import Markdown from "@/components/Markdown";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Link } from "@/lib/router"; import { Link } from "@/lib/router";
import { PublicApiError, getPublicPost } from "@/lib/public-api";
import { apiBaseUrl, siteUrl, toAbsoluteUrl } from "@/lib/site";
import { blogPostPath, blogPostUrl, normalizeBlogSlugParam } from "@/lib/blog-routes"; import { blogPostPath, blogPostUrl, normalizeBlogSlugParam } from "@/lib/blog-routes";
import { formatJalali } from "@/lib/utils"; import { extractMarkdownHeadings, type MarkdownHeading } from "@/lib/markdown-headings";
import { PublicApiError, getPublicPost, getRecommendedPosts } from "@/lib/public-api";
import { apiBaseUrl, siteUrl, toAbsoluteUrl } from "@/lib/site";
import type * as Types from "@/lib/types";
import { formatJalaliDate, getBlogCardImageUrl, getBlogHeroImageUrl } from "@/lib/utils";
type Params = Promise<{ slug: string }>; type Params = Promise<{ slug: string }>;
@@ -20,6 +23,10 @@ function cleanText(value?: string | null) {
return value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(); return value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
} }
function authorName(post: Types.PostListSchema) {
return [post.author.first_name, post.author.last_name].filter(Boolean).join(" ") || post.author.username;
}
async function loadPost(slug: string) { async function loadPost(slug: string) {
try { try {
return await getPublicPost(slug); return await getPublicPost(slug);
@@ -31,6 +38,85 @@ async function loadPost(slug: string) {
} }
} }
async function loadRecommended(slug: string) {
try {
return await getRecommendedPosts(slug, 3);
} catch {
return [];
}
}
function TableOfContents({ headings }: { headings: MarkdownHeading[] }) {
if (!headings.length) {
return <p className="text-sm leading-7 text-muted-foreground">برای این نوشته فهرست تیترها ثبت نشده است.</p>;
}
return (
<nav className="space-y-1 text-sm">
{headings.map((heading) => (
<a
key={heading.id}
href={`#${heading.id}`}
className="block rounded-2xl px-3 py-2 leading-6 text-muted-foreground transition hover:bg-primary/10 hover:text-primary"
style={{ paddingRight: `${(heading.level - 1) * 0.85 + 0.75}rem` }}
>
{heading.text}
</a>
))}
</nav>
);
}
function HashTags({ tags }: { tags: Types.PostListSchema["tags"] }) {
if (!tags.length) {
return <p className="text-sm text-muted-foreground">هشتگی برای این نوشته ثبت نشده است.</p>;
}
return (
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<Badge key={tag.id} variant="outline" className="rounded-full px-3 py-1">
#{tag.name}
</Badge>
))}
</div>
);
}
function RecommendedPosts({ posts }: { posts: Types.PostListSchema[] }) {
if (!posts.length) return null;
return (
<section className="mt-10 rounded-[2rem] border border-border/70 bg-card/90 p-5 shadow-sm">
<div className="mb-5 text-right">
<p className="text-sm font-medium text-primary">ادامه مطالعه</p>
<h2 className="mt-1 text-2xl font-bold">نوشتههای پیشنهادی</h2>
</div>
<div className="grid gap-4 md:grid-cols-3">
{posts.map((post) => (
<Link
key={post.id}
to={blogPostPath(post.slug)}
className="group overflow-hidden rounded-3xl border border-border/70 bg-background transition hover:-translate-y-1 hover:shadow-lg"
>
<BlogThumbnail
post={post}
imageUrl={toAbsoluteUrl(getBlogCardImageUrl(post), apiBaseUrl)}
className="aspect-[16/10]"
/>
<div className="space-y-2 p-4 text-right">
<h3 className="line-clamp-2 font-semibold leading-7 group-hover:text-primary">{post.title}</h3>
<time className="text-xs text-muted-foreground" dateTime={post.published_at || post.created_at}>
{formatJalaliDate(post.published_at || post.created_at)}
</time>
</div>
</Link>
))}
</div>
</section>
);
}
export async function generateMetadata({ export async function generateMetadata({
params, params,
}: { }: {
@@ -43,7 +129,7 @@ export async function generateMetadata({
const metaDescription = post.seo_description || post.og_description || description; const metaDescription = post.seo_description || post.og_description || description;
const canonical = post.canonical_url || blogPostPath(post.slug); const canonical = post.canonical_url || blogPostPath(post.slug);
const image = toAbsoluteUrl( const image = toAbsoluteUrl(
post.og_image_url || post.absolute_featured_image_url || post.featured_image, post.og_image_url || getBlogHeroImageUrl(post),
apiBaseUrl, apiBaseUrl,
) ?? `${siteUrl}/favicon.ico`; ) ?? `${siteUrl}/favicon.ico`;
@@ -56,7 +142,7 @@ export async function generateMetadata({
title: post.og_title || metaTitle, title: post.og_title || metaTitle,
description: post.og_description || metaDescription, description: post.og_description || metaDescription,
url: blogPostUrl(siteUrl, post.slug), url: blogPostUrl(siteUrl, post.slug),
siteName: "انجمن علمی کامپیوتر شرق گیلان", siteName: "انجمن علمی مهندسی کامپیوتر شرق گیلان",
type: "article", type: "article",
images: [image], images: [image],
locale: "fa_IR", locale: "fa_IR",
@@ -79,92 +165,126 @@ export default async function BlogDetailPage({
}) { }) {
const { slug } = await params; const { slug } = await params;
const post = await loadPost(normalizeBlogSlugParam(slug)); const post = await loadPost(normalizeBlogSlugParam(slug));
const recommendedPosts = await loadRecommended(post.slug);
const headings = extractMarkdownHeadings(post.content);
const description = cleanText(post.excerpt || post.content).slice(0, 160); const description = cleanText(post.excerpt || post.content).slice(0, 160);
const metaDescription = post.seo_description || post.og_description || description; const metaDescription = post.seo_description || post.og_description || description;
const image = toAbsoluteUrl( const coverImage = toAbsoluteUrl(getBlogHeroImageUrl(post), apiBaseUrl);
post.og_image_url || post.absolute_featured_image_url || post.featured_image, const seoImage = toAbsoluteUrl(post.og_image_url || getBlogHeroImageUrl(post), apiBaseUrl) ?? `${siteUrl}/favicon.ico`;
apiBaseUrl,
) ?? `${siteUrl}/favicon.ico`;
const structuredData = { const structuredData = {
"@context": "https://schema.org", "@context": "https://schema.org",
"@type": "BlogPosting", "@type": "BlogPosting",
headline: post.title, headline: post.title,
description: metaDescription, description: metaDescription,
image: [image], image: [seoImage],
datePublished: post.published_at || post.created_at, datePublished: post.published_at || post.created_at,
dateModified: post.updated_at, dateModified: post.updated_at,
url: blogPostUrl(siteUrl, post.slug), url: blogPostUrl(siteUrl, post.slug),
author: { author: {
"@type": "Person", "@type": "Person",
name: [post.author.first_name, post.author.last_name].filter(Boolean).join(" ") || post.author.username, name: authorName(post),
}, },
publisher: { publisher: {
"@type": "Organization", "@type": "Organization",
name: "انجمن علمی کامپیوتر شرق گیلان", name: "انجمن علمی مهندسی کامپیوتر شرق گیلان",
logo: { logo: {
"@type": "ImageObject", "@type": "ImageObject",
url: `${siteUrl}/favicon.ico`, url: `${siteUrl}/favicon.ico`,
}, },
}, },
keywords: post.tags.map((tag) => tag.name).join(", "),
}; };
return ( return (
<div className="min-h-screen bg-background" dir="rtl"> <div className="min-h-screen bg-[linear-gradient(180deg,hsl(var(--background)),hsl(var(--muted)/0.28))]" dir="rtl">
<script <script
type="application/ld+json" type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }} dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
/> />
<div className="container mx-auto px-4 py-8"> <div className="container mx-auto px-4 py-8">
<div className="mb-6 flex items-center justify-between gap-3"> <div className="mb-6 flex justify-start">
<Button variant="outline" asChild> <Button variant="outline" asChild className="rounded-full">
<Link to="/blog">بازگشت به وبلاگ</Link> <Link to="/blog">بازگشت به بلاگ</Link>
</Button> </Button>
<div className="text-sm text-muted-foreground">
{formatJalali(post.published_at || post.created_at, false)}
</div>
</div> </div>
<Card> <div className="gap-8 xl:flex xl:items-start">
{image && ( <aside className="hidden w-72 shrink-0 xl:block">
<div className="w-full aspect-video overflow-hidden rounded-t-lg bg-muted"> <div className="sticky top-24 space-y-4">
<img <section className="rounded-[1.75rem] border border-border/70 bg-card/90 p-4 shadow-sm backdrop-blur">
src={image} <h2 className="mb-3 text-right font-bold">فهرست نوشته</h2>
alt={post.title} <TableOfContents headings={headings} />
className="h-full w-full object-cover" </section>
loading="eager" <section className="rounded-[1.75rem] border border-border/70 bg-card/90 p-4 shadow-sm backdrop-blur">
/> <h2 className="mb-3 text-right font-bold">هشتگها</h2>
<HashTags tags={post.tags} />
</section>
</div> </div>
)} </aside>
<CardHeader>
<div className="flex flex-wrap gap-2"> <main className="min-w-0 flex-1">
{post.category?.name ? <Badge variant="secondary">{post.category.name}</Badge> : null} <article className="overflow-hidden rounded-[2.5rem] border border-border/70 bg-card/95 shadow-xl shadow-primary/5">
{post.tags.map((tag) => ( <header className="space-y-6 p-5 text-right md:p-8">
<Badge key={tag.id} variant="outline"> <div className="flex flex-wrap gap-2">
{tag.name} {post.category?.name ? <Badge className="rounded-full">{post.category.name}</Badge> : null}
</Badge> <Badge variant="outline" className="rounded-full">
))} {formatJalaliDate(post.published_at || post.created_at)}
</div> </Badge>
<CardTitle className="text-3xl leading-relaxed">{post.title}</CardTitle> </div>
<CardDescription className="text-sm"> <div className="max-w-4xl space-y-4">
نویسنده: {[post.author.first_name, post.author.last_name].filter(Boolean).join(" ") || post.author.username} <h1 className="text-3xl font-black leading-[1.7] tracking-tight md:text-5xl">
</CardDescription> {post.title}
</CardHeader> </h1>
<CardContent className="space-y-6"> <p className="text-sm text-muted-foreground">
{post.excerpt ? ( نوشته {authorName(post)}
<p className="rounded-lg border bg-muted/30 p-4 text-sm leading-7 text-muted-foreground"> </p>
{post.excerpt} {post.excerpt ? (
</p> <p className="max-w-3xl text-base leading-8 text-muted-foreground md:text-lg">
) : null} {post.excerpt}
<Markdown content={post.content} justify size="base" /> </p>
</CardContent> ) : null}
</Card> </div>
<BlogPostInteractions </header>
slug={post.slug}
initialLikes={post.likes_count ?? 0} <div className="px-5 md:px-8">
initialSaves={post.saves_count ?? 0} <BlogThumbnail
initialComments={post.comments_count ?? 0} post={post}
/> imageUrl={coverImage}
className="aspect-[16/9] rounded-[2rem]"
priority
/>
<BlogPostActions
slug={post.slug}
initialLikes={post.likes_count ?? 0}
initialSaves={post.saves_count ?? 0}
initialComments={post.comments_count ?? 0}
/>
</div>
<div className="space-y-5 p-5 md:p-8 xl:hidden">
<section className="rounded-[1.5rem] border border-border/70 bg-muted/20 p-4">
<h2 className="mb-3 text-right font-bold">فهرست نوشته</h2>
<TableOfContents headings={headings} />
</section>
<section className="rounded-[1.5rem] border border-border/70 bg-muted/20 p-4">
<h2 className="mb-3 text-right font-bold">هشتگها</h2>
<HashTags tags={post.tags} />
</section>
</div>
<div className="px-5 pb-8 pt-4 md:px-8 md:pb-10">
<Markdown content={post.content} justify size="base" className="mx-auto max-w-4xl" />
</div>
</article>
<RecommendedPosts posts={recommendedPosts} />
<BlogPostInteractions
slug={post.slug}
initialComments={post.comments_count ?? 0}
/>
</main>
</div>
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,120 @@
"use client";
import { useEffect, useState } from "react";
import { Bookmark, Heart, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/contexts/AuthContext";
import { api } from "@/lib/api";
import type * as Types from "@/lib/types";
import { cn, toPersianDigits } from "@/lib/utils";
type BlogPostActionsProps = {
slug: string;
initialLikes: number;
initialSaves: number;
initialComments: number;
};
export default function BlogPostActions({
slug,
initialLikes,
initialSaves,
initialComments,
}: BlogPostActionsProps) {
const { isAuthenticated } = useAuth();
const [loadingAction, setLoadingAction] = useState<"like" | "save" | null>(null);
const [interaction, setInteraction] = useState<Types.BlogInteractionSchema>({
liked: false,
saved: false,
likes_count: initialLikes,
saves_count: initialSaves,
comments_count: initialComments,
});
useEffect(() => {
let mounted = true;
if (!isAuthenticated) return;
api.getBlogInteraction(slug)
.then((data) => {
if (mounted) setInteraction(data);
})
.catch(() => undefined);
return () => {
mounted = false;
};
}, [isAuthenticated, slug]);
const toggleLike = async () => {
if (!isAuthenticated || loadingAction) return;
setLoadingAction("like");
try {
setInteraction(await api.toggleLike(slug));
} finally {
setLoadingAction(null);
}
};
const toggleSave = async () => {
if (!isAuthenticated || loadingAction) return;
setLoadingAction("save");
try {
setInteraction(await api.toggleSave(slug));
} finally {
setLoadingAction(null);
}
};
return (
<div className="flex flex-wrap items-center justify-center gap-3 pt-4" dir="rtl">
<Button
type="button"
variant="ghost"
size="lg"
onClick={toggleLike}
disabled={!isAuthenticated || Boolean(loadingAction)}
className="gap-2 rounded-full border border-border/60 bg-background/80 px-5 shadow-sm backdrop-blur hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/30"
aria-label="پسندیدن نوشته"
>
{loadingAction === "like" ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Heart
className={cn(
"h-5 w-5",
interaction.liked && "fill-rose-500 text-rose-500",
)}
/>
)}
<span>{toPersianDigits(interaction.likes_count)}</span>
</Button>
<Button
type="button"
variant="ghost"
size="lg"
onClick={toggleSave}
disabled={!isAuthenticated || Boolean(loadingAction)}
className="gap-2 rounded-full border border-border/60 bg-background/80 px-5 shadow-sm backdrop-blur hover:bg-amber-50 hover:text-amber-600 dark:hover:bg-amber-950/30"
aria-label="ذخیره نوشته"
>
{loadingAction === "save" ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Bookmark
className={cn(
"h-5 w-5",
interaction.saved && "fill-amber-500 text-amber-500",
)}
/>
)}
<span>ذخیره</span>
</Button>
{!isAuthenticated ? (
<span className="basis-full text-center text-xs text-muted-foreground">
برای پسندیدن یا ذخیره کردن وارد حساب کاربری شوید.
</span>
) : null}
</div>
);
}

View File

@@ -1,22 +1,19 @@
"use client"; "use client";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Bookmark, Heart, Loader2, MessageSquare, Send, Trash2 } from "lucide-react"; import { Loader2, MessageSquare, Reply, Send, Trash2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext"; import { useAuth } from "@/contexts/AuthContext";
import { api } from "@/lib/api"; import { api } from "@/lib/api";
import type * as Types from "@/lib/types"; import type * as Types from "@/lib/types";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Link } from "@/lib/router"; import { Link } from "@/lib/router";
import { formatJalali, resolveErrorMessage } from "@/lib/utils"; import { formatJalaliDate, resolveErrorMessage, toPersianDigits } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
type Props = { type Props = {
slug: string; slug: string;
initialLikes: number;
initialSaves: number;
initialComments: number; initialComments: number;
}; };
@@ -24,22 +21,35 @@ function displayName(author: Types.CommentSchema["author"]) {
return [author.first_name, author.last_name].filter(Boolean).join(" ") || author.username; return [author.first_name, author.last_name].filter(Boolean).join(" ") || author.username;
} }
function avatarInitial(author: Types.CommentSchema["author"]) {
return displayName(author).trim()[0] || "ک";
}
function countComments(comments: Types.CommentSchema[]) {
return comments.reduce(
(total, comment) => total + 1 + countComments(comment.replies || []),
0,
);
}
function findComment(comments: Types.CommentSchema[], id: number | null): Types.CommentSchema | undefined {
if (!id) return undefined;
for (const comment of comments) {
if (comment.id === id) return comment;
const reply = findComment(comment.replies || [], id);
if (reply) return reply;
}
return undefined;
}
export default function BlogPostInteractions({ export default function BlogPostInteractions({
slug, slug,
initialLikes,
initialSaves,
initialComments, initialComments,
}: Props) { }: Props) {
const { user, isAuthenticated } = useAuth(); const { user, isAuthenticated } = useAuth();
const { toast } = useToast(); const { toast } = useToast();
const [comments, setComments] = useState<Types.CommentSchema[]>([]); const [comments, setComments] = useState<Types.CommentSchema[]>([]);
const [interaction, setInteraction] = useState<Types.BlogInteractionSchema>({ const [commentCount, setCommentCount] = useState(initialComments);
liked: false,
saved: false,
likes_count: initialLikes,
saves_count: initialSaves,
comments_count: initialComments,
});
const [content, setContent] = useState(""); const [content, setContent] = useState("");
const [replyTo, setReplyTo] = useState<number | null>(null); const [replyTo, setReplyTo] = useState<number | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -48,30 +58,23 @@ export default function BlogPostInteractions({
const canModerate = Boolean(user?.is_staff || user?.is_superuser || user?.can_review_blog_posts); const canModerate = Boolean(user?.is_staff || user?.is_superuser || user?.can_review_blog_posts);
const replyTarget = useMemo( const replyTarget = useMemo(
() => comments.find((comment) => comment.id === replyTo), () => findComment(comments, replyTo),
[comments, replyTo], [comments, replyTo],
); );
const loadComments = async () => { const loadComments = async () => {
const data = await api.getComments(slug); const data = await api.getComments(slug);
setComments(data); setComments(data);
setInteraction((prev) => ({ ...prev, comments_count: data.length })); setCommentCount(countComments(data));
}; };
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
Promise.all([ api.getComments(slug)
api.getComments(slug), .then((data) => {
isAuthenticated ? api.getBlogInteraction(slug).catch(() => null) : Promise.resolve(null),
])
.then(([commentData, interactionData]) => {
if (!mounted) return; if (!mounted) return;
setComments(commentData); setComments(data);
if (interactionData) { setCommentCount(countComments(data));
setInteraction(interactionData);
} else {
setInteraction((prev) => ({ ...prev, comments_count: commentData.length }));
}
}) })
.finally(() => { .finally(() => {
if (mounted) setLoading(false); if (mounted) setLoading(false);
@@ -79,17 +82,7 @@ export default function BlogPostInteractions({
return () => { return () => {
mounted = false; mounted = false;
}; };
}, [isAuthenticated, slug]); }, [slug]);
const toggleLike = async () => {
if (!isAuthenticated) return;
setInteraction(await api.toggleLike(slug));
};
const toggleSave = async () => {
if (!isAuthenticated) return;
setInteraction(await api.toggleSave(slug));
};
const submitComment = async () => { const submitComment = async () => {
const trimmed = content.trim(); const trimmed = content.trim();
@@ -100,10 +93,10 @@ export default function BlogPostInteractions({
setContent(""); setContent("");
setReplyTo(null); setReplyTo(null);
await loadComments(); await loadComments();
toast({ title: "نظر ثبت شد", variant: "success" }); toast({ title: "کامنت ثبت شد", variant: "success" });
} catch (error) { } catch (error) {
toast({ toast({
title: "ثبت نظر ناموفق بود", title: "ثبت کامنت ناموفق بود",
description: resolveErrorMessage(error, "دوباره تلاش کنید"), description: resolveErrorMessage(error, "دوباره تلاش کنید"),
variant: "destructive", variant: "destructive",
}); });
@@ -116,10 +109,10 @@ export default function BlogPostInteractions({
try { try {
await api.hideComment(commentId); await api.hideComment(commentId);
await loadComments(); await loadComments();
toast({ title: "نظر مخفی شد", variant: "success" }); toast({ title: "کامنت مخفی شد", variant: "success" });
} catch (error) { } catch (error) {
toast({ toast({
title: "حذف نظر ناموفق بود", title: "حذف کامنت ناموفق بود",
description: resolveErrorMessage(error, "دوباره تلاش کنید"), description: resolveErrorMessage(error, "دوباره تلاش کنید"),
variant: "destructive", variant: "destructive",
}); });
@@ -127,30 +120,50 @@ export default function BlogPostInteractions({
}; };
const renderComment = (comment: Types.CommentSchema, nested = false) => ( const renderComment = (comment: Types.CommentSchema, nested = false) => (
<div key={comment.id} className={nested ? "mr-6 border-r pr-4" : ""}> <div
<div className="rounded-2xl border border-border/70 bg-background/80 p-4 text-right"> key={comment.id}
<div className="flex flex-wrap items-center justify-between gap-3"> className={nested ? "relative mr-7 border-r-2 border-primary/20 pr-5" : ""}
<div className="flex items-center gap-2"> >
{canModerate ? ( <div className="flex items-start gap-3 text-right">
<Button variant="ghost" size="sm" onClick={() => hideComment(comment.id)}> <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl bg-primary/12 text-lg font-black text-primary shadow-inner">
<Trash2 className="h-4 w-4" /> {avatarInitial(comment.author)}
</Button> </div>
) : null} <div className="min-w-0 flex-1">
<div className="mb-1 flex flex-wrap items-center gap-2 text-sm">
<span className="font-semibold">{displayName(comment.author)}</span>
<span className="text-xs text-muted-foreground">{formatJalaliDate(comment.created_at)}</span>
</div>
<div className="rounded-bl-3xl rounded-br-md rounded-tl-3xl rounded-tr-3xl border border-border/70 bg-muted/35 px-4 py-3 shadow-sm">
<p className="whitespace-pre-wrap text-sm leading-7">{comment.content}</p>
</div>
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{isAuthenticated ? ( {isAuthenticated ? (
<Button variant="ghost" size="sm" onClick={() => setReplyTo(comment.id)}> <Button
variant="ghost"
size="sm"
className="h-8 gap-1 rounded-full px-3 text-xs"
onClick={() => setReplyTo(comment.id)}
>
<Reply className="h-3.5 w-3.5" />
پاسخ پاسخ
</Button> </Button>
) : null} ) : null}
</div> {canModerate ? (
<div> <Button
<p className="font-medium">{displayName(comment.author)}</p> variant="ghost"
<p className="text-xs text-muted-foreground">{formatJalali(comment.created_at, false)}</p> size="sm"
className="h-8 gap-1 rounded-full px-3 text-xs text-destructive hover:text-destructive"
onClick={() => hideComment(comment.id)}
>
<Trash2 className="h-3.5 w-3.5" />
مخفیکردن
</Button>
) : null}
</div> </div>
</div> </div>
<p className="mt-3 whitespace-pre-wrap leading-7 text-sm">{comment.content}</p>
</div> </div>
{comment.replies?.length ? ( {comment.replies?.length ? (
<div className="mt-3 space-y-3"> <div className="mt-4 space-y-4">
{comment.replies.map((reply) => renderComment(reply, true))} {comment.replies.map((reply) => renderComment(reply, true))}
</div> </div>
) : null} ) : null}
@@ -158,52 +171,28 @@ export default function BlogPostInteractions({
); );
return ( return (
<Card className="mt-8 rounded-[1.75rem] border border-border/70 shadow-sm" dir="rtl"> <Card className="mt-10 rounded-[2rem] border border-border/70 bg-card/90 shadow-sm" dir="rtl">
<CardHeader className="text-right"> <CardHeader className="text-right">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between"> <CardTitle className="flex items-center justify-end gap-2 text-2xl">
<div className="flex items-center gap-2"> کامنتها
<Button <MessageSquare className="h-5 w-5 text-primary" />
variant={interaction.saved ? "default" : "outline"} </CardTitle>
onClick={toggleSave} <CardDescription>
disabled={!isAuthenticated} {toPersianDigits(commentCount)} کامنت برای این نوشته ثبت شده است.
> </CardDescription>
<Bookmark className="ml-2 h-4 w-4" />
ذخیره
<Badge className="mr-2" variant="secondary">{interaction.saves_count}</Badge>
</Button>
<Button
variant={interaction.liked ? "default" : "outline"}
onClick={toggleLike}
disabled={!isAuthenticated}
>
<Heart className="ml-2 h-4 w-4" />
پسندیدن
<Badge className="mr-2" variant="secondary">{interaction.likes_count}</Badge>
</Button>
</div>
<div>
<CardTitle className="flex items-center justify-end gap-2">
دیدگاهها
<MessageSquare className="h-5 w-5 text-primary" />
</CardTitle>
<CardDescription className="mt-2">
{interaction.comments_count} نظر برای این نوشته ثبت شده است.
</CardDescription>
</div>
</div>
</CardHeader> </CardHeader>
<CardContent className="space-y-5"> <CardContent className="space-y-6">
{!isAuthenticated ? ( {!isAuthenticated ? (
<div className="rounded-2xl border border-dashed border-border/70 bg-muted/20 p-5 text-center text-sm text-muted-foreground"> <div className="rounded-3xl border border-dashed border-border/70 bg-muted/20 p-5 text-center text-sm leading-7 text-muted-foreground">
برای پسندیدن، ذخیرهکردن یا ثبت نظر باید وارد حساب شوید. برای ثبت کامنت باید وارد حساب کاربری شوید.
<Button asChild className="mr-3" size="sm"> <Button asChild className="mr-3" size="sm">
<Link to="/auth">ورود / ثبتنام</Link> <Link to="/auth">ورود / ثبتنام</Link>
</Button> </Button>
</div> </div>
) : ( ) : (
<div className="rounded-2xl border border-border/70 bg-muted/20 p-4"> <div className="rounded-3xl border border-border/70 bg-muted/20 p-4">
{replyTarget ? ( {replyTarget ? (
<div className="mb-3 flex items-center justify-between rounded-xl bg-background px-3 py-2 text-sm"> <div className="mb-3 flex items-center justify-between rounded-2xl bg-background px-3 py-2 text-sm">
<Button variant="ghost" size="sm" onClick={() => setReplyTo(null)}> <Button variant="ghost" size="sm" onClick={() => setReplyTo(null)}>
لغو پاسخ لغو پاسخ
</Button> </Button>
@@ -213,13 +202,13 @@ export default function BlogPostInteractions({
<Textarea <Textarea
value={content} value={content}
onChange={(event) => setContent(event.target.value)} onChange={(event) => setContent(event.target.value)}
placeholder="نظر خود را بنویسید..." placeholder="کامنت خود را بنویسید..."
className="min-h-28 text-right" className="min-h-28 rounded-2xl bg-background text-right"
/> />
<div className="mt-3 flex justify-end"> <div className="mt-3 flex justify-end">
<Button onClick={submitComment} disabled={submitting || !content.trim()}> <Button onClick={submitComment} disabled={submitting || !content.trim()} className="gap-2 rounded-full">
{submitting ? <Loader2 className="ml-2 h-4 w-4 animate-spin" /> : <Send className="ml-2 h-4 w-4" />} {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
ثبت نظر ثبت کامنت
</Button> </Button>
</div> </div>
</div> </div>
@@ -230,10 +219,10 @@ export default function BlogPostInteractions({
<Loader2 className="h-5 w-5 animate-spin" /> <Loader2 className="h-5 w-5 animate-spin" />
</div> </div>
) : comments.length ? ( ) : comments.length ? (
<div className="space-y-4">{comments.map((comment) => renderComment(comment))}</div> <div className="space-y-5">{comments.map((comment) => renderComment(comment))}</div>
) : ( ) : (
<div className="rounded-2xl border border-dashed border-border/70 p-8 text-center text-sm text-muted-foreground"> <div className="rounded-3xl border border-dashed border-border/70 p-8 text-center text-sm text-muted-foreground">
هنوز نظری ثبت نشده است. هنوز کامنتی ثبت نشده است.
</div> </div>
)} )}
</CardContent> </CardContent>

View File

@@ -0,0 +1,58 @@
import type * as Types from "@/lib/types";
import { cn } from "@/lib/utils";
type BlogThumbnailProps = {
post: Pick<Types.PostListSchema, "title" | "category" | "absolute_featured_image_thumbnail_url" | "absolute_featured_image_preview_url" | "absolute_featured_image_url" | "featured_image">;
imageUrl?: string | null;
className?: string;
imageClassName?: string;
priority?: boolean;
};
function initials(title: string) {
return title
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0])
.join("");
}
export default function BlogThumbnail({
post,
imageUrl,
className,
imageClassName,
priority = false,
}: BlogThumbnailProps) {
if (imageUrl) {
return (
<div className={cn("overflow-hidden bg-muted", className)}>
<img
src={imageUrl}
alt={post.title}
className={cn("h-full w-full object-cover transition duration-500 group-hover:scale-[1.03]", imageClassName)}
loading={priority ? "eager" : "lazy"}
/>
</div>
);
}
return (
<div
className={cn(
"relative overflow-hidden bg-[radial-gradient(circle_at_20%_20%,rgba(34,197,94,0.28),transparent_32%),linear-gradient(135deg,#0f3d2e,#163f59_52%,#111827)] text-white",
className,
)}
>
<div className="absolute inset-0 bg-[linear-gradient(45deg,rgba(255,255,255,0.08)_25%,transparent_25%,transparent_50%,rgba(255,255,255,0.08)_50%,rgba(255,255,255,0.08)_75%,transparent_75%,transparent)] bg-[length:28px_28px] opacity-25" />
<div className="relative flex h-full flex-col items-center justify-center gap-3 p-6 text-center">
<span className="rounded-full border border-white/25 bg-white/15 px-3 py-1 text-xs backdrop-blur">
{post.category?.name || "بلاگ"}
</span>
<span className="text-5xl font-black tracking-tight">{initials(post.title) || "گـ"}</span>
</div>
</div>
);
}

View File

@@ -1,101 +1,164 @@
import React from 'react'; "use client";
import ReactMarkdown from 'react-markdown';
import type { PluggableList } from 'unified';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
type MarkdownSize = 'sm' | 'base' | 'lg'; import React, { useState } from "react";
import { Check, Copy } from "lucide-react";
import ReactMarkdown from "react-markdown";
import type { PluggableList } from "unified";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
import rehypeSanitize from "rehype-sanitize";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { extractMarkdownHeadings } from "@/lib/markdown-headings";
import { cn } from "@/lib/utils";
type MarkdownSize = "sm" | "base" | "lg";
type MarkdownProps = { type MarkdownProps = {
content?: string; content?: string;
allowHtml?: boolean; allowHtml?: boolean;
className?: string; className?: string;
dir?: 'rtl' | 'ltr'; dir?: "rtl" | "ltr";
justify?: boolean; justify?: boolean;
size?: MarkdownSize; size?: MarkdownSize;
}; };
function CodeBlock({
className,
children,
}: {
className?: string;
children: React.ReactNode;
}) {
const [copied, setCopied] = useState(false);
const language = /language-([\w-]+)/.exec(className || "")?.[1] || "text";
const code = String(children).replace(/\n$/, "");
const copyCode = async () => {
if (!navigator.clipboard) return;
await navigator.clipboard.writeText(code);
setCopied(true);
window.setTimeout(() => setCopied(false), 1600);
};
return (
<div
dir="ltr"
className="my-5 overflow-hidden rounded-2xl border border-slate-700/70 bg-[#0f172a] text-left shadow-xl shadow-slate-950/10"
>
<div className="flex items-center justify-between border-b border-white/10 bg-white/5 px-4 py-2 text-xs text-slate-300">
<span className="font-mono uppercase tracking-wide">{language}</span>
<button
type="button"
onClick={copyCode}
className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-slate-300 transition hover:bg-white/10 hover:text-white"
>
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
{copied ? "Copied" : "Copy"}
</button>
</div>
<SyntaxHighlighter
language={language}
style={oneDark}
PreTag="div"
customStyle={{
margin: 0,
background: "transparent",
direction: "ltr",
padding: "1rem",
}}
codeTagProps={{
dir: "ltr",
style: {
direction: "ltr",
textAlign: "left",
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
},
}}
>
{code}
</SyntaxHighlighter>
</div>
);
}
export default function Markdown({ export default function Markdown({
content = '', content = "",
allowHtml = false, allowHtml = false,
className = '', className = "",
dir = 'rtl', dir = "rtl",
justify = false, justify = false,
size = 'sm', size = "sm",
}: MarkdownProps) { }: MarkdownProps) {
const rehypePlugins: PluggableList | undefined = allowHtml ? [rehypeRaw, rehypeSanitize] : undefined; const rehypePlugins: PluggableList | undefined = allowHtml ? [rehypeRaw, rehypeSanitize] : undefined;
const headings = extractMarkdownHeadings(content);
let headingIndex = 0;
const baseSizeClass = const baseSizeClass =
size === 'sm' ? 'text-sm' : size === 'lg' ? 'text-lg' : 'text-base'; size === "sm" ? "text-sm" : size === "lg" ? "text-lg" : "text-base";
const hScale = const hScale =
size === 'sm' size === "sm"
? { h1: 'text-xl', h2: 'text-lg', h3: 'text-base', h4: 'text-base' } ? { h1: "text-xl", h2: "text-lg", h3: "text-base", h4: "text-base" }
: size === 'base' : size === "base"
? { h1: 'text-3xl', h2: 'text-2xl', h3: 'text-xl', h4: 'text-lg' } ? { h1: "text-3xl", h2: "text-2xl", h3: "text-xl", h4: "text-lg" }
: { h1: 'text-4xl', h2: 'text-3xl', h3: 'text-2xl', h4: 'text-xl' }; : { h1: "text-4xl", h2: "text-3xl", h3: "text-2xl", h4: "text-xl" };
const justifyStyle: React.CSSProperties | undefined = justify const justifyStyle: React.CSSProperties | undefined = justify
? { textAlign: 'justify', textJustify: 'inter-word' } ? { textAlign: "justify", textJustify: "inter-word" }
: undefined; : undefined;
const nextHeadingId = (level: 1 | 2 | 3) => {
while (headingIndex < headings.length) {
const heading = headings[headingIndex];
headingIndex += 1;
if (heading.level === level) return heading.id;
}
return undefined;
};
return ( return (
<div <div
dir={dir} dir={dir}
className={`markdown-body ${baseSizeClass} text-right leading-7 break-words ${className}`} className={cn("markdown-body break-words text-right leading-8", baseSizeClass, className)}
style={justifyStyle} style={justifyStyle}
> >
<ReactMarkdown <ReactMarkdown
remarkPlugins={[remarkGfm]} remarkPlugins={[remarkGfm]}
rehypePlugins={rehypePlugins} rehypePlugins={rehypePlugins}
components={{ components={{
h1: (p) => <h1 className={`mt-6 font-bold ${hScale.h1}`} {...p} />, h1: (p) => <h1 id={nextHeadingId(1)} className={cn("scroll-mt-28 pt-2 font-bold", hScale.h1)} {...p} />,
h2: (p) => <h2 className={`mt-6 font-bold ${hScale.h2}`} {...p} />, h2: (p) => <h2 id={nextHeadingId(2)} className={cn("scroll-mt-28 pt-2 font-bold", hScale.h2)} {...p} />,
h3: (p) => <h3 className={`mt-5 font-semibold ${hScale.h3}`} {...p} />, h3: (p) => <h3 id={nextHeadingId(3)} className={cn("scroll-mt-28 pt-2 font-semibold", hScale.h3)} {...p} />,
h4: (p) => <h4 className={`mt-4 font-semibold ${hScale.h4}`} {...p} />, h4: (p) => <h4 className={cn("mt-4 font-semibold", hScale.h4)} {...p} />,
p: (p) => <p className="my-3" {...p} />, p: (p) => <p className="my-4" {...p} />,
a: (p) => <a className="underline decoration-primary hover:opacity-90 break-all" target="_blank" rel="noopener noreferrer" {...p} />, a: (p) => <a className="break-all underline decoration-primary hover:opacity-90" target="_blank" rel="noopener noreferrer" {...p} />,
ul: (p) => <ul className="my-3 list-disc ps-6 space-y-1.5" {...p} />, ul: (p) => <ul className="my-4 list-disc space-y-1.5 pe-0 ps-6" {...p} />,
ol: (p) => <ol className="my-3 list-decimal ps-6 space-y-1.5" {...p} />, ol: (p) => <ol className="my-4 list-decimal space-y-1.5 pe-0 ps-6" {...p} />,
li: (p) => <li className="[&>ul]:my-1.5 [&>ol]:my-1.5" {...p} />, li: (p) => <li className="[&>ol]:my-1.5 [&>ul]:my-1.5" {...p} />,
hr: (p) => <hr className="my-5 border-muted" {...p} />, hr: (p) => <hr className="my-6 border-muted" {...p} />,
blockquote: (p) => ( blockquote: (p) => (
<blockquote className="my-3 border-r-4 pr-4 italic text-muted-foreground" {...p} /> <blockquote className="my-4 rounded-2xl border-r-4 border-primary bg-muted/40 py-3 pr-4 italic text-muted-foreground" {...p} />
), ),
code: ({ className, children, node, ...p }) => { code: ({ className, children, node, ...p }) => {
const isInline = const isInline =
node?.tagName === 'code' && node?.tagName === "code" &&
!/language-/.test(className || '') && !/language-/.test(className || "") &&
!String(children).includes('\n'); !String(children).includes("\n");
if (isInline) { if (isInline) {
return ( return (
<code className="rounded bg-muted px-1 py-0.5 text-[0.9em]" {...p}> <code dir="ltr" className="rounded bg-muted px-1.5 py-0.5 text-[0.9em]" {...p}>
{children} {children}
</code> </code>
); );
} }
return ( return <CodeBlock className={className}>{children}</CodeBlock>;
<code className={className} {...p}>
{children}
</code>
);
}, },
pre: ({ className = '', children, ...p }) => ( pre: ({ children }) => <>{children}</>,
<pre
className={[
"my-4 overflow-x-auto rounded-md bg-muted p-4 text-[0.9em]",
className,
].filter(Boolean).join(" ")}
{...p}
>
{children}
</pre>
),
table: (p) => ( table: (p) => (
<div className="my-3 overflow-x-auto"> <div className="my-4 overflow-x-auto">
<table className="w-full border-collapse" {...p} /> <table className="w-full border-collapse" {...p} />
</div> </div>
), ),

View File

@@ -0,0 +1,52 @@
export type MarkdownHeading = {
id: string;
level: 1 | 2 | 3;
text: string;
};
function plainHeadingText(value: string) {
return value
.replace(/`([^`]+)`/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1")
.replace(/\*([^*]+)\*/g, "$1")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/<[^>]*>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function headingIdBase(text: string) {
const normalized = text
.normalize("NFKC")
.toLowerCase()
.replace(/[^\p{L}\p{N}\s_-]/gu, "")
.trim()
.replace(/\s+/g, "-")
.slice(0, 80);
return normalized || "section";
}
export function extractMarkdownHeadings(content?: string): MarkdownHeading[] {
const counters = new Map<string, number>();
return (content || "")
.split(/\r?\n/)
.map((line) => {
const match = /^(#{1,3})\s+(.+?)\s*#*$/.exec(line.trim());
if (!match) return null;
const level = match[1].length as 1 | 2 | 3;
const text = plainHeadingText(match[2]);
const base = headingIdBase(text);
const nextCount = (counters.get(base) || 0) + 1;
counters.set(base, nextCount);
return {
id: nextCount === 1 ? base : `${base}-${nextCount}`,
level,
text,
};
})
.filter(Boolean) as MarkdownHeading[];
}

View File

@@ -89,6 +89,16 @@ export async function getPublicPost(slug: string) {
}); });
} }
export async function getRecommendedPosts(slug: string, limit = 3) {
return requestJson<Types.PostListSchema[]>(
`/api/blog/posts/${encodeURIComponent(slug)}/recommended`,
{
params: { limit },
revalidate: DEFAULT_REVALIDATE_SECONDS,
},
);
}
export async function getPublicEvents(options?: { search?: string; limit?: number }) { export async function getPublicEvents(options?: { search?: string; limit?: number }) {
const search = options?.search?.trim(); const search = options?.search?.trim();

View File

@@ -35,6 +35,24 @@ export function formatJalali(iso?: string, withTime: boolean = true): string {
} }
} }
export function formatJalaliDate(iso?: string): string {
if (!iso) return '—';
try {
const date = new Date(iso);
const locale = Intl.DateTimeFormat.supportedLocalesOf(['fa-IR-u-ca-persian']).length > 0
? 'fa-IR-u-ca-persian'
: 'fa-IR';
return new Intl.DateTimeFormat(locale, {
day: 'numeric',
month: 'long',
year: 'numeric',
}).format(date);
} catch {
return '—';
}
}
const DEFAULT_THUMB = "/placeholder.svg"; const DEFAULT_THUMB = "/placeholder.svg";
const pickFirstUrl = (...values: Array<string | null | undefined>) => const pickFirstUrl = (...values: Array<string | null | undefined>) =>
@@ -66,6 +84,22 @@ export const getEventSeoImageUrl = (event: Types.EventListItemSchema) =>
export const getThumbUrl = getEventCardImageUrl; export const getThumbUrl = getEventCardImageUrl;
export const getBlogCardImageUrl = (post: Types.PostListSchema) =>
[
post.absolute_featured_image_thumbnail_url,
post.absolute_featured_image_preview_url,
post.absolute_featured_image_url,
post.featured_image,
].find((value) => Boolean(value));
export const getBlogHeroImageUrl = (post: Types.PostListSchema) =>
[
post.absolute_featured_image_preview_url,
post.absolute_featured_image_url,
post.absolute_featured_image_thumbnail_url,
post.featured_image,
].find((value) => Boolean(value));
export const getGalleryImagePreviewUrl = ( export const getGalleryImagePreviewUrl = (
image: image:
| Types.EventGalleryItem | Types.EventGalleryItem

View File

@@ -1,12 +1,14 @@
"use client"; "use client";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import BlogThumbnail from "@/components/BlogThumbnail";
import { Input } from "@/components/ui/input";
import { Link, useLocation, useNavigate } from "@/lib/router"; import { Link, useLocation, useNavigate } from "@/lib/router";
import { api } from "@/lib/api"; import { api } from "@/lib/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type * as Types from "@/lib/types";
import { blogPostPath } from "@/lib/blog-routes"; import { blogPostPath } from "@/lib/blog-routes";
import { apiBaseUrl, toAbsoluteUrl } from "@/lib/site";
import type * as Types from "@/lib/types";
import { formatJalaliDate, getBlogCardImageUrl } from "@/lib/utils";
type BlogProps = { type BlogProps = {
initialPosts?: Types.PostListSchema[]; initialPosts?: Types.PostListSchema[];
@@ -60,59 +62,55 @@ export default function Blog({
}, [location.pathname, navigate, search]); }, [location.pathname, navigate, search]);
return ( return (
<div className="min-h-screen bg-background"> <div className="min-h-screen bg-[linear-gradient(180deg,hsl(var(--background)),hsl(var(--muted)/0.32))]" dir="rtl">
<div className="container mx-auto px-4 py-8"> <div className="container mx-auto px-4 py-10">
<h1 className="text-4xl font-bold mb-8">وبلاگ</h1> <div className="mb-8 flex flex-col gap-5 md:flex-row md:items-end md:justify-between">
<div className="text-right">
<div className="mb-8"> <p className="mb-2 text-sm font-medium text-primary">خواندنیهای انجمن</p>
<h1 className="text-4xl font-black tracking-tight">بلاگ</h1>
<p className="mt-3 max-w-2xl text-sm leading-7 text-muted-foreground">
نوشتههای آموزشی، تجربههای دانشجویی و یادداشتهای تخصصی اعضای انجمن علمی.
</p>
</div>
<Input <Input
type="text" type="text"
placeholder="جستجو در مقالات..." placeholder="جستجو در نوشته‌ها..."
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(event) => setSearch(event.target.value)}
className="max-w-md" className="max-w-md rounded-full bg-background/80 text-right shadow-sm backdrop-blur"
/> />
</div> </div>
{loading ? ( {loading ? (
<p className="text-center text-muted-foreground">در حال بارگذاری...</p> <p className="text-center text-muted-foreground">در حال بارگذاری...</p>
) : posts.length === 0 ? ( ) : posts.length === 0 ? (
<p className="text-center text-muted-foreground">مقالهای یافت نشد</p> <p className="rounded-3xl border border-dashed bg-background/70 p-10 text-center text-muted-foreground">
نوشتهای پیدا نشد.
</p>
) : ( ) : (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
{posts.map((post) => ( {posts.map((post) => (
<Link key={post.id} to={blogPostPath(post.slug)}> <Link
<Card className="h-full hover:shadow-lg transition-shadow"> key={post.id}
{(post.absolute_featured_image_thumbnail_url || post.absolute_featured_image_preview_url || post.absolute_featured_image_url || post.featured_image) ? ( to={blogPostPath(post.slug)}
<div className="aspect-video overflow-hidden rounded-t-lg bg-muted"> className="group overflow-hidden rounded-[2rem] border border-border/70 bg-card/85 shadow-sm transition duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-primary/10"
<img >
src={post.absolute_featured_image_thumbnail_url || post.absolute_featured_image_preview_url || post.absolute_featured_image_url || post.featured_image} <BlogThumbnail
alt={post.title} post={post}
className="h-full w-full object-cover transition duration-300 group-hover:scale-[1.02]" imageUrl={toAbsoluteUrl(getBlogCardImageUrl(post), apiBaseUrl)}
loading="lazy" className="aspect-[16/10] rounded-t-[2rem]"
/> />
</div> <article className="space-y-4 p-5 text-right">
) : null} <h2 className="line-clamp-2 text-xl font-bold leading-9 transition group-hover:text-primary">
<CardHeader> {post.title}
<CardTitle className="line-clamp-2">{post.title}</CardTitle> </h2>
<CardDescription> <p className="line-clamp-3 min-h-[5.25rem] text-sm leading-7 text-muted-foreground">
{post.category?.name && ( {post.excerpt || post.seo_description || "خلاصه‌ای برای این نوشته ثبت نشده است."}
<span className="text-primary ml-2">{post.category.name}</span> </p>
)} <time className="block text-xs font-medium text-primary/80" dateTime={post.published_at || post.created_at}>
{new Date(post.created_at).toLocaleDateString("fa-IR")} {formatJalaliDate(post.published_at || post.created_at)}
</CardDescription> </time>
</CardHeader> </article>
<CardContent>
{post.excerpt && (
<p className="text-muted-foreground line-clamp-3 mb-4">
{post.excerpt}
</p>
)}
<p className="text-sm">
نویسنده: {post.author.first_name} {post.author.last_name}
</p>
</CardContent>
</Card>
</Link> </Link>
))} ))}
</div> </div>