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: Improve diagram PNG clipboard clarity https://github.com/siyuan-note/siyuan/issues/19376
Daniel7cf11febe4ff
diff --git a/app/src/menus/copyPNG.test.ts b/app/src/menus/copyPNG.test.tsnew file mode 100644index 0000000000..ebc78ccdb0--- /dev/null+++ b/app/src/menus/copyPNG.test.ts@@ -0,0 +1,59 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const source = readFileSync("src/menus/util.ts", "utf8");+const compiled = transpileModule(source.substring(source.indexOf("export const copyPNGByLink =")), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++for (const scenario of [+ {type: "image/svg+xml", width: 1200, height: 600, ratio: 1, expected: [2400, 1200]},+ {type: "image/svg+xml", width: 1200, height: 600, ratio: 3, expected: [3600, 1800]},+ {type: "image/svg+xml", width: 4096, height: 4096, ratio: 2, expected: [4096, 4096]},+ {type: "image/jpeg", width: 1200, height: 600, ratio: 2, expected: [1200, 600]},+ {type: "image/png", width: 1200, height: 600, ratio: 2, expected: undefined},+]) {+ test(`copy PNG resolution: ${JSON.stringify(scenario)}`, async () => {+ const original = new Blob(["source"], {type: scenario.type});+ const png = new Blob(["rendered"], {type: "image/png"});+ const draws: unknown[][] = [];+ const copied: Blob[] = [];+ const canvas = {+ width: 0,+ height: 0,+ getContext: () => ({drawImage: (...args: unknown[]) => draws.push(args)}),+ toBlob: (callback: (blob: Blob) => void) => callback(png),+ };+ const exports = {} as {copyPNGByLink: (link: string) => void};+ runInNewContext(compiled, {+ exports,+ isInAndroid: () => false,+ showMessage: () => {},+ writePNGBlob: async (blob: Blob) => { copied.push(blob); return true; },+ window: {devicePixelRatio: scenario.ratio, siyuan: {languages: {}}},+ fetch: async () => ({ok: true, blob: async () => original}),+ URL: {createObjectURL: () => "blob:test", revokeObjectURL: () => {}},+ document: {+ createElement: (tag: string) => tag === "canvas" ? canvas : {+ naturalWidth: scenario.width,+ naturalHeight: scenario.height,+ onload: () => {},+ set src(value: string) { this.onload(); },+ },+ },+ });+ exports.copyPNGByLink("blob:diagram");+ await new Promise(resolve => setImmediate(resolve));+ if (scenario.expected) {+ assert.deepEqual([canvas.width, canvas.height], scenario.expected);+ assert.deepEqual(draws[0].slice(1), [0, 0, ...scenario.expected]);+ assert.deepEqual(copied, [png]);+ } else {+ assert.equal(draws.length, 0);+ assert.deepEqual(copied, [original]);+ }+ });+}diff --git a/app/src/menus/util.ts b/app/src/menus/util.tsindex 3d69f09c65..75df173780 100644--- a/app/src/menus/util.ts+++ b/app/src/menus/util.ts@@ -246,12 +246,16 @@ export const copyPNGByLink = (link: string) => {showMessage(window.siyuan.languages.copied);}};- const imageToPNGClipboard = (image: HTMLImageElement) => {+ const imageToPNGClipboard = (image: HTMLImageElement, vector = false) => {try {const canvas = document.createElement("canvas");- canvas.width = image.naturalWidth;- canvas.height = image.naturalHeight;- canvas.getContext("2d").drawImage(image, 0, 0);+ // 矢量图片以至少两倍分辨率采样,限制额外放大的画布尺寸和像素总量。+ const scale = vector ? Math.max(1, Math.min(Math.max(2, window.devicePixelRatio || 1),+ 16384 / image.naturalWidth, 16384 / image.naturalHeight,+ Math.sqrt(16777216 / (image.naturalWidth * image.naturalHeight)))) : 1;+ canvas.width = Math.round(image.naturalWidth * scale);+ canvas.height = Math.round(image.naturalHeight * scale);+ canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);canvas.toBlob((blob) => {if (blob) {copyBlob(blob);@@ -274,7 +278,7 @@ export const copyPNGByLink = (link: string) => {const objectURL = URL.createObjectURL(blob);const tempElement = document.createElement("img");tempElement.onload = () => {- imageToPNGClipboard(tempElement);+ imageToPNGClipboard(tempElement, blob.type.split(";")[0].trim().toLowerCase() === "image/svg+xml");URL.revokeObjectURL(objectURL);};tempElement.onerror = () => {diff --git a/app/src/protyle/preview/diagram.test.ts b/app/src/protyle/preview/diagram.test.tsnew file mode 100644index 0000000000..1b473d8fba--- /dev/null+++ b/app/src/protyle/preview/diagram.test.ts@@ -0,0 +1,56 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const compiled = transpileModule(readFileSync("src/protyle/preview/diagram.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++for (const scenario of [+ {viewBox: {width: 2400, height: 1200}, expected: [2400, 1200]},+ {viewBox: {width: 300, height: 150}, expected: [600, 300]},+ {viewBox: {width: 0, height: 0}, expected: [600, 300]},+]) {+ test(`diagram preview preserves intrinsic dimensions: ${JSON.stringify(scenario.viewBox)}`, async () => {+ const attributes = new Map<string, string>();+ const clone = {+ style: {} as Record<string, string>,+ querySelectorAll: (): Element[] => [],+ setAttribute: (name: string, value: string) => attributes.set(name, value),+ };+ const svg = {+ viewBox: {baseVal: scenario.viewBox},+ cloneNode: () => clone,+ querySelectorAll: (): Element[] => [],+ getBoundingClientRect: () => ({width: 600, height: 300}),+ };+ let previewBlob: Blob;+ let cleanup: () => void;+ const revoked: string[] = [];+ const exports = {} as {previewDiagram: (element: unknown) => Promise<void>};+ runInNewContext(compiled, {+ exports,+ require: () => ({+ Constants: {PROTYLE_CDN: ""},+ addScript: async () => {},+ previewImages: (urls: string[], current: string, onHidden: () => void) => { cleanup = onHidden; },+ }),+ window: {getComputedStyle: () => ({length: 0})},+ Blob,+ XMLSerializer: class { public serializeToString() { return "<svg/>"; } },+ URL: {+ createObjectURL: (blob: Blob) => { previewBlob = blob; return "blob:diagram"; },+ revokeObjectURL: (url: string) => revoked.push(url),+ },+ });+ await exports.previewDiagram({getAttribute: () => "mermaid", querySelector: () => svg});+ assert.deepEqual([Number(attributes.get("width")), Number(attributes.get("height"))], scenario.expected);+ assert.equal(clone.style.width, `${scenario.expected[0]}px`);+ assert.equal(clone.style.height, `${scenario.expected[1]}px`);+ assert.equal(previewBlob.type, "image/svg+xml");+ cleanup();+ assert.deepEqual(revoked, ["blob:diagram"]);+ });+}diff --git a/app/src/protyle/preview/diagram.ts b/app/src/protyle/preview/diagram.tsindex 12893b4ce7..8b030e2818 100644--- a/app/src/protyle/preview/diagram.ts+++ b/app/src/protyle/preview/diagram.ts@@ -27,7 +27,13 @@ const createDiagramSVG = (element: SVGSVGElement) => {target.style.setProperty(property, style.getPropertyValue(property));}});- const {width, height} = element.getBoundingClientRect();+ const bounds = element.getBoundingClientRect();+ const viewBox = element.viewBox.baseVal;+ // 使用图表坐标尺寸,避免将编辑器内缩小后的显示尺寸作为复制图片的分辨率。+ const scale = viewBox.width > 0 && viewBox.height > 0 ?+ Math.max(1, bounds.width / viewBox.width, bounds.height / viewBox.height) : 1;+ const width = viewBox.width > 0 && viewBox.height > 0 ? viewBox.width * scale : bounds.width;+ const height = viewBox.width > 0 && viewBox.height > 0 ? viewBox.height * scale : bounds.height;clone.setAttribute("width", `${width}`);clone.setAttribute("height", `${height}`);clone.style.width = `${width}px`;@@ -39,7 +45,7 @@ const createDiagramSVG = (element: SVGSVGElement) => {// SVG 图表保留矢量内容,画布图表使用 PNG,共用图片预览的缩放和拖动控件。export const previewDiagram = (diagramElement: HTMLElement) => {- addScript(`${Constants.PROTYLE_CDN}/js/html-to-image.min.js?v=1.11.13`, "protyleHtml2image").then(async () => {+ return addScript(`${Constants.PROTYLE_CDN}/js/html-to-image.min.js?v=1.11.13`, "protyleHtml2image").then(async () => {const type = diagramElement.getAttribute("data-subtype");const renderElement = type === "echarts" ?diagramElement.querySelector("canvas") :