Skip to content

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

:bug: Preserve ECharts rendering across theme changes and PNG exports https://github.com/siyuan-note/siyuan/issues/20476

Daniel4b0b2bccb029
diff --git a/app/src/protyle/export/imageLayout.test.ts b/app/src/protyle/export/imageLayout.test.ts
index 17576eae4e..8459161a3a 100644
--- a/app/src/protyle/export/imageLayout.test.ts
+++ b/app/src/protyle/export/imageLayout.test.ts
@@ -114,6 +114,7 @@ size-adjust: 85%;
"../../constants": {Constants: {LOCAL_EXPORTIMG: "image", DIALOG_EXPORTIMAGE: "image", TIMEOUT_LOAD: 0}},
"../render/highlightRender": {highlightRender: () => {}, lineNumberRender: () => {}},
"../util/processCode": {processRender: () => {}},
+ "../render/chartRender": {renderChartsForImage: async () => {}},
"../util/compatibility": {isIPhone: () => mobile && engine === "modern", isIPad: () => false,
isSafari: () => engine === "modern", isInAndroid: () => false, setStorageVal: () => {},
saveExportFile: async () => {}},
diff --git a/app/src/protyle/export/util.ts b/app/src/protyle/export/util.ts
index b698d64fa2..ea40205c68 100644
--- a/app/src/protyle/export/util.ts
+++ b/app/src/protyle/export/util.ts
@@ -12,6 +12,7 @@ import {isMobile} from "../../util/functions";
import {Constants} from "../../constants";
import {highlightRender, lineNumberRender} from "../render/highlightRender";
import {processRender} from "../util/processCode";
+import {renderChartsForImage} from "../render/chartRender";
import {isInAndroid, isIPad, isIPhone, isSafari, saveExportFile, setStorageVal} from "../util/compatibility";
import {useShell} from "../../util/pathName";
import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";
@@ -336,6 +337,10 @@ export const exportImage = (id: string, copyOnly = false) => {
previewElement.querySelectorAll(".code-block").forEach(item => {
item.setAttribute("linewrap", "true");
});
+ await renderChartsForImage(previewElement);
+ if (revision !== previewRevision || !document.body.contains(exportDialog.element)) {
+ return;
+ }
processRender(previewElement);
highlightRender(previewElement);
stopObservingLayout?.();
diff --git a/app/src/protyle/render/chartRender.test.ts b/app/src/protyle/render/chartRender.test.ts
new file mode 100644
index 0000000000..9dd7459b67
--- /dev/null
+++ b/app/src/protyle/render/chartRender.test.ts
@@ -0,0 +1,268 @@
+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 {promisify} from "node:util";
+import test from "node:test";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (sources: Record<string, string>, libraries: Record<string, string>) => {
+ const check: typeof assert = require("node:assert/strict");
+ const echarts = require(libraries.echarts);
+ window.echarts = echarts;
+ window.htmlToImage = require(libraries.html);
+ window.modernScreenshot = require(libraries.modern);
+ window.siyuan = {
+ config: {appearance: {mode: 0}, editor: {}, export: {addTitle: false}, system: {}},
+ languages: {exportFileSaveFailed: "Export failed"},
+ storage: {image: {keepFold: false, watermark: false}},
+ } as unknown as ISiyuan;
+ Object.defineProperty(window, "devicePixelRatio", {value: 1});
+ const tick = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
+ const unescape = (value: string) => {
+ const text = document.createElement("textarea");
+ text.innerHTML = value;
+ return text.value;
+ };
+ Object.assign(window, {Lute: {UnEscapeHTMLStr: unescape}});
+ let loading: Promise<void> = Promise.resolve();
+ let parsing: Promise<void> = Promise.resolve();
+ const chartAPI = {} as typeof import("./chartRender");
+ const chartDependencies: Record<string, unknown> = {
+ "../util/addScript": {addScript: () => loading},
+ "../util/echarts": {loadECharts: () => loading},
+ "./foldedContent": {isFoldedRenderContent: () => false},
+ "../../constants": {Constants: {PROTYLE_CDN: "", ZWSP: "\u200b"}},
+ "../util/hasClosest": {hasClosestByClassName: (element: Element) => element.closest(".protyle-wysiwyg")},
+ "../../util/functions": {looseJsonParse: async (text: string) => { await parsing; return JSON.parse(text); }},
+ "./util": {genIconHTML: () => '<div class="protyle-icons"></div>'},
+ "../../util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: false})},
+ "../../util/escape": {escapeHtml: (text: string) => text},
+ };
+ new Function("exports", "require", sources.chart)(chartAPI, (name: string) => chartDependencies[name]);
+ const option = {
+ animation: true, animationDuration: 60000, animationDelay: 60000,
+ title: {text: "Chart"},
+ xAxis: {type: "category", boundaryGap: false, data: Array.from({length: 31}, (_, i) => `${i}`)},
+ yAxis: {type: "value"},
+ series: [{type: "line", animation: true, animationDuration: 60000, animationDelay: 60000,
+ itemStyle: {color: "#4285f4"}, areaStyle: {}, data: Array.from({length: 31}, (_, i) => 20 + i % 5 * 5)}],
+ };
+ const block = () => {
+ const element = document.createElement("div");
+ element.dataset.subtype = "echarts";
+ element.dataset.content = JSON.stringify(option);
+ element.innerHTML = '<div class="protyle-icons"></div><div><span></span><div style="height:420px" contenteditable="false"></div></div>';
+ return element;
+ };
+ const host = document.createElement("div");
+ host.className = "protyle-wysiwyg";
+ host.style.width = "720px";
+ document.body.append(host);
+ const sourceBlock = block();
+ host.append(sourceBlock);
+ chartAPI.chartRender(sourceBlock);
+ await tick(30);
+ const sourceChart = echarts.getInstanceByDom(sourceBlock.querySelector("[_echarts_instance_]"));
+ check.ok(sourceChart);
+ check.equal(sourceChart.getOption().animation, true, "editor animation remains enabled");
+ check.equal(sourceChart.getOption().series[0].animationDuration, 60000);
+ const sourceWidth = sourceChart.getWidth();
+ const sourceHeight = sourceChart.getHeight();
+ const sourceID = sourceChart.id;
+ for (const hidden of [false, true]) {
+ host.style.display = hidden ? "none" : "";
+ for (const mode of [1, 0, 1, 0]) {
+ window.siyuan.config.appearance.mode = mode;
+ chartAPI.refreshChartTheme(document.body);
+ await tick(20);
+ const refreshed = echarts.getInstanceByDom(sourceBlock.querySelector("[_echarts_instance_]"));
+ check.equal(refreshed, sourceChart, "theme changes retain the chart instance");
+ check.equal(refreshed.id, sourceID);
+ check.equal(refreshed.getWidth(), sourceWidth, "hidden tabs retain a nonzero chart width");
+ check.equal(refreshed.getHeight(), sourceHeight);
+ const referenceElement = document.createElement("div");
+ const reference = echarts.init(referenceElement, mode ? "dark" : undefined, {width: sourceWidth, height: sourceHeight});
+ reference.setOption({...option, animation: false, series: option.series.map(series => ({...series, animation: false}))});
+ check.equal(refreshed.getOption().textStyle.color, reference.getOption().textStyle.color,
+ "both directions use the requested theme");
+ check.deepEqual(refreshed.getOption().series[0].data, option.series[0].data);
+ echarts.dispose(reference);
+ }
+ }
+ host.style.display = "";
+ check.equal(sourceChart.getWidth(), host.clientWidth, "showing the tab needs no corrective resize");
+ echarts.dispose(sourceChart);
+ host.remove();
+
+ let content = "";
+ let mobile = false;
+ let modern = false;
+ let dialog: {element: HTMLElement};
+ let captured: {blob: Blob; x: number; y: number; width: number; height: number};
+ const messages: string[] = [];
+ const layout = new Function("exports", sources.layout + "; return exports;")({});
+ const fonts = new Function("exports", sources.fonts + "; return exports;")({});
+ const remember = (blob: Blob) => {
+ const chartElement = dialog.element.querySelector<HTMLElement>("[_echarts_instance_]");
+ const instance = echarts.getInstanceByDom(chartElement);
+ check.equal(instance.getOption().animation, false);
+ check.equal(instance.getOption().series[0].animation, false, "series cannot re-enable export animation");
+ check.equal(instance.getOption().series[0].progressive, 0);
+ check.deepEqual(JSON.parse(chartElement.closest<HTMLElement>('[data-subtype="echarts"]').dataset.content), option,
+ "static rendering preserves the source configuration");
+ const bounds = chartElement.getBoundingClientRect();
+ const contentBounds = dialog.element.querySelector(".b3-dialog__content").getBoundingClientRect();
+ captured = {blob, x: bounds.left - contentBounds.left, y: bounds.top - contentBounds.top,
+ width: bounds.width, height: bounds.height};
+ return true;
+ };
+ class ExportDialog {
+ element: HTMLElement;
+ constructor(options: {content: string}) {
+ this.element = document.createElement("div");
+ this.element.innerHTML = `<div class="b3-dialog__container" style="width:${mobile ? 360 : 800}px">${options.content}</div>`;
+ document.body.append(this.element);
+ dialog = {element: this.element};
+ }
+ destroy() {
+ this.element.querySelectorAll("[_echarts_instance_]").forEach(element => echarts.dispose(element));
+ this.element.remove();
+ }
+ }
+ const dependencies: Record<string, unknown> = {
+ "./imageLayout": layout, "./imageFonts": fonts,
+ "../../dialog": {Dialog: ExportDialog},
+ "../../dialog/message": {showMessage: (text: string) => messages.push(text), hideMessage: () => {}},
+ "../../util/fetch": {fetchPost: (url: string, data: {file: File}, callback: (response: unknown) => void) => {
+ if (url === "/api/export/exportPreviewHTML") {
+ callback({data: {content, attrs: {}, type: "NodeDocument", name: "chart"}});
+ } else {
+ check.equal(url, "/api/export/exportAsFile");
+ remember(data.file);
+ callback({code: 0, data: {file: "chart.png"}});
+ }
+ return Promise.resolve();
+ }},
+ "../../util/contractFormData": {ContractFormData: class {file: File; constructor(data: {file: File}) { this.file = data.file; }}},
+ "./jsEmbed": {renderExportJSEmbeds: async () => {}},
+ "../util/addScript": {addScript: async () => {}},
+ "../../util/functions": {isMobile: () => mobile},
+ "../../constants": {Constants: {LOCAL_EXPORTIMG: "image", DIALOG_EXPORTIMAGE: "image", TIMEOUT_LOAD: 0}},
+ "../render/highlightRender": {highlightRender: () => {}},
+ "../render/chartRender": chartAPI,
+ "../util/processCode": {processRender: chartAPI.chartRender},
+ "../util/compatibility": {isIPhone: () => mobile && modern, isIPad: () => false, isSafari: () => modern,
+ isInAndroid: () => false, setStorageVal: () => {}, saveExportFile: async () => {}},
+ "../../util/hostCapabilities": {getHostCapabilities: () => ({documentImportExport: true}), sanitizeKernelHTML: (text: string) => text},
+ "../../menus/util": {writePNGBlob: async (blob: Blob) => remember(blob)},
+ };
+ const exports = {} as typeof import("../export/util");
+ new Function("exports", "require", sources.export)(exports, (name: string) => dependencies[name] || {});
+ const waitFor = async (predicate: () => boolean) => {
+ const deadline = Date.now() + 5000;
+ while (!predicate() && Date.now() < deadline) {
+ await tick(10);
+ }
+ check.ok(predicate(), messages.join("\n"));
+ };
+ const verifyPNG = async () => {
+ const image = new Image();
+ const url = URL.createObjectURL(captured.blob);
+ try {
+ image.src = url;
+ await image.decode();
+ const canvas = document.createElement("canvas");
+ canvas.width = image.naturalWidth;
+ canvas.height = image.naturalHeight;
+ const context = canvas.getContext("2d");
+ context.drawImage(image, 0, 0);
+ const pixels = context.getImageData(Math.floor(captured.x + captured.width * 0.7),
+ Math.floor(captured.y + captured.height * 0.15), Math.floor(captured.width * 0.15),
+ Math.floor(captured.height * 0.7)).data;
+ let blue = 0;
+ for (let i = 0; i < pixels.length; i += 4) {
+ if (pixels[i + 2] > pixels[i] + 30 && pixels[i + 2] > pixels[i + 1] + 10 && pixels[i + 3] > 100) {
+ blue++;
+ }
+ }
+ check.ok(blue > 100, `right side of the PNG is incomplete: mobile=${mobile}, modern=${modern}, blue=${blue}`);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ };
+ for (const viewport of [false, true]) {
+ mobile = viewport;
+ for (const engine of [false, true]) {
+ modern = engine;
+ for (const automatic of [true, false]) {
+ captured = undefined;
+ content = block().outerHTML;
+ let finishLoading: () => void;
+ let finishParsing: () => void;
+ loading = new Promise(resolve => { finishLoading = resolve; });
+ parsing = new Promise(resolve => { finishParsing = resolve; });
+ exports.exportImage("chart", automatic);
+ await tick(350);
+ check.equal(captured, undefined, "slow library loading must not produce an empty PNG");
+ check.equal((dialog.element.querySelector('[data-type="copy"]') as HTMLButtonElement).disabled, true);
+ finishLoading();
+ await tick(30);
+ check.equal(captured, undefined, "configuration parsing must finish before capture");
+ finishParsing();
+ if (!automatic) {
+ await waitFor(() => !(dialog.element.querySelector('[data-type="export"]') as HTMLButtonElement).disabled);
+ (dialog.element.querySelector('[data-type="export"]') as HTMLButtonElement).click();
+ }
+ await waitFor(() => !!captured);
+ await verifyPNG();
+ await waitFor(() => !dialog.element.isConnected);
+ }
+ }
+ }
+ return "Chart theme and PNG regression cases passed";
+};
+
+test("hidden chart themes and static PNG exports retain complete charts on desktop and mobile", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const sources = Object.fromEntries(Object.entries({chart: "chartRender.ts", export: "../export/util.ts",
+ layout: "../export/imageLayout.ts", fonts: "../export/imageFonts.ts"}).map(([name, file]) => [name,
+ transpileModule(readFileSync(path.resolve(__dirname, file), "utf8"), {
+ compilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},
+ }).outputText]));
+ const libraries = {echarts: path.resolve("stage/protyle/js/echarts/echarts.min.js"),
+ html: path.resolve("stage/protyle/js/html-to-image.min.js"),
+ modern: path.resolve("stage/protyle/js/modern-screenshot.min.js")};
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-chart-render-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show:false,width:850,height:650,
+ webPreferences:{nodeIntegration:true,contextIsolation:false,backgroundThrottling:false,offscreen:true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(
+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(libraries)})`)}));
+ win.destroy(); app.exit(0);
+ } catch (error) {
+ console.error(error); win.destroy(); 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, timeout: 40000, windowsHide: true,
+ });
+ assert.match(result.stdout, /Chart theme and PNG regression cases passed/, result.stderr);
+ } finally {
+ assert.equal(path.dirname(temporary), tmpdir());
+ assert.ok(path.basename(temporary).startsWith("siyuan-chart-render-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/protyle/render/chartRender.ts b/app/src/protyle/render/chartRender.ts
index 3725917979..2bcd4e21db 100644
--- a/app/src/protyle/render/chartRender.ts
+++ b/app/src/protyle/render/chartRender.ts
@@ -49,7 +49,33 @@ const secureEChartsOption = (option: any) => {
return option;
};
-export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
+// 导出副本直接绘制最终状态,覆盖系列和多组配置中单独启用的动画与渐进绘制。
+const prepareChartImageOption = (option: any) => {
+ option.animation = false;
+ const pending = [option];
+ while (pending.length > 0) {
+ const current = pending.pop();
+ Object.entries(current).forEach(([key, value]) => {
+ if (key === "animation") {
+ current[key] = false;
+ }
+ if (key === "series") {
+ (Array.isArray(value) ? value : [value]).forEach(series => {
+ if (series && typeof series === "object") {
+ series.animation = false;
+ series.progressive = 0;
+ }
+ });
+ }
+ if (value && typeof value === "object") {
+ pending.push(value);
+ }
+ });
+ }
+ return option;
+};
+
+const renderCharts = async (element: Element, cdn: string, image = false) => {
if (element.closest('[data-protyle-lite-render="safe"]')) {
return;
}
@@ -63,49 +89,59 @@ export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
if (echartsElements.length === 0) {
return;
}
- loadECharts(cdn).then(() => {
- addScript(`${cdn}/js/echarts/echarts-gl.min.js?v=2.1.0`, "protyleEchartsGLScript").then(() => {
- const wysiswgElement = hasClosestByClassName(element, "protyle-wysiwyg", true);
- let width: number = undefined;
- if (wysiswgElement && wysiswgElement.clientWidth > 0 && echartsElements[0].firstElementChild.clientWidth === 0 && wysiswgElement.firstElementChild) {
- width = wysiswgElement.firstElementChild.clientWidth;
+ await loadECharts(cdn);
+ await addScript(`${cdn}/js/echarts/echarts-gl.min.js?v=2.1.0`, "protyleEchartsGLScript");
+ const wysiswgElement = hasClosestByClassName(element, "protyle-wysiwyg", true);
+ let width: number = undefined;
+ if (wysiswgElement && wysiswgElement.clientWidth > 0 && echartsElements[0].firstElementChild.clientWidth === 0 && wysiswgElement.firstElementChild) {
+ width = wysiswgElement.firstElementChild.clientWidth;
+ }
+ await Promise.all(echartsElements.map(async (e: HTMLDivElement) => {
+ if (e.closest('[data-protyle-lite-render="safe"], .mindmap-view__preview-block')) {
+ return;
+ }
+ e.setAttribute("data-render", "true");
+ if (!e.firstElementChild.classList.contains("protyle-icons")) {
+ e.insertAdjacentHTML("afterbegin", genIconHTML(wysiswgElement, ["refresh", "edit", "more"]));
+ }
+ const renderElement = e.firstElementChild.nextElementSibling as HTMLElement;
+ if (!e.getAttribute("data-content")) {
+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span>`;
+ return;
+ }
+ try {
+ if (!renderElement.lastElementChild || renderElement.childElementCount === 1) {
+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div style="height:${e.style.height || "420px"}" contenteditable="false"></div>`;
+ } else {
+ renderElement.lastElementChild.classList.remove("ft__error");
}
- echartsElements.forEach(async (e: HTMLDivElement) => {
- if (e.closest('[data-protyle-lite-render="safe"], .mindmap-view__preview-block')) {
- return;
- }
- e.setAttribute("data-render", "true");
- if (!e.firstElementChild.classList.contains("protyle-icons")) {
- e.insertAdjacentHTML("afterbegin", genIconHTML(wysiswgElement, ["refresh", "edit", "more"]));
- }
- const renderElement = e.firstElementChild.nextElementSibling as HTMLElement;
- if (!e.getAttribute("data-content")) {
- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span>`;
- return;
- }
- try {
- if (!renderElement.lastElementChild || renderElement.childElementCount === 1) {
- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div style="height:${e.style.height || "420px"}" contenteditable="false"></div>`;
- } else {
- renderElement.lastElementChild.classList.remove("ft__error");
- }
- const chartInstance = window.echarts.getInstanceById(renderElement.lastElementChild?.getAttribute("_echarts_instance_"));
- const option = secureEChartsOption(await looseJsonParse(
- Lute.UnEscapeHTMLStr(e.getAttribute("data-content"))));
- if (chartInstance) {
- if (chartInstance.getOption().series[0]?.type !== option.series[0]?.type) {
- chartInstance.clear();
- }
- chartInstance?.resize();
- }
- window.echarts.init(renderElement.lastElementChild, window.siyuan.config.appearance.mode === 1 ? "dark" : undefined, {width}).setOption(option);
- } catch (error) {
- window.echarts.dispose(renderElement.lastElementChild);
- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">echarts render error: <br>${escapeHtml(String(error))}</div>`;
+ const chartInstance = window.echarts.getInstanceById(renderElement.lastElementChild?.getAttribute("_echarts_instance_"));
+ let option = secureEChartsOption(await looseJsonParse(
+ Lute.UnEscapeHTMLStr(e.getAttribute("data-content"))));
+ if (image) {
+ option = prepareChartImageOption(option);
+ }
+ if (chartInstance) {
+ if (chartInstance.getOption().series[0]?.type !== option.series[0]?.type) {
+ chartInstance.clear();
}
- });
- });
- });
+ chartInstance?.resize();
+ }
+ window.echarts.init(renderElement.lastElementChild, window.siyuan.config.appearance.mode === 1 ? "dark" : undefined, {width}).setOption(option);
+ } catch (error) {
+ window.echarts.dispose(renderElement.lastElementChild);
+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">echarts render error: <br>${escapeHtml(String(error))}</div>`;
+ }
+ }));
+};
+
+export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
+ void renderCharts(element, cdn);
+};
+
+// 图片预览在开放复制和导出操作前等待图表脚本加载、配置解析与静态绘制完成。
+export const renderChartsForImage = (element: Element) => {
+ return renderCharts(element, Constants.PROTYLE_CDN, true);
};
export const refreshChartTheme = (element: Element) => {
@@ -118,7 +154,6 @@ export const refreshChartTheme = (element: Element) => {
} else {
echartsElements = element.querySelectorAll<HTMLElement>('[data-subtype="echarts"]');
}
- const refreshElements: HTMLElement[] = [];
echartsElements.forEach((item) => {
if (item.closest('[data-protyle-lite-render="safe"], .mindmap-view__preview-block')) {
return;
@@ -127,9 +162,8 @@ export const refreshChartTheme = (element: Element) => {
if (!chartElement) {
return;
}
- window.echarts.dispose(chartElement);
- item.removeAttribute("data-render");
- refreshElements.push(item);
+ const chartInstance = window.echarts.getInstanceById(chartElement.getAttribute("_echarts_instance_"));
+ // 原地切换主题保留画布尺寸,后台页签无需测量隐藏容器。
+ chartInstance?.setTheme(window.siyuan.config.appearance.mode === 1 ? "dark" : "default");
});
- refreshElements.forEach(item => chartRender(item));
};
diff --git a/app/src/protyle/render/listMindmap/preview.test.ts b/app/src/protyle/render/listMindmap/preview.test.ts
index bd904eca62..6f3c5ac438 100644
--- a/app/src/protyle/render/listMindmap/preview.test.ts
+++ b/app/src/protyle/render/listMindmap/preview.test.ts
@@ -22,7 +22,6 @@ const extract = (file: string, names: string[]) => {
const cases = async (source: string, css: string) => {
const check = require("node:assert/strict");
const requests: {url: string, data: Record<string, string>}[] = [];
- const chartRefreshes: Element[] = [];
const dependencies = {
isFoldedRenderContent: () => false,
fetchPost: (url: string, data: Record<string, string>) => requests.push({url, data}),
@@ -30,7 +29,6 @@ const cases = async (source: string, css: string) => {
genRenderFrame: () => {},
isEncryptedBox: () => false,
hasClosestByClassName: (element: HTMLElement, name: string) => element.closest(`.${name}`),
- chartRender: (element: Element) => chartRefreshes.push(element),
mathRender: (): undefined => undefined,
};
const api = new Function(...Object.keys(dependencies), source + "; return {customBlockRender, " +
@@ -61,7 +59,7 @@ const cases = async (source: string, css: string) => {
const updates: string[] = [];
window.siyuan = {
languages: new Proxy({}, {get: (_target, key) => String(key)}),
- config: {editor: {embedBlockBreadcrumb: false, headingEmbedMode: 0}},
+ config: {editor: {embedBlockBreadcrumb: false, headingEmbedMode: 0}, appearance: {mode: 1}},
ws: {app: {plugins: [{name: "preview-test", customBlockRenders: {test: {
render: (options: {element: HTMLElement, setContent: (content: string) => boolean}) => {
renders++;
@@ -127,10 +125,19 @@ const cases = async (source: string, css: string) => {
chart.dataset.subtype = "echarts";
preview(chart);
const disposedCharts: Element[] = [];
- window.echarts = {dispose: (element: Element) => disposedCharts.push(element)} as unknown as typeof window.echarts;
+ const chartThemes: string[] = [];
+ const chartIDs: string[] = [];
+ window.echarts = {
+ dispose: (element: Element) => disposedCharts.push(element),
+ getInstanceById: (id: string) => {
+ chartIDs.push(id);
+ return {setTheme: (theme: string) => chartThemes.push(theme)};
+ },
+ } as unknown as typeof window.echarts;
api.refreshChartTheme(root);
- check.deepEqual(disposedCharts, [chart.firstElementChild], "theme changes never dispose the source through a preview copy");
- check.deepEqual(chartRefreshes, [chart]);
+ check.deepEqual(disposedCharts, [], "theme changes preserve the source instance");
+ check.deepEqual(chartIDs, ["source-instance"], "theme changes exclude preview copies");
+ check.deepEqual(chartThemes, ["dark"]);
const table = block("NodeTable", "<table><tbody><tr><td>Cell</td></tr></tbody></table>" +
'<div class="protyle-action__table"></div>');
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 7051aa4c5e..be0f1b9763 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -92,6 +92,7 @@ interface Window {
};
dispose(element: Element): void;
getInstanceById(id: string): {
+ setTheme: (theme: string) => void
resize: () => void
clear: () => void
getOption: () => { series: { type: string }[] }