Skip to content

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

:sparkles: Support HarmonyOS system fonts https://github.com/siyuan-note/siyuan/issues/20159

Daniel646c3923d25a
diff --git a/app/src/config/tabs/appearanceTab.test.ts b/app/src/config/tabs/appearanceTab.test.ts
index cb0572d924..bee23052f0 100644
--- a/app/src/config/tabs/appearanceTab.test.ts
+++ b/app/src/config/tabs/appearanceTab.test.ts
@@ -93,8 +93,9 @@ const createPendingFontMenu = (key: string) => {
});
const appearance = load("src/config/tabs/appearanceTab.ts", {
"../../plugin/Menu": pluginMenu,
- "../../util/customFont": {supportsCustomFonts: () => false},
- "../../util/systemFont": {loadSystemFonts: () => new Promise(resolve => { resolveFonts = resolve; })},
+ "../../util/availableFont": {loadAvailableFonts: () => new Promise(resolve => {
+ resolveFonts = fonts => resolve({customFontSupported: false, customFonts: [], fontItems: fonts});
+ })},
"../../util/functions": {isMobile: () => false},
"../../util/escape": {escapeAttr: (text: string) => text},
}, "\nexports.mountAppearanceFontFamily = mountAppearanceFontFamily;");
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.ts
index 90bef7085a..a5d963d0c1 100644
--- a/app/src/config/tabs/appearanceTab.ts
+++ b/app/src/config/tabs/appearanceTab.ts
@@ -30,15 +30,13 @@ import {upDownHint} from "../../util/upDownHint";
import {isThemeFrontendSupported} from "../../util/themeCompatibility";
import {setEditorFontSize} from "../../util/editorFontSize";
import {
- ICustomFont,
invalidateCustomFonts,
- supportsCustomFonts,
- loadCustomFonts,
registerCustomFont,
unregisterCustomFont
} from "../../util/customFont";
import {showMessage} from "../../dialog/message";
-import {IFontItem, loadSystemFonts} from "../../util/systemFont";
+import {IFontItem} from "../../util/systemFontCore";
+import {loadAvailableFonts} from "../../util/availableFont";
import {observeFontPreview} from "../../util/fontPreview";
import {
shouldShowBootAppearanceSetting,
@@ -81,19 +79,6 @@ const getEditorFontDisplay = (fonts: IFontItem[]) =>
const isCodeFont = (font: Pick<IFontItem, "spacing">) =>
font.spacing === "monospace" || font.spacing === "dual" || font.spacing === "character-cell";
-const loadAvailableFonts = async () => {
- const customFontSupported = supportsCustomFonts();
- const [systemFonts, customFonts] = await Promise.all([
- loadSystemFonts(),
- customFontSupported ? loadCustomFonts() : Promise.resolve([] as ICustomFont[])
- ]);
- return {
- customFontSupported,
- customFonts,
- fontItems: [...customFonts, ...systemFonts],
- };
-};
-
const genFontConfigHtml = (configKey: FontFamiliesConfigKey, title: string, description: string) => {
const fonts = getConfiguredFonts(getFontConfig(), configKey);
return `<div class="fn__flex b3-label config-item" data-font-config-key="${configKey}">
diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.ts
index 306808ebd3..48f67a68fe 100644
--- a/app/src/protyle/export/index.ts
+++ b/app/src/protyle/export/index.ts
@@ -8,6 +8,7 @@ import {afterExport} from "./util";
/// #endif
import {confirmDialog} from "../../dialog/confirmDialog";
import {getThemeMode, setInlineStyle} from "../../util/assets";
+import {getCustomFontStyle} from "../../util/customFont";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {Dialog} from "../../dialog";
import {replaceLocalPath} from "../../editor/rename";
@@ -360,6 +361,7 @@ const renderPDF = async (id: string) => {
visibility: hidden;
}
${await setInlineStyle(false, servePath)}
+ ${getHostCapabilities().customAppearance ? await getCustomFontStyle() : ""}
${await getPluginStyle()}
</style>
${getSnippetCSS()}
@@ -1146,7 +1148,7 @@ export const onExport = async (data: IWebSocketData, filePath: string, servePath
<!-- Exported by SiYuan v${Constants.SIYUAN_VERSION} -->
<style>
body {font-family: var(--b3-font-family);background-color: var(--b3-theme-background);color: var(--b3-theme-on-background)}
- ${await setInlineStyle(false, servePath)}
+ ${await setInlineStyle(false, servePath, data.data.content)}
${await getPluginStyle()}
${mobileHtml.css}
</style>
diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.ts
index 8c79ac76d5..9a814a1136 100644
--- a/app/src/protyle/toolbar/fontFamilyMenu.ts
+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts
@@ -5,8 +5,8 @@ import {
getFontFamilyDisplayName,
getUniqueFontFamilies,
IFontItem,
- loadSystemFonts,
-} from "../../util/systemFont";
+} from "../../util/systemFontCore";
+import {loadAvailableFonts} from "../../util/availableFont";
import {upDownHint} from "../../util/upDownHint";
import {Constants} from "../../constants";
import {getBlockRanges} from "../util/selection";
@@ -280,7 +280,7 @@ let loadedFontFamilies: IFontItem[] = [];
const loadFontFamilies = async (currentFamily?: string) => {
let fonts: IFontItem[] = [];
try {
- fonts = getUniqueFontFamilies(await loadSystemFonts());
+ fonts = getUniqueFontFamilies((await loadAvailableFonts()).fontItems);
} catch (error) {
console.warn("load system fonts failed", error);
}
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index c2fe21ff2a..7f99141908 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -244,6 +244,7 @@ interface Window {
logInputEvent?(details: string): void
};
JSHarmony: {
+ getSystemFonts?(): Promise<string>
openAuthURL(url: string): void
showKeyboard(): void
hideKeyboard(): void
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index 00424dd067..2871225fcb 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -338,7 +338,7 @@ export const initAssets = (keepLoading = false) => {
});
};
-export const setInlineStyle = async (set = true, servePath = "../../../") => {
+export const setInlineStyle = async (set = true, servePath = "../../../", exportHTML = "") => {
const allowCustomAppearance = getHostCapabilities().customAppearance;
const globalFonts = allowCustomAppearance ? window.siyuan.config.appearance.globalFontFamilies || [] : [];
const editorFonts = allowCustomAppearance ? window.siyuan.config.editor.fontFamilies || [] : [];
@@ -360,7 +360,8 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {
let style = getEmojiFontStyle(emojiPlatform, servePath);
style += getGlobalFontStyle(globalFonts);
if (!set) {
- style += "\n" + await getExportCustomFontStyle([...globalFonts, ...editorFonts, ...codeFonts]);
+ style += "\n" + await getExportCustomFontStyle([...globalFonts, ...editorFonts, ...codeFonts],
+ allowCustomAppearance ? exportHTML : "");
}
const editorFontFamilies = editorFonts.map((font) => CSS.escape(font.family)).join(", ");
const editorFontWeight = editorFonts[0]?.weight;
diff --git a/app/src/util/availableFont.ts b/app/src/util/availableFont.ts
new file mode 100644
index 0000000000..8f2f00fba1
--- /dev/null
+++ b/app/src/util/availableFont.ts
@@ -0,0 +1,22 @@
+import {ICustomFont, loadCustomFonts, syncCustomFonts, supportsCustomFonts} from "./customFont";
+import {loadSystemFonts} from "./systemFont";
+import type {IFontItem} from "./systemFontCore";
+
+export const loadAvailableFonts = async () => {
+ const customFontSupported = supportsCustomFonts();
+ const [systemResult, customResult] = await Promise.allSettled([
+ loadSystemFonts(),
+ customFontSupported ? loadCustomFonts() : Promise.resolve([] as ICustomFont[]),
+ ]);
+ const systemFonts: IFontItem[] = systemResult.status === "fulfilled" ? systemResult.value : [];
+ const customFonts = customResult.status === "fulfilled" ? customResult.value : [];
+ if (systemResult.status === "rejected") {
+ console.warn("load system fonts failed", systemResult.reason);
+ }
+ if (customResult.status === "rejected") {
+ console.warn("load custom fonts failed", customResult.reason);
+ } else if (customFontSupported) {
+ syncCustomFonts(customFonts);
+ }
+ return {customFontSupported, customFonts, fontItems: [...customFonts, ...systemFonts]};
+};
diff --git a/app/src/util/customFont.test.ts b/app/src/util/customFont.test.ts
index c541e7f412..533ef560ac 100644
--- a/app/src/util/customFont.test.ts
+++ b/app/src/util/customFont.test.ts
@@ -21,24 +21,25 @@ for (const container of ["docker", "android", "ios", "harmony", "std", "unknown"
const font = {id: "a".repeat(64), family: "SiYuanCustomFont-" + "a".repeat(64), weight: 400};
const customFont = evaluate("src/util/customFont.ts", {
window,
+ document: {getElementById: (): undefined => undefined, createElement: () => ({}), head: {append() {}}},
require: () => ({fetchSyncPost: async () => {
customRequests++;
- return {data: [font]};
+ return {code: 0, data: [font]};
}}),
});
- const appearance = evaluate("src/config/tabs/appearanceTab.ts", {
+ const availableFonts = evaluate("src/util/availableFont.ts", {
window,
require: (name: string) => {
- if (name === "../../util/customFont") {
+ if (name === "./customFont") {
return customFont;
}
- if (name === "../../util/systemFont") {
+ if (name === "./systemFont") {
return {loadSystemFonts: async (): Promise<unknown[]> => []};
}
return {};
},
- }, "\nexports.loadAvailableFonts = loadAvailableFonts;");
- const result = await appearance.loadAvailableFonts();
+ });
+ const result = await availableFonts.loadAvailableFonts();
const supported = ["docker", "android", "ios", "harmony"].includes(container);
assert.equal(customRequests, supported ? 1 : 0);
assert.equal(result.fontItems.length, supported ? 1 : 0);
@@ -48,6 +49,184 @@ for (const container of ["docker", "android", "ios", "harmony", "std", "unknown"
});
}
+test("inline font picker uses the same available fonts on desktop and mobile", async () => {
+ const font = {family: "SiYuanCustomFont-" + "a".repeat(64), weight: 400, displayName: "导入字体"};
+ const core = evaluate("src/util/systemFontCore.ts", {});
+ const menu = evaluate("src/protyle/toolbar/fontFamilyMenu.ts", {
+ require: (name: string) => {
+ if (name === "../../util/availableFont") {
+ return {loadAvailableFonts: async () => ({fontItems: [font]})};
+ }
+ if (name === "../../util/systemFontCore") {
+ return core;
+ }
+ return {};
+ },
+ }, "\nexports.loadFontFamilies = loadFontFamilies;");
+ const fonts = await menu.loadFontFamilies();
+ assert.equal(fonts[0].family, font.family);
+ assert.equal(menu.getInlineFontFamilyLabel({family: font.family}), font.displayName);
+ const source = readFileSync(resolve(process.cwd(), "src/protyle/toolbar/fontFamilyMenu.ts"), "utf8");
+ assert.equal(source.split("await loadFontFamilies(options.family)").length - 1, 2);
+});
+
+test("one unavailable font source does not hide the other source", async () => {
+ for (const failedSource of ["system", "custom"]) {
+ const font = {family: "Available", weight: 400, displayName: "Available"};
+ const availableFonts = evaluate("src/util/availableFont.ts", {
+ console: {warn() {}},
+ require: (name: string) => name === "./systemFont" ? {
+ loadSystemFonts: async () => {
+ if (failedSource === "system") throw new Error("unavailable");
+ return [font];
+ },
+ } : {
+ supportsCustomFonts: () => true,
+ syncCustomFonts() {},
+ loadCustomFonts: async () => {
+ if (failedSource === "custom") throw new Error("unavailable");
+ return [font];
+ },
+ },
+ });
+ assert.equal((await availableFonts.loadAvailableFonts()).fontItems[0].family, font.family);
+ }
+});
+
+test("reopening a document registers imported fonts even without a configured default", async () => {
+ const id = "a".repeat(64);
+ const font = {id, family: "SiYuanCustomFont-" + id, weight: 400};
+ const styles: {id?: string; textContent?: string}[] = [];
+ let loads = 0;
+ const customFont = evaluate("src/util/customFont.ts", {
+ window: {siyuan: {config: {system: {container: "harmony"}}}},
+ document: {
+ getElementById: (): undefined => undefined,
+ createElement: () => ({}),
+ head: {append: (style: typeof styles[number]) => styles.push(style)},
+ fonts: {load: () => { loads++; }},
+ },
+ require: () => ({fetchSyncPost: async () => ({code: 0, data: [font]})}),
+ });
+ await customFont.ensureSelectedCustomFonts([]);
+ assert.equal(styles.length, 1);
+ assert.match(styles[0].textContent, new RegExp(font.family));
+ assert.equal(loads, 0);
+});
+
+test("font lists refresh after another window imports a font and share concurrent requests", async () => {
+ const id = "d".repeat(64);
+ const font = {id, family: "SiYuanCustomFont-" + id, weight: 400, displayName: "Imported"};
+ let kernelFonts: typeof font[] = [];
+ const styles = new Map<string, {id?: string; textContent?: string}>();
+ let requests = 0;
+ let loads = 0;
+ const customFont = evaluate("src/util/customFont.ts", {
+ window: {siyuan: {config: {system: {container: "harmony"}}}},
+ document: {
+ getElementById: (styleID: string) => styles.get(styleID),
+ createElement: () => ({}),
+ head: {append: (style: {id?: string; textContent?: string}) => styles.set(style.id, style)},
+ fonts: {load: async (): Promise<FontFace[]> => { loads++; return []; }},
+ },
+ require: () => ({fetchSyncPost: async () => {
+ requests++;
+ return {code: 0, data: kernelFonts};
+ }}),
+ });
+ await customFont.ensureSelectedCustomFonts([]);
+ assert.equal(requests, 1);
+ assert.equal(styles.size, 0);
+ kernelFonts = [font];
+ await customFont.ensureSelectedCustomFonts([font]);
+ assert.equal(requests, 2);
+ assert.equal(styles.size, 1);
+ assert.equal(loads, 1);
+ const [first, second] = await Promise.all([customFont.loadCustomFonts(), customFont.loadCustomFonts()]);
+ assert.equal(requests, 3);
+ assert.equal(first[0].family, font.family);
+ assert.equal(second[0].family, font.family);
+});
+
+test("successful font refresh removes deleted registrations while failed reads preserve them", async () => {
+ const id = "e".repeat(64);
+ const font = {id, family: "SiYuanCustomFont-" + id, weight: 400};
+ let response: {code: number; data: typeof font[]} = {code: 0, data: [font]};
+ const styles = new Map<string, {id?: string; textContent?: string; remove?: () => void}>();
+ const customFont = evaluate("src/util/customFont.ts", {
+ window: {siyuan: {config: {system: {container: "harmony"}}}},
+ console: {warn() {}},
+ document: {
+ getElementById: (styleID: string) => styles.get(styleID),
+ createElement: () => ({}),
+ head: {append: (style: {id?: string; textContent?: string; remove?: () => void}) => {
+ styles.set(style.id, style);
+ style.remove = () => { styles.delete(style.id); };
+ }},
+ },
+ require: () => ({fetchSyncPost: async () => response}),
+ });
+ await customFont.ensureSelectedCustomFonts([]);
+ assert.equal(styles.size, 1);
+ response = {code: -1, data: []};
+ await customFont.ensureSelectedCustomFonts([]);
+ assert.equal(styles.size, 1);
+ response = {code: 0, data: []};
+ await customFont.ensureSelectedCustomFonts([]);
+ assert.equal(styles.size, 0);
+});
+
+test("invalidating an in-flight font read does not clear its replacement request", async () => {
+ const pending: Array<(response: {code: number; data: unknown[]}) => void> = [];
+ const customFont = evaluate("src/util/customFont.ts", {
+ require: () => ({fetchSyncPost: () => new Promise(resolve => pending.push(resolve))}),
+ });
+ const first = customFont.loadCustomFonts();
+ customFont.invalidateCustomFonts();
+ const replacement = customFont.loadCustomFonts();
+ pending[0]({code: 0, data: []});
+ await first;
+ assert.equal(customFont.loadCustomFonts(), replacement);
+ assert.equal(pending.length, 2);
+ pending[1]({code: 0, data: []});
+ await replacement;
+});
+
+test("HTML export embeds fonts used only in document styles and ignores plain text", async () => {
+ const id = "b".repeat(64);
+ const font = {id, family: "SiYuanCustomFont-" + id, weight: 400};
+ const unusedID = "c".repeat(64);
+ const unused = {id: unusedID, family: "SiYuanCustomFont-" + unusedID, weight: 400};
+ let requestedURL = "";
+ let parsedHTML = "";
+ const customFont = evaluate("src/util/customFont.ts", {
+ window: {siyuan: {config: {system: {container: "harmony"}}}},
+ document: {createElement: () => ({
+ set innerHTML(value: string) { parsedHTML = value; },
+ content: {querySelectorAll: () => [{style: {fontFamily: `'${font.family}', serif`}}]},
+ })},
+ fetch: async (url: string) => {
+ requestedURL = url;
+ return {ok: true, blob: async () => ({})};
+ },
+ FileReader: class {
+ result = "data:font/ttf;base64,AA==";
+ onload: () => void;
+ readAsDataURL() { this.onload(); }
+ },
+ require: () => ({fetchSyncPost: async () => ({code: 0, data: [font, unused]})}),
+ });
+ const html = `<span style="font-family: '${font.family}'">${unused.family}</span>`;
+ const css = await customFont.getExportCustomFontStyle([], html);
+ assert.equal(parsedHTML, html);
+ assert.equal(requestedURL, `/custom-fonts/${id}`);
+ assert.match(css, /data:font\/ttf;base64,AA==/);
+ assert.ok(css.includes(font.family));
+ assert.ok(!css.includes(unused.family));
+ const previewCSS = await customFont.getCustomFontStyle();
+ assert.ok(previewCSS.includes(`/custom-fonts/${id}`));
+});
+
for (const key of ["globalFontFamilies", "fontFamilies", "codeFontFamilies"]) {
test(`export embeds custom fonts when only ${key} is configured`, async () => {
const font = {family: "SiYuanCustomFont-" + "a".repeat(64), weight: 400};
diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.ts
index c4b5c149d8..da2b8e0609 100644
--- a/app/src/util/customFont.ts
+++ b/app/src/util/customFont.ts
@@ -22,12 +22,20 @@ export const supportsCustomFonts = () => {
export const loadCustomFonts = () => {
if (!customFontsPromise) {
- customFontsPromise = fetchSyncPost("/api/system/getCustomFonts").then((response) => {
- return Array.isArray(response.data) ? response.data as ICustomFont[] : [];
- }).catch((error) => {
- customFontsPromise = undefined;
- throw error;
+ const request = fetchSyncPost("/api/system/getCustomFonts").then((response) => {
+ if (response.code !== 0 || !Array.isArray(response.data)) {
+ throw new Error(response.msg || "load custom fonts failed");
+ }
+ return response.data as ICustomFont[];
});
+ customFontsPromise = request;
+ const clearRequest = () => {
+ // 仅合并在途请求,后续读取可以获取其他窗口导入或删除的字体。
+ if (customFontsPromise === request) {
+ customFontsPromise = undefined;
+ }
+ };
+ void request.then(clearRequest, clearRequest);
}
return customFontsPromise;
};
@@ -73,6 +81,19 @@ export const unregisterCustomFont = (id: string) => {
}
};
+export const syncCustomFonts = (fonts: ICustomFont[]) => {
+ if (window.siyuan.config.system.safeMode) {
+ return;
+ }
+ const ids = new Set(fonts.filter(isValidCustomFont).map(font => font.id));
+ registeredFonts.forEach((font, id) => {
+ if (!ids.has(id)) {
+ unregisterCustomFont(id);
+ }
+ });
+ registerCustomFonts(fonts);
+};
+
export const ensureSelectedCustomFont = async (family: string, weight: number) => {
if (window.siyuan.config.system.safeMode || !family.startsWith(CUSTOM_FONT_FAMILY_PREFIX)) {
return;
@@ -104,13 +125,39 @@ export const ensureSelectedCustomFont = async (family: string, weight: number) =
};
export const ensureSelectedCustomFonts = async (fonts: Array<{ family: string; weight: number }>) => {
- await Promise.all(fonts.map((font) => ensureSelectedCustomFont(font.family, font.weight)));
+ const registration = !window.siyuan.config.system.safeMode && supportsCustomFonts() ?
+ loadCustomFonts().then(customFonts => {
+ // 注册所有导入字体的 CSS,正文中使用的字体由浏览器按需加载。
+ syncCustomFonts(customFonts);
+ }).catch(error => {
+ console.warn("register custom fonts failed", error);
+ }) : Promise.resolve();
+ await Promise.all([registration, ...fonts.map((font) => ensureSelectedCustomFont(font.family, font.weight))]);
};
-export const getExportCustomFontStyle = async (fonts: Array<{family: string}>) => {
+export const getCustomFontStyle = async () => {
+ if (window.siyuan.config.system.safeMode) {
+ return "";
+ }
+ // 导出预览注册可用字体,字体文件仍由浏览器根据正文样式按需加载。
+ return (await loadCustomFonts()).filter(isValidCustomFont)
+ .map(font => getCustomFontCSS(font, `/custom-fonts/${font.id}`)).join("\n");
+};
+
+export const getExportCustomFontStyle = async (fonts: Array<{family: string}>, html = "") => {
+ if (window.siyuan.config.system.safeMode) {
+ return "";
+ }
const families = new Set(fonts.map((font) => font.family).filter((family) =>
family.startsWith(CUSTOM_FONT_FAMILY_PREFIX)));
- if (window.siyuan.config.system.safeMode || families.size === 0) {
+ if (html) {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ template.content.querySelectorAll<HTMLElement>("[style]").forEach(element => {
+ element.style.fontFamily.match(/SiYuanCustomFont-[a-f0-9]{64}/g)?.forEach(family => families.add(family));
+ });
+ }
+ if (families.size === 0) {
return "";
}
const customFonts = (await loadCustomFonts()).filter((font) => isValidCustomFont(font) && families.has(font.family));
@@ -126,11 +173,14 @@ export const getExportCustomFontStyle = async (fonts: Array<{family: string}>) =
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
- return `@font-face { font-family: "${font.family}"; src: url("${dataURL}"); font-style: normal; font-weight: ${Math.max(1, Math.min(1000, font.weight || 400))}; }`;
+ return getCustomFontCSS(font, dataURL);
}));
return styles.join("\n");
};
+const getCustomFontCSS = (font: ICustomFont, source: string) =>
+ `@font-face { font-family: "${font.family}"; src: url("${source}"); font-style: normal; font-weight: ${Math.max(1, Math.min(1000, font.weight || 400))}; font-display: swap; }`;
+
const setCustomFontStyle = (font: ICustomFont) => {
let styleElement = document.getElementById(`customFontStyle-${font.id}`) as HTMLStyleElement;
if (!styleElement) {
diff --git a/app/src/util/systemFont.test.ts b/app/src/util/systemFont.test.ts
index bb082b74fa..54fb4fb264 100644
--- a/app/src/util/systemFont.test.ts
+++ b/app/src/util/systemFont.test.ts
@@ -1,6 +1,84 @@
-import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {getFontFamilyDisplayName, getUniqueFontFamilies} from "./systemFontCore";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {describe, it, test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, transpileModule} from "typescript";
+import {getFontFamilyDisplayName, getUniqueFontFamilies, parseSystemFontsJSON} from "./systemFontCore";
+
+const font = {family: "HarmonyOS Sans", displayName: "HarmonyOS Sans", weight: 400};
+
+const load = (container: string, bridge?: () => Promise<string>, kernel?: () => Promise<unknown>) => {
+ let requests = 0;
+ const exports: {loadSystemFonts?: () => Promise<typeof font[]>} = {};
+ const window = {siyuan: {config: {system: {container}}}, JSHarmony: {getSystemFonts: bridge}};
+ runInNewContext(transpileModule(readFileSync(resolve(process.cwd(), "src/util/systemFont.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+ }).outputText, {
+ exports, window, console: {warn() {}},
+ require: (name: string) => name === "./systemFontCore" ? {parseSystemFontsJSON} : {
+ fetchSyncPost: async () => {
+ requests++;
+ return {data: kernel ? await kernel() : [font]};
+ },
+ },
+ });
+ return {load: () => exports.loadSystemFonts(), requests: () => requests};
+};
+
+test("HarmonyOS lists native families and refreshes after system font installation", async () => {
+ let calls = 0;
+ const harness = load("harmony", async () => {
+ calls++;
+ return JSON.stringify([{...font, family: calls === 1 ? font.family : "Newly Installed"}]);
+ });
+ assert.equal((await harness.load())[0].family, font.family);
+ assert.equal((await harness.load())[0].family, "Newly Installed");
+ assert.equal(harness.requests(), 0);
+});
+
+test("concurrent HarmonyOS pickers share one native enumeration", async () => {
+ let calls = 0;
+ const harness = load("harmony", async () => {
+ calls++;
+ return JSON.stringify([font]);
+ });
+ await Promise.all([harness.load(), harness.load()]);
+ assert.equal(calls, 1);
+});
+
+test("older HarmonyOS containers and native failures retain the kernel fallback", async () => {
+ const missing = load("harmony");
+ assert.equal((await missing.load())[0].family, font.family);
+ assert.equal(missing.requests(), 1);
+ for (const result of ["[]", "null", "invalid", '[{"family": "Invalid"}]']) {
+ const harness = load("harmony", async () => result);
+ assert.equal((await harness.load())[0].family, font.family);
+ assert.equal(harness.requests(), 1);
+ }
+ let calls = 0;
+ const retry = load("harmony", async () => {
+ if (++calls === 1) throw new Error("native unavailable");
+ return JSON.stringify([font]);
+ });
+ await retry.load();
+ await retry.load();
+ assert.equal(calls, 2);
+ assert.equal(retry.requests(), 1);
+});
+
+test("other containers retain cached kernel fonts", async () => {
+ const harness = load("std", async () => { throw new Error("must not call HarmonyOS"); });
+ await Promise.all([harness.load(), harness.load()]);
+ await harness.load();
+ assert.equal(harness.requests(), 1);
+});
+
+test("malformed native entries are skipped without losing valid fonts", () => {
+ assert.deepEqual(parseSystemFontsJSON(JSON.stringify([
+ null, {}, {...font, weight: 0}, {...font, aliases: [1]}, {...font, family: " "}, font,
+ ])), [font]);
+});
describe("getFontFamilyDisplayName", () => {
const fonts = [{
diff --git a/app/src/util/systemFont.ts b/app/src/util/systemFont.ts
index d4ec5d9db9..aec90b4850 100644
--- a/app/src/util/systemFont.ts
+++ b/app/src/util/systemFont.ts
@@ -1,16 +1,36 @@
import {fetchSyncPost} from "./fetch";
import type {IFontItem} from "./systemFontCore";
+import {parseSystemFontsJSON} from "./systemFontCore";
export {getFontFamilyDisplayName, getUniqueFontFamilies} from "./systemFontCore";
export type {IFontItem} from "./systemFontCore";
let systemFontsRequest: Promise<IFontItem[]> | undefined;
+const requestSystemFonts = async () => {
+ if (window.siyuan.config.system.container === "harmony" && window.JSHarmony?.getSystemFonts) {
+ try {
+ const fonts = parseSystemFontsJSON(await window.JSHarmony.getSystemFonts());
+ if (fonts.length > 0) {
+ return fonts;
+ }
+ } catch (error) {
+ console.warn("load HarmonyOS system fonts failed", error);
+ }
+ }
+ const response = await fetchSyncPost("/api/system/getSysFonts");
+ return Array.isArray(response.data) ? response.data as IFontItem[] : [];
+};
+
export const loadSystemFonts = async () => {
if (!systemFontsRequest) {
- systemFontsRequest = fetchSyncPost("/api/system/getSysFonts").then(response =>
- Array.isArray(response.data) ? response.data as IFontItem[] : []
- ).catch(error => {
+ systemFontsRequest = requestSystemFonts().then(fonts => {
+ // 鸿蒙字体可由系统动态安装,仅合并并发请求,后续打开列表时重新枚举。
+ if (window.siyuan.config.system.container === "harmony" || fonts.length === 0) {
+ systemFontsRequest = undefined;
+ }
+ return fonts;
+ }).catch(error => {
systemFontsRequest = undefined;
throw error;
});
diff --git a/app/src/util/systemFontCore.ts b/app/src/util/systemFontCore.ts
index 42292a77c1..71d2de7d1f 100644
--- a/app/src/util/systemFontCore.ts
+++ b/app/src/util/systemFontCore.ts
@@ -7,6 +7,19 @@ export interface IFontItem {
spacing?: string;
}
+export const parseSystemFontsJSON = (json: string): IFontItem[] => {
+ const value: unknown = JSON.parse(json);
+ if (!Array.isArray(value)) {
+ throw new Error("Invalid system font list");
+ }
+ return value.filter((font): font is IFontItem => font && typeof font.family === "string" &&
+ font.family.trim() && typeof font.displayName === "string" &&
+ Number.isInteger(font.weight) && font.weight >= 1 && font.weight <= 1000 &&
+ (font.aliases === undefined || (Array.isArray(font.aliases) &&
+ font.aliases.every((alias: unknown) => typeof alias === "string"))) &&
+ (font.spacing === undefined || typeof font.spacing === "string"));
+};
+
export const getFontFamilyDisplayName = (fonts: IFontItem[], family?: string) => {
if (!family) {
return family;
diff --git a/app/tests/customFont.test.js b/app/tests/customFont.test.js
new file mode 100644
index 0000000000..6d270c4054
--- /dev/null
+++ b/app/tests/customFont.test.js
@@ -0,0 +1,106 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const runCases = async () => {
+ const assert = require("node:assert/strict");
+ const family = "SiYuanCustomFont-" + "a".repeat(64);
+ const unused = "SiYuanCustomFont-" + "b".repeat(64);
+ await window.customFont.ensureSelectedCustomFonts([]);
+ document.body.innerHTML = `<span style="font-family: '${family}'">Readable text</span>`;
+ const loaded = await document.fonts.load(`400 16px "${family}"`, "Readable text");
+ assert.equal(loaded.length, 1);
+ assert.equal(loaded[0].status, "loaded");
+ const html = `<div style="font-family: var(--emoji), '${family}', serif">${unused}</div>` +
+ "<script>window.exportScriptExecuted = true;</script>";
+ const css = await window.customFont.getExportCustomFontStyle([], html);
+ assert.ok(css.includes(family));
+ assert.ok(!css.includes(unused));
+ assert.match(css, /data:font\/ttf;base64,/);
+ assert.equal(window.exportScriptExecuted, undefined);
+ const style = document.createElement("style");
+ style.textContent = css;
+ document.querySelectorAll('[id^="customFontStyle-"]').forEach(element => element.remove());
+ document.head.append(style);
+ // 导出字体使用嵌入数据,不依赖工作空间的字体地址。
+ document.body.innerHTML = `<span style="font-family: '${family}'">Offline text</span>`;
+ const exported = await document.fonts.load(`400 16px "${family}"`, "Offline text");
+ assert.equal(exported.length, 1);
+ assert.equal(exported[0].status, "loaded");
+};
+
+const runElectron = async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const fonts = ["a", "b"].map(character => {
+ const id = character.repeat(64);
+ return {id, family: "SiYuanCustomFont-" + id, displayName: "Imported", weight: 400};
+ });
+ const fontBytes = readFileSync(path.join(__dirname, "../stage/protyle/js/pdf/standard_fonts/LiberationSans-Regular.ttf"));
+ const requests = [];
+ const server = require("node:http").createServer((request, response) => {
+ if (request.url.startsWith("/custom-fonts/")) {
+ requests.push(request.url);
+ response.writeHead(200, {"Content-Type": "font/ttf"});
+ response.end(fontBytes);
+ } else {
+ response.writeHead(200, {"Content-Type": "text/html"});
+ response.end("<!DOCTYPE html><html><head></head><body></body></html>");
+ }
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ let exitCode = 0;
+ try {
+ const ts = require("typescript");
+ const source = ts.transpileModule(readFileSync(path.join(__dirname, "../src/util/customFont.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ await win.loadURL(`http://127.0.0.1:${server.address().port}/stage/build/desktop/`);
+ await win.webContents.executeJavaScript(`(() => {
+ window.siyuan = {config: {system: {container: "harmony"}}};
+ window.customFont = {};
+ new Function("exports", "require", ${JSON.stringify(source)})(window.customFont,
+ () => ({fetchSyncPost: async () => ({code: 0, data: ${JSON.stringify(fonts)}})}));
+ })()`);
+ await win.webContents.executeJavaScript(`(${runCases.toString()})()`);
+ assert.ok(requests.includes(`/custom-fonts/${fonts[0].id}`));
+ assert.ok(!requests.includes(`/custom-fonts/${fonts[1].id}`));
+ console.log("Imported font rendering and offline export passed");
+ } catch (error) {
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ win.destroy();
+ await new Promise(resolve => server.close(resolve));
+ app.exit(exitCode);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ runElectron().catch(error => {
+ console.error(error);
+ require("electron").app.exit(1);
+ });
+} else {
+ require("node:test").it("renders imported inline fonts after reopening and embeds only used fonts in HTML", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+ }, async () => {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-custom-font-"));
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
+ assert.match(stdout, /Imported font rendering and offline export passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-custom-font-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}