feat: implement blog post detail page with markdown rendering, table of contents, and reading progress bar

This commit is contained in:
Poyraz Avsever
2026-04-10 09:54:35 +03:00
parent af6d4c9f4d
commit 62e024c0a7
6 changed files with 257 additions and 153 deletions
+3 -2
View File
@@ -2,7 +2,7 @@ import { BlogContent } from "@/components/blog-content";
import { getBlogPageData } from "@/data/blog";
type BlogPageProps = {
searchParams?: Promise<{ page?: string | string[]; category?: string | string[] }>;
searchParams?: Promise<{ page?: string | string[]; category?: string | string[]; search?: string | string[] }>;
};
export default async function BlogPage({ searchParams }: BlogPageProps) {
@@ -11,9 +11,10 @@ export default async function BlogPage({ searchParams }: BlogPageProps) {
const categoryParam = Array.isArray(resolved?.category)
? resolved?.category[0]
: resolved?.category;
const searchParam = Array.isArray(resolved?.search) ? resolved?.search[0] : resolved?.search;
const page = Number(pageParam ?? "1");
const currentPage = Number.isFinite(page) && page > 0 ? Math.floor(page) : 1;
const data = await getBlogPageData(currentPage, 12, categoryParam);
const data = await getBlogPageData(currentPage, 12, categoryParam, searchParam);
return <BlogContent data={data} />;
}
+3 -3
View File
@@ -1,4 +1,4 @@
"use client";
"use client";
import { Icon } from "@iconify/react";
import Link from "next/link";
@@ -24,7 +24,7 @@ export function AppShell({ children }: AppShellProps) {
return (
<>
<NekoFollower />
<div className="mx-auto flex w-full max-w-4xl flex-col overflow-hidden px-4 py-4 sm:px-6">
<div className="mx-auto flex w-full max-w-4xl flex-col px-4 py-4 sm:px-6">
<SiteNavbar />
{announcement ? (
<AnnouncementBar
@@ -47,7 +47,7 @@ export function AppShell({ children }: AppShellProps) {
{announcement.text}
</AnnouncementBar>
) : null}
<main className="flex-1 overflow-hidden py-4">{children}</main>
<main className="flex-1 py-4">{children}</main>
</div>
</>
);
+132 -53
View File
@@ -1,10 +1,12 @@
"use client";
import { useState, useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Icon } from "@iconify/react";
import { Badge, Card, Typography } from "poyraz-ui/atoms";
import {
ArticleCard,
NewsCard,
Pagination,
PaginationContent,
PaginationItem,
@@ -19,72 +21,116 @@ type BlogContentProps = {
data: BlogPageData;
};
function pageHref(page: number, category: string) {
const params = new URLSearchParams();
function buildHref(params: { page?: number; category?: string; search?: string }) {
const qs = new URLSearchParams();
if (page > 1) {
params.set("page", String(page));
}
if (params.page && params.page > 1) qs.set("page", String(params.page));
if (params.category && params.category !== "All") qs.set("category", params.category);
if (params.search) qs.set("search", params.search);
if (category !== "All") {
params.set("category", category);
}
const query = params.toString();
const query = qs.toString();
return query ? `/blog?${query}` : "/blog";
}
function categoryHref(category: string) {
if (category === "All") {
return "/blog";
}
const params = new URLSearchParams();
params.set("category", category);
return `/blog?${params.toString()}`;
}
export function BlogContent({ data }: BlogContentProps) {
const pageNumbers = Array.from({ length: data.totalPages }, (_, index) => index + 1);
const router = useRouter();
const [searchInput, setSearchInput] = useState(data.searchQuery);
const pageNumbers = Array.from({ length: data.totalPages }, (_, i) => i + 1);
const hasArticles = data.articles.length > 0;
return (
<section className="flex h-full flex-col gap-3 overflow-hidden">
<div className="grid gap-3 md:grid-cols-[1.35fr_1fr]">
<div className="space-y-2">
{data.news.map((post) => (
<NewsCard
key={post.id}
image={post.image}
category={post.category}
title={post.title}
date={post.date}
href={post.href}
className="rounded-sm border-border"
/>
))}
</div>
const submitSearch = useCallback(
(value: string) => {
const trimmed = value.trim();
router.push(buildHref({ category: data.selectedCategory, search: trimmed }));
},
[router, data.selectedCategory],
);
<div className="grid gap-3 md:grid-rows-[auto_1fr]">
const clearFilters = useCallback(() => {
setSearchInput("");
router.push("/blog");
}, [router]);
return (
<section className="flex h-full flex-col gap-4 overflow-y-auto">
{/* Filtre Çubuğu */}
<Card className="rounded-sm border-border p-4">
<Typography variant="large">Kategoriler</Typography>
<div className="mt-3 flex flex-wrap gap-2">
<div className="flex flex-col gap-3">
{/* Kategoriler */}
<div className="flex flex-wrap items-center gap-2">
<Typography variant="small" className="mr-1 text-muted-foreground">
Kategori:
</Typography>
{data.categories.map((category) => (
<Link key={category} href={categoryHref(category)}>
<Link
key={category}
href={buildHref({ category, search: data.searchQuery })}
>
<Badge
variant={category === data.selectedCategory ? "default" : "outline"}
className="cursor-pointer rounded-sm"
className="cursor-pointer rounded-sm transition-colors"
>
{category}
</Badge>
</Link>
))}
</div>
</Card>
</div>
</div>
{/* Arama */}
<div className="relative">
<Icon
icon="mdi:magnify"
width={18}
height={18}
className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-muted-foreground"
/>
<input
id="blog-search"
type="text"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submitSearch(searchInput);
}}
placeholder="Başlık veya içerikte ara..."
className="w-full rounded-sm border border-border bg-background py-2 pr-10 pl-9 text-sm text-foreground placeholder:text-muted-foreground focus:border-red-600 focus:ring-1 focus:ring-red-600/30 focus:outline-none"
/>
{searchInput && (
<button
type="button"
onClick={() => {
setSearchInput("");
submitSearch("");
}}
className="absolute top-1/2 right-3 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground"
>
<Icon icon="mdi:close" width={16} height={16} />
</button>
)}
</div>
</div>
</Card>
{/* Aktif filtre göstergesi */}
{(data.searchQuery || data.selectedCategory !== "All") && (
<div className="flex items-center gap-2">
<Typography variant="small" className="text-muted-foreground">
{data.articles.length} sonuç
{data.searchQuery ? ` · "${data.searchQuery}"` : ""}
{data.selectedCategory !== "All" ? ` · ${data.selectedCategory}` : ""}
</Typography>
<button
type="button"
onClick={clearFilters}
className="inline-flex cursor-pointer items-center gap-1 rounded-sm border border-border px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
>
<Icon icon="mdi:filter-remove-outline" width={14} height={14} />
Temizle
</button>
</div>
)}
{/* Yazı Kartları */}
<div className="space-y-3">
{hasArticles ? (
<StaggerContainer className="grid gap-3 md:grid-cols-3">
@@ -98,27 +144,51 @@ export function BlogContent({ data }: BlogContentProps) {
date={post.date}
readTime={post.readTime}
href={post.href}
className="rounded-sm border-border [&_h3]:line-clamp-2 [&_h3]:min-h-[2.5rem]"
className="rounded-sm border-border [&_h3]:line-clamp-2 [&_h3]:min-h-[2.5rem] [&_p]:line-clamp-3"
author={{ name: post.author, avatar: "/logo/logo.jpeg" }}
/>
</StaggerItem>
))}
</StaggerContainer>
) : (
<Card className="rounded-sm border-border p-5">
<Card className="rounded-sm border-border p-8 text-center">
<Icon
icon="mdi:file-search-outline"
width={40}
height={40}
className="mx-auto mb-3 text-muted-foreground/50"
/>
<Typography variant="p" className="text-muted-foreground">
{data.selectedCategory === "All"
{data.searchQuery
? `"${data.searchQuery}" aramasına uygun sonuç bulunamadı.`
: data.selectedCategory === "All"
? "Henüz blog yazısı bulunmuyor."
: `"${data.selectedCategory}" kategorisinde henüz blog yazısı bulunmuyor.`}
</Typography>
{(data.searchQuery || data.selectedCategory !== "All") && (
<button
type="button"
onClick={clearFilters}
className="mt-3 inline-flex cursor-pointer items-center gap-1.5 rounded-sm border border-border px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<Icon icon="mdi:filter-remove-outline" width={16} height={16} />
Filtreleri Temizle
</button>
)}
</Card>
)}
{/* Sayfalama */}
{data.totalPages > 1 && (
<Pagination className="mx-0 mt-4 justify-start">
<PaginationContent className="justify-start">
<PaginationItem>
<PaginationPrevious
href={pageHref(Math.max(1, data.currentPage - 1), data.selectedCategory)}
href={buildHref({
page: Math.max(1, data.currentPage - 1),
category: data.selectedCategory,
search: data.searchQuery,
})}
aria-disabled={data.currentPage <= 1}
/>
</PaginationItem>
@@ -126,7 +196,11 @@ export function BlogContent({ data }: BlogContentProps) {
{pageNumbers.map((page) => (
<PaginationItem key={page}>
<PaginationLink
href={pageHref(page, data.selectedCategory)}
href={buildHref({
page,
category: data.selectedCategory,
search: data.searchQuery,
})}
isActive={page === data.currentPage}
>
{page}
@@ -136,12 +210,17 @@ export function BlogContent({ data }: BlogContentProps) {
<PaginationItem>
<PaginationNext
href={pageHref(Math.min(data.totalPages, data.currentPage + 1), data.selectedCategory)}
href={buildHref({
page: Math.min(data.totalPages, data.currentPage + 1),
category: data.selectedCategory,
search: data.searchQuery,
})}
aria-disabled={data.currentPage >= data.totalPages}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
)}
</div>
</section>
);
+57 -24
View File
@@ -3,7 +3,8 @@
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Icon } from "@iconify/react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";
import { Badge, Card, Typography } from "poyraz-ui/atoms";
@@ -99,38 +100,37 @@ const GISCUS_CATEGORY = process.env.NEXT_PUBLIC_GISCUS_CATEGORY || "Announcement
const GISCUS_CATEGORY_ID = process.env.NEXT_PUBLIC_GISCUS_CATEGORY_ID || "";
export function BlogDetailContent({ post }: BlogDetailContentProps) {
const scrollerRef = useRef<HTMLDivElement | null>(null);
const [progress, setProgress] = useState(0);
const progressWidth = useMemo(() => `${Math.min(100, Math.max(0, progress))}%`, [progress]);
const progressBarRef = useRef<HTMLDivElement | null>(null);
const [tocOpen, setTocOpen] = useState(false);
const handleScroll = () => {
const element = scrollerRef.current;
if (!element) return;
const closeToc = useCallback(() => setTocOpen(false), []);
const scrollable = element.scrollHeight - element.clientHeight;
if (scrollable <= 0) {
setProgress(100);
return;
}
setProgress((element.scrollTop / scrollable) * 100);
useEffect(() => {
const update = () => {
const bar = progressBarRef.current;
if (!bar) return;
const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const pct = docHeight <= 0 ? 100 : (window.scrollY / docHeight) * 100;
bar.style.width = `${Math.min(100, Math.max(0, pct))}%`;
};
window.addEventListener("scroll", update, { passive: true });
update();
return () => window.removeEventListener("scroll", update);
}, []);
const showGiscus = GISCUS_REPO && GISCUS_REPO_ID && GISCUS_CATEGORY_ID;
return (
<>
<div className="fixed top-0 left-0 z-50 h-1 w-full bg-border/70">
<div className="h-full bg-red-600 transition-[width] duration-100" style={{ width: progressWidth }} />
<div ref={progressBarRef} className="h-full w-0 bg-red-600" />
</div>
<div className="flex h-full gap-4">
<div
ref={scrollerRef}
onScroll={handleScroll}
className="relative h-full flex-1 overflow-y-auto rounded-sm border border-border"
>
<article className="space-y-5 p-5 md:p-8">
<div className="flex gap-4">
<div className="min-w-0 flex-1">
<article className="space-y-5 rounded-sm border border-border p-5 md:p-8">
<Link
href="/blog"
className="inline-flex items-center rounded-sm border border-border px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
@@ -332,11 +332,44 @@ export function BlogDetailContent({ post }: BlogDetailContentProps) {
</div>
<aside className="hidden w-52 shrink-0 lg:block">
<div className="sticky top-4">
<BlogToc markdown={post.markdown} scrollerRef={scrollerRef} />
<div className="sticky top-24">
<BlogToc markdown={post.markdown} />
</div>
</aside>
</div>
{/* Mobil İçindekiler Butonu */}
<button
type="button"
onClick={() => setTocOpen(true)}
className="fixed right-4 bottom-6 z-40 flex h-11 w-11 cursor-pointer items-center justify-center rounded-full border border-border bg-background shadow-lg transition-transform hover:scale-105 active:scale-95 lg:hidden"
aria-label="İçindekiler"
>
<Icon icon="mdi:table-of-contents" width={22} height={22} className="text-red-600" />
</button>
{/* Mobil İçindekiler Drawer */}
{tocOpen && (
<div className="fixed inset-0 z-50 lg:hidden" onClick={closeToc}>
<div className="absolute inset-0 bg-black/40" />
<div
className="absolute right-0 bottom-0 left-0 max-h-[60vh] overflow-y-auto rounded-t-xl border-t border-border bg-background p-5 shadow-2xl animate-in slide-in-from-bottom duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="mb-3 flex items-center justify-between">
<Typography variant="large">İçindekiler</Typography>
<button
type="button"
onClick={closeToc}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<Icon icon="mdi:close" width={18} height={18} />
</button>
</div>
<BlogToc markdown={post.markdown} onNavigate={closeToc} />
</div>
</div>
)}
</>
);
}
+10 -16
View File
@@ -36,30 +36,24 @@ function parseHeadings(markdown: string): TocHeading[] {
type BlogTocProps = {
markdown: string;
scrollerRef: React.RefObject<HTMLDivElement | null>;
onNavigate?: () => void;
};
export function BlogToc({ markdown, scrollerRef }: BlogTocProps) {
export function BlogToc({ markdown, onNavigate }: BlogTocProps) {
const headings = useMemo(() => parseHeadings(markdown), [markdown]);
const [activeId, setActiveId] = useState("");
const observerRef = useRef<IntersectionObserver | null>(null);
const handleClick = useCallback(
(id: string) => {
const scroller = scrollerRef.current;
if (!scroller) return;
const target = scroller.querySelector(`#${CSS.escape(id)}`);
const handleClick = useCallback((id: string) => {
const target = document.getElementById(id);
if (!target) return;
target.scrollIntoView({ behavior: "smooth", block: "start" });
},
[scrollerRef],
);
onNavigate?.();
}, [onNavigate]);
useEffect(() => {
const scroller = scrollerRef.current;
if (!scroller || headings.length === 0) return;
if (headings.length === 0) return;
observerRef.current = new IntersectionObserver(
(entries) => {
@@ -69,11 +63,11 @@ export function BlogToc({ markdown, scrollerRef }: BlogTocProps) {
}
}
},
{ root: scroller, rootMargin: "0px 0px -60% 0px", threshold: 0.1 },
{ root: null, rootMargin: "0px 0px -60% 0px", threshold: 0.1 },
);
const elements = headings
.map((h) => scroller.querySelector(`#${CSS.escape(h.id)}`))
.map((h) => document.getElementById(h.id))
.filter(Boolean) as Element[];
for (const el of elements) {
@@ -83,7 +77,7 @@ export function BlogToc({ markdown, scrollerRef }: BlogTocProps) {
return () => {
observerRef.current?.disconnect();
};
}, [headings, scrollerRef]);
}, [headings]);
if (headings.length < 2) return null;
+19 -22
View File
@@ -2,15 +2,6 @@ import "server-only";
import { listBlogDetails } from "@/data/blog-detail";
export type BlogNewsItem = {
id: string;
title: string;
category: string;
image: string;
date: string;
href: string;
};
export type BlogArticleItem = {
id: string;
slug: string;
@@ -25,10 +16,10 @@ export type BlogArticleItem = {
};
export type BlogPageData = {
news: BlogNewsItem[];
articles: BlogArticleItem[];
categories: string[];
selectedCategory: string;
searchQuery: string;
totalPages: number;
currentPage: number;
};
@@ -82,7 +73,7 @@ export async function getAllBlogArticles(): Promise<BlogArticleItem[]> {
return sortByDateDesc(articles);
}
export async function getHomeBlogNews(limit = 3): Promise<BlogNewsItem[]> {
export async function getHomeBlogNews(limit = 3) {
const articles = await getAllBlogArticles();
return articles.slice(0, limit).map((item) => ({
@@ -99,6 +90,7 @@ export async function getBlogPageData(
page = 1,
pageSize = 12,
selectedCategoryParam?: string,
searchQueryParam?: string,
): Promise<BlogPageData> {
const articles = await getAllBlogArticles();
const categories = BLOG_CATEGORIES;
@@ -108,27 +100,32 @@ export async function getBlogPageData(
const requestedCategory = selectedCategoryParam?.trim();
const selectedCategory =
(requestedCategory && categoryByNormalized.get(normalizeCategory(requestedCategory))) || "All";
const filteredArticles =
const searchQuery = (searchQueryParam ?? "").trim();
const searchLower = searchQuery.toLocaleLowerCase();
let filtered =
selectedCategory === "All"
? articles
: articles.filter((item) => normalizeCategory(item.category) === normalizeCategory(selectedCategory));
const totalPages = Math.max(1, Math.ceil(Math.max(filteredArticles.length, 1) / pageSize));
if (searchLower) {
filtered = filtered.filter(
(item) =>
item.title.toLocaleLowerCase().includes(searchLower) ||
item.excerpt.toLocaleLowerCase().includes(searchLower),
);
}
const totalPages = Math.max(1, Math.ceil(Math.max(filtered.length, 1) / pageSize));
const currentPage = Math.min(Math.max(1, page), totalPages);
const start = (currentPage - 1) * pageSize;
const paginated = filteredArticles.slice(start, start + pageSize);
const paginated = filtered.slice(start, start + pageSize);
return {
news: articles.slice(0, 4).map((item) => ({
id: `blog-news-${item.slug}`,
title: item.title,
category: item.category,
image: item.image,
date: item.date,
href: item.href,
})),
articles: paginated,
categories,
selectedCategory,
searchQuery,
totalPages,
currentPage,
};