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 hiding reference blocks in propagated backlinks https://github.com/siyuan-note/siyuan/issues/19251
Daniele1596eeeeab1
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 01835d33c1..0a1c39e70d 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "إخفاء كتل المراجع في الروابط الخلفية الموروثة",+ "backlinkHideReferenceTip": "إخفاء الكتل التي تحتوي فقط على مراجع كتل في الروابط الخلفية الموروثة عندما يبقى محتوى آخر ظاهرًا، وإظهارها مجددًا أثناء التحرير","uploadInsertTargetUnavailable": "لم تعد وجهة الرفع الأصلية متاحة. لم تُدرج النتيجة؛ تم الاحتفاظ بالملفات المرفوعة.","mobileToolbarEntryTip": "اضبط ظهور عناصر شريط الأدوات على الأجهزة المحمولة وترتيبها باستخدام ملفات التعريف نفسها لسطح المكتب","keymapAssigned": "مُعيَّن",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 5cf320afb6..dff1c07750 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Referenzblöcke in vererbten Rückverweisen ausblenden",+ "backlinkHideReferenceTip": "Blöcke mit ausschließlich Blockreferenzen in vererbten Rückverweisen ausblenden, wenn andere Inhalte sichtbar bleiben, und beim Bearbeiten wieder anzeigen","uploadInsertTargetUnavailable": "Das ursprüngliche Upload-Ziel ist nicht mehr verfügbar. Das Ergebnis wurde nicht eingefügt; hochgeladene Dateien bleiben erhalten.","mobileToolbarEntryTip": "Sichtbarkeit und Reihenfolge der mobilen Werkzeugleiste mit denselben Profilen wie auf dem Desktop konfigurieren","keymapAssigned": "Zugewiesen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 8d372bda95..73ff49116a 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Hide reference blocks in propagated backlinks",+ "backlinkHideReferenceTip": "Hide blocks containing only block references in propagated backlinks when other content remains visible, and show them again while editing","uploadInsertTargetUnavailable": "The original upload target is no longer available. The result was not inserted; uploaded files are retained.","mobileToolbarEntryTip": "Configure mobile toolbar visibility and order using the same profiles as desktop","keymapAssigned": "Assigned",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 061e2fcb10..075ed72e7d 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Ocultar bloques de referencia en enlaces inversos propagados",+ "backlinkHideReferenceTip": "Ocultar los bloques que solo contienen referencias a bloques en los enlaces inversos propagados cuando queda otro contenido visible y mostrarlos de nuevo al editar","uploadInsertTargetUnavailable": "El destino original de la carga ya no está disponible. No se insertó el resultado; los archivos cargados se conservan.","mobileToolbarEntryTip": "Configura la visibilidad y el orden de la barra de herramientas móvil con los mismos perfiles que en escritorio","keymapAssigned": "Asignados",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 99d7aeccac..0e025b53e5 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Masquer les blocs de référence dans les liens retour propagés",+ "backlinkHideReferenceTip": "Masquer les blocs contenant uniquement des références de bloc dans les liens retour propagés si un autre contenu reste visible, et les réafficher pendant la modification","uploadInsertTargetUnavailable": "La cible initiale du téléversement n’est plus disponible. Le résultat n’a pas été inséré ; les fichiers téléversés sont conservés.","mobileToolbarEntryTip": "Configurer la visibilité et l’ordre de la barre d’outils mobile avec les mêmes profils que sur ordinateur","keymapAssigned": "Attribués",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex fe19e120fb..cf6c32835f 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "הסתרת בלוקי הפניה בקישורים נכנסים מועברים",+ "backlinkHideReferenceTip": "הסתרת בלוקים המכילים רק הפניות לבלוקים בקישורים נכנסים מועברים כאשר תוכן אחר נשאר גלוי, והצגתם מחדש בזמן עריכה","uploadInsertTargetUnavailable": "יעד ההעלאה המקורי אינו זמין עוד. התוצאה לא הוכנסה; הקבצים שהועלו נשמרים.","mobileToolbarEntryTip": "הגדרת הנראות והסדר של סרגל הכלים בנייד באמצעות אותם פרופילים כמו במחשב","keymapAssigned": "מוקצים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex a0d2254377..3433f3c83e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "प्रसारित बैकलिंक में संदर्भ ब्लॉक छिपाएँ",+ "backlinkHideReferenceTip": "प्रसारित बैकलिंक में केवल ब्लॉक संदर्भ वाले ब्लॉक छिपाएँ जब अन्य सामग्री दिखाई देती रहे, और संपादन के दौरान उन्हें फिर से दिखाएँ","uploadInsertTargetUnavailable": "अपलोड का मूल लक्ष्य अब उपलब्ध नहीं है। परिणाम सम्मिलित नहीं किया गया; अपलोड की गई फ़ाइलें सुरक्षित रखी गई हैं।","mobileToolbarEntryTip": "डेस्कटॉप वाली प्रोफ़ाइल का उपयोग करके मोबाइल टूलबार की दृश्यता और क्रम कॉन्फ़िगर करें","keymapAssigned": "असाइन किए गए",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex ab1b22f580..063b3e1736 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Sembunyikan blok referensi pada tautan balik yang diteruskan",+ "backlinkHideReferenceTip": "Sembunyikan blok yang hanya berisi referensi blok pada tautan balik yang diteruskan jika konten lain tetap terlihat, dan tampilkan kembali saat mengedit","uploadInsertTargetUnavailable": "Tujuan unggahan awal tidak lagi tersedia. Hasil tidak disisipkan; berkas yang diunggah tetap disimpan.","mobileToolbarEntryTip": "Atur visibilitas dan urutan bilah alat seluler menggunakan profil yang sama dengan desktop","keymapAssigned": "Ditetapkan",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex e032c3b5d9..9a9c331abe 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Nascondi i blocchi di riferimento nei backlink propagati",+ "backlinkHideReferenceTip": "Nascondi i blocchi contenenti solo riferimenti a blocchi nei backlink propagati quando rimangono altri contenuti visibili e mostrali di nuovo durante la modifica","uploadInsertTargetUnavailable": "La destinazione originale del caricamento non è più disponibile. Il risultato non è stato inserito; i file caricati vengono conservati.","mobileToolbarEntryTip": "Configura visibilità e ordine della barra degli strumenti mobile usando gli stessi profili del desktop","keymapAssigned": "Assegnate",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 85de88b4e2..ca3e3c0011 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "伝播型バックリンクの参照ブロックを非表示",+ "backlinkHideReferenceTip": "伝播型バックリンクで、ほかに表示できる内容がある場合はブロック参照のみのブロックを非表示にし、編集中は再表示します","uploadInsertTargetUnavailable": "アップロード元の挿入先が無効になったため、結果を挿入しませんでした。アップロード済みのファイルは保持されます。","mobileToolbarEntryTip": "デスクトップと共通のプロファイルで、モバイルのツールバー項目の表示と順序を設定","keymapAssigned": "割り当て済み",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 122df45a46..3ce73e3eee 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "전파된 백링크의 참조 블록 숨기기",+ "backlinkHideReferenceTip": "전파된 백링크에서 다른 표시할 내용이 있으면 블록 참조만 포함된 블록을 숨기고 편집 중에는 다시 표시","uploadInsertTargetUnavailable": "원래 업로드 대상이 더 이상 유효하지 않습니다. 결과를 삽입하지 않았으며 업로드된 파일은 유지됩니다.","mobileToolbarEntryTip": "데스크톱과 동일한 프로필로 모바일 도구 모음 항목의 표시 여부와 순서 설정","keymapAssigned": "할당됨",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 08eb7482eb..abe5e20189 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Verwijzingsblokken in doorgegeven backlinks verbergen",+ "backlinkHideReferenceTip": "Verberg blokken met uitsluitend blokverwijzingen in doorgegeven backlinks als andere inhoud zichtbaar blijft en toon ze weer tijdens het bewerken","uploadInsertTargetUnavailable": "Het oorspronkelijke uploaddoel is niet meer beschikbaar. Het resultaat is niet ingevoegd; geüploade bestanden blijven behouden.","mobileToolbarEntryTip": "Configureer de zichtbaarheid en volgorde van de mobiele werkbalk met dezelfde profielen als op de desktop","keymapAssigned": "Toegewezen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex f209b64aee..e50342c79c 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Ukryj bloki odwołań w propagowanych linkach zwrotnych",+ "backlinkHideReferenceTip": "Ukrywaj bloki zawierające wyłącznie odwołania do bloków w propagowanych linkach zwrotnych, gdy pozostaje inna widoczna treść, i pokazuj je ponownie podczas edycji","uploadInsertTargetUnavailable": "Pierwotny cel przesyłania nie jest już dostępny. Wynik nie został wstawiony; przesłane pliki zostały zachowane.","mobileToolbarEntryTip": "Skonfiguruj widoczność i kolejność mobilnego paska narzędzi przy użyciu tych samych profili co na komputerze","keymapAssigned": "Przypisane",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex dbe62eb1e7..c82f3d4102 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Ocultar blocos de referência em backlinks propagados",+ "backlinkHideReferenceTip": "Ocultar blocos que contêm apenas referências a blocos em backlinks propagados quando houver outro conteúdo visível e exibi-los novamente durante a edição","uploadInsertTargetUnavailable": "O destino original do envio não está mais disponível. O resultado não foi inserido; os arquivos enviados foram mantidos.","mobileToolbarEntryTip": "Configure a visibilidade e a ordem da barra de ferramentas móvel usando os mesmos perfis da versão para computador","keymapAssigned": "Atribuídos",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 9295373a78..d523ad1a1f 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Скрывать блоки ссылок в наследуемых обратных ссылках",+ "backlinkHideReferenceTip": "Скрывать блоки, содержащие только ссылки на блоки, в наследуемых обратных ссылках, если остаётся другое содержимое, и показывать их при редактировании","uploadInsertTargetUnavailable": "Исходное место вставки больше недоступно. Результат не вставлен; загруженные файлы сохранены.","mobileToolbarEntryTip": "Настройте видимость и порядок элементов мобильной панели инструментов, используя общие с настольной версией профили","keymapAssigned": "Назначенные",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex f0ca205b51..63ec2dba29 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Skryť bloky odkazov v prenesených spätných odkazoch",+ "backlinkHideReferenceTip": "Skryť bloky obsahujúce iba odkazy na bloky v prenesených spätných odkazoch, ak zostáva viditeľný iný obsah, a znova ich zobraziť pri úpravách","uploadInsertTargetUnavailable": "Pôvodný cieľ nahrávania už nie je dostupný. Výsledok nebol vložený; nahrané súbory zostávajú zachované.","mobileToolbarEntryTip": "Nastavte viditeľnosť a poradie mobilného panela nástrojov pomocou rovnakých profilov ako na počítači","keymapAssigned": "Priradené",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 8f0c9d9420..ca20c03938 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "ซ่อนบล็อกอ้างอิงในลิงก์ย้อนกลับที่ส่งต่อ",+ "backlinkHideReferenceTip": "ซ่อนบล็อกที่มีเฉพาะการอ้างอิงบล็อกในลิงก์ย้อนกลับที่ส่งต่อเมื่อยังมีเนื้อหาอื่นให้แสดง และแสดงอีกครั้งขณะแก้ไข","uploadInsertTargetUnavailable": "ปลายทางเดิมของการอัปโหลดไม่พร้อมใช้งานแล้ว จึงไม่ได้แทรกผลลัพธ์ แต่ไฟล์ที่อัปโหลดแล้วจะยังคงอยู่","mobileToolbarEntryTip": "กำหนดการแสดงและลำดับรายการในแถบเครื่องมือบนมือถือโดยใช้โปรไฟล์เดียวกับเดสก์ท็อป","keymapAssigned": "กำหนดแล้ว",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex b04334a289..9fe3951aee 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Aktarılan geri bağlantılarda referans bloklarını gizle",+ "backlinkHideReferenceTip": "Başka içerik görünür kaldığında aktarılan geri bağlantılarda yalnızca blok referansları içeren blokları gizle ve düzenleme sırasında yeniden göster","uploadInsertTargetUnavailable": "Özgün yükleme hedefi artık kullanılamıyor. Sonuç eklenmedi; yüklenen dosyalar korunuyor.","mobileToolbarEntryTip": "Masaüstü ile aynı profilleri kullanarak mobil araç çubuğunun görünürlüğünü ve sırasını yapılandırın","keymapAssigned": "Atanmış",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex c952e43bcc..7af12f5c31 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "Приховувати блоки посилань в успадкованих зворотних посиланнях",+ "backlinkHideReferenceTip": "Приховувати блоки, що містять лише посилання на блоки, в успадкованих зворотних посиланнях, якщо залишається інший вміст, і показувати їх під час редагування","uploadInsertTargetUnavailable": "Початкове місце вставлення більше недоступне. Результат не вставлено; завантажені файли збережено.","mobileToolbarEntryTip": "Налаштуйте видимість і порядок елементів мобільної панелі інструментів, використовуючи спільні з настільною версією профілі","keymapAssigned": "Призначені",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 1550d55d7a..ef2a4e6b77 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "隐藏传递型反链的引用块",+ "backlinkHideReferenceTip": "在反链面板中隐藏仅含块引用且仍有其他内容可展示的传递型引用块,编辑时恢复显示","uploadInsertTargetUnavailable": "原上传目标已失效,未回填结果;已上传的文件会保留。","mobileToolbarEntryTip": "配置移动端工具栏项的显隐与排序,与桌面端共用方案","keymapAssigned": "已分配",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 33ae55e94a..ddd18e1bf8 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "backlinkHideReference": "隱藏傳遞型反向連結的引用區塊",+ "backlinkHideReferenceTip": "在反向連結面板中隱藏僅含區塊引用且仍有其他內容可顯示的傳遞型引用區塊,編輯時恢復顯示","uploadInsertTargetUnavailable": "原上傳目標已失效,未填入結果;已上傳的檔案會保留。","mobileToolbarEntryTip": "設定行動端工具列項目的顯示與排序,與桌面端共用方案","keymapAssigned": "已指派",diff --git a/app/scripts/backlinkReference.test.js b/app/scripts/backlinkReference.test.jsnew file mode 100644index 0000000000..b2e94bbe0e--- /dev/null+++ b/app/scripts/backlinkReference.test.js@@ -0,0 +1,178 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const sources = () => {+ const ts = require("typescript");+ const modules = {};+ for (const name of ["protyle/wysiwyg/backlinkReference", "protyle/wysiwyg/renderBacklink", "protyle/util/clear"]) {+ modules[name] = ts.transpileModule(readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},+ }).outputText;+ }+ return {+ modules,+ css: require("sass").compile(path.join(__dirname, "../src/assets/scss/protyle/_wysiwyg.scss")).css,+ lute: readFileSync(path.join(__dirname, "../stage/protyle/js/lute/lute.min.js"), "utf8"),+ };+};++const runCases = async ({modules, css, lute: luteSource}) => {+ const assert = require("node:assert/strict");+ const script = document.createElement("script");+ script.textContent = luteSource;+ document.head.appendChild(script);+ const style = document.createElement("style");+ style.textContent = css;+ document.head.appendChild(style);+ window.siyuan = {config: {editor: {backlinkHideReference: false}}};+ const cache = {};+ const noop = () => {};+ const stubs = {+ "protyle/ui/initUI": {removeLoading: noop},+ "protyle/util/processCode": {processRender: noop},+ "protyle/render/highlightRender": {highlightRender: noop},+ "protyle/render/av/backlink": {prepareBacklinkAV: noop},+ "protyle/render/av/render": {avRender: async () => {}},+ "protyle/render/blockRender": {blockRender: noop},+ "protyle/util/viewFold": {clearViewFoldDefaults: noop, applyViewFoldStates: async () => {},+ markViewFoldDefault: noop, clearViewFoldOccurrenceState: noop},+ "constants": {Constants: {CUSTOM_RIFF_DECKS: "custom-riff-decks"}},+ "protyle/wysiwyg/blockSelection": {BLOCK_SELECTION_MODE_CLASS: "protyle-wysiwyg--select-mode"},+ };+ const load = name => {+ if (!modules[name]) {+ return stubs[name] || {};+ }+ if (!cache[name]) {+ cache[name] = {};+ new Function("require", "exports", modules[name])(+ dependency => load(require("node:path").posix.normalize(require("node:path").posix.dirname(name) + "/" + dependency)),+ cache[name]);+ }+ return cache[name];+ };+ const {renderBacklink, getBacklinkHeadingMore} = load("protyle/wysiwyg/renderBacklink");+ const {updateBacklinkReferenceVisibility} = load("protyle/wysiwyg/backlinkReference");+ const {clearBlockElement} = load("protyle/util/clear");+ const lute = window.Lute.New();+ lute.SetBlockRef(true);+ document.body.innerHTML = '<button id="outside">outside</button><div id="editor"><div class="protyle-wysiwyg" contenteditable="true"></div></div>';+ const element = document.querySelector(".protyle-wysiwyg");+ const protyle = {element: document.querySelector("#editor"), options: {backlinkData: []}, block: {}, wysiwyg: {element}};+ const template = document.createElement("template");+ template.innerHTML = lute.Md2BlockDOM('- ((20240101000000-abcdefg "A")) ((20240101000001-abcdefg "B"))\n - content');+ const referenceID = template.content.querySelector('[data-type="NodeParagraph"]').dataset.nodeId;+ const data = {id: "parent", revision: "one", referenceBlockID: referenceID, dom: template.innerHTML, expand: true, blockPaths: []};+ await renderBacklink(protyle, [data]);+ const reference = () => element.querySelector(`[data-node-id="${referenceID}"]`);+ const visible = node => getComputedStyle(node).display !== "none";+ assert.equal(visible(reference()), true, "the default preserves reference blocks");+ const before = lute.BlockDOM2StdMd(element.innerHTML);+ window.siyuan.config.editor.backlinkHideReference = true;+ updateBacklinkReferenceVisibility(protyle);+ assert.equal(visible(reference()), false, "the option applies without a context revision change");+ const parentAction = () => reference().parentElement.querySelector(":scope > .protyle-action");+ const childList = () => reference().parentElement.querySelector(":scope > .list");+ assert.equal(visible(parentAction()), false, "the hidden reference must not leave a parent bullet");+ assert.equal(getComputedStyle(childList()).marginLeft, "0px", "child content loses the hidden parent indentation");+ assert.equal(visible(childList().querySelector(".protyle-action")), true, "the child keeps its own bullet");+ assert.equal(element.querySelectorAll('[data-type="block-ref"]').length, 2, "both references remain in the editor DOM");+ element.focus();+ assert.equal(visible(reference()), true, "editing restores the complete block structure");+ assert.equal(visible(parentAction()), true, "editing restores the parent bullet");+ assert.equal(getComputedStyle(childList()).marginLeft, "34px", "editing restores the parent indentation");+ const range = document.createRange();+ range.selectNodeContents(element);+ const selection = getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ assert.match(selection.getRangeAt(0).toString(), /A[\s\S]*B[\s\S]*content/, "cross-block selection retains the reference nodes");+ selection.removeAllRanges();+ document.querySelector("#outside").focus();+ assert.equal(visible(reference()), false, "leaving the editor restores the preference");+ assert.equal(lute.BlockDOM2StdMd(element.innerHTML), before, "display state cannot remove source references");+ const clone = reference().parentElement.cloneNode(true);+ clearBlockElement(clone);+ assert.equal(clone.querySelector("[data-backlink-reference]"), null, "runtime markers are removed before serialization");+ assert.equal(clone.hasAttribute("data-backlink-reference-list"), false, "list layout markers are removed before serialization");+ assert.equal(clone.querySelectorAll('[data-type="block-ref"]').length, 2, "serialization cleanup retains both references");+ reference().parentElement.setAttribute("fold", "1");+ assert.equal(visible(reference()), true, "folded lists retain their identifying reference");+ assert.equal(visible(parentAction()), true, "folded lists retain their parent bullet");+ reference().parentElement.removeAttribute("fold");+ await renderBacklink(protyle, [data]);+ assert.equal(visible(reference()), false, "unchanged context refresh preserves hiding");+ await renderBacklink(protyle, [{...data, revision: "two", referenceBlockID: undefined}]);+ assert.equal(visible(reference()), true, "changed eligibility removes stale hiding");+ await renderBacklink(protyle, [data]);+ protyle.element.setAttribute("data-ismention", "true");+ updateBacklinkReferenceVisibility(protyle);+ assert.equal(visible(reference()), true, "mentions are unaffected");+ protyle.element.removeAttribute("data-ismention");+ updateBacklinkReferenceVisibility(protyle);+ element.focus();+ reference().firstElementChild.append(" body");+ document.querySelector("#outside").focus();+ assert.equal(visible(reference()), true, "new body text remains visible before the next server response");+ assert.equal(visible(parentAction()), true, "new body text restores the parent bullet");++ template.innerHTML = lute.Md2BlockDOM('# ((20240101000000-abcdefg "A"))\n\nfirst\n\nsecond\n\nthird');+ const headingID = template.content.firstElementChild.dataset.nodeId;+ await renderBacklink(protyle, [{...data, id: "heading", dom: template.innerHTML, referenceBlockID: headingID}]);+ const heading = element.querySelector(`[data-node-id="${headingID}"]`);+ assert.equal(visible(heading), false, "pure reference headings can be hidden");+ getBacklinkHeadingMore(element.querySelector(".protyle-breadcrumb__item"));+ assert.equal(visible(heading), false, "expanding heading content does not reveal the hidden reference");+ assert.equal(visible(element.lastElementChild), true, "expanded content is visible");+ window.siyuan.config.editor.backlinkHideReference = false;+ updateBacklinkReferenceVisibility(protyle);+ assert.equal(visible(heading), true, "disabling the option restores references immediately");+ return "Backlink reference visibility cases passed";+};++if (process.versions.electron && process.type === "browser") {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {+ nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true,+ }});+ let code = 0;+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ win.webContents.debugger.attach("1.3");+ await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});+ console.log(await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources())})`));+ } catch (error) {+ console.error(error);+ code = 1;+ } finally {+ win.destroy();+ app.exit(code);+ }+ });+} else {+ const {it} = require("node:test");+ const {execFile} = require("node:child_process");+ const {promisify} = require("node:util");+ it("hides propagated references without losing editable source content", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-backlink-reference-"));+ try {+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {+ env, windowsHide: true, timeout: 40000,+ });+ assert.match(stdout, /Backlink reference visibility cases passed/);+ } finally {+ assert.equal(path.dirname(profile), os.tmpdir());+ assert.ok(path.basename(profile).startsWith("siyuan-backlink-reference-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex e3dbd1ce08..94c7a6adc5 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1641,6 +1641,20 @@ body.mobile-topbar--merged {.sy__backlink {min-height: 0;+ > .block__icons > .block__logo--counter {+ @extend .toolbar__text;+ margin: 0;+ font-weight: normal;++ > .counter {+ margin-left: 8px;+ padding: 0;+ background-color: transparent;+ font-size: 12px;+ color: var(--b3-theme-on-surface);+ }+ }+> .block__icons {flex-wrap: wrap;height: auto;diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex 13fa231abc..a3e8cf6949 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -1,6 +1,28 @@@use "../util/mixin";@use "tabs";+// 编辑时恢复引用块,保留完整的选择范围和块结构;折叠的列表项和标题保留定位内容。+.protyle-wysiwyg[data-backlink-hide-reference]:not(:focus-within) {+ [data-backlink-reference]:not([fold="1"]):not(.li[fold="1"] *) {+ display: none !important;+ }++ .li[data-backlink-reference-list]:not([fold="1"]):not(.li[fold="1"] *) {+ min-height: 0;++ &::before,+ > .protyle-action,+ > .protyle-attr {+ display: none !important;+ }++ > [data-node-id] {+ margin-left: 0 !important;+ margin-right: 0 !important;+ }+ }+}+.protyle-cross-block-preview {pointer-events: none;diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.tsindex bf022cc511..a753c1a514 100644--- a/app/src/config/tabs/editorTab.ts+++ b/app/src/config/tabs/editorTab.ts@@ -311,6 +311,10 @@ const registerEditorBidirectionalGroup = (tab: SettingTabBuilder) => {title: window.siyuan.languages.backlinkContainChildren,desc: window.siyuan.languages.backlinkContainChildrenTip,});+ group.switch("editor.backlinkHideReference", {+ title: window.siyuan.languages.backlinkHideReference,+ desc: window.siyuan.languages.backlinkHideReferenceTip,+ });if (!isMobile()) {group.switch("editor.backlinkShowBottom", {title: window.siyuan.languages.backlinkShowBottom,diff --git a/app/src/protyle/util/clear.ts b/app/src/protyle/util/clear.tsindex d5ed5cb8d8..990edac409 100644--- a/app/src/protyle/util/clear.ts+++ b/app/src/protyle/util/clear.ts@@ -16,7 +16,8 @@ const getAVElements = (element: Element) => {const clearViewState = (element: Element) => {const attributes = ["data-view-fold-source", "data-view-fold-hidden-source", "data-view-fold",- "data-view-fold-default", "data-view-fold-hidden", "data-view-heading-owner", "data-view-heading-loaded"];+ "data-view-fold-default", "data-view-fold-hidden", "data-view-heading-owner", "data-view-heading-loaded",+ "data-backlink-reference", "data-backlink-reference-list", "data-backlink-hide-reference"];const elements = [element, ...Array.from(element.querySelectorAll(attributes.map(attribute => {return `[${attribute}]`;}).join(", ")))];diff --git a/app/src/protyle/util/reload.ts b/app/src/protyle/util/reload.tsindex 823e936135..f9b3df9703 100644--- a/app/src/protyle/util/reload.ts+++ b/app/src/protyle/util/reload.ts@@ -10,8 +10,10 @@ import {hideKeyboardToolbar} from "../../mobile/util/keyboardToolbar";/// #endifimport {restoreLuteMarkdownSyntax} from "./paste";import {invalidateTrackedRanges} from "./trackedRange";+import {updateBacklinkReferenceVisibility} from "../wysiwyg/backlinkReference";export const reloadProtyle = (protyle: IProtyle, focus: boolean, updateReadonly?: boolean) => {+ updateBacklinkReferenceVisibility(protyle);invalidateTrackedRanges(protyle);/// #if MOBILEhideKeyboardToolbar();diff --git a/app/src/protyle/wysiwyg/backlinkReference.ts b/app/src/protyle/wysiwyg/backlinkReference.tsnew file mode 100644index 0000000000..c3b90a402b--- /dev/null+++ b/app/src/protyle/wysiwyg/backlinkReference.ts@@ -0,0 +1,58 @@+const initialized = new WeakSet<HTMLElement>();++const isPureReference = (element: HTMLElement) => {+ const content = element.querySelector(":scope > [contenteditable]");+ let hasReference = false;+ if (!content) {+ return false;+ }+ for (const node of Array.from(content.childNodes)) {+ if (node.nodeType === Node.TEXT_NODE && !node.textContent.trim()) {+ continue;+ }+ if (node instanceof HTMLElement && (node.dataset.type || "").split(" ").includes("block-ref")) {+ hasReference = true;+ continue;+ }+ return false;+ }+ return hasReference;+};++export const updateBacklinkReferenceVisibility = (protyle: IProtyle) => {+ const element = protyle.wysiwyg.element;+ element.toggleAttribute("data-backlink-hide-reference",+ Boolean(protyle.options.backlinkData) && protyle.element.getAttribute("data-ismention") !== "true" &&+ window.siyuan.config.editor.backlinkHideReference === true);+ if (protyle.options.backlinkData && !initialized.has(element)) {+ initialized.add(element);+ // 编辑后新增的正文立即保持可见,不等待反链请求刷新。+ element.addEventListener("focusout", () => {+ element.querySelectorAll<HTMLElement>("[data-backlink-reference]").forEach(reference => {+ if (!isPureReference(reference)) {+ reference.removeAttribute("data-backlink-reference");+ reference.parentElement.removeAttribute("data-backlink-reference-list");+ }+ });+ });+ }+};++export const markBacklinkReference = (root: HTMLElement | DocumentFragment, referenceBlockID: string) => {+ if (!referenceBlockID) {+ return;+ }+ const elements = Array.from(root.querySelectorAll<HTMLElement>("[data-node-id]"));+ if (root instanceof HTMLElement && root.hasAttribute("data-node-id")) {+ elements.unshift(root);+ }+ elements.forEach(element => {+ if (element.dataset.nodeId === referenceBlockID && isPureReference(element)) {+ element.setAttribute("data-backlink-reference", "true");+ const parent = element.parentElement;+ if (parent?.classList.contains("li") && parent.querySelector(":scope > [data-node-id]") === element) {+ parent.setAttribute("data-backlink-reference-list", "true");+ }+ }+ });+};diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.tsindex 34942629b1..8c120b98f9 100644--- a/app/src/protyle/wysiwyg/renderBacklink.ts+++ b/app/src/protyle/wysiwyg/renderBacklink.ts@@ -18,8 +18,10 @@ import {} from "../util/viewFold";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {IBacklinkAVTarget, prepareBacklinkAV} from "../render/av/backlink";+import {markBacklinkReference, updateBacklinkReferenceVisibility} from "./backlinkReference";interface IBacklinkData {+ referenceBlockID?: string,attributeViewTargets?: IBacklinkAVTarget[],id?: string,revision?: string,@@ -29,6 +31,7 @@ interface IBacklinkData {}interface IBacklinkDOMRecord {+ referenceBlockID: string,revision: string,anchor: HTMLElement,targets: IBacklinkAVTarget[],@@ -57,10 +60,12 @@ const removeBacklinkDOMRecord = (record: IBacklinkDOMRecord) => {const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string) => {const template = document.createElement("template");template.innerHTML = genBreadcrumb(item.blockPaths, false, index, id) + setBacklinkFold(item.dom, item.expand);+ markBacklinkReference(template.content, item.referenceBlockID);const nodes = Array.from(template.content.childNodes);(nodes[0] as HTMLElement).setAttribute("data-backlink-revision", item.revision || "");return {record: {+ referenceBlockID: item.referenceBlockID || "",revision: item.revision || "",anchor: nodes[0] as HTMLElement,targets: item.attributeViewTargets || [],@@ -84,6 +89,7 @@ const renderBacklinkDOMNodes = (protyle: IProtyle, nodes: Node[], record: IBackl};export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[]) => {+ updateBacklinkReferenceVisibility(protyle);protyle.block.showAll = true;const element = protyle.wysiwyg.element;let records = backlinkDOMRecords.get(protyle);@@ -223,6 +229,7 @@ export const loadBreadcrumb = (protyle: IProtyle, element: HTMLElement) => {const record = backlinkDOMRecords.get(protyle)?.get(element.parentElement.dataset.backlinkId);getBacklinkDOMNodes(element.parentElement).forEach(node => {if (node instanceof HTMLElement) {+ markBacklinkReference(node, record?.referenceBlockID);prepareBacklinkAV(node, record?.targets || []);}});diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 4e17067f72..81cdf26532 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -563,6 +563,8 @@ declare namespace Config {* Whether the backlink contains children*/backlinkContainChildren: boolean;+ /** 反链面板是否隐藏传递型纯引用块 */+ backlinkHideReference: boolean;/*** Whether to show backlinks at the bottom of the document*/diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.tsindex 344fbf8c98..d08d919a8a 100644--- a/app/src/types/protyle.d.ts+++ b/app/src/types/protyle.d.ts@@ -489,6 +489,7 @@ interface IProtyleOptions {snapshot?: string},backlinkData?: {+ referenceBlockID?: string,id?: string,revision?: string,blockPaths: IBreadcrumb[],diff --git a/kernel/api/ref_revision.go b/kernel/api/ref_revision.goindex ee7f82c3ff..f3ce60e685 100644--- a/kernel/api/ref_revision.go+++ b/kernel/api/ref_revision.go@@ -31,6 +31,7 @@ type backlinkPathResponse struct {}type backlinkContextResponse struct {+ ReferenceBlockID string `json:"referenceBlockID,omitempty"`AttributeViewTargets []*model.BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`ID string `json:"id"`DOM string `json:"dom"`@@ -117,6 +118,7 @@ func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkCoret = make([]*backlinkContextResponse, 0, len(backlinks))for _, item := range backlinks {response := &backlinkContextResponse{+ ReferenceBlockID: item.ReferenceBlockID,AttributeViewTargets: item.AttributeViewTargets,ID: item.ID,DOM: item.DOM,@@ -124,12 +126,13 @@ func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkCoExpand: item.Expand,}response.Revision = hashBacklinkRevision("bci1:", struct {+ ReferenceBlockID stringAttributeViewTargets []*model.BacklinkAttributeViewTargetID stringDOM stringBlockPaths []*model.BlockPathExpand bool- }{response.AttributeViewTargets, response.ID, response.DOM, response.BlockPaths, response.Expand})+ }{response.ReferenceBlockID, response.AttributeViewTargets, response.ID, response.DOM, response.BlockPaths, response.Expand})ret = append(ret, response)}returndiff --git a/kernel/api/ref_revision_test.go b/kernel/api/ref_revision_test.goindex 6c9b649853..2353d6ae4d 100644--- a/kernel/api/ref_revision_test.go+++ b/kernel/api/ref_revision_test.go@@ -94,3 +94,17 @@ func TestNewBacklinkResponses(t *testing.T) {t.Fatalf("expected context ID and revision, got %#v", contextResponses)}}++func TestBacklinkContextRevisionIncludesReferenceBlock(t *testing.T) {+ context := &model.Backlink{ID: "parent", DOM: "unchanged"}+ before := newBacklinkContextResponses([]*model.Backlink{context})[0].Revision+ context.ReferenceBlockID = "reference"+ response := newBacklinkContextResponses([]*model.Backlink{context})[0]+ if response.ReferenceBlockID != context.ReferenceBlockID || response.Revision == before {+ t.Fatal("reference metadata must be returned and invalidate the context revision")+ }+ context.ReferenceBlockID = ""+ if newBacklinkContextResponses([]*model.Backlink{context})[0].Revision != before {+ t.Fatal("removing the hidden reference must restore the original revision")+ }+}diff --git a/kernel/conf/editor.go b/kernel/conf/editor.goindex 43fb62b0cc..7ba5d0d71c 100644--- a/kernel/conf/editor.go+++ b/kernel/conf/editor.go@@ -94,6 +94,7 @@ type Editor struct {BackmentionExpandCount int `json:"backmentionExpandCount"` // 反链提及默认展开数量BacklinkMentionExclude string `json:"backlinkMentionExclude"` // 反链提及关键字排除列表BacklinkContainChildren bool `json:"backlinkContainChildren"` // 反向链接是否包含子块进行计算+ BacklinkHideReference bool `json:"backlinkHideReference"` // 反链面板是否隐藏传递型纯引用块BacklinkShowBottom bool `json:"backlinkShowBottom"` // 是否在文档底部显示反向链接BacklinkSort *int `json:"backlinkSort"` // 反向链接排序方式BackmentionSort *int `json:"backmentionSort"` // 反链提及排序方式diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 01f11724aa..799c352ab4 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -139,6 +139,7 @@ func refreshCrossTreeMoveRefs(refreshes []crossTreeMoveRefRefresh) {}type Backlink struct {+ ReferenceBlockID string `json:"referenceBlockID,omitempty"`AttributeViewTargets []*BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`ID string `json:"id"`DOM string `json:"dom"`@@ -461,6 +462,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[st}renderNodes, expand := getBacklinkRenderNodes(node, originalRefBlockIDs)+ referenceBlockID := getBacklinkReferenceBlockID(node, renderNodes, originalRefBlockIDs[node.ID])var blockPaths []*BlockPathif (nil != node.Parent && ast.NodeDocument != node.Parent.Type) || (ast.NodeHeading != node.Type && 0 < treenode.HeadingLevel(node)) {blockPaths = buildBlockBreadcrumb(node, nil, false)@@ -496,7 +498,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[stfillBlockRefCount(renderNodes, refTree.Box)dom := renderVisibleBlockDOMByNodes(renderNodes, luteEngine)- ret = &Backlink{ID: refID, DOM: dom, BlockPaths: blockPaths, Expand: expand, node: node}+ ret = &Backlink{ID: refID, DOM: dom, BlockPaths: blockPaths, Expand: expand, ReferenceBlockID: referenceBlockID, node: node}if 0 < len(avTargets) {appendBacklinkAttributeViewTargets(ret, renderNodes, avTargets)}diff --git a/kernel/model/backlink_parent.go b/kernel/model/backlink_parent.goindex 2f9478092c..5feb98da51 100644--- a/kernel/model/backlink_parent.go+++ b/kernel/model/backlink_parent.go@@ -18,7 +18,6 @@ package modelimport ("sort"- "strings""github.com/88250/lute""github.com/88250/lute/ast"@@ -189,18 +188,7 @@ func isPureBlockRefParagraph(block *Block, luteEngine *lute.Lute) bool {return false}- hasBlockRef := false- for node := inlineTree.Root.FirstChild.FirstChild; nil != node; node = node.Next {- if treenode.IsBlockRef(node) {- hasBlockRef = true- continue- }- if ast.NodeText == node.Type && "" == strings.TrimSpace(node.Text()) {- continue- }- return false- }- return hasBlockRef+ return isPureBacklinkReferenceNode(inlineTree.Root.FirstChild)}func isFirstBacklinkParentParagraph(refBlock, parent *Block, boxID string, treeCache map[string]*parse.Tree) bool {diff --git a/kernel/model/backlink_reference.go b/kernel/model/backlink_reference.gonew file mode 100644index 0000000000..0cca9f19c2--- /dev/null+++ b/kernel/model/backlink_reference.go@@ -0,0 +1,101 @@+// 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/siyuan-note/siyuan/kernel/treenode"+)++// 只标记承担传递作用且仍有其他内容可展示的纯引用块,不修改源节点。+func getBacklinkReferenceBlockID(node *ast.Node, renderNodes []*ast.Node, originalRefID string) string {+ var reference *ast.Node+ if "" == originalRefID {+ if ast.NodeHeading != node.Type {+ return ""+ }+ reference = node+ } else {+ for _, root := range renderNodes {+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && n.ID == originalRefID {+ reference = n+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if nil != reference {+ break+ }+ }+ }+ if nil == reference || !isPureBacklinkReferenceNode(reference) {+ return ""+ }++ for _, root := range renderNodes {+ hasContent := false+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if n == reference {+ return ast.WalkSkipChildren+ }+ if n != node && n.IsBlock() && !n.IsContainerBlock() && ast.NodeDocument != n.Type {+ if ast.NodeParagraph != n.Type || hasBacklinkParagraphContent(n) {+ hasContent = true+ return ast.WalkStop+ }+ }+ return ast.WalkContinue+ })+ if hasContent {+ return reference.ID+ }+ }+ return ""+}++func isPureBacklinkReferenceNode(node *ast.Node) bool {+ if ast.NodeParagraph != node.Type && ast.NodeHeading != node.Type {+ return false+ }+ hasReference := false+ for child := node.FirstChild; nil != child; child = child.Next {+ if treenode.IsBlockRef(child) {+ hasReference = true+ continue+ }+ if ast.NodeHeadingC8hMarker == child.Type || ast.NodeText == child.Type && "" == strings.TrimSpace(child.Text()) {+ continue+ }+ return false+ }+ return hasReference+}++func hasBacklinkParagraphContent(node *ast.Node) bool {+ for child := node.FirstChild; nil != child; child = child.Next {+ if ast.NodeText != child.Type || "" != strings.TrimSpace(child.Text()) {+ return true+ }+ }+ return false+}diff --git a/kernel/model/backlink_reference_test.go b/kernel/model/backlink_reference_test.gonew file mode 100644index 0000000000..3c4cecb15d--- /dev/null+++ b/kernel/model/backlink_reference_test.go@@ -0,0 +1,98 @@+// 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 (+ "testing"++ "github.com/88250/lute/ast"+)++func TestBacklinkReferenceBlockID(t *testing.T) {+ for _, parentType := range []ast.NodeType{ast.NodeDocument, ast.NodeListItem, ast.NodeBlockquote, ast.NodeSuperBlock, ast.NodeCallout} {+ t.Run(parentType.String(), func(t *testing.T) {+ parent := &ast.Node{Type: parentType, ID: "parent"}+ ref := &ast.Node{Type: ast.NodeParagraph, ID: "reference"}+ ref.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkTextContent: "A"})+ ref.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})+ ref.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkTextContent: "B"})+ parent.AppendChild(ref)+ nodes := []*ast.Node{parent}+ if got := getBacklinkReferenceBlockID(parent, nodes, ref.ID); "" != got {+ t.Fatal("a reference without other content must remain visible")+ }+ empty := &ast.Node{Type: ast.NodeParagraph, ID: "empty"}+ empty.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})+ parent.AppendChild(empty)+ if got := getBacklinkReferenceBlockID(parent, nodes, ref.ID); "" != got {+ t.Fatal("whitespace must not count as remaining content")+ }+ content := &ast.Node{Type: ast.NodeParagraph, ID: "content"}+ content.AppendChild(&ast.Node{Type: ast.NodeImage})+ parent.AppendChild(content)+ if got := getBacklinkReferenceBlockID(parent, nodes, ref.ID); ref.ID != got {+ t.Fatalf("multiple references with image content: got %q", got)+ }+ if parent.FirstChild != ref || ref.Next != empty || ref.FirstChild.Next.Next == nil {+ t.Fatal("reference detection must preserve the source tree")+ }+ if got := getBacklinkReferenceBlockID(parent, nodes, "missing"); "" != got {+ t.Fatal("only the original reference may be hidden")+ }+ ref.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("body")})+ if got := getBacklinkReferenceBlockID(parent, nodes, ref.ID); "" != got {+ t.Fatal("references with body text must remain visible")+ }+ })+ }+}++func TestBacklinkReferenceHeading(t *testing.T) {+ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading"}+ heading.AppendChild(&ast.Node{Type: ast.NodeHeadingC8hMarker})+ heading.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkTextContent: "A"})+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("content")})+ if got := getBacklinkReferenceBlockID(heading, []*ast.Node{heading}, ""); "" != got {+ t.Fatal("standalone reference headings must remain visible")+ }+ if got := getBacklinkReferenceBlockID(heading, []*ast.Node{heading, paragraph}, ""); heading.ID != got {+ t.Fatal("a pure reference heading with content below it may be hidden")+ }+ ref := &ast.Node{Type: ast.NodeParagraph, ID: "reference"}+ ref.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkTextContent: "B"})+ if got := getBacklinkReferenceBlockID(heading, []*ast.Node{heading, ref}, ref.ID); "" != got {+ t.Fatal("the parent heading alone must not count as remaining content")+ }+ if got := getBacklinkReferenceBlockID(heading, []*ast.Node{heading, ref, paragraph}, ref.ID); ref.ID != got {+ t.Fatal("the propagated paragraph should be marked instead of its heading")+ }+ if got := getBacklinkReferenceBlockID(ref, []*ast.Node{ref}, ""); "" != got {+ t.Fatal("standalone reference paragraphs must remain visible")+ }+}++func TestPureBacklinkReferenceRejectsOtherInlineContent(t *testing.T) {+ for _, inlineType := range []ast.NodeType{ast.NodeImage, ast.NodeTag, ast.NodeCodeSpan, ast.NodeInlineMath} {+ paragraph := &ast.Node{Type: ast.NodeParagraph}+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkTextContent: "A"})+ paragraph.AppendChild(&ast.Node{Type: inlineType})+ if isPureBacklinkReferenceNode(paragraph) {+ t.Fatalf("a reference with %s must remain visible", inlineType)+ }+ }+}