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: Improve automation collection condition editing and matching https://github.com/siyuan-note/siyuan/issues/20641
Danielbddca1c86031
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 e53981d414..c05c6bf2bf 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@@ -4526,12 +4526,12 @@"Type": "NodeParagraph","Properties": {"id": "20261015141042-nrq3k5z",- "updated": "20261016202856"+ "updated": "20261017200709"},"Children": [{"Type": "NodeText",- "Data": "Choose the “Block matches conditions” trigger, select notebooks or documents under “Watch scope (includes subdocuments)”, and optionally filter by block types, tags, and custom attributes. Notebook and document scopes are combined; document scopes include subdocuments. A block may have any selected type, but must match every tag and attribute condition. Custom attributes support exact equality, contains, exists, and does not exist."+ "Data": "Choose the Block matches conditions trigger and select notebooks or documents in Watch scope (includes subdocuments). Notebook and document scopes are combined. Block types, tags, and custom attributes use separate Chip groups; add conditions with each group's add button, and remove them with the Chip's close button. The block type picker supports search and repeated selections. Click a tag or attribute Chip to edit it; Enter confirms tags, while attribute changes remain drafts until confirmed, and Escape or Cancel discards them. Tags are trimmed and deduplicated. Block types use OR. Tags and custom attributes each default to Match all; choose Match any separately when needed. The three groups still use AND, and an empty group adds no restriction. Custom attributes support equality, contains, exists, and does not exist; the last two do not need a value. Match any requires automation format 3, while existing rules keep their Match all behavior."}]},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 f44d5526e8..353e9ae962 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@@ -4526,12 +4526,12 @@"Type": "NodeParagraph","Properties": {"id": "20261015141042-ux38r6d",- "updated": "20261016202635"+ "updated": "20261017200709"},"Children": [{"Type": "NodeText",- "Data": "选择“普通块符合条件”触发器,在“监听范围(包含子文档)”中选择笔记本或文档,并按需设置块类型、标签和自定义属性。笔记本与文档范围取并集,文档包含其子文档;块类型满足任意一种即可,标签和自定义属性条件须全部符合。自定义属性支持等于、包含、存在和不存在。"+ "Data": "选择「普通块符合条件」触发器,在「监听范围(包含子文档)」中选择笔记本或文档,范围取并集。块类型、标签和自定义属性分别使用 Chip 分组,通过各组的添加按钮配置,点击 Chip 的关闭图标移除。块类型列表支持搜索和连续多选;点击标签或属性 Chip 可编辑,标签按回车确认,属性先作为草稿编辑,确认后才保存,按 Esc 或取消不影响现有条件。标签会去除首尾空格并自动去重。块类型取任一匹配;标签和属性分别默认为「全部满足」,可独立改为「任一满足」。三个分组之间仍须全部满足,空分组不限制。属性支持等于、包含、存在和不存在,后两者不需要属性值。「任一满足」需要自动化格式 3,已有规则保留全部满足的行为。"}]},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 02ad36d9bb..abd405173b 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@@ -4526,12 +4526,12 @@"Type": "NodeParagraph","Properties": {"id": "20261015141042-155k3zl",- "updated": "20261016202635"+ "updated": "20261017200709"},"Children": [{"Type": "NodeText",- "Data": "選擇「一般區塊符合條件」觸發器,在「監聽範圍(包含子文件)」中選擇筆記本或文件,並依需要設定區塊類型、標籤及自訂屬性。筆記本與文件範圍取聯集,文件包含其子文件;區塊類型符合任意一種即可,標籤及自訂屬性條件須全部符合。自訂屬性支援等於、包含、存在及不存在。"+ "Data": "選擇「普通區塊符合條件」觸發器,在「監聽範圍(包含子文件)」中選擇筆記本或文件,範圍取聯集。區塊類型、標籤和自訂屬性分別使用 Chip 分組,透過各組的新增按鈕設定,點擊 Chip 的關閉圖示移除。區塊類型列表支援搜尋和連續多選;點擊標籤或屬性 Chip 可編輯,標籤按 Enter 確認,屬性先作為草稿編輯,確認後才儲存,按 Esc 或取消不影響既有條件。標籤會去除首尾空白並自動去重。區塊類型取任一匹配;標籤和屬性分別預設為「全部滿足」,可獨立改為「任一滿足」。三個分組之間仍須全部滿足,空分組不限制。屬性支援等於、包含、存在和不存在,後兩者不需要屬性值。「任一滿足」需要自動化格式 3,既有規則保留全部滿足的行為。"}]},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 c0aff48d80..eb6db07dd8 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@@ -4536,12 +4536,12 @@"Type": "NodeParagraph","Properties": {"id": "20261015141042-qt2jps9",- "updated": "20261016202856"+ "updated": "20261017200709"},"Children": [{"Type": "NodeText",- "Data": "「通常ブロックが条件に一致」トリガーを選び、「監視範囲(子文書を含む)」でノートブックまたは文書を指定して、必要に応じてブロックの種類、タグ、カスタム属性を設定します。ノートブックと文書の範囲は和集合となり、文書には子文書も含まれます。種類はいずれか一つ、タグと属性条件はすべてに一致する必要があります。カスタム属性は等しい、含む、存在する、存在しないを指定できます。"+ "Data": "「通常ブロックが条件に一致」トリガーを選び、「監視範囲(子文書を含む)」でノートブックや文書を指定します。範囲は和集合です。ブロック種類・タグ・カスタム属性はそれぞれ Chip で管理し、各組の追加ボタンで条件を加え、閉じるボタンで削除します。種類の一覧は検索と連続した複数選択に対応します。タグや属性の Chip を押すと編集でき、タグは Enter で確定します。属性は確定するまで下書きとして保持し、Esc またはキャンセルで既存条件を変えずに取り消せます。タグの前後の空白と重複は除去します。種類は OR、タグと属性はそれぞれ既定で「すべてに一致」で、「いずれかに一致」に個別に変更できます。三つの組の間は AND のままで、空の組は制限しません。属性は等しい・含む・存在する・存在しないを使え、後二者は値が不要です。「いずれかに一致」には自動化形式 3 が必要で、既存ルールの AND 動作は維持します。"}]},diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex 54b4c5d286..4967bb026e 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -3153,6 +3153,10 @@ img.av__cellassetimg {gap: 4px;}+ &-chips .b3-chip {+ max-width: 100%;+ }+&-enabled,&-tools {align-self: flex-end;diff --git a/app/src/menus/aliasInput.ts b/app/src/menus/aliasInput.tsindex d5f5ed565a..67c46bb5bf 100644--- a/app/src/menus/aliasInput.ts+++ b/app/src/menus/aliasInput.ts@@ -14,9 +14,11 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optiospellcheck: boolean,readonly?: boolean,dragThreshold?: number,+ normalize?: (value: string) => string,save: (value: string) => Promise<boolean>,}) => {- let aliases = parseAliases(initialValue);+ const normalize = (values: string[]) => Array.from(new Set(values.map(value => options.normalize ? options.normalize(value) : value).filter(Boolean)));+ let aliases = normalize(parseAliases(initialValue));let editing = -1;let pending: Promise<boolean>;let actions = Promise.resolve();@@ -238,7 +240,7 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optioif (input.classList.contains("fn__none")) {return Promise.resolve(true);}- const next = updateAliases(aliases, input.value, editing);+ const next = normalize(updateAliases(aliases, input.value, editing));if (next.join(",") === aliases.join(",")) {finish();if (restoreFocus) {diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.tsindex 0c6af68c49..4c10c3b2b3 100644--- a/app/src/protyle/render/av/automation.ts+++ b/app/src/protyle/render/av/automation.ts@@ -132,7 +132,7 @@ export const openAutomationMenu = async (options: {const filtersAvailable = (source: AVAttributeViewData, filters: IAVFilter[] = []): boolean => filters.every(filter =>filter.filters ? filtersAvailable(source, filter.filters) : fieldsOf(source).some(field => field.id === filter.column));const incomplete = (rule: AutomationRule): string => {- if (rule === rules[index] && Array.from(body.querySelectorAll<HTMLInputElement>("input")).some(input => !input.closest("[data-template-preview]") && !input.checkValidity())) {+ if (rule === rules[index] && Array.from(body.querySelectorAll<HTMLInputElement>("input")).some(input => !input.closest("[data-template-preview], [data-attribute-editor]") && !input.checkValidity())) {return lang.invalid;}if (!rule.name.trim()) {@@ -204,8 +204,9 @@ 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 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)};+ 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)};if (JSON.stringify(next) === JSON.stringify(previous)) {return;}diff --git a/app/src/protyle/render/av/blockCollection.test.ts b/app/src/protyle/render/av/blockCollection.test.tsindex 6c50b64e0a..f9df86e559 100644--- a/app/src/protyle/render/av/blockCollection.test.ts+++ b/app/src/protyle/render/av/blockCollection.test.ts@@ -18,8 +18,11 @@ test("collection scope requires a notebook or document and complete attribute na});test("collection type selection replaces overlapping parents and preserves independent types", () => {- const methods = {} as typeof import("./blockCollection");- runInNewContext(compiled, {exports: methods, require: () => ({})});+ const methods = {} as typeof import("./collectionConditions");+ const conditions = transpileModule(readFileSync("src/protyle/render/av/collectionConditions.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText;+ runInNewContext(conditions, {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"]);diff --git a/app/src/protyle/render/av/blockCollection.ts b/app/src/protyle/render/av/blockCollection.tsindex 9614527f7a..8fd09b8ff9 100644--- a/app/src/protyle/render/av/blockCollection.ts+++ b/app/src/protyle/render/av/blockCollection.ts@@ -1,7 +1,5 @@import type {AVAutomationBlockSourceInput, AVBlockCollectionMatch} from "../../../types/api";import {Dialog} from "../../../dialog";-import {Menu} from "../../../plugin/Menu";-import {toggleMenu} from "../../../menus/menuToggle";import {fetchSyncPost} from "../../../util/fetch";import {escapeAttr, escapeHtml} from "../../../util/escape";import {isMobile} from "../../../util/functions";@@ -9,13 +7,7 @@ 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];-};+import {mountCollectionConditions} from "./collectionConditions";export const collectionSourceIncomplete = (source: AVAutomationBlockSourceInput) => !source ||!(source.notebookIDs?.length || source.documentIDs?.length) ||@@ -24,17 +16,8 @@ export const collectionSourceIncomplete = (source: AVAutomationBlockSourceInput)export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomationBlockSourceInput,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.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.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 conditions = document.createElement("div");+ mountCollectionConditions(conditions, source, save, onResize);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>`;@@ -49,16 +32,12 @@ export const mountBlockCollectionSource = (host: HTMLElement, source: AVAutomatiif (!host.isConnected || revision !== version) { return; }const notebooks = source.notebookIDs || [];const documents = source.documentIDs || [];- const attributes = source.attributes || [];host.innerHTML = `<div class="av__automation-action"><div class="ft__on-surface ft__smaller av__automation-tip">${lang.automationCollectionTip}</div><button type="button" class="b3-button b3-button--outline 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>` : ""}-<label class="av__automation-control"><span class="av__automation-control-label">${lang.automationCollectionTags}</span><input class="b3-text-field av__automation-source-tags" data-tags value="${escapeAttr((source.tags || []).join(", "))}"></label>-<button type="button" class="b3-button b3-button--cancel av__automation-source-action" data-types><svg><use xlink:href="#iconDown"></use></svg><span class="av__automation-source-types">${lang.automationCollectionTypes}: ${escapeHtml((source.types || []).map(type => types[type] || type).join(", ") || lang.all)}</span></button>-${attributes.map((attr, i) => `<div class="av__automation-control" data-attribute="${i}"><div class="av__automation-row"><input class="b3-text-field fn__flex-1 av__automation-attribute-name" data-attr-name aria-label="${escapeAttr(lang.attr)}" placeholder="custom-name" value="${escapeAttr(attr.name)}">${removeButton("attribute", i)}</div><div class="av__automation-row"><select class="b3-select av__automation-attribute-operator" data-attr-operator aria-label="${escapeAttr(lang.filter)}">${Object.entries({equals: lang.filterOperatorIs, contains: lang.filterOperatorContains, exists: lang.automationAttrExists, notExists: lang.automationAttrNotExists}).map(([operator, label]) => `<option value="${operator}"${attr.operator === operator ? " selected" : ""}>${label}</option>`).join("")}</select>${["equals", "contains"].includes(attr.operator) ? `<input class="b3-text-field fn__flex-1 av__automation-attribute-value" data-attr-value aria-label="${escapeAttr(lang.text)}" value="${escapeAttr(attr.value || "")}">` : ""}</div></div>`).join("")}-<button type="button" class="b3-button b3-button--cancel av__automation-source-action" data-add-attribute><svg><use xlink:href="#iconAdd"></use></svg><span>${lang.addFilterCondition} - ${lang.attr}</span></button></div>`;+ host.firstElementChild.append(conditions);onResize();};host.addEventListener("click", event => {@@ -86,38 +65,10 @@ ${attributes.map((attr, i) => `<div class="av__automation-control" data-attribut}});return;}- if (target.hasAttribute("data-types")) {- let menu: Menu;- toggleMenu({target, build: () => {- menu = new Menu();- Object.entries(types).forEach(([type, label]) => menu.addItem({label, checked: source.types?.includes(type), click: () => {- 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});- }});- return;- }- if (target.hasAttribute("data-add-attribute")) {- source.attributes = [...(source.attributes || []), {name: "custom-", operator: "exists"}];- } else if (target.dataset.remove) {+ if (target.dataset.remove) {const i = Number(target.dataset.index);if (target.dataset.remove === "notebook") { source.notebookIDs.splice(i, 1); }if (target.dataset.remove === "document") { source.documentIDs.splice(i, 1); }- if (target.dataset.remove === "attribute") { source.attributes.splice(i, 1); }} else { return; }save();void render();@@ -130,23 +81,6 @@ ${attributes.map((attr, i) => `<div class="av__automation-control" data-attributtarget.dispatchEvent(new MouseEvent("click", {bubbles: true}));}});- host.addEventListener("change", event => {- const target = event.target as HTMLInputElement;- if (target.hasAttribute("data-tags")) {- source.tags = Array.from(new Set(target.value.split(/[,,]/).map(tag => tag.trim().replace(/^#|#$/g, "")).filter(Boolean)));- } else {- const row = target.closest<HTMLElement>("[data-attribute]");- if (!row) { return; }- const attr = source.attributes[Number(row.dataset.attribute)];- if (target.hasAttribute("data-attr-name")) { attr.name = target.value.trim().toLowerCase(); }- if (target.hasAttribute("data-attr-value")) { attr.value = target.value; }- if (target.hasAttribute("data-attr-operator")) {- attr.operator = target.value === "contains" ? "contains" : target.value === "exists" ? "exists" : target.value === "notExists" ? "notExists" : "equals";- void render();- }- }- save();- });void render();};diff --git a/app/src/protyle/render/av/collectionConditions.ts b/app/src/protyle/render/av/collectionConditions.tsnew file mode 100644index 0000000000..ea750ea08b--- /dev/null+++ b/app/src/protyle/render/av/collectionConditions.ts@@ -0,0 +1,217 @@+import type {AVAutomationBlockAttributeInput, AVAutomationBlockSourceInput} from "../../../types/api";+import {Menu} from "../../../plugin/Menu";+import {toggleMenu} from "../../../menus/menuToggle";+import {bindAliasInput} from "../../../menus/aliasInput";+import {escapeAttr, escapeHtml} from "../../../util/escape";+import {isMobile} from "../../../util/functions";+import {openInputDialog} from "../../../dialog/inputDialog";+import {upDownHint} from "../../../util/upDownHint";++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 mountCollectionConditions = (host: HTMLElement, source: AVAutomationBlockSourceInput,+ 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.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.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}`);+ (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 modeLabel = (mode: string) => mode === "or" ? lang.filterMatchAny : lang.filterMatchAll;+ 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 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.automationCollectionTags}</span>${modeButton("tagMatch", lang.automationCollectionTags)}</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>`;+ const typeChips = host.querySelector<HTMLElement>("[data-type-chips]");+ const attributes = host.querySelector<HTMLElement>("[data-attribute-chips]");+ const editor = host.querySelector<HTMLElement>("[data-attribute-editor]");+ let draft: AVAutomationBlockAttributeInput;+ let editing = -1;+ const resize = () => { if (host.isConnected) { onResize(); } };+ 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("");+ 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>` : "";+ host.querySelector<HTMLElement>("[data-add-attribute]").classList.toggle("fn__none", !!draft);+ resize();+ };+ const finishAttribute = (cancel = false) => {+ 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);+ if (!input.reportValidity()) { return; }+ const next = [...(source.attributes || [])];+ if (editing >= 0) { next[editing] = {...draft}; } else { next.push({...draft}); }+ source.attributes = next;+ save();+ }+ draft = undefined;+ editing = -1;+ renderChips();+ renderEditor();+ };+ bindAliasInput(host.querySelector("[data-tags]"), (source.tags || []).join(","), {+ addLabel: lang.addTag, removeLabel: lang.delete, placeholder: lang.automationCollectionTags, spellcheck: false,+ normalize: value => value.trim().replace(/^#+|#+$/g, ""),+ save: async value => {+ const tags = Array.from(new Set(value.split(",").map(tag => tag.trim().replace(/^#+|#+$/g, "")).filter(Boolean)));+ if (tags.length > 20) { return false; }+ source.tags = tags;+ save();+ window.setTimeout(resize, 0);+ return true;+ },+ });+ const openTypes = (target: HTMLElement) => {+ let menu: Menu;+ toggleMenu({target, build: () => {+ menu = new Menu();+ menu.addItem({type: "empty", label: `<div class="b3-menu__filter fn__flex-column"><input class="b3-text-field" data-type-search placeholder="${escapeAttr(lang.searchPlaceholder)}" aria-label="${escapeAttr(lang.search)}"><div class="fn__hr"></div><div class="b3-list b3-list--background fn__flex-1" data-type-list>${Object.entries(types).map(([type, label]) => `<button type="button" class="b3-list-item" data-collection-type="${escapeAttr(type)}"><span class="b3-list-item__text">${escapeHtml(label)}</span><svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg></button>`).join("")}</div>${addButton("data-custom-callout", `${lang.callout} - ${lang.custom}`)}</div>`, bind: element => {+ const search = element.querySelector<HTMLInputElement>("[data-type-search]");+ const list = element.querySelector<HTMLElement>("[data-type-list]");+ const refresh = () => {+ const keyword = search.value.trim().toLowerCase();+ list.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ list.querySelectorAll<HTMLElement>("[data-collection-type]").forEach(item => {+ item.classList.toggle("fn__none", !item.textContent.toLowerCase().includes(keyword));+ const selected = source.types?.includes(item.dataset.collectionType) || false;+ item.setAttribute("aria-pressed", String(selected));+ item.querySelector("svg").classList.toggle("fn__none", !selected);+ });+ list.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");+ };+ element.addEventListener("click", event => {+ event.stopPropagation();+ const item = (event.target as Element).closest<HTMLElement>("[data-collection-type]");+ if (item) {+ source.types = toggleCollectionType(source.types || [], item.dataset.collectionType);+ save();+ refresh();+ renderChips();+ } else if ((event.target as Element).closest("[data-custom-callout]")) {+ menu.close();+ openInputDialog({title: lang.callout, label: lang.type, value: "", maxLength: 256,+ onConfirm: (value, dialog) => {+ const type = value.trim();+ if (!type || /[\r\n\t]/.test(type)) { return; }+ types[`callout:${type}`] = `${lang.callout} - ${type}`;+ source.types = toggleCollectionType(source.types || [], `callout:${type}`);+ save();+ renderChips();+ dialog.destroy();+ }});+ }+ });+ search.addEventListener("input", refresh);+ search.addEventListener("keydown", event => {+ event.stopPropagation();+ if (event.isComposing) { return; }+ upDownHint(list, event);+ if (event.key === "Enter") {+ event.preventDefault();+ list.querySelector<HTMLElement>(".b3-list-item--focus, .b3-list-item:not(.fn__none)")?.click();+ }+ });+ refresh();+ }});+ }, show: () => {+ const rect = target.getBoundingClientRect();+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, target});+ if (!isMobile()) { menu.element.querySelector<HTMLInputElement>("[data-type-search]").focus(); }+ }});+ };+ const choose = (target: HTMLElement, items: Array<{value: string, label: string}>, current: string,+ select: (value: string) => void) => {+ let menu: Menu;+ toggleMenu({target, build: () => {+ menu = new Menu();+ items.forEach(item => menu.addItem({label: item.label, checked: item.value === current, click: () => select(item.value)}));+ }, show: () => {+ const rect = target.getBoundingClientRect();+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, target});+ }});+ };+ host.addEventListener("click", event => {+ const 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) {+ 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";+ save();+ target.firstChild.textContent = modeLabel(mode);+ });+ } 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";+ renderEditor();+ });+ } else if (target.hasAttribute("data-confirm-attribute")) { finishAttribute(); }+ else if (target.hasAttribute("data-cancel-attribute")) { finishAttribute(true); }+ else if (target.hasAttribute("data-add-attribute") || target.hasAttribute("data-edit-attribute")) {+ if (draft) { editor.querySelector<HTMLInputElement>("input").focus(); return; }+ editing = target.hasAttribute("data-edit-attribute") ? Number(target.dataset.editAttribute) : -1;+ if (editing < 0 && source.attributes?.length >= 20) { return; }+ draft = editing >= 0 ? {...source.attributes[editing]} : {name: "custom-", operator: "exists"};+ renderEditor();+ editor.querySelector<HTMLInputElement>("input").focus();+ } else if (target.dataset.removeFilter) {+ const index = Number(target.dataset.index);+ if (target.dataset.removeFilter === "type") { source.types.splice(index, 1); }+ else {+ source.attributes.splice(index, 1);+ if (editing === index) { draft = undefined; editing = -1; renderEditor(); }+ else if (editing > index) { editing--; }+ }+ save();+ renderChips();+ }+ resize();+ });+ const updateDraft = (event: Event) => {+ const input = event.target as HTMLInputElement;+ if (!draft) { return; }+ if (input.hasAttribute("data-attr-name")) { draft.name = input.value; input.setCustomValidity(""); }+ if (input.hasAttribute("data-attr-value")) { draft.value = input.value; }+ };+ host.addEventListener("input", updateDraft);+ host.addEventListener("change", updateDraft);+ host.addEventListener("keydown", event => {+ event.stopPropagation();+ if (event.isComposing) { return; }+ const target = event.target as HTMLElement;+ if (editor.contains(target) && target.matches("input")) {+ if (event.key === "Enter") { event.preventDefault(); finishAttribute(); }+ if (event.key === "Escape") { event.preventDefault(); finishAttribute(true); }+ } else if (target.matches("[data-remove-filter], [data-edit-attribute]") && (event.key === "Enter" || event.key === " ")) {+ event.preventDefault();+ target.dispatchEvent(new MouseEvent("click", {bubbles: true}));+ }+ });+ renderChips();+};diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex cf42ac2066..7b70ae2615 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 = { "attributes"?: Array<AVAutomationBlockAttribute | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "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"; "tags"?: Array<string>; "types"?: Array<string>; };-export type AVAutomationBlockSourceInput = { "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "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 AVAutomationConfig = { "rules": Array<AVAutomationRule | null> | null; "spec": number; };@@ -7816,6 +7816,7 @@ export interface APIPOSTRoutes {* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。* 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。* 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。* addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。* 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。* 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.jsindex 83cd618662..bb3b4d7627 100644--- a/app/tests/automationPanel.test.js+++ b/app/tests/automationPanel.test.js@@ -430,8 +430,8 @@ const runCases = async (sources, css, mobile) => {button.focus();assert.equal(document.activeElement, button, "collection controls remain keyboard focusable");}- assert.ok(typesRect.top - tagsRect.bottom <= 12, "tag field has no extra trailing margin");- assert.ok(addRect.top - typesRect.bottom <= 12, "empty attributes do not leave a gap");+ assert.ok(typesRect.height > 0 && addRect.height > 0);+ assert.equal(menu.querySelector("[data-attr-name]"), null, "attribute editors stay collapsed until needed");}menu.style.fontSize = "";get("[data-source-conditions]").scrollIntoView({block: "center"});@@ -439,29 +439,67 @@ const runCases = async (sources, css, mobile) => {}}await click("[data-types] svg");- fieldMenu.items.find(item => item.label === lang.list1).click();+ const typePopup = fieldMenu.element;+ typePopup.querySelector('[data-collection-type="l"]').click();assert.deepEqual(latest().blockSource.types, ["l"]);- fieldMenu.items.find(item => item.label === lang["ordered-list"]).click();+ typePopup.querySelector('[data-collection-type="l:o"]').click();assert.deepEqual(latest().blockSource.types, ["l:o"]);assert.equal(transactions.at(-1).perform[0].data.spec, 3);- fieldMenu.items.at(-1).click();+ assert.equal(typePopup.isConnected, true, "type selection keeps the searchable list open");+ const typeSearch = typePopup.querySelector("[data-type-search]");+ typeSearch.value = lang.heading1;+ typeSearch.dispatchEvent(new Event("input"));+ assert.equal(typePopup.querySelector('[data-collection-type="l:o"]').classList.contains("fn__none"), true);+ assert.equal(typePopup.querySelector('[data-collection-type="h:h1"]').classList.contains("fn__none"), false);+ typePopup.querySelector("[data-custom-callout]").click();collectionTypeInput.onConfirm("CUSTOM", {destroy() {}});assert.deepEqual(latest().blockSource.types, ["l:o", "callout:CUSTOM"]);- fieldMenu.items.slice(0, -1).forEach(item => item.click());+ await click("[data-types]");+ fieldMenu.element.querySelectorAll("[data-collection-type]").forEach(item => item.click());await tick();await require("electron").ipcRenderer.invoke("automation-size", mobile ? 360 : 420, 900);menu.style.fontSize = "28px";await tick();assert.ok(latest().blockSource.types.length > 10);assert.ok(get("[data-types]").scrollWidth <= get("[data-types]").clientWidth + 1, "many selected block types wrap");+ assert.equal(menu.querySelectorAll("[data-type-chips] .b3-chip").length, latest().blockSource.types.length);+ const draftWrites = transactions.length;await click("[data-add-attribute] svg");- assert.equal(latest().blockSource.attributes.length, 1);+ assert.equal(transactions.length, draftWrites, "adding an attribute starts an unsaved draft");await change("[data-attr-name]", "custom-status");- await change("[data-attr-operator]", "equals");+ await click("[data-attr-operator]");+ fieldMenu.items.find(item => item.label === lang.filterOperatorIs).click();await change("[data-attr-value]", "ready");+ assert.equal(transactions.length, draftWrites, "editing a draft does not save it");+ await click("[data-confirm-attribute]");assert.deepEqual(latest().blockSource.attributes, [{name: "custom-status", operator: "equals", value: "ready"}]);- await click('[data-remove="attribute"]');+ await click("[data-edit-attribute]");+ await change("[data-attr-value]", "cancelled");+ get("[data-attr-value]").dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ await tick();+ 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);+ await click('[data-match="tagMatch"]');+ fieldMenu.items.find(item => item.label === lang.filterMatchAny).click();+ assert.equal(latest().blockSource.tagMatch, "or");+ await click('[data-match="attributeMatch"]');+ fieldMenu.items.find(item => item.label === lang.filterMatchAny).click();+ assert.equal(latest().blockSource.attributeMatch, "or");+ await click("[data-tags] button");+ const tagInput = get("[data-tags] input");+ tagInput.value = " #todo# ";+ tagInput.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));+ await tick();+ assert.deepEqual(latest().blockSource.tags, ["todo"]);+ assert.equal(get("[data-tags] .b3-chip span").textContent, "todo");+ await click("[data-tags] button");+ get("[data-tags] input").value = "todo";+ get("[data-tags] input").dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));+ await tick();+ assert.equal(menu.querySelectorAll("[data-tags] .b3-chip").length, 1, "tag normalization removes duplicates");+ await click("[data-tags] .b3-chip__close");+ assert.deepEqual(latest().blockSource.tags, []);await click('[data-action="add-rule"]');const secondID = transactions.at(-1).perform[0].data.rules[1].id;await click('[data-action="rules"]');@@ -503,12 +541,15 @@ if (process.versions.electron && process.type === "browser") {const sass = require("sass");const sources = {icons: fs.readFileSync(path.join(__dirname, "../appearance/icons/litheness/icon.js"), "utf8"),languages: JSON.parse(fs.readFileSync(path.join(__dirname, "../appearance/langs/zh-CN.json"), "utf8"))};- for (const name of ["automation", "automationRules", "automationPosition", "automationTemplate", "capabilities", "capabilities.generated", "filter", "filterTree", "fieldValueEditor", "blockCollection", "selectPosition", "filterDropdown"]) {+ for (const name of ["automation", "automationRules", "automationPosition", "automationTemplate", "capabilities", "capabilities.generated", "filter", "filterTree", "fieldValueEditor", "blockCollection", "collectionConditions", "selectPosition", "filterDropdown"]) {sources[`protyle/render/av/${name}`] = ts.transpileModule(fs.readFileSync(path.join(__dirname, `../src/protyle/render/av/${name}.ts`), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},}).outputText;}- for (const name of ["escape", "setPosition"]) {+ sources["menus/aliasInput"] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/menus/aliasInput.ts"), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},+ }).outputText;+ for (const name of ["escape", "setPosition", "upDownHint"]) {sources[`util/${name}`] = ts.transpileModule(fs.readFileSync(path.join(__dirname, `../src/util/${name}.ts`), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS},}).outputText;diff --git a/docs/API.ja.md b/docs/API.ja.mdindex b865733e50..8d22732934 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` が含まれる場合があります。手動で追加した既存項目は保持されます。削除後に再び一致すると初期値を持つ新しい項目を作成し、元に戻す操作では元の項目とフィールドを復元します+ * `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 のままで、空の組は制限しません。### 主キー値を取得diff --git a/docs/API.md b/docs/API.mdindex 00513b9f84..ea34278677 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+ * `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.### Get primary key valuesdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex ac39708619..55116bb012 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`。已有手动条目不受影响;移出后再次匹配会创建新条目并初始化字段,撤销则恢复原条目及字段+ * `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`;组间仍取与关系,空组不限制。### 获取主键值diff --git a/kernel/api/av_contract_automation.go b/kernel/api/av_contract_automation.goindex ca7e698e7e..716d68bde8 100644--- a/kernel/api/av_contract_automation.go+++ b/kernel/api/av_contract_automation.go@@ -64,6 +64,7 @@ func toContractAVAutomationBlockSource(source *av.AutomationBlockSource) *apiconreturn nil}return &apicontract.AVAutomationBlockSource{NotebookIDs: source.NotebookIDs, DocumentIDs: source.DocumentIDs,+ TagMatch: source.TagMatch, 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 e25f716421..656eb3e193 100644--- a/kernel/api/contract_av_automation_test.go+++ b/kernel/api/contract_av_automation_test.go@@ -231,4 +231,23 @@ func TestAVContractAutomationWrites(t *testing.T) {if err != nil || len(preview.Blocks) != 0 {t.Fatalf("unmatched subtype preview: %+v %v", preview, err)}+ collection.BlockSource.Types = []string{"d"}+ collection.BlockSource.Tags, collection.BlockSource.TagMatch = []string{"collect", "other"}, "or"+ collection.BlockSource.Attributes = []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "ready"}, {Name: "custom-flag", Operator: "exists"}}+ collection.BlockSource.AttributeMatch = "or"+ 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/attr/setBlockAttrs", map[string]any{"id": tree.ID, "attrs": map[string]string{"tags": "other", "custom-state": "ready"}}, setBlockAttrs)+ stored, _ = av.ParseAttributeView(database.ID)+ if stored.GetBlockValueByBoundID(tree.ID) == nil {+ t.Fatal("OR groups did not collect a matching document")+ }+ call("/api/attr/setBlockAttrs", map[string]any{"id": tree.ID, "attrs": map[string]string{"custom-state": "blocked"}}, setBlockAttrs)+ stored, _ = av.ParseAttributeView(database.ID)+ if stored.GetBlockValueByBoundID(tree.ID) != nil {+ t.Fatal("OR tag group bypassed an unmatched attribute group")+ }}diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.goindex 68dd34883f..d7b418622a 100644--- a/kernel/apicontract/av_automation.go+++ b/kernel/apicontract/av_automation.go@@ -27,7 +27,8 @@ 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:类型名;提示块类型区分大小写,允许自定义名称。// 列表项首段的标签默认归属列表项;显式选择段落类型时可匹配该段落。@@ -36,11 +37,13 @@ type AVAutomationRule struct {// 再次匹配创建新条目并初始化字段,不恢复移出条目的字段;撤销重做仍恢复原事务快照。// 配置变更、启用规则、导入、同步和历史恢复不补收存量内容,也不串联触发其他自动化。type AVAutomationBlockSource struct {- NotebookIDs []string `json:"notebookIDs,omitempty" api:"optional"`- DocumentIDs []string `json:"documentIDs,omitempty" api:"optional"`- Types []string `json:"types,omitempty" api:"optional"`- Tags []string `json:"tags,omitempty" api:"optional"`- Attributes []*AVAutomationBlockAttribute `json:"attributes,omitempty" api:"optional"`+ NotebookIDs []string `json:"notebookIDs,omitempty" api:"optional"`+ DocumentIDs []string `json:"documentIDs,omitempty" api:"optional"`+ Types []string `json:"types,omitempty" api:"optional"`+ Tags []string `json:"tags,omitempty" api:"optional"`+ Attributes []*AVAutomationBlockAttribute `json:"attributes,omitempty" api:"optional"`+ TagMatch string `json:"tagMatch,omitempty" api:"optional,enum=|and|or"`+ AttributeMatch string `json:"attributeMatch,omitempty" api:"optional,enum=|and|or"`}type AVAutomationBlockAttribute struct {diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex e9c64cb84e..bc3275e951 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1439,6 +1439,7 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1、2 或 3,所有视图共享数据库级规则。// 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。// addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。// 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。// 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex ca2cf84155..80f4d2abbd 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -6655,6 +6655,14 @@"AVAutomationBlockSource": {"type": "object","properties": {+ "attributeMatch": {+ "type": "string",+ "enum": [+ "",+ "and",+ "or"+ ]+ },"attributes": {"type": "array","items": {@@ -6680,6 +6688,14 @@"type": "string"}},+ "tagMatch": {+ "type": "string",+ "enum": [+ "",+ "and",+ "or"+ ]+ },"tags": {"type": "array","items": {@@ -6698,6 +6714,14 @@"AVAutomationBlockSourceInput": {"type": "object","properties": {+ "attributeMatch": {+ "type": "string",+ "enum": [+ "",+ "and",+ "or"+ ]+ },"attributes": {"type": "array","items": {@@ -6723,6 +6747,14 @@"type": "string"}},+ "tagMatch": {+ "type": "string",+ "enum": [+ "",+ "and",+ "or"+ ]+ },"tags": {"type": "array","items": {diff --git a/kernel/av/automation.go b/kernel/av/automation.goindex 3c747479cb..2fc836dc0c 100644--- a/kernel/av/automation.go+++ b/kernel/av/automation.go@@ -28,11 +28,13 @@ type AutomationRule struct {// AutomationBlockSource 的范围取并集,各类条件取交集;文档范围包含其子文档。type AutomationBlockSource struct {- NotebookIDs []string `json:"notebookIDs,omitempty"`- DocumentIDs []string `json:"documentIDs,omitempty"`- Types []string `json:"types,omitempty"`- Tags []string `json:"tags,omitempty"`- Attributes []*AutomationBlockAttribute `json:"attributes,omitempty"`+ NotebookIDs []string `json:"notebookIDs,omitempty"`+ DocumentIDs []string `json:"documentIDs,omitempty"`+ Types []string `json:"types,omitempty"`+ Tags []string `json:"tags,omitempty"`+ Attributes []*AutomationBlockAttribute `json:"attributes,omitempty"`+ TagMatch string `json:"tagMatch,omitempty"`+ AttributeMatch string `json:"attributeMatch,omitempty"`}type AutomationBlockAttribute struct {@@ -64,6 +66,9 @@ func IsAutomationBlockType(value string) bool {func (rule *AutomationRule) RequiredSpec() int {ret := 1if rule.BlockSource != nil {+ if rule.BlockSource.TagMatch == "or" || rule.BlockSource.AttributeMatch == "or" {+ return 3+ }for _, typ := range rule.BlockSource.Types {if strings.Contains(typ, ":") {return 3diff --git a/kernel/av/automation_test.go b/kernel/av/automation_test.goindex f35c614b62..b6293d7f8d 100644--- a/kernel/av/automation_test.go+++ b/kernel/av/automation_test.go@@ -151,6 +151,13 @@ func TestAutomationBlockTypeAndSpecCompatibility(t *testing.T) {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) {+ t.Fatalf("OR spec %d: %v", spec, err)+ }}}diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 66c7e7df28..abb3c89709 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -61,37 +61,10 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, trreturn false}}- for _, attr := range source.Attributes {- if attr == nil {- return false- }- value, present := "", false- for _, pair := range node.KramdownIAL {- if len(pair) == 2 && pair[0] == attr.Name {- value, present = util.UnescapeHTML(pair[1]), true- break- }- }- switch attr.Operator {- case "equals":- if !present || value != attr.Value {- return false- }- case "contains":- if !present || !strings.Contains(value, attr.Value) {- return false- }- case "exists":- if !present {- return false- }- case "notExists":- if present {- return false- }- default:- return false- }+ if !collectionConditionsMatch(source.Attributes, source.AttributeMatch, func(attr *av.AutomationBlockAttribute) bool {+ return collectionAttributeMatches(attr, node)+ }) {+ return false}if len(source.Tags) == 0 {return true@@ -125,12 +98,44 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, tr}return ast.WalkContinue})- for _, tag := range source.Tags {- if !tags[strings.Trim(strings.TrimSpace(tag), "#")] {- return false+ return collectionConditionsMatch(source.Tags, source.TagMatch, func(tag string) bool {+ return tags[strings.Trim(strings.TrimSpace(tag), "#")]+ })+}++// 条件组为空时不限制,缺省保持全部匹配;不同条件组仍由调用方取交集。+func collectionConditionsMatch[T any](values []T, mode string, matches func(T) bool) bool {+ if len(values) == 0 {+ return true+ }+ if mode == "or" {+ return slices.ContainsFunc(values, matches)+ }+ 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+ }+ 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 true+ switch attr.Operator {+ case "equals":+ return present && value == attr.Value+ case "contains":+ return present && strings.Contains(value, attr.Value)+ case "exists":+ return present+ case "notExists":+ return !present+ }+ return false}func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rule *av.AutomationRule, boxID string) error {@@ -140,6 +145,10 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rulelen(rule.Conditions) != 0 || rule.KeyID != "" || len(rule.Actions) != 1 {return fmt.Errorf("invalid block collection source")}+ if !slices.Contains([]string{"", "and", "or"}, source.TagMatch) ||+ !slices.Contains([]string{"", "and", "or"}, source.AttributeMatch) {+ return fmt.Errorf("invalid block collection match mode")+ }for _, id := range source.NotebookIDs {if !ast.IsNodeIDPattern(id) || Conf.Box(id) == nil || !IsSameCryptoBoundary(boxID, id) {return fmt.Errorf("invalid block collection notebook [%s]", id)diff --git a/kernel/model/attribute_view_collection_fts5_test.go b/kernel/model/attribute_view_collection_fts5_test.goindex 2ba002e11d..a8fcade0f9 100644--- a/kernel/model/attribute_view_collection_fts5_test.go+++ b/kernel/model/attribute_view_collection_fts5_test.go@@ -293,6 +293,75 @@ func TestBlockCollectionSubtypes(t *testing.T) {}}+func TestBlockCollectionConditionCombinations(t *testing.T) {+ id := ast.NewNodeID()+ node := &ast.Node{ID: id, Type: ast.NodeDocument}+ node.SetIALAttr("tags", "todo")+ node.SetIALAttr("custom-state", "ready")+ tree := &parse.Tree{ID: id, Box: "notebook", Path: "/" + id + ".sy", Root: node}+ source := &av.AutomationBlockSource{DocumentIDs: []string{id}, Tags: []string{"todo", "other"},+ Attributes: []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "ready"},+ {Name: "custom-flag", Operator: "exists"}}}+ for _, modes := range []struct {+ tags, attrs string+ want bool+ }{+ {"", "", false}, {"and", "and", false}, {"or", "and", false}, {"and", "or", false}, {"or", "or", true},+ } {+ source.TagMatch, source.AttributeMatch = modes.tags, modes.attrs+ if got := collectionBlockMatches(source, node, tree); got != modes.want {+ t.Fatalf("%+v: %v", modes, got)+ }+ }+ source.Tags = []string{"missing"}+ if collectionBlockMatches(source, node, tree) {+ t.Fatal("OR inside a group bypassed the other group")+ }+ source.Tags, source.Attributes = nil, nil+ if !collectionBlockMatches(source, node, tree) {+ t.Fatal("empty OR groups restricted matches")+ }+ source.Types = []string{"p"}+ if collectionBlockMatches(source, node, tree) {+ t.Fatal("empty groups bypassed type filtering")+ }+}++func TestBlockCollectionAnyTagTransitions(t *testing.T) {+ fixture, view, _ := setupBlockCollectionTest(t)+ rule := view.Automations.Rules[0]+ view.Automations.Spec = 3+ rule.BlockSource.Tags, rule.BlockSource.TagMatch = []string{"todo", "other"}, "or"+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ var itemID string+ for _, tags := range []string{"other", "todo", "none"} {+ if err := PerformTxSync(blockCollectionTags(t, fixture.sourceID, tags)); err != nil {+ t.Fatal(err)+ }+ stored := readAttributeViewItemsTest(t, view.ID)+ row := stored.GetBlockValueByBoundID(fixture.sourceID)+ preview, err := PreviewAttributeViewCollection(view.ID, rule.ID, 1)+ if err != nil {+ t.Fatal(err)+ }+ if tags == "none" {+ if row != nil || len(preview.Blocks) != 0 {+ t.Fatal("OR mismatch kept a row or preview match")+ }+ } else {+ if row == nil || len(preview.Blocks) != 1 {+ t.Fatal("OR match not reflected in collection and preview")+ }+ if itemID != "" && row.BlockID != itemID {+ t.Fatal("switching between matching tags recreated the row")+ }+ itemID = row.BlockID+ }+ }+}+func TestBlockCollectionCreateAndMoveAcrossScope(t *testing.T) {fixture, view, _ := setupBlockCollectionTest(t)rule := view.Automations.Rules[0]