From ea6f00f3c1ea5287169332bc19f433a2b811d162 Mon Sep 17 00:00:00 2001 From: Victor Lin <13424970+victorlin@users.noreply.github.com> Date: Wed, 11 Dec 2024 16:04:35 -0800 Subject: [PATCH] Add anchor links to headings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit adds GitHub-style anchor links¹ to heading elements. I also added a '#' on hover. ¹ https://github.com/markedjs/marked/blob/10020d018d4448b1d2d4612baf650c4e3a5949bf/docs/USING_PRO.md#the-renderer--renderer --- static-site/app/blog/parseMarkdown.ts | 27 ++++++++++++++++++++++++++- static-site/app/blog/utils.ts | 5 ++++- static-site/app/styles/globals.css | 13 +++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/static-site/app/blog/parseMarkdown.ts b/static-site/app/blog/parseMarkdown.ts index 2f77b7439..ff45cfd2c 100644 --- a/static-site/app/blog/parseMarkdown.ts +++ b/static-site/app/blog/parseMarkdown.ts @@ -3,7 +3,32 @@ import sanitizeHtml, { Attributes, IOptions, Tag } from "sanitize-html"; import { siteUrl } from "../../data/BaseConfig"; -export default async function parseMarkdown(mdString: string): Promise { +export default async function parseMarkdown({ + mdString, + addHeadingAnchors = false, +}: { + mdString: string + + /** Should `` tags be added to headings? */ + addHeadingAnchors?: boolean +}): Promise { + if (addHeadingAnchors) { + marked.use({ + renderer: { + heading({ tokens, depth }) { + const text = this.parser.parseInline(tokens); + const anchor = text.toLowerCase().replace(/[^\w]+/g, '-'); + return ` + + # + ${text} + + `; + } + } + }); + } + const rawDescription = await marked.parse(mdString); const sanitizerConfig: IOptions = { diff --git a/static-site/app/blog/utils.ts b/static-site/app/blog/utils.ts index c6a47de11..7416cb605 100644 --- a/static-site/app/blog/utils.ts +++ b/static-site/app/blog/utils.ts @@ -63,7 +63,10 @@ export function getBlogPosts(): BlogPost[] { export async function markdownToHtml(mdString:string): Promise { try { - return await parseMarkdown(mdString) + return await parseMarkdown({ + mdString, + addHeadingAnchors: true, + }) } catch(error) { console.error(`Error parsing markdown: ${error}`); diff --git a/static-site/app/styles/globals.css b/static-site/app/styles/globals.css index be933d28e..aa321ec25 100644 --- a/static-site/app/styles/globals.css +++ b/static-site/app/styles/globals.css @@ -139,3 +139,16 @@ p.wideParagraph { line-height: var(--tightLineHight); margin: 20px 0 0; } + + +/* For blog posts */ + +.anchor { + position: absolute; + left: -3px; + opacity: 0; +} + +.anchor:hover { + opacity: 100; +}