Render theme of Mermaid diagram properly (#6307)

This commit is contained in:
Davy
2023-12-22 08:30:52 +08:00
committed by GitHub
parent 3ca8dc775d
commit 20d25a086a

View File

@@ -33,11 +33,14 @@ class Cache {
} }
} }
private static maxSize = 10; private static maxSize = 20;
private static data: Map<string, string> = new Map(); private static data: Map<string, string> = new Map();
} }
type RendererFunc = (block: { node: Node; pos: number }) => void; type RendererFunc = (
block: { node: Node; pos: number },
isDark: boolean
) => void;
class MermaidRenderer { class MermaidRenderer {
readonly diagramId: string; readonly diagramId: string;
@@ -53,11 +56,15 @@ class MermaidRenderer {
this.element.classList.add("mermaid-diagram-wrapper"); this.element.classList.add("mermaid-diagram-wrapper");
} }
renderImmediately = async (block: { node: Node; pos: number }) => { renderImmediately = async (
block: { node: Node; pos: number },
isDark: boolean
) => {
const element = this.element; const element = this.element;
const text = block.node.textContent; const text = block.node.textContent;
const cache = Cache.get(text); const cacheKey = `${isDark ? "dark" : "light"}-${text}`;
const cache = Cache.get(cacheKey);
if (cache) { if (cache) {
element.classList.remove("parse-error", "empty"); element.classList.remove("parse-error", "empty");
element.innerHTML = cache; element.innerHTML = cache;
@@ -66,13 +73,16 @@ class MermaidRenderer {
try { try {
const { default: mermaid } = await import("mermaid"); const { default: mermaid } = await import("mermaid");
mermaid.mermaidAPI.setConfig({
theme: isDark ? "dark" : "default",
});
mermaid.render( mermaid.render(
`mermaid-diagram-${this.diagramId}`, `mermaid-diagram-${this.diagramId}`,
text, text,
(svgCode, bindFunctions) => { (svgCode, bindFunctions) => {
this.currentTextContent = text; this.currentTextContent = text;
if (text) { if (text) {
Cache.set(text, svgCode); Cache.set(cacheKey, svgCode);
} }
element.classList.remove("parse-error", "empty"); element.classList.remove("parse-error", "empty");
element.innerHTML = svgCode; element.innerHTML = svgCode;
@@ -190,7 +200,7 @@ function getNewState({
const diagramDecoration = Decoration.widget( const diagramDecoration = Decoration.widget(
block.pos + block.node.nodeSize, block.pos + block.node.nodeSize,
() => { () => {
void renderer.render(block); void renderer.render(block, pluginState.isDark);
return renderer.element; return renderer.element;
}, },
{ {