Fix relative markdown file links

Signed-off-by: Sebastian Martinez <me@sebastinez.dev>
This commit is contained in:
Sebastian Martinez
2023-04-14 17:05:42 +02:00
parent e5ec6e33fb
commit 534430b2ec
2 changed files with 30 additions and 1 deletions
+21 -1
View File
@@ -5,7 +5,8 @@
import { onMount } from "svelte";
import { toDom } from "hast-util-to-dom";
import { base } from "@app/lib/router";
import * as utils from "@app/lib/utils";
import { base, updateProjectRoute, activeRouteStore } from "@app/lib/router";
import { isUrl, twemoji, scrollIntoView, canonicalize } from "@app/lib/utils";
import { highlight } from "@app/lib/syntax";
import {
@@ -30,6 +31,20 @@
// eslint-disable-next-line @typescript-eslint/naming-convention
dompurify.sanitize(marked.parse(content), { SANITIZE_DOM: false });
function navigateToMarkdownLink(event: any) {
if (event.target.matches(".file-link")) {
event.preventDefault();
if ($activeRouteStore.resource === "projects") {
updateProjectRoute({
path: utils.canonicalize(
event.target.getAttribute("href"),
$activeRouteStore.params.path ?? "",
),
});
}
}
}
onMount(async () => {
// Don't underline <a> tags that contain images.
for (const e of container.querySelectorAll("a")) {
@@ -55,6 +70,11 @@
}
}
const fileAnchorTags = document.querySelectorAll(".file-link");
fileAnchorTags.forEach(anchorTag => {
anchorTag.addEventListener("click", navigateToMarkdownLink);
});
// Replaces code blocks in the background with highlighted code.
const prefix = "language-";
const nodes = Array.from(document.body.querySelectorAll("pre code"));
+9
View File
@@ -1,6 +1,7 @@
import emojis from "@app/lib/emojis";
import katex from "katex";
import { marked } from "marked";
import { isUrl } from "./utils";
const emojisMarkedExtension = {
name: "emoji",
@@ -136,6 +137,14 @@ export const renderer = {
)}</div>`;
return `<li>${liContent}</li>`;
},
link(href: string, _title: string, text: string) {
// If the link is not a URL nor starts with a #, we add the file-link class to it,
// so we're able to query it in the Markdown component.
if (!isUrl(href) && !href.startsWith("#")) {
return `<a href="${href}" class="file-link">${text}</a>`;
}
return `<a href="${href}">${text}</a>`;
},
};
export const markdownExtensions = [