An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support explicit tag collection targets https://github.com/siyuan-note/siyuan/issues/20646
Daniel39ebb5baee79
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 915ae5acae..bb5c1c21a6 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "هدف التجميع",+ "automationCollectionTargetBlock": "الكتلة التي تحتوي على الوسم",+ "automationCollectionTargetContainer": "كتلة الحاوية",+ "automationCollectionTargetDefaultTip": "عند استخدام شروط الوسوم، تنتمي الفقرة الأولى من عنصر القائمة إلى العنصر؛ وتطابق الكتل الأخرى وسومها الخاصة",+ "automationCollectionTargetBlockTip": "عند استخدام شروط الوسوم، اجمع الكتلة التي تحتوي على الوسم وفق نوعها وسماتها",+ "automationCollectionTargetContainerTip": "عند استخدام شروط الوسوم، اجمع أقرب حاوية تطابق النوع والسمات؛ ويجب تحديد المستندات صراحةً",+ "automationCollectionTargetChangeTip": "يحافظ تغيير الخيار على الإدخالات والحقول الحالية؛ راجع النتائج الجديدة في المعاينة","automationCollectionRuleChangeTip": "يحافظ تغيير الشروط أو تعطيل القاعدة أو حذفها على العناصر المجمّعة وقيم حقولها","automationNotifySuccess": "الإشعار عند النجاح","automationResultRule": "اكتملت الأتمتة «${1}»: ${2}",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 092eefe3f9..b498a06863 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Sammelziel",+ "automationCollectionTargetBlock": "Block mit dem Tag",+ "automationCollectionTargetContainer": "Containerblock",+ "automationCollectionTargetDefaultTip": "Bei Tag-Bedingungen gehört der erste Absatz eines Listeneintrags zum Eintrag; andere Blöcke prüfen ihre eigenen Tags",+ "automationCollectionTargetBlockTip": "Bei Tag-Bedingungen den Block mit dem Tag anhand seines Typs und seiner Attribute sammeln",+ "automationCollectionTargetContainerTip": "Bei Tag-Bedingungen den nächsten Container mit passendem Typ und passenden Attributen sammeln; Dokumente müssen ausdrücklich ausgewählt werden",+ "automationCollectionTargetChangeTip": "Ein Wechsel erhält vorhandene Einträge und Felder; prüfen Sie die neuen Ergebnisse in der Vorschau","automationCollectionRuleChangeTip": "Geänderte Bedingungen sowie das Deaktivieren oder Löschen einer Regel erhalten gesammelte Einträge und ihre Feldwerte","automationNotifySuccess": "Bei Erfolg benachrichtigen","automationResultRule": "Automatisierung „${1}“ abgeschlossen: ${2}",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 1bf1ca4203..044c5dc54e 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Collect",+ "automationCollectionTargetBlock": "Block containing the tag",+ "automationCollectionTargetContainer": "Container block",+ "automationCollectionTargetDefaultTip": "With tag conditions, the first paragraph of a list item belongs to the list item; other blocks match their own tags",+ "automationCollectionTargetBlockTip": "With tag conditions, collect the block containing the tag using its type and attributes",+ "automationCollectionTargetContainerTip": "With tag conditions, collect the nearest container matching the type and attributes; documents must be explicitly selected",+ "automationCollectionTargetChangeTip": "Changing this option preserves existing entries and fields; preview the collection to check the new results","automationCollectionRuleChangeTip": "Changing conditions, disabling, or deleting a rule preserves collected entries and their field values","automationNotifySuccess": "Notify on success","automationResultRule": "Automation \"${1}\" completed: ${2}",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 599404e63d..7d9f40a30d 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Objeto de recopilación",+ "automationCollectionTargetBlock": "Bloque que contiene la etiqueta",+ "automationCollectionTargetContainer": "Bloque contenedor",+ "automationCollectionTargetDefaultTip": "Con condiciones de etiquetas, el primer párrafo de un elemento de lista pertenece al elemento; los demás bloques comparan sus propias etiquetas",+ "automationCollectionTargetBlockTip": "Con condiciones de etiquetas, recopilar el bloque que contiene la etiqueta según su tipo y atributos",+ "automationCollectionTargetContainerTip": "Con condiciones de etiquetas, recopilar el contenedor más cercano que cumpla el tipo y los atributos; los documentos deben seleccionarse explícitamente",+ "automationCollectionTargetChangeTip": "Cambiar esta opción conserva las entradas y los campos existentes; compruebe los nuevos resultados en la vista previa","automationCollectionRuleChangeTip": "Cambiar condiciones, desactivar o eliminar una regla conserva las entradas recopiladas y los valores de sus campos","automationNotifySuccess": "Notificar al completarse correctamente","automationResultRule": "Automatización «${1}» completada: ${2}",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 8f16cc7c1d..ac1db97bf0 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Objet à collecter",+ "automationCollectionTargetBlock": "Bloc contenant l’étiquette",+ "automationCollectionTargetContainer": "Bloc conteneur",+ "automationCollectionTargetDefaultTip": "Avec des conditions d’étiquettes, le premier paragraphe d’un élément de liste appartient à cet élément ; les autres blocs vérifient leurs propres étiquettes",+ "automationCollectionTargetBlockTip": "Avec des conditions d’étiquettes, collecter le bloc contenant l’étiquette selon son type et ses attributs",+ "automationCollectionTargetContainerTip": "Avec des conditions d’étiquettes, collecter le conteneur le plus proche correspondant au type et aux attributs ; les documents doivent être sélectionnés explicitement",+ "automationCollectionTargetChangeTip": "Changer cette option conserve les entrées et champs existants ; vérifiez les nouveaux résultats dans l’aperçu","automationCollectionRuleChangeTip": "Modifier les conditions, désactiver ou supprimer une règle conserve les entrées collectées et les valeurs de leurs champs","automationNotifySuccess": "Notifier en cas de succès","automationResultRule": "Automatisation « ${1} » terminée : ${2}",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex db9ef067f5..225a9e8b0a 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "יעד האיסוף",+ "automationCollectionTargetBlock": "בלוק המכיל את התגית",+ "automationCollectionTargetContainer": "בלוק מכל",+ "automationCollectionTargetDefaultTip": "כאשר מוגדרים תנאי תגיות, הפסקה הראשונה בפריט רשימה שייכת לפריט; בלוקים אחרים בודקים את התגיות שלהם",+ "automationCollectionTargetBlockTip": "כאשר מוגדרים תנאי תגיות, יש לאסוף את הבלוק המכיל את התגית לפי הסוג והמאפיינים שלו",+ "automationCollectionTargetContainerTip": "כאשר מוגדרים תנאי תגיות, יש לאסוף את המכל הקרוב ביותר התואם לסוג ולמאפיינים; יש לבחור מסמכים במפורש",+ "automationCollectionTargetChangeTip": "שינוי האפשרות שומר על הרשומות והשדות הקיימים; ניתן לבדוק את התוצאות החדשות בתצוגה המקדימה","automationCollectionRuleChangeTip": "שינוי תנאים, השבתה או מחיקה של כלל שומרים על הרשומות שנאספו ועל ערכי השדות שלהן","automationNotifySuccess": "הודעה לאחר הצלחה","automationResultRule": "האוטומציה „${1}” הושלמה: ${2}",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 5b5b4ef39f..3e1380e623 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "संग्रह लक्ष्य",+ "automationCollectionTargetBlock": "टैग वाला ब्लॉक",+ "automationCollectionTargetContainer": "कंटेनर ब्लॉक",+ "automationCollectionTargetDefaultTip": "टैग की शर्तें होने पर सूची आइटम का पहला अनुच्छेद उसी आइटम का भाग माना जाता है; अन्य ब्लॉक अपने टैग से मिलान करते हैं",+ "automationCollectionTargetBlockTip": "टैग की शर्तें होने पर टैग वाले ब्लॉक को उसके प्रकार और विशेषताओं के अनुसार संग्रहित करें",+ "automationCollectionTargetContainerTip": "टैग की शर्तें होने पर प्रकार और विशेषताओं से मेल खाने वाला निकटतम कंटेनर संग्रहित करें; दस्तावेज़ स्पष्ट रूप से चुनने होंगे",+ "automationCollectionTargetChangeTip": "यह विकल्प बदलने पर मौजूदा प्रविष्टियाँ और फ़ील्ड सुरक्षित रहते हैं; नए परिणाम पूर्वावलोकन में देखें","automationCollectionRuleChangeTip": "शर्तें बदलने, नियम बंद करने या हटाने पर एकत्रित प्रविष्टियाँ और उनके फ़ील्ड मान बने रहते हैं","automationNotifySuccess": "सफल होने पर सूचना दें","automationResultRule": "स्वचालन “${1}” पूरा हुआ: ${2}",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex bbd8da9a92..7548f71309 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Objek pengumpulan",+ "automationCollectionTargetBlock": "Blok yang berisi tag",+ "automationCollectionTargetContainer": "Blok wadah",+ "automationCollectionTargetDefaultTip": "Dengan kondisi tag, paragraf pertama item daftar menjadi bagian item tersebut; blok lain mencocokkan tag masing-masing",+ "automationCollectionTargetBlockTip": "Dengan kondisi tag, kumpulkan blok yang berisi tag berdasarkan jenis dan atributnya",+ "automationCollectionTargetContainerTip": "Dengan kondisi tag, kumpulkan wadah terdekat yang sesuai dengan jenis dan atribut; dokumen harus dipilih secara eksplisit",+ "automationCollectionTargetChangeTip": "Perubahan mempertahankan entri dan kolom yang ada; periksa hasil baru melalui pratinjau","automationCollectionRuleChangeTip": "Mengubah kondisi, menonaktifkan, atau menghapus aturan mempertahankan entri yang dikumpulkan dan nilai bidangnya","automationNotifySuccess": "Beri tahu saat berhasil","automationResultRule": "Otomatisasi “${1}” selesai: ${2}",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 8c590a654a..e9ea36b3f3 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Oggetto da raccogliere",+ "automationCollectionTargetBlock": "Blocco contenente il tag",+ "automationCollectionTargetContainer": "Blocco contenitore",+ "automationCollectionTargetDefaultTip": "Con condizioni sui tag, il primo paragrafo di una voce di elenco appartiene alla voce; gli altri blocchi verificano i propri tag",+ "automationCollectionTargetBlockTip": "Con condizioni sui tag, raccogli il blocco contenente il tag in base al tipo e agli attributi",+ "automationCollectionTargetContainerTip": "Con condizioni sui tag, raccogli il contenitore più vicino che soddisfa tipo e attributi; i documenti vanno selezionati esplicitamente",+ "automationCollectionTargetChangeTip": "La modifica conserva le voci e i campi esistenti; controlla i nuovi risultati nell’anteprima","automationCollectionRuleChangeTip": "Modificare le condizioni, disabilitare o eliminare una regola conserva le voci raccolte e i valori dei loro campi","automationNotifySuccess": "Notifica in caso di successo","automationResultRule": "Automazione «${1}» completata: ${2}",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 64810532b7..2d184fde75 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "収集対象",+ "automationCollectionTargetBlock": "タグを含むブロック",+ "automationCollectionTargetContainer": "コンテナブロック",+ "automationCollectionTargetDefaultTip": "タグ条件がある場合、リスト項目の最初の段落はリスト項目に属し、他のブロックは自身のタグと照合します",+ "automationCollectionTargetBlockTip": "タグ条件がある場合、タグを含むブロックの種類と属性で絞り込んで収集します",+ "automationCollectionTargetContainerTip": "タグ条件がある場合、種類と属性の条件に一致する最も近いコンテナを収集します。文書は明示的な選択が必要です",+ "automationCollectionTargetChangeTip": "切り替えても既存の項目やフィールドは変更されません。プレビューで新しい収集結果を確認できます","automationCollectionRuleChangeTip": "条件の変更、ルールの無効化や削除では、収集済みの項目とフィールド値を保持します","automationNotifySuccess": "実行成功時に通知","automationResultRule": "自動化「${1}」を実行しました:${2}",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex d05d49fb98..c7518d73c8 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "수집 대상",+ "automationCollectionTargetBlock": "태그가 있는 블록",+ "automationCollectionTargetContainer": "컨테이너 블록",+ "automationCollectionTargetDefaultTip": "태그 조건이 있으면 목록 항목의 첫 문단은 해당 항목에 속하며, 다른 블록은 자체 태그로 일치 여부를 확인합니다",+ "automationCollectionTargetBlockTip": "태그 조건이 있으면 태그가 있는 블록의 유형과 속성에 따라 수집합니다",+ "automationCollectionTargetContainerTip": "태그 조건이 있으면 유형과 속성 조건을 충족하는 가장 가까운 컨테이너를 수집합니다. 문서는 명시적으로 선택해야 합니다",+ "automationCollectionTargetChangeTip": "변경해도 기존 항목과 필드는 유지됩니다. 미리보기에서 새로운 수집 결과를 확인하세요","automationCollectionRuleChangeTip": "조건 변경, 규칙 비활성화 또는 삭제 시에도 수집한 항목과 필드 값은 유지됩니다","automationNotifySuccess": "실행 성공 시 알림","automationResultRule": "자동화 “${1}” 실행 완료: ${2}",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex afff839e05..7167753fda 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Verzameldoel",+ "automationCollectionTargetBlock": "Blok met de tag",+ "automationCollectionTargetContainer": "Containerblok",+ "automationCollectionTargetDefaultTip": "Bij tagvoorwaarden hoort de eerste alinea van een lijstitem bij dat item; andere blokken controleren hun eigen tags",+ "automationCollectionTargetBlockTip": "Bij tagvoorwaarden het blok met de tag verzamelen op basis van het type en de kenmerken",+ "automationCollectionTargetContainerTip": "Bij tagvoorwaarden de dichtstbijzijnde container met het juiste type en de juiste kenmerken verzamelen; documenten moeten expliciet worden geselecteerd",+ "automationCollectionTargetChangeTip": "Wijzigen behoudt bestaande items en velden; controleer de nieuwe resultaten in het voorbeeld","automationCollectionRuleChangeTip": "Voorwaarden wijzigen of een regel uitschakelen of verwijderen behoudt verzamelde items en hun veldwaarden","automationNotifySuccess": "Melden bij succes","automationResultRule": "Automatisering ‘${1}’ voltooid: ${2}",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 928b0eb8b3..db9916c786 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Obiekt zbierania",+ "automationCollectionTargetBlock": "Blok zawierający tag",+ "automationCollectionTargetContainer": "Blok kontenera",+ "automationCollectionTargetDefaultTip": "Przy warunkach tagów pierwszy akapit elementu listy należy do tego elementu; pozostałe bloki sprawdzają własne tagi",+ "automationCollectionTargetBlockTip": "Przy warunkach tagów zbieraj blok zawierający tag według jego typu i atrybutów",+ "automationCollectionTargetContainerTip": "Przy warunkach tagów zbieraj najbliższy kontener zgodny z typem i atrybutami; dokumenty wymagają jawnego wyboru",+ "automationCollectionTargetChangeTip": "Zmiana zachowuje istniejące wpisy i pola; sprawdź nowe wyniki w podglądzie","automationCollectionRuleChangeTip": "Zmiana warunków, wyłączenie lub usunięcie reguły zachowuje zebrane wpisy i wartości ich pól","automationNotifySuccess": "Powiadamiaj po pomyślnym wykonaniu","automationResultRule": "Automatyzacja „${1}” zakończona: ${2}",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex e138b5f581..ef1e688f6d 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Objeto da coleta",+ "automationCollectionTargetBlock": "Bloco que contém a etiqueta",+ "automationCollectionTargetContainer": "Bloco contêiner",+ "automationCollectionTargetDefaultTip": "Com condições de etiquetas, o primeiro parágrafo de um item de lista pertence ao item; os demais blocos verificam suas próprias etiquetas",+ "automationCollectionTargetBlockTip": "Com condições de etiquetas, coletar o bloco que contém a etiqueta conforme seu tipo e atributos",+ "automationCollectionTargetContainerTip": "Com condições de etiquetas, coletar o contêiner mais próximo que corresponda ao tipo e aos atributos; documentos devem ser selecionados explicitamente",+ "automationCollectionTargetChangeTip": "Alterar esta opção preserva as entradas e os campos existentes; confira os novos resultados na prévia","automationCollectionRuleChangeTip": "Alterar condições, desativar ou excluir uma regra preserva as entradas coletadas e os valores dos campos","automationNotifySuccess": "Notificar em caso de sucesso","automationResultRule": "Automação “${1}” concluída: ${2}",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 5522cddf18..63154020e2 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Объект сбора",+ "automationCollectionTargetBlock": "Блок с тегом",+ "automationCollectionTargetContainer": "Блок-контейнер",+ "automationCollectionTargetDefaultTip": "При условиях по тегам первый абзац элемента списка относится к этому элементу; остальные блоки проверяют собственные теги",+ "automationCollectionTargetBlockTip": "При условиях по тегам собирать блок с тегом с учётом его типа и атрибутов",+ "automationCollectionTargetContainerTip": "При условиях по тегам собирать ближайший контейнер, соответствующий типу и атрибутам; документы нужно выбирать явно",+ "automationCollectionTargetChangeTip": "Изменение сохраняет существующие записи и поля; проверьте новые результаты в предпросмотре","automationCollectionRuleChangeTip": "Изменение условий, отключение или удаление правила сохраняет собранные записи и значения их полей","automationNotifySuccess": "Уведомлять об успешном выполнении","automationResultRule": "Автоматизация «${1}» выполнена: ${2}",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 38dd3ebd91..6dff34e192 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Objekt zbierania",+ "automationCollectionTargetBlock": "Blok obsahujúci značku",+ "automationCollectionTargetContainer": "Kontajnerový blok",+ "automationCollectionTargetDefaultTip": "Pri podmienkach značiek patrí prvý odsek položky zoznamu k položke; ostatné bloky porovnávajú vlastné značky",+ "automationCollectionTargetBlockTip": "Pri podmienkach značiek zbierať blok obsahujúci značku podľa jeho typu a atribútov",+ "automationCollectionTargetContainerTip": "Pri podmienkach značiek zbierať najbližší kontajner zodpovedajúci typu a atribútom; dokumenty treba výslovne vybrať",+ "automationCollectionTargetChangeTip": "Zmena zachová existujúce položky a polia; nové výsledky skontrolujte v náhľade","automationCollectionRuleChangeTip": "Zmena podmienok, vypnutie alebo odstránenie pravidla zachová zhromaždené položky a hodnoty ich polí","automationNotifySuccess": "Upozorniť pri úspechu","automationResultRule": "Automatizácia „${1}“ dokončená: ${2}",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex e635e04dac..4b2effac99 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Објекат прикупљања",+ "automationCollectionTargetBlock": "Блок који садржи ознаку",+ "automationCollectionTargetContainer": "Контејнерски блок",+ "automationCollectionTargetDefaultTip": "Када постоје услови ознака, први пасус ставке листе припада тој ставци; остали блокови проверавају сопствене ознаке",+ "automationCollectionTargetBlockTip": "Када постоје услови ознака, прикупљај блок који садржи ознаку према његовом типу и атрибутима",+ "automationCollectionTargetContainerTip": "Када постоје услови ознака, прикупљај најближи контејнер који одговара типу и атрибутима; документи морају бити изричито изабрани",+ "automationCollectionTargetChangeTip": "Промена чува постојеће ставке и поља; проверите нове резултате у прегледу","automationCollectionRuleChangeTip": "Промена услова, искључивање или брисање правила задржава прикупљене ставке и вредности њихових поља","automationNotifySuccess": "Обавести о успешном извршавању","automationResultRule": "Аутоматизација „${1}“ је завршена: ${2}",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 1bf0e33c1a..6e39974714 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "เป้าหมายการรวบรวม",+ "automationCollectionTargetBlock": "บล็อกที่มีแท็ก",+ "automationCollectionTargetContainer": "บล็อกคอนเทนเนอร์",+ "automationCollectionTargetDefaultTip": "เมื่อมีเงื่อนไขแท็ก ย่อหน้าแรกของรายการจะถือเป็นส่วนหนึ่งของรายการ ส่วนบล็อกอื่นจะตรวจสอบแท็กของตนเอง",+ "automationCollectionTargetBlockTip": "เมื่อมีเงื่อนไขแท็ก ให้รวบรวมบล็อกที่มีแท็กตามประเภทและคุณลักษณะของบล็อกนั้น",+ "automationCollectionTargetContainerTip": "เมื่อมีเงื่อนไขแท็ก ให้รวบรวมคอนเทนเนอร์ที่ใกล้ที่สุดซึ่งตรงตามประเภทและคุณลักษณะ ต้องเลือกเอกสารอย่างชัดเจน",+ "automationCollectionTargetChangeTip": "การเปลี่ยนตัวเลือกจะคงรายการและเขตข้อมูลเดิมไว้ ตรวจสอบผลลัพธ์ใหม่ได้ในการแสดงตัวอย่าง","automationCollectionRuleChangeTip": "การเปลี่ยนเงื่อนไข ปิดใช้งาน หรือลบกฎจะเก็บรายการที่รวบรวมและค่าฟิลด์ไว้","automationNotifySuccess": "แจ้งเตือนเมื่อสำเร็จ","automationResultRule": "ระบบอัตโนมัติ “${1}” ทำงานเสร็จแล้ว: ${2}",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 63d5ee8c27..238bd0349e 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Toplanacak nesne",+ "automationCollectionTargetBlock": "Etiketi içeren blok",+ "automationCollectionTargetContainer": "Kapsayıcı blok",+ "automationCollectionTargetDefaultTip": "Etiket koşullarında liste öğesinin ilk paragrafı öğeye aittir; diğer bloklar kendi etiketleriyle eşleştirilir",+ "automationCollectionTargetBlockTip": "Etiket koşullarında etiketi içeren bloğu türüne ve özniteliklerine göre topla",+ "automationCollectionTargetContainerTip": "Etiket koşullarında tür ve öznitelik koşullarına uyan en yakın kapsayıcıyı topla; belgeler açıkça seçilmelidir",+ "automationCollectionTargetChangeTip": "Değişiklik mevcut kayıtları ve alanları korur; yeni sonuçları önizlemede kontrol edin","automationCollectionRuleChangeTip": "Koşulları değiştirmek, bir kuralı devre dışı bırakmak veya silmek toplanan kayıtları ve alan değerlerini korur","automationNotifySuccess": "Başarıyla tamamlandığında bildir","automationResultRule": "“${1}” otomasyonu tamamlandı: ${2}",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 32fb218021..21158c70f2 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "Об’єкт збирання",+ "automationCollectionTargetBlock": "Блок із тегом",+ "automationCollectionTargetContainer": "Блок-контейнер",+ "automationCollectionTargetDefaultTip": "За умовами тегів перший абзац елемента списку належить цьому елементу; інші блоки перевіряють власні теги",+ "automationCollectionTargetBlockTip": "За умовами тегів збирати блок із тегом відповідно до його типу й атрибутів",+ "automationCollectionTargetContainerTip": "За умовами тегів збирати найближчий контейнер, що відповідає типу й атрибутам; документи потрібно вибирати явно",+ "automationCollectionTargetChangeTip": "Зміна зберігає наявні записи й поля; перевірте нові результати в попередньому перегляді","automationCollectionRuleChangeTip": "Зміна умов, вимкнення або видалення правила зберігає зібрані записи та значення їхніх полів","automationNotifySuccess": "Сповіщати про успішне виконання","automationResultRule": "Автоматизацію «${1}» виконано: ${2}",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex aa0d67b1d5..0c58b718a6 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "收集对象",+ "automationCollectionTargetBlock": "标签所在块",+ "automationCollectionTargetContainer": "容器块",+ "automationCollectionTargetDefaultTip": "有标签条件时,列表项首段默认归属列表项,其他块匹配自身标签",+ "automationCollectionTargetBlockTip": "有标签条件时,按标签所在块的类型和属性筛选并收集",+ "automationCollectionTargetContainerTip": "有标签条件时,收集最近的符合类型和属性条件的容器;文档需要显式选择",+ "automationCollectionTargetChangeTip": "切换不会转换已有条目或修改其字段,可通过预览确认新的收集结果","automationCollectionRuleChangeTip": "修改条件、停用或删除规则不会清理已收集的条目,也不会重置字段","automationNotifySuccess": "执行成功时通知","automationResultRule": "自动化「${1}」已执行:${2}",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 73d3b932f0..6dcd859545 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,11 @@{+ "automationCollectionTarget": "收集對象",+ "automationCollectionTargetBlock": "標籤所在區塊",+ "automationCollectionTargetContainer": "容器區塊",+ "automationCollectionTargetDefaultTip": "有標籤條件時,清單項目首段預設歸屬清單項目,其他區塊比對自身標籤",+ "automationCollectionTargetBlockTip": "有標籤條件時,依標籤所在區塊的類型與屬性篩選並收集",+ "automationCollectionTargetContainerTip": "有標籤條件時,收集最近且符合類型與屬性條件的容器;文件需明確選取",+ "automationCollectionTargetChangeTip": "切換不會轉換既有項目或修改其欄位,可透過預覽確認新的收集結果","automationCollectionRuleChangeTip": "修改條件、停用或刪除規則不會清理已收集的項目,也不會重設欄位","automationNotifySuccess": "執行成功時通知","automationResultRule": "自動化「${1}」已執行:${2}",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.syindex f02176090d..6a8e95d1ca 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": "20261016202856"+ "updated": "20261017204817"},"Children": [{@@ -4549,6 +4549,20 @@}]},+ {+ "ID": "20261017204817-jfdo45b",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017204817-jfdo45b",+ "updated": "20261017204817"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "The Collect menu beside the tag conditions offers Default, Block containing the tag, and Container block. Default preserves existing behavior, including treating a list item’s first paragraph as part of that item. Block containing the tag filters and collects the actual tagged block by its type and attributes. Container block collects the nearest container meeting the selected type and attribute conditions, deduplicating by block ID; documents are eligible only when explicitly selected. All required tags must occur in the same source block, rather than being combined across children. With no tag conditions, this option has no effect. Preview shows the final collection targets. Changing this option preserves existing entries and fields without converting their bound blocks. The two explicit modes require automation format 4; older formats remain readable, and older clients reject format 4 without rewriting the database."+ }+ ]+ },{"ID": "20261017195341-czg1ilm","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.syindex 2466f52442..ff9422ee9e 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": "20261016202635"+ "updated": "20261017204817"},"Children": [{@@ -4549,6 +4549,20 @@}]},+ {+ "ID": "20261017204817-4ocp9jq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017204817-4ocp9jq",+ "updated": "20261017204817"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "标签条件旁的「收集对象」提供「默认」「标签所在块」和「容器块」。默认沿用现有行为,包括将列表项首段归属列表项;标签所在块按实际包含标签的块的类型和属性筛选并收集;容器块向上选择最近的符合类型和属性条件的容器,并按块 ID 去重,文档只有被显式选择时才参与。要求全部标签时,标签必须出现在同一个来源块中,不会合并不同子块的标签。没有标签条件时,此选项不影响筛选。预览显示最终收集对象。切换不会转换已有条目的绑定块或修改其字段。两种显式模式需要自动化格式 4,已有格式仍可读取;旧客户端会拒绝格式 4,不会改写数据库。"+ }+ ]+ },{"ID": "20261017195341-0qeydtk","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.syindex a930c758ea..f14d12388d 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": "20261016202635"+ "updated": "20261017204817"},"Children": [{@@ -4549,6 +4549,20 @@}]},+ {+ "ID": "20261017204817-t0qt0db",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017204817-t0qt0db",+ "updated": "20261017204817"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "標籤條件旁的「收集對象」提供「預設」「標籤所在區塊」和「容器區塊」。預設沿用既有行為,包括將清單項目首段歸屬清單項目;標籤所在區塊依實際包含標籤的區塊類型與屬性篩選並收集;容器區塊向上選擇最近且符合類型與屬性條件的容器,並依區塊 ID 去除重複,文件只有被明確選取時才參與。要求全部標籤時,標籤必須出現在同一個來源區塊中,不會合併不同子區塊的標籤。沒有標籤條件時,此選項不影響篩選。預覽顯示最終收集對象。切換不會轉換既有項目的繫結區塊或修改其欄位。兩種明確模式需要自動化格式 4,既有格式仍可讀取;舊用戶端會拒絕格式 4,不會改寫資料庫。"+ }+ ]+ },{"ID": "20261017195341-h2pn2cd","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.syindex f73631bb89..caac6ed1f1 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": "20261016202856"+ "updated": "20261017204817"},"Children": [{@@ -4559,6 +4559,20 @@}]},+ {+ "ID": "20261017204817-a41svnn",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017204817-a41svnn",+ "updated": "20261017204817"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "タグ条件の横にある「収集対象」では、「デフォルト」「タグを含むブロック」「コンテナブロック」を選べます。デフォルトはリスト項目の最初の段落をその項目に属するものとして扱う既存の動作を維持します。「タグを含むブロック」はタグが実際にあるブロックの種類と属性で絞り込み、収集します。「コンテナブロック」は種類と属性の条件に一致する最も近いコンテナを選び、ブロック ID で重複を除きます。文書は明示的に選択した場合のみ対象になります。すべてのタグを要求する場合、同じ元ブロック内にそろっている必要があり、別々の子ブロックのタグは結合しません。タグ条件がなければ、この設定は絞り込みに影響しません。プレビューには最終的な収集対象が表示されます。切り替えても既存項目のバインド先やフィールドは変更されません。明示的な二つのモードには自動化形式 4 が必要です。既存形式は引き続き読み込めますが、古いクライアントは形式 4 を拒否し、データベースを書き換えません。"+ }+ ]+ },{"ID": "20261017195341-nu6ize6","Type": "NodeParagraph",diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex d5a7f68379..aa3ab6cc36 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -3142,8 +3142,6 @@ img.av__cellassetimg {align-self: flex-start;justify-content: flex-start;max-width: 100%;- white-space: normal;- overflow-wrap: anywhere;text-align: left;}diff --git a/app/src/assets/scss/component/_button.scss b/app/src/assets/scss/component/_button.scssindex 4590850156..c1d86d354c 100644--- a/app/src/assets/scss/component/_button.scss+++ b/app/src/assets/scss/component/_button.scss@@ -53,6 +53,12 @@padding: 2px 8px;}+ &--wrap {+ white-space: normal;+ overflow-wrap: anywhere;+ line-height: max(20px, 1.4em);+ }+&--big {min-width: 214px;background: var(--b3-theme-secondary);diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.tsindex 95c71f0829..12fd7b9224 100644--- a/app/src/protyle/render/av/automation.ts+++ b/app/src/protyle/render/av/automation.ts@@ -206,7 +206,8 @@ export const openAutomationMenu = async (options: {const usesTemplates = rules.some(rule => rule.actions.some(action => Object.values(action.fields).some(value => value.mode === "template")));const usesSourceOptions = rules.some(rule => rule.blockSource?.types?.some(type => type.includes(":")) ||rule.blockSource?.tagMatch === "or" || rule.blockSource?.attributeMatch === "or");- const next = {spec: Math.max(previous.spec, usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};+ const usesTagTarget = rules.some(rule => !!rule.blockSource?.tagTarget);+ const next = {spec: Math.max(previous.spec, usesTagTarget ? 4 : usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};if (JSON.stringify(next) === JSON.stringify(previous)) {return;}diff --git a/app/src/protyle/render/av/blockCollection.ts b/app/src/protyle/render/av/blockCollection.tsindex 11ea4029fd..b2a3101b55 100644--- a/app/src/protyle/render/av/blockCollection.ts+++ b/app/src/protyle/render/av/blockCollection.ts@@ -34,7 +34,7 @@ export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomaticonst documents = source.documentIDs || [];host.innerHTML = `<div class="av__automation-action"><div class="ft__on-surface ft__smaller av__automation-tip" data-collection-removal-tip>${lang.automationCollectionTip}</div>-<button type="button" class="b3-button b3-button--outline av__automation-source-action" data-scope>${lang.automationCollectionScope}</button>+<button type="button" class="b3-button b3-button--outline b3-button--wrap av__automation-source-action" data-scope>${lang.automationCollectionScope}</button>${notebooks.length || documents.length ? `<div class="av__automation-source-list">${notebooks.map((id, i) => `<div class="av__automation-row av__automation-source-row"><svg class="block__logoicon ft__on-surface"><use xlink:href="#iconNotebook"></use></svg><span class="fn__flex-1 ft__breakword av__automation-notebook-name">${escapeHtml(window.siyuan.notebooks.find(box => box.id === id)?.name || id)}</span>${removeButton("notebook", i)}</div>`).join("")}${documents.map((id, i) => `<div class="av__automation-row av__automation-source-row"><span class="b3-list-item__icon fn__pointer popover__block" data-id="${escapeAttr(id)}"><svg><use xlink:href="#iconFile"></use></svg></span><a href="siyuan://blocks/${escapeAttr(id)}" class="fn__flex-1 ft__breakword av__automation-document-name">${escapeHtml(names.get(id) || id)}</a>${removeButton("document", i)}</div>`).join("")}</div>` : ""}</div>`;host.firstElementChild.append(conditions);diff --git a/app/src/protyle/render/av/collectionConditions.ts b/app/src/protyle/render/av/collectionConditions.tsindex cb40ff6be4..2bd93852a3 100644--- a/app/src/protyle/render/av/collectionConditions.ts+++ b/app/src/protyle/render/av/collectionConditions.ts@@ -31,13 +31,15 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatioconst operators = {equals: lang.filterOperatorIs, contains: lang.filterOperatorContains,exists: lang.automationAttrExists, notExists: lang.automationAttrNotExists};const modeLabel = (mode: string) => mode === "or" ? lang.filterMatchAny : lang.filterMatchAll;+ const tagTargets = {"": lang.default, block: lang.automationCollectionTargetBlock, container: lang.automationCollectionTargetContainer};+ const tagTargetTips = {"": lang.automationCollectionTargetDefaultTip, block: lang.automationCollectionTargetBlockTip, container: lang.automationCollectionTargetContainerTip};const modeButton = (field: "tagMatch" | "attributeMatch", label: string) => `<button type="button" class="b3-button b3-button--cancel" data-match="${field}" aria-label="${escapeAttr(label)}">${modeLabel(source[field])}<svg><use xlink:href="#iconDown"></use></svg></button>`;- const addButton = (action: string, label: string) => `<button type="button" class="b3-button b3-button--cancel av__automation-source-action" ${action}><svg><use xlink:href="#iconAdd"></use></svg><span>${escapeHtml(label)}</span></button>`;+ const addButton = (action: string, label: string) => `<button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" ${action}><svg><use xlink:href="#iconAdd"></use></svg><span>${escapeHtml(label)}</span></button>`;const chip = (kind: string, index: number, label: string, editable = false) => `<div class="b3-chip b3-chip--middle"><span class="fn__ellipsis${editable ? " b3-chip--pointer" : ""} ariaLabel" ${editable ? `data-edit-attribute="${index}" role="button" tabindex="0"` : ""} aria-label="${escapeAttr(label)}">${escapeHtml(label)}</span><svg class="b3-chip__close" data-remove-filter="${kind}" data-index="${index}" role="button" tabindex="0" aria-label="${escapeAttr(lang.delete)}"><use xlink:href="#iconClose"></use></svg></div>`;host.className = "av__automation-control";- host.innerHTML = `<div class="av__automation-control"><span class="av__automation-control-label">${lang.automationCollectionTypes}</span><div class="b3-chips b3-chips__doctag av__automation-chips" data-type-chips></div>${addButton("data-types", `${lang.add} - ${lang.automationCollectionTypes}`)}</div>-<div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.tag}</span>${modeButton("tagMatch", lang.tag)}</div><div data-tags></div></div>-<div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.attr}</span>${modeButton("attributeMatch", lang.attr)}</div><div class="b3-chips b3-chips__doctag av__automation-chips" data-attribute-chips></div>${addButton("data-add-attribute", `${lang.add} - ${lang.attr}`)}<div data-attribute-editor></div></div>`;+ host.innerHTML = `<div class="av__automation-control"><span class="av__automation-control-label">${lang.automationCollectionTypes}</span><div class="b3-chips b3-chips__doctag av__automation-chips" data-type-chips></div>${addButton("data-types", `${lang.addAttr} - ${lang.automationCollectionTypes}`)}</div>+<div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.tag}</span>${modeButton("tagMatch", lang.tag)}</div><div data-tags></div><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.automationCollectionTarget}</span><button type="button" class="b3-button b3-button--cancel b3-button--wrap av__automation-source-action" data-tag-target aria-label="${escapeAttr(lang.automationCollectionTarget)}"><span>${tagTargets[source.tagTarget || ""]}</span><svg><use xlink:href="#iconDown"></use></svg></button></div><div class="ft__on-surface ft__smaller av__automation-tip" data-tag-target-tip>${tagTargetTips[source.tagTarget || ""]}</div><div class="ft__on-surface ft__smaller av__automation-tip fn__none" data-tag-target-change-tip>${lang.automationCollectionTargetChangeTip}</div></div>+<div class="av__automation-control"><div class="av__automation-row"><span class="av__automation-control-label fn__flex-1">${lang.attr}</span>${modeButton("attributeMatch", lang.attr)}</div><div class="b3-chips b3-chips__doctag av__automation-chips" data-attribute-chips></div>${addButton("data-add-attribute", `${lang.addAttr} - ${lang.attr}`)}<div data-attribute-editor></div></div>`;const typeChips = host.querySelector<HTMLElement>("[data-type-chips]");const attributes = host.querySelector<HTMLElement>("[data-attribute-chips]");const editor = host.querySelector<HTMLElement>("[data-attribute-editor]");@@ -159,7 +161,18 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatioconst target = (event.target as Element).closest<HTMLElement>("button, [data-remove-filter], [data-edit-attribute]");if (!target) { return; }if (target.hasAttribute("data-types")) { openTypes(target); }- else if (target.dataset.match) {+ else if (target.hasAttribute("data-tag-target")) {+ choose(target, Object.entries(tagTargets).map(([value, label]) => ({value, label})), source.tagTarget || "", value => {+ const next = value === "block" ? "block" : value === "container" ? "container" : "";+ if (next === (source.tagTarget || "")) { return; }+ if (next) { source.tagTarget = next; } else { delete source.tagTarget; }+ target.querySelector("span").textContent = tagTargets[next];+ host.querySelector("[data-tag-target-tip]").textContent = tagTargetTips[next];+ host.querySelector("[data-tag-target-change-tip]").classList.remove("fn__none");+ save();+ resize();+ });+ } else if (target.dataset.match) {const field = target.dataset.match === "tagMatch" ? "tagMatch" : "attributeMatch";choose(target, [{value: "and", label: lang.filterMatchAll}, {value: "or", label: lang.filterMatchAny}], source[field] || "and", mode => {source[field] = mode === "or" ? "or" : "and";diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 791e5da8a7..d490351d56 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -256,9 +256,9 @@ export type AVAutomationBlockAttribute = { "name": string; "operator": "equals"export type AVAutomationBlockAttributeInput = { "name": string; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };-export type AVAutomationBlockSource = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tags"?: Array<string>; "types"?: Array<string>; };+export type AVAutomationBlockSource = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };-export type AVAutomationBlockSourceInput = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tags"?: Array<string>; "types"?: Array<string>; };+export type AVAutomationBlockSourceInput = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };export type AVAutomationConfig = { "rules": Array<AVAutomationRule | null> | null; "spec": number; };@@ -7814,9 +7814,12 @@ export interface APIPOSTRoutes {/*** move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。- * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。+ * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 4,所有视图共享数据库级规则。* blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。* blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。+ * spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。+ * 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。+ * 无标签时收集对象不影响筛选;变更收集对象不转换已有条目,预览与实际收集使用相同规则。* 规则的 notifyOnSuccess 缺省或 null 为开启,仅实际变更且事务成功提交后通知,同一事务合并;错误提示不受其控制。* 手动收集、无变化、撤销重放和失败回滚不发送成功通知。* addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.jsindex ee81a1c2c8..b5a7aff7f9 100644--- a/app/tests/automationPanel.test.js+++ b/app/tests/automationPanel.test.js@@ -53,7 +53,12 @@ const runCases = async (sources, css, mobile) => {item.bind(this.element);}}- open() { this.element.className = "b3-menu"; document.body.append(this.element); fieldMenu = {items: this.items, element: this.element}; }+ open() {+ document.querySelectorAll("body > .b3-menu").forEach(popup => popup.remove());+ this.element.className = "b3-menu";+ document.body.append(this.element);+ fieldMenu = {items: this.items, element: this.element};+ }close() { this.element.remove(); }showSubMenu() {}}},@@ -339,11 +344,13 @@ const runCases = async (sources, css, mobile) => {await change("[data-mode]", "currentTime");const theme = document.createElement("style");await require("electron").ipcRenderer.invoke("automation-size", mobile ? 360 : 560, 620);+ for (let attempt = 0; window.innerHeight !== 620 && attempt < 100; attempt++) { await tick(); }+ assert.equal(window.innerHeight, 620, "the resized viewport is ready before testing assignment scrolling");get("[data-mode]").scrollIntoView({block: "center"});await tick();const scroller = get(".b3-menu__items");const assignmentScrollTop = scroller.scrollTop;- assert.ok(assignmentScrollTop > 100, "the assignment is reached by scrolling before changing its mode");+ assert.ok(assignmentScrollTop > 0, `the assignment is reached by scrolling before changing its mode: ${assignmentScrollTop}`);await change("[data-mode]", "template");assert.ok(Math.abs(scroller.scrollTop - assignmentScrollTop) <= 1,`switching to a template preserves the scrolled assignment: ${assignmentScrollTop} -> ${scroller.scrollTop}`);@@ -425,6 +432,7 @@ const runCases = async (sources, css, mobile) => {}}await change("[data-trigger]", "block");+ assert.ok(!get("[data-source-conditions]").textContent.includes("undefined"), "collection controls use defined localized labels");assert.equal(get("[data-collection-removal-tip]").textContent, lang.automationCollectionTip);assert.equal(get("[data-rule-change-tip]").textContent, lang.automationCollectionRuleChangeTip);assert.equal(get("[data-source-conditions]").closest("section").textContent.includes(lang.automationBlockConditions), true);@@ -452,10 +460,15 @@ const runCases = async (sources, css, mobile) => {const button = get(selector);assert.equal(button.getBoundingClientRect().left, tagsRect.left, "collection controls align with the form");assert.ok(button.scrollWidth <= button.clientWidth + 1, "collection controls wrap without horizontal overflow");+ assert.ok(parseFloat(getComputedStyle(button).lineHeight) >= parseFloat(getComputedStyle(button).fontSize) * 1.2,+ "wrapped collection controls leave enough line height for large fonts");button.focus();assert.equal(document.activeElement, button, "collection controls remain keyboard focusable");}assert.ok(typesRect.height > 0 && addRect.height > 0);+ const targetButton = get("[data-tag-target]");+ assert.ok(targetButton.scrollWidth <= targetButton.clientWidth + 1, "collection targets wrap with shared button styles");+ assert.ok(targetButton.getBoundingClientRect().right <= window.innerWidth, "collection targets stay inside narrow layouts");assert.equal(menu.querySelector("[data-attr-name]"), null, "attribute editors stay collapsed until needed");}menu.style.fontSize = "";@@ -511,6 +524,25 @@ const runCases = async (sources, css, mobile) => {await click('[data-match="attributeMatch"]');fieldMenu.items.find(item => item.label === lang.filterMatchAny).click();assert.equal(latest().blockSource.attributeMatch, "or");+ assert.equal(get("[data-tag-target] span").textContent, lang.default);+ assert.equal(latest().blockSource.tagTarget, undefined, "existing rules retain their collection granularity");+ for (const [value, label] of [["block", lang.automationCollectionTargetBlock], ["container", lang.automationCollectionTargetContainer], ["", lang.default]]) {+ await click("[data-tag-target]");+ const targetOption = fieldMenu.items.find(item => item.label === get("[data-tag-target] span").textContent);+ assert.equal(targetOption.checked, true, "the current target is checked in the shared menu");+ fieldMenu.items.find(item => item.label === label).click();+ assert.equal(latest().blockSource.tagTarget, value || undefined);+ assert.equal(transactions.at(-1).perform[0].data.spec, 4);+ assert.equal(get("[data-tag-target] span").textContent, label);+ assert.ok(get("[data-tag-target]").scrollWidth <= get("[data-tag-target]").clientWidth + 1, "all target labels wrap at narrow widths and large fonts");+ assert.equal(get("[data-tag-target-change-tip]").classList.contains("fn__none"), false);+ assert.ok(get("[data-tag-target-change-tip]").textContent.includes(lang.automationCollectionTargetChangeTip));+ if (value === "container") {+ get("[data-tag-target]").scrollIntoView({block: "center"});+ await tick();+ await require("electron").ipcRenderer.invoke("automation-capture", `${mobile ? "mobile" : "desktop"}-${window.innerWidth}-midnight-collection`);+ }+ }await click("[data-tags] button");const tagInput = get("[data-tags] input");tagInput.value = " #todo# ";diff --git a/docs/API.ja.md b/docs/API.ja.mdindex e79ca4c92d..9c7e295ff9 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -2212,7 +2212,7 @@ if (response.code === 0 && response.data) {* `data.av`: 完全な `AttributeView` 定義——フィールド(`keyValues`)、フィールド順序(`keyIDs`、`null` の場合あり)、および全ビューの生のレイアウト設定(`table`/`gallery`/`kanban`)とアイテム順序(`itemIds`)。互換性フィールド `viewID` は最初に利用可能なビューから算出され、永続化されません。レンダリング後の行やページングは含まれないため、計算後の行データが必要な場合は [レンダリング](#レンダリング) を使用してください- * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`、`2`、`3`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。手動で追加した既存項目は保持されます。削除後に再び一致すると初期値を持つ新しい項目を作成し、元に戻す操作では元の項目とフィールドを復元します `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。+ * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`~`4`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。手動で追加した既存項目は保持されます。削除後に再び一致すると初期値を持つ新しい項目を作成し、元に戻す操作では元の項目とフィールドを復元します `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。 形式 4 では省略可能な `blockSource.tagTarget` を追加しています。省略・空文字列は従来動作、`block` はタグを含むブロック、`container` は種類と属性の条件に一致する最も近いコンテナを収集し、ブロック ID で重複を除きます。文書には明示的な `d` の選択が必要です。AND のタグは同じ元ブロックに必要で、タグ条件がなければこの設定は影響しません。プレビューと実際の収集対象は一致し、切り替えても既存項目とフィールドは維持されます。### 主キー値を取得diff --git a/docs/API.md b/docs/API.mdindex 13d9cb5d9d..86dc6b622b 100644--- a/docs/API.md+++ b/docs/API.md@@ -2222,7 +2222,7 @@ The field types (`keyType`) are:* `data.av`: The full `AttributeView` definition — fields (`keyValues`), field ordering (`keyIDs`, may be `null`), and all views with their raw layout config (`table`/`list`/`gallery`/`kanban`) and item ordering (`itemIds`). The compatibility `viewID` is computed as the first available view and is not persisted. Returns no rendered rows or pagination; therefore, use [Render](#Render) for computed rows- * `data.av.automations` optionally contains database-wide rules (`spec: 1`, `2`, or `3`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Existing manual rows are preserved; a new match after removal creates a new initialized row, while undo restores the original row and fields `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages.+ * `data.av.automations` optionally contains database-wide rules (`spec: 1` through `4`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Existing manual rows are preserved; a new match after removal creates a new initialized row, while undo restores the original row and fields `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages. Format 4 adds optional `blockSource.tagTarget`: omitted/empty keeps legacy behavior, `block` collects the tagged block itself, and `container` collects the nearest container meeting type and attribute conditions, deduplicated by block ID. Documents require an explicit `d` type. AND tags must occur in one source block; without tag conditions this option has no effect. Preview and actual collection share the same targets; changing this option preserves existing rows and fields.### Get primary key valuesdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 6278c7cbf0..acf234fd25 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -2218,7 +2218,7 @@ if (response.code === 0 && response.data) {* `data.av`: 完整的 `AttributeView` 定义——字段(`keyValues`)、字段顺序(`keyIDs`,可能为 `null`),以及所有视图的原始布局配置(`table`/`list`/`gallery`/`kanban`)和条目顺序(`itemIds`)。兼容字段 `viewID` 动态取第一个可用视图,不会持久化。返回值不含渲染后的行或分页;需要计算后的行数据请使用 [渲染](#渲染)- * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1`、`2` 或 `3`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。已有手动条目不受影响;移出后再次匹配会创建新条目并初始化字段,撤销则恢复原条目及字段 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。+ * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1` 至 `4`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。已有手动条目不受影响;移出后再次匹配会创建新条目并初始化字段,撤销则恢复原条目及字段 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。 格式 4 增加可选的 `blockSource.tagTarget`:缺省或空字符串沿用原行为,`block` 收集标签所在块,`container` 选择最近的符合类型和属性条件的容器并按块 ID 去重;文档需显式选择 `d`。全部标签须在同一个来源块中,无标签条件时此选项不影响筛选。预览与实际收集对象一致,切换保留已有条目及字段。### 获取主键值diff --git a/kernel/api/av_contract_automation.go b/kernel/api/av_contract_automation.goindex f0985676a5..6890cfff43 100644--- a/kernel/api/av_contract_automation.go+++ b/kernel/api/av_contract_automation.go@@ -64,7 +64,7 @@ func toContractAVAutomationBlockSource(source *av.AutomationBlockSource) *apiconreturn nil}return &apicontract.AVAutomationBlockSource{NotebookIDs: source.NotebookIDs, DocumentIDs: source.DocumentIDs,- TagMatch: source.TagMatch, AttributeMatch: source.AttributeMatch,+ TagMatch: source.TagMatch, TagTarget: source.TagTarget, AttributeMatch: source.AttributeMatch,Types: source.Types, Tags: source.Tags, Attributes: avContractSlice(source.Attributes, func(attr *av.AutomationBlockAttribute) *apicontract.AVAutomationBlockAttribute {if attr == nil {return nildiff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.goindex 14cfd3ee9a..599de82b4f 100644--- a/kernel/api/contract_av_automation_test.go+++ b/kernel/api/contract_av_automation_test.go@@ -252,4 +252,90 @@ func TestAVContractAutomationWrites(t *testing.T) {if stored.GetBlockValueByBoundID(tree.ID) != nil {t.Fatal("OR tag group bypassed an unmatched attribute group")}+ collection.BlockSource = &av.AutomationBlockSource{DocumentIDs: []string{tree.ID}, Types: []string{"b"},+ Tags: []string{"collect"}, TagTarget: "container"}+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,+ Data: &av.AutomationConfig{Spec: 4, Rules: []*av.AutomationRule{collection}}}}); err != nil {+ t.Fatal(err)+ }+ response := callAttributeViewContextFilterAPI(t, "/api/av/getAttributeView", map[string]any{"id": database.ID}, getAttributeView)+ requireAPIContract(t, http.MethodPost, "/api/av/getAttributeView", response)+ var readBack struct {+ Data struct {+ AV struct{ Automations av.AutomationConfig }+ }+ }+ if err = json.Unmarshal(response.Body.Bytes(), &readBack); err != nil ||+ readBack.Data.AV.Automations.Spec != 4 || len(readBack.Data.AV.Automations.Rules) != 1 ||+ readBack.Data.AV.Automations.Rules[0].BlockSource.TagTarget != "container" {+ t.Fatalf("tag target contract round trip: %s %v", response.Body.String(), err)+ }+ call("/api/block/appendBlock", map[string]any{"parentID": tree.ID, "dataType": "markdown", "data": "> First #collect#\n>\n> Second #collect#"}, appendBlock)+ stored, _ = av.ParseAttributeView(database.ID)+ preview, err = model.PreviewAttributeViewCollection(database.ID, collection.ID, 1)+ if err != nil || len(preview.Blocks) != 1 || stored.GetBlockValueByBoundID(preview.Blocks[0].ID) == nil {+ t.Fatalf("container preview and collection disagree: %+v %v", preview, err)+ }+ quoteID := preview.Blocks[0].ID+ sourceTree, err := model.LoadTreeByBlockID(quoteID)+ if err != nil {+ t.Fatal(err)+ }+ quote := treenode.GetNodeInTree(sourceTree, quoteID)+ if quote == nil || quote.Type != ast.NodeBlockquote {+ t.Fatal("collected a descendant instead of the quote")+ }+ var paragraphs []string+ for child := quote.FirstChild; child != nil; child = child.Next {+ if child.Type == ast.NodeParagraph {+ paragraphs = append(paragraphs, child.ID)+ }+ }+ if len(paragraphs) != 2 {+ t.Fatalf("quote fixture paragraphs: %v", paragraphs)+ }+ collection.BlockSource.TagTarget, collection.BlockSource.Types = "block", []string{"p"}+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,+ Data: &av.AutomationConfig{Spec: 4, Rules: []*av.AutomationRule{collection}}}}); err != nil {+ t.Fatal(err)+ }+ stored, _ = av.ParseAttributeView(database.ID)+ if stored.GetBlockValueByBoundID(quoteID) == nil {+ t.Fatal("changing target converted the existing quote entry")+ }+ preview, err = model.PreviewAttributeViewCollection(database.ID, collection.ID, 1)+ if err != nil || len(preview.Blocks) != 2 {+ t.Fatalf("direct target preview: %+v %v", preview, err)+ }+ for _, block := range preview.Blocks {+ if block.ID != paragraphs[0] && block.ID != paragraphs[1] {+ t.Fatal("direct preview returned a container")+ }+ }+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "collectAttrViewBlocks", AvID: database.ID,+ Data: map[string]any{"ruleID": collection.ID, "blockIDs": paragraphs}}}); err != nil {+ t.Fatal(err)+ }+ stored, _ = av.ParseAttributeView(database.ID)+ for _, id := range paragraphs {+ if stored.GetBlockValueByBoundID(id) == nil {+ t.Fatal("explicit collection disagreed with direct preview")+ }+ }+ collection.BlockSource.TagTarget, collection.BlockSource.Types = "container", []string{"b"}+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,+ Data: &av.AutomationConfig{Spec: 4, Rules: []*av.AutomationRule{collection}}}}); err != nil {+ t.Fatal(err)+ }+ for index, id := range paragraphs {+ call("/api/block/updateBlock", map[string]any{"id": id, "dataType": "markdown", "data": "Without tag"}, updateBlock)+ stored, _ = av.ParseAttributeView(database.ID)+ if (stored.GetBlockValueByBoundID(quoteID) != nil) != (index == 0) {+ t.Fatal("container must remain until its last matching source disappears")+ }+ }+ preview, err = model.PreviewAttributeViewCollection(database.ID, collection.ID, 1)+ if err != nil || len(preview.Blocks) != 0 {+ t.Fatalf("unmatched container preview: %+v %v", preview, err)+ }}diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.goindex 57bd5c7eaa..e4b68885d2 100644--- a/kernel/apicontract/av_automation.go+++ b/kernel/apicontract/av_automation.go@@ -1,7 +1,8 @@package apicontract// AVAutomationConfig 通过 setAttrViewAutomations 事务操作整体保存,所有镜像和视图共享。-// spec 为 1、2 或 3;模板赋值至少使用 2,块子类型至少使用 3;旧读取器拒绝新版本,防止配置静默丢失。+// spec 为 1 至 4;模板赋值至少使用 2,块子类型至少使用 3,标签收集对象至少使用 4。+// 旧读取器拒绝新版本,防止配置静默丢失。// 缺省配置不会触发自动化,既有版本的主类型匹配含义不变。// 普通条目新增、字段编辑及对应 API 会触发启用的规则,// 导入、同步、历史恢复和撤销重放不会再次触发,自动化之间不串联。@@ -30,10 +31,14 @@ type AVAutomationRule struct {// AVAutomationBlockSource 监听范围取笔记本与文档的并集,文档包含子文档;范围至少选择一项。// 类型组取或关系;标签和属性组各自通过 tagMatch、attributeMatch 选择 and(缺省)或 or(至少 spec 3)。-// 各条件组之间取与关系,空组不限制;标签精确匹配,不递归匹配父容器。+// 各条件组之间取与关系,空组不限制;标签精确匹配,全部标签必须出现在同一个来源块中。// types 为空不限制类型;主类型匹配其全部子类型,类型之间取或关系。// spec 3 支持 h:h1 至 h:h6、l:u/o/t、i:u/o/t 和 callout:类型名;提示块类型区分大小写,允许自定义名称。// 列表项首段的标签默认归属列表项;显式选择段落类型时可匹配该段落。+// tagTarget 缺省或空字符串沿用默认行为;block 收集直接包含标签的块,不做列表项提升。+// container 从标签来源块向上选择最近的满足类型及属性条件的容器,按块 ID 去重。+// 文档仅在 types 显式包含 d 时作为目标容器;无标签条件时 tagTarget 不改变类型及属性筛选结果。+// 切换收集对象不转换或移出已有条目;预览、收集及后续原文失配移出使用相同的匹配逻辑。// 仅从不匹配变为匹配时收集,原条目不会重置;失配时移出本功能创建的条目,保留源块。// 其他启用的收集规则仍匹配时保留条目;停用或删除创建规则会保留既有条目。// 再次匹配创建新条目并初始化字段,不恢复移出条目的字段;撤销重做仍恢复原事务快照。@@ -45,6 +50,7 @@ type AVAutomationBlockSource struct {Tags []string `json:"tags,omitempty" api:"optional"`Attributes []*AVAutomationBlockAttribute `json:"attributes,omitempty" api:"optional"`TagMatch string `json:"tagMatch,omitempty" api:"optional,enum=|and|or"`+ TagTarget string `json:"tagTarget,omitempty" api:"optional,enum=|block|container"`AttributeMatch string `json:"attributeMatch,omitempty" api:"optional,enum=|and|or"`}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 6bdb9fcfbb..01ebc65c9f 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1437,9 +1437,12 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system// move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。-// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。+// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 4,所有视图共享数据库级规则。// blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。// blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。+// spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。+// 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。+// 无标签时收集对象不影响筛选;变更收集对象不转换已有条目,预览与实际收集使用相同规则。// 规则的 notifyOnSuccess 缺省或 null 为开启,仅实际变更且事务成功提交后通知,同一事务合并;错误提示不受其控制。// 手动收集、无变化、撤销重放和失败回滚不发送成功通知。// addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 7b8fb6d3b0..8661fd7c31 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -6696,6 +6696,14 @@"or"]},+ "tagTarget": {+ "type": "string",+ "enum": [+ "",+ "block",+ "container"+ ]+ },"tags": {"type": "array","items": {@@ -6755,6 +6763,14 @@"or"]},+ "tagTarget": {+ "type": "string",+ "enum": [+ "",+ "block",+ "container"+ ]+ },"tags": {"type": "array","items": {diff --git a/kernel/av/automation.go b/kernel/av/automation.goindex beb41c6d36..207bba75dc 100644--- a/kernel/av/automation.go+++ b/kernel/av/automation.go@@ -35,6 +35,7 @@ type AutomationBlockSource struct {Tags []string `json:"tags,omitempty"`Attributes []*AutomationBlockAttribute `json:"attributes,omitempty"`TagMatch string `json:"tagMatch,omitempty"`+ TagTarget string `json:"tagTarget,omitempty"`AttributeMatch string `json:"attributeMatch,omitempty"`}@@ -67,6 +68,9 @@ func IsAutomationBlockType(value string) bool {func (rule *AutomationRule) RequiredSpec() int {ret := 1if rule.BlockSource != nil {+ if rule.BlockSource.TagTarget != "" {+ return 4+ }if rule.BlockSource.TagMatch == "or" || rule.BlockSource.AttributeMatch == "or" {return 3}@@ -93,7 +97,7 @@ func (config *AutomationConfig) ValidateSpec() error {if config == nil {return nil}- if config.Spec < 1 || config.Spec > 3 {+ if config.Spec < 1 || config.Spec > 4 {return fmt.Errorf("unsupported database automation specification [%d]", config.Spec)}for _, rule := range config.Rules {diff --git a/kernel/av/automation_test.go b/kernel/av/automation_test.goindex b6293d7f8d..db7d261809 100644--- a/kernel/av/automation_test.go+++ b/kernel/av/automation_test.go@@ -112,7 +112,7 @@ func TestAutomationClonePreservesPausedRules(t *testing.T) {if copiedRule.Actions[1].RelationKeyID == relationID || !rule.Enabled || rule.KeyID != primaryID {t.Fatal("copy changed the original rule or retained its source field")}- source.Automations.Spec = 4+ source.Automations.Spec = 5future, _ := json.Marshal(source)if _, err := ParseAttributeViewData(source.ID, future); err == nil {t.Fatal("unknown automation format was accepted")@@ -134,7 +134,7 @@ func TestAutomationBlockTypeAndSpecCompatibility(t *testing.T) {if err != nil {t.Fatal(err)}- for _, spec := range []int{1, 2, 3} {+ for _, spec := range []int{1, 2, 3, 4} {view, err := ParseAttributeViewData("20260921000000-layouts", data)if err != nil {t.Fatal(err)@@ -148,16 +148,24 @@ func TestAutomationBlockTypeAndSpecCompatibility(t *testing.T) {rule.BlockSource.Types = []string{"l:t"}raw, _ = json.Marshal(view)_, err = ParseAttributeViewData(view.ID, raw)- if (err == nil) != (spec == 3) {+ if (err == nil) != (spec >= 3) {t.Fatalf("subtype spec %d: %v", spec, err)}rule.BlockSource.Types = []string{"l"}rule.BlockSource.TagMatch = "or"raw, _ = json.Marshal(view)_, err = ParseAttributeViewData(view.ID, raw)- if (err == nil) != (spec == 3) {+ if (err == nil) != (spec >= 3) {t.Fatalf("OR spec %d: %v", spec, err)}+ for _, target := range []string{"block", "container"} {+ rule.BlockSource.TagTarget = target+ raw, _ = json.Marshal(view)+ _, err = ParseAttributeViewData(view.ID, raw)+ if (err == nil) != (spec == 4) {+ t.Fatalf("tag target %s spec %d: %v", target, spec, err)+ }+ }}}diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 931f7e2cdb..49f8af459f 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -51,6 +51,26 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, trif node == nil || !node.IsBlock() || !ast.IsNodeIDPattern(node.ID) || !collectionScopeMatches(source, tree) {return false}+ if !collectionBlockConditionsMatch(source, node) {+ return false+ }+ if len(source.Tags) == 0 {+ return true+ }+ root := node+ if source.TagTarget == "" {+ if node.Type == ast.NodeListItem {+ root = treenode.FirstLeafBlock(node)+ }+ if node.Type == ast.NodeParagraph && node.Parent != nil && node.Parent.Type == ast.NodeListItem &&+ treenode.FirstLeafBlock(node.Parent) == node && !slices.Contains(source.Types, "p") {+ return false+ }+ }+ return collectionTagsMatch(source, root)+}++func collectionBlockConditionsMatch(source *av.AutomationBlockSource, node *ast.Node) bool {if len(source.Types) > 0 {typ := treenode.TypeAbbr(node.Type.String())matched := slices.Contains(source.Types, typ)@@ -61,28 +81,18 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, trreturn false}}- if !collectionConditionsMatch(source.Attributes, source.AttributeMatch, func(attr *av.AutomationBlockAttribute) bool {+ return collectionConditionsMatch(source.Attributes, source.AttributeMatch, func(attr *av.AutomationBlockAttribute) bool {return collectionAttributeMatches(attr, node)- }) {- return false- }- if len(source.Tags) == 0 {- return true- }- root := node- if node.Type == ast.NodeListItem {- root = treenode.FirstLeafBlock(node)- }- if node.Type == ast.NodeParagraph && node.Parent != nil && node.Parent.Type == ast.NodeListItem &&- treenode.FirstLeafBlock(node.Parent) == node && !slices.Contains(source.Types, "p") {- return false- }+ })+}++func collectionTagsMatch(source *av.AutomationBlockSource, root *ast.Node) bool {if root == nil {return false}tags := map[string]bool{}- if node.Type == ast.NodeDocument {- for tag := range strings.SplitSeq(node.IALAttr("tags"), ",") {+ if root.Type == ast.NodeDocument {+ for tag := range strings.SplitSeq(root.IALAttr("tags"), ",") {tags[strings.Trim(strings.TrimSpace(tag), "#")] = true}}@@ -103,6 +113,41 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, tr})}+// 每个标签来源只选择最近的合格容器;整棵树共用结果,避免嵌套容器反复扫描子树。+func collectionMatches(source *av.AutomationBlockSource, tree *parse.Tree) map[string]bool {+ ret := map[string]bool{}+ if !collectionScopeMatches(source, tree) {+ return ret+ }+ var containers []*ast.Node+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ if len(containers) > 0 && containers[len(containers)-1] == node {+ containers = containers[:len(containers)-1]+ }+ return ast.WalkContinue+ }+ if !node.IsBlock() || !ast.IsNodeIDPattern(node.ID) {+ return ast.WalkContinue+ }+ if source.TagTarget != "container" || len(source.Tags) == 0 {+ if collectionBlockMatches(source, node, tree) {+ ret[node.ID] = true+ }+ return ast.WalkContinue+ }+ if node.IsContainerBlock() && (node.Type != ast.NodeDocument || slices.Contains(source.Types, "d")) &&+ collectionBlockConditionsMatch(source, node) {+ containers = append(containers, node)+ }+ if len(containers) > 0 && collectionTagsMatch(source, node) {+ ret[containers[len(containers)-1].ID] = true+ }+ return ast.WalkContinue+ })+ return ret+}+// 条件组为空时不限制,缺省保持全部匹配;不同条件组仍由调用方取交集。func collectionConditionsMatch[T any](values []T, mode string, matches func(T) bool) bool {if len(values) == 0 {@@ -146,7 +191,8 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rulereturn fmt.Errorf("invalid block collection source")}if !slices.Contains([]string{"", "and", "or"}, source.TagMatch) ||- !slices.Contains([]string{"", "and", "or"}, source.AttributeMatch) {+ !slices.Contains([]string{"", "and", "or"}, source.AttributeMatch) ||+ !slices.Contains([]string{"", "block", "container"}, source.TagTarget) {return fmt.Errorf("invalid block collection match mode")}for _, id := range source.NotebookIDs {@@ -329,13 +375,8 @@ func (tx *Transaction) runAttributeViewCollections() error {notifyRule *av.AutomationRule}var changes []collectionChange- beforeNodes, afterNodes := map[string]*ast.Node{}, map[string]*ast.Node{}- beforeTrees, afterTrees := map[string]*parse.Tree{}, map[string]*parse.Tree{}- for _, before := range state.before {- for blockID, node := range collectionNodes(before) {- beforeNodes[blockID], beforeTrees[blockID] = node, before- }- }+ afterNodes := map[string]*ast.Node{}+ afterTrees := map[string]*parse.Tree{}for _, after := range tx.trees {for blockID, node := range collectionNodes(after) {afterNodes[blockID], afterTrees[blockID] = node, after@@ -385,8 +426,22 @@ func (tx *Transaction) runAttributeViewCollections() error {}ReloadAttrView(id)}+ beforeMatches, afterMatches := map[*av.AutomationRule]map[string]bool{}, map[*av.AutomationRule]map[string]bool{}+ for _, rule := range rules {+ beforeMatches[rule], afterMatches[rule] = map[string]bool{}, map[string]bool{}+ for _, tree := range state.before {+ for id := range collectionMatches(rule.BlockSource, tree) {+ beforeMatches[rule][id] = true+ }+ }+ for _, tree := range tx.trees {+ for id := range collectionMatches(rule.BlockSource, tree) {+ afterMatches[rule][id] = true+ }+ }+ }for _, blockID := range blockIDs {- node, tree := afterNodes[blockID], afterTrees[blockID]+ tree := afterTrees[blockID]if !IsSameCryptoBoundary(boxID, tree.Box) {continue}@@ -395,8 +450,8 @@ func (tx *Transaction) runAttributeViewCollections() error {var ownerRule *av.AutomationRulerow := view.GetBlockValueByBoundID(blockID)for _, rule := range rules {- before := collectionBlockMatches(rule.BlockSource, beforeNodes[blockID], beforeTrees[blockID])- after := collectionBlockMatches(rule.BlockSource, node, tree)+ before := beforeMatches[rule][blockID]+ after := afterMatches[rule][blockID]matching = matching || afterpreviouslyMatching = previouslyMatching || beforeif after && (!before || slices.Contains(state.requested[id][rule.ID], blockID)) && entering == nil {@@ -528,13 +583,14 @@ func PreviewAttributeViewCollection(avID, ruleID string, page int) (*apicontractreturn nil, loadErr}nodes := collectionNodes(tree)+ matches := collectionMatches(rule.BlockSource, tree)ids := []string{}for id := range nodes {ids = append(ids, id)}sort.Strings(ids)for _, id := range ids {- if !collectionBlockMatches(rule.BlockSource, nodes[id], tree) {+ if !matches[id] {continue}if skipped < (page-1)*size {@@ -582,6 +638,7 @@ func (tx *Transaction) doCollectAttrViewBlocks(op *Operation) *TxErr {return fail(err)}state := tx.collectionState()+ matchesByTree := map[string]map[string]bool{}if state.requested[op.AvID] == nil {state.requested[op.AvID] = map[string][]string{}}@@ -594,7 +651,12 @@ func (tx *Transaction) doCollectAttrViewBlocks(op *Operation) *TxErr {if loadErr != nil {return fail(loadErr)}- if collectionBlockMatches(rule.BlockSource, treenode.GetNodeInTree(tree, id), tree) {+ matches := matchesByTree[tree.ID]+ if matches == nil {+ matches = collectionMatches(rule.BlockSource, tree)+ matchesByTree[tree.ID] = matches+ }+ if matches[id] {state.requested[op.AvID][rule.ID] = append(state.requested[op.AvID][rule.ID], id)}}diff --git a/kernel/model/attribute_view_collection_sqlcipher_test.go b/kernel/model/attribute_view_collection_sqlcipher_test.goindex ae254e9f12..4db306618d 100644--- a/kernel/model/attribute_view_collection_sqlcipher_test.go+++ b/kernel/model/attribute_view_collection_sqlcipher_test.go@@ -9,6 +9,7 @@ import ("path/filepath""testing"+ "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/cache""github.com/siyuan-note/siyuan/kernel/conf"@@ -18,6 +19,16 @@ import ()func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {+ for _, target := range []string{"", "block", "container"} {+ name := target+ if name == "" {+ name = "default"+ }+ t.Run(name, func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, target) })+ }+}++func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string) {fixture, view, _ := setupBlockCollectionTest(t)boxID := fixture.box.IDtree, err := LoadTreeByBlockID(fixture.sourceID)@@ -54,11 +65,33 @@ func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {delete(cachedDEKs, boxID)cachedDEKsLock.Unlock()})+ sourceID := tree.ID+ if target != "" {+ view.Automations.Spec = 4+ view.Automations.Rules[0].BlockSource.TagTarget = target+ paragraph := treenode.NewParagraph("")+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ if target == "container" {+ quote := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockquote}+ quote.SetIALAttr("id", quote.ID)+ quote.AppendChild(&ast.Node{Type: ast.NodeBlockquoteMarker, Tokens: []byte(">")})+ tree.Root.AppendChild(quote)+ quote.AppendChild(paragraph)+ sourceID = quote.ID+ view.Automations.Rules[0].BlockSource.Types = []string{"b"}+ } else {+ tree.Root.AppendChild(paragraph)+ sourceID = paragraph.ID+ view.Automations.Rules[0].BlockSource.Types = []string{"p"}+ }+ }if _, err = filesys.WriteTree(tree); err != nil {t.Fatal(err)}treenode.UpsertBlockTree(tree)- view.Automations.Rules[0].BlockSource.Tags = nil+ if target == "" {+ view.Automations.Rules[0].BlockSource.Tags = nil+ }view.Automations.Rules[0].BlockSource.Attributes = []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "active"}}if err = av.SaveAttributeView(view); err != nil {t.Fatal(err)@@ -68,13 +101,13 @@ func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {t.Fatal(err)}cache.ClearAVCache()- op := &Operation{Action: "setAttrs", ID: tree.ID, Data: `{"custom-state":"active"}`}- tx := &Transaction{fromAPI: true, DoOperations: []*Operation{op}, UndoOperations: []*Operation{{Action: "setAttrs", ID: tree.ID, Data: `{"custom-state":""}`}}}+ op := &Operation{Action: "setAttrs", ID: sourceID, Data: `{"custom-state":"active"}`}+ tx := &Transaction{fromAPI: true, DoOperations: []*Operation{op}, UndoOperations: []*Operation{{Action: "setAttrs", ID: sourceID, Data: `{"custom-state":""}`}}}if err = PerformTxSync(tx); err != nil {t.Fatal(err)}stored, err := av.ParseAttributeViewForIndexInBox(view.ID, boxID)- if err != nil || stored.GetBlockValueByBoundID(tree.ID) == nil {+ if err != nil || stored.GetBlockValueByBoundID(sourceID) == nil {t.Fatal("encrypted source was not collected", err)}if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(tx.UndoOperations), isReplay: true}); err != nil {@@ -115,7 +148,7 @@ func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {if _, err = PreviewAttributeViewCollection(view.ID, view.Automations.Rules[0].ID, 1); err == nil {t.Fatal("preview accepted inaccessible ciphertext")}- if err = PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "setAttrs", ID: tree.ID, Data: `{"custom-state":"inactive"}`}}}); err == nil {+ if err = PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "setAttrs", ID: sourceID, Data: `{"custom-state":"inactive"}`}}}); err == nil {t.Fatal("collection accepted inaccessible ciphertext")}for path, before := range map[string][]byte{avPath: beforeView, docPath: beforeDoc} {diff --git a/kernel/model/attribute_view_collection_target_fts5_test.go b/kernel/model/attribute_view_collection_target_fts5_test.gonew file mode 100644index 0000000000..5bedcdcebf--- /dev/null+++ b/kernel/model/attribute_view_collection_target_fts5_test.go@@ -0,0 +1,182 @@+//go:build fts5++package model++import (+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestBlockCollectionTagTargets(t *testing.T) {+ newNode := func(typ ast.NodeType) *ast.Node { return &ast.Node{ID: ast.NewNodeID(), Type: typ} }+ tag := func(node *ast.Node, name string) {+ node.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: name})+ }+ for _, typ := range []ast.NodeType{ast.NodeList, ast.NodeBlockquote, ast.NodeCallout, ast.NodeSuperBlock,+ ast.NodeTabs, ast.NodeTabItem, ast.NodeMindmap, ast.NodeMindmapItem} {+ t.Run(typ.String(), func(t *testing.T) {+ root, outer, inner := newNode(ast.NodeDocument), newNode(typ), newNode(ast.NodeListItem)+ first, second := newNode(ast.NodeParagraph), newNode(ast.NodeParagraph)+ root.AppendChild(outer)+ parent := outer+ if typ == ast.NodeTabs {+ parent = newNode(ast.NodeTabItem)+ outer.AppendChild(parent)+ } else if typ == ast.NodeMindmap {+ parent = newNode(ast.NodeMindmapItem)+ outer.AppendChild(parent)+ } else if typ == ast.NodeTabItem || typ == ast.NodeMindmapItem {+ wrapperType := ast.NodeTabs+ if typ == ast.NodeMindmapItem {+ wrapperType = ast.NodeMindmap+ }+ wrapper := newNode(wrapperType)+ outer.Unlink()+ root.AppendChild(wrapper)+ wrapper.AppendChild(outer)+ }+ if typ != ast.NodeList {+ list := newNode(ast.NodeList)+ parent.AppendChild(list)+ parent = list+ }+ parent.AppendChild(inner)+ inner.AppendChild(first)+ inner.AppendChild(second)+ tag(first, "todo")+ tag(second, "todo")+ tree := &parse.Tree{ID: root.ID, Root: root, Box: "box", Path: "/" + root.ID + ".sy"}+ source := &av.AutomationBlockSource{DocumentIDs: []string{root.ID}, Tags: []string{"todo"}}+ matches := collectionMatches(source, tree)+ if len(matches) != 2 || !matches[inner.ID] || !matches[second.ID] {+ t.Fatalf("default list-item behavior changed: %v", matches)+ }+ source.TagTarget = "block"+ matches = collectionMatches(source, tree)+ if len(matches) != 2 || !matches[first.ID] || !matches[second.ID] {+ t.Fatalf("direct tag blocks: %v", matches)+ }+ source.TagTarget = "container"+ matches = collectionMatches(source, tree)+ if len(matches) != 1 || !matches[inner.ID] {+ t.Fatalf("nearest container and duplicate sources: %v", matches)+ }+ outer.SetIALAttr("custom-state", "ready")+ source.Attributes = []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "ready"}}+ matches = collectionMatches(source, tree)+ if len(matches) != 1 || !matches[outer.ID] {+ t.Fatalf("attributes must select the target container: %v", matches)+ }+ source.Tags = []string{"todo", "other"}+ tag(second, "other")+ matches = collectionMatches(source, tree)+ if len(matches) != 1 || !matches[outer.ID] {+ t.Fatal("one source containing all tags did not match")+ }+ second.FirstChild.Unlink()+ if len(collectionMatches(source, tree)) != 0 {+ t.Fatal("AND tags were combined across different source blocks")+ }+ source.TagMatch = "or"+ if !collectionMatches(source, tree)[outer.ID] {+ t.Fatal("OR tags did not match independently")+ }+ source.DocumentIDs = []string{"outside"}+ if len(collectionMatches(source, tree)) != 0 {+ t.Fatal("container matching escaped its document scope")+ }+ })+ }+}++func TestBlockCollectionTagTargetUndoAndPreservation(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ rule := view.Automations.Rules[0]+ view.Automations.Spec = 4+ rule.BlockSource.TagTarget = "container"+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(blockCollectionTags(t, fixture.sourceID, "todo")); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ row := view.GetBlockValueByBoundID(fixture.sourceID)+ if row == nil {+ t.Fatal("explicit document container did not collect")+ }+ itemID := row.BlockID+ view.GetValue(keyID, itemID).Text.Content = "Edited"+ rule = view.Automations.Rules[0]+ rule.BlockSource.TagTarget = "block"+ if err := PerformAttributeViewOperations([]*Operation{{Action: "setAttrViewAutomations", AvID: view.ID, Data: view.Automations}}); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if view.GetBlockValue(itemID) == nil {+ t.Fatal("changing target removed an existing entry")+ }+ view.GetValue(keyID, itemID).Text.Content = "Edited"+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ remove := blockCollectionTags(t, fixture.sourceID, "")+ if err := PerformTxSync(remove); err != nil {+ t.Fatal(err)+ }+ if readAttributeViewItemsTest(t, view.ID).GetBlockValue(itemID) != nil {+ t.Fatal("lost tag did not remove entry")+ }+ undo := &Transaction{DoOperations: cloneOperations(remove.UndoOperations), UndoOperations: cloneOperations(remove.DoOperations), isReplay: true}+ if err := PerformTxSync(undo); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if view.GetBlockValue(itemID) == nil || view.GetValue(keyID, itemID).Text.Content != "Edited" {+ t.Fatal("undo lost the original entry or its edited fields")+ }+}++func TestBlockCollectionTagTargetTypesAndDocuments(t *testing.T) {+ root := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeDocument}+ list := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeList, ListData: &ast.ListData{Typ: 1}}+ item := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeListItem, ListData: &ast.ListData{Typ: 1}}+ paragraph := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}+ tag := &ast.Node{Type: ast.NodeTag}+ tag.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("todo")})+ paragraph.AppendChild(tag)+ root.AppendChild(list)+ list.AppendChild(item)+ item.AppendChild(paragraph)+ tree := &parse.Tree{ID: root.ID, Root: root, Box: "box", Path: "/" + root.ID + ".sy"}+ source := &av.AutomationBlockSource{NotebookIDs: []string{"box"}, Tags: []string{"todo"}, TagTarget: "container"}+ for _, test := range []struct {+ types []string+ want string+ }{+ {[]string{"p", "i:o", "l:o", "d"}, item.ID},+ {[]string{"l:o"}, list.ID},+ {[]string{"l:t"}, ""},+ {[]string{"p"}, ""},+ {[]string{"d"}, root.ID},+ } {+ source.Types = test.types+ matches := collectionMatches(source, tree)+ if test.want == "" && len(matches) != 0 || test.want != "" && (len(matches) != 1 || !matches[test.want]) {+ t.Fatalf("types %v: %v want %s", test.types, matches, test.want)+ }+ }+ source.Types = nil+ list.Unlink()+ root.AppendChild(paragraph)+ if len(collectionMatches(source, tree)) != 0 {+ t.Fatal("unrestricted containers unexpectedly collected the document")+ }+ source.Tags, source.Types = nil, []string{"p"}+ if !collectionMatches(source, tree)[paragraph.ID] {+ t.Fatal("tag target changed a rule without tag conditions")+ }+}