Skip to content

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

:sparkles: Support precise automation block subtype filters https://github.com/siyuan-note/siyuan/issues/20644

Daniel7ea40a42d127
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 b4a41c8801..e53981d414 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
@@ -4535,6 +4535,20 @@
}
]
},
+ {
+ "ID": "20261017195341-czg1ilm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017195341-czg1ilm",
+ "updated": "20261017195341"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "A main block type includes all its subtypes. You can instead select heading levels H1-H6, unordered/ordered/task lists or list items, and built-in or custom callout types. Lists and list items match independently; multiple choices use OR, and an empty selection allows every type. Selecting a main type replaces its selected subtypes. Changing a block subtype uses the same matching logic for automatic collection, removal, and preview. Subtype filters require automation format 3; existing format 1 and 2 rules remain readable, and older clients reject format 3 without rewriting the database."
+ }
+ ]
+ },
{
"ID": "20261015141042-dmlyxmz",
"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.sy
index 7e49b2635c..f44d5526e8 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
@@ -4535,6 +4535,20 @@
}
]
},
+ {
+ "ID": "20261017195341-0qeydtk",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017195341-0qeydtk",
+ "updated": "20261017195341"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "选择主块类型会匹配其全部子类型,也可单独选择 H1~H6 标题、无序/有序/任务列表及列表项,以及内置或自定义提示块类型。列表和列表项独立匹配,多个选项取任一匹配,不选择类型则不限制。选择主类型会替换已选的子类型。修改块子类型后,自动收集、移出和预览使用同一匹配逻辑。子类型筛选需要自动化格式 3,已有格式 1 和 2 的规则仍可读取;旧客户端会拒绝格式 3,不会改写数据库。"
+ }
+ ]
+ },
{
"ID": "20261015141042-4c491yc",
"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.sy
index f73f11d97e..02ad36d9bb 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
@@ -4535,6 +4535,20 @@
}
]
},
+ {
+ "ID": "20261017195341-h2pn2cd",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017195341-h2pn2cd",
+ "updated": "20261017195341"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "選擇主區塊類型會匹配其全部子類型,也可單獨選擇 H1~H6 標題、無序/有序/任務列表及列表項,以及內建或自訂提示區塊類型。列表和列表項獨立匹配,多個選項取任一匹配,不選擇類型則不限制。選擇主類型會替換已選的子類型。修改區塊子類型後,自動收集、移出和預覽使用同一匹配邏輯。子類型篩選需要自動化格式 3,既有格式 1 和 2 的規則仍可讀取;舊版客戶端會拒絕格式 3,不會改寫資料庫。"
+ }
+ ]
+ },
{
"ID": "20261015141042-yui12an",
"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.sy
index c98bc4ee35..c0aff48d80 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
@@ -4545,6 +4545,20 @@
}
]
},
+ {
+ "ID": "20261017195341-nu6ize6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017195341-nu6ize6",
+ "updated": "20261017195341"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ブロックの主種類を選ぶと、そのすべてのサブタイプに一致します。H1~H6 の見出し、箇条書き・番号付き・タスクリストとその項目、組み込みまたは独自のコールアウト種類を個別に選べます。リストとリスト項目は別々に判定し、複数選択は OR、未選択は種類を制限しません。主種類を選ぶと、そのサブタイプの選択を置き換えます。サブタイプの変更後も自動収集・削除・プレビューは同じ判定を使います。サブタイプ条件には自動化形式 3 が必要です。既存の形式 1 と 2 は引き続き読み込めます。旧クライアントは形式 3 を拒否し、データベースを書き換えません。"
+ }
+ ]
+ },
{
"ID": "20261015141042-ag8e3p7",
"Type": "NodeParagraph",
diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.ts
index c2c01715c5..0c6af68c49 100644
--- a/app/src/protyle/render/av/automation.ts
+++ b/app/src/protyle/render/av/automation.ts
@@ -204,7 +204,8 @@ export const openAutomationMenu = async (options: {
updateStatus();
onResize();
const usesTemplates = rules.some(rule => rule.actions.some(action => Object.values(action.fields).some(value => value.mode === "template")));
- const next = {spec: usesTemplates ? 2 : previous.spec, rules: clone(rules)};
+ const usesSubtypes = rules.some(rule => rule.blockSource?.types?.some(type => type.includes(":")));
+ const next = {spec: Math.max(previous.spec, usesSubtypes ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};
if (JSON.stringify(next) === JSON.stringify(previous)) {
return;
}
diff --git a/app/src/protyle/render/av/blockCollection.test.ts b/app/src/protyle/render/av/blockCollection.test.ts
index def1d76483..6c50b64e0a 100644
--- a/app/src/protyle/render/av/blockCollection.test.ts
+++ b/app/src/protyle/render/av/blockCollection.test.ts
@@ -17,6 +17,16 @@ test("collection scope requires a notebook or document and complete attribute na
assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"], attributes: [{name: "custom-state", operator: "equals", value: "open"}]}), false);
});
+test("collection type selection replaces overlapping parents and preserves independent types", () => {
+ const methods = {} as typeof import("./blockCollection");
+ runInNewContext(compiled, {exports: methods, require: () => ({})});
+ const toggle = (types: string[], type: string): string[] => JSON.parse(JSON.stringify(methods.toggleCollectionType(types, type)));
+ assert.deepEqual(toggle(["l:u", "l:t", "i:t"], "l"), ["i:t", "l"]);
+ assert.deepEqual(toggle(["l", "h:h1"], "l:o"), ["h:h1", "l:o"]);
+ assert.deepEqual(toggle(["h:h1"], "h:h2"), ["h:h1", "h:h2"]);
+ assert.deepEqual(toggle(["callout:WARNING"], "callout:WARNING"), []);
+});
+
test("collection preview is read-only and explicit collection uses only unbound previewed IDs", async () => {
const listeners = new Map<string, () => Promise<void>>();
const elements = new Map<string, {disabled: boolean, innerHTML: string, addEventListener: (name: string, callback: () => Promise<void>) => void}>();
diff --git a/app/src/protyle/render/av/blockCollection.ts b/app/src/protyle/render/av/blockCollection.ts
index 0cec8cd03e..9614527f7a 100644
--- a/app/src/protyle/render/av/blockCollection.ts
+++ b/app/src/protyle/render/av/blockCollection.ts
@@ -9,6 +9,13 @@ import {movePathTo} from "../../../util/pathName";
import {transaction} from "../../wysiwyg/transaction";
import {waitForPendingTransactions} from "../../util/transactionQueue";
import {openLink} from "../../../editor/openLink";
+import {openInputDialog} from "../../../dialog/inputDialog";
+
+export const toggleCollectionType = (types: string[], type: string) => {
+ if (types.includes(type)) { return types.filter(item => item !== type); }
+ const main = type.split(":")[0];
+ return [...types.filter(item => type.includes(":") ? item !== main : !item.startsWith(main + ":")), type];
+};
export const collectionSourceIncomplete = (source: AVAutomationBlockSourceInput) => !source ||
!(source.notebookIDs?.length || source.documentIDs?.length) ||
@@ -18,12 +25,16 @@ export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomati
protyle: IProtyle, save: () => void, onResize: () => void) => {
const lang = window.siyuan.languages;
const types: Record<string, string> = {
- d: lang.documentBlock, p: lang.paragraph, h: lang.headings, l: lang.list, i: lang.listItem,
+ d: lang.documentBlock, p: lang.paragraph, h: lang.headings, l: lang.list1, i: lang.listItem,
c: lang.code, m: lang.math, t: lang.tableBlock, b: lang.quote, s: lang.superBlock,
- html: lang.htmlBlock, query_embed: lang.blockEmbed, av: lang.database, iframe: lang.iframeBlock,
- widget: lang.widget, tb: lang.line, video: lang.video, audio: lang.audio, custom: lang.customBlock,
+ html: lang.htmlBlock, query_embed: lang.blockEmbed, av: lang.databaseBlock, iframe: lang.iframeBlock,
+ widget: lang.widgetBlock, tb: lang.line, video: lang.videoBlock, audio: lang.audioBlock, custom: lang.customBlock,
callout: lang.callout, tabs: lang.tabs, tab: lang.tabItem, mindmap: lang.mindmap, mindmap_item: lang.mindmapItem,
};
+ for (let level = 1; level <= 6; level++) { types[`h:h${level}`] = lang[`heading${level}`]; }
+ Object.assign(types, {"l:u": lang.list, "l:o": lang["ordered-list"], "l:t": lang.check,
+ "i:u": lang.unorderedListItemBlock, "i:o": lang.orderedListItemBlock, "i:t": lang.taskListItemBlock});
+ ["NOTE", "TIP", "IMPORTANT", "WARNING", "CAUTION"].forEach(type => types[`callout:${type}`] = `${lang.callout} - ${type}`);
const names = new Map<string, string>();
let revision = 0;
const removeButton = (kind: string, index: number) => `<svg class="b3-menu__action b3-menu__action--show b3-menu__action--warning fn__pointer ariaLabel" data-remove="${kind}" data-index="${index}" role="button" tabindex="0" data-position="north" aria-label="${escapeAttr(lang.delete)}"><use xlink:href="#iconClose"></use></svg>`;
@@ -80,10 +91,20 @@ ${attributes.map((attr, i) => `<div class="av__automation-control" data-attribut
toggleMenu({target, build: () => {
menu = new Menu();
Object.entries(types).forEach(([type, label]) => menu.addItem({label, checked: source.types?.includes(type), click: () => {
- source.types = source.types?.includes(type) ? source.types.filter(item => item !== type) : [...(source.types || []), type];
+ source.types = toggleCollectionType(source.types || [], type);
save();
void render();
}}));
+ menu.addItem({label: `${lang.callout} - ${lang.custom}`, click: () => { openInputDialog({
+ title: lang.callout, label: lang.type, value: "", maxLength: 256, onConfirm: (value, dialog) => {
+ const type = value.trim();
+ if (!type || type.length > 256 || /[\r\n\t]/.test(type)) { return; }
+ source.types = toggleCollectionType(source.types || [], `callout:${type}`);
+ save();
+ void render();
+ dialog.destroy();
+ },
+ }); }});
}, show: () => {
const rect = target.getBoundingClientRect();
menu.open({x: rect.left, y: rect.bottom, h: rect.height, target});
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 4a1825068a..cf42ac2066 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -7814,7 +7814,8 @@ export interface APIPOSTRoutes {
/**
* move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
- * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 或 2,所有视图共享数据库级规则。
+ * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。
+ * blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。
* addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。
* 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。
* 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。
diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.js
index c5389d6ab1..83cd618662 100644
--- a/app/tests/automationPanel.test.js
+++ b/app/tests/automationPanel.test.js
@@ -37,6 +37,7 @@ const runCases = async (sources, css, mobile) => {
const templatePreviews = [];
const searches = [];
let fieldMenu;
+ let collectionTypeInput;
let nextID = 0;
window.Lute = {NewNodeID: () => `generated-${++nextID}`};
window.siyuan = {languages: lang, config: {}, notebooks: [], zIndex: 0, menus: {menu: {remove() {}}}};
@@ -57,6 +58,7 @@ const runCases = async (sources, css, mobile) => {
showSubMenu() {}
}},
"util/functions": {isMobile: () => mobile},
+ "dialog/inputDialog": {openInputDialog: options => { collectionTypeInput = options; }},
"util/fetch": {fetchSyncPost: async (url, request) => url.includes("previewAttributeViewTemplate") ?
(templatePreviews.push(request), {code: 0, data: {type: "date", date: {content: 1792713600000, isNotEmpty: true, isNotTime: true}}}) : url.includes("getHPathByID") ? {code: 0, data: "/Tasks"} :
{code: 0, data: {av: request.id === "source" ? database : targetDatabase}},
@@ -437,7 +439,15 @@ const runCases = async (sources, css, mobile) => {
}
}
await click("[data-types] svg");
- fieldMenu.items.forEach(item => item.click());
+ fieldMenu.items.find(item => item.label === lang.list1).click();
+ assert.deepEqual(latest().blockSource.types, ["l"]);
+ fieldMenu.items.find(item => item.label === lang["ordered-list"]).click();
+ assert.deepEqual(latest().blockSource.types, ["l:o"]);
+ assert.equal(transactions.at(-1).perform[0].data.spec, 3);
+ fieldMenu.items.at(-1).click();
+ collectionTypeInput.onConfirm("CUSTOM", {destroy() {}});
+ assert.deepEqual(latest().blockSource.types, ["l:o", "callout:CUSTOM"]);
+ fieldMenu.items.slice(0, -1).forEach(item => item.click());
await tick();
await require("electron").ipcRenderer.invoke("automation-size", mobile ? 360 : 420, 900);
menu.style.fontSize = "28px";
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 23ed095dc8..b865733e50 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`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。手動で追加した既存項目は保持されます。削除後に再び一致すると初期値を持つ新しい項目を作成し、元に戻す操作では元の項目とフィールドを復元します
+ * `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` が含まれる場合があります。手動で追加した既存項目は保持されます。削除後に再び一致すると初期値を持つ新しい項目を作成し、元に戻す操作では元の項目とフィールドを復元します
### 主キー値を取得
diff --git a/docs/API.md b/docs/API.md
index d33499b0ae..00513b9f84 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`). 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. 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
+ * `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
### Get primary key values
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 3416a092dd..ac39708619 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`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。已有手动条目不受影响;移出后再次匹配会创建新条目并初始化字段,撤销则恢复原条目及字段
+ * `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`。已有手动条目不受影响;移出后再次匹配会创建新条目并初始化字段,撤销则恢复原条目及字段
### 获取主键值
diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.go
index 15da1b6a3e..e25f716421 100644
--- a/kernel/api/contract_av_automation_test.go
+++ b/kernel/api/contract_av_automation_test.go
@@ -199,4 +199,36 @@ func TestAVContractAutomationWrites(t *testing.T) {
if stored.GetBlockValueByBoundID(collected.Block.ID) != nil {
t.Fatal("batch attribute API left an unmatched row")
}
+ collection.BlockSource.Attributes = nil
+ collection.BlockSource.Types = []string{"h:h1"}
+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,
+ Data: &av.AutomationConfig{Spec: 3, Rules: []*av.AutomationRule{collection}}}}); err != nil {
+ t.Fatal(err)
+ }
+ call("/api/av/getAttributeView", map[string]any{"id": database.ID}, getAttributeView)
+ call("/api/block/appendBlock", map[string]any{"parentID": tree.ID, "dataType": "markdown", "data": "# Collected heading"}, appendBlock)
+ stored, _ = av.ParseAttributeView(database.ID)
+ var heading *av.Value
+ for _, row := range stored.GetBlockKeyValues().Values {
+ if row.Block.CollectionRuleID == collection.ID {
+ heading = row
+ break
+ }
+ }
+ if heading == nil {
+ t.Fatal("heading subtype did not collect")
+ }
+ preview, err := model.PreviewAttributeViewCollection(database.ID, collection.ID, 1)
+ if err != nil || len(preview.Blocks) != 1 || preview.Blocks[0].ID != heading.Block.ID {
+ t.Fatalf("subtype preview: %+v %v", preview, err)
+ }
+ call("/api/block/updateBlock", map[string]any{"id": heading.Block.ID, "dataType": "markdown", "data": "## Collected heading"}, updateBlock)
+ stored, _ = av.ParseAttributeView(database.ID)
+ if stored.GetBlockValueByBoundID(heading.Block.ID) != nil {
+ t.Fatal("heading subtype change did not remove row")
+ }
+ preview, err = model.PreviewAttributeViewCollection(database.ID, collection.ID, 1)
+ if err != nil || len(preview.Blocks) != 0 {
+ t.Fatalf("unmatched subtype preview: %+v %v", preview, err)
+ }
}
diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.go
index 3e673a6061..68dd34883f 100644
--- a/kernel/apicontract/av_automation.go
+++ b/kernel/apicontract/av_automation.go
@@ -1,7 +1,8 @@
package apicontract
// AVAutomationConfig 通过 setAttrViewAutomations 事务操作整体保存,所有镜像和视图共享。
-// spec 为 1 或 2;模板赋值必须使用 2,旧版本会拒绝读取,防止配置静默丢失。缺省配置不会触发自动化。
+// spec 为 1、2 或 3;模板赋值至少使用 2,块子类型至少使用 3;旧读取器拒绝新版本,防止配置静默丢失。
+// 缺省配置不会触发自动化,既有版本的主类型匹配含义不变。
// 普通条目新增、字段编辑及对应 API 会触发启用的规则,
// 导入、同步、历史恢复和撤销重放不会再次触发,自动化之间不串联。
// 自动操作与源修改一同提交、失败回滚及撤销;单笔事务最多产生 1000 个自动操作。
@@ -27,6 +28,8 @@ type AVAutomationRule struct {
// AVAutomationBlockSource 监听范围取笔记本与文档的并集,文档包含子文档;范围至少选择一项。
// 类型和标签分别取或、与关系,所有自定义属性条件取与关系。标签精确匹配,不递归匹配父容器。
+// types 为空不限制类型;主类型匹配其全部子类型,类型之间取或关系。
+// spec 3 支持 h:h1 至 h:h6、l:u/o/t、i:u/o/t 和 callout:类型名;提示块类型区分大小写,允许自定义名称。
// 列表项首段的标签默认归属列表项;显式选择段落类型时可匹配该段落。
// 仅从不匹配变为匹配时收集,原条目不会重置;失配时移出本功能创建的条目,保留源块。
// 其他启用的收集规则仍匹配时保留条目;停用或删除创建规则会保留既有条目。
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 91e53eaef9..e9c64cb84e 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1437,7 +1437,8 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system
// move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
-// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 或 2,所有视图共享数据库级规则。
+// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。
+// blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。
// addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。
// 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。
// 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。
diff --git a/kernel/av/automation.go b/kernel/av/automation.go
index 5cc17e3bd1..3c747479cb 100644
--- a/kernel/av/automation.go
+++ b/kernel/av/automation.go
@@ -2,6 +2,8 @@ package av
import (
"fmt"
+ "slices"
+ "strings"
"github.com/88250/lute/ast"
)
@@ -39,6 +41,63 @@ type AutomationBlockAttribute struct {
Value string `json:"value,omitempty"`
}
+// IsAutomationBlockType 校验主类型或主类型与子类型的组合,提示块允许自定义类型名称。
+func IsAutomationBlockType(value string) bool {
+ typ, sub, qualified := strings.Cut(value, ":")
+ if !qualified {
+ return slices.Contains([]string{"d", "h", "l", "i", "c", "m", "t", "b", "s", "p", "html",
+ "query_embed", "av", "iframe", "widget", "tb", "video", "audio", "custom", "callout", "tabs", "tab",
+ "mindmap", "mindmap_item"}, typ)
+ }
+ switch typ {
+ case "h":
+ return slices.Contains([]string{"h1", "h2", "h3", "h4", "h5", "h6"}, sub)
+ case "l", "i":
+ return slices.Contains([]string{"u", "o", "t"}, sub)
+ case "callout":
+ return sub != "" && sub == strings.TrimSpace(sub) && len(sub) <= 256 && !strings.ContainsAny(sub, "\r\n\t")
+ }
+ return false
+}
+
+// RequiredSpec 保留普通规则的版本,仅在使用新增语义时要求支持该语义的读取器。
+func (rule *AutomationRule) RequiredSpec() int {
+ ret := 1
+ if rule.BlockSource != nil {
+ for _, typ := range rule.BlockSource.Types {
+ if strings.Contains(typ, ":") {
+ return 3
+ }
+ }
+ }
+ for _, action := range rule.Actions {
+ if action == nil {
+ continue
+ }
+ for _, value := range action.Fields {
+ if value != nil && value.Mode == "template" {
+ ret = 2
+ }
+ }
+ }
+ return ret
+}
+
+func (config *AutomationConfig) ValidateSpec() error {
+ if config == nil {
+ return nil
+ }
+ if config.Spec < 1 || config.Spec > 3 {
+ return fmt.Errorf("unsupported database automation specification [%d]", config.Spec)
+ }
+ for _, rule := range config.Rules {
+ if rule != nil && rule.RequiredSpec() > config.Spec {
+ return fmt.Errorf("automation rule requires specification [%d]", rule.RequiredSpec())
+ }
+ }
+ return nil
+}
+
type AutomationAction struct {
Type string `json:"type"` // edit、add 或 collect
Target string `json:"target"` // current、related 或 filtered
diff --git a/kernel/av/automation_test.go b/kernel/av/automation_test.go
index 9be36cbc83..f35c614b62 100644
--- a/kernel/av/automation_test.go
+++ b/kernel/av/automation_test.go
@@ -112,13 +112,48 @@ 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 = 3
+ source.Automations.Spec = 4
future, _ := json.Marshal(source)
if _, err := ParseAttributeViewData(source.ID, future); err == nil {
t.Fatal("unknown automation format was accepted")
}
}
+func TestAutomationBlockTypeAndSpecCompatibility(t *testing.T) {
+ for _, typ := range []string{"l", "i", "h", "mindmap", "callout", "l:u", "l:o", "l:t", "i:t", "h:h1", "h:h6", "callout:WARNING", "callout:CUSTOM"} {
+ if !IsAutomationBlockType(typ) {
+ t.Fatalf("valid type rejected: %s", typ)
+ }
+ }
+ for _, typ := range []string{"ial", "l:task", "h:h7", "p:u", "mindmap:u", "callout:", "callout: NOTE", "callout:NOTE\n"} {
+ if IsAutomationBlockType(typ) {
+ t.Fatalf("invalid type accepted: %s", typ)
+ }
+ }
+ data, err := os.ReadFile("testdata/spec9-layouts.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, spec := range []int{1, 2, 3} {
+ view, err := ParseAttributeViewData("20260921000000-layouts", data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rule := &AutomationRule{ID: ast.NewNodeID(), Name: "Collect", BlockSource: &AutomationBlockSource{Types: []string{"l"}}}
+ view.Automations = &AutomationConfig{Spec: spec, Rules: []*AutomationRule{rule}}
+ raw, _ := json.Marshal(view)
+ if _, err := ParseAttributeViewData(view.ID, raw); err != nil {
+ t.Fatalf("legacy type spec %d: %v", spec, err)
+ }
+ rule.BlockSource.Types = []string{"l:t"}
+ raw, _ = json.Marshal(view)
+ _, err = ParseAttributeViewData(view.ID, raw)
+ if (err == nil) != (spec == 3) {
+ t.Fatalf("subtype spec %d: %v", spec, err)
+ }
+ }
+}
+
func TestAutomationPreservesPersistedColors(t *testing.T) {
view := &AttributeView{Automations: &AutomationConfig{Spec: 1, Rules: []*AutomationRule{{
Actions: []*AutomationAction{{Fields: map[string]*AutomationValue{"select": {
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 8cd30ab56d..202c1d251d 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -960,25 +960,8 @@ func parseAttributeViewData(avID string, data []byte, normalizeRichText bool) (r
if nil == err {
err = CheckSpec(ret)
}
- if err == nil && ret.Automations != nil && ret.Automations.Spec != 1 && ret.Automations.Spec != 2 {
- err = fmt.Errorf("unsupported database automation specification [%d]", ret.Automations.Spec)
- }
- if err == nil && ret.Automations != nil && ret.Automations.Spec == 1 {
- for _, rule := range ret.Automations.Rules {
- if rule == nil {
- continue
- }
- for _, action := range rule.Actions {
- if action == nil {
- continue
- }
- for _, field := range action.Fields {
- if field != nil && field.Mode == "template" {
- err = fmt.Errorf("template assignments require automation spec 2")
- }
- }
- }
- }
+ if err == nil {
+ err = ret.Automations.ValidateSpec()
}
if nil == err {
err = ret.ValidateLayouts()
diff --git a/kernel/model/attribute_view_automation.go b/kernel/model/attribute_view_automation.go
index be85307676..4edfef30bd 100644
--- a/kernel/model/attribute_view_automation.go
+++ b/kernel/model/attribute_view_automation.go
@@ -764,7 +764,10 @@ func (tx *Transaction) doSetAttrViewAutomations(op *Operation) *TxErr {
if err = json.Unmarshal(data, &config); err != nil {
return fail(err)
}
- if config.Spec != 1 && config.Spec != 2 || len(config.Rules) > 100 {
+ if err = config.ValidateSpec(); err != nil {
+ return fail(err)
+ }
+ if len(config.Rules) > 100 {
return fail(fmt.Errorf("unsupported automation configuration"))
}
if err = (&av.AttributeView{Automations: &config}).NormalizeLocations(); nil != err {
diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.go
index 89b16c6eae..66c7e7df28 100644
--- a/kernel/model/attribute_view_collection.go
+++ b/kernel/model/attribute_view_collection.go
@@ -51,8 +51,15 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, tr
if node == nil || !node.IsBlock() || !ast.IsNodeIDPattern(node.ID) || !collectionScopeMatches(source, tree) {
return false
}
- if len(source.Types) > 0 && !slices.Contains(source.Types, treenode.TypeAbbr(node.Type.String())) {
- return false
+ if len(source.Types) > 0 {
+ typ := treenode.TypeAbbr(node.Type.String())
+ matched := slices.Contains(source.Types, typ)
+ if !matched && (typ == "h" || typ == "callout" || (typ == "l" || typ == "i") && node.ListData != nil) {
+ matched = slices.Contains(source.Types, typ+":"+treenode.SubTypeAbbr(node))
+ }
+ if !matched {
+ return false
+ }
}
for _, attr := range source.Attributes {
if attr == nil {
@@ -145,7 +152,7 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rule
}
}
for _, typ := range source.Types {
- if !slices.Contains([]string{"d", "h", "l", "i", "c", "m", "t", "b", "s", "p", "html", "query_embed", "av", "iframe", "widget", "tb", "video", "audio", "custom", "callout", "tabs", "tab", "mindmap", "mindmap_item"}, typ) {
+ if !av.IsAutomationBlockType(typ) {
return fmt.Errorf("invalid block collection type [%s]", typ)
}
}
diff --git a/kernel/model/attribute_view_collection_fts5_test.go b/kernel/model/attribute_view_collection_fts5_test.go
index 60449570bc..2ba002e11d 100644
--- a/kernel/model/attribute_view_collection_fts5_test.go
+++ b/kernel/model/attribute_view_collection_fts5_test.go
@@ -263,6 +263,36 @@ func TestBlockCollectionInlineTagsAndAttributes(t *testing.T) {
}
}
+func TestBlockCollectionSubtypes(t *testing.T) {
+ rootID := ast.NewNodeID()
+ tree := &parse.Tree{ID: rootID, Box: "notebook", Path: "/" + rootID + ".sy"}
+ for _, test := range []struct {
+ typ ast.NodeType
+ sub string
+ listType, level int
+ }{
+ {ast.NodeList, "u", 0, 0}, {ast.NodeList, "o", 1, 0}, {ast.NodeList, "t", 3, 0},
+ {ast.NodeListItem, "u", 0, 0}, {ast.NodeListItem, "o", 1, 0}, {ast.NodeListItem, "t", 3, 0},
+ {ast.NodeHeading, "h1", 0, 1}, {ast.NodeHeading, "h2", 0, 2}, {ast.NodeHeading, "h6", 0, 6},
+ {ast.NodeCallout, "WARNING", 0, 0}, {ast.NodeCallout, "NOTE", 0, 0}, {ast.NodeCallout, "CUSTOM", 0, 0},
+ {ast.NodeParagraph, "", 0, 0},
+ } {
+ node := &ast.Node{ID: ast.NewNodeID(), Type: test.typ, HeadingLevel: test.level,
+ ListData: &ast.ListData{Typ: test.listType}, CalloutType: test.sub}
+ main := treenode.TypeAbbr(node.Type.String())
+ for _, types := range [][]string{nil, {main}, {"l:u"}, {"i:t"}, {"h:h1", "h:h2"}, {"callout:WARNING"}, {"callout:CUSTOM"}} {
+ source := &av.AutomationBlockSource{DocumentIDs: []string{rootID}, Types: types}
+ want := len(types) == 0
+ for _, typ := range types {
+ want = want || typ == main || test.sub != "" && typ == main+":"+test.sub
+ }
+ if got := collectionBlockMatches(source, node, tree); got != want {
+ t.Fatalf("%s:%s with %v: %v want %v", main, test.sub, types, got, want)
+ }
+ }
+ }
+}
+
func TestBlockCollectionCreateAndMoveAcrossScope(t *testing.T) {
fixture, view, _ := setupBlockCollectionTest(t)
rule := view.Automations.Rules[0]