Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: mermaid support #133

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 70 additions & 17 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export class Renderer extends Marked.Renderer {
allowMath: boolean;
baseUrl: string | undefined;
#slugger: GitHubSlugger;
mermaidImport: boolean = false;

constructor(options: Marked.MarkedOptions & RenderOptions = {}) {
super(options);
Expand Down Expand Up @@ -63,23 +64,41 @@ export class Renderer extends Marked.Renderer {
// a language of `ts, ignore` should really be `ts`
// and it should be lowercase to ensure it has parity with regular github markdown
language = language?.split(",")?.[0].toLocaleLowerCase();
const isMermaid = language === "mermaid";

// transform math code blocks into HTML+MathML
// https://github.blog/changelog/2022-06-28-fenced-block-syntax-for-mathematical-expressions/
if (language === "math" && this.allowMath) {
return katex.renderToString(code, { displayMode: true });
}
if (isMermaid) {
this.mermaidImport = true;
}
const grammar =
language && Object.hasOwnProperty.call(Prism.languages, language)
? Prism.languages[language]
: undefined;
if (grammar === undefined) {
if (isMermaid) {
return minify(`<div class="mermaid-container">
<pre><code class="notranslate">${code}</code></pre>
<div class="mermaid-code">${code}</div>
</div>`);
}
return `<pre><code class="notranslate">${he.encode(code)}</code></pre>`;
}
const html = Prism.highlight(code, grammar, language!);
const titleHtml = title
? `<div class="markdown-code-title">${title}</div>`
: ``;
if (isMermaid) {
return minify(`
<div class="mermaid-container">
<div class="highlight highlight-source-${language} notranslate">${titleHtml}<pre>${html}</pre></div>
<div class="mermaid-code">${code}</div>
</div>
`);
}
return `<div class="highlight highlight-source-${language} notranslate">${titleHtml}<pre>${html}</pre></div>`;
}

Expand All @@ -99,6 +118,10 @@ export class Renderer extends Marked.Renderer {
}
}

function minify(str: string): string {
return str.replace(/^\s+|\s+$|\n/gm, "");
}

const BLOCK_MATH_REGEXP = /\$\$\s(.+?)\s\$\$/g;
const INLINE_MATH_REGEXP = /\s\$((?=\S).*?(?=\S))\$/g;

Expand Down Expand Up @@ -169,8 +192,33 @@ export function render(markdown: string, opts: RenderOptions = {}): string {
: Marked.marked.parse(markdown, marked_opts)
) as string;

let additionalCode = "";
if (marked_opts.renderer.mermaidImport) {
additionalCode = minify(`
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs";
mermaid.initialize({ startOnLoad: false, theme: "neutral" });

const elements = document.querySelectorAll(".mermaid-container");
elements.forEach((element) => {
const code = element.querySelector(".mermaid-code")?.textContent || "";
if (code) {
element.innerHTML = \`<div class="mermaid">\${code}</div>\`;
}
});

await mermaid.run();
</script>
<style>
.mermaid-code {
display: none;
}
</style>
`);
}

if (opts.disableHtmlSanitization) {
return html;
return additionalCode + html;
}

let defaultAllowedTags = sanitizeHtml.defaults.allowedTags.concat([
Expand Down Expand Up @@ -243,6 +291,8 @@ export function render(markdown: string, opts: RenderOptions = {}): string {
"markdown-alert",
"markdown-alert-*",
"markdown-code-title",
"mermaid-code",
"mermaid-container",
],
span: [
"token",
Expand Down Expand Up @@ -334,22 +384,25 @@ export function render(markdown: string, opts: RenderOptions = {}): string {
],
};

return sanitizeHtml(html, {
transformTags: {
img: transformMedia,
video: transformMedia,
},
allowedTags: [...defaultAllowedTags, ...(opts.allowedTags ?? [])],
allowedAttributes: mergeAttributes(
defaultAllowedAttributes,
opts.allowedAttributes ?? {},
),
allowedClasses: { ...defaultAllowedClasses, ...opts.allowedClasses },
allowProtocolRelative: false,
parser: {
lowerCaseAttributeNames: false,
},
});
return (
additionalCode +
sanitizeHtml(html, {
transformTags: {
img: transformMedia,
video: transformMedia,
},
allowedTags: [...defaultAllowedTags, ...(opts.allowedTags ?? [])],
allowedAttributes: mergeAttributes(
defaultAllowedAttributes,
opts.allowedAttributes ?? {},
),
allowedClasses: { ...defaultAllowedClasses, ...opts.allowedClasses },
allowProtocolRelative: false,
parser: {
lowerCaseAttributeNames: false,
},
})
);
}

function mergeAttributes(
Expand Down
34 changes: 34 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,40 @@ Deno.test("code fence with a title", () => {
assertEquals(html, expected);
});

Deno.test("code containing mermaid", () => {
// test with two code blocks to see if the script and styles are not replicated
const markdown =
"```mermaid\ngraph TD;A-->B;A-->C;B-->D;C-->D;\n```\n\n```mermaid\ngraph TD;A-->B;A-->C;B-->D;C-->D;\n```";
const expected = `<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs";
mermaid.initialize({ startOnLoad: false, theme: "neutral" });
const elements = document.querySelectorAll(".mermaid-container");
elements.forEach((element) => {
const code = element.querySelector(".mermaid-code")?.textContent || "";
if (code) {
element.innerHTML = \`<div class="mermaid">\${code}</div>\`;
}
});
await mermaid.run();
</script>
<style>
.mermaid-code {
display: none;
}
</style>
<div class="mermaid-container"><pre><code>graph TD;A--&gt;B;A--&gt;C;B--&gt;D;C--&gt;D;</code></pre><div class="mermaid-code">graph TD;A--&gt;B;A--&gt;C;B--&gt;D;C--&gt;D;</div></div>
<div class="mermaid-container"><pre><code>graph TD;A--&gt;B;A--&gt;C;B--&gt;D;C--&gt;D;</code></pre><div class="mermaid-code">graph TD;A--&gt;B;A--&gt;C;B--&gt;D;C--&gt;D;</div></div>`;

const html = render(markdown);
assertEquals(
html,
expected
.split("\n")
.map((line) => line.trim())
.join(""),
);
});

Deno.test("link with title", () => {
const markdown = `[link](https://example.com "asdf")`;
const expected =
Expand Down