sass-site/source/helpers/components/anchors.ts

47 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-04-21 21:01:43 +02:00
import Token from 'markdown-it/lib/token';
2023-04-24 18:28:42 +02:00
import type anchor from 'markdown-it-anchor';
2023-04-21 21:01:43 +02:00
2023-05-01 20:01:28 +02:00
/**
* Custom permalink function, inspired by `linkInsideHeader`,
* modified to include title text in permalink a11y text.
* @see https://github.com/valeriangalliat/markdown-it-anchor#custom-permalink
* @see https://github.com/valeriangalliat/markdown-it-anchor/blob/649582d58185b00cfb2ceee9b6b4cd6aafc645b7/permalink.js#L76
*/
2023-04-21 21:01:43 +02:00
export const renderPermalink: anchor.PermalinkGenerator = (
slug,
opts: anchor.LinkInsideHeaderPermalinkOptions,
state,
idx,
) => {
2023-05-01 20:01:28 +02:00
// https://github.com/valeriangalliat/markdown-it-anchor/blob/649582d58185b00cfb2ceee9b6b4cd6aafc645b7/permalink.js#L148-L151
const title = state.tokens[idx + 1]?.children
2023-04-21 21:01:43 +02:00
?.filter(
(token: Token) => token.type === 'text' || token.type === 'code_inline',
)
.reduce((acc, t) => acc + t.content, '');
2023-05-01 20:01:28 +02:00
opts.class = 'anchor';
opts.ariaHidden = false;
opts.symbol = `<span class="visuallyhidden">${
title || 'section'
} permalink</span>`;
// https://github.com/valeriangalliat/markdown-it-anchor/blob/649582d58185b00cfb2ceee9b6b4cd6aafc645b7/permalink.js#L77-L97
2023-04-21 21:01:43 +02:00
const linkTokens = [
Object.assign(new state.Token('link_open', 'a', 1), {
attrs: [
2023-05-01 20:01:28 +02:00
...(opts.class ? [['class', opts.class]] : []),
2023-04-21 21:01:43 +02:00
['href', `#${slug}`],
...(opts.ariaHidden ? [['aria-hidden', 'true']] : []),
],
}),
Object.assign(new state.Token('html_inline', '', 0), {
2023-05-01 20:01:28 +02:00
content: opts.symbol,
meta: { isPermalinkSymbol: true },
2023-04-21 21:01:43 +02:00
}),
new state.Token('link_close', 'a', -1),
];
2023-05-01 20:01:28 +02:00
state.tokens[idx + 1]?.children?.push(...linkTokens);
2023-04-21 21:01:43 +02:00
};