node.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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. package treenode
  17. import (
  18. "bytes"
  19. "github.com/siyuan-note/siyuan/kernel/av"
  20. "github.com/siyuan-note/siyuan/kernel/cache"
  21. "strings"
  22. "sync"
  23. "text/template"
  24. "time"
  25. "github.com/88250/gulu"
  26. "github.com/88250/lute"
  27. "github.com/88250/lute/ast"
  28. "github.com/88250/lute/editor"
  29. "github.com/88250/lute/html"
  30. "github.com/88250/lute/lex"
  31. "github.com/88250/lute/parse"
  32. "github.com/88250/lute/render"
  33. "github.com/88250/vitess-sqlparser/sqlparser"
  34. "github.com/siyuan-note/logging"
  35. "github.com/siyuan-note/siyuan/kernel/util"
  36. )
  37. func GetEmbedBlockRef(embedNode *ast.Node) (blockRefID string) {
  38. if nil == embedNode || ast.NodeBlockQueryEmbed != embedNode.Type {
  39. return
  40. }
  41. scriptNode := embedNode.ChildByType(ast.NodeBlockQueryEmbedScript)
  42. if nil == scriptNode {
  43. return
  44. }
  45. stmt := scriptNode.TokensStr()
  46. parsedStmt, err := sqlparser.Parse(stmt)
  47. if nil != err {
  48. return
  49. }
  50. switch parsedStmt.(type) {
  51. case *sqlparser.Select:
  52. slct := parsedStmt.(*sqlparser.Select)
  53. if nil == slct.Where || nil == slct.Where.Expr {
  54. return
  55. }
  56. switch slct.Where.Expr.(type) {
  57. case *sqlparser.ComparisonExpr: // WHERE id = '20060102150405-1a2b3c4'
  58. comp := slct.Where.Expr.(*sqlparser.ComparisonExpr)
  59. switch comp.Left.(type) {
  60. case *sqlparser.ColName:
  61. col := comp.Left.(*sqlparser.ColName)
  62. if nil == col || "id" != col.Name.Lowered() {
  63. return
  64. }
  65. }
  66. switch comp.Right.(type) {
  67. case *sqlparser.SQLVal:
  68. val := comp.Right.(*sqlparser.SQLVal)
  69. if nil == val || sqlparser.StrVal != val.Type {
  70. return
  71. }
  72. idVal := string(val.Val)
  73. if !ast.IsNodeIDPattern(idVal) {
  74. return
  75. }
  76. blockRefID = idVal
  77. }
  78. }
  79. }
  80. return
  81. }
  82. func GetBlockRef(n *ast.Node) (blockRefID, blockRefText, blockRefSubtype string) {
  83. if !IsBlockRef(n) {
  84. return
  85. }
  86. blockRefID = n.TextMarkBlockRefID
  87. blockRefText = n.TextMarkTextContent
  88. blockRefSubtype = n.TextMarkBlockRefSubtype
  89. return
  90. }
  91. func IsBlockRef(n *ast.Node) bool {
  92. if nil == n {
  93. return false
  94. }
  95. return ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref")
  96. }
  97. func IsFileAnnotationRef(n *ast.Node) bool {
  98. if nil == n {
  99. return false
  100. }
  101. return ast.NodeTextMark == n.Type && n.IsTextMarkType("file-annotation-ref")
  102. }
  103. func IsEmbedBlockRef(n *ast.Node) bool {
  104. return "" != GetEmbedBlockRef(n)
  105. }
  106. func FormatNode(node *ast.Node, luteEngine *lute.Lute) string {
  107. markdown, err := lute.FormatNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  108. if nil != err {
  109. root := TreeRoot(node)
  110. logging.LogFatalf(logging.ExitCodeFatal, "format node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  111. }
  112. return markdown
  113. }
  114. func ExportNodeStdMd(node *ast.Node, luteEngine *lute.Lute) string {
  115. markdown, err := lute.ProtyleExportMdNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  116. if nil != err {
  117. root := TreeRoot(node)
  118. logging.LogFatalf(logging.ExitCodeFatal, "export markdown for node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  119. }
  120. return markdown
  121. }
  122. func IsNodeOCRed(node *ast.Node) (ret bool) {
  123. if !util.TesseractEnabled || nil == node {
  124. return true
  125. }
  126. ret = true
  127. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  128. if !entering {
  129. return ast.WalkContinue
  130. }
  131. if ast.NodeImage == n.Type {
  132. linkDest := n.ChildByType(ast.NodeLinkDest)
  133. if nil == linkDest {
  134. return ast.WalkContinue
  135. }
  136. linkDestStr := linkDest.TokensStr()
  137. if !cache.ExistAsset(linkDestStr) {
  138. return ast.WalkContinue
  139. }
  140. if !util.ExistsAssetText(linkDestStr) {
  141. ret = false
  142. return ast.WalkStop
  143. }
  144. }
  145. return ast.WalkContinue
  146. })
  147. return
  148. }
  149. func NodeStaticContent(node *ast.Node, excludeTypes []string, includeTextMarkATitleURL, includeAssetPath bool) string {
  150. if nil == node {
  151. return ""
  152. }
  153. if ast.NodeDocument == node.Type {
  154. return node.IALAttr("title")
  155. }
  156. if ast.NodeAttributeView == node.Type {
  157. return getAttributeViewContent(node.AttributeViewID)
  158. }
  159. buf := bytes.Buffer{}
  160. buf.Grow(4096)
  161. lastSpace := false
  162. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  163. if !entering {
  164. return ast.WalkContinue
  165. }
  166. if n.IsContainerBlock() {
  167. if !lastSpace {
  168. buf.WriteByte(' ')
  169. lastSpace = true
  170. }
  171. return ast.WalkContinue
  172. }
  173. if gulu.Str.Contains(n.Type.String(), excludeTypes) {
  174. return ast.WalkContinue
  175. }
  176. switch n.Type {
  177. case ast.NodeTableCell:
  178. // 表格块写入数据库表时在单元格之间添加空格 https://github.com/siyuan-note/siyuan/issues/7654
  179. if 0 < buf.Len() && ' ' != buf.Bytes()[buf.Len()-1] {
  180. buf.WriteByte(' ')
  181. }
  182. case ast.NodeImage:
  183. linkDest := n.ChildByType(ast.NodeLinkDest)
  184. var linkDestStr, ocrText string
  185. if nil != linkDest {
  186. linkDestStr = linkDest.TokensStr()
  187. ocrText = util.GetAssetText(linkDestStr, false)
  188. }
  189. linkText := n.ChildByType(ast.NodeLinkText)
  190. if nil != linkText {
  191. buf.Write(linkText.Tokens)
  192. buf.WriteByte(' ')
  193. }
  194. if "" != ocrText {
  195. buf.WriteString(ocrText)
  196. buf.WriteByte(' ')
  197. }
  198. if nil != linkDest {
  199. if !bytes.HasPrefix(linkDest.Tokens, []byte("assets/")) || includeAssetPath {
  200. buf.Write(linkDest.Tokens)
  201. buf.WriteByte(' ')
  202. }
  203. }
  204. if linkTitle := n.ChildByType(ast.NodeLinkTitle); nil != linkTitle {
  205. buf.Write(linkTitle.Tokens)
  206. }
  207. return ast.WalkSkipChildren
  208. case ast.NodeLinkText:
  209. buf.Write(n.Tokens)
  210. buf.WriteByte(' ')
  211. case ast.NodeLinkDest:
  212. buf.Write(n.Tokens)
  213. buf.WriteByte(' ')
  214. case ast.NodeLinkTitle:
  215. buf.Write(n.Tokens)
  216. case ast.NodeText, ast.NodeCodeBlockCode, ast.NodeMathBlockContent, ast.NodeHTMLBlock:
  217. tokens := n.Tokens
  218. if IsChartCodeBlockCode(n) {
  219. // 图表块的内容在数据库 `blocks` 表 `content` 字段中被转义 https://github.com/siyuan-note/siyuan/issues/6326
  220. tokens = html.UnescapeHTML(tokens)
  221. }
  222. buf.Write(tokens)
  223. case ast.NodeTextMark:
  224. for _, excludeType := range excludeTypes {
  225. if strings.HasPrefix(excludeType, "NodeTextMark-") {
  226. if n.IsTextMarkType(excludeType[len("NodeTextMark-"):]) {
  227. return ast.WalkContinue
  228. }
  229. }
  230. }
  231. if n.IsTextMarkType("tag") {
  232. buf.WriteByte('#')
  233. }
  234. buf.WriteString(n.Content())
  235. if n.IsTextMarkType("tag") {
  236. buf.WriteByte('#')
  237. }
  238. if n.IsTextMarkType("a") && includeTextMarkATitleURL {
  239. // 搜索不到超链接元素的 URL 和标题 https://github.com/siyuan-note/siyuan/issues/7352
  240. if "" != n.TextMarkATitle {
  241. buf.WriteString(" " + html.UnescapeHTMLStr(n.TextMarkATitle))
  242. }
  243. if !strings.HasPrefix(n.TextMarkAHref, "assets/") || includeAssetPath {
  244. buf.WriteString(" " + html.UnescapeHTMLStr(n.TextMarkAHref))
  245. }
  246. }
  247. case ast.NodeBackslash:
  248. buf.WriteByte(lex.ItemBackslash)
  249. case ast.NodeBackslashContent:
  250. buf.Write(n.Tokens)
  251. }
  252. lastSpace = false
  253. return ast.WalkContinue
  254. })
  255. return strings.TrimSpace(buf.String())
  256. }
  257. func FirstLeafBlock(node *ast.Node) (ret *ast.Node) {
  258. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  259. if !entering || n.IsMarker() {
  260. return ast.WalkContinue
  261. }
  262. if !n.IsContainerBlock() {
  263. ret = n
  264. return ast.WalkStop
  265. }
  266. return ast.WalkContinue
  267. })
  268. return
  269. }
  270. func CountBlockNodes(node *ast.Node) (ret int) {
  271. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  272. if !entering || !n.IsBlock() || ast.NodeList == n.Type || ast.NodeBlockquote == n.Type || ast.NodeSuperBlock == n.Type {
  273. return ast.WalkContinue
  274. }
  275. if "1" == n.IALAttr("fold") {
  276. ret++
  277. return ast.WalkSkipChildren
  278. }
  279. ret++
  280. return ast.WalkContinue
  281. })
  282. return
  283. }
  284. func ParentNodes(node *ast.Node) (parents []*ast.Node) {
  285. const maxDepth = 256
  286. i := 0
  287. for n := node.Parent; nil != n; n = n.Parent {
  288. i++
  289. parents = append(parents, n)
  290. if ast.NodeDocument == n.Type {
  291. return
  292. }
  293. if maxDepth < i {
  294. logging.LogWarnf("parent nodes of node [%s] is too deep", node.ID)
  295. return
  296. }
  297. }
  298. return
  299. }
  300. func ChildBlockNodes(node *ast.Node) (children []*ast.Node) {
  301. children = []*ast.Node{}
  302. if !node.IsContainerBlock() || ast.NodeDocument == node.Type {
  303. children = append(children, node)
  304. return
  305. }
  306. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  307. if !entering || !n.IsBlock() {
  308. return ast.WalkContinue
  309. }
  310. children = append(children, n)
  311. return ast.WalkContinue
  312. })
  313. return
  314. }
  315. func ParentBlock(node *ast.Node) *ast.Node {
  316. for p := node.Parent; nil != p; p = p.Parent {
  317. if "" != p.ID && p.IsBlock() {
  318. return p
  319. }
  320. }
  321. return nil
  322. }
  323. func GetNodeInTree(tree *parse.Tree, id string) (ret *ast.Node) {
  324. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  325. if !entering {
  326. return ast.WalkContinue
  327. }
  328. if id == n.ID {
  329. ret = n
  330. ret.Box = tree.Box
  331. ret.Path = tree.Path
  332. return ast.WalkStop
  333. }
  334. return ast.WalkContinue
  335. })
  336. return
  337. }
  338. func GetDocTitleImgPath(root *ast.Node) (ret string) {
  339. if nil == root {
  340. return
  341. }
  342. const background = "background-image: url("
  343. titleImg := root.IALAttr("title-img")
  344. titleImg = strings.TrimSpace(titleImg)
  345. titleImg = html.UnescapeString(titleImg)
  346. titleImg = strings.ReplaceAll(titleImg, "background-image:url(", background)
  347. if !strings.Contains(titleImg, background) {
  348. return
  349. }
  350. start := strings.Index(titleImg, background) + len(background)
  351. end := strings.LastIndex(titleImg, ")")
  352. ret = titleImg[start:end]
  353. ret = strings.TrimPrefix(ret, "\"")
  354. ret = strings.TrimPrefix(ret, "'")
  355. ret = strings.TrimSuffix(ret, "\"")
  356. ret = strings.TrimSuffix(ret, "'")
  357. return ret
  358. }
  359. var typeAbbrMap = map[string]string{
  360. // 块级元素
  361. "NodeDocument": "d",
  362. "NodeHeading": "h",
  363. "NodeList": "l",
  364. "NodeListItem": "i",
  365. "NodeCodeBlock": "c",
  366. "NodeMathBlock": "m",
  367. "NodeTable": "t",
  368. "NodeBlockquote": "b",
  369. "NodeSuperBlock": "s",
  370. "NodeParagraph": "p",
  371. "NodeHTMLBlock": "html",
  372. "NodeBlockQueryEmbed": "query_embed",
  373. "NodeAttributeView": "av",
  374. "NodeKramdownBlockIAL": "ial",
  375. "NodeIFrame": "iframe",
  376. "NodeWidget": "widget",
  377. "NodeThematicBreak": "tb",
  378. "NodeVideo": "video",
  379. "NodeAudio": "audio",
  380. // 行级元素
  381. "NodeText": "text",
  382. "NodeImage": "img",
  383. "NodeLinkText": "link_text",
  384. "NodeLinkDest": "link_dest",
  385. "NodeTextMark": "textmark",
  386. }
  387. var abbrTypeMap = map[string]string{}
  388. func init() {
  389. for typ, abbr := range typeAbbrMap {
  390. abbrTypeMap[abbr] = typ
  391. }
  392. }
  393. func TypeAbbr(nodeType string) string {
  394. return typeAbbrMap[nodeType]
  395. }
  396. func FromAbbrType(abbrType string) string {
  397. return abbrTypeMap[abbrType]
  398. }
  399. func SubTypeAbbr(n *ast.Node) string {
  400. switch n.Type {
  401. case ast.NodeList, ast.NodeListItem:
  402. if 0 == n.ListData.Typ {
  403. return "u"
  404. }
  405. if 1 == n.ListData.Typ {
  406. return "o"
  407. }
  408. if 3 == n.ListData.Typ {
  409. return "t"
  410. }
  411. case ast.NodeHeading:
  412. if 1 == n.HeadingLevel {
  413. return "h1"
  414. }
  415. if 2 == n.HeadingLevel {
  416. return "h2"
  417. }
  418. if 3 == n.HeadingLevel {
  419. return "h3"
  420. }
  421. if 4 == n.HeadingLevel {
  422. return "h4"
  423. }
  424. if 5 == n.HeadingLevel {
  425. return "h5"
  426. }
  427. if 6 == n.HeadingLevel {
  428. return "h6"
  429. }
  430. }
  431. return ""
  432. }
  433. var DynamicRefTexts = sync.Map{}
  434. func SetDynamicBlockRefText(blockRef *ast.Node, refText string) {
  435. if !IsBlockRef(blockRef) {
  436. return
  437. }
  438. blockRef.TextMarkBlockRefSubtype = "d"
  439. blockRef.TextMarkTextContent = refText
  440. // 偶发编辑文档标题后引用处的动态锚文本不更新 https://github.com/siyuan-note/siyuan/issues/5891
  441. DynamicRefTexts.Store(blockRef.TextMarkBlockRefID, refText)
  442. }
  443. func IsChartCodeBlockCode(code *ast.Node) bool {
  444. if nil == code.Previous || ast.NodeCodeBlockFenceInfoMarker != code.Previous.Type || 1 > len(code.Previous.CodeBlockInfo) {
  445. return false
  446. }
  447. language := gulu.Str.FromBytes(code.Previous.CodeBlockInfo)
  448. language = strings.ReplaceAll(language, editor.Caret, "")
  449. return render.NoHighlight(language)
  450. }
  451. func GetAttributeViewName(avID string) (name string) {
  452. if "" == avID {
  453. return
  454. }
  455. attrView, err := av.ParseAttributeView(avID)
  456. if nil != err {
  457. logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
  458. return
  459. }
  460. buf := bytes.Buffer{}
  461. for _, v := range attrView.Views {
  462. buf.WriteString(v.Name)
  463. buf.WriteByte(' ')
  464. }
  465. name = strings.TrimSpace(buf.String())
  466. return
  467. }
  468. func getAttributeViewContent(avID string) (content string) {
  469. if "" == avID {
  470. return
  471. }
  472. attrView, err := av.ParseAttributeView(avID)
  473. if nil != err {
  474. logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
  475. return
  476. }
  477. buf := bytes.Buffer{}
  478. buf.WriteString(attrView.Name)
  479. buf.WriteByte(' ')
  480. for _, v := range attrView.Views {
  481. buf.WriteString(v.Name)
  482. buf.WriteByte(' ')
  483. }
  484. if 1 > len(attrView.Views) {
  485. content = strings.TrimSpace(buf.String())
  486. return
  487. }
  488. var view *av.View
  489. for _, v := range attrView.Views {
  490. if av.LayoutTypeTable == v.LayoutType {
  491. view = v
  492. break
  493. }
  494. }
  495. if nil == view {
  496. content = strings.TrimSpace(buf.String())
  497. return
  498. }
  499. table, err := renderAttributeViewTable(attrView, view)
  500. if nil != err {
  501. content = strings.TrimSpace(buf.String())
  502. return
  503. }
  504. for _, col := range table.Columns {
  505. buf.WriteString(col.Name)
  506. buf.WriteByte(' ')
  507. }
  508. for _, row := range table.Rows {
  509. for _, cell := range row.Cells {
  510. if nil == cell.Value {
  511. continue
  512. }
  513. buf.WriteString(cell.Value.String())
  514. buf.WriteByte(' ')
  515. }
  516. }
  517. content = strings.TrimSpace(buf.String())
  518. return
  519. }
  520. func renderAttributeViewTable(attrView *av.AttributeView, view *av.View) (ret *av.Table, err error) {
  521. ret = &av.Table{
  522. ID: view.ID,
  523. Icon: view.Icon,
  524. Name: view.Name,
  525. Columns: []*av.TableColumn{},
  526. Rows: []*av.TableRow{},
  527. }
  528. // 组装列
  529. for _, col := range view.Table.Columns {
  530. key, getErr := attrView.GetKey(col.ID)
  531. if nil != getErr {
  532. err = getErr
  533. return
  534. }
  535. ret.Columns = append(ret.Columns, &av.TableColumn{
  536. ID: key.ID,
  537. Name: key.Name,
  538. Type: key.Type,
  539. Icon: key.Icon,
  540. Options: key.Options,
  541. NumberFormat: key.NumberFormat,
  542. Template: key.Template,
  543. Relation: key.Relation,
  544. Rollup: key.Rollup,
  545. Wrap: col.Wrap,
  546. Hidden: col.Hidden,
  547. Width: col.Width,
  548. Pin: col.Pin,
  549. Calc: col.Calc,
  550. })
  551. }
  552. // 生成行
  553. rows := map[string][]*av.KeyValues{}
  554. for _, keyValues := range attrView.KeyValues {
  555. for _, val := range keyValues.Values {
  556. values := rows[val.BlockID]
  557. if nil == values {
  558. values = []*av.KeyValues{{Key: keyValues.Key, Values: []*av.Value{val}}}
  559. } else {
  560. values = append(values, &av.KeyValues{Key: keyValues.Key, Values: []*av.Value{val}})
  561. }
  562. rows[val.BlockID] = values
  563. }
  564. }
  565. // 过滤掉不存在的行
  566. var notFound []string
  567. for blockID, keyValues := range rows {
  568. blockValue := getRowBlockValue(keyValues)
  569. if nil == blockValue {
  570. notFound = append(notFound, blockID)
  571. continue
  572. }
  573. if blockValue.IsDetached {
  574. continue
  575. }
  576. if nil != blockValue.Block && "" == blockValue.Block.ID {
  577. notFound = append(notFound, blockID)
  578. continue
  579. }
  580. if GetBlockTree(blockID) == nil {
  581. notFound = append(notFound, blockID)
  582. }
  583. }
  584. for _, blockID := range notFound {
  585. delete(rows, blockID)
  586. }
  587. // 生成行单元格
  588. for rowID, row := range rows {
  589. var tableRow av.TableRow
  590. for _, col := range ret.Columns {
  591. var tableCell *av.TableCell
  592. for _, keyValues := range row {
  593. if keyValues.Key.ID == col.ID {
  594. tableCell = &av.TableCell{
  595. ID: keyValues.Values[0].ID,
  596. Value: keyValues.Values[0],
  597. ValueType: col.Type,
  598. }
  599. break
  600. }
  601. }
  602. if nil == tableCell {
  603. tableCell = &av.TableCell{
  604. ID: ast.NewNodeID(),
  605. ValueType: col.Type,
  606. }
  607. }
  608. tableRow.ID = rowID
  609. switch tableCell.ValueType {
  610. case av.KeyTypeNumber: // 格式化数字
  611. if nil != tableCell.Value && nil != tableCell.Value.Number && tableCell.Value.Number.IsNotEmpty {
  612. tableCell.Value.Number.Format = col.NumberFormat
  613. tableCell.Value.Number.FormatNumber()
  614. }
  615. case av.KeyTypeTemplate: // 渲染模板列
  616. tableCell.Value = &av.Value{ID: tableCell.ID, KeyID: col.ID, BlockID: rowID, Type: av.KeyTypeTemplate, Template: &av.ValueTemplate{Content: col.Template}}
  617. case av.KeyTypeCreated: // 填充创建时间列值,后面再渲染
  618. tableCell.Value = &av.Value{ID: tableCell.ID, KeyID: col.ID, BlockID: rowID, Type: av.KeyTypeCreated}
  619. case av.KeyTypeUpdated: // 填充更新时间列值,后面再渲染
  620. tableCell.Value = &av.Value{ID: tableCell.ID, KeyID: col.ID, BlockID: rowID, Type: av.KeyTypeUpdated}
  621. }
  622. FillAttributeViewTableCellNilValue(tableCell, rowID, col.ID)
  623. tableRow.Cells = append(tableRow.Cells, tableCell)
  624. }
  625. ret.Rows = append(ret.Rows, &tableRow)
  626. }
  627. // 渲染自动生成的列值,比如模板列、创建时间列和更新时间列
  628. for _, row := range ret.Rows {
  629. for _, cell := range row.Cells {
  630. switch cell.ValueType {
  631. case av.KeyTypeTemplate: // 渲染模板列
  632. keyValues := rows[row.ID]
  633. ial := map[string]string{}
  634. block := row.GetBlockValue()
  635. if nil != block && !block.IsDetached {
  636. ial = cache.GetBlockIAL(row.ID)
  637. if nil == ial {
  638. ial = map[string]string{}
  639. }
  640. }
  641. content := renderTemplateCol(ial, cell.Value.Template.Content, keyValues)
  642. cell.Value.Template.Content = content
  643. case av.KeyTypeCreated: // 渲染创建时间
  644. createdStr := row.ID[:len("20060102150405")]
  645. created, parseErr := time.ParseInLocation("20060102150405", createdStr, time.Local)
  646. if nil == parseErr {
  647. cell.Value.Created = av.NewFormattedValueCreated(created.UnixMilli(), 0, av.CreatedFormatNone)
  648. cell.Value.Created.IsNotEmpty = true
  649. } else {
  650. cell.Value.Created = av.NewFormattedValueCreated(time.Now().UnixMilli(), 0, av.CreatedFormatNone)
  651. }
  652. case av.KeyTypeUpdated: // 渲染更新时间
  653. ial := map[string]string{}
  654. block := row.GetBlockValue()
  655. if nil != block && !block.IsDetached {
  656. ial = cache.GetBlockIAL(row.ID)
  657. if nil == ial {
  658. ial = map[string]string{}
  659. }
  660. }
  661. updatedStr := ial["updated"]
  662. if "" == updatedStr && nil != block {
  663. cell.Value.Updated = av.NewFormattedValueUpdated(block.Block.Updated, 0, av.UpdatedFormatNone)
  664. cell.Value.Updated.IsNotEmpty = true
  665. } else {
  666. updated, parseErr := time.ParseInLocation("20060102150405", updatedStr, time.Local)
  667. if nil == parseErr {
  668. cell.Value.Updated = av.NewFormattedValueUpdated(updated.UnixMilli(), 0, av.UpdatedFormatNone)
  669. cell.Value.Updated.IsNotEmpty = true
  670. } else {
  671. cell.Value.Updated = av.NewFormattedValueUpdated(time.Now().UnixMilli(), 0, av.UpdatedFormatNone)
  672. }
  673. }
  674. }
  675. }
  676. }
  677. return
  678. }
  679. func FillAttributeViewTableCellNilValue(tableCell *av.TableCell, rowID, colID string) {
  680. if nil == tableCell.Value {
  681. tableCell.Value = &av.Value{ID: tableCell.ID, KeyID: colID, BlockID: rowID, Type: tableCell.ValueType}
  682. }
  683. tableCell.Value.Type = tableCell.ValueType
  684. switch tableCell.ValueType {
  685. case av.KeyTypeText:
  686. if nil == tableCell.Value.Text {
  687. tableCell.Value.Text = &av.ValueText{}
  688. }
  689. case av.KeyTypeNumber:
  690. if nil == tableCell.Value.Number {
  691. tableCell.Value.Number = &av.ValueNumber{}
  692. }
  693. case av.KeyTypeDate:
  694. if nil == tableCell.Value.Date {
  695. tableCell.Value.Date = &av.ValueDate{}
  696. }
  697. case av.KeyTypeSelect:
  698. if 1 > len(tableCell.Value.MSelect) {
  699. tableCell.Value.MSelect = []*av.ValueSelect{}
  700. }
  701. case av.KeyTypeMSelect:
  702. if 1 > len(tableCell.Value.MSelect) {
  703. tableCell.Value.MSelect = []*av.ValueSelect{}
  704. }
  705. case av.KeyTypeURL:
  706. if nil == tableCell.Value.URL {
  707. tableCell.Value.URL = &av.ValueURL{}
  708. }
  709. case av.KeyTypeEmail:
  710. if nil == tableCell.Value.Email {
  711. tableCell.Value.Email = &av.ValueEmail{}
  712. }
  713. case av.KeyTypePhone:
  714. if nil == tableCell.Value.Phone {
  715. tableCell.Value.Phone = &av.ValuePhone{}
  716. }
  717. case av.KeyTypeMAsset:
  718. if 1 > len(tableCell.Value.MAsset) {
  719. tableCell.Value.MAsset = []*av.ValueAsset{}
  720. }
  721. case av.KeyTypeTemplate:
  722. if nil == tableCell.Value.Template {
  723. tableCell.Value.Template = &av.ValueTemplate{}
  724. }
  725. case av.KeyTypeCreated:
  726. if nil == tableCell.Value.Created {
  727. tableCell.Value.Created = &av.ValueCreated{}
  728. }
  729. case av.KeyTypeUpdated:
  730. if nil == tableCell.Value.Updated {
  731. tableCell.Value.Updated = &av.ValueUpdated{}
  732. }
  733. case av.KeyTypeCheckbox:
  734. if nil == tableCell.Value.Checkbox {
  735. tableCell.Value.Checkbox = &av.ValueCheckbox{}
  736. }
  737. case av.KeyTypeRelation:
  738. if nil == tableCell.Value.Relation {
  739. tableCell.Value.Relation = &av.ValueRelation{}
  740. }
  741. case av.KeyTypeRollup:
  742. if nil == tableCell.Value.Rollup {
  743. tableCell.Value.Rollup = &av.ValueRollup{}
  744. }
  745. }
  746. }
  747. func renderTemplateCol(ial map[string]string, tplContent string, rowValues []*av.KeyValues) string {
  748. if "" == ial["id"] {
  749. block := getRowBlockValue(rowValues)
  750. ial["id"] = block.Block.ID
  751. }
  752. if "" == ial["updated"] {
  753. block := getRowBlockValue(rowValues)
  754. ial["updated"] = time.UnixMilli(block.Block.Updated).Format("20060102150405")
  755. }
  756. funcMap := util.BuiltInTemplateFuncs()
  757. goTpl := template.New("").Delims(".action{", "}")
  758. tpl, tplErr := goTpl.Funcs(funcMap).Parse(tplContent)
  759. if nil != tplErr {
  760. logging.LogWarnf("parse template [%s] failed: %s", tplContent, tplErr)
  761. return ""
  762. }
  763. buf := &bytes.Buffer{}
  764. dataModel := map[string]interface{}{} // 复制一份 IAL 以避免修改原始数据
  765. for k, v := range ial {
  766. dataModel[k] = v
  767. // Database template column supports `created` and `updated` built-in variables https://github.com/siyuan-note/siyuan/issues/9364
  768. createdStr := ial["id"]
  769. if "" != createdStr {
  770. createdStr = createdStr[:len("20060102150405")]
  771. }
  772. created, parseErr := time.ParseInLocation("20060102150405", createdStr, time.Local)
  773. if nil == parseErr {
  774. dataModel["created"] = created
  775. } else {
  776. logging.LogWarnf("parse created [%s] failed: %s", createdStr, parseErr)
  777. dataModel["created"] = time.Now()
  778. }
  779. updatedStr := ial["updated"]
  780. updated, parseErr := time.ParseInLocation("20060102150405", updatedStr, time.Local)
  781. if nil == parseErr {
  782. dataModel["updated"] = updated
  783. } else {
  784. dataModel["updated"] = time.Now()
  785. }
  786. }
  787. for _, rowValue := range rowValues {
  788. if 0 < len(rowValue.Values) {
  789. v := rowValue.Values[0]
  790. if av.KeyTypeNumber == v.Type {
  791. dataModel[rowValue.Key.Name] = v.Number.Content
  792. } else if av.KeyTypeDate == v.Type {
  793. dataModel[rowValue.Key.Name] = time.UnixMilli(v.Date.Content)
  794. } else {
  795. dataModel[rowValue.Key.Name] = v.String()
  796. }
  797. }
  798. }
  799. if err := tpl.Execute(buf, dataModel); nil != err {
  800. logging.LogWarnf("execute template [%s] failed: %s", tplContent, err)
  801. }
  802. return buf.String()
  803. }
  804. func getRowBlockValue(keyValues []*av.KeyValues) (ret *av.Value) {
  805. for _, kv := range keyValues {
  806. if av.KeyTypeBlock == kv.Key.Type && 0 < len(kv.Values) {
  807. ret = kv.Values[0]
  808. break
  809. }
  810. }
  811. return
  812. }