From 804bfbd08048a4824b19d3e011cc096d1ecef865 Mon Sep 17 00:00:00 2001 From: ClovertaTheTrilobita Date: Sat, 18 Apr 2026 21:38:42 +0300 Subject: [PATCH] Added navigation in posts --- src/components/Posts/PostNav.astro | 109 +++++++++++++++++++++++++ src/layouts/MarkdownPostLayout.astro | 7 +- src/pages/[lang]/posts/[...slug].astro | 1 + 3 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 src/components/Posts/PostNav.astro diff --git a/src/components/Posts/PostNav.astro b/src/components/Posts/PostNav.astro new file mode 100644 index 0000000..6a323eb --- /dev/null +++ b/src/components/Posts/PostNav.astro @@ -0,0 +1,109 @@ +--- +import { getCollection } from "astro:content"; +import type { CollectionEntry } from "astro:content"; +import type { Lang } from "@/i18n"; + +interface Props { + post: CollectionEntry<"blog">; + lang: Lang; +} + +const { post, lang } = Astro.props; + +const allPosts = await getCollection("blog"); + +// 只保留当前语言 +const sameLangPosts = allPosts.filter((p) => { + const [postLang] = p.id.split("/"); + return postLang === lang; +}); + +// 按日期倒序:越新越靠前 +const sortedPosts = [...sameLangPosts].sort( + (a, b) => + new Date(b.data.pubDate).getTime() - new Date(a.data.pubDate).getTime(), +); + +// 找当前文章位置 +const currentIndex = sortedPosts.findIndex((p) => p.id === post.id); + +// 更旧的一篇 +const prevPost = + currentIndex < sortedPosts.length - 1 + ? sortedPosts[currentIndex + 1] + : null; + +// 更新的一篇 +const nextPost = currentIndex > 0 ? sortedPosts[currentIndex - 1] : null; + +const getSlugFromId = (id: string) => id.split("/").slice(1).join("/"); + +const prevSlug = prevPost ? getSlugFromId(prevPost.id) : null; +const nextSlug = nextPost ? getSlugFromId(nextPost.id) : null; +--- + + + + diff --git a/src/layouts/MarkdownPostLayout.astro b/src/layouts/MarkdownPostLayout.astro index 873ed51..4c45f43 100644 --- a/src/layouts/MarkdownPostLayout.astro +++ b/src/layouts/MarkdownPostLayout.astro @@ -1,11 +1,12 @@ --- import BaseLayout from "./BaseLayout.astro"; import Remark42Embed from "@/components/Remark42Embed.astro"; +import PostNav from "@/components/Posts/PostNav.astro"; import { fade } from "astro:transitions"; -import { getLangFromUrl, getTranslations } from "@/i18n"; +import { getTranslations } from "@/i18n"; import "@/styles/global.css"; -const { frontmatter, lang, slug, postId } = Astro.props; +const { post, frontmatter, lang, slug, postId } = Astro.props; const comments = lang === "zh" ? "评论区" : "comments"; const t = getTranslations(lang); --- @@ -76,6 +77,8 @@ const t = getTranslations(lang); + +

{comments}

diff --git a/src/pages/[lang]/posts/[...slug].astro b/src/pages/[lang]/posts/[...slug].astro index be0def1..e09f631 100644 --- a/src/pages/[lang]/posts/[...slug].astro +++ b/src/pages/[lang]/posts/[...slug].astro @@ -29,6 +29,7 @@ const slug = slugParts.join("/"); ---