An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support setting font family for inline-level text https://github.com/siyuan-note/siyuan/issues/17336
Daniel29d56b431eba
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 952c0268bd..d06dbca8e1 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "fontFamily": "عائلة الخط",+ "mixed": "مختلط","entryDock": "شريط الإرساء","scrollPageUpWithoutMovingCaret": "التمرير شاشة واحدة لأعلى دون تحريك المؤشر","scrollPageDownWithoutMovingCaret": "التمرير شاشة واحدة لأسفل دون تحريك المؤشر",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 118d565d0a..6116092732 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "fontFamily": "Schriftfamilie",+ "mixed": "Gemischt","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Eine Bildschirmseite nach oben scrollen, ohne den Cursor zu bewegen","scrollPageDownWithoutMovingCaret": "Eine Bildschirmseite nach unten scrollen, ohne den Cursor zu bewegen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 3d46f06660..fac36332c5 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "fontFamily": "Font family",+ "mixed": "Mixed","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Scroll up one screen without moving the cursor","scrollPageDownWithoutMovingCaret": "Scroll down one screen without moving the cursor",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex abbe5148a8..375a73927e 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "fontFamily": "Familia tipográfica",+ "mixed": "Mixto","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Desplazarse una pantalla hacia arriba sin mover el cursor","scrollPageDownWithoutMovingCaret": "Desplazarse una pantalla hacia abajo sin mover el cursor",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 7974710ab8..4cb457756b 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "fontFamily": "Famille de polices",+ "mixed": "Mixte","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Faire défiler d’un écran vers le haut sans déplacer le curseur","scrollPageDownWithoutMovingCaret": "Faire défiler d’un écran vers le bas sans déplacer le curseur",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex ad2d75c3d1..da42c5d349 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "fontFamily": "משפחת גופנים",+ "mixed": "מעורב","entryDock": "רציף","scrollPageUpWithoutMovingCaret": "גלילה מסך אחד למעלה מבלי להזיז את הסמן","scrollPageDownWithoutMovingCaret": "גלילה מסך אחד למטה מבלי להזיז את הסמן",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex b2aa6af526..66d519f014 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "fontFamily": "फ़ॉन्ट परिवार",+ "mixed": "मिश्रित","entryDock": "डॉक","scrollPageUpWithoutMovingCaret": "कर्सर को हिलाए बिना एक स्क्रीन ऊपर स्क्रॉल करें","scrollPageDownWithoutMovingCaret": "कर्सर को हिलाए बिना एक स्क्रीन नीचे स्क्रॉल करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 0b00f7a525..3c238dc400 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "fontFamily": "Keluarga font",+ "mixed": "Campuran","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Gulir satu layar ke atas tanpa memindahkan kursor","scrollPageDownWithoutMovingCaret": "Gulir satu layar ke bawah tanpa memindahkan kursor",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex fd01eef1ab..45da8d97cd 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "fontFamily": "Famiglia di caratteri",+ "mixed": "Misto","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Scorri di una schermata verso l'alto senza spostare il cursore","scrollPageDownWithoutMovingCaret": "Scorri di una schermata verso il basso senza spostare il cursore",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 38b45679cd..3836cc95e4 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "fontFamily": "フォントファミリー",+ "mixed": "混在","entryDock": "ドック","scrollPageUpWithoutMovingCaret": "カーソルを移動せずに 1 画面上へスクロール","scrollPageDownWithoutMovingCaret": "カーソルを移動せずに 1 画面下へスクロール",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 5c4cfabfc4..173f78bc24 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "fontFamily": "글꼴 모음",+ "mixed": "혼합","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "커서를 이동하지 않고 한 화면 위로 스크롤","scrollPageDownWithoutMovingCaret": "커서를 이동하지 않고 한 화면 아래로 스크롤",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 07902840cf..60f3625b5c 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "fontFamily": "Lettertypefamilie",+ "mixed": "Gemengd","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Eén scherm omhoog scrollen zonder de cursor te verplaatsen","scrollPageDownWithoutMovingCaret": "Eén scherm omlaag scrollen zonder de cursor te verplaatsen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 5ed2c83476..99f63938cc 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "fontFamily": "Rodzina czcionek",+ "mixed": "Mieszane","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Przewiń o jeden ekran w górę bez przesuwania kursora","scrollPageDownWithoutMovingCaret": "Przewiń o jeden ekran w dół bez przesuwania kursora",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex fdd03bdf8c..efaeb3c64a 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "fontFamily": "Família da fonte",+ "mixed": "Misto","entryDock": "Dock","scrollPageUpWithoutMovingCaret": "Rolar uma tela para cima sem mover o cursor","scrollPageDownWithoutMovingCaret": "Rolar uma tela para baixo sem mover o cursor",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex fa75e522d0..0f4a726540 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "fontFamily": "Семейство шрифтов",+ "mixed": "Смешанный","entryDock": "Док-панель","scrollPageUpWithoutMovingCaret": "Прокрутить на один экран вверх, не перемещая курсор","scrollPageDownWithoutMovingCaret": "Прокрутить на один экран вниз, не перемещая курсор",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex cd8a78e02c..847a839682 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "fontFamily": "Rodina písiem",+ "mixed": "Zmiešané","entryDock": "Dok","scrollPageUpWithoutMovingCaret": "Posunúť o jednu obrazovku nahor bez presunutia kurzora","scrollPageDownWithoutMovingCaret": "Posunúť o jednu obrazovku nadol bez presunutia kurzora",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 2ad639eca5..e099a29f86 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "fontFamily": "ตระกูลฟอนต์",+ "mixed": "ผสม","entryDock": "ด็อก","scrollPageUpWithoutMovingCaret": "เลื่อนขึ้นหนึ่งหน้าจอโดยไม่ย้ายเคอร์เซอร์","scrollPageDownWithoutMovingCaret": "เลื่อนลงหนึ่งหน้าจอโดยไม่ย้ายเคอร์เซอร์",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex edf6a78eb2..4adb9bd06e 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "fontFamily": "Yazı tipi ailesi",+ "mixed": "Karışık","entryDock": "Yuva","scrollPageUpWithoutMovingCaret": "İmleci hareket ettirmeden bir ekran yukarı kaydır","scrollPageDownWithoutMovingCaret": "İmleci hareket ettirmeden bir ekran aşağı kaydır",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 61410916ad..0ec5b05097 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "fontFamily": "Сімейство шрифтів",+ "mixed": "Змішаний","entryDock": "Док","scrollPageUpWithoutMovingCaret": "Прокрутити на один екран угору, не переміщуючи курсор","scrollPageDownWithoutMovingCaret": "Прокрутити на один екран униз, не переміщуючи курсор",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex db773b3db4..09c04ccb31 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "fontFamily": "字体",+ "mixed": "混合","entryDock": "停靠栏","scrollPageUpWithoutMovingCaret": "光标不动向上滚动一屏","scrollPageDownWithoutMovingCaret": "光标不动向下滚动一屏",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex e5e0ae9a11..44a2685a2a 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "fontFamily": "字體",+ "mixed": "混合","entryDock": "停靠欄","scrollPageUpWithoutMovingCaret": "游標不動向上滾動一畫面","scrollPageDownWithoutMovingCaret": "游標不動向下滾動一畫面",diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex 619ec41f43..e832db2d1d 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -36,6 +36,7 @@ import {unregisterCustomFont} from "../../util/customFont";import {showMessage} from "../../dialog/message";+import {IFontItem, loadSystemFonts} from "../../util/systemFont";import {shouldShowBootAppearanceSetting,type IBootAppearanceListItem,@@ -49,15 +50,6 @@ import {genMobileSidePanelSettingHTML, mountMobileSidePanelSetting} from "../../import {genEntryVisibilityHtml, mountEntryVisibility} from "../entryVisibility/ui";/// #endif-interface IFontItem {- id?: string;- family: string;- weight: number;- displayName: string;- aliases?: string[];- spacing?: string;-}-interface IBootAppearanceListData {appearances: IBootAppearanceListItem[];current: IBootAppearanceSelection;@@ -76,11 +68,10 @@ const isCodeFont = (font: Pick<IFontItem, "spacing">) =>const loadAvailableFonts = async () => {const nativeMobile = isNativeMobileContainer();- const [systemResponse, customFonts] = await Promise.all([- fetchSyncPost("/api/system/getSysFonts"),+ const [systemFonts, customFonts] = await Promise.all([+ loadSystemFonts(),nativeMobile ? loadCustomFonts() : Promise.resolve([] as ICustomFont[])]);- const systemFonts = Array.isArray(systemResponse.data) ? systemResponse.data as IFontItem[] : [];return {nativeMobile,customFonts,diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 372a9765b0..796c4e981e 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -60,6 +60,12 @@ import {getTextWithoutSemanticMarkers,stripSemanticMarkersFromRangeText} from "../../protyle/util/inlineElementMarker";+import {+ getInlineFontFamilyLabel,+ getInlineFontFamilyState,+ getInlineFontFamilyValue,+ renderMobileFontFamilyMenu,+} from "../../protyle/toolbar/fontFamilyMenu";type TAndroidBoundedSelection = {container: HTMLElement,@@ -503,6 +509,8 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {lastColorHTML += "</div>";}const {fontSize, baseFontSize} = getFontSizeInfo(protyle, nodeElements);+ const fontFamilyState = getInlineFontFamilyState(protyle, nodeElements);+ const disableFontFamily = disableFont || fontFamilyState.disabled;const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;utilElement.innerHTML = `${lastColorHTML}<div data-id="color" class="keyboard__slash-title">${window.siyuan.languages.color}</div>@@ -537,6 +545,13 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {<span class="keyboard__slash-text">${window.siyuan.languages.clearFontStyle}</span></button></div>+<div data-id="fontFamily" class="keyboard__slash-title${disableFontFamily ? " fn__none" : ""}">${window.siyuan.languages.fontFamily}</div>+<div data-id="fontFamilyWrap" class="keyboard__slash-block${disableFontFamily ? " fn__none" : ""}">+ <button class="keyboard__slash-item" data-action="fontFamilyMenu">+ <span class="keyboard__slash-icon" data-type="fontFamilyPreview">A</span>+ <span class="keyboard__slash-text">${escapeHtml(getInlineFontFamilyLabel(fontFamilyState))}</span>+ </button>+</div><div data-id="fontSize" class="keyboard__slash-title${disableFont ? " fn__none" : ""}">${window.siyuan.languages.fontSize}</div><div data-id="fontSizeWrap" class="keyboard__slash-block${disableFont ? " fn__none" : ""}"><label class="keyboard__font-size-toggle">@@ -553,6 +568,10 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {<span data-type="fontSizeValue">${(parseFloat(fontSize) * 100).toFixed(0)}%</span></label></div>`;+ if (fontFamilyState.family) {+ (utilElement.querySelector('[data-type="fontFamilyPreview"]') as HTMLElement).style.fontFamily =+ getInlineFontFamilyValue(fontFamilyState.family);+ }const switchElement = utilElement.querySelector('[data-id="fontSizeWrap"] .b3-switch') as HTMLInputElement;const fontSizePXElement = utilElement.querySelector('[data-type="fontSizePX"]') as HTMLInputElement;const fontSizeEMElement = utilElement.querySelector('[data-type="fontSizeEM"]') as HTMLInputElement;@@ -1163,6 +1182,42 @@ export const initKeyboardToolbar = () => {const protyle = getCurrentEditor()?.protyle;const target = event.target as HTMLElement;const slashBtnElement = hasClosestByClassName(event.target as HTMLElement, "keyboard__slash-item");+ if (slashBtnElement && slashBtnElement.dataset.action === "fontFamilyMenu") {+ const range = protyle.toolbar.range.cloneRange();+ const nodeElements = getFontNodeElements(protyle);+ const fontFamilyState = getInlineFontFamilyState(protyle, nodeElements);+ const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;+ const isFontFamilyMenuValid = () => getCurrentEditor()?.protyle === protyle &&+ toolbarElement.clientHeight > 100 && range.startContainer.isConnected &&+ range.endContainer.isConnected && toolbarElement.querySelector('.keyboard__action[data-type="text"]')+ ?.classList.contains("protyle-toolbar__item--current") === true;+ preventKeyboardToolbarRender();+ void renderMobileFontFamilyMenu(utilElement, {+ ...fontFamilyState,+ isOpenValid: isFontFamilyMenuValid,+ onBack() {+ if (!isFontFamilyMenuValid()) {+ return;+ }+ protyle.toolbar.range = range;+ renderTextMenu(protyle, toolbarElement);+ focusByRange(range);+ },+ onInteraction: preventKeyboardToolbarRender,+ onSelect(family) {+ if (!isFontFamilyMenuValid()) {+ return;+ }+ protyle.toolbar.range = range;+ fontEvent(protyle, nodeElements, "fontFamily", getInlineFontFamilyValue(family), false);+ renderTextMenu(protyle, toolbarElement);+ focusByRange(protyle.toolbar.range);+ }+ });+ event.preventDefault();+ event.stopPropagation();+ return;+ }if (slashBtnElement && slashBtnElement.dataset.action === "manageInlineStyle") {openInlineStyleDialog(slashBtnElement.dataset.inlineStyleType as TInlineStyleType, () => {renderTextMenu(protyle, toolbarElement);diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.tsindex 7e7ec87ed7..a34387f245 100644--- a/app/src/protyle/toolbar/Font.ts+++ b/app/src/protyle/toolbar/Font.ts@@ -10,7 +10,7 @@ import {SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE,setSubElementSource,} from "./subElementLifecycle";-import {escapeAttr} from "../../util/escape";+import {escapeAttr, escapeHtml} from "../../util/escape";import {decodeStyle1,encodeStyle1,@@ -38,6 +38,13 @@ import {hasSemanticInlineType,stripSemanticMarkersFromRangeText} from "../util/inlineElementMarker";+import {+ getInlineFontFamilyLabel,+ getInlineFontFamilyState,+ getInlineFontFamilyValue,+ openFontFamilyMenu,+} from "./fontFamilyMenu";+import {hasInlineFontFamilyExcludedType} from "./fontFamilyCore";const MAX_RECENT_FONT_STYLES = 14;@@ -150,7 +157,8 @@ export const convertFontSize = (fontSize: string, unit: "px" | "em", baseFontSiz};export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],- onChange?: (type: string, color?: string) => void) => {+ onChange?: (type: string, color?: string) => void,+ fontFamilyElements?: Element[]) => {const builtinStyleLabels: Record<TBuiltinInlineStyleID, string> = {error: window.siyuan.languages.errorStyle,warning: window.siyuan.languages.warningStyle,@@ -252,17 +260,20 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],lastColorHTML += "</div>";}const {fontSize, baseFontSize} = getFontSizeInfo(protyle, nodeElements);+ const fontFamilyState = getInlineFontFamilyState(protyle, fontFamilyElements || nodeElements);+ const disableFontFamily = disableFont || fontFamilyState.disabled;const applyFontStyle = (type: string, color?: string) => {fontEvent(protyle, nodeElements, type, color, true, onChange);};const closeSelectionToolbarAppearance = () => {if (protyle.toolbar.subElement.dataset.subElementSource !== SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE) {- return;+ return false;}protyle.toolbar.subElement.classList.add("fn__none");closeSubElement(protyle.toolbar);protyle.toolbar.render(protyle, protyle.toolbar.range);focusByRange(protyle.toolbar.range);+ return true;};element.innerHTML = `${lastColorHTML}<div class="fn__hr"></div>@@ -294,6 +305,15 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],<button data-type="style2" class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.hollow}" style="-webkit-text-stroke: 0.2px var(--b3-theme-on-background);-webkit-text-fill-color : transparent;">A</button><button data-type="style4" class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.shadow}" style="text-shadow: 1px 1px var(--b3-theme-surface-lighter), 2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), 4px 4px var(--b3-theme-surface-lighter)">A</button></div>+<div class="fn__hr${disableFontFamily ? " fn__none" : ""}"></div>+<div data-id="fontFamily" class="fn__flex${disableFontFamily ? " fn__none" : ""}">+ ${window.siyuan.languages.fontFamily}+ <span class="fn__flex-1"></span>+ <button class="b3-button b3-button--outline fn__flex-center" data-type="fontFamilyMenu">+ <span class="fn__ellipsis" data-type="fontFamilyLabel">${escapeHtml(getInlineFontFamilyLabel(fontFamilyState))}</span>+ <svg><use xlink:href="#iconRight"></use></svg>+ </button>+</div><div class="fn__hr${disableFont ? " fn__none" : ""}"></div><div data-id="fontSize" class="fn__flex${disableFont ? " fn__none" : ""}">${window.siyuan.languages.fontSize}@@ -332,6 +352,25 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],protyle.toolbar.subElement.classList.add("fn__none");protyle.toolbar.element.classList.add("fn__none");openInlineStyleDialog(target.dataset.inlineStyleType as TInlineStyleType);+ } else if (dataType === "fontFamilyMenu") {+ const range = protyle.toolbar.range.cloneRange();+ void openFontFamilyMenu(target, {+ ...fontFamilyState,+ isOpenValid: () => target.isConnected && element.isConnected &&+ protyle.toolbar.subElement.contains(element) &&+ !protyle.toolbar.subElement.classList.contains("fn__none") &&+ range.startContainer.isConnected && range.endContainer.isConnected,+ onSelect(family) {+ if (!range.startContainer.isConnected || !range.endContainer.isConnected) {+ return;+ }+ protyle.toolbar.range = range;+ applyFontStyle("fontFamily", getInlineFontFamilyValue(family));+ if (!closeSelectionToolbarAppearance()) {+ focusByRange(protyle.toolbar.range);+ }+ }+ });} else if (dataType === "style1") {applyFontStyle(dataType, encodeStyle1(target.style.backgroundColor, target.style.color));closeSelectionToolbarAppearance();@@ -394,12 +433,14 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: strfocusRange = true, onChange?: (type: string, color?: string) => void) => {let localFontStyles = window.siyuan.storage[Constants.LOCAL_FONTSTYLES];if (type) {- const value = `${type}${Constants.ZWSP}${color}`;- const recentKey = getRecentInlineStyleKey(value);- localFontStyles = [value, ...localFontStyles.filter((item: string) =>- getRecentInlineStyleKey(item) !== recentKey)].slice(0, MAX_RECENT_FONT_STYLES);- window.siyuan.storage[Constants.LOCAL_FONTSTYLES] = localFontStyles;- setStorageVal(Constants.LOCAL_FONTSTYLES, window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);+ if (type !== "fontFamily") {+ const value = `${type}${Constants.ZWSP}${color}`;+ const recentKey = getRecentInlineStyleKey(value);+ localFontStyles = [value, ...localFontStyles.filter((item: string) =>+ getRecentInlineStyleKey(item) !== recentKey)].slice(0, MAX_RECENT_FONT_STYLES);+ window.siyuan.storage[Constants.LOCAL_FONTSTYLES] = localFontStyles;+ setStorageVal(Constants.LOCAL_FONTSTYLES, window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);+ }} else {const visibleFontStyles = filterHiddenRecentInlineStyles(localFontStyles);if (visibleFontStyles.length === 0) {@@ -422,6 +463,20 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: strreturn;}if (nodeElements && nodeElements.length > 0) {+ if (type === "clear" &&+ protyle.toolbar.setBlockElementsInlineMark(protyle, nodeElements, type, {type: "text"}, true)) {+ if (focusRange) {+ focusByRange(protyle.toolbar.range);+ }+ return;+ }+ if (type === "fontFamily" &&+ protyle.toolbar.setBlockElementsInlineMark(protyle, nodeElements, "text", {type, color})) {+ if (focusRange) {+ focusByRange(protyle.toolbar.range);+ }+ return;+ }updateBatchTransaction(nodeElements, protyle, (e: HTMLElement) => {if (type === "clear") {e.style.color = "";@@ -430,6 +485,7 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: stre.style.textShadow = "";e.style.backgroundColor = "";e.style.fontSize = "";+ e.style.fontFamily = "";e.style.removeProperty("--b3-parent-background");} else if (type === "style1") {const style = decodeStyle1(color);@@ -448,6 +504,9 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: stre.style.setProperty("--b3-parent-background", color);} else if (type === "fontSize") {e.style.fontSize = color;+ } else if (type === "fontFamily" &&+ !["NodeCodeBlock", "NodeMathBlock", "NodeAttributeView"].includes(e.getAttribute("data-type"))) {+ e.style.fontFamily = color;}if ((type === "fontSize" || type === "clear") && e.getAttribute("data-type") === "NodeCodeBlock") {lineNumberRender(e.querySelector(".hljs"));@@ -506,6 +565,12 @@ export const setFontStyle = (textElement: HTMLElement, textOption: ITextOption)case "fontSize":textElement.style.fontSize = textOption.color;break;+ case "fontFamily":+ if (!hasInlineFontFamilyExcludedType(+ (textElement.getAttribute("data-type") || "").split(" ").filter(Boolean))) {+ textElement.style.fontFamily = textOption.color;+ }+ break;case "backgroundColor":textElement.style.backgroundColor = textOption.color;break;@@ -577,7 +642,8 @@ export const hasSameTextStyle = (currentElement: HTMLElement, sideElement: HTMLEsideElement.style.webkitTextStroke === currentElement.style.webkitTextStroke &&sideElement.style.textShadow === currentElement.style.textShadow &&sideElement.style.backgroundColor === currentElement.style.backgroundColor &&- sideElement.style.fontSize === currentElement.style.fontSize) {+ sideElement.style.fontSize === currentElement.style.fontSize &&+ sideElement.style.fontFamily === currentElement.style.fontFamily) {return true;}return false;@@ -591,6 +657,7 @@ export const hasSameTextStyle = (currentElement: HTMLElement, sideElement: HTMLE!sideElement.style.webkitTextStroke &&!sideElement.style.textShadow &&!sideElement.style.fontSize &&+ !sideElement.style.fontFamily &&!sideElement.style.backgroundColor;}if (textObj.type === "color") {@@ -614,6 +681,9 @@ export const hasSameTextStyle = (currentElement: HTMLElement, sideElement: HTMLEif (textObj.type === "fontSize") {return textObj.color === sideElement.style.fontSize;}+ if (textObj.type === "fontFamily") {+ return textObj.color === sideElement.style.fontFamily;+ }}return false;};diff --git a/app/src/protyle/toolbar/FormatPainter.ts b/app/src/protyle/toolbar/FormatPainter.tsindex c4a9cd8898..3a18c45a4a 100644--- a/app/src/protyle/toolbar/FormatPainter.ts+++ b/app/src/protyle/toolbar/FormatPainter.ts@@ -16,12 +16,19 @@ const getSegment = (textNode: Text, editableElement: Element) => {const types: string[] = [];const styles: IFormatPainterStyle = {};let element = textNode.parentElement;+ let fontFamilyAllowed = true;while (element && editableElement.contains(element)) {const elementTypes = (element.getAttribute("data-type") || "").split(" ").filter(Boolean);types.push(...elementTypes);if (elementTypes.includes("inline-math")) {return;}+ if (elementTypes.includes("code") || elementTypes.includes("kbd")) {+ fontFamilyAllowed = false;+ }+ if (fontFamilyAllowed) {+ styles.fontFamily = styles.fontFamily || element.style.fontFamily || undefined;+ }if (elementTypes.includes("text")) {styles.backgroundColor = styles.backgroundColor || element.style.backgroundColor || undefined;styles.color = styles.color || element.style.color || undefined;@@ -35,6 +42,7 @@ const getSegment = (textNode: Text, editableElement: Element) => {element = element.parentElement;}return {+ fontFamilyExcluded: !fontFamilyAllowed,styles,types: [...new Set(types)].filter(type => FORMAT_PAINTER_TYPES.includes(type)),};@@ -50,7 +58,7 @@ export const getFormatPainterSnapshot = (rootElement: Element, range: Range) =>const start = item.range.startContainer === textNode ? item.range.startOffset : 0;const end = item.range.endContainer === textNode ? item.range.endOffset : textNode.data.length;if (start < end && textNode.data.substring(start, end).split(Constants.ZWSP).join("")) {- const segment = getSegment(textNode, item.editableElement);+ const segment = getSegment(textNode, item.blockElement);if (segment) {segments.push(segment);}diff --git a/app/src/protyle/toolbar/fontFamilyCore.test.ts b/app/src/protyle/toolbar/fontFamilyCore.test.tsnew file mode 100644index 0000000000..30850bb234--- /dev/null+++ b/app/src/protyle/toolbar/fontFamilyCore.test.ts@@ -0,0 +1,61 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ getInlineFontFamilyName,+ getInlineFontFamilySelection,+ getInlineFontFamilyStyle,+ hasInlineFontFamilyExcludedType,+} from "./fontFamilyCore";++describe("inline font family", () => {+ it("round-trips font names and preserves the editor fallback stack", () => {+ const family = 'A "quoted" \\ family 字体';+ const value = getInlineFontFamilyStyle(family);+ assert.match(value, /^"Emojis Additional", "Emojis Reset",/);+ assert.match(value, /var\(--b3-font-family-editor\), var\(--b3-font-family\)$/);+ assert.equal(getInlineFontFamilyName(value), family);+ const defaultValue = getInlineFontFamilyStyle();+ assert.equal(defaultValue,+ '"Emojis Additional", "Emojis Reset", var(--b3-font-family-editor), var(--b3-font-family)');+ assert.equal(getInlineFontFamilyName(defaultValue), undefined);+ assert.equal(getInlineFontFamilyName('"Emojis Additional", "Emojis Reset", "Font, Name", serif'),+ "Font, Name");+ assert.equal(getInlineFontFamilyName('"Plain Font", serif'), "Plain Font");+ assert.equal(getInlineFontFamilyName("unset"), undefined);+ assert.equal(getInlineFontFamilyName('"\\ffffff "'), "�");+ });++ it("distinguishes default, uniform and mixed selections", () => {+ assert.deepEqual(getInlineFontFamilySelection([undefined, undefined], true), {+ disabled: false,+ family: undefined,+ mixed: false,+ });+ assert.deepEqual(getInlineFontFamilySelection([+ getInlineFontFamilyStyle("Arial"),+ getInlineFontFamilyStyle("Arial"),+ ], true), {+ disabled: false,+ family: "Arial",+ mixed: false,+ });+ assert.deepEqual(getInlineFontFamilySelection([+ getInlineFontFamilyStyle("Arial"),+ getInlineFontFamilyStyle("Georgia"),+ ], true), {+ disabled: false,+ family: undefined,+ mixed: true,+ });+ });++ it("disables selections without eligible text and recognizes protected inline types", () => {+ assert.deepEqual(getInlineFontFamilySelection([], false), {+ disabled: true,+ family: undefined,+ mixed: false,+ });+ assert.equal(hasInlineFontFamilyExcludedType(["strong", "code", "text"]), true);+ assert.equal(hasInlineFontFamilyExcludedType(["strong", "a", "text"]), false);+ });+});diff --git a/app/src/protyle/toolbar/fontFamilyCore.ts b/app/src/protyle/toolbar/fontFamilyCore.tsnew file mode 100644index 0000000000..b734ebaff0--- /dev/null+++ b/app/src/protyle/toolbar/fontFamilyCore.ts@@ -0,0 +1,91 @@+const INLINE_FONT_FAMILY_PREFIX = '"Emojis Additional", "Emojis Reset"';+const INLINE_FONT_FAMILY_SUFFIX = "var(--b3-font-family-editor), var(--b3-font-family)";++export const INLINE_FONT_FAMILY_EXCLUDED_TYPES = ["code", "kbd", "inline-math"];+export const FONT_FAMILY_EXCLUDED_BLOCK_TYPES = ["NodeCodeBlock", "NodeMathBlock", "NodeAttributeView"];++const escapeCSSString = (value: string) => Array.from(value).map(character => {+ const codePoint = character.codePointAt(0);+ if (character === '"' || character === "\\") {+ return `\\${character}`;+ }+ if (codePoint < 32 || codePoint === 127) {+ return `\\${codePoint.toString(16)} `;+ }+ return character;+}).join("");++const unescapeCSSString = (value: string) => value.replace(/\\([0-9a-fA-F]{1,6})(?:\s)?|\\([\s\S])/g,+ (match, hex: string, escaped: string) => {+ if (!hex) {+ return escaped;+ }+ const codePoint = parseInt(hex, 16);+ return codePoint === 0 || codePoint > 0x10FFFF ? "�" : String.fromCodePoint(codePoint);+ });++export const getInlineFontFamilyStyle = (family?: string) => family ?+ `${INLINE_FONT_FAMILY_PREFIX}, "${escapeCSSString(family)}", ${INLINE_FONT_FAMILY_SUFFIX}` :+ `${INLINE_FONT_FAMILY_PREFIX}, ${INLINE_FONT_FAMILY_SUFFIX}`;++export const getInlineFontFamilyName = (fontFamily?: string) => {+ const value = fontFamily?.trim();+ if (!value) {+ return;+ }+ const families: string[] = [];+ let escaped = false;+ let parentheses = 0;+ let quote = "";+ let start = 0;+ for (let index = 0; index < value.length; index++) {+ const character = value[index];+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (quote) {+ if (character === quote) {+ quote = "";+ }+ } else if (character === '"' || character === "'") {+ quote = character;+ } else if (character === "(") {+ parentheses++;+ } else if (character === ")") {+ parentheses = Math.max(0, parentheses - 1);+ } else if (character === "," && parentheses === 0) {+ families.push(value.slice(start, index));+ start = index + 1;+ }+ }+ families.push(value.slice(start));+ for (const item of families) {+ let family = item.trim();+ if (family.length > 1 && ((family.startsWith('"') && family.endsWith('"')) ||+ (family.startsWith("'") && family.endsWith("'")))) {+ family = family.slice(1, -1);+ }+ family = unescapeCSSString(family);+ const normalized = family.toLowerCase();+ if (family && normalized !== "emojis additional" && normalized !== "emojis reset" &&+ !["inherit", "initial", "revert", "revert-layer", "unset"].includes(normalized) &&+ !normalized.startsWith("var(")) {+ return family;+ }+ }+};++export const hasInlineFontFamilyExcludedType = (types: string[]) =>+ INLINE_FONT_FAMILY_EXCLUDED_TYPES.some(type => types.includes(type));++export const getInlineFontFamilySelection = (fontFamilies: (string | undefined)[], eligible: boolean) => {+ if (!eligible || fontFamilies.length === 0) {+ return {disabled: true, family: undefined, mixed: false};+ }+ const families = [...new Set(fontFamilies.map(getInlineFontFamilyName))];+ if (families.length > 1) {+ return {disabled: false, family: undefined, mixed: true};+ }+ return {disabled: false, family: families[0], mixed: false};+};diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.tsnew file mode 100644index 0000000000..4700e9e35c--- /dev/null+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts@@ -0,0 +1,333 @@+import {Menu} from "../../plugin/Menu";+import {escapeAttr, escapeHtml} from "../../util/escape";+import {getUniqueFontFamilies, IFontItem, loadSystemFonts} from "../../util/systemFont";+import {upDownHint} from "../../util/upDownHint";+import {Constants} from "../../constants";+import {getBlockRanges} from "../util/selection";+import {hasClosestBlock} from "../util/hasClosest";+import {+ FONT_FAMILY_EXCLUDED_BLOCK_TYPES,+ getInlineFontFamilySelection,+ getInlineFontFamilyStyle,+ hasInlineFontFamilyExcludedType,+} from "./fontFamilyCore";++export interface IInlineFontFamilyState {+ disabled: boolean;+ family?: string;+ mixed: boolean;+}++interface IFontFamilyPickerOptions extends IInlineFontFamilyState {+ isOpenValid?: () => boolean;+ onBack?: () => void;+ onClose?: () => void;+ onInteraction?: () => void;+ onSelect: (family?: string) => void;+}++const getNodeFontFamily = (node: Node, root: HTMLElement) => {+ let element = node.nodeType === Node.ELEMENT_NODE ? node as HTMLElement : node.parentElement;+ let fontFamily: string | undefined;+ while (element && root.contains(element)) {+ const types = (element.getAttribute("data-type") || "").split(" ").filter(Boolean);+ if (hasInlineFontFamilyExcludedType(types)) {+ return {excluded: true, fontFamily: undefined};+ }+ const ownFontFamily = element.style.fontFamily;+ if (!fontFamily && ownFontFamily && !["inherit", "unset"].includes(ownFontFamily.trim().toLowerCase())) {+ fontFamily = ownFontFamily;+ }+ if (element === root) {+ break;+ }+ element = element.parentElement;+ }+ return {excluded: false, fontFamily};+};++export const getInlineFontFamilyState = (protyle: IProtyle, nodeElements?: Element[]) => {+ const fontFamilies: (string | undefined)[] = [];+ let eligible = false;+ const collectBoundary = (boundary: HTMLElement, range?: Range) => {+ if (FONT_FAMILY_EXCLUDED_BLOCK_TYPES.includes(boundary.getAttribute("data-type")) ||+ boundary.classList.contains("li")) {+ return;+ }+ let hasVisibleText = false;+ let roots = [boundary];+ if (!range) {+ roots = Array.from(boundary.querySelectorAll<HTMLElement>('[contenteditable="true"]'));+ if (boundary.matches('[contenteditable="true"]')) {+ roots.unshift(boundary);+ }+ if (roots.length === 0) {+ roots.push(boundary);+ }+ }+ roots.forEach(root => {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let textNode = walker.nextNode() as Text;+ while (textNode) {+ if ((!range || range.intersectsNode(textNode)) &&+ textNode.data.split(Constants.ZWSP).join("")) {+ hasVisibleText = true;+ const info = getNodeFontFamily(textNode, protyle.wysiwyg.element);+ if (!info.excluded) {+ eligible = true;+ fontFamilies.push(info.fontFamily);+ }+ }+ textNode = walker.nextNode() as Text;+ }+ });+ if (!hasVisibleText && !range && boundary.tagName !== "TD" && boundary.tagName !== "TH") {+ const info = getNodeFontFamily(boundary, protyle.wysiwyg.element);+ if (!info.excluded) {+ eligible = true;+ fontFamilies.push(info.fontFamily);+ }+ }+ };++ if (nodeElements?.length) {+ nodeElements.forEach(item => collectBoundary(item as HTMLElement));+ return getInlineFontFamilySelection(fontFamilies, eligible) as IInlineFontFamilyState;+ }++ const range = protyle.toolbar.range;+ if (range.collapsed) {+ const boundary = hasClosestBlock(range.startContainer);+ if (!boundary || FONT_FAMILY_EXCLUDED_BLOCK_TYPES.includes(boundary.getAttribute("data-type"))) {+ return getInlineFontFamilySelection([], false) as IInlineFontFamilyState;+ }+ let positionNode = range.startContainer;+ if (positionNode.nodeType === Node.ELEMENT_NODE) {+ const children = positionNode.childNodes;+ positionNode = children[Math.max(0, range.startOffset - 1)] || children[range.startOffset] || positionNode;+ }+ const info = getNodeFontFamily(positionNode, protyle.wysiwyg.element);+ return getInlineFontFamilySelection(info.excluded ? [] : [info.fontFamily], !info.excluded) as+ IInlineFontFamilyState;+ }++ getBlockRanges(protyle.wysiwyg.element, range, FONT_FAMILY_EXCLUDED_BLOCK_TYPES).forEach(item => {+ collectBoundary(item.blockElement, item.range);+ });+ return getInlineFontFamilySelection(fontFamilies, eligible) as IInlineFontFamilyState;+};++const genFontListItemHTML = (font: IFontItem | undefined, currentFamily: string | null | undefined, id: string) => {+ const family = font?.family || "";+ const name = font?.displayName || window.siyuan.languages.default;+ const search = font ? [font.family, font.displayName, ...(font.aliases || [])].join("\n").toLowerCase() :+ window.siyuan.languages.default.toLowerCase();+ const selected = currentFamily !== null && family === (currentFamily || "");+ return `<div class="b3-list-item b3-list-item--narrow" data-family="${escapeAttr(family)}" id="${id}" role="option" aria-selected="${selected}">+ <span class="b3-menu__label" data-family="${escapeAttr(family)}" data-name="${escapeAttr(name)}" data-search="${escapeAttr(search)}">${escapeHtml(name)}</span>+ ${selected ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}+</div>`;+};++let pickerID = 0;++const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptions, mobile: boolean) => {+ const currentFamily = options.mixed ? null : options.family;+ const items = [undefined, ...fonts];+ const id = `fontFamilyPicker${++pickerID}`;+ const listID = `${id}List`;+ const searchInput = `<input class="b3-text-field fn__flex-1" data-type="font-family-search" role="combobox" aria-expanded="true" aria-controls="${listID}" aria-label="${escapeAttr(window.siyuan.languages.fontFamily)}" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">`;+ return `<div class="fn__flex-column${mobile ? "" : " b3-menu__filter"}" style="height:100%">+ <div class="fn__flex">+ ${mobile ? `<button class="block__icon block__icon--show fn__flex-center" data-action="fontFamilyBack" aria-label="${escapeAttr(window.siyuan.languages.back)}"><svg><use xlink:href="#iconLeft"></use></svg></button><span class="fn__space"></span>` : ""}+ ${searchInput}+ </div>+ <div class="fn__hr"></div>+ <div class="b3-list fn__flex-1 b3-list--background" data-type="font-family-list" id="${listID}" role="listbox" style="overflow:auto">${items.map((item, index) => genFontListItemHTML(item, currentFamily, `${id}Option${index}`)).join("")}</div>+</div>`;+};++const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions) => {+ const listElement = element.querySelector<HTMLElement>('[data-type="font-family-list"]');+ const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-family-search"]');+ let previewObserver: IntersectionObserver;+ let removalObserver: MutationObserver;+ const syncActiveDescendant = () => {+ const activeElement = listElement.querySelector<HTMLElement>(".b3-list-item--focus");+ if (activeElement) {+ inputElement.setAttribute("aria-activedescendant", activeElement.id);+ } else {+ inputElement.removeAttribute("aria-activedescendant");+ }+ };+ const filterFontList = () => {+ const value = inputElement.value.toLowerCase().trim();+ listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ listElement.querySelectorAll<HTMLElement>(".b3-list-item .b3-menu__label").forEach(item => {+ const visible = !value || item.dataset.search.includes(value);+ item.parentElement.classList.toggle("fn__none", !visible);+ const name = item.dataset.name;+ const index = name.toLowerCase().indexOf(value);+ item.replaceChildren(document.createTextNode(name));+ if (value && index !== -1) {+ const markElement = document.createElement("mark");+ markElement.textContent = name.slice(index, index + value.length);+ item.replaceChildren(+ document.createTextNode(name.slice(0, index)),+ markElement,+ document.createTextNode(name.slice(index + value.length))+ );+ }+ });+ listElement.querySelector<HTMLElement>(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");+ syncActiveDescendant();+ };+ const cleanup = () => {+ previewObserver?.disconnect();+ removalObserver?.disconnect();+ };+ const selectItem = (item: HTMLElement) => {+ options.onInteraction?.();+ cleanup();+ options.onSelect(item.dataset.family || undefined);+ };++ if ("IntersectionObserver" in window) {+ previewObserver = new IntersectionObserver(entries => {+ entries.forEach(entry => {+ const labelElement = (entry.target as HTMLElement).querySelector<HTMLElement>(".b3-menu__label");+ if (!entry.isIntersecting || !labelElement?.dataset.family) {+ labelElement?.style.removeProperty("font-family");+ return;+ }+ labelElement.style.fontFamily = getInlineFontFamilyStyle(labelElement.dataset.family);+ });+ }, {root: listElement});+ listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach(item => previewObserver.observe(item));+ } else {+ listElement.querySelectorAll<HTMLElement>('.b3-menu__label[data-family]:not([data-family=""])').forEach(item => {+ item.style.fontFamily = getInlineFontFamilyStyle(item.dataset.family);+ });+ }+ inputElement.addEventListener("keydown", event => {+ options.onInteraction?.();+ event.stopPropagation();+ if (event.isComposing) {+ return;+ }+ upDownHint(listElement, event);+ syncActiveDescendant();+ if (event.key === "Enter") {+ const item = listElement.querySelector<HTMLElement>(".b3-list-item--focus");+ if (item) {+ selectItem(item);+ }+ } else if (event.key === "Escape") {+ event.preventDefault();+ cleanup();+ if (options.onBack) {+ options.onBack();+ } else {+ window.siyuan.menus.menu.remove();+ options.onClose?.();+ }+ }+ });+ inputElement.addEventListener("input", (event: InputEvent) => {+ options.onInteraction?.();+ if (!event.isComposing) {+ filterFontList();+ }+ });+ inputElement.addEventListener("compositionend", filterFontList);+ listElement.addEventListener("click", event => {+ const item = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item");+ if (item) {+ selectItem(item);+ }+ });+ element.querySelector<HTMLElement>('[data-action="fontFamilyBack"]')?.addEventListener("click", event => {+ options.onInteraction?.();+ event.preventDefault();+ event.stopPropagation();+ cleanup();+ options.onBack?.();+ });+ if (options.onBack) {+ removalObserver = new MutationObserver(() => {+ if (!listElement.isConnected) {+ cleanup();+ }+ });+ removalObserver.observe(element, {childList: true});+ }+ filterFontList();+ return cleanup;+};++const loadFontFamilies = async (currentFamily?: string) => {+ let fonts: IFontItem[] = [];+ try {+ fonts = getUniqueFontFamilies(await loadSystemFonts());+ } catch (error) {+ console.warn("load system fonts failed", error);+ }+ if (currentFamily && !fonts.some(font => font.family === currentFamily)) {+ fonts.unshift({family: currentFamily, displayName: currentFamily, weight: 400});+ }+ return fonts;+};++let desktopRequestID = 0;++export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamilyPickerOptions) => {+ if (options.disabled) {+ return;+ }+ const requestID = ++desktopRequestID;+ const fonts = await loadFontFamilies(options.family);+ if (requestID !== desktopRequestID || !target.isConnected || options.isOpenValid?.() === false) {+ return;+ }+ let cleanup: () => void;+ const menu = new Menu(undefined, () => cleanup?.());+ menu.addItem({+ iconHTML: "",+ type: "empty",+ label: genFontPickerHTML(fonts, options, false),+ bind(element) {+ cleanup = bindFontPicker(element, {+ ...options,+ onClose: () => target.focus(),+ onSelect(family) {+ menu.close();+ options.onSelect(family);+ }+ });+ }+ });+ const rect = target.getBoundingClientRect();+ menu.open({x: rect.right, y: rect.top, h: rect.height});+ menu.element.querySelector(".b3-menu__items")?.setAttribute("style", "overflow: initial");+ menu.element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();+};++let mobileRequestID = 0;++export const renderMobileFontFamilyMenu = async (element: HTMLElement, options: IFontFamilyPickerOptions) => {+ const requestID = ++mobileRequestID;+ element.innerHTML = `<div class="keyboard__slash-title" data-font-family-request="${requestID}">${window.siyuan.languages.loading}</div>`;+ const fonts = await loadFontFamilies(options.family);+ if (requestID !== mobileRequestID || !element.isConnected ||+ !element.querySelector(`[data-font-family-request="${requestID}"]`) || options.isOpenValid?.() === false) {+ return;+ }+ element.innerHTML = genFontPickerHTML(fonts, options, true);+ bindFontPicker(element, options);+ element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();+};++export const getInlineFontFamilyLabel = (state: IInlineFontFamilyState) => state.mixed ?+ window.siyuan.languages.mixed : (state.family || window.siyuan.languages.default);++export const getInlineFontFamilyValue = (family?: string) => getInlineFontFamilyStyle(family);diff --git a/app/src/protyle/toolbar/formatPainter.test.ts b/app/src/protyle/toolbar/formatPainter.test.tsindex 6f9a140146..53d47e1792 100644--- a/app/src/protyle/toolbar/formatPainter.test.ts+++ b/app/src/protyle/toolbar/formatPainter.test.ts@@ -10,13 +10,50 @@ describe("getCommonFormatPainterSnapshot", () => {it("keeps only formats shared by every selected text segment", () => {assert.deepEqual(getCommonFormatPainterSnapshot([{types: ["strong", "em"],- styles: {color: "red", fontSize: "16px"},+ styles: {color: "red", fontFamily: "Arial", fontSize: "16px"},}, {types: ["strong", "u"],- styles: {color: "blue", fontSize: "16px"},+ styles: {color: "blue", fontFamily: "Arial", fontSize: "16px"},}]), {types: ["strong"],- styles: {fontSize: "16px"},+ styles: {fontFamily: "Arial", fontSize: "16px"},+ });+ });++ it("omits mixed or partially missing font families so painting can clear the target family", () => {+ assert.deepEqual(getCommonFormatPainterSnapshot([{+ types: [],+ styles: {fontFamily: "Arial"},+ }, {+ types: [],+ styles: {fontFamily: "Georgia"},+ }]), {+ types: [],+ styles: {},+ });+ assert.deepEqual(getCommonFormatPainterSnapshot([{+ types: [],+ styles: {fontFamily: "Arial"},+ }, {+ types: [],+ styles: {},+ }]), {+ types: [],+ styles: {},+ });+ });++ it("does not let protected inline segments clear a shared font family", () => {+ assert.deepEqual(getCommonFormatPainterSnapshot([{+ types: [],+ styles: {fontFamily: "Arial"},+ }, {+ fontFamilyExcluded: true,+ types: ["code"],+ styles: {},+ }]), {+ types: [],+ styles: {fontFamily: "Arial"},});});diff --git a/app/src/protyle/toolbar/formatPainterCore.ts b/app/src/protyle/toolbar/formatPainterCore.tsindex 5041ad2a6f..0fa537a6b9 100644--- a/app/src/protyle/toolbar/formatPainterCore.ts+++ b/app/src/protyle/toolbar/formatPainterCore.ts@@ -1,6 +1,7 @@export interface IFormatPainterStyle {backgroundColor?: string;color?: string;+ fontFamily?: string;fontSize?: string;shadow?: boolean;hollow?: boolean;@@ -18,6 +19,7 @@ export interface IFormatPainterSnapshot {}export interface IFormatPainterSegment {+ fontFamilyExcluded?: boolean;styles: IFormatPainterStyle;types: string[];}@@ -27,11 +29,13 @@ export const FORMAT_PAINTER_TYPES = ["strong", "em", "u", "s", "mark", "sup", "sconst getCommonStyles = (segments: IFormatPainterSegment[]) => {const styles: IFormatPainterStyle = {};const keys: (keyof IFormatPainterStyle)[] = [- "backgroundColor", "color", "fontSize", "shadow", "hollow"+ "backgroundColor", "color", "fontFamily", "fontSize", "shadow", "hollow"];keys.forEach(key => {- const value = segments[0].styles[key];- if (value && segments.every(item => item.styles[key] === value)) {+ const comparableSegments = key === "fontFamily" ?+ segments.filter(item => !item.fontFamilyExcluded) : segments;+ const value = comparableSegments[0]?.styles[key];+ if (value && comparableSegments.every(item => item.styles[key] === value)) {(styles as Record<keyof IFormatPainterStyle, string | boolean>)[key] = value;}});diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex 3041081447..af69eafec7 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -1,5 +1,10 @@import {Divider} from "./Divider";import {Font, hasSameTextStyle, setFontStyle} from "./Font";+import {+ FONT_FAMILY_EXCLUDED_BLOCK_TYPES,+ hasInlineFontFamilyExcludedType,+ INLINE_FONT_FAMILY_EXCLUDED_TYPES+} from "./fontFamilyCore";import {ToolbarItem} from "./ToolbarItem";import {fixTableRange,@@ -15,7 +20,13 @@ import {IBlockRange,selectAll} from "../util/selection";-import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName, hasClosestByTag} from "../util/hasClosest";+import {+ hasClosestBlock,+ hasClosestByAttribute,+ hasClosestByClassName,+ hasClosestByTag,+ isInEmbedBlock+} from "../util/hasClosest";import {Link} from "./Link";import {setPosition} from "../../util/setPosition";import {transaction, updateBatchTransaction, updateTransaction} from "../wysiwyg/transaction";@@ -28,7 +39,7 @@ import {setStorageVal} from "../util/compatibility";import {upDownHint} from "../../util/upDownHint";-import {highlightRender} from "../render/highlightRender";+import {highlightRender, lineNumberRender} from "../render/highlightRender";import {getContenteditableElement, hasNextSibling, hasPreviousSibling, isEndOfBlock} from "../wysiwyg/getBlock";import {processRender} from "../util/processCode";import {BlockRef} from "./BlockRef";@@ -435,6 +446,9 @@ export class Toolbar {if (snapshot.styles.fontSize) {applyMark("text", {type: "fontSize", color: snapshot.styles.fontSize});}+ if (snapshot.styles.fontFamily) {+ applyMark("text", {type: "fontFamily", color: snapshot.styles.fontFamily});+ }if (snapshot.styles.shadow) {applyMark("text", {type: "style4"});}@@ -520,27 +534,141 @@ export class Toolbar {return this.setRangesInlineMark(protyle, this.getTableCellRanges(cellElements), type, "range", textObj);}+ public setBlockElementsInlineMark(protyle: IProtyle, blockElements: Element[], type: string,+ textObj?: ITextOption, clearBlockStyle = false) {+ const ranges: IBlockRange[] = [];+ const editableElements = new Set<Element>();+ const includeEmpty = type === "text" && textObj?.type === "fontFamily";+ const allowEmptyRanges = includeEmpty || type === "clear";+ const addRange = (blockElement: HTMLElement, editableElement: Element, range: Range) => {+ if (editableElements.has(editableElement) ||+ (!allowEmptyRanges && !stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join(""))) {+ return;+ }+ const position = getSelectionOffset(editableElement, undefined, range);+ editableElements.add(editableElement);+ ranges.push({+ blockElement,+ editableElement,+ range,+ start: position.start,+ end: position.end,+ });+ };+ new Set(blockElements).forEach(blockElement => {+ if (!blockElement.isConnected || !protyle.wysiwyg.element.contains(blockElement)) {+ return;+ }+ const blockRange = document.createRange();+ blockRange.selectNodeContents(blockElement);+ getBlockRanges(protyle.wysiwyg.element, blockRange,+ ["NodeCodeBlock", "NodeMathBlock", "NodeAttributeView"]).forEach(item => {+ addRange(item.blockElement, item.editableElement, item.range);+ });+ const candidateBlocks = [blockElement, ...Array.from(blockElement.querySelectorAll("[data-node-id]"))];+ candidateBlocks.forEach((candidate: HTMLElement) => {+ if (FONT_FAMILY_EXCLUDED_BLOCK_TYPES.includes(candidate.getAttribute("data-type")) ||+ isInEmbedBlock(candidate)) {+ return;+ }+ if (candidate.getAttribute("data-type") === "NodeCallout") {+ const titleElement = candidate.querySelector<HTMLElement>(+ ":scope > .callout-info > .callout-title");+ if (titleElement && !editableElements.has(titleElement)) {+ const range = document.createRange();+ range.selectNodeContents(titleElement);+ addRange(candidate, titleElement, range);+ }+ }+ if (!includeEmpty) {+ return;+ }+ if (candidate.getAttribute("data-type") === "NodeTable") {+ candidate.querySelectorAll("th, td").forEach(editableElement => {+ if (editableElements.has(editableElement)) {+ return;+ }+ const range = document.createRange();+ range.selectNodeContents(editableElement);+ addRange(candidate, editableElement, range);+ });+ return;+ }+ const editableElement = getContenteditableElement(candidate);+ if (!editableElement || hasClosestBlock(editableElement) !== candidate ||+ editableElements.has(editableElement)) {+ return;+ }+ const range = document.createRange();+ range.selectNodeContents(editableElement);+ addRange(candidate, editableElement, range);+ });+ });+ if (ranges.length === 0 && !clearBlockStyle) {+ return includeEmpty ? [] : undefined;+ }++ const currentRange = this.range.cloneRange();+ const currentItem = ranges.find(item => item.editableElement.contains(currentRange.startContainer) &&+ item.editableElement.contains(currentRange.endContainer));+ const currentPosition = currentItem ?+ getSelectionOffset(currentItem.editableElement, undefined, currentRange, true) : undefined;+ const nodes = this.setRangesInlineMark(protyle, ranges, type, "range", textObj, {+ allowCollapsed: includeEmpty,+ clearBlockElements: clearBlockStyle ? blockElements as HTMLElement[] : undefined,+ transactionBlockElements: blockElements as HTMLElement[],+ });+ if (currentItem?.editableElement.isConnected && currentPosition) {+ const restoredRange = focusByOffset(currentItem.editableElement, currentPosition.start,+ currentPosition.end, false, true) as Range;+ if (restoredRange) {+ this.range = restoredRange;+ }+ } else if (currentRange.startContainer.isConnected && currentRange.endContainer.isConnected) {+ this.range = currentRange;+ }+ return nodes;+ }+private setRangesInlineMark(protyle: IProtyle, ranges: IBlockRange[], type: string, action: "range" | "toolbar",- textObj?: ITextOption, options?: {+ textObj?: ITextOption, options?: {+ allowCollapsed?: boolean,+ clearBlockElements?: HTMLElement[],focusRange?: boolean,preserveEnd?: boolean,preserveStart?: boolean,selectedRange?: Range,+ transactionBlockElements?: HTMLElement[],}) {- if (ranges.length === 0) {+ const requestedTransactionBlockElements = [...new Set(options?.transactionBlockElements || [])].filter(item =>+ item.isConnected && protyle.wysiwyg.element.contains(item));+ const transactionBlockElements = requestedTransactionBlockElements.filter(item =>+ !requestedTransactionBlockElements.some(parent => parent !== item && parent.contains(item)));+ const requestedClearBlockElements = [...new Set(options?.clearBlockElements || [])].filter(item =>+ item.isConnected && protyle.wysiwyg.element.contains(item));+ const clearBlockElements = requestedClearBlockElements.filter(item =>+ !requestedClearBlockElements.some(parent => parent !== item && parent.contains(item)));+ if (ranges.length === 0 && clearBlockElements.length === 0) {return;}const actionBtn = action === "toolbar" ? this.element.querySelector(`[data-type="${type}"]`) : undefined;const remove = type === "clear" || actionBtn?.classList.contains("protyle-toolbar__item--current") ||(!textObj && ranges.every(item => this.hasInlineMark(item.editableElement, item.range, type)));- const rangesByBlock = new Map<HTMLElement, typeof ranges>();const visibleOffsets = new Map(ranges.map(item =>[item, getSelectionOffset(item.editableElement, undefined, item.range, true)]));+ const rangesByBlock = new Map<HTMLElement, typeof ranges>();ranges.forEach(item => {- const blockRanges = rangesByBlock.get(item.blockElement) || [];+ const transactionElement = transactionBlockElements.find(element =>+ element === item.blockElement || element.contains(item.blockElement)) || item.blockElement;+ const blockRanges = rangesByBlock.get(transactionElement) || [];blockRanges.push(item);- rangesByBlock.set(item.blockElement, blockRanges);+ rangesByBlock.set(transactionElement, blockRanges);+ });+ clearBlockElements.forEach(item => {+ if (!rangesByBlock.has(item)) {+ rangesByBlock.set(item, []);+ }});const blockElements = Array.from(rangesByBlock.keys());const memoOldHTMLs = type === "inline-memo" ?@@ -548,10 +676,26 @@ export class Toolbar {const newNodes: Node[] = [];let selectionRange: Range;updateBatchTransaction(blockElements, protyle, blockElement => {- rangesByBlock.get(blockElement).forEach(item => {- const range = blockElement.getAttribute("data-type") === "NodeTable" ?+ requestedClearBlockElements.forEach(clearElement => {+ if (clearElement !== blockElement && !blockElement.contains(clearElement)) {+ return;+ }+ clearElement.style.color = "";+ clearElement.style.webkitTextFillColor = "";+ clearElement.style.webkitTextStroke = "";+ clearElement.style.textShadow = "";+ clearElement.style.backgroundColor = "";+ clearElement.style.fontSize = "";+ clearElement.style.fontFamily = "";+ clearElement.style.removeProperty("--b3-parent-background");+ if (clearElement.getAttribute("data-type") === "NodeCodeBlock") {+ lineNumberRender(clearElement.querySelector(".hljs"));+ }+ });+ rangesByBlock.get(blockElement)?.forEach(item => {+ const range = item.blockElement.getAttribute("data-type") === "NodeTable" ?focusByOffset(item.editableElement, item.start, item.end, false) : item.range;- if (!range || range.collapsed) {+ if (!range || (range.collapsed && !options?.allowCollapsed)) {return;}this.range = range;@@ -626,6 +770,14 @@ export class Toolbar {rangeTypes = rangeTypes.concat((this.range.startContainer.parentElement.getAttribute("data-type") || "").split(" "));}const selectText = stripSemanticMarkersFromRangeText(this.range);+ const isInSameExcludedFontFamilyElement = INLINE_FONT_FAMILY_EXCLUDED_TYPES.some(inlineType => {+ const startElement = hasClosestByAttribute(this.range.startContainer, "data-type", inlineType);+ return startElement && startElement ===+ hasClosestByAttribute(this.range.endContainer, "data-type", inlineType);+ });+ if (type === "text" && textObj?.type === "fontFamily" && isInSameExcludedFontFamilyElement) {+ return;+ }let keepZWPS = false;// ctrl+b/u/i https://github.com/siyuan-note/siyuan/issues/14820const rangeStartMarkerLength = getSemanticMarkerPrefixLengthForNode(this.range.startContainer);@@ -851,6 +1003,7 @@ export class Toolbar {item.style.textShadow = "";item.style.backgroundColor = "";item.style.fontSize = "";+ item.style.fontFamily = "";}item.setAttribute("data-type", types.join(" "));if (hasSemanticInlineType(types.join(" "))) {@@ -870,7 +1023,8 @@ export class Toolbar {if (!this.element.classList.contains("fn__none") && type !== "text" && actionBtn) {actionBtn.classList.add("protyle-toolbar__item--current");}- if (selectText === "") {+ if (selectText === "" || (type === "text" && textObj?.type === "fontFamily" &&+ !selectText.split(Constants.ZWSP).join("") && contents.childNodes.length === 0)) {const inlineElement = document.createElement("span");rangeTypes.push(type);@@ -932,6 +1086,11 @@ export class Toolbar {} else if (item.nodeType === 1) {const wasSemanticInline = hasSemanticInlineType(item.getAttribute("data-type"));let types = (item.getAttribute("data-type") || "").split(" ");+ if (type === "text" && textObj?.type === "fontFamily" &&+ hasInlineFontFamilyExcludedType(types)) {+ newNodes.push(item);+ return;+ }for (let i = 0; i < types.length; i++) {// "backslash", "virtual-block-ref", "search-mark" 只能单独存在if (["backslash", "virtual-block-ref", "search-mark"].includes(types[i])) {diff --git a/app/src/protyle/toolbar/tableCell.ts b/app/src/protyle/toolbar/tableCell.tsindex 8ff79804d4..21bbf44c1b 100644--- a/app/src/protyle/toolbar/tableCell.ts+++ b/app/src/protyle/toolbar/tableCell.ts@@ -31,7 +31,7 @@ export const openTableCellAppearance = (protyle: IProtyle, cellElements: HTMLTabconst appearanceElement = appearanceMenu(protyle, [fontElement], (type, color) => {applyTableCellFontStyle(protyle, cells, type, color);onApply?.();- });+ }, cells);protyle.toolbar.subElement.append(appearanceElement);protyle.toolbar.subElement.style.zIndex = (++window.siyuan.zIndex).toString();protyle.toolbar.subElement.classList.remove("fn__none");diff --git a/app/src/util/systemFont.test.ts b/app/src/util/systemFont.test.tsnew file mode 100644index 0000000000..fbe58c1b59--- /dev/null+++ b/app/src/util/systemFont.test.ts@@ -0,0 +1,32 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getUniqueFontFamilies} from "./systemFontCore";++describe("getUniqueFontFamilies", () => {+ it("keeps one regular entry per family and merges searchable aliases", () => {+ assert.deepEqual(getUniqueFontFamilies([{+ family: "Example Sans",+ weight: 700,+ displayName: "Example Sans Bold",+ aliases: ["示例粗体"],+ }, {+ family: "Example Sans",+ weight: 400,+ displayName: "Example Sans",+ aliases: ["示例"],+ }, {+ family: "Another Font",+ weight: 400,+ displayName: "Another Font",+ }]), [{+ family: "Another Font",+ weight: 400,+ displayName: "Another Font",+ }, {+ family: "Example Sans",+ weight: 400,+ displayName: "Example Sans",+ aliases: ["示例粗体", "示例"],+ }]);+ });+});diff --git a/app/src/util/systemFont.ts b/app/src/util/systemFont.tsnew file mode 100644index 0000000000..969e72f49a--- /dev/null+++ b/app/src/util/systemFont.ts@@ -0,0 +1,19 @@+import {fetchSyncPost} from "./fetch";+import type {IFontItem} from "./systemFontCore";++export {getUniqueFontFamilies} from "./systemFontCore";+export type {IFontItem} from "./systemFontCore";++let systemFontsRequest: Promise<IFontItem[]> | undefined;++export const loadSystemFonts = async () => {+ if (!systemFontsRequest) {+ systemFontsRequest = fetchSyncPost("/api/system/getSysFonts").then(response =>+ Array.isArray(response.data) ? response.data as IFontItem[] : []+ ).catch(error => {+ systemFontsRequest = undefined;+ throw error;+ });+ }+ return systemFontsRequest;+};diff --git a/app/src/util/systemFontCore.ts b/app/src/util/systemFontCore.tsnew file mode 100644index 0000000000..e43e84c2f3--- /dev/null+++ b/app/src/util/systemFontCore.ts@@ -0,0 +1,27 @@+export interface IFontItem {+ id?: string;+ family: string;+ weight: number;+ displayName: string;+ aliases?: string[];+ spacing?: string;+}++export const getUniqueFontFamilies = (fonts: IFontItem[]) => {+ const families = new Map<string, IFontItem>();+ fonts.forEach(font => {+ const current = families.get(font.family);+ if (!current) {+ families.set(font.family, {...font});+ return;+ }+ const aliases = [...new Set([...(current.aliases || []), ...(font.aliases || [])])];+ if (current.weight !== 400 && font.weight === 400) {+ families.set(font.family, {...font, aliases});+ } else {+ current.aliases = aliases;+ }+ });+ return Array.from(families.values()).sort((fontA, fontB) =>+ (fontA.displayName || fontA.family).localeCompare(fontB.displayName || fontB.family));+};diff --git a/kernel/model/export.go b/kernel/model/export.goindex bc16af8960..59580835c7 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -1102,9 +1102,11 @@ func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptio}}- if !hasPandocOption(args, "--lua-filter") && "" != pandocRuntime.ColorFilterPath {- args = append(args, "--lua-filter", pandocRuntime.ColorFilterPath)+ filterPath, filterErr := writePandocDocxFilter(tmpDir)+ if nil != filterErr {+ return filterErr}+ args = appendBuiltinPandocDocxFilter(args, filterPath)if !hasPandocOption(args, "--reference-doc") && "" != pandocRuntime.TemplatePath {args = append(args, "--reference-doc", pandocRuntime.TemplatePath)@@ -3224,6 +3226,7 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,luteEngine.SetUnorderedListMarker("-")luteEngine.SetImgTag(imgTag)+ prepareMarkdownFontFamilyTextMarks(tree.Root)renderer := render.NewProtyleExportMdRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)ret = gulu.Str.FromBytes(renderer.Render())returndiff --git a/kernel/model/export_markdown_font_family.go b/kernel/model/export_markdown_font_family.gonew file mode 100644index 0000000000..c11256f079--- /dev/null+++ b/kernel/model/export_markdown_font_family.go@@ -0,0 +1,141 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/html"+)++func prepareMarkdownFontFamilyTextMarks(root *ast.Node) {+ if nil == root {+ return+ }++ var textMarks []*ast.Node+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type {+ textMarks = append(textMarks, node)+ }+ return ast.WalkContinue+ })++ for _, textMark := range textMarks {+ if nil == textMark.Parent {+ continue+ }++ types := strings.Fields(textMark.TextMarkType)+ remainingTypes := make([]string, 0, len(types))+ hasText := false+ hasProtectedType := false+ for _, typ := range types {+ if "text" == typ {+ hasText = true+ continue+ }+ if isFontFamilyProtectedTextMarkType(typ) {+ hasProtectedType = true+ }+ remainingTypes = append(remainingTypes, typ)+ }+ if !hasText || hasProtectedType {+ continue+ }++ style := textMark.IALAttr("style")+ if !hasCSSFontFamily(style) {+ continue+ }++ openTag := `<span data-type="text" style="` + escapeMarkdownHTMLAttribute(style) + `">`+ textMark.InsertBefore(&ast.Node{Type: ast.NodeInlineHTML, Tokens: []byte(openTag)})+ textMark.InsertAfter(&ast.Node{Type: ast.NodeInlineHTML, Tokens: []byte("</span>")})+ if 0 < len(remainingTypes) {+ textMark.TextMarkType = strings.Join(remainingTypes, " ")+ }+ textMark.RemoveIALAttr("style")+ }+}++func isFontFamilyProtectedTextMarkType(typ string) bool {+ return "code" == typ || "kbd" == typ || "inline-math" == typ+}++func hasCSSFontFamily(style string) bool {+ start := 0+ quote := byte(0)+ escaped := false+ parentheses := 0+ for i := 0; i <= len(style); i++ {+ if i == len(style) {+ return isCSSFontFamilyDeclaration(style[start:])+ }++ character := style[i]+ if escaped {+ escaped = false+ continue+ }+ if '\\' == character {+ escaped = true+ continue+ }+ if 0 != quote {+ if quote == character {+ quote = 0+ }+ continue+ }+ if '"' == character || '\'' == character {+ quote = character+ continue+ }+ if '(' == character {+ parentheses+++ continue+ }+ if ')' == character {+ if 0 < parentheses {+ parentheses--+ }+ continue+ }+ if ';' == character && 0 == parentheses {+ if isCSSFontFamilyDeclaration(style[start:i]) {+ return true+ }+ start = i + 1+ }+ }+ return false+}++func isCSSFontFamilyDeclaration(declaration string) bool {+ property, _, found := strings.Cut(declaration, ":")+ return found && strings.EqualFold(strings.TrimSpace(property), "font-family")+}++func escapeMarkdownHTMLAttribute(value string) string {+ value = strings.ReplaceAll(value, "\r\n", "\n")+ value = strings.ReplaceAll(value, "\r", "\n")+ value = html.EscapeHTMLStr(value)+ value = strings.ReplaceAll(value, "|", "|")+ return strings.ReplaceAll(value, "\n", " ")+}diff --git a/kernel/model/export_markdown_font_family_test.go b/kernel/model/export_markdown_font_family_test.gonew file mode 100644index 0000000000..ce9506968e--- /dev/null+++ b/kernel/model/export_markdown_font_family_test.go@@ -0,0 +1,169 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/88250/lute/render"+)++func TestPrepareMarkdownFontFamilyTextMarks(t *testing.T) {+ style := `font-family: "A&B"; color: red;`+ strong := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "text strong",+ TextMarkTextContent: "bold",+ }+ strong.SetIALAttr("style", style)+ strong.SetIALAttr("custom", "kept")+ tree := markdownTextMarkTestTree(strong)+ prepareMarkdownFontFamilyTextMarks(tree.Root)++ if "strong" != strong.TextMarkType {+ t.Fatalf("unexpected remaining text mark types: %q", strong.TextMarkType)+ }+ if "" != strong.IALAttr("style") {+ t.Fatalf("style should be moved to the raw HTML wrapper: %q", strong.IALAttr("style"))+ }+ if "kept" != strong.IALAttr("custom") {+ t.Fatalf("unrelated IAL attribute should be preserved: %q", strong.IALAttr("custom"))+ }+ expectedOpen := `<span data-type="text" style="font-family: "A&B"; color: red;">`+ if nil == strong.Previous || ast.NodeInlineHTML != strong.Previous.Type ||+ expectedOpen != string(strong.Previous.Tokens) {+ t.Fatalf("unexpected opening raw HTML: %q", string(strong.Previous.Tokens))+ }+ if nil == strong.Next || ast.NodeInlineHTML != strong.Next.Type || "</span>" != string(strong.Next.Tokens) {+ t.Fatalf("unexpected closing raw HTML: %q", string(strong.Next.Tokens))+ }++ markdown := renderMarkdownTextMarkTestTree(tree)+ expectedMarkdown := expectedOpen + "**bold**</span>"+ if expectedMarkdown != markdown {+ t.Fatalf("unexpected Markdown export:\nexpected: %q\nactual: %q", expectedMarkdown, markdown)+ }+}++func TestPrepareMarkdownFontFamilyTextMarkPreservesLink(t *testing.T) {+ link := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "text a strong",+ TextMarkTextContent: "link",+ TextMarkAHref: "https://example.com",+ }+ link.SetIALAttr("style", "FONT-FAMILY: serif")+ tree := markdownTextMarkTestTree(link)+ prepareMarkdownFontFamilyTextMarks(tree.Root)++ markdown := renderMarkdownTextMarkTestTree(tree)+ expected := `<span data-type="text" style="FONT-FAMILY: serif">**[link](https://example.com)**</span>`+ if expected != markdown {+ t.Fatalf("unexpected Markdown link export:\nexpected: %q\nactual: %q", expected, markdown)+ }+}++func TestPrepareMarkdownFontFamilyPlainTextMarkEscapesStyle(t *testing.T) {+ textMark := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "text",+ TextMarkTextContent: "plain",+ }+ textMark.SetIALAttr("style", `font-family: "A|B", serif`)+ tree := markdownTextMarkTestTree(textMark)+ prepareMarkdownFontFamilyTextMarks(tree.Root)++ markdown := renderMarkdownTextMarkTestTree(tree)+ expected := `<span data-type="text" style="font-family: "A|B", serif"><span data-type="text">plain</span></span>`+ if expected != markdown {+ t.Fatalf("unexpected plain text Markdown export:\nexpected: %q\nactual: %q", expected, markdown)+ }+}++func TestPrepareMarkdownFontFamilyTextMarksLeavesUnsupportedMarksAlone(t *testing.T) {+ tests := []struct {+ name string+ types string+ style string+ }{+ {name: "no font family", types: "text strong", style: "color: red"},+ {name: "no text", types: "strong", style: "font-family: serif"},+ {name: "protected code", types: "text code", style: "font-family: serif"},+ {name: "protected keyboard", types: "text kbd", style: "font-family: serif"},+ {name: "protected math", types: "text inline-math", style: "font-family: serif"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ textMark := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: test.types,+ TextMarkTextContent: "content",+ }+ textMark.SetIALAttr("style", test.style)+ tree := markdownTextMarkTestTree(textMark)+ prepareMarkdownFontFamilyTextMarks(tree.Root)+ if test.types != textMark.TextMarkType || test.style != textMark.IALAttr("style") {+ t.Fatalf("text mark was unexpectedly changed: types=%q style=%q", textMark.TextMarkType, textMark.IALAttr("style"))+ }+ if nil != textMark.Previous || nil != textMark.Next {+ t.Fatal("raw HTML wrappers were unexpectedly inserted")+ }+ })+ }+}++func TestHasCSSFontFamily(t *testing.T) {+ tests := []struct {+ style string+ want bool+ }{+ {style: "font-family: serif", want: true},+ {style: "color: red; FONT-FAMILY: serif", want: true},+ {style: `background: url("data:text/plain;x-font-family:value")`, want: false},+ {style: "--label: font-family: serif", want: false},+ {style: "color: red", want: false},+ }+ for _, test := range tests {+ if got := hasCSSFontFamily(test.style); test.want != got {+ t.Fatalf("hasCSSFontFamily(%q): expected %t, got %t", test.style, test.want, got)+ }+ }+}++func TestEscapeMarkdownHTMLAttribute(t *testing.T) {+ const value = "font-family: \"A&B<Font>|Fallback\";\r\ncolor: red"+ const expected = "font-family: "A&B<Font>|Fallback"; color: red"+ if actual := escapeMarkdownHTMLAttribute(value); expected != actual {+ t.Fatalf("unexpected escaped attribute:\nexpected: %q\nactual: %q", expected, actual)+ }+}++func markdownTextMarkTestTree(textMark *ast.Node) *parse.Tree {+ root := &ast.Node{Type: ast.NodeDocument}+ paragraph := &ast.Node{Type: ast.NodeParagraph}+ root.AppendChild(paragraph)+ paragraph.AppendChild(textMark)+ return &parse.Tree{Root: root}+}++func renderMarkdownTextMarkTestTree(tree *parse.Tree) string {+ renderer := render.NewProtyleExportMdRenderer(tree, render.NewOptions(), parse.NewOptions())+ return strings.TrimSpace(string(renderer.Render()))+}diff --git a/kernel/model/pandoc_docx_filter.go b/kernel/model/pandoc_docx_filter.gonew file mode 100644index 0000000000..be169ffb6b--- /dev/null+++ b/kernel/model/pandoc_docx_filter.go@@ -0,0 +1,41 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ _ "embed"+ "fmt"+ "os"+ "path/filepath"+)++const pandocDocxFilterName = "siyuan-docx-filter.lua"++//go:embed pandoc_docx_filter.lua+var pandocDocxFilter []byte++func writePandocDocxFilter(dir string) (string, error) {+ filterPath := filepath.Join(dir, pandocDocxFilterName)+ if err := os.WriteFile(filterPath, pandocDocxFilter, 0600); err != nil {+ return "", fmt.Errorf("write pandoc docx filter: %w", err)+ }+ return filterPath, nil+}++func appendBuiltinPandocDocxFilter(args []string, filterPath string) []string {+ return append(args, "--lua-filter", filterPath)+}diff --git a/kernel/model/pandoc_docx_filter.lua b/kernel/model/pandoc_docx_filter.luanew file mode 100644index 0000000000..fd8e33199b--- /dev/null+++ b/kernel/model/pandoc_docx_filter.lua@@ -0,0 +1,494 @@+local CONSUMED_STYLE_PROPERTIES = {+ ["background"] = true,+ ["background-color"] = true,+ ["color"] = true,+ ["font-family"] = true+}++local INLINE_CONTAINERS = {+ Cite = true,+ Emph = true,+ Link = true,+ Quoted = true,+ SmallCaps = true,+ Span = true,+ Strikeout = true,+ Strong = true,+ Subscript = true,+ Superscript = true,+ Underline = true+}++local function trim(value)+ return value:gsub("^%s*(.-)%s*$", "%1")+end++local function strip_important(value)+ value = trim(value)+ local start = value:lower():find("%s*!%s*important%s*$")+ if start then+ value = trim(value:sub(1, start - 1))+ end+ return value+end++local function xml_escape(value)+ value = value:gsub("&", "&")+ value = value:gsub("<", "<")+ value = value:gsub(">", ">")+ value = value:gsub('"', """)+ value = value:gsub("'", "'")+ return value+end++local function split_css(value, separator)+ local parts = {}+ local quote+ local escaped = false+ local parentheses = 0+ local start = 1+ for index = 1, #value do+ local character = value:sub(index, index)+ if escaped then+ escaped = false+ elseif character == "\\" then+ escaped = true+ elseif quote then+ if character == quote then+ quote = nil+ end+ elseif character == '"' or character == "'" then+ quote = character+ elseif character == "(" then+ parentheses = parentheses + 1+ elseif character == ")" then+ parentheses = math.max(0, parentheses - 1)+ elseif character == separator and parentheses == 0 then+ table.insert(parts, value:sub(start, index - 1))+ start = index + 1+ end+ end+ table.insert(parts, value:sub(start))+ return parts+end++local function parse_style(style)+ local properties = {}+ for _, declaration in ipairs(split_css(style, ";")) do+ local key, value = declaration:match("^%s*([%w%-]+)%s*:%s*(.-)%s*$")+ if key and value then+ properties[key:lower()] = value+ end+ end+ return properties+end++local function remaining_style(style)+ if not style then+ return nil+ end+ local declarations = {}+ for _, declaration in ipairs(split_css(style, ";")) do+ local key = declaration:match("^%s*([%w%-]+)%s*:")+ if key and not CONSUMED_STYLE_PROPERTIES[key:lower()] then+ declaration = trim(declaration)+ if declaration ~= "" then+ table.insert(declarations, declaration)+ end+ end+ end+ if #declarations == 0 then+ return nil+ end+ return table.concat(declarations, "; ") .. ";"+end++-- 解析颜色字符串为 6 位大写十六进制(不带 #),支持颜色名、#hex、#rgb、rgb()/rgba()+local function parse_color(value)+ if not value then+ return nil+ end+ local compact = strip_important(value):gsub("%s+", "")+ local lower = compact:lower()+ local named = {+ red = "FF0000", blue = "0000FF", green = "008000",+ yellow = "FFFF00", orange = "FFA500", purple = "800080",+ black = "000000", white = "FFFFFF", gray = "808080", grey = "808080"+ }+ if named[lower] then+ return named[lower]+ end++ local hex6 = lower:match("^#(%x%x%x%x%x%x)$") or lower:match("^(%x%x%x%x%x%x)$")+ if hex6 then+ return hex6:upper()+ end+ local hex3 = lower:match("^#(%x%x%x)$") or lower:match("^(%x%x%x)$")+ if hex3 then+ local red = hex3:sub(1, 1)+ local green = hex3:sub(2, 2)+ local blue = hex3:sub(3, 3)+ return (red .. red .. green .. green .. blue .. blue):upper()+ end++ local red, green, blue = lower:match("^rgb%((%d+),(%d+),(%d+)%)$")+ if red and green and blue then+ local function hex(component)+ local number = math.max(0, math.min(255, tonumber(component) or 0))+ return string.format("%02X", number)+ end+ return hex(red) .. hex(green) .. hex(blue)+ end++ local alpha+ red, green, blue, alpha = lower:match("^rgba%((%d+),(%d+),(%d+),([%d%.]+)%)$")+ if red and green and blue and alpha then+ local opacity = math.max(0, math.min(1, tonumber(alpha) or 1))+ local function composite(component)+ local number = math.floor((opacity * (tonumber(component) or 0) + (1 - opacity) * 255) + 0.5)+ return string.format("%02X", math.max(0, math.min(255, number)))+ end+ return composite(red) .. composite(green) .. composite(blue)+ end+ return nil+end++local function normalize_font_family(value)+ local family = trim(value)+ if #family >= 2 then+ local first = family:sub(1, 1)+ local last = family:sub(-1)+ if (first == '"' and last == '"') or (first == "'" and last == "'") then+ family = family:sub(2, -2)+ end+ end+ return family:gsub("\\(.)", "%1")+end++local function selected_font_family(value)+ if not value then+ return nil+ end+ for _, item in ipairs(split_css(strip_important(value), ",")) do+ local family = normalize_font_family(item)+ local lower = family:lower()+ if lower:match("^var%s*%(%s*%-%-b3%-font%-family%-editor%s*%)$") then+ return nil+ end+ if family ~= "" and lower ~= "emojis additional" and lower ~= "emojis reset" and+ lower ~= "inherit" and lower ~= "initial" and lower ~= "unset" and lower ~= "revert" and+ lower ~= "revert-layer" and not lower:match("^var%s*%(") then+ return family+ end+ end+ return nil+end++local function set_parsed_property(properties, key, raw_value, parser, inherited)+ if raw_value == nil then+ return false+ end+ local value = strip_important(raw_value)+ local lower = value:lower()+ if lower == "inherit" or (inherited and lower == "unset") then+ return true+ end+ properties[key] = parser(value) or false+ return true+end++local function span_properties(style)+ if not style then+ return nil+ end+ local css = parse_style(style)+ local properties = {}+ local consumed = false+ consumed = set_parsed_property(properties, "font_family", css["font-family"], selected_font_family, true) or consumed+ consumed = set_parsed_property(properties, "text_color", css["color"], parse_color, true) or consumed+ local background = css["background-color"]+ if background == nil then+ background = css["background"]+ end+ consumed = set_parsed_property(properties, "background_color", background, parse_color, false) or consumed+ if not consumed then+ return nil+ end+ return properties+end++local function copy_properties(properties)+ local copy = {}+ for key, value in pairs(properties) do+ copy[key] = value+ end+ return copy+end++local function merge_properties(parent, child)+ local merged = copy_properties(parent)+ if child then+ for key, value in pairs(child) do+ merged[key] = value+ end+ end+ return merged+end++local function run_properties_xml(properties)+ local xml = ""+ if properties.code then+ xml = xml .. '<w:rStyle w:val="VerbatimChar"/>'+ elseif properties.hyperlink then+ xml = xml .. '<w:rStyle w:val="Hyperlink"/>'+ end+ if properties.font_family then+ local family = xml_escape(properties.font_family)+ xml = xml .. '<w:rFonts w:ascii="' .. family .. '" w:hAnsi="' .. family ..+ '" w:eastAsia="' .. family .. '" w:cs="' .. family .. '"/>'+ end+ if properties.bold then+ xml = xml .. "<w:b/><w:bCs/>"+ end+ if properties.italic then+ xml = xml .. "<w:i/><w:iCs/>"+ end+ if properties.small_caps then+ xml = xml .. "<w:smallCaps/>"+ end+ if properties.strikeout then+ xml = xml .. "<w:strike/>"+ end+ if properties.text_color then+ xml = xml .. '<w:color w:val="' .. properties.text_color .. '"/>'+ end+ if properties.underline then+ xml = xml .. '<w:u w:val="single"/>'+ end+ if properties.background_color then+ xml = xml .. '<w:shd w:val="clear" w:color="auto" w:fill="' .. properties.background_color .. '"/>'+ end+ if properties.vertical_align then+ xml = xml .. '<w:vertAlign w:val="' .. properties.vertical_align .. '"/>'+ end+ return xml+end++local function text_run(text, properties)+ text = text:gsub("\r\n", "\n"):gsub("\r", "\n")+ local preserve = text:match("^%s") or text:match("%s$") or text:match(" ")+ local space_attribute = preserve and ' xml:space="preserve"' or ""+ local xml = '<w:r><w:rPr>' .. run_properties_xml(properties) .. '</w:rPr><w:t' .. space_attribute .. '>' ..+ xml_escape(text) .. '</w:t></w:r>'+ return pandoc.RawInline("openxml", xml)+end++local function break_run(properties)+ local xml = '<w:r><w:rPr>' .. run_properties_xml(properties) .. '</w:rPr><w:br/></w:r>'+ return pandoc.RawInline("openxml", xml)+end++local function has_attributes(attributes)+ for _ in pairs(attributes) do+ return true+ end+ return false+end++local function preserve_span(element, content)+ element.content = pandoc.Inlines(content)+ element.attributes.style = remaining_style(element.attributes.style)+ if element.identifier == "" and #element.classes == 0 and not has_attributes(element.attributes) then+ return element.content+ end+ return {element}+end++local function has_class(element, name)+ for _, class_name in ipairs(element.classes) do+ if class_name == name then+ return true+ end+ end+ return false+end++local transform_inlines++local function transform_inline(inline, properties)+ local inline_type = inline.t+ if inline_type == "Str" then+ return {text_run(inline.text, properties)}+ elseif inline_type == "Space" or inline_type == "SoftBreak" then+ return {text_run(" ", properties)}+ elseif inline_type == "LineBreak" then+ return {break_run(properties)}+ elseif inline_type == "Code" then+ local code_properties = copy_properties(properties)+ code_properties.code = true+ code_properties.font_family = false+ return {text_run(inline.text, code_properties)}+ elseif inline_type == "Strong" or inline_type == "Emph" or inline_type == "Underline" or+ inline_type == "Strikeout" or inline_type == "Superscript" or inline_type == "Subscript" or+ inline_type == "SmallCaps" then+ local semantic_properties = copy_properties(properties)+ if inline_type == "Strong" then+ semantic_properties.bold = true+ elseif inline_type == "Emph" then+ semantic_properties.italic = true+ elseif inline_type == "Underline" then+ semantic_properties.underline = true+ elseif inline_type == "Strikeout" then+ semantic_properties.strikeout = true+ elseif inline_type == "Superscript" then+ semantic_properties.vertical_align = "superscript"+ elseif inline_type == "Subscript" then+ semantic_properties.vertical_align = "subscript"+ elseif inline_type == "SmallCaps" then+ semantic_properties.small_caps = true+ end+ return transform_inlines(inline.content, semantic_properties)+ elseif inline_type == "Quoted" then+ local quote_type = tostring(inline.quotetype):lower()+ local opening = quote_type:find("single", 1, true) and utf8.char(0x2018) or utf8.char(0x201C)+ local closing = quote_type:find("single", 1, true) and utf8.char(0x2019) or utf8.char(0x201D)+ local quoted = {text_run(opening, properties)}+ for _, item in ipairs(transform_inlines(inline.content, properties)) do+ table.insert(quoted, item)+ end+ table.insert(quoted, text_run(closing, properties))+ return quoted+ elseif inline_type == "Link" then+ local link_properties = copy_properties(properties)+ link_properties.hyperlink = true+ inline.content = pandoc.Inlines(transform_inlines(inline.content, link_properties))+ return {inline}+ elseif inline_type == "Span" then+ local nested_properties = merge_properties(properties, span_properties(inline.attributes.style))+ if properties.suppress_font_family or has_class(inline, "kbd") then+ nested_properties.font_family = false+ nested_properties.suppress_font_family = true+ end+ return preserve_span(inline, transform_inlines(inline.content, nested_properties))+ elseif inline_type == "Cite" then+ inline.content = pandoc.Inlines(transform_inlines(inline.content, properties))+ end+ return {inline}+end++transform_inlines = function(inlines, properties)+ local transformed = {}+ for _, inline in ipairs(inlines) do+ for _, item in ipairs(transform_inline(inline, properties)) do+ table.insert(transformed, item)+ end+ end+ return transformed+end++function Span(element)+ local properties = span_properties(element.attributes.style)+ if not properties then+ return nil+ end+ return preserve_span(element, transform_inlines(element.content, properties))+end++local function insert_after_pattern(value, pattern, insertion)+ local _, finish = value:find(pattern)+ if not finish then+ return nil+ end+ return value:sub(1, finish) .. insertion .. value:sub(finish + 1)+end++local function insert_before_pattern(value, pattern, insertion)+ local start = value:find(pattern)+ if not start then+ return nil+ end+ return value:sub(1, start - 1) .. insertion .. value:sub(start)+end++local function insert_run_property(value, property_xml, position)+ if position == "after-fonts" then+ return insert_after_pattern(value, "<w:rFonts [^>]-/>", property_xml) or+ insert_after_pattern(value, "<w:rStyle [^>]-/>", property_xml) or+ insert_after_pattern(value, "<w:rPr>", property_xml)+ elseif position == "after-bold" then+ return insert_after_pattern(value, "<w:bCs/>", property_xml) or+ insert_after_pattern(value, "<w:b/>", property_xml) or+ insert_run_property(value, property_xml, "after-fonts")+ elseif position == "before-color" then+ return insert_before_pattern(value, "<w:color ", property_xml) or+ insert_before_pattern(value, "<w:u ", property_xml) or+ insert_before_pattern(value, "<w:shd ", property_xml) or+ insert_before_pattern(value, "<w:vertAlign ", property_xml) or+ insert_before_pattern(value, "</w:rPr>", property_xml)+ elseif position == "before-shading" then+ return insert_before_pattern(value, "<w:shd ", property_xml) or+ insert_before_pattern(value, "<w:vertAlign ", property_xml) or+ insert_before_pattern(value, "</w:rPr>", property_xml)+ end+ return insert_before_pattern(value, "</w:rPr>", property_xml)+end++local function augment_raw_runs(inlines, property_xml, marker, position)+ for _, inline in ipairs(inlines) do+ if inline.t == "RawInline" and inline.format == "openxml" and+ inline.text:find("<w:r><w:rPr>", 1, true) and not inline.text:find(marker, 1, true) then+ inline.text = insert_run_property(inline.text, property_xml, position)+ elseif INLINE_CONTAINERS[inline.t] then+ augment_raw_runs(inline.content, property_xml, marker, position)+ end+ end+end++local function preserve_semantic_runs(element, property_xml, marker, position)+ augment_raw_runs(element.content, property_xml, marker, position)+ return element+end++local function preserve_link_runs(element)+ local function apply_hyperlink_style(inlines)+ for _, inline in ipairs(inlines) do+ if inline.t == "RawInline" and inline.format == "openxml" and+ inline.text:find("<w:r><w:rPr>", 1, true) and not inline.text:find("<w:rStyle ", 1, true) then+ inline.text = inline.text:gsub("<w:rPr>", '<w:rPr><w:rStyle w:val="Hyperlink"/>', 1)+ elseif INLINE_CONTAINERS[inline.t] then+ apply_hyperlink_style(inline.content)+ end+ end+ end+ apply_hyperlink_style(element.content)+ return element+end++-- 样式 Span 位于 strong 或链接内部时,Pandoc 不会把外层语义应用到原始 OpenXML,需要再补到各个 run+return {+ {traverse = "topdown", Span = Span},+ {+ Strong = function(element)+ return preserve_semantic_runs(element, "<w:b/><w:bCs/>", "<w:b/>", "after-fonts")+ end,+ Emph = function(element)+ return preserve_semantic_runs(element, "<w:i/><w:iCs/>", "<w:i/>", "after-bold")+ end,+ Underline = function(element)+ return preserve_semantic_runs(element, '<w:u w:val="single"/>', "<w:u ", "before-shading")+ end,+ Strikeout = function(element)+ return preserve_semantic_runs(element, "<w:strike/>", "<w:strike/>", "before-color")+ end,+ Superscript = function(element)+ return preserve_semantic_runs(element, '<w:vertAlign w:val="superscript"/>', "<w:vertAlign ", "end")+ end,+ Subscript = function(element)+ return preserve_semantic_runs(element, '<w:vertAlign w:val="subscript"/>', "<w:vertAlign ", "end")+ end,+ SmallCaps = function(element)+ return preserve_semantic_runs(element, "<w:smallCaps/>", "<w:smallCaps/>", "before-color")+ end,+ Link = preserve_link_runs+ }+}diff --git a/kernel/model/pandoc_docx_filter_test.go b/kernel/model/pandoc_docx_filter_test.gonew file mode 100644index 0000000000..7e6b06e94f--- /dev/null+++ b/kernel/model/pandoc_docx_filter_test.go@@ -0,0 +1,48 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "slices"+ "testing"+)++func TestAppendBuiltinPandocDocxFilter(t *testing.T) {+ args := []string{+ "-f", "html+tex_math_dollars",+ "--lua-filter", "custom.lua",+ "--lua-filter=another.lua",+ }+ actual := appendBuiltinPandocDocxFilter(args, "siyuan-docx-filter.lua")+ expected := []string{+ "-f", "html+tex_math_dollars",+ "--lua-filter", "custom.lua",+ "--lua-filter=another.lua",+ "--lua-filter", "siyuan-docx-filter.lua",+ }+ if !slices.Equal(expected, actual) {+ t.Fatalf("unexpected Pandoc arguments:\nexpected: %q\nactual: %q", expected, actual)+ }+}++func TestAppendBuiltinPandocDocxFilterWithoutCustomFilter(t *testing.T) {+ actual := appendBuiltinPandocDocxFilter([]string{"-t", "docx"}, "siyuan-docx-filter.lua")+ expected := []string{"-t", "docx", "--lua-filter", "siyuan-docx-filter.lua"}+ if !slices.Equal(expected, actual) {+ t.Fatalf("unexpected Pandoc arguments:\nexpected: %q\nactual: %q", expected, actual)+ }+}