Skip to content

Commit

Permalink
[#69560] add url mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
Trzcin committed Nov 29, 2024
1 parent 9695957 commit 8b682f0
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
19 changes: 19 additions & 0 deletions src/hooks/markdownUrlMapping.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import markdownIt from "markdown-it";

const mappedAttrs = ["src", "href"];

const mapToken = (token, mapFunc) => {
for (const attrName of mappedAttrs) {
const attr = token.attrGet(attrName);
if (attr) token.attrSet(attrName, mapFunc(token.tag, attr));
}
};

export function markdownItMapUrls(/** @type {markdownIt} */ md) {
md.core.ruler.after("inline", "map_urls", (state) => {
for (const token of state.tokens) {
mapToken(token, state.env.mapUrl);
token.children?.forEach?.((c) => mapToken(c, state.env.mapUrl));
}
});
}
6 changes: 4 additions & 2 deletions src/hooks/useText.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { MystState } from "../mystState";
import { useComputed } from "@preact/signals";
import markdownCheckboxes from "markdown-it-checkbox";
import { colonFencedBlocks } from "./markdownFence";
import { markdownItMapUrls } from "./markdownUrlMapping";

const countOccurences = (str, pattern) => (str?.match(pattern) || []).length;

Expand Down Expand Up @@ -112,6 +113,7 @@ export const useText = ({ preview }) => {
.use(markdownSourceMap)
.use(checkLinks)
.use(colonFencedBlocks)
.use(markdownItMapUrls)
.use(markdownCheckboxes);

if (options.backslashLineBreak.value) md.use(backslashLineBreakPlugin);
Expand Down Expand Up @@ -187,14 +189,14 @@ export const useText = ({ preview }) => {

const html =
lookup[hash] ||
purify.sanitize(markdown.value.render(md, { chunkId, startLine, lineMap, view: editorView.value }), {
purify.sanitize(markdown.value.render(md, { chunkId, startLine, lineMap, view: editorView.value, mapUrl: options.mapUrl.value }), {
// Taken from Mermaid JS settings: https://github.com/mermaid-js/mermaid/blob/dd0304387e85fc57a9ebb666f89ef788c012c2c5/packages/mermaid/src/mermaidAPI.ts#L50
ADD_TAGS: ["foreignobject"],
ADD_ATTR: ["dominant-baseline"],
});
return { md, hash, id: chunkId, html };
}),
[markdown.value, options.id.value],
[markdown.value, options.id.value, options.mapUrl.value],
);

useEffect(() => readyToRender && updateHtmlChunks({ newMarkdown: text }), [readyToRender]);
Expand Down
1 change: 1 addition & 0 deletions src/mystState.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const defaults = {
parent: null,
syncScroll: false,
unfoldedHeadings: null,
mapUrl: (tag, url) => url,
};

export function createMystState(/** @type {typeof defaults} */ opts) {
Expand Down

0 comments on commit 8b682f0

Please sign in to comment.