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: Preserve native font metrics in image exports https://github.com/siyuan-note/siyuan/issues/20451
Daniel10289d6ae042
diff --git a/app/src/protyle/export/imageFonts.ts b/app/src/protyle/export/imageFonts.tsnew file mode 100644index 0000000000..0c97e86536--- /dev/null+++ b/app/src/protyle/export/imageFonts.ts@@ -0,0 +1,26 @@+const getLocalFontRules = (rules: CSSRuleList): string => Array.from(rules).map(rule => {+ if (rule instanceof CSSFontFaceRule) {+ const source = rule.style.getPropertyValue("src");+ return /\blocal\s*\(/i.test(source) && !/\burl\s*\(/i.test(source) ? rule.cssText : "";+ }+ if (rule instanceof CSSGroupingRule) {+ const fonts = getLocalFontRules(rule.cssRules);+ return fonts ? `${rule.cssText.slice(0, rule.cssText.indexOf("{") + 1)}\n${fonts}\n}` : "";+ }+ return "";+}).filter(Boolean).join("\n");++export const getExportImageLocalFontCSS = (ownerDocument: Document) => Array.from(ownerDocument.styleSheets).map(sheet => {+ try {+ return getLocalFontRules(sheet.cssRules);+ } catch {+ // 跨域样式表不可读取,继续使用截图引擎的字体嵌入流程。+ return "";+ }+}).filter(Boolean).join("\n");++export const getExportImageFontCSS = async (element: HTMLElement) => {+ // 本地字体声明保留缩放和字符范围,网络字体仍由截图引擎嵌入。+ const localFonts = getExportImageLocalFontCSS(element.ownerDocument);+ return `${localFonts}\n${await window.htmlToImage.getFontEmbedCSS(element)}`;+};diff --git a/app/src/protyle/export/imageLayout.test.ts b/app/src/protyle/export/imageLayout.test.tsindex fa6a009db3..17576eae4e 100644--- a/app/src/protyle/export/imageLayout.test.ts+++ b/app/src/protyle/export/imageLayout.test.ts@@ -18,13 +18,29 @@ test("image limits account for device pixels, side length and bitmap area", () =assert.equal(isExportImageSizeSupported({width: 100, height: 100}, NaN), false);});-const browserCases = async (layoutSource: string, exportSource: string, mobile: boolean) => {+const browserCases = async (layoutSource: string, fontSource: string, exportSource: string, mobile: boolean) => {const check = require("node:assert/strict");const layout: {updateExportImageLayout: typeof updateExportImageLayout,getExportImageSize: typeof getExportImageSize,isExportImageSizeSupported: typeof isExportImageSizeSupported,} = new Function("exports", `${layoutSource}; return exports;`)({});+ const fonts = new Function("exports", `${fontSource}; return exports;`)({});+ const nativeFonts = document.createElement("style");+ nativeFonts.textContent = `@font-face {+font-family: "ExportLocalFont";+src: local("Arial"), local("Helvetica"), local("Liberation Sans"), local("DejaVu Sans");+size-adjust: 50%;+unicode-range: U+0-7f;+}+@supports (display: block) {+@font-face {+font-family: "ExportEmojiFont";+src: local("Segoe UI Emoji"), local("Apple Color Emoji"), local("Noto Color Emoji");+size-adjust: 85%;+}+}`;+ document.head.append(nativeFonts);let engine = "html";let content = "";let dialog: {element: HTMLElement, resize: () => void};@@ -73,6 +89,7 @@ const browserCases = async (layoutSource: string, exportSource: string, mobile:};const dependencies: Record<string, unknown> = {"./imageLayout": layout,+ "./imageFonts": fonts,"../../dialog": {Dialog: ExportDialog},"../../dialog/message": {showMessage: (message: string) => messages.push(message), hideMessage: () => {}},"../../util/fetch": {fetchPost: (url: string, data: {file: File}, callback: (response: unknown) => void) => {@@ -152,7 +169,7 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;const context = canvas.getContext("2d");context.drawImage(image, 0, 0);const pixel = context.getImageData(Math.floor(captured.x * 2), Math.floor(captured.y * 2), 1, 1).data;- check.deepEqual(Array.from(pixel), [255, 0, 0, 255], `Last column was clipped (${engine}, mobile=${mobile})`);+ check.deepEqual(Array.from(pixel), [255, 0, 0, 255], `PNG marker moved or was clipped (${engine}, mobile=${mobile})`);} finally {URL.revokeObjectURL(url);}@@ -169,6 +186,18 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;check.equal(narrow.scrollWidth, narrow.clientWidth);await capture();+ const localFontTable = await open(`<div class="table" data-node-id="table"><div><table>+<colgroup><col style="min-width:60px"><col style="min-width:60px"><col style="min-width:60px"></colgroup>+<thead><tr><th></th><th></th><th></th></tr></thead>+<tbody><tr><td>Hello <span style="font-family:ExportEmojiFont,Arial">⭐⭐⭐</span></td><td>Hello ⭐⭐⭐</td><td></td></tr>+<tr><td>1232 ⭐⭐⭐</td><td><span style="font-family:ExportLocalFont,Arial">WWWWWWWW</span><span class="marker" style="display:inline-block;width:20px;height:20px;background:red"></span></td><td></td></tr></tbody>+</table></div></div><div class="callout" data-node-id="tip" data-type="NodeCallout" data-subtype="TIP"><div class="callout-info">💡 Tip</div><div class="callout-content"><div class="p" data-node-id="paragraph">12312312</div></div></div>`);+ await document.fonts.ready;+ const tableRect = localFontTable.querySelector("table").getBoundingClientRect();+ check.ok(localFontTable.querySelector(".callout").getBoundingClientRect().top >= tableRect.bottom,+ "The following block must start below the table");+ await capture();+const wide = await open(table(4));const imageElement = wide.querySelector<HTMLElement>(".export-img");const cell = wide.querySelector("td");@@ -260,12 +289,13 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;"Watermark tiles must be bounded by the viewport");await capture();document.body.replaceChildren();+ nativeFonts.remove();return `Image exports passed (mobile=${mobile})`;};test("wide PNG exports preserve text and all columns in both screenshot engines and viewport sizes", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,- timeout: 95000,+ timeout: 185000,}, async () => {const sass = require("sass");const css = sass.compileString('@use "component/dialog"; @use "protyle/wysiwyg"; ' +@@ -276,6 +306,7 @@ test("wide PNG exports preserve text and all columns in both screenshot enginescompilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},}).outputText;const layoutSource = compile("imageLayout.ts");+ const fontSource = compile("imageFonts.ts");const exportSource = compile("util.ts");const libraries = ["html-to-image.min.js", "modern-screenshot.min.js"].map(file =>readFileSync(path.resolve("stage/protyle/js", file), "utf8"));@@ -307,7 +338,7 @@ ${libraries.map(source => `new Function("module", "exports", ${JSON.stringify(sophase = "export cases " + mobile;console.log(await win.webContents.executeJavaScript("const __name = value => value; (" + ${JSON.stringify(browserCases.toString())} + ")(" +- ${JSON.stringify(JSON.stringify(layoutSource) + "," + JSON.stringify(exportSource))} + "," + mobile + ")"));+ ${JSON.stringify(JSON.stringify(layoutSource) + "," + JSON.stringify(fontSource) + "," + JSON.stringify(exportSource))} + "," + mobile + ")"));win.destroy();}app.exit(0);@@ -319,7 +350,7 @@ ${libraries.map(source => `new Function("module", "exports", ${JSON.stringify(sodelete env.ELECTRON_RUN_AS_NODE;try {const result = await promisify(execFile)(require("electron") as unknown as string, [script], {- env, timeout: 90000, windowsHide: true,+ env, timeout: 180000, windowsHide: true,});assert.match(result.stdout, /Image exports passed \(mobile=false\)/, result.stderr);assert.match(result.stdout, /Image exports passed \(mobile=true\)/, result.stderr);diff --git a/app/src/protyle/export/util.ts b/app/src/protyle/export/util.tsindex 595f37b6fb..b698d64fa2 100644--- a/app/src/protyle/export/util.ts+++ b/app/src/protyle/export/util.ts@@ -17,6 +17,7 @@ import {useShell} from "../../util/pathName";import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";import {copyPNGByLink, writePNGBlob} from "../../menus/util";import {getExportImageSize, isExportImageSizeSupported, observeExportImageLayout, updateExportImageLayout} from "./imageLayout";+import {getExportImageFontCSS, getExportImageLocalFontCSS} from "./imageFonts";const IMAGE_PLACEHOLDER = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";@@ -157,12 +158,20 @@ export const exportImage = (id: string, copyOnly = false) => {if (isIPhone() || isIPad() || isSafari()) {// modern-screenshot 通过缓存默认样式提高 WebKit/WKWebView 环境下的导出性能。await addScript(`${Constants.PROTYLE_CDN}/js/modern-screenshot.min.js?v=4.7.0`, "protyleModernScreenshot");+ const localFontCSS = getExportImageLocalFontCSS(contentElement.ownerDocument);return window.modernScreenshot.domToBlob(contentElement, {...size,style,type: "image/png",scale: pixelRatio,+ onCreateForeignObjectSvg: (svgElement: SVGSVGElement) => {+ if (localFontCSS) {+ const fontStyle = document.createElementNS(svgElement.namespaceURI, "style");+ fontStyle.textContent = localFontCSS;+ svgElement.insertBefore(fontStyle, svgElement.firstChild);+ }+ },fetch: {placeholderImage: IMAGE_PLACEHOLDER}});}@@ -172,6 +181,7 @@ export const exportImage = (id: string, copyOnly = false) => {...size,style,pixelRatio,+ fontEmbedCSS: await getExportImageFontCSS(contentElement),imagePlaceholder: IMAGE_PLACEHOLDER,onImageErrorHandler: (event: Event) => {(event.target as HTMLImageElement).src = IMAGE_PLACEHOLDER;@@ -291,7 +301,9 @@ export const exportImage = (id: string, copyOnly = false) => {const width = Math.max(Math.min(imageElement.clientWidth, contentElement.clientWidth) / 3, 150);watermarkPreviewElement.setAttribute("style", `width: ${width}px;height: ${width}px;display: flex;justify-content: center;align-items: center;color: var(--b3-border-color);font-size: 14px;`);watermarkPreviewElement.innerHTML = sanitizeKernelHTML(`<div style="transform: rotate(-45deg)">${window.siyuan.config.export.imageWatermarkStr}</div>`);- const canvas = await window.htmlToImage.toCanvas(watermarkPreviewElement);+ const canvas = await window.htmlToImage.toCanvas(watermarkPreviewElement, {+ fontEmbedCSS: await getExportImageFontCSS(watermarkPreviewElement),+ });watermarkPreviewElement.innerHTML = "";watermarkPreviewElement.setAttribute("style", `background-image: url(${canvas.toDataURL("image/png")});background-repeat: repeat;position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: var(--b3-border-radius-b);`);}diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 359aa08a51..7051aa4c5e 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -201,6 +201,7 @@ interface Window {}};htmlToImage: {+ getFontEmbedCSS: (element: Element, options?: IHtmlToImageOptions) => Promise<string>toCanvas: (element: Element, options?: IHtmlToImageOptions) => Promise<HTMLCanvasElement>toBlob: (element: Element, options?: IHtmlToImageOptions) => Promise<Blob>};