From 280a35b2975aa9711ada4f1dd2d0f5bef54b45fc Mon Sep 17 00:00:00 2001 From: miyaji255 <84168445+miyaji255@users.noreply.github.com> Date: Fri, 17 Jan 2025 10:19:20 +0900 Subject: [PATCH] Add table of contents to blog page --- src/components/blog/BlogContent.astro | 13 ++++++++++++- src/components/blog/TableOfContents.astro | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/components/blog/TableOfContents.astro diff --git a/src/components/blog/BlogContent.astro b/src/components/blog/BlogContent.astro index 832e314..ef85956 100644 --- a/src/components/blog/BlogContent.astro +++ b/src/components/blog/BlogContent.astro @@ -9,6 +9,8 @@ import TagSmallList from './tag/TagSmallList.astro' import AuthorIcon from './icon/AuthorIcon.astro' import { formatDate } from '@/utils/format-date' import '@/styles/remark-link-card.css' +import TableOfContents from './TableOfContents.astro' + interface Props { blog: CollectionEntry<'blogs'> } @@ -20,7 +22,15 @@ const { data: blogMeta } = (await getEntry({ })) ?? { data: { postDate: new Date(), updateDate: undefined } } const tags = await getEntries(blog.data.tags) const author = await getEntry(blog.data.author) -const { Content } = await render(blog) +const { Content, headings } = await render(blog) + +const hasH1 = headings.some((heading) => heading.depth === 1) +const tocHeadings = hasH1 + ? headings.filter((heading) => heading.depth <= 2) + : headings.filter((heading) => heading.depth <= 3).map((heading) => ({ + ...heading, + depth: heading.depth - 1, + })) ---