diff --git a/src/components/tree/Headings.astro b/src/components/tree/Headings.astro index b374b13..b77220f 100644 --- a/src/components/tree/Headings.astro +++ b/src/components/tree/Headings.astro @@ -8,6 +8,27 @@ interface Props { headings: MarkdownHeading[]; } +export type Nested = MarkdownHeading & { children?: MarkdownHeading[] }; + + +function fold(headings: MarkdownHeading[]): Nested[] { + const toc = [] as Nested[]; + const map = new Map(); + for (const h of headings) { + const heading = { ...h }; + map.set(heading.depth, heading); + if (heading.depth === 2) + toc.push(heading) + else { + const backref = map.get(heading.depth - 1)!; + backref.children + ? backref.children.push(heading) + : backref.children = [heading]; + } + } + return toc; +} + const { headings } = Astro.props; --- @@ -16,5 +37,7 @@ const { headings } = Astro.props; Content diff --git a/src/components/tree/HeadingsList.astro b/src/components/tree/HeadingsList.astro index 26f2bbe..c7efdf5 100644 --- a/src/components/tree/HeadingsList.astro +++ b/src/components/tree/HeadingsList.astro @@ -1,38 +1,17 @@ --- -import type { MarkdownHeading } from 'astro'; import { Maybe } from 'purify-ts'; +import type { Nested } from './Headings.astro'; interface Props { - headings: Maybe; + headings: Maybe; } -type Nested = MarkdownHeading & { children?: MarkdownHeading[] }; - const { headings } = Astro.props; - -function fold(headings: MarkdownHeading[]) { - const toc = [] as Nested[]; - const map = new Map(); - for (const h of headings) { - const heading = { ...h }; - map.set(heading.depth, heading); - if (heading.depth === 2) - toc.push(heading) - else { - const backref = map.get(heading.depth - 1)!; - backref.children - ? backref.children.push(heading) - : backref.children = [heading]; - } - } - return toc; -} --- {headings - .map(fold) .map(headings =>