Skip to content

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

:sparkles: Improve Mermaid block resizing and alignment https://github.com/siyuan-note/siyuan/issues/20684

Daniel93f3d5ea8e97
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
index 914c969158..28deda225a 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
@@ -8,7 +8,7 @@
"title": "Formatting elements",
"title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;",
"type": "doc",
- "updated": "20261018210230"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4608,7 +4608,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104091509-oihpzcz",
- "updated": "20210415200955"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4617,6 +4617,38 @@
}
]
},
+ {
+ "ID": "20261018213321-j5qp01p",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261018213321-j5qp01p",
+ "updated": "20261018213321"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Drag the handle on the right edge of a Mermaid block to adjust its width. After reducing the width, choose "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Layout"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Center"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " from the block menu to center the block."
+ }
+ ]
+ },
{
"ID": "20210104091509-viqif92",
"Type": "NodeCodeBlock",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
index f695f6f77c..ac5043e718 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
@@ -8,7 +8,7 @@
"title": "排版元素",
"title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);",
"type": "doc",
- "updated": "20261018210230"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4603,7 +4603,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104091228-2nz4ows",
- "updated": "20210604223148"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4612,6 +4612,38 @@
}
]
},
+ {
+ "ID": "20261018213321-q522rrs",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261018213321-q522rrs",
+ "updated": "20261018213321"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "可拖动 Mermaid 块右侧的手柄调整宽度。缩小后,在块菜单中选择 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "居中"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 将块居中显示。"
+ }
+ ]
+ },
{
"ID": "20210104091228-ez3uzqu",
"Type": "NodeCodeBlock",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
index 71cd549c94..0749b945f6 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
@@ -8,7 +8,7 @@
"title": "排版元素",
"title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);",
"type": "doc",
- "updated": "20261018210230"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4602,7 +4602,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122008-l775ci5",
- "updated": "20211226122008"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4611,6 +4611,38 @@
}
]
},
+ {
+ "ID": "20261018213321-x7k2w2a",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261018213321-x7k2w2a",
+ "updated": "20261018213321"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "可拖曳 Mermaid 區塊右側的控制柄調整寬度。縮小後,在區塊選單中選擇 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "佈局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "置中"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 將區塊置中顯示。"
+ }
+ ]
+ },
{
"ID": "20211226122008-0thor8h",
"Type": "NodeCodeBlock",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
index 0364ee2a69..40595a3784 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
@@ -9,7 +9,7 @@
"title": "書式要素",
"title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;",
"type": "doc",
- "updated": "20261018210230"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4770,7 +4770,7 @@
"Properties": {
"ID": "20240530101000-lbctees",
"id": "20240530101000-9x9ue7u",
- "updated": "20240530101000"
+ "updated": "20261018213321"
},
"Children": [
{
@@ -4779,6 +4779,38 @@
}
]
},
+ {
+ "ID": "20261018213321-ho943st",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261018213321-ho943st",
+ "updated": "20261018213321"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Mermaid ブロックの右端にあるハンドルをドラッグすると、幅を調整できます。幅を狭めた後、ブロックメニューの "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "レイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "中央揃え"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を選択すると、ブロックを中央に配置できます。"
+ }
+ ]
+ },
{
"ID": "20240530101000-0nu0sip",
"Type": "NodeCodeBlock",
diff --git a/app/src/assets/scss/component/_typography.scss b/app/src/assets/scss/component/_typography.scss
index c7db47bcb1..15b3d315bd 100644
--- a/app/src/assets/scss/component/_typography.scss
+++ b/app/src/assets/scss/component/_typography.scss
@@ -620,6 +620,17 @@
text-align: center;
}
+ [data-subtype="mermaid"] {
+ &[style*="text-align: center"] {
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ &[style*="text-align: right"] {
+ margin-left: auto;
+ }
+ }
+
[data-type="NodeIFrame"] {
height: 256px;
}
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scss
index 9d5f0b293a..cf08f19f95 100644
--- a/app/src/assets/scss/protyle/_wysiwyg.scss
+++ b/app/src/assets/scss/protyle/_wysiwyg.scss
@@ -964,10 +964,16 @@ body[data-format-painter] .protyle-wysiwyg[data-readonly="false"] {
cursor: text;
}
-.protyle-wysiwyg[data-readonly="true"] .iframe .protyle-block-resize {
+.protyle-wysiwyg[data-readonly="true"] .iframe .protyle-block-resize,
+.protyle-wysiwyg[data-readonly="true"] [data-subtype="mermaid"] > .protyle-block-resize,
+.protyle-wysiwyg .sb > [data-subtype="mermaid"] > .protyle-block-resize {
display: none;
}
+.protyle-wysiwyg [data-subtype="mermaid"]:hover > .protyle-block-resize {
+ opacity: 1;
+}
+
.protyle-wysiwyg[data-readonly="true"] .protyle-image-resize,
.protyle-wysiwyg__embed .protyle-image-resize,
.mindmap-view__preview-block .protyle-image-resize {
diff --git a/app/src/protyle/render/mermaidRender.ts b/app/src/protyle/render/mermaidRender.ts
index 94285fdeb9..5dbaf9f8a6 100644
--- a/app/src/protyle/render/mermaidRender.ts
+++ b/app/src/protyle/render/mermaidRender.ts
@@ -164,6 +164,15 @@ const initMermaid = (mermaidElements: Element[]) => {
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);
diagramElement.innerHTML = svg;
+ if (wysiswgElement && !item.closest(".protyle-wysiwyg__embed, .mindmap-view__preview-block") &&
+ !item.querySelector(":scope > .protyle-action__drag")) {
+ const handle = item.ownerDocument.createElement("span");
+ handle.className = "protyle-action__drag protyle-block-resize";
+ handle.contentEditable = "false";
+ handle.dataset.resizeAxis = "width";
+ handle.setAttribute("data-prevent-swipe", "true");
+ renderElement.insertAdjacentElement("afterend", handle);
+ }
} catch (e) {
if (renderElement.lastElementChild !== diagramElement) {
return;
diff --git a/app/src/protyle/render/mermaidResize.test.ts b/app/src/protyle/render/mermaidResize.test.ts
new file mode 100644
index 0000000000..e142a213f8
--- /dev/null
+++ b/app/src/protyle/render/mermaidResize.test.ts
@@ -0,0 +1,251 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {compileString} from "sass";
+import {createSourceFile, isIfStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (sources: Record<string, string>, resizeSource: string, css: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ new Function(sources.lute)();
+ const lute = Lute.New();
+ const script = document.createElement("script");
+ script.textContent = sources.mermaid;
+ document.head.appendChild(script);
+ const style = document.createElement("style");
+ style.textContent = css + `
+ body { margin: 24px; }
+ :root { --b3-theme-on-surface-light: #888; --b3-theme-on-surface: #555; --b3-theme-primary: #4285f4; }
+ .protyle-wysiwyg { width: min(600px, calc(100vw - 48px)); font-size: 24px; }
+ `;
+ document.head.appendChild(style);
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ root.dataset.readonly = "false";
+ document.body.appendChild(root);
+ const api = {} as typeof import("./mermaidRender");
+ const image = {} as typeof import("./imageResize");
+ new Function("exports", sources.image)(image);
+ 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 () => {},
+ isFoldedRenderContent: () => false, isZenumlDiagram: () => false,
+ getMermaidLayout: (): undefined => undefined, applyMermaidLayout: (value: string) => value,
+ hasClosestByClassName: (element: Element, name: string) => element.closest("." + name),
+ 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);
+ 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 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```");
+ const block = root.firstElementChild as HTMLElement;
+ check.equal(block.dataset.subtype, "mermaid");
+ block.style.width = width;
+ block.style.textAlign = alignment;
+ await render(block);
+ check.equal(block.querySelectorAll(":scope > .protyle-block-resize").length, 1);
+ return block;
+ };
+ const updates: {before: string, after: string}[] = [];
+ const start = new Function("getImageResizeWidth", "protyle", "target", "nodeElement", "event", "documentSelf",
+ "mostRight", "mostBottom", "y", "focusBlock", "updateTransaction", "img3115", resizeSource);
+ const begin = (block: HTMLElement, event: MouseEvent, disabled = false) => {
+ updates.length = 0;
+ start(image.getImageResizeWidth, {disabled}, block.querySelector(":scope > .protyle-block-resize"), block,
+ event, document, root.getBoundingClientRect().right, 1000, event.clientY, () => {},
+ (_owner: unknown, node: HTMLElement, old: string) => updates.push({before: old, after: node.outerHTML}), () => {});
+ };
+ for (const alignment of ["", "left", "center", "right"]) {
+ const block = await create(alignment);
+ const rect = block.getBoundingClientRect();
+ const parentRect = root.getBoundingClientRect();
+ const parentStyle = getComputedStyle(root);
+ const left = parentRect.left + parseFloat(parentStyle.paddingLeft);
+ const right = parentRect.right - parseFloat(parentStyle.paddingRight);
+ if (alignment === "center") {
+ check.ok(Math.abs(rect.left + rect.right - left - right) < 1, "33% blocks center");
+ } else if (alignment === "right") {
+ check.ok(Math.abs(rect.right - right) < 1, "33% blocks align right");
+ } else {
+ check.equal(rect.left, left);
+ }
+ const handle = block.querySelector<HTMLElement>(":scope > .protyle-block-resize");
+ const handleRect = handle.getBoundingClientRect();
+ check.equal(document.elementFromPoint(handleRect.left + handleRect.width / 2,
+ handleRect.top + handleRect.height / 2), handle,
+ JSON.stringify({alignment, rect: rect.toJSON(), handle: handleRect.toJSON(),
+ parent: parentRect.toJSON(), width: innerWidth}));
+ const width = parseFloat(getComputedStyle(block).width);
+ const svgWidth = block.querySelector("svg").getBoundingClientRect().width;
+ const before = lute.BlockDOM2Md(block.outerHTML);
+ check.doesNotMatch(before, /protyle-block-resize|data-resize-axis/);
+ begin(block, new MouseEvent("mousedown", {clientX: handleRect.left, clientY: handleRect.top}));
+ document.onmousemove(new MouseEvent("mousemove", {clientX: handleRect.left - 20, clientY: handleRect.top + 50}));
+ document.onmouseup(new MouseEvent("mouseup"));
+ const expected = width - (alignment === "center" ? 40 : 20);
+ check.ok(Math.abs(parseFloat(block.style.width) - expected) < 0.1,
+ JSON.stringify({alignment, initial: width, expected, actual: block.style.width, viewport: innerWidth}));
+ check.equal(block.style.height, "", "width dragging preserves the SVG aspect ratio");
+ check.ok(block.querySelector("svg").getBoundingClientRect().width < svgWidth, "the diagram shrinks with the block");
+ check.equal(updates.length, 1);
+ check.equal(lute.BlockDOM2Md(updates[0].before), before);
+ const after = lute.BlockDOM2Md(block.outerHTML);
+ root.innerHTML = lute.Md2BlockDOM(before);
+ await render(root.firstElementChild);
+ check.equal(lute.BlockDOM2Md(root.innerHTML), before, "undo retains percentage widths and alignment");
+ root.innerHTML = lute.Md2BlockDOM(after);
+ await render(root.firstElementChild);
+ check.equal(lute.BlockDOM2Md(root.innerHTML), after, "redo retains the resized width");
+ api.refreshMermaidTheme(root);
+ await render(root.firstElementChild);
+ check.equal(root.querySelectorAll(".protyle-block-resize").length, 1, "theme rendering does not duplicate handles");
+ }
+ const zoomed = await create("center", "160px");
+ root.style.zoom = "1.5";
+ begin(zoomed, new MouseEvent("mousedown", {clientX: 300}));
+ document.onmousemove(new MouseEvent("mousemove", {clientX: 315}));
+ document.onmouseup(new MouseEvent("mouseup"));
+ check.equal(zoomed.style.width, "180px", "dragging accounts for editor zoom and centered placement");
+ const bounded = await create("left", "100%");
+ begin(bounded, new MouseEvent("mousedown", {clientX: 300}));
+ document.onmousemove(new MouseEvent("mousemove", {clientX: 3000}));
+ document.onmouseup(new MouseEvent("mouseup"));
+ check.ok(bounded.getBoundingClientRect().right <= root.getBoundingClientRect().right + 1, "width stays inside the editor");
+ begin(bounded, new MouseEvent("mousedown", {clientX: 300}));
+ document.onmousemove(new MouseEvent("mousemove", {clientX: -3000}));
+ document.onmouseup(new MouseEvent("mouseup"));
+ check.equal(bounded.style.width, "17px");
+ const borderBox = await create("left", "160px");
+ borderBox.style.boxSizing = "border-box";
+ borderBox.style.border = "1px solid";
+ begin(borderBox, new MouseEvent("mousedown", {clientX: 300}));
+ document.onmousemove(new MouseEvent("mousemove", {clientX: 320}));
+ document.onmouseup(new MouseEvent("mouseup"));
+ check.equal(borderBox.style.width, "180px", "theme box sizing preserves drag distances");
+ const touchBlock = await create("center", "160px");
+ const core = {};
+ const bridge = {} as {initTouchDragBridge: () => void};
+ new Function("exports", sources.core)(core);
+ new Function("exports", "require", sources.bridge)(bridge, (id: string) => id === "./touchDragBridgeCore" ? core : {
+ Constants: {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 460, TIMEOUT_MOUSE_DRAG_DELAY: 150},
+ isInAndroid: () => false, isInHarmony: () => false, isMobile: () => false,
+ ipcRenderer: {on() {}}, stopScrollAnimation() {},
+ });
+ bridge.initTouchDragBridge();
+ const handle = touchBlock.querySelector<HTMLElement>(":scope > .protyle-block-resize");
+ handle.addEventListener("mousedown", event => begin(touchBlock, event));
+ const touchRect = handle.getBoundingClientRect();
+ for (const type of ["touchstart", "touchmove", "touchend"]) {
+ const touch = new Touch({identifier: 1, target: handle, radiusX: 1, radiusY: 1,
+ clientX: touchRect.left + touchRect.width / 2 - (type === "touchstart" ? 0 : 20),
+ clientY: touchRect.top + touchRect.height / 2});
+ handle.dispatchEvent(new TouchEvent(type, {bubbles: true, cancelable: true,
+ touches: type === "touchend" ? [] : [touch], changedTouches: [touch]}));
+ }
+ check.equal(touchBlock.style.width, "120px", "touch resizing shares the desktop width and alignment behavior");
+ check.equal(updates.length, 1);
+ check.equal(document.onmousemove, null);
+ root.dataset.readonly = "true";
+ check.equal(getComputedStyle(handle).display, "none");
+ begin(touchBlock, new MouseEvent("mousedown"), true);
+ check.equal(document.onmousemove, null, "read-only content cannot start resizing");
+ root.dataset.readonly = "false";
+ const sb = document.createElement("div");
+ sb.className = "sb";
+ root.appendChild(sb);
+ sb.appendChild(touchBlock);
+ check.equal(getComputedStyle(handle).display, "none", "columns retain their own width controls");
+ begin(touchBlock, new MouseEvent("mousedown"));
+ check.equal(document.onmousemove, null);
+ for (const className of ["protyle-wysiwyg__embed", "mindmap-view__preview-block", "b3-typography"]) {
+ const preview = document.createElement("div");
+ preview.className = className;
+ preview.innerHTML = lute.Md2BlockDOM("```mermaid\ngraph TD; A-->B;\n```");
+ const previewBlock = preview.firstElementChild as HTMLElement;
+ previewBlock.style.width = "33%";
+ previewBlock.style.textAlign = "center";
+ (className === "b3-typography" ? document.body : root).appendChild(preview);
+ await render(preview);
+ check.equal(preview.querySelector(".protyle-block-resize"), null, "previews do not expose editing controls");
+ const previewRect = preview.getBoundingClientRect();
+ const blockRect = previewBlock.getBoundingClientRect();
+ check.ok(Math.abs(blockRect.left + blockRect.right - previewRect.left - previewRect.right) < 1,
+ "previews retain centered block placement");
+ preview.remove();
+ }
+ return "Mermaid resize cases passed";
+};
+
+test("Mermaid width handles support alignment, replay, zoom and touch without changing diagram source", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 60000,
+}, async () => {
+ const compile = (file: string) => transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const source = createSourceFile("index.ts", readFileSync("src/protyle/wysiwyg/index.ts", "utf8"), ScriptTarget.ES2021, true);
+ let resize = "";
+ const visit = (node: import("typescript").Node) => {
+ if (isIfStatement(node) && node.expression.getText(source) === '!protyle.disabled && target.classList.contains("protyle-action__drag")') {
+ resize = node.getText(source);
+ }
+ node.forEachChild(visit);
+ };
+ visit(source);
+ assert.ok(resize);
+ const resizeSource = transpileModule(`function resize() { ${resize} }`, {compilerOptions: {target: ScriptTarget.ES2021}})
+ .outputText + "\nreturn resize.call(this);";
+ const sources = {
+ renderer: compile("src/protyle/render/mermaidRender.ts"), image: compile("src/protyle/render/imageResize.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";',
+ {loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;
+ const mobileCSS = compileString('@use "main/mobile";',
+ {loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;
+ const code = (styles: string) => "const __name = value => value; (" + browserCases.toString() + ")(" +
+ [sources, resizeSource, styles].map(value => JSON.stringify(value)).join(",") + ")";
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mermaid-resize-test-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, width: 900, height: 700,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ win.webContents.setBackgroundThrottling(false);
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code(css))}));
+ win.webContents.debugger.attach("1.3");
+ await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled: true});
+ win.setSize(390, 700);
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code(css + mobileCSS))}));
+ app.exit(0);
+ } catch (error) { console.error(error); app.exit(1); }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script], {env, windowsHide: true, timeout: 55000});
+ assert.match(result.stdout, /Mermaid resize cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) && path.basename(temporary).startsWith("siyuan-mermaid-resize-test-")) {
+ rmSync(temporary, {recursive: true, force: true, maxRetries: 20, retryDelay: 100});
+ }
+ }
+});
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 4f4df50160..4c4594835c 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -1989,15 +1989,21 @@ export class WYSIWYG {
};
return false;
}
- // 图片、iframe、video、挂件缩放
+ // 图片、iframe、video、挂件和 Mermaid 缩放。
if (!protyle.disabled && target.classList.contains("protyle-action__drag")) {
if (!nodeElement) {
return;
}
const html = nodeElement.outerHTML;
const isIFrame = ["NodeIFrame", "NodeWidget"].includes(nodeElement.dataset.type);
+ const isMermaid = nodeElement.dataset.subtype === "mermaid";
let isCenter = true;
- if ("NodeVideo" === nodeElement.dataset.type) {
+ if (isMermaid) {
+ if (nodeElement.parentElement.classList.contains("sb")) {
+ return;
+ }
+ isCenter = nodeElement.style.textAlign === "center";
+ } else if ("NodeVideo" === nodeElement.dataset.type) {
nodeElement.classList.add("iframe--drag");
if (["left", "right", ""].includes(nodeElement.style.textAlign)) {
isCenter = false;
@@ -2011,16 +2017,18 @@ export class WYSIWYG {
const x = event.clientX;
const imageFrame = target.closest(".protyle-image-resize");
- const dragElement = isIFrame ? nodeElement.querySelector<HTMLElement>(":scope > .iframe-content > iframe") :
+ const dragElement = isMermaid ? nodeElement :
+ isIFrame ? nodeElement.querySelector<HTMLElement>(":scope > .iframe-content > iframe") :
imageFrame ? imageFrame.parentElement.querySelector<HTMLImageElement>(":scope > img") :
target.previousElementSibling as HTMLElement;
if (!dragElement) {
nodeElement.classList.remove("iframe--drag");
return;
}
- const dragWidth = dragElement.clientWidth;
+ const mermaidStyle = isMermaid ? getComputedStyle(nodeElement) : null;
+ const dragWidth = isMermaid ? parseFloat(mermaidStyle.width) : dragElement.clientWidth;
const dragHeight = dragElement.clientHeight;
- const resizeAxis = isIFrame || dragElement.tagName === "IMG" ?
+ const resizeAxis = isMermaid ? "width" : isIFrame || dragElement.tagName === "IMG" ?
target.dataset.resizeAxis || (isIFrame ? "both" : "width") : "both";
if (target.classList.contains("protyle-block-resize")) {
target.classList.add("touch-resize-active");
@@ -2032,11 +2040,25 @@ export class WYSIWYG {
const imageMultiple = !imgElement.style.minWidth && nodeElement.style.textAlign !== "center" ? 1 : 2;
const imageMaxWidth = Math.max(17, (mostRight - imageRect.left -
(imageMultiple === 2 ? imageRect.width / 2 : 0)) * imageMultiple / imageScale);
+ const mermaidInsets = mermaidStyle?.boxSizing === "content-box" ?
+ parseFloat(mermaidStyle.paddingLeft) + parseFloat(mermaidStyle.paddingRight) +
+ parseFloat(mermaidStyle.borderLeftWidth) + parseFloat(mermaidStyle.borderRightWidth) : 0;
+ const mermaidScale = isMermaid ? imageRect.width / (dragWidth + mermaidInsets) || 1 : 1;
+ const mermaidParentStyle = isMermaid ? getComputedStyle(nodeElement.parentElement) : null;
+ const mermaidMaxWidth = isMermaid ? Math.max(17, nodeElement.parentElement.clientWidth -
+ parseFloat(mermaidParentStyle.paddingLeft) - parseFloat(mermaidParentStyle.paddingRight) -
+ mermaidInsets) : 0;
if (dragElement.tagName === "IMG") {
imgElement.classList.add("img--drag");
img3115(imgElement);
}
documentSelf.onmousemove = (moveEvent: MouseEvent) => {
+ if (isMermaid) {
+ nodeElement.style.width = getImageResizeWidth(dragWidth, dragHeight,
+ (moveEvent.clientX - x) / mermaidScale, 0, "width", isCenter ? 2 : 1, mermaidMaxWidth) + "px";
+ nodeElement.style.flex = "none";
+ return;
+ }
if (dragElement.tagName === "IMG") {
const image = dragElement as HTMLImageElement;
const height = image.naturalWidth && image.naturalHeight ?