Skip to content

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

:sparkles: Support indexed document creation templates https://github.com/siyuan-note/siyuan/issues/18390 https://github.com/siyuan-note/siyuan/issues/18404

Danielad925200d7ee
diff --git a/app/src/config/tabs/fileTab.ts b/app/src/config/tabs/fileTab.ts
index eaa503b06e..949e849585 100644
--- a/app/src/config/tabs/fileTab.ts
+++ b/app/src/config/tabs/fileTab.ts
@@ -21,6 +21,10 @@ const genNotebookSavePathHtml = (
selectId: string,
pathId: string,
optionsHtml: string,
+ template?: {
+ id: string;
+ desc: string;
+ },
) => `<div class="b3-label config-item config-item--save-path">
${genConfigItemName(title)}
<div class="b3-label__text">${desc}</div>
@@ -30,6 +34,10 @@ const genNotebookSavePathHtml = (
<div class="fn__space"></div>
<input class="b3-text-field fn__flex-1" id="${pathId}" value="">
</div>
+ ${template ? `<div class="fn__hr"></div>
+ <div class="b3-label__text">${template.desc}</div>
+ <div class="fn__hr--small"></div>
+ <input class="b3-text-field fn__flex-center fn__block" id="${template.id}" value="">` : ""}
</div>`;
/// #if !MOBILE
@@ -87,18 +95,35 @@ const registerFileNewDocumentGroup = (tab: SettingTabBuilder) => {
const docCreateDesc = window.siyuan.languages.fileTree13;
group.composite({
key: "docCreateSavePath",
- keywords: [docCreateTitle, docCreateDesc],
+ keywords: [
+ docCreateTitle,
+ docCreateDesc,
+ window.siyuan.languages.template,
+ window.siyuan.languages.fileTree15,
+ ],
html: () => genNotebookSavePathHtml(
docCreateTitle,
docCreateDesc,
"fileTree.docCreateSaveBox",
"fileTree.docCreateSavePath",
genNotebookOption(window.siyuan.config.fileTree.docCreateSaveBox),
+ {
+ id: "fileTree.docCreateTemplatePath",
+ desc: window.siyuan.languages.fileTree15,
+ },
),
afterMount: (root) => {
- const el = root.querySelector<HTMLInputElement>(`#${CSS.escape("fileTree.docCreateSavePath")}`);
- if (el) {
- el.value = window.siyuan.config.fileTree.docCreateSavePath;
+ const savePathElement = root.querySelector<HTMLInputElement>(
+ `#${CSS.escape("fileTree.docCreateSavePath")}`,
+ );
+ if (savePathElement) {
+ savePathElement.value = window.siyuan.config.fileTree.docCreateSavePath;
+ }
+ const templatePathElement = root.querySelector<HTMLInputElement>(
+ `#${CSS.escape("fileTree.docCreateTemplatePath")}`,
+ );
+ if (templatePathElement) {
+ templatePathElement.value = window.siyuan.config.fileTree.docCreateTemplatePath;
}
},
controls: [
@@ -110,6 +135,10 @@ const registerFileNewDocumentGroup = (tab: SettingTabBuilder) => {
control: controlString("fileTree.docCreateSavePath"),
save: (v) => fileConfigApi.patch("docCreateSavePath", v),
},
+ {
+ control: controlString("fileTree.docCreateTemplatePath"),
+ save: (v) => fileConfigApi.patch("docCreateTemplatePath", v),
+ },
],
});
diff --git a/app/src/menus/onGetnotebookconf.ts b/app/src/menus/onGetnotebookconf.ts
index 1cefb8afa6..b2e330c8f0 100644
--- a/app/src/menus/onGetnotebookconf.ts
+++ b/app/src/menus/onGetnotebookconf.ts
@@ -16,6 +16,7 @@ declare interface INotebookConf {
dailyNoteSavePath: string
refCreateSaveBox: string;
docCreateSaveBox: string;
+ docCreateTemplatePath: string;
dailyNoteTemplatePath: string
}
}
@@ -61,6 +62,10 @@ export const onGetnotebookconf = (data: INotebookConf) => {
<div class="fn__space"></div>
<input class="b3-text-field fn__flex-1" id="docCreateSavePath" value="">
</div>
+ <div class="fn__hr"></div>
+ <div class="b3-label__text">${window.siyuan.languages.fileTree15}</div>
+ <div class="fn__hr"></div>
+ <input class="b3-text-field fn__flex-center fn__block" id="docCreateTemplatePath" value="${data.conf.docCreateTemplatePath}">
</div>
<div class="b3-label config-item config-item--save-path">
<div class="config-name">${window.siyuan.languages.fileTree5}</div>
@@ -111,6 +116,8 @@ const bindSettingEvent = (contentElement: Element, data: INotebookConf) => {
dailyNoteSavePathElement.value = data.conf.dailyNoteSavePath;
const docCreateSavePathElement = contentElement.querySelector("#docCreateSavePath") as HTMLInputElement;
docCreateSavePathElement.value = data.conf.docCreateSavePath;
+ const docCreateTemplatePathElement = contentElement.querySelector("#docCreateTemplatePath") as HTMLInputElement;
+ docCreateTemplatePathElement.value = data.conf.docCreateTemplatePath;
const refCreateSavePathElement = contentElement.querySelector("#refCreateSavePath") as HTMLInputElement;
refCreateSavePathElement.value = data.conf.refCreateSavePath;
const dailyNoteTemplatePathElement = contentElement.querySelector("#dailyNoteTemplatePath") as HTMLInputElement;
@@ -124,6 +131,7 @@ const bindSettingEvent = (contentElement: Element, data: INotebookConf) => {
refCreateSaveBox: (contentElement.querySelector("#refCreateSaveBox") as HTMLInputElement).value,
docCreateSaveBox: (contentElement.querySelector("#docCreateSaveBox") as HTMLInputElement).value,
docCreateSavePath: docCreateSavePathElement.value,
+ docCreateTemplatePath: docCreateTemplatePathElement.value,
dailyNoteSavePath: dailyNoteSavePathElement.value,
dailyNoteTemplatePath: dailyNoteTemplatePathElement.value,
}
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index eeb50ce99c..3c732a173e 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -15,7 +15,12 @@ import {
getSelectionPosition,
} from "../util/selection";
import {genHintItemHTML, hintEmbed, hintRef, hintSlash} from "./extend";
-import {getBlockRefAnchorText, newFileByRefHint, newFileInProtyle} from "../../util/newFile";
+import {
+ getBlockRefAnchorText,
+ getDocCreateTemplatePath,
+ newFileByRefHint,
+ newFileInProtyle
+} from "../../util/newFile";
import {isAbnormalItem, upDownHint} from "../../util/upDownHint";
import {setPosition} from "../../util/setPosition";
import {getContenteditableElement, hasNextSibling, hasPreviousSibling} from "../wysiwyg/getBlock";
@@ -714,22 +719,25 @@ ${genHintItemHTML(item)}
} else if (value === Constants.ZWSP + 6) {
// 新建子文档
const newSubDocId = Lute.NewNodeID();
- fetchPost("/api/filetree/createDoc", {
- notebook: protyle.notebookId,
- path: pathPosix().join(getDisplayName(protyle.path, false, true), newSubDocId + ".sy"),
- title: "",
- md: ""
- }, () => {
- insertHTML(`<span data-type="block-ref" data-id="${newSubDocId}" data-subtype="d">${getBlockRefAnchorText("")}</span>`, protyle);
- /// #if MOBILE
- openMobileFileById(protyle.app, newSubDocId, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);
- /// #else
- openFileById({
- app: protyle.app,
- id: newSubDocId,
- action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]
+ getDocCreateTemplatePath(protyle.notebookId, (docCreateTemplatePath) => {
+ fetchPost("/api/filetree/createDoc", {
+ notebook: protyle.notebookId,
+ path: pathPosix().join(getDisplayName(protyle.path, false, true), newSubDocId + ".sy"),
+ title: "",
+ md: "",
+ docCreateTemplatePath,
+ }, () => {
+ insertHTML(`<span data-type="block-ref" data-id="${newSubDocId}" data-subtype="d">${getBlockRefAnchorText("")}</span>`, protyle);
+ /// #if MOBILE
+ openMobileFileById(protyle.app, newSubDocId, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);
+ /// #else
+ openFileById({
+ app: protyle.app,
+ id: newSubDocId,
+ action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]
+ });
+ /// #endif
});
- /// #endif
});
return;
} else if (value === Constants.ZWSP + 5) {
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 3b75dbf57b..a7626a2ee4 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -806,6 +806,10 @@ declare namespace Config {
* The storage path of the new document
*/
docCreateSavePath: string;
+ /**
+ * The content template path of the new document
+ */
+ docCreateTemplatePath: string;
/**
* The maximum number of documents listed
*/
diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.ts
index ed1d969eb9..c8fc5f5056 100644
--- a/app/src/util/newFile.ts
+++ b/app/src/util/newFile.ts
@@ -194,9 +194,10 @@ function getNewFilePath(): Pick<NewDocRequest, "notebookId" | "currentPath" | "h
function runNewDoc(request: NewDocRequest) {
fetchPost("/api/filetree/getDocCreateSavePath", {notebook: request.notebookId}, (savePathResponse) => {
const templatePath = savePathResponse.data.path as string;
+ const docCreateTemplatePath = savePathResponse.data.docCreateTemplatePath as string;
const targetNotebookId = savePathResponse.data.box as string;
getNewDocHPath(targetNotebookId, request.notebookId, request.currentPath, (hPath) => {
- createNewDoc(request, templatePath, targetNotebookId, hPath);
+ createNewDoc(request, templatePath, docCreateTemplatePath, targetNotebookId, hPath);
});
});
}
@@ -215,7 +216,8 @@ function getNewDocHPath(targetNotebookId: string, currentNotebookId: string, cur
});
}
-function createNewDoc(request: NewDocRequest, templatePath: string, targetNotebookId: string, hPath: string) {
+function createNewDoc(request: NewDocRequest, templatePath: string, docCreateTemplatePath: string,
+ targetNotebookId: string, hPath: string) {
const target = getNewDocTargetFromSavePath({
templatePath,
hPath: hPath || "/",
@@ -226,9 +228,9 @@ function createNewDoc(request: NewDocRequest, templatePath: string, targetNotebo
currentPath: request.currentPath,
});
if (target.kind === "hPath") {
- createNewDocByHPath(request, target);
+ createNewDocByHPath(request, target, docCreateTemplatePath);
} else if (target.kind === "subDoc") {
- createNewDocAsSubDoc(request, target);
+ createNewDocAsSubDoc(request, target, docCreateTemplatePath);
}
}
@@ -240,7 +242,7 @@ function runNewDocInTree(request: NewDocRequest) {
currentPath: request.currentPath,
name: request.name,
});
- createNewDocAsSubDoc(request, target);
+ createNewDocAsSubDoc(request, target, savePathResponse.data.docCreateTemplatePath as string);
});
}
@@ -251,7 +253,7 @@ function getCreateDocParentID(hasFocusTarget: boolean, notebookId: string, curre
: undefined;
}
-function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPath) {
+function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPath, docCreateTemplatePath: string) {
if (target.title && !validateName(target.title)) {
return;
}
@@ -262,12 +264,13 @@ function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPath
parentID,
markdown: "",
titleEmpty: !target.title,
+ docCreateTemplatePath,
}, (response) => {
openCreatedDoc(request.app, response.data, request.onCreated, target.title);
});
}
-function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc) {
+function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc, docCreateTemplatePath: string) {
const id = Lute.NewNodeID();
const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");
if (request.paths) {
@@ -278,6 +281,7 @@ function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc
path: newPath,
title: target.title,
md: "",
+ docCreateTemplatePath,
sorts: request.paths,
listDocTree: request.listDocTree,
}, () => {
@@ -285,6 +289,12 @@ function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc
});
}
+export const getDocCreateTemplatePath = (notebookId: string, callback: (templatePath: string) => void) => {
+ fetchPost("/api/filetree/getDocCreateSavePath", {notebook: notebookId}, (response) => {
+ callback(response.data.docCreateTemplatePath as string);
+ });
+};
+
function openCreatedDoc(app: App, id: string, onCreated?: (id: string, title: string) => void, title?: string) {
if (onCreated) {
onCreated(id, title || "");
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 403c168c3f..900d18de3c 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1004,10 +1004,14 @@ func getDocCreateSavePath(c *gin.Context) {
box := model.Conf.Box(notebook)
var docCreateSaveBox string
docCreateSavePathTpl := model.Conf.FileTree.DocCreateSavePath
+ docCreateTemplatePath := model.Conf.FileTree.DocCreateTemplatePath
if nil != box {
boxConf := box.GetConf()
docCreateSaveBox = boxConf.DocCreateSaveBox
docCreateSavePathTpl = boxConf.DocCreateSavePath
+ if "" != boxConf.DocCreateTemplatePath {
+ docCreateTemplatePath = boxConf.DocCreateTemplatePath
+ }
}
if "" == docCreateSaveBox && "" == docCreateSavePathTpl {
docCreateSaveBox = model.Conf.FileTree.DocCreateSaveBox
@@ -1041,8 +1045,9 @@ func getDocCreateSavePath(c *gin.Context) {
}
ret.Data = map[string]any{
- "box": docCreateSaveBox,
- "path": docCreateSavePath,
+ "box": docCreateSaveBox,
+ "path": docCreateSavePath,
+ "docCreateTemplatePath": docCreateTemplatePath,
}
}
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index 54f4ec56c4..fbfad84fcc 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -393,6 +393,7 @@ func setNotebookConf(c *gin.Context) {
boxConf.BoxCrypt = savedBoxCrypt
boxConf.DocCreateSavePath = util.TrimSpaceInPath(boxConf.DocCreateSavePath)
+ boxConf.DocCreateTemplatePath = util.NormalizeTemplatePath(boxConf.DocCreateTemplatePath)
boxConf.RefCreateSavePath = util.TrimSpaceInPath(boxConf.RefCreateSavePath)
@@ -408,15 +409,7 @@ func setNotebookConf(c *gin.Context) {
return
}
- boxConf.DailyNoteTemplatePath = util.TrimSpaceInPath(boxConf.DailyNoteTemplatePath)
- if "" != boxConf.DailyNoteTemplatePath {
- if !strings.HasSuffix(boxConf.DailyNoteTemplatePath, ".md") {
- boxConf.DailyNoteTemplatePath += ".md"
- }
- if !strings.HasPrefix(boxConf.DailyNoteTemplatePath, "/") {
- boxConf.DailyNoteTemplatePath = "/" + boxConf.DailyNoteTemplatePath
- }
- }
+ boxConf.DailyNoteTemplatePath = util.NormalizeTemplatePath(boxConf.DailyNoteTemplatePath)
if err := box.SaveConf(boxConf); err != nil {
ret.Code = -1
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index b93168daa8..67b1ba5d00 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -538,6 +538,7 @@ func setFiletree(c *gin.Context) {
oldBoxDocEnabled := model.IsBoxDocEnabled()
fileTree.DocCreateSavePath = util.TrimSpaceInPath(fileTree.DocCreateSavePath)
+ fileTree.DocCreateTemplatePath = util.NormalizeTemplatePath(fileTree.DocCreateTemplatePath)
fileTree.RefCreateSavePath = util.TrimSpaceInPath(fileTree.RefCreateSavePath)
diff --git a/kernel/conf/box.go b/kernel/conf/box.go
index b59f9b8d6d..6282488ac3 100644
--- a/kernel/conf/box.go
+++ b/kernel/conf/box.go
@@ -28,6 +28,7 @@ type BoxConf struct {
RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径
DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本
DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径
+ DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径
DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径
DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径
SortMode int `json:"sortMode"` // 排序方式
diff --git a/kernel/conf/filetree.go b/kernel/conf/filetree.go
index ad3a27c6d2..773522bfc4 100644
--- a/kernel/conf/filetree.go
+++ b/kernel/conf/filetree.go
@@ -30,6 +30,7 @@ type FileTree struct {
RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径
DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本
DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径
+ DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径
ShorthandSaveBox string `json:"shorthandSaveBox"` // 闪念速记存储笔记本
ShorthandSavePath string `json:"shorthandSavePath"` // 闪念速记存储路径
MaxListCount int `json:"maxListCount"` // 最大列出数量
diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.go
index 298b25729b..6417261dc5 100644
--- a/kernel/model/attribute_view_new_item.go
+++ b/kernel/model/attribute_view_new_item.go
@@ -19,16 +19,13 @@ package model
import (
"errors"
"fmt"
- "os"
"path"
- "path/filepath"
"strings"
"sync"
"time"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
- "github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -569,77 +566,7 @@ func buildNewItemFieldValueOperations(attrView *av.AttributeView, fieldValues ma
}
func applyNewItemContentTemplate(templatePath, docID string) error {
- absPath, err := resolveNewItemContentTemplatePath(templatePath)
- if nil != err {
- return err
- }
- templateTree, templateDOM, err := RenderTemplate(absPath, docID, false)
- if nil != err {
- return err
- }
- if "" == templateDOM {
- return nil
- }
- tree, err := LoadTreeByBlockID(docID)
- if nil != err {
- return err
- }
- if nil != tree.Root.FirstChild {
- tree.Root.FirstChild.Unlink()
- }
- newTree := util.NewLute().BlockDOM2Tree(templateDOM)
- var children []*ast.Node
- for child := newTree.Root.FirstChild; nil != child; child = child.Next {
- children = append(children, child)
- }
- for _, child := range children {
- tree.Root.AppendChild(child)
- }
- templateIALs := parse.IAL2Map(templateTree.Root.KramdownIAL)
- for key, value := range templateIALs {
- if "name" == key || "alias" == key || "bookmark" == key || "memo" == key || "icon" == key || strings.HasPrefix(key, "custom-") {
- tree.Root.SetIALAttr(key, value)
- }
- }
- tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
- if err = indexWriteTreeUpsertQueue(tree); nil != err {
- return err
- }
- FlushTxQueue()
- return nil
-}
-
-func resolveNewItemContentTemplatePath(templatePath string) (string, error) {
- cleanPath := filepath.Clean(filepath.FromSlash(strings.TrimSpace(templatePath)))
- if "" == cleanPath || "." == cleanPath || filepath.IsAbs(cleanPath) || ".." == cleanPath || strings.HasPrefix(cleanPath, ".."+string(os.PathSeparator)) {
- return "", errors.New("invalid content template path")
- }
- templateRoot := filepath.Join(util.DataDir, "templates")
- absPath := filepath.Join(templateRoot, cleanPath)
- rel, err := filepath.Rel(templateRoot, absPath)
- if nil != err || ".." == rel || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
- return "", errors.New("content template path is outside templates directory")
- }
- if !filelock.IsExist(absPath) {
- return "", fmt.Errorf("content template [%s] not found", templatePath)
- }
- realRoot, err := filepath.EvalSymlinks(templateRoot)
- if nil != err {
- return "", err
- }
- realPath, err := filepath.EvalSymlinks(absPath)
- if nil != err {
- return "", err
- }
- info, err := os.Stat(realPath)
- if nil != err || !info.Mode().IsRegular() {
- return "", fmt.Errorf("content template [%s] is not a regular file", templatePath)
- }
- realRel, err := filepath.Rel(realRoot, realPath)
- if nil != err || ".." == realRel || strings.HasPrefix(realRel, ".."+string(os.PathSeparator)) {
- return "", errors.New("content template path is outside templates directory")
- }
- return realPath, nil
+ return applyDocContentTemplateAfterIndex(templatePath, docID)
}
func removeCreatedNewItemDoc(docID string) error {
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index ac23661cfc..ac3e990a1b 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -325,6 +325,7 @@ func InitConf() {
Conf.FileTree.MaxOpenTabCount = 32
}
Conf.FileTree.DocCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.DocCreateSavePath)
+ Conf.FileTree.DocCreateTemplatePath = util.NormalizeTemplatePath(Conf.FileTree.DocCreateTemplatePath)
Conf.FileTree.RefCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.RefCreateSavePath)
Conf.FileTree.ShorthandSavePath = util.TrimSpaceInPath(Conf.FileTree.ShorthandSavePath)
util.UseSingleLineSave = Conf.FileTree.UseSingleLineSave
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 68a59a2d79..aa17459000 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1255,6 +1255,7 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]an
}
FlushTxQueue()
+ applyRequestedDocCreateTemplate(arg, md, tree.Root.ID)
PushCreate(box, p, arg)
return
}
@@ -1310,10 +1311,25 @@ func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bo
box.setSortByConf(path.Dir(bt.Path), retID)
FlushTxQueue()
+ applyRequestedDocCreateTemplate(arg, md, retID)
PushCreate(box, bt.Path, arg)
return
}
+func applyRequestedDocCreateTemplate(arg map[string]any, markdown, docID string) {
+ if nil == arg || "" != strings.TrimSpace(markdown) {
+ return
+ }
+ templatePath, _ := arg["docCreateTemplatePath"].(string)
+ if "" == strings.TrimSpace(templatePath) {
+ return
+ }
+ if err := applyDocContentTemplateAfterIndex(templatePath, docID); nil != err {
+ logging.LogWarnf("apply document creation template [%s] failed: %s", templatePath, err)
+ util.PushErrMsg(err.Error(), 7000)
+ }
+}
+
const (
DailyNoteAttrPrefix = "custom-dailynote-"
NodeAttrTitleEmpty = "custom-sy-title-empty"
@@ -1370,48 +1386,10 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {
return
}
- var templateTree *parse.Tree
- var templateDom string
if "" != boxConf.DailyNoteTemplatePath {
- tplPath := filepath.Join(util.DataDir, "templates", boxConf.DailyNoteTemplatePath)
- if !filelock.IsExist(tplPath) {
- logging.LogWarnf("not found daily note template [%s]", tplPath)
- } else {
- var renderErr error
- templateTree, templateDom, renderErr = RenderTemplate(tplPath, id, false)
- if nil != renderErr {
- logging.LogWarnf("render daily note template [%s] failed: %s", boxConf.DailyNoteTemplatePath, err)
- }
- }
- }
- if "" != templateDom {
- var tree *parse.Tree
- tree, err = LoadTreeByBlockID(id)
- if err == nil {
- tree.Root.FirstChild.Unlink()
-
- luteEngine := util.NewLute()
- newTree := luteEngine.BlockDOM2Tree(templateDom)
- var children []*ast.Node
- for c := newTree.Root.FirstChild; nil != c; c = c.Next {
- children = append(children, c)
- }
- for _, c := range children {
- tree.Root.AppendChild(c)
- }
-
- // Creating a dailynote template supports doc attributes https://github.com/siyuan-note/siyuan/issues/10698
- templateIALs := parse.IAL2Map(templateTree.Root.KramdownIAL)
- for k, v := range templateIALs {
- if "name" == k || "alias" == k || "bookmark" == k || "memo" == k || "icon" == k || strings.HasPrefix(k, "custom-") {
- tree.Root.SetIALAttr(k, v)
- }
- }
-
- tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
- if err = indexWriteTreeUpsertQueue(tree); err != nil {
- return
- }
+ sql.FlushQueue()
+ if renderErr := applyDocContentTemplate(boxConf.DailyNoteTemplatePath, id); nil != renderErr {
+ logging.LogWarnf("render daily note template [%s] failed: %s", boxConf.DailyNoteTemplatePath, renderErr)
}
}
IncSync()
@@ -1429,6 +1407,9 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {
if err = indexWriteTreeUpsertQueue(tree); err != nil {
return
}
+ if "" != boxConf.DailyNoteTemplatePath {
+ sql.FlushQueue()
+ }
return
}
diff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.go
index 27411bb6df..095f8f22df 100644
--- a/kernel/model/file_index_test.go
+++ b/kernel/model/file_index_test.go
@@ -31,6 +31,7 @@ import (
)
const removeDocSQLTestEnv = "SIYUAN_TEST_REMOVE_DOC_SQL"
+const docTemplateSQLTestEnv = "SIYUAN_TEST_DOC_TEMPLATE_SQL"
func TestRemoveDocFlushesDatabaseIndex(t *testing.T) {
if "1" != os.Getenv(removeDocSQLTestEnv) {
@@ -92,6 +93,111 @@ func TestRemoveDocFlushesDatabaseIndex(t *testing.T) {
assertDatabaseBlockExists(t, tree.ID, false)
}
+func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {
+ if "1" != os.Getenv(docTemplateSQLTestEnv) {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestDocumentTemplatesWaitForDatabaseIndex$", "-test.v")
+ cmd.Env = append(os.Environ(), docTemplateSQLTestEnv+"=1")
+ output, err := cmd.CombinedOutput()
+ if nil != err {
+ t.Fatalf("document template SQL subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+
+ workspaceDir := t.TempDir()
+ util.WorkspaceDir = workspaceDir
+ util.ConfDir = filepath.Join(workspaceDir, "conf")
+ util.DataDir = filepath.Join(workspaceDir, "data")
+ util.HistoryDir = filepath.Join(workspaceDir, "history")
+ util.TempDir = filepath.Join(workspaceDir, "temp")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.ConfDir, util.DataDir, util.HistoryDir, util.TempDir, util.QueueDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatalf("create test directory [%s] failed: %v", dir, err)
+ }
+ }
+
+ Conf = NewAppConf()
+ Conf.FileTree = conf.NewFileTree()
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ Conf.Lang = "en"
+ util.WorkingDir = filepath.Clean(filepath.Join("..", "..", "app"))
+ initLang()
+
+ box := &Box{ID: "20260728000000-abcdefg"}
+ boxConf := conf.NewBoxConf()
+ boxConf.Name = "Document template SQL test"
+ boxConf.Closed = false
+ boxConf.DailyNoteSavePath = "/Daily note"
+ boxConf.DailyNoteTemplatePath = "/indexed.md"
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatalf("save test notebook conf failed: %v", err)
+ }
+ templateDir := filepath.Join(util.DataDir, "templates")
+ if err := os.MkdirAll(templateDir, 0755); err != nil {
+ t.Fatalf("create templates directory failed: %v", err)
+ }
+ template := `.action{range queryBlocks "SELECT * FROM blocks WHERE id = '?' LIMIT 1" .id}.action{.ID}.action{end}`
+ if err := os.WriteFile(filepath.Join(templateDir, "indexed.md"), []byte(template), 0644); err != nil {
+ t.Fatalf("write test template failed: %v", err)
+ }
+
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+
+ dailyPath, existed, err := CreateDailyNote(box.ID)
+ if nil != err {
+ t.Fatalf("create daily note failed: %v", err)
+ }
+ if existed {
+ t.Fatal("the first daily note creation should not reuse an existing document")
+ }
+ dailyID := util.GetTreeID(dailyPath)
+ assertTemplateOutputIndexed(t, dailyID)
+
+ docID := "20260728000001-abcdefg"
+ arg := map[string]any{"docCreateTemplatePath": "/indexed.md"}
+ createdID, err := CreateWithMarkdown("", box.ID, "/Default template", "", "", docID, false, "", arg)
+ if nil != err {
+ t.Fatalf("create document with default template failed: %v", err)
+ }
+ if docID != createdID {
+ t.Fatalf("unexpected created document ID: got %s, want %s", createdID, docID)
+ }
+ assertTemplateOutputIndexed(t, docID)
+
+ attributeViewDocID := "20260728000002-abcdefg"
+ createdID, err = CreateWithMarkdown("", box.ID, "/Attribute view template", "", "", attributeViewDocID, false, "", nil)
+ if nil != err {
+ t.Fatalf("create attribute view item document failed: %v", err)
+ }
+ if err = applyNewItemContentTemplate("/indexed.md", createdID); nil != err {
+ t.Fatalf("apply attribute view item content template failed: %v", err)
+ }
+ assertTemplateOutputIndexed(t, attributeViewDocID)
+}
+
+func assertTemplateOutputIndexed(t *testing.T, docID string) {
+ t.Helper()
+
+ blocks := sql.SelectBlocksRawStmt("SELECT * FROM blocks WHERE root_id = '"+docID+"' AND type = 'p'", 1, 32)
+ for _, block := range blocks {
+ if docID == block.Content {
+ return
+ }
+ }
+ t.Fatalf("template did not query and persist the indexed document [%s]", docID)
+}
+
func assertDatabaseBlockExists(t *testing.T, id string, expected bool) {
t.Helper()
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 23302acccc..df2aa29c23 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -273,6 +273,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
}
boxConf.RefCreateSavePath = importedBoxConf.RefCreateSavePath
boxConf.DocCreateSavePath = importedBoxConf.DocCreateSavePath
+ boxConf.DocCreateTemplatePath = importedBoxConf.DocCreateTemplatePath
boxConf.DailyNoteSavePath = importedBoxConf.DailyNoteSavePath
boxConf.DailyNoteTemplatePath = importedBoxConf.DailyNoteTemplatePath
boxConf.SortMode = importedBoxConf.SortMode
diff --git a/kernel/model/template.go b/kernel/model/template.go
index a49ac8020c..ad35c82474 100644
--- a/kernel/model/template.go
+++ b/kernel/model/template.go
@@ -610,6 +610,88 @@ func addBlockIALNodes(tree *parse.Tree, removeUpdated bool) {
}
}
+func applyDocContentTemplateAfterIndex(templatePath, docID string) error {
+ sql.FlushQueue()
+ if err := applyDocContentTemplate(templatePath, docID); nil != err {
+ return err
+ }
+ sql.FlushQueue()
+ return nil
+}
+
+func applyDocContentTemplate(templatePath, docID string) error {
+ absPath, err := resolveDocContentTemplatePath(templatePath)
+ if nil != err {
+ return err
+ }
+ templateTree, templateDOM, err := RenderTemplate(absPath, docID, false)
+ if nil != err {
+ return err
+ }
+ if "" == templateDOM {
+ return nil
+ }
+ tree, err := LoadTreeByBlockID(docID)
+ if nil != err {
+ return err
+ }
+ if nil != tree.Root.FirstChild {
+ tree.Root.FirstChild.Unlink()
+ }
+ newTree := util.NewLute().BlockDOM2Tree(templateDOM)
+ var children []*ast.Node
+ for child := newTree.Root.FirstChild; nil != child; child = child.Next {
+ children = append(children, child)
+ }
+ for _, child := range children {
+ tree.Root.AppendChild(child)
+ }
+ templateIALs := parse.IAL2Map(templateTree.Root.KramdownIAL)
+ for key, value := range templateIALs {
+ if "name" == key || "alias" == key || "bookmark" == key || "memo" == key || "icon" == key ||
+ strings.HasPrefix(key, "custom-") {
+ tree.Root.SetIALAttr(key, value)
+ }
+ }
+ tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
+ return indexWriteTreeUpsertQueue(tree)
+}
+
+func resolveDocContentTemplatePath(templatePath string) (string, error) {
+ templatePath = strings.TrimPrefix(filepath.ToSlash(strings.TrimSpace(templatePath)), "/")
+ cleanPath := filepath.Clean(filepath.FromSlash(templatePath))
+ if "" == cleanPath || "." == cleanPath || filepath.IsAbs(cleanPath) || ".." == cleanPath ||
+ strings.HasPrefix(cleanPath, ".."+string(os.PathSeparator)) {
+ return "", errors.New("invalid content template path")
+ }
+ templateRoot := filepath.Join(util.DataDir, "templates")
+ absPath := filepath.Join(templateRoot, cleanPath)
+ rel, err := filepath.Rel(templateRoot, absPath)
+ if nil != err || ".." == rel || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
+ return "", errors.New("content template path is outside templates directory")
+ }
+ if !filelock.IsExist(absPath) {
+ return "", fmt.Errorf("content template [%s] not found", templatePath)
+ }
+ realRoot, err := filepath.EvalSymlinks(templateRoot)
+ if nil != err {
+ return "", err
+ }
+ realPath, err := filepath.EvalSymlinks(absPath)
+ if nil != err {
+ return "", err
+ }
+ info, err := os.Stat(realPath)
+ if nil != err || !info.Mode().IsRegular() {
+ return "", fmt.Errorf("content template [%s] is not a regular file", templatePath)
+ }
+ realRel, err := filepath.Rel(realRoot, realPath)
+ if nil != err || ".." == realRel || strings.HasPrefix(realRel, ".."+string(os.PathSeparator)) {
+ return "", errors.New("content template path is outside templates directory")
+ }
+ return realPath, nil
+}
+
// CreateTemplate 在 <data>/templates/ 下创建模板文件。name 不含扩展名,content 为 markdown 文本。
// overwrite=false 且文件已存在时返回 code=1(与 DocSaveAsTemplate 一致)。
func CreateTemplate(name, content string, overwrite bool) (code int, err error) {
diff --git a/kernel/util/path.go b/kernel/util/path.go
index fff1bde6b1..717a9bd4f9 100644
--- a/kernel/util/path.go
+++ b/kernel/util/path.go
@@ -53,6 +53,20 @@ func TrimSpaceInPath(p string) string {
return strings.Join(parts, "/")
}
+func NormalizeTemplatePath(p string) string {
+ p = TrimSpaceInPath(p)
+ if "" == p {
+ return ""
+ }
+ if !strings.HasSuffix(p, ".md") {
+ p += ".md"
+ }
+ if !strings.HasPrefix(p, "/") {
+ p = "/" + p
+ }
+ return p
+}
+
func GetTreeID(treePath string) string {
base := path.Base(strings.ReplaceAll(treePath, "\\", "/"))
return strings.TrimSuffix(base, ".sy")