An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Refresh Mermaid diagrams when switching themes https://github.com/siyuan-note/siyuan/issues/19995
Daniel9de50899456c
diff --git a/app/src/protyle/render/mermaidRender.test.ts b/app/src/protyle/render/mermaidRender.test.tsnew file mode 100644index 0000000000..da9d25440d--- /dev/null+++ b/app/src/protyle/render/mermaidRender.test.ts@@ -0,0 +1,73 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {readFileSync} from "node:fs";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const compiled = transpileModule(readFileSync("src/protyle/render/mermaidRender.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++test("Mermaid follows both theme directions and discards renders superseded by a theme change", async () => {+ const attributes = new Map([["data-subtype", "mermaid"], ["data-content", "graph TD; A-->B"]]);+ const renders: Array<{theme: string, resolve: (value: {svg: string}) => void}> = [];+ let theme = "";+ let counter = 0;+ const container = {+ lastElementChild: undefined as {innerHTML?: string},+ set innerHTML(_value: string) { this.lastElementChild = {}; },+ };+ const block = {+ firstElementChild: {clientWidth: 100, classList: {contains: () => true}, nextElementSibling: container},+ getAttribute: (name: string) => attributes.get(name),+ setAttribute: (name: string, value: string) => attributes.set(name, value),+ removeAttribute: (name: string) => attributes.delete(name),+ querySelectorAll: (): Element[] => [],+ matches: () => true,+ };+ const config = {appearance: {mode: 0}};+ const api = {} as {mermaidRender: (element: unknown) => void, refreshMermaidTheme: (element: unknown) => void};+ runInNewContext(compiled, {+ exports: api,+ require: () => ({+ Constants: {PROTYLE_CDN: "", ZWSP: ""}, addScript: async () => {},+ isFoldedRenderContent: () => false, isZenumlDiagram: () => false,+ getMermaidLayout: () => "", applyMermaidLayout: (value: string) => value,+ hasClosestByClassName: (): Element => null, getHostCapabilities: () => ({remoteKernel: false}),+ }),+ Lute: {NewNodeID: () => String(++counter), UnEscapeHTMLStr: (value: string) => value},+ window: {siyuan: {config}, DOMPurify: {sanitize: (value: string) => value}, mermaid: {+ registerIconPacks() {}, initialize: (value: {theme: string}) => { theme = value.theme; },+ render: () => new Promise(resolve => renders.push({theme, resolve})),+ }},+ });+ const flush = async () => { for (let i = 0; i < 8; i++) { await Promise.resolve(); } };+ api.mermaidRender(block);+ await flush();+ assert.equal(renders[0].theme, "default");+ config.appearance.mode = 1;+ api.refreshMermaidTheme(block);+ await flush();+ assert.equal(renders[1].theme, "dark");+ renders[1].resolve({svg: "dark diagram"});+ await flush();+ assert.equal(container.lastElementChild.innerHTML, "dark diagram");+ renders[0].resolve({svg: "stale light diagram"});+ await flush();+ assert.equal(container.lastElementChild.innerHTML, "dark diagram");+ config.appearance.mode = 0;+ api.refreshMermaidTheme(block);+ await flush();+ assert.equal(renders[2].theme, "default");+ renders[2].resolve({svg: "light diagram"});+ await flush();+ assert.equal(container.lastElementChild.innerHTML, "light diagram");+ const body = {getAttribute: (): string => null, matches: () => false, querySelectorAll: () => [block]};+ config.appearance.mode = 1;+ api.refreshMermaidTheme(body);+ await flush();+ assert.equal(renders[3].theme, "dark");+ renders[3].resolve({svg: "dark body diagram"});+ await flush();+ assert.equal(container.lastElementChild.innerHTML, "dark body diagram");+});diff --git a/app/src/protyle/render/mermaidRender.ts b/app/src/protyle/render/mermaidRender.tsindex b119bd4fad..c5c6391050 100644--- a/app/src/protyle/render/mermaidRender.ts+++ b/app/src/protyle/render/mermaidRender.ts@@ -64,6 +64,7 @@ export const mermaidRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>},]);const config: any = {+ theme: window.siyuan.config.appearance.mode === 1 ? "dark" : "default",// 升级后无 https://github.com/siyuan-note/siyuan/issues/3587,可使用 loosesecurityLevel: getHostCapabilities().remoteKernel ? "strict" : "loose",altFontFamily: "sans-serif",@@ -85,9 +86,6 @@ export const mermaidRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>rightPadding: 20}};- if (window.siyuan.config.appearance.mode === 1) {- config.theme = "dark";- }window.mermaid.initialize(config);const hideElements: Element[] = [];const normalElements: Element[] = [];@@ -119,7 +117,19 @@ export const mermaidRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>});};+export const refreshMermaidTheme = (element: Element) => {+ const elements = element.matches('[data-subtype="mermaid"]') ? [element] :+ element.querySelectorAll('[data-subtype="mermaid"]');+ elements.forEach(item => {+ item.removeAttribute("data-render");+ });+ mermaidRender(element);+};+const initMermaid = (mermaidElements: Element[]) => {+ if (!mermaidElements.length) {+ return;+ }const wysiswgElement = hasClosestByClassName(mermaidElements[0], "protyle-wysiwyg", true);mermaidElements.forEach(async (item: HTMLElement) => {if (item.getAttribute("data-render") === "true") {@@ -135,17 +145,25 @@ const initMermaid = (mermaidElements: Element[]) => {return;}const id = "mermaid" + Lute.NewNodeID();+ let diagramElement: Element;try {renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"><span id="${id}"></span></div>`;+ diagramElement = renderElement.lastElementChild;const content = applyMermaidLayout(Lute.UnEscapeHTMLStr(item.getAttribute("data-content")),getMermaidLayout(item.getAttribute(MERMAID_LAYOUT_ATTR)));const mermaidData = await window.mermaid.render(id, content);+ if (renderElement.lastElementChild !== diagramElement) {+ return;+ }let svg = mermaidData.svg.replace(/(href|src|xlink:href)\s*=\s*["']\\\\/gi, (match, p1) => `${p1}="about:blank"`);svg = window.DOMPurify.sanitize(svg, MERMAID_SANITIZE_OPTIONS);- renderElement.lastElementChild.innerHTML = svg;+ diagramElement.innerHTML = svg;} catch (e) {+ if (renderElement.lastElementChild !== diagramElement) {+ return;+ }const errorElement = document.querySelector("#" + id);const errorDiagram = errorElement ?window.DOMPurify.sanitize(errorElement.outerHTML, MERMAID_SANITIZE_OPTIONS) : "";diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex 2b0f5d3199..b1a68bfe65 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -20,6 +20,7 @@ import {isWin11} from "../protyle/util/compatibility";import {setCodeTheme} from "../protyle/render/util";+import {refreshMermaidTheme} from "../protyle/render/mermaidRender";import {getBackend, getFrontend} from "./functions";import {getWorkspaceName} from "./processTitle";import {ensureSelectedCustomFonts, getExportCustomFontStyle} from "./customFont";@@ -163,6 +164,7 @@ export const loadAssets = async (appearance: Config.IAppearance) => {}if (previousThemeMode && previousThemeMode !== themeMode) {refreshChartTheme(document.body);+ refreshMermaidTheme(document.body);}const defaultStyleElement = document.getElementById("themeDefaultStyle");const defaultThemeAddress = `/appearance/themes/${data.mode === 1 ? "midnight" : "daylight"}/theme.css?v=${Constants.SIYUAN_VERSION}`;