Skip to content

Commit

Permalink
Add anchor links to headings
Browse files Browse the repository at this point in the history
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
  • Loading branch information
victorlin committed Dec 12, 2024
1 parent c562b67 commit ea6f00f
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
27 changes: 26 additions & 1 deletion static-site/app/blog/parseMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
export default async function parseMarkdown({
mdString,
addHeadingAnchors = false,
}: {
mdString: string

/** Should `<a>` tags be added to headings? */
addHeadingAnchors?: boolean
}): Promise<string> {
if (addHeadingAnchors) {
marked.use({
renderer: {
heading({ tokens, depth }) {
const text = this.parser.parseInline(tokens);
const anchor = text.toLowerCase().replace(/[^\w]+/g, '-');
return `
<h${depth}>
<a name="${anchor}" class="anchor" href="#${anchor}">#</a>
${text}
</h${depth}>
`;
}
}
});
}

const rawDescription = await marked.parse(mdString);

const sanitizerConfig: IOptions = {
Expand Down
5 changes: 4 additions & 1 deletion static-site/app/blog/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ export function getBlogPosts(): BlogPost[] {

export async function markdownToHtml(mdString:string): Promise<string> {
try {
return await parseMarkdown(mdString)
return await parseMarkdown({
mdString,
addHeadingAnchors: true,
})
}
catch(error) {
console.error(`Error parsing markdown: ${error}`);
Expand Down
13 changes: 13 additions & 0 deletions static-site/app/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit ea6f00f

Please sign in to comment.