diff --git a/src/components/Markdown.svelte b/src/components/Markdown.svelte index b55054107..35bfb0692 100644 --- a/src/components/Markdown.svelte +++ b/src/components/Markdown.svelte @@ -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 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")); diff --git a/src/lib/markdown.ts b/src/lib/markdown.ts index f5ea35756..918c7361a 100644 --- a/src/lib/markdown.ts +++ b/src/lib/markdown.ts @@ -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 = { )}`; return `
  • ${liContent}
  • `; }, + 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 `
    ${text}`; + } + return `${text}`; + }, }; export const markdownExtensions = [