A privacy-first, self-hosted, fully open source personal knowledge management software, written in typescript and golang. (PERSONAL FORK)
1// SiYuan - Refactor your thinking
2// Copyright (c) 2020-present, b3log.org
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU Affero General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU Affero General Public License for more details.
13//
14// You should have received a copy of the GNU Affero General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17package model
18
19import (
20 "bytes"
21 "errors"
22 "fmt"
23 "io/fs"
24 "os"
25 "path/filepath"
26 "sort"
27 "strings"
28 "text/template"
29
30 "github.com/88250/gulu"
31 "github.com/88250/lute/ast"
32 "github.com/88250/lute/parse"
33 "github.com/88250/lute/render"
34 "github.com/siyuan-note/filelock"
35 "github.com/siyuan-note/logging"
36 "github.com/siyuan-note/siyuan/kernel/av"
37 "github.com/siyuan-note/siyuan/kernel/filesys"
38 "github.com/siyuan-note/siyuan/kernel/search"
39 "github.com/siyuan-note/siyuan/kernel/sql"
40 "github.com/siyuan-note/siyuan/kernel/treenode"
41 "github.com/siyuan-note/siyuan/kernel/util"
42 "github.com/xrash/smetrics"
43)
44
45func RenderGoTemplate(templateContent string) (ret string, err error) {
46 tmpl := template.New("")
47 tplFuncMap := filesys.BuiltInTemplateFuncs()
48 sql.SQLTemplateFuncs(&tplFuncMap)
49 tmpl = tmpl.Funcs(tplFuncMap)
50 tpl, err := tmpl.Parse(templateContent)
51 if err != nil {
52 return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
53 }
54
55 buf := &bytes.Buffer{}
56 buf.Grow(4096)
57 err = tpl.Execute(buf, nil)
58 if err != nil {
59 return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
60 }
61 ret = buf.String()
62 return
63}
64
65func RemoveTemplate(p string) (err error) {
66 err = filelock.Remove(p)
67 if err != nil {
68 logging.LogErrorf("remove template failed: %s", err)
69 }
70 return
71}
72
73func SearchTemplate(keyword string) (ret []*Block) {
74 ret = []*Block{}
75
76 templates := filepath.Join(util.DataDir, "templates")
77 if !util.IsPathRegularDirOrSymlinkDir(templates) {
78 return
79 }
80
81 groups, err := os.ReadDir(templates)
82 if err != nil {
83 logging.LogErrorf("read templates failed: %s", err)
84 return
85 }
86
87 sort.Slice(ret, func(i, j int) bool {
88 return util.PinYinCompare(filepath.Base(groups[i].Name()), filepath.Base(groups[j].Name()))
89 })
90
91 keyword = strings.TrimSpace(keyword)
92 type result struct {
93 block *Block
94 score float64
95 }
96 var results []*result
97 keywords := strings.Fields(keyword)
98 for _, group := range groups {
99 if strings.HasPrefix(group.Name(), ".") {
100 continue
101 }
102
103 if group.IsDir() {
104 templateDir := filepath.Join(templates, group.Name())
105 filelock.Walk(templateDir, func(path string, d fs.DirEntry, err error) error {
106 name := strings.ToLower(d.Name())
107 if strings.HasPrefix(name, ".") {
108 if d.IsDir() {
109 return filepath.SkipDir
110 }
111 return nil
112 }
113
114 if !strings.HasSuffix(name, ".md") || strings.HasPrefix(name, "readme") {
115 return nil
116 }
117
118 content := strings.TrimPrefix(path, templates)
119 content = strings.TrimSuffix(content, ".md")
120 p := filepath.Join(group.Name(), content)
121 score := 0.0
122 hit := true
123 for _, k := range keywords {
124 if strings.Contains(strings.ToLower(p), strings.ToLower(k)) {
125 score += smetrics.JaroWinkler(name, k, 0.7, 4)
126 } else {
127 hit = false
128 break
129 }
130 }
131 if hit {
132 content = strings.TrimPrefix(path, templates)
133 content = strings.TrimSuffix(content, ".md")
134 content = filepath.ToSlash(content)
135 _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.CaseSensitive)
136 b := &Block{Path: path, Content: content}
137 results = append(results, &result{block: b, score: score})
138 }
139 return nil
140 })
141 } else {
142 name := strings.ToLower(group.Name())
143 if strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".md") || "readme.md" == name {
144 continue
145 }
146
147 content := group.Name()
148 content = strings.TrimSuffix(content, ".md")
149 score := 0.0
150 hit := true
151 for _, k := range keywords {
152 if strings.Contains(strings.ToLower(content), strings.ToLower(k)) {
153 score += smetrics.JaroWinkler(name, k, 0.7, 4)
154 } else {
155 hit = false
156 break
157 }
158 }
159 if hit {
160 content = filepath.ToSlash(content)
161 _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.CaseSensitive)
162 b := &Block{Path: filepath.Join(templates, group.Name()), Content: content}
163 results = append(results, &result{block: b, score: score})
164 }
165 }
166 }
167
168 sort.Slice(results, func(i, j int) bool {
169 return results[i].score > results[j].score
170 })
171 for _, r := range results {
172 ret = append(ret, r.block)
173 }
174 return
175}
176
177func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error) {
178 bt := treenode.GetBlockTree(id)
179 if nil == bt {
180 return
181 }
182
183 tree := prepareExportTree(bt)
184 addBlockIALNodes(tree, true)
185
186 ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
187 if !entering {
188 return ast.WalkContinue
189 }
190
191 // Content in templates is not properly escaped
192 // https://github.com/siyuan-note/siyuan/issues/9649
193 // https://github.com/siyuan-note/siyuan/issues/13701
194 switch n.Type {
195 case ast.NodeCodeBlockCode:
196 n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("""), []byte("\""))
197 case ast.NodeCodeSpanContent:
198 n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("""), []byte("\""))
199 case ast.NodeBlockQueryEmbedScript:
200 n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("""), []byte("\""))
201 case ast.NodeTextMark:
202 if n.IsTextMarkType("code") {
203 n.TextMarkTextContent = strings.ReplaceAll(n.TextMarkTextContent, """, "\"")
204 }
205 }
206 return ast.WalkContinue
207 })
208
209 var unlinks []*ast.Node
210 ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
211 if !entering {
212 return ast.WalkContinue
213 }
214
215 if ast.NodeCodeBlockFenceInfoMarker == n.Type {
216 if lang := string(n.CodeBlockInfo); "siyuan-template" == lang || "template" == lang {
217 // 将模板代码转换为段落文本 https://github.com/siyuan-note/siyuan/pull/15345
218 unlinks = append(unlinks, n.Parent)
219 p := treenode.NewParagraph(n.Parent.ID)
220 // 代码块内可能会有多个空行,但是这里不需要分块处理,后面渲染一个文本节点即可
221 p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: n.Next.Tokens})
222 n.Parent.InsertBefore(p)
223 }
224 }
225 return ast.WalkContinue
226 })
227 for _, n := range unlinks {
228 n.Unlink()
229 }
230
231 luteEngine := NewLute()
232 formatRenderer := render.NewFormatRenderer(tree, luteEngine.RenderOptions)
233 md := formatRenderer.Render()
234
235 // 单独渲染根节点的 IAL
236 if 0 < len(tree.Root.KramdownIAL) {
237 // 把 docIAL 中的 id 调整到第一个
238 tree.Root.RemoveIALAttr("id")
239 tree.Root.KramdownIAL = append([][]string{{"id", tree.Root.ID}}, tree.Root.KramdownIAL...)
240 md = append(md, []byte("\n")...)
241 md = append(md, parse.IAL2Tokens(tree.Root.KramdownIAL)...)
242 }
243
244 name = util.FilterFileName(name) + ".md"
245 name = util.TruncateLenFileName(name)
246 savePath := filepath.Join(util.DataDir, "templates", name)
247 if filelock.IsExist(savePath) {
248 if !overwrite {
249 code = 1
250 return
251 }
252 }
253
254 err = filelock.WriteFile(savePath, md)
255 return
256}
257
258func RenderDynamicIconContentTemplate(content, id string) (ret string) {
259 tree, err := LoadTreeByBlockID(id)
260 if err != nil {
261 return
262 }
263
264 node := treenode.GetNodeInTree(tree, id)
265 if nil == node {
266 return
267 }
268 block := sql.BuildBlockFromNode(node, tree)
269 if nil == block {
270 return
271 }
272
273 dataModel := map[string]string{}
274 title := block.Name
275 if "d" == block.Type {
276 title = block.Content
277 }
278 dataModel["title"] = title
279 dataModel["id"] = block.ID
280 dataModel["name"] = block.Name
281 dataModel["alias"] = block.Alias
282
283 goTpl := template.New("").Delims(".action{", "}")
284 tplFuncMap := filesys.BuiltInTemplateFuncs()
285 sql.SQLTemplateFuncs(&tplFuncMap)
286 goTpl = goTpl.Funcs(tplFuncMap)
287 tpl, err := goTpl.Funcs(tplFuncMap).Parse(content)
288 if err != nil {
289 err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
290 return
291 }
292
293 buf := &bytes.Buffer{}
294 buf.Grow(4096)
295 if err = tpl.Execute(buf, dataModel); err != nil {
296 err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
297 return
298 }
299 ret = buf.String()
300 return
301}
302
303func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, err error) {
304 tree, err = LoadTreeByBlockID(id)
305 if err != nil {
306 return
307 }
308
309 node := treenode.GetNodeInTree(tree, id)
310 if nil == node {
311 err = ErrBlockNotFound
312 return
313 }
314 block := sql.BuildBlockFromNode(node, tree)
315 md, err := os.ReadFile(p)
316 if err != nil {
317 return
318 }
319
320 dataModel := map[string]string{}
321 var titleVar string
322 if nil != block {
323 titleVar = block.Name
324 if "d" == block.Type {
325 titleVar = block.Content
326 }
327 dataModel["title"] = titleVar
328 dataModel["id"] = block.ID
329 dataModel["name"] = block.Name
330 dataModel["alias"] = block.Alias
331 }
332
333 goTpl := template.New("").Delims(".action{", "}")
334 tplFuncMap := filesys.BuiltInTemplateFuncs()
335 sql.SQLTemplateFuncs(&tplFuncMap)
336 goTpl = goTpl.Funcs(tplFuncMap)
337 tpl, err := goTpl.Funcs(tplFuncMap).Parse(gulu.Str.FromBytes(md))
338 if err != nil {
339 err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
340 return
341 }
342
343 buf := &bytes.Buffer{}
344 buf.Grow(4096)
345 if err = tpl.Execute(buf, dataModel); err != nil {
346 err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
347 return
348 }
349 md = buf.Bytes()
350 tree = parseKTree(md)
351 if nil == tree {
352 msg := fmt.Sprintf("parse tree [%s] failed", p)
353 logging.LogErrorf(msg)
354 err = errors.New(msg)
355 return
356 }
357
358 var nodesNeedAppendChild, unlinks []*ast.Node
359 ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
360 if !entering {
361 return ast.WalkContinue
362 }
363
364 if "" != n.ID {
365 // 重新生成 ID
366 n.ID = ast.NewNodeID()
367 n.SetIALAttr("id", n.ID)
368 n.RemoveIALAttr(av.NodeAttrNameAvs)
369
370 // Blocks created via template update time earlier than creation time https://github.com/siyuan-note/siyuan/issues/8607
371 refreshUpdated(n)
372 }
373
374 if (ast.NodeListItem == n.Type && (nil == n.FirstChild ||
375 (3 == n.ListData.Typ && (nil == n.FirstChild.Next || ast.NodeKramdownBlockIAL == n.FirstChild.Next.Type)))) ||
376 (ast.NodeBlockquote == n.Type && nil != n.FirstChild && nil != n.FirstChild.Next && ast.NodeKramdownBlockIAL == n.FirstChild.Next.Type) {
377 nodesNeedAppendChild = append(nodesNeedAppendChild, n)
378 }
379
380 if n.IsTextMarkType("block-ref") {
381 if refText := n.Text(); "" == refText {
382 refText = strings.TrimSpace(sql.GetRefText(n.TextMarkBlockRefID))
383 if "" != refText {
384 treenode.SetDynamicBlockRefText(n, refText)
385 } else {
386 unlinks = append(unlinks, n)
387 }
388 }
389 } else if ast.NodeBlockRef == n.Type {
390 if refText := n.Text(); "" == refText {
391 if refID := n.ChildByType(ast.NodeBlockRefID); nil != refID {
392 refText = strings.TrimSpace(sql.GetRefText(refID.TokensStr()))
393 if "" != refText {
394 treenode.SetDynamicBlockRefText(n, refText)
395 } else {
396 unlinks = append(unlinks, n)
397 }
398 }
399 }
400 } else if n.IsTextMarkType("inline-math") {
401 if n.ParentIs(ast.NodeTableCell) {
402 // 表格中的公式中带有管道符时使用 HTML 实体替换管道符 Improve the handling of inline-math containing `|` in the table https://github.com/siyuan-note/siyuan/issues/9227
403 n.TextMarkInlineMathContent = strings.ReplaceAll(n.TextMarkInlineMathContent, "|", "|")
404 }
405 }
406
407 if ast.NodeAttributeView == n.Type {
408 // 重新生成数据库视图
409 attrView, parseErr := av.ParseAttributeView(n.AttributeViewID)
410 if nil != parseErr {
411 logging.LogErrorf("parse attribute view [%s] failed: %s", n.AttributeViewID, parseErr)
412 } else {
413 cloned := attrView.Clone()
414 if nil == cloned {
415 logging.LogErrorf("clone attribute view [%s] failed", n.AttributeViewID)
416 return ast.WalkContinue
417 }
418
419 n.AttributeViewID = cloned.ID
420 if !preview {
421 // 非预览时持久化数据库
422 if saveErr := av.SaveAttributeView(cloned); nil != saveErr {
423 logging.LogErrorf("save attribute view [%s] failed: %s", cloned.ID, saveErr)
424 }
425 } else {
426 // 预览时使用简单表格渲染
427 viewID := n.IALAttr(av.NodeAttrView)
428 view, getErr := attrView.GetCurrentView(viewID)
429 if nil != getErr {
430 logging.LogErrorf("get attribute view [%s] failed: %s", n.AttributeViewID, getErr)
431 return ast.WalkContinue
432 }
433
434 table := getAttrViewTable(attrView, view, "")
435
436 var aligns []int
437 for range table.Columns {
438 aligns = append(aligns, 0)
439 }
440 mdTable := &ast.Node{Type: ast.NodeTable, TableAligns: aligns}
441 mdTableHead := &ast.Node{Type: ast.NodeTableHead}
442 mdTable.AppendChild(mdTableHead)
443 mdTableHeadRow := &ast.Node{Type: ast.NodeTableRow, TableAligns: aligns}
444 mdTableHead.AppendChild(mdTableHeadRow)
445 for _, col := range table.Columns {
446 cell := &ast.Node{Type: ast.NodeTableCell}
447 cell.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(col.Name)})
448 mdTableHeadRow.AppendChild(cell)
449 }
450
451 n.InsertBefore(mdTable)
452 unlinks = append(unlinks, n)
453 }
454 }
455 }
456
457 return ast.WalkContinue
458 })
459 for _, n := range nodesNeedAppendChild {
460 if ast.NodeBlockquote == n.Type {
461 n.FirstChild.InsertAfter(treenode.NewParagraph(""))
462 } else {
463 n.AppendChild(treenode.NewParagraph(""))
464 }
465 }
466 for _, n := range unlinks {
467 n.Unlink()
468 }
469
470 // 折叠标题导出为模板后使用会出现内容重复 https://github.com/siyuan-note/siyuan/issues/4488
471 ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
472 if !entering {
473 return ast.WalkContinue
474 }
475
476 if "1" == n.IALAttr("heading-fold") { // 为标题折叠下方块添加属性,前端渲染以后会统一做移除处理
477 n.SetIALAttr("status", "temp")
478 }
479 return ast.WalkContinue
480 })
481
482 icon := tree.Root.IALAttr("icon")
483 if "" != icon {
484 // 动态图标需要反转义 https://github.com/siyuan-note/siyuan/issues/13211
485 icon = util.UnescapeHTML(icon)
486 tree.Root.SetIALAttr("icon", icon)
487 }
488
489 luteEngine := NewLute()
490 dom = luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions)
491 return
492}
493
494func addBlockIALNodes(tree *parse.Tree, removeUpdated bool) {
495 var blocks []*ast.Node
496 ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
497 if !entering || !n.IsBlock() {
498 return ast.WalkContinue
499 }
500
501 if ast.NodeBlockQueryEmbed == n.Type {
502 if script := n.ChildByType(ast.NodeBlockQueryEmbedScript); nil != script {
503 script.Tokens = bytes.ReplaceAll(script.Tokens, []byte("\n"), []byte(" "))
504 }
505 } else if ast.NodeHTMLBlock == n.Type {
506 n.Tokens = bytes.TrimSpace(n.Tokens)
507 // 使用 <div> 包裹,否则后续解析时会识别为行级 HTML https://github.com/siyuan-note/siyuan/issues/4244
508 if !bytes.HasPrefix(n.Tokens, []byte("<div>")) {
509 n.Tokens = append([]byte("<div>\n"), n.Tokens...)
510 }
511 if !bytes.HasSuffix(n.Tokens, []byte("</div>")) {
512 n.Tokens = append(n.Tokens, []byte("\n</div>")...)
513 }
514 }
515
516 if removeUpdated {
517 n.RemoveIALAttr("updated")
518 }
519 if 0 < len(n.KramdownIAL) {
520 blocks = append(blocks, n)
521 }
522 return ast.WalkContinue
523 })
524 for _, block := range blocks {
525 block.InsertAfter(&ast.Node{Type: ast.NodeKramdownBlockIAL, Tokens: parse.IAL2Tokens(block.KramdownIAL)})
526 }
527}