forked from shadowfacts/shadowfacts.net
Adjust how link markdown decorations are shown
Use a custom data attribute that omits the scheme and is truncated at 40 chars
This commit is contained in:
parent
4d47e32b49
commit
2159a16b94
|
@ -2,6 +2,7 @@ import MarkdownIt from "markdown-it";
|
|||
import MarkdownItFootnote from "markdown-it-footnote";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import * as util from "./util";
|
||||
import { URL } from "url";
|
||||
|
||||
const md = new MarkdownIt({
|
||||
highlight: util.highlight,
|
||||
|
@ -13,7 +14,7 @@ md.use(MarkdownItFootnote);
|
|||
|
||||
// Inserts heading anchors
|
||||
// Based on https://github.com/valeriangalliat/markdown-it-anchor
|
||||
md.core.ruler.push("anchor", (state) => {
|
||||
md.core.ruler.push("header anchor", (state) => {
|
||||
const tokens = state.tokens;
|
||||
|
||||
tokens
|
||||
|
@ -48,6 +49,29 @@ md.core.ruler.push("anchor", (state) => {
|
|||
});
|
||||
});
|
||||
|
||||
// Adds data-link attributes to anchor elements
|
||||
const defaultRenderer = md.renderer.rules.link_open || function(tokens, index, options, env, self) {
|
||||
return self.renderToken(tokens, index, options);
|
||||
};
|
||||
md.renderer.rules.link_open = function(tokens, index, options, env, self) {
|
||||
const href = tokens[index].attrGet("href");
|
||||
if (href != null) {
|
||||
try {
|
||||
const parsed = new URL(href);
|
||||
const formattedPathname = parsed.pathname === "/" ? "" : parsed.pathname;//.length > 20 ? parsed.pathname.substr(0, 20) + "..." : parsed.pathname;
|
||||
let formatted = `${parsed.hostname}${formattedPathname}`;
|
||||
if (formatted.length > 40) {
|
||||
formatted = formatted.substr(0, 40) + "...";
|
||||
}
|
||||
tokens[index].attrPush(["data-link", formatted]);
|
||||
} catch (e) {
|
||||
// URL constructor throws on invalid URLs (such as ones that only contain a fragment), so swallow those exceptions
|
||||
}
|
||||
}
|
||||
|
||||
return defaultRenderer(tokens, index, options, env, self);
|
||||
};
|
||||
|
||||
export function render(text: string): string {
|
||||
return md.render(text);
|
||||
}
|
||||
|
|
|
@ -110,7 +110,7 @@ article {
|
|||
// Markdown decorations
|
||||
@media (min-width: 768px) {
|
||||
a::before { content: "["; }
|
||||
a::after { content: "](" attr(href) ")"; word-wrap: break-word; }
|
||||
a::after { content: "](" attr(data-link) ")"; word-wrap: break-word; }
|
||||
a::before, a::after {
|
||||
color: var(--secondary-ui-text-color);
|
||||
font-family: $monospace;
|
||||
|
|
Loading…
Reference in New Issue