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 database block reference collection https://github.com/siyuan-note/siyuan/issues/20907
Daniel0f0f228a4391
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex eaac1ff1d9..465c0be470 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "هدف المرجع",+ "automationCollectionReferenceTip": "الصق معرّف كتلة أو رابط كتلة؛ تُجمع مراجع الكتل في المتن وفق قواعد الروابط الخلفية؛ يشمل هدف المستند كتل محتواه دون المستندات الفرعية","newItemTemplateOpenAfterCreate": "فتح العنصر في عرض مقسّم بعد إنشائه","deleteAll": "حذف الكل","listMindmapManageNodeColors": "إدارة ألوان العقد",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 46304381f0..bf3d79a232 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Referenzziel",+ "automationCollectionReferenceTip": "Block-ID oder Blocklink einfügen; Blockreferenzen im Text werden nach den Rückverweisregeln gruppiert; ein Dokumentziel umfasst seine Inhaltsblöcke, aber keine Unterdokumente","newItemTemplateOpenAfterCreate": "Eintrag nach dem Erstellen automatisch in geteilter Ansicht öffnen","deleteAll": "Alle löschen","listMindmapManageNodeColors": "Knotenfarben verwalten",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex f25e3887b2..e57df7b909 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Reference target",+ "automationCollectionReferenceTip": "Paste a block ID or block link; body block references are collected using backlink grouping; a document target includes its content blocks, excluding child documents","newItemTemplateOpenAfterCreate": "Open item in split view after creation","deleteAll": "Delete all","listMindmapManageNodeColors": "Manage node colors",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 3eda4cf41c..931f70cd67 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Destino de la referencia",+ "automationCollectionReferenceTip": "Pegue un ID de bloque o enlace de bloque; las referencias del cuerpo se agrupan según las reglas de los enlaces inversos; un documento incluye sus bloques de contenido, sin los subdocumentos","newItemTemplateOpenAfterCreate": "Abrir el elemento en vista dividida después de crearlo","deleteAll": "Eliminar todo","listMindmapManageNodeColors": "Gestionar colores de nodos",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex fc8dc65bac..11fc732f7e 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Cible de référence",+ "automationCollectionReferenceTip": "Collez un ID de bloc ou un lien de bloc ; les références du corps sont regroupées selon les règles des liens retour ; un document inclut ses blocs de contenu, sans les sous-documents","newItemTemplateOpenAfterCreate": "Ouvrir l’élément en vue scindée après sa création","deleteAll": "Tout supprimer","listMindmapManageNodeColors": "Gérer les couleurs des nœuds",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex d96ea84c6b..fef8e7523e 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "יעד ההפניה",+ "automationCollectionReferenceTip": "יש להדביק מזהה בלוק או קישור לבלוק; הפניות לבלוקים בגוף התוכן נאספות לפי כללי הקישורים החוזרים; יעד מסוג מסמך כולל את בלוקי התוכן שלו, ללא מסמכי משנה","newItemTemplateOpenAfterCreate": "פתיחת הפריט בתצוגה מפוצלת לאחר יצירתו","deleteAll": "מחיקת הכול","listMindmapManageNodeColors": "ניהול צבעי צמתים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 0ff5069e56..babcd58e5c 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "संदर्भ लक्ष्य",+ "automationCollectionReferenceTip": "ब्लॉक ID या ब्लॉक लिंक पेस्ट करें; मुख्य सामग्री के ब्लॉक संदर्भ बैकलिंक नियमों के अनुसार समूहित होते हैं; दस्तावेज़ लक्ष्य में उसके सामग्री ब्लॉक शामिल हैं, उपदस्तावेज़ नहीं","newItemTemplateOpenAfterCreate": "बनाने के बाद आइटम को विभाजित दृश्य में खोलें","deleteAll": "सभी हटाएँ","listMindmapManageNodeColors": "नोड के रंग प्रबंधित करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 3c28fead5a..893f811676 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Tujuan referensi",+ "automationCollectionReferenceTip": "Tempel ID blok atau tautan blok; referensi blok dalam isi dikumpulkan menurut aturan tautan balik; tujuan dokumen mencakup blok isinya tanpa subdokumen","newItemTemplateOpenAfterCreate": "Buka item dalam tampilan terbagi setelah dibuat","deleteAll": "Hapus semua","listMindmapManageNodeColors": "Kelola warna simpul",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex e0515c9b6b..65e65c67e6 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Destinazione del riferimento",+ "automationCollectionReferenceTip": "Incolla un ID di blocco o un collegamento al blocco; i riferimenti nel corpo vengono raggruppati secondo le regole dei collegamenti inversi; un documento include i suoi blocchi di contenuto, esclusi i documenti secondari","newItemTemplateOpenAfterCreate": "Apri l’elemento in vista divisa dopo la creazione","deleteAll": "Elimina tutto","listMindmapManageNodeColors": "Gestisci i colori dei nodi",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex a84c142e41..cd5b85be70 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "参照先",+ "automationCollectionReferenceTip": "ブロック ID またはブロックリンクを貼り付けてください。本文中のブロック参照をバックリンクと同じ規則でまとめます。文書を指定すると内部のブロックも対象になり、子文書は含まれません","newItemTemplateOpenAfterCreate": "作成後に項目を分割表示で開く","deleteAll": "すべて削除","listMindmapManageNodeColors": "ノードの色を管理",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 098d87e289..65e51ae51b 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "참조 대상",+ "automationCollectionReferenceTip": "블록 ID 또는 블록 링크를 붙여넣으세요. 본문의 블록 참조는 백링크 규칙에 따라 묶이며, 문서를 대상으로 지정하면 내부 콘텐츠 블록도 포함하지만 하위 문서는 제외합니다","newItemTemplateOpenAfterCreate": "생성 후 항목을 분할 화면으로 열기","deleteAll": "모두 삭제","listMindmapManageNodeColors": "노드 색상 관리",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 6b8834a23e..78474d2ec1 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Verwijzingsdoel",+ "automationCollectionReferenceTip": "Plak een blok-ID of bloklink; blokverwijzingen in de tekst worden gegroepeerd volgens de teruglinkregels; een documentdoel omvat zijn inhoudsblokken, maar geen subdocumenten","newItemTemplateOpenAfterCreate": "Item na aanmaken in gesplitste weergave openen","deleteAll": "Alles verwijderen","listMindmapManageNodeColors": "Knoopkleuren beheren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 02c3f29efe..9f6a3df164 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Cel odwołania",+ "automationCollectionReferenceTip": "Wklej ID bloku lub łącze do bloku; odwołania w treści są grupowane według reguł linków zwrotnych; dokument obejmuje swoje bloki treści, bez dokumentów podrzędnych","newItemTemplateOpenAfterCreate": "Otwórz element w podzielonym widoku po utworzeniu","deleteAll": "Usuń wszystko","listMindmapManageNodeColors": "Zarządzaj kolorami węzłów",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 9f0b0ac491..e2b5bbc712 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Destino da referência",+ "automationCollectionReferenceTip": "Cole um ID de bloco ou link de bloco; as referências no corpo são agrupadas pelas regras dos backlinks; um documento inclui seus blocos de conteúdo, sem os subdocumentos","newItemTemplateOpenAfterCreate": "Abrir o item em visualização dividida após a criação","deleteAll": "Excluir tudo","listMindmapManageNodeColors": "Gerenciar cores dos nós",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex a595a1e1a1..4e3b59af7a 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Цель ссылки",+ "automationCollectionReferenceTip": "Вставьте ID блока или ссылку на блок; ссылки в основном тексте группируются по правилам обратных ссылок; документ включает свои блоки содержимого, но не дочерние документы","newItemTemplateOpenAfterCreate": "Открывать элемент в разделённом представлении после создания","deleteAll": "Удалить всё","listMindmapManageNodeColors": "Управление цветами узлов",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 87c2ba8da7..71d444f65d 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Cieľ odkazu",+ "automationCollectionReferenceTip": "Vložte ID bloku alebo odkaz na blok; odkazy v texte sa zoskupujú podľa pravidiel spätných odkazov; dokument zahŕňa svoje bloky obsahu, nie však podriadené dokumenty","newItemTemplateOpenAfterCreate": "Po vytvorení otvoriť položku v rozdelenom zobrazení","deleteAll": "Odstrániť všetko","listMindmapManageNodeColors": "Spravovať farby uzlov",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 1a90e84e79..a1e2a07b60 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Циљ референце",+ "automationCollectionReferenceTip": "Налепите ID блока или везу ка блоку; референце у садржају се групишу по правилима повратних веза; документ обухвата своје блокове садржаја, без поддокумената","newItemTemplateOpenAfterCreate": "Отвори ставку у подељеном приказу након креирања","deleteAll": "Обриши све","listMindmapManageNodeColors": "Управљај бојама чворова",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f555d16450..ca7c858165 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "เป้าหมายการอ้างอิง",+ "automationCollectionReferenceTip": "วาง ID บล็อกหรือลิงก์บล็อก การอ้างอิงบล็อกในเนื้อหาจะจัดกลุ่มตามกฎลิงก์ย้อนกลับ หากเลือกเอกสารจะรวมบล็อกเนื้อหาภายใน แต่ไม่รวมเอกสารย่อย","newItemTemplateOpenAfterCreate": "เปิดรายการในมุมมองแบบแบ่งหลังจากสร้าง","deleteAll": "ลบทั้งหมด","listMindmapManageNodeColors": "จัดการสีโหนด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 3e31597412..6a2980bfda 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Başvuru hedefi",+ "automationCollectionReferenceTip": "Bir blok kimliği veya blok bağlantısı yapıştırın; gövde içindeki blok başvuruları geri bağlantı kurallarına göre gruplanır; belge hedefi içerik bloklarını kapsar, alt belgeleri kapsamaz","newItemTemplateOpenAfterCreate": "Öğeyi oluşturduktan sonra bölünmüş görünümde aç","deleteAll": "Tümünü sil","listMindmapManageNodeColors": "Düğüm renklerini yönet",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 3c476338ed..102916c34d 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "Ціль посилання",+ "automationCollectionReferenceTip": "Вставте ID блоку або посилання на блок; посилання в основному тексті групуються за правилами зворотних посилань; документ охоплює свої блоки вмісту, але не дочірні документи","newItemTemplateOpenAfterCreate": "Відкривати елемент у розділеному поданні після створення","deleteAll": "Видалити все","listMindmapManageNodeColors": "Керувати кольорами вузлів",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex fc6939d639..5536a71365 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "引用目标",+ "automationCollectionReferenceTip": "粘贴块 ID 或块链接;仅收集正文块引用,按反链规则归并;文档目标包含其内部内容块,不含子文档","newItemTemplateOpenAfterCreate": "创建后分屏打开条目","deleteAll": "全部删除","listMindmapManageNodeColors": "管理节点配色",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 5c19b17916..53690bcc63 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "automationCollectionReference": "引用目標",+ "automationCollectionReferenceTip": "貼上區塊 ID 或區塊連結;僅收集正文區塊引用,依反鏈規則合併;文件目標包含內部內容區塊,不含子文件","newItemTemplateOpenAfterCreate": "建立後分割畫面開啟條目","deleteAll": "全部刪除","listMindmapManageNodeColors": "管理節點配色",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.syindex d7e1ef5a31..9b1ca54ea7 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy@@ -7,7 +7,7 @@"id": "20240208172514-9dsv6na","title": "Database","type": "doc",- "updated": "20261025205717"+ "updated": "20261026103001"},"Children": [{@@ -4125,7 +4125,7 @@"HeadingLevel": 2,"Properties": {"id": "20261002224707-n5wvv5s",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4956,7 +4956,7 @@"HeadingLevel": 3,"Properties": {"id": "20261015141042-fm4qoja",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4970,7 +4970,7 @@"Type": "NodeHeading","Properties": {"id": "20261024163013-6bomil1",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -5120,6 +5120,34 @@}]},+ {+ "ID": "20261026103001-3cdya4m",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-3cdya4m",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "To collect block references, select a reference target and paste its block ID or block link, or choose Current document. The target is saved as a fixed block ID shared by all database mirrors. A document target includes references to its internal content blocks, but not its child documents. Only body block references are included; ordinary links, embeds and references in database rich-text fields are excluded."+ }+ ]+ },+ {+ "ID": "20261026103001-47dxurt",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-47dxurt",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Reference sources use the same grouping rules as backlinks, including list items, blockquotes, super blocks, callouts, and document or heading propagation from a first paragraph containing only block references. Type and attribute conditions apply to the final grouped block; tag conditions apply to the reference source. The tag collection target option does not apply while a reference target is set. Clear the reference target to return to ordinary collection. Removing a reference preserves existing entries and fields; preview collection management to collect older matches. Reference targets require automation format 8; formats 1–7 remain readable, and older clients reject format 8 without rewriting the database."+ }+ ]+ },{"ID": "20261021135332-1brkvpw","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.syindex 5c7fc4d76c..3970f5bdd3 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy@@ -7,7 +7,7 @@"id": "20240208113259-nykkvaq","title": "数据库","type": "doc",- "updated": "20261025205717"+ "updated": "20261026103001"},"Children": [{@@ -4055,7 +4055,7 @@"HeadingLevel": 2,"Properties": {"id": "20261002224707-l8jclpi",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4844,7 +4844,7 @@"HeadingLevel": 3,"Properties": {"id": "20261015141042-j06dkl9",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4858,7 +4858,7 @@"Type": "NodeHeading","Properties": {"id": "20261024163013-33obidb",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4966,6 +4966,34 @@}]},+ {+ "ID": "20261026103001-owfyyeu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-owfyyeu",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "收集块引用时,选择引用目标并粘贴目标块 ID 或块链接,也可选择「当前文档」。目标保存为固定的块 ID,由所有数据库镜像共享。文档目标包含对其内部内容块的引用,不含子文档。仅匹配正文中的块引用,不包含普通链接、嵌入块和数据库富文本字段中的引用。"+ }+ ]+ },+ {+ "ID": "20261026103001-quehwxj",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-quehwxj",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "引用来源按反链规则归并,包括列表项、引述块、超级块、提示块,以及文档首段或标题后首段为纯块引用时的传递规则。块类型和自定义属性约束归并后的最终块,标签条件约束引用来源块;设置引用目标后,标签的收集对象选项不参与选择。清除引用目标可恢复普通收集。移除引用会保留已有条目和字段,历史引用可通过收集管理预览并补收。引用目标需要自动化格式 8,既有格式 1–7 仍可读取,旧客户端会拒绝格式 8 且不改写数据库。"+ }+ ]+ },{"ID": "20261021135332-xudc33f","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.syindex 014b64e420..c709345280 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy@@ -7,7 +7,7 @@"id": "20240208171522-y7dxcno","title": "資料庫","type": "doc",- "updated": "20261025205717"+ "updated": "20261026103001"},"Children": [{@@ -4055,7 +4055,7 @@"HeadingLevel": 2,"Properties": {"id": "20261002224707-f9wjtlr",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4844,7 +4844,7 @@"HeadingLevel": 3,"Properties": {"id": "20261015141042-sk1ubzp",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4858,7 +4858,7 @@"Type": "NodeHeading","Properties": {"id": "20261024163013-n6h5527",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4966,6 +4966,34 @@}]},+ {+ "ID": "20261026103001-covc0xz",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-covc0xz",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "收集區塊引用時,選擇引用目標並貼上目標區塊 ID 或區塊連結,也可選擇「目前文件」。目標儲存為固定的區塊 ID,由所有資料庫鏡像共用。文件目標包含對內部內容區塊的引用,不含子文件。僅匹配正文中的區塊引用,不包含一般連結、嵌入區塊和資料庫富文字欄位中的引用。"+ }+ ]+ },+ {+ "ID": "20261026103001-jv2ou95",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-jv2ou95",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "引用來源依反鏈規則合併,包括列表項、引述區塊、超級區塊、提示區塊,以及文件首段或標題後首段為純區塊引用時的傳遞規則。區塊類型和自訂屬性限制合併後的最終區塊,標籤條件限制引用來源區塊;設定引用目標後,標籤的收集對象選項不參與選擇。清除引用目標可恢復一般收集。移除引用會保留既有項目和欄位,歷史引用可透過收集管理預覽並補收。引用目標需要自動化格式 8,既有格式 1–7 仍可讀取,舊用戶端會拒絕格式 8 且不改寫資料庫。"+ }+ ]+ },{"ID": "20261021135332-36rh1ee","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.syindex 7757a92036..a90f669656 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy@@ -8,7 +8,7 @@"id": "20240530101000-3eaevtp","title": "データベース","type": "doc",- "updated": "20261025205717"+ "updated": "20261026103001"},"Children": [{@@ -4149,7 +4149,7 @@"HeadingLevel": 2,"Properties": {"id": "20261002224707-2ctdjhm",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4966,7 +4966,7 @@"HeadingLevel": 3,"Properties": {"id": "20261015141042-aj3t5af",- "updated": "20261024164212"+ "updated": "20261026103001"},"Children": [{@@ -4980,7 +4980,7 @@"Type": "NodeHeading","Properties": {"id": "20261024163013-daifyta",- "updated": "20261024163013"+ "updated": "20261026103001"},"Children": [{@@ -5102,6 +5102,34 @@}]},+ {+ "ID": "20261026103001-u3e7mth",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-u3e7mth",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "ブロック参照を収集するには、参照先を選択してブロック ID またはブロックリンクを貼り付けるか、「現在の文書」を選択します。参照先は固定のブロック ID として保存され、すべてのデータベースミラーで共有されます。文書を指定すると、その内部のコンテンツブロックへの参照も対象になりますが、子文書は含まれません。本文中のブロック参照のみが対象で、通常のリンク、埋め込み、データベースのリッチテキストフィールド内の参照は含まれません。"+ }+ ]+ },+ {+ "ID": "20261026103001-ceuhthk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261026103001-ceuhthk",+ "updated": "20261026103001"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "参照元はバックリンクと同じ規則でまとめられます。リスト項目、引用ブロック、スーパーブロック、コールアウトに加え、文書の先頭段落または見出し直後の段落がブロック参照のみの場合の引き継ぎも適用されます。ブロック種類とカスタム属性はまとめた後のブロックを、タグ条件は参照元のブロックを判定します。参照先の設定中はタグの収集対象設定を使用しません。参照先を解除すると通常の収集に戻ります。参照を削除しても既存の項目とフィールドは保持され、以前の参照は収集管理でプレビューして追加できます。参照先の設定には自動化形式 8 が必要です。既存の形式 1–7 は引き続き読み取れますが、古いクライアントはデータベースを書き換えずに形式 8 を拒否します。"+ }+ ]+ },{"ID": "20261021135332-1xj7aht","Type": "NodeParagraph",diff --git a/app/src/protyle/render/av/automation.test.ts b/app/src/protyle/render/av/automation.test.tsindex 57fa94d42f..1518aeac1d 100644--- a/app/src/protyle/render/av/automation.test.ts+++ b/app/src/protyle/render/av/automation.test.ts@@ -11,7 +11,7 @@ const compiled = transpileModule(readFileSync("src/protyle/render/av/automation.compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},}).outputText;-test("collection autosave versions document depth, attribute names and self exclusion with independent undo snapshots", async () => {+test("collection autosave versions document depth, attribute names, self exclusion and references with independent undo snapshots", async () => {const transactions: Array<{perform: IOperation[], undo: IOperation[]}> = [];let source: AVAutomationBlockSourceInput;let save: () => void;@@ -83,6 +83,17 @@ test("collection autosave versions document depth, attribute names and self exclassert.equal(included.perform[0].data.spec, 7);assert.equal(included.perform[0].data.rules[0].blockSource.includeSelectedDocuments, undefined);assert.deepEqual(included.undo, excluded.perform);+ source.referenceID = "20261026000000-target1";+ save();+ const referenced = JSON.parse(JSON.stringify(transactions.at(-1)));+ assert.equal(referenced.perform[0].data.spec, 8);+ assert.equal(referenced.perform[0].data.rules[0].blockSource.referenceID, source.referenceID);+ assert.deepEqual(referenced.undo, included.perform);+ delete source.referenceID;+ save();+ const cleared = JSON.parse(JSON.stringify(transactions.at(-1)));+ assert.equal(cleared.perform[0].data.spec, 8);+ assert.equal(cleared.perform[0].data.rules[0].blockSource.referenceID, undefined);});test("automation settings reject readonly, publishing and historical editors before fetching data", async () => {diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.tsindex e6c76c1034..e48efc23d7 100644--- a/app/src/protyle/render/av/automation.ts+++ b/app/src/protyle/render/av/automation.ts@@ -214,7 +214,8 @@ export const openAutomationMenu = async (options: {const usesAttributeNameMatch = rules.some(rule => rule.blockSource?.attributes?.some(attr =>attr?.nameOperator && attr.nameOperator !== "equals"));const excludesSelectedDocuments = rules.some(rule => rule.blockSource?.includeSelectedDocuments === false);- const next = {spec: Math.max(previous.spec, excludesSelectedDocuments ? 7 : usesAttributeNameMatch ? 6 : usesDocumentDepth ? 5 : usesTagTarget ? 4 : usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};+ const usesReferences = rules.some(rule => !!rule.blockSource?.referenceID);+ const next = {spec: Math.max(previous.spec, usesReferences ? 8 : excludesSelectedDocuments ? 7 : usesAttributeNameMatch ? 6 : usesDocumentDepth ? 5 : usesTagTarget ? 4 : usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};if (JSON.stringify(next) === JSON.stringify(previous)) {return;}diff --git a/app/src/protyle/render/av/blockCollection.test.ts b/app/src/protyle/render/av/blockCollection.test.tsindex b3903b9e79..794dea31ba 100644--- a/app/src/protyle/render/av/blockCollection.test.ts+++ b/app/src/protyle/render/av/blockCollection.test.ts@@ -44,6 +44,7 @@ const browserCases = async (sourceCode: string, languages: Record<string, string"../../../util/escape": {escapeAttr: String, escapeHtml: String},"../../../util/fetch": {fetchSyncPost: async () => ({code: 0, data: "/Selected document"})},"./collectionConditions": {mountCollectionConditions() {}},+ "./collectionReference": {mountCollectionReference() {}},"../../../util/pathName": {movePathTo: (options: {cb: typeof addScope}) => { addScope = options.cb; }},"../../../menus/menuToggle": {toggleMenu: (options: {build: () => void, show: () => void}) => { options.build(); options.show(); }},"../../../plugin/Menu": {Menu: class {diff --git a/app/src/protyle/render/av/blockCollection.ts b/app/src/protyle/render/av/blockCollection.tsindex d474443caa..4ea87a7a2c 100644--- a/app/src/protyle/render/av/blockCollection.ts+++ b/app/src/protyle/render/av/blockCollection.ts@@ -6,9 +6,11 @@ import {mountCollectionConditions} from "./collectionConditions";import {BlockPanel} from "../../../block/Panel";import {Menu} from "../../../plugin/Menu";import {toggleMenu} from "../../../menus/menuToggle";+import {mountCollectionReference} from "./collectionReference";export const collectionSourceIncomplete = (source: AVAutomationBlockSourceInput) => !source ||!(source.notebookIDs?.length || source.documentIDs?.length) ||+ (!!source.referenceID && !/^\d{14}-[a-z0-9]{7}$/.test(source.referenceID)) ||(source.documentDepth != null && (!Number.isSafeInteger(source.documentDepth) || source.documentDepth < 0)) ||(source.attributes || []).some(attr => !attr || !attr.name || attr.name.length > 256 ||(attr.nameOperator === "regex" ? false :@@ -19,6 +21,10 @@ export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomaticonst lang = window.siyuan.languages;const conditions = document.createElement("div");mountCollectionConditions(conditions, source, save, onResize);+ const reference = document.createElement("div");+ const updateTarget = () => conditions.querySelector("[data-tag-target-control]")?.classList.toggle("fn__none", !!source.referenceID);+ mountCollectionReference(reference, source, protyle, () => { updateTarget(); save(); }, onResize);+ updateTarget();const names = new Map<string, string>();let revision = 0;const depthMode = () => source.documentDepth == null ? "unlimited" : source.documentDepth === 0 ? "current" : "limited";@@ -44,7 +50,7 @@ ${notebooks.length || documents.length ? `<div class="av__automation-source-list${documents.length ? `<div class="av__automation-control"><label class="av__automation-row"><span class="fn__flex-1">${lang.automationCollectionIncludeSelf}</span><input type="checkbox" class="b3-switch" data-include-selected-documents${source.includeSelectedDocuments !== false ? " checked" : ""}></label><div class="ft__on-surface ft__smaller av__automation-tip">${lang.automationCollectionIncludeSelfTip}</div></div><div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.automationCollectionDepth}</span><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-depth-mode aria-label="${escapeAttr(lang.automationCollectionDepth)}"><span>${depthLabels[depthMode()]}</span><svg><use xlink:href="#iconDown"></use></svg></button></div>${depthMode() === "limited" ? `<input type="number" class="b3-text-field fn__block" min="1" step="1" required data-document-depth value="${source.documentDepth}" aria-label="${escapeAttr(lang.automationCollectionDepth)}">` : ""}<div class="ft__on-surface ft__smaller av__automation-tip">${lang.automationCollectionDepthTip}</div></div>` : ""}</div>`;- host.firstElementChild.append(conditions);+ host.firstElementChild.append(reference, conditions);onResize();};host.addEventListener("click", event => {diff --git a/app/src/protyle/render/av/collectionConditions.ts b/app/src/protyle/render/av/collectionConditions.tsindex 6e1f09e11c..84f8fb3402 100644--- a/app/src/protyle/render/av/collectionConditions.ts+++ b/app/src/protyle/render/av/collectionConditions.ts@@ -38,7 +38,7 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatioconst addButton = (action: string, label: string) => `<button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" ${action}><svg><use xlink:href="#iconAdd"></use></svg><span>${escapeHtml(label)}</span></button>`;const chip = (kind: string, index: number, label: string, editable = false) => `<div class="b3-chip b3-chip--middle"><span class="fn__ellipsis${editable ? " b3-chip--pointer" : ""} ariaLabel" ${editable ? `data-edit-attribute="${index}" role="button" tabindex="0"` : ""} aria-label="${escapeAttr(label)}">${escapeHtml(label)}</span><svg class="b3-chip__close" data-remove-filter="${kind}" data-index="${index}" role="button" tabindex="0" aria-label="${escapeAttr(lang.delete)}"><use xlink:href="#iconClose"></use></svg></div>`;host.className = "av__automation-control";- host.innerHTML = `<div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.automationCollectionTarget}</span><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-tag-target aria-label="${escapeAttr(lang.automationCollectionTarget)}"><span>${tagTargets[source.tagTarget || ""]}</span><svg><use xlink:href="#iconDown"></use></svg></button></div><div class="ft__on-surface ft__smaller av__automation-tip" data-tag-target-tip>${tagTargetTips[source.tagTarget || ""]}</div><div class="ft__on-surface ft__smaller av__automation-tip fn__none" data-tag-target-change-tip>${lang.automationCollectionTargetChangeTip}</div></div>+ host.innerHTML = `<div class="av__automation-control" data-tag-target-control><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.automationCollectionTarget}</span><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-tag-target aria-label="${escapeAttr(lang.automationCollectionTarget)}"><span>${tagTargets[source.tagTarget || ""]}</span><svg><use xlink:href="#iconDown"></use></svg></button></div><div class="ft__on-surface ft__smaller av__automation-tip" data-tag-target-tip>${tagTargetTips[source.tagTarget || ""]}</div><div class="ft__on-surface ft__smaller av__automation-tip fn__none" data-tag-target-change-tip>${lang.automationCollectionTargetChangeTip}</div></div><div class="av__automation-control"><span class="av__automation-control-label">${lang.automationCollectionTypes}</span><div class="fn__flex-column"><div class="b3-chips b3-chips__doctag av__automation-chips" data-type-chips></div>${addButton("data-types", `${lang.addAttr} - ${lang.automationCollectionTypes}`)}</div></div><div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.tag}</span>${modeButton("tagMatch", lang.tag)}</div><div class="fn__flex-column" data-tags></div></div><div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.attr}</span>${modeButton("attributeMatch", lang.attr)}</div><div class="fn__flex-column"><div class="b3-chips b3-chips__doctag av__automation-chips" data-attribute-chips></div>${addButton("data-add-attribute", `${lang.addAttr} - ${lang.attr}`)}</div><div data-attribute-editor></div></div>`;diff --git a/app/src/protyle/render/av/collectionReference.test.ts b/app/src/protyle/render/av/collectionReference.test.tsnew file mode 100644index 0000000000..77cabcc90c--- /dev/null+++ b/app/src/protyle/render/av/collectionReference.test.ts@@ -0,0 +1,125 @@+import * as assert from "node:assert/strict";+import {readFileSync, mkdtempSync, rmSync, writeFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {execFile} from "node:child_process";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {promisify} from "node:util";+import type {AVAutomationBlockSourceInput} from "../../../types/api";+import type {openInputDialog} from "../../../dialog/inputDialog";++const compiled = transpileModule(readFileSync("src/protyle/render/av/collectionReference.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+}).outputText;++test("reference targets accept block IDs and block links without matching arbitrary text", () => {+ const api = {} as typeof import("./collectionReference");+ runInNewContext(compiled, {exports: api, require: () => ({})});+ const id = "20261026000000-target1";+ for (const value of [id, ` ${id} `, `siyuan://blocks/${id}`, `siyuan://blocks/${id}?focus=1`]) {+ assert.equal(api.parseCollectionReference(value), id);+ }+ for (const value of ["", "not-a-block", `https://example.com/${id}`, `text ${id}`, `siyuan://blocks/${id}/other`, `${id}extra`]) {+ assert.equal(api.parseCollectionReference(value), undefined);+ }+});++const browserCases = async (sourceCode: string, languages: Record<string, string>) => {+ const check: typeof assert = require("node:assert/strict");+ const api = {} as typeof import("./collectionReference");+ let inputOptions: Parameters<typeof openInputDialog>[0];+ const target = "20261026000000-target1";+ const rootID = "20261026000000-source1";+ const pendingNames: Array<(value: unknown) => void> = [];+ let pendingSelection: (value: unknown) => void;+ Object.assign(window, {siyuan: {languages, blockPanels: []}});+ new Function("exports", "require", sourceCode)(api, (name: string) => ({+ "../../../util/escape": {escapeAttr: String, escapeHtml: String},+ "../../../dialog/inputDialog": {openInputDialog: (options: typeof inputOptions) => { inputOptions = options; }},+ "../../../util/fetch": {fetchSyncPost: async (url: string, body: {id: string}) => {+ if (url === "/api/block/getBlockInfo") {+ if (body.id === "20261026000000-pending") { return new Promise(resolve => { pendingSelection = resolve; }); }+ return {code: body.id === "20261026000000-missing" ? -1 : 0};+ }+ return new Promise(resolve => pendingNames.push(resolve));+ }},+ "../../../block/Panel": {BlockPanel: class {}},+ })[name] || {});+ const tick = () => new Promise(resolve => setTimeout(resolve, 0));+ for (const width of [1000, 320]) {+ const host = document.createElement("div");+ host.style.width = `${width}px`;+ document.body.append(host);+ const source: AVAutomationBlockSourceInput = {};+ const saves: AVAutomationBlockSourceInput[] = [];+ api.mountCollectionReference(host, source, {block: {rootID}} as IProtyle,+ () => saves.push(JSON.parse(JSON.stringify(source))), () => {});+ host.querySelector<HTMLButtonElement>("[data-reference]").click();+ const input = document.createElement("input");+ let destroyed = false;+ const dialog = {element: {querySelector: () => input}, destroy() { destroyed = true; }} as unknown as Parameters<typeof inputOptions.onConfirm>[1];+ await inputOptions.onConfirm("invalid", dialog);+ check.equal(input.validationMessage, languages.invalid);+ check.equal(saves.length, 0);+ await inputOptions.onConfirm(`siyuan://blocks/${target}?focus=1`, dialog);+ check.equal(source.referenceID, target);+ check.equal(saves.at(-1).referenceID, target);+ check.equal(destroyed, true);+ host.querySelector<HTMLButtonElement>("[data-preview-reference]").click();+ check.equal(window.siyuan.blockPanels.length, 1);+ window.siyuan.blockPanels.length = 0;+ host.querySelector<HTMLButtonElement>("[data-reference-document]").click();+ await tick();+ check.equal(source.referenceID, rootID);+ check.equal(saves.at(-1).referenceID, rootID);+ const stale = pendingNames.splice(0);+ stale[stale.length - 1]({code: 0, data: "<Current document>"});+ stale[0]({code: 0, data: "Outdated target"});+ await tick();+ check.equal(host.querySelector("[data-preview-reference]").textContent, "<Current document>");+ check.equal(host.querySelector("[data-preview-reference]").children.length, 0);+ host.querySelector<HTMLButtonElement>("[data-reference]").click();+ const pending = inputOptions.onConfirm("20261026000000-pending", dialog);+ host.querySelector<HTMLButtonElement>("[data-clear-reference]").click();+ pendingSelection({code: 0});+ await pending;+ check.equal(source.referenceID, undefined);+ check.equal(host.querySelector("[data-preview-reference]"), null);+ check.equal(saves.at(-1).referenceID, undefined);+ check.ok(host.scrollWidth <= width);+ host.remove();+ }+ return "Reference collection DOM cases passed";+};++test("reference selection, current document, clearing and stale labels work on desktop and narrow layouts", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-collection-reference-"));+ const script = path.join(temporary, "run.cjs");+ const languages = JSON.parse(readFileSync("appearance/langs/en.json", "utf8"));+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ try {+ await win.loadURL("about:blank");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(`const __name = value => value; (${browserCases.toString()})(${JSON.stringify(compiled)}, ${JSON.stringify(languages)})`)}));+ win.destroy(); app.exit(0);+ } catch (error) { console.error(error); win.destroy(); app.exit(1); }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const {stdout} = await promisify(execFile)(require("electron") as unknown as string, [script], {env, timeout: 40000, windowsHide: true});+ assert.match(stdout, /Reference collection DOM cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-collection-reference-"));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/render/av/collectionReference.ts b/app/src/protyle/render/av/collectionReference.tsnew file mode 100644index 0000000000..274e75afc6--- /dev/null+++ b/app/src/protyle/render/av/collectionReference.ts@@ -0,0 +1,73 @@+import type {AVAutomationBlockSourceInput} from "../../../types/api";+import {openInputDialog} from "../../../dialog/inputDialog";+import {fetchSyncPost} from "../../../util/fetch";+import {escapeAttr, escapeHtml} from "../../../util/escape";+import {BlockPanel} from "../../../block/Panel";++export const parseCollectionReference = (value: string) => {+ const match = /^(?:siyuan:\/\/blocks\/)?(\d{14}-[a-z0-9]{7})(?:\?[^\s]*)?$/.exec(value.trim());+ return match?.[1];+};++export const mountCollectionReference = (host: HTMLElement, source: AVAutomationBlockSourceInput,+ protyle: IProtyle, save: () => void, resize: () => void) => {+ const lang = window.siyuan.languages;+ let revision = 0;+ let selectionRevision = 0;+ const render = async () => {+ const version = ++revision;+ const id = source.referenceID;+ host.className = "av__automation-control";+ host.innerHTML = `<span class="av__automation-control-label">${lang.automationCollectionReference}</span>+<div class="av__automation-row">${id ? `<button type="button" class="b3-button b3-button--cancel b3-button--wrap fn__flex-1 av__automation-source-action" data-preview-reference data-id="${escapeAttr(id)}">${escapeHtml(id)}</button><button type="button" class="block__icon" data-clear-reference aria-label="${escapeAttr(lang.delete)}"><svg><use xlink:href="#iconClose"></use></svg></button>` : ""}</div>+<div class="av__automation-row"><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-reference>${lang.select}</button><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-reference-document>${lang.filterCurrentDocument}</button></div>+<div class="ft__on-surface ft__smaller av__automation-tip">${lang.automationCollectionReferenceTip}</div>`;+ resize();+ if (id) {+ const result = await fetchSyncPost("/api/block/getRefText", {id});+ if (version === revision && host.isConnected && result.code === 0) {+ host.querySelector("[data-preview-reference]").textContent = result.data || id;+ resize();+ }+ }+ };+ const setReference = async (id: string): Promise<boolean> => {+ const version = ++selectionRevision;+ const result = await fetchSyncPost("/api/block/getBlockInfo", {id});+ if (version !== selectionRevision || !host.isConnected || result.code !== 0) { return false; }+ source.referenceID = id;+ save();+ void render();+ return true;+ };+ host.addEventListener("click", event => {+ const target = (event.target as Element).closest<HTMLElement>("button");+ if (!target) { return; }+ if (target.hasAttribute("data-clear-reference")) {+ selectionRevision++;+ delete source.referenceID;+ save();+ void render();+ } else if (target.hasAttribute("data-preview-reference")) {+ window.siyuan.blockPanels.push(new BlockPanel({app: protyle.app, targetElement: target,+ isBacklink: false, refDefs: [{refID: source.referenceID}]}));+ } else if (target.hasAttribute("data-reference-document")) {+ void setReference(protyle.block.rootID);+ } else if (target.hasAttribute("data-reference")) {+ openInputDialog({title: lang.automationCollectionReference, value: source.referenceID || "",+ description: lang.automationCollectionReferenceTip,+ onConfirm: async (value, dialog) => {+ const id = parseCollectionReference(value);+ const input = dialog.element.querySelector<HTMLInputElement>("[data-dialog-input]");+ if (!id) {+ input.setCustomValidity(lang.invalid);+ input.reportValidity();+ return;+ }+ input.setCustomValidity("");+ if (await setReference(id)) { dialog.destroy(); }+ }});+ }+ });+ void render();+};diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 2bf1d8f9d6..db8778f27b 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -260,9 +260,9 @@ export type AVAutomationBlockAttribute = { "name": string; "nameOperator"?: "" |export type AVAutomationBlockAttributeInput = { "name": string; "nameOperator"?: "" | "equals" | "contains" | "regex"; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };-export type AVAutomationBlockSource = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentDepth"?: number; "documentIDs"?: Array<string>; "includeSelectedDocuments"?: boolean; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };+export type AVAutomationBlockSource = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentDepth"?: number; "documentIDs"?: Array<string>; "includeSelectedDocuments"?: boolean; "notebookIDs"?: Array<string>; "referenceID"?: string; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };-export type AVAutomationBlockSourceInput = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentDepth"?: number | null; "documentIDs"?: Array<string>; "includeSelectedDocuments"?: boolean | null; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };+export type AVAutomationBlockSourceInput = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentDepth"?: number | null; "documentIDs"?: Array<string>; "includeSelectedDocuments"?: boolean | null; "notebookIDs"?: Array<string>; "referenceID"?: string; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };export type AVAutomationConfig = { "rules": Array<AVAutomationRule | null> | null; "spec": number; };@@ -8563,13 +8563,15 @@ export interface APIPOSTRoutes {/*** move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。- * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 7,所有视图共享数据库级规则。+ * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 8,所有视图共享数据库级规则。* blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。* blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。* spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。* spec 5 的 blockSource.documentDepth 限制各文档范围的子文档深度,0 仅自身,1 包含自身及一级子文档。* spec 6 的属性 nameOperator 支持 contains 和 Go regex;缺省或 equals 保持精确名称匹配,值条件独立。* spec 7 支持 blockSource.includeSelectedDocuments=false,排除所选文档及其内部块,子文档仍按深度匹配;缺省、null 或 true 保持包含自身。+ * spec 8 的 blockSource.referenceID 匹配正文块引用;文档目标包含内部内容块,不含子文档、嵌入或数据库字段引用。+ * 引用来源按反链规则归并后匹配类型和属性,标签条件约束同一来源块,tagTarget 不参与选择;目标须在同一加密边界。* 排除自身不影响其他范围的并集;与 documentDepth=0 组合时对应文档范围为空。配置变更保留条目和字段,不自动补收或清理。* 深度缺省或 null 不限,不影响笔记本范围,各范围仍取并集;修改不自动清理或补收已有内容。* 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。diff --git a/docs/API.ja.md b/docs/API.ja.mdindex 205d27d0c1..fd0605d0e9 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -2240,7 +2240,7 @@ if (response.code === 0 && response.data) {* `data.av`: 完全な `AttributeView` 定義——フィールド(`keyValues`)、フィールド順序(`keyIDs`、`null` の場合あり)、および全ビューの生のレイアウト設定(`table`/`gallery`/`kanban`)とアイテム順序(`itemIds`)。互換性フィールド `viewID` は最初に利用可能なビューから算出され、永続化されません。レンダリング後の行やページングは含まれないため、計算後の行データが必要な場合は [レンダリング](#レンダリング) を使用してください- * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`~`7`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。自動収集は追加だけを行います。原文やルールの条件・範囲・対象・有効状態が変わっても既存の項目とフィールドを保持し、再び一致しても同じ項目を使います。明示的な整理ではすべての有効な収集ルールを使い、手動・自動でバインドした項目を同じ基準で確認します。一致する項目や判定できない項目は保持し、実行前の再確認で不一致が確定した項目だけを除去します。元に戻す操作で元の項目と全フィールドを復元します。 `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。 形式 4 では省略可能な `blockSource.tagTarget` を追加しています。省略・空文字列は既定の選択で、最初の内容ブロックより条件に合うリスト項目を優先、`block` はタグを含むブロック、`container` は種類と属性の条件に一致する最も近いコンテナを収集し、ブロック ID で重複を除きます。文書には明示的な `d` の選択が必要です。AND のタグは同じ元ブロックに必要で、タグ条件がなければこの設定は影響しません。プレビューと実際の収集対象は一致し、切り替えても既存項目とフィールドは維持されます。 形式 5 では省略可能な `blockSource.documentDepth` を追加しています。省略または `null` は無制限、`0` は選択した各文書自体のみ、`1` は直接の子文書も含み、他の非負整数は相対的な最大階層数を指定します。文書の範囲すべてに共通し、ノートブックの範囲は制限せず、範囲は和集合のままです。深さを変更しても既存の項目とフィールドを保持し、既存の内容を自動で追加収集しません。 形式 6 は各属性条件に省略可能な `nameOperator` を追加します。省略・空文字列・`equals` は完全な名前との一致を維持し、`contains` は `custom-` 接頭辞の入力を必要としない文字列の部分一致、`regex` は接頭辞を含む完全な名前に対する Go の正規表現です。カスタム属性だけを照合し、名前と値は大文字小文字を区別して同じ属性で満たす必要があります。`exists` は名前の一致が一つ以上、`notExists` は一致がないことを要求し、値は無視します。名前パターンは最大 256 バイトで、不正な式は保存を拒否します。既存の形式 1–5 の動作は維持し、古いリーダーはデータベースを書き換えずに形式 6 を拒否します。 形式 7 は省略可能な `blockSource.includeSelectedDocuments` を追加します。省略・`null`・`true` は選択した各文書自体を含み、`false` はその文書と内部のすべてのブロックを除外し、子孫文書には引き続き `documentDepth` を適用します。この設定は文書範囲に共通で、ノートブックの範囲や重なる別の文書範囲には影響せず、範囲は和集合のままです。`false` と深さ `0` の組み合わせでは、対応する文書範囲は空です。変更しても既存の項目とフィールドを保持し、自動で追加収集や除去を行いません。形式 1–6 は引き続き読み取れ、古いリーダーはデータベースを書き換えずに形式 7 を拒否します。+ * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`~`8`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。自動収集は追加だけを行います。原文やルールの条件・範囲・対象・有効状態が変わっても既存の項目とフィールドを保持し、再び一致しても同じ項目を使います。明示的な整理ではすべての有効な収集ルールを使い、手動・自動でバインドした項目を同じ基準で確認します。一致する項目や判定できない項目は保持し、実行前の再確認で不一致が確定した項目だけを除去します。元に戻す操作で元の項目と全フィールドを復元します。 `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。 形式 4 では省略可能な `blockSource.tagTarget` を追加しています。省略・空文字列は既定の選択で、最初の内容ブロックより条件に合うリスト項目を優先、`block` はタグを含むブロック、`container` は種類と属性の条件に一致する最も近いコンテナを収集し、ブロック ID で重複を除きます。文書には明示的な `d` の選択が必要です。AND のタグは同じ元ブロックに必要で、タグ条件がなければこの設定は影響しません。プレビューと実際の収集対象は一致し、切り替えても既存項目とフィールドは維持されます。 形式 5 では省略可能な `blockSource.documentDepth` を追加しています。省略または `null` は無制限、`0` は選択した各文書自体のみ、`1` は直接の子文書も含み、他の非負整数は相対的な最大階層数を指定します。文書の範囲すべてに共通し、ノートブックの範囲は制限せず、範囲は和集合のままです。深さを変更しても既存の項目とフィールドを保持し、既存の内容を自動で追加収集しません。 形式 6 は各属性条件に省略可能な `nameOperator` を追加します。省略・空文字列・`equals` は完全な名前との一致を維持し、`contains` は `custom-` 接頭辞の入力を必要としない文字列の部分一致、`regex` は接頭辞を含む完全な名前に対する Go の正規表現です。カスタム属性だけを照合し、名前と値は大文字小文字を区別して同じ属性で満たす必要があります。`exists` は名前の一致が一つ以上、`notExists` は一致がないことを要求し、値は無視します。名前パターンは最大 256 バイトで、不正な式は保存を拒否します。既存の形式 1–5 の動作は維持し、古いリーダーはデータベースを書き換えずに形式 6 を拒否します。 形式 7 は省略可能な `blockSource.includeSelectedDocuments` を追加します。省略・`null`・`true` は選択した各文書自体を含み、`false` はその文書と内部のすべてのブロックを除外し、子孫文書には引き続き `documentDepth` を適用します。この設定は文書範囲に共通で、ノートブックの範囲や重なる別の文書範囲には影響せず、範囲は和集合のままです。`false` と深さ `0` の組み合わせでは、対応する文書範囲は空です。変更しても既存の項目とフィールドを保持し、自動で追加収集や除去を行いません。形式 1–6 は引き続き読み取れ、古いリーダーはデータベースを書き換えずに形式 7 を拒否します。 形式 8 は省略可能な `blockSource.referenceID` を追加します。本文中でこのブロックを参照するブロック参照を照合し、文書を指定した場合は内部のコンテンツブロックも含みますが、子文書は含みません。埋め込み、通常のリンク、データベースのリッチテキストフィールド内の参照は対象外です。タグは同じ参照元を判定し、バックリンクの親ブロック規則でまとめた後に種類と属性を判定します。`tagTarget` は使用しません。参照先は同じ暗号化境界内に限られます。参照の削除や参照先の変更でも既存の項目とフィールドを保持し、以前の内容はプレビューして明示的に収集します。形式 1–7 は引き続き読み取れ、古いクライアントはデータベースを書き換えずに形式 8 を拒否します。### 主キー値を取得diff --git a/docs/API.md b/docs/API.mdindex cf73ac3500..8c59695adf 100644--- a/docs/API.md+++ b/docs/API.md@@ -2250,7 +2250,7 @@ The field types (`keyType`) are:* `data.av`: The full `AttributeView` definition — fields (`keyValues`), field ordering (`keyIDs`, may be `null`), and all views with their raw layout config (`table`/`list`/`gallery`/`kanban`) and item ordering (`itemIds`). The compatibility `viewID` is computed as the first available view and is not persisted. Returns no rendered rows or pagination; therefore, use [Render](#Render) for computed rows- * `data.av.automations` optionally contains database-wide rules (`spec: 1` through `7`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Automatic collection only adds entries. Source changes and changes to rule conditions, scope, target, or activation preserve existing rows and fields; matching again keeps the same row. Explicit cleanup checks all enabled collection rules for manual and automatic bound entries alike, preserves matches and indeterminate entries, and rechecks before removing unmatched entries; undo restores the original row and all fields. `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages. Format 4 adds optional `blockSource.tagTarget`: omitted/empty uses default selection, preferring an eligible list item over its first content block, `block` collects the tagged block itself, and `container` collects the nearest container meeting type and attribute conditions, deduplicated by block ID. Documents require an explicit `d` type. AND tags must occur in one source block; without tag conditions this option has no effect. Preview and actual collection share the same targets; changing this option preserves existing rows and fields. Format 5 adds optional `blockSource.documentDepth`: omitted or `null` means unlimited, `0` includes only each selected document itself, and `1` also includes its direct children. Other nonnegative integers set the maximum relative descendant depth. It applies uniformly to document scopes, not notebook scopes; scopes remain combined by union. Changing depth preserves existing rows and fields and does not backfill existing content. Format 6 adds each attribute condition's optional `nameOperator`: omitted/empty or `equals` retains exact full-name matching, `contains` matches a literal substring without requiring the `custom-` prefix, and `regex` uses Go regular expressions against the full name including that prefix. Only custom attributes are considered. Names and values are case-sensitive and must match on the same attribute; `exists` requires at least one name match and `notExists` requires none, ignoring the value. Name patterns are limited to 256 bytes; invalid expressions are rejected on save. Existing formats 1–5 retain their behavior; older readers reject format 6 without rewriting the database. Format 7 adds optional `blockSource.includeSelectedDocuments`: omitted, `null`, or `true` includes each selected document itself; `false` excludes it and all blocks inside it while descendants still follow `documentDepth`. This option is shared by document scopes and does not affect notebook scopes or other overlapping document scopes; scopes remain combined by union. With `false` and depth `0`, the corresponding document scope is empty. Changing it preserves existing rows and fields without automatic backfill or removal. Formats 1–6 remain readable; older readers reject format 7 without rewriting the database.+ * `data.av.automations` optionally contains database-wide rules (`spec: 1` through `8`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Automatic collection only adds entries. Source changes and changes to rule conditions, scope, target, or activation preserve existing rows and fields; matching again keeps the same row. Explicit cleanup checks all enabled collection rules for manual and automatic bound entries alike, preserves matches and indeterminate entries, and rechecks before removing unmatched entries; undo restores the original row and all fields. `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages. Format 4 adds optional `blockSource.tagTarget`: omitted/empty uses default selection, preferring an eligible list item over its first content block, `block` collects the tagged block itself, and `container` collects the nearest container meeting type and attribute conditions, deduplicated by block ID. Documents require an explicit `d` type. AND tags must occur in one source block; without tag conditions this option has no effect. Preview and actual collection share the same targets; changing this option preserves existing rows and fields. Format 5 adds optional `blockSource.documentDepth`: omitted or `null` means unlimited, `0` includes only each selected document itself, and `1` also includes its direct children. Other nonnegative integers set the maximum relative descendant depth. It applies uniformly to document scopes, not notebook scopes; scopes remain combined by union. Changing depth preserves existing rows and fields and does not backfill existing content. Format 6 adds each attribute condition's optional `nameOperator`: omitted/empty or `equals` retains exact full-name matching, `contains` matches a literal substring without requiring the `custom-` prefix, and `regex` uses Go regular expressions against the full name including that prefix. Only custom attributes are considered. Names and values are case-sensitive and must match on the same attribute; `exists` requires at least one name match and `notExists` requires none, ignoring the value. Name patterns are limited to 256 bytes; invalid expressions are rejected on save. Existing formats 1–5 retain their behavior; older readers reject format 6 without rewriting the database. Format 7 adds optional `blockSource.includeSelectedDocuments`: omitted, `null`, or `true` includes each selected document itself; `false` excludes it and all blocks inside it while descendants still follow `documentDepth`. This option is shared by document scopes and does not affect notebook scopes or other overlapping document scopes; scopes remain combined by union. With `false` and depth `0`, the corresponding document scope is empty. Changing it preserves existing rows and fields without automatic backfill or removal. Formats 1–6 remain readable; older readers reject format 7 without rewriting the database. Format 8 adds optional `blockSource.referenceID`: body block references must point to this block; a document target also includes its internal content blocks, excluding child documents. Embeds, ordinary links and references in database rich-text fields are excluded. Tags constrain the same reference source; sources are grouped using backlink parent rules before type and attribute filtering, and `tagTarget` is ignored. The target must be in the same encryption boundary. Existing rows and fields are preserved when references are removed or the target changes; older matches require explicit preview and collection. Formats 1–7 remain readable; older readers reject format 8 without rewriting the database.### Get primary key valuesdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 5e1acdaa23..27b6940db8 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -2246,7 +2246,7 @@ if (response.code === 0 && response.data) {* `data.av`: 完整的 `AttributeView` 定义——字段(`keyValues`)、字段顺序(`keyIDs`,可能为 `null`),以及所有视图的原始布局配置(`table`/`list`/`gallery`/`kanban`)和条目顺序(`itemIds`)。兼容字段 `viewID` 动态取第一个可用视图,不会持久化。返回值不含渲染后的行或分页;需要计算后的行数据请使用 [渲染](#渲染)- * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1` 至 `7`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。自动收集只添加条目,原文变化及规则条件、范围、对象或启用状态变化均保留已有条目和字段,再次匹配仍使用原条目。主动清理按全部启用的收集规则统一检查手动和自动绑定条目,保留匹配或无法判断的条目,执行前复查后仅移出确认不匹配的条目;撤销恢复原条目及全部字段。 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。 格式 4 增加可选的 `blockSource.tagTarget`:缺省或空字符串使用默认选择,优先收集合格列表项而非其首个内容块,`block` 收集标签所在块,`container` 选择最近的符合类型和属性条件的容器并按块 ID 去重;文档需显式选择 `d`。全部标签须在同一个来源块中,无标签条件时此选项不影响筛选。预览与实际收集对象一致,切换保留已有条目及字段。 格式 5 增加可选的 `blockSource.documentDepth`:缺省或 `null` 表示不限,`0` 仅包含每个选中文档本身,`1` 还包含一级子文档,其他非负整数指定最大相对后代深度。该设置统一限制文档范围,不影响笔记本范围,各范围仍取并集。修改深度保留已有条目和字段,不自动补收存量内容。 格式 6 为每条属性条件增加可选的 `nameOperator`:缺省、空字符串或 `equals` 保持完整名称精确匹配,`contains` 按字面子串匹配且无需输入 `custom-` 前缀,`regex` 使用 Go 正则语法匹配包含该前缀的完整名称。仅匹配自定义属性,名称和值区分大小写,且必须由同一条属性同时满足;`exists` 要求至少一个名称匹配,`notExists` 要求没有名称匹配,两者忽略属性值。名称模式最多 256 字节,非法正则拒绝保存。既有格式 1–5 的行为保持不变,旧读取器拒绝格式 6 且不改写数据库。 格式 7 增加可选的 `blockSource.includeSelectedDocuments`:缺省、`null` 或 `true` 包含每个所选文档自身;`false` 排除该文档及其内部所有块,子文档仍按 `documentDepth` 匹配。该设置由所有文档范围共用,不影响笔记本范围或其他重叠文档范围,各范围仍取并集。`false` 与深度 `0` 组合时,对应文档范围为空。修改后保留已有条目和字段,不自动补收或移出。格式 1–6 仍可读取,旧读取器拒绝格式 7 且不改写数据库。+ * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1` 至 `8`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。自动收集只添加条目,原文变化及规则条件、范围、对象或启用状态变化均保留已有条目和字段,再次匹配仍使用原条目。主动清理按全部启用的收集规则统一检查手动和自动绑定条目,保留匹配或无法判断的条目,执行前复查后仅移出确认不匹配的条目;撤销恢复原条目及全部字段。 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。 格式 4 增加可选的 `blockSource.tagTarget`:缺省或空字符串使用默认选择,优先收集合格列表项而非其首个内容块,`block` 收集标签所在块,`container` 选择最近的符合类型和属性条件的容器并按块 ID 去重;文档需显式选择 `d`。全部标签须在同一个来源块中,无标签条件时此选项不影响筛选。预览与实际收集对象一致,切换保留已有条目及字段。 格式 5 增加可选的 `blockSource.documentDepth`:缺省或 `null` 表示不限,`0` 仅包含每个选中文档本身,`1` 还包含一级子文档,其他非负整数指定最大相对后代深度。该设置统一限制文档范围,不影响笔记本范围,各范围仍取并集。修改深度保留已有条目和字段,不自动补收存量内容。 格式 6 为每条属性条件增加可选的 `nameOperator`:缺省、空字符串或 `equals` 保持完整名称精确匹配,`contains` 按字面子串匹配且无需输入 `custom-` 前缀,`regex` 使用 Go 正则语法匹配包含该前缀的完整名称。仅匹配自定义属性,名称和值区分大小写,且必须由同一条属性同时满足;`exists` 要求至少一个名称匹配,`notExists` 要求没有名称匹配,两者忽略属性值。名称模式最多 256 字节,非法正则拒绝保存。既有格式 1–5 的行为保持不变,旧读取器拒绝格式 6 且不改写数据库。 格式 7 增加可选的 `blockSource.includeSelectedDocuments`:缺省、`null` 或 `true` 包含每个所选文档自身;`false` 排除该文档及其内部所有块,子文档仍按 `documentDepth` 匹配。该设置由所有文档范围共用,不影响笔记本范围或其他重叠文档范围,各范围仍取并集。`false` 与深度 `0` 组合时,对应文档范围为空。修改后保留已有条目和字段,不自动补收或移出。格式 1–6 仍可读取,旧读取器拒绝格式 7 且不改写数据库。 格式 8 增加可选的 `blockSource.referenceID`:匹配正文中指向该块的块引用,文档目标还包含内部内容块,不含子文档;不包含嵌入块、普通链接和数据库富文本字段中的引用。标签约束同一引用来源块,来源按反链父块规则归并后再匹配类型和属性,`tagTarget` 不参与选择。目标必须位于同一加密边界。移除引用或更改目标会保留已有条目和字段,历史内容需预览后显式补收。既有格式 1–7 仍可读取,旧客户端会拒绝格式 8 且不改写数据库。### 获取主键值diff --git a/kernel/api/av_contract_automation.go b/kernel/api/av_contract_automation.goindex 41d529ae33..2c055f9228 100644--- a/kernel/api/av_contract_automation.go+++ b/kernel/api/av_contract_automation.go@@ -78,6 +78,7 @@ func toContractAVAutomationBlockSource(source *av.AutomationBlockSource) *apiconreturn &apicontract.AVAutomationBlockSource{NotebookIDs: source.NotebookIDs, DocumentIDs: source.DocumentIDs,DocumentDepth: source.DocumentDepth,IncludeSelectedDocuments: source.IncludeSelectedDocuments,+ ReferenceID: source.ReferenceID,TagMatch: source.TagMatch, TagTarget: source.TagTarget, AttributeMatch: source.AttributeMatch,Types: source.Types, Tags: source.Tags, Attributes: avContractSlice(source.Attributes, func(attr *av.AutomationBlockAttribute) *apicontract.AVAutomationBlockAttribute {if attr == nil {diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.goindex 481226553e..ceba1bb9db 100644--- a/kernel/api/contract_av_automation_test.go+++ b/kernel/api/contract_av_automation_test.go@@ -465,4 +465,31 @@ func TestAVContractAutomationWrites(t *testing.T) {if _, err = model.LoadTreeByBlockID(quoteID); err != nil {t.Fatal("cleanup removed original quote", err)}+ t.Run("reference collection contract", func(t *testing.T) {+ collection.BlockSource.ReferenceID = tree.ID+ collection.BlockSource.Tags = nil+ collection.BlockSource.TagTarget = "block"+ config := &av.AutomationConfig{Spec: 7, Rules: []*av.AutomationRule{collection}}+ if err := model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID, Data: config}}); err == nil {+ t.Fatal("reference matching accepted an old automation format")+ }+ config.Spec = 8+ if err := model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID, Data: config}}); err != nil {+ t.Fatal(err)+ }+ response := callAttributeViewContextFilterAPI(t, "/api/av/getAttributeView", map[string]any{"id": database.ID}, getAttributeView)+ requireAPIContract(t, http.MethodPost, "/api/av/getAttributeView", response)+ if err := json.Unmarshal(response.Body.Bytes(), &readBack); err != nil {+ t.Fatal(err)+ }+ if readBack.Data.AV.Automations.Spec != 8 || readBack.Data.AV.Automations.Rules[0].BlockSource.ReferenceID != tree.ID {+ t.Fatal("reference target did not survive the API contract round trip")+ }+ call("/api/block/updateBlock", map[string]any{"id": paragraphs[0], "dataType": "markdown", "data": "Source ((" + tree.ID + " 'Target'))"}, updateBlock)+ call("/api/av/previewAttributeViewCollection", map[string]any{"avID": database.ID, "ruleID": collection.ID}, previewAttributeViewCollection)+ stored, err := av.ParseAttributeView(database.ID)+ if err != nil || stored.GetBlockValueByBoundID(quoteID) == nil {+ t.Fatal("API reference edit did not collect the backlink parent", err)+ }+ })}diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.goindex a09fa7c21f..c039e56f4c 100644--- a/kernel/apicontract/av_automation.go+++ b/kernel/apicontract/av_automation.go@@ -1,7 +1,7 @@package apicontract// AVAutomationConfig 通过 setAttrViewAutomations 事务操作整体保存,所有镜像和视图共享。-// spec 为 1 至 7;模板赋值至少使用 2,块子类型至少使用 3,标签收集对象至少使用 4,有限文档深度至少使用 5。+// spec 为 1 至 8;模板赋值至少使用 2,块子类型至少使用 3,标签收集对象至少使用 4,有限文档深度至少使用 5。// 属性名包含或正则匹配至少使用 6;缺省或 equals 保持既有的精确匹配。// 旧读取器拒绝新版本,防止配置静默丢失。// 缺省配置不会触发自动化,既有版本的主类型匹配含义不变。@@ -51,6 +51,11 @@ type AVAutomationRule struct {// 仅从不匹配变为匹配时收集,原条目不会重置;原文失配、修改条件、停用或删除规则均保留已有条目和字段。// 既有条目再次匹配时仍保留其字段;主动移出条目后再次匹配才新建并初始化,撤销重做恢复原事务快照。// 配置变更、启用规则、导入、同步和历史恢复不补收存量内容,也不串联触发其他自动化。+// referenceID 非空时要求 spec 8,匹配正文中指向该块的块引用;目标为文档时也匹配其内部块,不含子文档。+// 不包含嵌入块、普通超链接和数据库富文本字段引用;标签条件约束同一引用来源块。+// 引用来源按反链的父块归并规则选择并去重,再用类型和属性约束最终对象;此时 tagTarget 不参与选择。+// 引用目标须位于数据库的同一加密边界;移除引用或更改目标保留已有条目和字段,存量内容通过预览显式补收。+// 引用目标失效时,后续来源修改会停用规则并保留条目和字段,不阻止原文编辑;修复后须手动启用。type AVAutomationBlockSource struct {NotebookIDs []string `json:"notebookIDs,omitempty" api:"optional"`DocumentIDs []string `json:"documentIDs,omitempty" api:"optional"`@@ -58,6 +63,7 @@ type AVAutomationBlockSource struct {IncludeSelectedDocuments *bool `json:"includeSelectedDocuments,omitempty" api:"optional"`Types []string `json:"types,omitempty" api:"optional"`Tags []string `json:"tags,omitempty" api:"optional"`+ ReferenceID string `json:"referenceID,omitempty" api:"optional"`Attributes []*AVAutomationBlockAttribute `json:"attributes,omitempty" api:"optional"`TagMatch string `json:"tagMatch,omitempty" api:"optional,enum=|and|or"`TagTarget string `json:"tagTarget,omitempty" api:"optional,enum=|block|container"`diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 9cf9294330..7e8da660df 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1733,13 +1733,15 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system// move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。-// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 7,所有视图共享数据库级规则。+// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 8,所有视图共享数据库级规则。// blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。// blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。// spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。// spec 5 的 blockSource.documentDepth 限制各文档范围的子文档深度,0 仅自身,1 包含自身及一级子文档。// spec 6 的属性 nameOperator 支持 contains 和 Go regex;缺省或 equals 保持精确名称匹配,值条件独立。// spec 7 支持 blockSource.includeSelectedDocuments=false,排除所选文档及其内部块,子文档仍按深度匹配;缺省、null 或 true 保持包含自身。+// spec 8 的 blockSource.referenceID 匹配正文块引用;文档目标包含内部内容块,不含子文档、嵌入或数据库字段引用。+// 引用来源按反链规则归并后匹配类型和属性,标签条件约束同一来源块,tagTarget 不参与选择;目标须在同一加密边界。// 排除自身不影响其他范围的并集;与 documentDepth=0 组合时对应文档范围为空。配置变更保留条目和字段,不自动补收或清理。// 深度缺省或 null 不限,不影响笔记本范围,各范围仍取并集;修改不自动清理或补收已有内容。// 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 82a96e8ac3..d80951b3c9 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -6776,6 +6776,9 @@"type": "string"}},+ "referenceID": {+ "type": "string"+ },"tagMatch": {"type": "string","enum": [@@ -6863,6 +6866,9 @@"type": "string"}},+ "referenceID": {+ "type": "string"+ },"tagMatch": {"type": "string","enum": [diff --git a/kernel/av/automation.go b/kernel/av/automation.goindex 9b0b6d41c1..056c08c4ab 100644--- a/kernel/av/automation.go+++ b/kernel/av/automation.go@@ -36,6 +36,7 @@ type AutomationBlockSource struct {IncludeSelectedDocuments *bool `json:"includeSelectedDocuments,omitempty"`Types []string `json:"types,omitempty"`Tags []string `json:"tags,omitempty"`+ ReferenceID string `json:"referenceID,omitempty"`Attributes []*AutomationBlockAttribute `json:"attributes,omitempty"`TagMatch string `json:"tagMatch,omitempty"`TagTarget string `json:"tagTarget,omitempty"`@@ -94,6 +95,9 @@ func IsAutomationBlockType(value string) bool {func (rule *AutomationRule) RequiredSpec() int {ret := 1if rule.BlockSource != nil {+ if rule.BlockSource.ReferenceID != "" {+ return 8+ }if rule.BlockSource.IncludeSelectedDocuments != nil && !*rule.BlockSource.IncludeSelectedDocuments {return 7}@@ -134,7 +138,7 @@ func (config *AutomationConfig) ValidateSpec() error {if config == nil {return nil}- if config.Spec < 1 || config.Spec > 7 {+ if config.Spec < 1 || config.Spec > 8 {return fmt.Errorf("unsupported database automation specification [%d]", config.Spec)}for _, rule := range config.Rules {diff --git a/kernel/av/automation_test.go b/kernel/av/automation_test.goindex 63138d0ffc..b6b5e3da8a 100644--- a/kernel/av/automation_test.go+++ b/kernel/av/automation_test.go@@ -112,7 +112,7 @@ func TestAutomationClonePreservesPausedRules(t *testing.T) {if copiedRule.Actions[1].RelationKeyID == relationID || !rule.Enabled || rule.KeyID != primaryID {t.Fatal("copy changed the original rule or retained its source field")}- source.Automations.Spec = 8+ source.Automations.Spec = 9future, _ := json.Marshal(source)if _, err := ParseAttributeViewData(source.ID, future); err == nil {t.Fatal("unknown automation format was accepted")@@ -263,3 +263,29 @@ func TestAutomationPreservesPersistedColors(t *testing.T) {t.Fatal("automation-only custom color was considered unused")}}++func TestAutomationReferenceSpecCompatibility(t *testing.T) {+ data, err := os.ReadFile("testdata/spec9-layouts.json")+ if err != nil {+ t.Fatal(err)+ }+ for spec := 1; spec <= 8; spec++ {+ view, err := ParseAttributeViewData("20260921000000-layouts", data)+ if err != nil {+ t.Fatal(err)+ }+ source := &AutomationBlockSource{ReferenceID: "20261026000000-target1", IncludeSelectedDocuments: new(false), TagTarget: "container"}+ view.Automations = &AutomationConfig{Spec: spec, Rules: []*AutomationRule{{BlockSource: source}}}+ raw, _ := json.Marshal(view)+ read, err := ParseAttributeViewData(view.ID, raw)+ if (err == nil) != (spec == 8) {+ t.Fatalf("reference spec %d: %v", spec, err)+ }+ if spec == 8 && read.Automations.Rules[0].BlockSource.ReferenceID != source.ReferenceID {+ t.Fatal("reference target lost in storage round trip")+ }+ if view.Automations.Rules[0].RequiredSpec() != 8 {+ t.Fatal("other options masked the reference specification")+ }+ }+}diff --git a/kernel/av/collection_index_test.go b/kernel/av/collection_index_test.goindex 59a23e3a63..b242f1fdd0 100644--- a/kernel/av/collection_index_test.go+++ b/kernel/av/collection_index_test.go@@ -146,7 +146,7 @@ func TestBlockCollectionIndexScopesAndSnapshots(t *testing.T) {t.Fatal("disabling last rule did not update empty fast path")}view.Automations.Rules[0].Enabled = true- view.Automations.Spec = 8+ view.Automations.Spec = 9rememberCollectionView(view, "")unknown, err := BlockCollectionIndexInBox("")if err != nil || !unknown.MatchesDocument("unrelated", child, "/child.sy") {diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 8ca6a28e74..0448a55f4e 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -91,6 +91,9 @@ func collectionMatches(source *av.AutomationBlockSource, tree *parse.Tree) map[sfor _, attr := range source.Attributes {attributes = append(attributes, collectionAttributeMatcher(attr))}+ if source.ReferenceID != "" {+ return collectionReferenceMatches(source, tree, attributes)+ }var containers []*ast.Nodeast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {if !entering {@@ -245,6 +248,15 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rulereturn fmt.Errorf("invalid block collection document [%s]", id)}}+ if source.ReferenceID != "" {+ if !ast.IsNodeIDPattern(source.ReferenceID) {+ return fmt.Errorf("invalid block collection reference [%s]", source.ReferenceID)+ }+ if attributeViewBindingBlockTree(source.ReferenceID, boxID) == nil {+ return unavailableAutomationReference("automationCollectionReference", source.ReferenceID,+ fmt.Sprintf("unavailable block collection reference [%s]", source.ReferenceID))+ }+ }for _, typ := range source.Types {if !av.IsAutomationBlockType(typ) {return fmt.Errorf("invalid block collection type [%s]", typ)diff --git a/kernel/model/attribute_view_collection_reference.go b/kernel/model/attribute_view_collection_reference.gonew file mode 100644index 0000000000..ef4fc3a0bd--- /dev/null+++ b/kernel/model/attribute_view_collection_reference.go@@ -0,0 +1,114 @@+package model++import (+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 正文引用直接从事务快照提取,避免异步引用索引尚未更新时漏收或使用旧的块结构。+func collectionReferenceMatches(source *av.AutomationBlockSource, tree *parse.Tree,+ attributes []func(*ast.Node) bool) map[string]bool {+ matched := map[string]bool{}+ nodes := collectionNodes(tree)+ boxID := ""+ if IsEncryptedBox(tree.Box) {+ boxID = tree.Box+ }+ target := attributeViewBindingBlockTree(source.ReferenceID, boxID)+ if target == nil {+ return matched+ }+ refs := map[string]bool{}+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if node.Type == ast.NodeCustomBlock || node.Type == ast.NodeAttributeView {+ return ast.WalkSkipChildren+ }+ if !treenode.IsBlockRef(node) {+ return ast.WalkContinue+ }+ id, _, _ := treenode.GetBlockRef(node)+ matches := id == source.ReferenceID+ if !matches && target.Type == "d" {+ definition := attributeViewBindingBlockTree(id, boxID)+ matches = definition != nil && definition.RootID == source.ReferenceID+ }+ if block := treenode.ParentBlock(node); matches && block != nil && collectionTagsMatch(source, block) {+ refs[block.ID] = true+ }+ return ast.WalkContinue+ })+ luteEngine := util.NewLute()+ blocks := map[string]*Block{}+ blockFor := func(node *ast.Node) *Block {+ if block := blocks[node.ID]; block != nil {+ return block+ }+ block := &Block{ID: node.ID, RootID: tree.ID, Type: node.Type.String()}+ parent := treenode.HeadingParent(node)+ if parent == nil {+ parent = treenode.ParentBlock(node)+ }+ if parent != nil {+ block.ParentID = parent.ID+ }+ if node.Type == ast.NodeParagraph {+ block.Content = sql.NodeStaticContent(node, nil, true, false, true)+ block.Markdown = treenode.ExportNodeStdMd(node, luteEngine)+ } else if node.Type == ast.NodeListItem {+ block.FContent = sql.NodeStaticContent(treenode.FirstLeafBlock(node), nil, true, false, true)+ }+ blocks[node.ID] = block+ return block+ }+ var refBlocks, parents []*Block+ parentRefs := map[string][]*Block{}+ for id := range refs {+ node := nodes[id]+ if node == nil {+ continue+ }+ block := blockFor(node)+ refBlocks = append(refBlocks, block)+ if node.Type != ast.NodeParagraph {+ continue+ }+ if parent := nodes[block.ParentID]; parent != nil {+ if len(parentRefs[parent.ID]) == 0 {+ parents = append(parents, blockFor(parent))+ }+ parentRefs[parent.ID] = append(parentRefs[parent.ID], block)+ }+ }+ treeCache := map[string]*parse.Tree{tree.ID: tree}+ mappings := buildBacklinkParentMappingsForSources(refBlocks, parentRefs, parents, true,+ func(parent *Block, refs []*Block) *Block {+ return selectBacklinkParentRef(parent, refs, boxID, luteEngine, treeCache)+ }, func(parent *Block) map[string]bool {+ return backlinkHeadingCoveredIDs(parent, boxID, treeCache)+ })+ covered := map[string]bool{}+ add := func(id string) {+ if node := nodes[id]; node != nil && collectionBlockConditionsMatch(source, node, attributes) {+ matched[id] = true+ }+ }+ for _, mapping := range mappings {+ for id := range mapping.coveredRefIDs {+ covered[id] = true+ }+ add(mapping.parent.ID)+ }+ for id := range refs {+ if !covered[id] {+ add(id)+ }+ }+ return matched+}diff --git a/kernel/model/attribute_view_collection_reference_fts5_test.go b/kernel/model/attribute_view_collection_reference_fts5_test.gonew file mode 100644index 0000000000..611bfc5786--- /dev/null+++ b/kernel/model/attribute_view_collection_reference_fts5_test.go@@ -0,0 +1,214 @@+//go:build fts5++package model++import (+ "fmt"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func collectionTestReference(id string, pure bool) *ast.Node {+ paragraph := treenode.NewParagraph("")+ if !pure {+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Source ")})+ }+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: id,+ TextMarkBlockRefSubtype: "d", TextMarkTextContent: "Target"})+ return paragraph+}++func TestBlockCollectionReferenceTargetsAndSources(t *testing.T) {+ fixture, _, _ := setupBlockCollectionTest(t)+ target, err := LoadTreeByBlockID(fixture.targetID)+ if err != nil {+ t.Fatal(err)+ }+ var childID string+ for id, node := range collectionNodes(target) {+ if node.Type == ast.NodeParagraph {+ childID = id+ break+ }+ }+ if childID == "" {+ t.Fatal("target has no content block")+ }+ childDocument, err := CreateDocByMdSync(fixture.box.ID, strings.TrimSuffix(target.Path, ".sy")+"/"+ast.NewNodeID()+".sy", "Child document", "Content", nil, nil)+ if err != nil {+ t.Fatal(err)+ }+ root := &ast.Node{ID: fixture.sourceID, Type: ast.NodeDocument}+ direct, content, subdocument := collectionTestReference(target.ID, false), collectionTestReference(childID, false), collectionTestReference(childDocument.ID, false)+ root.AppendChild(direct)+ root.AppendChild(content)+ root.AppendChild(subdocument)+ // 同一来源中的重复引用仍只收集一次,静态锚文本与动态锚文本使用相同的目标 ID。+ direct.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: target.ID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Renamed"})+ embed := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockQueryEmbed}+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: []byte("select * from blocks where id='" + target.ID + "'")})+ root.AppendChild(embed)+ link := treenode.NewParagraph("")+ link.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: "siyuan://blocks/" + target.ID, TextMarkTextContent: "Link"})+ root.AppendChild(link)+ database := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeAttributeView, AttributeViewID: ast.NewNodeID()}+ root.AppendChild(database)+ tree := &parse.Tree{ID: root.ID, Root: root, Box: fixture.box.ID, Path: "/" + root.ID + ".sy"}+ source := &av.AutomationBlockSource{DocumentIDs: []string{root.ID}, ReferenceID: target.ID}+ matches := collectionMatches(source, tree)+ if len(matches) != 2 || !matches[direct.ID] || !matches[content.ID] {+ t.Fatalf("document references must include internal blocks only: %v", matches)+ }+ source.ReferenceID = childID+ if matches = collectionMatches(source, tree); len(matches) != 1 || !matches[content.ID] {+ t.Fatalf("a non-document target must match its own ID: %v", matches)+ }+ source.Tags = []string{"todo"}+ direct.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ if matches = collectionMatches(source, tree); len(matches) != 0 {+ t.Fatal("tag and reference matched across different sources")+ }+ content.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ if matches = collectionMatches(source, tree); len(matches) != 1 || !matches[content.ID] {+ t.Fatal("tag and reference did not match on the same source")+ }+ source.DocumentIDs = []string{target.ID}+ if len(collectionMatches(source, tree)) != 0 {+ t.Fatal("reference matching escaped the source scope")+ }+}++func TestBlockCollectionReferenceBacklinkGrouping(t *testing.T) {+ fixture, _, _ := setupBlockCollectionTest(t)+ for _, typ := range []ast.NodeType{ast.NodeDocument, ast.NodeHeading, ast.NodeListItem, ast.NodeBlockquote, ast.NodeSuperBlock, ast.NodeCallout} {+ t.Run(typ.String(), func(t *testing.T) {+ root := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeDocument}+ parent := &ast.Node{ID: ast.NewNodeID(), Type: typ, HeadingLevel: 1}+ first, second := collectionTestReference(fixture.targetID, true), collectionTestReference(fixture.targetID, false)+ switch typ {+ case ast.NodeDocument:+ parent = root+ root.AppendChild(first)+ root.AppendChild(second)+ case ast.NodeHeading:+ introduction := treenode.NewParagraph("")+ introduction.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Introduction")})+ root.AppendChild(introduction)+ root.AppendChild(parent)+ root.AppendChild(first)+ root.AppendChild(second)+ case ast.NodeListItem:+ list := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeList, ListData: &ast.ListData{Typ: 0}}+ parent.ListData = &ast.ListData{Typ: 0}+ root.AppendChild(list)+ list.AppendChild(parent)+ parent.AppendChild(first)+ parent.AppendChild(second)+ default:+ root.AppendChild(parent)+ other := treenode.NewParagraph("")+ other.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Other content")})+ parent.AppendChild(other)+ parent.AppendChild(first)+ parent.AppendChild(second)+ }+ tree := &parse.Tree{ID: root.ID, Root: root, Box: fixture.box.ID, Path: "/" + root.ID + ".sy"}+ source := &av.AutomationBlockSource{DocumentIDs: []string{root.ID}, ReferenceID: fixture.targetID, TagTarget: "block"}+ matches := collectionMatches(source, tree)+ if len(matches) != 1 || !matches[parent.ID] {+ t.Fatalf("backlink parent was not selected exclusively: %v", matches)+ }+ parent.SetIALAttr("custom-state", "ready")+ source.Attributes = []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "ready"}}+ if !collectionMatches(source, tree)[parent.ID] {+ t.Fatal("attributes did not constrain the final parent")+ }+ source.Types = []string{"p"}+ if len(collectionMatches(source, tree)) != 0 {+ t.Fatal("type filtering fell back from the backlink parent to a child")+ }+ source.Types, source.Attributes = nil, nil+ if typ == ast.NodeDocument || typ == ast.NodeHeading {+ first.PrependChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Text ")})+ matches = collectionMatches(source, tree)+ if len(matches) != 2 || !matches[first.ID] || !matches[second.ID] {+ t.Fatal("a mixed-text first paragraph propagated to its document or heading")+ }+ }+ })+ }+}++func TestBlockCollectionReferenceTransactionsAndReview(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ view.Automations.Spec = 8+ rule := view.Automations.Rules[0]+ rule.BlockSource = &av.AutomationBlockSource{DocumentIDs: []string{fixture.sourceID}, ReferenceID: fixture.targetID}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ dom := func(content string) string {+ return fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">%s</div></div>`, fixture.childID, content)+ }+ reference := fmt.Sprintf(`Source <span data-type="block-ref" data-id="%s" data-subtype="d">Target</span>`, fixture.targetID)+ tx := &Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom(reference)}},+ UndoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom("Source")}}}+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ row := view.GetBlockValueByBoundID(fixture.childID)+ if row == nil || view.GetValue(keyID, row.BlockID).Text.Content != "New" {+ t.Fatal("new reference did not bind the original block and initialize its fields")+ }+ for _, operations := range [][]*Operation{cloneOperations(tx.UndoOperations), cloneOperations(tx.DoOperations)} {+ if err := PerformTxSync(&Transaction{DoOperations: operations, isReplay: true}); err != nil {+ t.Fatal(err)+ }+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if view.GetBlockValueByBoundID(fixture.childID).BlockID != row.BlockID {+ t.Fatal("redo did not restore the original item ID")+ }+ view.GetValue(keyID, row.BlockID).Text.Content = "Edited"+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom("Removed")}}}); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if view.GetBlockValue(row.BlockID) == nil || view.GetValue(keyID, row.BlockID).Text.Content != "Edited" {+ t.Fatal("removing the reference discarded the item or fields")+ }+ review, err := ReviewAttributeViewCollection(view.ID, 1, "")+ if err != nil || review.Unmatched != 1 {+ t.Fatalf("review did not detect the removed reference: %+v %v", review, err)+ }+ if err := PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom(reference)}}}); err != nil {+ t.Fatal(err)+ }+ preview, err := PreviewAttributeViewCollection(view.ID, rule.ID, 1)+ if err != nil || len(preview.Blocks) != 1 || preview.Blocks[0].ID != fixture.childID || !preview.Blocks[0].Collected {+ t.Fatalf("preview disagreed with real-time collection: %+v %v", preview, err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != 1 || view.GetValue(keyID, row.BlockID).Text.Content != "Edited" {+ t.Fatal("matching again duplicated the item or reset edited fields")+ }+ // 删除引用目标后,来源仍可编辑,失效规则停用并保留已收集的数据。+ treenode.RemoveBlockTreesByRootID(fixture.box.ID, fixture.targetID)+ if err := PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom("Still editable")}}}); err != nil {+ t.Fatal("missing target blocked source editing", err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if view.Automations.Rules[0].Enabled || view.GetValue(keyID, row.BlockID).Text.Content != "Edited" {+ t.Fatal("missing target did not pause safely while preserving fields")+ }+}diff --git a/kernel/model/attribute_view_collection_sqlcipher_test.go b/kernel/model/attribute_view_collection_sqlcipher_test.goindex b090ba14a0..4980aa6d56 100644--- a/kernel/model/attribute_view_collection_sqlcipher_test.go+++ b/kernel/model/attribute_view_collection_sqlcipher_test.go@@ -34,6 +34,7 @@ func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {t.Run(mode, func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, "", nil, mode, false) })}t.Run("exclude selected document", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, "", new(1), "", true) })+ t.Run("reference", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, "reference", nil, "", false) })}func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string, depth *int, nameOperator string, excludeSelf bool) {@@ -87,6 +88,13 @@ func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string,view.Automations.Rules[0].BlockSource.TagTarget = targetparagraph := treenode.NewParagraph("")paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ if target == "reference" {+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: tree.ID,+ TextMarkBlockRefSubtype: "d", TextMarkTextContent: "Target"})+ view.Automations.Spec = 8+ view.Automations.Rules[0].BlockSource.ReferenceID = tree.ID+ view.Automations.Rules[0].BlockSource.TagTarget = ""+ }if target == "container" {quote := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockquote}quote.SetIALAttr("id", quote.ID)@@ -132,6 +140,14 @@ func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string,view.Automations.Spec = 7view.Automations.Rules[0].BlockSource.IncludeSelectedDocuments = new(false)}+ if target == "reference" {+ source := view.Automations.Rules[0].BlockSource+ source.ReferenceID = fixture.targetID+ if err := (&Transaction{}).validateBlockCollectionRule(view, view.Automations.Rules[0], boxID); err == nil {+ t.Fatal("encrypted collection accepted a target from the normal index")+ }+ source.ReferenceID = tree.ID+ }if err = av.SaveAttributeView(view); err != nil {t.Fatal(err)}diff --git a/kernel/model/backlink_parent.go b/kernel/model/backlink_parent.goindex edd3d76624..79d0cde0ba 100644--- a/kernel/model/backlink_parent.go+++ b/kernel/model/backlink_parent.go@@ -55,13 +55,25 @@ func buildBacklinkParentMappingsWithDocumentGrouping(refBlocks []*Block, boxID sluteEngine := util.NewLute()treeCache := map[string]*parse.Tree{}+ return buildBacklinkParentMappingsForSources(refBlocks, parentRefParagraphs, paragraphParents, groupDocuments,+ func(parent *Block, refs []*Block) *Block {+ return selectBacklinkParentRef(parent, refs, boxID, luteEngine, treeCache)+ }, func(parent *Block) map[string]bool {+ return backlinkHeadingCoveredIDs(parent, boxID, treeCache)+ })+}++// 查询反链与事务内收集共享归并过程,调用方提供同一快照中的父块和标题覆盖范围。+func buildBacklinkParentMappingsForSources(refBlocks []*Block, parentRefParagraphs map[string][]*Block,+ paragraphParents []*Block, groupDocuments bool, selectRef func(*Block, []*Block) *Block,+ headingCoveredIDsFor func(*Block) map[string]bool) (ret []*backlinkParentMapping) {var mappings []*backlinkParentMappingfor _, parent := range paragraphParents {if nil == parent || !groupDocuments && "NodeDocument" == parent.Type {continue}- refBlock := selectBacklinkParentRef(parent, parentRefParagraphs[parent.ID], boxID, luteEngine, treeCache)+ refBlock := selectRef(parent, parentRefParagraphs[parent.ID])if nil == refBlock {continue}@@ -93,7 +105,7 @@ func buildBacklinkParentMappingsWithDocumentGrouping(refBlocks []*Block, boxID scontinue}- mapping.coveredIDs = backlinkHeadingCoveredIDs(mapping.parent, boxID, treeCache)+ mapping.coveredIDs = headingCoveredIDsFor(mapping.parent)for _, refBlock := range refBlocks {if nil != refBlock && mapping.coveredIDs[refBlock.ID] {mapping.coveredRefIDs[refBlock.ID] = true