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: Add automatic split opening for new database items https://github.com/siyuan-note/siyuan/issues/20880
Daniela836e8a07fb9
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 0bc53dcc5c..eaac1ff1d9 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "فتح العنصر في عرض مقسّم بعد إنشائه","deleteAll": "حذف الكل","listMindmapManageNodeColors": "إدارة ألوان العقد","listMindmapManageLineColors": "إدارة ألوان الخطوط",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex f1782d7be7..46304381f0 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Eintrag nach dem Erstellen automatisch in geteilter Ansicht öffnen","deleteAll": "Alle löschen","listMindmapManageNodeColors": "Knotenfarben verwalten","listMindmapManageLineColors": "Linienfarben verwalten",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 63b7e17d9b..f25e3887b2 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Open item in split view after creation","deleteAll": "Delete all","listMindmapManageNodeColors": "Manage node colors","listMindmapManageLineColors": "Manage line colors",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 1e334b9cca..3eda4cf41c 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Abrir el elemento en vista dividida después de crearlo","deleteAll": "Eliminar todo","listMindmapManageNodeColors": "Gestionar colores de nodos","listMindmapManageLineColors": "Gestionar colores de líneas",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex d92c07a234..fc8dc65bac 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Ouvrir l’élément en vue scindée après sa création","deleteAll": "Tout supprimer","listMindmapManageNodeColors": "Gérer les couleurs des nœuds","listMindmapManageLineColors": "Gérer les couleurs des lignes",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 851e7a6308..d96ea84c6b 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "פתיחת הפריט בתצוגה מפוצלת לאחר יצירתו","deleteAll": "מחיקת הכול","listMindmapManageNodeColors": "ניהול צבעי צמתים","listMindmapManageLineColors": "ניהול צבעי קווים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f3d5ffa581..0ff5069e56 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "बनाने के बाद आइटम को विभाजित दृश्य में खोलें","deleteAll": "सभी हटाएँ","listMindmapManageNodeColors": "नोड के रंग प्रबंधित करें","listMindmapManageLineColors": "रेखाओं के रंग प्रबंधित करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex c015c3e5a2..3c28fead5a 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Buka item dalam tampilan terbagi setelah dibuat","deleteAll": "Hapus semua","listMindmapManageNodeColors": "Kelola warna simpul","listMindmapManageLineColors": "Kelola warna garis",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 99a3ddac7f..e0515c9b6b 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Apri l’elemento in vista divisa dopo la creazione","deleteAll": "Elimina tutto","listMindmapManageNodeColors": "Gestisci i colori dei nodi","listMindmapManageLineColors": "Gestisci i colori delle linee",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex b275bb8c4a..a84c142e41 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "作成後に項目を分割表示で開く","deleteAll": "すべて削除","listMindmapManageNodeColors": "ノードの色を管理","listMindmapManageLineColors": "線の色を管理",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 1be5cf0026..098d87e289 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "생성 후 항목을 분할 화면으로 열기","deleteAll": "모두 삭제","listMindmapManageNodeColors": "노드 색상 관리","listMindmapManageLineColors": "선 색상 관리",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex c297201cd1..6b8834a23e 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Item na aanmaken in gesplitste weergave openen","deleteAll": "Alles verwijderen","listMindmapManageNodeColors": "Knoopkleuren beheren","listMindmapManageLineColors": "Lijnkleuren beheren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex bd89085271..02c3f29efe 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Otwórz element w podzielonym widoku po utworzeniu","deleteAll": "Usuń wszystko","listMindmapManageNodeColors": "Zarządzaj kolorami węzłów","listMindmapManageLineColors": "Zarządzaj kolorami linii",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 8793acf1f7..9f0b0ac491 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Abrir o item em visualização dividida após a criação","deleteAll": "Excluir tudo","listMindmapManageNodeColors": "Gerenciar cores dos nós","listMindmapManageLineColors": "Gerenciar cores das linhas",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 7d545541ab..a595a1e1a1 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Открывать элемент в разделённом представлении после создания","deleteAll": "Удалить всё","listMindmapManageNodeColors": "Управление цветами узлов","listMindmapManageLineColors": "Управление цветами линий",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex b05061369b..87c2ba8da7 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Po vytvorení otvoriť položku v rozdelenom zobrazení","deleteAll": "Odstrániť všetko","listMindmapManageNodeColors": "Spravovať farby uzlov","listMindmapManageLineColors": "Spravovať farby čiar",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 6ea253efb1..1a90e84e79 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Отвори ставку у подељеном приказу након креирања","deleteAll": "Обриши све","listMindmapManageNodeColors": "Управљај бојама чворова","listMindmapManageLineColors": "Управљај бојама линија",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f6f4e3e7bb..f555d16450 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "เปิดรายการในมุมมองแบบแบ่งหลังจากสร้าง","deleteAll": "ลบทั้งหมด","listMindmapManageNodeColors": "จัดการสีโหนด","listMindmapManageLineColors": "จัดการสีเส้น",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex aa15ceb68d..3e31597412 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Öğeyi oluşturduktan sonra bölünmüş görünümde aç","deleteAll": "Tümünü sil","listMindmapManageNodeColors": "Düğüm renklerini yönet","listMindmapManageLineColors": "Çizgi renklerini yönet",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 5b3a75df38..3c476338ed 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "Відкривати елемент у розділеному поданні після створення","deleteAll": "Видалити все","listMindmapManageNodeColors": "Керувати кольорами вузлів","listMindmapManageLineColors": "Керувати кольорами ліній",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex fe2b10f7fe..fc6939d639 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "创建后分屏打开条目","deleteAll": "全部删除","listMindmapManageNodeColors": "管理节点配色","listMindmapManageLineColors": "管理连线颜色",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex b953924b43..5c19b17916 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "newItemTemplateOpenAfterCreate": "建立後分割畫面開啟條目","deleteAll": "全部刪除","listMindmapManageNodeColors": "管理節點配色","listMindmapManageLineColors": "管理連線顏色",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 9e50a50581..d7e1ef5a31 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": "20261025011511"+ "updated": "20261025205717"},"Children": [{@@ -3279,6 +3279,43 @@}]},+ {+ "ID": "20261025205717-wu88xyc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-wu88xyc",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "In an entry template, enable "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Open item in split view after creation"+ },+ {+ "Type": "NodeText",+ "Data": " to open each new bound or unbound entry on the right after creating it from a database view. A bound document focuses its title when available; otherwise, the primary key is focused. Unbound entries focus the primary key. Mobile uses the existing page or dialog."+ }+ ]+ },+ {+ "ID": "20261025205717-d3xd5xk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-d3xd5xk",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "New templates have this option off. Turn it off to stop automatic opening. Existing templates retain their previous behavior until you change this switch, including automatic opening in calendars. Empty entries created without a template keep the view’s existing behavior; to configure them, create an empty unbound-entry template and make it the default."+ }+ ]+ },{"ID": "20240208172555-x0jaxkf","Type": "NodeHeading",@@ -5462,4 +5499,4 @@}}]-}\ No newline at end of file+}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 b0fb60bd99..5c7fc4d76c 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": "20261025011511"+ "updated": "20261025205717"},"Children": [{@@ -3237,6 +3237,43 @@}]},+ {+ "ID": "20261025205717-sfr9z2f",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-sfr9z2f",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在条目模板中启用 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "创建后分屏打开条目"+ },+ {+ "Type": "NodeText",+ "Data": " 后,从数据库视图使用该模板新建绑定或游离条目时,会自动在右侧打开。绑定文档的标题可编辑时聚焦标题,否则聚焦主键;游离条目聚焦主键。移动端使用已有的页面或弹层打开。"+ }+ ]+ },+ {+ "ID": "20261025205717-vkvh44q",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-vkvh44q",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "新模板默认关闭此选项,关闭开关即可停止自动打开。已有模板在未改动此开关时保留原行为,包括日历中的自动打开。不使用模板的空白新建沿用视图原有行为;若需配置,可创建空白游离条目模板并设为默认。"+ }+ ]+ },{"ID": "20240208115420-4440x2c","Type": "NodeHeading",@@ -5210,4 +5247,4 @@}}]-}\ No newline at end of file+}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 eaccd2651a..014b64e420 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": "20261025011511"+ "updated": "20261025205717"},"Children": [{@@ -3237,6 +3237,43 @@}]},+ {+ "ID": "20261025205717-hk9622e",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-hk9622e",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在條目範本中啟用 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "建立後分割畫面開啟條目"+ },+ {+ "Type": "NodeText",+ "Data": " 後,從資料庫視圖使用該範本新增綁定或游離條目時,會自動在右側開啟。綁定文檔的標題可編輯時聚焦標題,否則聚焦主鍵;游離條目聚焦主鍵。行動端使用既有的頁面或彈出層開啟。"+ }+ ]+ },+ {+ "ID": "20261025205717-tlxui8k",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-tlxui8k",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "新範本預設關閉此選項,關閉開關即可停止自動開啟。既有範本在未變更此開關時保留原行為,包括日曆中的自動開啟。不使用範本的空白新增沿用視圖原有行為;如需設定,可建立空白游離條目範本並設為預設。"+ }+ ]+ },{"ID": "20240208171620-kdmsvx8","Type": "NodeHeading",@@ -5202,4 +5239,4 @@]}]-}\ No newline at end of file+}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 d6b34cc622..7757a92036 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": "20261025011511"+ "updated": "20261025205717"},"Children": [{@@ -3294,6 +3294,43 @@}]},+ {+ "ID": "20261025205717-ima2aoo",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-ima2aoo",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "エントリテンプレートで "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "作成後に項目を分割表示で開く"+ },+ {+ "Type": "NodeText",+ "Data": " を有効にすると、データベースビューでそのテンプレートを使ってバインド済みまたは未バインドのエントリを作成した後、右側で自動的に開きます。バインドされたドキュメントは編集可能なタイトルにフォーカスし、タイトルを編集できない場合は主キーにフォーカスします。未バインドのエントリは主キーにフォーカスします。モバイルでは既存のページまたはダイアログを使用します。"+ }+ ]+ },+ {+ "ID": "20261025205717-gqvztkm",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261025205717-gqvztkm",+ "updated": "20261025205717"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "新しいテンプレートでは既定で無効です。スイッチを無効にすると自動で開かなくなります。既存のテンプレートは、このスイッチを変更するまでカレンダーでの自動表示を含む従来の動作を維持します。テンプレートを使わない空のエントリ作成は、ビューの従来の動作を維持します。設定が必要な場合は、空の未バインドエントリ用テンプレートを作成してデフォルトにしてください。"+ }+ ]+ },{"ID": "20240530101000-nfsvrj5","Type": "NodeHeading",@@ -5390,4 +5427,4 @@]}]-}\ No newline at end of file+}diff --git a/app/src/editor/databaseRow.ts b/app/src/editor/databaseRow.tsindex d47364f783..56954acafb 100644--- a/app/src/editor/databaseRow.ts+++ b/app/src/editor/databaseRow.ts@@ -36,6 +36,7 @@ export const newDatabaseRowModel = (options: {matchedKeyID?: string,keywords?: string[],focusPrimary?: boolean,+ focusTitle?: boolean,bindPrimary?: boolean,navigation?: IDatabaseRowOpenData["navigation"],boundBlockID?: string,diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.tsindex c503c1bf1a..ae800324aa 100644--- a/app/src/protyle/render/av/newItemTemplate.ts+++ b/app/src/protyle/render/av/newItemTemplate.ts@@ -205,6 +205,11 @@ const collectTemplate = (root: HTMLElement, itemTemplate: IAVNewItemTemplate, fiitemTemplate.name = (root.querySelector('[data-role="template-name"]') as HTMLInputElement).value.trim();itemTemplate.targetType = (root.querySelector('[data-role="target-type"]') as HTMLSelectElement).value as TAVNewItemTarget;itemTemplate.icon = (root.querySelector('[data-role="template-icon"]') as HTMLElement).dataset.value || "";+ const openAfterCreate = root.querySelector<HTMLInputElement>('[data-role="open-after-create"]');+ // 编辑旧模板的其他配置时保留缺省值,避免改变其在日历和其他视图中的既有行为。+ if (itemTemplate.openAfterCreate !== undefined || openAfterCreate.dataset.changed === "true") {+ itemTemplate.openAfterCreate = openAfterCreate.checked;+ }itemTemplate.primaryKeyTemplate = (root.querySelector('[data-role="primary-key"]') as HTMLInputElement).value;itemTemplate.contentTemplatePath = (root.querySelector('[data-role="content-template"]') as HTMLElement).dataset.value || "";const boxID = (root.querySelector('[data-role="box-id"]') as HTMLSelectElement).value;@@ -238,7 +243,7 @@ const collectTemplate = (root: HTMLElement, itemTemplate: IAVNewItemTemplate, fiitemTemplate.fieldValues = fieldValues;};-const getEditorHTML = (itemTemplate: IAVNewItemTemplate, primaryKey: IAVColumn | undefined, fields: IAVColumn[], currentNotebookID: string) => {+const getEditorHTML = (itemTemplate: IAVNewItemTemplate, primaryKey: IAVColumn | undefined, fields: IAVColumn[], currentNotebookID: string, isCalendar: boolean) => {const currentNotebook = window.siyuan.notebooks?.find(item => item.id === currentNotebookID);const forceCurrentNotebook = !!currentNotebook?.encrypted;const isDocument = itemTemplate.targetType === "document";@@ -274,6 +279,12 @@ const getEditorHTML = (itemTemplate: IAVNewItemTemplate, primaryKey: IAVColumn |<div class="fn__flex-1 fn__flex custom-attr__avvalue" style="align-items:center"><button class="b3-text-field b3-text-field--text fn__flex-1 fn__flex" data-role="template-icon" data-value="${escapeAttr(itemTemplate.icon || "")}" type="button" style="align-items:center;text-align:left"><span class="b3-menu__avemoji">${getAVBlockIconHTML({isDetached: !isDocument, block: {content: "", icon: itemTemplate.icon}})}</span></button></div></div></div>+ <div class="custom-attr">+ <div class="block__icons av__row">+ <div class="block__logo block__logo--icon ariaLabel" data-position="parentE" aria-label="${escapeAttr(window.siyuan.languages.newItemTemplateOpenAfterCreate)}"><svg class="block__logoicon"><use xlink:href="#iconOpen"></use></svg><span>${window.siyuan.languages.newItemTemplateOpenAfterCreate}</span></div>+ <div class="fn__flex custom-attr__avvalue av__template-switch" style="align-items:center;justify-content:flex-end"><input class="b3-switch" data-role="open-after-create" type="checkbox" aria-label="${escapeAttr(window.siyuan.languages.newItemTemplateOpenAfterCreate)}"${(itemTemplate.openAfterCreate ?? isCalendar) ? " checked" : ""}></div>+ </div>+ </div><div data-role="document-options" class="${isDocument ? "" : "fn__none"}"><div class="fn__hr"></div><div class="custom-attr">@@ -319,7 +330,7 @@ export const openNewItemTemplateDialog = (options: {});});if (options.createNew) {- templates.push({id: Lute.NewNodeID(), name: window.siyuan.languages.template, targetType: "detached"});+ templates.push({id: Lute.NewNodeID(), name: window.siyuan.languages.template, targetType: "detached", openAfterCreate: false});}let selectedIndex = options.selectedTemplateID ? templates.findIndex(item => item.id === options.selectedTemplateID) :(templates.length ? templates.length - 1 : -1);@@ -372,7 +383,10 @@ export const openNewItemTemplateDialog = (options: {const render = () => {listElement.innerHTML = `<li class="b3-list-item" data-role="add-template"><svg class="b3-list-item__graphic"><use xlink:href="#iconAdd"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.newTemplate}</span></li><li class="b3-menu__separator"></li>` +templates.map((item, index) => `<li class="b3-list-item b3-list-item--hide-action${index === selectedIndex ? " b3-list-item--focus" : ""}" data-index="${index}" draggable="true"><svg class="b3-list-item__graphic fn__grab"><use xlink:href="#iconDrag"></use></svg><span class="b3-list-item__text">${escapeHtml(item.name)}</span>${item.id === defaultTemplateID ? `<span class="b3-list-item__meta">${window.siyuan.languages.default}</span>` : ""}<span class="b3-list-item__action ariaLabel" data-menu="true" data-position="4west" data-role="template-action" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span></li>`).join("");- hostElement.innerHTML = selectedIndex < 0 ? "" : getEditorHTML(templates[selectedIndex], primaryKey, fields, options.protyle.notebookId);+ hostElement.innerHTML = selectedIndex < 0 ? "" : getEditorHTML(templates[selectedIndex], primaryKey, fields, options.protyle.notebookId, options.blockElement.dataset.avType === "calendar");+ hostElement.querySelector<HTMLInputElement>('[data-role="open-after-create"]')?.addEventListener("change", event => {+ (event.currentTarget as HTMLElement).dataset.changed = "true";+ });const target = hostElement.querySelector('[data-role="target-type"]') as HTMLSelectElement;target?.addEventListener("change", () => {hostElement.querySelector('[data-role="document-options"]')?.classList.toggle("fn__none", target.value !== "document");@@ -589,7 +603,7 @@ export const openNewItemTemplateDialog = (options: {}if (roleElement?.dataset.role === "add-template") {collectCurrent();- templates.push({id: Lute.NewNodeID(), name: window.siyuan.languages.template, targetType: "detached"});+ templates.push({id: Lute.NewNodeID(), name: window.siyuan.languages.template, targetType: "detached", openAfterCreate: false});selectedIndex = templates.length - 1;render();} else if (roleElement?.dataset.role === "template-action" && itemElement) {@@ -644,6 +658,7 @@ export const createAttributeViewItem = (options: {templateID?: string;position?: ICreatePosition;}) => {+ const isCalendar = options.blockElement.dataset.avType === "calendar";fetchPost("/api/av/createAttributeViewItem", {calendarDate: options.position?.calendarDate ?? getCalendarCreationDate(options.blockElement),viewID: options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW) || "",@@ -665,14 +680,15 @@ export const createAttributeViewItem = (options: {}options.blockElement.removeAttribute("data-render");avRender(options.blockElement, options.protyle);- if (options.blockElement.dataset.avType === "calendar" && response.code === 0 &&- response.data && "itemID" in response.data) {+ if (response.code === 0 && response.data && "itemID" in response.data &&+ (response.data.openAfterCreate ?? isCalendar) && options.blockElement.isConnected && !options.protyle.disabled) {void openDatabaseRowByData(options.protyle, {avID: options.blockElement.dataset.avId, databaseBlockID: options.blockElement.dataset.nodeId,notebookID: options.protyle.notebookId, itemID: response.data.itemID, valueID: "",title: response.data.content || window.siyuan.languages.untitled,boundBlockID: response.data.blockID, isDetached: response.data.isDetached,focusPrimary: true,+ focusTitle: response.data.openAfterCreate === true && !response.data.isDetached,});}});diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.tsindex afe3792a0c..bdeb4f87c3 100644--- a/app/src/protyle/render/av/openDatabaseRow.ts+++ b/app/src/protyle/render/av/openDatabaseRow.ts@@ -36,6 +36,7 @@ export interface IDatabaseRowOpenData {matchedKeyID?: string;keywords?: string[];focusPrimary?: boolean;+ focusTitle?: boolean;bindPrimary?: boolean;navigation?: IDatabaseRowNavigation;}diff --git a/app/src/protyle/render/av/primaryFocus.ts b/app/src/protyle/render/av/primaryFocus.tsindex bab2e6b369..ae1738948d 100644--- a/app/src/protyle/render/av/primaryFocus.ts+++ b/app/src/protyle/render/av/primaryFocus.ts@@ -1,18 +1,40 @@import {popTextCell} from "./cell";import {openAVBindBlock} from "./bindBlock";+/// #if !MOBILE+import {focusByOffset} from "../../util/selection";+/// #endif-// 打开条目后只在首次完成渲染时进入主键编辑,刷新不重复聚焦,也不覆盖现有内容。+// 打开条目后只在首次完成渲染时进入标题或主键编辑,刷新不重复聚焦,也不覆盖现有内容。export const focusDatabasePrimary = (root: Element, protyle: IProtyle,- request: {avID: string; itemID: string; focusPrimary?: boolean; bindPrimary?: boolean}) => {- if ((!request.focusPrimary && !request.bindPrimary) || !root.isConnected) {+ request: {avID: string; itemID: string; boundBlockID?: string; focusPrimary?: boolean; focusTitle?: boolean; bindPrimary?: boolean}) => {+ if ((!request.focusPrimary && !request.focusTitle && !request.bindPrimary) || !root.isConnected) {return;}delete request.focusPrimary;const bindPrimary = request.bindPrimary;delete request.bindPrimary;+ const focusTitle = request.focusTitle;+ delete request.focusTitle;if (protyle.disabled || window.siyuan.isPublish || protyle.options.history?.created || protyle.options.history?.snapshot) {return;}+ if (focusTitle && !bindPrimary && request.boundBlockID && request.boundBlockID === protyle.block?.rootID) {+ /// #if MOBILE+ const titleInput = document.getElementById("toolbarName") as HTMLInputElement;+ if (titleInput && !titleInput.disabled && !titleInput.readOnly && titleInput.getClientRects().length) {+ titleInput.focus({preventScroll: true});+ titleInput.setSelectionRange(titleInput.value.length, titleInput.value.length);+ return;+ }+ /// #else+ const title = protyle.title?.editElement;+ if (title?.isContentEditable && title.getClientRects().length) {+ title.focus({preventScroll: true});+ focusByOffset(title, title.textContent.length, title.textContent.length);+ return;+ }+ /// #endif+ }const field = root.querySelector<HTMLElement>(`[data-av-id="${request.avID}"] [data-primary="true"] [data-row-id="${request.itemID}"]`);if (field) {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex ec7fa9f889..dd688ef27c 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -328,11 +328,11 @@ export type AVContextFilterData = { "contextFilter": AVAttributeViewContextFilteexport type AVCreateAttributeViewItemDocsResult = { "blockIDs": Array<string> | null; "itemIDs": Array<string> | null; "skippedItemIDs"?: Array<string>; "warnings"?: Array<string>; };-export type AVCreateAttributeViewItemResult = { "blockID": string; "content": string; "isDetached": boolean; "itemID": string; "warnings"?: Array<string>; };+export type AVCreateAttributeViewItemResult = { "blockID": string; "content": string; "isDetached": boolean; "itemID": string; "openAfterCreate"?: boolean; "warnings"?: Array<string>; };export type AVCreateItemDocsResult = (AVCreateAttributeViewItemDocsResult & { "unavailableNotebook"?: never; }) | (AVUnavailableNotebook & { "blockIDs"?: never; "itemIDs"?: never; "skippedItemIDs"?: never; "warnings"?: never; });-export type AVCreateItemResult = (AVCreateAttributeViewItemResult & { "unavailableNotebook"?: never; }) | (AVUnavailableNotebook & { "blockID"?: never; "content"?: never; "isDetached"?: never; "itemID"?: never; "warnings"?: never; });+export type AVCreateItemResult = (AVCreateAttributeViewItemResult & { "unavailableNotebook"?: never; }) | (AVUnavailableNotebook & { "blockID"?: never; "content"?: never; "isDetached"?: never; "itemID"?: never; "openAfterCreate"?: never; "warnings"?: never; });export type AVCreated = { "includeTime": boolean; };@@ -400,9 +400,9 @@ export type AVNewItemSaveLocation = { "boxID"?: string; "pathTemplate": string;export type AVNewItemSaveLocationInput = { "boxID"?: string | null; "pathTemplate"?: string | null; };-export type AVNewItemTemplate = { "contentTemplatePath"?: string; "fieldValues"?: Record<string, AVNewItemFieldValue | null>; "hideInFileTree"?: boolean; "icon"?: string; "id": string; "name": string; "primaryKeyTemplate"?: string; "saveLocation"?: AVNewItemSaveLocation; "targetType": "detached" | "document"; };+export type AVNewItemTemplate = { "contentTemplatePath"?: string; "fieldValues"?: Record<string, AVNewItemFieldValue | null>; "hideInFileTree"?: boolean; "icon"?: string; "id": string; "name": string; "openAfterCreate"?: boolean; "primaryKeyTemplate"?: string; "saveLocation"?: AVNewItemSaveLocation; "targetType": "detached" | "document"; };-export type AVNewItemTemplateInput = { "contentTemplatePath"?: string | null; "fieldValues"?: Record<string, AVNewItemFieldValueInput | null> | null; "hideInFileTree"?: boolean | null; "icon"?: string | null; "id"?: string | null; "name"?: string | null; "primaryKeyTemplate"?: string | null; "saveLocation"?: AVNewItemSaveLocationInput | null; "targetType"?: "detached" | "document"; };+export type AVNewItemTemplateInput = { "contentTemplatePath"?: string | null; "fieldValues"?: Record<string, AVNewItemFieldValueInput | null> | null; "hideInFileTree"?: boolean | null; "icon"?: string | null; "id"?: string | null; "name"?: string | null; "openAfterCreate"?: boolean | null; "primaryKeyTemplate"?: string | null; "saveLocation"?: AVNewItemSaveLocationInput | null; "targetType"?: "detached" | "document"; };export type AVPasteRowsData = { "inferableKeyIDs": Array<string> | null; "view": AVTable | null; };@@ -3812,6 +3812,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 按模板创建条目;templateID 为空时创建空白游离条目。openAfterCreate 返回模板的交互偏好:+ * true 表示创建后分屏打开,false 表示不打开,省略时保留旧行为(仅日历自动打开)。API 本身不触发界面操作。+ */"/api/av/createAttributeViewItem": {request: CreateAttributeViewItemRequestInput;response: { "code": 0; "data": AVCreateItemResult; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null | AVCreateItemResult; "msg": string; };diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex a79618dd43..6184d9de2a 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1199,6 +1199,8 @@ interface IAVNewItemTemplate {saveLocation?: IAVNewItemSaveLocation;contentTemplatePath?: string;hideInFileTree?: boolean;+ /** 创建后分屏打开条目;省略时保留旧行为(仅日历自动打开),false 表示不打开。 */+ openAfterCreate?: boolean;}/** 单字段条件颜色规则按顺序匹配,默认背景同样占据优先级。 */diff --git a/app/tests/avNewItemTemplate.test.js b/app/tests/avNewItemTemplate.test.jsnew file mode 100644index 0000000000..bc3621da60--- /dev/null+++ b/app/tests/avNewItemTemplate.test.js@@ -0,0 +1,233 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const runCases = (sources, mobile) => {+ const assert = require("node:assert/strict");+ const load = (source, imports) => {+ const exports = {};+ new Function("require", "exports", source)(name => imports[name] || {}, exports);+ return exports;+ };+ window.siyuan = {languages: new Proxy({untitled: "Untitled"}, {get: (target, key) => target[key] || key}),+ notebooks: [], config: {editor: {databaseAttrShow: true}}};+ window.Lute = {NewNodeID: () => "new-template"};+ const calls = [];+ const pending = [];+ let dialog;+ let saved;+ const api = load(sources.template, {+ "../../../dialog": {Dialog: class {+ constructor(options) {+ this.element = document.createElement("div");+ this.element.innerHTML = options.content;+ document.body.append(this.element);+ dialog = {element: this.element, destroy: () => this.destroy()};+ }+ destroy() { this.element.remove(); }+ }},+ "../../../util/functions": {isMobile: () => mobile},+ "../../../util/escape": {escapeHtml: String, escapeAttr: String},+ "./blockIcon": {getAVBlockIconHTML: () => ""},+ "./view": {getFieldsByData: () => []},+ "./fieldValueEditor": {bindFieldLunarDates() {}},+ "../../../constants": {Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"}},+ "../../../util/fetch": {fetchPost: (url, data, callback) => {+ assert.equal(url, "/api/av/createAttributeViewItem");+ pending.push({data, callback});+ }},+ "./calendar/state": {getCalendarCreationDate: () => 123},+ "./render": {avRender() {}},+ "../../wysiwyg/transaction": {transaction: (_protyle, operations, undo) => { saved = {operations, undo}; }},+ "./openDatabaseRow": {openDatabaseRowByData: (_protyle, data, options) => calls.push({data, options})},+ "../../../dialog/message": {showMessage() {}},+ "../../../mobile/util/bindBottomSheetDialog": {bindBottomSheetDialog: () => () => {}},+ "../../../mobile/util/keyboardToolbar": {activeBlur() {}},+ });+ const block = document.createElement("div");+ Object.assign(block.dataset, {avId: "database", nodeId: "carrier", avType: "table"});+ document.body.append(block);+ const protyle = {id: "session", notebookId: "notebook", app: {appId: "app"}, options: {}};++ for (const targetType of ["detached", "document"]) {+ for (const view of ["table", "list", "gallery", "kanban", "calendar"]) {+ for (const preference of [undefined, false, true]) {+ block.dataset.avType = view;+ const template = {id: "template", name: "Template", targetType};+ if (preference !== undefined) template.openAfterCreate = preference;+ const data = {id: "database", newItemTemplates: [template]};+ api.openNewItemTemplateDialog({protyle, blockElement: block, data});+ const checkbox = dialog.element.querySelector('[data-role="open-after-create"]');+ assert.equal(checkbox.checked, preference ?? view === "calendar");+ assert.equal(checkbox.closest('[data-role="document-options"]'), null);+ dialog.element.querySelector('[data-role="template-name"]').value = "Renamed";+ dialog.element.querySelector('[data-role="confirm"]').click();+ assert.equal(saved.operations[0].data.templates[0].openAfterCreate, preference,+ "unrelated template edits must preserve an omitted preference");+ assert.equal(saved.undo[0].data.templates[0].openAfterCreate, preference);+ dialog.destroy();++ api.openNewItemTemplateDialog({protyle, blockElement: block, data});+ const toggle = dialog.element.querySelector('[data-role="open-after-create"]');+ toggle.click();+ dialog.element.querySelector('[data-role="confirm"]').click();+ assert.equal(saved.operations[0].data.templates[0].openAfterCreate, toggle.checked);+ assert.equal(template.openAfterCreate, preference, "dialog must not mutate its input");+ dialog.destroy();++ const before = calls.length;+ api.createAttributeViewItem({protyle, blockElement: block, templateID: "template"});+ const request = pending.pop();+ assert.equal(request.data.templateID, "template");+ // A view switch while the request is pending must not change legacy calendar behavior.+ block.dataset.avType = view === "calendar" ? "table" : "calendar";+ request.callback({code: 0, data: {itemID: "created", blockID: "document", content: "Template title",+ isDetached: targetType === "detached", openAfterCreate: preference}});+ assert.equal(calls.length - before, Number(preference ?? view === "calendar"));+ if (calls.length > before) {+ const opened = calls.at(-1);+ assert.equal(opened.options, undefined, "use the existing split-opening behavior");+ assert.equal(opened.data.focusPrimary, true);+ assert.equal(opened.data.focusTitle, preference === true && targetType === "document");+ assert.equal(opened.data.itemID, "created");+ }+ }+ }+ }+ api.openNewItemTemplateDialog({protyle, blockElement: block, data: {id: "database"}, createNew: true});+ assert.equal(dialog.element.querySelector('[data-role="open-after-create"]').checked, false);+ dialog.element.querySelector('[data-role="confirm"]').click();+ assert.equal(saved.operations[0].data.templates[0].openAfterCreate, false);+ dialog.destroy();++ for (const failure of ["error", "unavailable", "closed", "readonly"]) {+ const before = calls.length;+ api.createAttributeViewItem({protyle, blockElement: block});+ if (failure === "closed") block.remove();+ if (failure === "readonly") protyle.disabled = true;+ pending.pop().callback(failure === "unavailable" ? {code: 1, data: {unavailableNotebook: true}} : {+ code: failure === "error" ? -1 : 0,+ data: {itemID: "created", openAfterCreate: true, isDetached: true},+ });+ assert.equal(calls.length, before);+ document.body.append(block);+ protyle.disabled = false;+ }++ // Real DOM focus: bound document title, hidden-title fallback, detached primary and mobile title.+ const primary = load(sources.primary, {+ "../../util/selection": {focusByOffset: (element, start, end) => {+ assert.equal(start, end);+ const selection = getSelection();+ const range = document.createRange();+ range.selectNodeContents(element);+ range.collapse(false);+ selection.removeAllRanges();+ selection.addRange(range);+ }},+ "./cell": {popTextCell: () => assert.fail("the editable primary has an input")},+ });+ const root = document.createElement("div");+ root.innerHTML = '<input id="toolbarName" value="Mobile title"><div contenteditable="true">Document title</div>' ++ '<div data-av-id="database"><div data-primary="true"><div data-row-id="created"><input value="Primary title"></div></div></div>';+ document.body.append(root);+ const title = root.querySelector("[contenteditable]");+ const titleInput = root.querySelector("#toolbarName");+ const input = root.querySelector("[data-row-id] input");+ const target = {...protyle, block: {rootID: "document"}, title: {editElement: title}};+ const focusRequest = () => ({avID: "database", itemID: "created", boundBlockID: "document", focusPrimary: true, focusTitle: true});+ const request = focusRequest();+ primary.focusDatabasePrimary(root, target, request);+ assert.equal(document.activeElement, mobile ? titleInput : title);+ if (mobile) {+ assert.equal(titleInput.selectionStart, titleInput.value.length);+ } else {+ const beforeCaret = document.createRange();+ beforeCaret.selectNodeContents(title);+ beforeCaret.setEnd(getSelection().anchorNode, getSelection().anchorOffset);+ assert.equal(beforeCaret.toString().length, title.textContent.length);+ }+ input.focus();+ primary.focusDatabasePrimary(root, target, request);+ assert.equal(document.activeElement, input, "refresh must not focus the title again");+ (mobile ? titleInput : title).style.display = "none";+ document.activeElement.blur();+ primary.focusDatabasePrimary(root, target, focusRequest());+ assert.equal(document.activeElement, input, "hidden titles fall back to the primary key");+ (mobile ? titleInput : title).style.display = "";+ document.activeElement.blur();+ primary.focusDatabasePrimary(root, {...target, block: {rootID: "carrier"}}, focusRequest());+ assert.equal(document.activeElement, input, "standalone row previews must not focus the carrier title");+ for (const mode of ["disabled", "publish", "created", "snapshot"]) {+ document.activeElement.blur();+ window.siyuan.isPublish = mode === "publish";+ primary.focusDatabasePrimary(root, {...target, disabled: mode === "disabled", options: {history: {[mode]: "archive"}}}, focusRequest());+ assert.notEqual(document.activeElement, mobile ? titleInput : title);+ assert.notEqual(document.activeElement, input);+ }+ root.remove();+ block.remove();+ return "Template opening cases passed";+};++const runElectron = async () => {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.commandLine.appendSwitch("disable-gpu");+ await app.whenReady();+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ let exitCode = 0;+ try {+ const ts = require("typescript");+ const ifdef = require("ifdef-loader");+ for (const mobile of [false, true]) {+ const sources = Object.fromEntries(Object.entries({template: "newItemTemplate", primary: "primaryFocus"}).map(([key, file]) => {+ const source = readFileSync(path.join(__dirname, `../src/protyle/render/av/${file}.ts`), "utf8");+ let processed;+ ifdef.call({query: {MOBILE: mobile, "ifdef-triple-slash": true}, callback(error, result) {+ if (error) throw error;+ processed = result;+ }}, source);+ return [key, ts.transpileModule(processed, {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},+ }).outputText];+ }));+ await win.loadURL("data:text/html,<html><body></body></html>");+ const result = await win.webContents.executeJavaScript(`(() => {+ try { return {message: (${runCases.toString()})(${JSON.stringify(sources)}, ${mobile})}; }+ catch (error) { return {error: error.stack}; }+ })()`);+ assert.equal(result.error, undefined);+ console.log(result.message);+ }+ } catch (error) {+ console.error(error);+ exitCode = 1;+ } finally {+ win.destroy();+ app.exit(exitCode);+ }+};++if (process.versions.electron && process.type === "browser") {+ runElectron().catch(error => { console.error(error); require("electron").app.exit(1); });+} else {+ require("node:test").test("template creation preserves legacy behavior and opens and focuses bound and detached items on desktop and mobile", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 60000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-new-item-template-"));+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 55000});+ assert.equal(stdout.match(/Template opening cases passed/g)?.length, 2);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(profile).startsWith("siyuan-new-item-template-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/kernel/api/av_contract_mapping.go b/kernel/api/av_contract_mapping.goindex 681e7ec665..69495d14f0 100644--- a/kernel/api/av_contract_mapping.go+++ b/kernel/api/av_contract_mapping.go@@ -936,6 +936,7 @@ func toContractAVNewItemTemplate(value *av.NewItemTemplate) *apicontract.AVNewItSaveLocation: toContractAVNewItemSaveLocation(value.SaveLocation),ContentTemplatePath: value.ContentTemplatePath,HideInFileTree: value.HideInFileTree,+ OpenAfterCreate: value.OpenAfterCreate,}}func toContractAVNewItemFieldValue(value *av.NewItemFieldValue) *apicontract.AVNewItemFieldValue {@@ -1303,11 +1304,12 @@ func toContractAVCreateAttributeViewItemResult(value *model.CreateAttributeViewIreturn nil}return &apicontract.AVCreateAttributeViewItemResult{- ItemID: value.ItemID,- BlockID: value.BlockID,- Content: value.Content,- IsDetached: value.IsDetached,- Warnings: value.Warnings,+ ItemID: value.ItemID,+ BlockID: value.BlockID,+ Content: value.Content,+ IsDetached: value.IsDetached,+ Warnings: value.Warnings,+ OpenAfterCreate: value.OpenAfterCreate,}}func toContractAVCreateAttributeViewItemDocsResult(value *model.CreateAttributeViewItemDocsResult) *apicontract.AVCreateAttributeViewItemDocsResult {diff --git a/kernel/api/contract_av_test.go b/kernel/api/contract_av_test.goindex 989d56dd49..04bdb06d0a 100644--- a/kernel/api/contract_av_test.go+++ b/kernel/api/contract_av_test.go@@ -244,6 +244,15 @@ func assertAVContractJSONEqual(t *testing.T, want, got any) {}func TestAVContractTransportMapping(t *testing.T) {+ for _, preference := range []*bool{nil, new(false), new(true)} {+ for _, target := range []av.NewItemTargetType{av.NewItemTargetDetached, av.NewItemTargetDocument} {+ template := &av.NewItemTemplate{ID: "template", Name: "Entry", TargetType: target, OpenAfterCreate: preference}+ assertAVContractJSONEqual(t, template, toContractAVNewItemTemplate(template))+ result := &model.CreateAttributeViewItemResult{ItemID: "item", BlockID: "block", Content: "Entry",+ IsDetached: target == av.NewItemTargetDetached, OpenAfterCreate: preference}+ assertAVContractJSONEqual(t, result, toContractAVCreateAttributeViewItemResult(result))+ }+ }for _, visibility := range []string{"", "always", "hide-empty", "hide"} {key := &av.Key{ID: "key", Type: av.KeyTypeText, AttributePanelVisibility: visibility}assertAVContractJSONEqual(t, key, toContractAVKey(key))diff --git a/kernel/apicontract/av_test.go b/kernel/apicontract/av_test.goindex bcdf80b7b0..3a03d2dfc5 100644--- a/kernel/apicontract/av_test.go+++ b/kernel/apicontract/av_test.go@@ -7,6 +7,33 @@ import ("testing")+func TestAVNewItemTemplateOpenAfterCreateContract(t *testing.T) {+ endpoint := Endpoint[AVNewItemTemplate, Null]{definition: Definition{Path: "/test", Body: JSONBody}}+ for _, test := range []struct {+ body string+ want *bool+ }{+ {`{}`, nil}, {`{"openAfterCreate":null}`, nil},+ {`{"openAfterCreate":false}`, new(false)}, {`{"openAfterCreate":true}`, new(true)},+ } {+ value, err := endpoint.Decode(strings.NewReader(test.body))+ if err != nil || (value.OpenAfterCreate == nil) != (test.want == nil) ||+ test.want != nil && *value.OpenAfterCreate != *test.want {+ t.Fatalf("opening preference %s: %+v %v", test.body, value, err)+ }+ raw, _ := json.Marshal(value)+ var output map[string]json.RawMessage+ if err = json.Unmarshal(raw, &output); err != nil || (output["openAfterCreate"] != nil) != (test.want != nil) {+ t.Fatalf("opening preference presence lost: %s %v", raw, err)+ }+ }+ for _, body := range []string{`{"openAfterCreate":0}`, `{"openAfterCreate":"false"}`, `{"openAfterCreate":[]}`} {+ if _, err := endpoint.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("invalid opening preference accepted: %s", body)+ }+ }+}+func TestAVAutomationDocumentDepthContract(t *testing.T) {endpoint := Endpoint[AVAutomationBlockSource, Null]{definition: Definition{Path: "/test", Body: JSONBody}}for _, test := range []struct {diff --git a/kernel/apicontract/av_types.go b/kernel/apicontract/av_types.goindex 64a66f76db..7f7c8ded3c 100644--- a/kernel/apicontract/av_types.go+++ b/kernel/apicontract/av_types.go@@ -449,6 +449,9 @@ type AVNewItemTemplate struct {SaveLocation *AVNewItemSaveLocation `json:"saveLocation,omitempty" api:"optional,nullable"`ContentTemplatePath string `json:"contentTemplatePath,omitempty" api:"optional,nullable"`HideInFileTree bool `json:"hideInFileTree,omitempty" api:"optional,nullable"`+ // 创建后是否由交互客户端分屏打开绑定或游离条目。省略或 null 保留旧行为(仅日历自动打开);false 禁止自动打开。+ // 该配置随模板保存,API 调用本身不会打开界面;移动端使用已有的页面或弹层。+ OpenAfterCreate *bool `json:"openAfterCreate,omitempty" api:"optional,nullable"`}type AVNewItemFieldValue struct {@@ -691,6 +694,8 @@ type AVCreateAttributeViewItemResult struct {Content string `json:"content" api:"optional,nullable"`IsDetached bool `json:"isDetached" api:"optional,nullable"`Warnings []string `json:"warnings,omitempty" api:"optional,nullable"`+ // 返回实际使用模板的自动打开偏好,省略时交互客户端保留旧行为;此字段不会触发服务端界面操作。+ OpenAfterCreate *bool `json:"openAfterCreate,omitempty" api:"optional,nullable"`}type AVCreateAttributeViewItemDocsResult struct {diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex f597873f94..95dc8e2c80 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1495,6 +1495,9 @@ var ReviewAttributeViewCollection = define[AVCollectionReviewRequest, *AVCollectvar PreviewAttributeViewTemplate = define[AVAutomationTemplatePreviewRequest, *AVValue]("previewAttributeViewTemplate", "/api/av/previewAttributeViewTemplate", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")var GetAttributeViewPasteRows = define[GetAttributeViewPasteRowsRequest, AVPasteRowsData]("getAttributeViewPasteRows", "/api/av/getAttributeViewPasteRows", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var GetAttributeViewFieldViews = define[GetAttributeViewFieldViewsRequest, AVFieldViewsData]("getAttributeViewFieldViews", "/api/av/getAttributeViewFieldViews", AuthenticatedAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// 按模板创建条目;templateID 为空时创建空白游离条目。openAfterCreate 返回模板的交互偏好:+// true 表示创建后分屏打开,false 表示不打开,省略时保留旧行为(仅日历自动打开)。API 本身不触发界面操作。var CreateAttributeViewItem = define[CreateAttributeViewItemRequest, AVCreateItemResult]("createAttributeViewItem", "/api/av/createAttributeViewItem", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true, AdditionalCodes: []int{1}}, "POST")var CreateAttributeViewRelationItem = define[CreateAttributeViewRelationItemRequest, AVCreateItemResult]("createAttributeViewRelationItem", "/api/av/createAttributeViewRelationItem", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true, AdditionalCodes: []int{1}}, "POST")var CreateAttributeViewItemWithMarkdown = define[CreateAttributeViewItemWithMarkdownRequest, AVCreateItemResult]("createAttributeViewItemWithMarkdown", "/api/av/createAttributeViewItemWithMarkdown", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true, AdditionalCodes: []int{1}}, "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 2876a5b510..2862fd1b7b 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -8133,6 +8133,9 @@"itemID": {"type": "string"},+ "openAfterCreate": {+ "type": "boolean"+ },"warnings": {"type": "array","items": {@@ -10420,6 +10423,9 @@"name": {"type": "string"},+ "openAfterCreate": {+ "type": "boolean"+ },"primaryKeyTemplate": {"type": "string"},@@ -10514,6 +10520,16 @@}]},+ "openAfterCreate": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"primaryKeyTemplate": {"anyOf": [{diff --git a/kernel/av/av.go b/kernel/av/av.goindex a3815a605f..3ee1c5a32e 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -117,6 +117,8 @@ type NewItemTemplate struct {SaveLocation *NewItemSaveLocation `json:"saveLocation,omitempty"`ContentTemplatePath string `json:"contentTemplatePath,omitempty"`HideInFileTree bool `json:"hideInFileTree,omitempty"`+ // nil 保留旧客户端行为;false 不自动打开,true 创建后由交互客户端分屏打开。+ OpenAfterCreate *bool `json:"openAfterCreate,omitempty"`}// NewItemTemplatesConfig 描述一次完整的新增条目模板配置修改。diff --git a/kernel/av/new_item_template.go b/kernel/av/new_item_template.goindex 1322808fbb..661146cbf4 100644--- a/kernel/av/new_item_template.go+++ b/kernel/av/new_item_template.go@@ -486,6 +486,9 @@ func cloneNewItemTemplate(itemTemplate *NewItemTemplate) *NewItemTemplate {ContentTemplatePath: itemTemplate.ContentTemplatePath,HideInFileTree: itemTemplate.HideInFileTree,}+ if nil != itemTemplate.OpenAfterCreate {+ ret.OpenAfterCreate = new(*itemTemplate.OpenAfterCreate)+ }if nil != itemTemplate.SaveLocation {ret.SaveLocation = &NewItemSaveLocation{BoxID: itemTemplate.SaveLocation.BoxID,diff --git a/kernel/av/new_item_template_test.go b/kernel/av/new_item_template_test.goindex 77b3e009bc..5ccd8ec9b3 100644--- a/kernel/av/new_item_template_test.go+++ b/kernel/av/new_item_template_test.go@@ -9,11 +9,41 @@package avimport (+ "encoding/json""testing""github.com/88250/lute/ast")+func TestNewItemTemplateOpenAfterCreate(t *testing.T) {+ for _, target := range []NewItemTargetType{NewItemTargetDetached, NewItemTargetDocument} {+ for _, preference := range []*bool{nil, new(false), new(true)} {+ view := &AttributeView{Spec: CurrentSpec, ID: ast.NewNodeID()}+ template := &NewItemTemplate{ID: ast.NewNodeID(), Name: "Entry", TargetType: target, OpenAfterCreate: preference}+ if err := view.SetNewItemTemplates(&NewItemTemplatesConfig{Templates: []*NewItemTemplate{template}}); err != nil {+ t.Fatal(err)+ }+ stored := view.NewItemTemplates[0]+ if preference != nil && (stored.OpenAfterCreate == preference || stored.OpenAfterCreate == nil || *stored.OpenAfterCreate != *preference) {+ t.Fatalf("opening preference was lost or not cloned: %+v", stored)+ }+ raw, err := json.Marshal(stored)+ if err != nil {+ t.Fatal(err)+ }+ var fields map[string]json.RawMessage+ if err = json.Unmarshal(raw, &fields); err != nil || (fields["openAfterCreate"] != nil) != (preference != nil) {+ t.Fatalf("opening preference presence changed: %s %v", raw, err)+ }+ var restored NewItemTemplate+ if err = json.Unmarshal(raw, &restored); err != nil || (restored.OpenAfterCreate == nil) != (preference == nil) ||+ preference != nil && *restored.OpenAfterCreate != *preference {+ t.Fatalf("opening preference did not round-trip: %s %v", raw, err)+ }+ }+ }+}+func TestSetNewItemTemplates(t *testing.T) {attrView := &AttributeView{Spec: CurrentSpec, ID: ast.NewNodeID()}textKey := NewKey(ast.NewNodeID(), "Text", "", KeyTypeText)diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.goindex 3a19156888..bdea34a4e8 100644--- a/kernel/model/attribute_view_new_item.go+++ b/kernel/model/attribute_view_new_item.go@@ -42,12 +42,13 @@ type NewItemTemplatePreview struct {// CreateAttributeViewItemResult 描述按模板创建数据库条目的结果。type CreateAttributeViewItemResult struct {- ItemID string `json:"itemID"`- BlockID string `json:"blockID"`- Content string `json:"content"`- IsDetached bool `json:"isDetached"`- Warnings []string `json:"warnings,omitempty"`- Transaction *Transaction `json:"-"`+ ItemID string `json:"itemID"`+ BlockID string `json:"blockID"`+ Content string `json:"content"`+ IsDetached bool `json:"isDetached"`+ Warnings []string `json:"warnings,omitempty"`+ OpenAfterCreate *bool `json:"openAfterCreate,omitempty"`+ Transaction *Transaction `json:"-"`}// CreateAttributeViewItemMarkdown 描述通过数据库条目模板创建文档时使用的 Markdown 内容。@@ -249,6 +250,7 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, groureturn &CreateAttributeViewItemResult{ItemID: itemID, BlockID: boundBlockID, Content: content, IsDetached: isDetached,Warnings: preview.Warnings, Transaction: tx,+ OpenAfterCreate: itemTemplate.OpenAfterCreate,}, nil}diff --git a/kernel/model/attribute_view_new_item_group_fts5_test.go b/kernel/model/attribute_view_new_item_group_fts5_test.goindex ca408ec33b..ca29b7d76c 100644--- a/kernel/model/attribute_view_new_item_group_fts5_test.go+++ b/kernel/model/attribute_view_new_item_group_fts5_test.go@@ -60,6 +60,7 @@ func TestCreateAttributeViewItemPreservesFilteredGroups(t *testing.T) {groupID := group.IDtemplate := &av.NewItemTemplate{ID: ast.NewNodeID(), Name: "Entry", TargetType: target, HideInFileTree: target == av.NewItemTargetDocument,+ OpenAfterCreate: new(true),}attrView.NewItemTemplates = []*av.NewItemTemplate{template}if err := av.SaveAttributeView(attrView); err != nil {@@ -70,6 +71,9 @@ func TestCreateAttributeViewItemPreservesFilteredGroups(t *testing.T) {if err != nil {t.Fatal(err)}+ if created.OpenAfterCreate == nil || !*created.OpenAfterCreate {+ t.Fatal("creation did not return the template opening preference")+ }stored := readAttributeViewItemsTest(t, attrView.ID)value := stored.GetValue(filterKey.ID, created.ItemID)if value == nil || !av.MSelectExistOption(value.MSelect, "Feedback") {