An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve backlink filtering with source document criteria https://github.com/siyuan-note/siyuan/issues/18851
Daniela4b85a7a009e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 2bf1ef583a..307d080675 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "تصفية مصادر الروابط الخلفية",+ "excludeSelfBacklink": "استبعاد الروابط الخلفية من المستند الحالي",+ "nonDailyNote": "ملاحظات غير يومية","backlinkMentionExclude": "قائمة استبعاد الكلمات المفتاحية لإشارات الروابط الخلفية","entryToolbar": "شريط الأدوات","appMenuAbout": "حول SiYuan",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 26473f4ce9..90b10ebe84 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Rückverweisquellen filtern",+ "excludeSelfBacklink": "Rückverweise aus dem aktuellen Dokument ausschließen",+ "nonDailyNote": "Nicht tägliche Notizen","backlinkMentionExclude": "Ausschlussliste für Schlüsselwörter in Backlink-Erwähnungen","entryToolbar": "Symbolleiste","appMenuAbout": "Über SiYuan",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 014b09ed55..9ad52e76c9 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filter backlink sources",+ "excludeSelfBacklink": "Exclude backlinks from the current document",+ "nonDailyNote": "Non-daily notes","backlinkMentionExclude": "Backlink mention keyword exclusion list","entryToolbar": "Toolbar","appMenuAbout": "About SiYuan",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex f89e6b22af..08d25e7d67 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtrar fuentes de enlaces inversos",+ "excludeSelfBacklink": "Excluir enlaces inversos del documento actual",+ "nonDailyNote": "Notas no diarias","backlinkMentionExclude": "Lista de exclusión de palabras clave de menciones de enlaces inversos","entryToolbar": "Barra de herramientas","appMenuAbout": "Acerca de SiYuan",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f2e54d3c26..d4d9ca3237 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtrer les sources des liens retour",+ "excludeSelfBacklink": "Exclure les liens retour du document actuel",+ "nonDailyNote": "Notes non quotidiennes","backlinkMentionExclude": "Liste d’exclusion des mots-clés des mentions de liens retour","entryToolbar": "Barre d’outils","appMenuAbout": "À propos de SiYuan",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 7ef2cf41ad..1e00ba8d35 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "סינון מקורות קישורים חוזרים",+ "excludeSelfBacklink": "החרגת קישורים חוזרים מהמסמך הנוכחי",+ "nonDailyNote": "הערות שאינן יומיות","backlinkMentionExclude": "רשימת אי-הכללה של מילות מפתח לאזכורי קישורים חוזרים","entryToolbar": "סרגל כלים","appMenuAbout": "אודות SiYuan",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f89366f962..0106158f11 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "बैकलिंक स्रोत फ़िल्टर करें",+ "excludeSelfBacklink": "वर्तमान दस्तावेज़ के बैकलिंक बाहर रखें",+ "nonDailyNote": "गैर-दैनिक नोट्स","backlinkMentionExclude": "बैकलिंक उल्लेख कीवर्ड बहिष्करण सूची","entryToolbar": "टूलबार","appMenuAbout": "SiYuan के बारे में",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 72ee3ef7cc..be02d8cd6e 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filter sumber backlink",+ "excludeSelfBacklink": "Kecualikan backlink dari dokumen saat ini",+ "nonDailyNote": "Catatan nonharian","backlinkMentionExclude": "Daftar pengecualian kata kunci penyebutan backlink","entryToolbar": "Bilah alat","appMenuAbout": "Tentang SiYuan",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 87109b3a83..f24a2f8be3 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtra le origini dei backlink",+ "excludeSelfBacklink": "Escludi i backlink dal documento corrente",+ "nonDailyNote": "Note non giornaliere","backlinkMentionExclude": "Elenco di esclusione delle parole chiave delle menzioni dei backlink","entryToolbar": "Barra degli strumenti","appMenuAbout": "Informazioni su SiYuan",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 54e46bc545..d5731ad0d9 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "バックリンク元を絞り込む",+ "excludeSelfBacklink": "現在の文書からのバックリンクを除外",+ "nonDailyNote": "日記以外","backlinkMentionExclude": "バックリンク言及キーワード除外リスト","entryToolbar": "ツールバー","appMenuAbout": "SiYuan について",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 39c1a09d58..f2a12c33d6 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "백링크 출처 필터",+ "excludeSelfBacklink": "현재 문서의 백링크 제외",+ "nonDailyNote": "일일 노트 아님","backlinkMentionExclude": "백링크 언급 키워드 제외 목록","entryToolbar": "도구 모음","appMenuAbout": "SiYuan 정보",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 7a282a48ea..912a4109c5 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Backlinkbronnen filteren",+ "excludeSelfBacklink": "Backlinks uit het huidige document uitsluiten",+ "nonDailyNote": "Niet-dagelijkse notities","backlinkMentionExclude": "Uitsluitingslijst voor trefwoorden in backlinkvermeldingen","entryToolbar": "Werkbalk","appMenuAbout": "Over SiYuan",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex da7a9e5876..1e61501b9c 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtruj źródła linków zwrotnych",+ "excludeSelfBacklink": "Wyklucz linki zwrotne z bieżącego dokumentu",+ "nonDailyNote": "Notatki inne niż dzienne","backlinkMentionExclude": "Lista wykluczeń słów kluczowych wzmianek o linkach zwrotnych","entryToolbar": "Pasek narzędzi","appMenuAbout": "O programie SiYuan",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 5ed9a8f794..e68b537b6e 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtrar origens de backlinks",+ "excludeSelfBacklink": "Excluir backlinks do documento atual",+ "nonDailyNote": "Notas não diárias","backlinkMentionExclude": "Lista de exclusão de palavras-chave de menções de backlinks","entryToolbar": "Barra de ferramentas","appMenuAbout": "Sobre o SiYuan",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 7c99ca6e25..1d61cb13c2 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Фильтровать источники обратных ссылок",+ "excludeSelfBacklink": "Исключить обратные ссылки из текущего документа",+ "nonDailyNote": "Не ежедневные заметки","backlinkMentionExclude": "Список исключений ключевых слов для упоминаний обратных ссылок","entryToolbar": "Панель инструментов","appMenuAbout": "О программе SiYuan",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex c53d8d25e4..535db35c1f 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Filtrovať zdroje spätných odkazov",+ "excludeSelfBacklink": "Vylúčiť spätné odkazy z aktuálneho dokumentu",+ "nonDailyNote": "Poznámky mimo denníka","backlinkMentionExclude": "Zoznam vylúčených kľúčových slov zmienok o spätných odkazoch","entryToolbar": "Panel s nástrojmi","appMenuAbout": "O aplikácii SiYuan",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 0b4e47419a..2bcfa6992b 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "กรองแหล่งที่มาของลิงก์ย้อนกลับ",+ "excludeSelfBacklink": "ไม่รวมลิงก์ย้อนกลับจากเอกสารปัจจุบัน",+ "nonDailyNote": "บันทึกที่ไม่ใช่รายวัน","backlinkMentionExclude": "รายการยกเว้นคำสำคัญสำหรับการกล่าวถึงลิงก์ย้อนกลับ","entryToolbar": "แถบเครื่องมือ","appMenuAbout": "เกี่ยวกับ SiYuan",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 07da2bb8d7..8a0bdfdb64 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Geri bağlantı kaynaklarını filtrele",+ "excludeSelfBacklink": "Geçerli belgeden gelen geri bağlantıları hariç tut",+ "nonDailyNote": "Günlük olmayan notlar","backlinkMentionExclude": "Geri bağlantı bahsi anahtar kelime hariç tutma listesi","entryToolbar": "Araç çubuğu","appMenuAbout": "SiYuan Hakkında",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 62d0ed5c9b..e535fd33b1 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "Фільтрувати джерела зворотних посилань",+ "excludeSelfBacklink": "Виключити зворотні посилання з поточного документа",+ "nonDailyNote": "Не щоденні нотатки","backlinkMentionExclude": "Список виключень ключових слів для згадок зворотних посилань","entryToolbar": "Панель інструментів","appMenuAbout": "Про SiYuan",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex ebdb3082b9..1f8d3cc6de 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "筛选反链来源",+ "excludeSelfBacklink": "排除当前文档反链",+ "nonDailyNote": "非日记","backlinkMentionExclude": "反链提及关键字排除列表","entryToolbar": "工具栏","appMenuAbout": "关于思源笔记",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 9f019c7a44..7b6914e168 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,7 @@{+ "backlinkSourceFilter": "篩選反向連結來源",+ "excludeSelfBacklink": "排除目前文件的反向連結",+ "nonDailyNote": "非日記","backlinkMentionExclude": "反連提及關鍵字排除列表","entryToolbar": "工具列","appMenuAbout": "關於思源筆記",diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.tsindex b938ae5ef6..7924711d6d 100644--- a/app/src/layout/dock/Backlink.ts+++ b/app/src/layout/dock/Backlink.ts@@ -29,6 +29,14 @@ import {expandHeight,isHeightAnimating} from "../../util/heightAnimation";+import {+ createBacklinkSourceFilter,+ getBacklinkSourceFilterParam,+ type IBacklinkSourceFilter,+ normalizeBacklinkSourceFilter,+ type TBacklinkDailyNoteFilter+} from "./backlinkSourceFilter";+import {escapeHtml} from "../../util/escape";interface IBacklinkItemRecord {revision: string,@@ -108,6 +116,7 @@ export class Backlink extends Model {private visibilityObserver?: IntersectionObserver;private empty = false;private emptyChange?: (empty: boolean) => void;+ private sourceFilter = createBacklinkSourceFilter();constructor(options: {app: App,@@ -175,6 +184,8 @@ export class Backlink extends Model {<span class="fn__space"></span>`}<span data-type="search" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span><span class="fn__space"></span>+ <span data-type="sourceFilter" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.backlinkSourceFilter}"><svg><use xlink:href='#iconListFilterPlus'></use></svg></span>+ <span class="fn__space"></span><span data-type="sort" data-sort="${backlinkSort}" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href='#iconSort'></use></svg></span><span class="fn__space"></span><span data-type="expand" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.expand}${this.type === "bottom" ? "" : updateHotkeyAfterTip(window.siyuan.config.keymap.editor.general.expand.custom)}">@@ -394,6 +405,10 @@ export class Backlink extends Model {window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});event.stopPropagation();break;+ case "sourceFilter":+ this.showSourceFilterMenu(event);+ event.stopPropagation();+ break;case "layout":if (this.type === "bottom") {this.setBottomLayout(target, this.mTree.element);@@ -638,6 +653,86 @@ export class Backlink extends Model {}).element);}+ private applySourceFilter(filter: IBacklinkSourceFilter) {+ this.sourceFilter = normalizeBacklinkSourceFilter(filter);+ this.element.querySelector('[data-type="sourceFilter"]')?.classList.toggle(+ "block__icon--active",+ Boolean(getBacklinkSourceFilterParam(this.sourceFilter)),+ );+ this.searchBacklinks();+ }++ private showSourceFilterMenu(event: MouseEvent) {+ const dailyNoteSubmenu = ([+ ["all", window.siyuan.languages.all],+ ["only", window.siyuan.languages.dailyNote],+ ["exclude", window.siyuan.languages.nonDailyNote],+ ] as Array<[TBacklinkDailyNoteFilter, string]>).map(([value, label]) => ({+ checked: this.sourceFilter.dailyNote === value,+ iconHTML: "",+ label,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, dailyNote: value});+ }+ }));+ const notebookSubmenu: IMenu[] = [{+ checked: this.sourceFilter.excludedNotebookIDs.length === 0,+ iconHTML: "",+ label: window.siyuan.languages.allNotebooks,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: []});+ }+ }, {type: "separator"}];+ (window.siyuan.notebooks || []).filter(item => !item.closed).forEach(item => {+ notebookSubmenu.push({+ checked: !this.sourceFilter.excludedNotebookIDs.includes(item.id),+ iconHTML: "",+ label: escapeHtml(item.name),+ click: () => {+ const excludedNotebookIDs = new Set(this.sourceFilter.excludedNotebookIDs);+ if (excludedNotebookIDs.has(item.id)) {+ excludedNotebookIDs.delete(item.id);+ } else {+ excludedNotebookIDs.add(item.id);+ }+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: Array.from(excludedNotebookIDs)});+ }+ });+ });++ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconCalendar",+ label: window.siyuan.languages.dailyNote,+ type: "submenu",+ submenu: dailyNoteSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconFiles",+ label: window.siyuan.languages.allNotebooks,+ type: "submenu",+ submenu: notebookSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: this.sourceFilter.excludeSelf,+ iconHTML: "",+ label: window.siyuan.languages.excludeSelfBacklink,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludeSelf: !this.sourceFilter.excludeSelf});+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ disabled: !getBacklinkSourceFilterParam(this.sourceFilter),+ icon: "iconUndo",+ label: window.siyuan.languages.reset,+ click: () => {+ this.applySourceFilter(createBacklinkSourceFilter());+ }+ }).element);+ window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});+ }+private toggleItem(liElement: HTMLElement, isMention: boolean) {const svgElement = liElement.firstElementChild?.firstElementChild;if (!svgElement || svgElement.getAttribute("disabled")) {@@ -1154,13 +1249,26 @@ export class Backlink extends Model {}});}- const param: IObject = {+ const param: {+ sort: string,+ mSort: string,+ k: string,+ mk: string,+ id: string,+ sourceFilter?: IBacklinkSourceFilter,+ notebook?: string,+ knownRevision?: string,+ } = {sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")).toString(),mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")).toString(),k: this.inputsElement[0].value,mk: this.inputsElement[1].value,id: this.blockId,};+ const sourceFilter = getBacklinkSourceFilterParam(this.sourceFilter);+ if (sourceFilter) {+ param.sourceFilter = sourceFilter;+ }const blockId = this.blockId;if (isEncryptedBox(notebookId)) {param.notebook = notebookId;diff --git a/app/src/layout/dock/backlinkSourceFilter.test.ts b/app/src/layout/dock/backlinkSourceFilter.test.tsnew file mode 100644index 0000000000..e90715b0ae--- /dev/null+++ b/app/src/layout/dock/backlinkSourceFilter.test.ts@@ -0,0 +1,25 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ createBacklinkSourceFilter,+ getBacklinkSourceFilterParam,+ normalizeBacklinkSourceFilter+} from "./backlinkSourceFilter";++describe("backlink source filter", () => {+ it("omits the default filter", () => {+ assert.equal(getBacklinkSourceFilterParam(createBacklinkSourceFilter()), undefined);+ });++ it("normalizes notebook IDs", () => {+ assert.deepEqual(normalizeBacklinkSourceFilter({+ dailyNote: "only",+ excludedNotebookIDs: ["box-b", "", "box-a", "box-b"],+ excludeSelf: true,+ }), {+ dailyNote: "only",+ excludedNotebookIDs: ["box-a", "box-b"],+ excludeSelf: true,+ });+ });+});diff --git a/app/src/layout/dock/backlinkSourceFilter.ts b/app/src/layout/dock/backlinkSourceFilter.tsnew file mode 100644index 0000000000..5b18d10de8--- /dev/null+++ b/app/src/layout/dock/backlinkSourceFilter.ts@@ -0,0 +1,27 @@+export type TBacklinkDailyNoteFilter = "all" | "only" | "exclude";++export interface IBacklinkSourceFilter {+ dailyNote: TBacklinkDailyNoteFilter;+ excludedNotebookIDs: string[];+ excludeSelf: boolean;+}++export const createBacklinkSourceFilter = (): IBacklinkSourceFilter => ({+ dailyNote: "all",+ excludedNotebookIDs: [],+ excludeSelf: false,+});++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),+});++export const getBacklinkSourceFilterParam = (filter: IBacklinkSourceFilter) => {+ const normalized = normalizeBacklinkSourceFilter(filter);+ if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf) {+ return;+ }+ return normalized;+};diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 2edc83acca..158e2acdf1 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -212,6 +212,7 @@ func getBacklink2(c *gin.Context) {if val, ok := arg["containChildren"]; ok {containChildren = val.(bool)}+ sourceFilter := parseBacklinkSourceFilter(arg)var boxID stringvar backlinks, backmentions []*model.Pathvar linkRefsCount, mentionsCount int@@ -224,9 +225,9 @@ func getBacklink2(c *gin.Context) {return}if notebook != "" && model.IsEncryptedBox(notebook) {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter)} else {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2WithFilter(id, keyword, mentionKeyword, sort, mentionSort, containChildren, sourceFilter)}}if model.IsReadOnlyRoleContext(c) {@@ -255,6 +256,7 @@ func getBacklink2(c *gin.Context) {MentionSort intContainChildren boolNotebook string+ SourceFilter *model.BacklinkSourceFilterBacklinks []stringLinkRefsCount intBackmentions []string@@ -268,6 +270,7 @@ func getBacklink2(c *gin.Context) {mentionSort,containChildren,notebook,+ sourceFilter,backlinkPathRevisions(backlinkResponses),linkRefsCount,backlinkPathRevisions(backmentionResponses),@@ -281,6 +284,25 @@ func getBacklink2(c *gin.Context) {ret.Data = response}+func parseBacklinkSourceFilter(arg map[string]any) *model.BacklinkSourceFilter {+ filterArg, ok := arg["sourceFilter"].(map[string]any)+ if !ok {+ return nil+ }++ filter := &model.BacklinkSourceFilter{}+ filter.DailyNote, _ = filterArg["dailyNote"].(string)+ filter.ExcludeSelf, _ = filterArg["excludeSelf"].(bool)+ if notebookIDs, ok := filterArg["excludedNotebookIDs"].([]any); ok {+ for _, notebookID := range notebookIDs {+ if id, ok := notebookID.(string); ok {+ filter.ExcludedNotebookIDs = append(filter.ExcludedNotebookIDs, id)+ }+ }+ }+ return model.NormalizeBacklinkSourceFilter(filter)+}+func getBacklink(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/ref_filter_test.go b/kernel/api/ref_filter_test.gonew file mode 100644index 0000000000..3c0253f67a--- /dev/null+++ b/kernel/api/ref_filter_test.go@@ -0,0 +1,47 @@+// 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 api++import (+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestParseBacklinkSourceFilter(t *testing.T) {+ if nil != parseBacklinkSourceFilter(map[string]any{}) {+ t.Fatal("missing filter should remain nil")+ }+ if nil != parseBacklinkSourceFilter(map[string]any{"sourceFilter": map[string]any{}}) {+ t.Fatal("default filter should normalize to nil")+ }++ filter := parseBacklinkSourceFilter(map[string]any{+ "sourceFilter": map[string]any{+ "dailyNote": model.BacklinkDailyNoteExclude,+ "excludedNotebookIDs": []any{"box-b", "box-a", "box-b"},+ "excludeSelf": true,+ },+ })+ if nil == filter || model.BacklinkDailyNoteExclude != filter.DailyNote || !filter.ExcludeSelf {+ t.Fatalf("unexpected parsed filter: %+v", filter)+ }+ if !reflect.DeepEqual([]string{"box-a", "box-b"}, filter.ExcludedNotebookIDs) {+ t.Fatalf("unexpected notebook IDs: %v", filter.ExcludedNotebookIDs)+ }+}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex f1d5d3a53b..ac388379d4 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -147,6 +147,47 @@ type Backlink struct {node *ast.Node // 仅用于按文档内容顺序排序}+const (+ BacklinkDailyNoteAll = "all"+ BacklinkDailyNoteOnly = "only"+ BacklinkDailyNoteExclude = "exclude"+)++type BacklinkSourceFilter struct {+ DailyNote string `json:"dailyNote"`+ ExcludedNotebookIDs []string `json:"excludedNotebookIDs"`+ ExcludeSelf bool `json:"excludeSelf"`+}++func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceFilter {+ if nil == filter {+ return nil+ }++ dailyNote := filter.DailyNote+ if BacklinkDailyNoteOnly != dailyNote && BacklinkDailyNoteExclude != dailyNote {+ dailyNote = BacklinkDailyNoteAll+ }+ excludedNotebookIDs := make([]string, 0, len(filter.ExcludedNotebookIDs))+ excludedNotebookIDSet := map[string]bool{}+ for _, notebookID := range filter.ExcludedNotebookIDs {+ if "" == notebookID || excludedNotebookIDSet[notebookID] {+ continue+ }+ excludedNotebookIDSet[notebookID] = true+ excludedNotebookIDs = append(excludedNotebookIDs, notebookID)+ }+ sort.Strings(excludedNotebookIDs)+ if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf {+ return nil+ }+ return &BacklinkSourceFilter{+ DailyNote: dailyNote,+ ExcludedNotebookIDs: excludedNotebookIDs,+ ExcludeSelf: filter.ExcludeSelf,+ }+}+func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlight bool) (ret []*Backlink, keywords []string) {keyword = strings.TrimSpace(keyword)if "" != keyword {@@ -515,11 +556,19 @@ func getBacklinkRenderNodes(n *ast.Node, originalRefBlockIDs map[string]string)}func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool) (boxID string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {- return GetBacklink2InBox(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, "")+ return GetBacklink2WithFilter(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, nil)+}++func GetBacklink2WithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, sourceFilter *BacklinkSourceFilter) (boxID string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {+ return GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, "", sourceFilter)}// GetBacklink2InBox 与 GetBacklink2 一致,但按 boxID 路由到加密 db 或全局 db。func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {+ return GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, boxID, nil)+}++func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {keyword = strings.TrimSpace(keyword)var keywords []stringif "" != keyword {@@ -539,7 +588,11 @@ func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSortrefs = removeDuplicatedRefs(refs)linkRefs, linkRefsCount, excludeBacklinkIDs, _ := buildLinkRefsInBox(rootID, refs, keywords, boxID)- tmpBacklinks := toFlatTree(linkRefs, 0, "backlink", nil)+ filteredLinkRefs := filterBacklinkSourcesInBox(linkRefs, rootID, boxID, sourceFilter)+ if nil != NormalizeBacklinkSourceFilter(sourceFilter) {+ linkRefsCount = len(filteredLinkRefs)+ }+ tmpBacklinks := toFlatTree(filteredLinkRefs, 0, "backlink", nil)for _, l := range tmpBacklinks {l.Blocks = nilbacklinks = append(backlinks, l)@@ -908,6 +961,74 @@ func matchBacklinkKeyword(block *Block, keywords []string) bool {return false}+func filterBacklinkSourcesInBox(linkRefs []*Block, defRootID, boxID string, filter *BacklinkSourceFilter) (ret []*Block) {+ filter = NormalizeBacklinkSourceFilter(filter)+ if nil == filter {+ return linkRefs+ }+ dailyNoteRootIDs := backlinkDailyNoteRootIDsInBox(linkRefs, boxID, BacklinkDailyNoteAll != filter.DailyNote)+ return filterBacklinkSources(linkRefs, defRootID, filter, dailyNoteRootIDs)+}++func filterBacklinkSources(linkRefs []*Block, defRootID string, filter *BacklinkSourceFilter, dailyNoteRootIDs map[string]bool) (ret []*Block) {+ excludedNotebookIDs := map[string]bool{}+ for _, notebookID := range filter.ExcludedNotebookIDs {+ excludedNotebookIDs[notebookID] = true+ }+ for _, linkRef := range linkRefs {+ if nil == linkRef || excludedNotebookIDs[linkRef.Box] || filter.ExcludeSelf && defRootID == linkRef.RootID {+ continue+ }+ isDailyNote := dailyNoteRootIDs[linkRef.RootID]+ if BacklinkDailyNoteOnly == filter.DailyNote && !isDailyNote ||+ BacklinkDailyNoteExclude == filter.DailyNote && isDailyNote {+ continue+ }+ ret = append(ret, linkRef)+ }+ return+}++func backlinkDailyNoteRootIDsInBox(linkRefs []*Block, boxID string, load bool) (ret map[string]bool) {+ ret = map[string]bool{}+ if !load {+ return+ }++ var rootIDs []string+ rootIDSet := map[string]bool{}+ for _, linkRef := range linkRefs {+ if nil == linkRef || "" == linkRef.RootID || rootIDSet[linkRef.RootID] {+ continue+ }+ rootIDSet[linkRef.RootID] = true+ rootIDs = append(rootIDs, linkRef.RootID)+ }+ const batchSize = 512+ for start := 0; start < len(rootIDs); start += batchSize {+ end := min(start+batchSize, len(rootIDs))+ for _, sqlBlock := range sql.GetBlocksInBox(rootIDs[start:end], boxID) {+ block := fromSQLBlock(sqlBlock, "", 0)+ if isDailyNoteBlock(block) {+ ret[block.ID] = true+ }+ }+ }+ return+}++func isDailyNoteBlock(block *Block) bool {+ if nil == block {+ return false+ }+ for name := range block.IAL {+ if strings.HasPrefix(name, DailyNoteAttrPrefix) {+ return true+ }+ }+ return false+}+func removeDuplicatedRefs(refs []*sql.Ref) (ret []*sql.Ref) {// 同一个块中引用多个块后反链去重// De-duplication of backlinks after referencing multiple blocks in the same block https://github.com/siyuan-note/siyuan/issues/12147diff --git a/kernel/model/backlink_source_filter_test.go b/kernel/model/backlink_source_filter_test.gonew file mode 100644index 0000000000..e95e1ad36e--- /dev/null+++ b/kernel/model/backlink_source_filter_test.go@@ -0,0 +1,93 @@+// 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 (+ "reflect"+ "testing"+)++func TestNormalizeBacklinkSourceFilter(t *testing.T) {+ if nil != NormalizeBacklinkSourceFilter(nil) {+ t.Fatal("nil filter should remain nil")+ }+ if nil != NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{DailyNote: "invalid"}) {+ t.Fatal("default filter should normalize to nil")+ }++ filter := NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{+ DailyNote: BacklinkDailyNoteOnly,+ ExcludedNotebookIDs: []string{"box-b", "", "box-a", "box-b"},+ ExcludeSelf: true,+ })+ if nil == filter {+ t.Fatal("active filter should not normalize to nil")+ }+ if BacklinkDailyNoteOnly != filter.DailyNote || !filter.ExcludeSelf {+ t.Fatalf("unexpected normalized filter: %+v", filter)+ }+ if !reflect.DeepEqual([]string{"box-a", "box-b"}, filter.ExcludedNotebookIDs) {+ t.Fatalf("unexpected notebook IDs: %v", filter.ExcludedNotebookIDs)+ }+}++func TestFilterBacklinkSources(t *testing.T) {+ linkRefs := []*Block{+ {ID: "daily", RootID: "daily-root", Box: "box-a"},+ {ID: "regular", RootID: "regular-root", Box: "box-a"},+ {ID: "excluded-box", RootID: "other-root", Box: "box-b"},+ {ID: "self", RootID: "target-root", Box: "box-a"},+ }+ dailyNoteRootIDs := map[string]bool{"daily-root": true}++ onlyDaily := filterBacklinkSources(linkRefs, "target-root", &BacklinkSourceFilter{+ DailyNote: BacklinkDailyNoteOnly,+ }, dailyNoteRootIDs)+ assertBacklinkSourceIDs(t, onlyDaily, []string{"daily"})++ excludeDaily := filterBacklinkSources(linkRefs, "target-root", &BacklinkSourceFilter{+ DailyNote: BacklinkDailyNoteExclude,+ }, dailyNoteRootIDs)+ assertBacklinkSourceIDs(t, excludeDaily, []string{"regular", "excluded-box", "self"})++ combined := filterBacklinkSources(linkRefs, "target-root", &BacklinkSourceFilter{+ DailyNote: BacklinkDailyNoteExclude,+ ExcludedNotebookIDs: []string{"box-b"},+ ExcludeSelf: true,+ }, dailyNoteRootIDs)+ assertBacklinkSourceIDs(t, combined, []string{"regular"})+}++func TestIsDailyNoteBlock(t *testing.T) {+ if isDailyNoteBlock(nil) || isDailyNoteBlock(&Block{IAL: map[string]string{"custom-test": "value"}}) {+ t.Fatal("regular block should not be recognized as a daily note")+ }+ if !isDailyNoteBlock(&Block{IAL: map[string]string{"custom-dailynote-20260819": "20260819"}}) {+ t.Fatal("daily note attribute should be recognized")+ }+}++func assertBacklinkSourceIDs(t *testing.T, blocks []*Block, expected []string) {+ t.Helper()+ actual := make([]string, 0, len(blocks))+ for _, block := range blocks {+ actual = append(actual, block.ID)+ }+ if !reflect.DeepEqual(expected, actual) {+ t.Fatalf("expected IDs %v, got %v", expected, actual)+ }+}