Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support contextual filters for database blocks https://github.com/siyuan-note/siyuan/issues/19121

Danielc1d7c9b7aa25
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index aeaae20d48..72f2ac6e13 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "مرشح السياق",
+ "contextFilterTip": "يُطبّق على جميع طرق العرض في كتلة قاعدة البيانات هذه",
+ "contextFilterNoRelation": "أنشئ حقل علاقة وقم بتكوينه قبل تمكين مرشح السياق",
+ "filterCurrentDocument": "المستند الحالي",
+ "filterCurrentDocumentTip": "يُحل إلى عنصر قاعدة البيانات المرتبط بالمستند الذي يحتوي على كتلة قاعدة البيانات هذه",
+ "templateDatabaseMode": "قواعد البيانات في القالب",
+ "templateDatabaseCopyTip": "ينشئ قواعد بيانات مستقلة لا تبقى متزامنة مع المصدر",
+ "templateDatabaseReferenceTip": "يحتفظ بمراجع قواعد البيانات الحالية ويشارك بياناتها وإعدادات العرض",
"entryTopBar": "الشريط العلوي",
"entryTopBarDrag": "منطقة سحب النافذة",
"bazaarFrontendDesktop": "نافذة سطح المكتب الرئيسية",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 3e4b5d484f..2ef699210e 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Kontextfilter",
+ "contextFilterTip": "Gilt für alle Ansichten in diesem Datenbankblock",
+ "contextFilterNoRelation": "Erstelle und konfiguriere ein Beziehungsfeld, bevor du den Kontextfilter aktivierst",
+ "filterCurrentDocument": "Aktuelles Dokument",
+ "filterCurrentDocumentTip": "Wird als der Datenbankeintrag aufgelöst, der mit dem Dokument dieses Datenbankblocks verknüpft ist",
+ "templateDatabaseMode": "Datenbanken in der Vorlage",
+ "templateDatabaseCopyTip": "Erstellt unabhängige Datenbanken, die nicht mehr mit der Quelle synchronisiert werden",
+ "templateDatabaseReferenceTip": "Behält Verweise auf vorhandene Datenbanken bei und teilt deren Daten und Ansichtseinstellungen",
"entryTopBar": "Obere Leiste",
"entryTopBarDrag": "Ziehbereich des Fensters",
"bazaarFrontendDesktop": "Desktop-Hauptfenster",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index f7e3879236..08b9bff0c8 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Context filter",
+ "contextFilterTip": "Applies to every view in this database block",
+ "contextFilterNoRelation": "Create and configure a relation field before enabling the context filter",
+ "filterCurrentDocument": "Current document",
+ "filterCurrentDocumentTip": "Resolves to the database item bound to the document containing this database block",
+ "templateDatabaseMode": "Databases in the template",
+ "templateDatabaseCopyTip": "Creates independent databases that no longer stay synchronized with the source",
+ "templateDatabaseReferenceTip": "Keeps references to existing databases and shares their data and view settings",
"entryTopBar": "Top bar",
"entryTopBarDrag": "Window drag area",
"bazaarFrontendDesktop": "Desktop main window",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 0bdb8ccd22..9b9868e047 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filtro contextual",
+ "contextFilterTip": "Se aplica a todas las vistas de este bloque de base de datos",
+ "contextFilterNoRelation": "Crea y configura un campo de relación antes de activar el filtro contextual",
+ "filterCurrentDocument": "Documento actual",
+ "filterCurrentDocumentTip": "Se resuelve como el elemento de base de datos vinculado al documento que contiene este bloque de base de datos",
+ "templateDatabaseMode": "Bases de datos de la plantilla",
+ "templateDatabaseCopyTip": "Crea bases de datos independientes que dejan de sincronizarse con el origen",
+ "templateDatabaseReferenceTip": "Conserva las referencias a las bases de datos existentes y comparte sus datos y ajustes de vista",
"entryTopBar": "Barra superior",
"entryTopBarDrag": "Área de arrastre de la ventana",
"bazaarFrontendDesktop": "Ventana principal de escritorio",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index c0d8d0de54..2d99ae399f 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filtre contextuel",
+ "contextFilterTip": "S’applique à toutes les vues de ce bloc de base de données",
+ "contextFilterNoRelation": "Créez et configurez un champ de relation avant d’activer le filtre contextuel",
+ "filterCurrentDocument": "Document actuel",
+ "filterCurrentDocumentTip": "Correspond à l’élément de base de données lié au document contenant ce bloc de base de données",
+ "templateDatabaseMode": "Bases de données du modèle",
+ "templateDatabaseCopyTip": "Crée des bases de données indépendantes qui ne restent plus synchronisées avec la source",
+ "templateDatabaseReferenceTip": "Conserve les références aux bases de données existantes et partage leurs données et paramètres de vue",
"entryTopBar": "Barre supérieure",
"entryTopBarDrag": "Zone de déplacement de la fenêtre",
"bazaarFrontendDesktop": "Fenêtre principale de bureau",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index c27de8eb78..0a7e1220de 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "מסנן הקשר",
+ "contextFilterTip": "חל על כל התצוגות בבלוק מסד הנתונים הזה",
+ "contextFilterNoRelation": "יש ליצור ולהגדיר שדה קשר לפני הפעלת מסנן ההקשר",
+ "filterCurrentDocument": "המסמך הנוכחי",
+ "filterCurrentDocumentTip": "מזוהה כפריט מסד הנתונים המקושר למסמך שמכיל את בלוק מסד הנתונים הזה",
+ "templateDatabaseMode": "מסדי נתונים בתבנית",
+ "templateDatabaseCopyTip": "יוצר מסדי נתונים עצמאיים שאינם נשארים מסונכרנים עם המקור",
+ "templateDatabaseReferenceTip": "שומר הפניות למסדי נתונים קיימים ומשתף את הנתונים והגדרות התצוגה שלהם",
"entryTopBar": "סרגל עליון",
"entryTopBarDrag": "אזור גרירת החלון",
"bazaarFrontendDesktop": "חלון שולחן עבודה ראשי",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 75a288e9d0..3f9c8d2aac 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "संदर्भ फ़िल्टर",
+ "contextFilterTip": "इस डेटाबेस ब्लॉक के हर दृश्य पर लागू होता है",
+ "contextFilterNoRelation": "संदर्भ फ़िल्टर चालू करने से पहले संबंध फ़ील्ड बनाएँ और कॉन्फ़िगर करें",
+ "filterCurrentDocument": "वर्तमान दस्तावेज़",
+ "filterCurrentDocumentTip": "इस डेटाबेस ब्लॉक वाले दस्तावेज़ से बंधी डेटाबेस प्रविष्टि के रूप में हल होता है",
+ "templateDatabaseMode": "टेम्पलेट में डेटाबेस",
+ "templateDatabaseCopyTip": "स्वतंत्र डेटाबेस बनाता है जो स्रोत के साथ सिंक नहीं रहते",
+ "templateDatabaseReferenceTip": "मौजूदा डेटाबेस के संदर्भ बनाए रखता है और उनका डेटा व दृश्य सेटिंग साझा करता है",
"entryTopBar": "शीर्ष पट्टी",
"entryTopBarDrag": "विंडो खींचने का क्षेत्र",
"bazaarFrontendDesktop": "डेस्कटॉप मुख्य विंडो",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 3f8335fbd6..78ae1f3561 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filter konteks",
+ "contextFilterTip": "Berlaku untuk setiap tampilan dalam blok basis data ini",
+ "contextFilterNoRelation": "Buat dan konfigurasikan bidang relasi sebelum mengaktifkan filter konteks",
+ "filterCurrentDocument": "Dokumen saat ini",
+ "filterCurrentDocumentTip": "Diuraikan menjadi item basis data yang terikat ke dokumen tempat blok basis data ini berada",
+ "templateDatabaseMode": "Basis data dalam templat",
+ "templateDatabaseCopyTip": "Membuat basis data mandiri yang tidak lagi disinkronkan dengan sumber",
+ "templateDatabaseReferenceTip": "Mempertahankan referensi ke basis data yang ada serta berbagi data dan pengaturan tampilannya",
"entryTopBar": "Bilah atas",
"entryTopBarDrag": "Area seret jendela",
"bazaarFrontendDesktop": "Jendela utama desktop",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index d1738a3327..f0794c79a8 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filtro contestuale",
+ "contextFilterTip": "Si applica a tutte le viste di questo blocco database",
+ "contextFilterNoRelation": "Crea e configura un campo relazione prima di attivare il filtro contestuale",
+ "filterCurrentDocument": "Documento corrente",
+ "filterCurrentDocumentTip": "Viene risolto come l’elemento del database associato al documento che contiene questo blocco database",
+ "templateDatabaseMode": "Database nel modello",
+ "templateDatabaseCopyTip": "Crea database indipendenti che non restano sincronizzati con l’origine",
+ "templateDatabaseReferenceTip": "Mantiene i riferimenti ai database esistenti e ne condivide dati e impostazioni di visualizzazione",
"entryTopBar": "Barra superiore",
"entryTopBarDrag": "Area di trascinamento della finestra",
"bazaarFrontendDesktop": "Finestra principale desktop",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index a0ae87f515..3035527e81 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "コンテキストフィルター",
+ "contextFilterTip": "このデータベースブロックのすべてのビューに適用します",
+ "contextFilterNoRelation": "コンテキストフィルターを有効にする前に関連フィールドを作成して設定してください",
+ "filterCurrentDocument": "現在の文書",
+ "filterCurrentDocumentTip": "このデータベースブロックが存在する文書に紐付けられたデータベース項目として解決します",
+ "templateDatabaseMode": "テンプレート内のデータベース",
+ "templateDatabaseCopyTip": "独立したデータベースを作成し、元のデータベースとは同期しません",
+ "templateDatabaseReferenceTip": "既存のデータベースへの参照を保持し、データとビュー設定を共有します",
"entryTopBar": "トップバー",
"entryTopBarDrag": "ウィンドウのドラッグ領域",
"bazaarFrontendDesktop": "デスクトップメインウィンドウ",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 1be1d65f5f..0172466abf 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "컨텍스트 필터",
+ "contextFilterTip": "이 데이터베이스 블록의 모든 보기에 적용됩니다",
+ "contextFilterNoRelation": "컨텍스트 필터를 사용하기 전에 관계 필드를 만들고 구성하세요",
+ "filterCurrentDocument": "현재 문서",
+ "filterCurrentDocumentTip": "이 데이터베이스 블록이 있는 문서에 연결된 데이터베이스 항목으로 확인됩니다",
+ "templateDatabaseMode": "템플릿의 데이터베이스",
+ "templateDatabaseCopyTip": "원본과 더 이상 동기화되지 않는 독립 데이터베이스를 만듭니다",
+ "templateDatabaseReferenceTip": "기존 데이터베이스 참조를 유지하고 데이터와 보기 설정을 공유합니다",
"entryTopBar": "상단 표시줄",
"entryTopBarDrag": "창 끌기 영역",
"bazaarFrontendDesktop": "데스크톱 기본 창",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index d3b383a3b4..28a638bf62 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Contextfilter",
+ "contextFilterTip": "Is van toepassing op alle weergaven in dit databaseblok",
+ "contextFilterNoRelation": "Maak en configureer een relatieveld voordat je het contextfilter inschakelt",
+ "filterCurrentDocument": "Huidig document",
+ "filterCurrentDocumentTip": "Wordt omgezet naar het database-item dat is gekoppeld aan het document met dit databaseblok",
+ "templateDatabaseMode": "Databases in de sjabloon",
+ "templateDatabaseCopyTip": "Maakt onafhankelijke databases die niet langer met de bron worden gesynchroniseerd",
+ "templateDatabaseReferenceTip": "Behoudt verwijzingen naar bestaande databases en deelt hun gegevens en weergave-instellingen",
"entryTopBar": "Bovenbalk",
"entryTopBarDrag": "Sleepgebied voor venster",
"bazaarFrontendDesktop": "Hoofdvenster van desktop-app",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 17d21d3436..51866a8af7 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filtr kontekstowy",
+ "contextFilterTip": "Dotyczy wszystkich widoków w tym bloku bazy danych",
+ "contextFilterNoRelation": "Przed włączeniem filtra kontekstowego utwórz i skonfiguruj pole relacji",
+ "filterCurrentDocument": "Bieżący dokument",
+ "filterCurrentDocumentTip": "Jest rozpoznawany jako element bazy danych powiązany z dokumentem zawierającym ten blok bazy danych",
+ "templateDatabaseMode": "Bazy danych w szablonie",
+ "templateDatabaseCopyTip": "Tworzy niezależne bazy danych, które nie są już synchronizowane ze źródłem",
+ "templateDatabaseReferenceTip": "Zachowuje odwołania do istniejących baz danych oraz współdzieli ich dane i ustawienia widoku",
"entryTopBar": "Górny pasek",
"entryTopBarDrag": "Obszar przeciągania okna",
"bazaarFrontendDesktop": "Główne okno aplikacji komputerowej",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 8b41f29f9f..58540cf08d 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Filtro contextual",
+ "contextFilterTip": "Aplica-se a todas as visualizações deste bloco de banco de dados",
+ "contextFilterNoRelation": "Crie e configure um campo de relação antes de ativar o filtro contextual",
+ "filterCurrentDocument": "Documento atual",
+ "filterCurrentDocumentTip": "É resolvido como o item do banco de dados vinculado ao documento que contém este bloco de banco de dados",
+ "templateDatabaseMode": "Bancos de dados no modelo",
+ "templateDatabaseCopyTip": "Cria bancos de dados independentes que deixam de ser sincronizados com a origem",
+ "templateDatabaseReferenceTip": "Mantém referências aos bancos de dados existentes e compartilha seus dados e configurações de visualização",
"entryTopBar": "Barra superior",
"entryTopBarDrag": "Área de arrasto da janela",
"bazaarFrontendDesktop": "Janela principal do desktop",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index d8b4f8d6b0..b1938ce99b 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Контекстный фильтр",
+ "contextFilterTip": "Применяется ко всем представлениям в этом блоке базы данных",
+ "contextFilterNoRelation": "Перед включением контекстного фильтра создайте и настройте поле связи",
+ "filterCurrentDocument": "Текущий документ",
+ "filterCurrentDocumentTip": "Определяется как элемент базы данных, связанный с документом, содержащим этот блок базы данных",
+ "templateDatabaseMode": "Базы данных в шаблоне",
+ "templateDatabaseCopyTip": "Создаёт независимые базы данных, которые больше не синхронизируются с источником",
+ "templateDatabaseReferenceTip": "Сохраняет ссылки на существующие базы данных и использует общие данные и настройки представления",
"entryTopBar": "Верхняя панель",
"entryTopBarDrag": "Область перетаскивания окна",
"bazaarFrontendDesktop": "Главное окно приложения",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 08c011bd23..d0620d0c77 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Kontextový filter",
+ "contextFilterTip": "Použije sa na všetky zobrazenia v tomto databázovom bloku",
+ "contextFilterNoRelation": "Pred zapnutím kontextového filtra vytvorte a nastavte pole vzťahu",
+ "filterCurrentDocument": "Aktuálny dokument",
+ "filterCurrentDocumentTip": "Vyhodnotí sa ako položka databázy prepojená s dokumentom, ktorý obsahuje tento databázový blok",
+ "templateDatabaseMode": "Databázy v šablóne",
+ "templateDatabaseCopyTip": "Vytvorí nezávislé databázy, ktoré už nie sú synchronizované so zdrojom",
+ "templateDatabaseReferenceTip": "Zachová odkazy na existujúce databázy a zdieľa ich údaje a nastavenia zobrazenia",
"entryTopBar": "Horný panel",
"entryTopBarDrag": "Oblasť na presúvanie okna",
"bazaarFrontendDesktop": "Hlavné okno počítačovej aplikácie",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 6450a13726..c31b263a06 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "ตัวกรองบริบท",
+ "contextFilterTip": "ใช้กับทุกมุมมองในบล็อกฐานข้อมูลนี้",
+ "contextFilterNoRelation": "สร้างและกำหนดค่าฟิลด์ความสัมพันธ์ก่อนเปิดใช้ตัวกรองบริบท",
+ "filterCurrentDocument": "เอกสารปัจจุบัน",
+ "filterCurrentDocumentTip": "แปลงเป็นรายการฐานข้อมูลที่ผูกกับเอกสารซึ่งมีบล็อกฐานข้อมูลนี้อยู่",
+ "templateDatabaseMode": "ฐานข้อมูลในเทมเพลต",
+ "templateDatabaseCopyTip": "สร้างฐานข้อมูลอิสระที่ไม่ซิงค์กับต้นฉบับอีกต่อไป",
+ "templateDatabaseReferenceTip": "คงการอ้างอิงไปยังฐานข้อมูลที่มีอยู่และใช้ข้อมูลกับการตั้งค่ามุมมองร่วมกัน",
"entryTopBar": "แถบด้านบน",
"entryTopBarDrag": "พื้นที่ลากหน้าต่าง",
"bazaarFrontendDesktop": "หน้าต่างหลักเดสก์ท็อป",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 046ad7864a..b3e1f4cfa2 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Bağlam filtresi",
+ "contextFilterTip": "Bu veritabanı bloğundaki tüm görünümlere uygulanır",
+ "contextFilterNoRelation": "Bağlam filtresini etkinleştirmeden önce bir ilişki alanı oluşturup yapılandırın",
+ "filterCurrentDocument": "Geçerli belge",
+ "filterCurrentDocumentTip": "Bu veritabanı bloğunu içeren belgeye bağlı veritabanı öğesi olarak çözümlenir",
+ "templateDatabaseMode": "Şablondaki veritabanları",
+ "templateDatabaseCopyTip": "Kaynakla artık eşitlenmeyen bağımsız veritabanları oluşturur",
+ "templateDatabaseReferenceTip": "Mevcut veritabanlarına başvuruları korur ve verileriyle görünüm ayarlarını paylaşır",
"entryTopBar": "Üst çubuk",
"entryTopBarDrag": "Pencere sürükleme alanı",
"bazaarFrontendDesktop": "Masaüstü ana penceresi",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index d535760ae3..e5f838506a 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "Контекстний фільтр",
+ "contextFilterTip": "Застосовується до всіх подань у цьому блоці бази даних",
+ "contextFilterNoRelation": "Перед увімкненням контекстного фільтра створіть і налаштуйте поле зв’язку",
+ "filterCurrentDocument": "Поточний документ",
+ "filterCurrentDocumentTip": "Визначається як елемент бази даних, пов’язаний із документом, що містить цей блок бази даних",
+ "templateDatabaseMode": "Бази даних у шаблоні",
+ "templateDatabaseCopyTip": "Створює незалежні бази даних, які більше не синхронізуються з джерелом",
+ "templateDatabaseReferenceTip": "Зберігає посилання на наявні бази даних і спільно використовує їхні дані та налаштування подання",
"entryTopBar": "Верхня панель",
"entryTopBarDrag": "Область перетягування вікна",
"bazaarFrontendDesktop": "Головне вікно програми",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index bc2f229582..6e24186b30 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "上下文筛选",
+ "contextFilterTip": "应用于当前数据库块的所有视图",
+ "contextFilterNoRelation": "请先创建并配置关联字段,再启用上下文筛选",
+ "filterCurrentDocument": "当前文档",
+ "filterCurrentDocumentTip": "解析为绑定了当前数据库块所在文档的数据库条目",
+ "templateDatabaseMode": "模板中的数据库",
+ "templateDatabaseCopyTip": "创建独立数据库,不再与源数据库同步",
+ "templateDatabaseReferenceTip": "保留对现有数据库的引用,共享数据和视图配置",
"entryTopBar": "顶栏",
"entryTopBarDrag": "窗口拖拽区域",
"bazaarFrontendDesktop": "桌面主窗口",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 34bfbe85ff..498148a986 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,12 @@
{
+ "contextFilter": "情境篩選",
+ "contextFilterTip": "套用於此資料庫區塊的所有檢視",
+ "contextFilterNoRelation": "啟用情境篩選前,請先建立並設定關聯欄位",
+ "filterCurrentDocument": "目前文件",
+ "filterCurrentDocumentTip": "解析為綁定目前資料庫區塊所在文件的資料庫項目",
+ "templateDatabaseMode": "範本中的資料庫",
+ "templateDatabaseCopyTip": "建立獨立資料庫,不再與來源資料庫同步",
+ "templateDatabaseReferenceTip": "保留現有資料庫的引用,共用資料與檢視設定",
"entryTopBar": "頂欄",
"entryTopBarDrag": "視窗拖曳區域",
"bazaarFrontendDesktop": "桌面主視窗",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy
index cd707cc43b..e97a3e04c6 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy
@@ -6,7 +6,7 @@
"id": "20201204184532-3qm9l8n",
"title": "Template snippet",
"type": "doc",
- "updated": "20260830143000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1705,6 +1705,35 @@
}
]
},
+ {
+ "ID": "20260904022100-kqbyhrl",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260904022100-kqbyhrl",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Databases in saved templates"
+ }
+ ]
+ },
+ {
+ "ID": "20260904022100-vq38you",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-vq38you",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "When saving a document as a template, “Databases in the template” applies one mode to every database block in that document. “Create complete copy” is the default: each use creates independent databases that no longer synchronize with the sources, and block-level Context filters are removed. “Create mirror copy” preserves the existing database references and Context filters: inserted database blocks share data and view settings with the source databases. Reference mode requires the target document to be able to access the source databases within the same encryption boundary; otherwise template insertion fails. Combining a referenced shared task database with the database block’s Context filter set to the Project relation field (“Contains any item - Current document”) lets one reusable project template show only the tasks related to each project document."
+ }
+ ]
+ },
{
"ID": "20260830143000-tplen01",
"Type": "NodeHeading",
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.sy
index 4d043c278b..cf89b88d04 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": "20260902120000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -45,7 +45,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20251224101749-zybcbjk",
- "updated": "20260613162855"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -984,7 +984,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613171129-edm1pru",
- "updated": "20260613171129"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1013,7 +1013,7 @@
"HeadingLevel": 4,
"Properties": {
"id": "20260613171129-5zjv62o",
- "updated": "20260613171129"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1042,7 +1042,7 @@
"ListData": {},
"Properties": {
"id": "20260613171129-438l9c3",
- "updated": "20260613171129"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1318,6 +1318,39 @@
}
]
},
+ {
+ "ID": "20260904022100-t3p2t45",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260904022100-t3p2t45",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "ID": "20260904022100-h1drat7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-h1drat7",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "strong",
+ "TextMarkTextContent": "Context filter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ": Use the database block’s “Context filter” to select a configured Relation field. It applies “Contains any item - Current document” to every view in this database block, resolving the containing document to its item in the related database. Ordinary view filters remain view-specific and are combined with the context filter using AND. Change the selected field or disable the context filter from the same panel"
+ }
+ ]
+ }
+ ]
+ },
{
"ID": "20260613171129-4a6yi6q",
"Type": "NodeListItem",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy
index a1d299356b..e633c2b4c5 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy
@@ -6,7 +6,7 @@
"id": "20201204181006-7bkppue",
"title": "模板片段",
"type": "doc",
- "updated": "20260830143000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1717,6 +1717,35 @@
}
]
},
+ {
+ "ID": "20260904022100-7ay9g5b",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260904022100-7ay9g5b",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "保存模板中的数据库"
+ }
+ ]
+ },
+ {
+ "ID": "20260904022100-t5w801p",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-t5w801p",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "将文档保存为模板时,“模板中的数据库”会对文档内所有数据库块统一应用一种模式。“创建完整副本”为默认选项:每次使用模板都会创建独立数据库,之后不再与源数据库同步,并会移除块级上下文筛选。“创建镜像副本”会保留现有数据库引用和上下文筛选:插入的数据库块与源数据库共享数据和视图配置。引用模式要求目标文档能在同一加密边界内访问源数据库,否则模板插入会失败。将引用的共享任务数据库与数据库块“上下文筛选”中的“项目”关联字段组合使用(包含任一 - 当前文档),可让同一个项目模板在每个项目文档中只显示关联到该项目的任务。"
+ }
+ ]
+ },
{
"ID": "20260830143000-tplcn01",
"Type": "NodeHeading",
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.sy
index 2bad286bd8..83a655e324 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": "20260902120000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -45,7 +45,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20240208115136-9g2b46l",
- "updated": "20260613162748"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -984,7 +984,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613170258-y3mj135",
- "updated": "20260613170258"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1013,7 +1013,7 @@
"HeadingLevel": 4,
"Properties": {
"id": "20260613170258-kfaoevw",
- "updated": "20260613170258"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1042,7 +1042,7 @@
"ListData": {},
"Properties": {
"id": "20260613170258-stvvay1",
- "updated": "20260613170258"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1318,6 +1318,39 @@
}
]
},
+ {
+ "ID": "20260904022100-u8yv871",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260904022100-u8yv871",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "ID": "20260904022100-k06aj5m",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-k06aj5m",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "strong",
+ "TextMarkTextContent": "上下文筛选"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ":在数据库块工具栏的“上下文筛选”中选择已配置的关联字段。系统会对该数据库块的所有视图应用“包含任一 - 当前文档”,把数据库块所在文档解析为目标数据库中的对应条目。普通视图筛选仍只属于各自视图,并与上下文筛选通过“且”组合。可在同一面板中更换字段或禁用上下文筛选"
+ }
+ ]
+ }
+ ]
+ },
{
"ID": "20260613170258-uwddfvi",
"Type": "NodeListItem",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy
index 36c4bce94a..57e293be17 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy
@@ -6,7 +6,7 @@
"id": "20211226123004-dplpw0o",
"title": "範本片段",
"type": "doc",
- "updated": "20260830143000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1694,6 +1694,35 @@
}
]
},
+ {
+ "ID": "20260904022100-yzmze6l",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260904022100-yzmze6l",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "儲存範本中的資料庫"
+ }
+ ]
+ },
+ {
+ "ID": "20260904022100-hk0s7f1",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-hk0s7f1",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "將文檔儲存為範本時,「範本中的資料庫」會對文檔內所有資料庫區塊統一套用一種模式。「建立完整副本」為預設選項:每次使用範本都會建立獨立資料庫,之後不再與來源資料庫同步,並會移除區塊級情境篩選。「建立鏡像副本」會保留現有資料庫引用與情境篩選:插入的資料庫區塊與來源資料庫共用資料和檢視設定。引用模式要求目標文檔能在同一加密邊界內存取來源資料庫,否則範本插入會失敗。將引用的共用任務資料庫與資料庫區塊「情境篩選」中的「專案」關聯欄位搭配使用(包含任一項 - 目前文件),可讓同一個專案範本在每個專案文件中只顯示關聯至該專案的任務。"
+ }
+ ]
+ },
{
"ID": "20260830143000-tpltw01",
"Type": "NodeHeading",
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.sy
index 540f696dce..42c145a6ee 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": "20260902120000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -45,7 +45,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20251224101729-yhz5zrt",
- "updated": "20260613164228"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -984,7 +984,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613171246-whfdkq8",
- "updated": "20260613171246"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1013,7 +1013,7 @@
"HeadingLevel": 4,
"Properties": {
"id": "20260613171246-qovn46w",
- "updated": "20260613171246"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1042,7 +1042,7 @@
"ListData": {},
"Properties": {
"id": "20260613171246-frygk48",
- "updated": "20260613171246"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1318,6 +1318,39 @@
}
]
},
+ {
+ "ID": "20260904022100-5x68nm2",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260904022100-5x68nm2",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "ID": "20260904022100-ivb080o",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-ivb080o",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "strong",
+ "TextMarkTextContent": "情境篩選"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ":在資料庫區塊工具列的「情境篩選」中選擇已設定的關聯欄位。系統會對此資料庫區塊的所有檢視套用「包含任一項 - 目前文件」,將資料庫區塊所在文件解析為目標資料庫中的對應項目。一般檢視篩選仍只屬於各自檢視,並與情境篩選以且組合。可在同一面板中更換欄位或停用情境篩選"
+ }
+ ]
+ }
+ ]
+ },
{
"ID": "20260613171246-7d13uv1",
"Type": "NodeListItem",
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.sy
index f3e2b1c766..f446663bc4 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": "20260902120000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -46,7 +46,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20251224101829-lva3op2",
- "updated": "20260613164213"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -985,7 +985,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613171234-4oam4x1",
- "updated": "20260613171234"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1014,7 +1014,7 @@
"HeadingLevel": 4,
"Properties": {
"id": "20260613171234-x40bu7m",
- "updated": "20260613171234"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1043,7 +1043,7 @@
"ListData": {},
"Properties": {
"id": "20260613171234-lbxo0ro",
- "updated": "20260613171234"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1319,6 +1319,39 @@
}
]
},
+ {
+ "ID": "20260904022100-hzqmv7b",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260904022100-hzqmv7b",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "ID": "20260904022100-mif3i0m",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-mif3i0m",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "strong",
+ "TextMarkTextContent": "コンテキストフィルター"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ":「コンテキストフィルター」で設定済みのリレーションフィールドを選択します。「いずれかを含む - 現在の文書」がこのデータベースブロックのすべてのビューに適用され、ブロックを含む文書を関連先データベース内の対応する項目として解決します。通常のビューフィルターは各ビュー専用のままで、コンテキストフィルターとは AND で組み合わせます。同じパネルでフィールドの変更やコンテキストフィルターの無効化ができます"
+ }
+ ]
+ }
+ ]
+ },
{
"ID": "20260613171234-y9o6lwt",
"Type": "NodeListItem",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy
index 750863c353..7fc665db2c 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-6x9ivi7",
"title": "テンプレートスニペット",
"type": "doc",
- "updated": "20260809232000"
+ "updated": "20260904091600"
},
"Children": [
{
@@ -1714,6 +1714,35 @@
}
]
},
+ {
+ "ID": "20260904022100-cvnck64",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260904022100-cvnck64",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "保存したテンプレート内のデータベース"
+ }
+ ]
+ },
+ {
+ "ID": "20260904022100-n8kvyo2",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260904022100-n8kvyo2",
+ "updated": "20260904091600"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ドキュメントをテンプレートとして保存するとき、「テンプレート内のデータベース」で、そのドキュメントにあるすべてのデータベースブロックへ同じモードを適用します。「完全なコピーを作成」がデフォルトです。テンプレートを使用するたびに独立したデータベースが作成され、元のデータベースとは同期せず、ブロック単位のコンテキストフィルターは削除されます。「ミラーのコピーを作成」は既存のデータベース参照とコンテキストフィルターを保持し、挿入されたデータベースブロックは元のデータベースとデータおよびビュー設定を共有します。参照モードでは、対象ドキュメントが同じ暗号化境界内で元のデータベースにアクセスできる必要があります。アクセスできない場合、テンプレートの挿入は失敗します。参照した共有タスクデータベースと、データベースブロックの「コンテキストフィルター」で「プロジェクト」関連フィールドを組み合わせると(いずれかを含む - 現在の文書)、同じプロジェクトテンプレートを使いながら、各プロジェクト文書に関連するタスクだけを表示できます。"
+ }
+ ]
+ },
{
"ID": "20240530101000-3jhyboz",
"Type": "NodeHeading",
@@ -1836,4 +1865,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index 9514f0909f..4a40d3a409 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -563,7 +563,19 @@ export const exportMd = (id: string) => {
const dialog = new Dialog({
title: window.siyuan.languages.fileName,
- content: `<div class="b3-dialog__content"><input class="b3-text-field fn__block" value=""></div>
+ content: `<div class="b3-dialog__content"><input class="b3-text-field fn__block" value="">
+<div class="fn__hr"></div>
+<div class="b3-label__text">${window.siyuan.languages.templateDatabaseMode}</div>
+<label class="fn__flex b3-label">
+ <input type="radio" name="templateDatabaseMode" value="copy" checked>
+ <span class="fn__space"></span>
+ <div>${window.siyuan.languages.duplicateCompletely}<div class="b3-label__text">${window.siyuan.languages.templateDatabaseCopyTip}</div></div>
+</label>
+<label class="fn__flex b3-label">
+ <input type="radio" name="templateDatabaseMode" value="reference">
+ <span class="fn__space"></span>
+ <div>${window.siyuan.languages.duplicateMirror}<div class="b3-label__text">${window.siyuan.languages.templateDatabaseReferenceTip}</div></div>
+</label></div>
<div class="b3-dialog__action">
<button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>
<button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
@@ -598,17 +610,23 @@ export const exportMd = (id: string) => {
name = name.substring(0, maxNameLen);
}
- fetchPost("/api/template/docSaveAsTemplate", {
+ const templateName = inputElement.value;
+ const selectedDatabaseMode = (dialog.element.querySelector(
+ "input[name=\"templateDatabaseMode\"]:checked") as HTMLInputElement)?.value;
+ const databaseMode: "copy" | "reference" = selectedDatabaseMode === "reference" ?
+ "reference" : "copy";
+ const requestData = {
id,
- name: inputElement.value,
- overwrite: false
- }, response => {
+ name: templateName,
+ overwrite: false,
+ databaseMode,
+ };
+ fetchPost("/api/template/docSaveAsTemplate", requestData, response => {
if (response.code === 1) {
// 重名
confirmDialog(window.siyuan.languages.export, window.siyuan.languages.exportTplTip, () => {
fetchPost("/api/template/docSaveAsTemplate", {
- id,
- name: inputElement.value,
+ ...requestData,
overwrite: true
}, resp => {
if (resp.code === 0) {
diff --git a/app/src/protyle/preview/image.ts b/app/src/protyle/preview/image.ts
index f0e6371134..f8926d45f4 100644
--- a/app/src/protyle/preview/image.ts
+++ b/app/src/protyle/preview/image.ts
@@ -62,9 +62,10 @@ export const previewDocImage = (currentSrc: string, id: string) => {
});
};
-export const previewAttrViewImages = (currentSrc: string, avID: string, viewID: string, query: string) => {
+export const previewAttrViewImages = (currentSrc: string, avID: string, blockID: string, viewID: string, query: string) => {
fetchPost("/api/av/getCurrentAttrViewImages", {
id: avID,
+ blockID,
viewID,
query,
}, (response) => {
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index 7d18533d72..a62ec17220 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -384,6 +384,11 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
event.preventDefault();
event.stopPropagation();
return true;
+ } else if (type === "av-context-filter" && !protyle.disabled) {
+ openMenuPanel({protyle, blockElement, type: "contextFilter"});
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
} else if (type === "av-filter" && !protyle.disabled) {
openMenuPanel({protyle, blockElement, type: "filters"});
event.preventDefault();
@@ -690,6 +695,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
previewAttrViewImages(
removeCompressURL((target as HTMLImageElement).getAttribute("src")),
blockElement.getAttribute("data-av-id"),
+ blockElement.getAttribute("data-node-id"),
blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || ""
);
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 98b448f22a..7ba0c100ad 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -399,6 +399,7 @@ export const editAssetItem = (options: {
previewAttrViewImages(
linkAddress,
options.blockElement.getAttribute("data-av-id"),
+ options.blockElement.getAttribute("data-node-id"),
options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
options.blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || ""
);
diff --git a/app/src/protyle/render/av/contextFilter.ts b/app/src/protyle/render/av/contextFilter.ts
new file mode 100644
index 0000000000..c1507c677d
--- /dev/null
+++ b/app/src/protyle/render/av/contextFilter.ts
@@ -0,0 +1,72 @@
+import {transaction} from "../../wysiwyg/transaction";
+import {escapeAttr, escapeHtml} from "../../../util/escape";
+import {
+ createContextFilter,
+ getContextFilterFields,
+ getContextFilterKeyID,
+} from "./contextFilterState";
+import {unicode2Emoji} from "../../../emoji";
+
+export const getContextFilterHTML = (data: IAV) => {
+ const selectedKeyID = getContextFilterKeyID(data.contextFilter);
+ const fields = getContextFilterFields(data.contextFilterFields);
+ const optionsHTML = fields.map((field) => `<button class="b3-menu__item" data-type="contextFilterField" data-id="${escapeAttr(field.id)}">
+ ${field.icon ? unicode2Emoji(field.icon, "b3-menu__icon", true) : "<svg class=\"b3-menu__icon\"><use xlink:href=\"#iconRef\"></use></svg>"}
+ <span class="b3-menu__label"><span class="fn__block fn__ellipsis">${escapeHtml(field.name || window.siyuan.languages.untitled)}</span><span class="b3-label__text fn__block" title="${escapeAttr(window.siyuan.languages.filterCurrentDocumentTip)}">${window.siyuan.languages.filterOperatorContainsAnyItem} - ${window.siyuan.languages.filterCurrentDocument}</span></span>
+ <svg class="b3-menu__icon b3-menu__icon--small"><use xlink:href="#${field.id === selectedKeyID ? "iconCheck" : "iconUncheck"}"></use></svg>
+</button>`).join("");
+
+ return `<div class="b3-menu__items">
+<button class="b3-menu__item" data-type="nobg">
+ <span class="block__icon" style="padding: 8px;margin-left: -4px;" data-type="go-config">
+ <svg><use xlink:href="#iconLeft"></use></svg>
+ </span>
+ <span class="b3-menu__label ft__center">${window.siyuan.languages.contextFilter}</span>
+</button>
+<button class="b3-menu__separator"></button>
+<div class="b3-menu__item b3-menu__item--readonly">
+ <span class="b3-menu__label ft__on-surface">${window.siyuan.languages.contextFilterTip}</span>
+</div>
+${optionsHTML || `<div class="b3-menu__item b3-menu__item--readonly"><span class="b3-menu__label ft__on-surface">${window.siyuan.languages.contextFilterNoRelation}</span></div>`}
+<button class="b3-menu__separator${selectedKeyID ? "" : " fn__none"}"></button>
+<button class="b3-menu__item b3-menu__item--warning${selectedKeyID ? "" : " fn__none"}" data-type="disableContextFilter">
+ <svg class="b3-menu__icon"><use xlink:href="#iconTrashcan"></use></svg>
+ <span class="b3-menu__label">${window.siyuan.languages.disable}</span>
+</button>
+</div>`;
+};
+
+export const bindContextFilterEvent = (options: {
+ protyle: IProtyle,
+ menuElement: HTMLElement,
+ data: IAV,
+ avID: string,
+ blockID: string,
+}) => {
+ options.menuElement.addEventListener("click", (event: MouseEvent) => {
+ const target = event.target as HTMLElement;
+ const fieldElement = target.closest('[data-type="contextFilterField"]') as HTMLElement;
+ const disableElement = target.closest('[data-type="disableContextFilter"]') as HTMLElement;
+ if (!fieldElement && !disableElement) {
+ return;
+ }
+ const oldKeyID = getContextFilterKeyID(options.data.contextFilter);
+ const keyID = disableElement ? "" : fieldElement.dataset.id || "";
+ if (keyID === oldKeyID) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ const operation = (operationKeyID: string): IOperation => ({
+ action: "setAttrViewContextFilter",
+ avID: options.avID,
+ blockID: options.blockID,
+ keyID: operationKeyID,
+ });
+ transaction(options.protyle, [operation(keyID)], [operation(oldKeyID)]);
+ options.data.contextFilter = createContextFilter(keyID);
+ options.menuElement.innerHTML = getContextFilterHTML(options.data);
+ event.preventDefault();
+ event.stopPropagation();
+ });
+};
diff --git a/app/src/protyle/render/av/contextFilterState.test.ts b/app/src/protyle/render/av/contextFilterState.test.ts
new file mode 100644
index 0000000000..52744e4fae
--- /dev/null
+++ b/app/src/protyle/render/av/contextFilterState.test.ts
@@ -0,0 +1,34 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ createContextFilter,
+ getContextFilterFields,
+ getContextFilterKeyID,
+} from "./contextFilterState";
+
+describe("database block context filter", () => {
+ it("reads only the supported context filter specification", () => {
+ assert.equal(getContextFilterKeyID({spec: 1, keyID: "relation-a"}), "relation-a");
+ assert.equal(getContextFilterKeyID(null), "");
+ assert.equal(getContextFilterKeyID({spec: 2, keyID: "relation-a"} as unknown as IAVContextFilter), "");
+ });
+
+ it("offers configured relation fields returned for the whole database", () => {
+ const fields = [
+ {id: "relation-a", name: "Project", icon: "", targetAvID: "target-a"},
+ {id: "relation-other-view", name: "Area", icon: "", targetAvID: "target-b"},
+ {id: "relation-unconfigured", name: "Empty", icon: "", targetAvID: ""},
+ ];
+
+ assert.deepEqual(getContextFilterFields(fields).map((field) => field.id), [
+ "relation-a",
+ "relation-other-view",
+ ]);
+ assert.deepEqual(getContextFilterFields(), []);
+ });
+
+ it("normalizes an empty field selection to a disabled filter", () => {
+ assert.deepEqual(createContextFilter("relation-a"), {spec: 1, keyID: "relation-a"});
+ assert.equal(createContextFilter(""), null);
+ });
+});
diff --git a/app/src/protyle/render/av/contextFilterState.ts b/app/src/protyle/render/av/contextFilterState.ts
new file mode 100644
index 0000000000..4950e3d179
--- /dev/null
+++ b/app/src/protyle/render/av/contextFilterState.ts
@@ -0,0 +1,11 @@
+export const getContextFilterKeyID = (contextFilter?: IAVContextFilter | null) => {
+ return contextFilter?.spec === 1 && typeof contextFilter.keyID === "string" ? contextFilter.keyID : "";
+};
+
+export const getContextFilterFields = (fields?: IAVContextFilterField[]) => {
+ return (fields || []).filter((field) => !!field.id && !!field.targetAvID);
+};
+
+export const createContextFilter = (keyID: string): IAVContextFilter | null => {
+ return keyID ? {spec: 1, keyID} : null;
+};
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 5459104df0..a34507b1a2 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -81,11 +81,12 @@ import {
import {openFieldVisibilityPanel} from "./fieldVisibility";
import {clearSelect} from "../../util/clear";
import {applyAVColorPalette, getAVCustomColors} from "./color";
+import {bindContextFilterEvent, getContextFilterHTML} from "./contextFilter";
export const openMenuPanel = (options: {
protyle: IProtyle,
blockElement: Element,
- type: "select" | "properties" | "config" | "sorts" | "filters" | "edit" | "date" | "asset" | "switcher" | "relation" | "rollup",
+ type: "select" | "properties" | "config" | "sorts" | "filters" | "contextFilter" | "edit" | "date" | "asset" | "switcher" | "relation" | "rollup",
colId?: string, // for edit, rollup
// 使用前端构造的数据
editData?: {
@@ -109,8 +110,9 @@ export const openMenuPanel = (options: {
}
const avID = options.blockElement.getAttribute("data-av-id");
const avPageSize = getPageSize(options.blockElement);
- // config/properties/sorts/filters/switcher 菜单只需要字段/视图元数据,不需要行数据,跳过行渲染以提升大体量视图下的响应速度
- const ignoreRows = ["config", "properties", "sorts", "filters", "switcher"].includes(options.type);
+ // config/properties/sorts/filters/contextFilter/switcher 菜单只需要字段/视图元数据,不需要行数据,
+ // 跳过行渲染以提升大体量视图下的响应速度。
+ const ignoreRows = ["config", "properties", "sorts", "filters", "contextFilter", "switcher"].includes(options.type);
const fetchPayload = {
id: avID,
query: options.blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || "",
@@ -160,6 +162,8 @@ export const openMenuPanel = (options: {
html = getSwitcherHTML(data.views, data.viewID, options.blockElement);
} else if (options.type === "filters") {
html = getFiltersHTML(data);
+ } else if (options.type === "contextFilter") {
+ html = getContextFilterHTML(data);
} else if (options.type === "select") {
html = getSelectHTML(fields, options.cellElements, true, options.blockElement);
} else if (options.type === "asset") {
@@ -312,6 +316,8 @@ export const openMenuPanel = (options: {
} else if (options.type === "filters") {
bindInlineFilterEvents(avPanelElement as HTMLElement, data, options.protyle, blockID, avID,
options.filterOperation);
+ } else if (options.type === "contextFilter") {
+ bindContextFilterEvent({protyle: options.protyle, menuElement, data, blockID, avID});
} else if (options.type === "edit") {
bindEditEvent({protyle: options.protyle, data, menuElement, isCustomAttr, blockID});
} else if (options.type === "config") {
@@ -1803,7 +1809,8 @@ export const openMenuPanel = (options: {
const assetLink = target.parentElement.dataset.content;
if (target.parentElement.dataset.type === "image" &&
isBrowserRenderableImagePath(assetLink)) {
- previewAttrViewImages(assetLink, avID, options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
+ previewAttrViewImages(assetLink, avID, options.blockElement.getAttribute("data-node-id"),
+ options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
options.blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || "");
} else {
openLink(options.protyle.app, assetLink, event, event.ctrlKey || event.metaKey);
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index 308a2ebcc3..b929baf9c7 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -55,6 +55,7 @@ import {
} from "./groupTableVirtual";
import {getAVHeaderEditingState} from "./headerEditing";
import {getAVColorStyle} from "./color";
+import {getContextFilterKeyID} from "./contextFilterState";
interface IIds {
groupId: string,
@@ -148,6 +149,10 @@ export const genTabHeaderHTML = (data: IAV, showSearch: boolean, editable: boole
<svg><use xlink:href="#iconFilter"></use></svg>
</span>
<div class="fn__space"></div>
+ ${blockElement.classList.contains("av") ? `<span data-type="av-context-filter" aria-label="${window.siyuan.languages.contextFilter}" data-position="8south" class="ariaLabel block__icon${getContextFilterKeyID(data.contextFilter) ? " block__icon--active" : ""}">
+ <svg><use xlink:href="#iconFocus"></use></svg>
+ </span>
+ <div class="fn__space"></div>` : ""}
<span data-type="av-sort" aria-label="${window.siyuan.languages.sort}" data-position="8south" class="ariaLabel block__icon${data.view.sorts.length > 0 ? " block__icon--active" : ""}">
<svg><use xlink:href="#iconSort"></use></svg>
</span>
@@ -865,6 +870,16 @@ export const refreshAV = (protyle: IProtyle, operation: IOperation) => {
});
return;
}
+ if (operation.action === "setAttrViewContextFilter") {
+ getAVElements(protyle, operation.avID).forEach((item) => {
+ if (item.dataset.nodeId !== operation.blockID) {
+ return;
+ }
+ item.removeAttribute("data-render");
+ avRender(item, protyle);
+ });
+ return;
+ }
if (operation.action === "setAttrViewName") {
getAVElements(protyle, operation.id).forEach((item) => {
const titleElement = item.querySelector(".av__title") as HTMLElement;
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 6471589327..9ed488f87a 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -1342,7 +1342,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
"updateAttrViewColRelation", "setAttrViewColRelationFilters", "setAttrViewPageSize", "updateAttrViewColRollup",
"setAttrViewColRollupFilters", "sortAttrViewKey", "setAttrViewColDesc",
"duplicateAttrViewKey", "setAttrViewViewDesc", "setAttrViewCoverFrom", "setAttrViewCoverFromAssetKeyID", "setAttrViewCardCoverPosition",
- "setAttrViewBlockView", "setAttrViewBlockVisibleViews", "setAttrViewCardSize", "setAttrViewCardWidth", "setAttrViewCardAspectRatio",
+ "setAttrViewBlockView", "setAttrViewBlockVisibleViews", "setAttrViewContextFilter", "setAttrViewCardSize", "setAttrViewCardWidth", "setAttrViewCardAspectRatio",
"setAttrViewCardAspectRatioValue", "setAttrViewCardLayout", "setAttrViewColFullRow", "hideAttrViewName", "setAttrViewShowIcon",
"setAttrViewWrapField", "setAttrViewGroup", "removeAttrViewGroup", "hideAttrViewGroup", "sortAttrViewGroup",
"foldAttrViewGroup", "foldAttrViewGroups", "hideAttrViewAllGroups", "setAttrViewFitImage", "setAttrViewDisplayFieldName", "setAttrViewDisplayEmptyFields",
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 14f0481ad3..aff5b894ef 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -59,6 +59,7 @@ type TOperation =
| "duplicateAttrViewView"
| "duplicateAttrViewRow"
| "setAttrViewBlockVisibleViews"
+ | "setAttrViewContextFilter"
| "sortAttrViewView"
| "setAttrViewPageSize"
| "updateAttrViewColRelation"
@@ -796,7 +797,7 @@ interface IOperation {
backRelationKeyID?: string, // 双向关联的目标关联列 ID
avID?: string, // av
format?: string // 属性视图字段格式化
- keyID?: string // updateAttrViewCell 专享
+ keyID?: string // 属性视图字段 ID
rowID?: string // updateAttrViewCell 专享
cellUpdates?: Array<{
keyID: string,
@@ -1248,9 +1249,23 @@ interface IAV {
customColors?: IAVCustomColor[];
colorOrder?: string[];
usedCustomColorIndexes?: number[];
+ contextFilter?: IAVContextFilter | null;
+ contextFilterFields?: IAVContextFilterField[];
target?: IAVRenderTarget;
}
+interface IAVContextFilter {
+ spec: 1;
+ keyID: string;
+}
+
+interface IAVContextFilterField {
+ id: string;
+ name: string;
+ icon: string;
+ targetAvID: string;
+}
+
interface IAVRenderTarget {
status: "visible" | "filtered" | "itemNotFound" | "groupHidden";
itemID: string;
diff --git a/docs/API.ja.md b/docs/API.ja.md
index be03eec61f..ae98495091 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -1328,6 +1328,34 @@
}
```
+### ドキュメントをテンプレートとして保存
+
+* `/api/template/docSaveAsTemplate`
+* パラメータ
+
+ ```json
+ {
+ "id": "20220724223548-j6g0o87",
+ "name": "プロジェクト",
+ "overwrite": false,
+ "databaseMode": "copy"
+ }
+ ```
+
+ * `id`: 保存元ドキュメントの ID
+ * `name`: テンプレート名。カーネルが名前を整形し、`.md` 拡張子を追加します
+ * `overwrite`: 同名のテンプレートを上書きするかどうか。`false` でテンプレートがすでに存在する場合、レスポンスの `code` は `1` です
+ * `databaseMode`: ドキュメント内のすべてのデータベースブロックに対する任意の処理方法。`copy`(デフォルト)はテンプレートを使用するたびに独立したデータベースを作成し、ブロック単位のコンテキストフィルターを削除します。`reference` は既存のデータベース ID とコンテキストフィルターを保持するため、レンダリングされたブロックは元のデータベースとデータおよびビュー設定を共有するミラーになります。対象ドキュメントの暗号化境界内で元のデータベースを利用できない場合、参照モードのテンプレートレンダリングは失敗します
+* 戻り値
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
### Sprigをレンダリング
* `/api/template/renderSprig`
@@ -1859,7 +1887,7 @@
```
* `id`: データベース ID
- * `blockID`: このデータベースを埋め込むデータベースブロック。アクティブなビューや公開権限の解決に使用します。`custom-sy-av-view` が存在しないか無効な場合は、最初に利用可能なビューを使用します。独立したデータベースをレンダリングする場合は省略します
+ * `blockID`: このデータベースを埋め込むデータベースブロック。アクティブなビュー、公開権限、ブロック単位のコンテキストフィルターの解決に使用します。`custom-sy-av-view` が存在しないか無効な場合は、最初に利用可能なビューを使用します。独立したデータベースをレンダリングする場合は省略できますが、コンテキストフィルターが設定されている場合は有効なデータベースブロックのインスタンスが必要です
* `viewID`: レンダリングするビューを明示的に指定します。無効な値はエラーになります。省略時は `blockID` から解決し、解決できなければ最初に利用可能なビューを使用します
* `page`: ページ番号(1 始まり)。デフォルトは `1`
* `pageSize`: 1 ページあたりのアイテム数。`-1` または省略時はビューのデフォルト(`50`)を使用
@@ -1881,6 +1909,8 @@
"viewType": "table",
"viewID": "20240118120204-7rnmyc1",
"isMirror": false,
+ "contextFilter": null,
+ "contextFilterFields": [],
"views": [
{
"id": "20240118120204-7rnmyc1",
@@ -1963,6 +1993,67 @@
* `data.view.rows[].cells[].value`: `Value` オブジェクト——すべての value 形状は [セル値を設定](#セル値を設定) を参照。`createdAt`/`updatedAt` は int64 ミリ秒タイムスタンプ。通常フィールドに空でない `renderTemplate` が設定されている場合、任意の `renderedContent` プロパティに実行時の表示テンプレート結果が入ります。このプロパティは永続化されず、元の型のプロパティには引き続き保存値が入ります。`data.view.cards[]` 内の値も同じ規則に従います
* `data.views`: 全ビューのメタデータ(行データなし)
* `data.isMirror`: データベースブロックがデータベースのミラー(読み取り専用コピー)の場合 `true`
+ * `data.contextFilter`: このデータベースブロックに設定されたコンテキストフィルター。無効の場合は `null` です。現在の仕様は `{ "spec": 1, "keyID": "<関連フィールド ID>" }` で、すべてのビューに対し、選択した関連フィールドが `blockID` を含むルート文書に紐付いたデータベース項目を含む行だけに絞り込み、選択中のビューのフィルターとは AND で組み合わせます。選択したフィールドが削除された場合、リレーション以外の型に変更された場合、または関連先が無効になった場合もブロック単位の設定は保持されますが、フィールドの修復・変更またはコンテキストフィルターの無効化を行うまで行は表示されません
+ * `data.contextFilterFields`: 選択中のビューに依存しない、データベース内の設定済み関連フィールドすべての軽量メタデータです。各項目は `id`、`name`、`icon`、`targetAvID` を含み、`contextFilter` の設定に使用します。公開読み取り専用レスポンスでは `contextFilter` は `null`、この一覧は `[]` に隠されますが、保存済みのコンテキストフィルターはレンダリング結果に引き続き適用されます
+
+### データベースブロックのコンテキストフィルターを設定
+
+* `/api/av/setAttrViewContextFilter`
+* パラメータ
+
+ ```json
+ {
+ "avID": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "keyID": "20240118120300-relation"
+ }
+ ```
+
+ * `avID`: データベース ID
+ * `blockID`: コンテキストフィルターを変更する具体的なデータベースブロックの ID。`avID` のインスタンスである必要があります
+ * `keyID`: データベースで設定済みの関連フィールドの ID。フィルターの意味は `いずれかを含む - 現在の文書` に固定されます。空文字列を渡すとコンテキストフィルターを無効にします
+* 戻り値:正規化された設定を `data.contextFilter` に返します。無効化後は `null` です
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "contextFilter": {
+ "spec": 1,
+ "keyID": "20240118120300-relation"
+ }
+ }
+ }
+ ```
+
+### 現在のデータベースビューの画像を取得
+
+* `/api/av/getCurrentAttrViewImages`
+* パラメータ
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "viewID": "20240118120204-7rnmyc1",
+ "query": ""
+ }
+ ```
+
+ * `id`: データベース ID
+ * `blockID`: データベースを埋め込むデータベースブロック。現在のビュー、公開アクセス権、およびブロック単位のコンテキストフィルターの解決に使用します。独立したデータベースでブロックコンテキストが不要な場合のみ省略します
+ * `viewID`: 明示的なビュー ID(任意)。省略時は `blockID` から解決し、解決できなければ最初に利用可能なビューを使用します
+ * `query`: 主キー値に対する任意の全文フィルターキーワード
+* 戻り値:データベースブロックのコンテキストフィルター、ビューのフィルター、ソートを適用した後、表示されているアセットフィールドに含まれる画像アセットパスの配列
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": ["assets/example-20240118120201-abc1234.png"]
+ }
+ ```
### 取得
diff --git a/docs/API.md b/docs/API.md
index 86af107ac6..cd077a8c1f 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1366,6 +1366,34 @@ Note: To ensure data security, access to this interface is prohibited in Publish
* `depth`: Depth relative to the document where the template is inserted
* A single plan can contain at most 128 documents, and its declared child document tree can be at most 16 levels deep. The resulting absolute file tree depth remains subject to the setting that controls whether sub-documents deeper than 7 levels may be created
+### Save a document as a template
+
+* `/api/template/docSaveAsTemplate`
+* Parameters
+
+ ```json
+ {
+ "id": "20220724223548-j6g0o87",
+ "name": "Project",
+ "overwrite": false,
+ "databaseMode": "copy"
+ }
+ ```
+
+ * `id`: Source document ID
+ * `name`: Template name. The kernel sanitizes the name and adds the `.md` extension
+ * `overwrite`: Whether to replace an existing template with the same name. When `false` and the template exists, the response `code` is `1`
+ * `databaseMode`: Optional handling for all database blocks in the document. `copy` (the default) creates independent databases whenever the template is used and clears their block-level context filters; `reference` keeps the existing database IDs and context filters, so rendered blocks are mirrors that share data and view settings with the source databases. Rendering a reference-mode template fails if a source database is unavailable in the target document's encryption boundary
+* Return value
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
### Render Sprig
* `/api/template/renderSprig`
@@ -1899,7 +1927,7 @@ The field types (`keyType`) are:
```
* `id`: Database ID
- * `blockID`: The database block that embeds this database. Used to resolve the active view and publish access. If its `custom-sy-av-view` is missing or invalid, the first available view is used. Omit when rendering a detached database
+ * `blockID`: The database block that embeds this database. Used to resolve the active view, publish access, and the block-level context filter. If its `custom-sy-av-view` is missing or invalid, the first available view is used. Omit when rendering a detached database; a configured context filter requires a valid block instance
* `viewID`: An explicit view to render. An invalid value returns an error. When omitted, the view is resolved from `blockID`, then falls back to the first available view
* `page`: Page number, 1-based. Defaults to `1`
* `pageSize`: Items per page. `-1` or omitted means use the view's default (`50`)
@@ -1921,6 +1949,8 @@ The field types (`keyType`) are:
"viewType": "table",
"viewID": "20240118120204-7rnmyc1",
"isMirror": false,
+ "contextFilter": null,
+ "contextFilterFields": [],
"views": [
{
"id": "20240118120204-7rnmyc1",
@@ -2003,6 +2033,67 @@ The field types (`keyType`) are:
* `data.view.rows[].cells[].value`: A `Value` object — see [Set a cell value](#Set-a-cell-value) for all value shapes. `createdAt`/`updatedAt` are int64 millisecond timestamps. When a normal field has a non-empty `renderTemplate`, its optional `renderedContent` property contains the runtime display-template result; this property is not persisted, and the original typed property continues to contain the stored value. Values under `data.view.cards[]` follow the same rule
* `data.views`: Metadata of every view (no rows)
* `data.isMirror`: `true` when the database block is a mirror (read-only copy) of the database
+ * `data.contextFilter`: The context filter configured for this database block, or `null` when disabled. The current specification is `{ "spec": 1, "keyID": "<relation-field-ID>" }`; it filters every view to rows whose selected relation field contains the database item bound to the root document containing `blockID`, and is combined with the selected view's filters using AND. If the selected field is deleted, changed to a non-relation field, or loses its relation target, the block-level configuration is retained but renders no rows until the field is repaired, replaced, or the context filter is disabled
+ * `data.contextFilterFields`: Lightweight metadata for every configured relation field in the database, independent of the selected view. Each item contains `id`, `name`, `icon`, and `targetAvID`; use this list to configure `contextFilter`. Publish read-only responses mask `contextFilter` as `null` and this list as `[]`, while the stored context filter still applies to rendered rows
+
+### Set a database block context filter
+
+* `/api/av/setAttrViewContextFilter`
+* Parameters
+
+ ```json
+ {
+ "avID": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "keyID": "20240118120300-relation"
+ }
+ ```
+
+ * `avID`: Database ID
+ * `blockID`: ID of the concrete database block whose context filter is changed. It must be an instance of `avID`
+ * `keyID`: ID of a configured relation field in the database. The filter uses fixed semantics equivalent to `Contains any item - Current document`. Pass an empty string to disable the context filter
+* Return value: the normalized configuration in `data.contextFilter`, or `null` after disabling it
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "contextFilter": {
+ "spec": 1,
+ "keyID": "20240118120300-relation"
+ }
+ }
+ }
+ ```
+
+### Get images in the current database view
+
+* `/api/av/getCurrentAttrViewImages`
+* Parameters
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "viewID": "20240118120204-7rnmyc1",
+ "query": ""
+ }
+ ```
+
+ * `id`: Database ID
+ * `blockID`: The database block that embeds the database. It resolves the active view, publish access, and the block-level context filter. Omit only for a detached database that does not require block context
+ * `viewID`: Optional explicit view ID. When omitted, the view is resolved from `blockID`, then falls back to the first available view
+ * `query`: Optional full-text filter for the primary-key values
+* Return value: an array of image asset paths from visible asset fields after applying the database block's context filter, the view's filters, and sorting
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": ["assets/example-20240118120201-abc1234.png"]
+ }
+ ```
### Get
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 8b252852ee..0cd0f65cfd 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -1327,6 +1327,34 @@
}
```
+### 将文档保存为模板
+
+* `/api/template/docSaveAsTemplate`
+* 参数
+
+ ```json
+ {
+ "id": "20220724223548-j6g0o87",
+ "name": "项目",
+ "overwrite": false,
+ "databaseMode": "copy"
+ }
+ ```
+
+ * `id`: 源文档 ID
+ * `name`: 模板名称。内核会清理名称并添加 `.md` 扩展名
+ * `overwrite`: 是否覆盖同名模板。为 `false` 且模板已存在时,响应 `code` 为 `1`
+ * `databaseMode`: 文档中所有数据库块的可选处理方式。`copy`(默认值)在每次使用模板时创建独立数据库,并清除块级上下文筛选;`reference` 保留原有数据库 ID 和上下文筛选,使渲染出的块成为与源数据库共享数据和视图配置的镜像。若目标文档的加密边界内无法访问源数据库,引用模式的模板渲染会失败
+* 返回值
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
### 渲染 Sprig
* `/api/template/renderSprig`
@@ -1859,7 +1887,7 @@
```
* `id`: 数据库 ID
- * `blockID`: 嵌入该数据库的数据库块,用于解析当前视图和发布权限。其 `custom-sy-av-view` 缺失或无效时使用第一个可用视图。渲染独立数据库时可省略
+ * `blockID`: 嵌入该数据库的数据库块,用于解析当前视图、发布权限和块级上下文筛选。其 `custom-sy-av-view` 缺失或无效时使用第一个可用视图。渲染独立数据库时可省略;已配置上下文筛选时必须传入有效的数据库块实例
* `viewID`: 明确指定要渲染的视图。值无效时返回错误;省略时先通过 `blockID` 解析,无法解析则使用第一个可用视图
* `page`: 页码,从 1 开始。默认为 `1`
* `pageSize`: 每页条目数。`-1` 或省略表示使用视图默认值(`50`)
@@ -1881,6 +1909,8 @@
"viewType": "table",
"viewID": "20240118120204-7rnmyc1",
"isMirror": false,
+ "contextFilter": null,
+ "contextFilterFields": [],
"views": [
{
"id": "20240118120204-7rnmyc1",
@@ -1963,6 +1993,67 @@
* `data.view.rows[].cells[].value`: 一个 `Value` 对象——所有 value 形态见 [设置单元格值](#设置单元格值)。`createdAt`/`updatedAt` 为 int64 毫秒时间戳。当普通字段配置了非空 `renderTemplate` 时,可选属性 `renderedContent` 包含运行时显示模板结果;该属性不会持久化,原有类型属性仍包含存储值。`data.view.cards[]` 中的值遵循相同规则
* `data.views`: 所有视图的元数据(不含行数据)
* `data.isMirror`: 当数据库块为数据库的镜像(只读副本)时为 `true`
+ * `data.contextFilter`: 当前数据库块配置的上下文筛选;禁用时为 `null`。当前规格为 `{ "spec": 1, "keyID": "<关联字段 ID>" }`,它会在所有视图中筛选出所选关联字段包含 `blockID` 所在根文档所绑定数据库条目的行,并与当前视图的筛选条件通过“且”组合。所选字段被删除、改为非关联字段或关联目标失效时,该块级配置会保留,但渲染结果为空,直至修复字段、更换字段或禁用上下文筛选
+ * `data.contextFilterFields`: 数据库中所有已配置关联字段的轻量元数据,不受当前所选视图影响。每项包含 `id`、`name`、`icon` 和 `targetAvID`,用于配置 `contextFilter`。发布只读响应会将 `contextFilter` 隐藏为 `null`,并将此列表隐藏为 `[]`,但已保存的上下文筛选仍会应用于渲染结果
+
+### 设置数据库块上下文筛选
+
+* `/api/av/setAttrViewContextFilter`
+* 参数
+
+ ```json
+ {
+ "avID": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "keyID": "20240118120300-relation"
+ }
+ ```
+
+ * `avID`: 数据库 ID
+ * `blockID`: 要修改上下文筛选的具体数据库块 ID,必须是 `avID` 的实例
+ * `keyID`: 数据库中已配置的关联字段 ID,筛选语义固定等同于 `包含任一 - 当前文档`。传入空字符串可禁用上下文筛选
+* 返回值:`data.contextFilter` 中的规范化配置;禁用后为 `null`
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "contextFilter": {
+ "spec": 1,
+ "keyID": "20240118120300-relation"
+ }
+ }
+ }
+ ```
+
+### 获取当前数据库视图中的图片
+
+* `/api/av/getCurrentAttrViewImages`
+* 参数
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "blockID": "20240118120201-kldj15t",
+ "viewID": "20240118120204-7rnmyc1",
+ "query": ""
+ }
+ ```
+
+ * `id`: 数据库 ID
+ * `blockID`: 嵌入该数据库的数据库块,用于解析当前视图、发布权限和块级上下文筛选。仅在独立数据库且不需要块上下文时省略
+ * `viewID`: 可选的明确视图 ID。省略时先通过 `blockID` 解析,无法解析则使用第一个可用视图
+ * `query`: 可选的主键值全文过滤关键字
+* 返回值:应用数据库块上下文筛选、视图筛选与排序后,可见资源字段中的图片资源路径数组
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": ["assets/example-20240118120201-abc1234.png"]
+ }
+ ```
### 获取
diff --git a/kernel/api/av.go b/kernel/api/av.go
index 6da7ce6655..823987049d 100644
--- a/kernel/api/av.go
+++ b/kernel/api/av.go
@@ -292,6 +292,32 @@ func setAttrViewFilters(c *gin.Context) {
c.JSON(http.StatusOK, ret)
}
+func setAttrViewContextFilter(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ avID := arg["avID"].(string)
+ blockID := arg["blockID"].(string)
+ keyID, _ := arg["keyID"].(string)
+ if err := holdAttributeViewRequest(c, blockID, avID); nil != err {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+
+ contextFilter, err := model.SetAttributeViewContextFilter(blockID, avID, keyID)
+ if nil != err {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = map[string]any{"contextFilter": contextFilter}
+}
+
func setAttrViewSorts(c *gin.Context) {
ret := gulu.Ret.NewResult()
arg, ok := util.JsonArg(c, ret)
@@ -1346,6 +1372,9 @@ func renderAttributeView(c *gin.Context) {
if ret.Code == 0 && readOnlyRole {
retDataMap := ret.Data.(map[string]any)
retDataMap["view"] = model.FilterAttributeViewByPublishAccess(c, publishAccess, id, blockID, retDataMap["view"].(av.Viewable))
+ // 发布只读渲染不暴露当前视图之外的实例筛选配置和关联字段元数据。
+ retDataMap["contextFilter"] = nil
+ retDataMap["contextFilterFields"] = []*av.AttributeViewContextFilterField{}
}
// 大体量响应(如全量数据库视图)用 goccy 序列化后直接写字节,跳过 gin 内部基于标准库的二次序列化
@@ -1359,8 +1388,20 @@ func renderAttributeView(c *gin.Context) {
func holdAttributeViewRequest(c *gin.Context, blockID, avID string) error {
if blockID != "" {
- if block := treenode.GetBlockTree(blockID); block != nil && model.IsEncryptedBox(block.BoxID) {
- return holdEncryptedBoxRequest(c, block.BoxID)
+ block := treenode.GetBlockTree(blockID)
+ if nil == block {
+ for _, encryptedBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if block = treenode.GetBlockTreeInBox(blockID, encryptedBoxID); nil != block {
+ break
+ }
+ }
+ }
+ if nil != block {
+ if model.IsEncryptedBox(block.BoxID) {
+ return holdEncryptedBoxRequest(c, block.BoxID)
+ }
+ // 已解析的普通载体是权威上下文,不得再按 avID 回退到已打开的加密笔记本。
+ return nil
}
}
if _, boxID := av.FindAttributeViewPath(avID); boxID != "" {
@@ -1397,6 +1438,12 @@ func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, gro
PageSize: v.PageSize,
})
}
+ contextFilter, err := model.GetAttributeViewContextFilter(attrView, blockID)
+ if nil != err {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
retData := map[string]any{
"name": attrView.Name,
@@ -1411,6 +1458,8 @@ func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, gro
"isMirror": av.IsMirror(attrView.ID),
"newItemTemplates": attrView.NewItemTemplates,
"defaultTemplateID": attrView.DefaultTemplateID,
+ "contextFilter": contextFilter,
+ "contextFilterFields": attrView.ContextFilterFields(),
}
if nil != target {
retData["target"] = target
@@ -1429,6 +1478,7 @@ func getCurrentAttrViewImages(c *gin.Context) {
}
id := arg["id"].(string)
+ blockID, _ := arg["blockID"].(string)
viewIDArg := arg["viewID"]
var viewID string
if nil != viewIDArg {
@@ -1441,7 +1491,13 @@ func getCurrentAttrViewImages(c *gin.Context) {
query = queryArg.(string)
}
- images, err := model.GetCurrentAttributeViewImages(c, id, viewID, query)
+ if err := holdAttributeViewRequest(c, blockID, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+
+ images, err := model.GetCurrentAttributeViewImages(c, id, blockID, viewID, query)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/av_box_test.go b/kernel/api/av_box_test.go
new file mode 100644
index 0000000000..1d5ba1157b
--- /dev/null
+++ b/kernel/api/av_box_test.go
@@ -0,0 +1,84 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestHoldAttributeViewRequestUsesOrdinaryCarrierContext(t *testing.T) {
+ const (
+ ordinaryBoxID = "20260904121000-boxnorm"
+ documentID = "20260904121001-docnorm"
+ foreignBoxID = "20260904121002-boxenc0"
+ foreignAvID = "20260904121003-avenc00"
+ missingID = "20260904121004-missing"
+ )
+
+ oldDataDir, oldBlockTreeDBPath := util.DataDir, util.BlockTreeDBPath
+ util.DataDir = t.TempDir()
+ util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ util.DataDir, util.BlockTreeDBPath = oldDataDir, oldBlockTreeDBPath
+ if "" != oldBlockTreeDBPath {
+ treenode.InitBlockTree(false)
+ }
+ })
+
+ oldEncryptedBoxIDs := av.AVEncryptedBoxIDs
+ av.AVEncryptedBoxIDs = func() []string { return []string{foreignBoxID} }
+ t.Cleanup(func() { av.AVEncryptedBoxIDs = oldEncryptedBoxIDs })
+
+ tree := treenode.NewTree(ordinaryBoxID, "/"+documentID+".sy", "/Ordinary", "Ordinary")
+ treenode.UpsertBlockTree(tree)
+ foreignAvPath := filepath.Join(util.DataDir, foreignBoxID, "storage", "av", foreignAvID+".json")
+ if err := os.MkdirAll(filepath.Dir(foreignAvPath), 0755); nil != err {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(foreignAvPath, []byte("encrypted"), 0644); nil != err {
+ t.Fatal(err)
+ }
+ foreignConfPath := filepath.Join(util.DataDir, foreignBoxID, ".siyuan", "conf.json")
+ if err := os.MkdirAll(filepath.Dir(foreignConfPath), 0755); nil != err {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(foreignConfPath, []byte(`{"encrypted":true}`), 0644); nil != err {
+ t.Fatal(err)
+ }
+ if !model.IsEncryptedBox(foreignBoxID) {
+ t.Fatal("foreign box should be recognized as encrypted")
+ }
+
+ context, _ := gin.CreateTestContext(httptest.NewRecorder())
+ if err := holdAttributeViewRequest(context, documentID, foreignAvID); nil != err {
+ t.Fatalf("ordinary carrier should not acquire a foreign encrypted box lease: %v", err)
+ }
+ if err := holdAttributeViewRequest(context, missingID, foreignAvID); nil == err {
+ t.Fatal("missing carrier compatibility fallback should still require the encrypted box lease")
+ }
+}
diff --git a/kernel/api/av_context_filter_test.go b/kernel/api/av_context_filter_test.go
new file mode 100644
index 0000000000..4d08b13283
--- /dev/null
+++ b/kernel/api/av_context_filter_test.go
@@ -0,0 +1,244 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type attributeViewContextFilterAPIFixture struct {
+ attrView *av.AttributeView
+ databaseID string
+ paragraphID string
+ relationKeyID string
+ textKeyID string
+}
+
+func TestSetAttrViewContextFilterHandler(t *testing.T) {
+ fixture := setupAttributeViewContextFilterAPITest(t)
+
+ success := callAttributeViewContextFilterAPI(t, "/api/av/setAttrViewContextFilter", map[string]any{
+ "avID": fixture.attrView.ID, "blockID": fixture.databaseID, "keyID": fixture.relationKeyID,
+ }, setAttrViewContextFilter)
+ var successResponse struct {
+ Code int `json:"code"`
+ Data struct {
+ ContextFilter *av.AttributeViewContextFilter `json:"contextFilter"`
+ } `json:"data"`
+ }
+ decodeAttributeViewContextFilterAPIResponse(t, success, &successResponse)
+ if 0 != successResponse.Code || nil == successResponse.Data.ContextFilter ||
+ fixture.relationKeyID != successResponse.Data.ContextFilter.KeyID {
+ t.Fatalf("unexpected successful setter response: %s", success.Body.String())
+ }
+
+ for _, test := range []struct {
+ name string
+ blockID string
+ keyID string
+ }{
+ {name: "non relation key", blockID: fixture.databaseID, keyID: fixture.textKeyID},
+ {name: "non database carrier", blockID: fixture.paragraphID, keyID: fixture.relationKeyID},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ response := callAttributeViewContextFilterAPI(t, "/api/av/setAttrViewContextFilter", map[string]any{
+ "avID": fixture.attrView.ID, "blockID": test.blockID, "keyID": test.keyID,
+ }, setAttrViewContextFilter)
+ var result struct {
+ Code int `json:"code"`
+ }
+ decodeAttributeViewContextFilterAPIResponse(t, response, &result)
+ if -1 != result.Code {
+ t.Fatalf("invalid setter request was accepted: %s", response.Body.String())
+ }
+ })
+ }
+}
+
+func TestRenderAttributeViewReturnsContextFilterMetadata(t *testing.T) {
+ fixture := setupAttributeViewContextFilterAPITest(t)
+ payload := map[string]any{
+ "id": fixture.attrView.ID, "blockID": fixture.databaseID, "viewID": fixture.attrView.Views[0].ID,
+ "page": 1, "pageSize": -1, "createIfNotExist": false, "ignoreRows": true,
+ }
+ response := callAttributeViewContextFilterAPI(t, "/api/av/renderAttributeView", payload, renderAttributeView)
+ var result struct {
+ Code int `json:"code"`
+ Data struct {
+ ContextFilter *av.AttributeViewContextFilter `json:"contextFilter"`
+ ContextFilterFields []*av.AttributeViewContextFilterField `json:"contextFilterFields"`
+ } `json:"data"`
+ }
+ decodeAttributeViewContextFilterAPIResponse(t, response, &result)
+ if 0 != result.Code || nil == result.Data.ContextFilter ||
+ fixture.relationKeyID != result.Data.ContextFilter.KeyID {
+ t.Fatalf("render response omitted the instance context filter: %s", response.Body.String())
+ }
+ if 1 != len(result.Data.ContextFilterFields) {
+ t.Fatalf("unexpected render context filter fields: %s", response.Body.String())
+ }
+ field := result.Data.ContextFilterFields[0]
+ if fixture.relationKeyID != field.ID || "Project" != field.Name || "1f4c1" != field.Icon ||
+ fixture.attrView.ID != field.TargetAvID {
+ t.Fatalf("unexpected render context filter field: %#v", field)
+ }
+
+ readOnlyResponse := callAttributeViewContextFilterAPIWithRole(t, "/api/av/renderAttributeView", payload,
+ renderAttributeView, model.RoleReader)
+ var readOnlyResult struct {
+ Code int `json:"code"`
+ Data struct {
+ ContextFilter *av.AttributeViewContextFilter `json:"contextFilter"`
+ ContextFilterFields []*av.AttributeViewContextFilterField `json:"contextFilterFields"`
+ } `json:"data"`
+ }
+ decodeAttributeViewContextFilterAPIResponse(t, readOnlyResponse, &readOnlyResult)
+ if 0 != readOnlyResult.Code || nil != readOnlyResult.Data.ContextFilter ||
+ 0 != len(readOnlyResult.Data.ContextFilterFields) {
+ t.Fatalf("read-only render leaked context filter metadata: %s", readOnlyResponse.Body.String())
+ }
+}
+
+func setupAttributeViewContextFilterAPITest(t *testing.T) *attributeViewContextFilterAPIFixture {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+
+ oldDataDir, oldBlockTreeDBPath := util.DataDir, util.BlockTreeDBPath
+ oldLang, oldLangs, oldAttrViewLangs := util.Lang, util.Langs, util.AttrViewLangs
+ oldConf := model.Conf
+ util.DataDir = t.TempDir()
+ util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")
+ util.Lang = "en"
+ util.Langs = map[string]map[int]string{"en": {105: "Database", 314: "Database is unavailable"}}
+ util.AttrViewLangs = map[string]map[string]any{
+ "en": {"key": "Key", "select": "Select", "table": "Table"},
+ }
+ model.Conf = model.NewAppConf()
+ model.Conf.Lang = "en"
+ model.Conf.FileTree = conf.NewFileTree()
+ model.Conf.Sync = conf.NewSync()
+ cache.ClearAVCache()
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ cache.ClearAVCache()
+ treenode.CloseDatabase()
+ util.DataDir, util.BlockTreeDBPath = oldDataDir, oldBlockTreeDBPath
+ util.Lang, util.Langs, util.AttrViewLangs = oldLang, oldLangs, oldAttrViewLangs
+ model.Conf = oldConf
+ if "" != oldBlockTreeDBPath {
+ treenode.InitBlockTree(false)
+ }
+ })
+
+ const (
+ boxID = "20260904002000-ctxbox0"
+ documentID = "20260904002001-ctxdoc0"
+ databaseID = "20260904002002-ctxav00"
+ paragraphID = "20260904002003-ctxpara"
+ attributeViewID = "20260904002004-ctxdata"
+ relationKeyID = "20260904002005-ctxrel0"
+ textKeyID = "20260904002006-ctxtext"
+ )
+ attrView := av.NewAttributeView(attributeViewID)
+ attrView.KeyValues = append(attrView.KeyValues,
+ &av.KeyValues{Key: &av.Key{
+ ID: relationKeyID, Name: "Project", Icon: "1f4c1", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: attributeViewID},
+ }},
+ &av.KeyValues{Key: &av.Key{ID: textKeyID, Name: "Text", Type: av.KeyTypeText}},
+ )
+ if err := av.SaveAttributeView(attrView); nil != err {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { av.SetAVBoxID(attributeViewID, "") })
+
+ contextFilter := &av.AttributeViewContextFilter{
+ Spec: av.AttributeViewContextFilterSpec, KeyID: relationKeyID,
+ }
+ raw, err := contextFilter.Marshal()
+ if nil != err {
+ t.Fatal(err)
+ }
+ tree := treenode.NewTree(boxID, "/"+documentID+".sy", "/Context filter", "Context filter")
+ for nil != tree.Root.FirstChild {
+ tree.Root.FirstChild.Unlink()
+ }
+ database := &ast.Node{
+ Type: ast.NodeAttributeView, ID: databaseID, AttributeViewID: attributeViewID,
+ AttributeViewType: string(av.LayoutTypeTable),
+ }
+ database.SetIALAttr("id", databaseID)
+ database.SetIALAttr(av.NodeAttrView, attrView.Views[0].ID)
+ database.SetIALAttr(av.NodeAttrContextFilter, raw)
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: paragraphID}
+ paragraph.SetIALAttr("id", paragraphID)
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("not a database")})
+ tree.Root.AppendChild(database)
+ tree.Root.AppendChild(paragraph)
+ if _, err = filesys.WriteTree(tree); nil != err {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+
+ return &attributeViewContextFilterAPIFixture{
+ attrView: attrView, databaseID: databaseID, paragraphID: paragraphID,
+ relationKeyID: relationKeyID, textKeyID: textKeyID,
+ }
+}
+
+func callAttributeViewContextFilterAPI(t *testing.T, path string, payload map[string]any,
+ handler gin.HandlerFunc) *httptest.ResponseRecorder {
+ return callAttributeViewContextFilterAPIWithRole(t, path, payload, handler, model.RoleAdministrator)
+}
+
+func callAttributeViewContextFilterAPIWithRole(t *testing.T, path string, payload map[string]any,
+ handler gin.HandlerFunc, role model.Role) *httptest.ResponseRecorder {
+ t.Helper()
+ body, err := json.Marshal(payload)
+ if nil != err {
+ t.Fatal(err)
+ }
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
+ context.Request.Header.Set("Content-Type", "application/json")
+ context.Set(model.RoleContextKey, role)
+ handler(context)
+ return recorder
+}
+
+func decodeAttributeViewContextFilterAPIResponse(t *testing.T, recorder *httptest.ResponseRecorder, target any) {
+ t.Helper()
+ if err := json.Unmarshal(recorder.Body.Bytes(), target); nil != err {
+ t.Fatalf("decode API response failed: %v\n%s", err, recorder.Body.String())
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 98fe7dee6f..ed25c65c7d 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -595,6 +595,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/av/searchAttributeViewRollupDestKeys", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, searchAttributeViewRollupDestKeys)
ginServer.Handle("POST", "/api/av/getAttributeViewFilterSort", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getAttributeViewFilterSort)
ginServer.Handle("POST", "/api/av/setAttrViewFilters", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAttrViewFilters)
+ ginServer.Handle("POST", "/api/av/setAttrViewContextFilter", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAttrViewContextFilter)
ginServer.Handle("POST", "/api/av/setAttrViewSorts", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAttrViewSorts)
ginServer.Handle("POST", "/api/av/addAttributeViewKey", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, addAttributeViewKey)
ginServer.Handle("POST", "/api/av/removeAttributeViewKey", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeAttributeViewKey)
diff --git a/kernel/api/template.go b/kernel/api/template.go
index c1d7d3012c..00badc0426 100644
--- a/kernel/api/template.go
+++ b/kernel/api/template.go
@@ -57,7 +57,15 @@ func docSaveAsTemplate(c *gin.Context) {
id := arg["id"].(string)
name := arg["name"].(string)
overwrite := arg["overwrite"].(bool)
- code, err := model.DocSaveAsTemplate(id, name, overwrite)
+ databaseMode := model.TemplateDatabaseModeCopy
+ if value, exists := arg["databaseMode"]; exists {
+ if mode, ok := value.(string); ok {
+ databaseMode = model.TemplateDatabaseMode(mode)
+ } else {
+ databaseMode = model.TemplateDatabaseMode("invalid")
+ }
+ }
+ code, err := model.DocSaveAsTemplateWithDatabaseMode(id, name, overwrite, databaseMode)
if err != nil {
ret.Code = -1
ret.Msg = util.EscapeHTML(err.Error())
diff --git a/kernel/api/template_test.go b/kernel/api/template_test.go
index 37e4d2ece9..8146b2be8e 100644
--- a/kernel/api/template_test.go
+++ b/kernel/api/template_test.go
@@ -140,3 +140,48 @@ func TestIsPathInTemplatesDir(t *testing.T) {
t.Errorf("isPathInTemplatesDir(symlink -> conf.json) = true, want false")
}
}
+
+func TestDocSaveAsTemplateDatabaseMode(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ tests := []struct {
+ name string
+ databaseMode any
+ includeMode bool
+ wantCode int
+ }{
+ {name: "legacy default", wantCode: 0},
+ {name: "copy", databaseMode: "copy", includeMode: true, wantCode: 0},
+ {name: "reference", databaseMode: "reference", includeMode: true, wantCode: 0},
+ {name: "unknown", databaseMode: "unknown", includeMode: true, wantCode: -1},
+ {name: "invalid type", databaseMode: true, includeMode: true, wantCode: -1},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ arg := map[string]any{
+ "id": "20260904000999-api0001", "name": "template", "overwrite": false,
+ }
+ if test.includeMode {
+ arg["databaseMode"] = test.databaseMode
+ }
+ body, err := json.Marshal(arg)
+ if nil != err {
+ t.Fatal(err)
+ }
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodPost, "/api/template/docSaveAsTemplate", bytes.NewReader(body))
+ context.Request.Header.Set("Content-Type", "application/json")
+ docSaveAsTemplate(context)
+
+ response := &struct {
+ Code int `json:"code"`
+ }{}
+ if err = json.Unmarshal(recorder.Body.Bytes(), response); nil != err {
+ t.Fatal(err)
+ }
+ if test.wantCode != response.Code {
+ t.Fatalf("unexpected response code: got %d, want %d", response.Code, test.wantCode)
+ }
+ })
+ }
+}
diff --git a/kernel/api/transaction.go b/kernel/api/transaction.go
index c07900bda1..3873ea9960 100644
--- a/kernel/api/transaction.go
+++ b/kernel/api/transaction.go
@@ -136,7 +136,15 @@ func holdTransactionEncryptedBoxRequests(c *gin.Context, transactions []*model.T
if blockID == "" {
return
}
- if block := treenode.GetBlockTree(blockID); block != nil {
+ block := treenode.GetBlockTree(blockID)
+ if nil == block {
+ for _, encryptedBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if block = treenode.GetBlockTreeInBox(blockID, encryptedBoxID); nil != block {
+ break
+ }
+ }
+ }
+ if nil != block {
addBoxID(block.BoxID)
return
}
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 723cbc0c94..0f60f60883 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -1338,10 +1338,11 @@ var (
)
const (
- NodeAttrNameAvs = "custom-avs" // 用于标记块所属的属性视图,逗号分隔 av id
- NodeAttrView = "custom-sy-av-view" // 用于标记块所属的属性视图视图 view id Database block support specified view https://github.com/siyuan-note/siyuan/issues/10443
- NodeAttrVisibleViewIDs = "custom-sy-av-visible-views" // 用于标记数据库块显示的视图 ID,逗号分隔
- NodeAttrViewStaticText = "custom-sy-av-s-text" // 用于标记块所属的属性视图静态文本 Database-bound block primary key supports setting static anchor text https://github.com/siyuan-note/siyuan/issues/10049
+ NodeAttrNameAvs = "custom-avs" // 用于标记块所属的属性视图,逗号分隔 av id
+ NodeAttrView = "custom-sy-av-view" // 用于标记块所属的属性视图视图 view id Database block support specified view https://github.com/siyuan-note/siyuan/issues/10443
+ NodeAttrVisibleViewIDs = "custom-sy-av-visible-views" // 用于标记数据库块显示的视图 ID,逗号分隔
+ NodeAttrContextFilter = "custom-sy-av-context-filter" // 用于保存数据库块独有的上下文筛选配置
+ NodeAttrViewStaticText = "custom-sy-av-s-text" // 用于标记块所属的属性视图静态文本 Database-bound block primary key supports setting static anchor text https://github.com/siyuan-note/siyuan/issues/10049
NodeAttrViewNames = "av-names" // 用于临时标记块所属的属性视图名称,空格分隔
)
diff --git a/kernel/av/context_filter.go b/kernel/av/context_filter.go
new file mode 100644
index 0000000000..634cbe1822
--- /dev/null
+++ b/kernel/av/context_filter.go
@@ -0,0 +1,137 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package av
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+const AttributeViewContextFilterSpec = 1
+
+var (
+ ErrInvalidAttributeViewContextFilter = errors.New("invalid attribute view context filter")
+ ErrAttributeViewContextNotBound = errors.New("current document is not bound to the context filter target database")
+)
+
+// AttributeViewContextFilter 描述物理数据库块独有的上下文筛选配置。
+type AttributeViewContextFilter struct {
+ Spec int `json:"spec"`
+ KeyID string `json:"keyID"`
+}
+
+// AttributeViewContextFilterField 描述可用于物理数据库块上下文筛选的关联字段。
+type AttributeViewContextFilterField struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Icon string `json:"icon"`
+ TargetAvID string `json:"targetAvID"`
+}
+
+// FilterContext 保存一次数据库块渲染所需的上下文筛选值,不参与持久化。
+type FilterContext struct {
+ KeyID string
+ CurrentDocumentItemIDs []string
+}
+
+// ParseAttributeViewContextFilter 从数据库块 IAL 中解析上下文筛选配置。
+func ParseAttributeViewContextFilter(data string) (ret *AttributeViewContextFilter, err error) {
+ data = strings.TrimSpace(data)
+ if "" == data {
+ return
+ }
+
+ decoder := json.NewDecoder(bytes.NewBufferString(data))
+ decoder.DisallowUnknownFields()
+ ret = &AttributeViewContextFilter{}
+ if err = decoder.Decode(ret); nil != err {
+ err = fmt.Errorf("%w: %v", ErrInvalidAttributeViewContextFilter, err)
+ ret = nil
+ return
+ }
+ if err = ensureAttributeViewContextFilterJSONEOF(decoder); nil != err {
+ ret = nil
+ return
+ }
+ if AttributeViewContextFilterSpec != ret.Spec || "" == strings.TrimSpace(ret.KeyID) {
+ err = ErrInvalidAttributeViewContextFilter
+ ret = nil
+ }
+ return
+}
+
+func ensureAttributeViewContextFilterJSONEOF(decoder *json.Decoder) error {
+ var trailing any
+ err := decoder.Decode(&trailing)
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if nil == err {
+ return ErrInvalidAttributeViewContextFilter
+ }
+ return fmt.Errorf("%w: %v", ErrInvalidAttributeViewContextFilter, err)
+}
+
+// Validate 校验上下文筛选引用的是当前数据库中的有效关联字段。
+func (filter *AttributeViewContextFilter) Validate(attrView *AttributeView) error {
+ if nil == filter || AttributeViewContextFilterSpec != filter.Spec || nil == attrView {
+ return ErrInvalidAttributeViewContextFilter
+ }
+ key, err := attrView.GetKey(filter.KeyID)
+ if nil != err || nil == key || KeyTypeRelation != key.Type || nil == key.Relation ||
+ "" == strings.TrimSpace(key.Relation.AvID) {
+ return ErrInvalidAttributeViewContextFilter
+ }
+ return nil
+}
+
+// Marshal 返回适合写入数据库块 IAL 的紧凑 JSON。
+func (filter *AttributeViewContextFilter) Marshal() (string, error) {
+ if nil == filter {
+ return "", nil
+ }
+ data, err := json.Marshal(filter)
+ if nil != err {
+ return "", err
+ }
+ return string(data), nil
+}
+
+// ContextFilterFields 返回整个数据库中可用于上下文筛选的关联字段,不受当前视图布局限制。
+func (av *AttributeView) ContextFilterFields() (ret []*AttributeViewContextFilterField) {
+ ret = []*AttributeViewContextFilterField{}
+ if nil == av {
+ return
+ }
+ for _, keyValues := range av.KeyValues {
+ if nil == keyValues || nil == keyValues.Key {
+ continue
+ }
+ key := keyValues.Key
+ if KeyTypeRelation != key.Type || nil == key.Relation || "" == strings.TrimSpace(key.Relation.AvID) {
+ continue
+ }
+ ret = append(ret, &AttributeViewContextFilterField{
+ ID: key.ID, Name: key.Name, Icon: key.Icon, TargetAvID: key.Relation.AvID,
+ })
+ }
+ return
+}
diff --git a/kernel/av/context_filter_test.go b/kernel/av/context_filter_test.go
new file mode 100644
index 0000000000..c8c09910d0
--- /dev/null
+++ b/kernel/av/context_filter_test.go
@@ -0,0 +1,250 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package av
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestAttributeViewContextFilterJSON(t *testing.T) {
+ filter := &AttributeViewContextFilter{
+ Spec: AttributeViewContextFilterSpec,
+ KeyID: "relation-key",
+ }
+ data, err := json.Marshal(filter)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if got, want := string(data), `{"spec":1,"keyID":"relation-key"}`; got != want {
+ t.Fatalf("unexpected context filter JSON: got %s, want %s", got, want)
+ }
+
+ parsed, err := ParseAttributeViewContextFilter(string(data))
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == parsed || AttributeViewContextFilterSpec != parsed.Spec || "relation-key" != parsed.KeyID {
+ t.Fatalf("unexpected parsed context filter: %#v", parsed)
+ }
+}
+
+func TestParseAttributeViewContextFilter(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ wantNil bool
+ wantErr bool
+ }{
+ {name: "missing", wantNil: true},
+ {name: "malformed", raw: `{`, wantNil: true, wantErr: true},
+ {name: "missing spec", raw: `{"keyID":"relation-key"}`, wantNil: true, wantErr: true},
+ {name: "unknown spec", raw: `{"spec":2,"keyID":"relation-key"}`, wantNil: true, wantErr: true},
+ {name: "current spec", raw: `{"spec":1,"keyID":"relation-key"}`},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ filter, err := ParseAttributeViewContextFilter(test.raw)
+ if test.wantErr != (nil != err) {
+ t.Fatalf("unexpected error state: %v", err)
+ }
+ if test.wantNil != (nil == filter) {
+ t.Fatalf("unexpected parsed context filter: %#v", filter)
+ }
+ })
+ }
+}
+
+func TestAttributeViewContextFilterValidate(t *testing.T) {
+ attrView := &AttributeView{KeyValues: []*KeyValues{
+ {Key: &Key{ID: "relation-key", Type: KeyTypeRelation, Relation: &Relation{AvID: "target-av"}}},
+ {Key: &Key{ID: "text-key", Type: KeyTypeText}},
+ {Key: &Key{ID: "unconfigured-relation-key", Type: KeyTypeRelation}},
+ {Key: &Key{ID: "empty-target-relation-key", Type: KeyTypeRelation, Relation: &Relation{}}},
+ }}
+ tests := []struct {
+ name string
+ filter *AttributeViewContextFilter
+ attrView *AttributeView
+ wantErr bool
+ }{
+ {
+ name: "valid relation",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "relation-key"},
+ attrView: attrView,
+ },
+ {
+ name: "nil attribute view",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "relation-key"},
+ wantErr: true,
+ },
+ {
+ name: "unknown spec",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec + 1, KeyID: "relation-key"},
+ attrView: attrView,
+ wantErr: true,
+ },
+ {
+ name: "missing key ID",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec},
+ attrView: attrView,
+ wantErr: true,
+ },
+ {
+ name: "unknown key",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "missing-key"},
+ attrView: attrView,
+ wantErr: true,
+ },
+ {
+ name: "non relation key",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "text-key"},
+ attrView: attrView,
+ wantErr: true,
+ },
+ {
+ name: "relation without configuration",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "unconfigured-relation-key"},
+ attrView: attrView,
+ wantErr: true,
+ },
+ {
+ name: "relation without target",
+ filter: &AttributeViewContextFilter{Spec: AttributeViewContextFilterSpec, KeyID: "empty-target-relation-key"},
+ attrView: attrView,
+ wantErr: true,
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ err := test.filter.Validate(test.attrView)
+ if test.wantErr != (nil != err) {
+ t.Fatalf("unexpected validation result: %v", err)
+ }
+ })
+ }
+}
+
+func TestFilterWithContext(t *testing.T) {
+ relationKey := &Key{ID: "relation", Type: KeyTypeRelation, Relation: &Relation{AvID: "projects"}}
+ textKey := &Key{ID: "status", Type: KeyTypeText}
+ attrView := &AttributeView{KeyValues: []*KeyValues{
+ {
+ Key: relationKey,
+ Values: []*Value{
+ contextFilterRelationValue(relationKey.ID, "alpha-open", "project-alpha"),
+ contextFilterRelationValue(relationKey.ID, "alpha-closed", "project-alpha"),
+ contextFilterRelationValue(relationKey.ID, "beta-open", "project-beta"),
+ },
+ },
+ {Key: textKey},
+ }}
+ context := &FilterContext{KeyID: relationKey.ID, CurrentDocumentItemIDs: []string{"project-alpha"}}
+
+ t.Run("without view filter and without relation layout field", func(t *testing.T) {
+ table := contextFilterTable(nil, textKey)
+ FilterWithContext(table, attrView, nil, nil, context)
+ assertContextFilterItemIDs(t, table, "alpha-open", "alpha-closed")
+ })
+
+ t.Run("combined with view filter using AND", func(t *testing.T) {
+ filters := []*ViewFilter{{
+ Combination: FilterCombinationAnd,
+ Filters: []*ViewFilter{{
+ Column: textKey.ID, Operator: FilterOperatorIsEqual,
+ Value: &Value{Type: KeyTypeText, Text: &ValueText{Content: "open"}},
+ }},
+ }}
+ table := contextFilterTable(filters, textKey)
+ FilterWithContext(table, attrView, nil, nil, context)
+ assertContextFilterItemIDs(t, table, "alpha-open")
+ })
+
+ t.Run("empty current document items", func(t *testing.T) {
+ table := contextFilterTable(nil, textKey)
+ FilterWithContext(table, attrView, nil, nil, &FilterContext{KeyID: relationKey.ID})
+ assertContextFilterItemIDs(t, table)
+ })
+}
+
+func TestAttributeViewContextFilterFields(t *testing.T) {
+ attrView := &AttributeView{KeyValues: []*KeyValues{
+ nil,
+ {},
+ {Key: &Key{ID: "text", Name: "Text", Type: KeyTypeText}},
+ {Key: &Key{ID: "nil-relation", Name: "Nil relation", Type: KeyTypeRelation}},
+ {Key: &Key{ID: "empty-target", Name: "Empty target", Type: KeyTypeRelation, Relation: &Relation{}}},
+ {Key: &Key{
+ ID: "project", Name: "Project", Icon: "1f4c1", Type: KeyTypeRelation,
+ Relation: &Relation{AvID: "projects"},
+ }},
+ }}
+
+ fields := attrView.ContextFilterFields()
+ if 1 != len(fields) {
+ t.Fatalf("unexpected context filter fields: %#v", fields)
+ }
+ field := fields[0]
+ if nil == field || "project" != field.ID || "Project" != field.Name || "1f4c1" != field.Icon ||
+ "projects" != field.TargetAvID {
+ t.Fatalf("unexpected context filter field: %#v", field)
+ }
+ if fields := (*AttributeView)(nil).ContextFilterFields(); nil == fields || 0 != len(fields) {
+ t.Fatalf("nil attribute view should return a non-nil empty field list: %#v", fields)
+ }
+}
+
+func contextFilterRelationValue(keyID, blockID, relationItemID string) *Value {
+ return &Value{
+ KeyID: keyID, BlockID: blockID, Type: KeyTypeRelation,
+ Relation: &ValueRelation{BlockIDs: []string{relationItemID}},
+ }
+}
+
+func contextFilterTable(filters []*ViewFilter, textKey *Key) *Table {
+ view := &View{ID: "view", LayoutType: LayoutTypeTable, Filters: filters, Table: NewLayoutTable()}
+ return &Table{
+ BaseInstance: NewViewBaseInstance(view),
+ // 上下文关联字段有意不放入视图列,验证隐藏字段仍可参与筛选。
+ Columns: []*TableColumn{{BaseInstanceField: &BaseInstanceField{ID: textKey.ID, Type: textKey.Type}}},
+ Rows: []*TableRow{
+ contextFilterTableRow("alpha-open", textKey.ID, "open"),
+ contextFilterTableRow("alpha-closed", textKey.ID, "closed"),
+ contextFilterTableRow("beta-open", textKey.ID, "open"),
+ },
+ }
+}
+
+func contextFilterTableRow(id, keyID, content string) *TableRow {
+ return &TableRow{ID: id, Cells: []*TableCell{{BaseValue: &BaseValue{
+ ValueType: KeyTypeText,
+ Value: &Value{KeyID: keyID, BlockID: id, Type: KeyTypeText, Text: &ValueText{Content: content}},
+ }}}}
+}
+
+func assertContextFilterItemIDs(t *testing.T, table *Table, expected ...string) {
+ t.Helper()
+ items := table.GetItems()
+ if len(expected) != len(items) {
+ t.Fatalf("unexpected item count: got %d, want %d", len(items), len(expected))
+ }
+ for i, item := range items {
+ if expected[i] != item.GetID() {
+ t.Fatalf("unexpected item at %d: got %s, want %s", i, item.GetID(), expected[i])
+ }
+ }
+}
diff --git a/kernel/av/filter.go b/kernel/av/filter.go
index 54db8907b5..238323c2ce 100644
--- a/kernel/av/filter.go
+++ b/kernel/av/filter.go
@@ -112,28 +112,79 @@ const (
func Filter(viewable Viewable, attrView *AttributeView, rollupFurtherCollections map[string]*RollupRenderContext,
cachedAttrViews map[string]*AttributeView) {
+ FilterWithContext(viewable, attrView, rollupFurtherCollections, cachedAttrViews, nil)
+}
+
+// FilterWithContext 使用一次渲染请求的上下文过滤视图数据。
+func FilterWithContext(viewable Viewable, attrView *AttributeView, rollupFurtherCollections map[string]*RollupRenderContext,
+ cachedAttrViews map[string]*AttributeView, context *FilterContext) {
collection := viewable.(Collection)
filters := collection.GetFilters()
- if 1 > len(filters) {
- return
+ if 0 < len(filters) {
+ // 归一化为单一根组:spec 5 起顶层应为一个根组;旧数据/异常数据为扁平叶子数组时,
+ // 在内存里包成隐式 AND 根组参与求值,不修改原数据、不崩溃。
+ root := normalizeFiltersAsRoot(filters)
+ if nil != root {
+ // 递归收集所有叶子引用的列 ID 在 values 中的下标,避免每行重复查找。
+ fields := collection.GetFields()
+ colIndexByColumn := map[string]int{}
+ collectLeafColumnIndexes([]*ViewFilter{root}, fields, colIndexByColumn)
+
+ var items []Item
+ for _, item := range collection.GetItems() {
+ values := item.GetValues()
+ if evalNode(root, values, colIndexByColumn, attrView, item.GetID(), rollupFurtherCollections,
+ cachedAttrViews) {
+ items = append(items, item)
+ }
+ }
+ collection.SetItems(items)
+ }
}
- // 归一化为单一根组:spec 5 起顶层应为一个根组;旧数据/异常数据为扁平叶子数组时,
- // 在内存里包成隐式 AND 根组参与求值,不修改原数据、不崩溃。
- root := normalizeFiltersAsRoot(filters)
- if nil == root {
+ filterByContext(collection, attrView, rollupFurtherCollections, cachedAttrViews, context)
+}
+
+// filterByContext 将物理数据库块的上下文筛选与当前视图筛选按 AND 组合。
+func filterByContext(collection Collection, attrView *AttributeView,
+ rollupFurtherCollections map[string]*RollupRenderContext, cachedAttrViews map[string]*AttributeView,
+ context *FilterContext) {
+ if nil == context || "" == context.KeyID {
+ return
+ }
+ if nil == attrView || 1 > len(context.CurrentDocumentItemIDs) {
+ collection.SetItems(nil)
+ return
+ }
+ keyValues, err := attrView.GetKeyValues(context.KeyID)
+ if nil != err || nil == keyValues {
+ collection.SetItems(nil)
return
}
- // 递归收集所有叶子引用的列 ID 在 values 中的下标,避免每行重复查找。
- fields := collection.GetFields()
- colIndexByColumn := map[string]int{}
- collectLeafColumnIndexes([]*ViewFilter{root}, fields, colIndexByColumn)
-
+ filter := &ViewFilter{
+ Column: context.KeyID,
+ Operator: FilterOperatorContainsAnyItem,
+ Value: &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{
+ BlockIDs: context.CurrentDocumentItemIDs,
+ },
+ },
+ }
+ valuesByItemID := make(map[string]*Value, len(keyValues.Values))
+ for _, value := range keyValues.Values {
+ if nil == value {
+ continue
+ }
+ if _, exists := valuesByItemID[value.BlockID]; !exists {
+ valuesByItemID[value.BlockID] = value
+ }
+ }
var items []Item
for _, item := range collection.GetItems() {
- values := item.GetValues()
- if evalNode(root, values, colIndexByColumn, attrView, item.GetID(), rollupFurtherCollections, cachedAttrViews) {
+ value := valuesByItemID[item.GetID()]
+ if nil != value && value.Filter(filter, attrView, item.GetID(), rollupFurtherCollections, cachedAttrViews) {
items = append(items, item)
}
}
@@ -319,15 +370,23 @@ func CloneFilters(filters []*ViewFilter) (ret []*ViewFilter) {
continue
}
cloned := &ViewFilter{
- Column: f.Column,
- ValueSource: f.ValueSource,
- Qualifier: f.Qualifier,
- Operator: f.Operator,
- Value: f.Value,
- RelativeDate: f.RelativeDate,
- RelativeDate2: f.RelativeDate2,
- DateEndpoint: f.DateEndpoint,
- Combination: f.Combination,
+ Column: f.Column,
+ ValueSource: f.ValueSource,
+ Qualifier: f.Qualifier,
+ Operator: f.Operator,
+ DateEndpoint: f.DateEndpoint,
+ Combination: f.Combination,
+ }
+ if nil != f.Value {
+ cloned.Value = f.Value.Clone()
+ }
+ if nil != f.RelativeDate {
+ relativeDate := *f.RelativeDate
+ cloned.RelativeDate = &relativeDate
+ }
+ if nil != f.RelativeDate2 {
+ relativeDate := *f.RelativeDate2
+ cloned.RelativeDate2 = &relativeDate
}
if 0 < len(f.Filters) {
cloned.Filters = CloneFilters(f.Filters)
diff --git a/kernel/av/filter_test.go b/kernel/av/filter_test.go
index 360a4cdd8e..3df2a2209c 100644
--- a/kernel/av/filter_test.go
+++ b/kernel/av/filter_test.go
@@ -672,6 +672,7 @@ func TestRemoveExactRelationFiltersByColumn(t *testing.T) {
if !changed || 1 != len(got) || 1 != len(got[0].Filters) || got[0].Filters[0] != keyword {
t.Fatalf("only exact filters for the retargeted relation column should be removed")
}
+
}
func TestAttributeViewRemoveRelationFilterItems(t *testing.T) {
@@ -736,6 +737,8 @@ func TestCloneFilters(t *testing.T) {
endpointLeaf := leaf("c1")
endpointLeaf.DateEndpoint = DateEndpointEnd
endpointLeaf.ValueSource = ValueSourceRendered
+ endpointLeaf.Value.Text = &ValueText{Content: "original"}
+ endpointLeaf.RelativeDate = &RelativeDate{Count: 1, Unit: RelativeDateUnitDay}
original := []*ViewFilter{group(FilterCombinationAnd, endpointLeaf, group(FilterCombinationOr, leaf("c2")))}
cloned := CloneFilters(original)
if len(cloned) != len(original) {
@@ -756,6 +759,11 @@ func TestCloneFilters(t *testing.T) {
if ValueSourceRendered != cloned[0].Filters[0].ValueSource {
t.Fatalf("value source not cloned")
}
+ cloned[0].Filters[0].Value.Text.Content = "changed"
+ cloned[0].Filters[0].RelativeDate.Count = 2
+ if "original" != original[0].Filters[0].Value.Text.Content || 1 != original[0].Filters[0].RelativeDate.Count {
+ t.Fatal("filter values and relative dates should be deeply cloned")
+ }
}
func TestFilterByRenderedValue(t *testing.T) {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 61ccdd09df..e0682389e7 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -334,7 +334,7 @@ func GetAttributeViewBoundBlockIDs(avID string, itemIDs []string) (ret map[strin
func GetAttrViewAddingBlockDefaultValues(avID, blockID, viewID, groupID, previousBlockID, addingBlockID string) (ret map[string]*av.Value, err error) {
ret = map[string]*av.Value{}
- attrView, err := av.ParseAttributeView(avID)
+ attrView, err := avParseView(avID, blockID)
if err != nil {
logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
return
@@ -345,9 +345,18 @@ func GetAttrViewAddingBlockDefaultValues(avID, blockID, viewID, groupID, previou
logging.LogErrorf("view [%s] not found in attribute view [%s]", viewID, avID)
return
}
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, blockID)
+ if nil != contextErr {
+ err = contextErr
+ return
+ }
+ if nil != filterContext && 1 > len(filterContext.CurrentDocumentItemIDs) {
+ err = av.ErrAttributeViewContextNotBound
+ return
+ }
useGroupDefault := "" != groupID
- if 1 > len(view.Filters) && !useGroupDefault {
+ if 1 > len(view.Filters) && !useGroupDefault && nil == filterContext {
// 没有过滤条件也没有分组条件时忽略
return
}
@@ -361,7 +370,8 @@ func GetAttrViewAddingBlockDefaultValues(avID, blockID, viewID, groupID, previou
return
}
- ret = getAttrViewAddingBlockDefaultValues(attrView, view, groupView, previousBlockID, addingBlockID, true, useGroupDefault)
+ ret = getAttrViewAddingBlockDefaultValues(attrView, view, groupView, previousBlockID, addingBlockID, true,
+ useGroupDefault, filterContext)
for _, value := range ret {
// 主键都不返回内容,避免闪烁 https://github.com/siyuan-note/siyuan/issues/15561#issuecomment-3184746195
if av.KeyTypeBlock == value.Type {
@@ -380,9 +390,12 @@ func newAttrViewValueSelect(option *av.SelectOption) *av.ValueSelect {
return ret
}
-func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, groupView *av.View, previousItemID, addingItemID string, isCreate, useGroupDefault bool) (ret map[string]*av.Value) {
+func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, groupView *av.View, previousItemID,
+ addingItemID string, isCreate, useGroupDefault bool, filterContexts ...*av.FilterContext) (ret map[string]*av.Value) {
ret = map[string]*av.Value{}
+ filterContext := firstAttributeViewFilterContext(filterContexts)
defer func() {
+ applyAttributeViewContextFilterDefaultValue(attrView, addingItemID, filterContext, ret)
for keyID, value := range ret {
key, _ := attrView.GetKey(keyID)
normalizeAttrViewAddingDefaultValue(key, value)
@@ -390,12 +403,12 @@ func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, group
}
}()
- if 1 > len(view.Filters) && !useGroupDefault {
+ if 1 > len(view.Filters) && !useGroupDefault && nil == filterContext {
// 没有过滤条件也没有分组条件时忽略
return
}
- nearItem := getNearItem(attrView, view, groupView, previousItemID)
+ nearItem := getNearItem(attrView, view, groupView, previousItemID, filterContext)
// 使用模板或汇总进行过滤或分组时,需要解析涉及到的其他字段
templateRelevantKeys, rollupRelevantKeys := map[string][]*av.Key{}, map[string]*av.Key{}
@@ -421,7 +434,8 @@ func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, group
}
filterKeyIDs := map[string]bool{}
- if applyFilterDefaultValues(view.Filters, attrView, addingItemID, nearItem, templateRelevantKeys, rollupRelevantKeys, ret, filterKeyIDs) {
+ if applyFilterDefaultValues(view.Filters, attrView, addingItemID, nearItem, templateRelevantKeys, rollupRelevantKeys,
+ ret, filterKeyIDs) {
// 遇到 mAsset 过滤即结束全部默认值计算(保留原外层 return 语义)
return
}
@@ -588,6 +602,13 @@ func normalizeAttrViewAddingDefaultValue(key *av.Key, value *av.Value) {
}
}
+func firstAttributeViewFilterContext(contexts []*av.FilterContext) *av.FilterContext {
+ if 0 < len(contexts) {
+ return contexts[0]
+ }
+ return nil
+}
+
// applyFilterDefaultValues 递归遍历过滤节点树,对叶子节点计算新增行的默认值。
// AND 分组合并后验证所有子节点,OR 分组采用首个可满足的分支;无法满足时不生成默认值。
// 返回 true 表示遇到 mAsset 过滤,调用方应立即结束全部默认值计算(保留原外层 return 语义)。
@@ -596,7 +617,8 @@ func applyFilterDefaultValues(filters []*av.ViewFilter, attrView *av.AttributeVi
ret map[string]*av.Value, filterKeyIDs map[string]bool) (stop bool) {
originalRet := cloneDefaultValues(ret)
originalFilterKeyIDs := cloneBoolMap(filterKeyIDs)
- if applyFilterDefaultValues0(filters, attrView, addingItemID, nearItem, templateRelevantKeys, rollupRelevantKeys, ret, filterKeyIDs) {
+ if applyFilterDefaultValues0(filters, attrView, addingItemID, nearItem, templateRelevantKeys, rollupRelevantKeys,
+ ret, filterKeyIDs) {
return true
}
if !filterBranchesMatchDefaultValues(filters, attrView, addingItemID, ret) {
@@ -631,7 +653,8 @@ func applyFilterDefaultValues0(filters []*av.ViewFilter, attrView *av.AttributeV
}
continue
}
- if applyFilterDefaultValues(filter.Filters, attrView, addingItemID, nearItem, templateRelevantKeys, rollupRelevantKeys, ret, filterKeyIDs) {
+ if applyFilterDefaultValues(filter.Filters, attrView, addingItemID, nearItem, templateRelevantKeys,
+ rollupRelevantKeys, ret, filterKeyIDs) {
return true
}
continue
@@ -760,6 +783,49 @@ func filterBranchMatchesDefaultValues(filter *av.ViewFilter, attrView *av.Attrib
return value.Filter(filter, attrView, addingItemID, nil, nil)
}
+func applyAttributeViewContextFilterDefaultValue(attrView *av.AttributeView, addingItemID string,
+ context *av.FilterContext, values map[string]*av.Value) {
+ if nil == attrView || nil == context || "" == context.KeyID || 1 > len(context.CurrentDocumentItemIDs) {
+ return
+ }
+ keyValues, err := attrView.GetKeyValues(context.KeyID)
+ if nil != err || nil == keyValues || nil == keyValues.Key || av.KeyTypeRelation != keyValues.Key.Type {
+ return
+ }
+
+ value := values[context.KeyID]
+ if nil == value {
+ if existing := keyValues.GetValue(addingItemID); nil != existing {
+ value = existing.Clone()
+ }
+ }
+ if nil == value {
+ value = av.GetAttributeViewDefaultValue(ast.NewNodeID(), context.KeyID, addingItemID,
+ av.KeyTypeRelation, false)
+ }
+ if nil == value.Relation {
+ value.Relation = &av.ValueRelation{}
+ }
+ seen := map[string]bool{}
+ blockIDs := value.Relation.BlockIDs[:0]
+ for _, itemID := range value.Relation.BlockIDs {
+ if "" == itemID || seen[itemID] {
+ continue
+ }
+ seen[itemID] = true
+ blockIDs = append(blockIDs, itemID)
+ }
+ value.Relation.BlockIDs = blockIDs
+ for _, itemID := range context.CurrentDocumentItemIDs {
+ if "" == itemID || seen[itemID] {
+ continue
+ }
+ seen[itemID] = true
+ value.Relation.BlockIDs = append(value.Relation.BlockIDs, itemID)
+ }
+ values[context.KeyID] = value
+}
+
func replaceDefaultValues(target, source map[string]*av.Value) {
clear(target)
for key, value := range source {
@@ -4102,24 +4168,29 @@ func setAttrViewGroupStates(view *av.View, groupStates map[string]*GroupState) {
}
}
-func GetCurrentAttributeViewImages(c *gin.Context, avID, viewID, query string) (ret []string, err error) {
+func GetCurrentAttributeViewImages(c *gin.Context, avID, blockID, viewID, query string) (ret []string, err error) {
var attrView *av.AttributeView
- attrView, err = av.ParseAttributeView(avID)
+ attrView, err = avParseView(avID, blockID)
if err != nil {
logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
return
}
var view *av.View
- view, err = resolveAttributeViewView(attrView, viewID, "", "")
+ view, err = resolveAttributeViewView(attrView, viewID, "", blockID)
if nil != err {
return
}
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, blockID)
+ if nil != contextErr {
+ err = contextErr
+ return
+ }
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollections(attrView, cachedAttrViews)
table := getAttrViewTable(attrView, view, query)
- av.Filter(table, attrView, rollupFurtherCollections, cachedAttrViews)
+ av.FilterWithContext(table, attrView, rollupFurtherCollections, cachedAttrViews, filterContext)
av.Sort(table, attrView)
if IsReadOnlyRoleContext(c) {
table = FilterViewByPublishAccess(c, GetPublishAccess(), table).(*av.Table)
@@ -5347,10 +5418,14 @@ func (tx *Transaction) doSetAttrViewColRollupFilters(operation *Operation) (ret
return
}
-// avParseView 根据 blockID 推导 box 上下文,使用 box-aware 或全局 AV 解析。
+// avParseView 根据 blockID 推导 AV 的精确加密边界。
func avParseView(avID, blockID string) (*av.AttributeView, error) {
- boxID := deriveAVBoxID(blockID)
- if boxID != "" {
+ boxID, exact, err := resolveAttributeViewCarrierBoxID(blockID)
+ if nil != err {
+ return nil, err
+ }
+ if exact {
+ av.SetAVBoxID(avID, boxID)
return av.ParseAttributeViewInBox(avID, boxID)
}
return av.ParseAttributeView(avID)
@@ -5358,34 +5433,200 @@ func avParseView(avID, blockID string) (*av.AttributeView, error) {
// avSaveView 根据 blockID 推导 box 上下文,使用 box-aware 或全局 AV 保存。
func avSaveView(attrView *av.AttributeView, blockID string) error {
- boxID := deriveAVBoxID(blockID)
- if boxID != "" {
- _, parseErr := av.ParseAttributeViewInBox(attrView.ID, boxID)
- if parseErr == nil {
- return av.SaveAttributeView(attrView)
- }
+ boxID, exact, err := resolveAttributeViewCarrierBoxID(blockID)
+ if nil != err {
+ return err
+ }
+ if exact {
+ av.SetAVBoxID(attrView.ID, boxID)
}
return av.SaveAttributeView(attrView)
}
-// deriveAVBoxID 通过 blockID 反查所在 box。blockID 为空或不是加密 box 时返回空串。
-func deriveAVBoxID(blockID string) string {
- if blockID == "" {
- return ""
+// GetAttributeViewContextFilter 读取物理数据库块独有的上下文筛选配置。
+func GetAttributeViewContextFilter(attrView *av.AttributeView,
+ blockID string) (ret *av.AttributeViewContextFilter, err error) {
+ if nil == attrView || "" == blockID {
+ return
}
- bt := treenode.GetBlockTree(blockID)
- if bt == nil {
- for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
- if encBT := treenode.GetBlockTreeInBox(blockID, encBoxID); encBT != nil {
- bt = encBT
- break
+ node, _, err := getNodeByBlockID(nil, blockID)
+ if nil != err {
+ return nil, err
+ }
+ // 普通内容块的数据库属性面板也会以内容块 ID 渲染属性视图,此时不存在块级上下文筛选。
+ if nil == node || ast.NodeAttributeView != node.Type {
+ return nil, nil
+ }
+ if node.AttributeViewID != attrView.ID {
+ return nil, fmt.Errorf("block [%s] is not an instance of attribute view [%s]", blockID, attrView.ID)
+ }
+ ret, err = av.ParseAttributeViewContextFilter(node.IALAttr(av.NodeAttrContextFilter))
+ if nil != err {
+ return nil, fmt.Errorf("parse attribute view context filter: %w", err)
+ }
+ return
+}
+
+func getAttributeViewInstanceNode(attrView *av.AttributeView,
+ blockID string) (node *ast.Node, tree *parse.Tree, err error) {
+ if nil == attrView || "" == blockID {
+ return nil, nil, av.ErrAttributeViewNotFound
+ }
+ node, tree, err = getNodeByBlockID(nil, blockID)
+ if nil != err {
+ return
+ }
+ if nil == node || nil == tree || ast.NodeAttributeView != node.Type || node.AttributeViewID != attrView.ID {
+ return nil, nil, fmt.Errorf("block [%s] is not an instance of attribute view [%s]", blockID, attrView.ID)
+ }
+ return
+}
+
+// SetAttributeViewContextFilter 设置物理数据库块独有的上下文筛选配置,keyID 为空时清除。
+func SetAttributeViewContextFilter(blockID, avID, keyID string) (ret *av.AttributeViewContextFilter, err error) {
+ return setAttributeViewContextFilter(nil, blockID, avID, keyID)
+}
+
+func setAttributeViewContextFilter(tx *Transaction, blockID, avID,
+ keyID string) (ret *av.AttributeViewContextFilter, err error) {
+ attrView, err := avParseView(avID, blockID)
+ if nil != err {
+ return nil, err
+ }
+ node, tree, err := getAttributeViewInstanceNode(attrView, blockID)
+ if nil != err {
+ return nil, err
+ }
+
+ var value string
+ keyID = strings.TrimSpace(keyID)
+ if "" != keyID {
+ ret = &av.AttributeViewContextFilter{Spec: av.AttributeViewContextFilterSpec, KeyID: keyID}
+ // undo/redo 重放需要能恢复字段删除或改型后留下的旧配置;普通事务和公开 API 仍严格校验。
+ if nil == tx || !tx.isReplay {
+ if err = ret.Validate(attrView); nil != err {
+ return nil, err
+ }
+ if _, err = resolveAttributeViewContextFilterTarget(attrView, ret, tree.Box); nil != err {
+ return nil, fmt.Errorf("validate attribute view context filter target: %w", err)
}
}
+ if value, err = ret.Marshal(); nil != err {
+ return nil, err
+ }
}
- if bt == nil || !IsEncryptedBox(bt.BoxID) {
- return ""
+ if value == node.IALAttr(av.NodeAttrContextFilter) {
+ return
+ }
+
+ attrs := map[string]string{av.NodeAttrContextFilter: value}
+ if nil != tx {
+ err = setNodeAttrsWithTx(tx, node, tree, attrs)
+ } else {
+ err = setNodeAttrs(node, tree, attrs)
+ }
+ return
+}
+
+func (tx *Transaction) doSetAttrViewContextFilter(operation *Operation) (ret *TxErr) {
+ _, err := setAttributeViewContextFilter(tx, operation.BlockID, operation.AvID, operation.KeyID)
+ if nil != err {
+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
+ }
+ return
+}
+
+// resolveAttributeViewFilterContext 将数据库块所在根文档映射为关联目标数据库的条目 ID。
+func resolveAttributeViewFilterContext(attrView *av.AttributeView, view *av.View,
+ blockID string) (*av.FilterContext, error) {
+ if nil == attrView || "" == blockID {
+ return nil, nil
+ }
+ contextFilter, err := GetAttributeViewContextFilter(attrView, blockID)
+ if nil != err {
+ return nil, err
+ }
+ if nil == contextFilter {
+ return nil, nil
}
- return bt.BoxID
+
+ context := &av.FilterContext{KeyID: contextFilter.KeyID}
+ // 字段删除、改型或关联目标失效时保留块级配置,并以空上下文安全渲染。
+ // 这样撤销字段变更后配置可自动恢复,用户也可在界面中显式禁用。
+ if err = contextFilter.Validate(attrView); nil != err {
+ return context, nil
+ }
+ key, err := attrView.GetKey(contextFilter.KeyID)
+ if nil != err || nil == key || nil == key.Relation {
+ return context, nil
+ }
+ _, tree, err := getAttributeViewInstanceNode(attrView, blockID)
+ if nil != err {
+ return nil, err
+ }
+ targetAttrView, targetErr := resolveAttributeViewContextFilterTarget(attrView, contextFilter, tree.Box)
+ if nil != targetErr {
+ return context, nil
+ }
+ blockValue := targetAttrView.GetBlockValueByBoundID(tree.Root.ID)
+ if nil != blockValue && "" != blockValue.BlockID {
+ context.CurrentDocumentItemIDs = []string{blockValue.BlockID}
+ }
+ return context, nil
+}
+
+func resolveAttributeViewContextFilterTarget(attrView *av.AttributeView, contextFilter *av.AttributeViewContextFilter,
+ carrierBoxID string) (ret *av.AttributeView, err error) {
+ if err = contextFilter.Validate(attrView); nil != err {
+ return nil, err
+ }
+ key, _ := attrView.GetKey(contextFilter.KeyID)
+ if key.Relation.AvID == attrView.ID {
+ return attrView, nil
+ }
+ targetBoxID := ""
+ if IsEncryptedBox(carrierBoxID) {
+ targetBoxID = carrierBoxID
+ }
+ av.SetAVBoxID(key.Relation.AvID, targetBoxID)
+ ret, err = av.ParseAttributeViewInBox(key.Relation.AvID, targetBoxID)
+ if nil != err {
+ return nil, err
+ }
+ if nil == ret {
+ return nil, av.ErrAttributeViewNotFound
+ }
+ return
+}
+
+func getAttributeViewCarrierBlockTree(blockID string) *treenode.BlockTree {
+ if "" == blockID {
+ return nil
+ }
+ blockTree := treenode.GetBlockTree(blockID)
+ if nil != blockTree {
+ return blockTree
+ }
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if blockTree = treenode.GetBlockTreeInBox(blockID, encBoxID); nil != blockTree {
+ return blockTree
+ }
+ }
+ return nil
+}
+
+func resolveAttributeViewCarrierBoxID(blockID string) (boxID string, exact bool, err error) {
+ if "" == blockID {
+ return "", false, nil
+ }
+ blockTree := getAttributeViewCarrierBlockTree(blockID)
+ if nil == blockTree {
+ return "", true, fmt.Errorf("resolve attribute view carrier: block [%s] not found", blockID)
+ }
+ if IsEncryptedBox(blockTree.BoxID) {
+ return blockTree.BoxID, true, nil
+ }
+ return "", true, nil
}
// SetAttrViewFilters 用新的过滤规则数组整体替换指定视图的过滤规则,并持久化。
@@ -5780,7 +6021,7 @@ func addAttributeViewBlocks(tx *Transaction, srcs []map[string]any, avID, dbBloc
return
}
slices.Reverse(srcs) // https://github.com/siyuan-note/siyuan/issues/11286
- attrView, err := av.ParseAttributeView(avID)
+ attrView, err := avParseView(avID, dbBlockID)
if err != nil {
return
}
@@ -5829,7 +6070,7 @@ func addAttributeViewBlocks(tx *Transaction, srcs []map[string]any, avID, dbBloc
}
func addAttributeViewBlock(now int64, avID, dbBlockID, viewID, groupID, previousItemID, addingItemID, addingBoundBlockID, addingBlockContent string, src map[string]any, isDetached, ignoreDefaultFill bool, tree *parse.Tree, tx *Transaction, result *insertAttrViewBlockResult) (err error) {
- attrView, err := av.ParseAttributeView(avID)
+ attrView, err := avParseView(avID, dbBlockID)
if err != nil {
return
}
@@ -5929,8 +6170,23 @@ func addAttributeViewBlock0(attrView *av.AttributeView, now int64, avID, dbBlock
}
useGroupDefault := "" != groupID
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, dbBlockID)
+ if nil != contextErr {
+ return contextErr
+ }
+ if nil != filterContext && 1 > len(filterContext.CurrentDocumentItemIDs) {
+ return av.ErrAttributeViewContextNotBound
+ }
if !ignoreDefaultFill {
- fillDefaultValue(attrView, view, groupView, previousItemID, addingItemID, true, useGroupDefault)
+ if err = fillDefaultValue(attrView, view, groupView, previousItemID, addingItemID, true, useGroupDefault,
+ dbBlockID, filterContext); nil != err {
+ return
+ }
+ } else {
+ if err = fillAttributeViewContextFilterValue(attrView, groupView, addingItemID, filterContext,
+ dbBlockID); nil != err {
+ return
+ }
}
// 处理日期字段默认填充当前创建时间
@@ -6005,8 +6261,25 @@ func fillAttrViewAutoFillNowValues(attrView *av.AttributeView, addingItemID stri
}
}
-func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, previousItemID, addingItemID string, isCreate, useGroupDefault bool) {
- defaultValues := getAttrViewAddingBlockDefaultValues(attrView, view, groupView, previousItemID, addingItemID, isCreate, useGroupDefault)
+func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, previousItemID, addingItemID string,
+ isCreate, useGroupDefault bool, blockID string, filterContexts ...*av.FilterContext) (err error) {
+ filterContext := firstAttributeViewFilterContext(filterContexts)
+ defaultValues := getAttrViewAddingBlockDefaultValues(attrView, view, groupView, previousItemID, addingItemID,
+ isCreate, useGroupDefault, filterContext)
+ err = writeAttributeViewDefaultValues(attrView, groupView, addingItemID, defaultValues, blockID)
+ return
+}
+
+func fillAttributeViewContextFilterValue(attrView *av.AttributeView, groupView *av.View, addingItemID string,
+ filterContext *av.FilterContext, blockID string) (err error) {
+ defaultValues := map[string]*av.Value{}
+ applyAttributeViewContextFilterDefaultValue(attrView, addingItemID, filterContext, defaultValues)
+ err = writeAttributeViewDefaultValues(attrView, groupView, addingItemID, defaultValues, blockID)
+ return
+}
+
+func writeAttributeViewDefaultValues(attrView *av.AttributeView, groupView *av.View, addingItemID string,
+ defaultValues map[string]*av.Value, blockID string) (err error) {
for keyID, newValue := range defaultValues {
newValue.BlockID = addingItemID
keyValues, getErr := attrView.GetKeyValues(keyID)
@@ -6019,7 +6292,8 @@ func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, prev
continue
}
- if (av.KeyTypeSelect == newValue.Type || av.KeyTypeMSelect == newValue.Type) && 1 > len(newValue.MSelect) && groupValueDefault != groupView.GetGroupValue() {
+ if nil != groupView && (av.KeyTypeSelect == newValue.Type || av.KeyTypeMSelect == newValue.Type) &&
+ 1 > len(newValue.MSelect) && groupValueDefault != groupView.GetGroupValue() {
// 单选或多选类型的值可能需要从分组条件中获取默认值
if opt := keyValues.Key.GetOption(groupView.GetGroupValue()); nil != opt {
newValue.MSelect = append(newValue.MSelect, newAttrViewValueSelect(opt))
@@ -6028,7 +6302,10 @@ func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, prev
if av.KeyTypeRelation == newValue.Type && nil != keyValues.Key.Relation && keyValues.Key.Relation.IsTwoWay {
// 双向关联需要同时更新目标字段的值
- updateTwoWayRelationDestAttrView(attrView, keyValues.Key, newValue, 1, []string{})
+ if err = updateTwoWayRelationDestAttrViewInBlock(attrView, keyValues.Key, newValue, 1, []string{},
+ blockID); nil != err {
+ return
+ }
}
existingVal := keyValues.GetValue(addingItemID)
@@ -6044,6 +6321,7 @@ func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, prev
}
}
}
+ return
}
func getNewValueByNearItem(nearItem av.Item, key *av.Key, addingBlockID string) (ret *av.Value) {
@@ -6067,11 +6345,13 @@ func getNewValueByNearItem(nearItem av.Item, key *av.Key, addingBlockID string)
return
}
-func getNearItem(attrView *av.AttributeView, view, groupView *av.View, previousItemID string) (ret av.Item) {
+func getNearItem(attrView *av.AttributeView, view, groupView *av.View, previousItemID string,
+ filterContexts ...*av.FilterContext) (ret av.Item) {
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollections(attrView, cachedAttrViews)
viewable := sql.RenderGroupView(attrView, view, groupView, "")
- av.Filter(viewable, attrView, rollupFurtherCollections, cachedAttrViews)
+ av.FilterWithContext(viewable, attrView, rollupFurtherCollections, cachedAttrViews,
+ firstAttributeViewFilterContext(filterContexts))
av.Sort(viewable, attrView)
items := viewable.(av.Collection).GetItems()
if 0 < len(items) {
@@ -6093,7 +6373,7 @@ func getNearItem(attrView *av.AttributeView, view, groupView *av.View, previousI
}
func (tx *Transaction) doRemoveAttrViewBlock(operation *Operation) (ret *TxErr) {
- err := removeAttributeViewBlock(operation.SrcIDs, operation.AvID, tx)
+ err := removeAttributeViewBlock(operation.SrcIDs, operation.AvID, operation.BlockID, tx)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID}
}
@@ -6101,12 +6381,12 @@ func (tx *Transaction) doRemoveAttrViewBlock(operation *Operation) (ret *TxErr)
}
func RemoveAttributeViewBlock(srcIDs []string, avID string) (err error) {
- err = removeAttributeViewBlock(srcIDs, avID, nil)
+ err = removeAttributeViewBlock(srcIDs, avID, "", nil)
return
}
-func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (err error) {
- attrView, err := av.ParseAttributeView(avID)
+func removeAttributeViewBlock(srcIDs []string, avID, blockID string, tx *Transaction) (err error) {
+ attrView, err := avParseView(avID, blockID)
if err != nil {
return
}
@@ -6130,6 +6410,16 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
if !gulu.Str.Contains(val.BlockID, srcIDs) {
tmp = append(tmp, keyValues.Values[i])
} else {
+ if av.KeyTypeRelation == keyValues.Key.Type && nil != keyValues.Key.Relation &&
+ keyValues.Key.Relation.IsTwoWay && nil != val.Relation && 0 < len(val.Relation.BlockIDs) {
+ clearedValue := val.Clone()
+ oldRelationBlockIDs := append([]string(nil), val.Relation.BlockIDs...)
+ clearedValue.Relation.BlockIDs = nil
+ if err = updateTwoWayRelationDestAttrViewInBlock(attrView, keyValues.Key, clearedValue, 2,
+ oldRelationBlockIDs, blockID); nil != err {
+ return
+ }
+ }
// Remove av block also remove node attr https://github.com/siyuan-note/siyuan/issues/9091#issuecomment-1709824006
if !val.IsDetached && nil != val.Block {
bt := treenode.GetBlockTree(val.Block.ID)
@@ -6175,15 +6465,15 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
regenAttrViewGroups(attrView)
- err = av.SaveAttributeView(attrView)
+ err = avSaveView(attrView, blockID)
if nil != err {
return
}
- if err = removeRelatedRelationItems(avID, srcIDs); nil != err {
+ if err = removeRelatedRelationItems(avID, srcIDs, blockID); nil != err {
return
}
- refreshRelatedSrcAvs(avID, tx)
+ refreshRelatedSrcAvsInBlock(avID, blockID, tx)
for destAvID := range relationDestAvIDs {
if "" != destAvID && destAvID != avID {
ReloadAttrView(destAvID)
@@ -6196,10 +6486,17 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
return
}
blockIDs := treenode.GetMirrorAttrViewBlockIDs(avID)
- for _, blockID := range blockIDs {
- tree := trees[blockID]
+ carrierBoxID, exact, _ := resolveAttributeViewCarrierBoxID(blockID)
+ for _, mirrorBlockID := range blockIDs {
+ if exact {
+ mirrorBoxID, mirrorExact, resolveErr := resolveAttributeViewCarrierBoxID(mirrorBlockID)
+ if nil != resolveErr || !mirrorExact || mirrorBoxID != carrierBoxID {
+ continue
+ }
+ }
+ tree := trees[mirrorBlockID]
if nil == tree {
- tree, _ = LoadTreeByBlockID(blockID)
+ tree, _ = LoadTreeByBlockID(mirrorBlockID)
}
if nil == tree {
continue
@@ -6213,11 +6510,19 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
}
}
- srcAvPath, _ := av.FindAttributeViewPath(avID)
+ var srcAvPath string
+ if exact {
+ srcAvPath, _ = av.FindAttributeViewPathInBox(avID, carrierBoxID)
+ } else {
+ srcAvPath, _ = av.FindAttributeViewPath(avID)
+ }
if srcAvPath == "" {
return
}
destAvPath := filepath.Join(historyDir, "storage", "av", avID+".json")
+ if exact && "" != carrierBoxID {
+ destAvPath = filepath.Join(historyDir, carrierBoxID, "storage", "av", avID+".json")
+ }
if copyErr := filelock.Copy(srcAvPath, destAvPath); nil != copyErr {
logging.LogErrorf("copy av [%s] failed: %s", srcAvPath, copyErr)
}
@@ -6226,12 +6531,12 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
return
}
-func removeRelatedRelationItems(avID string, itemIDs []string) (err error) {
+func removeRelatedRelationItems(avID string, itemIDs []string, blockID string) (err error) {
for _, relatedAvID := range av.GetSrcAvIDs(avID) {
if relatedAvID == avID {
continue
}
- relatedAv, parseErr := av.ParseAttributeView(relatedAvID)
+ relatedAv, parseErr := avParseView(relatedAvID, blockID)
if nil != parseErr || nil == relatedAv {
continue
}
@@ -6240,7 +6545,7 @@ func removeRelatedRelationItems(avID string, itemIDs []string) (err error) {
if !templateChanged && !filterChanged {
continue
}
- if err = av.SaveAttributeView(relatedAv); nil != err {
+ if err = avSaveView(relatedAv, blockID); nil != err {
return
}
ReloadAttrView(relatedAvID)
@@ -6744,7 +7049,7 @@ func sortAttributeViewRow(operation *Operation) (err error) {
return
}
- attrView, err := av.ParseAttributeView(operation.AvID)
+ attrView, err := avParseView(operation.AvID, operation.BlockID)
if err != nil {
return
}
@@ -6791,7 +7096,14 @@ func sortAttributeViewRow(operation *Operation) (err error) {
if isAcrossGroup {
if targetGroupView := view.GetGroupByID(operation.TargetGroupID); nil != targetGroupView && !gulu.Str.Contains(itemID, targetGroupView.GroupItemIDs) {
- fillDefaultValue(attrView, view, targetGroupView, operation.PreviousID, itemID, false, true)
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, operation.BlockID)
+ if nil != contextErr {
+ return contextErr
+ }
+ if err = fillDefaultValue(attrView, view, targetGroupView, operation.PreviousID, itemID, false,
+ true, operation.BlockID, filterContext); nil != err {
+ return
+ }
if val := attrView.GetValue(groupKey.ID, itemID); nil != val {
if av.MSelectExistOption(val.MSelect, groupView.GetGroupValue()) {
@@ -7641,7 +7953,8 @@ func BatchReplaceAttributeViewBlocks(avID string, isDetached bool, oldNew []map[
}
func (tx *Transaction) doUpdateAttrViewCell(operation *Operation) (ret *TxErr) {
- _, err := UpdateAttributeViewCell(tx, operation.AvID, operation.KeyID, operation.RowID, operation.Data)
+ _, err := updateAttributeViewCellInBlock(tx, operation.AvID, operation.BlockID, operation.KeyID,
+ operation.RowID, operation.Data)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
@@ -7649,21 +7962,22 @@ func (tx *Transaction) doUpdateAttrViewCell(operation *Operation) (ret *TxErr) {
}
func (tx *Transaction) doBatchUpdateAttrViewCells(operations []*Operation) (ret *TxErr) {
- attrView, err := av.ParseAttributeView(operations[0].AvID)
+ attrView, err := avParseView(operations[0].AvID, operations[0].BlockID)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operations[0].AvID, msg: err.Error()}
}
for _, operation := range operations {
- if _, err = updateAttributeViewValue(tx, attrView, operation.KeyID, operation.RowID, operation.Data, false); err != nil {
+ if _, err = updateAttributeViewValue(tx, attrView, operation.KeyID, operation.RowID, operation.Data, false,
+ operations[0].BlockID); err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
}
regenAttrViewGroups(attrView)
- if err = av.SaveAttributeView(attrView); err != nil {
+ if err = avSaveView(attrView, operations[0].BlockID); err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: attrView.ID, msg: err.Error()}
}
- refreshRelatedSrcAvs(attrView.ID, tx)
+ refreshRelatedSrcAvsInBlock(attrView.ID, operations[0].BlockID, tx)
return
}
@@ -7671,7 +7985,7 @@ func (tx *Transaction) doUpdateAttrViewCells(operation *Operation) (ret *TxErr)
if "" == operation.AvID || 0 == len(operation.CellUpdates) {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: "invalid attribute view cell updates"}
}
- attrView, err := av.ParseAttributeView(operation.AvID)
+ attrView, err := avParseView(operation.AvID, operation.BlockID)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
@@ -7680,15 +7994,16 @@ func (tx *Transaction) doUpdateAttrViewCells(operation *Operation) (ret *TxErr)
if nil == cell || "" == cell.KeyID || "" == cell.RowID {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: "invalid attribute view cell update"}
}
- if _, err = updateAttributeViewValue0(tx, attrView, cell.KeyID, cell.RowID, cell.Data, false, context); err != nil {
+ if _, err = updateAttributeViewValue0(tx, attrView, cell.KeyID, cell.RowID, cell.Data, false, context,
+ operation.BlockID); err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
}
regenAttrViewGroups(attrView)
- if err = av.SaveAttributeView(attrView); err != nil {
+ if err = avSaveView(attrView, operation.BlockID); err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: attrView.ID, msg: err.Error()}
}
- refreshRelatedSrcAvs(attrView.ID, tx)
+ refreshRelatedSrcAvsInBlock(attrView.ID, operation.BlockID, tx)
return
}
@@ -7728,20 +8043,31 @@ func BatchUpdateAttributeViewCells(tx *Transaction, avID string, values []any) (
}
func UpdateAttributeViewCell(tx *Transaction, avID, keyID, itemID string, valueData any) (val *av.Value, err error) {
- attrView, err := av.ParseAttributeView(avID)
+ return updateAttributeViewCellInBlock(tx, avID, "", keyID, itemID, valueData)
+}
+
+func updateAttributeViewCellInBlock(tx *Transaction, avID, blockID, keyID, itemID string,
+ valueData any) (val *av.Value, err error) {
+ attrView, err := avParseView(avID, blockID)
if err != nil {
return
}
- val, err = updateAttributeViewValue(tx, attrView, keyID, itemID, valueData, true)
+ val, err = updateAttributeViewValue(tx, attrView, keyID, itemID, valueData, false, blockID)
if nil != err {
return
}
+ regenAttrViewGroups(attrView)
+ if err = avSaveView(attrView, blockID); nil != err {
+ return
+ }
+ refreshRelatedSrcAvsInBlock(attrView.ID, blockID, tx)
return
}
-func updateAttributeViewValue(tx *Transaction, attrView *av.AttributeView, keyID, itemID string, valueData any, save bool) (val *av.Value, err error) {
- return updateAttributeViewValue0(tx, attrView, keyID, itemID, valueData, save, nil)
+func updateAttributeViewValue(tx *Transaction, attrView *av.AttributeView, keyID, itemID string, valueData any,
+ save bool, blockIDs ...string) (val *av.Value, err error) {
+ return updateAttributeViewValue0(tx, attrView, keyID, itemID, valueData, save, nil, blockIDs...)
}
type attrViewValueUpdateContext struct {
@@ -7781,8 +8107,13 @@ func newAttrViewValueUpdateContext(attrView *av.AttributeView) *attrViewValueUpd
return context
}
-func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyID, itemID string, valueData any, save bool, context *attrViewValueUpdateContext) (val *av.Value, err error) {
+func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyID, itemID string, valueData any,
+ save bool, context *attrViewValueUpdateContext, blockIDs ...string) (val *av.Value, err error) {
avID := attrView.ID
+ blockID := ""
+ if 0 < len(blockIDs) {
+ blockID = blockIDs[0]
+ }
var keyValues *av.KeyValues
var blockVal *av.Value
if nil == context {
@@ -8011,12 +8342,15 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyI
if nil != key && av.KeyTypeRelation == key.Type && nil != key.Relation && key.Relation.IsTwoWay {
// 双向关联需要同时更新目标字段的值
- updateTwoWayRelationDestAttrView(attrView, key, val, relationChangeMode, oldRelationBlockIDs)
+ if err = updateTwoWayRelationDestAttrViewInBlock(attrView, key, val, relationChangeMode,
+ oldRelationBlockIDs, blockID); nil != err {
+ return
+ }
}
if save {
regenAttrViewGroups(attrView)
- if err = av.SaveAttributeView(attrView); nil != err {
+ if err = avSaveView(attrView, blockID); nil != err {
return
}
}
@@ -8025,12 +8359,16 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyI
}
if save {
- refreshRelatedSrcAvs(avID, tx)
+ refreshRelatedSrcAvsInBlock(avID, blockID, tx)
}
return
}
func refreshRelatedSrcAvs(destAvID string, tx *Transaction) {
+ refreshRelatedSrcAvsInBlock(destAvID, "", tx)
+}
+
+func refreshRelatedSrcAvsInBlock(destAvID, blockID string, tx *Transaction) {
relatedAvIDs := av.GetSrcAvIDs(destAvID)
var tmp []string
@@ -8048,13 +8386,13 @@ func refreshRelatedSrcAvs(destAvID string, tx *Transaction) {
tx.relatedAvIDs = append(tx.relatedAvIDs, relatedAvIDs...)
} else {
for _, relatedAvID := range relatedAvIDs {
- destAv, _ := av.ParseAttributeView(relatedAvID)
+ destAv, _ := avParseView(relatedAvID, blockID)
if nil == destAv {
continue
}
regenAttrViewGroups(destAv)
- av.SaveAttributeView(destAv)
+ avSaveView(destAv, blockID)
ReloadAttrView(relatedAvID)
}
}
@@ -8065,13 +8403,19 @@ func refreshRelatedSrcAvs(destAvID string, tx *Transaction) {
// 1:关联字段值增加,增加目标值
// 2:关联字段值减少,减少目标值
func updateTwoWayRelationDestAttrView(attrView *av.AttributeView, relKey *av.Key, val *av.Value, relationChangeMode int, oldRelationBlockIDs []string) {
+ _ = updateTwoWayRelationDestAttrViewInBlock(attrView, relKey, val, relationChangeMode, oldRelationBlockIDs, "")
+}
+
+func updateTwoWayRelationDestAttrViewInBlock(attrView *av.AttributeView, relKey *av.Key, val *av.Value,
+ relationChangeMode int, oldRelationBlockIDs []string, blockID string) (err error) {
var destAv *av.AttributeView
if attrView.ID == relKey.Relation.AvID {
destAv = attrView
} else {
- destAv, _ = av.ParseAttributeView(relKey.Relation.AvID)
+ destAv, _ = avParseView(relKey.Relation.AvID, blockID)
}
+ // 目标数据库已删除或损坏时无法清理反向值,但不能因此阻止源条目删除。
if nil == destAv {
return
}
@@ -8125,8 +8469,9 @@ func updateTwoWayRelationDestAttrView(attrView *av.AttributeView, relKey *av.Key
if destAv != attrView {
regenAttrViewGroups(destAv)
- av.SaveAttributeView(destAv)
+ err = avSaveView(destAv, blockID)
}
+ return
}
// regenAttrViewGroups 重新生成分组视图。
diff --git a/kernel/model/attribute_view_box_test.go b/kernel/model/attribute_view_box_test.go
new file mode 100644
index 0000000000..f28dfffe74
--- /dev/null
+++ b/kernel/model/attribute_view_box_test.go
@@ -0,0 +1,177 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAttributeViewCarrierUsesExactCryptoBoundary(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const (
+ carrierBlockID = "20260803091003-avblock"
+ foreignBoxID = "20260904120000-boxenc0"
+ foreignAvID = "20260904120001-avenc00"
+ )
+
+ oldEncryptedBoxIDs := av.AVEncryptedBoxIDs
+ av.AVEncryptedBoxIDs = func() []string { return []string{foreignBoxID} }
+ t.Cleanup(func() { av.AVEncryptedBoxIDs = oldEncryptedBoxIDs })
+
+ foreignPath := filepath.Join(util.DataDir, foreignBoxID, "storage", "av", foreignAvID+".json")
+ if err := os.MkdirAll(filepath.Dir(foreignPath), 0755); nil != err {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(foreignPath, []byte("foreign encrypted attribute view"), 0644); nil != err {
+ t.Fatal(err)
+ }
+ if path, boxID := av.FindAttributeViewPath(foreignAvID); path != foreignPath || boxID != foreignBoxID {
+ t.Fatalf("foreign attribute view fallback precondition failed: %q, %q", path, boxID)
+ }
+
+ parsed, err := avParseView(fixture.attrView.ID, carrierBlockID)
+ if nil != err || nil == parsed || parsed.ID != fixture.attrView.ID {
+ t.Fatalf("ordinary carrier did not load its global attribute view: %+v, %v", parsed, err)
+ }
+ if _, err = avParseView(foreignAvID, carrierBlockID); !errors.Is(err, av.ErrViewNotFound) {
+ t.Fatalf("ordinary carrier should not parse an encrypted attribute view through fallback: %v", err)
+ }
+ if _, err = avParseView(fixture.attrView.ID, "20260904120002-missing"); nil == err ||
+ !strings.Contains(err.Error(), "carrier") {
+ t.Fatalf("a supplied but missing carrier should fail closed: %v", err)
+ }
+
+ if _, err = GetCurrentAttributeViewImages(nil, foreignAvID, carrierBlockID, "", ""); !errors.Is(err, av.ErrViewNotFound) {
+ t.Fatalf("image lookup should preserve the carrier crypto boundary: %v", err)
+ }
+ if _, _, _, err = RenderAttributeViewWithTarget(carrierBlockID, foreignAvID, "", "", 1, -1, nil,
+ av.LayoutTypeTable, false, false, "", ""); !errors.Is(err, av.ErrAttributeViewNotFound) {
+ t.Fatalf("render should reject a foreign attribute view: %v", err)
+ }
+ if _, _, _, err = RenderAttributeViewWithTarget(carrierBlockID, foreignAvID, "", "", 1, -1, nil,
+ av.LayoutTypeTable, true, false, "", ""); !errors.Is(err, av.ErrAttributeViewNotFound) {
+ t.Fatalf("render should not create a cross-boundary duplicate attribute view: %v", err)
+ }
+ if _, statErr := os.Stat(av.GetAttributeViewDataPath(foreignAvID)); !os.IsNotExist(statErr) {
+ t.Fatalf("cross-boundary render unexpectedly created a global attribute view: %v", statErr)
+ }
+
+ relationKey := &av.Key{
+ ID: "foreign-relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: foreignAvID},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ contextFilter := &av.AttributeViewContextFilter{Spec: av.AttributeViewContextFilterSpec, KeyID: relationKey.ID}
+ contextFilterJSON, marshalErr := contextFilter.Marshal()
+ if nil != marshalErr {
+ t.Fatal(marshalErr)
+ }
+ carrierNode := treenode.GetNodeInTree(fixture.tree, carrierBlockID)
+ carrierNode.SetIALAttr(av.NodeAttrContextFilter, contextFilterJSON)
+ if _, writeErr := filesys.WriteTree(fixture.tree); nil != writeErr {
+ t.Fatal(writeErr)
+ }
+ treenode.UpsertBlockTree(fixture.tree)
+ context, contextErr := resolveAttributeViewFilterContext(fixture.attrView, fixture.tableView, carrierBlockID)
+ if nil != contextErr || nil == context || relationKey.ID != context.KeyID ||
+ 0 != len(context.CurrentDocumentItemIDs) {
+ t.Fatalf("cross-boundary context target should fail closed with no matched items: %#v, %v", context, contextErr)
+ }
+}
+
+func TestTwoWayRelationWriteUsesCarrierCryptoBoundary(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const (
+ carrierBlockID = "20260803091003-avblock"
+ foreignBoxID = "20260904122000-boxenc1"
+ sharedAvID = "20260904122001-shared0"
+ targetItemID = "20260904122002-target0"
+ sourceItemID = "20260904122003-source0"
+ )
+
+ oldEncryptedBoxIDs := av.AVEncryptedBoxIDs
+ av.AVEncryptedBoxIDs = func() []string { return []string{foreignBoxID} }
+ t.Cleanup(func() {
+ av.AVEncryptedBoxIDs = oldEncryptedBoxIDs
+ av.SetAVBoxID(sharedAvID, "")
+ })
+
+ backRelationKey := av.NewKey(ast.NewNodeID(), "Tasks", "", av.KeyTypeRelation)
+ globalTarget := av.NewAttributeView(sharedAvID)
+ globalTarget.KeyValues = append(globalTarget.KeyValues, &av.KeyValues{Key: backRelationKey})
+ globalTarget.GetBlockKeyValues().Values = append(globalTarget.GetBlockKeyValues().Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: globalTarget.GetBlockKey().ID, BlockID: targetItemID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "Global target"},
+ })
+ globalTarget.Views[0].ItemIDs = append(globalTarget.Views[0].ItemIDs, targetItemID)
+ av.SetAVBoxID(sharedAvID, "")
+ if err := av.SaveAttributeView(globalTarget); nil != err {
+ t.Fatal(err)
+ }
+
+ foreignPath := filepath.Join(util.DataDir, foreignBoxID, "storage", "av", sharedAvID+".json")
+ if err := os.MkdirAll(filepath.Dir(foreignPath), 0755); nil != err {
+ t.Fatal(err)
+ }
+ const foreignData = "foreign encrypted attribute view"
+ if err := os.WriteFile(foreignPath, []byte(foreignData), 0644); nil != err {
+ t.Fatal(err)
+ }
+ av.SetAVBoxID(sharedAvID, foreignBoxID)
+
+ relationKey := av.NewKey(ast.NewNodeID(), "Project", "", av.KeyTypeRelation)
+ relationKey.Relation = &av.Relation{
+ AvID: sharedAvID, IsTwoWay: true, BackKeyID: backRelationKey.ID,
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ fixture.attrView.GetBlockKeyValues().Values = append(fixture.attrView.GetBlockKeyValues().Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: fixture.attrView.GetBlockKey().ID, BlockID: sourceItemID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "Source item"},
+ })
+ fixture.attrView.Views[0].ItemIDs = append(fixture.attrView.Views[0].ItemIDs, sourceItemID)
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+
+ if _, err := updateAttributeViewCellInBlock(nil, fixture.attrView.ID, carrierBlockID, relationKey.ID,
+ sourceItemID, &av.Value{Type: av.KeyTypeRelation, Relation: &av.ValueRelation{
+ BlockIDs: []string{targetItemID},
+ }}); nil != err {
+ t.Fatal(err)
+ }
+ updatedTarget, err := av.ParseAttributeViewInBox(sharedAvID, "")
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, targetItemID), sourceItemID)
+ data, err := os.ReadFile(foreignPath)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if foreignData != string(data) {
+ t.Fatalf("foreign same-ID attribute view was overwritten: %q", data)
+ }
+}
diff --git a/kernel/model/attribute_view_context_filter_template_test.go b/kernel/model/attribute_view_context_filter_template_test.go
new file mode 100644
index 0000000000..2e132812dd
--- /dev/null
+++ b/kernel/model/attribute_view_context_filter_template_test.go
@@ -0,0 +1,135 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestTemplateDatabaseReferencePreservesContextFilter(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904001000-ctxref1")
+ key := addTemplateContextFilterKey(t, database)
+ setTemplateDatabaseContextFilters(t, fixture.sourceID, database, key.ID)
+
+ code, err := DocSaveAsTemplateWithDatabaseMode(fixture.sourceID, "context-filter-reference", false,
+ TemplateDatabaseModeReference)
+ if nil != err || 0 != code {
+ t.Fatalf("save reference template failed: code=%d, err=%v", code, err)
+ }
+ _, templateNodes := parseSavedTemplateAttributeViews(t, "context-filter-reference")
+ assertTemplateDatabaseContextFilters(t, templateNodes, key.ID)
+
+ contentTree, _, _, err := RenderTemplateWithMode(
+ filepath.Join(util.DataDir, "templates", "context-filter-reference.md"),
+ fixture.targetID, TemplateRenderModeContent)
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertTemplateDatabaseContextFilters(t, contentTree.Root.ChildrenByType(ast.NodeAttributeView), key.ID)
+}
+
+func TestTemplateDatabaseCopyClearsContextFilterForDisconnectedRelation(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904001100-ctxcopy")
+ key := addTemplateContextFilterKey(t, database)
+ setTemplateDatabaseContextFilters(t, fixture.sourceID, database, key.ID)
+
+ code, err := DocSaveAsTemplate(fixture.sourceID, "context-filter-copy", false)
+ if nil != err || 0 != code {
+ t.Fatalf("save copy template failed: code=%d, err=%v", code, err)
+ }
+ _, templateNodes := parseSavedTemplateAttributeViews(t, "context-filter-copy")
+ assertTemplateDatabaseContextFilters(t, templateNodes, key.ID)
+
+ contentTree, _, _, err := RenderTemplateWithMode(
+ filepath.Join(util.DataDir, "templates", "context-filter-copy.md"),
+ fixture.targetID, TemplateRenderModeContent)
+ if nil != err {
+ t.Fatal(err)
+ }
+ renderedNodes := contentTree.Root.ChildrenByType(ast.NodeAttributeView)
+ if len(database.nodes) != len(renderedNodes) {
+ t.Fatalf("unexpected rendered database block count: %d", len(renderedNodes))
+ }
+ for i, node := range renderedNodes {
+ if raw := node.IALAttr(av.NodeAttrContextFilter); "" != raw {
+ t.Fatalf("copied database block %d retained disconnected context filter: %q", i, raw)
+ }
+ }
+}
+
+func addTemplateContextFilterKey(t *testing.T, database *templateAttributeViewTestFixture) *av.Key {
+ t.Helper()
+ key := &av.Key{
+ ID: ast.NewNodeID(), Name: "Context relation", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: database.attrView.ID},
+ }
+ database.attrView.KeyValues = append(database.attrView.KeyValues, &av.KeyValues{Key: key})
+ if err := av.SaveAttributeView(database.attrView); nil != err {
+ t.Fatal(err)
+ }
+ return key
+}
+
+func setTemplateDatabaseContextFilters(t *testing.T, sourceID string,
+ database *templateAttributeViewTestFixture, keyID string) {
+ t.Helper()
+ filter := &av.AttributeViewContextFilter{Spec: av.AttributeViewContextFilterSpec, KeyID: keyID}
+ raw, err := filter.Marshal()
+ if nil != err {
+ t.Fatal(err)
+ }
+ tree, err := LoadTreeByBlockID(sourceID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ for _, fixtureNode := range database.nodes {
+ node := treenode.GetNodeInTree(tree, fixtureNode.ID)
+ if nil == node {
+ t.Fatalf("database block [%s] not found", fixtureNode.ID)
+ }
+ node.SetIALAttr(av.NodeAttrContextFilter, raw)
+ }
+ if _, err = filesys.WriteTree(tree); nil != err {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+}
+
+func assertTemplateDatabaseContextFilters(t *testing.T, nodes []*ast.Node, expectedKeyID string) {
+ t.Helper()
+ if 2 != len(nodes) {
+ t.Fatalf("unexpected database block count: %d", len(nodes))
+ }
+ for i, node := range nodes {
+ filter, err := av.ParseAttributeViewContextFilter(node.IALAttr(av.NodeAttrContextFilter))
+ if nil != err {
+ t.Fatalf("parse database block %d context filter failed: %v", i, err)
+ }
+ if nil == filter || expectedKeyID != filter.KeyID {
+ t.Fatalf("unexpected database block %d context filter: %#v", i, filter)
+ }
+ }
+}
diff --git a/kernel/model/attribute_view_context_filter_test.go b/kernel/model/attribute_view_context_filter_test.go
new file mode 100644
index 0000000000..6ce68386c7
--- /dev/null
+++ b/kernel/model/attribute_view_context_filter_test.go
@@ -0,0 +1,737 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestRenderViewableInstanceAppliesContextFilterToEveryView(t *testing.T) {
+ relationKey := &av.Key{
+ ID: "relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: "projects"},
+ }
+ textKey := &av.Key{ID: "status", Type: av.KeyTypeText}
+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{
+ {Key: relationKey, Values: []*av.Value{
+ newContextFilterRelationValue(relationKey.ID, "alpha-open", "project-alpha"),
+ newContextFilterRelationValue(relationKey.ID, "alpha-closed", "project-alpha"),
+ newContextFilterRelationValue(relationKey.ID, "beta-open", "project-beta"),
+ newContextFilterRelationValue(relationKey.ID, "beta-closed", "project-beta"),
+ }},
+ {Key: textKey},
+ }}
+ context := &av.FilterContext{KeyID: relationKey.ID, CurrentDocumentItemIDs: []string{"project-alpha"}}
+
+ for _, layoutType := range []av.LayoutType{av.LayoutTypeTable, av.LayoutTypeGallery, av.LayoutTypeKanban} {
+ t.Run(string(layoutType), func(t *testing.T) {
+ view := &av.View{
+ ID: "view-" + string(layoutType),
+ LayoutType: layoutType,
+ PageSize: 10,
+ Filters: []*av.ViewFilter{{
+ Combination: av.FilterCombinationAnd,
+ Filters: []*av.ViewFilter{{
+ Column: textKey.ID, Operator: av.FilterOperatorIsEqual,
+ Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "open"}},
+ }},
+ }},
+ }
+ field := &av.BaseInstanceField{ID: textKey.ID, Type: textKey.Type}
+ var viewable av.Viewable
+ switch layoutType {
+ case av.LayoutTypeTable:
+ view.Table = av.NewLayoutTable()
+ viewable = &av.Table{
+ BaseInstance: av.NewViewBaseInstance(view),
+ Columns: []*av.TableColumn{{BaseInstanceField: field}},
+ Rows: []*av.TableRow{
+ newContextFilterTextTableRow("alpha-open", textKey.ID, "open"),
+ newContextFilterTextTableRow("alpha-closed", textKey.ID, "closed"),
+ newContextFilterTextTableRow("beta-open", textKey.ID, "open"),
+ },
+ }
+ case av.LayoutTypeGallery:
+ view.Gallery = av.NewLayoutGallery()
+ viewable = &av.Gallery{
+ BaseInstance: av.NewViewBaseInstance(view),
+ Fields: []*av.GalleryField{{BaseInstanceField: field}},
+ Cards: []*av.GalleryCard{
+ newContextFilterGalleryCard("alpha-open", textKey.ID, "open"),
+ newContextFilterGalleryCard("alpha-closed", textKey.ID, "closed"),
+ newContextFilterGalleryCard("beta-open", textKey.ID, "open"),
+ },
+ }
+ case av.LayoutTypeKanban:
+ view.Kanban = av.NewLayoutKanban()
+ viewable = &av.Kanban{
+ BaseInstance: av.NewViewBaseInstance(view),
+ Fields: []*av.KanbanField{{BaseInstanceField: field}},
+ Cards: []*av.KanbanCard{
+ newContextFilterKanbanCard("alpha-open", textKey.ID, "open"),
+ newContextFilterKanbanCard("alpha-closed", textKey.ID, "closed"),
+ newContextFilterKanbanCard("beta-open", textKey.ID, "open"),
+ },
+ }
+ }
+
+ if _, _, err := renderViewableInstance(viewable, view, attrView, 1, 10, false, "",
+ sql.NewAttributeViewRenderContext(), context); nil != err {
+ t.Fatal(err)
+ }
+ items := viewable.(av.Collection).GetItems()
+ if 1 != len(items) || "alpha-open" != items[0].GetID() {
+ t.Fatalf("context and view filters should be combined with AND: %+v", items)
+ }
+ })
+ }
+}
+
+func newContextFilterTextBaseValue(id, keyID, content string) *av.BaseValue {
+ return &av.BaseValue{ValueType: av.KeyTypeText, Value: &av.Value{
+ KeyID: keyID, BlockID: id, Type: av.KeyTypeText, Text: &av.ValueText{Content: content},
+ }}
+}
+
+func newContextFilterTextTableRow(id, keyID, content string) *av.TableRow {
+ return &av.TableRow{ID: id, Cells: []*av.TableCell{{BaseValue: newContextFilterTextBaseValue(id, keyID, content)}}}
+}
+
+func newContextFilterGalleryCard(id, keyID, content string) *av.GalleryCard {
+ return &av.GalleryCard{ID: id, Values: []*av.GalleryFieldValue{{
+ BaseValue: newContextFilterTextBaseValue(id, keyID, content),
+ }}}
+}
+
+func newContextFilterKanbanCard(id, keyID, content string) *av.KanbanCard {
+ return &av.KanbanCard{ID: id, Values: []*av.KanbanFieldValue{{
+ BaseValue: newContextFilterTextBaseValue(id, keyID, content),
+ }}}
+}
+
+func newContextFilterRelationValue(keyID, blockID, relationItemID string) *av.Value {
+ return &av.Value{
+ KeyID: keyID, BlockID: blockID, Type: av.KeyTypeRelation,
+ Relation: &av.ValueRelation{BlockIDs: []string{relationItemID}},
+ }
+}
+
+func TestContextFilterProvidesNewItemDefaultForEveryView(t *testing.T) {
+ relationKey := &av.Key{
+ ID: "relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: "projects"},
+ }
+ textKey := &av.Key{ID: "status", Type: av.KeyTypeText}
+ attrView := &av.AttributeView{
+ ID: "context-defaults", KeyValues: []*av.KeyValues{{Key: relationKey}, {Key: textKey}},
+ RenderedViewables: map[string]av.Viewable{},
+ }
+ context := &av.FilterContext{KeyID: relationKey.ID, CurrentDocumentItemIDs: []string{"project-alpha"}}
+
+ for _, status := range []string{"open", "closed"} {
+ t.Run(status, func(t *testing.T) {
+ layout := av.NewLayoutTable()
+ layout.Columns = []*av.ViewTableColumn{
+ {BaseField: &av.BaseField{ID: relationKey.ID}},
+ {BaseField: &av.BaseField{ID: textKey.ID}},
+ }
+ view := &av.View{
+ ID: "view-" + status, LayoutType: av.LayoutTypeTable,
+ Table: layout,
+ Filters: []*av.ViewFilter{{
+ Combination: av.FilterCombinationAnd,
+ Filters: []*av.ViewFilter{{
+ Column: textKey.ID, Operator: av.FilterOperatorIsEqual,
+ Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: status}},
+ }},
+ }}}
+ groupView := *view
+ groupView.Table = av.NewLayoutTable()
+ values := getAttrViewAddingBlockDefaultValues(attrView, view, &groupView, "", "new-item", true, false, context)
+ relationValue := values[relationKey.ID]
+ if nil == relationValue || nil == relationValue.Relation ||
+ 1 != len(relationValue.Relation.BlockIDs) || "project-alpha" != relationValue.Relation.BlockIDs[0] {
+ t.Fatalf("unexpected context relation default: %#v", relationValue)
+ }
+ textValue := values[textKey.ID]
+ if nil == textValue || nil == textValue.Text || status != textValue.Text.Content {
+ t.Fatalf("unexpected view filter default: %#v", textValue)
+ }
+ })
+ }
+}
+
+func TestMergeNewItemTemplateAndContextRelationsKeepsTwoWayValues(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const blockID = "20260803091003-avblock"
+
+ target := av.NewAttributeView(ast.NewNodeID())
+ relationKey := av.NewKey(ast.NewNodeID(), "Project", "", av.KeyTypeRelation)
+ backRelationKey := av.NewKey(ast.NewNodeID(), "Tasks", "", av.KeyTypeRelation)
+ relationKey.Relation = &av.Relation{
+ AvID: target.ID, IsTwoWay: true, BackKeyID: backRelationKey.ID,
+ }
+ backRelationKey.Relation = &av.Relation{
+ AvID: fixture.attrView.ID, IsTwoWay: true, BackKeyID: relationKey.ID,
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ target.KeyValues = append(target.KeyValues, &av.KeyValues{Key: backRelationKey})
+
+ currentProjectID := ast.NewNodeID()
+ staticProjectID := ast.NewNodeID()
+ target.GetBlockKeyValues().Values = append(target.GetBlockKeyValues().Values,
+ &av.Value{
+ ID: ast.NewNodeID(), KeyID: target.GetBlockKey().ID, BlockID: currentProjectID, Type: av.KeyTypeBlock,
+ Block: &av.ValueBlock{ID: fixture.tree.Root.ID, Content: "Current project"},
+ },
+ &av.Value{
+ ID: ast.NewNodeID(), KeyID: target.GetBlockKey().ID, BlockID: staticProjectID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "Static project"},
+ },
+ )
+ for _, view := range target.Views {
+ view.ItemIDs = append(view.ItemIDs, currentProjectID, staticProjectID)
+ }
+ if err := av.SaveAttributeView(target); nil != err {
+ t.Fatal(err)
+ }
+
+ templateID := ast.NewNodeID()
+ if err := fixture.attrView.SetNewItemTemplates(&av.NewItemTemplatesConfig{Templates: []*av.NewItemTemplate{{
+ ID: templateID, Name: "With static project", TargetType: av.NewItemTargetDetached,
+ FieldValues: map[string]*av.NewItemFieldValue{
+ relationKey.ID: {
+ Mode: av.NewItemFieldValueStatic,
+ Value: &av.Value{Type: av.KeyTypeRelation, Relation: &av.ValueRelation{
+ BlockIDs: []string{staticProjectID, staticProjectID},
+ }},
+ },
+ },
+ }}}); nil != err {
+ t.Fatal(err)
+ }
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+
+ itemTemplate := fixture.attrView.GetNewItemTemplate(templateID)
+ fieldValues, err := resolveNewItemFieldValues(fixture.attrView, itemTemplate, time.Now(), fixture.tree.Box)
+ if nil != err {
+ t.Fatal(err)
+ }
+ filterContext, err := resolveAttributeViewFilterContext(fixture.attrView, fixture.tableView, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ itemID := ast.NewNodeID()
+ applyAttributeViewContextFilterDefaultValue(fixture.attrView, itemID, filterContext, fieldValues)
+ operations := buildNewItemFieldValueOperations(fixture.attrView, fieldValues, itemID, blockID)
+ if 1 != len(operations) || blockID != operations[0].BlockID {
+ t.Fatalf("unexpected template field operations: %+v", operations)
+ }
+
+ fixture.attrView.GetBlockKeyValues().Values = append(fixture.attrView.GetBlockKeyValues().Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: fixture.attrView.GetBlockKey().ID, BlockID: itemID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "New task"},
+ })
+ if err = fillAttributeViewContextFilterValue(fixture.attrView, fixture.tableView, itemID, filterContext,
+ blockID); nil != err {
+ t.Fatal(err)
+ }
+ if _, err = updateAttributeViewValue(nil, fixture.attrView, relationKey.ID, itemID,
+ fieldValues[relationKey.ID], false); nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, fixture.attrView.GetValue(relationKey.ID, itemID),
+ staticProjectID, currentProjectID)
+
+ updatedTarget, err := av.ParseAttributeView(target.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, staticProjectID), itemID)
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, currentProjectID), itemID)
+}
+
+func assertContextFilterRelationIDs(t *testing.T, value *av.Value, expected ...string) {
+ t.Helper()
+ if nil == value || nil == value.Relation {
+ t.Fatalf("expected a relation value, got %#v", value)
+ }
+ counts := map[string]int{}
+ for _, id := range value.Relation.BlockIDs {
+ counts[id]++
+ }
+ if len(expected) != len(value.Relation.BlockIDs) {
+ t.Fatalf("unexpected relation IDs: %v", value.Relation.BlockIDs)
+ }
+ for _, id := range expected {
+ if 1 != counts[id] {
+ t.Fatalf("relation ID %q occurred %d times in %v", id, counts[id], value.Relation.BlockIDs)
+ }
+ }
+}
+
+func TestSetAttributeViewContextFilterPersistsPerDatabaseBlock(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ firstKey := &av.Key{
+ ID: "first-relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: fixture.attrView.ID},
+ }
+ secondKey := &av.Key{
+ ID: "second-relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: fixture.attrView.ID},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues,
+ &av.KeyValues{Key: firstKey}, &av.KeyValues{Key: secondKey})
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+
+ const firstBlockID = "20260803091003-avblock"
+ const secondBlockID = "20260803091004-mirror0"
+ secondNode := &ast.Node{
+ Type: ast.NodeAttributeView,
+ ID: secondBlockID,
+ AttributeViewID: fixture.attrView.ID,
+ AttributeViewType: string(av.LayoutTypeTable),
+ }
+ secondNode.SetIALAttr("id", secondBlockID)
+ secondNode.SetIALAttr(av.NodeAttrView, fixture.tableView.ID)
+ fixture.tree.Root.AppendChild(secondNode)
+ if _, err := filesys.WriteTree(fixture.tree); nil != err {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(fixture.tree)
+
+ firstFilter, err := setAttributeViewContextFilterForTest(firstBlockID, fixture.attrView.ID, firstKey.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == firstFilter || firstKey.ID != firstFilter.KeyID {
+ t.Fatalf("unexpected first context filter: %#v", firstFilter)
+ }
+ assertDatabaseBlockContextFilter(t, firstBlockID, firstKey.ID)
+ assertDatabaseBlockContextFilter(t, secondBlockID, "")
+
+ secondFilter, err := setAttributeViewContextFilterForTest(secondBlockID, fixture.attrView.ID, secondKey.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == secondFilter || secondKey.ID != secondFilter.KeyID {
+ t.Fatalf("unexpected second context filter: %#v", secondFilter)
+ }
+ assertDatabaseBlockContextFilter(t, firstBlockID, firstKey.ID)
+ assertDatabaseBlockContextFilter(t, secondBlockID, secondKey.ID)
+
+ cleared, err := setAttributeViewContextFilterForTest(firstBlockID, fixture.attrView.ID, "")
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil != cleared {
+ t.Fatalf("clearing should not return a context filter: %#v", cleared)
+ }
+ assertDatabaseBlockContextFilter(t, firstBlockID, "")
+ assertDatabaseBlockContextFilter(t, secondBlockID, secondKey.ID)
+}
+
+func TestSetAttributeViewContextFilterRejectsInvalidCarrierAndKey(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const blockID = "20260803091003-avblock"
+ missingTargetKey := &av.Key{
+ ID: "missing-target-relation", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: "20260904004000-missing"},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: missingTargetKey})
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+
+ tests := []struct {
+ name string
+ blockID string
+ avID string
+ keyID string
+ }{
+ {name: "missing carrier", avID: fixture.attrView.ID, keyID: fixture.attrView.KeyValues[1].Key.ID},
+ {name: "unknown carrier", blockID: "20260803091005-missing", avID: fixture.attrView.ID, keyID: fixture.attrView.KeyValues[1].Key.ID},
+ {name: "wrong attribute view", blockID: blockID, avID: "20260803091006-otherav", keyID: fixture.attrView.KeyValues[1].Key.ID},
+ {name: "non relation key", blockID: blockID, avID: fixture.attrView.ID, keyID: fixture.attrView.KeyValues[1].Key.ID},
+ {name: "unknown key", blockID: blockID, avID: fixture.attrView.ID, keyID: "missing-key"},
+ {name: "missing relation target", blockID: blockID, avID: fixture.attrView.ID, keyID: missingTargetKey.ID},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if _, err := setAttributeViewContextFilterForTest(test.blockID, test.avID, test.keyID); nil == err {
+ t.Fatal("invalid context filter should return an error")
+ }
+ assertDatabaseBlockContextFilter(t, blockID, "")
+ })
+ }
+}
+
+func TestResolveAttributeViewContextFilterValidatesCarrier(t *testing.T) {
+ t.Run("ordinary block attribute panel", func(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, false)
+ view := fixture.attrView.Views[0]
+ context, err := resolveAttributeViewFilterContext(fixture.attrView, view, "")
+ if nil != err || nil != context {
+ t.Fatalf("an unscoped definition render should have no context: %#v, %v", context, err)
+ }
+ context, err = resolveAttributeViewFilterContext(fixture.attrView, view, "20260803091002-anchor0")
+ if nil != err || nil != context {
+ t.Fatalf("an ordinary block attribute panel should have no context: %#v, %v", context, err)
+ }
+
+ viewable, _, _, renderErr := RenderAttributeViewWithTarget("20260803091002-anchor0", fixture.attrView.ID,
+ "", "", 1, -1, nil, av.LayoutTypeTable, false, true, "", "")
+ if nil != renderErr || nil == viewable {
+ t.Fatalf("rendering an ordinary block attribute panel failed: %#v, %v", viewable, renderErr)
+ }
+ if _, err = setAttributeViewContextFilterForTest("20260803091002-anchor0", fixture.attrView.ID, ""); nil == err {
+ t.Fatal("the setter should reject an ordinary block carrier")
+ }
+ })
+
+ t.Run("mismatched database block", func(t *testing.T) {
+ setupDatabaseBlockTransactionTest(t, true)
+ other := av.NewAttributeView("20260904005000-otherav")
+ if _, err := resolveAttributeViewFilterContext(other, other.Views[0],
+ "20260803091003-avblock"); nil == err {
+ t.Fatal("a database block from another attribute view should fail closed")
+ }
+ })
+}
+
+func TestResolveAttributeViewContextFilterMapsCarrierDocument(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ relationKey := &av.Key{
+ ID: "relation", Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: fixture.attrView.ID},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+ const blockID = "20260803091003-avblock"
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+
+ context, err := resolveAttributeViewFilterContext(fixture.attrView, fixture.tableView, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == context || relationKey.ID != context.KeyID || 0 != len(context.CurrentDocumentItemIDs) {
+ t.Fatalf("an unbound carrier document should resolve to an empty context: %#v", context)
+ }
+ if _, err = GetAttrViewAddingBlockDefaultValues(fixture.attrView.ID, blockID, fixture.tableView.ID,
+ "", "", "new-item"); !errors.Is(err, av.ErrAttributeViewContextNotBound) {
+ t.Fatalf("creating an item with an unbound context returned %v", err)
+ }
+
+ fixture.attrView.GetBlockKeyValues().Values = append(fixture.attrView.GetBlockKeyValues().Values, &av.Value{
+ BlockID: "project-item", Type: av.KeyTypeBlock, Block: &av.ValueBlock{ID: fixture.tree.Root.ID},
+ })
+ context, err = resolveAttributeViewFilterContext(fixture.attrView, fixture.tableView, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == context || 1 != len(context.CurrentDocumentItemIDs) ||
+ "project-item" != context.CurrentDocumentItemIDs[0] {
+ t.Fatalf("unexpected bound carrier context: %#v", context)
+ }
+}
+
+func TestAttributeViewContextFilterSurvivesFieldLifecycle(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const blockID = "20260803091003-avblock"
+ relationKey := &av.Key{
+ ID: "lifecycle-relation", Name: "Project", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: fixture.attrView.ID},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ blockKeyValues := fixture.attrView.GetBlockKeyValues()
+ blockKeyValues.Values = append(blockKeyValues.Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: blockKeyValues.Key.ID, BlockID: "project-item", Type: av.KeyTypeBlock,
+ Block: &av.ValueBlock{ID: fixture.tree.Root.ID},
+ })
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+ originalRaw := databaseBlockContextFilterRaw(t, blockID)
+ assertResolvedAttributeViewContext(t, fixture.attrView, blockID, relationKey.ID, "project-item")
+
+ if err := updateAttributeViewColumn(&Operation{
+ AvID: fixture.attrView.ID, ID: relationKey.ID, Name: relationKey.Name, Typ: string(av.KeyTypeText),
+ }); nil != err {
+ t.Fatal(err)
+ }
+ current := parseAttributeViewContextFilterLifecycleTest(t, fixture.attrView.ID)
+ assertPersistedAttributeViewContextFilter(t, current, blockID, relationKey.ID, originalRaw)
+ emptyContext := assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID)
+ assertAttributeViewContextFilterRendersNoRows(t, current, emptyContext)
+
+ if err := updateAttributeViewColumn(&Operation{
+ AvID: fixture.attrView.ID, ID: relationKey.ID, Name: relationKey.Name, Typ: string(av.KeyTypeRelation),
+ }); nil != err {
+ t.Fatal(err)
+ }
+ current = parseAttributeViewContextFilterLifecycleTest(t, fixture.attrView.ID)
+ assertPersistedAttributeViewContextFilter(t, current, blockID, relationKey.ID, originalRaw)
+ assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID, "project-item")
+
+ currentKey, err := current.GetKey(relationKey.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ currentKey.Relation.AvID = "20260904003000-missing"
+ if err = av.SaveAttributeView(current); nil != err {
+ t.Fatal(err)
+ }
+ assertPersistedAttributeViewContextFilter(t, current, blockID, relationKey.ID, originalRaw)
+ assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID)
+
+ currentKey.Relation.AvID = current.ID
+ if err = av.SaveAttributeView(current); nil != err {
+ t.Fatal(err)
+ }
+ assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID, "project-item")
+
+ if err = RemoveAttributeViewKey(current.ID, relationKey.ID, false); nil != err {
+ t.Fatal(err)
+ }
+ current = parseAttributeViewContextFilterLifecycleTest(t, fixture.attrView.ID)
+ assertPersistedAttributeViewContextFilter(t, current, blockID, relationKey.ID, originalRaw)
+ assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID)
+
+ current.KeyValues = append(current.KeyValues, &av.KeyValues{Key: &av.Key{
+ ID: relationKey.ID, Name: relationKey.Name, Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: current.ID},
+ }})
+ if err = av.SaveAttributeView(current); nil != err {
+ t.Fatal(err)
+ }
+ assertPersistedAttributeViewContextFilter(t, current, blockID, relationKey.ID, originalRaw)
+ assertResolvedAttributeViewContext(t, current, blockID, relationKey.ID, "project-item")
+
+ if err = RemoveAttributeViewKey(current.ID, relationKey.ID, false); nil != err {
+ t.Fatal(err)
+ }
+ if cleared, clearErr := setAttributeViewContextFilterForTest(blockID, current.ID, ""); nil != clearErr || nil != cleared {
+ t.Fatalf("clear stale context filter failed: %#v, %v", cleared, clearErr)
+ }
+ current = parseAttributeViewContextFilterLifecycleTest(t, fixture.attrView.ID)
+ filter, err := GetAttributeViewContextFilter(current, blockID)
+ if nil != err || nil != filter || "" != databaseBlockContextFilterRaw(t, blockID) {
+ t.Fatalf("stale context filter was not cleared: %#v, %v", filter, err)
+ }
+ context, err := resolveAttributeViewFilterContext(current, current.Views[0], blockID)
+ if nil != err || nil != context {
+ t.Fatalf("cleared context filter should not resolve: %#v, %v", context, err)
+ }
+}
+
+func TestAttributeViewContextFilterReplayRestoresStaleConfiguration(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const blockID = "20260803091003-avblock"
+ relationKey := &av.Key{
+ ID: "stale-relation", Name: "Project", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: fixture.attrView.ID},
+ }
+ fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ if err := av.SaveAttributeView(fixture.attrView); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+ if err := RemoveAttributeViewKey(fixture.attrView.ID, relationKey.ID, false); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, ""); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, fixture.attrView.ID, relationKey.ID); nil == err {
+ t.Fatal("a normal transaction restored an invalid stale context filter")
+ }
+ assertDatabaseBlockContextFilter(t, blockID, "")
+
+ if _, err := setAttributeViewContextFilterReplayForTest(blockID, fixture.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+ assertDatabaseBlockContextFilter(t, blockID, relationKey.ID)
+ if _, err := setAttributeViewContextFilterReplayForTest(blockID, fixture.attrView.ID, ""); nil != err {
+ t.Fatal(err)
+ }
+ assertDatabaseBlockContextFilter(t, blockID, "")
+}
+
+func TestAttributeViewContextFilterRejectsMalformedLifecycleMetadata(t *testing.T) {
+ fixture := setupDatabaseBlockTransactionTest(t, true)
+ const blockID = "20260803091003-avblock"
+ for _, test := range []struct {
+ name string
+ raw string
+ }{
+ {name: "malformed", raw: `{`},
+ {name: "unknown spec", raw: `{"spec":2,"keyID":"relation"}`},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ setDatabaseBlockContextFilterRawForTest(t, blockID, test.raw)
+ if _, err := GetAttributeViewContextFilter(fixture.attrView, blockID); !errors.Is(err, av.ErrInvalidAttributeViewContextFilter) {
+ t.Fatalf("invalid metadata returned %v", err)
+ }
+ if _, err := resolveAttributeViewFilterContext(fixture.attrView, fixture.tableView,
+ blockID); !errors.Is(err, av.ErrInvalidAttributeViewContextFilter) {
+ t.Fatalf("resolving invalid metadata returned %v", err)
+ }
+ })
+ }
+}
+
+func parseAttributeViewContextFilterLifecycleTest(t *testing.T, avID string) *av.AttributeView {
+ t.Helper()
+ attrView, err := av.ParseAttributeView(avID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ return attrView
+}
+
+func assertPersistedAttributeViewContextFilter(t *testing.T, attrView *av.AttributeView, blockID, keyID, raw string) {
+ t.Helper()
+ filter, err := GetAttributeViewContextFilter(attrView, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == filter || keyID != filter.KeyID || raw != databaseBlockContextFilterRaw(t, blockID) {
+ t.Fatalf("unexpected persisted lifecycle metadata: %#v, %q", filter, databaseBlockContextFilterRaw(t, blockID))
+ }
+}
+
+func assertResolvedAttributeViewContext(t *testing.T, attrView *av.AttributeView, blockID, keyID string,
+ wantItemIDs ...string) *av.FilterContext {
+ t.Helper()
+ context, err := resolveAttributeViewFilterContext(attrView, attrView.Views[0], blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == context || keyID != context.KeyID || len(wantItemIDs) != len(context.CurrentDocumentItemIDs) {
+ t.Fatalf("unexpected resolved lifecycle context: %#v", context)
+ }
+ for i, want := range wantItemIDs {
+ if want != context.CurrentDocumentItemIDs[i] {
+ t.Fatalf("unexpected context item at %d: got %s, want %s", i, context.CurrentDocumentItemIDs[i], want)
+ }
+ }
+ return context
+}
+
+func assertAttributeViewContextFilterRendersNoRows(t *testing.T, attrView *av.AttributeView, context *av.FilterContext) {
+ t.Helper()
+ view := attrView.Views[0]
+ table := &av.Table{
+ BaseInstance: av.NewViewBaseInstance(view),
+ Rows: []*av.TableRow{{ID: "otherwise-visible"}},
+ }
+ if _, _, err := renderViewableInstance(table, view, attrView, 1, 10, false, "",
+ sql.NewAttributeViewRenderContext(), context); nil != err {
+ t.Fatal(err)
+ }
+ if 0 != len(table.GetItems()) {
+ t.Fatalf("stale context rendered rows: %#v", table.GetItems())
+ }
+}
+
+func databaseBlockContextFilterRaw(t *testing.T, blockID string) string {
+ t.Helper()
+ node, _, err := getNodeByBlockID(nil, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ return node.IALAttr(av.NodeAttrContextFilter)
+}
+
+func setDatabaseBlockContextFilterRawForTest(t *testing.T, blockID, raw string) {
+ t.Helper()
+ node, tree, err := getNodeByBlockID(nil, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ node.SetIALAttr(av.NodeAttrContextFilter, raw)
+ if _, err = filesys.WriteTree(tree); nil != err {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+}
+
+func assertDatabaseBlockContextFilter(t *testing.T, blockID, expectedKeyID string) {
+ t.Helper()
+ node, _, err := getNodeByBlockID(nil, blockID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ raw := node.IALAttr(av.NodeAttrContextFilter)
+ if "" == expectedKeyID {
+ if "" != raw {
+ t.Fatalf("context filter attribute should be absent, got %q", raw)
+ }
+ return
+ }
+ filter, err := av.ParseAttributeViewContextFilter(raw)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil == filter || av.AttributeViewContextFilterSpec != filter.Spec || expectedKeyID != filter.KeyID {
+ t.Fatalf("unexpected persisted context filter: %#v", filter)
+ }
+}
+
+func setAttributeViewContextFilterForTest(blockID, avID, keyID string) (*av.AttributeViewContextFilter, error) {
+ return setAttributeViewContextFilterWithReplayForTest(blockID, avID, keyID, false)
+}
+
+func setAttributeViewContextFilterReplayForTest(blockID, avID, keyID string) (*av.AttributeViewContextFilter, error) {
+ return setAttributeViewContextFilterWithReplayForTest(blockID, avID, keyID, true)
+}
+
+func setAttributeViewContextFilterWithReplayForTest(blockID, avID, keyID string,
+ replay bool) (*av.AttributeViewContextFilter, error) {
+ tx := &Transaction{trees: map[string]*parse.Tree{}, isReplay: replay}
+ filter, err := setAttributeViewContextFilter(tx, blockID, avID, keyID)
+ if nil != err {
+ return nil, err
+ }
+ for _, tree := range tx.trees {
+ if _, err = filesys.WriteTree(tree); nil != err {
+ return nil, err
+ }
+ treenode.UpsertBlockTree(tree)
+ }
+ return filter, nil
+}
diff --git a/kernel/model/attribute_view_group_test.go b/kernel/model/attribute_view_group_test.go
index 9918ef3ad0..ad99d71c0d 100644
--- a/kernel/model/attribute_view_group_test.go
+++ b/kernel/model/attribute_view_group_test.go
@@ -177,6 +177,47 @@ func TestRenderReusedGroupViewPreservesFilterSortCalcAndPagination(t *testing.T)
}
}
+func TestHideEmptyGroupViewsUsesUnpaginatedCounts(t *testing.T) {
+ view := &av.View{Group: &av.ViewGroup{Field: "field", HideEmpty: true}}
+ for _, layoutType := range []av.LayoutType{av.LayoutTypeTable, av.LayoutTypeGallery, av.LayoutTypeKanban} {
+ t.Run(string(layoutType), func(t *testing.T) {
+ base := &av.BaseInstance{GroupHidden: 0}
+ var viewable av.Viewable
+ switch layoutType {
+ case av.LayoutTypeTable:
+ viewable = &av.Table{BaseInstance: base, RowCount: 0}
+ case av.LayoutTypeGallery:
+ viewable = &av.Gallery{BaseInstance: base, CardCount: 0}
+ case av.LayoutTypeKanban:
+ viewable = &av.Kanban{BaseInstance: base, CardCount: 0}
+ }
+ hideEmptyGroupViews(view, viewable)
+ if 1 != viewable.GetGroupHidden() {
+ t.Fatal("an empty group should be hidden at runtime")
+ }
+
+ switch layoutType {
+ case av.LayoutTypeTable:
+ viewable.(*av.Table).RowCount = 2
+ case av.LayoutTypeGallery:
+ viewable.(*av.Gallery).CardCount = 2
+ case av.LayoutTypeKanban:
+ viewable.(*av.Kanban).CardCount = 2
+ }
+ hideEmptyGroupViews(view, viewable)
+ if 0 != viewable.GetGroupHidden() {
+ t.Fatal("an unpaginated non-empty group should remain visible when the current page has no items")
+ }
+
+ viewable.SetGroupHidden(2)
+ hideEmptyGroupViews(view, viewable)
+ if 2 != viewable.GetGroupHidden() {
+ t.Fatal("manual group hiding should be preserved")
+ }
+ })
+ }
+}
+
func TestRenderedGroupsUseItemsBeforeParentPagination(t *testing.T) {
oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangs
util.Lang = "en"
diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.go
index 1157a48321..40988e848c 100644
--- a/kernel/model/attribute_view_new_item.go
+++ b/kernel/model/attribute_view_new_item.go
@@ -93,7 +93,7 @@ func CreateAttributeViewItemWithMarkdown(avID, blockID, viewID, templateID, prev
func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, groupID string,
document *CreateAttributeViewItemMarkdown) (*CreateAttributeViewItemResult, error) {
- attrView, err := av.ParseAttributeView(avID)
+ attrView, err := avParseView(avID, blockID)
if nil != err {
return nil, err
}
@@ -132,11 +132,6 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, grou
}
}
- itemID := ast.NewNodeID()
- fieldValues, err := resolveNewItemFieldValues(attrView, itemTemplate, createdAt)
- if nil != err {
- return nil, err
- }
dbTree, err := LoadTreeByBlockID(blockID)
if nil != err {
return nil, err
@@ -145,6 +140,20 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, grou
if nil == dbNode {
return nil, ErrBlockNotFound
}
+ itemID := ast.NewNodeID()
+ fieldValues, err := resolveNewItemFieldValues(attrView, itemTemplate, createdAt, dbTree.Box)
+ if nil != err {
+ return nil, err
+ }
+ filterContext, err := resolveAttributeViewFilterContext(attrView, nil, blockID)
+ if nil != err {
+ return nil, err
+ }
+ if nil != filterContext && 1 > len(filterContext.CurrentDocumentItemIDs) {
+ return nil, av.ErrAttributeViewContextNotBound
+ }
+ // 模板字段会在插入条目后写入,需提前合并上下文关系,避免覆盖插入阶段自动填充的当前文档。
+ applyAttributeViewContextFilterDefaultValue(attrView, itemID, filterContext, fieldValues)
boundBlockID := itemID
isDetached := av.NewItemTargetDocument != itemTemplate.TargetType
var createdTree *parse.Tree
@@ -164,11 +173,11 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, grou
PreviousID: previousID, IgnoreDefaultFill: false,
Srcs: []map[string]any{{"itemID": itemID, "id": boundBlockID, "content": preview.PrimaryKey, "isDetached": isDetached}},
})
- fieldOperations := buildNewItemFieldValueOperations(attrView, fieldValues, itemID)
+ fieldOperations := buildNewItemFieldValueOperations(attrView, fieldValues, itemID, blockID)
doOperations = append(doOperations, fieldOperations...)
doOperations = append(doOperations, &Operation{Action: "doUpdateUpdated", ID: blockID, Data: util.CurrentTimeSecondsStr()})
- undoOperations := []*Operation{{Action: "removeAttrViewBlock", AvID: avID, SrcIDs: []string{itemID}}}
+ undoOperations := []*Operation{{Action: "removeAttrViewBlock", AvID: avID, BlockID: blockID, SrcIDs: []string{itemID}}}
if nil != createdTree {
undoOperations = append(undoOperations, &Operation{Action: "removeCreatedDoc", ID: boundBlockID, Tree: createdTree})
}
@@ -176,7 +185,7 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, grou
tx := &Transaction{DoOperations: doOperations, UndoOperations: undoOperations, Timestamp: createdAt.UnixMilli()}
tx.MarkFromAPI()
if err = PerformTxSync(tx); nil != err {
- cleanupErr := RemoveAttributeViewBlock([]string{itemID}, avID)
+ cleanupErr := removeAttributeViewBlock([]string{itemID}, avID, blockID, nil)
if nil != createdTree {
cleanupErr = errors.Join(cleanupErr, removeCreatedNewItemDoc(boundBlockID))
}
@@ -568,7 +577,8 @@ func newItemTitleFromPath(renderedPath string) string {
return normalizeDocTitle(path.Base(renderedPath))
}
-func resolveNewItemFieldValues(attrView *av.AttributeView, itemTemplate *av.NewItemTemplate, createdAt time.Time) (ret map[string]*av.Value, err error) {
+func resolveNewItemFieldValues(attrView *av.AttributeView, itemTemplate *av.NewItemTemplate, createdAt time.Time,
+ carrierBoxID string) (ret map[string]*av.Value, err error) {
ret = map[string]*av.Value{}
for keyID, fieldValue := range itemTemplate.FieldValues {
key, getErr := attrView.GetKey(keyID)
@@ -592,7 +602,7 @@ func resolveNewItemFieldValues(attrView *av.AttributeView, itemTemplate *av.NewI
}
value = fieldValue.Value.Clone()
if av.KeyTypeRelation == key.Type {
- filterNewItemTemplateRelationValue(attrView, key, value)
+ filterNewItemTemplateRelationValue(attrView, key, value, carrierBoxID)
if nil == value.Relation || 0 == len(value.Relation.BlockIDs) {
continue
}
@@ -605,13 +615,17 @@ func resolveNewItemFieldValues(attrView *av.AttributeView, itemTemplate *av.NewI
return
}
-func filterNewItemTemplateRelationValue(attrView *av.AttributeView, key *av.Key, value *av.Value) {
+func filterNewItemTemplateRelationValue(attrView *av.AttributeView, key *av.Key, value *av.Value,
+ carrierBoxID string) {
if nil == key.Relation || nil == value.Relation {
return
}
targetAv := attrView
if key.Relation.AvID != attrView.ID {
- targetAv, _ = av.ParseAttributeView(key.Relation.AvID)
+ contextFilter := &av.AttributeViewContextFilter{
+ Spec: av.AttributeViewContextFilterSpec, KeyID: key.ID,
+ }
+ targetAv, _ = resolveAttributeViewContextFilterTarget(attrView, contextFilter, carrierBoxID)
}
if nil == targetAv {
value.Relation.BlockIDs = nil
@@ -631,7 +645,8 @@ func filterNewItemTemplateRelationValue(attrView *av.AttributeView, key *av.Key,
value.Relation.BlockIDs = blockIDs
}
-func buildNewItemFieldValueOperations(attrView *av.AttributeView, fieldValues map[string]*av.Value, itemID string) (ret []*Operation) {
+func buildNewItemFieldValueOperations(attrView *av.AttributeView, fieldValues map[string]*av.Value, itemID,
+ blockID string) (ret []*Operation) {
for _, keyValues := range attrView.KeyValues {
if nil == keyValues || nil == keyValues.Key {
continue
@@ -641,7 +656,10 @@ func buildNewItemFieldValueOperations(attrView *av.AttributeView, fieldValues ma
if nil == value {
continue
}
- ret = append(ret, &Operation{Action: "updateAttrViewCell", ID: ast.NewNodeID(), AvID: attrView.ID, KeyID: keyID, RowID: itemID, Data: value})
+ ret = append(ret, &Operation{
+ Action: "updateAttrViewCell", ID: ast.NewNodeID(), AvID: attrView.ID, BlockID: blockID,
+ KeyID: keyID, RowID: itemID, Data: value,
+ })
}
return
}
diff --git a/kernel/model/attribute_view_new_item_test.go b/kernel/model/attribute_view_new_item_test.go
index 96bd8853f4..cf26f1785a 100644
--- a/kernel/model/attribute_view_new_item_test.go
+++ b/kernel/model/attribute_view_new_item_test.go
@@ -120,10 +120,15 @@ func TestBuildNewItemFieldValueOperationsWithoutKeyIDs(t *testing.T) {
attrView.KeyValues = []*av.KeyValues{{Key: blockKey}, {Key: textKey}}
value := &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "value"}}
- operations := buildNewItemFieldValueOperations(attrView, map[string]*av.Value{textKey.ID: value}, ast.NewNodeID())
+ blockID := ast.NewNodeID()
+ operations := buildNewItemFieldValueOperations(attrView, map[string]*av.Value{textKey.ID: value},
+ ast.NewNodeID(), blockID)
if 1 != len(operations) || "updateAttrViewCell" != operations[0].Action || textKey.ID != operations[0].KeyID {
t.Fatalf("unexpected field operations: %+v", operations)
}
+ if blockID != operations[0].BlockID {
+ t.Fatalf("field operation lost its database carrier: %+v", operations[0])
+ }
}
func TestAttributeViewItemDocumentTemplate(t *testing.T) {
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index fd45ba8441..44b04d9bc1 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -35,7 +35,6 @@ import (
"github.com/siyuan-note/logging"
"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"
)
@@ -408,36 +407,30 @@ func RenderAttributeViewWithTarget(blockID, avID, viewID, query string, page, pa
waitForSyncingStorages()
- // 加密笔记本的 AV 定义存笔记本级路径,通过 blockID 反查 boxID
- avBoxID := ""
- if "" != blockID {
- bt := treenode.GetBlockTree(blockID)
- if nil == bt {
- for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
- if encBT := treenode.GetBlockTreeInBox(blockID, encBoxID); nil != encBT {
- bt = encBT
- break
- }
- }
- }
- if nil != bt && IsEncryptedBox(bt.BoxID) {
- avBoxID = bt.BoxID
- }
+ avBoxID, exactBox, resolveErr := resolveAttributeViewCarrierBoxID(blockID)
+ if nil != resolveErr {
+ err = resolveErr
+ return
}
- // 通过 fallback 查找 AV 定义路径(普通 box 全局,加密笔记本笔记本级)
- // 已知 box 时直接用 InBox 查找,避免全局 pending 映射被并发覆盖
+ // 已知载体时只在同一加密边界内查找;无载体的兼容调用保留全局回退。
var existPath string
- if avBoxID != "" {
+ if exactBox {
existPath, _ = av.FindAttributeViewPathInBox(avID, avBoxID)
} else {
existPath, _ = av.FindAttributeViewPath(avID)
}
if "" == existPath {
+ if exactBox {
+ if foreignPath, foreignBoxID := av.FindAttributeViewPath(avID); "" != foreignPath &&
+ foreignBoxID != avBoxID {
+ err = av.ErrAttributeViewNotFound
+ return
+ }
+ }
if avBoxID != "" {
existPath = filepath.Join(util.DataDir, avBoxID, "storage", "av", avID+".json")
} else {
- // fallback 找不到时按全局路径检查(首次创建场景)
existPath = av.GetAttributeViewDataPath(avID)
}
}
@@ -462,8 +455,7 @@ func RenderAttributeViewWithTarget(blockID, avID, viewID, query string, page, pa
}
}
- // 已知 box 时直接用 InBox 解析,不依赖全局 pending 状态
- if avBoxID != "" {
+ if exactBox {
attrView, err = av.ParseAttributeViewInBox(avID, avBoxID)
} else {
attrView, err = av.ParseAttributeView(avID)
@@ -531,6 +523,11 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
return
}
}
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, nodeID)
+ if nil != contextErr {
+ err = contextErr
+ return
+ }
// 渲染视图
renderContext := sql.NewAttributeViewRenderContext()
@@ -552,7 +549,7 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
}
var targetIndex, targetOffset int
targetIndex, targetOffset, err = renderViewableInstance(viewable, view, attrView, page, pageSize, ignoreRows,
- renderTargetItemID, renderContext)
+ renderTargetItemID, renderContext, filterContext)
if nil != err {
return
}
@@ -566,7 +563,7 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
// 渲染分组视图。当 ignoreRows 时若有已生成的分组则渲染元数据供面板使用,无分组则跳过(生成分组需要行数据)
if !ignoreRows || len(view.Groups) > 0 {
err = renderAttributeViewGroups(viewable, attrView, view, query, page, pageSize, groupPaging, groupRenderSource,
- ignoreRows, writable, target, targetGroupID, renderContext)
+ ignoreRows, writable, target, targetGroupID, renderContext, filterContext)
}
if writable && nil == err && attrView.HasCardCoverPositionChanges() {
if err = av.SaveAttributeView(attrView); nil != err {
@@ -579,7 +576,8 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
func renderAttributeViewGroups(viewable av.Viewable, attrView *av.AttributeView, view *av.View, query string, page,
pageSize int, groupPaging map[string]any, groupRenderSource *sql.GroupViewRenderSource, ignoreRows, writable bool,
- target *AttributeViewRenderTarget, targetGroupID string, renderContext *sql.AttributeViewRenderContext) (err error) {
+ target *AttributeViewRenderTarget, targetGroupID string, renderContext *sql.AttributeViewRenderContext,
+ filterContext *av.FilterContext) (err error) {
groupKey := view.GetGroupKey(attrView)
if nil == groupKey {
if view.LayoutType == av.LayoutTypeKanban {
@@ -694,7 +692,7 @@ func renderAttributeViewGroups(viewable av.Viewable, attrView *av.AttributeView,
}
}
targetIndex, targetOffset, renderErr := renderViewableInstance(groupViewable, view, attrView, groupPage,
- groupPageSize, ignoreRows, groupTargetItemID, renderContext)
+ groupPageSize, ignoreRows, groupTargetItemID, renderContext, filterContext)
err = renderErr
if nil != err {
return
@@ -754,15 +752,28 @@ func hideEmptyGroupViews(view *av.View, viewable av.Viewable) {
}
groupHidden := viewable.GetGroupHidden()
+ if 2 == groupHidden {
+ return
+ }
if !view.Group.HideEmpty {
- if 2 != groupHidden {
- viewable.SetGroupHidden(0)
- }
+ viewable.SetGroupHidden(0)
return
}
- itemCount := viewable.(av.Collection).CountItems()
- if 1 == groupHidden && 0 < itemCount {
+ itemCount := 0
+ switch viewable.GetType() {
+ case av.LayoutTypeTable:
+ itemCount = viewable.(*av.Table).RowCount
+ case av.LayoutTypeGallery:
+ itemCount = viewable.(*av.Gallery).CardCount
+ case av.LayoutTypeKanban:
+ itemCount = viewable.(*av.Kanban).CardCount
+ default:
+ itemCount = viewable.(av.Collection).CountItems()
+ }
+ if 1 > itemCount {
+ viewable.SetGroupHidden(1)
+ } else {
viewable.SetGroupHidden(0)
}
}
@@ -1022,7 +1033,7 @@ func attrViewFiltersUseRenderedValues(filters []*av.ViewFilter, renderTemplateKe
func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.AttributeView, page, pageSize int,
ignoreRows bool, targetItemID string,
- renderContext *sql.AttributeViewRenderContext) (targetIndex, targetOffset int, err error) {
+ renderContext *sql.AttributeViewRenderContext, filterContexts ...*av.FilterContext) (targetIndex, targetOffset int, err error) {
targetIndex = -1
if nil == viewable {
err = av.ErrViewNotFound
@@ -1037,7 +1048,11 @@ func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.At
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollectionsWithContext(attrView, cachedAttrViews, renderContext)
- av.Filter(viewable, attrView, rollupFurtherCollections, cachedAttrViews)
+ var filterContext *av.FilterContext
+ if 0 < len(filterContexts) {
+ filterContext = filterContexts[0]
+ }
+ av.FilterWithContext(viewable, attrView, rollupFurtherCollections, cachedAttrViews, filterContext)
av.Sort(viewable, attrView)
av.Calc(viewable, attrView)
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 59580835c7..d25ba2c6d3 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -162,26 +162,30 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {
// Database block supports export as CSV https://github.com/siyuan-note/siyuan/issues/10072
err = withExportReadLockByBlockID(blockID, func() error {
+ bt := getExportBlockTree(blockID)
+ if nil == bt {
+ return ErrBlockNotFound
+ }
+ node, _, nodeErr := getNodeByBlockID(nil, blockID)
+ if nil != nodeErr {
+ return nodeErr
+ }
+ if nil == node || ast.NodeAttributeView != node.Type || node.AttributeViewID != avID {
+ return av.ErrAttributeViewNotFound
+ }
+
avBoxID := ""
- if bt := getExportBlockTree(blockID); nil != bt && IsEncryptedBox(bt.BoxID) {
+ if IsEncryptedBox(bt.BoxID) {
avBoxID = bt.BoxID
av.SetAVBoxID(avID, avBoxID)
}
- var attrView *av.AttributeView
- if avBoxID != "" {
- attrView, err = av.ParseAttributeViewInBox(avID, avBoxID)
- } else {
- attrView, err = av.ParseAttributeView(avID)
- }
+ attrView, parseErr := av.ParseAttributeViewInBox(avID, avBoxID)
+ err = parseErr
if err != nil {
return err
}
- node, _, nodeErr := getNodeByBlockID(nil, blockID)
- if nil == node {
- return nodeErr
- }
viewID := node.IALAttr(av.NodeAttrView)
view, viewErr := resolveAttributeViewView(attrView, viewID, "", "")
if viewErr != nil {
@@ -194,7 +198,11 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {
// 遵循视图过滤和排序规则 Use filtering and sorting of current view settings when exporting database blocks https://github.com/siyuan-note/siyuan/issues/10474
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollections(attrView, cachedAttrViews)
- av.Filter(table, attrView, rollupFurtherCollections, cachedAttrViews)
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, blockID)
+ if nil != contextErr {
+ return contextErr
+ }
+ av.FilterWithContext(table, attrView, rollupFurtherCollections, cachedAttrViews, filterContext)
av.Sort(table, attrView)
exportFolder := filepath.Join(util.TempDir, "export")
@@ -2891,13 +2899,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i
func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {
// 用 box-aware 路径解析 + 自动解密读取 AV 定义明文(加密笔记本的 AV 在 <boxID>/storage/av/,
// GetAttributeViewDataPath 只查全局路径会漏;filelock.Copy 会拷密文)。
- var avData []byte
- var readErr error
- if boxID != "" {
- avData, readErr = av.ReadAttributeViewDataInBox(avID, boxID)
- } else {
- avData, readErr = av.ReadAttributeViewData(avID)
- }
+ avData, readErr := av.ReadAttributeViewDataInBox(avID, boxID)
if readErr != nil {
logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)
return
@@ -2919,13 +2921,7 @@ func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap
}
}
- var attrView *av.AttributeView
- var parseErr error
- if boxID != "" {
- attrView, parseErr = av.ParseAttributeViewInBox(avID, boxID)
- } else {
- attrView, parseErr = av.ParseAttributeView(avID)
- }
+ attrView, parseErr := av.ParseAttributeViewInBox(avID, boxID)
if parseErr != nil {
logging.LogErrorf("parse attribute view [%s] failed: %s", avID, parseErr)
return
@@ -2968,13 +2964,7 @@ func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, ass
if relAvID == avID {
continue
}
- var relAvData []byte
- var readErr error
- if boxID != "" {
- relAvData, readErr = av.ReadAttributeViewDataInBox(relAvID, boxID)
- } else {
- relAvData, readErr = av.ReadAttributeViewData(relAvID)
- }
+ relAvData, readErr := av.ReadAttributeViewDataInBox(relAvID, boxID)
if readErr != nil {
logging.LogErrorf("read relation attribute view [%s] failed: %s", relAvID, readErr)
continue
@@ -2994,13 +2984,7 @@ func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, ass
logging.LogErrorf("write av json failed: %s", writeErr)
}
- var attrView *av.AttributeView
- var parseErr error
- if boxID != "" {
- attrView, parseErr = av.ParseAttributeViewInBox(relAvID, boxID)
- } else {
- attrView, parseErr = av.ParseAttributeView(relAvID)
- }
+ attrView, parseErr := av.ParseAttributeViewInBox(relAvID, boxID)
if parseErr != nil {
logging.LogErrorf("parse relation attribute view [%s] failed: %s", relAvID, parseErr)
continue
@@ -3014,12 +2998,7 @@ func walkRelationAvs(avID, boxID string, exportAvIDs *hashset.Set) {
return
}
- var attrView *av.AttributeView
- if boxID != "" {
- attrView, _ = av.ParseAttributeViewInBox(avID, boxID)
- } else {
- attrView, _ = av.ParseAttributeView(avID)
- }
+ attrView, _ := av.ParseAttributeViewInBox(avID, boxID)
if nil == attrView {
return
}
@@ -3582,12 +3561,16 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,
}
avID := n.AttributeViewID
- // 用 box-aware 路径解析(加密笔记本的 AV 在 <boxID>/storage/av/,GetAttributeViewDataPath 只查全局会漏)
- if avJSONPath, _ := av.FindAttributeViewPath(avID); "" == avJSONPath {
+ avBoxID := ""
+ if IsEncryptedBox(tree.Box) {
+ avBoxID = tree.Box
+ }
+ // 数据库定义只能从文档所在的加密边界读取,普通文档不能回退到已解锁的加密笔记本。
+ if avJSONPath, _ := av.FindAttributeViewPathInBox(avID, avBoxID); "" == avJSONPath {
return ast.WalkContinue
}
- attrView, err := av.ParseAttributeView(avID)
+ attrView, err := av.ParseAttributeViewInBox(avID, avBoxID)
if err != nil {
logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
return ast.WalkContinue
@@ -3605,7 +3588,13 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,
// 遵循视图过滤和排序规则 Use filtering and sorting of current view settings when exporting database blocks https://github.com/siyuan-note/siyuan/issues/10474
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollections(attrView, cachedAttrViews)
- av.Filter(table, attrView, rollupFurtherCollections, cachedAttrViews)
+ filterContext, contextErr := resolveAttributeViewFilterContext(attrView, view, n.ID)
+ if nil != contextErr {
+ logging.LogErrorf("resolve attribute view [%s] filter context failed: %s", avID, contextErr)
+ table.Rows = nil
+ } else {
+ av.FilterWithContext(table, attrView, rollupFurtherCollections, cachedAttrViews, filterContext)
+ }
av.Sort(table, attrView)
aligns := getAttrViewTableAligns(table, avHiddenCol)
@@ -4641,12 +4630,11 @@ func exportRefTrees(tree *parse.Tree, defBlockIDs *[]string, retTrees map[string
return ast.WalkContinue
}
- var attrView *av.AttributeView
+ avBoxID := ""
if IsEncryptedBox(tree.Box) {
- attrView, _ = av.ParseAttributeViewInBox(avID, tree.Box)
- } else {
- attrView, _ = av.ParseAttributeView(avID)
+ avBoxID = tree.Box
}
+ attrView, _ := av.ParseAttributeViewInBox(avID, avBoxID)
if nil == attrView {
return ast.WalkContinue
}
diff --git a/kernel/model/export_attribute_view_test.go b/kernel/model/export_attribute_view_test.go
index bb5bfd02ae..dba8bab4f2 100644
--- a/kernel/model/export_attribute_view_test.go
+++ b/kernel/model/export_attribute_view_test.go
@@ -17,10 +17,16 @@
package model
import (
+ "bytes"
"reflect"
"testing"
+ "github.com/88250/lute/ast"
+ "github.com/emirpasic/gods/sets/hashset"
"github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestGetAttrViewTableAligns(t *testing.T) {
@@ -59,3 +65,98 @@ func TestGetAttrViewCSVRenderedValue(t *testing.T) {
t.Fatal("a field without a display template should use its stored CSV formatting")
}
}
+
+func TestAttributeViewExportDoesNotCrossEncryptedBoundary(t *testing.T) {
+ const (
+ normalBoxID = "20260904010000-box0001"
+ docID = "20260904010001-doc0001"
+ blockID = "20260904010002-avnode1"
+ encryptedBoxID = "20260904010003-box0002"
+ encryptedAvID = "20260904010004-av00001"
+ otherAvID = "20260904010005-av00002"
+ directAvID = "20260904010006-av00003"
+ middleAvID = "20260904010007-av00004"
+ recursiveAvID = "20260904010008-av00005"
+ )
+
+ setupExportRelatedTest(t, normalBoxID)
+ Conf.Editor = conf.NewEditor()
+ oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangs
+ util.Lang = "en"
+ util.AttrViewLangs = map[string]map[string]any{
+ "en": {"key": "Key", "select": "Select", "table": "Table", "gallery": "Gallery"},
+ }
+ markRuntimeEncryptedBox(encryptedBoxID)
+ setDEKForTest(encryptedBoxID, bytes.Repeat([]byte{0x42}, 32))
+ t.Cleanup(func() {
+ util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangs
+ av.SetAVBoxID(encryptedAvID, "")
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, encryptedBoxID)
+ cachedDEKsLock.Unlock()
+ forgetRuntimeEncryptedBox(encryptedBoxID)
+ })
+
+ attrView := av.NewAttributeView(encryptedAvID)
+ av.SetAVBoxID(encryptedAvID, encryptedBoxID)
+ if err := av.SaveAttributeView(attrView); nil != err {
+ t.Fatalf("save encrypted attribute view failed: %v", err)
+ }
+ if parsed, err := av.ParseAttributeView(encryptedAvID); nil != err || nil == parsed {
+ t.Fatalf("fallback precondition failed: parsed=%v, err=%v", parsed, err)
+ }
+
+ tree := treenode.NewTree(normalBoxID, "/"+docID+".sy", "/Export", "Export")
+ for nil != tree.Root.FirstChild {
+ tree.Root.FirstChild.Unlink()
+ }
+ database := &ast.Node{
+ Type: ast.NodeAttributeView, ID: blockID, AttributeViewID: encryptedAvID,
+ AttributeViewType: string(av.LayoutTypeTable),
+ }
+ database.SetIALAttr("id", blockID)
+ database.SetIALAttr(av.NodeAttrView, attrView.Views[0].ID)
+ tree.Root.AppendChild(database)
+ writeExportRelatedTestTree(t, tree)
+
+ if _, err := ExportAv2CSV(otherAvID, blockID); nil == err {
+ t.Fatal("CSV export accepted an attribute view ID that is not bound to the database block")
+ }
+ if _, err := ExportAv2CSV(encryptedAvID, blockID); nil == err {
+ t.Fatal("CSV export crossed from a normal document to an encrypted attribute view")
+ }
+
+ exported := exportTree(tree, false, false, true, 0, 0, 0, "", "", "", "", false, "", false, false, false)
+ if nodes := exported.Root.ChildrenByType(ast.NodeAttributeView); 1 != len(nodes) {
+ t.Fatal("document export resolved an encrypted attribute view from a normal document")
+ }
+
+ newRelationAttributeView := func(id, targetID string) *av.AttributeView {
+ ret := av.NewAttributeView(id)
+ ret.KeyValues = append(ret.KeyValues, &av.KeyValues{Key: &av.Key{
+ ID: ast.NewNodeID(), Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: targetID},
+ }})
+ return ret
+ }
+ for _, relationAv := range []*av.AttributeView{
+ newRelationAttributeView(directAvID, encryptedAvID),
+ newRelationAttributeView(middleAvID, encryptedAvID),
+ newRelationAttributeView(recursiveAvID, middleAvID),
+ } {
+ if err := av.SaveAttributeView(relationAv); nil != err {
+ t.Fatalf("save relation attribute view [%s] failed: %v", relationAv.ID, err)
+ }
+ }
+
+ directIDs := hashset.New()
+ walkRelationAvs(directAvID, "", directIDs)
+ if !directIDs.Contains(directAvID) || directIDs.Contains(encryptedAvID) {
+ t.Fatalf("direct relation export crossed the encrypted boundary: %v", directIDs.Values())
+ }
+ recursiveIDs := hashset.New()
+ walkRelationAvs(recursiveAvID, "", recursiveIDs)
+ if !recursiveIDs.Contains(recursiveAvID) || !recursiveIDs.Contains(middleAvID) ||
+ recursiveIDs.Contains(encryptedAvID) {
+ t.Fatalf("recursive relation export crossed the encrypted boundary: %v", recursiveIDs.Values())
+ }
+}
diff --git a/kernel/model/template.go b/kernel/model/template.go
index 7ebcff087d..862c319537 100644
--- a/kernel/model/template.go
+++ b/kernel/model/template.go
@@ -52,6 +52,15 @@ type TemplateSearchResult struct {
Content string `json:"content"`
}
+type TemplateDatabaseMode string
+
+const (
+ TemplateDatabaseModeCopy TemplateDatabaseMode = "copy"
+ TemplateDatabaseModeReference TemplateDatabaseMode = "reference"
+
+ templateDatabaseModeAttr = "custom-sy-av-template-mode"
+)
+
func RenderGoTemplate(templateContent string) (ret string, err error) {
return RenderGoTemplateAtInBox(templateContent, time.Now(), "")
}
@@ -244,12 +253,24 @@ func SearchTemplate(keyword string) (ret []*TemplateSearchResult) {
}
func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error) {
+ return DocSaveAsTemplateWithDatabaseMode(id, name, overwrite, TemplateDatabaseModeCopy)
+}
+
+func DocSaveAsTemplateWithDatabaseMode(id, name string, overwrite bool, databaseMode TemplateDatabaseMode) (code int, err error) {
+ if databaseMode == "" {
+ databaseMode = TemplateDatabaseModeCopy
+ }
+ if TemplateDatabaseModeCopy != databaseMode && TemplateDatabaseModeReference != databaseMode {
+ return 0, fmt.Errorf("unsupported template database mode [%s]", databaseMode)
+ }
+
bt := treenode.GetBlockTree(id)
if nil == bt {
return
}
tree := prepareExportTree(bt)
+ markTemplateAttributeViewModes(tree.Root, databaseMode)
addBlockIALNodes(tree, true)
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -324,6 +345,23 @@ func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error) {
return
}
+func markTemplateAttributeViewModes(root *ast.Node, databaseMode TemplateDatabaseMode) {
+ if nil == root {
+ return
+ }
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeAttributeView != n.Type {
+ return ast.WalkContinue
+ }
+ if TemplateDatabaseModeReference == databaseMode {
+ n.SetIALAttr(templateDatabaseModeAttr, string(databaseMode))
+ } else {
+ n.RemoveIALAttr(templateDatabaseModeAttr)
+ }
+ return ast.WalkContinue
+ })
+}
+
func RenderDynamicIconContentTemplate(content, id string) (ret string) {
tree, err := LoadTreeByBlockID(id)
if err != nil {
@@ -381,6 +419,283 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e
return
}
+type templateAttributeViewPlan struct {
+ mode TemplateDatabaseMode
+ source *av.AttributeView
+ target *av.AttributeView
+ selectedView *av.View
+ copiedViewIDs map[string]string
+}
+
+type templateAttributeViewCopy struct {
+ target *av.AttributeView
+ copiedViewIDs map[string]string
+}
+
+func templateAttributeViewBoxID(tree *parse.Tree) string {
+ if nil != tree && IsEncryptedBox(tree.Box) {
+ return tree.Box
+ }
+ return ""
+}
+
+func templateAttributeViewMode(node *ast.Node) (ret TemplateDatabaseMode, err error) {
+ value := strings.TrimSpace(node.IALAttr(templateDatabaseModeAttr))
+ if "" == value {
+ return TemplateDatabaseModeCopy, nil
+ }
+ ret = TemplateDatabaseMode(value)
+ if TemplateDatabaseModeCopy != ret && TemplateDatabaseModeReference != ret {
+ return "", fmt.Errorf("unsupported template database mode [%s]", value)
+ }
+ return
+}
+
+func validateTemplateAttributeViewNode(node *ast.Node, attrView *av.AttributeView) (selectedView *av.View, err error) {
+ viewID := strings.TrimSpace(node.IALAttr(av.NodeAttrView))
+ if "" != viewID {
+ selectedView = attrView.GetView(viewID)
+ if nil == selectedView {
+ return nil, fmt.Errorf("attribute view [%s] view [%s] not found", attrView.ID, viewID)
+ }
+ } else if selectedView, err = attrView.GetFirstView(); nil != err {
+ return nil, fmt.Errorf("attribute view [%s] has no available view: %w", attrView.ID, err)
+ }
+
+ visibleViewIDs := strings.TrimSpace(node.IALAttr(av.NodeAttrVisibleViewIDs))
+ if "" == visibleViewIDs {
+ return
+ }
+ visibleViewCount := 0
+ for _, visibleViewID := range strings.Split(visibleViewIDs, ",") {
+ visibleViewID = strings.TrimSpace(visibleViewID)
+ if "" == visibleViewID {
+ continue
+ }
+ visibleViewCount++
+ if nil == attrView.GetView(visibleViewID) {
+ return nil, fmt.Errorf("attribute view [%s] visible view [%s] not found", attrView.ID, visibleViewID)
+ }
+ }
+ if 1 > visibleViewCount {
+ return nil, fmt.Errorf("attribute view [%s] has no available visible view", attrView.ID)
+ }
+ return
+}
+
+func resolveCopyTemplateAttributeView(node *ast.Node, attrView *av.AttributeView) *av.View {
+ if viewID := strings.TrimSpace(node.IALAttr(av.NodeAttrView)); "" != viewID {
+ if view := attrView.GetView(viewID); nil != view {
+ return view
+ }
+ }
+ view, _ := attrView.GetFirstView()
+ return view
+}
+
+func copyTemplateAttributeView(source *av.AttributeView) (ret *templateAttributeViewCopy, err error) {
+ target := source.Clone()
+ if nil == target {
+ return nil, fmt.Errorf("clone attribute view [%s] failed", source.ID)
+ }
+ if len(source.Views) != len(target.Views) {
+ return nil, fmt.Errorf("clone attribute view [%s] views failed", source.ID)
+ }
+ copiedViewIDs := map[string]string{}
+ for i, sourceView := range source.Views {
+ if nil == sourceView || nil == target.Views[i] {
+ return nil, fmt.Errorf("clone attribute view [%s] view failed", source.ID)
+ }
+ copiedViewIDs[sourceView.ID] = target.Views[i].ID
+ }
+ return &templateAttributeViewCopy{target: target, copiedViewIDs: copiedViewIDs}, nil
+}
+
+func prepareTemplateAttributeViews(tree *parse.Tree, preview bool) (plans map[*ast.Node]*templateAttributeViewPlan,
+ copies []*templateAttributeViewCopy, err error) {
+ plans = map[*ast.Node]*templateAttributeViewPlan{}
+ referenceSources := map[string]*av.AttributeView{}
+ copySources := map[string]*av.AttributeView{}
+ copyBySourceID := map[string]*templateAttributeViewCopy{}
+ boxID := templateAttributeViewBoxID(tree)
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeAttributeView != n.Type {
+ return ast.WalkContinue
+ }
+
+ mode, modeErr := templateAttributeViewMode(n)
+ if nil != modeErr {
+ err = modeErr
+ return ast.WalkStop
+ }
+ if TemplateDatabaseModeReference == mode {
+ source := referenceSources[n.AttributeViewID]
+ if nil == source {
+ source, modeErr = av.ParseAttributeViewInBox(n.AttributeViewID, boxID)
+ if nil != modeErr {
+ err = fmt.Errorf("parse attribute view [%s] in box [%s] failed: %w", n.AttributeViewID, boxID, modeErr)
+ return ast.WalkStop
+ }
+ if nil == source || source.ID != n.AttributeViewID {
+ err = fmt.Errorf("attribute view [%s] not found in box [%s]", n.AttributeViewID, boxID)
+ return ast.WalkStop
+ }
+ referenceSources[n.AttributeViewID] = source
+ }
+ selectedView, validateErr := validateTemplateAttributeViewNode(n, source)
+ if nil != validateErr {
+ err = validateErr
+ return ast.WalkStop
+ }
+ plans[n] = &templateAttributeViewPlan{
+ mode: mode, source: source, target: source, selectedView: selectedView,
+ }
+ return ast.WalkContinue
+ }
+
+ source := copySources[n.AttributeViewID]
+ if nil == source {
+ source, modeErr = av.ParseAttributeView(n.AttributeViewID)
+ if nil != modeErr || nil == source {
+ if nil == modeErr {
+ modeErr = av.ErrViewNotFound
+ }
+ logging.LogErrorf("parse attribute view [%s] failed: %s", n.AttributeViewID, modeErr)
+ plans[n] = &templateAttributeViewPlan{mode: mode}
+ return ast.WalkContinue
+ }
+ copySources[n.AttributeViewID] = source
+ }
+ selectedView := resolveCopyTemplateAttributeView(n, source)
+ plan := &templateAttributeViewPlan{mode: mode, source: source, target: source, selectedView: selectedView}
+ if !preview {
+ copied := copyBySourceID[source.ID]
+ if nil == copied {
+ copied, err = copyTemplateAttributeView(source)
+ if nil != err {
+ logging.LogErrorf("%s", err)
+ err = nil
+ plans[n] = &templateAttributeViewPlan{mode: mode}
+ return ast.WalkContinue
+ }
+ copyBySourceID[source.ID] = copied
+ copies = append(copies, copied)
+ }
+ plan.target = copied.target
+ plan.copiedViewIDs = copied.copiedViewIDs
+ }
+ plans[n] = plan
+ return ast.WalkContinue
+ })
+ return
+}
+
+func saveTemplateAttributeViewCopies(copies []*templateAttributeViewCopy, boxID string) {
+ for _, copied := range copies {
+ if "" != boxID {
+ av.SetAVBoxID(copied.target.ID, boxID)
+ }
+ err := av.SaveAttributeView(copied.target)
+ if "" != boxID {
+ av.SetAVBoxID(copied.target.ID, "")
+ }
+ if nil != err {
+ logging.LogErrorf("save attribute view [%s] failed: %s", copied.target.ID, err)
+ }
+ }
+}
+
+func applyTemplateAttributeViewPlan(node *ast.Node, plan *templateAttributeViewPlan) (*av.View, error) {
+ node.RemoveIALAttr(templateDatabaseModeAttr)
+ if TemplateDatabaseModeCopy == plan.mode {
+ // 完整复制会断开关联字段,实例上下文筛选不再有有效的目标数据库。
+ node.RemoveIALAttr(av.NodeAttrContextFilter)
+ }
+ if nil == plan.source || nil == plan.target || nil == plan.selectedView {
+ return nil, nil
+ }
+ node.AttributeViewID = plan.target.ID
+ viewID := plan.selectedView.ID
+ if TemplateDatabaseModeCopy == plan.mode && nil != plan.copiedViewIDs {
+ viewID = plan.copiedViewIDs[viewID]
+ if "" == viewID {
+ return nil, fmt.Errorf("copied attribute view [%s] view mapping not found", plan.source.ID)
+ }
+ if sourceViewID := strings.TrimSpace(node.IALAttr(av.NodeAttrView)); "" != sourceViewID {
+ if copiedViewID := plan.copiedViewIDs[sourceViewID]; "" != copiedViewID {
+ node.SetIALAttr(av.NodeAttrView, copiedViewID)
+ } else {
+ node.RemoveIALAttr(av.NodeAttrView)
+ }
+ }
+ if visibleViewIDs := strings.TrimSpace(node.IALAttr(av.NodeAttrVisibleViewIDs)); "" != visibleViewIDs {
+ var copiedVisibleViewIDs []string
+ for _, sourceViewID := range strings.Split(visibleViewIDs, ",") {
+ sourceViewID = strings.TrimSpace(sourceViewID)
+ if copiedViewID := plan.copiedViewIDs[sourceViewID]; "" != copiedViewID {
+ copiedVisibleViewIDs = append(copiedVisibleViewIDs, copiedViewID)
+ }
+ }
+ if 0 < len(copiedVisibleViewIDs) {
+ node.SetIALAttr(av.NodeAttrVisibleViewIDs, strings.Join(copiedVisibleViewIDs, ","))
+ } else {
+ node.RemoveIALAttr(av.NodeAttrVisibleViewIDs)
+ }
+ }
+ }
+ view := plan.target.GetView(viewID)
+ if nil == view {
+ return nil, fmt.Errorf("attribute view [%s] view [%s] not found", plan.target.ID, viewID)
+ }
+ node.AttributeViewType = string(view.LayoutType)
+ return view, nil
+}
+
+func templateAttributeViewPreviewTable(node *ast.Node, plan *templateAttributeViewPlan) *ast.Node {
+ view := *plan.selectedView
+ if nil != plan.selectedView.Table {
+ table := *plan.selectedView.Table
+ table.Columns = append([]*av.ViewTableColumn(nil), plan.selectedView.Table.Columns...)
+ view.Table = &table
+ }
+ var table *av.Table
+ if TemplateDatabaseModeReference == plan.mode {
+ // 引用数据库模板的预览只显示结构和表头,避免在预览中暴露被引用数据库的数据。
+ switch view.LayoutType {
+ case av.LayoutTypeGallery:
+ view.Table = av.NewLayoutTable()
+ for _, field := range view.Gallery.CardFields {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
+ }
+ case av.LayoutTypeKanban:
+ view.Table = av.NewLayoutTable()
+ for _, field := range view.Kanban.Fields {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
+ }
+ }
+ depth := 1
+ table = sql.RenderAttributeViewTable(plan.source, &view, "", &depth, map[string]*av.AttributeView{}, true)
+ table.Rows = nil
+ table.RowCount = 0
+ } else {
+ table = getAttrViewTable(plan.source, &view, "")
+ }
+
+ aligns := getAttrViewTableAligns(table, false)
+ mdTable := &ast.Node{Type: ast.NodeTable, TableAligns: aligns}
+ mdTableHead := &ast.Node{Type: ast.NodeTableHead}
+ mdTable.AppendChild(mdTableHead)
+ mdTableHeadRow := &ast.Node{Type: ast.NodeTableRow, TableAligns: aligns}
+ mdTableHead.AppendChild(mdTableHeadRow)
+ for _, col := range table.Columns {
+ cell := &ast.Node{Type: ast.NodeTableCell}
+ cell.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(col.Name)})
+ mdTableHeadRow.AppendChild(cell)
+ }
+ node.InsertBefore(mdTable)
+ return mdTable
+}
+
func RenderTemplateWithMode(p, id string, mode TemplateRenderMode) (tree *parse.Tree, dom string,
summary *TemplateDocTreePlanSummary, err error) {
if TemplateRenderModeContent != mode && TemplateRenderModePreview != mode && TemplateRenderModeEditorInsert != mode {
@@ -483,6 +798,11 @@ func RenderTemplateWithMode(p, id string, mode TemplateRenderMode) (tree *parse.
return
}
}
+ attributeViewPlans, attributeViewCopies, prepareErr := prepareTemplateAttributeViews(tree, preview)
+ if nil != prepareErr {
+ err = prepareErr
+ return
+ }
var nodesNeedAppendChild, unlinks []*ast.Node
// 模板内部块旧 ID 到新 ID 的映射,用于成套改写模板内部的自引用
@@ -523,54 +843,30 @@ func RenderTemplateWithMode(p, id string, mode TemplateRenderMode) (tree *parse.
}
if ast.NodeAttributeView == n.Type {
- // 重新生成数据库视图
- attrView, parseErr := av.ParseAttributeView(n.AttributeViewID)
- if nil != parseErr {
- logging.LogErrorf("parse attribute view [%s] failed: %s", n.AttributeViewID, parseErr)
- } else {
- cloned := attrView.Clone()
- if nil == cloned {
- logging.LogErrorf("clone attribute view [%s] failed", n.AttributeViewID)
- return ast.WalkContinue
- }
-
- n.AttributeViewID = cloned.ID
- if !preview {
- // 非预览时持久化数据库
- if saveErr := av.SaveAttributeView(cloned); nil != saveErr {
- logging.LogErrorf("save attribute view [%s] failed: %s", cloned.ID, saveErr)
- }
- } else {
- // 预览时使用简单表格渲染
- viewID := n.IALAttr(av.NodeAttrView)
- view, getErr := resolveAttributeViewView(attrView, viewID, "", "")
- if nil != getErr {
- logging.LogErrorf("get attribute view [%s] failed: %s", n.AttributeViewID, getErr)
- return ast.WalkContinue
- }
-
- table := getAttrViewTable(attrView, view, "")
-
- aligns := getAttrViewTableAligns(table, false)
- mdTable := &ast.Node{Type: ast.NodeTable, TableAligns: aligns}
- mdTableHead := &ast.Node{Type: ast.NodeTableHead}
- mdTable.AppendChild(mdTableHead)
- mdTableHeadRow := &ast.Node{Type: ast.NodeTableRow, TableAligns: aligns}
- mdTableHead.AppendChild(mdTableHeadRow)
- for _, col := range table.Columns {
- cell := &ast.Node{Type: ast.NodeTableCell}
- cell.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(col.Name)})
- mdTableHeadRow.AppendChild(cell)
- }
-
- n.InsertBefore(mdTable)
- unlinks = append(unlinks, n)
- }
+ plan := attributeViewPlans[n]
+ if nil == plan {
+ err = fmt.Errorf("attribute view [%s] template plan not found", n.AttributeViewID)
+ return ast.WalkStop
+ }
+ appliedView, applyErr := applyTemplateAttributeViewPlan(n, plan)
+ if nil != applyErr {
+ err = applyErr
+ return ast.WalkStop
+ }
+ if preview && nil != appliedView {
+ templateAttributeViewPreviewTable(n, plan)
+ unlinks = append(unlinks, n)
}
}
return ast.WalkContinue
})
+ if nil != err {
+ return
+ }
+ if !preview {
+ saveTemplateAttributeViewCopies(attributeViewCopies, templateAttributeViewBoxID(tree))
+ }
// 用映射成套改写模板内部的自引用,并补全指向外部块的引用锚文本
// 仅命中 blockIDs 的引用(模板内部块)才会改写 ID;未命中的(外部块)保持不变
@@ -771,7 +1067,11 @@ func applyDocContentTemplate(templatePath, docID string) error {
}
}
tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
- return indexWriteTreeUpsertQueue(tree)
+ if err = indexWriteTreeUpsertQueue(tree); nil != err {
+ return err
+ }
+ av.BatchUpsertBlockRel(tree.Root.ChildrenByType(ast.NodeAttributeView))
+ return nil
}
func resolveDocContentTemplatePath(templatePath string) (string, error) {
diff --git a/kernel/model/template_database_fts5_test.go b/kernel/model/template_database_fts5_test.go
new file mode 100644
index 0000000000..235c232520
--- /dev/null
+++ b/kernel/model/template_database_fts5_test.go
@@ -0,0 +1,189 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestApplyTemplateDatabaseReferenceRegistersMirrors(t *testing.T) {
+ fixture := setupTemplateDocTreeTransactionTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904000300-avtmpl4")
+ code, err := DocSaveAsTemplateWithDatabaseMode(fixture.sourceID, "reference-mirror", false,
+ TemplateDatabaseModeReference)
+ if nil != err || 0 != code {
+ t.Fatalf("save reference template failed: code=%d, err=%v", code, err)
+ }
+
+ if err = applyDocContentTemplate("reference-mirror.md", fixture.targetID); nil != err {
+ t.Fatalf("apply reference content template failed: %v", err)
+ }
+ targetTree, err := LoadTreeByBlockID(fixture.targetID)
+ if nil != err {
+ t.Fatalf("load target tree failed: %v", err)
+ }
+ targetNodes := targetTree.Root.ChildrenByType(ast.NodeAttributeView)
+ if 2 != len(targetNodes) {
+ t.Fatalf("unexpected applied database block count: %d", len(targetNodes))
+ }
+ mirrors := treenode.GetMirrorAttrViewBlockIDs(database.attrView.ID)
+ for _, node := range targetNodes {
+ if !containsString(mirrors, node.ID) {
+ t.Fatalf("applied reference block [%s] was not registered as a mirror", node.ID)
+ }
+ }
+}
+
+func TestCreateAttributeViewItemMergesTemplateAndContextRelations(t *testing.T) {
+ fixture := setupTemplateDocTreeTransactionTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, ast.NewNodeID())
+ blockID := database.nodes[0].ID
+
+ target := av.NewAttributeView(ast.NewNodeID())
+ relationKey := av.NewKey(ast.NewNodeID(), "Project", "", av.KeyTypeRelation)
+ backRelationKey := av.NewKey(ast.NewNodeID(), "Tasks", "", av.KeyTypeRelation)
+ relationKey.Relation = &av.Relation{
+ AvID: target.ID, IsTwoWay: true, BackKeyID: backRelationKey.ID,
+ }
+ backRelationKey.Relation = &av.Relation{
+ AvID: database.attrView.ID, IsTwoWay: true, BackKeyID: relationKey.ID,
+ }
+ database.attrView.KeyValues = append(database.attrView.KeyValues, &av.KeyValues{Key: relationKey})
+ target.KeyValues = append(target.KeyValues, &av.KeyValues{Key: backRelationKey})
+
+ currentProjectID := ast.NewNodeID()
+ staticProjectID := ast.NewNodeID()
+ target.GetBlockKeyValues().Values = append(target.GetBlockKeyValues().Values,
+ &av.Value{
+ ID: ast.NewNodeID(), KeyID: target.GetBlockKey().ID, BlockID: currentProjectID, Type: av.KeyTypeBlock,
+ Block: &av.ValueBlock{ID: fixture.sourceID, Content: "Current project"},
+ },
+ &av.Value{
+ ID: ast.NewNodeID(), KeyID: target.GetBlockKey().ID, BlockID: staticProjectID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "Static project"},
+ },
+ )
+ for _, view := range target.Views {
+ view.ItemIDs = append(view.ItemIDs, currentProjectID, staticProjectID)
+ }
+ if err := av.SaveAttributeView(target); nil != err {
+ t.Fatal(err)
+ }
+
+ templateID := ast.NewNodeID()
+ if err := database.attrView.SetNewItemTemplates(&av.NewItemTemplatesConfig{Templates: []*av.NewItemTemplate{{
+ ID: templateID, Name: "With static project", TargetType: av.NewItemTargetDetached,
+ FieldValues: map[string]*av.NewItemFieldValue{
+ relationKey.ID: {
+ Mode: av.NewItemFieldValueStatic,
+ Value: &av.Value{Type: av.KeyTypeRelation, Relation: &av.ValueRelation{
+ BlockIDs: []string{staticProjectID, staticProjectID},
+ }},
+ },
+ },
+ }}}); nil != err {
+ t.Fatal(err)
+ }
+ if err := av.SaveAttributeView(database.attrView); nil != err {
+ t.Fatal(err)
+ }
+ if _, err := setAttributeViewContextFilterForTest(blockID, database.attrView.ID, relationKey.ID); nil != err {
+ t.Fatal(err)
+ }
+
+ created, err := CreateAttributeViewItem(database.attrView.ID, blockID, database.attrView.Views[0].ID,
+ templateID, "", "")
+ if nil != err {
+ t.Fatal(err)
+ }
+ updated, err := av.ParseAttributeView(database.attrView.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, updated.GetValue(relationKey.ID, created.ItemID),
+ staticProjectID, currentProjectID)
+
+ updatedTarget, err := av.ParseAttributeView(target.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, staticProjectID), created.ItemID)
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, currentProjectID), created.ItemID)
+
+ if err = removeAttributeViewBlock([]string{created.ItemID}, database.attrView.ID, blockID, nil); nil != err {
+ t.Fatal(err)
+ }
+ updated, err = av.ParseAttributeView(database.attrView.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if value := updated.GetValue(relationKey.ID, created.ItemID); nil != value {
+ t.Fatalf("removed item retained its source relation value: %#v", value)
+ }
+ updatedTarget, err = av.ParseAttributeView(target.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, staticProjectID))
+ assertContextFilterRelationIDs(t, updatedTarget.GetValue(backRelationKey.ID, currentProjectID))
+}
+
+func TestRemoveAttributeViewItemAllowsMissingTwoWayTarget(t *testing.T) {
+ fixture := setupTemplateDocTreeTransactionTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, ast.NewNodeID())
+ blockID := database.nodes[0].ID
+ itemID := ast.NewNodeID()
+ relationKey := av.NewKey(ast.NewNodeID(), "Missing", "", av.KeyTypeRelation)
+ relationKey.Relation = &av.Relation{
+ AvID: ast.NewNodeID(), IsTwoWay: true, BackKeyID: ast.NewNodeID(),
+ }
+ database.attrView.KeyValues = append(database.attrView.KeyValues, &av.KeyValues{
+ Key: relationKey,
+ Values: []*av.Value{{
+ ID: ast.NewNodeID(), KeyID: relationKey.ID, BlockID: itemID, Type: av.KeyTypeRelation,
+ Relation: &av.ValueRelation{BlockIDs: []string{ast.NewNodeID()}},
+ }},
+ })
+ database.attrView.GetBlockKeyValues().Values = append(database.attrView.GetBlockKeyValues().Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: database.attrView.GetBlockKey().ID, BlockID: itemID, Type: av.KeyTypeBlock,
+ IsDetached: true, Block: &av.ValueBlock{Content: "Stale relation"},
+ })
+ for _, view := range database.attrView.Views {
+ view.ItemIDs = append(view.ItemIDs, itemID)
+ }
+ if err := av.SaveAttributeView(database.attrView); nil != err {
+ t.Fatal(err)
+ }
+
+ if err := removeAttributeViewBlock([]string{itemID}, database.attrView.ID, blockID, nil); nil != err {
+ t.Fatal(err)
+ }
+ updated, err := av.ParseAttributeView(database.attrView.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if nil != updated.GetValue(database.attrView.GetBlockKey().ID, itemID) ||
+ nil != updated.GetValue(relationKey.ID, itemID) {
+ t.Fatal("item with a missing two-way target was not removed")
+ }
+}
diff --git a/kernel/model/template_doc_tree_fts5_test.go b/kernel/model/template_doc_tree_fts5_test.go
index a9f926a548..ef974be29b 100644
--- a/kernel/model/template_doc_tree_fts5_test.go
+++ b/kernel/model/template_doc_tree_fts5_test.go
@@ -447,16 +447,18 @@ func setupTemplateDocTreeTransactionTest(t *testing.T) *fileOperationTestFixture
originalTempDir := util.TempDir
originalQueueDir := util.QueueDir
originalConfDir := util.ConfDir
+ originalHistoryDir := util.HistoryDir
originalDBPath := util.DBPath
originalHistoryDBPath := util.HistoryDBPath
originalAssetContentDBPath := util.AssetContentDBPath
util.TempDir = t.TempDir()
util.QueueDir = filepath.Join(util.TempDir, "queue")
util.ConfDir = filepath.Join(util.TempDir, "conf")
+ util.HistoryDir = filepath.Join(util.TempDir, "history")
util.DBPath = filepath.Join(util.TempDir, util.DBName)
util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
- for _, dir := range []string{util.QueueDir, util.ConfDir} {
+ for _, dir := range []string{util.QueueDir, util.ConfDir, util.HistoryDir} {
if err := os.MkdirAll(dir, 0755); nil != err {
t.Fatalf("create transaction test directory [%s] failed: %v", dir, err)
}
@@ -480,6 +482,7 @@ func setupTemplateDocTreeTransactionTest(t *testing.T) *fileOperationTestFixture
util.TempDir = originalTempDir
util.QueueDir = originalQueueDir
util.ConfDir = originalConfDir
+ util.HistoryDir = originalHistoryDir
util.DBPath = originalDBPath
util.HistoryDBPath = originalHistoryDBPath
util.AssetContentDBPath = originalAssetContentDBPath
diff --git a/kernel/model/template_test.go b/kernel/model/template_test.go
index 16a5fe7061..b6d85b9d35 100644
--- a/kernel/model/template_test.go
+++ b/kernel/model/template_test.go
@@ -17,10 +17,18 @@ package model
import (
"fmt"
+ "os"
+ "path/filepath"
"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/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestRenderTemplateMapsDocumentReferenceToTargetRoot(t *testing.T) {
@@ -83,3 +91,319 @@ Internal target
t.Fatalf("external reference changed: got %q, want %q", refs["external"], fixture.targetID)
}
}
+
+type templateAttributeViewTestFixture struct {
+ attrView *av.AttributeView
+ nodes []*ast.Node
+}
+
+func addTemplateAttributeViewTestFixture(t *testing.T, fixture *fileOperationTestFixture,
+ avID string) *templateAttributeViewTestFixture {
+ t.Helper()
+ if nil == Conf.Editor {
+ Conf.Editor = conf.NewEditor()
+ }
+ if nil == Conf.Export {
+ Conf.Export = conf.NewExport()
+ }
+ if err := os.MkdirAll(filepath.Join(util.DataDir, "templates"), 0755); nil != err {
+ t.Fatalf("create templates directory failed: %v", err)
+ }
+ oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangs
+ util.Lang = "en"
+ util.AttrViewLangs = map[string]map[string]any{
+ "en": {
+ "key": "Key", "select": "Select", "table": "Table", "gallery": "Gallery",
+ },
+ }
+ t.Cleanup(func() { util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangs })
+ attrView := av.NewAttributeView(avID)
+ attrView.Name = "Template database"
+ attrView.Views[0].Name = "Table"
+ galleryView := av.NewGalleryView()
+ galleryView.Name = "Gallery"
+ for _, column := range attrView.Views[0].Table.Columns {
+ galleryView.Gallery.CardFields = append(galleryView.Gallery.CardFields,
+ &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: column.ID}})
+ }
+ attrView.Views = append(attrView.Views, galleryView)
+
+ itemID := ast.NewNodeID()
+ blockKey := attrView.GetBlockKey()
+ attrView.GetBlockKeyValues().Values = append(attrView.GetBlockKeyValues().Values, &av.Value{
+ ID: ast.NewNodeID(), KeyID: blockKey.ID, BlockID: itemID, Type: av.KeyTypeBlock, IsDetached: true,
+ Block: &av.ValueBlock{Content: "REFERENCE_TEMPLATE_PRIVATE_ROW"},
+ })
+ for _, view := range attrView.Views {
+ view.ItemIDs = append(view.ItemIDs, itemID)
+ }
+ if err := av.SaveAttributeView(attrView); nil != err {
+ t.Fatalf("save attribute view failed: %v", err)
+ }
+ t.Cleanup(func() { av.SetAVBoxID(attrView.ID, "") })
+
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("load source tree failed: %v", err)
+ }
+ for nil != tree.Root.FirstChild {
+ tree.Root.FirstChild.Unlink()
+ }
+ first := &ast.Node{
+ Type: ast.NodeAttributeView,
+ ID: "20260904000001-avnode1",
+ AttributeViewID: attrView.ID,
+ AttributeViewType: string(av.LayoutTypeTable),
+ }
+ first.SetIALAttr("id", first.ID)
+ first.SetIALAttr(av.NodeAttrView, attrView.Views[0].ID)
+ first.SetIALAttr(av.NodeAttrVisibleViewIDs, attrView.Views[0].ID+","+attrView.Views[1].ID)
+ second := &ast.Node{
+ Type: ast.NodeAttributeView,
+ ID: "20260904000002-avnode2",
+ AttributeViewID: attrView.ID,
+ AttributeViewType: string(av.LayoutTypeGallery),
+ }
+ second.SetIALAttr("id", second.ID)
+ second.SetIALAttr(av.NodeAttrView, attrView.Views[1].ID)
+ second.SetIALAttr(av.NodeAttrVisibleViewIDs, attrView.Views[1].ID)
+ tree.Root.AppendChild(first)
+ tree.Root.AppendChild(second)
+ if _, err = filesys.WriteTree(tree); nil != err {
+ t.Fatalf("write source tree failed: %v", err)
+ }
+ treenode.UpsertBlockTree(tree)
+ av.BatchUpsertBlockRel([]*ast.Node{first, second})
+ return &templateAttributeViewTestFixture{attrView: attrView, nodes: []*ast.Node{first, second}}
+}
+
+func parseSavedTemplateAttributeViews(t *testing.T, name string) (*ast.Node, []*ast.Node) {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join(util.DataDir, "templates", name+".md"))
+ if nil != err {
+ t.Fatalf("read saved template failed: %v", err)
+ }
+ tree := parseKTree(data)
+ if nil == tree {
+ t.Fatal("parse saved template failed")
+ }
+ return tree.Root, tree.Root.ChildrenByType(ast.NodeAttributeView)
+}
+
+func attributeViewFileCount(t *testing.T) int {
+ t.Helper()
+ files, err := filepath.Glob(filepath.Join(util.DataDir, "storage", "av", "*.json"))
+ if nil != err {
+ t.Fatalf("list attribute view files failed: %v", err)
+ }
+ return len(files)
+}
+
+func containsString(values []string, expected string) bool {
+ for _, value := range values {
+ if value == expected {
+ return true
+ }
+ }
+ return false
+}
+
+func TestTemplateDatabaseReferencePreservesViews(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904000000-avtmpl1")
+ code, err := DocSaveAsTemplateWithDatabaseMode(fixture.sourceID, "reference", false,
+ TemplateDatabaseModeReference)
+ if nil != err || 0 != code {
+ t.Fatalf("save reference template failed: code=%d, err=%v", code, err)
+ }
+
+ _, templateNodes := parseSavedTemplateAttributeViews(t, "reference")
+ if 2 != len(templateNodes) {
+ t.Fatalf("unexpected saved database block count: %d", len(templateNodes))
+ }
+ for i, node := range templateNodes {
+ if string(TemplateDatabaseModeReference) != node.IALAttr(templateDatabaseModeAttr) {
+ t.Fatalf("reference marker missing from saved block %d", i)
+ }
+ if "" != database.nodes[i].IALAttr(templateDatabaseModeAttr) {
+ t.Fatalf("reference marker leaked into source block %d", i)
+ }
+ }
+
+ beforeFiles := attributeViewFileCount(t)
+ beforeRels := av.GetBlockRels()[database.attrView.ID]
+ previewTree, previewDOM, _, err := RenderTemplateWithMode(
+ filepath.Join(util.DataDir, "templates", "reference.md"), fixture.targetID, TemplateRenderModePreview)
+ if nil != err {
+ t.Fatalf("preview reference template failed: %v", err)
+ }
+ if 0 != len(previewTree.Root.ChildrenByType(ast.NodeAttributeView)) {
+ t.Fatal("reference preview should replace database blocks with structural tables")
+ }
+ if strings.Contains(previewDOM, "REFERENCE_TEMPLATE_PRIVATE_ROW") {
+ t.Fatal("reference preview exposed database row content")
+ }
+ if !strings.Contains(previewDOM, "Key") {
+ t.Fatal("reference preview did not retain the database table header")
+ }
+ if beforeFiles != attributeViewFileCount(t) {
+ t.Fatal("reference preview persisted an attribute view copy")
+ }
+ if len(beforeRels) != len(av.GetBlockRels()[database.attrView.ID]) {
+ t.Fatal("reference preview changed mirror registrations")
+ }
+
+ contentTree, _, _, err := RenderTemplateWithMode(
+ filepath.Join(util.DataDir, "templates", "reference.md"), fixture.targetID, TemplateRenderModeContent)
+ if nil != err {
+ t.Fatalf("render reference template failed: %v", err)
+ }
+ renderedNodes := contentTree.Root.ChildrenByType(ast.NodeAttributeView)
+ if 2 != len(renderedNodes) {
+ t.Fatalf("unexpected rendered database block count: %d", len(renderedNodes))
+ }
+ for i, node := range renderedNodes {
+ if database.attrView.ID != node.AttributeViewID {
+ t.Fatalf("reference block %d changed database ID: %s", i, node.AttributeViewID)
+ }
+ if database.nodes[i].IALAttr(av.NodeAttrView) != node.IALAttr(av.NodeAttrView) ||
+ database.nodes[i].IALAttr(av.NodeAttrVisibleViewIDs) != node.IALAttr(av.NodeAttrVisibleViewIDs) {
+ t.Fatalf("reference block %d changed view selection", i)
+ }
+ if "" != node.IALAttr(templateDatabaseModeAttr) {
+ t.Fatalf("reference marker leaked into rendered block %d", i)
+ }
+ }
+ if beforeFiles != attributeViewFileCount(t) {
+ t.Fatal("reference rendering persisted an attribute view copy")
+ }
+}
+
+func TestTemplateDatabaseCopyClonesSharedDatabaseOnce(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904000100-avtmpl2")
+ code, err := DocSaveAsTemplate(fixture.sourceID, "copy", false)
+ if nil != err || 0 != code {
+ t.Fatalf("save copy template failed: code=%d, err=%v", code, err)
+ }
+ _, templateNodes := parseSavedTemplateAttributeViews(t, "copy")
+ for i, node := range templateNodes {
+ if "" != node.IALAttr(templateDatabaseModeAttr) {
+ t.Fatalf("copy marker persisted on saved block %d", i)
+ }
+ }
+
+ beforeFiles := attributeViewFileCount(t)
+ if _, _, _, err = RenderTemplateWithMode(filepath.Join(util.DataDir, "templates", "copy.md"), fixture.targetID,
+ TemplateRenderModePreview); nil != err {
+ t.Fatalf("preview copy template failed: %v", err)
+ }
+ if beforeFiles != attributeViewFileCount(t) {
+ t.Fatal("copy preview persisted an attribute view")
+ }
+
+ contentTree, _, _, err := RenderTemplateWithMode(filepath.Join(util.DataDir, "templates", "copy.md"), fixture.targetID,
+ TemplateRenderModeContent)
+ if nil != err {
+ t.Fatalf("render copy template failed: %v", err)
+ }
+ if beforeFiles+1 != attributeViewFileCount(t) {
+ t.Fatalf("shared database should be cloned once: before=%d, after=%d", beforeFiles, attributeViewFileCount(t))
+ }
+ renderedNodes := contentTree.Root.ChildrenByType(ast.NodeAttributeView)
+ if 2 != len(renderedNodes) || renderedNodes[0].AttributeViewID != renderedNodes[1].AttributeViewID {
+ t.Fatalf("shared database blocks did not reuse one copy: %+v", renderedNodes)
+ }
+ if database.attrView.ID == renderedNodes[0].AttributeViewID {
+ t.Fatal("copy template retained the source database ID")
+ }
+ cloned, err := av.ParseAttributeViewInBox(renderedNodes[0].AttributeViewID, "")
+ if nil != err {
+ t.Fatalf("parse cloned attribute view failed: %v", err)
+ }
+ if database.attrView.Views[0].ID == cloned.Views[0].ID || database.attrView.Views[1].ID == cloned.Views[1].ID {
+ t.Fatal("copied database retained source view IDs")
+ }
+ if cloned.Views[0].ID != renderedNodes[0].IALAttr(av.NodeAttrView) ||
+ cloned.Views[1].ID != renderedNodes[1].IALAttr(av.NodeAttrView) {
+ t.Fatal("copied database block view IDs were not remapped")
+ }
+ if cloned.Views[0].ID+","+cloned.Views[1].ID != renderedNodes[0].IALAttr(av.NodeAttrVisibleViewIDs) ||
+ cloned.Views[1].ID != renderedNodes[1].IALAttr(av.NodeAttrVisibleViewIDs) {
+ t.Fatal("copied database visible view IDs were not remapped")
+ }
+}
+
+func TestTemplateDatabaseReferenceValidatesExistenceViewsAndEncryptionBoundary(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904000200-avtmpl3")
+ referenceNode := &ast.Node{Type: ast.NodeAttributeView, AttributeViewID: database.attrView.ID}
+ referenceNode.SetIALAttr(templateDatabaseModeAttr, string(TemplateDatabaseModeReference))
+ referenceNode.SetIALAttr(av.NodeAttrView, "20260904000201-missing")
+ tree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}, Box: fixture.box.ID}
+ tree.Root.AppendChild(referenceNode)
+ if _, _, err := prepareTemplateAttributeViews(tree, false); nil == err {
+ t.Fatal("reference template accepted a missing selected view")
+ }
+
+ referenceNode.SetIALAttr(av.NodeAttrView, database.attrView.Views[0].ID)
+ referenceNode.SetIALAttr(av.NodeAttrVisibleViewIDs, "20260904000202-missing")
+ if _, _, err := prepareTemplateAttributeViews(tree, false); nil == err {
+ t.Fatal("reference template accepted a missing visible view")
+ }
+
+ referenceNode.SetIALAttr(templateDatabaseModeAttr, string(TemplateDatabaseModeCopy))
+ referenceNode.SetIALAttr(av.NodeAttrView, "20260904000201-missing")
+ referenceNode.SetIALAttr(av.NodeAttrVisibleViewIDs,
+ database.attrView.Views[0].ID+",20260904000202-missing")
+ plans, copies, err := prepareTemplateAttributeViews(tree, false)
+ if nil != err || 1 != len(copies) {
+ t.Fatalf("copy template should tolerate stale view IDs: copies=%d, err=%v", len(copies), err)
+ }
+ if _, err = applyTemplateAttributeViewPlan(referenceNode, plans[referenceNode]); nil != err {
+ t.Fatalf("apply tolerant copy plan failed: %v", err)
+ }
+ if "" != referenceNode.IALAttr(av.NodeAttrView) {
+ t.Fatal("copy template retained a stale selected view ID")
+ }
+ if copies[0].target.Views[0].ID != referenceNode.IALAttr(av.NodeAttrVisibleViewIDs) {
+ t.Fatal("copy template did not retain the valid visible view ID")
+ }
+
+ referenceNode.AttributeViewID = database.attrView.ID
+ referenceNode.SetIALAttr(templateDatabaseModeAttr, string(TemplateDatabaseModeCopy))
+ markRuntimeEncryptedBox(fixture.box.ID)
+ t.Cleanup(func() { forgetRuntimeEncryptedBox(fixture.box.ID) })
+ if _, _, err := prepareTemplateAttributeViews(tree, false); nil != err {
+ t.Fatalf("copy template should retain legacy cross-box fallback: %v", err)
+ }
+ referenceNode.SetIALAttr(templateDatabaseModeAttr, string(TemplateDatabaseModeReference))
+ referenceNode.SetIALAttr(av.NodeAttrView, database.attrView.Views[0].ID)
+ referenceNode.SetIALAttr(av.NodeAttrVisibleViewIDs, database.attrView.Views[0].ID)
+ if _, _, err := prepareTemplateAttributeViews(tree, false); nil == err {
+ t.Fatal("reference template crossed from an encrypted notebook to a global database")
+ }
+
+ if _, err := DocSaveAsTemplateWithDatabaseMode(fixture.sourceID, "invalid", false,
+ TemplateDatabaseMode("invalid")); nil == err {
+ t.Fatal("save template accepted an unsupported database mode")
+ }
+}
+
+func TestTemplateDatabasePreviewDoesNotMutateSourceView(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, "20260904000400-avtmpl5")
+ gallery := database.attrView.Views[1]
+ if nil != gallery.Table {
+ t.Fatal("gallery test fixture unexpectedly has a table layout")
+ }
+ root := &ast.Node{Type: ast.NodeDocument}
+ node := &ast.Node{Type: ast.NodeAttributeView, AttributeViewID: database.attrView.ID}
+ root.AppendChild(node)
+ templateAttributeViewPreviewTable(node, &templateAttributeViewPlan{
+ mode: TemplateDatabaseModeReference, source: database.attrView, target: database.attrView, selectedView: gallery,
+ })
+ if nil != gallery.Table {
+ t.Fatal("reference preview mutated the source gallery view")
+ }
+}
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index e04c408495..03e653dfb6 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -297,6 +297,8 @@ func performTx(tx *Transaction) (ret *TxErr) {
ret = tx.doSetAttrViewNewItemTemplates(op)
case "setAttrViewFilters":
ret = tx.doSetAttrViewFilters(op)
+ case "setAttrViewContextFilter":
+ ret = tx.doSetAttrViewContextFilter(op)
case "setAttrViewColRelationFilters":
ret = tx.doSetAttrViewColRelationFilters(op)
case "setAttrViewColRollupFilters":
@@ -343,7 +345,8 @@ func performTx(tx *Transaction) (ret *TxErr) {
operations := []*Operation{op}
for nextIndex := operationIndex + 1; nextIndex < len(tx.DoOperations); nextIndex++ {
nextOperation := tx.DoOperations[nextIndex]
- if "updateAttrViewCell" != nextOperation.Action || op.AvID != nextOperation.AvID {
+ if "updateAttrViewCell" != nextOperation.Action || op.AvID != nextOperation.AvID ||
+ op.BlockID != nextOperation.BlockID {
break
}
operations = append(operations, nextOperation)