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 explicit formatting modes for pasted HTML https://github.com/siyuan-note/siyuan/issues/19155
Daniel825b996bfdd5
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex d883258cb1..e41e46bdf1 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "لصق ومطابقة العناصر",+ "pasteAndKeepSourceFormat": "لصق مع الاحتفاظ بتنسيق المصدر","templatePackageMoveTip": "لا يمكن إعادة تسمية مجلدات حزم القوالب أو نقلها","avDragRemoveSorts": "يتعارض هذا النقل مع قواعد الفرز الحالية. هل تريد إزالة قواعد الفرز لهذا العرض وحفظ الترتيب الكامل الناتج عن السحب كترتيب مخصص؟","templateManager": "إدارة القوالب",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex a33b042768..23ef9ea10d 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Einfügen und Elemente anpassen",+ "pasteAndKeepSourceFormat": "Einfügen und Quellformatierung beibehalten","templatePackageMoveTip": "Ordner von Vorlagenpaketen können nicht umbenannt oder verschoben werden","avDragRemoveSorts": "Diese Verschiebung widerspricht den aktuellen Sortierregeln. Möchtest du die Sortierregeln dieser Ansicht entfernen und die vollständige Reihenfolge nach dem Ziehen als benutzerdefinierte Reihenfolge speichern?","templateManager": "Vorlagenverwaltung",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 07f94e0b86..075d0856c6 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Paste and match elements",+ "pasteAndKeepSourceFormat": "Paste and keep source formatting","templatePackageMoveTip": "Template package folders cannot be renamed or moved","avDragRemoveSorts": "This move conflicts with the current sort rules. Remove the sort rules for this view and save the complete order after dragging as the custom order?","templateManager": "Template manager",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 78f6f434ce..bc42ba1fc2 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Pegar y hacer coincidir elementos",+ "pasteAndKeepSourceFormat": "Pegar y conservar el formato de origen","templatePackageMoveTip": "Las carpetas de paquetes de plantillas no se pueden renombrar ni mover","avDragRemoveSorts": "Este movimiento entra en conflicto con las reglas de ordenación actuales. ¿Quieres eliminar las reglas de ordenación de esta vista y guardar el orden completo resultante del arrastre como orden personalizado?","templateManager": "Gestor de plantillas",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 3fefa40241..fedb1c3310 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Coller et harmoniser les éléments",+ "pasteAndKeepSourceFormat": "Coller en conservant la mise en forme source","templatePackageMoveTip": "Les dossiers de paquets de modèles ne peuvent pas être renommés ni déplacés","avDragRemoveSorts": "Ce déplacement est incompatible avec les règles de tri actuelles. Supprimer les règles de tri de cette vue et enregistrer l’ordre complet après le déplacement comme ordre personnalisé ?","templateManager": "Gestionnaire de modèles",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 7236ea5747..80099b0d83 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "הדבק והתאם רכיבים",+ "pasteAndKeepSourceFormat": "הדבק ושמור על עיצוב המקור","templatePackageMoveTip": "לא ניתן לשנות שם או להעביר תיקיות של חבילות תבניות","avDragRemoveSorts": "ההעברה הזו מתנגשת עם כללי המיון הנוכחיים. להסיר את כללי המיון של התצוגה הזו ולשמור את הסדר המלא לאחר הגרירה כסדר מותאם אישית?","templateManager": "מנהל תבניות",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 1e8b40051e..414f8e464e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "तत्वों से मिलान करके चिपकाएँ",+ "pasteAndKeepSourceFormat": "स्रोत स्वरूपण बनाए रखते हुए चिपकाएँ","templatePackageMoveTip": "टेम्पलेट पैकेज फ़ोल्डर का नाम बदलना या उसे स्थानांतरित करना संभव नहीं है","avDragRemoveSorts": "यह स्थानांतरण मौजूदा क्रमबद्ध करने के नियमों से टकराता है। क्या इस दृश्य के क्रमबद्ध करने के नियम हटाकर खींचने के बाद के पूरे क्रम को कस्टम क्रम के रूप में सहेजना है?","templateManager": "टेम्पलेट प्रबंधक",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 3822109073..255a0074ac 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Tempel dan cocokkan elemen",+ "pasteAndKeepSourceFormat": "Tempel dan pertahankan pemformatan sumber","templatePackageMoveTip": "Folder paket templat tidak dapat diganti namanya atau dipindahkan","avDragRemoveSorts": "Pemindahan ini bertentangan dengan aturan pengurutan saat ini. Hapus aturan pengurutan untuk tampilan ini dan simpan urutan lengkap setelah penyeretan sebagai urutan khusus?","templateManager": "Pengelola templat",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 91858efd36..5bd0b8f291 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Incolla e abbina elementi",+ "pasteAndKeepSourceFormat": "Incolla mantenendo la formattazione originale","templatePackageMoveTip": "Le cartelle dei pacchetti di modelli non possono essere rinominate o spostate","avDragRemoveSorts": "Questo spostamento è in conflitto con le regole di ordinamento attuali. Rimuovere le regole di ordinamento di questa vista e salvare l’ordine completo dopo il trascinamento come ordine personalizzato?","templateManager": "Gestione modelli",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 9d6a43d7ba..a55bbd095f 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "要素に合わせて貼り付け",+ "pasteAndKeepSourceFormat": "元の書式を保持して貼り付け","templatePackageMoveTip": "テンプレートパッケージのフォルダーは名前の変更や移動ができません","avDragRemoveSorts": "この移動は現在の並べ替えルールと競合します。このビューの並べ替えルールを削除し、ドラッグ後の全項目の順序をカスタム順序として保存しますか?","templateManager": "テンプレート管理",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 81a5bde840..9defc01772 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "요소에 맞춰 붙여넣기",+ "pasteAndKeepSourceFormat": "원본 서식을 유지하여 붙여넣기","templatePackageMoveTip": "템플릿 패키지 폴더는 이름을 변경하거나 이동할 수 없습니다","avDragRemoveSorts": "이 이동은 현재 정렬 규칙과 충돌합니다. 이 보기의 정렬 규칙을 제거하고 드래그 후의 전체 순서를 사용자 지정 순서로 저장할까요?","templateManager": "템플릿 관리",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 16e1d4fc41..d7577cdf0a 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Plakken en elementen aanpassen",+ "pasteAndKeepSourceFormat": "Plakken met behoud van bronopmaak","templatePackageMoveTip": "Mappen van sjabloonpakketten kunnen niet worden hernoemd of verplaatst","avDragRemoveSorts": "Deze verplaatsing is in strijd met de huidige sorteerregels. Wil je de sorteerregels voor deze weergave verwijderen en de volledige volgorde na het slepen opslaan als aangepaste volgorde?","templateManager": "Sjabloonbeheer",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 302a5826f6..9d3f95232a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Wklej i dopasuj elementy",+ "pasteAndKeepSourceFormat": "Wklej z zachowaniem formatowania źródłowego","templatePackageMoveTip": "Nie można zmieniać nazw ani przenosić folderów pakietów szablonów","avDragRemoveSorts": "To przeniesienie jest sprzeczne z bieżącymi regułami sortowania. Czy usunąć reguły sortowania tego widoku i zapisać pełną kolejność po przeciągnięciu jako kolejność niestandardową?","templateManager": "Menedżer szablonów",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex b419a36350..baad3b0704 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Colar e corresponder elementos",+ "pasteAndKeepSourceFormat": "Colar mantendo a formatação original","templatePackageMoveTip": "As pastas de pacotes de modelos não podem ser renomeadas ou movidas","avDragRemoveSorts": "Este movimento entra em conflito com as regras de ordenação atuais. Remover as regras de ordenação desta visualização e salvar a ordem completa após arrastar como ordem personalizada?","templateManager": "Gerenciador de modelos",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 879c64e472..6f2fd5e46a 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Вставить и согласовать элементы",+ "pasteAndKeepSourceFormat": "Вставить с сохранением исходного форматирования","templatePackageMoveTip": "Папки пакетов шаблонов нельзя переименовывать или перемещать","avDragRemoveSorts": "Это перемещение противоречит текущим правилам сортировки. Удалить правила сортировки для этого представления и сохранить полный порядок после перетаскивания как пользовательский?","templateManager": "Управление шаблонами",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 03203ba29b..082609983e 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Prilepiť a prispôsobiť prvky",+ "pasteAndKeepSourceFormat": "Prilepiť so zachovaním zdrojového formátovania","templatePackageMoveTip": "Priečinky balíkov šablón nemožno premenovať ani presunúť","avDragRemoveSorts": "Tento presun je v rozpore s aktuálnymi pravidlami zoradenia. Odstrániť pravidlá zoradenia tohto zobrazenia a uložiť úplné poradie po presunutí ako vlastné poradie?","templateManager": "Správca šablón",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex c1382959f3..a417021606 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "วางและจับคู่องค์ประกอบ",+ "pasteAndKeepSourceFormat": "วางโดยคงการจัดรูปแบบต้นฉบับ","templatePackageMoveTip": "ไม่สามารถเปลี่ยนชื่อหรือย้ายโฟลเดอร์แพ็กเกจแม่แบบได้","avDragRemoveSorts": "การย้ายนี้ขัดแย้งกับกฎการเรียงลำดับปัจจุบัน ต้องการลบกฎการเรียงลำดับของมุมมองนี้และบันทึกลำดับทั้งหมดหลังการลากเป็นลำดับที่กำหนดเองหรือไม่?","templateManager": "ตัวจัดการแม่แบบ",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 843d37fc2b..2981b51ec6 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Öğeleri eşleştirerek yapıştır",+ "pasteAndKeepSourceFormat": "Kaynak biçimlendirmesini koruyarak yapıştır","templatePackageMoveTip": "Şablon paketi klasörleri yeniden adlandırılamaz veya taşınamaz","avDragRemoveSorts": "Bu taşıma mevcut sıralama kurallarıyla çelişiyor. Bu görünümün sıralama kuralları kaldırılsın ve sürükleme sonrasındaki tam sıra özel sıra olarak kaydedilsin mi?","templateManager": "Şablon yöneticisi",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 54ad9c33e2..0703d6612a 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "Вставити й узгодити елементи",+ "pasteAndKeepSourceFormat": "Вставити зі збереженням вихідного форматування","templatePackageMoveTip": "Папки пакетів шаблонів не можна перейменовувати або переміщувати","avDragRemoveSorts": "Це переміщення суперечить поточним правилам сортування. Видалити правила сортування для цього подання та зберегти повний порядок після перетягування як користувацький?","templateManager": "Керування шаблонами",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 2fce552c5e..f1000e0431 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "粘贴并匹配元素",+ "pasteAndKeepSourceFormat": "粘贴并保留源格式","templatePackageMoveTip": "模板包文件夹不支持重命名或移动","avDragRemoveSorts": "此次拖拽与当前排序规则冲突。是否移除此视图的排序规则,并将拖拽后的完整顺序保存为自定义顺序?","templateManager": "模板管理",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 64cbb36e18..6ccac176b9 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "pasteAndMatchElements": "貼上並匹配元素",+ "pasteAndKeepSourceFormat": "貼上並保留來源格式","templatePackageMoveTip": "範本套件資料夾不支援重新命名或移動","avDragRemoveSorts": "此次拖曳與目前的排序規則衝突。是否移除此檢視的排序規則,並將拖曳後的完整順序儲存為自訂順序?","templateManager": "範本管理",diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.tsindex 7cf29156e5..90fd581902 100644--- a/app/src/boot/globalEvent/commonHotkey.ts+++ b/app/src/boot/globalEvent/commonHotkey.ts@@ -202,7 +202,7 @@ export const syncAppMenuShortcuts = () => {cut: window.siyuan.languages.cut,copy: window.siyuan.languages.copy,paste: window.siyuan.languages.paste,- pasteAndMatchStyle: window.siyuan.languages.appMenuPasteAndMatchStyle,+ pasteAndMatchStyle: window.siyuan.languages.pasteAsPlainText,selectAll: window.siyuan.languages.selectAll,window: window.siyuan.languages.appMenuWindow,minimize: window.siyuan.languages.appMenuMinimize,diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 50dc8e0cd3..ac0d1c4e09 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -311,6 +311,16 @@ test("toolbar catalog follows the default toolbar declaration", () => {assert.equal(children.every((item) => item.simple), true);});+test("inline text paste entries follow the menu order", () => {+ const keys = getEntryCatalogChildren("inline.text").map((item) => item.key);+ const pasteIndex = keys.indexOf("paste");+ assert.deepEqual(keys.slice(pasteIndex, pasteIndex + 3), [+ "paste",+ "pasteAndKeepSourceFormat",+ "pasteAsPlainText",+ ]);+});+test("toolbar catalog follows plugin insertion slots and removes unloaded plugin entries", () => {const defaults = getDefaultToolbar(false).map((item) => typeof item === "string" ? {name: item} : item);const pluginItem = {name: "shared.item"};diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 9b553f00e2..e3c7ff2e2b 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -817,7 +817,8 @@ export const entryCatalog: IEntryCatalogSection[] = [node("cut", lang("cut")),node("delete", lang("delete")),separator("separator_paste"),- node("paste", lang("paste")),+ node("paste", lang("pasteAndMatchElements")),+ node("pasteAndKeepSourceFormat", lang("pasteAndKeepSourceFormat")),node("pasteAsPlainText", lang("pasteAsPlainText")),node("pasteEscaped", lang("pasteEscaped"), false),node("selectAll", lang("selectAll")),diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex 256eeb6464..4ebd8ceb9c 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -36,7 +36,7 @@ import {Constants} from "../constants";import {copyPlainText, readClipboard, setStorageVal, updateHotkeyTip, writeText} from "../protyle/util/compatibility";import {onGet} from "../protyle/util/onGet";import {getAllModels} from "../layout/getAll";-import {paste, pasteAsPlainText, pasteEscaped} from "../protyle/util/paste";+import {paste, pasteAndKeepSourceFormat, pasteAsPlainText, pasteEscaped} from "../protyle/util/paste";/// #if !MOBILEimport {openFileById, updateBacklinkGraph} from "../editor/util";import {openGlobalSearch} from "../search/util";@@ -848,7 +848,7 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {if (!protyle.disabled && !captionElement) {window.siyuan.menus.menu.append(new MenuItem({id: "paste",- label: window.siyuan.languages.paste,+ label: window.siyuan.languages.pasteAndMatchElements,icon: "iconPaste",accelerator: "⌘V",async click() {@@ -865,6 +865,14 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {}}}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "pasteAndKeepSourceFormat",+ label: window.siyuan.languages.pasteAndKeepSourceFormat,+ click() {+ focusByRange(getEditorRange(nodeElement));+ pasteAndKeepSourceFormat(protyle, nodeElement as HTMLElement);+ }+ }).element);window.siyuan.menus.menu.append(new MenuItem({id: "pasteAsPlainText",label: window.siyuan.languages.pasteAsPlainText,diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex b11f4b52fa..c6c5c5fcdd 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -7,7 +7,7 @@ import {isUploadInsertPositionAvailable,} from "../upload/insertPosition";import {processPasteCode, processRender} from "./processCode";-import {getLocalFiles, getTextSiyuanFromTextHTML, readText} from "./compatibility";+import {getLocalFiles, getTextSiyuanFromTextHTML, readClipboard, readText} from "./compatibility";import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "./hasClosest";import {focusByOffset, getEditorRange, getSelectionOffset, getUndoFocusContext} from "./selection";import {blockRender} from "../render/blockRender";@@ -308,6 +308,15 @@ export const pasteAsPlainText = async (protyle: IProtyle) => {}};+export const pasteAndKeepSourceFormat = async (protyle: IProtyle, target: HTMLElement) => {+ try {+ const data = await readClipboard();+ await paste(protyle, {...data, target, preserveSourceFormat: true});+ } catch (error) {+ console.error(error);+ }+};+export const enableLuteMarkdownSyntax = (protyle: IProtyle) => {protyle.lute.SetInlineAsterisk(true);protyle.lute.SetGFMStrikethrough(true);@@ -643,6 +652,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenlet wps = "";let wpsPresentation: IWPSPresentationClipboard | undefined;let officeListConverted = false;+ const preserveSourceFormat = "preserveSourceFormat" in event && event.preserveSourceFormat === true;if ("clipboardData" in event) {textHTML = event.clipboardData.getData("text/html");textPlain = event.clipboardData.getData("text/plain");@@ -1205,6 +1215,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenoffice,officeMathHTML,wps,+ preserveSourceFormat,};if (localAssets.length > 0 || hasHTMLEmbeddedAssets(tempElement)) {try {diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 78203d3a1c..a88c28335f 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -484,6 +484,7 @@ interface IClipboardData {siyuanHTML?: string,files?: FileList | DataTransferItemList | File[],localFiles?: ILocalFiles[],+ preserveSourceFormat?: boolean,}interface IRefDefs {diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex 92ac9742cc..2d51fb4f68 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -127,11 +127,12 @@ func html2BlockDOM(c *gin.Context) {skipInlineSVGAssets, _ := arg["skipInlineSVGAssets"].(bool)preflight, _ := arg["preflight"].(bool)preparedHTML, _ := arg["preparedHTML"].(bool)+ preserveSourceFormat, _ := arg["preserveSourceFormat"].(bool)luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})dom, useHTML := prepareHTMLClipboardContent(luteEngine, dom, text, mathML, office, officeMathHTML, wps,- preparedHTML, convertClipboardMath, convertOfficeHTMLClipboardMath)+ preserveSourceFormat, preparedHTML, convertClipboardMath, convertOfficeHTMLClipboardMath)if !useHTML {if preflight {ret.Data = map[string]any{"converted": true, "dom": dom, "useHTML": false}@@ -339,7 +340,7 @@ type clipboardMathConverter func(mathML, office, wps string) (markdown string, ctype officeHTMLClipboardMathConverter func(officeMathHTML string) (markdown string, converted bool)func prepareHTMLClipboardContent(luteEngine *lute.Lute, dom, text, mathML, office, officeMathHTML, wps string,- preparedHTML bool, mathConverter clipboardMathConverter,+ preserveSourceFormat, preparedHTML bool, mathConverter clipboardMathConverter,officeHTMLMathConverter officeHTMLClipboardMathConverter) (resolvedDOM string, useHTML bool) {if preparedHTML {return dom, true@@ -352,7 +353,9 @@ func prepareHTMLClipboardContent(luteEngine *lute.Lute, dom, text, mathML, offic// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748resolvedDOM = normalizeWPSComments(resolvedDOM, text, wps)resolvedDOM = normalizeMSWordComments(resolvedDOM)- resolvedDOM = normalizeBrowserClipboardStyle(resolvedDOM, office != "" || officeMathHTML != "" || wps != "")+ if !preserveSourceFormat {+ resolvedDOM = matchHTMLClipboardElements(resolvedDOM)+ }return resolvedDOM, true}diff --git a/kernel/api/lute_clipboard_math_test.go b/kernel/api/lute_clipboard_math_test.goindex b039de3ed5..4563ff9444 100644--- a/kernel/api/lute_clipboard_math_test.go+++ b/kernel/api/lute_clipboard_math_test.go@@ -95,13 +95,13 @@ func TestPrepareHTMLClipboardContentFreezesNormalizedHTML(t *testing.T) {noMath := func(string, string, string) (string, bool) { return "", false }noOfficeMath := func(string) (string, bool) { return "", false }normalizedHTML, useHTML := prepareHTMLClipboardContent(util.NewLute(), htmlWithCommentImage, "", "", "", "", "",- false, noMath, noOfficeMath)+ false, false, noMath, noOfficeMath)if !useHTML || !strings.Contains(normalizedHTML, "kept") || strings.Contains(normalizedHTML, "data:image") {t.Fatalf("unexpected normalized HTML: useHTML=%v dom=%q", useHTML, normalizedHTML)}preparedHTML, useHTML := prepareHTMLClipboardContent(util.NewLute(), normalizedHTML, "", "ignored", "", "", "",- true, func(string, string, string) (string, bool) {+ false, true, func(string, string, string) (string, bool) {t.Fatal("prepared HTML should not run clipboard math conversion")return "", false}, func(string) (string, bool) {diff --git a/kernel/api/lute_clipboard_style.go b/kernel/api/lute_clipboard_style.goindex e7b4cdc53f..91413af67d 100644--- a/kernel/api/lute_clipboard_style.go+++ b/kernel/api/lute_clipboard_style.go@@ -17,7 +17,7 @@package apiimport (- "regexp"+ "strconv""strings""github.com/88250/lute/parse"@@ -25,244 +25,150 @@ import (nethtml "golang.org/x/net/html")-var clipboardThemeProperties = []string{"color", "background-color", "font-family", "font-size"}--var clipboardTransparentColor = regexp.MustCompile(`(?i)^(transparent|#[0-9a-f]{3}0|#[0-9a-f]{6}00|(?:rgba|hsla)\([^)]*,\s*(?:0(?:\.0*)?|\.0+)%?\s*\)|(?:rgb|rgba|hsl|hsla)\([^)]*/\s*(?:0(?:\.0*)?|\.0+)%?\s*\))$`)+var clipboardTextStyleProperties = map[string]bool{+ "background": true,+ "background-color": true,+ "color": true,+ "font": true,+ "font-family": true,+ "font-size": true,+ "font-style": true,+ "font-weight": true,+ "text-decoration": true,+ "text-decoration-line": true,+}-// normalizeBrowserClipboardStyle 移除浏览器复制正文时附带的共同主题样式,保留局部格式差异。-func normalizeBrowserClipboardStyle(dom string, documentSource bool) string {+// matchHTMLClipboardElements 保留 HTML 元素及基本强调,移除由来源应用决定的文字外观。+func matchHTMLClipboardElements(dom string) string {lower := strings.ToLower(dom)- if strings.Contains(lower, "data-type=") {- return dom- }- if !strings.Contains(lower, "style") {+ if !strings.Contains(lower, "style") && !strings.Contains(lower, "<font") {return dom}doc, err := goquery.NewDocumentFromReader(strings.NewReader(dom))if err != nil {return dom}- doc.Find("*").Each(func(_ int, selection *goquery.Selection) {- if isClipboardDocumentBoundary(selection.Get(0)) {- documentSource = true+ preserveClipboardCSSSemantics(doc.Find("body").Get(0))+ doc.Find("[style]").Each(func(_ int, selection *goquery.Selection) {+ style, _ := selection.Attr("style")+ style = filterClipboardStyle(style, clipboardTextStyleProperties)+ if strings.TrimSpace(style) == "" {+ selection.RemoveAttr("style")+ } else {+ selection.SetAttr("style", style)}})- changed := false- if !documentSource {- doc.Find("[style]").Each(func(_ int, selection *goquery.Selection) {- decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(selection.Get(0)))- changed = changed || clipboardTransparentColor.MatchString(decl["background-color"])- })- // 网页链接自身的外观交给编辑器,子元素中的显式格式及语义标签继续保留。- doc.Find("a[href]").Each(func(_ int, selection *goquery.Selection) {- n := selection.Get(0)- for i := range n.Attr {- if n.Attr[i].Key != "style" {- continue- }- style := n.Attr[i].Val- remove := map[string]bool{"color": true, "background-color": true, "font-family": true, "font-size": true}- decl := parse.HTMLStyleDeclarations(style)- var retained strings.Builder- for _, key := range []string{"text-decoration", "text-decoration-line"} {- var parts []string- for _, part := range strings.Fields(decl[key]) {- if strings.EqualFold(part, "underline") {- remove[key] = true- } else {- parts = append(parts, part)- }- }- if remove[key] && len(parts) > 0 {- retained.WriteString(key + ": " + strings.Join(parts, " ") + ";")- }- }- n.Attr[i].Val = filterClipboardStyle(style, remove) + retained.String()- changed = changed || n.Attr[i].Val != style- }- })- // 语义元素由编辑器提供基础外观,内部独立设置的强调样式继续保留。- doc.Find("h1,h2,h3,h4,h5,h6,pre,code,blockquote,ul,ol,li,table,thead,tbody,tfoot,tr,th,td").Each(func(_ int, selection *goquery.Selection) {- n := selection.Get(0)- remove := map[string]bool{"font-family": true, "font-size": true}- switch n.Data {- case "table", "thead", "tbody", "tfoot", "tr", "th", "td":- // 表格颜色可能表达状态,仅由正文主题基准规则清理相同颜色。- default:- remove["color"], remove["background-color"] = true, true- }- changed = filterClipboardNodeStyle(n, remove) || changed- if n.Data == "pre" || n.Data == "code" {- // 代码的空白、语言和文本由语义结构保留,着色交给编辑器的代码渲染器。- selection.Find("[style]").Each(func(_ int, child *goquery.Selection) {- changed = filterClipboardNodeStyle(child.Get(0), remove) || changed- })- }- })+ // font 的外观属性与对应 CSS 属性采用相同的匹配规则。+ doc.Find("font").RemoveAttr("color").RemoveAttr("face").RemoveAttr("size")+ ret, err := doc.Find("body").Html()+ if err != nil {+ return dom}- var roots []*nethtml.Node- var baseline map[string]string- ambiguous := false+ return ret+}++func preserveClipboardCSSSemantics(root *nethtml.Node) {+ if root == nil {+ return+ }+ var texts []*nethtml.Nodevar collect func(*nethtml.Node)collect = func(n *nethtml.Node) {- if n.Type == nethtml.ElementNode {- switch n.Data {- case "p", "div", "span", "body":- decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))- if isBrowserClipboardTheme(decl) && (!documentSource || isClipboardDocumentThemeWrapper(n)) {- if baseline == nil {- baseline = decl- } else {- for _, key := range clipboardThemeProperties {- if decl[key] != baseline[key] {- ambiguous = true- }- }- }- roots = append(roots, n)- return- }- }- // 文档正文内部的统一字体、字号也可能是作者主动设置,不能用重复次数推断默认格式。- if documentSource && isClipboardDocumentBoundary(n) {- return- }+ if n.Type == nethtml.TextNode && strings.TrimSpace(n.Data) != "" {+ texts = append(texts, n)}for child := n.FirstChild; child != nil; child = child.NextSibling {collect(child)}}- collect(doc.Find("body").Get(0))- if len(roots) == 0 || ambiguous {- roots = nil- if !changed {- return dom- }- }- var clean func(*nethtml.Node, map[string]string)- clean = func(n *nethtml.Node, inherited map[string]string) {- decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))- effective := make(map[string]string, len(clipboardThemeProperties))- remove := map[string]bool{}- var resets strings.Builder- for _, key := range clipboardThemeProperties {- effective[key] = inherited[key]- if value := decl[key]; value != "" && value != "inherit" && value != "unset" {- effective[key] = value- if value == baseline[key] {- remove[key] = true- // 局部格式之后恢复正文基准时,显式重置,避免继续继承局部格式。- if inherited[key] != "" && inherited[key] != baseline[key] {- resets.WriteString(key + ": initial;")- }+ collect(root)+ for _, text := range texts {+ weight, fontStyle := "", ""+ underline, strike := false, false+ strongTag, emTag, underlineTag, strikeTag, ignored := false, false, false, false, false+ for n := text.Parent; n != nil; n = n.Parent {+ switch n.Data {+ case "script", "style":+ ignored = true+ case "strong", "b":+ strongTag = true+ case "em", "i":+ emTag = true+ case "u":+ underlineTag = true+ case "s", "del", "strike":+ strikeTag = true+ }+ decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))+ font := strings.ToLower(decl["font"])+ if weight == "" {+ weight = strings.ToLower(decl["font-weight"])+ if weight == "" && font != "" {+ weight = font}}- }- for i := range n.Attr {- if n.Attr[i].Key == "style" && len(remove) > 0 {- n.Attr[i].Val = filterClipboardStyle(n.Attr[i].Val, remove) + resets.String()+ if fontStyle == "" {+ fontStyle = strings.ToLower(decl["font-style"])+ if fontStyle == "" && font != "" {+ fontStyle = font+ }}+ decoration := strings.ToLower(decl["text-decoration"] + " " + decl["text-decoration-line"])+ underline = underline || n.Data != "a" && strings.Contains(decoration, "underline")+ strike = strike || strings.Contains(decoration, "line-through")}- // 文档来源只清理外层浏览器包装;即使子元素与主题同色,也保留其显式格式。- if documentSource {- return+ if ignored {+ continue}- for child := n.FirstChild; child != nil; child = child.NextSibling {- clean(child, effective)+ var tags []string+ if !strongTag && isClipboardCSSBold(weight) {+ tags = append(tags, "strong")}- }- for _, root := range roots {- clean(root, nil)- }- if !documentSource {- // 透明背景不生成文本样式;存在祖先背景时保留重置语义,避免被文本样式继承重新着色。- doc.Find("[style]").Each(func(_ int, selection *goquery.Selection) {- n := selection.Get(0)- for i := range n.Attr {- if n.Attr[i].Key != "style" {- continue- }- decl := parse.HTMLStyleDeclarations(n.Attr[i].Val)- if !clipboardTransparentColor.MatchString(decl["background-color"]) {- continue- }- n.Attr[i].Val = filterClipboardStyle(n.Attr[i].Val, map[string]bool{"background-color": true})- for parent := n.Parent; parent != nil; parent = parent.Parent {- if parse.HTMLStyleDeclarations(clipboardNodeStyle(parent))["background-color"] != "" {- n.Attr[i].Val += "background-color: initial;"- break- }- }- }- })- }- ret, err := doc.Find("body").Html()- if err != nil {- return dom- }- return ret-}--func filterClipboardNodeStyle(n *nethtml.Node, remove map[string]bool) bool {- for i := range n.Attr {- if n.Attr[i].Key == "style" {- style := n.Attr[i].Val- n.Attr[i].Val = filterClipboardStyle(style, remove)- return n.Attr[i].Val != style+ if !emTag && (strings.Contains(fontStyle, "italic") || strings.Contains(fontStyle, "oblique")) {+ tags = append(tags, "em")}+ if !underlineTag && underline {+ tags = append(tags, "u")+ }+ if !strikeTag && strike {+ tags = append(tags, "s")+ }+ wrapClipboardTextNode(text, tags)}- return false}-func isClipboardDocumentBoundary(n *nethtml.Node) bool {- for _, attr := range n.Attr {- key, value := strings.ToLower(attr.Key), strings.ToLower(attr.Val)- if strings.HasPrefix(key, "data-lark") || strings.Contains(value, "urn:schemas-microsoft-com:office") {+func isClipboardCSSBold(value string) bool {+ for _, word := range strings.FieldsFunc(value, func(r rune) bool {+ return r == ' ' || r == '/' || r == ','+ }) {+ if word == "bold" || word == "bolder" {return true}- if key == "style" && strings.Contains(value, "mso-") {+ weight, err := strconv.Atoi(word)+ if err == nil && weight >= 600 && weight <= 1000 {return true}- if key == "class" {- for _, class := range strings.Fields(value) {- if strings.HasPrefix(class, "mso") {- return true- }- }- }}return false}-func isClipboardDocumentThemeWrapper(n *nethtml.Node) bool {- if n.Data != "div" && n.Data != "body" {- return false- }- if isClipboardDocumentBoundary(n) {- // 飞书仅允许根容器参与浏览器样式识别;正文节点和 Office 样式节点不作为主题基准。- larkRoot := false- for _, attr := range n.Attr {- if attr.Key == "data-lark-html-role" && attr.Val == "root" {- larkRoot = true- }- if attr.Key == "style" && strings.Contains(strings.ToLower(attr.Val), "mso-") {- return false- }- }- if !larkRoot {- return false- }+func wrapClipboardTextNode(text *nethtml.Node, tags []string) {+ if len(tags) == 0 || text.Parent == nil {+ return+ }+ parent, next := text.Parent, text.NextSibling+ parent.RemoveChild(text)+ var wrapped = text+ for _, tag := range tags {+ wrapper := &nethtml.Node{Type: nethtml.ElementNode, Data: tag}+ wrapper.AppendChild(wrapped)+ wrapped = wrapper+ }+ if next == nil {+ parent.AppendChild(wrapped)+ } else {+ parent.InsertBefore(wrapped, next)}- hasContent := false- for child := n.FirstChild; child != nil; child = child.NextSibling {- if child.Type == nethtml.TextNode && strings.TrimSpace(child.Data) != "" {- return false- }- if child.Type == nethtml.ElementNode {- hasContent = true- }- }- return hasContent}func clipboardNodeStyle(n *nethtml.Node) string {@@ -274,16 +180,6 @@ func clipboardNodeStyle(n *nethtml.Node) string {return ""}-func isBrowserClipboardTheme(decl map[string]string) bool {- // 同时要求浏览器序列化特征及完整正文基准,避免把普通手写样式识别为页面主题。- for _, key := range []string{"-webkit-text-stroke-width", "font-variant-caps", "letter-spacing", "orphans", "widows", "text-indent", "text-transform", "word-spacing", "white-space", "color", "background-color", "font-family", "font-size"} {- if decl[key] == "" {- return false- }- }- return true-}-// filterClipboardStyle 仅移除目标声明,原样保留其他声明的优先级、引号和函数内容。func filterClipboardStyle(style string, remove map[string]bool) string {var ret strings.Builderdiff --git a/kernel/api/lute_clipboard_style_test.go b/kernel/api/lute_clipboard_style_test.goindex 5dcbfea29b..b76d413c46 100644--- a/kernel/api/lute_clipboard_style_test.go+++ b/kernel/api/lute_clipboard_style_test.go@@ -36,325 +36,105 @@ func githubClipboardFixture(t *testing.T) string {return string(data)}-func TestBrowserClipboardTheme(t *testing.T) {- input := render.Sanitize(githubClipboardFixture(t))- output := normalizeBrowserClipboardStyle(input, false)- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(output))- doc.Find("p").Each(func(_ int, p *goquery.Selection) {- style, _ := p.Attr("style")+func TestMatchHTMLClipboardElements(t *testing.T) {+ input := render.Sanitize(githubClipboardFixture(t)) + `<h2 style="color:red;background:yellow;font:20px serif">` ++ `<strong>heading</strong></h2><p style="color:gray;font-size:1rem">text ` ++ `<a href="https://example.com" title="title" style="color:blue;background-color:transparent;` ++ `font-family:monospace;font-size:12px;text-decoration:underline line-through">link</a></p>`+ output := matchHTMLClipboardElements(input)+ doc, err := goquery.NewDocumentFromReader(strings.NewReader(output))+ if err != nil {+ t.Fatal(err)+ }+ doc.Find("[style]").Each(func(_ int, selection *goquery.Selection) {+ style, _ := selection.Attr("style")decl := parse.HTMLStyleDeclarations(style)- for _, key := range clipboardThemeProperties {- if decl[key] != "" {- t.Errorf("theme property %s survived: %s", key, style)+ for property := range clipboardTextStyleProperties {+ if decl[property] != "" {+ t.Errorf("text style %s survived: %s", property, output)}}})lute := util.NewLute()lute.SetHTMLTag2TextMark(true)blockDOM := lute.HTML2BlockDOM(output)- if strings.Contains(blockDOM, "rgb(") || strings.Contains(blockDOM, "font-size:") || strings.Contains(blockDOM, "font-family:") {- t.Fatalf("theme leaked into BlockDOM: %s", blockDOM)- }- if !strings.Contains(blockDOM, "感谢分享经验") || !strings.Contains(blockDOM, "欢迎提供") {- t.Fatalf("content lost: %s", blockDOM)- }- if again := normalizeBrowserClipboardStyle(output, false); again != output {- t.Fatal("normalization is not idempotent")- }-}--func TestBrowserClipboardLocalStyles(t *testing.T) {- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))- style, _ := doc.Find("p").First().Attr("style")- input := `<div style='` + style + `'>plain <strong>bold</strong><em>italic</em><a href="https://example.com">link</a>` +- `<span style="color: red; background: yellow; font-family: serif; font-size: 20px">highlight` +- `<span style="color: rgb(240, 246, 252)">reset</span></span><small>small</small><code>code</code></div>`- output := normalizeBrowserClipboardStyle(input, false)- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- blockDOM := lute.HTML2BlockDOM(output)- for _, expected := range []string{"color: red", "background-color: yellow", "font-family: serif", "font-size: 20.000000px", "strong", "em", "https://example.com", "code", "font-size: 0.833333em"} {- if !strings.Contains(blockDOM, expected) {- t.Errorf("missing %q in %s", expected, blockDOM)+ for _, want := range []string{`data-type="NodeHeading"`, `data-type="strong"`, `data-type="a"`, `data-type="s"`, `data-href="https://example.com"`, `data-title="title"`} {+ if !strings.Contains(blockDOM, want) {+ t.Errorf("missing %q: %s", want, blockDOM)}}- if strings.Contains(blockDOM, "rgb(240") || strings.Contains(blockDOM, "rgb(13") {- t.Fatalf("theme survived nested reset: %s", blockDOM)- }-}--func TestBrowserClipboardThemeVariants(t *testing.T) {- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))- style, _ := doc.Find("p").First().Attr("style")- for _, tag := range []string{"p", "span", "div"} {- for _, light := range []bool{false, true} {- baseline := style- if light {- baseline = strings.ReplaceAll(baseline, "rgb(240, 246, 252)", "rgb(31, 35, 40)")- baseline = strings.ReplaceAll(baseline, "rgb(13, 17, 23)", "rgb(255, 255, 255)")- }- input := "<" + tag + " style='" + baseline + "'>plain<span style='" + baseline + "'>repeated</span></" + tag + ">"- output := normalizeBrowserClipboardStyle(input, false)- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- blockDOM := lute.HTML2BlockDOM(output)- if strings.Contains(blockDOM, "rgb(") || strings.Contains(blockDOM, "font-size:") || strings.Contains(blockDOM, "font-family:") || !strings.Contains(blockDOM, "plainrepeated") {- t.Errorf("theme variant %s light=%v: %s", tag, light, blockDOM)- }+ for _, unexpected := range []string{"color:", "background", "font-family:", "font-size:", `data-type="a u`} {+ if strings.Contains(blockDOM, unexpected) {+ t.Errorf("unexpected %q: %s", unexpected, blockDOM)}}+ if again := matchHTMLClipboardElements(output); again != output {+ t.Fatal("matching elements is not idempotent")+ }}-func TestBrowserClipboardPreservesExplicitStyles(t *testing.T) {- fixture := githubClipboardFixture(t)+func TestMatchHTMLClipboardElementsAcrossSources(t *testing.T) {for _, input := range []string{- `<p style="color: white; background-color: black; font-family: serif; font-size: 14px">explicit</p>`,- `<div data-lark-html-role="root">` + fixture + `</div>`,- `<div style="mso-style-name: normal">` + fixture + `</div>`,- `<div data-type="NodeParagraph">` + fixture + `</div>`,- strings.Replace(fixture, "rgb(240, 246, 252)", "red", 1),+ `<div data-lark-html-role="root"><div style="color:gray;font-size:14px">text<span style="color:red;background:yellow">mark</span></div></div>`,+ `<p class="MsoNormal"><span style="font-family:Calibri;font-size:11pt;color:red;background:yellow;font-weight:bold">Office</span></p>`,+ `<p class="MsoNormal"><span style="font-family:宋体;font-size:12pt;color:red;background:yellow;text-decoration:underline;font-style:italic">WPS</span></p>`,+ `<font color="red" face="Arial" size="4"><em>legacy</em></font>`,} {- if output := normalizeBrowserClipboardStyle(input, false); output != input {- t.Errorf("explicit or ambiguous formatting changed: %s", output)+ output := matchHTMLClipboardElements(input)+ lower := strings.ToLower(output)+ for _, unexpected := range []string{"color:", "background", "font-family:", "font-size:", " face=", " size="} {+ if strings.Contains(lower, unexpected) {+ t.Errorf("source appearance survived %q: %s", unexpected, output)+ }}- }- noMath := func(string, string, string) (string, bool) { return "", false }- noOffice := func(string) (string, bool) { return "", false }- normalized, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", "", "", "", false, noMath, noOffice)- if strings.Contains(normalized, "rgb(240, 246, 252)") {- t.Fatal("clipboard preparation did not normalize browser styles")- }- frozen, _ := prepareHTMLClipboardContent(util.NewLute(), normalized, "", "", "", "", "", true, noMath, noOffice)- if frozen != normalized {- t.Fatal("normalized HTML changed during the second conversion stage")- }- for _, office := range [][3]string{{"office", "", ""}, {"", "officeHTML", ""}, {"", "", "wps"}} {- output, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", office[0], office[1], office[2], false, noMath, noOffice)- if !strings.Contains(output, "rgb(240, 246, 252)") {- t.Fatal("Office theme-like formatting was removed")+ for trigger, expected := range map[string]string{"font-weight": "<strong>", "text-decoration": "<u>", "font-style": "<em>", "<em>": "<em>"} {+ if strings.Contains(input, trigger) && !strings.Contains(output, expected) {+ t.Errorf("semantic emphasis %q was lost: %s", expected, output)+ }}}- prepared, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", "", "", "", true, noMath, noOffice)- if prepared != fixture {- t.Fatal("prepared HTML was processed again")- }}-func TestFilterClipboardStyle(t *testing.T) {- input := `color: red !important; color: blue; font-family: "a;b"; background-image: url("a;b"); margin: 0 !important;`- output := filterClipboardStyle(input, map[string]bool{"color": true})- if strings.Contains(output, "color:") || !strings.Contains(output, `font-family: "a;b";`) || !strings.Contains(output, `background-image: url("a;b");`) || !strings.Contains(output, "margin: 0 !important;") {+func TestMatchHTMLClipboardElementsPreservesSemanticOverrides(t *testing.T) {+ input := `<p><span style="font-weight:bold;font-style:italic">bold italic ` ++ `<span style="font-weight:normal;font-style:normal">normal</span></span>` ++ `<a href="https://example.com" style="text-decoration:underline">link</a></p>`+ output := matchHTMLClipboardElements(input)+ if !strings.Contains(output, "<em><strong>bold italic </strong></em>") || strings.Contains(output, "<strong><span>normal") || strings.Contains(output, "<u>link</u>") || strings.Contains(output, "style=") {t.Fatal(output)}}-func TestDocumentClipboardThemeWrapper(t *testing.T) {- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))- theme, _ := doc.Find("p").First().Attr("style")+func TestPrepareHTMLClipboardStyleModes(t *testing.T) {+ input := `<p style="color:red;background:yellow;font-family:Arial;font-size:18px"><strong>text</strong></p>`noMath := func(string, string, string) (string, bool) { return "", false }noOffice := func(string) (string, bool) { return "", false }- for _, tc := range []struct {- name, root, content, office, officeHTML, wps string- }{- {"wps", "", `<p class=MsoNormal><span style="font-family:宋体;font-size:12pt">正文</span><u><span style="color:red;background:yellow">强调</span></u></p>`, "", "", "wps"},- {"office", "", `<p class='MsoNormal'><span style="font-family:Calibri;font-size:11pt">正文</span><strong>强调</strong></p>`, "office", "", ""},- {"officeHTML", "", `<p><span style="font-family:Calibri;font-size:11pt">正文</span></p>`, "", "officeHTML", ""},- {"feishu", `data-lark-html-role="root"`, `<div>正文<span style="color:red;background-color:yellow">强调</span></div>`, "", "", ""},- {"officeDetected", "", `<p class='MsoNormal'><span style="font-family:Calibri;font-size:11pt">正文</span></p>`, "", "", ""},- {"sameAsTheme", `data-lark-html-role="root"`, `<p><span style='` + theme + `'>显式格式</span></p>`, "", "", ""},- } {- t.Run(tc.name, func(t *testing.T) {- input := `<div id="wrapper" ` + tc.root + ` style='` + theme + `'>` + tc.content + `</div>`- output, useHTML := prepareHTMLClipboardContent(util.NewLute(), input, "", "", tc.office, tc.officeHTML, tc.wps, false, noMath, noOffice)- if !useHTML {- t.Fatal("HTML conversion was skipped")- }- actual, _ := goquery.NewDocumentFromReader(strings.NewReader(output))- wrapper := actual.Find("#wrapper")- style, _ := wrapper.Attr("style")- decl := parse.HTMLStyleDeclarations(style)- for _, key := range clipboardThemeProperties {- if decl[key] != "" {- t.Errorf("wrapper retained %s: %s", key, output)- }- }- before, _ := goquery.NewDocumentFromReader(strings.NewReader(input))- want, _ := before.Find("#wrapper").Html()- got, _ := wrapper.Html()- if got != want {- t.Errorf("explicit content formatting changed:\nwant %s\ngot %s", want, got)- }- if again := normalizeBrowserClipboardStyle(output, tc.office != "" || tc.officeHTML != "" || tc.wps != ""); again != output {- t.Fatal("document normalization is not idempotent")- }- })- }-}--func TestDocumentClipboardAmbiguousStyles(t *testing.T) {- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))- theme, _ := doc.Find("p").First().Attr("style")- for _, input := range []string{- `<div style='` + theme + `'>direct text</div>`,- `<div class='MsoNormal' style='` + theme + `'><span>text</span></div>`,- `<div style='` + theme + `mso-style-name:Normal'><span>text</span></div>`,- `<div data-lark-html-role="paragraph" style='` + theme + `'><span>text</span></div>`,- `<div><span style="font-family:宋体;font-size:12pt">text</span></div>`,- } {- if output := normalizeBrowserClipboardStyle(input, true); output != input {- t.Errorf("ambiguous document style changed: %s", output)- }- }-}--func TestBrowserClipboardLinkAppearance(t *testing.T) {- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))- theme, _ := doc.Find("p").First().Attr("style")- for _, input := range []string{- `<p>before <a href="https://example.com" title="title" style="color:rgb(9,105,218);background-color:rgba(0,0,0,0);text-decoration:underline">link</a> after</p>`,- `<a href="https://example.com" title="title" style='` + theme + `text-decoration:underline'>link</a>`,- `<p style='` + theme + `'>before <a href="https://example.com" title="title" style="color:rgb(9,105,218);text-decoration-line:underline">link</a> after</p>`,- } {- output := normalizeBrowserClipboardStyle(input, false)- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- blockDOM := lute.HTML2BlockDOM(output)- if !strings.Contains(blockDOM, `data-type="a"`) || !strings.Contains(blockDOM, `data-href="https://example.com"`) || !strings.Contains(blockDOM, `data-title="title"`) {- t.Errorf("link semantics lost: %s", blockDOM)- }- for _, unexpected := range []string{"color:", "font-family:", "font-size:", `data-type="a u"`} {- if strings.Contains(blockDOM, unexpected) {- t.Errorf("link appearance survived %q: %s", unexpected, blockDOM)- }- }- if again := normalizeBrowserClipboardStyle(output, false); again != output {- t.Fatal("link cleanup is not idempotent")- }- }-}--func TestBrowserClipboardLinkExplicitContent(t *testing.T) {- input := `<a href="https://example.com" style="color:blue;text-decoration:underline line-through"><strong>bold</strong><u>underline</u><span style="color:red;background:yellow;font-size:20px;font-family:serif">styled</span></a>`- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- output := lute.HTML2BlockDOM(normalizeBrowserClipboardStyle(input, false))- for _, want := range []string{"strong", "u", "s", "color: red", "background-color: yellow", "font-size: 20.000000px", "font-family: serif"} {- if !strings.Contains(output, want) {- t.Errorf("missing %s: %s", want, output)- }+ matched, useHTML := prepareHTMLClipboardContent(util.NewLute(), input, "", "", "", "", "", false, false, noMath, noOffice)+ if !useHTML || strings.Contains(matched, "color:") || strings.Contains(matched, "font-size:") || !strings.Contains(matched, "<strong>") {+ t.Fatalf("unexpected matched HTML: %s", matched)}- for _, input := range []string{input, `<div data-lark-html-role="root">` + input + `</div>`, `<p class=MsoNormal>` + input + `</p>`} {- if output := normalizeBrowserClipboardStyle(input, true); output != input {- t.Errorf("document link changed: %s", output)- }+ preserved, useHTML := prepareHTMLClipboardContent(util.NewLute(), input, "", "", "", "", "", true, false, noMath, noOffice)+ if !useHTML || preserved != input {+ t.Fatalf("source formatting was not preserved: %s", preserved)}-}--func TestBrowserClipboardTransparentBackground(t *testing.T) {- for _, color := range []string{"transparent", "rgba(0, 0, 0, 0)", "rgb(0 0 0 / 0%)", "#1230", "#12345600"} {- input := `<span style="background-color:` + color + `">plain</span>`- output := normalizeBrowserClipboardStyle(input, false)- if strings.Contains(output, "background-color") {- t.Error(output)- }- }- for _, color := range []string{"#abcd00", "rgba(0,0,0,0.5)", "yellow"} {- input := `<span style="background-color:` + color + `">highlight</span>`- if output := normalizeBrowserClipboardStyle(input, false); output != input {- t.Errorf("visible background changed: %s", output)- }- }- input := `<div style="background-color:yellow"><span style="background-color:rgba(0,0,0,0)">plain</span></div>`- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- output := lute.HTML2BlockDOM(normalizeBrowserClipboardStyle(input, false))- if strings.Contains(output, "background-color:") {- t.Errorf("transparent text inherited a background: %s", output)+ frozen, useHTML := prepareHTMLClipboardContent(util.NewLute(), preserved, "", "", "", "", "", true, true, noMath, noOffice)+ if !useHTML || frozen != preserved {+ t.Fatalf("prepared HTML changed: %s", frozen)}}-func TestBrowserClipboardSemanticAppearance(t *testing.T) {- style := `color: white; background-color: black; font-family: Arial; font-size: 14px;`- for _, tc := range []struct {- tag, content, blockType string- }{- {"h2", "heading", "NodeHeading"},- {"blockquote", "<p>quote</p>", "NodeBlockquote"},- {"ul", "<li>first<ul><li>nested</li></ul></li>", "NodeList"},- {"ol", "<li>first</li><li>second</li>", "NodeList"},- {"code", "inline", "NodeParagraph"},- {"pre", "<code class=\"language-go\"> first\n\tsecond\n</code>", "NodeCodeBlock"},- } {- t.Run(tc.tag, func(t *testing.T) {- input := "<" + tc.tag + " style='" + style + "'>" + tc.content + "</" + tc.tag + ">"- output := normalizeBrowserClipboardStyle(input, false)- before, _ := goquery.NewDocumentFromReader(strings.NewReader(input))- after, _ := goquery.NewDocumentFromReader(strings.NewReader(output))- want, _ := before.Find(tc.tag).First().Html()- got, _ := after.Find(tc.tag).First().Html()- if got != want {- t.Errorf("semantic content changed: want %q, got %q", want, got)- }- lute := util.NewLute()- lute.SetHTMLTag2TextMark(true)- blockDOM := lute.HTML2BlockDOM(output)- if !strings.Contains(blockDOM, tc.blockType) {- t.Errorf("semantic type lost: %s", blockDOM)- }- for _, property := range clipboardThemeProperties {- if strings.Contains(blockDOM, property+":") {- t.Errorf("default style %s survived: %s", property, blockDOM)- }- }- if again := normalizeBrowserClipboardStyle(output, false); again != output {- t.Fatal("semantic normalization is not idempotent")- }- })- }-}--func TestBrowserClipboardSemanticLocalFormatting(t *testing.T) {- input := `<h2 style="color:black;font-size:24px"><strong>heading</strong><span style="color:red;font-size:30px">emphasis</span></h2>` +- `<blockquote style="color:gray"><p><u>underline</u><mark>highlight</mark></p></blockquote>` +- `<ol start="3"><li style="font-family:Arial;color:black"><span style="background:yellow">item</span></li></ol>`- output := normalizeBrowserClipboardStyle(input, false)- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(output))- if start, _ := doc.Find("ol").Attr("start"); start != "3" || doc.Find("strong,u,mark").Length() != 3 {- t.Fatal("semantic attributes or emphasis lost: " + output)- }- for _, want := range []string{"color:red", "font-size:30px", "background:yellow"} {- if !strings.Contains(output, want) {- t.Errorf("local style %s lost: %s", want, output)- }- }- for _, wrapper := range []string{`<div data-lark-html-role="root">`, `<div class="MsoNormal">`, `<div data-type="NodeParagraph">`} {- protected := wrapper + input + `</div>`- if actual := normalizeBrowserClipboardStyle(protected, false); actual != protected {- t.Error("document semantic formatting changed: " + actual)- }- }- if actual := normalizeBrowserClipboardStyle(input, true); actual != input {- t.Error("Office clipboard semantic formatting changed: " + actual)+func TestMatchHTMLClipboardElementsPreservesLayout(t *testing.T) {+ input := `<iframe src="https://example.com" style="position:relative;width:100%;color:red;font-size:14px"></iframe>`+ output := matchHTMLClipboardElements(input)+ if !strings.Contains(output, "position:relative") || !strings.Contains(output, "width:100%") || strings.Contains(output, "color:red") || strings.Contains(output, "font-size") {+ t.Fatal(output)}}-func TestBrowserClipboardCodeAndTable(t *testing.T) {- code := "<pre style='background:black'><code class='language-go' style='color:white'><span style='color:red'> first</span>\n\tsecond\n</code></pre>"- output := normalizeBrowserClipboardStyle(code, false)- doc, _ := goquery.NewDocumentFromReader(strings.NewReader(output))- if doc.Find("code").Text() != " first\n\tsecond\n" {- t.Fatal("code whitespace changed: " + output)- }- if language, _ := doc.Find("code").Attr("class"); language != "language-go" || strings.Contains(output, "color:") {- t.Fatal("code language or coloring changed incorrectly: " + output)- }- table := `<table style="font-family:Arial"><thead><tr><th style="font-size:14px;background:gray">header</th></tr></thead><tbody><tr><td rowspan="2" style="color:red;background:yellow;font-size:14px">status</td></tr><tr></tr></tbody></table>`- output = normalizeBrowserClipboardStyle(table, false)- doc, _ = goquery.NewDocumentFromReader(strings.NewReader(output))- if rowspan, _ := doc.Find("td").Attr("rowspan"); rowspan != "2" || doc.Find("th").Text() != "header" {- t.Fatal("table structure lost: " + output)- }- if strings.Contains(output, "font-family") || strings.Contains(output, "font-size") || !strings.Contains(output, "color:red;background:yellow") || !strings.Contains(output, "background:gray") {- t.Fatal("table appearance changed incorrectly: " + output)+func TestFilterClipboardStyle(t *testing.T) {+ input := `color: red !important; color: blue; font-family: "a;b"; background-image: url("a;b"); margin: 0 !important;`+ output := filterClipboardStyle(input, map[string]bool{"color": true})+ if strings.Contains(output, "color:") || !strings.Contains(output, `font-family: "a;b";`) || !strings.Contains(output, `background-image: url("a;b");`) || !strings.Contains(output, "margin: 0 !important;") {+ t.Fatal(output)}}diff --git a/kernel/api/lute_text_style_test.go b/kernel/api/lute_text_style_test.goindex a6af99cc25..f450e09317 100644--- a/kernel/api/lute_text_style_test.go+++ b/kernel/api/lute_text_style_test.go@@ -43,7 +43,7 @@ func TestHTML2BlockDOMQuotedFontFamily(t *testing.T) {input = "<table><tr>" + input + "<td>cell</td></tr></table>"}body, err := json.Marshal(map[string]any{- "dom": input, "skipBase64Assets": true, "skipInlineSVGAssets": true,+ "dom": input, "skipBase64Assets": true, "skipInlineSVGAssets": true, "preserveSourceFormat": true,})if err != nil {t.Fatal(err)@@ -88,3 +88,39 @@ func TestHTML2BlockDOMQuotedFontFamily(t *testing.T) {})}}++func TestHTML2BlockDOMMatchesElementsByDefault(t *testing.T) {+ originalConf := model.Conf+ model.Conf = model.NewAppConf()+ model.Conf.System = &conf.System{}+ t.Cleanup(func() { model.Conf = originalConf })+ gin.SetMode(gin.TestMode)+ input := `<h2 style="color:gray;font-family:Arial;font-size:20px"><span style="font-weight:bold">heading</span></h2>` ++ `<p><a href="https://example.com" style="color:blue;text-decoration:underline">link</a></p>`+ body, err := json.Marshal(map[string]any{+ "dom": input, "skipBase64Assets": true, "skipInlineSVGAssets": true,+ })+ if err != nil {+ t.Fatal(err)+ }+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.Request = httptest.NewRequest(http.MethodPost, "/api/lute/html2BlockDOM", strings.NewReader(string(body)))+ context.Request.Header.Set("Content-Type", "application/json")+ html2BlockDOM(context)+ var response struct {+ Code int+ Data string+ }+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {+ t.Fatalf("conversion failed: %s, %v", recorder.Body.String(), err)+ }+ for _, expected := range []string{`data-type="NodeHeading"`, `data-type="strong"`, `data-type="a"`, `data-href="https://example.com"`} {+ if !strings.Contains(response.Data, expected) {+ t.Errorf("missing %q: %s", expected, response.Data)+ }+ }+ if strings.Contains(response.Data, "style=") || strings.Contains(response.Data, `data-type="a u"`) {+ t.Fatalf("source appearance survived: %s", response.Data)+ }+}