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 filtering backlinks by database fields https://github.com/siyuan-note/siyuan/issues/20802
Daniel726fc46a60eb
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex f6cfc66795..8abb344f36 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "حقول قاعدة البيانات","listMindmapPaletteOcean": "محيط","listMindmapPaletteSunset": "غروب","listMindmapPaletteLavender": "لافندر",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 2084f76dc9..dff9371420 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Datenbankfelder","listMindmapPaletteOcean": "Ozean","listMindmapPaletteSunset": "Sonnenuntergang","listMindmapPaletteLavender": "Lavendel",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex d741a976d5..99f5905175 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Database fields","listMindmapPaletteOcean": "Ocean","listMindmapPaletteSunset": "Sunset","listMindmapPaletteLavender": "Lavender",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 2059dc7612..f4b44896d8 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Campos de la base de datos","listMindmapPaletteOcean": "Océano","listMindmapPaletteSunset": "Atardecer","listMindmapPaletteLavender": "Lavanda",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex c5be57b1f6..8d7f74fb7f 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Champs de la base de données","listMindmapPaletteOcean": "Océan","listMindmapPaletteSunset": "Coucher de soleil","listMindmapPaletteLavender": "Lavande",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 253816c2fc..3acc114d12 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "שדות מסד נתונים","listMindmapPaletteOcean": "אוקיינוס","listMindmapPaletteSunset": "שקיעה","listMindmapPaletteLavender": "לבנדר",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 71c8d97465..0f332b9e1e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "डेटाबेस फ़ील्ड","listMindmapPaletteOcean": "महासागर","listMindmapPaletteSunset": "सूर्यास्त","listMindmapPaletteLavender": "लैवेंडर",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex b60543e37e..84d414daf5 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Bidang basis data","listMindmapPaletteOcean": "Samudra","listMindmapPaletteSunset": "Senja","listMindmapPaletteLavender": "Lavendel",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex ba4ac4ee87..077e35725b 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Campi del database","listMindmapPaletteOcean": "Oceano","listMindmapPaletteSunset": "Tramonto","listMindmapPaletteLavender": "Lavanda",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex cfc1bdea99..c327619b27 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "データベースのフィールド","listMindmapPaletteOcean": "海","listMindmapPaletteSunset": "夕日","listMindmapPaletteLavender": "ラベンダー",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 98659c95e2..dba78ba507 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "데이터베이스 필드","listMindmapPaletteOcean": "바다","listMindmapPaletteSunset": "일몰","listMindmapPaletteLavender": "라벤더",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 9ac572652d..aeb8fd66fc 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Databasevelden","listMindmapPaletteOcean": "Oceaan","listMindmapPaletteSunset": "Zonsondergang","listMindmapPaletteLavender": "Lavendel",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex a9bb3c62c4..684e453cb3 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Pola bazy danych","listMindmapPaletteOcean": "Ocean","listMindmapPaletteSunset": "Zachód słońca","listMindmapPaletteLavender": "Lawenda",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex c3a53ed8e2..aae1e9ed07 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Campos do banco de dados","listMindmapPaletteOcean": "Oceano","listMindmapPaletteSunset": "Pôr do sol","listMindmapPaletteLavender": "Lavanda",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 56ed331bdb..6264452d57 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Поля базы данных","listMindmapPaletteOcean": "Океан","listMindmapPaletteSunset": "Закат","listMindmapPaletteLavender": "Лавандовая",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex e588bf7536..0f4cf0f086 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Polia databázy","listMindmapPaletteOcean": "Oceán","listMindmapPaletteSunset": "Západ slnka","listMindmapPaletteLavender": "Levanduľa",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex d2fddce0b7..8123509a35 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Поља базе података","listMindmapPaletteOcean": "Океан","listMindmapPaletteSunset": "Залазак сунца","listMindmapPaletteLavender": "Лаванда",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 106cbcfd55..2bd2ee0aec 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "ฟิลด์ฐานข้อมูล","listMindmapPaletteOcean": "มหาสมุทร","listMindmapPaletteSunset": "พระอาทิตย์ตก","listMindmapPaletteLavender": "ลาเวนเดอร์",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 2e6cd962b4..bd77260917 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Veritabanı alanları","listMindmapPaletteOcean": "Okyanus","listMindmapPaletteSunset": "Gün batımı","listMindmapPaletteLavender": "Lavanta",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 1b974bb353..f7e7339c2f 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "Поля бази даних","listMindmapPaletteOcean": "Океан","listMindmapPaletteSunset": "Захід сонця","listMindmapPaletteLavender": "Лавандова",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 19f9f932ef..978a170ae4 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "数据库字段","listMindmapPaletteOcean": "海洋","listMindmapPaletteSunset": "日落","listMindmapPaletteLavender": "薰衣草",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex a822bc10f9..df46dfd693 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "backlinkDatabaseFields": "資料庫欄位","listMindmapPaletteOcean": "海洋","listMindmapPaletteSunset": "日落","listMindmapPaletteLavender": "薰衣草",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.syindex df4916f38c..9a12348571 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy@@ -6,7 +6,7 @@"id": "20200924101256-f8b1sbi","title": "Ref Content Block","type": "doc",- "updated": "20261015221015"+ "updated": "20261022133332"},"Children": [{@@ -167,7 +167,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104091542-v1yca4p",- "updated": "20210512154424"+ "updated": "20261022133332"},"Children": [{@@ -360,6 +360,76 @@}]},+ {+ "ID": "20261022133332-4f7jodf",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20261022133332-4f7jodf",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Filter backlinks by database fields"+ }+ ]+ },+ {+ "ID": "20261022133332-rl5m4fh",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-rl5m4fh",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "In the backlink panel or bottom backlinks, open "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Filter backlink sources"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Database fields"+ },+ {+ "Type": "NodeText",+ "Data": " to select a database containing the source blocks and configure combined field conditions. Only sources bound to that database and matching the conditions are shown. With no field conditions, all backlink sources bound to the selected database are shown. The database view filters and mentions remain unchanged. This is available on desktop and mobile."+ }+ ]+ },+ {+ "ID": "20261022133332-hnpzneg",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-hnpzneg",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "To clear only the database conditions, choose "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Reset"+ },+ {+ "Type": "NodeText",+ "Data": " in the database menu. Other source filters remain active."+ }+ ]+ },{"ID": "20220623201008-is3nn7u","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.syindex c000129391..86790c0d9d 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy@@ -6,7 +6,7 @@"id": "20200813013559-sgbzl5k","title": "引用内容块","type": "doc",- "updated": "20261015221015"+ "updated": "20261022133332"},"Children": [{@@ -167,7 +167,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104090557-841hf2w",- "updated": "20210512154248"+ "updated": "20261022133332"},"Children": [{@@ -376,6 +376,76 @@}]},+ {+ "ID": "20261022133332-njjdkzb",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20261022133332-njjdkzb",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "按数据库字段筛选反链"+ }+ ]+ },+ {+ "ID": "20261022133332-yn53f3z",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-yn53f3z",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在反链面板或底部反链中,打开 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "筛选反链来源"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "数据库字段"+ },+ {+ "Type": "NodeText",+ "Data": ",选择来源块已加入的数据库,再设置字段组合条件。只显示绑定到所选数据库且满足条件的反链来源;不设置字段条件时,显示所有绑定到该库的反链来源。此操作不会修改数据库原视图的筛选,也不影响提及。桌面端和移动端均支持此功能。"+ }+ ]+ },+ {+ "ID": "20261022133332-p6btymk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-p6btymk",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在数据库菜单中选择 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "重置"+ },+ {+ "Type": "NodeText",+ "Data": " 可清除数据库条件,其他来源筛选保持不变。"+ }+ ]+ },{"ID": "20220623194755-30vtsr7","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.syindex 4f4d255241..285ef7b972 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy@@ -6,7 +6,7 @@"id": "20211226120247-63nd8y5","title": "引用内容區塊","type": "doc",- "updated": "20261015221015"+ "updated": "20261022133332"},"Children": [{@@ -167,7 +167,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226120337-nfx8mlg",- "updated": "20230630092034"+ "updated": "20261022133332"},"Children": [{@@ -338,6 +338,76 @@}]},+ {+ "ID": "20261022133332-ng7mw26",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20261022133332-ng7mw26",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "依資料庫欄位篩選反向連結"+ }+ ]+ },+ {+ "ID": "20261022133332-9qfgdrg",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-9qfgdrg",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在反向連結面板或底部反向連結中,開啟 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "篩選反向連結來源"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "資料庫欄位"+ },+ {+ "Type": "NodeText",+ "Data": ",選擇來源區塊已加入的資料庫,再設定欄位組合條件。只顯示綁定到所選資料庫且符合條件的反向連結來源;未設定欄位條件時,顯示所有綁定到該資料庫的反向連結來源。此操作不會修改資料庫原檢視的篩選,也不影響提及。桌面端和行動端均支援此功能。"+ }+ ]+ },+ {+ "ID": "20261022133332-ws4lowq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-ws4lowq",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在資料庫選單中選擇 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "重置"+ },+ {+ "Type": "NodeText",+ "Data": " 可清除資料庫條件,其他來源篩選保持不變。"+ }+ ]+ },{"ID": "20220623200754-u00gfsg","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.syindex 2c204d307c..57c79f0274 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy@@ -7,7 +7,7 @@"id": "20240530101000-uxno1yp","title": "コンテンツブロックの参照","type": "doc",- "updated": "20261015221015"+ "updated": "20261022133332"},"Children": [{@@ -172,7 +172,7 @@"Properties": {"ID": "20240530101000-at31i2r","id": "20240530101000-avpxozm",- "updated": "20240530101000"+ "updated": "20261022133332"},"Children": [{@@ -364,6 +364,76 @@}]},+ {+ "ID": "20261022133332-0jxmx6d",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20261022133332-0jxmx6d",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "データベースのフィールドでバックリンクを絞り込む"+ }+ ]+ },+ {+ "ID": "20261022133332-do55tkp",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-do55tkp",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "バックリンクパネルまたは下部のバックリンクで "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "バックリンク元を絞り込む"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "データベースのフィールド"+ },+ {+ "Type": "NodeText",+ "Data": " を開き、参照元ブロックが登録されているデータベースを選択して、フィールド条件を組み合わせます。選択したデータベースにバインドされ、条件を満たす参照元のみが表示されます。フィールド条件を設定しない場合は、そのデータベースにバインドされた参照元がすべて表示されます。データベースの元のビューのフィルタやメンションは変更されません。デスクトップ版とモバイル版の両方で利用できます。"+ }+ ]+ },+ {+ "ID": "20261022133332-68vgkre",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261022133332-68vgkre",+ "updated": "20261022133332"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "データベースのメニューで "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "リセット"+ },+ {+ "Type": "NodeText",+ "Data": " を選択すると、データベースの条件だけを解除できます。他の参照元フィルタは保持されます。"+ }+ ]+ },{"ID": "20240530101000-k5rp4xa","Type": "NodeHeading",diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex ed11c80bc6..32461a2620 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -51,6 +51,7 @@ import {import {escapeHtml} from "../../util/escape";import {ViewStateService} from "../../util/viewState";import {loadBacklinkRefFilterMenu} from "./backlinkRefFilterMenu";+import {loadBacklinkDatabaseFilterMenu} from "./backlinkDatabaseFilter";import {BacklinkMentionCache, getBacklinkMentionQueryKey} from "./backlinkMentionCache";import {BottomBacklinkScroll} from "./bottomBacklinkScroll";import {@@ -963,7 +964,8 @@ export class BacklinkContent extends Model {countElement.textContent = total.toString();countElement.classList.toggle("fn__none", total === 0 && this.type !== "bottom");if (this.type === "bottom") {- const hideBacklinks = total === 0 && !this.inputsElement[0].value && !this.globalList?.hasError;+ const hideBacklinks = total === 0 && !this.inputsElement[0].value &&+ !getBacklinkSourceFilterParam(this.sourceFilter) && !this.globalList?.hasError;this.element.classList.toggle("sy__backlink--backlinks-empty", hideBacklinks);const empty = hideBacklinks &&this.element.classList.contains("sy__backlink--mentions-empty");@@ -1117,6 +1119,23 @@ export class BacklinkContent extends Model {}}).element);const refFilterGeneration = this.viewStateGeneration;+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.backlinkDatabaseFields,+ icon: "iconDatabase",+ checked: Boolean(this.sourceFilter.database),+ disabled: !this.blockId || window.siyuan.isPublish,+ loadSubmenu: () => loadBacklinkDatabaseFilterMenu({+ id: this.blockId,+ notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",+ keyword: this.inputsElement[0].value,+ filter: this.sourceFilter,+ target,+ protyle: this.ownerProtyle || this.editors[0]?.protyle,+ getSelected: () => this.sourceFilter.database,+ isCurrent: () => !this.destroyed && refFilterGeneration === this.viewStateGeneration,+ apply: database => this.applySourceFilter({...this.sourceFilter, database}),+ }),+ }).element);let refFilterMenuElement: HTMLElement;window.siyuan.menus.menu.append(new MenuItem({iconHTML: "",@@ -2229,7 +2248,8 @@ export class BacklinkContent extends Model {});}const bottomVisibility = this.type === "bottom" ?- getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk) : undefined;+ getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk,+ Boolean(getBacklinkSourceFilterParam(this.sourceFilter))) : undefined;if (bottomVisibility) {if (this.globalList?.hasError) {bottomVisibility.hideBacklinks = false;@@ -2422,7 +2442,7 @@ export class BacklinkContent extends Model {this.globalList?.markDirty();this.indexChangeVersion++;this.dirty = true;- this.pendingFull = this.pendingFull || Boolean(change.backlinkFull);+ this.pendingFull = this.pendingFull || Boolean(change.backlinkFull) || Boolean(this.sourceFilter.database);change.rootIDs?.forEach(rootID => this.pendingRootIDs.add(rootID));this.itemRecords.forEach(records => records.forEach((record, rootID) => {if (this.pendingFull || this.pendingRootIDs.has(rootID)) {diff --git a/app/src/layout/dock/backlinkDatabaseFilter.test.ts b/app/src/layout/dock/backlinkDatabaseFilter.test.tsnew file mode 100644index 0000000000..dc9e064828--- /dev/null+++ b/app/src/layout/dock/backlinkDatabaseFilter.test.ts@@ -0,0 +1,71 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import type {IOpenAVPanelOptions} from "../../protyle/render/av/panels/types";+import type {IBacklinkSourceFilter} from "./backlinkSourceFilter";++const setup = () => {+ let current = true;+ let selected: IBacklinkSourceFilter["database"];+ let opened: IOpenAVPanelOptions;+ let resolve: (value: unknown) => void;+ const requests: unknown[] = [];+ const methods = {} as typeof import("./backlinkDatabaseFilter");+ runInNewContext(transpileModule(readFileSync("src/layout/dock/backlinkDatabaseFilter.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText, {+ exports: methods,+ require: (name: string) => ({+ "../../util/fetch": {fetchSyncPost: (route: string, payload: unknown) => {+ requests.push({route, payload});+ return new Promise(done => { resolve = done; });+ }},+ "../../util/escape": {escapeHtml: (text: string) => text.replaceAll("<", "<")},+ "../../protyle/render/av/openMenuPanel": {openMenuPanel: (options: IOpenAVPanelOptions) => { opened = options; }},+ })[name],+ window: {siyuan: {config: {editor: {backlinkContainChildren: true}}, languages: {reset: "Reset", invalid: "Invalid", emptyContent: "Empty"}}},+ });+ const options = {+ id: "topic", notebook: "", keyword: "", filter: {dailyNote: "all", excludeSelf: false, excludedNotebookIDs: []} as IBacklinkSourceFilter,+ target: {} as HTMLElement,+ isCurrent: () => current,+ getSelected: () => selected,+ apply: (value?: IBacklinkSourceFilter["database"]) => { selected = value; },+ };+ return {methods, options, requests, respond: (value: unknown) => resolve(value),+ stale: () => { current = false; }, get selected() { return selected; }, get opened() { return opened; }};+};++test("database selection and query editing never mutate database metadata or another selection", async () => {+ const h = setup();+ const database = {id: "tasks", name: "<Tasks>", keys: [{id: "status", name: "Status", type: "text"}]};+ const pending = h.methods.loadBacklinkDatabaseFilterMenu(h.options);+ h.respond({code: 0, data: [database]});+ const menu = await pending;+ assert.equal(menu[2].label, "<Tasks>");+ menu[2].click(null, null);+ assert.equal(h.selected.avID, "tasks");+ assert.equal(h.opened.protyle, undefined);+ assert.ok("rows" in h.opened.data.view);+ assert.equal(h.opened.data.view.rows.length, 0);+ const filters: IAVFilter[] = [{column: "status", operator: "Contains", value: {type: "text", text: {content: "open"}}}];+ h.opened.filterOperation.save(filters);+ assert.equal(h.selected.filters, filters);+ assert.equal(database.keys[0].name, "Status");+ menu[0].click(null, null);+ assert.equal(h.selected, undefined);+ h.opened.filterOperation.save(filters);+ assert.equal(h.selected, undefined, "a stale panel must not re-enable cleared database filtering");+ assert.equal(h.requests.length, 1);+});++test("database candidates arriving after the target changes do not reopen a filter panel", async () => {+ const h = setup();+ const pending = h.methods.loadBacklinkDatabaseFilterMenu(h.options);+ h.stale();+ h.respond({code: 0, data: [{id: "tasks", name: "Tasks", keys: []}]});+ assert.equal((await pending).length, 0);+ assert.equal(h.opened, undefined);+});diff --git a/app/src/layout/dock/backlinkDatabaseFilter.ts b/app/src/layout/dock/backlinkDatabaseFilter.tsnew file mode 100644index 0000000000..0c52b8e264--- /dev/null+++ b/app/src/layout/dock/backlinkDatabaseFilter.ts@@ -0,0 +1,92 @@+import {fetchSyncPost} from "../../util/fetch";+import {escapeHtml} from "../../util/escape";+import {openMenuPanel} from "../../protyle/render/av/openMenuPanel";+import type {BacklinkDatabase} from "../../types/api";+import type {IBacklinkSourceFilter} from "./backlinkSourceFilter";++export const getBacklinkDatabaseFilterData = (database: BacklinkDatabase, filters: IAVFilter[]): IAV => ({+ id: database.id,+ name: database.name,+ viewID: "",+ viewType: "table",+ views: [],+ view: {+ id: "",+ type: "table",+ filters: JSON.parse(JSON.stringify(filters.length ? filters : [{combination: "and", filters: []}])),+ sorts: [],+ columns: database.keys.map(key => ({...key, wrap: false, pin: false, width: "", hidden: false})),+ rows: [],+ rowCount: 0,+ },+});++export const loadBacklinkDatabaseFilterMenu = async (options: {+ id: string;+ notebook: string;+ keyword: string;+ filter: IBacklinkSourceFilter;+ target: HTMLElement;+ protyle?: IProtyle;+ isCurrent: () => boolean;+ getSelected: () => IBacklinkSourceFilter["database"];+ apply: (database?: IBacklinkSourceFilter["database"]) => void;+}): Promise<IMenu[]> => {+ const response = await fetchSyncPost("/api/ref/getBacklinkDatabases", {+ id: options.id,+ notebook: options.notebook,+ keyword: options.keyword,+ containChildren: window.siyuan.config.editor.backlinkContainChildren,+ sourceFilter: options.filter,+ });+ if (!options.isCurrent() || response.code !== 0 || !response.data) {+ return [];+ }+ const candidates = response.data;+ const selected = options.getSelected();+ const items: IMenu[] = [{+ label: window.siyuan.languages.reset,+ icon: "iconUndo",+ checked: !selected,+ click: () => {+ if (options.isCurrent()) {+ options.apply();+ }+ },+ }, {type: "separator"}];+ candidates.forEach(database => items.push({+ label: escapeHtml(database.name),+ iconHTML: "",+ checked: selected?.avID === database.id,+ bind: element => { element.title = database.id; },+ click: () => {+ if (!options.isCurrent()) {+ return;+ }+ const current = options.getSelected();+ const filters = current?.avID === database.id ? current.filters : [];+ options.apply({avID: database.id, filters});+ openMenuPanel({+ protyle: options.protyle,+ blockElement: options.target,+ anchorElement: options.target,+ type: "filters",+ data: getBacklinkDatabaseFilterData(database, filters),+ filterOperation: {+ save: filters => {+ if (options.isCurrent() && options.getSelected()?.avID === database.id) {+ options.apply({avID: database.id, filters});+ }+ },+ },+ });+ },+ }));+ if (selected && !candidates.some(item => item.id === selected.avID)) {+ items.push({type: "readonly", label: `${escapeHtml(selected.avID)} (${window.siyuan.languages.invalid})`});+ }+ if (candidates.length === 0) {+ items.push({type: "readonly", label: window.siyuan.languages.emptyContent});+ }+ return items;+};diff --git a/app/src/layout/dock/backlinkRefresh.test.ts b/app/src/layout/dock/backlinkRefresh.test.tsindex 76c8c5dc19..e0f176c11c 100644--- a/app/src/layout/dock/backlinkRefresh.test.ts+++ b/app/src/layout/dock/backlinkRefresh.test.ts@@ -37,6 +37,13 @@ describe("shouldDeferBottomBacklinkRefresh", () => {});describe("getBottomBacklinkVisibility", () => {+ it("keeps the filter controls available after a database condition matches nothing", () => {+ assert.deepEqual(getBottomBacklinkVisibility(0, 0, "", "", true), {+ hideBacklinks: false,+ hideMentions: true,+ hidePanel: false,+ });+ });it("hides empty sections independently", () => {assert.deepEqual(getBottomBacklinkVisibility(0, 0, "", ""), {hideBacklinks: true,diff --git a/app/src/layout/dock/backlinkRefresh.ts b/app/src/layout/dock/backlinkRefresh.tsindex 851f4c7131..f37e95eb6d 100644--- a/app/src/layout/dock/backlinkRefresh.ts+++ b/app/src/layout/dock/backlinkRefresh.ts@@ -14,9 +14,10 @@ export const getBottomBacklinkVisibility = (linkRefsCount: number,mentionsCount: number,backlinkKeyword: string,- mentionKeyword: string+ mentionKeyword: string,+ sourceFilterActive = false,) => {- const hideBacklinks = linkRefsCount === 0 && !backlinkKeyword;+ const hideBacklinks = linkRefsCount === 0 && !backlinkKeyword && !sourceFilterActive;const hideMentions = mentionsCount === 0 && !mentionKeyword;return {hideBacklinks,diff --git a/app/src/layout/dock/backlinkSourceFilter.test.ts b/app/src/layout/dock/backlinkSourceFilter.test.tsindex ddd2eba396..bb9d63aa66 100644--- a/app/src/layout/dock/backlinkSourceFilter.test.ts+++ b/app/src/layout/dock/backlinkSourceFilter.test.ts@@ -7,6 +7,15 @@ import {} from "./backlinkSourceFilter";describe("backlink source filter", () => {+ it("keeps membership-only database filters active and clones their conditions", () => {+ const source = {...createBacklinkSourceFilter(), database: {avID: "database", filters: [] as IAVFilter[]}};+ const normalized = getBacklinkSourceFilterParam(source);+ assert.equal(normalized.database.avID, "database");+ normalized.database.filters.push({column: "field", operator: "Is empty", value: {type: "text"}});+ assert.equal(source.database.filters.length, 0);+ delete source.database;+ assert.equal(getBacklinkSourceFilterParam(source), undefined);+ });it("omits the default filter", () => {assert.equal(getBacklinkSourceFilterParam(createBacklinkSourceFilter()), undefined);});diff --git a/app/src/layout/dock/backlinkSourceFilter.ts b/app/src/layout/dock/backlinkSourceFilter.tsindex 5b072b7c58..e07b426c53 100644--- a/app/src/layout/dock/backlinkSourceFilter.ts+++ b/app/src/layout/dock/backlinkSourceFilter.ts@@ -5,6 +5,7 @@ export interface IBacklinkSourceFilter {excludedNotebookIDs: string[];excludeSelf: boolean;excludedRefDefIDs?: string[];+ database?: {avID: string; filters: IAVFilter[]};}export const createBacklinkSourceFilter = (): IBacklinkSourceFilter => ({@@ -22,12 +23,16 @@ export const normalizeBacklinkSourceFilter = (filter: IBacklinkSourceFilter): IBexcludedNotebookIDs: Array.from(new Set(filter.excludedNotebookIDs.filter(Boolean))).sort(),excludeSelf: Boolean(filter.excludeSelf),excludedRefDefIDs: normalizeExcludedRefDefIDs(filter.excludedRefDefIDs),+ ...(filter.database ? {database: {+ avID: filter.database.avID,+ filters: JSON.parse(JSON.stringify(filter.database.filters || [])),+ }} : {}),});export const getBacklinkSourceFilterParam = (filter: IBacklinkSourceFilter) => {const normalized = normalizeBacklinkSourceFilter(filter);if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf &&- normalized.excludedRefDefIDs.length === 0) {+ normalized.excludedRefDefIDs.length === 0 && !normalized.database) {return;}return normalized;diff --git a/app/src/protyle/render/av/filter.ts b/app/src/protyle/render/av/filter.tsindex 472e87ed28..4084b80d5e 100644--- a/app/src/protyle/render/av/filter.ts+++ b/app/src/protyle/render/av/filter.ts@@ -15,7 +15,7 @@ import {getAVColorStyle} from "./color";import {setFilterSelectPosition} from "./selectPosition";import {closeInlineFilterDropdowns} from "./filterDropdown";-interface FilterEditorOptions {+export interface FilterEditorOptions {action?: IAVFilterOperation["action"];keyID?: string;save?: (filters: IAVFilter[]) => void;@@ -196,12 +196,16 @@ export const addFilter = (options: {targetGroupFilters.push(filter);const blockID = options.blockElement.getAttribute("data-node-id");// 保存新增的占位条件,inline 控件立即可编辑(无需弹层)- transaction(options.protyle, [- getSetFiltersOperation(options.avId, blockID,- JSON.parse(JSON.stringify(options.data.view.filters)), options.filterOperation)- ], [- getSetFiltersOperation(options.avId, blockID, oldFilters, options.filterOperation)- ]);+ if (options.filterOperation?.save) {+ options.filterOperation.save(options.data.view.filters);+ } else {+ transaction(options.protyle, [+ getSetFiltersOperation(options.avId, blockID,+ JSON.parse(JSON.stringify(options.data.view.filters)), options.filterOperation)+ ], [+ getSetFiltersOperation(options.avId, blockID, oldFilters, options.filterOperation)+ ]);+ }options.menuElement.innerHTML = getFiltersHTML(options.data);setPosition(options.menuElement, options.tabRect.right - options.menuElement.clientWidth, options.tabRect.bottom, options.tabRect.height, 0, true);}diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex f2f3345bc3..3ffc1feae3 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -29,7 +29,7 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {options.destroyCallback?.();return;}- const avID = options.blockElement.getAttribute("data-av-id");+ const avID = options.data?.id || options.blockElement.getAttribute("data-av-id");const avPageSize = getPageSize(options.blockElement);// config/properties/sorts/filters/contextFilter/switcher 菜单只需要字段/视图元数据,不需要行数据,// 跳过行渲染以提升大体量视图下的响应速度。@@ -56,6 +56,10 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {}const blockID = options.blockElement.getAttribute("data-node-id");const saveFilters = (newFilters: IAVFilter[], oldFilters: IAVFilter[]) => {+ if (options.filterOperation?.save) {+ options.filterOperation.save(newFilters);+ return;+ }const operation = (filters: IAVFilter[]): IOperation => ({action: options.filterOperation?.action || "setAttrViewFilters",avID,@@ -144,12 +148,13 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {inputElement.dispatchEvent(new Event("input"));}};- let tabRect = options.blockElement.querySelector(`.av__views, .av__row[data-col-id="${options.colId}"] > .block__logo`)?.getBoundingClientRect();+ let tabRect = options.anchorElement?.getBoundingClientRect() ||+ options.blockElement.querySelector(`.av__views, .av__row[data-col-id="${options.colId}"] > .block__logo`)?.getBoundingClientRect();const resizeMenu = ignoreRows && !isMobile() ? () => {if (!menuElement.isConnected) {return;}- tabRect = options.blockElement.querySelector(".av__views")?.getBoundingClientRect();+ tabRect = options.anchorElement?.getBoundingClientRect() || options.blockElement.querySelector(".av__views")?.getBoundingClientRect();if (!tabRect) {return;}@@ -256,7 +261,7 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {break;}if (type === "close") {- if (!options.protyle.toolbar.subElement.classList.contains("fn__none")) {+ if (options.protyle?.toolbar && !options.protyle.toolbar.subElement.classList.contains("fn__none")) {// 优先关闭资源文件搜索hideElements(["util"], options.protyle);} else if (!options.keepMenuOpen &&@@ -266,7 +271,9 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {closeCB?.();avPanelElement.remove();setTimeout(() => {- focusBlock(options.blockElement);+ if (!options.anchorElement) {+ focusBlock(options.blockElement);+ }}, Constants.TIMEOUT_TRANSITION); // 单选使用 enter 修改选项后会滚动}if (!options.keepMenuOpen || !isProgrammaticClose) {diff --git a/app/src/protyle/render/av/panels/config.ts b/app/src/protyle/render/av/panels/config.tsindex 05d84be6e5..0f231aad6a 100644--- a/app/src/protyle/render/av/panels/config.ts+++ b/app/src/protyle/render/av/panels/config.ts@@ -41,6 +41,12 @@ export const configPanel: IAVPanelDescriptor = {return "handled";},"go-config": (context, action) => {+ if (context.options.filterOperation?.save) {+ context.avPanelElement.remove();+ action.event.preventDefault();+ action.event.stopPropagation();+ return "handled";+ }if (context.menuElement.classList.contains("av__conditional-panel") ||context.menuElement.classList.contains("av__automation-panel")) {delete context.menuElement.dataset.positionX;diff --git a/app/src/protyle/render/av/panels/lifecycle.test.ts b/app/src/protyle/render/av/panels/lifecycle.test.tsindex e0c78e87d2..caa838844d 100644--- a/app/src/protyle/render/av/panels/lifecycle.test.ts+++ b/app/src/protyle/render/av/panels/lifecycle.test.ts@@ -69,6 +69,28 @@ test("window resizing uses the automation height constraint only while its panelassert.deepEqual(h.calls, ["setPosition"]);});+for (const mobile of [false, true]) {+ test(`query filter panels save without database transactions or an editor (${mobile ? "mobile" : "desktop"})`, async () => {+ const h = createPanel(mobile);+ const saved: IAVFilter[][] = [];+ h.options.type = "filters";+ h.options.protyle = undefined;+ h.options.anchorElement = {getBoundingClientRect: () => ({right: 400, bottom: 50, height: 20})} as HTMLElement;+ h.options.filterOperation = {save: filters => saved.push(filters)};+ h.open(h.options);+ await Promise.resolve();+ const filters: IAVFilter[] = [{combination: "and", filters: []}];+ h.context.saveFilters(filters, []);+ assert.equal(saved[0], filters);+ assert.equal(h.context.avID, "av");+ assert.ok(!h.calls.includes("transaction"));+ h.calls.length = 0;+ await h.click("close");+ assert.ok(h.calls.includes("remove"));+ assert.ok(!h.calls.includes("focusBlock"));+ });+}+test("mobile back returns within a database panel and closes the root through its save callback", async () => {const h = createPanel(true);h.options.keepMenuOpen = true;diff --git a/app/src/protyle/render/av/panels/types.ts b/app/src/protyle/render/av/panels/types.tsindex 93d64ff64c..b548d79378 100644--- a/app/src/protyle/render/av/panels/types.ts+++ b/app/src/protyle/render/av/panels/types.ts@@ -1,4 +1,5 @@import type {RenderAttributeViewRequestInput} from "../../../../types/api";+import type {FilterEditorOptions} from "../filter";export interface IOpenAVPanelOptions {protyle: IProtyle;@@ -11,7 +12,8 @@ export interface IOpenAVPanelOptions {cb?: (avPanelElement: Element) => void;destroyCallback?: () => void;keepMenuOpen?: boolean;- filterOperation?: IAVFilterOperation;+ filterOperation?: FilterEditorOptions;+ anchorElement?: HTMLElement;requireExplicitChange?: boolean;}diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 871bb67bc6..04ee05f93f 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -652,6 +652,12 @@ export type BacklinkContext = { "attributeViewTargets"?: Array<BacklinkAttributeexport type BacklinkContextData = { "backlinks": Array<BacklinkContext | null> | null; "backmentions": Array<BacklinkContext | null> | null; "keywords": Array<string> | null; "revision": string; "unchanged": boolean; };+export type BacklinkDatabase = { "id": string; "keys": Array<AVKey | null> | null; "name": string; };++export type BacklinkDatabaseFilterInput = { "avID": string; "filters": Array<AVViewFilterInput | null>; };++export type BacklinkDatabasesRequestInput = { "containChildren"?: boolean | null; "id": string; "keyword"?: string; "notebook"?: string; "sourceFilter"?: BacklinkSourceFilterInput | null; };+export type BacklinkDocumentRequestInput = { "blockSort"?: number; "containChildren"?: boolean | null; "defID": string; "highlight"?: boolean | null; "keyword": string; "knownRevision"?: string | null; "notebook"?: string; "refTreeID": string; "sourceFilter"?: BacklinkSourceFilterInput | null; };export type BacklinkList = { "backlinks": Array<BacklinkPath | null> | null; "backmentions": Array<BacklinkPath | null> | null; "box": string; "k": string; "linkRefsCount": number; "mentionsCount": number; "mk": string; "revision": string; "unchanged": boolean; };@@ -664,7 +670,7 @@ export type BacklinkRefDef = { "id": string; "path": string; "text": string; };export type BacklinkRefDefs = { "refDefs": Array<BacklinkRefDef | null> | null; };-export type BacklinkSourceFilterInput = { "dailyNote"?: string | null; "excludeSelf"?: boolean | null; "excludedNotebookIDs"?: Array<string> | null; "excludedRefDefIDs"?: Array<string> | null; };+export type BacklinkSourceFilterInput = { "dailyNote"?: string | null; "database"?: BacklinkDatabaseFilterInput | null; "excludeSelf"?: boolean | null; "excludedNotebookIDs"?: Array<string> | null; "excludedRefDefIDs"?: Array<string> | null; };export type BackmentionDocumentRequestInput = { "containChildren"?: boolean | null; "defID": string; "highlight"?: boolean | null; "keyword": string; "knownRevision"?: string | null; "notebook"?: string; "refTreeID": string; };@@ -6353,6 +6359,7 @@ export interface APIPOSTRoutes {};/*** 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。+ * 可选 sourceFilter.database 按单个数据库的字段筛选反链及数量,不影响提及或数据库原视图。*/"/api/ref/getBacklink2": {request: BacklinkListRequestInput;@@ -6361,6 +6368,21 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 返回实际绑定反链来源的数据库名称及字段元数据,不返回条目值。+ * 忽略当前数据库条件并应用其他来源限制;发布读者不可查询,保持加密笔记本隔离及请求租约。+ */+ "/api/ref/getBacklinkDatabases": {+ request: BacklinkDatabasesRequestInput;+ response: { "code": 0; "data": Array<BacklinkDatabase | null> | null; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };+ /**+ * sourceFilter.database 在父块合并前按来源块的数据库字段筛选,不修改原数据库视图。+ * 无条件仅筛数据库成员,失效字段不放宽结果;原来源筛选、排序及加密笔记本租约保持不变。+ */"/api/ref/getBacklinkDoc": {request: BacklinkDocumentRequestInput;response: { "code": 0; "data": BacklinkContextData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6378,6 +6400,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 数据库条件与列表快照一致,不修改来源数据或原数据库视图。+ */"/api/ref/getGlobalBacklinkContexts": {request: GlobalBacklinkContextRequestInput;response: { "code": 0; "data": GlobalBacklinkContextData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6385,6 +6410,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * sourceFilter.database 在完整结果分页前求值,快照绑定全部筛选条件;原分页、排序和访问检查保持不变。+ */"/api/ref/getGlobalBacklinks": {request: GlobalBacklinkListRequestInput;response: { "code": 0; "data": GlobalBacklinkListData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/tests/backlinkRefresh.test.js b/app/tests/backlinkRefresh.test.jsindex 42d5d1db4b..78385ae572 100644--- a/app/tests/backlinkRefresh.test.js+++ b/app/tests/backlinkRefresh.test.js@@ -33,6 +33,7 @@ const setup = (type = "local") => {Object.assign(panel, {type, blockId: "target", dirty: false, destroyed: false, requesting: false,pendingFull: false, pendingRootIDs: new Set(), itemRecords: [new Map(), new Map()], indexChangeVersion: 0,+ sourceFilter: {},element: {contains: () => focused, isConnected: true, getClientRects: () => visible ? [{}] : []},ownerProtyle: {element: {getClientRects: () => visible ? [{}] : []}}, empty: true,searchBacklinks() { this.requesting = true; requests.push(this.indexChangeVersion); },@@ -55,6 +56,12 @@ const setup = (type = "local") => {};for (const type of ["local", "bottom"]) {+ test(`${type} database field changes invalidate all filtered contexts`, () => {+ const {panel, change} = setup(type);+ panel.sourceFilter.database = {avID: "tasks", filters: []};+ change("database-carrier-document");+ assert.equal(panel.pendingFull, true);+ });test(`${type} backlink refresh coalesces edits and retains every changed document`, () => {const {panel, requests, advance, change} = setup(type);change("one");diff --git a/kernel/api/backlink_database_filter.go b/kernel/api/backlink_database_filter.gonew file mode 100644index 0000000000..73c56613bc--- /dev/null+++ b/kernel/api/backlink_database_filter.go@@ -0,0 +1,49 @@+package api++import (+ "fmt"+ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func validateBacklinkDatabaseRequest(c *gin.Context, filter *model.BacklinkSourceFilter, boxID string) error {+ if filter == nil || filter.Database == nil {+ return nil+ }+ if model.IsReadOnlyRoleContext(c) {+ return fmt.Errorf("database field filtering is unavailable to published readers")+ }+ return model.ValidateBacklinkDatabaseFilter(filter, boxID)+}++var getBacklinkDatabases = contractHandler(apicontract.GetBacklinkDatabases, func(c *gin.Context, request apicontract.BacklinkDatabasesRequest) apicontract.Response[[]*apicontract.BacklinkDatabase] {+ if !ast.IsNodeIDPattern(request.ID) {+ return apicontract.Failure[[]*apicontract.BacklinkDatabase](-1, "invalid block ID")+ }+ if model.IsReadOnlyRoleContext(c) || isEncryptedNotebookDeniedForPublish(c, request.Notebook) {+ return apicontract.Success([]*apicontract.BacklinkDatabase{})+ }+ boxID := request.Notebook+ if !model.IsEncryptedBox(boxID) {+ boxID = ""+ }+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {+ return apicontract.Failure[[]*apicontract.BacklinkDatabase](1, err.Error())+ }+ containChildren := model.Conf.Editor.Load().BacklinkContainChildren+ if request.ContainChildren != nil {+ containChildren = *request.ContainChildren+ }+ items, err := model.GetBacklinkDatabases(request.ID, request.Keyword, boxID, containChildren, backlinkSourceFilterModel(request.SourceFilter))+ if err != nil {+ return apicontract.Failure[[]*apicontract.BacklinkDatabase](1, err.Error())+ }+ ret := []*apicontract.BacklinkDatabase{}+ for _, item := range items {+ ret = append(ret, &apicontract.BacklinkDatabase{ID: item.ID, Name: item.Name,+ Keys: avContractSlice(item.Keys, toContractAVKey)})+ }+ return apicontract.Success(ret)+})diff --git a/kernel/api/backlink_database_filter_test.go b/kernel/api/backlink_database_filter_test.gonew file mode 100644index 0000000000..c36da643bd--- /dev/null+++ b/kernel/api/backlink_database_filter_test.go@@ -0,0 +1,63 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestBacklinkDatabaseFilterContractMapping(t *testing.T) {+ request, err := apicontract.GetBacklinkDoc.Decode(strings.NewReader(`{"defID":"","refTreeID":"","keyword":"","sourceFilter":{"database":{"avID":"20261022130000-databas","filters":[{"combination":"or","filters":[{"column":"status","operator":"=","value":{"type":"text","text":{"content":"open"}}}]}]}}}`))+ if err != nil {+ t.Fatal(err)+ }+ filter := backlinkSourceFilterModel(request.SourceFilter)+ if filter == nil || filter.Database == nil || filter.Database.AvID != "20261022130000-databas" ||+ filter.Database.Filters[0].Filters[0].Value.Text.Content != "open" {+ t.Fatalf("database condition mapping failed: %+v", filter)+ }+}++func TestBacklinkDatabasePublishReaderContract(t *testing.T) {+ oldConf := model.Conf+ model.Conf = model.NewAppConf()+ model.Conf.Editor.Store(conf.NewEditor())+ t.Cleanup(func() { model.Conf = oldConf })+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleReader); c.Next() })+ engine.POST("/api/ref/getBacklinkDatabases", getBacklinkDatabases)+ engine.POST("/api/ref/getBacklink2", getBacklink2)+ for _, route := range []string{"getBacklinkDatabases", "getBacklink2"} {+ t.Run(route, func(t *testing.T) {+ path := "/api/ref/" + route+ recorder := httptest.NewRecorder()+ body := `{"id":"20261022130000-topic00","k":"","mk":"","sourceFilter":{"database":{"avID":"20261022130001-private","filters":[]}}}`+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ Data json.RawMessage `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if route == "getBacklinkDatabases" {+ if response.Code != 0 || string(response.Data) != "[]" {+ t.Fatalf("database metadata exposed: %s", recorder.Body.String())+ }+ } else if response.Code == 0 {+ t.Fatal("private database fields were available for published-reader filtering")+ }+ })+ }+}diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 3767e98979..f661292d2b 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -147,6 +147,9 @@ var getBacklinkDoc = contractHandler(apicontract.GetBacklinkDoc, func(c *gin.Conif err := holdEncryptedBoxRequest(c, notebook); err != nil {return apicontract.Failure[apicontract.BacklinkContextData](1, err.Error())}+ if err := validateBacklinkDatabaseRequest(c, backlinkSourceFilterModel(request.SourceFilter), notebook); err != nil {+ return apicontract.Failure[apicontract.BacklinkContextData](1, err.Error())+ }}containChildren := model.Conf.Editor.Load().BacklinkContainChildrenif request.ContainChildren != nil {@@ -189,8 +192,13 @@ func backlinkSourceFilterModel(filter *apicontract.BacklinkSourceFilter) *model.if filter == nil {return nil}- return model.NormalizeBacklinkSourceFilter(&model.BacklinkSourceFilter{DailyNote: filter.DailyNote, ExcludeSelf: filter.ExcludeSelf,- ExcludedRefDefIDs: filter.ExcludedRefDefIDs, ExcludedNotebookIDs: filter.ExcludedNotebookIDs})+ ret := &model.BacklinkSourceFilter{DailyNote: filter.DailyNote, ExcludeSelf: filter.ExcludeSelf,+ ExcludedRefDefIDs: filter.ExcludedRefDefIDs, ExcludedNotebookIDs: filter.ExcludedNotebookIDs}+ if filter.Database != nil {+ ret.Database = &model.BacklinkDatabaseFilter{AvID: filter.Database.AvID,+ Filters: avContractSlice(filter.Database.Filters, fromContractAVViewFilter)}+ }+ return model.NormalizeBacklinkSourceFilter(ret)}var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Context, request apicontract.BacklinkListRequest) apicontract.Response[apicontract.BacklinkListData] {@@ -253,8 +261,14 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Contextreturn apicontract.Failure[apicontract.BacklinkListData](1, err.Error())}if notebook != "" && model.IsEncryptedBox(notebook) {+ if err := validateBacklinkDatabaseRequest(c, sourceFilter, notebook); err != nil {+ return apicontract.Failure[apicontract.BacklinkListData](1, err.Error())+ }boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions, includeBacklinks, notify)} else {+ if err := validateBacklinkDatabaseRequest(c, sourceFilter, ""); err != nil {+ return apicontract.Failure[apicontract.BacklinkListData](1, err.Error())+ }boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions, includeBacklinks, notify)}}diff --git a/kernel/api/ref_global.go b/kernel/api/ref_global.goindex 631a6a981c..2b8f2894bd 100644--- a/kernel/api/ref_global.go+++ b/kernel/api/ref_global.go@@ -23,6 +23,9 @@ func globalBacklinkQuery(c *gin.Context, request apicontract.GlobalBacklinkQueryif err := holdEncryptedBoxRequest(c, query.Notebook); err != nil {return query, err}+ if err := validateBacklinkDatabaseRequest(c, query.SourceFilter, query.Notebook); err != nil {+ return query, err+ }return query, nil}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 90f753b371..80370edd56 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -510,6 +510,7 @@ func registerFileRoutes(ginServer *gin.Engine) {func registerRefRoutes(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ref/refreshBacklink", contractRouteHandlers(apicontract.RefreshBacklink, refreshBacklink)...)ginServer.Handle("POST", "/api/ref/getBacklink2", contractRouteHandlers(apicontract.GetBacklink2, getBacklink2)...)+ ginServer.Handle("POST", "/api/ref/getBacklinkDatabases", contractRouteHandlers(apicontract.GetBacklinkDatabases, getBacklinkDatabases)...)ginServer.Handle("POST", "/api/ref/getGlobalBacklinks", contractRouteHandlers(apicontract.GetGlobalBacklinks, getGlobalBacklinks)...)ginServer.Handle("POST", "/api/ref/getGlobalBacklinkContexts", contractRouteHandlers(apicontract.GetGlobalBacklinkContexts, getGlobalBacklinkContexts)...)ginServer.Handle("POST", "/api/ref/getBacklinkDoc", contractRouteHandlers(apicontract.GetBacklinkDoc, getBacklinkDoc)...)diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 9b10680f0a..b30510e58b 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -657,11 +657,22 @@ var RefreshBacklink = define[RefreshBacklinkRequest, Null]("refreshBacklink", "/// 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。var GetBackmentionDoc = define[BackmentionDocumentRequest, BacklinkContextData]("getBackmentionDoc", "/api/ref/getBackmentionDoc", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")+// sourceFilter.database 在父块合并前按来源块的数据库字段筛选,不修改原数据库视图。+// 无条件仅筛数据库成员,失效字段不放宽结果;原来源筛选、排序及加密笔记本租约保持不变。var GetBacklinkDoc = define[BacklinkDocumentRequest, BacklinkContextData]("getBacklinkDoc", "/api/ref/getBacklinkDoc", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")// 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。+// 可选 sourceFilter.database 按单个数据库的字段筛选反链及数量,不影响提及或数据库原视图。var GetBacklink2 = define[BacklinkListRequest, BacklinkListData]("getBacklink2", "/api/ref/getBacklink2", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")++// 返回实际绑定反链来源的数据库名称及字段元数据,不返回条目值。+// 忽略当前数据库条件并应用其他来源限制;发布读者不可查询,保持加密笔记本隔离及请求租约。+var GetBacklinkDatabases = define[BacklinkDatabasesRequest, []*BacklinkDatabase]("getBacklinkDatabases", "/api/ref/getBacklinkDatabases", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// sourceFilter.database 在完整结果分页前求值,快照绑定全部筛选条件;原分页、排序和访问检查保持不变。var GetGlobalBacklinks = define[GlobalBacklinkListRequest, GlobalBacklinkListData]("getGlobalBacklinks", "/api/ref/getGlobalBacklinks", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 数据库条件与列表快照一致,不修改来源数据或原数据库视图。var GetGlobalBacklinkContexts = define[GlobalBacklinkContextRequest, GlobalBacklinkContextData]("getGlobalBacklinkContexts", "/api/ref/getGlobalBacklinkContexts", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var ContinueImportSY = define[ContinueImportSYRequest, ImportDocumentData]("continueImportSY", "/api/import/continueImportSY", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/ref.go b/kernel/apicontract/ref.goindex 8bbf6545db..6b49230204 100644--- a/kernel/apicontract/ref.go+++ b/kernel/apicontract/ref.go@@ -37,10 +37,32 @@ type BacklinkDocumentRequest struct {}type BacklinkSourceFilter struct {- DailyNote string `json:"dailyNote" api:"optional,nullable,ignoretype"`- ExcludeSelf bool `json:"excludeSelf" api:"optional,nullable"`- ExcludedRefDefIDs []string `json:"excludedRefDefIDs" api:"optional,nullable,filterstrings"`- ExcludedNotebookIDs []string `json:"excludedNotebookIDs" api:"optional,nullable,filterstrings"`+ DailyNote string `json:"dailyNote" api:"optional,nullable,ignoretype"`+ ExcludeSelf bool `json:"excludeSelf" api:"optional,nullable"`+ ExcludedRefDefIDs []string `json:"excludedRefDefIDs" api:"optional,nullable,filterstrings"`+ ExcludedNotebookIDs []string `json:"excludedNotebookIDs" api:"optional,nullable,filterstrings"`+ Database *BacklinkDatabaseFilter `json:"database" api:"optional,nullable"`+}++// 数据库字段按 avID 隔离。空条件仅限制数据库成员;失效数据库或条件不放宽为全部结果。+// 条件不修改数据库原视图,不影响提及;列表、正文及全局分页使用相同条件。+type BacklinkDatabaseFilter struct {+ AvID string `json:"avID"`+ Filters []*AVViewFilter `json:"filters"`+}++type BacklinkDatabasesRequest struct {+ ID string `json:"id"`+ Notebook string `json:"notebook" api:"optional"`+ Keyword string `json:"keyword" api:"optional"`+ ContainChildren *bool `json:"containChildren" api:"optional"`+ SourceFilter *BacklinkSourceFilter `json:"sourceFilter" api:"optional"`+}++type BacklinkDatabase struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Keys []*AVKey `json:"keys"`}type BacklinkAttributeViewTarget struct {@@ -131,6 +153,11 @@ func decodeBacklinkSourceFilter(raw json.RawMessage) *BacklinkSourceFilter {return nil}filter := &BacklinkSourceFilter{}+ if raw, exists := fields["database"]; exists && !bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {+ filter.Database = &BacklinkDatabaseFilter{}+ // 非法数据库条件仍保留启用状态,由模型拒绝匹配,避免静默退回全部反链。+ _ = json.Unmarshal(raw, filter.Database)+ }_ = json.Unmarshal(fields["dailyNote"], &filter.DailyNote)_ = json.Unmarshal(fields["excludeSelf"], &filter.ExcludeSelf)for _, field := range []struct {diff --git a/kernel/apicontract/ref_test.go b/kernel/apicontract/ref_test.goindex 3e3a3bc807..3e852bde1e 100644--- a/kernel/apicontract/ref_test.go+++ b/kernel/apicontract/ref_test.go@@ -44,3 +44,20 @@ func TestBacklinkSourceFilterCompatibility(t *testing.T) {}}}++func TestBacklinkDatabaseFilterContract(t *testing.T) {+ request, err := GetBacklinkDoc.Decode(strings.NewReader(`{"defID":"","refTreeID":"","keyword":"","sourceFilter":{"database":{"avID":"tasks","filters":[{"combination":"and","filters":[{"column":"status","operator":"=","value":{"type":"text","text":{"content":"open"}}}]}]}}}`))+ if err != nil || request.SourceFilter == nil || request.SourceFilter.Database == nil {+ t.Fatalf("database filter decode: %+v %v", request, err)+ }+ filter := request.SourceFilter.Database+ if filter.AvID != "tasks" || len(filter.Filters) != 1 || filter.Filters[0].Filters[0].Value.Text.Content != "open" {+ t.Fatalf("lost database fields: %+v", filter)+ }+ for _, malformed := range []string{`false`, `"tasks"`, `{}`} {+ request, err := GetBacklinkDoc.Decode(strings.NewReader(`{"defID":"","refTreeID":"","keyword":"","sourceFilter":{"database":` + malformed + `}}`))+ if err != nil || request.SourceFilter == nil || request.SourceFilter.Database == nil {+ t.Fatal("malformed database filters must remain enabled for fail-closed validation")+ }+ }+}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 1d536e8053..6549ee83ae 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -15903,6 +15903,107 @@],"additionalProperties": false},+ "BacklinkDatabase": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "keys": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AVKey"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "name": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "keys",+ "name"+ ],+ "additionalProperties": false+ },+ "BacklinkDatabaseFilterInput": {+ "type": "object",+ "properties": {+ "avID": {+ "type": "string"+ },+ "filters": {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AVViewFilterInput"+ },+ {+ "type": "null"+ }+ ]+ }+ }+ },+ "required": [+ "avID",+ "filters"+ ],+ "additionalProperties": false+ },+ "BacklinkDatabasesRequestInput": {+ "type": "object",+ "properties": {+ "containChildren": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "id": {+ "type": "string"+ },+ "keyword": {+ "type": "string"+ },+ "notebook": {+ "type": "string"+ },+ "sourceFilter": {+ "anyOf": [+ {+ "$ref": "#/$defs/BacklinkSourceFilterInput"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ },"BacklinkDocumentRequestInput": {"type": "object","properties": {@@ -16313,6 +16414,16 @@}]},+ "database": {+ "anyOf": [+ {+ "$ref": "#/$defs/BacklinkDatabaseFilterInput"+ },+ {+ "type": "null"+ }+ ]+ },"excludeSelf": {"anyOf": [{@@ -158023,6 +158134,103 @@]}},+ {+ "method": "POST",+ "path": "/api/ref/getBacklinkDatabases",+ "handler": "getBacklinkDatabases",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/BacklinkDatabasesRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BacklinkDatabase"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/ref/getBacklinkDoc",diff --git a/kernel/av/av.go b/kernel/av/av.goindex 8c503fd103..a3815a605f 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -1107,9 +1107,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {return err}cacheAttributeViewData(av, avBoxID, data)- if RichTextSpec <= av.Spec {- NotifyAttributeViewSaved(av.ID, avBoxID)- }+ NotifyAttributeViewSaved(av.ID, avBoxID)return nil}if cachedData, version, ok := cache.GetAVDataWithVersionInBox(av.ID, avBoxID); ok {@@ -1158,9 +1156,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {}cacheAttributeViewData(av, avBoxID, data)- if RichTextSpec <= av.Spec {- NotifyAttributeViewSaved(av.ID, avBoxID)- }+ NotifyAttributeViewSaved(av.ID, avBoxID)if util.ExceedLargeFileWarningSize(len(data)) {msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize.Load())diff --git a/kernel/model/attribute_view_ref_index.go b/kernel/model/attribute_view_ref_index.goindex 8361c131a1..4f62219991 100644--- a/kernel/model/attribute_view_ref_index.go+++ b/kernel/model/attribute_view_ref_index.go@@ -35,10 +35,15 @@ func queueAttributeViewRefIndex(avID, avBoxID string) {return}attrView, err := av.ParseAttributeViewForIndexInBox(avID, avBoxID)- if nil != err || nil == attrView || av.RichTextSpec > attrView.Spec {+ if nil != err || nil == attrView {return}- queueAttributeViewRefCarrierIndex(avID, avBoxID, attributeViewRichTextRefDefIDs(attrView))+ var definitions []string+ if av.RichTextSpec <= attrView.Spec {+ definitions = attributeViewRichTextRefDefIDs(attrView)+ }+ // 普通字段同样影响反链数据库筛选,通过载体索引提交通知现有面板刷新。+ queueAttributeViewRefCarrierIndex(avID, avBoxID, definitions)}// queueExternalAttributeViewRefIndex 用于同步、历史和快照直接替换 AV 文件后的引用重建。diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 8e49cbb2bf..a0e0e66c26 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -29,6 +29,7 @@ import ("github.com/88250/lute/parse""github.com/emirpasic/gods/sets/hashset""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/search""github.com/siyuan-note/siyuan/kernel/sql"@@ -157,10 +158,16 @@ const ()type BacklinkSourceFilter struct {- DailyNote string `json:"dailyNote"`- ExcludedNotebookIDs []string `json:"excludedNotebookIDs"`- ExcludeSelf bool `json:"excludeSelf"`- ExcludedRefDefIDs []string `json:"excludedRefDefIDs"`+ DailyNote string `json:"dailyNote"`+ ExcludedNotebookIDs []string `json:"excludedNotebookIDs"`+ ExcludeSelf bool `json:"excludeSelf"`+ ExcludedRefDefIDs []string `json:"excludedRefDefIDs"`+ Database *BacklinkDatabaseFilter `json:"database,omitempty"`+}++type BacklinkDatabaseFilter struct {+ AvID string `json:"avID"`+ Filters []*av.ViewFilter `json:"filters"`}func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceFilter {@@ -183,7 +190,7 @@ func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSource}sort.Strings(excludedNotebookIDs)excludedRefDefIDs := normalizeBacklinkRefDefIDs(filter.ExcludedRefDefIDs)- if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf && 0 == len(excludedRefDefIDs) {+ if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf && 0 == len(excludedRefDefIDs) && nil == filter.Database {return nil}return &BacklinkSourceFilter{@@ -191,6 +198,7 @@ func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceExcludedNotebookIDs: excludedNotebookIDs,ExcludeSelf: filter.ExcludeSelf,ExcludedRefDefIDs: excludedRefDefIDs,+ Database: filter.Database,}}@@ -312,7 +320,7 @@ func GetBacklinkDocWithSort(defID, refTreeID, keyword string, containChildren, h}refs = removeDuplicatedRefs(refs)- linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, encBoxIDUsed)+ linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, encBoxIDUsed, filters...)if len(filters) > 0 {linkRefs = filterBacklinkSourcesInBox(linkRefs, rootID, encBoxIDUsed, filters[0])}@@ -322,7 +330,7 @@ func GetBacklinkDocWithSort(defID, refTreeID, keyword string, containChildren, hreturn}- linkRefs = expandBacklinkDocumentEntries(linkRefs, tmpRefs, rootID, keywords, encBoxIDUsed, originalRefBlockIDs, blockSort)+ linkRefs = expandBacklinkDocumentEntries(linkRefs, tmpRefs, rootID, keywords, encBoxIDUsed, originalRefBlockIDs, blockSort, filters...)anchorKeys := backlinkAnchorSortKeys(linkRefs, refTree, tmpRefs, originalRefBlockIDs, blockSort)avTargets := backlinkAttributeViewTargets(refTree, tmpRefs)luteEngine := util.NewLute()@@ -369,7 +377,7 @@ func GetBacklinkDocInBoxWithSort(defID, refTreeID, keyword string, containChildr}refs = removeDuplicatedRefs(refs)- linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID)+ linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID, filters...)if len(filters) > 0 {linkRefs = filterBacklinkSourcesInBox(linkRefs, rootID, boxID, filters[0])}@@ -379,7 +387,7 @@ func GetBacklinkDocInBoxWithSort(defID, refTreeID, keyword string, containChildrreturn}- linkRefs = expandBacklinkDocumentEntries(linkRefs, tmpRefs, rootID, keywords, boxID, originalRefBlockIDs, blockSort)+ linkRefs = expandBacklinkDocumentEntries(linkRefs, tmpRefs, rootID, keywords, boxID, originalRefBlockIDs, blockSort, filters...)anchorKeys := backlinkAnchorSortKeys(linkRefs, refTree, tmpRefs, originalRefBlockIDs, blockSort)avTargets := backlinkAttributeViewTargets(refTree, tmpRefs)luteEngine := util.NewLute()@@ -639,7 +647,11 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,linkRefs, linkRefsCount, excludeBacklinkIDs, _ := buildLinkRefsInBox(rootID, refs, keywords, boxID)if includeBacklinks {- filteredLinkRefs := filterBacklinkSourcesInBox(linkRefs, rootID, boxID, sourceFilter)+ backlinkRefs := linkRefs+ if sourceFilter != nil && sourceFilter.Database != nil {+ backlinkRefs, _, _, _ = buildLinkRefsInBox(rootID, refs, keywords, boxID, sourceFilter)+ }+ filteredLinkRefs := filterBacklinkSourcesInBox(backlinkRefs, rootID, boxID, sourceFilter)if nil != NormalizeBacklinkSourceFilter(sourceFilter) {linkRefsCount = len(filteredLinkRefs)}@@ -755,11 +767,13 @@ func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []}// buildLinkRefsInBox 与 buildLinkRefs 一致,但按 boxID 路由到加密 db 或全局 db。-func buildLinkRefsInBox(defRootID string, refs []*sql.Ref, keywords []string, boxID string) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {- return buildLinkRefsInBoxWithDocumentGrouping(defRootID, refs, keywords, boxID, true)+func buildLinkRefsInBox(defRootID string, refs []*sql.Ref, keywords []string, boxID string, filters ...*BacklinkSourceFilter) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {+ return buildLinkRefsInBoxWithDocumentGrouping(defRootID, refs, keywords, boxID, true, filters...)}-func buildLinkRefsInBoxWithDocumentGrouping(defRootID string, refs []*sql.Ref, keywords []string, boxID string, groupDocuments bool) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {+func buildLinkRefsInBoxWithDocumentGrouping(defRootID string, refs []*sql.Ref, keywords []string, boxID string, groupDocuments bool, filters ...*BacklinkSourceFilter) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {+ // 数据库条件先约束实际引用来源,再合并父块,避免一个来源命中后放行同文档的其他引用。+ refs = filterBacklinkDatabaseRefs(refs, boxID, filters...)// 为了减少查询,组装好 IDs 后一次查出defSQLBlockIDs, refSQLBlockIDs := map[string]bool{}, map[string]bool{}var queryBlockIDs []stringdiff --git a/kernel/model/backlink_database_filter.go b/kernel/model/backlink_database_filter.gonew file mode 100644index 0000000000..7da774f7bd--- /dev/null+++ b/kernel/model/backlink_database_filter.go@@ -0,0 +1,271 @@+package model++import (+ "fmt"+ "sort"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/sql"+)++type BacklinkDatabase struct {+ ID string+ Name string+ Keys []*av.Key+}++func backlinkDatabaseBindings(view *av.AttributeView) map[string]string {+ ret := map[string]string{}+ if view == nil || view.GetBlockKeyValues() == nil {+ return ret+ }+ for _, value := range view.GetBlockKeyValues().Values {+ if value != nil && !value.IsDetached && value.Block != nil && value.Block.ID != "" {+ ret[value.Block.ID] = value.BlockID+ }+ }+ return ret+}++// 来源自身优先;仅复用反链既有的列表项、标题和文档提升关系,不继承任意祖先的数据库字段。+func backlinkDatabaseSources(blocks []*Block, boxID string) map[string][]*Block {+ ret := map[string][]*Block{}+ for _, block := range blocks {+ ret[block.ID] = []*Block{block}+ }+ for _, mapping := range buildBacklinkParentMappings(blocks, boxID) {+ for id := range mapping.coveredRefIDs {+ if mapping.parent.ID != id {+ ret[id] = append(ret[id], mapping.parent)+ }+ }+ }+ return ret+}++func filterBacklinkDatabaseRefs(refs []*sql.Ref, boxID string, filters ...*BacklinkSourceFilter) []*sql.Ref {+ if len(filters) == 0 || filters[0] == nil || filters[0].Database == nil {+ return refs+ }+ var ids []string+ for _, ref := range refs {+ ids = append(ids, ref.BlockID)+ }+ rows := sql.GetBlocksInBox(uniqueBacklinkStrings(ids), boxID)+ blocks := fromSQLBlocks(&rows, "", 0)+ matched := map[string]bool{}+ for _, block := range filterBacklinkDatabaseBlocks(blocks, boxID, filters[0]) {+ matched[block.ID] = true+ }+ ret := make([]*sql.Ref, 0, len(refs))+ for _, ref := range refs {+ if matched[ref.BlockID] {+ ret = append(ret, ref)+ }+ }+ return ret+}++func filterBacklinkDatabaseBlocks(blocks []*Block, boxID string, filter *BacklinkSourceFilter) []*Block {+ if filter == nil || filter.Database == nil || len(blocks) == 0 {+ return blocks+ }+ database := filter.Database+ view, err := av.ParseAttributeViewInBox(database.AvID, boxID)+ if err != nil || view == nil {+ logging.LogWarnf("read backlink database [%s] failed: %s", database.AvID, err)+ return nil+ }+ matched, err := backlinkDatabaseMatchedItems(view, database.Filters)+ if err != nil {+ logging.LogWarnf("evaluate backlink database [%s] failed: %s", database.AvID, err)+ return nil+ }+ ret := make([]*Block, 0, len(blocks))+ bindings := backlinkDatabaseBindings(view)+ owners := backlinkDatabaseSources(blocks, boxID)+ for _, block := range blocks {+ for _, owner := range owners[block.ID] {+ itemID, bound := bindings[owner.ID]+ if !bound {+ continue+ }+ if matched[itemID] {+ ret = append(ret, block)+ }+ break+ }+ }+ return ret+}++// 使用独立临时视图求值,包含隐藏字段,不套用数据库原视图的筛选、分组或分页。+func backlinkDatabaseMatchedItems(attrView *av.AttributeView, filters []*av.ViewFilter) (map[string]bool, error) {+ if err := validateBacklinkDatabaseFilters(attrView, filters); err != nil {+ return nil, err+ }+ view := &av.View{ID: ast.NewNodeID(), LayoutType: av.LayoutTypeTable,+ Filters: av.CloneFilters(filters), Table: av.NewLayoutTable()}+ for _, kv := range attrView.KeyValues {+ if kv != nil && kv.Key != nil {+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: kv.Key.ID}})+ }+ }+ table := sql.RenderView(attrView, view, "", false)+ if table == nil {+ return nil, fmt.Errorf("render backlink database failed")+ }+ cache := map[string]*av.AttributeView{attrView.ID: attrView}+ av.Filter(table, attrView, sql.GetFurtherCollections(attrView, cache), cache)+ ret := map[string]bool{}+ for _, item := range table.(av.Collection).GetItems() {+ ret[item.GetID()] = true+ }+ return ret, nil+}++func ValidateBacklinkDatabaseFilter(filter *BacklinkSourceFilter, boxID string) error {+ if filter == nil || filter.Database == nil {+ return nil+ }+ view, err := av.ParseAttributeViewInBox(filter.Database.AvID, boxID)+ if err != nil {+ return err+ }+ if view == nil {+ return fmt.Errorf("backlink database is unavailable")+ }+ return validateBacklinkDatabaseFilters(view, filter.Database.Filters)+}++func validateBacklinkDatabaseFilters(attrView *av.AttributeView, filters []*av.ViewFilter) error {+ if err := av.ValidateFilterDepth(filters); err != nil {+ return err+ }+ count := 0+ var validate func([]*av.ViewFilter) error+ validate = func(nodes []*av.ViewFilter) error {+ for _, filter := range nodes {+ count+++ if filter == nil || count > 1000 {+ return fmt.Errorf("invalid backlink database filter")+ }+ if filter.IsGroup() {+ if filter.Combination != av.FilterCombinationAnd && filter.Combination != av.FilterCombinationOr {+ return fmt.Errorf("invalid backlink database filter combination")+ }+ if err := validate(filter.Filters); err != nil {+ return err+ }+ continue+ }+ key, err := attrView.GetKey(filter.Column)+ if err != nil || key == nil {+ return fmt.Errorf("invalid backlink database field or operator")+ }+ typ := key.Type+ if filter.ValueSource == av.ValueSourceRendered {+ typ = av.KeyTypeText+ } else if filter.ValueSource != "" && filter.ValueSource != av.ValueSourceStored {+ return fmt.Errorf("invalid backlink database value source")+ }+ if !av.IsFilterOperatorAllowed(typ, filter.Operator) ||+ filter.Value != nil && filter.Value.Type != typ || filter.Value == nil && filter.RelativeDate == nil {+ return fmt.Errorf("invalid backlink database field or value type")+ }+ }+ return nil+ }+ if err := validate(filters); err != nil {+ return err+ }+ return nil+}++// 候选忽略当前数据库条件,保留其他来源限制,只返回确实绑定引用来源的数据库元数据。+func GetBacklinkDatabases(id, keyword, boxID string, containChildren bool, filter *BacklinkSourceFilter) ([]*BacklinkDatabase, error) {+ ret := []*BacklinkDatabase{}+ definition := sql.GetBlockInBox(id, boxID)+ if definition == nil {+ return ret, nil+ }+ refs := sql.QueryRefsByDefIDInBox(id, containChildren, boxID)+ var ids []string+ for _, ref := range refs {+ ids = append(ids, ref.BlockID)+ }+ rows := sql.GetBlocksInBox(uniqueBacklinkStrings(ids), boxID)+ blocks := fromSQLBlocks(&rows, "", 0)+ if filter != nil {+ copyFilter := *filter+ copyFilter.Database = nil+ blocks = filterBacklinkSourcesInBox(blocks, definition.RootID, boxID, ©Filter)+ }+ owners := backlinkDatabaseSources(blocks, boxID)+ views := map[string]*av.AttributeView{}+ bindings := map[string]map[string]string{}+ added := map[string]bool{}+ keywords := strings.Fields(keyword)+ for _, block := range blocks {+ for _, owner := range owners[block.ID] {+ if !matchBacklinkKeyword(block, keywords) && !matchBacklinkKeyword(owner, keywords) {+ continue+ }+ for _, avID := range strings.Split(owner.IAL[av.NodeAttrNameAvs], ",") {+ if !ast.IsNodeIDPattern(avID) {+ continue+ }+ view, loaded := views[avID]+ if !loaded {+ var err error+ view, err = av.ParseAttributeViewInBox(avID, boxID)+ if err != nil {+ return nil, err+ }+ if view == nil {+ return nil, fmt.Errorf("backlink database is unavailable")+ }+ views[avID] = view+ bindings[avID] = backlinkDatabaseBindings(view)+ }+ if _, bound := bindings[avID][owner.ID]; !bound {+ continue+ }+ if !added[avID] {+ added[avID] = true+ candidate := &BacklinkDatabase{ID: avID, Name: getAttrViewName(view), Keys: []*av.Key{}}+ for _, kv := range view.KeyValues {+ if kv != nil && kv.Key != nil {+ candidate.Keys = append(candidate.Keys, kv.Key)+ }+ }+ ret = append(ret, candidate)+ }+ }+ }+ }+ // 已选数据库即使暂时没有命中也能继续编辑条件;不存在或不可读时仅由客户端保留失效标识。+ if filter != nil && filter.Database != nil {+ if !added[filter.Database.AvID] {+ if view, err := av.ParseAttributeViewInBox(filter.Database.AvID, boxID); err == nil && view != nil {+ candidate := &BacklinkDatabase{ID: view.ID, Name: getAttrViewName(view), Keys: []*av.Key{}}+ for _, kv := range view.KeyValues {+ if kv != nil && kv.Key != nil {+ candidate.Keys = append(candidate.Keys, kv.Key)+ }+ }+ ret = append(ret, candidate)+ }+ }+ }+ sort.Slice(ret, func(i, j int) bool {+ if ret[i].Name == ret[j].Name {+ return ret[i].ID < ret[j].ID+ }+ return ret[i].Name < ret[j].Name+ })+ return ret, nil+}diff --git a/kernel/model/backlink_database_filter_fts5_test.go b/kernel/model/backlink_database_filter_fts5_test.gonew file mode 100644index 0000000000..5eb95a533e--- /dev/null+++ b/kernel/model/backlink_database_filter_fts5_test.go@@ -0,0 +1,241 @@+//go:build fts5++package model++import (+ "fmt"+ "reflect"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestBacklinkDatabaseFilteringPaginationAndMentions(t *testing.T) {+ setupAttributeViewValidationTest(t)+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().BacklinkMentionDoc = true+ t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })+ view := av.NewAttributeView(ast.NewNodeID())+ savedNotifications := 0+ previousSaved := av.AttributeViewSaved+ av.AttributeViewSaved = func(avID, boxID string) {+ if avID == view.ID {+ savedNotifications+++ }+ if previousSaved != nil {+ previousSaved(avID, boxID)+ }+ }+ t.Cleanup(func() { av.AttributeViewSaved = previousSaved })+ view.Name = "Tasks"+ status := &av.Key{ID: ast.NewNodeID(), Name: "Status", Type: av.KeyTypeText}+ done := &av.Key{ID: ast.NewNodeID(), Name: "Done", Type: av.KeyTypeCheckbox}+ view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: status}, &av.KeyValues{Key: done})+ view.Views[0].Filters = []*av.ViewFilter{{Column: status.ID, Operator: av.FilterOperatorIsEqual,+ Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "closed"}}}}+ var ids []string+ for _, rootID := range []string{fixture.sourceID, fixture.targetID} {+ tree, err := LoadTreeByBlockID(rootID)+ if err != nil {+ t.Fatal(err)+ }+ for tree.Root.FirstChild != nil {+ tree.Root.FirstChild.Unlink()+ }+ if rootID == fixture.sourceID {+ tree.Root.SetIALAttr("title", "DatabaseBacklinkTopic")+ tree.HPath = "/DatabaseBacklinkTopic"+ } else {+ intro := treenode.NewParagraph(ast.NewNodeID())+ intro.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("DatabaseBacklinkTopic")})+ tree.Root.AppendChild(intro)+ for i := 0; i < 70; i++ {+ id := ast.NewNodeID()+ ids = append(ids, id)+ p := treenode.NewParagraph(id)+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Task ")})+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: fixture.sourceID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: fmt.Sprintf("A%d", i+1)})+ if i < 65 {+ p.SetIALAttr(av.NodeAttrNameAvs, view.ID)+ itemID := ast.NewNodeID()+ view.KeyValues[0].Values = append(view.KeyValues[0].Values, &av.Value{ID: ast.NewNodeID(), KeyID: view.GetBlockKey().ID,+ BlockID: itemID, Type: av.KeyTypeBlock, Block: &av.ValueBlock{ID: id, Content: fmt.Sprintf("Task %d", i)}})+ content := "open"+ if i >= 60 {+ content = "closed"+ }+ view.KeyValues[2].Values = append(view.KeyValues[2].Values, &av.Value{ID: ast.NewNodeID(), KeyID: status.ID,+ BlockID: itemID, Type: av.KeyTypeText, Text: &av.ValueText{Content: content}})+ view.KeyValues[3].Values = append(view.KeyValues[3].Values, &av.Value{ID: ast.NewNodeID(), KeyID: done.ID,+ BlockID: itemID, Type: av.KeyTypeCheckbox, Checkbox: &av.ValueCheckbox{Checked: true}})+ }+ tree.Root.AppendChild(p)+ }+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.UpdateRefsTreeQueue(tree)+ }+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if savedNotifications != 1 {+ t.Fatal("plain-text database field saves must notify filtered backlinks")+ }+ sql.FlushQueue()+ filter := &BacklinkSourceFilter{Database: &BacklinkDatabaseFilter{AvID: view.ID, Filters: []*av.ViewFilter{+ {Combination: av.FilterCombinationAnd, Filters: []*av.ViewFilter{+ {Column: done.ID, Operator: av.FilterOperatorIsTrue, Value: &av.Value{Type: av.KeyTypeCheckbox, Checkbox: &av.ValueCheckbox{Checked: true}}},+ {Combination: av.FilterCombinationOr, Filters: []*av.ViewFilter{+ {Column: status.ID, Operator: av.FilterOperatorIsEqual, Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "open"}}},+ {Column: status.ID, Operator: av.FilterOperatorIsEqual, Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "pending"}}},+ }},+ }},+ }}}+ _, _, mentions, originalCount, mentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, true, true)+ _, docs, filteredMentions, count, filteredMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, true, true)+ if originalCount != 70 || count != 60 || len(docs) != 1 || docs[0].Count != 60 {+ t.Fatalf("counts: %d -> %d, %+v", originalCount, count, docs)+ }+ if mentionCount != filteredMentionCount || !reflect.DeepEqual(mentions, filteredMentions) {+ t.Fatal("database filtering changed mentions")+ }+ contexts, _ := GetBacklinkDocInBox(fixture.sourceID, fixture.targetID, "", false, false, "", filter)+ if len(contexts) != 60 {+ t.Fatalf("detail count: %d", len(contexts))+ }+ query := GlobalBacklinkQuery{ID: fixture.sourceID, Sort: 1, SourceFilter: filter}+ allow := func(string) bool { return true }+ token, page, total, _, expired, err := GetGlobalBacklinks(query, "", 0, "", allow)+ if err != nil || expired || total != 60 || len(page) != 50 {+ t.Fatalf("first filtered page: %d %d %v %v", total, len(page), expired, err)+ }+ _, page, total, offset, expired, err := GetGlobalBacklinks(query, token, 50, "", allow)+ if err != nil || expired || total != 60 || offset != 50 || len(page) != 10 || page[0].ID != ids[50] {+ t.Fatalf("second filtered page: %d %d %v %v", total, len(page), expired, err)+ }+ candidates, err := GetBacklinkDatabases(fixture.sourceID, "", "", false, filter)+ if err != nil || len(candidates) != 1 || candidates[0].ID != view.ID || len(candidates[0].Keys) != 4 {+ t.Fatalf("database candidates: %+v %v", candidates, err)+ }+ loaded, err := av.ParseAttributeView(view.ID)+ if err != nil || loaded.Views[0].Filters[0].Value.Text.Content != "closed" {+ t.Fatal("backlink filtering changed the original database view", err)+ }+ filter.Database.Filters = nil+ _, _, _, count, _ = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, false, true)+ if count != 65 {+ t.Fatalf("membership-only filter included unbound blocks: %d", count)+ }+ if _, _, _, _, expired, _ := GetGlobalBacklinks(query, token, 0, "", allow); !expired {+ t.Fatal("snapshot accepted changed database conditions")+ }+ filter.Database.Filters = []*av.ViewFilter{{Column: "removed-field", Operator: av.FilterOperatorIsEmpty}}+ _, _, _, count, _ = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, false, true)+ if count != 0 {+ t.Fatal("removed field expanded results")+ }+ _, _, _, count, _ = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, false, true)+ if count != 70 {+ t.Fatal("clearing filter did not restore all backlinks")+ }+}++func TestBacklinkDatabaseListItemBindingAndDirectPrecedence(t *testing.T) {+ setupAttributeViewValidationTest(t)+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search.Store(conf.NewSearch())+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ sql.IndexTreeQueue(source)+ view := av.NewAttributeView(ast.NewNodeID())+ key := &av.Key{ID: ast.NewNodeID(), Name: "Status", Type: av.KeyTypeText}+ view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: key})+ tree, err := LoadTreeByBlockID(fixture.targetID)+ if err != nil {+ t.Fatal(err)+ }+ for tree.Root.FirstChild != nil {+ tree.Root.FirstChild.Unlink()+ }+ intro := treenode.NewParagraph(ast.NewNodeID())+ intro.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Intro")})+ tree.Root.AppendChild(intro)+ list := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeList, ListData: &ast.ListData{}}+ item := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeListItem, ListData: &ast.ListData{}}+ paragraph := treenode.NewParagraph(ast.NewNodeID())+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: fixture.sourceID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Topic"})+ item.AppendChild(paragraph)+ list.AppendChild(item)+ tree.Root.AppendChild(list)+ item.SetIALAttr(av.NodeAttrNameAvs, view.ID)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.UpdateRefsTreeQueue(tree)+ appendItem := func(blockID, state string, detached bool) {+ itemID := ast.NewNodeID()+ view.KeyValues[0].Values = append(view.KeyValues[0].Values, &av.Value{ID: ast.NewNodeID(), KeyID: view.GetBlockKey().ID,+ BlockID: itemID, Type: av.KeyTypeBlock, IsDetached: detached, Block: &av.ValueBlock{ID: blockID, Content: "Task"}})+ view.KeyValues[2].Values = append(view.KeyValues[2].Values, &av.Value{ID: ast.NewNodeID(), KeyID: key.ID,+ BlockID: itemID, Type: av.KeyTypeText, Text: &av.ValueText{Content: state}})+ }+ appendItem(item.ID, "open", false)+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+ filter := &BacklinkSourceFilter{Database: &BacklinkDatabaseFilter{AvID: view.ID, Filters: []*av.ViewFilter{+ {Column: key.ID, Operator: av.FilterOperatorIsEqual, Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "open"}}},+ }}}+ _, _, _, count, _ := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, false, true)+ contexts, _ := GetBacklinkDocInBox(fixture.sourceID, fixture.targetID, "", false, false, "", filter)+ if count != 1 || len(contexts) != 1 || contexts[0].ID != item.ID {+ t.Fatalf("list binding not used consistently: %d %+v", count, contexts)+ }+ query := GlobalBacklinkQuery{ID: fixture.sourceID, Sort: 1, SourceFilter: filter}+ _, page, total, _, _, err := GetGlobalBacklinks(query, "", 0, "", func(string) bool { return true })+ if err != nil || total != 1 || page[0].ID != paragraph.ID {+ t.Fatalf("global list owner: %+v %v", page, err)+ }+ candidates, err := GetBacklinkDatabases(fixture.sourceID, "", "", false, nil)+ if err != nil || len(candidates) != 1 || candidates[0].ID != view.ID {+ t.Fatalf("list binding candidates: %+v %v", candidates, err)+ }+ appendItem(paragraph.ID, "closed", false)+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ _, _, _, count, _ = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, false, true)+ if count != 0 {+ t.Fatal("a matching parent overrode the source block's own database row")+ }+ other := av.NewAttributeView(ast.NewNodeID())+ other.Name = view.Name+ if err := av.SaveAttributeView(other); err != nil {+ t.Fatal(err)+ }+ filter.Database = &BacklinkDatabaseFilter{AvID: other.ID}+ _, _, _, count, _ = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, false, true)+ if count != 0 {+ t.Fatal("same-named databases were mixed")+ }+ ClearGlobalBacklinkSnapshots("")+}diff --git a/kernel/model/backlink_database_filter_sqlcipher_test.go b/kernel/model/backlink_database_filter_sqlcipher_test.gonew file mode 100644index 0000000000..b0310f89ca--- /dev/null+++ b/kernel/model/backlink_database_filter_sqlcipher_test.go@@ -0,0 +1,135 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestBacklinkDatabaseEncryptedScope(t *testing.T) {+ setupAttributeViewValidationTest(t)+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search.Store(conf.NewSearch())+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ target, err := LoadTreeByBlockID(fixture.targetID)+ if err != nil {+ t.Fatal(err)+ }+ boxID := fixture.box.ID+ dek := bytes.Repeat([]byte{0x73}, 32)+ markRuntimeEncryptedBox(boxID)+ prepareUnlockedEncryptedBoxTest(t, boxID, dek)+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted, boxConf.BoxCrypt = true, &conf.BoxEncryption{Spec: boxEncryptionSpec}+ if err := encryptBoxMetadata(boxID, boxConf, dek); err != nil {+ t.Fatal(err)+ }+ data, _ := json.Marshal(boxConf)+ if err := os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), data, 0600); err != nil {+ t.Fatal(err)+ }+ mountedEncryptedBoxes.Store(boxID, true)+ if err := treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ if err := sql.OpenEncryptedDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ view := av.NewAttributeView(ast.NewNodeID())+ av.SetAVBoxID(view.ID, boxID)+ t.Cleanup(func() {+ ClearGlobalBacklinkSnapshots(boxID)+ sql.CloseEncryptedDB(boxID)+ treenode.CloseEncryptedBlockTreeDB(boxID)+ mountedEncryptedBoxes.Delete(boxID)+ av.SetAVBoxID(view.ID, "")+ forgetRuntimeEncryptedBox(boxID)+ encryptedBoxLifecycles.Delete(boxID)+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ })+ for target.Root.FirstChild != nil {+ target.Root.FirstChild.Unlink()+ }+ paragraph := treenode.NewParagraph(ast.NewNodeID())+ paragraph.SetIALAttr(av.NodeAttrNameAvs, view.ID)+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Task ")})+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: source.ID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Topic"})+ target.Root.AppendChild(paragraph)+ for _, tree := range []*parse.Tree{source, target} {+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.UpdateRefsTreeQueue(tree)+ }+ view.KeyValues[0].Values = []*av.Value{{ID: ast.NewNodeID(), KeyID: view.GetBlockKey().ID,+ BlockID: ast.NewNodeID(), Type: av.KeyTypeBlock, Block: &av.ValueBlock{ID: paragraph.ID, Content: "Task"}}}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+ cache.ClearAVCache()+ filter := &BacklinkSourceFilter{Database: &BacklinkDatabaseFilter{AvID: view.ID}}+ if err := ValidateBacklinkDatabaseFilter(filter, boxID); err != nil {+ t.Fatal(err)+ }+ if err := ValidateBacklinkDatabaseFilter(filter, ""); err == nil {+ t.Fatal("ordinary queries reached encrypted database fields")+ }+ _, _, _, count, _ := GetBacklink2InBoxWithOptions(source.ID, "", "", 0, 0, false, boxID, filter, false, true)+ if count != 1 {+ t.Fatalf("encrypted filtered count: %d", count)+ }+ contexts, _ := GetBacklinkDocInBox(source.ID, target.ID, "", false, false, boxID, filter)+ if len(contexts) != 1 || contexts[0].ID != paragraph.ID {+ t.Fatal("encrypted list/context mismatch")+ }+ candidates, err := GetBacklinkDatabases(source.ID, "", boxID, false, nil)+ if err != nil || len(candidates) != 1 || candidates[0].ID != view.ID {+ t.Fatalf("encrypted metadata: %+v %v", candidates, err)+ }+ _, _, total, _, expired, err := GetGlobalBacklinks(GlobalBacklinkQuery{ID: source.ID, Notebook: boxID, Sort: 1, SourceFilter: filter}, "", 0, "", func(string) bool { return true })+ if err != nil || expired || total != 1 {+ t.Fatalf("encrypted virtual list: %d %v %v", total, expired, err)+ }+ path := filepath.Join(util.DataDir, boxID, "storage", "av", view.ID+".json")+ original, err := os.ReadFile(path)+ if err != nil || json.Valid(original) {+ t.Fatal("encrypted source became plaintext", err)+ }+ cache.ClearAVCache()+ corrupt := append([]byte(nil), original...)+ corrupt[len(corrupt)-1] ^= 1+ if err := os.WriteFile(path, corrupt, 0600); err != nil {+ t.Fatal(err)+ }+ if err := ValidateBacklinkDatabaseFilter(filter, boxID); err == nil {+ t.Fatal("authentication failure bypassed")+ }+ preserved, _ := os.ReadFile(path)+ if !bytes.Equal(preserved, corrupt) {+ t.Fatal("failed authenticated read modified the original ciphertext")+ }+}diff --git a/kernel/model/backlink_database_filter_test.go b/kernel/model/backlink_database_filter_test.gonew file mode 100644index 0000000000..8c4e92b81b--- /dev/null+++ b/kernel/model/backlink_database_filter_test.go@@ -0,0 +1,63 @@+package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestBacklinkDatabaseFilterValidation(t *testing.T) {+ setupAttributeViewValidationTest(t)+ view := av.NewAttributeView("20261022130000-databas")+ key := view.GetBlockKey()+ leaf := &av.ViewFilter{Column: key.ID, Operator: av.FilterOperatorContains,+ Value: &av.Value{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "task"}}}+ if err := validateBacklinkDatabaseFilters(view, []*av.ViewFilter{{Combination: av.FilterCombinationAnd, Filters: []*av.ViewFilter{leaf}}}); err != nil {+ t.Fatal(err)+ }+ if err := validateBacklinkDatabaseFilters(view, nil); err != nil {+ t.Fatal("membership-only filters must be allowed", err)+ }+ for name, filters := range map[string][]*av.ViewFilter{+ "nil condition": {nil},+ "removed field": {{Column: "missing", Operator: av.FilterOperatorIsEmpty}},+ "wrong operator": {{Column: key.ID, Operator: av.FilterOperatorIsGreater}},+ "changed field type": {{Column: key.ID, Operator: av.FilterOperatorIsEqual, Value: &av.Value{Type: av.KeyTypeNumber}}},+ "wrong combination": {{Combination: "xor", Filters: []*av.ViewFilter{leaf}}},+ } {+ t.Run(name, func(t *testing.T) {+ if err := validateBacklinkDatabaseFilters(view, filters); err == nil {+ t.Fatal("invalid conditions must not expand the result set")+ }+ })+ }+ deep := leaf+ for i := 0; i < 10; i++ {+ deep = &av.ViewFilter{Combination: av.FilterCombinationAnd, Filters: []*av.ViewFilter{deep}}+ }+ if err := validateBacklinkDatabaseFilters(view, []*av.ViewFilter{deep}); err == nil {+ t.Fatal("excessively nested filters accepted")+ }+ filter := NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{Database: &BacklinkDatabaseFilter{AvID: view.ID}})+ if filter == nil || filter.Database == nil {+ t.Fatal("membership-only filters must remain active")+ }+ if NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{Database: &BacklinkDatabaseFilter{}}) == nil {+ t.Fatal("malformed database filters must not silently disappear")+ }+}++func TestBacklinkDatabaseBindingsExcludeDetachedItems(t *testing.T) {+ setupAttributeViewValidationTest(t)+ view := av.NewAttributeView("20261022130000-databas")+ view.KeyValues[0].Values = []*av.Value{+ {BlockID: "bound-item", Block: &av.ValueBlock{ID: "source-block"}},+ {BlockID: "detached-item", IsDetached: true, Block: &av.ValueBlock{ID: "detached-source"}},+ {BlockID: "empty-item", Block: &av.ValueBlock{}},+ nil,+ }+ bindings := backlinkDatabaseBindings(view)+ if len(bindings) != 1 || bindings["source-block"] != "bound-item" {+ t.Fatalf("unexpected database bindings: %+v", bindings)+ }+}diff --git a/kernel/model/backlink_global.go b/kernel/model/backlink_global.goindex a0665d066f..67934621aa 100644--- a/kernel/model/backlink_global.go+++ b/kernel/model/backlink_global.go@@ -185,6 +185,7 @@ func collectGlobalBacklinks(query GlobalBacklinkQuery, accessible func(string) b}}}+ blocks = filterBacklinkDatabaseBlocks(blocks, query.Notebook, query.SourceFilter)blocks = filterBacklinkSourcesInBox(blocks, definition.RootID, query.Notebook, query.SourceFilter)byRoot := map[string]map[string]*Block{}for _, block := range blocks {diff --git a/kernel/model/backlink_ref_filter.go b/kernel/model/backlink_ref_filter.goindex 0b0694ff2b..5104b416ef 100644--- a/kernel/model/backlink_ref_filter.go+++ b/kernel/model/backlink_ref_filter.go@@ -125,7 +125,7 @@ func GetBacklinkRefDefs(id, keyword string, containChildren bool, boxID string,if keyword = strings.TrimSpace(keyword); "" != keyword {keywords = strings.Split(keyword, " ")}- entries, _, _, _ := buildLinkRefsInBox(block.RootID, refs, keywords, boxID)+ entries, _, _, _ := buildLinkRefsInBox(block.RootID, refs, keywords, boxID, filter)entries = filterBacklinkSourcesInBox(entries, block.RootID, boxID, filter)entryRefs, err := backlinkEntryRefDefs(entries, boxID)if nil != err {diff --git a/kernel/model/backlink_sort.go b/kernel/model/backlink_sort.goindex 769899025e..6f5ce6899a 100644--- a/kernel/model/backlink_sort.go+++ b/kernel/model/backlink_sort.go@@ -14,7 +14,7 @@ import (// 将通过来源过滤的整篇文档条目展开为可独立排序的引用,保留列表项和标题等局部上下文。func expandBacklinkDocumentEntries(blocks []*Block, refs []*sql.Ref, defRootID string, keywords []string,- boxID string, originalRefBlockIDs map[string]string, mode int) []*Block {+ boxID string, originalRefBlockIDs map[string]string, mode int, filters ...*BacklinkSourceFilter) []*Block {if mode != 1 && mode != 2 {return blocks}@@ -30,7 +30,7 @@ func expandBacklinkDocumentEntries(blocks []*Block, refs []*sql.Ref, defRootID sdocumentRefs = append(documentRefs, ref)}}- entries, _, _, mappings := buildLinkRefsInBoxWithDocumentGrouping(defRootID, removeDuplicatedRefs(documentRefs), keywords, boxID, false)+ entries, _, _, mappings := buildLinkRefsInBoxWithDocumentGrouping(defRootID, removeDuplicatedRefs(documentRefs), keywords, boxID, false, filters...)maps.Copy(originalRefBlockIDs, mappings)result = append(result, entries...)}