Skip to content

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

:art: https://github.com/siyuan-note/siyuan/issues/16923

Vanessad48f57508d66
diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scss
index 04e0fcda63..3c09668698 100644
--- a/app/src/assets/scss/business/_config.scss
+++ b/app/src/assets/scss/business/_config.scss
@@ -96,6 +96,19 @@
overflow: visible;
}
+ &-font-family {
+ &__chip {
+ height: 24px;
+ }
+
+ &__text {
+ align-self: stretch;
+ align-items: center;
+ display: flex;
+ line-height: normal;
+ }
+ }
+
&-cloud-space {
position: relative;
flex-wrap: wrap;
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.ts
index 0f39f0ab10..0b5c2ef78e 100644
--- a/app/src/config/tabs/appearanceTab.ts
+++ b/app/src/config/tabs/appearanceTab.ts
@@ -19,7 +19,7 @@ import {confirmDialog} from "../../dialog/confirmDialog";
import {Dialog} from "../../dialog";
import {Menu} from "../../plugin/Menu";
import {escapeAttr, escapeHtml} from "../../util/escape";
-import {genConfigItemMainHtml, genListSwitchItemHtml} from "../render/fragments";
+import {genListSwitchItemHtml} from "../render/fragments";
import {genStackHtml} from "../render/render";
import {controlBoolean} from "../setting/control";
import {editorConfigApi} from "./editorRuntime";
@@ -47,23 +47,29 @@ interface IFontItem {
aliases?: string[];
}
+const getEditorFonts = (editor: Config.IEditor): IFontItem[] => editor.fontFamilies || [];
+
+const getEditorFontDisplay = (fonts: IFontItem[]) =>
+ fonts.map((font) => font.displayName || font.family).join(", ");
+
const registerAppearanceContentGroup = (tab: SettingTabBuilder) => {
const group = tab.group("content", window.siyuan.languages.configGroupContent);
group.slot({
- key: "fontFamily",
+ key: "fontFamilies",
keywords: [window.siyuan.languages.font, window.siyuan.languages.font1],
html: () =>
`<div class="fn__flex b3-label config-item config-wrap">
- ${genConfigItemMainHtml(window.siyuan.languages.font, window.siyuan.languages.font1)}
+ <div class="fn__flex-1 config-item__main">
+ <div class="config-name">${window.siyuan.languages.font}</div>
+ <div class="b3-label__text">${window.siyuan.languages.font1}</div>
+ <div class="b3-chips b3-chips__doctag${getEditorFonts(window.siyuan.config.editor).length === 0 ? " fn__none" : ""}" data-type="selected-fonts">${genSelectedFontListHtml(getEditorFonts(window.siyuan.config.editor))}</div>
+ </div>
<span class="fn__space"></span>
<input
class="b3-select fn__flex-center fn__size200"
- id="editor.fontFamily"
- data-family="${escapeAttr(window.siyuan.config.editor.fontFamily)}"
- data-weight="${window.siyuan.config.editor.fontWeight}"
- data-display="${escapeAttr(window.siyuan.config.editor.fontFamilyDisplay)}"
- value="${escapeAttr(window.siyuan.config.editor.fontFamilyDisplay || window.siyuan.config.editor.fontFamily || window.siyuan.languages.default)}"
+ id="editor.fontFamilies"
+ value="${escapeAttr(getEditorFontDisplay(getEditorFonts(window.siyuan.config.editor)) || window.siyuan.languages.default)}"
readonly
>
</div>`,
@@ -110,13 +116,149 @@ const genFontListItemHtml = (item: IFontItem, checked: boolean) => {
</div>`;
};
+const genSelectedFontListHtml = (fonts: IFontItem[]) => fonts.map((font, index) => `<div class="b3-chip b3-chip--middle config-font-family__chip fn__grab" data-index="${index}" data-family="${escapeAttr(font.family)}" data-weight="${font.weight || 400}">
+ <span class="fn__ellipsis config-font-family__text">${escapeHtml(font.displayName || font.family)}</span>
+ <svg class="b3-chip__close ariaLabel" data-type="font-remove" aria-label="${escapeAttr(window.siyuan.languages.remove)}"><use xlink:href="#iconClose"></use></svg>
+</div>`).join("");
+
+const bindSelectedFontList = (element: HTMLElement, getFonts: () => IFontItem[],
+ persist: (fonts: IFontItem[]) => void) => {
+ element.addEventListener("click", (event) => {
+ const action = (event.target as HTMLElement).closest<HTMLElement>('[data-type="font-remove"]');
+ const chipElement = action?.closest<HTMLElement>(".b3-chip");
+ const index = parseInt(chipElement?.dataset.index, 10);
+ if (!action || !Number.isInteger(index)) {
+ return;
+ }
+ const fonts = [...getFonts()];
+ fonts.splice(index, 1);
+ persist(fonts);
+ });
+ element.addEventListener("mousedown", (event: MouseEvent) => {
+ if (event.button !== 0 || (event.target as HTMLElement).closest('[data-type="font-remove"]')) {
+ return;
+ }
+ const chipElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-chip");
+ if (!chipElement || !element.contains(chipElement)) {
+ return;
+ }
+ event.preventDefault();
+ const fontsBeforeDrag = getFonts();
+ const startX = event.clientX;
+ const startY = event.clientY;
+ const initialRect = chipElement.getBoundingClientRect();
+ const offsetX = startX - initialRect.left;
+ const offsetY = startY - initialRect.top;
+ let dragging = false;
+ let dragClone: HTMLElement;
+ const finishDragging = (upEvent: MouseEvent) => {
+ document.removeEventListener("mousemove", moveChip);
+ document.removeEventListener("mouseup", finishDragging);
+ document.body.style.cursor = "";
+ if (!dragging) {
+ return;
+ }
+ upEvent.preventDefault();
+ upEvent.stopPropagation();
+ dragClone.remove();
+ chipElement.classList.remove("b3-chip--dragging");
+ const fonts = Array.from(element.querySelectorAll<HTMLElement>(".b3-chip")).map((chip) =>
+ fontsBeforeDrag[parseInt(chip.dataset.index, 10)]);
+ if (fonts.some((font, index) => font !== fontsBeforeDrag[index])) {
+ persist(fonts);
+ }
+ };
+ const moveChip = (moveEvent: MouseEvent) => {
+ const deltaX = moveEvent.clientX - startX;
+ const deltaY = moveEvent.clientY - startY;
+ if (!dragging) {
+ if (Math.abs(deltaX) < Constants.SIZE_DRAG_THRESHOLD &&
+ Math.abs(deltaY) < Constants.SIZE_DRAG_THRESHOLD) {
+ return;
+ }
+ dragging = true;
+ dragClone = chipElement.cloneNode(true) as HTMLElement;
+ dragClone.classList.add("b3-chip--dragclone");
+ Object.assign(dragClone.style, {
+ position: "fixed",
+ left: `${moveEvent.clientX - offsetX}px`,
+ top: `${moveEvent.clientY - offsetY}px`,
+ width: `${initialRect.width}px`,
+ height: `${initialRect.height}px`,
+ margin: "0",
+ zIndex: "9999",
+ pointerEvents: "none",
+ transition: "none",
+ });
+ document.body.append(dragClone);
+ chipElement.classList.add("b3-chip--dragging");
+ document.body.style.cursor = "grabbing";
+ }
+ dragClone.style.left = `${moveEvent.clientX - offsetX}px`;
+ dragClone.style.top = `${moveEvent.clientY - offsetY}px`;
+ const targetChip = document.elementFromPoint(moveEvent.clientX, moveEvent.clientY)
+ ?.closest<HTMLElement>(".b3-chip");
+ if (!targetChip || targetChip === chipElement || !element.contains(targetChip)) {
+ return;
+ }
+ const targetRect = targetChip.getBoundingClientRect();
+ const sameRow = moveEvent.clientY >= targetRect.top && moveEvent.clientY <= targetRect.bottom;
+ const after = sameRow ? moveEvent.clientX > targetRect.left + targetRect.width / 2 :
+ moveEvent.clientY > targetRect.top + targetRect.height / 2;
+ if (after) {
+ targetChip.after(chipElement);
+ } else {
+ targetChip.before(chipElement);
+ }
+ };
+ document.addEventListener("mousemove", moveChip);
+ document.addEventListener("mouseup", finishDragging);
+ });
+};
+
const mountAppearanceFontFamily = (root: HTMLElement) => {
- const fontFamilyEl = root.querySelector<HTMLInputElement>(`#${CSS.escape("editor.fontFamily")}`);
- if (!fontFamilyEl) {
+ const fontFamiliesElement = root.querySelector<HTMLInputElement>(`#${CSS.escape("editor.fontFamilies")}`);
+ const selectedListElement = root.querySelector<HTMLElement>('[data-type="selected-fonts"]');
+ if (!fontFamiliesElement || !selectedListElement) {
return;
}
+ let selectedFonts = getEditorFonts(window.siyuan.config.editor);
+ let refreshOpenMenu: (() => void) | undefined;
+ const renderSelectedFonts = () => {
+ selectedListElement.innerHTML = genSelectedFontListHtml(selectedFonts);
+ selectedListElement.classList.toggle("fn__none", selectedFonts.length === 0);
+ selectedListElement.querySelectorAll<HTMLElement>(".b3-chip").forEach((chip) => {
+ const textElement = chip.querySelector<HTMLElement>(".config-font-family__text");
+ if (textElement) {
+ textElement.style.fontFamily = CSS.escape(chip.dataset.family);
+ textElement.style.fontWeight = chip.dataset.weight;
+ }
+ });
+ fontFamiliesElement.value = getEditorFontDisplay(selectedFonts) || window.siyuan.languages.default;
+ };
+ const persistEditorFonts = (fonts: IFontItem[]) => {
+ fetchPost(
+ "/api/setting/setEditor",
+ {
+ ...window.siyuan.config.editor,
+ fontFamilies: fonts.map((font) => ({
+ family: font.family,
+ weight: font.weight,
+ displayName: font.displayName,
+ })),
+ },
+ (response) => {
+ const data = response.data as Config.IEditor;
+ selectedFonts = getEditorFonts(data);
+ editorConfigApi.apply(data);
+ renderSelectedFonts();
+ refreshOpenMenu?.();
+ }
+ );
+ };
+ bindSelectedFontList(selectedListElement, () => selectedFonts, persistEditorFonts);
updateFontInput(window.siyuan.config.editor);
- fontFamilyEl.addEventListener("click", async () => {
+ fontFamiliesElement.addEventListener("click", async () => {
const nativeMobile = isNativeMobileContainer();
let systemResponse: IWebSocketData;
let customFonts: ICustomFont[];
@@ -131,26 +273,22 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
}
const systemFonts = Array.isArray(systemResponse.data) ? systemResponse.data as IFontItem[] : [];
- const curFamily = fontFamilyEl.dataset.family;
- const curWeight = parseInt(fontFamilyEl.dataset.weight || "400", 10);
const fontItems = [...customFonts, ...systemFonts];
- const selectedFont = fontItems.find((item) => item.family === curFamily && item.weight === curWeight);
- if (selectedFont) {
- fontFamilyEl.value = selectedFont.displayName;
- fontFamilyEl.dataset.display = selectedFont.displayName;
- }
- const defaultItemHtml = genFontListItemHtml({
- family: "",
- displayName: window.siyuan.languages.default,
- weight: 400,
- }, curFamily === "");
+ selectedFonts = getEditorFonts(window.siyuan.config.editor).map((selectedFont) =>
+ fontItems.find((font) => font.family === selectedFont.family && font.weight === selectedFont.weight) ||
+ selectedFont);
+ renderSelectedFonts();
const fontItemHtml = fontItems.map((item) =>
- genFontListItemHtml(item, item.family === curFamily && item.weight === curWeight)
+ genFontListItemHtml(item, selectedFonts.some((font) =>
+ font.family === item.family && font.weight === item.weight))
).join("");
const canManageCustomFonts = nativeMobile && !window.siyuan.config.readonly;
const customFontsByID = new Map(customFonts.map((font) => [font.id, font]));
let fontPreviewObserver: IntersectionObserver;
- const fontMenu = new Menu(undefined, () => fontPreviewObserver?.disconnect());
+ const fontMenu = new Menu(undefined, () => {
+ fontPreviewObserver?.disconnect();
+ refreshOpenMenu = undefined;
+ });
fontMenu.addItem({
iconHTML: "",
type: "empty",
@@ -162,11 +300,24 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
${nativeMobile ? `<div class="b3-label__text ft__on-surface" style="margin-top: 8px">${escapeHtml(window.siyuan.languages.fontFileTip)}</div>` : ""}
${canManageCustomFonts ? '<input class="fn__none" data-type="font-file" type="file" accept=".ttf,.otf,font/ttf,font/otf">' : ""}
<div class="fn__hr"></div>
- <div class="b3-list fn__flex-1 b3-list--background">${defaultItemHtml}${fontItemHtml}</div>
+ <div class="b3-list fn__flex-1 b3-list--background" data-type="available-fonts">${fontItemHtml}</div>
</div>`,
bind(element) {
- const listElement = element.querySelector<HTMLElement>(".b3-list");
+ const listElement = element.querySelector<HTMLElement>('[data-type="available-fonts"]');
const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-search"]');
+ const refreshFontMenu = () => {
+ listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {
+ const label = item.querySelector<HTMLElement>(".b3-menu__label");
+ const checked = selectedFonts.some((font) =>
+ font.family === label.dataset.family && font.weight === parseInt(label.dataset.weight, 10));
+ item.querySelector(".b3-menu__checked")?.remove();
+ if (checked) {
+ item.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');
+ }
+ });
+ };
+ refreshOpenMenu = refreshFontMenu;
+ refreshFontMenu();
if ("IntersectionObserver" in window) {
fontPreviewObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
@@ -228,8 +379,7 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
if (event.key === "Enter") {
const itemEl = listElement.querySelector<HTMLElement>(".b3-list-item--focus .b3-menu__label");
if (itemEl) {
- persistEditorFont(fontItemFromElement(itemEl));
- fontMenu.close();
+ toggleEditorFont(fontItemFromElement(itemEl));
}
} else if (event.key === "Escape") {
window.siyuan.menus.menu.remove();
@@ -261,9 +411,8 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
const font = response.data as ICustomFont;
invalidateCustomFonts();
registerCustomFont(font);
- persistEditorFont(font);
+ persistEditorFonts([...selectedFonts.filter((item) => item.family !== font.family), font]);
showMessage(window.siyuan.languages.imported);
- fontMenu.close();
});
});
listElement.addEventListener("click", (event) => {
@@ -295,45 +444,30 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
);
return;
}
- persistEditorFont(fontItemFromElement(itemEl));
- fontMenu.close();
+ toggleEditorFont(fontItemFromElement(itemEl));
});
+
+ function toggleEditorFont(item: IFontItem) {
+ const selected = selectedFonts.some((font) => font.family === item.family && font.weight === item.weight);
+ const fonts = selected ? selectedFonts.filter((font) =>
+ font.family !== item.family || font.weight !== item.weight) :
+ [...selectedFonts.filter((font) => font.family !== item.family), item];
+ persistEditorFonts(fonts);
+ }
}
});
- const rect = fontFamilyEl.getBoundingClientRect();
+ const rect = fontFamiliesElement.getBoundingClientRect();
fontMenu.open({x: rect.left, y: rect.bottom, h: rect.height});
// 内部列表自行滚动,搜索框保持固定
fontMenu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");
fontMenu.element.querySelector<HTMLInputElement>('[data-type="font-search"]').focus();
});
- function persistEditorFont(item: IFontItem) {
- if (fontFamilyEl.dataset.family === item.family &&
- parseInt(fontFamilyEl.dataset.weight || "400", 10) === item.weight) {
- return;
- }
- fetchPost(
- "/api/setting/setEditor",
- {
- ...window.siyuan.config.editor,
- fontFamily: item.family,
- fontWeight: item.weight,
- fontFamilyDisplay: item.displayName,
- },
- (response) => {
- const data = response.data as Config.IEditor;
- editorConfigApi.apply(data);
- updateFontInput(data);
- }
- );
- }
-
function updateFontInput(data: Config.IEditor) {
- fontFamilyEl.value = data.fontFamilyDisplay || data.fontFamily || window.siyuan.languages.default;
- fontFamilyEl.dataset.family = data.fontFamily;
- fontFamilyEl.dataset.weight = String(data.fontWeight || 400);
- fontFamilyEl.style.fontFamily = data.fontFamily;
- fontFamilyEl.style.fontWeight = String(data.fontWeight || 400);
+ selectedFonts = getEditorFonts(data);
+ fontFamiliesElement.style.removeProperty("font-family");
+ fontFamiliesElement.style.removeProperty("font-weight");
+ renderSelectedFonts();
}
};
diff --git a/app/src/config/tabs/editorRuntime.ts b/app/src/config/tabs/editorRuntime.ts
index fabdaf8499..d146047e58 100644
--- a/app/src/config/tabs/editorRuntime.ts
+++ b/app/src/config/tabs/editorRuntime.ts
@@ -5,6 +5,7 @@ import {reloadProtyle} from "../../protyle/util/reload";
import {resize} from "../../protyle/util/resize";
import {createConfigNamespaceApi} from "../util/namespaceApi";
import {shouldResetBottomBacklinkPanel} from "./editorRuntimeState";
+import {objEquals} from "../../util/functions";
const applyEditorConfig = (data: Config.IEditor) => {
const refreshKeepLoadedContent = window.siyuan.config.editor.keepLoadedContent !== data.keepLoadedContent;
@@ -13,8 +14,7 @@ const applyEditorConfig = (data: Config.IEditor) => {
const refreshHeadingNumbers = window.siyuan.config.editor.headingNumber !== data.headingNumber ||
window.siyuan.config.editor.headingNumberFormat !== data.headingNumberFormat;
const remeasureHeadingNumbers = window.siyuan.config.editor.fontSize !== data.fontSize ||
- window.siyuan.config.editor.fontFamily !== data.fontFamily ||
- window.siyuan.config.editor.fontWeight !== data.fontWeight;
+ !objEquals(window.siyuan.config.editor.fontFamilies, data.fontFamilies);
window.siyuan.config.editor = data;
const models = getAllModels();
models.editor.forEach(item => item.updateBacklinkPanel(resetBottomBacklinkPanel));
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 5009d067f4..0cce52cc12 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -668,17 +668,13 @@ declare namespace Config {
*/
floatWindowDelay: number;
/**
- * The font used in the editor
+ * 编辑器字体,按优先级从高到低排列
*/
- fontFamily: string;
- /**
- * The font weight used in the editor, 0 means not set
- */
- fontWeight: number;
- /**
- * Label shown in Settings for the selected editor font (e.g. PostScript name + subfamily). May be empty; falls back to fontFamily in UI when empty.
- */
- fontFamilyDisplay: string;
+ fontFamilies: Array<{
+ family: string;
+ weight: number;
+ displayName: string;
+ }>;
/**
* The font size used in the editor
*/
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index ae5d2bc217..646f670f64 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -21,7 +21,7 @@ import {
import {setCodeTheme} from "../protyle/render/util";
import {getBackend, getFrontend} from "./functions";
import {getWorkspaceName} from "./processTitle";
-import {ensureSelectedCustomFont} from "./customFont";
+import {ensureSelectedCustomFonts} from "./customFont";
import {isCurrentThemeSupported, shouldUnloadThemeScript} from "./themeCompatibility";
let headingNumberMeasurementRefreshTimer: number;
@@ -270,8 +270,9 @@ export const initAssets = () => {
};
export const setInlineStyle = async (set = true, servePath = "../../../") => {
+ const editorFonts = window.siyuan.config.editor.fontFamilies || [];
if (set) {
- await ensureSelectedCustomFont(window.siyuan.config.editor.fontFamily, window.siyuan.config.editor.fontWeight);
+ await ensureSelectedCustomFonts(editorFonts);
}
let style;
// Emojis Reset: 字体中包含了 emoji,需重置
@@ -351,10 +352,12 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {
size-adjust: 92%;
}`;
}
- style += `\n:root { --b3-font-size-editor: ${window.siyuan.config.editor.fontSize}px }
+ const editorFontFamilies = editorFonts.map((font) => CSS.escape(font.family)).join(", ");
+ const editorFontWeight = editorFonts[0]?.weight;
+ style += `\n:root { --b3-font-size-editor: ${window.siyuan.config.editor.fontSize}px; --b3-font-family-editor: ${editorFontFamilies || "var(--b3-font-family-protyle)"} }
.b3-typography code:not(.hljs), .protyle-wysiwyg span[data-type~=code] { font-variant-ligatures: ${window.siyuan.config.editor.codeLigatures ? "normal" : "none"} }${window.siyuan.config.editor.justify ? "\n.protyle-wysiwyg [data-node-id] { text-align: justify }" : ""}`;
- if (window.siyuan.config.editor.fontFamily) {
- style += `\n.b3-typography:not(.b3-typography--default), .protyle-wysiwyg, .protyle-title {${window.siyuan.config.editor.fontWeight ? `font-weight: ${window.siyuan.config.editor.fontWeight};` : ""}font-family: "Emojis Additional", "Emojis Reset", ${CSS.escape(window.siyuan.config.editor.fontFamily)}, var(--b3-font-family)}`;
+ if (editorFontFamilies) {
+ style += `\n.b3-typography:not(.b3-typography--default), .protyle-wysiwyg, .protyle-title {${editorFontWeight ? `font-weight: ${editorFontWeight};` : ""}font-family: "Emojis Additional", "Emojis Reset", var(--b3-font-family-editor), var(--b3-font-family)}`;
}
// pad 端菜单移除显示,如工作空间
if ("ontouchend" in document) {
diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.ts
index a15bda37a6..f95799bb26 100644
--- a/app/src/util/customFont.ts
+++ b/app/src/util/customFont.ts
@@ -102,6 +102,10 @@ 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 setCustomFontStyle = (font: ICustomFont) => {
let styleElement = document.getElementById(`customFontStyle-${font.id}`) as HTMLStyleElement;
if (!styleElement) {
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 747f3d611e..df368a43e8 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -439,6 +439,11 @@ func setEditor(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ if _, ok = arg["fontFamilies"]; !ok && editor.FontFamily == model.Conf.Editor.FontFamily &&
+ editor.FontWeight == model.Conf.Editor.FontWeight {
+ editor.FontFamilies = model.Conf.Editor.FontFamilies
+ }
+ editor.NormalizeFontFamilies()
if "" == editor.PlantUMLServePath {
editor.PlantUMLServePath = "https://www.plantuml.com/plantuml/svg/~1"
diff --git a/kernel/api/system.go b/kernel/api/system.go
index cf49561641..11579dc125 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -472,11 +472,17 @@ func exportConf(c *gin.Context) {
}
if nil != clonedConf.Editor {
clonedConf.Editor.Emoji = []string{}
- if strings.HasPrefix(clonedConf.Editor.FontFamily, util.CustomFontFamilyPrefix) {
- clonedConf.Editor.FontFamily = ""
- clonedConf.Editor.FontWeight = 400
- clonedConf.Editor.FontFamilyDisplay = ""
+ fonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.FontFamilies))
+ for _, font := range clonedConf.Editor.FontFamilies {
+ if nil != font && !strings.HasPrefix(font.Family, util.CustomFontFamilyPrefix) {
+ fonts = append(fonts, font)
+ }
}
+ clonedConf.Editor.FontFamilies = fonts
+ clonedConf.Editor.FontFamily = ""
+ clonedConf.Editor.FontWeight = 400
+ clonedConf.Editor.FontFamilyDisplay = ""
+ clonedConf.Editor.NormalizeFontFamilies()
}
if nil != clonedConf.Export {
clonedConf.Export.PandocBin = ""
@@ -1100,10 +1106,18 @@ func removeCustomFont(c *gin.Context) {
}
var editor *conf.Editor
- if model.Conf.Editor.FontFamily == font.Family {
+ fonts := make([]*conf.EditorFont, 0, len(model.Conf.Editor.FontFamilies))
+ for _, selectedFont := range model.Conf.Editor.FontFamilies {
+ if nil != selectedFont && selectedFont.Family != font.Family {
+ fonts = append(fonts, selectedFont)
+ }
+ }
+ if len(fonts) != len(model.Conf.Editor.FontFamilies) {
+ model.Conf.Editor.FontFamilies = fonts
model.Conf.Editor.FontFamily = ""
model.Conf.Editor.FontWeight = 400
model.Conf.Editor.FontFamilyDisplay = ""
+ model.Conf.Editor.NormalizeFontFamilies()
model.Conf.Save()
editor = model.Conf.Editor
}
diff --git a/kernel/conf/editor.go b/kernel/conf/editor.go
index b96bf8f3d1..f4d5459cc6 100644
--- a/kernel/conf/editor.go
+++ b/kernel/conf/editor.go
@@ -36,14 +36,22 @@ type AssetOpen struct {
ShiftClick string `json:"shiftClick"` // Shift 加单击资源的打开方式
}
+// EditorFont 描述编辑器字体及其显示信息。
+type EditorFont struct {
+ Family string `json:"family"`
+ Weight int `json:"weight"`
+ DisplayName string `json:"displayName"`
+}
+
type Editor struct {
AllowSVGScript bool `json:"allowSVGScript"` // 允许执行 SVG 内脚本
AllowHTMLBLockScript bool `json:"allowHTMLBLockScript"` // 允许执行 HTML 内容中的脚本
FontSize int `json:"fontSize"` // 字体大小
FontSizeScrollZoom bool `json:"fontSizeScrollZoom"` // 字体大小是否支持滚轮缩放
- FontFamily string `json:"fontFamily"` // 字体
- FontWeight int `json:"fontWeight"` // 字重
+ FontFamily string `json:"fontFamily"` // 首选字体(兼容旧版本)
+ FontWeight int `json:"fontWeight"` // 首选字体字重(兼容旧版本)
FontFamilyDisplay string `json:"fontFamilyDisplay"` // 设置面板中展示的字体名称(与 FontFamily/FontWeight 对应,可选)
+ FontFamilies []*EditorFont `json:"fontFamilies"` // 按优先级排列的字体
CodeSyntaxHighlightLineNum bool `json:"codeSyntaxHighlightLineNum"` // 代码块是否显示行号
CodeTabSpaces int `json:"codeTabSpaces"` // 代码块中 Tab 转换空格数,配置为 0 则表示不转换
CodeLineWrap bool `json:"codeLineWrap"` // 代码块是否自动折行
@@ -94,6 +102,41 @@ type Editor struct {
Markdown *util.Markdown `json:"markdown"` // Markdown 配置
}
+// NormalizeFontFamilies 清理字体列表并同步兼容旧版本的首选字体字段。
+func (editor *Editor) NormalizeFontFamilies() {
+ if 1 > len(editor.FontFamilies) && "" != editor.FontFamily {
+ editor.FontFamilies = []*EditorFont{{
+ Family: editor.FontFamily,
+ Weight: editor.FontWeight,
+ DisplayName: editor.FontFamilyDisplay,
+ }}
+ }
+
+ fonts := make([]*EditorFont, 0, len(editor.FontFamilies))
+ families := map[string]bool{}
+ for _, font := range editor.FontFamilies {
+ if nil == font || "" == font.Family || families[font.Family] {
+ continue
+ }
+ families[font.Family] = true
+ if 1 > font.Weight || 1000 < font.Weight {
+ font.Weight = 400
+ }
+ fonts = append(fonts, font)
+ }
+ editor.FontFamilies = fonts
+ if 0 == len(fonts) {
+ editor.FontFamily = ""
+ editor.FontWeight = 400
+ editor.FontFamilyDisplay = ""
+ return
+ }
+
+ editor.FontFamily = fonts[0].Family
+ editor.FontWeight = fonts[0].Weight
+ editor.FontFamilyDisplay = fonts[0].DisplayName
+}
+
const (
MinDynamicLoadBlocks = 48
DefaultHeadingNumberFormat = "decimal-hierarchical"
diff --git a/kernel/conf/editor_test.go b/kernel/conf/editor_test.go
index 7abe43e4d9..6a830b4dcc 100644
--- a/kernel/conf/editor_test.go
+++ b/kernel/conf/editor_test.go
@@ -65,3 +65,46 @@ func TestNormalizeAssetOpen(t *testing.T) {
t.Fatalf("expected app fallback, got %q", assetOpen.ShiftClick)
}
}
+
+func TestNormalizeFontFamiliesMigratesLegacyConfig(t *testing.T) {
+ editor := &Editor{
+ FontFamily: "Inter",
+ FontWeight: 500,
+ FontFamilyDisplay: "Inter Medium",
+ }
+ editor.NormalizeFontFamilies()
+
+ if 1 != len(editor.FontFamilies) {
+ t.Fatalf("expected one migrated font, got %d", len(editor.FontFamilies))
+ }
+ font := editor.FontFamilies[0]
+ if "Inter" != font.Family || 500 != font.Weight || "Inter Medium" != font.DisplayName {
+ t.Fatalf("unexpected migrated font: %+v", font)
+ }
+}
+
+func TestNormalizeFontFamiliesPreservesOrderAndMirrorsFirstFont(t *testing.T) {
+ editor := &Editor{
+ FontFamilies: []*EditorFont{
+ {Family: "Source Han Sans", Weight: 0, DisplayName: "Source Han Sans"},
+ nil,
+ {Family: "Inter", Weight: 500, DisplayName: "Inter Medium"},
+ {Family: "Source Han Sans", Weight: 700, DisplayName: "Duplicate"},
+ },
+ }
+ editor.NormalizeFontFamilies()
+
+ if 2 != len(editor.FontFamilies) {
+ t.Fatalf("expected two normalized fonts, got %d", len(editor.FontFamilies))
+ }
+ if "Source Han Sans" != editor.FontFamilies[0].Family || "Inter" != editor.FontFamilies[1].Family {
+ t.Fatalf("unexpected font order: %+v", editor.FontFamilies)
+ }
+ if 400 != editor.FontFamilies[0].Weight {
+ t.Fatalf("expected invalid weight to use 400, got %d", editor.FontFamilies[0].Weight)
+ }
+ if editor.FontFamily != editor.FontFamilies[0].Family || editor.FontWeight != editor.FontFamilies[0].Weight ||
+ editor.FontFamilyDisplay != editor.FontFamilies[0].DisplayName {
+ t.Fatalf("legacy fields do not mirror the first font: %+v", editor)
+ }
+}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 3b5ffe1ab7..1b1683f493 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -469,6 +469,7 @@ func InitConf() {
Conf.Editor.DatabaseAttrUseTabs = defaultEditor.DatabaseAttrUseTabs
}
Conf.Editor.AssetOpen = conf.NormalizeAssetOpen(Conf.Editor.AssetOpen)
+ Conf.Editor.NormalizeFontFamilies()
Conf.Editor.Emoji = util.FilterRecentIconValues(Conf.Editor.Emoji)
if 9 > Conf.Editor.FontSize || 72 < Conf.Editor.FontSize {
Conf.Editor.FontSize = 16