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 collapsing backlinks by block type by default https://github.com/siyuan-note/siyuan/issues/19257
Daniel99e5bd19acb6
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 0a1c39e70d..9e7ca784cf 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "طي افتراضي حسب نوع الكتلة","backlinkHideReference": "إخفاء كتل المراجع في الروابط الخلفية الموروثة","backlinkHideReferenceTip": "إخفاء الكتل التي تحتوي فقط على مراجع كتل في الروابط الخلفية الموروثة عندما يبقى محتوى آخر ظاهرًا، وإظهارها مجددًا أثناء التحرير","uploadInsertTargetUnavailable": "لم تعد وجهة الرفع الأصلية متاحة. لم تُدرج النتيجة؛ تم الاحتفاظ بالملفات المرفوعة.",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex dff1c07750..2b5a6a5afe 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Standardmäßig nach Blocktyp einklappen","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.",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 73ff49116a..546733249e 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Collapse by block type by default","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.",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 075ed72e7d..29184cff36 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Contraer por tipo de bloque de forma predeterminada","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.",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 0e025b53e5..2e192f405c 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Replier par défaut selon le type de bloc","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.",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex cf6c32835f..b16f09256d 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "כיווץ כברירת מחדל לפי סוג בלוק","backlinkHideReference": "הסתרת בלוקי הפניה בקישורים נכנסים מועברים","backlinkHideReferenceTip": "הסתרת בלוקים המכילים רק הפניות לבלוקים בקישורים נכנסים מועברים כאשר תוכן אחר נשאר גלוי, והצגתם מחדש בזמן עריכה","uploadInsertTargetUnavailable": "יעד ההעלאה המקורי אינו זמין עוד. התוצאה לא הוכנסה; הקבצים שהועלו נשמרים.",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 3433f3c83e..654bfcc003 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "ब्लॉक प्रकार के अनुसार डिफ़ॉल्ट रूप से संक्षिप्त करें","backlinkHideReference": "प्रसारित बैकलिंक में संदर्भ ब्लॉक छिपाएँ","backlinkHideReferenceTip": "प्रसारित बैकलिंक में केवल ब्लॉक संदर्भ वाले ब्लॉक छिपाएँ जब अन्य सामग्री दिखाई देती रहे, और संपादन के दौरान उन्हें फिर से दिखाएँ","uploadInsertTargetUnavailable": "अपलोड का मूल लक्ष्य अब उपलब्ध नहीं है। परिणाम सम्मिलित नहीं किया गया; अपलोड की गई फ़ाइलें सुरक्षित रखी गई हैं।",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 063b3e1736..6c2529be38 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Ciutkan menurut jenis blok secara bawaan","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.",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 9a9c331abe..0c66042992 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Comprimi per tipo di blocco per impostazione predefinita","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.",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex ca3e3c0011..d532b7a47f 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "ブロックの種類ごとにデフォルトで折りたたむ","backlinkHideReference": "伝播型バックリンクの参照ブロックを非表示","backlinkHideReferenceTip": "伝播型バックリンクで、ほかに表示できる内容がある場合はブロック参照のみのブロックを非表示にし、編集中は再表示します","uploadInsertTargetUnavailable": "アップロード元の挿入先が無効になったため、結果を挿入しませんでした。アップロード済みのファイルは保持されます。",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 3ce73e3eee..46294d4fdb 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "블록 유형별로 기본 접기","backlinkHideReference": "전파된 백링크의 참조 블록 숨기기","backlinkHideReferenceTip": "전파된 백링크에서 다른 표시할 내용이 있으면 블록 참조만 포함된 블록을 숨기고 편집 중에는 다시 표시","uploadInsertTargetUnavailable": "원래 업로드 대상이 더 이상 유효하지 않습니다. 결과를 삽입하지 않았으며 업로드된 파일은 유지됩니다.",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex abe5e20189..6c96fa498d 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Standaard inklappen per bloktype","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.",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex e50342c79c..c59d3a709d 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Domyślnie zwijaj według typu bloku","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.",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex c82f3d4102..78d599a163 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Recolher por tipo de bloco por padrão","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.",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex d523ad1a1f..38d655f711 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Сворачивать по типу блока по умолчанию","backlinkHideReference": "Скрывать блоки ссылок в наследуемых обратных ссылках","backlinkHideReferenceTip": "Скрывать блоки, содержащие только ссылки на блоки, в наследуемых обратных ссылках, если остаётся другое содержимое, и показывать их при редактировании","uploadInsertTargetUnavailable": "Исходное место вставки больше недоступно. Результат не вставлен; загруженные файлы сохранены.",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 63ec2dba29..e3ccf91d4b 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Predvolene zbaliť podľa typu bloku","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é.",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex ca20c03938..718ef607c4 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "ยุบตามประเภทบล็อกโดยค่าเริ่มต้น","backlinkHideReference": "ซ่อนบล็อกอ้างอิงในลิงก์ย้อนกลับที่ส่งต่อ","backlinkHideReferenceTip": "ซ่อนบล็อกที่มีเฉพาะการอ้างอิงบล็อกในลิงก์ย้อนกลับที่ส่งต่อเมื่อยังมีเนื้อหาอื่นให้แสดง และแสดงอีกครั้งขณะแก้ไข","uploadInsertTargetUnavailable": "ปลายทางเดิมของการอัปโหลดไม่พร้อมใช้งานแล้ว จึงไม่ได้แทรกผลลัพธ์ แต่ไฟล์ที่อัปโหลดแล้วจะยังคงอยู่",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 9fe3951aee..549d2a0520 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Blok türüne göre varsayılan olarak daralt","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.",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 7af12f5c31..909aef45c2 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "Згортати за типом блоку за замовчуванням","backlinkHideReference": "Приховувати блоки посилань в успадкованих зворотних посиланнях","backlinkHideReferenceTip": "Приховувати блоки, що містять лише посилання на блоки, в успадкованих зворотних посиланнях, якщо залишається інший вміст, і показувати їх під час редагування","uploadInsertTargetUnavailable": "Початкове місце вставлення більше недоступне. Результат не вставлено; завантажені файли збережено.",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex ef2a4e6b77..0b712f7d7f 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "按块类型默认折叠","backlinkHideReference": "隐藏传递型反链的引用块","backlinkHideReferenceTip": "在反链面板中隐藏仅含块引用且仍有其他内容可展示的传递型引用块,编辑时恢复显示","uploadInsertTargetUnavailable": "原上传目标已失效,未回填结果;已上传的文件会保留。",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex ddd18e1bf8..224adca9c3 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "backlinkFoldByType": "依區塊類型預設摺疊","backlinkHideReference": "隱藏傳遞型反向連結的引用區塊","backlinkHideReferenceTip": "在反向連結面板中隱藏僅含區塊引用且仍有其他內容可顯示的傳遞型引用區塊,編輯時恢復顯示","uploadInsertTargetUnavailable": "原上傳目標已失效,未填入結果;已上傳的檔案會保留。",diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scssindex 0120800edf..41ecb6b8df 100644--- a/app/src/assets/scss/protyle/_protyle.scss+++ b/app/src/assets/scss/protyle/_protyle.scss@@ -539,6 +539,20 @@}.sy__backlink {+ [data-backlink-type-folded] {+ display: none !important;+ }++ .backlinkTypeFold {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ width: auto;+ font-size: 12px;+ line-height: 20px;+ flex-shrink: 0;+ }+> .backlinkList,> .backlinkMList {> .b3-list > .backlinkList__item {diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex c4bd8f2752..4eca76dcd2 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -21,6 +21,7 @@ import {getAllEditor} from "../getAll";import {isMobile} from "../../util/functions";import {hideElements} from "../../protyle/ui/hideElements";import {renderBacklink} from "../../protyle/wysiwyg/renderBacklink";+import {BACKLINK_BLOCK_TYPES, configureBacklinkTypeFold, normalizeBacklinkFoldTypes} from "../../protyle/wysiwyg/backlinkTypeFold";import {getBottomBacklinkVisibility,getInitialBacklinkSectionState,@@ -853,37 +854,33 @@ export class BacklinkContent extends Model {}private showSourceFilterMenu(event: MouseEvent) {- const blockTypeSubmenu: IMenu[] = [{- label: window.siyuan.languages.all,- checked: !this.sourceFilter.excludedBlockTypes.length,- iconHTML: "",- click: () => this.applySourceFilter({...this.sourceFilter, excludedBlockTypes: []}),- }, {type: "separator"}];- [- ["NodeDocument", "doc"], ["NodeParagraph", "paragraph"], ["NodeHeading", "headings"],- ["NodeList", "list1"], ["NodeListItem", "listItem"], ["NodeBlockquote", "quote"],- ["NodeSuperBlock", "superBlock"], ["NodeCallout", "callout"],- ["NodeTabs", "tabs"], ["NodeTabItem", "tabItem"], ["NodeAttributeView", "database"],- ["NodeTable", "table"], ["NodeCodeBlock", "code"], ["NodeMathBlock", "math"],- ["NodeBlockQueryEmbed", "embedBlock"], ["NodeVideo", "video"], ["NodeAudio", "audio"],- ["NodeWidget", "widget"], ["NodeHTMLBlock", "HTML"], ["NodeIFrame", "IFrame"],- ["NodeThematicBreak", "line"], ["NodeCustomBlock", "custom"],- ].forEach(([type, label]) => {- blockTypeSubmenu.push({- label: window.siyuan.languages[label] || label,- checked: !this.sourceFilter.excludedBlockTypes.includes(type),- iconHTML: "",- click: () => {- const excluded = new Set(this.sourceFilter.excludedBlockTypes);- if (excluded.has(type)) {- excluded.delete(type);- } else {- excluded.add(type);- }- this.applySourceFilter({...this.sourceFilter, excludedBlockTypes: Array.from(excluded)});- },+ const foldedTypes = normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes"));+ const applyFoldTypes = (types: string[]) => {+ this.viewState?.set("foldedBlockTypes", types);+ BACKLINK_BLOCK_TYPES.forEach(([type]) => {+ if (foldedTypes.includes(type) !== types.includes(type)) {+ const field = `type-fold-generation:${type}`;+ this.viewState?.set(field, (this.viewState.get<number>(field) || 0) + 1);+ }});- });+ this.itemRecords[0].forEach(record => {+ if (record.editor && this.viewState) {+ configureBacklinkTypeFold(record.editor.protyle, types, this.viewState);+ }+ });+ };+ const blockTypeFoldSubmenu: IMenu[] = [{+ label: window.siyuan.languages.reset,+ icon: "iconUndo",+ disabled: foldedTypes.length === 0,+ click: () => applyFoldTypes([]),+ }, {type: "separator"}, ...BACKLINK_BLOCK_TYPES.map(([type, label]) => ({+ label: window.siyuan.languages[label] || label,+ checked: foldedTypes.includes(type),+ iconHTML: "",+ click: () => applyFoldTypes(foldedTypes.includes(type) ?+ foldedTypes.filter(item => item !== type) : [...foldedTypes, type]),+ }))];const dailyNoteSubmenu = ([["all", window.siyuan.languages.all],["only", window.siyuan.languages.dailyNote],@@ -923,10 +920,11 @@ export class BacklinkContent extends Model {window.siyuan.menus.menu.remove();window.siyuan.menus.menu.append(new MenuItem({- icon: "iconListFilterPlus",- label: window.siyuan.languages.type,+ icon: "iconContract",+ label: window.siyuan.languages.backlinkFoldByType,type: "submenu",- submenu: blockTypeSubmenu,+ disabled: !this.viewStateLoaded || !this.viewState,+ submenu: blockTypeFoldSubmenu,}).element);window.siyuan.menus.menu.append(new MenuItem({icon: "iconCalendar",@@ -950,11 +948,12 @@ export class BacklinkContent extends Model {}).element);window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);window.siyuan.menus.menu.append(new MenuItem({- disabled: !getBacklinkSourceFilterParam(this.sourceFilter),+ disabled: !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0,icon: "iconUndo",label: window.siyuan.languages.reset,click: () => {this.applySourceFilter(createBacklinkSourceFilter());+ applyFoldTypes([]);}}).element);window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});@@ -1148,6 +1147,9 @@ export class BacklinkContent extends Model {this.editors.push(editor);record.editor = editor;const service = this.viewState;+ if (!isMention && service) {+ configureBacklinkTypeFold(editor.protyle, normalizeBacklinkFoldTypes(service.get("foldedBlockTypes")), service);+ }const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);const anchorQueryKey = this.renderedQueryKey;if (service) {diff --git a/app/src/layout/dock/backlinkSourceFilter.test.ts b/app/src/layout/dock/backlinkSourceFilter.test.tsindex 48147019da..e90715b0ae 100644--- a/app/src/layout/dock/backlinkSourceFilter.test.ts+++ b/app/src/layout/dock/backlinkSourceFilter.test.ts@@ -20,16 +20,6 @@ describe("backlink source filter", () => {dailyNote: "only",excludedNotebookIDs: ["box-a", "box-b"],excludeSelf: true,- excludedBlockTypes: [],});});-- it("keeps a block type filter active and resets it to all types", () => {- const filter = getBacklinkSourceFilterParam({- ...createBacklinkSourceFilter(),- excludedBlockTypes: ["NodeParagraph", "NodeAttributeView", "NodeParagraph", ""],- });- assert.deepEqual(filter.excludedBlockTypes, ["NodeAttributeView", "NodeParagraph"]);- assert.equal(getBacklinkSourceFilterParam({...filter, excludedBlockTypes: []}), undefined);- });});diff --git a/app/src/layout/dock/backlinkSourceFilter.ts b/app/src/layout/dock/backlinkSourceFilter.tsindex e42ac22b45..5b18d10de8 100644--- a/app/src/layout/dock/backlinkSourceFilter.ts+++ b/app/src/layout/dock/backlinkSourceFilter.ts@@ -4,27 +4,23 @@ export interface IBacklinkSourceFilter {dailyNote: TBacklinkDailyNoteFilter;excludedNotebookIDs: string[];excludeSelf: boolean;- excludedBlockTypes?: string[];}export const createBacklinkSourceFilter = (): IBacklinkSourceFilter => ({dailyNote: "all",excludedNotebookIDs: [],excludeSelf: false,- excludedBlockTypes: [],});export const normalizeBacklinkSourceFilter = (filter: IBacklinkSourceFilter): IBacklinkSourceFilter => ({dailyNote: ["only", "exclude"].includes(filter.dailyNote) ? filter.dailyNote : "all",excludedNotebookIDs: Array.from(new Set(filter.excludedNotebookIDs.filter(Boolean))).sort(),excludeSelf: Boolean(filter.excludeSelf),- excludedBlockTypes: Array.from(new Set((filter.excludedBlockTypes || []).filter(Boolean))).sort(),});export const getBacklinkSourceFilterParam = (filter: IBacklinkSourceFilter) => {const normalized = normalizeBacklinkSourceFilter(filter);- if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf &&- normalized.excludedBlockTypes.length === 0) {+ if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf) {return;}return normalized;diff --git a/app/src/protyle/wysiwyg/backlinkTypeFold.test.ts b/app/src/protyle/wysiwyg/backlinkTypeFold.test.tsnew file mode 100644index 0000000000..950b2311bb--- /dev/null+++ b/app/src/protyle/wysiwyg/backlinkTypeFold.test.ts@@ -0,0 +1,105 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {+ configureBacklinkTypeFold,+ getBacklinkTypeFoldKey,+ normalizeBacklinkFoldTypes,+ setBacklinkTypeFoldExpandHandler,+ updateBacklinkTypeFolds,+} from "./backlinkTypeFold";++class ElementFixture {+ public dataset: Record<string, string> = {};+ public nextElementSibling: ElementFixture;+ public button: ElementFixture;+ public className = "";+ public type = "";+ public innerHTML = "";+ public onclick: (event: {preventDefault: () => void, stopPropagation: () => void}) => void;+ public attributes = new Map<string, string>();+ public classList = {contains: (name: string) => this.className.split(" ").includes(name)};+ public owner: ElementFixture;+ public text = "";++ public querySelector() { return this.button; }+ public prepend(button: ElementFixture) { this.button = button; button.owner = this; }+ public appendChild(text: string) { this.text = text; }+ public addEventListener() { /* 测试只模拟按钮点击。 */ }+ public setAttribute(key: string, value: string) { this.attributes.set(key, value); }+ public getAttribute(key: string) { return this.attributes.get(key) ?? null; }+ public hasAttribute(key: string) { return this.attributes.has(key); }+ public toggleAttribute(key: string, enabled: boolean) {+ if (enabled) {+ this.attributes.set(key, "");+ } else {+ this.attributes.delete(key);+ }+ }+ public remove() { this.owner.button = undefined; }+}++const makeOccurrence = (id: string, type: string) => {+ const anchor = new ElementFixture();+ anchor.dataset = {backlinkId: id, backlinkType: type};+ anchor.className = "protyle-breadcrumb__bar";+ const content = new ElementFixture();+ anchor.nextElementSibling = content;+ return {anchor, content};+};++test("normalizes supported types and distinguishes item identities and policy generations", () => {+ assert.deepEqual(normalizeBacklinkFoldTypes(["NodeAttributeView", "unknown", "NodeAttributeView"]), ["NodeAttributeView"]);+ assert.deepEqual(normalizeBacklinkFoldTypes(null), []);+ assert.notEqual(getBacklinkTypeFoldKey("a", "NodeHeading"), getBacklinkTypeFoldKey("b", "NodeHeading"));+ assert.notEqual(getBacklinkTypeFoldKey("a", "NodeHeading"), getBacklinkTypeFoldKey("a", "NodeHeading", 1));+});++test("collapses whole occurrences, preserves neighbors and source folds, and restores manual choices", t => {+ const globals = globalThis as unknown as Record<string, unknown>;+ const previousDocument = globals.document;+ const previousWindow = globals.window;+ globals.document = {createElement: () => new ElementFixture(), createTextNode: (text: string) => text};+ globals.window = {siyuan: {languages: {database: "Database", expand: "Expand", collapse: "Collapse"}}};+ t.after(() => {+ globals.document = previousDocument;+ globals.window = previousWindow;+ });+ const database = makeOccurrence("database", "NodeAttributeView");+ const heading = makeOccurrence("heading", "NodeHeading");+ database.content.nextElementSibling = heading.anchor;+ heading.content.setAttribute("fold", "1");+ const anchors = [database.anchor, heading.anchor];+ const protyle = {wysiwyg: {element: {querySelectorAll: () => anchors}}} as unknown as IProtyle;+ const expanded: string[] = [];+ setBacklinkTypeFoldExpandHandler(protyle, id => expanded.push(id));+ const values = new Map<string, unknown>();+ const store = {+ get: <T>(key: string) => values.get(key) as T,+ set: <T>(key: string, value: T) => { values.set(key, value); },+ remove: (key: string) => { values.delete(key); },+ };+ configureBacklinkTypeFold(protyle, [], store);+ assert.equal(database.anchor.button, undefined);+ configureBacklinkTypeFold(protyle, ["NodeAttributeView"], store);+ assert.equal(database.content.attributes.has("data-backlink-type-folded"), true);+ assert.equal(heading.content.attributes.has("data-backlink-type-folded"), false);+ assert.equal(heading.content.getAttribute("fold"), "1");+ assert.equal(database.anchor.button.getAttribute("aria-expanded"), "false");+ database.anchor.button.onclick({preventDefault() {}, stopPropagation() {}});+ assert.deepEqual(expanded, ["database"]);+ assert.equal(database.content.attributes.has("data-backlink-type-folded"), false);+ updateBacklinkTypeFolds(protyle);+ assert.deepEqual(expanded, ["database"]);+ assert.equal(database.anchor.button.getAttribute("aria-expanded"), "true");++ const replacement = makeOccurrence("database", "NodeAttributeView");+ anchors[0] = replacement.anchor;+ configureBacklinkTypeFold(protyle, ["NodeAttributeView"], store);+ assert.equal(replacement.anchor.button.getAttribute("aria-expanded"), "true");+ store.set("type-fold-generation:NodeAttributeView", 1);+ updateBacklinkTypeFolds(protyle);+ assert.equal(replacement.anchor.button.getAttribute("aria-expanded"), "false");+ configureBacklinkTypeFold(protyle, [], store);+ assert.equal(replacement.anchor.button, undefined);+ assert.equal(replacement.content.attributes.has("data-backlink-type-folded"), false);+});diff --git a/app/src/protyle/wysiwyg/backlinkTypeFold.ts b/app/src/protyle/wysiwyg/backlinkTypeFold.tsnew file mode 100644index 0000000000..4dea0c798d--- /dev/null+++ b/app/src/protyle/wysiwyg/backlinkTypeFold.ts@@ -0,0 +1,82 @@+import type {IViewFoldStateStore} from "../util/viewFold";++export const BACKLINK_BLOCK_TYPES = [+ ["NodeDocument", "doc"], ["NodeParagraph", "paragraph"], ["NodeHeading", "headings"],+ ["NodeList", "list1"], ["NodeListItem", "listItem"], ["NodeBlockquote", "quote"],+ ["NodeSuperBlock", "superBlock"], ["NodeCallout", "callout"],+ ["NodeTabs", "tabs"], ["NodeTabItem", "tabItem"], ["NodeAttributeView", "database"],+ ["NodeTable", "table"], ["NodeCodeBlock", "code"], ["NodeMathBlock", "math"],+ ["NodeBlockQueryEmbed", "embedBlock"], ["NodeVideo", "video"], ["NodeAudio", "audio"],+ ["NodeWidget", "widget"], ["NodeHTMLBlock", "HTML"], ["NodeIFrame", "IFrame"],+ ["NodeThematicBreak", "line"], ["NodeCustomBlock", "custom"],+];++export const normalizeBacklinkFoldTypes = (value: unknown): string[] => Array.isArray(value) ?+ BACKLINK_BLOCK_TYPES.map(([type]) => type).filter(type => value.includes(type)) : [];++const contexts = new WeakMap<IProtyle, {types: string[], store: IViewFoldStateStore}>();+const expandHandlers = new WeakMap<IProtyle, (id: string) => void>();++export const setBacklinkTypeFoldExpandHandler = (protyle: IProtyle, handler: (id: string) => void) => {+ expandHandlers.set(protyle, handler);+};++export const configureBacklinkTypeFold = (protyle: IProtyle, types: string[], store: IViewFoldStateStore) => {+ contexts.set(protyle, {types: normalizeBacklinkFoldTypes(types), store});+ updateBacklinkTypeFolds(protyle);+};++export const getBacklinkTypeFoldKey = (id: string, type: string, generation = 0) =>+ `type-fold:${encodeURIComponent(type)}:${generation}:${encodeURIComponent(id)}`;++export const updateBacklinkTypeFolds = (protyle: IProtyle) => {+ const context = contexts.get(protyle);+ if (!context) {+ return;+ }+ protyle.wysiwyg.element.querySelectorAll<HTMLElement>(".protyle-breadcrumb__bar[data-backlink-id]").forEach(anchor => {+ const type = anchor.dataset.backlinkType;+ const enabled = context.types.includes(type);+ const key = getBacklinkTypeFoldKey(anchor.dataset.backlinkId, type,+ context.store.get<number>(`type-fold-generation:${type}`) || 0);+ const collapsed = enabled && context.store.get<boolean>(key) !== false;+ let button = anchor.querySelector<HTMLButtonElement>(".backlinkTypeFold");+ if (!enabled) {+ button?.remove();+ } else {+ if (!button) {+ button = document.createElement("button");+ button.className = "backlinkTypeFold block__icon block__icon--show";+ button.type = "button";+ button.addEventListener("mousedown", event => {+ event.preventDefault();+ event.stopPropagation();+ });+ anchor.prepend(button);+ }+ button.onclick = event => {+ event.preventDefault();+ event.stopPropagation();+ context.store.set(key, button.getAttribute("aria-expanded") === "true");+ updateBacklinkTypeFolds(protyle);+ };+ const labelKey = BACKLINK_BLOCK_TYPES.find(([nodeType]) => nodeType === type)?.[1];+ const label = window.siyuan.languages[labelKey] || labelKey;+ button.innerHTML = `<svg><use xlink:href="#${collapsed ? "iconRight" : "iconDown"}"></use></svg>`;+ button.appendChild(document.createTextNode(label));+ button.setAttribute("aria-expanded", String(!collapsed));+ button.setAttribute("aria-label", `${collapsed ? window.siyuan.languages.expand : window.siyuan.languages.collapse} ${label}`);+ }+ // 仅折叠当前反链条目的内容,保留分隔栏和原有块折叠状态。+ let next = anchor.nextElementSibling;+ let revealed = false;+ while (next && !next.classList.contains("protyle-breadcrumb__bar")) {+ revealed = revealed || (!collapsed && next.hasAttribute("data-backlink-type-folded"));+ next.toggleAttribute("data-backlink-type-folded", collapsed);+ next = next.nextElementSibling;+ }+ if (revealed) {+ expandHandlers.get(protyle)?.(anchor.dataset.backlinkId);+ }+ });+};diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.tsindex 8c120b98f9..0b166d35e9 100644--- a/app/src/protyle/wysiwyg/renderBacklink.ts+++ b/app/src/protyle/wysiwyg/renderBacklink.ts@@ -19,8 +19,10 @@ import {import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {IBacklinkAVTarget, prepareBacklinkAV} from "../render/av/backlink";import {markBacklinkReference, updateBacklinkReferenceVisibility} from "./backlinkReference";+import {setBacklinkTypeFoldExpandHandler, updateBacklinkTypeFolds} from "./backlinkTypeFold";interface IBacklinkData {+ type?: string,referenceBlockID?: string,attributeViewTargets?: IBacklinkAVTarget[],id?: string,@@ -63,6 +65,7 @@ const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string)markBacklinkReference(template.content, item.referenceBlockID);const nodes = Array.from(template.content.childNodes);(nodes[0] as HTMLElement).setAttribute("data-backlink-revision", item.revision || "");+ (nodes[0] as HTMLElement).setAttribute("data-backlink-type", item.type || "");return {record: {referenceBlockID: item.referenceBlockID || "",@@ -98,6 +101,13 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])backlinkDOMRecords.set(protyle, records);element.replaceChildren();}+ setBacklinkTypeFoldExpandHandler(protyle, id => {+ const record = records.get(id);+ if (record) {+ // 展开后重新计算数据库等内容的布局,避免沿用隐藏时的尺寸。+ void renderBacklinkDOMNodes(protyle, getBacklinkDOMNodes(record.anchor), record);+ }+ });const ids = new Set(backlinkData.map((item, index) => item.id || `legacy-${index}`));records.forEach((record, id) => {@@ -163,7 +173,10 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {disabledProtyle(protyle);}- return Promise.all(applyPromises).then(() => undefined);+ updateBacklinkTypeFolds(protyle);+ return Promise.all(applyPromises).then(() => {+ updateBacklinkTypeFolds(protyle);+ });};// 传递型折叠处理@@ -236,6 +249,7 @@ export const loadBreadcrumb = (protyle: IProtyle, element: HTMLElement) => {avRender(element.parentElement.parentElement, protyle);blockRender(protyle, element.parentElement.parentElement);void applyViewFoldStates(protyle);+ updateBacklinkTypeFolds(protyle);if (getResponse.data.isSyncing) {disabledForeverProtyle(protyle);} else if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex bb4e750819..b5668763e1 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -295,13 +295,6 @@ func parseBacklinkSourceFilter(arg map[string]any) *model.BacklinkSourceFilter {}filter := &model.BacklinkSourceFilter{}- if blockTypes, ok := filterArg["excludedBlockTypes"].([]any); ok {- for _, blockType := range blockTypes {- if value, ok := blockType.(string); ok {- filter.ExcludedBlockTypes = append(filter.ExcludedBlockTypes, value)- }- }- }filter.DailyNote, _ = filterArg["dailyNote"].(string)filter.ExcludeSelf, _ = filterArg["excludeSelf"].(bool)if notebookIDs, ok := filterArg["excludedNotebookIDs"].([]any); ok {diff --git a/kernel/api/ref_filter_test.go b/kernel/api/ref_filter_test.goindex 4d2fefd986..3c0253f67a 100644--- a/kernel/api/ref_filter_test.go+++ b/kernel/api/ref_filter_test.go@@ -36,7 +36,6 @@ func TestParseBacklinkSourceFilter(t *testing.T) {"dailyNote": model.BacklinkDailyNoteExclude,"excludedNotebookIDs": []any{"box-b", "box-a", "box-b"},"excludeSelf": true,- "excludedBlockTypes": []any{"NodeAttributeView", 42, "NodeParagraph", "NodeAttributeView", "unknown"},},})if nil == filter || model.BacklinkDailyNoteExclude != filter.DailyNote || !filter.ExcludeSelf {@@ -45,7 +44,4 @@ func TestParseBacklinkSourceFilter(t *testing.T) {if !reflect.DeepEqual([]string{"box-a", "box-b"}, filter.ExcludedNotebookIDs) {t.Fatalf("unexpected notebook IDs: %v", filter.ExcludedNotebookIDs)}- if !reflect.DeepEqual([]string{"NodeAttributeView", "NodeParagraph"}, filter.ExcludedBlockTypes) {- t.Fatalf("unexpected block types: %v", filter.ExcludedBlockTypes)- }}diff --git a/kernel/api/ref_revision.go b/kernel/api/ref_revision.goindex f3ce60e685..501d0273b7 100644--- a/kernel/api/ref_revision.go+++ b/kernel/api/ref_revision.go@@ -31,6 +31,7 @@ type backlinkPathResponse struct {}type backlinkContextResponse struct {+ Type string `json:"type,omitempty"`ReferenceBlockID string `json:"referenceBlockID,omitempty"`AttributeViewTargets []*model.BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`ID string `json:"id"`@@ -118,6 +119,7 @@ func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkCoret = make([]*backlinkContextResponse, 0, len(backlinks))for _, item := range backlinks {response := &backlinkContextResponse{+ Type: item.Type,ReferenceBlockID: item.ReferenceBlockID,AttributeViewTargets: item.AttributeViewTargets,ID: item.ID,@@ -126,13 +128,14 @@ func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkCoExpand: item.Expand,}response.Revision = hashBacklinkRevision("bci1:", struct {+ Type stringReferenceBlockID stringAttributeViewTargets []*model.BacklinkAttributeViewTargetID stringDOM stringBlockPaths []*model.BlockPathExpand bool- }{response.ReferenceBlockID, response.AttributeViewTargets, response.ID, response.DOM, response.BlockPaths, response.Expand})+ }{response.Type, 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 2353d6ae4d..b176e59468 100644--- a/kernel/api/ref_revision_test.go+++ b/kernel/api/ref_revision_test.go@@ -108,3 +108,13 @@ func TestBacklinkContextRevisionIncludesReferenceBlock(t *testing.T) {t.Fatal("removing the hidden reference must restore the original revision")}}++func TestBacklinkContextRevisionIncludesBlockType(t *testing.T) {+ context := &model.Backlink{ID: "source", DOM: "unchanged", Type: "NodeParagraph"}+ before := newBacklinkContextResponses([]*model.Backlink{context})[0].Revision+ context.Type = "NodeAttributeView"+ response := newBacklinkContextResponses([]*model.Backlink{context})[0]+ if response.Type != context.Type || response.Revision == before {+ t.Fatal("block type must be returned and invalidate the context revision")+ }+}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 660e322870..eba6d51f5d 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -139,6 +139,7 @@ func refreshCrossTreeMoveRefs(refreshes []crossTreeMoveRefRefresh) {}type Backlink struct {+ Type string `json:"type,omitempty"`ReferenceBlockID string `json:"referenceBlockID,omitempty"`AttributeViewTargets []*BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`ID string `json:"id"`@@ -159,7 +160,6 @@ type BacklinkSourceFilter struct {DailyNote string `json:"dailyNote"`ExcludedNotebookIDs []string `json:"excludedNotebookIDs"`ExcludeSelf bool `json:"excludeSelf"`- ExcludedBlockTypes []string `json:"excludedBlockTypes"`}func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceFilter {@@ -181,21 +181,13 @@ func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceexcludedNotebookIDs = append(excludedNotebookIDs, notebookID)}sort.Strings(excludedNotebookIDs)- excludedBlockTypes := []string{}- for _, blockType := range filter.ExcludedBlockTypes {- if "" != treenode.TypeAbbr(blockType) && !gulu.Str.Contains(blockType, excludedBlockTypes) {- excludedBlockTypes = append(excludedBlockTypes, blockType)- }- }- sort.Strings(excludedBlockTypes)- if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf && 0 == len(excludedBlockTypes) {+ if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf {return nil}return &BacklinkSourceFilter{DailyNote: dailyNote,ExcludedNotebookIDs: excludedNotebookIDs,ExcludeSelf: filter.ExcludeSelf,- ExcludedBlockTypes: excludedBlockTypes,}}@@ -514,6 +506,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[stdom := renderVisibleBlockDOMByNodes(renderNodes, luteEngine)ret = &Backlink{ID: refID, DOM: dom, BlockPaths: blockPaths, Expand: expand, ReferenceBlockID: referenceBlockID, node: node}+ ret.Type = node.Type.String()if 0 < len(avTargets) {appendBacklinkAttributeViewTargets(ret, renderNodes, avTargets)}@@ -889,9 +882,6 @@ func filterBacklinkSources(linkRefs []*Block, defRootID string, filter *Backlinkif nil == linkRef || excludedNotebookIDs[linkRef.Box] || filter.ExcludeSelf && defRootID == linkRef.RootID {continue}- if gulu.Str.Contains(linkRef.Type, filter.ExcludedBlockTypes) {- continue- }isDailyNote := dailyNoteRootIDs[linkRef.RootID]if BacklinkDailyNoteOnly == filter.DailyNote && !isDailyNote ||BacklinkDailyNoteExclude == filter.DailyNote && isDailyNote {diff --git a/kernel/model/backlink_source_filter_test.go b/kernel/model/backlink_source_filter_test.goindex 105296a8d1..e95e1ad36e 100644--- a/kernel/model/backlink_source_filter_test.go+++ b/kernel/model/backlink_source_filter_test.go@@ -81,26 +81,6 @@ func TestIsDailyNoteBlock(t *testing.T) {}}-func TestBacklinkBlockTypeFilter(t *testing.T) {- filter := NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{- ExcludedBlockTypes: []string{"NodeAttributeView", "", "unknown", "NodeAttributeView"},- })- if nil == filter || !reflect.DeepEqual(filter.ExcludedBlockTypes, []string{"NodeAttributeView"}) {- t.Fatalf("unexpected block types: %+v", filter)- }- database := &Block{ID: "database", Type: "NodeAttributeView"}- parent := &Block{ID: "parent", Type: "NodeHeading", Children: []*Block{database}}- paragraph := &Block{ID: "paragraph", Type: "NodeParagraph", RootID: "same-document"}- refs := []*Block{database, parent, paragraph}- filtered := filterBacklinkSources(refs, "target", filter, nil)- assertBacklinkSourceIDs(t, filtered, []string{"parent", "paragraph"})- if len(parent.Children) != 1 || parent.Children[0] != database || len(refs) != 3 {- t.Fatal("filter must preserve nested content and original references")- }- filter.ExcludedBlockTypes = append(filter.ExcludedBlockTypes, "NodeHeading", "NodeParagraph")- assertBacklinkSourceIDs(t, filterBacklinkSources(refs, "target", filter, nil), []string{})-}-func assertBacklinkSourceIDs(t *testing.T, blocks []*Block, expected []string) {t.Helper()actual := make([]string, 0, len(blocks))