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"; import { getBlogPageData } from "@/data/blog";
type BlogPageProps = { 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) { export default async function BlogPage({ searchParams }: BlogPageProps) {
@@ -11,9 +11,10 @@ export default async function BlogPage({ searchParams }: BlogPageProps) {
const categoryParam = Array.isArray(resolved?.category) const categoryParam = Array.isArray(resolved?.category)
? resolved?.category[0] ? resolved?.category[0]
: resolved?.category; : resolved?.category;
const searchParam = Array.isArray(resolved?.search) ? resolved?.search[0] : resolved?.search;
const page = Number(pageParam ?? "1"); const page = Number(pageParam ?? "1");
const currentPage = Number.isFinite(page) && page > 0 ? Math.floor(page) : 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} />; return <BlogContent data={data} />;
} }
+3 -3
View File
@@ -1,4 +1,4 @@
"use client"; "use client";
import { Icon } from "@iconify/react"; import { Icon } from "@iconify/react";
import Link from "next/link"; import Link from "next/link";
@@ -24,7 +24,7 @@ export function AppShell({ children }: AppShellProps) {
return ( return (
<> <>
<NekoFollower /> <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 /> <SiteNavbar />
{announcement ? ( {announcement ? (
<AnnouncementBar <AnnouncementBar
@@ -47,7 +47,7 @@ export function AppShell({ children }: AppShellProps) {
{announcement.text} {announcement.text}
</AnnouncementBar> </AnnouncementBar>
) : null} ) : null}
<main className="flex-1 overflow-hidden py-4">{children}</main> <main className="flex-1 py-4">{children}</main>
</div> </div>
</> </>
); );
+163 -84
View File
@@ -1,10 +1,12 @@
"use client"; "use client";
import { useState, useCallback } from "react";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation";
import { Icon } from "@iconify/react";
import { Badge, Card, Typography } from "poyraz-ui/atoms"; import { Badge, Card, Typography } from "poyraz-ui/atoms";
import { import {
ArticleCard, ArticleCard,
NewsCard,
Pagination, Pagination,
PaginationContent, PaginationContent,
PaginationItem, PaginationItem,
@@ -19,72 +21,116 @@ type BlogContentProps = {
data: BlogPageData; data: BlogPageData;
}; };
function pageHref(page: number, category: string) { function buildHref(params: { page?: number; category?: string; search?: string }) {
const params = new URLSearchParams(); const qs = new URLSearchParams();
if (page > 1) { if (params.page && params.page > 1) qs.set("page", String(params.page));
params.set("page", String(page)); if (params.category && params.category !== "All") qs.set("category", params.category);
} if (params.search) qs.set("search", params.search);
if (category !== "All") { const query = qs.toString();
params.set("category", category);
}
const query = params.toString();
return query ? `/blog?${query}` : "/blog"; 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) { 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; const hasArticles = data.articles.length > 0;
const submitSearch = useCallback(
(value: string) => {
const trimmed = value.trim();
router.push(buildHref({ category: data.selectedCategory, search: trimmed }));
},
[router, data.selectedCategory],
);
const clearFilters = useCallback(() => {
setSearchInput("");
router.push("/blog");
}, [router]);
return ( return (
<section className="flex h-full flex-col gap-3 overflow-hidden"> <section className="flex h-full flex-col gap-4 overflow-y-auto">
<div className="grid gap-3 md:grid-cols-[1.35fr_1fr]"> {/* Filtre Çubuğu */}
<div className="space-y-2"> <Card className="rounded-sm border-border p-4">
{data.news.map((post) => ( <div className="flex flex-col gap-3">
<NewsCard {/* Kategoriler */}
key={post.id} <div className="flex flex-wrap items-center gap-2">
image={post.image} <Typography variant="small" className="mr-1 text-muted-foreground">
category={post.category} Kategori:
title={post.title} </Typography>
date={post.date} {data.categories.map((category) => (
href={post.href} <Link
className="rounded-sm border-border" key={category}
href={buildHref({ category, search: data.searchQuery })}
>
<Badge
variant={category === data.selectedCategory ? "default" : "outline"}
className="cursor-pointer rounded-sm transition-colors"
>
{category}
</Badge>
</Link>
))}
</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> </div>
</Card>
<div className="grid gap-3 md:grid-rows-[auto_1fr]"> {/* Aktif filtre göstergesi */}
<Card className="rounded-sm border-border p-4"> {(data.searchQuery || data.selectedCategory !== "All") && (
<Typography variant="large">Kategoriler</Typography> <div className="flex items-center gap-2">
<div className="mt-3 flex flex-wrap gap-2"> <Typography variant="small" className="text-muted-foreground">
{data.categories.map((category) => ( {data.articles.length} sonuç
<Link key={category} href={categoryHref(category)}> {data.searchQuery ? ` · "${data.searchQuery}"` : ""}
<Badge {data.selectedCategory !== "All" ? ` · ${data.selectedCategory}` : ""}
variant={category === data.selectedCategory ? "default" : "outline"} </Typography>
className="cursor-pointer rounded-sm" <button
> type="button"
{category} onClick={clearFilters}
</Badge> 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"
</Link> >
))} <Icon icon="mdi:filter-remove-outline" width={14} height={14} />
</div> Temizle
</Card> </button>
</div> </div>
</div> )}
{/* Yazı Kartları */}
<div className="space-y-3"> <div className="space-y-3">
{hasArticles ? ( {hasArticles ? (
<StaggerContainer className="grid gap-3 md:grid-cols-3"> <StaggerContainer className="grid gap-3 md:grid-cols-3">
@@ -98,50 +144,83 @@ export function BlogContent({ data }: BlogContentProps) {
date={post.date} date={post.date}
readTime={post.readTime} readTime={post.readTime}
href={post.href} 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" }} author={{ name: post.author, avatar: "/logo/logo.jpeg" }}
/> />
</StaggerItem> </StaggerItem>
))} ))}
</StaggerContainer> </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"> <Typography variant="p" className="text-muted-foreground">
{data.selectedCategory === "All" {data.searchQuery
? "Henüz blog yazısı bulunmuyor." ? `"${data.searchQuery}" aramasına uygun sonuç bulunamadı.`
: `"${data.selectedCategory}" kategorisinde henüz blog yazısı bulunmuyor.`} : data.selectedCategory === "All"
? "Henüz blog yazısı bulunmuyor."
: `"${data.selectedCategory}" kategorisinde henüz blog yazısı bulunmuyor.`}
</Typography> </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> </Card>
)} )}
<Pagination className="mx-0 mt-4 justify-start"> {/* Sayfalama */}
<PaginationContent className="justify-start"> {data.totalPages > 1 && (
<PaginationItem> <Pagination className="mx-0 mt-4 justify-start">
<PaginationPrevious <PaginationContent className="justify-start">
href={pageHref(Math.max(1, data.currentPage - 1), data.selectedCategory)} <PaginationItem>
aria-disabled={data.currentPage <= 1} <PaginationPrevious
/> href={buildHref({
</PaginationItem> page: Math.max(1, data.currentPage - 1),
category: data.selectedCategory,
{pageNumbers.map((page) => ( search: data.searchQuery,
<PaginationItem key={page}> })}
<PaginationLink aria-disabled={data.currentPage <= 1}
href={pageHref(page, data.selectedCategory)} />
isActive={page === data.currentPage}
>
{page}
</PaginationLink>
</PaginationItem> </PaginationItem>
))}
<PaginationItem> {pageNumbers.map((page) => (
<PaginationNext <PaginationItem key={page}>
href={pageHref(Math.min(data.totalPages, data.currentPage + 1), data.selectedCategory)} <PaginationLink
aria-disabled={data.currentPage >= data.totalPages} href={buildHref({
/> page,
</PaginationItem> category: data.selectedCategory,
</PaginationContent> search: data.searchQuery,
</Pagination> })}
isActive={page === data.currentPage}
>
{page}
</PaginationLink>
</PaginationItem>
))}
<PaginationItem>
<PaginationNext
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> </div>
</section> </section>
); );
+57 -24
View File
@@ -3,7 +3,8 @@
import Link from "next/link"; import Link from "next/link";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm"; 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 { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism"; import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";
import { Badge, Card, Typography } from "poyraz-ui/atoms"; 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 || ""; const GISCUS_CATEGORY_ID = process.env.NEXT_PUBLIC_GISCUS_CATEGORY_ID || "";
export function BlogDetailContent({ post }: BlogDetailContentProps) { export function BlogDetailContent({ post }: BlogDetailContentProps) {
const scrollerRef = useRef<HTMLDivElement | null>(null); const progressBarRef = useRef<HTMLDivElement | null>(null);
const [progress, setProgress] = useState(0); const [tocOpen, setTocOpen] = useState(false);
const progressWidth = useMemo(() => `${Math.min(100, Math.max(0, progress))}%`, [progress]);
const handleScroll = () => { const closeToc = useCallback(() => setTocOpen(false), []);
const element = scrollerRef.current;
if (!element) return;
const scrollable = element.scrollHeight - element.clientHeight; useEffect(() => {
if (scrollable <= 0) { const update = () => {
setProgress(100); const bar = progressBarRef.current;
return; 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))}%`;
};
setProgress((element.scrollTop / scrollable) * 100); window.addEventListener("scroll", update, { passive: true });
}; update();
return () => window.removeEventListener("scroll", update);
}, []);
const showGiscus = GISCUS_REPO && GISCUS_REPO_ID && GISCUS_CATEGORY_ID; const showGiscus = GISCUS_REPO && GISCUS_REPO_ID && GISCUS_CATEGORY_ID;
return ( return (
<> <>
<div className="fixed top-0 left-0 z-50 h-1 w-full bg-border/70"> <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>
<div className="flex h-full gap-4"> <div className="flex gap-4">
<div <div className="min-w-0 flex-1">
ref={scrollerRef} <article className="space-y-5 rounded-sm border border-border p-5 md:p-8">
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">
<Link <Link
href="/blog" 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" 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> </div>
<aside className="hidden w-52 shrink-0 lg:block"> <aside className="hidden w-52 shrink-0 lg:block">
<div className="sticky top-4"> <div className="sticky top-24">
<BlogToc markdown={post.markdown} scrollerRef={scrollerRef} /> <BlogToc markdown={post.markdown} />
</div> </div>
</aside> </aside>
</div> </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>
)}
</> </>
); );
} }
+12 -18
View File
@@ -36,30 +36,24 @@ function parseHeadings(markdown: string): TocHeading[] {
type BlogTocProps = { type BlogTocProps = {
markdown: string; 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 headings = useMemo(() => parseHeadings(markdown), [markdown]);
const [activeId, setActiveId] = useState(""); const [activeId, setActiveId] = useState("");
const observerRef = useRef<IntersectionObserver | null>(null); const observerRef = useRef<IntersectionObserver | null>(null);
const handleClick = useCallback( const handleClick = useCallback((id: string) => {
(id: string) => { const target = document.getElementById(id);
const scroller = scrollerRef.current; if (!target) return;
if (!scroller) return;
const target = scroller.querySelector(`#${CSS.escape(id)}`); target.scrollIntoView({ behavior: "smooth", block: "start" });
if (!target) return; onNavigate?.();
}, [onNavigate]);
target.scrollIntoView({ behavior: "smooth", block: "start" });
},
[scrollerRef],
);
useEffect(() => { useEffect(() => {
const scroller = scrollerRef.current; if (headings.length === 0) return;
if (!scroller || headings.length === 0) return;
observerRef.current = new IntersectionObserver( observerRef.current = new IntersectionObserver(
(entries) => { (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 const elements = headings
.map((h) => scroller.querySelector(`#${CSS.escape(h.id)}`)) .map((h) => document.getElementById(h.id))
.filter(Boolean) as Element[]; .filter(Boolean) as Element[];
for (const el of elements) { for (const el of elements) {
@@ -83,7 +77,7 @@ export function BlogToc({ markdown, scrollerRef }: BlogTocProps) {
return () => { return () => {
observerRef.current?.disconnect(); observerRef.current?.disconnect();
}; };
}, [headings, scrollerRef]); }, [headings]);
if (headings.length < 2) return null; if (headings.length < 2) return null;
+19 -22
View File
@@ -2,15 +2,6 @@ import "server-only";
import { listBlogDetails } from "@/data/blog-detail"; import { listBlogDetails } from "@/data/blog-detail";
export type BlogNewsItem = {
id: string;
title: string;
category: string;
image: string;
date: string;
href: string;
};
export type BlogArticleItem = { export type BlogArticleItem = {
id: string; id: string;
slug: string; slug: string;
@@ -25,10 +16,10 @@ export type BlogArticleItem = {
}; };
export type BlogPageData = { export type BlogPageData = {
news: BlogNewsItem[];
articles: BlogArticleItem[]; articles: BlogArticleItem[];
categories: string[]; categories: string[];
selectedCategory: string; selectedCategory: string;
searchQuery: string;
totalPages: number; totalPages: number;
currentPage: number; currentPage: number;
}; };
@@ -82,7 +73,7 @@ export async function getAllBlogArticles(): Promise<BlogArticleItem[]> {
return sortByDateDesc(articles); return sortByDateDesc(articles);
} }
export async function getHomeBlogNews(limit = 3): Promise<BlogNewsItem[]> { export async function getHomeBlogNews(limit = 3) {
const articles = await getAllBlogArticles(); const articles = await getAllBlogArticles();
return articles.slice(0, limit).map((item) => ({ return articles.slice(0, limit).map((item) => ({
@@ -99,6 +90,7 @@ export async function getBlogPageData(
page = 1, page = 1,
pageSize = 12, pageSize = 12,
selectedCategoryParam?: string, selectedCategoryParam?: string,
searchQueryParam?: string,
): Promise<BlogPageData> { ): Promise<BlogPageData> {
const articles = await getAllBlogArticles(); const articles = await getAllBlogArticles();
const categories = BLOG_CATEGORIES; const categories = BLOG_CATEGORIES;
@@ -108,27 +100,32 @@ export async function getBlogPageData(
const requestedCategory = selectedCategoryParam?.trim(); const requestedCategory = selectedCategoryParam?.trim();
const selectedCategory = const selectedCategory =
(requestedCategory && categoryByNormalized.get(normalizeCategory(requestedCategory))) || "All"; (requestedCategory && categoryByNormalized.get(normalizeCategory(requestedCategory))) || "All";
const filteredArticles = const searchQuery = (searchQueryParam ?? "").trim();
const searchLower = searchQuery.toLocaleLowerCase();
let filtered =
selectedCategory === "All" selectedCategory === "All"
? articles ? articles
: articles.filter((item) => normalizeCategory(item.category) === normalizeCategory(selectedCategory)); : 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 currentPage = Math.min(Math.max(1, page), totalPages);
const start = (currentPage - 1) * pageSize; const start = (currentPage - 1) * pageSize;
const paginated = filteredArticles.slice(start, start + pageSize); const paginated = filtered.slice(start, start + pageSize);
return { 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, articles: paginated,
categories, categories,
selectedCategory, selectedCategory,
searchQuery,
totalPages, totalPages,
currentPage, currentPage,
}; };