From 33d6838dc40f765660c879037436690abc284790 Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Sun, 20 Aug 2023 22:04:21 -0700 Subject: [PATCH] start work on table of contents --- src/lib/Post.svelte | 3 ++ src/lib/Toc.svelte | 67 +++++++++++++++++++++++++++++++++++++++++++ src/plugins/rehype.js | 2 +- src/plugins/remark.js | 19 ++++++++++++ 4 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 src/lib/Toc.svelte create mode 100644 src/plugins/remark.js diff --git a/src/lib/Post.svelte b/src/lib/Post.svelte index 4a2d17e..2fa47ec 100644 --- a/src/lib/Post.svelte +++ b/src/lib/Post.svelte @@ -3,6 +3,7 @@ import { formatDate } from './datefmt.js'; import { makeSlug } from '$lib/utils.js'; + import Toc from './Toc.svelte'; import Link from './Link.svelte'; export { Link as a }; @@ -11,6 +12,7 @@ export let title, date; export const description = ''; export const draft = false; + export let toc = null; + + +
+
Table of Contents
+ +
\ No newline at end of file diff --git a/src/plugins/rehype.js b/src/plugins/rehype.js index 2d5249d..83235cf 100644 --- a/src/plugins/rehype.js +++ b/src/plugins/rehype.js @@ -4,7 +4,7 @@ import { toText } from 'hast-util-to-text'; import { makeSlug } from '../lib/utils.js'; -export function localPlugins() { +export function localRehype() { let printed = false; return (tree, vfile) => { diff --git a/src/plugins/remark.js b/src/plugins/remark.js new file mode 100644 index 0000000..cbc1d82 --- /dev/null +++ b/src/plugins/remark.js @@ -0,0 +1,19 @@ +import { visit } from 'unist-util-visit'; +import { toString } from 'mdast-util-to-string'; + + +// build table of contents and inject into frontmatter +export function localRemark() { + return (tree, vfile) => { + let toc = []; + + visit(tree, 'heading', node => { + toc.push({ + text: toString(node), + depth: node.depth, + }); + }); + + vfile.data.fm.toc = toc; + } +}