node.go 23 KB

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