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 template management interactions https://github.com/siyuan-note/siyuan/issues/19738
Daniel541c8ad7a427
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 6106c4ae30..d7bd55e4dd 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "المستند المصدر للقالب غير موجود أو لا يمكن الوصول إليه",+ "templateOpenSourceDoc": "فتح المستند المصدر للقالب","taskCompletionToggle": "تبديل حالة إكمال المهمة","addAlias": "إضافة اسم مستعار","listMindmapExpandToLevel": "توسيع حتى المستوى ${level}",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex a8a7f5393b..a1261b17f7 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Das Quelldokument der Vorlage existiert nicht oder ist nicht zugänglich",+ "templateOpenSourceDoc": "Quelldokument der Vorlage öffnen","taskCompletionToggle": "Erledigungsstatus der Aufgabe umschalten","addAlias": "Alias hinzufügen","listMindmapExpandToLevel": "Bis Ebene ${level} aufklappen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex eff757678a..fbc59b7f57 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "The template source document does not exist or is inaccessible",+ "templateOpenSourceDoc": "Open template source document","taskCompletionToggle": "Toggle task completion","addAlias": "Add alias","listMindmapExpandToLevel": "Expand to level ${level}",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex e30e96287b..c814bc3abc 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "El documento de origen de la plantilla no existe o no es accesible",+ "templateOpenSourceDoc": "Abrir el documento de origen de la plantilla","taskCompletionToggle": "Alternar la finalización de la tarea","addAlias": "Añadir alias","listMindmapExpandToLevel": "Expandir hasta el nivel ${level}",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 7c808de3dd..e8bc154473 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Le document source du modèle est introuvable ou inaccessible",+ "templateOpenSourceDoc": "Ouvrir le document source du modèle","taskCompletionToggle": "Basculer l’état d’achèvement de la tâche","addAlias": "Ajouter un alias","listMindmapExpandToLevel": "Développer jusqu’au niveau ${level}",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 5b53eb9615..b855f5945d 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "מסמך המקור של התבנית אינו קיים או אינו נגיש",+ "templateOpenSourceDoc": "פתיחת מסמך המקור של התבנית","taskCompletionToggle": "החלפת מצב השלמת המשימה","addAlias": "הוספת כינוי","listMindmapExpandToLevel": "הרחבה עד לרמה ${level}",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex ab0e222941..0890e4b2af 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "टेम्पलेट का स्रोत दस्तावेज़ मौजूद नहीं है या उस तक पहुँच नहीं है",+ "templateOpenSourceDoc": "टेम्पलेट का स्रोत दस्तावेज़ खोलें","taskCompletionToggle": "कार्य की पूर्णता स्थिति बदलें","addAlias": "उपनाम जोड़ें","listMindmapExpandToLevel": "स्तर ${level} तक विस्तृत करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex b18eca65e8..d3f0ed71aa 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Dokumen sumber templat tidak ada atau tidak dapat diakses",+ "templateOpenSourceDoc": "Buka dokumen sumber templat","taskCompletionToggle": "Alihkan status penyelesaian tugas","addAlias": "Tambah alias","listMindmapExpandToLevel": "Perluas hingga tingkat ${level}",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 6bb68846fa..cbc41cb3f6 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Il documento di origine del modello non esiste o non è accessibile",+ "templateOpenSourceDoc": "Apri il documento di origine del modello","taskCompletionToggle": "Alterna il completamento dell’attività","addAlias": "Aggiungi alias","listMindmapExpandToLevel": "Espandi fino al livello ${level}",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex c2f66c76ed..42a5cc60a9 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "テンプレートのエクスポート元文書が存在しないか、アクセスできません",+ "templateOpenSourceDoc": "テンプレートのエクスポート元文書を開く","taskCompletionToggle": "タスクの完了状態を切り替え","addAlias": "エイリアスを追加","listMindmapExpandToLevel": "第 ${level} 階層まで展開",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 3b605eceb3..b9c511ff0d 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "템플릿 원본 문서가 없거나 접근할 수 없습니다",+ "templateOpenSourceDoc": "템플릿 원본 문서 열기","taskCompletionToggle": "작업 완료 상태 전환","addAlias": "별칭 추가","listMindmapExpandToLevel": "${level}단계까지 펼치기",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 7f6edc94ed..4c1ecc4e16 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Het brondocument van de sjabloon bestaat niet of is niet toegankelijk",+ "templateOpenSourceDoc": "Brondocument van sjabloon openen","taskCompletionToggle": "Voltooiingsstatus van taak wisselen","addAlias": "Alias toevoegen","listMindmapExpandToLevel": "Uitvouwen tot niveau ${level}",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex ed14c42472..6be85bcf7a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Dokument źródłowy szablonu nie istnieje lub jest niedostępny",+ "templateOpenSourceDoc": "Otwórz dokument źródłowy szablonu","taskCompletionToggle": "Przełącz stan ukończenia zadania","addAlias": "Dodaj alias","listMindmapExpandToLevel": "Rozwiń do poziomu ${level}",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 642019b963..5357924996 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "O documento de origem do modelo não existe ou está inacessível",+ "templateOpenSourceDoc": "Abrir documento de origem do modelo","taskCompletionToggle": "Alternar a conclusão da tarefa","addAlias": "Adicionar alias","listMindmapExpandToLevel": "Expandir até o nível ${level}",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex ee3c604440..f05137d14b 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Исходный документ шаблона не существует или недоступен",+ "templateOpenSourceDoc": "Открыть исходный документ шаблона","taskCompletionToggle": "Переключить состояние выполнения задачи","addAlias": "Добавить псевдоним","listMindmapExpandToLevel": "Развернуть до уровня ${level}",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 3df9f41282..08085ea167 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Zdrojový dokument šablóny neexistuje alebo je neprístupný",+ "templateOpenSourceDoc": "Otvoriť zdrojový dokument šablóny","taskCompletionToggle": "Prepnúť stav dokončenia úlohy","addAlias": "Pridať alias","listMindmapExpandToLevel": "Rozbaliť po úroveň ${level}",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 4e5cf8cec8..4fa7e3d8cb 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Изворни документ шаблона не постоји или није доступан",+ "templateOpenSourceDoc": "Отвори изворни документ шаблона","taskCompletionToggle": "Промени стање завршености задатка","addAlias": "Додај псеудоним","listMindmapExpandToLevel": "Прошири до нивоа ${level}",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 7ebc5cdb04..8ec7a85076 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "เอกสารต้นฉบับของแม่แบบไม่มีอยู่หรือไม่สามารถเข้าถึงได้",+ "templateOpenSourceDoc": "เปิดเอกสารต้นฉบับของแม่แบบ","taskCompletionToggle": "สลับสถานะการทำงานเสร็จสิ้น","addAlias": "เพิ่มชื่อเรียกอื่น","listMindmapExpandToLevel": "ขยายถึงระดับ ${level}",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 061d1b224f..45b27b5820 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Şablonun kaynak belgesi mevcut değil veya erişilemiyor",+ "templateOpenSourceDoc": "Şablonun kaynak belgesini aç","taskCompletionToggle": "Görevin tamamlanma durumunu değiştir","addAlias": "Takma ad ekle","listMindmapExpandToLevel": "${level}. düzeye kadar genişlet",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 3dfd1059ff..59e47605f7 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "Вихідний документ шаблону не існує або недоступний",+ "templateOpenSourceDoc": "Відкрити вихідний документ шаблону","taskCompletionToggle": "Перемкнути стан виконання завдання","addAlias": "Додати псевдонім","listMindmapExpandToLevel": "Розгорнути до рівня ${level}",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 40880ab966..572c4f5be9 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "导出模板的源文档不存在或无法访问",+ "templateOpenSourceDoc": "打开导出模板的文档","taskCompletionToggle": "切换任务完成状态","addAlias": "新增别名","listMindmapExpandToLevel": "展开到第 ${level} 级",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex bd08e29b34..5af59b90f3 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "templateSourceDocUnavailable": "匯出範本的來源文件不存在或無法存取",+ "templateOpenSourceDoc": "開啟匯出範本的文件","taskCompletionToggle": "切換任務完成狀態","addAlias": "新增別名","listMindmapExpandToLevel": "展開到第 ${level} 級",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.syindex e97a3e04c6..e37645de98 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy@@ -6,7 +6,7 @@"id": "20201204184532-3qm9l8n","title": "Template snippet","type": "doc",- "updated": "20260904091600"+ "updated": "20260922175505"},"Children": [{@@ -51,6 +51,77 @@}]},+ {+ "ID": "20260922175505-i0dqml8",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20260922175505-i0dqml8",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Template management"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20260922175505-khz1yar",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-khz1yar",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Use the More button beside a template or folder to rename, move or delete it. On desktop, right-click the entry to open the same menu. On mobile, the editor also provides a More button for the current template."+ }+ ]+ },+ {+ "ID": "20260922175505-jh595vg",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-jh595vg",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "On wide desktop windows, the source and preview appear side by side. On narrow windows and mobile devices, the preview appears below the source. The preview context selects the document whose information is used to run the template; previewing does not modify that document."+ }+ ]+ },+ {+ "ID": "20260922175505-13670ji",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-13670ji",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "For templates that retain the exported document ID, use Open template source document beside the preview button or in the entry menu to return to that document. The source must still be available in the current workspace. Opening it closes template management; after editing and exporting again, reopen template management to load the updated template."+ }+ ]+ },+ {+ "ID": "20260922175505-mbdsd8w",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-mbdsd8w",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "On mobile, returning from the editor shows the template list; returning again exits template management. Leaving unsaved edits requires confirmation. Cancelling keeps the current content."+ }+ ]+ },{"ID": "20210104091444-jy56z0p","Type": "NodeHeading",@@ -127,7 +198,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": ".action{now | date \u0026quot;2006-01-02 15:04:05\u0026quot;}"+ "TextMarkTextContent": ".action{now | date "2006-01-02 15:04:05"}"},{"Type": "NodeText",@@ -467,7 +538,7 @@},{"Type": "NodeCodeBlockCode",- "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated \u003e '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"+ "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated > '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"},{"Type": "NodeCodeBlockFenceCloseMarker",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.syindex e633c2b4c5..5dda3e6d14 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy@@ -6,7 +6,7 @@"id": "20201204181006-7bkppue","title": "模板片段","type": "doc",- "updated": "20260904091600"+ "updated": "20260922175505"},"Children": [{@@ -63,6 +63,77 @@}]},+ {+ "ID": "20260922175505-xgufvef",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20260922175505-xgufvef",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "模板管理"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20260922175505-uy1blur",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-uy1blur",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "点击模板或文件夹旁的更多按钮,可以重命名、移动或删除该条目。桌面端也可以右键打开同一菜单。移动端编辑页提供当前模板的更多按钮。"+ }+ ]+ },+ {+ "ID": "20260922175505-trnfvug",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-trnfvug",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面窗口足够宽时,源码与预览左右排列;窄窗口和移动端的预览位于源码下方。预览上下文用于选择运行模板时使用哪个文档的信息,预览不会修改该文档。"+ }+ ]+ },+ {+ "ID": "20260922175505-7isxnce",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-7isxnce",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "模板保留了导出源文档 ID 时,可以点击预览按钮旁或条目菜单中的打开导出模板的文档,返回仍可在当前工作空间访问的源文档。打开后会关闭模板管理;编辑并重新导出后,再次打开模板管理即可加载更新后的模板。"+ }+ ]+ },+ {+ "ID": "20260922175505-oqrt5k3",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-oqrt5k3",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "移动端从编辑页返回时显示模板列表,再次返回退出模板管理。离开有未保存修改的编辑页时需要确认,取消后保留当前内容。"+ }+ ]+ },{"ID": "20210104091309-fhb549c","Type": "NodeHeading",@@ -139,7 +210,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": ".action{now | date \u0026quot;2006-01-02 15:04:05\u0026quot;}"+ "TextMarkTextContent": ".action{now | date "2006-01-02 15:04:05"}"},{"Type": "NodeText",@@ -479,7 +550,7 @@},{"Type": "NodeCodeBlockCode",- "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated \u003e '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"+ "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated > '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"},{"Type": "NodeCodeBlockFenceCloseMarker",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.syindex 57e293be17..fecf90c5ba 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy@@ -6,7 +6,7 @@"id": "20211226123004-dplpw0o","title": "範本片段","type": "doc",- "updated": "20260904091600"+ "updated": "20260922175505"},"Children": [{@@ -47,6 +47,77 @@}]},+ {+ "ID": "20260922175505-mj0agjm",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20260922175505-mj0agjm",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "範本管理"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20260922175505-vs8l1r3",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-vs8l1r3",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "點擊範本或資料夾旁的更多按鈕,可以重新命名、移動或刪除該項目。桌面端也可以按右鍵開啟同一選單。行動端編輯頁提供目前範本的更多按鈕。"+ }+ ]+ },+ {+ "ID": "20260922175505-qt76rpk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-qt76rpk",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面視窗足夠寬時,原始碼與預覽左右排列;窄視窗和行動端的預覽位於原始碼下方。預覽上下文用於選擇執行範本時使用哪個文件的資訊,預覽不會修改該文件。"+ }+ ]+ },+ {+ "ID": "20260922175505-ekb7fu9",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-ekb7fu9",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "範本保留了匯出來源文件 ID 時,可以點擊預覽按鈕旁或項目選單中的開啟匯出範本的文件,返回仍可在目前工作空間存取的來源文件。開啟後會關閉範本管理;編輯並重新匯出後,再次開啟範本管理即可載入更新後的範本。"+ }+ ]+ },+ {+ "ID": "20260922175505-lpm1s5w",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-lpm1s5w",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "行動端從編輯頁返回時顯示範本清單,再次返回退出範本管理。離開有未儲存修改的編輯頁時需要確認,取消後保留目前內容。"+ }+ ]+ },{"ID": "20211226123024-eyagqur","Type": "NodeHeading",@@ -119,7 +190,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": ".action{now | date \u0026quot;2006-01-02 15:04:05\u0026quot;}"+ "TextMarkTextContent": ".action{now | date "2006-01-02 15:04:05"}"},{"Type": "NodeText",@@ -460,7 +531,7 @@},{"Type": "NodeCodeBlockCode",- "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated \u003e '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"+ "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated > '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"},{"Type": "NodeCodeBlockFenceCloseMarker",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.syindex 7fc665db2c..67347192d0 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy@@ -7,7 +7,7 @@"id": "20240530101000-6x9ivi7","title": "テンプレートスニペット","type": "doc",- "updated": "20260904091600"+ "updated": "20260922175505"},"Children": [{@@ -59,6 +59,77 @@}]},+ {+ "ID": "20260922175505-kzu7qf4",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20260922175505-kzu7qf4",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "テンプレート管理"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20260922175505-hd2pnph",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-hd2pnph",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "テンプレートやフォルダーの横にあるその他ボタンから、名前の変更、移動、削除を行えます。デスクトップでは右クリックでも同じメニューを開けます。モバイルの編集画面にも、編集中のテンプレートを操作するその他ボタンがあります。"+ }+ ]+ },+ {+ "ID": "20260922175505-ryhme24",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-ryhme24",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "デスクトップのウィンドウに十分な幅がある場合、ソースとプレビューは左右に並びます。幅が狭いウィンドウやモバイルでは、プレビューはソースの下に表示されます。プレビューコンテキストでは、テンプレートの実行に使用する文書情報を選択します。プレビューによってその文書が変更されることはありません。"+ }+ ]+ },+ {+ "ID": "20260922175505-vie0xdd",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-vie0xdd",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "エクスポート元の文書 ID が残っているテンプレートでは、プレビューボタンの横または項目メニューのテンプレートのエクスポート元文書を開くから、現在のワークスペースでアクセス可能な元の文書に戻れます。文書を開くとテンプレート管理は閉じます。編集して再度エクスポートした後、テンプレート管理を開き直すと更新されたテンプレートを読み込めます。"+ }+ ]+ },+ {+ "ID": "20260922175505-w5kogof",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260922175505-w5kogof",+ "updated": "20260922175505"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "モバイルでは、編集画面から戻るとテンプレート一覧が表示され、もう一度戻るとテンプレート管理を終了します。未保存の変更がある編集画面から離れる際には確認が表示され、キャンセルすると現在の内容が保持されます。"+ }+ ]+ },{"ID": "20240530101000-pi05yzt","Type": "NodeHeading",@@ -144,7 +215,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": ".action{now | date \u0026quot;2006-01-02 15:04:05\u0026quot;}"+ "TextMarkTextContent": ".action{now | date "2006-01-02 15:04:05"}"},{"Type": "NodeText",@@ -478,7 +549,7 @@},{"Type": "NodeCodeBlockCode",- "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated \u003e '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"+ "Data": ".action{ $today := now | date \"20060102150405\" }\n.action{ $blocks := queryBlocks \"SELECT * FROM blocks WHERE content LIKE '?' AND updated > '?' LIMIT ?\" \"%foo%\" $today \"3\" }\n"},{"Type": "NodeCodeBlockFenceCloseMarker",diff --git a/app/src/assets/scss/business/_template-manager.scss b/app/src/assets/scss/business/_template-manager.scssindex 7567611a27..29ae034812 100644--- a/app/src/assets/scss/business/_template-manager.scss+++ b/app/src/assets/scss/business/_template-manager.scss@@ -16,6 +16,12 @@display: flex;flex-wrap: wrap;gap: 8px;++ > .b3-button {+ max-width: 100%;+ white-space: normal;+ overflow-wrap: anywhere;+ }}&__panels {@@ -28,7 +34,8 @@&__sidebar {display: flex;flex-direction: column;- width: 28%;+ width: clamp(200px, 25%, 280px);+ flex-shrink: 0;min-width: 0;min-height: 0;gap: 8px;@@ -107,6 +114,32 @@gap: 8px;}+ &__source-panel,+ &__preview-panel {+ display: flex;+ flex-direction: column;+ min-width: 0;+ gap: 8px;+ flex: 1 0 auto;+ }++ &__heading {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ &__path {+ flex: 1;+ min-width: 0;+ }++ &__more {+ min-width: 32px;+ min-height: 36px;+ justify-content: center;+ }+&__source {flex: 1 0 180px;width: 100%;@@ -147,6 +180,26 @@}}+.template-manager--wide {+ .template-manager__editor {+ flex-direction: row;+ overflow: hidden;+ gap: 16px;+ }++ .template-manager__source-panel,+ .template-manager__preview-panel {+ flex: 1 1 0;+ min-height: 0;+ overflow: auto;+ }++ .template-manager__preview {+ flex: 1 0 180px;+ max-height: none;+ }+}+@media (max-width: 600px) {.template-manager {&__panels {@@ -170,6 +223,11 @@}.template-manager--mobile {+ .template-manager__more {+ min-width: 40px;+ min-height: 40px;+ }+.template-manager__sidebar {width: 100%;flex: 1;@@ -182,6 +240,10 @@}&.template-manager--editing {+ .template-manager__global-actions {+ display: none;+ }+.template-manager__sidebar {display: none;}diff --git a/app/src/template/actionState.test.ts b/app/src/template/actionState.test.tsindex 60f7a63069..2de6041431 100644--- a/app/src/template/actionState.test.ts+++ b/app/src/template/actionState.test.ts@@ -6,7 +6,7 @@ describe("template manager action state", () => {it("keeps editing actions on the open file when a directory is selected", () => {const selected = {path: "folder", isDir: true};const editing = {path: "folder/note.md", isDir: false};- for (const action of ["save", "preview"]) {+ for (const action of ["save", "preview", "source", "more"]) {const entry = getTemplateActionEntry(action, selected, editing);assert.equal(entry, editing);assert.equal(getTemplateActionState(action, entry, true, false).disabled, false);diff --git a/app/src/template/actionState.ts b/app/src/template/actionState.tsindex 50525a5462..08faa02279 100644--- a/app/src/template/actionState.ts+++ b/app/src/template/actionState.ts@@ -1,7 +1,7 @@import {TemplateEntry} from "./fileTree";export const getTemplateActionEntry = (action: string, selected: TemplateEntry | undefined, editing: TemplateEntry | undefined) =>- ["save", "preview"].includes(action) ? editing : selected;+ ["save", "preview", "source", "more"].includes(action) ? editing : selected;export const getTemplateActionState = (action: string, selected: TemplateEntry | undefined, dirty: boolean, busy: boolean,hasPreviewContext = true) => {diff --git a/app/src/template/manager.ts b/app/src/template/manager.tsindex 93dddba6e0..7382cbbf18 100644--- a/app/src/template/manager.ts+++ b/app/src/template/manager.ts@@ -9,7 +9,7 @@ import type {TemplateEntry} from "./fileTree";import {getFileRenameTarget, getFileTree} from "../util/fileTree";import {getTemplateActionEntry, getTemplateActionState} from "./actionState";/// #if !MOBILE-import {openBy} from "../editor/util";+import {openBy, openFileById} from "../editor/util";/// #endifimport {replaceFileName} from "../editor/rename";import {getHostCapabilities} from "../util/hostCapabilities";@@ -17,6 +17,14 @@ import {isBrowser, isMobile} from "../util/functions";import type {TemplateFileRequestInput} from "../types/api";import {openModel} from "../mobile/menu/model";import {closeModel} from "../mobile/util/closePanel";+import {loadMobileFileById} from "../mobile/editor";+import {MenuItem} from "../menus/Menu";+import {closeMobileBacklinkSheets} from "../mobile/util/backlinkPanels";+import {Constants} from "../constants";+import {setStorageVal} from "../protyle/util/compatibility";+import {isEncryptedBox} from "../util/pathName";++type TemplateActionTarget = {entry: TemplateEntry, revision: string, sourceDocID?: string};export const loadTemplateDirectories = async (select: HTMLSelectElement, initialDirectory?: string) => {const response = await fetchSyncPost("/api/template/manage", {action: "list"});@@ -43,15 +51,18 @@ export const openTemplateManager = (contextID = "", onClose?: () => void, initialet useCRLF = false;let revision = "";let previewPath = "";+ let sourceDocID = "";let busy = false;let closed = false;+ let layoutObserver: ResizeObserver;+ const canOpenFolder = !isBrowser() && !mobile && getHostCapabilities().localFileSystem;const expandedPaths = new Set<string>();const button = (action: string, label: string) => `<button type="button" class="b3-button b3-button--outline" data-action="${action}">${label}</button>`;const content = `<div class="template-manager${mobile ? " template-manager--mobile" : ""}">-<div class="template-manager__actions">+<div class="template-manager__actions template-manager__global-actions">${button("new", lang.newTemplate)}${button("mkdir", lang.templateNewFolder)}-${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", lang.remove)}${button("refresh", lang.refresh)}-${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button("open", lang.showInFolder) : ""}+${button("refresh", lang.refresh)}+${canOpenFolder ? button("open", lang.showInFolder) : ""}</div><div class="template-manager__panels"><div class="template-manager__sidebar">@@ -59,9 +70,13 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(<ul class="template-manager__files b3-list b3-list--background" aria-label="${lang.template}"></ul></div><div class="template-manager__editor">-<div class="template-manager__path ft__breakword"></div>+<div class="template-manager__source-panel">+<div class="template-manager__heading"><div class="template-manager__path ft__breakword"></div>+<button type="button" class="block__icon block__icon--show template-manager__more" data-action="more" aria-label="${lang.more}" aria-haspopup="menu"><svg><use xlink:href="#iconMore"></use></svg></button></div><textarea class="b3-text-field template-manager__source" spellcheck="false" aria-label="${lang.templateSource}" disabled></textarea>-<div class="template-manager__actions">${button("save", lang.save)}${button("preview", lang.templatePreview)}</div>+<div class="template-manager__actions">${button("save", lang.save)}${button("preview", lang.templatePreview)}${button("source", lang.templateOpenSourceDoc)}</div>+</div>+<div class="template-manager__preview-panel"><div class="template-manager__context"><div>${lang.templateContext}<span class="template-manager__context-name"></span></div><div class="ft__on-surface">${lang.templateContextTip}</div>@@ -69,10 +84,11 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(<input spellcheck="false" class="b3-text-field" type="search" placeholder="${lang.templateContextSearch}" aria-label="${lang.templateContextSearch}"><select class="b3-select" aria-label="${lang.templateContext}"></select></div></div><div class="template-manager__preview"></div>-</div></div>+</div></div></div></div>`;const onDestroy = () => {closed = true;+ layoutObserver?.disconnect();clearTemplatePreview(preview);window.removeEventListener("beforeunload", beforeUnload);onClose?.();@@ -80,7 +96,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(let element: HTMLElement;const dialog = mobile ? undefined : new Dialog({title: lang.templateManager,- width: "min(1100px, 96vw)",+ width: "min(1440px, 96vw)",height: "min(800px, 90vh)",content,destroyCallback: onDestroy,@@ -111,6 +127,14 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(const search = element.querySelector<HTMLInputElement>(".template-manager__context input");const context = element.querySelector<HTMLSelectElement>("select");const contextName = element.querySelector<HTMLElement>(".template-manager__context-name");+ const editorMore = element.querySelector<HTMLButtonElement>(".template-manager__heading [data-action=more]");+ const sourceButton = element.querySelector<HTMLButtonElement>("[data-action=source]");+ if (!mobile) {+ layoutObserver = new ResizeObserver(entries => {+ root.classList.toggle("template-manager--wide", entries[0].contentRect.width >= 1180);+ });+ layoutObserver.observe(root);+ }if (contextID) {context.add(new Option(contextID, contextID));}@@ -132,24 +156,39 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(if (busy || closed) {return;}+ const proceed = () => {+ if (!busy && !closed) {+ action();+ }+ };if (dirty()) {- confirmDialog(lang.confirm, lang.discardUnsavedChanges, action);+ confirmDialog(lang.confirm, lang.discardUnsavedChanges, proceed);} else {- action();+ proceed();}};const destroy = mobile ? closeModel : dialog.destroy.bind(dialog);- const back = () => guard(() => {- if (mobile && root.classList.contains("template-manager--editing")) {- void run(async () => {- await select();- renderList();- element.closest("#model")?.querySelector<HTMLElement>(".toolbar__icon").focus({preventScroll: true});- });- } else {- destroy();+ const back = () => {+ const menu = window.siyuan.menus.menu;+ if (!menu.element.classList.contains("fn__none")) {+ menu.remove();+ return;}- });+ guard(() => {+ if (mobile && root.classList.contains("template-manager--editing")) {+ const path = editing?.path;+ void run(async () => {+ await select();+ renderList();+ Array.from(list.querySelectorAll<HTMLElement>("li[data-path]"))+ .find(row => row.dataset.path === path)?.querySelector<HTMLButtonElement>(".template-manager__file")+ .focus({preventScroll: true});+ });+ } else {+ destroy();+ }+ });+ };if (dialog) {dialog.destroy = back;}@@ -159,14 +198,22 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(source.disabled = !editing;source.readOnly = busy;list.setAttribute("aria-busy", String(busy));+ editorMore.disabled = !editing || busy;+ sourceButton.classList.toggle("fn__none", !sourceDocID || !editing);+ list.querySelectorAll<HTMLButtonElement>(".template-manager__more").forEach(button => {+ button.disabled = busy;+ });element.querySelectorAll<HTMLButtonElement>(".template-manager__actions > [data-action]").forEach(element => {const action = element.dataset.action;const state = getTemplateActionState(action, getTemplateActionEntry(action, selected, editing),dirty(), busy, Boolean(context.value));element.title = state.packageMove ? lang.templatePackageMoveTip : "";element.disabled = state.disabled;+ if (action === "source") {+ element.disabled = !editing || !sourceDocID;+ }// 请求期间保留按钮外观,由事件入口拦截重复操作。- element.setAttribute("aria-disabled", String(state.ariaDisabled));+ element.setAttribute("aria-disabled", String(state.ariaDisabled || element.disabled));});};const run = async (action: () => Promise<void>) => {@@ -263,6 +310,22 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(}});row.append(element);+ const more = document.createElement("button");+ more.type = "button";+ more.className = "block__icon block__icon--show template-manager__more";+ more.setAttribute("aria-label", lang.more + " " + entry.name);+ more.setAttribute("aria-haspopup", "menu");+ more.innerHTML = '<svg><use xlink:href="#iconMore"></use></svg>';+ more.addEventListener("click", event => {+ event.stopPropagation();+ openEntryMenu(entry, more);+ });+ row.addEventListener("contextmenu", event => {+ event.preventDefault();+ event.stopPropagation();+ openEntryMenu(entry, more, event);+ });+ row.append(more);list.append(row);});list.scrollTop = scrollTop;@@ -270,6 +333,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(const select = async (entry?: TemplateEntry, preserveEditor = false) => {let content = "";let absolutePath = "";+ let documentID = "";if (entry) {const response = await api({action: "read", path: entry.path});if (!response?.data || Array.isArray(response.data) || !("content" in response.data)) {@@ -278,6 +342,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(revision = response.data.revision;content = response.data.content;absolutePath = response.data.path || "";+ documentID = response.data.sourceDocID || "";} else {revision = "";}@@ -288,6 +353,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(editingRevision = editing ? revision : "";useCRLF = content.includes("\r\n") && !content.replace(/\r\n/g, "").includes("\n");previewPath = absolutePath;+ sourceDocID = documentID;source.value = content;saved = source.value;clearTemplatePreview(preview);@@ -319,7 +385,8 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(list.querySelector(".b3-list-item--focus")?.scrollIntoView({block: "nearest", inline: "nearest"});}};- const inputPath = (title: string, value: string, callback: (value: string) => Promise<void>, nameOnly = false) => {+ const inputPath = (title: string, value: string, callback: (value: string) => Promise<void>, renamePath?: string) => {+ const nameOnly = renamePath !== undefined;const prompt = openInputDialog({title,value,@@ -333,7 +400,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(input.focus();return;}- if (nameOnly && getFileRenameTarget(selected.path, input.value.trim()) === undefined) {+ if (nameOnly && getFileRenameTarget(renamePath, input.value.trim()) === undefined) {input.setCustomValidity(lang.templateNameTip);input.reportValidity();return;@@ -345,8 +412,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(const input = prompt.element.querySelector<HTMLInputElement>("input");input.addEventListener("input", () => input.setCustomValidity(""));};- const move = () => {- const entry = selected;+ const move = ({entry, revision}: TemplateActionTarget) => {const prompt = new Dialog({title: lang.move,width: "min(520px, 92vw)",@@ -374,6 +440,135 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(});});};+ const openSourceDocument = (id: string) => guard(() => {+ void run(async () => {+ const response = await fetchSyncPost("/api/block/getBlockInfo", {id});+ if (closed || response.code !== 0) {+ return;+ }+ if (response.data.rootID !== id) {+ showMessage(lang.templateSourceDocUnavailable, 5000, "error");+ return;+ }+ if (mobile) {+ await closeMobileBacklinkSheets();+ if (closed) {+ return;+ }+ const tabs = window.siyuan.mobile.tabs;+ // 来源打开失败时保留管理页,不能通过恢复原页签的导航关闭当前面板。+ const opened = tabs ? await tabs.open(id, {notebookId: response.data.box}) === "success" :+ await new Promise<boolean>(resolve => {+ loadMobileFileById(window.siyuan.ws.app, id, undefined, undefined, response.data.box,+ protyle => {+ const value = isEncryptedBox(protyle.notebookId) ? {id: ""} : {id};+ window.siyuan.storage[Constants.LOCAL_DOCINFO] = value;+ setStorageVal(Constants.LOCAL_DOCINFO, value);+ resolve(true);+ }, false, () => !closed, undefined, undefined, true, () => resolve(false));+ });+ if (opened && !closed) {+ destroy();+ } else if (!opened && !closed) {+ showMessage(lang.templateSourceDocUnavailable, 5000, "error");+ }+ } else {+ /// #if !MOBILE+ const tab = await openFileById({app: window.siyuan.ws.app, id, notebookId: response.data.box});+ if (tab && !closed) {+ destroy();+ }+ /// #endif+ }+ });+ });+ const actOnEntry = (action: string, target: TemplateActionTarget) => {+ const {entry, revision} = target;+ if (getTemplateActionState(action, entry, dirty(), busy).ariaDisabled || closed) {+ return;+ }+ if (action === "source") {+ if (target.sourceDocID) {+ openSourceDocument(target.sourceDocID);+ }+ return;+ }+ if (action === "open") {+ /// #if !MOBILE+ const root = window.siyuan.config.system.dataDir.replace(/\\/g, "/").replace(/\/$/, "") + "/templates";+ openBy(root + "/" + entry.path, "folder");+ /// #endif+ return;+ }+ guard(() => {+ if (action === "move") {+ move(target);+ } else if (action === "remove") {+ confirmDialog(lang.remove, escapeHtml(entry.path) + "<br>" + lang.templateDeleteTip, () => {+ void run(async () => {+ if (await api({action: "remove", path: entry.path, revision})) {+ await reload("");+ }+ });+ }, undefined, true);+ } else if (action === "rename") {+ inputPath(lang.rename, entry.path.split("/").pop(), async value => {+ const target = getFileRenameTarget(entry.path, value);+ if (target !== entry.path && await api({action: "move", path: entry.path, target, revision})) {+ await reload(target, true);+ }+ }, entry.path);+ }+ });+ };+ const openEntryMenu = (entry: TemplateEntry, anchor: HTMLElement, event?: MouseEvent) => {+ void run(async () => {+ // 菜单固定操作对象和读取版本,打开菜单不切换编辑器或丢弃未保存的源码。+ let target: TemplateActionTarget;+ if (entry.path === editing?.path) {+ target = {entry, revision: editingRevision, sourceDocID};+ } else {+ const response = await api({action: "read", path: entry.path});+ if (!response?.data || Array.isArray(response.data) || !("content" in response.data) || closed) {+ return;+ }+ target = {entry, revision: response.data.revision, sourceDocID: response.data.sourceDocID};+ }+ const menu = window.siyuan.menus.menu;+ menu.remove();+ menu.element.setAttribute("data-name", "template-manager");+ const add = (action: string, label: string, icon: string) => {+ const state = getTemplateActionState(action, entry, dirty(), false);+ const item = new MenuItem({+ id: action,+ label,+ icon,+ disabled: state.disabled,+ click: () => actOnEntry(action, target),+ }).element;+ if (state.packageMove) {+ item.title = lang.templatePackageMoveTip;+ }+ menu.append(item);+ };+ if (target.sourceDocID && !entry.isDir) {+ add("source", lang.templateOpenSourceDoc, "iconFile");+ }+ add("rename", lang.rename, "iconEdit");+ add("move", lang.move, "iconMove");+ if (canOpenFolder) {+ add("open", lang.showInFolder, "iconFolder");+ }+ add("remove", lang.remove, "iconTrashcan");+ const rect = anchor.getBoundingClientRect();+ menu.popup(event ? {x: event.clientX, y: event.clientY} : {x: rect.left, y: rect.bottom, h: rect.height});+ });+ };+ editorMore.addEventListener("click", () => {+ if (editing) {+ openEntryMenu(editing, editorMore);+ }+ });source.addEventListener("input", () => {clearTemplatePreview(preview);update();@@ -438,6 +633,9 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(if (response?.data && !Array.isArray(response.data)) {saved = source.value;editingRevision = response.data.revision;+ const current = await api({action: "read", path: editing.path});+ sourceDocID = current?.data && !Array.isArray(current.data) && "content" in current.data &&+ current.data.revision === editingRevision ? current.data.sourceDocID || "" : "";if (selected?.path === editing.path) {revision = editingRevision;} else if (selected?.isDir && editing.path.startsWith(selected.path + "/")) {@@ -451,45 +649,31 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(} else if (action === "open") {/// #if !MOBILEconst root = window.siyuan.config.system.dataDir.replace(/\\/g, "/").replace(/\/$/, "") + "/templates";- openBy(selected ? root + "/" + selected.path : root, selected ? "folder" : "app");+ openBy(root, "app");/// #endif} else if (action === "preview") {previewTemplate(previewPath, preview, context.value, source.value);+ } else if (action === "source") {+ openSourceDocument(sourceDocID);} else {guard(() => {if (action === "refresh") {void run(() => reload());- } else if (action === "move") {- move();- } else if (action === "remove") {- confirmDialog(lang.remove, escapeHtml(selected.path) + "<br>" + lang.templateDeleteTip, () => {- void run(async () => {- if (await api({action: "remove", path: selected.path, revision})) {- await reload("");- }- });- }, undefined, true);} else {const directory = selected?.isDir ? selected.path + "/" : (selected?.path.substring(0, selected.path.lastIndexOf("/") + 1) || "");- const initial = action === "rename" ? selected.path.split("/").pop() : directory + (action === "new" ? lang.untitled + ".md" : lang.untitled);- inputPath(action === "mkdir" ? lang.templateNewFolder : (action === "rename" ? lang.rename : lang.newTemplate), initial, async value => {+ const initial = directory + (action === "new" ? lang.untitled + ".md" : lang.untitled);+ inputPath(action === "mkdir" ? lang.templateNewFolder : lang.newTemplate, initial, async value => {let response;if (action === "new") {value = /\.md$/i.test(value) ? value : value + ".md";response = await api({action: "write", path: value, content: "", revision: ""});} else if (action === "mkdir") {response = await api({action: "mkdir", path: value});- } else {- value = getFileRenameTarget(selected.path, value);- if (value === selected.path) {- return;- }- response = await api({action: "move", path: selected.path, target: value, revision});}if (response) {await reload(value, true);}- }, action === "rename");+ });}});}diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 66921c59c8..7cdb1965b4 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -2172,7 +2172,7 @@ export type TemplateFileRequestInput = { "action"?: string; "content"?: string;export type TemplateFileRevision = { "revision": string; };-export type TemplateFileSource = { "content": string; "path"?: string; "revision": string; };+export type TemplateFileSource = { "content": string; "path"?: string; "revision": string; "sourceDocID"?: string; };export type TemplatePlan = { "count": number; "id": string; "nodes": Array<TemplatePlanNode | null> | null; };@@ -5515,7 +5515,7 @@ export interface APIPOSTRoutes {};"/api/template/manage": {request: TemplateFileRequestInput;- response: { "code": 0; "data": Array<TemplateFileEntry> | TemplateFileSource | (TemplateFileRevision & { "content"?: never; "path"?: never; }) | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": Array<TemplateFileEntry> | TemplateFileSource | (TemplateFileRevision & { "content"?: never; "path"?: never; "sourceDocID"?: never; }) | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "structJSON";};"/api/template/render": {diff --git a/app/tests/templateManager.test.js b/app/tests/templateManager.test.jsnew file mode 100644index 0000000000..1632812940--- /dev/null+++ b/app/tests/templateManager.test.js@@ -0,0 +1,359 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const runCases = async (sources, css, mobile, legacyMobile) => {+ const assert = require("node:assert/strict");+ const tick = () => new Promise(resolve => setTimeout(resolve, 30));+ document.body.innerHTML = '<div id="model"><button class="toolbar__icon">Back</button><div id="modelMain"></div></div>';+ new Function(sources.icons)();+ const style = document.createElement("style");+ style.textContent = css + "body {margin:0;}" + (mobile ? "#modelMain {height:calc(100dvh - 44px);}" : "#model {display:none;}");+ document.head.replaceChildren(style);+ const requests = [];+ const files = new Map([+ ["alpha.md", {content: "Original source", revision: "alpha-v1", sourceDocID: "20260921000000-abcdefg"}],+ ["beta.md", {content: "Other source", revision: "beta-v1"}],+ ["folder", {content: "", revision: "folder-v1", isDir: true}],+ ["package", {content: "", revision: "package-v1", isDir: true, isPackage: true}],+ ]);+ const dialogs = [];+ const confirmations = [];+ const opened = [];+ let modelOptions;+ let sourceUnavailable = false;+ let confirmInput;+ let openSucceeded = true;+ let closed = 0;+ const menuElement = document.createElement("div");+ menuElement.className = "fn__none";+ document.body.append(menuElement);+ const menu = {+ element: menuElement,+ remove() {menuElement.classList.add("fn__none"); menuElement.replaceChildren();},+ append(element) {menuElement.append(element);},+ popup() {menuElement.classList.remove("fn__none");},+ };+ class Dialog {+ constructor(options) {+ this.options = options;+ this.element = document.createElement("div");+ this.element.style.width = options.width || "400px";+ this.element.style.height = options.height || "auto";+ this.element.innerHTML = options.content;+ document.body.append(this.element);+ dialogs.push(this);+ }+ destroy() {this.element.remove(); this.options.destroyCallback?.();}+ }+ const languages = JSON.parse(sources.languages);+ window.siyuan = {languages, dialogs: [], storage: {}, mobile: {}, ws: {app: {}}, config: {system: {dataDir: "/workspace/data"}}, menus: {menu}};+ if (!legacyMobile) {+ window.siyuan.mobile.tabs = {open: async id => {+ opened.push(id);+ return openSucceeded ? "success" : "failed";+ }};+ }+ const stubs = {+ "dialog": {Dialog},+ "dialog/inputDialog": {openInputDialog(options) {+ const prompt = new Dialog({content: "<input>"});+ prompt.element.querySelector("input").value = options.value;+ confirmInput = value => {+ prompt.element.querySelector("input").value = value;+ options.onConfirm(value, prompt);+ };+ return prompt;+ }},+ "dialog/confirmDialog": {confirmDialog: (title, text, callback) => confirmations.push({title, text, callback})},+ "dialog/message": {showMessage() {}},+ "util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: true})},+ "util/functions": {isMobile: () => mobile, isBrowser: () => false},+ "editor/rename": {replaceFileName: value => value},+ "editor/util": {openBy() {}, openFileById: async options => {+ opened.push(options.id);+ return openSucceeded ? {} : undefined;+ }},+ "mobile/editor": {loadMobileFileById: (_app, id, _action, _scroll, _box, afterOpen, _force, _valid, _signal, _attr, _recent, onFailure) => {+ opened.push(id);+ if (openSucceeded) {afterOpen({notebookId: "notebook"});} else {onFailure();}+ }},+ "mobile/util/backlinkPanels": {closeMobileBacklinkSheets: async () => {}},+ "constants": {Constants: {LOCAL_DOCINFO: "docInfo"}},+ "protyle/util/compatibility": {setStorageVal() {}},+ "util/pathName": {isEncryptedBox: () => false},+ "mobile/menu/model": {openModel: options => {+ modelOptions = options;+ document.getElementById("model").style.transform = "translateX(0px)";+ const element = document.getElementById("modelMain");+ element.innerHTML = options.html;+ options.bindEvent(element);+ }},+ "mobile/util/closePanel": {closeModel: () => {+ document.getElementById("modelMain").replaceChildren();+ modelOptions.destroyCallback();+ }},+ "protyle/toolbar/util": {+ clearTemplatePreview: element => {element.innerHTML = "";},+ previewTemplate: (_path, element, _context, source) => {element.textContent = source;},+ },+ "menus/Menu": {MenuItem: class {+ constructor(options) {+ this.element = document.createElement("button");+ this.element.dataset.id = options.id;+ this.element.textContent = options.label;+ this.element.disabled = options.disabled;+ this.element.onclick = () => {options.click(); menu.remove();};+ }+ }},+ "util/fetch": {fetchSyncPost: async (url, data) => {+ requests.push({url, ...data});+ if (url === "/api/block/getRefText") {return {code: 0, data: "Context document"};}+ if (url === "/api/block/getBlockInfo") {+ return sourceUnavailable ? {code: -1} : {code: 0, data: {rootID: data.id, box: "notebook"}};+ }+ assert.equal(url, "/api/template/manage");+ if (data.action === "list") {+ return {code: 0, data: Array.from(files, ([path, file]) => ({path, isDir: !!file.isDir, isPackage: file.isPackage}))};+ }+ const file = files.get(data.path);+ if (data.action === "read") {+ return file ? {code: 0, data: {...file, path: "/templates/" + data.path}} : {code: -1};+ }+ if (file?.revision !== data.revision) {return {code: -1};}+ if (data.action === "move") {+ files.set(data.target, file);+ files.delete(data.path);+ } else if (data.action === "remove") {+ files.delete(data.path);+ } else if (data.action === "write") {+ file.content = data.content;+ file.revision += "-saved";+ file.sourceDocID = undefined;+ return {code: 0, data: {revision: file.revision}};+ }+ return {code: 0, data: null};+ }},+ };+ const cache = {};+ const load = name => {+ if (stubs[name]) {return stubs[name];}+ if (cache[name]) {return cache[name];}+ assert.ok(sources[name], name);+ const exports = cache[name] = {};+ new Function("require", "exports", sources[name])(reference => {+ const segments = name.split("/").slice(0, -1);+ for (const segment of reference.split("/")) {+ if (segment === "..") {segments.pop();}+ else if (segment !== ".") {segments.push(segment);}+ }+ return load(segments.join("/"));+ }, exports);+ return exports;+ };+ const {openTemplateManager} = load("template/manager");+ openTemplateManager("context", () => closed++, "alpha.md");+ await tick();+ const root = document.querySelector(".template-manager");+ const source = root.querySelector("textarea");+ const row = name => Array.from(root.querySelectorAll("li[data-path]")).find(row => row.dataset.path === name);+ const button = action => root.querySelector(`.template-manager__actions > [data-action="${action}"]`);+ const select = async name => {row(name).querySelector(".template-manager__file").click(); await tick();};+ const more = async name => {row(name).querySelector(".template-manager__more").click(); await tick();};+ const action = name => menuElement.querySelector(`[data-id="${name}"]`).click();+ const edit = value => {source.value = value; source.dispatchEvent(new Event("input"));};+ assert.equal(source.value, "Original source");+ assert.equal(button("rename"), null);+ assert.equal(button("move"), null);+ assert.equal(button("remove"), null);+ assert.equal(button("source").classList.contains("fn__none"), false);+ if (mobile) {+ assert.equal(button("open"), null);+ assert.equal(getComputedStyle(root.querySelector(".template-manager__sidebar")).display, "none");+ root.querySelector(".template-manager__heading [data-action=more]").click();+ await tick();+ assert.equal(menuElement.querySelector("[data-id=open]"), null);+ assert.ok(menuElement.querySelector("[data-id=source]"));+ modelOptions.backCallback();+ assert.ok(menuElement.classList.contains("fn__none"));+ assert.ok(root.classList.contains("template-manager--editing"));+ edit("Unsaved mobile content");+ modelOptions.backCallback();+ assert.equal(confirmations.length, 1);+ confirmations.pop();+ assert.equal(source.value, "Unsaved mobile content");+ modelOptions.backCallback();+ confirmations.pop().callback();+ await tick();+ assert.equal(root.classList.contains("template-manager--editing"), false);+ assert.equal(closed, 0);+ await more("folder");+ assert.equal(root.classList.contains("template-manager--editing"), false);+ assert.equal(row("folder").querySelector(".template-manager__toggle").getAttribute("aria-expanded"), "false");+ menu.remove();+ await select("alpha.md");+ } else {+ await select("folder");+ root.querySelector(".template-manager__heading [data-action=more]").click();+ await tick();+ assert.ok(menuElement.querySelector("[data-id=source]"));+ menu.remove();+ row("beta.md").dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true}));+ await tick();+ assert.equal(menuElement.querySelector("[data-id=source]"), null);+ assert.equal(source.value, "Original source");+ menu.remove();+ }+ edit("Unsaved content");+ await more("beta.md");+ assert.equal(source.value, "Unsaved content");+ assert.equal(confirmations.length, 0);+ assert.equal(menuElement.querySelector("[data-id=source]"), null);+ action("rename");+ assert.equal(confirmations.length, 1);+ confirmations.pop();+ assert.ok(files.has("beta.md"));+ await more("beta.md");+ action("rename");+ confirmations.pop().callback();+ confirmInput("renamed.md");+ await tick();+ assert.ok(files.has("renamed.md"));+ assert.ok(files.has("alpha.md"));+ assert.equal(requests.find(request => request.action === "move").revision, "beta-v1");+ assert.equal(source.value, "Other source");+ await more("renamed.md");+ action("move");+ const moveDialog = dialogs.at(-1);+ moveDialog.element.querySelector("select").value = "folder";+ moveDialog.element.querySelector("[data-action=confirm]").click();+ await tick();+ assert.ok(files.has("folder/renamed.md"));+ await more("package");+ assert.equal(menuElement.querySelector("[data-id=rename]").disabled, true);+ assert.equal(menuElement.querySelector("[data-id=move]").disabled, true);+ assert.equal(menuElement.querySelector("[data-id=remove]").disabled, false);+ menu.remove();+ await more("folder/renamed.md");+ files.get("folder/renamed.md").revision = "external-change";+ action("remove");+ confirmations.pop().callback();+ await tick();+ assert.ok(files.has("folder/renamed.md"));+ assert.equal(source.value, "Other source");+ await select("alpha.md");+ edit("Source without document attributes");+ button("save").click();+ await tick();+ assert.equal(button("source").classList.contains("fn__none"), true);+ files.get("alpha.md").sourceDocID = "20260921000000-abcdefg";+ button("refresh").click();+ await tick();+ sourceUnavailable = true;+ button("source").click();+ await tick();+ assert.equal(opened.length, 0);+ assert.equal(closed, 0);+ sourceUnavailable = false;+ openSucceeded = false;+ button("source").click();+ await tick();+ assert.equal(closed, 0);++ for (const width of mobile ? [360, 740] : [1440, 850]) {+ await require("electron").ipcRenderer.invoke("template-manager-size", width, 800);+ await tick();+ const wide = !mobile && width === 1440;+ assert.equal(root.classList.contains("template-manager--wide"), wide);+ assert.equal(getComputedStyle(root.querySelector(".template-manager__editor")).flexDirection, wide ? "row" : "column");+ assert.ok(root.scrollWidth <= root.clientWidth + 1, `${mobile}/${width}: manager overflows`);+ assert.ok(root.getBoundingClientRect().top < 100, "manager must stay within the viewport");+ const editor = root.querySelector(".template-manager__editor");+ assert.ok(editor.scrollWidth <= editor.clientWidth + 1, `${mobile}/${width}: editor overflows`);+ button("source").textContent = "Open the document from which this template was originally exported";+ root.style.fontSize = "28px";+ await tick();+ assert.ok(root.scrollWidth <= root.clientWidth + 1, `${mobile}/${width}: large text overflows`);+ assert.ok(editor.scrollWidth <= editor.clientWidth + 1, `${mobile}/${width}: large editor text overflows`);+ root.style.fontSize = "";+ button("source").textContent = languages.templateOpenSourceDoc;+ const original = source.value;+ source.value = "# Project plan\n\n## Goals\n\n- Plan the next milestone\n- Review progress\n\n## Notes\n\n.action{.title}";+ root.querySelector(".template-manager__preview").innerHTML = '<div class="protyle-wysiwyg"><h1>Project plan</h1><h2>Goals</h2><ul><li>Plan the next milestone</li><li>Review progress</li></ul><h2>Notes</h2><p>Context document</p></div>';+ await tick();+ await require("electron").ipcRenderer.invoke("template-manager-capture", `${mobile ? "mobile" : "desktop"}-${width}`);+ source.value = original;+ if (mobile && width === 360) {+ await require("electron").ipcRenderer.invoke("template-manager-size", width, 360);+ await tick();+ button("source").scrollIntoView({block: "nearest"});+ assert.ok(button("source").getBoundingClientRect().bottom <= 360, "actions remain reachable above the keyboard");+ }+ }+ openSucceeded = true;+ button("source").click();+ await tick();+ assert.equal(closed, 1);+ assert.equal(opened.at(-1), "20260921000000-abcdefg");+};++if (process.versions.electron && process.type === "browser") {+ const {app, BrowserWindow, ipcMain} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, width: 1500, height: 900, webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true}});+ let code = 0;+ try {+ ipcMain.handle("template-manager-size", (_event, width, height) => win.setContentSize(width, height));+ ipcMain.handle("template-manager-capture", async (_event, name) => {+ if (process.env.SIYUAN_TEMPLATE_CAPTURE_DIR) {+ assert.match(name, /^(mobile|desktop)-\d+$/);+ win.webContents.invalidate();+ await new Promise(resolve => setTimeout(resolve, 150));+ fs.writeFileSync(path.join(process.env.SIYUAN_TEMPLATE_CAPTURE_DIR, name + ".png"), (await win.webContents.capturePage()).toPNG());+ }+ });+ const ts = require("typescript");+ const preprocess = require("ifdef-loader/preprocessor").parse;+ const sass = require("sass");+ const theme = fs.readFileSync(path.join(__dirname, "../appearance/themes/daylight/theme.css"), "utf8");+ for (const [mobile, legacyMobile] of [[false, false], [true, false], [true, true]]) {+ await win.loadURL("data:text/html,<html><body></body></html>");+ const sources = {+ icons: fs.readFileSync(path.join(__dirname, "../appearance/icons/litheness/icon.js"), "utf8"),+ languages: fs.readFileSync(path.join(__dirname, "../appearance/langs/zh-CN.json"), "utf8"),+ };+ for (const name of ["template/manager", "template/actionState", "util/fileTree", "util/escape"]) {+ sources[name] = ts.transpileModule(preprocess(fs.readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),+ {MOBILE: mobile, BROWSER: false}, false, true), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText;+ }+ const css = theme + sass.compile(path.join(__dirname, `../src/assets/scss/${mobile ? "mobile" : "base"}.scss`), {logger: sass.Logger.silent}).css;+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(css)}, ${mobile}, ${legacyMobile})`);+ }+ } catch (error) {+ console.error(error);+ code = 1;+ } finally {+ win.destroy();+ app.exit(code);+ }+ });+} else {+ const {test} = require("node:test");+ const {execFile} = require("node:child_process");+ const {promisify} = require("node:util");+ test("template manager preserves action targets, unsaved edits, source navigation and mobile layout", async () => {+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-template-manager-"));+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 60000});+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/kernel/api/contract_template_test.go b/kernel/api/contract_template_test.goindex 40a31b32b5..e0ee218527 100644--- a/kernel/api/contract_template_test.go+++ b/kernel/api/contract_template_test.go@@ -58,6 +58,10 @@ func TestAPIContractTemplateManagement(t *testing.T) {if err := os.WriteFile(file, []byte("original"), 0644); err != nil {t.Fatal(err)}+ exported := "Body\n\n{: id=\"20260921000000-abcdefg\" type=\"doc\"}"+ if err := os.WriteFile(filepath.Join(root, "exported.md"), []byte(exported), 0644); err != nil {+ t.Fatal(err)+ }engine := gin.New()engine.POST("/api/template/manage", manageTemplateFiles)for _, entry := range []struct {@@ -67,6 +71,7 @@ func TestAPIContractTemplateManagement(t *testing.T) {{`{"action":"list"}`, 0},{`{"Action":"read","Path":"sample.md"}`, 0},{`{"action":"read","path":"folder"}`, 0},+ {`{"action":"read","path":"exported.md"}`, 0},{`{"action":"write","path":"sample.md","content":"replacement","revision":"stale"}`, -1},{`{"action":"read","path":"../outside.md"}`, -1},{`{"action":false}`, -1},@@ -88,6 +93,14 @@ func TestAPIContractTemplateManagement(t *testing.T) {if strings.Contains(entry.body, `"path":"folder"`) && strings.Contains(string(response.Data), `"path"`) {t.Fatalf("directory read gained a path field: %s", response.Data)}+ if strings.Contains(entry.body, `"path":"exported.md"`) {+ var source map[string]string+ if err := json.Unmarshal(response.Data, &source); err != nil || source["content"] != exported || source["sourceDocID"] != "20260921000000-abcdefg" {+ t.Fatalf("export source metadata changed: %s, %v", response.Data, err)+ }+ } else if strings.Contains(entry.body, `"read"`) && strings.Contains(string(response.Data), `"sourceDocID"`) {+ t.Fatalf("non-exported template gained source metadata: %s", response.Data)+ }}content, err := os.ReadFile(file)if err != nil || string(content) != "original" {diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 7f463fda6b..3eef975224 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -47268,6 +47268,9 @@},"revision": {"type": "string"+ },+ "sourceDocID": {+ "type": "string"}},"required": [diff --git a/kernel/apicontract/template_manage.go b/kernel/apicontract/template_manage.goindex 40e6939eee..447314db36 100644--- a/kernel/apicontract/template_manage.go+++ b/kernel/apicontract/template_manage.go@@ -20,6 +20,9 @@ type TemplateFileSource struct {Content string `json:"content"`Revision string `json:"revision"`Path *string `json:"path,omitempty"`+ // SourceDocID 是原始模板末尾文档级属性中的有效 ID;未声明时省略,不执行模板动作或检查来源可访问性。+ // 该 ID 仅用于尝试打开导出来源,不代表预览上下文;目录、普通 Markdown 和代码示例不提供来源。+ SourceDocID *string `json:"sourceDocID,omitempty"`}type TemplateFileRevision struct {diff --git a/kernel/model/template_manage.go b/kernel/model/template_manage.goindex 0fbc5b0450..8094974b3a 100644--- a/kernel/model/template_manage.go+++ b/kernel/model/template_manage.go@@ -30,6 +30,7 @@ import ("unicode/utf8""github.com/88250/lute/ast"+ "github.com/88250/lute/parse""github.com/siyuan-note/filelock""github.com/siyuan-note/siyuan/kernel/util")@@ -165,6 +166,24 @@ func readTemplateSource(root *os.Root, p string) (string, error) {return string(content), nil}+// 从源码的文档级属性读取导出来源,不执行模板动作,也不使用解析器生成的 ID。+func templateSourceDocumentID(content string) string {+ engine := util.NewLute()+ engine.SetKramdownBlockIAL(false)+ engine.SetIndentCodeBlock(true)+ tree := parse.Block("", []byte(content), engine.ParseOptions)+ if tree == nil || tree.Root.LastChild == nil || tree.Root.LastChild.Type != ast.NodeParagraph {+ return ""+ }+ // 导出器把文档属性写在末尾;单独解析属性,保留任意属性顺序并拒绝动态或无效 ID。+ attrs := parseTemplateDocumentAttributes(strings.TrimSpace(string(tree.Root.LastChild.Tokens)))+ id := parse.IAL2Map(attrs)["id"]+ if !ast.IsNodeIDPattern(id) {+ return ""+ }+ return id+}+// 同目录临时文件写入完成后替换,写入失败时保留原模板。func writeTemplateSource(root *os.Root, p, content string, create bool) error {if !utf8.ValidString(content) {@@ -263,7 +282,14 @@ func ManageTemplateFiles(request TemplateFileRequest) (ret any, err error) {return map[string]string{"content": "", "revision": revision}, readErr}content, readErr := readTemplateSource(root, request.Path)- return map[string]string{"content": content, "revision": fmt.Sprintf("%x", sha256.Sum256([]byte(content))), "path": filepath.Join(util.DataDir, "templates", filepath.FromSlash(request.Path))}, readErr+ if readErr != nil {+ return nil, readErr+ }+ ret := map[string]string{"content": content, "revision": fmt.Sprintf("%x", sha256.Sum256([]byte(content))), "path": filepath.Join(util.DataDir, "templates", filepath.FromSlash(request.Path))}+ if id := templateSourceDocumentID(content); id != "" {+ ret["sourceDocID"] = id+ }+ return ret, nil}if info != nil {revision, revisionErr := templateFileRevision(root, request.Path)diff --git a/kernel/model/template_manage_test.go b/kernel/model/template_manage_test.goindex 100952ac33..6efe319c11 100644--- a/kernel/model/template_manage_test.go+++ b/kernel/model/template_manage_test.go@@ -74,6 +74,33 @@ func TestTemplateFileManagement(t *testing.T) {}}+func TestTemplateSourceDocumentID(t *testing.T) {+ id := "20260921000000-abcdefg"+ attrs := `{: id="` + id + `" title="Source" type="doc"}`+ for _, test := range []struct {+ name, content, want string+ }{+ {"exported", "Body\n\n" + attrs, id},+ {"crlf", "Body\r\n\r\n" + attrs + "\r\n", id},+ {"attribute order", `Body` + "\n\n" + `{: type="doc" title="Source" id="` + id + `"}`, id},+ {"plain", "Body", ""},+ {"block", "Body\n{: id=\"" + id + "\"}", ""},+ {"code", "```markdown\n" + attrs + "\n```", ""},+ {"indented code", " " + attrs, ""},+ {"standalone attributes", "```" + templateDocumentAttributeMarker + "\n" + attrs + "\n```", ""},+ {"dynamic identity", "Body\n\n{: id=\".action{.id}\" type=\"doc\"}", ""},+ {"invalid identity", "Body\n\n{: id=\"invalid\" type=\"doc\"}", ""},+ {"unexecuted action", ".action{fail \"must not execute\"}\n\n" + attrs, id},+ {"example and source", "```markdown\n{: id=\"20260921000000-example\" type=\"doc\"}\n```\n\n" + attrs, id},+ } {+ t.Run(test.name, func(t *testing.T) {+ if got := templateSourceDocumentID(test.content); got != test.want {+ t.Fatalf("source document = %q, want %q", got, test.want)+ }+ })+ }+}+func TestTemplateDeletePreservesLegacyTrash(t *testing.T) {previous := util.DataDirutil.DataDir = t.TempDir()