1
0
mirror of https://github.com/avinal/avinal.github.io.git synced 2026-07-04 07:40:09 +05:30
Files
avinal.github.io/src/pages/posts/[...slug].astro
T
avinal 5fa9a10203 feat: add TOC, related posts, and reading progress bar
Assisted by Claude Code

Signed-off-by: Avinal Kumar <avinal.xlvii@gmail.com>
2026-05-02 18:18:32 +05:30

50 lines
1.4 KiB
Plaintext

---
import { getCollection, render } from "astro:content";
import PostLayout from "@/layouts/PostLayout.astro";
export async function getStaticPaths() {
const posts = await getCollection("posts", ({ data }) => !data.draft);
return posts.map((post) => ({
params: { slug: post.id },
props: { post },
}));
}
const { post } = Astro.props;
const { Content, headings } = await render(post);
const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
const wordCount = post.body?.split(/\s+/).length ?? 0;
const minutes = Math.max(1, Math.round(wordCount / 220));
const readingTime = `${minutes} min read`;
const allPosts = await getCollection("posts", ({ data }) => !data.draft);
const relatedPosts = allPosts
.filter((p) => p.id !== post.id)
.map((p) => {
let score = 0;
if (p.data.category === post.data.category) score += 10;
score += p.data.tags.filter((t) => post.data.tags.includes(t)).length * 3;
return { post: p, score };
})
.filter((s) => s.score > 0)
.sort((a, b) => b.score - a.score || b.post.data.date.getTime() - a.post.data.date.getTime())
.slice(0, 3)
.map((s) => s.post);
---
<PostLayout
title={post.data.title}
description={post.data.description}
date={post.data.date}
modified={post.data.modified}
category={post.data.category}
tags={post.data.tags}
image={post.data.image}
readingTime={readingTime}
headings={tocHeadings}
relatedPosts={relatedPosts}
>
<Content />
</PostLayout>