Skip to content

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

:sparkles: Improve attribute name matching in database auto-collection https://github.com/siyuan-note/siyuan/issues/20781

Danield5a79475d26d
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 4bfac99159..3e55f9b732 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": "20261020211145"
+ "updated": "20261021135332"
},
"Children": [
{
@@ -4563,6 +4563,20 @@
}
]
},
+ {
+ "ID": "20261021135332-1brkvpw",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021135332-1brkvpw",
+ "updated": "20261021135332"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Attribute name supports Equals (the default), Contains, and Regex, independently of the attribute value condition. Equals uses the full name, such as custom-state. Contains accepts a literal substring without the custom- prefix: dailynote matches custom-dailynote-20261021. Regex uses Go syntax against the full name, for example ^custom-dailynote-[0-9]{8}$. Only custom attributes are checked. Names and values are case-sensitive and must match the same attribute; Exists requires any matching name, while Does not exist requires none and ignores the value. Invalid regular expressions cannot be saved, and patterns are limited to 256 bytes. Contains and Regex require automation format 6; existing formats 1–5 remain readable, while older clients reject format 6 without rewriting the database."
+ }
+ ]
+ },
{
"ID": "20261017204817-jfdo45b",
"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 1eb3a7423d..eb64dc4e19 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": "20261020211145"
+ "updated": "20261021135332"
},
"Children": [
{
@@ -4563,6 +4563,20 @@
}
]
},
+ {
+ "ID": "20261021135332-xudc33f",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021135332-xudc33f",
+ "updated": "20261021135332"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "「属性名」可独立选择「等于」(默认)、「包含」或「正则表达式」,不影响属性值的条件。「等于」使用 custom-state 这样的完整名称;「包含」只需输入字面子串,无需 custom- 前缀,例如 dailynote 可匹配 custom-dailynote-20261021;正则使用 Go 语法匹配完整名称,例如 ^custom-dailynote-[0-9]{8}$。只检查自定义属性,名称和值区分大小写,且须由同一条属性同时满足条件;「存在」要求至少一个名称匹配,「不存在」要求没有名称匹配,两者忽略属性值。非法正则无法保存,名称模式最多 256 字节。「包含」和「正则表达式」需要自动化格式 6;已有格式 1–5 仍可读取,旧客户端会拒绝格式 6 且不改写数据库。"
+ }
+ ]
+ },
{
"ID": "20261017204817-4ocp9jq",
"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 939a73cfe2..e03499f9ca 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": "20261020211145"
+ "updated": "20261021135332"
},
"Children": [
{
@@ -4563,6 +4563,20 @@
}
]
},
+ {
+ "ID": "20261021135332-36rh1ee",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021135332-36rh1ee",
+ "updated": "20261021135332"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "「屬性名稱」可獨立選擇「等於」(預設)、「包含」或「正規表示式」,不影響屬性值的條件。「等於」使用 custom-state 這類完整名稱;「包含」只需輸入字面子字串,不必輸入 custom- 前綴,例如 dailynote 可符合 custom-dailynote-20261021;正規表示式使用 Go 語法比對完整名稱,例如 ^custom-dailynote-[0-9]{8}$。僅檢查自訂屬性,名稱和值區分大小寫,且須由同一條屬性同時滿足條件;「存在」要求至少一個名稱符合,「不存在」要求沒有名稱符合,兩者忽略屬性值。無效的正規表示式無法儲存,名稱模式最多 256 位元組。「包含」和「正規表示式」需要自動化格式 6;既有格式 1–5 仍可讀取,舊用戶端會拒絕格式 6 且不改寫資料庫。"
+ }
+ ]
+ },
{
"ID": "20261017204817-t0qt0db",
"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 31b0bc1ca6..1730bbcc6d 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": "20261020211145"
+ "updated": "20261021135332"
},
"Children": [
{
@@ -4573,6 +4573,20 @@
}
]
},
+ {
+ "ID": "20261021135332-1xj7aht",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021135332-1xj7aht",
+ "updated": "20261021135332"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "「属性名」は値の条件とは独立して「等しい」(既定)、「含む」、「正規表現」を選べます。「等しい」は custom-state のような完全な名前を使用します。「含む」は custom- 接頭辞を入力する必要がなく、dailynote で custom-dailynote-20261021 に一致します。正規表現は Go の構文で完全な名前と照合し、例は ^custom-dailynote-[0-9]{8}$ です。カスタム属性だけを対象とし、名前と値は大文字小文字を区別して同じ属性で条件を満たす必要があります。「存在する」は名前の一致が一つ以上、「存在しない」は一致がないことを要求し、値は無視します。不正な式は保存できず、名前パターンは最大 256 バイトです。「含む」と「正規表現」には自動化形式 6 が必要です。既存の形式 1–5 は読み込めますが、古いクライアントは形式 6 を拒否し、データベースを書き換えません。"
+ }
+ ]
+ },
{
"ID": "20261017204817-a41svnn",
"Type": "NodeParagraph",
diff --git a/app/src/protyle/render/av/automation.test.ts b/app/src/protyle/render/av/automation.test.ts
index 6a88148771..875b701a5c 100644
--- a/app/src/protyle/render/av/automation.test.ts
+++ b/app/src/protyle/render/av/automation.test.ts
@@ -11,7 +11,7 @@ const compiled = transpileModule(readFileSync("src/protyle/render/av/automation.
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
}).outputText;
-test("document depth autosave upgrades format including zero and preserves undo snapshots", async () => {
+test("collection autosave versions document depth and attribute name modes with independent undo snapshots", async () => {
const transactions: Array<{perform: IOperation[], undo: IOperation[]}> = [];
let source: AVAutomationBlockSourceInput;
let save: () => void;
@@ -58,6 +58,18 @@ test("document depth autosave upgrades format including zero and preserves undo
assert.equal(last.rules[0].blockSource.documentDepth, undefined);
assert.equal(last.rules[0].enabled, true);
assert.equal(database.automations.spec, 1);
+ source.attributes = [{name: "dailynote", nameOperator: "contains", operator: "exists"}];
+ save();
+ const named = JSON.parse(JSON.stringify(transactions.at(-1)));
+ assert.equal(named.perform[0].data.spec, 6);
+ assert.equal(named.perform[0].data.rules[0].blockSource.attributes[0].nameOperator, "contains");
+ assert.equal(named.undo[0].data.spec, 5);
+ source.attributes[0] = {name: "^custom-dailynote-[0-9]{8}$", nameOperator: "regex", operator: "notExists"};
+ save();
+ assert.equal(JSON.parse(JSON.stringify(transactions.at(-1).perform[0].data)).spec, 6);
+ source.attributes = [];
+ save();
+ assert.equal(JSON.parse(JSON.stringify(transactions.at(-1).perform[0].data)).spec, 6);
});
test("automation settings reject readonly, publishing and historical editors before fetching data", async () => {
diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.ts
index 4c83ac3cbd..c1925a1016 100644
--- a/app/src/protyle/render/av/automation.ts
+++ b/app/src/protyle/render/av/automation.ts
@@ -211,7 +211,9 @@ export const openAutomationMenu = async (options: {
rule.blockSource?.tagMatch === "or" || rule.blockSource?.attributeMatch === "or");
const usesTagTarget = rules.some(rule => !!rule.blockSource?.tagTarget);
const usesDocumentDepth = rules.some(rule => rule.blockSource?.documentDepth != null);
- const next = {spec: Math.max(previous.spec, usesDocumentDepth ? 5 : usesTagTarget ? 4 : usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};
+ const usesAttributeNameMatch = rules.some(rule => rule.blockSource?.attributes?.some(attr =>
+ attr?.nameOperator && attr.nameOperator !== "equals"));
+ const next = {spec: Math.max(previous.spec, usesAttributeNameMatch ? 6 : usesDocumentDepth ? 5 : usesTagTarget ? 4 : usesSourceOptions ? 3 : usesTemplates ? 2 : 1), rules: clone(rules)};
if (JSON.stringify(next) === JSON.stringify(previous)) {
return;
}
diff --git a/app/src/protyle/render/av/blockCollection.test.ts b/app/src/protyle/render/av/blockCollection.test.ts
index f33dbc3c27..beed4b71ab 100644
--- a/app/src/protyle/render/av/blockCollection.test.ts
+++ b/app/src/protyle/render/av/blockCollection.test.ts
@@ -21,6 +21,10 @@ test("collection scope requires a notebook or document and complete attribute na
assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"]}), false);
assert.equal(methods.collectionSourceIncomplete({notebookIDs: ["notebook"], attributes: [{name: "custom-", operator: "exists"}]}), true);
assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"], attributes: [{name: "custom-state", operator: "equals", value: "open"}]}), false);
+ for (const [nameOperator, name] of [["contains", "dailynote"], ["regex", "^custom-dailynote-[0-9]{8}$"]] as const) {
+ assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"], attributes: [{name, nameOperator, operator: "exists"}]}), false);
+ assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"], attributes: [{name: "", nameOperator, operator: "exists"}]}), true);
+ }
for (const documentDepth of [undefined, null, 0, 1, 12]) {
assert.equal(methods.collectionSourceIncomplete({documentIDs: ["doc"], documentDepth}), false);
}
diff --git a/app/src/protyle/render/av/blockCollection.ts b/app/src/protyle/render/av/blockCollection.ts
index dbb95e0cf3..cd55b3239d 100644
--- a/app/src/protyle/render/av/blockCollection.ts
+++ b/app/src/protyle/render/av/blockCollection.ts
@@ -10,7 +10,9 @@ import {toggleMenu} from "../../../menus/menuToggle";
export const collectionSourceIncomplete = (source: AVAutomationBlockSourceInput) => !source ||
!(source.notebookIDs?.length || source.documentIDs?.length) ||
(source.documentDepth != null && (!Number.isSafeInteger(source.documentDepth) || source.documentDepth < 0)) ||
- (source.attributes || []).some(attr => !attr || !/^custom-[\w-]+$/.test(attr.name));
+ (source.attributes || []).some(attr => !attr || !attr.name || attr.name.length > 256 ||
+ (attr.nameOperator === "regex" ? false :
+ !(attr.nameOperator === "contains" ? /^[a-z0-9-]+$/ : /^custom-[\w-]+$/).test(attr.name)));
export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomationBlockSourceInput,
protyle: IProtyle, save: () => void, onResize: () => void) => {
diff --git a/app/src/protyle/render/av/collectionConditions.ts b/app/src/protyle/render/av/collectionConditions.ts
index d60362f412..6e1f09e11c 100644
--- a/app/src/protyle/render/av/collectionConditions.ts
+++ b/app/src/protyle/render/av/collectionConditions.ts
@@ -30,6 +30,7 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatio
(source.types || []).filter(type => type.startsWith("callout:")).forEach(type => types[type] = `${lang.callout} - ${type.slice(8)}`);
const operators = {equals: lang.filterOperatorIs, contains: lang.filterOperatorContains,
exists: lang.automationAttrExists, notExists: lang.automationAttrNotExists};
+ const nameOperators = {equals: lang.filterOperatorIs, contains: lang.filterOperatorContains, regex: lang.regex};
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};
@@ -50,13 +51,13 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatio
const renderChips = () => {
typeChips.innerHTML = (source.types || []).map((type, i) => chip("type", i, types[type] || type)).join("");
attributes.innerHTML = (source.attributes || []).map((attr, i) => chip("attribute", i,
- `${attr.name} ${operators[attr.operator]}${["equals", "contains"].includes(attr.operator) ? " " + (attr.value || "") : ""}`, true)).join("");
+ `${attr.nameOperator && attr.nameOperator !== "equals" ? nameOperators[attr.nameOperator] + " " : ""}${attr.name} ${operators[attr.operator]}${["equals", "contains"].includes(attr.operator) ? " " + (attr.value || "") : ""}`, true)).join("");
typeChips.classList.toggle("fn__none", !source.types?.length);
attributes.classList.toggle("fn__none", !source.attributes?.length);
resize();
};
const renderEditor = () => {
- editor.innerHTML = draft ? `<div class="av__automation-control"><input class="b3-text-field" data-attr-name aria-label="${escapeAttr(lang.attr)}" placeholder="custom-name" maxlength="256" value="${escapeAttr(draft.name)}"><div class="av__automation-row"><button type="button" class="b3-button b3-button--cancel" data-attr-operator>${operators[draft.operator]}<svg><use xlink:href="#iconDown"></use></svg></button>${["equals", "contains"].includes(draft.operator) ? `<input class="b3-text-field fn__flex-1" data-attr-value aria-label="${escapeAttr(lang.text)}" value="${escapeAttr(draft.value || "")}">` : ""}</div><div class="av__automation-row"><button type="button" class="b3-button b3-button--text" data-confirm-attribute>${lang.confirm}</button><button type="button" class="b3-button b3-button--cancel" data-cancel-attribute>${lang.cancel}</button></div></div>` : "";
+ editor.innerHTML = draft ? `<div class="av__automation-control"><div class="av__automation-row"><span class="fn__flex-1">${lang.attrName}</span><button type="button" class="b3-button b3-button--cancel" data-attr-name-operator>${nameOperators[draft.nameOperator || "equals"]}<svg><use xlink:href="#iconDown"></use></svg></button></div><input class="b3-text-field" data-attr-name aria-label="${escapeAttr(lang.attrName)}" placeholder="${draft.nameOperator === "regex" ? "^custom-dailynote-[0-9]{8}$" : draft.nameOperator === "contains" ? "dailynote" : "custom-name"}" maxlength="256" value="${escapeAttr(draft.name)}"><div class="av__automation-row"><button type="button" class="b3-button b3-button--cancel" data-attr-operator>${operators[draft.operator]}<svg><use xlink:href="#iconDown"></use></svg></button>${["equals", "contains"].includes(draft.operator) ? `<input class="b3-text-field fn__flex-1" data-attr-value aria-label="${escapeAttr(lang.text)}" value="${escapeAttr(draft.value || "")}">` : ""}</div><div class="av__automation-row"><button type="button" class="b3-button b3-button--text" data-confirm-attribute>${lang.confirm}</button><button type="button" class="b3-button b3-button--cancel" data-cancel-attribute>${lang.cancel}</button></div></div>` : "";
host.querySelector<HTMLElement>("[data-add-attribute]").classList.toggle("fn__none", !!draft);
resize();
};
@@ -64,8 +65,10 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatio
if (!draft) { return; }
if (!cancel) {
const input = editor.querySelector<HTMLInputElement>("[data-attr-name]");
- draft.name = input.value.trim().toLowerCase();
- input.setCustomValidity(/^custom-[\w-]+$/.test(draft.name) ? "" : lang.invalid);
+ draft.name = draft.nameOperator === "regex" ? input.value.trim() : input.value.trim().toLowerCase();
+ const valid = draft.nameOperator === "regex" ? !!draft.name :
+ (draft.nameOperator === "contains" ? /^[a-z0-9-]+$/ : /^custom-[\w-]+$/).test(draft.name);
+ input.setCustomValidity(valid ? "" : lang.invalid);
if (!input.reportValidity()) { return; }
const next = [...(source.attributes || [])];
if (editing >= 0) { next[editing] = {...draft}; } else { next.push({...draft}); }
@@ -181,6 +184,12 @@ export const mountCollectionConditions = (host: HTMLElement, source: AVAutomatio
save();
target.firstChild.textContent = modeLabel(mode);
});
+ } else if (target.hasAttribute("data-attr-name-operator") && draft) {
+ choose(target, Object.entries(nameOperators).map(([value, label]) => ({value, label})), draft.nameOperator || "equals", value => {
+ if (value === "contains" || value === "regex") { draft.nameOperator = value; }
+ else { delete draft.nameOperator; }
+ renderEditor();
+ });
} else if (target.hasAttribute("data-attr-operator") && draft) {
choose(target, Object.entries(operators).map(([value, label]) => ({value, label})), draft.operator, value => {
draft.operator = value === "contains" ? "contains" : value === "exists" ? "exists" : value === "notExists" ? "notExists" : "equals";
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 3e3df66548..6b59d55039 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -256,9 +256,9 @@ export type AVAutomationAction = { "avID"?: string; "fields": Record<string, AVA
export type AVAutomationActionInput = { "avID"?: string; "fields": Record<string, AVAutomationValueInput | null>; "filters"?: Array<AVViewFilterInput | null>; "relationKeyID"?: string; "target": "current" | "related" | "filtered"; "type": "add" | "edit" | "collect"; };
-export type AVAutomationBlockAttribute = { "name": string; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };
+export type AVAutomationBlockAttribute = { "name": string; "nameOperator"?: "" | "equals" | "contains" | "regex"; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };
-export type AVAutomationBlockAttributeInput = { "name": string; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };
+export type AVAutomationBlockAttributeInput = { "name": string; "nameOperator"?: "" | "equals" | "contains" | "regex"; "operator": "equals" | "contains" | "exists" | "notExists"; "value"?: string; };
export type AVAutomationBlockSource = { "attributeMatch"?: "" | "and" | "or"; "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentDepth"?: number; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tagMatch"?: "" | "and" | "or"; "tagTarget"?: "" | "block" | "container"; "tags"?: Array<string>; "types"?: Array<string>; };
@@ -8187,11 +8187,12 @@ export interface APIPOSTRoutes {
/**
* move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
- * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 5,所有视图共享数据库级规则。
+ * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 6,所有视图共享数据库级规则。
* blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。
* blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。
* spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。
* spec 5 的 blockSource.documentDepth 限制各文档范围的子文档深度,0 仅自身,1 包含自身及一级子文档。
+ * spec 6 的属性 nameOperator 支持 contains 和 Go regex;缺省或 equals 保持精确名称匹配,值条件独立。
* 深度缺省或 null 不限,不影响笔记本范围,各范围仍取并集;修改不自动清理或补收已有内容。
* 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。
* 类型和属性始终筛选最终对象;默认首个内容块优先归属合格列表项,每次标签命中只选择一个对象。
diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.js
index 85e3c26ebe..b932371450 100644
--- a/app/tests/automationPanel.test.js
+++ b/app/tests/automationPanel.test.js
@@ -675,6 +675,23 @@ const runCases = async (sources, css, mobile) => {
assert.deepEqual(latest().blockSource.attributes, [{name: "custom-status", operator: "equals", value: "ready"}]);
await click('[data-remove-filter="attribute"]');
assert.equal(latest().blockSource.attributes.length, 0);
+ for (const [nameOperator, label, name] of [
+ ["contains", lang.filterOperatorContains, "dailynote"],
+ ["regex", lang.regex, "^custom-\\D+-[0-9]{8}$"],
+ ]) {
+ await click("[data-add-attribute]");
+ await click("[data-attr-name-operator]");
+ assert.equal(fieldMenu.items.find(item => item.label === lang.filterOperatorIs).checked, true);
+ fieldMenu.items.find(item => item.label === label).click();
+ await change("[data-attr-name]", name);
+ await click("[data-confirm-attribute]");
+ assert.deepEqual(latest().blockSource.attributes, [{name, nameOperator, operator: "exists"}]);
+ assert.equal(transactions.at(-1).perform[0].data.spec, 6);
+ await click("[data-edit-attribute]");
+ assert.equal(get("[data-attr-name]").value, name, "regex escapes retain their case");
+ await click("[data-cancel-attribute]");
+ await click('[data-remove-filter="attribute"]');
+ }
await click('[data-match="tagMatch"]');
fieldMenu.items.find(item => item.label === lang.filterMatchAny).click();
assert.equal(latest().blockSource.tagMatch, "or");
@@ -689,7 +706,7 @@ const runCases = async (sources, css, mobile) => {
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(transactions.at(-1).perform[0].data.spec, 6);
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);
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 01e8cc94a0..aa30f2c95e 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -2213,7 +2213,7 @@ if (response.code === 0 && response.data) {
* `data.av`: 完全な `AttributeView` 定義——フィールド(`keyValues`)、フィールド順序(`keyIDs`、`null` の場合あり)、および全ビューの生のレイアウト設定(`table`/`gallery`/`kanban`)とアイテム順序(`itemIds`)。互換性フィールド `viewID` は最初に利用可能なビューから算出され、永続化されません。レンダリング後の行やページングは含まれないため、計算後の行データが必要な場合は [レンダリング](#レンダリング) を使用してください
- * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`~`5`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。自動収集は追加だけを行います。原文やルールの条件・範囲・対象・有効状態が変わっても既存の項目とフィールドを保持し、再び一致しても同じ項目を使います。明示的な整理ではすべての有効な収集ルールを使い、手動・自動でバインドした項目を同じ基準で確認します。一致する項目や判定できない項目は保持し、実行前の再確認で不一致が確定した項目だけを除去します。元に戻す操作で元の項目と全フィールドを復元します。 `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。 形式 4 では省略可能な `blockSource.tagTarget` を追加しています。省略・空文字列は既定の選択で、最初の内容ブロックより条件に合うリスト項目を優先、`block` はタグを含むブロック、`container` は種類と属性の条件に一致する最も近いコンテナを収集し、ブロック ID で重複を除きます。文書には明示的な `d` の選択が必要です。AND のタグは同じ元ブロックに必要で、タグ条件がなければこの設定は影響しません。プレビューと実際の収集対象は一致し、切り替えても既存項目とフィールドは維持されます。 形式 5 では省略可能な `blockSource.documentDepth` を追加しています。省略または `null` は無制限、`0` は選択した各文書自体のみ、`1` は直接の子文書も含み、他の非負整数は相対的な最大階層数を指定します。文書の範囲すべてに共通し、ノートブックの範囲は制限せず、範囲は和集合のままです。深さを変更しても既存の項目とフィールドを保持し、既存の内容を自動で追加収集しません。
+ * `data.av.automations` は省略可能で、データベース全体のルール(`spec: 1`~`6`)を保持します。`block` トリガーの `blockSource` はノートブック/文書の範囲、ブロックの種類、タグ、カスタム属性を指定し、`collect` アクションは一致する元のブロックを現在のデータベースにバインドします。主種類はすべてのサブタイプを含みます。形式 3 は `h:h1`~`h:h6`、`l:u/o/t`、`i:u/o/t`、`callout:TYPE`(大文字小文字を区別し、独自種類も指定可能)をサポートします。種類の未選択は制限なし、複数選択は OR です。自動作成された主キー値には、カーネルが管理する `block.collectionRuleID` が含まれる場合があります。自動収集は追加だけを行います。原文やルールの条件・範囲・対象・有効状態が変わっても既存の項目とフィールドを保持し、再び一致しても同じ項目を使います。明示的な整理ではすべての有効な収集ルールを使い、手動・自動でバインドした項目を同じ基準で確認します。一致する項目や判定できない項目は保持し、実行前の再確認で不一致が確定した項目だけを除去します。元に戻す操作で元の項目と全フィールドを復元します。 `blockSource.tagMatch` と `attributeMatch` は既定で `and`、形式 3 では各組を個別に `or` にできます。組の間は AND のままで、空の組は制限しません。 各ルールの省略可能な `notifyOnSuccess` は既定(`null` を含む)で `true` です。実際の変更をトランザクション確定後に一つの通知にまとめます。無効にしてもエラーは通知します。変更なし・明示的な収集・元に戻す・やり直し・ロールバックでは成功通知を送信しません。 形式 4 では省略可能な `blockSource.tagTarget` を追加しています。省略・空文字列は既定の選択で、最初の内容ブロックより条件に合うリスト項目を優先、`block` はタグを含むブロック、`container` は種類と属性の条件に一致する最も近いコンテナを収集し、ブロック ID で重複を除きます。文書には明示的な `d` の選択が必要です。AND のタグは同じ元ブロックに必要で、タグ条件がなければこの設定は影響しません。プレビューと実際の収集対象は一致し、切り替えても既存項目とフィールドは維持されます。 形式 5 では省略可能な `blockSource.documentDepth` を追加しています。省略または `null` は無制限、`0` は選択した各文書自体のみ、`1` は直接の子文書も含み、他の非負整数は相対的な最大階層数を指定します。文書の範囲すべてに共通し、ノートブックの範囲は制限せず、範囲は和集合のままです。深さを変更しても既存の項目とフィールドを保持し、既存の内容を自動で追加収集しません。 形式 6 は各属性条件に省略可能な `nameOperator` を追加します。省略・空文字列・`equals` は完全な名前との一致を維持し、`contains` は `custom-` 接頭辞の入力を必要としない文字列の部分一致、`regex` は接頭辞を含む完全な名前に対する Go の正規表現です。カスタム属性だけを照合し、名前と値は大文字小文字を区別して同じ属性で満たす必要があります。`exists` は名前の一致が一つ以上、`notExists` は一致がないことを要求し、値は無視します。名前パターンは最大 256 バイトで、不正な式は保存を拒否します。既存の形式 1–5 の動作は維持し、古いリーダーはデータベースを書き換えずに形式 6 を拒否します。
### 主キー値を取得
diff --git a/docs/API.md b/docs/API.md
index d4f8ccebea..2d19281fd2 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -2223,7 +2223,7 @@ The field types (`keyType`) are:
* `data.av`: The full `AttributeView` definition — fields (`keyValues`), field ordering (`keyIDs`, may be `null`), and all views with their raw layout config (`table`/`list`/`gallery`/`kanban`) and item ordering (`itemIds`). The compatibility `viewID` is computed as the first available view and is not persisted. Returns no rendered rows or pagination; therefore, use [Render](#Render) for computed rows
- * `data.av.automations` optionally contains database-wide rules (`spec: 1` through `5`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Automatic collection only adds entries. Source changes and changes to rule conditions, scope, target, or activation preserve existing rows and fields; matching again keeps the same row. Explicit cleanup checks all enabled collection rules for manual and automatic bound entries alike, preserves matches and indeterminate entries, and rechecks before removing unmatched entries; undo restores the original row and all fields. `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages. Format 4 adds optional `blockSource.tagTarget`: omitted/empty uses default selection, preferring an eligible list item over its first content block, `block` collects the tagged block itself, and `container` collects the nearest container meeting type and attribute conditions, deduplicated by block ID. Documents require an explicit `d` type. AND tags must occur in one source block; without tag conditions this option has no effect. Preview and actual collection share the same targets; changing this option preserves existing rows and fields. Format 5 adds optional `blockSource.documentDepth`: omitted or `null` means unlimited, `0` includes only each selected document itself, and `1` also includes its direct children. Other nonnegative integers set the maximum relative descendant depth. It applies uniformly to document scopes, not notebook scopes; scopes remain combined by union. Changing depth preserves existing rows and fields and does not backfill existing content.
+ * `data.av.automations` optionally contains database-wide rules (`spec: 1` through `6`). A `block` trigger uses `blockSource` to select notebooks/documents, block types, tags, and custom attributes; its `collect` action binds matching source blocks to this database. Main types include every subtype; format 3 supports `h:h1` through `h:h6`, `l:u/o/t`, `i:u/o/t`, and `callout:TYPE` (case-sensitive, including custom types). Empty types impose no restriction, and multiple types use OR. Automatically created primary values may include `block.collectionRuleID`, which is maintained by the kernel. Automatic collection only adds entries. Source changes and changes to rule conditions, scope, target, or activation preserve existing rows and fields; matching again keeps the same row. Explicit cleanup checks all enabled collection rules for manual and automatic bound entries alike, preserves matches and indeterminate entries, and rechecks before removing unmatched entries; undo restores the original row and all fields. `blockSource.tagMatch` and `attributeMatch` default to `and`; format 3 also supports `or` independently within each group. Groups remain ANDed, and empty groups add no restriction. Each rule's optional `notifyOnSuccess` defaults to `true` (including `null`); successful changes are summarized once after the transaction commits. Disabled notifications do not suppress errors. No-op actions, explicit collection, undo, redo, and rolled-back transactions do not generate success messages. Format 4 adds optional `blockSource.tagTarget`: omitted/empty uses default selection, preferring an eligible list item over its first content block, `block` collects the tagged block itself, and `container` collects the nearest container meeting type and attribute conditions, deduplicated by block ID. Documents require an explicit `d` type. AND tags must occur in one source block; without tag conditions this option has no effect. Preview and actual collection share the same targets; changing this option preserves existing rows and fields. Format 5 adds optional `blockSource.documentDepth`: omitted or `null` means unlimited, `0` includes only each selected document itself, and `1` also includes its direct children. Other nonnegative integers set the maximum relative descendant depth. It applies uniformly to document scopes, not notebook scopes; scopes remain combined by union. Changing depth preserves existing rows and fields and does not backfill existing content. Format 6 adds each attribute condition's optional `nameOperator`: omitted/empty or `equals` retains exact full-name matching, `contains` matches a literal substring without requiring the `custom-` prefix, and `regex` uses Go regular expressions against the full name including that prefix. Only custom attributes are considered. Names and values are case-sensitive and must match on the same attribute; `exists` requires at least one name match and `notExists` requires none, ignoring the value. Name patterns are limited to 256 bytes; invalid expressions are rejected on save. Existing formats 1–5 retain their behavior; older readers reject format 6 without rewriting the database.
### Get primary key values
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index c8ad236f27..43bb0c4101 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -2219,7 +2219,7 @@ if (response.code === 0 && response.data) {
* `data.av`: 完整的 `AttributeView` 定义——字段(`keyValues`)、字段顺序(`keyIDs`,可能为 `null`),以及所有视图的原始布局配置(`table`/`list`/`gallery`/`kanban`)和条目顺序(`itemIds`)。兼容字段 `viewID` 动态取第一个可用视图,不会持久化。返回值不含渲染后的行或分页;需要计算后的行数据请使用 [渲染](#渲染)
- * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1` 至 `5`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。自动收集只添加条目,原文变化及规则条件、范围、对象或启用状态变化均保留已有条目和字段,再次匹配仍使用原条目。主动清理按全部启用的收集规则统一检查手动和自动绑定条目,保留匹配或无法判断的条目,执行前复查后仅移出确认不匹配的条目;撤销恢复原条目及全部字段。 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。 格式 4 增加可选的 `blockSource.tagTarget`:缺省或空字符串使用默认选择,优先收集合格列表项而非其首个内容块,`block` 收集标签所在块,`container` 选择最近的符合类型和属性条件的容器并按块 ID 去重;文档需显式选择 `d`。全部标签须在同一个来源块中,无标签条件时此选项不影响筛选。预览与实际收集对象一致,切换保留已有条目及字段。 格式 5 增加可选的 `blockSource.documentDepth`:缺省或 `null` 表示不限,`0` 仅包含每个选中文档本身,`1` 还包含一级子文档,其他非负整数指定最大相对后代深度。该设置统一限制文档范围,不影响笔记本范围,各范围仍取并集。修改深度保留已有条目和字段,不自动补收存量内容。
+ * `data.av.automations` 可选,保存数据库共享的规则(`spec: 1` 至 `6`)。`block` 触发器通过 `blockSource` 指定笔记本/文档范围、块类型、标签和自定义属性,`collect` 动作将符合条件的原块绑定到当前数据库。主类型包含全部子类型;格式 3 支持 `h:h1` 至 `h:h6`、`l:u/o/t`、`i:u/o/t` 和 `callout:TYPE`(区分大小写,允许自定义提示类型)。类型为空不限制,多个类型取任一匹配。自动创建的主键值可能包含由内核维护的 `block.collectionRuleID`。自动收集只添加条目,原文变化及规则条件、范围、对象或启用状态变化均保留已有条目和字段,再次匹配仍使用原条目。主动清理按全部启用的收集规则统一检查手动和自动绑定条目,保留匹配或无法判断的条目,执行前复查后仅移出确认不匹配的条目;撤销恢复原条目及全部字段。 `blockSource.tagMatch` 和 `attributeMatch` 缺省为 `and`,格式 3 支持各组独立设置 `or`;组间仍取与关系,空组不限制。 每条规则的可选 `notifyOnSuccess` 缺省或 `null` 为 `true`,实际变更在事务提交成功后合并通知;关闭不影响错误提示。无变化、手动收集、撤销重做及回滚事务不发送成功通知。 格式 4 增加可选的 `blockSource.tagTarget`:缺省或空字符串使用默认选择,优先收集合格列表项而非其首个内容块,`block` 收集标签所在块,`container` 选择最近的符合类型和属性条件的容器并按块 ID 去重;文档需显式选择 `d`。全部标签须在同一个来源块中,无标签条件时此选项不影响筛选。预览与实际收集对象一致,切换保留已有条目及字段。 格式 5 增加可选的 `blockSource.documentDepth`:缺省或 `null` 表示不限,`0` 仅包含每个选中文档本身,`1` 还包含一级子文档,其他非负整数指定最大相对后代深度。该设置统一限制文档范围,不影响笔记本范围,各范围仍取并集。修改深度保留已有条目和字段,不自动补收存量内容。 格式 6 为每条属性条件增加可选的 `nameOperator`:缺省、空字符串或 `equals` 保持完整名称精确匹配,`contains` 按字面子串匹配且无需输入 `custom-` 前缀,`regex` 使用 Go 正则语法匹配包含该前缀的完整名称。仅匹配自定义属性,名称和值区分大小写,且必须由同一条属性同时满足;`exists` 要求至少一个名称匹配,`notExists` 要求没有名称匹配,两者忽略属性值。名称模式最多 256 字节,非法正则拒绝保存。既有格式 1–5 的行为保持不变,旧读取器拒绝格式 6 且不改写数据库。
### 获取主键值
diff --git a/kernel/api/av_contract_automation.go b/kernel/api/av_contract_automation.go
index 282359496a..a2ca20af38 100644
--- a/kernel/api/av_contract_automation.go
+++ b/kernel/api/av_contract_automation.go
@@ -82,6 +82,7 @@ func toContractAVAutomationBlockSource(source *av.AutomationBlockSource) *apicon
if attr == nil {
return nil
}
- return &apicontract.AVAutomationBlockAttribute{Name: attr.Name, Operator: attr.Operator, Value: attr.Value}
+ return &apicontract.AVAutomationBlockAttribute{Name: attr.Name, NameOperator: attr.NameOperator,
+ Operator: attr.Operator, Value: attr.Value}
})}
}
diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.go
index 61a5ed0303..a3c344de6a 100644
--- a/kernel/api/contract_av_automation_test.go
+++ b/kernel/api/contract_av_automation_test.go
@@ -289,6 +289,45 @@ func TestAVContractAutomationWrites(t *testing.T) {
t.Fatalf("document depth contract round trip: %s", response.Body.String())
}
}
+ previousAttributes := collection.BlockSource.Attributes
+ for _, mode := range []string{"equals", "contains", "regex"} {
+ attr := &av.AutomationBlockAttribute{Name: "custom-state", NameOperator: mode, Operator: "exists"}
+ if mode == "contains" {
+ attr.Name = "state"
+ }
+ if mode == "regex" {
+ attr.Name = "^custom-state$"
+ }
+ collection.BlockSource.Attributes = []*av.AutomationBlockAttribute{attr}
+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,
+ Data: &av.AutomationConfig{Spec: 6, 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)
+ readBack.Data.AV.Automations = av.AutomationConfig{}
+ if err = json.Unmarshal(response.Body.Bytes(), &readBack); err != nil {
+ t.Fatal(err)
+ }
+ got := readBack.Data.AV.Automations.Rules[0].BlockSource.Attributes[0]
+ if got.NameOperator != mode || got.Name != attr.Name || got.Operator != "exists" {
+ t.Fatalf("attribute name contract round trip: %s", response.Body.String())
+ }
+ }
+ collection.BlockSource.Attributes[0].Name = "["
+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,
+ Data: &av.AutomationConfig{Spec: 6, Rules: []*av.AutomationRule{collection}}}}); err == nil {
+ t.Fatal("invalid attribute name expression was saved")
+ }
+ persisted, err := av.ParseAttributeView(database.ID)
+ if err != nil || persisted.Automations.Rules[0].BlockSource.Attributes[0].Name != "^custom-state$" {
+ t.Fatal("invalid expression changed the previous saved rule", err)
+ }
+ collection.BlockSource.Attributes = previousAttributes
+ if err = model.PerformAttributeViewOperations([]*model.Operation{{Action: "setAttrViewAutomations", AvID: database.ID,
+ Data: &av.AutomationConfig{Spec: 5, Rules: []*av.AutomationRule{collection}}}}); err != nil {
+ t.Fatal(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)
diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.go
index c26681eec7..423fa6b9f1 100644
--- a/kernel/apicontract/av_automation.go
+++ b/kernel/apicontract/av_automation.go
@@ -1,7 +1,8 @@
package apicontract
// AVAutomationConfig 通过 setAttrViewAutomations 事务操作整体保存,所有镜像和视图共享。
-// spec 为 1 至 5;模板赋值至少使用 2,块子类型至少使用 3,标签收集对象至少使用 4,有限文档深度至少使用 5。
+// spec 为 1 至 6;模板赋值至少使用 2,块子类型至少使用 3,标签收集对象至少使用 4,有限文档深度至少使用 5。
+// 属性名包含或正则匹配至少使用 6;缺省或 equals 保持既有的精确匹配。
// 旧读取器拒绝新版本,防止配置静默丢失。
// 缺省配置不会触发自动化,既有版本的主类型匹配含义不变。
// 普通条目新增、字段编辑及对应 API 会触发启用的规则,
@@ -59,10 +60,16 @@ type AVAutomationBlockSource struct {
AttributeMatch string `json:"attributeMatch,omitempty" api:"optional,enum=|and|or"`
}
+// AVAutomationBlockAttribute 仅匹配 custom- 前缀的自定义属性,名称与值必须在同一条属性上满足条件。
+// nameOperator 缺省、空值或 equals 精确匹配完整名称;contains 匹配名称中的字面子串,无需输入 custom- 前缀。
+// regex 使用 Go 正则语法匹配含 custom- 前缀的完整名称,可用 ^、$ 限定边界;表达式最长 256 字节,非法表达式拒绝保存。
+// exists 要求至少一个名称匹配,notExists 要求没有名称匹配;两者忽略 value。
+// 名称与值均区分大小写;包含和正则名称匹配要求自动化 spec 6,等于匹配兼容 spec 1 至 5。
type AVAutomationBlockAttribute struct {
- Name string `json:"name"`
- Operator string `json:"operator" api:"enum=equals|contains|exists|notExists"`
- Value string `json:"value,omitempty" api:"optional"`
+ Name string `json:"name"`
+ NameOperator string `json:"nameOperator,omitempty" api:"optional,enum=|equals|contains|regex"`
+ Operator string `json:"operator" api:"enum=equals|contains|exists|notExists"`
+ Value string `json:"value,omitempty" api:"optional"`
}
// AVAutomationAction 的 current 指触发条目所在数据库,related 通过源关联字段选择条目,
diff --git a/kernel/apicontract/av_test.go b/kernel/apicontract/av_test.go
index 9b98b725fd..afbae55fa2 100644
--- a/kernel/apicontract/av_test.go
+++ b/kernel/apicontract/av_test.go
@@ -40,6 +40,27 @@ func TestAVAutomationDocumentDepthContract(t *testing.T) {
}
}
+func TestAVAutomationAttributeNameContract(t *testing.T) {
+ endpoint := Endpoint[AVAutomationBlockAttribute, Null]{definition: Definition{Path: "/test", Body: JSONBody}}
+ for _, mode := range []string{"", "equals", "contains", "regex"} {
+ raw, _ := json.Marshal(map[string]string{"name": "custom-state", "nameOperator": mode, "operator": "exists"})
+ value, err := endpoint.Decode(strings.NewReader(string(raw)))
+ if err != nil || value.NameOperator != mode {
+ t.Fatalf("name operator %q: %+v %v", mode, value, err)
+ }
+ }
+ value, err := endpoint.Decode(strings.NewReader(`{"name":"custom-state","operator":"exists"}`))
+ if err != nil || value.NameOperator != "" {
+ t.Fatalf("legacy exact default: %+v %v", value, err)
+ }
+ for _, raw := range []string{`{"name":"state","nameOperator":"glob","operator":"exists"}`,
+ `{"name":"state","nameOperator":1,"operator":"exists"}`} {
+ if _, err := endpoint.Decode(strings.NewReader(raw)); err == nil {
+ t.Fatalf("invalid name operator accepted: %s", raw)
+ }
+ }
+}
+
func TestAVRequestCompatibility(t *testing.T) {
group, err := SetAttrViewGroup.Decode(strings.NewReader(`{"avID":" av ","blockID":" block ","group":{"FIELD":"key","method":2,"unknown":true},"ignoreRows":"ignored"}`))
if err != nil || group.AvID != " av " || group.BlockID != " block " || group.Group.Field != "key" || group.Group.Method != 2 || group.IgnoreRows {
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 64e4e64c97..8cc631d84a 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1580,11 +1580,12 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system
// move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
-// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 5,所有视图共享数据库级规则。
+// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 至 6,所有视图共享数据库级规则。
// blockSource.types 主类型包含全部子类型;spec 3 可指定 h:h1 至 h:h6、l:u/o/t、i:u/o/t、callout:类型名。
// blockSource 的 tagMatch、attributeMatch 缺省为 and;spec 3 支持各组独立设置 or,空组不限制,组间仍为 and。
// spec 4 的 blockSource.tagTarget 支持 block(标签所在块)和 container(最近合格容器),缺省保持原行为。
// spec 5 的 blockSource.documentDepth 限制各文档范围的子文档深度,0 仅自身,1 包含自身及一级子文档。
+// spec 6 的属性 nameOperator 支持 contains 和 Go regex;缺省或 equals 保持精确名称匹配,值条件独立。
// 深度缺省或 null 不限,不影响笔记本范围,各范围仍取并集;修改不自动清理或补收已有内容。
// 容器按类型及属性条件选择并去重;全部标签须在同一个来源块中,文档容器须显式选择 d。
// 类型和属性始终筛选最终对象;默认首个内容块优先归属合格列表项,每次标签命中只选择一个对象。
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 74fd84dba4..8db72a3eb5 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -6672,6 +6672,15 @@
"name": {
"type": "string"
},
+ "nameOperator": {
+ "type": "string",
+ "enum": [
+ "",
+ "equals",
+ "contains",
+ "regex"
+ ]
+ },
"operator": {
"type": "string",
"enum": [
@@ -6697,6 +6706,15 @@
"name": {
"type": "string"
},
+ "nameOperator": {
+ "type": "string",
+ "enum": [
+ "",
+ "equals",
+ "contains",
+ "regex"
+ ]
+ },
"operator": {
"type": "string",
"enum": [
diff --git a/kernel/av/automation.go b/kernel/av/automation.go
index 91a44e7e7e..06c097dfb1 100644
--- a/kernel/av/automation.go
+++ b/kernel/av/automation.go
@@ -41,9 +41,10 @@ type AutomationBlockSource struct {
}
type AutomationBlockAttribute struct {
- Name string `json:"name"`
- Operator string `json:"operator"`
- Value string `json:"value,omitempty"`
+ Name string `json:"name"`
+ NameOperator string `json:"nameOperator,omitempty"`
+ Operator string `json:"operator"`
+ Value string `json:"value,omitempty"`
}
// IsAutomationBlockType 校验主类型或主类型与子类型的组合,提示块允许自定义类型名称。
@@ -69,6 +70,11 @@ func IsAutomationBlockType(value string) bool {
func (rule *AutomationRule) RequiredSpec() int {
ret := 1
if rule.BlockSource != nil {
+ for _, attr := range rule.BlockSource.Attributes {
+ if attr != nil && attr.NameOperator != "" && attr.NameOperator != "equals" {
+ return 6
+ }
+ }
if rule.BlockSource.DocumentDepth != nil {
return 5
}
@@ -101,7 +107,7 @@ func (config *AutomationConfig) ValidateSpec() error {
if config == nil {
return nil
}
- if config.Spec < 1 || config.Spec > 5 {
+ if config.Spec < 1 || config.Spec > 6 {
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.go
index 4acbf1336f..f570fcc75f 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 = 6
+ source.Automations.Spec = 7
future, _ := 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, 4, 5} {
+ for _, spec := range []int{1, 2, 3, 4, 5, 6} {
view, err := ParseAttributeViewData("20260921000000-layouts", data)
if err != nil {
t.Fatal(err)
@@ -180,6 +180,42 @@ func TestAutomationBlockTypeAndSpecCompatibility(t *testing.T) {
}
}
+func TestAutomationAttributeNameSpecCompatibility(t *testing.T) {
+ data, err := os.ReadFile("testdata/spec9-layouts.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for spec := 1; spec <= 6; spec++ {
+ for _, mode := range []string{"", "equals", "contains", "regex"} {
+ view, err := ParseAttributeViewData("20260921000000-layouts", data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ attr := &AutomationBlockAttribute{Name: "custom-state", NameOperator: mode, Operator: "exists"}
+ view.Automations = &AutomationConfig{Spec: spec, Rules: []*AutomationRule{{BlockSource: &AutomationBlockSource{
+ Attributes: []*AutomationBlockAttribute{attr}, DocumentDepth: new(0),
+ }}}}
+ // 先检查独立的名称语义,再叠加文档深度,避免较低优先级覆盖新格式要求。
+ view.Automations.Rules[0].BlockSource.DocumentDepth = nil
+ raw, _ := json.Marshal(view)
+ read, err := ParseAttributeViewData(view.ID, raw)
+ want := spec >= 6 || mode == "" || mode == "equals"
+ if (err == nil) != want {
+ t.Fatalf("name mode %q spec %d: %v", mode, spec, err)
+ }
+ if want && read.Automations.Rules[0].BlockSource.Attributes[0].NameOperator != mode {
+ t.Fatal("name operator lost during storage round trip")
+ }
+ if mode == "contains" || mode == "regex" {
+ view.Automations.Rules[0].BlockSource.DocumentDepth = new(0)
+ if got := view.Automations.Rules[0].RequiredSpec(); got != 6 {
+ t.Fatalf("combined spec = %d", got)
+ }
+ }
+ }
+ }
+}
+
func TestAutomationPreservesPersistedColors(t *testing.T) {
view := &AttributeView{Automations: &AutomationConfig{Spec: 1, Rules: []*AutomationRule{{
Actions: []*AutomationAction{{Fields: map[string]*AutomationValue{"select": {
diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.go
index ec20664af7..86306e07a8 100644
--- a/kernel/model/attribute_view_collection.go
+++ b/kernel/model/attribute_view_collection.go
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "regexp"
"slices"
"sort"
"strings"
@@ -51,7 +52,7 @@ func collectionScopeMatches(source *av.AutomationBlockSource, tree *parse.Tree)
return false
}
-func collectionBlockConditionsMatch(source *av.AutomationBlockSource, node *ast.Node) bool {
+func collectionBlockConditionsMatch(source *av.AutomationBlockSource, node *ast.Node, attributes []func(*ast.Node) bool) bool {
if len(source.Types) > 0 {
typ := treenode.TypeAbbr(node.Type.String())
matched := slices.Contains(source.Types, typ)
@@ -62,8 +63,8 @@ func collectionBlockConditionsMatch(source *av.AutomationBlockSource, node *ast.
return false
}
}
- return collectionConditionsMatch(source.Attributes, source.AttributeMatch, func(attr *av.AutomationBlockAttribute) bool {
- return collectionAttributeMatches(attr, node)
+ return collectionConditionsMatch(attributes, source.AttributeMatch, func(matches func(*ast.Node) bool) bool {
+ return matches(node)
})
}
@@ -100,6 +101,10 @@ func collectionMatches(source *av.AutomationBlockSource, tree *parse.Tree) map[s
if !collectionScopeMatches(source, tree) {
return ret
}
+ attributes := make([]func(*ast.Node) bool, 0, len(source.Attributes))
+ for _, attr := range source.Attributes {
+ attributes = append(attributes, collectionAttributeMatcher(attr))
+ }
var containers []*ast.Node
ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
if !entering {
@@ -112,14 +117,14 @@ func collectionMatches(source *av.AutomationBlockSource, tree *parse.Tree) map[s
return ast.WalkContinue
}
if len(source.Tags) == 0 {
- if collectionBlockConditionsMatch(source, node) {
+ if collectionBlockConditionsMatch(source, node, attributes) {
ret[node.ID] = true
}
return ast.WalkContinue
}
if source.TagTarget == "container" && node.IsContainerBlock() &&
(node.Type != ast.NodeDocument || slices.Contains(source.Types, "d")) &&
- collectionBlockConditionsMatch(source, node) {
+ collectionBlockConditionsMatch(source, node, attributes) {
containers = append(containers, node)
}
if !collectionTagsMatch(source, node) {
@@ -132,15 +137,15 @@ func collectionMatches(source *av.AutomationBlockSource, tree *parse.Tree) map[s
target = containers[len(containers)-1]
}
case "block":
- if collectionBlockConditionsMatch(source, node) {
+ if collectionBlockConditionsMatch(source, node, attributes) {
target = node
}
default:
parent := node.Parent
if parent != nil && parent.Type == ast.NodeListItem && treenode.FirstLeafBlock(parent) == node &&
- collectionBlockConditionsMatch(source, parent) {
+ collectionBlockConditionsMatch(source, parent, attributes) {
target = parent
- } else if collectionBlockConditionsMatch(source, node) {
+ } else if collectionBlockConditionsMatch(source, node, attributes) {
target = node
}
}
@@ -163,28 +168,69 @@ func collectionConditionsMatch[T any](values []T, mode string, matches func(T) b
return !slices.ContainsFunc(values, func(value T) bool { return !matches(value) })
}
-func collectionAttributeMatches(attr *av.AutomationBlockAttribute, node *ast.Node) bool {
- if attr == nil {
- return false
+// 每次扫描文档前编译名称条件,避免按块重复编译正则;非法条件始终不匹配。
+func collectionAttributeMatcher(attr *av.AutomationBlockAttribute) func(*ast.Node) bool {
+ invalid := func(*ast.Node) bool { return false }
+ pattern, err := validateCollectionAttribute(attr)
+ if err != nil {
+ return invalid
+ }
+ matchesName := func(name string) bool { return name == attr.Name }
+ switch attr.NameOperator {
+ case "contains":
+ matchesName = func(name string) bool { return strings.Contains(name, attr.Name) }
+ case "regex":
+ matchesName = pattern.MatchString
}
- value, present := "", false
- for _, pair := range node.KramdownIAL {
- if len(pair) == 2 && pair[0] == attr.Name {
- value, present = util.UnescapeHTML(pair[1]), true
- break
+ return func(node *ast.Node) bool {
+ for _, pair := range node.KramdownIAL {
+ if len(pair) != 2 || !strings.HasPrefix(pair[0], "custom-") || !matchesName(pair[0]) {
+ continue
+ }
+ value := util.UnescapeHTML(pair[1])
+ switch attr.Operator {
+ case "equals":
+ if value == attr.Value {
+ return true
+ }
+ case "contains":
+ if strings.Contains(value, attr.Value) {
+ return true
+ }
+ case "exists":
+ return true
+ case "notExists":
+ return false
+ }
}
+ return attr.Operator == "notExists"
}
- switch attr.Operator {
- case "equals":
- return present && value == attr.Value
+}
+
+func validateCollectionAttribute(attr *av.AutomationBlockAttribute) (*regexp.Regexp, error) {
+ if attr == nil || attr.Name == "" || len(attr.Name) > 256 ||
+ !slices.Contains([]string{"equals", "contains", "exists", "notExists"}, attr.Operator) {
+ return nil, fmt.Errorf("invalid collection attribute")
+ }
+ switch attr.NameOperator {
+ case "", "equals":
+ if !strings.HasPrefix(attr.Name, "custom-") || len(attr.Name) <= len("custom-") || !isValidAttrName(attr.Name) {
+ return nil, fmt.Errorf("invalid collection attribute name")
+ }
case "contains":
- return present && strings.Contains(value, attr.Value)
- case "exists":
- return present
- case "notExists":
- return !present
+ if !validateChars(attr.Name, 0, len(attr.Name)) {
+ return nil, fmt.Errorf("invalid collection attribute name")
+ }
+ case "regex":
+ pattern, err := regexp.Compile(attr.Name)
+ if err != nil {
+ return nil, fmt.Errorf("invalid collection attribute name expression: %w", err)
+ }
+ return pattern, nil
+ default:
+ return nil, fmt.Errorf("invalid collection attribute name operator")
}
- return false
+ return nil, nil
}
func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rule *av.AutomationRule, boxID string) error {
@@ -224,10 +270,8 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rule
}
}
for _, attr := range source.Attributes {
- if attr == nil || !strings.HasPrefix(attr.Name, "custom-") || len(attr.Name) <= len("custom-") ||
- len(attr.Name) > 256 || !isValidAttrName(attr.Name) ||
- !slices.Contains([]string{"equals", "contains", "exists", "notExists"}, attr.Operator) {
- return fmt.Errorf("invalid collection attribute")
+ if _, err := validateCollectionAttribute(attr); err != nil {
+ return err
}
}
action := rule.Actions[0]
diff --git a/kernel/model/attribute_view_collection_attribute_fts5_test.go b/kernel/model/attribute_view_collection_attribute_fts5_test.go
new file mode 100644
index 0000000000..a8c81dd643
--- /dev/null
+++ b/kernel/model/attribute_view_collection_attribute_fts5_test.go
@@ -0,0 +1,63 @@
+//go:build fts5
+
+package model
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func TestBlockCollectionAttributeNames(t *testing.T) {
+ node := &ast.Node{Type: ast.NodeDocument, KramdownIAL: [][]string{
+ {"id", "document"}, {"custom-dailynote-20261020", "old"}, {"custom-dailynote-20261021", "A&amp;B"},
+ {"custom-abc-example-def", "other"}, {"custom-empty", ""},
+ }}
+ for _, test := range []struct {
+ name, mode, operator, value string
+ want bool
+ }{
+ {"custom-dailynote-20261021", "", "equals", "A&B", true},
+ {"custom-dailynote-20261021", "equals", "equals", "A&B", true},
+ {"dailynote", "contains", "exists", "", true},
+ {"example", "contains", "exists", "", true},
+ {"-example", "contains", "exists", "", true},
+ {"dailynote", "contains", "equals", "A&B", true},
+ {"dailynote", "contains", "contains", "&", true},
+ {"dailynote", "contains", "equals", "other", false},
+ {"dailynote", "contains", "notExists", "", false},
+ {"missing", "contains", "notExists", "", true},
+ {"^custom-dailynote-[0-9]{8}$", "regex", "equals", "A&B", true},
+ {`^custom-\D+-20261021$`, "regex", "exists", "", true},
+ {"^dailynote", "regex", "exists", "", false},
+ {"^id$", "regex", "exists", "", false},
+ {"^id$", "regex", "notExists", "", true},
+ {"custom-empty", "", "equals", "", true},
+ {"custom-missing", "", "equals", "", false},
+ {"[", "regex", "notExists", "", false},
+ {"(?=custom)", "regex", "notExists", "", false},
+ {"custom-state", "unknown", "notExists", "", false},
+ {"", "contains", "notExists", "", false},
+ } {
+ t.Run(test.mode+"/"+test.name+"/"+test.operator+"/"+test.value, func(t *testing.T) {
+ attr := &av.AutomationBlockAttribute{Name: test.name, NameOperator: test.mode, Operator: test.operator, Value: test.value}
+ if got := collectionAttributeMatcher(attr)(node); got != test.want {
+ t.Fatalf("matched %v, want %v", got, test.want)
+ }
+ })
+ }
+ if collectionAttributeMatcher(nil)(node) {
+ t.Fatal("nil condition matched")
+ }
+ for _, attr := range []*av.AutomationBlockAttribute{
+ {Name: strings.Repeat("a", 257), NameOperator: "regex", Operator: "exists"},
+ {Name: "custom-", Operator: "exists"}, {Name: "state", Operator: "exists"},
+ {Name: "state space", NameOperator: "contains", Operator: "exists"},
+ } {
+ if _, err := validateCollectionAttribute(attr); err == nil {
+ t.Fatalf("invalid condition accepted: %+v", attr)
+ }
+ }
+}
diff --git a/kernel/model/attribute_view_collection_sqlcipher_test.go b/kernel/model/attribute_view_collection_sqlcipher_test.go
index c257c8db6c..bf4ee798c1 100644
--- a/kernel/model/attribute_view_collection_sqlcipher_test.go
+++ b/kernel/model/attribute_view_collection_sqlcipher_test.go
@@ -25,13 +25,16 @@ func TestBlockCollectionEncryptedSourceAndRecovery(t *testing.T) {
name = "default"
}
t.Run(name, func(t *testing.T) {
- t.Run("unlimited", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, target, nil) })
- t.Run("current", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, target, new(0)) })
+ t.Run("unlimited", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, target, nil, "") })
+ t.Run("current", func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, target, new(0), "") })
})
}
+ for _, mode := range []string{"contains", "regex"} {
+ t.Run(mode, func(t *testing.T) { testBlockCollectionEncryptedSourceAndRecovery(t, "", nil, mode) })
+ }
}
-func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string, depth *int) {
+func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string, depth *int, nameOperator string) {
fixture, view, keyID := setupBlockCollectionTest(t)
boxID := fixture.box.ID
tree, err := LoadTreeByBlockID(fixture.sourceID)
@@ -100,6 +103,15 @@ func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string,
view.Automations.Spec = 5
view.Automations.Rules[0].BlockSource.DocumentDepth = depth
}
+ if nameOperator != "" {
+ view.Automations.Spec = 6
+ attr := view.Automations.Rules[0].BlockSource.Attributes[0]
+ attr.NameOperator = nameOperator
+ attr.Name = "state"
+ if nameOperator == "regex" {
+ attr.Name = "^custom-st(?:ate|atus)$"
+ }
+ }
if err = av.SaveAttributeView(view); err != nil {
t.Fatal(err)
}