2022-02-22 19:02:53 +08:00
|
|
|
import { md5Base64 } from "../../lib/utils";
|
|
|
|
import CacheLRU from "../../lib/cache_lru";
|
|
|
|
|
2022-01-17 05:04:24 +08:00
|
|
|
let idCount = 0;
|
|
|
|
let getId = () => `mermaid-graph-${idCount++}`;
|
|
|
|
|
|
|
|
let mermaidInitialized = false;
|
|
|
|
|
2022-01-23 02:36:00 +08:00
|
|
|
const fontAwesomeVersion = "5.15.4";
|
|
|
|
|
2022-02-22 19:02:53 +08:00
|
|
|
const cache = new CacheLRU(25);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Renders SVG graph from mermaid definition.
|
|
|
|
*/
|
|
|
|
export function renderMermaid(definition) {
|
|
|
|
const hash = md5Base64(definition);
|
|
|
|
const svg = cache.get(hash);
|
|
|
|
|
|
|
|
if (svg) {
|
|
|
|
return Promise.resolve(svg);
|
|
|
|
}
|
|
|
|
|
|
|
|
return importMermaid().then((mermaid) => {
|
|
|
|
injectFontAwesomeIfNeeded(definition);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const svg = mermaid.render(getId(), definition);
|
|
|
|
cache.set(hash, svg);
|
|
|
|
return svg;
|
|
|
|
} catch (e) {
|
|
|
|
return `<div class="error-box whitespace-pre-wrap"><span class="font-semibold">Mermaid</span>\n${e.message}</div>`;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-01-17 05:04:24 +08:00
|
|
|
function importMermaid() {
|
|
|
|
return import(
|
|
|
|
/* webpackChunkName: "mermaid" */
|
|
|
|
"mermaid"
|
|
|
|
).then(({ default: mermaid }) => {
|
|
|
|
if (!mermaidInitialized) {
|
|
|
|
mermaid.initialize({ startOnLoad: false });
|
|
|
|
mermaidInitialized = true;
|
|
|
|
}
|
|
|
|
return mermaid;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-02-22 19:02:53 +08:00
|
|
|
function injectFontAwesomeIfNeeded(definition) {
|
2022-01-23 02:36:00 +08:00
|
|
|
const fontAwesomeUrl = `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/${fontAwesomeVersion}/css/all.min.css`;
|
2022-02-22 19:02:53 +08:00
|
|
|
|
|
|
|
// Graphs may include Font Awesome icons via fa: prefix, so we
|
|
|
|
// load the icon set if needed
|
2022-01-23 02:36:00 +08:00
|
|
|
if (
|
2022-02-22 19:02:53 +08:00
|
|
|
definition.includes("fa:") &&
|
2022-01-23 02:36:00 +08:00
|
|
|
!document.querySelector(`link[href="${fontAwesomeUrl}"]`)
|
|
|
|
) {
|
|
|
|
const link = document.createElement("link");
|
|
|
|
link.rel = "stylesheet";
|
|
|
|
link.type = "text/css";
|
|
|
|
link.href = fontAwesomeUrl;
|
|
|
|
document.head.appendChild(link);
|
|
|
|
}
|
2022-01-17 05:04:24 +08:00
|
|
|
}
|