Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Render aligned Mermaid blocks with automatic widths https://github.com/siyuan-note/siyuan/issues/21020

Daniel9f0a4f10cd24
diff --git a/app/src/protyle/render/mermaidRender.test.ts b/app/src/protyle/render/mermaidRender.test.ts
index 197e8f082c..61cfd77ab0 100644
--- a/app/src/protyle/render/mermaidRender.test.ts
+++ b/app/src/protyle/render/mermaidRender.test.ts
@@ -22,7 +22,8 @@ test("Mermaid follows both theme directions and discards renders superseded by a
set innerHTML(_value: string) { this.lastElementChild = {}; },
};
const block = {
- firstElementChild: {clientWidth: 100, classList: {contains: () => true}, nextElementSibling: container},
+ firstElementChild: {classList: {contains: () => true}, nextElementSibling: container},
+ getClientRects: () => [{}],
getAttribute: (name: string) => attributes.get(name),
setAttribute: (name: string, value: string) => attributes.set(name, value),
removeAttribute: (name: string) => attributes.delete(name),
diff --git a/app/src/protyle/render/mermaidRender.ts b/app/src/protyle/render/mermaidRender.ts
index 7f72a7ec18..f05422f9de 100644
--- a/app/src/protyle/render/mermaidRender.ts
+++ b/app/src/protyle/render/mermaidRender.ts
@@ -92,7 +92,8 @@ export const mermaidRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>
const hideElements: Element[] = [];
const normalElements: Element[] = [];
mermaidElements.forEach(item => {
- if (item.firstElementChild.clientWidth === 0) {
+ // 可见的自动宽度块在图形生成前可能没有内容宽度,按布局盒判断是否隐藏。
+ if (item.getClientRects().length === 0) {
hideElements.push(item);
} else {
normalElements.push(item);
diff --git a/app/src/protyle/render/mermaidResize.test.ts b/app/src/protyle/render/mermaidResize.test.ts
index 06f1c6aae7..705e56688c 100644
--- a/app/src/protyle/render/mermaidResize.test.ts
+++ b/app/src/protyle/render/mermaidResize.test.ts
@@ -29,25 +29,31 @@ const browserCases = async (sources: Record<string, string>, resizeSource: strin
const api = {} as typeof import("./mermaidRender");
const image = {} as typeof import("./imageResize");
new Function("exports", sources.image)(image);
+ const closest = {} as typeof import("../util/hasClosest");
+ new Function("exports", sources.closest)(closest);
Object.assign(window, {siyuan: {config: {appearance: {mode: 0}}}, DOMPurify: {sanitize: (value: string) => value}});
new Function("exports", "require", sources.renderer)(api, () => ({
Constants: {PROTYLE_CDN: "", ZWSP: "\u200b"}, addScript: async () => {},
ensureBrowserCompatibility: async () => {},
isFoldedRenderContent: () => false, isZenumlDiagram: () => false,
getMermaidLayout: (): undefined => undefined, applyMermaidLayout: (value: string) => value,
- hasClosestByClassName: (element: Element, name: string) => element.closest("." + name),
+ ...closest,
genIconHTML: () => '<div class="protyle-icons"></div>', getHostCapabilities: () => ({remoteKernel: false}),
escapeHtml: (value: string) => value,
}));
const settle = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
- const render = async (element: Element) => {
- api.mermaidRender(element);
+ const waitForRender = async (element: Element) => {
+ await settle();
for (let count = 0; count < 100 && !element.querySelector("svg"); count++) {
await new Promise(resolve => setTimeout(resolve, 20));
}
check.ok(element.querySelector("svg"), element.outerHTML);
await settle();
};
+ const render = async (element: Element) => {
+ api.mermaidRender(element);
+ await waitForRender(element);
+ };
const create = async (alignment = "", width = "33%") => {
root.style.zoom = "";
root.innerHTML = lute.Md2BlockDOM("```mermaid\ngraph LR; A[First Mermaid diagram node]-->B[Second Mermaid diagram node];\n```");
@@ -59,6 +65,44 @@ const browserCases = async (sources: Record<string, string>, resizeSource: strin
check.equal(block.querySelectorAll(":scope > .protyle-block-resize").length, 1);
return block;
};
+ for (const alignment of ["", "left", "center", "right"]) {
+ const block = await create(alignment, "");
+ check.equal(block.style.width, "", "automatic widths render without persisting a width");
+ check.ok(block.querySelector("svg").getBoundingClientRect().width > 0);
+ const before = lute.BlockDOM2Md(block.outerHTML);
+ window.siyuan.config.appearance.mode = 1;
+ api.refreshMermaidTheme(block);
+ await waitForRender(block);
+ check.equal(lute.BlockDOM2Md(block.outerHTML), before, "theme changes preserve automatic widths and alignment");
+ window.siyuan.config.appearance.mode = 0;
+ root.innerHTML = lute.Md2BlockDOM(before);
+ await render(root.firstElementChild);
+ check.equal(lute.BlockDOM2Md(root.innerHTML), before, "automatic widths render again after reopening");
+ }
+ const hiddenDiagram = lute.Md2BlockDOM("```mermaid\ngraph TD; A-->B;\n```");
+ root.innerHTML = '<div class="bq" data-node-id="folded" data-type="NodeBlockquote" fold="1">' +
+ '<div data-node-id="summary">Summary</div>' + hiddenDiagram + "</div>";
+ const foldedDiagram = root.querySelector('[data-subtype="mermaid"]');
+ check.equal(foldedDiagram.getClientRects().length, 0);
+ api.mermaidRender(foldedDiagram);
+ await settle();
+ check.equal(foldedDiagram.hasAttribute("data-render"), false, "folded diagrams wait for expansion");
+ root.firstElementChild.removeAttribute("fold");
+ await waitForRender(foldedDiagram);
+ const card = document.createElement("div");
+ card.className = "card__block card__block--hideh";
+ document.body.appendChild(card);
+ card.appendChild(root);
+ root.innerHTML = '<div data-node-id="heading" data-type="NodeHeading" custom-riff-decks="deck">Question</div>' + hiddenDiagram;
+ const cardDiagram = root.querySelector('[data-subtype="mermaid"]');
+ check.equal(cardDiagram.getClientRects().length, 0);
+ api.mermaidRender(cardDiagram);
+ await settle();
+ check.equal(cardDiagram.hasAttribute("data-render"), false, "flashcard answers wait until revealed");
+ card.classList.remove("card__block--hideh");
+ await waitForRender(cardDiagram);
+ document.body.appendChild(root);
+ card.remove();
const updates: {before: string, after: string}[] = [];
const start = new Function("getImageResizeWidth", "protyle", "target", "nodeElement", "event", "documentSelf",
"mostRight", "mostBottom", "y", "focusBlock", "updateTransaction", "img3115", resizeSource);
@@ -189,7 +233,7 @@ const browserCases = async (sources: Record<string, string>, resizeSource: strin
return "Mermaid resize cases passed";
};
-test("Mermaid width handles support alignment, replay, zoom and touch without changing diagram source", {
+test("Mermaid automatic widths and width handles support alignment, visibility, replay, zoom and touch", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
timeout: 60000,
}, async () => {
@@ -210,11 +254,12 @@ test("Mermaid width handles support alignment, replay, zoom and touch without ch
.outputText + "\nreturn resize.call(this);";
const sources = {
renderer: compile("src/protyle/render/mermaidRender.ts"), image: compile("src/protyle/render/imageResize.ts"),
+ closest: compile("src/protyle/util/hasClosest.ts"),
lute: readFileSync("stage/protyle/js/lute/lute.min.js", "utf8"),
mermaid: readFileSync("stage/protyle/js/mermaid/mermaid.min.js", "utf8"),
bridge: compile("src/util/touchDragBridge.ts"), core: compile("src/util/touchDragBridgeCore.ts"),
};
- const css = compileString('@use "protyle/protyle"; @use "component/typography";',
+ const css = compileString('@use "util/function"; @use "protyle/protyle"; @use "component/typography"; @use "business/card";',
{loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;
const mobileCSS = compileString('@use "main/mobile";',
{loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;