node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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/88250/gulu"
  20. "github.com/88250/lute"
  21. "github.com/88250/lute/ast"
  22. "github.com/88250/lute/editor"
  23. "github.com/88250/lute/html"
  24. "github.com/88250/lute/parse"
  25. "github.com/88250/lute/render"
  26. "github.com/88250/vitess-sqlparser/sqlparser"
  27. "github.com/emirpasic/gods/sets/hashset"
  28. "github.com/siyuan-note/logging"
  29. "github.com/siyuan-note/siyuan/kernel/cache"
  30. "github.com/siyuan-note/siyuan/kernel/util"
  31. "strings"
  32. "sync"
  33. )
  34. func GetEmbedBlockRef(embedNode *ast.Node) (blockRefID string) {
  35. if nil == embedNode || ast.NodeBlockQueryEmbed != embedNode.Type {
  36. return
  37. }
  38. scriptNode := embedNode.ChildByType(ast.NodeBlockQueryEmbedScript)
  39. if nil == scriptNode {
  40. return
  41. }
  42. stmt := scriptNode.TokensStr()
  43. parsedStmt, err := sqlparser.Parse(stmt)
  44. if nil != err {
  45. return
  46. }
  47. switch parsedStmt.(type) {
  48. case *sqlparser.Select:
  49. slct := parsedStmt.(*sqlparser.Select)
  50. if nil == slct.Where || nil == slct.Where.Expr {
  51. return
  52. }
  53. switch slct.Where.Expr.(type) {
  54. case *sqlparser.ComparisonExpr: // WHERE id = '20060102150405-1a2b3c4'
  55. comp := slct.Where.Expr.(*sqlparser.ComparisonExpr)
  56. switch comp.Left.(type) {
  57. case *sqlparser.ColName:
  58. col := comp.Left.(*sqlparser.ColName)
  59. if nil == col || "id" != col.Name.Lowered() {
  60. return
  61. }
  62. }
  63. switch comp.Right.(type) {
  64. case *sqlparser.SQLVal:
  65. val := comp.Right.(*sqlparser.SQLVal)
  66. if nil == val || sqlparser.StrVal != val.Type {
  67. return
  68. }
  69. idVal := string(val.Val)
  70. if !ast.IsNodeIDPattern(idVal) {
  71. return
  72. }
  73. blockRefID = idVal
  74. }
  75. }
  76. }
  77. return
  78. }
  79. func GetBlockRef(n *ast.Node) (blockRefID, blockRefText, blockRefSubtype string) {
  80. if !IsBlockRef(n) {
  81. return
  82. }
  83. blockRefID = n.TextMarkBlockRefID
  84. blockRefText = n.TextMarkTextContent
  85. blockRefSubtype = n.TextMarkBlockRefSubtype
  86. return
  87. }
  88. func IsBlockRef(n *ast.Node) bool {
  89. if nil == n {
  90. return false
  91. }
  92. return ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref")
  93. }
  94. func IsFileAnnotationRef(n *ast.Node) bool {
  95. if nil == n {
  96. return false
  97. }
  98. return ast.NodeTextMark == n.Type && n.IsTextMarkType("file-annotation-ref")
  99. }
  100. func IsEmbedBlockRef(n *ast.Node) bool {
  101. return "" != GetEmbedBlockRef(n)
  102. }
  103. func FormatNode(node *ast.Node, luteEngine *lute.Lute) string {
  104. markdown, err := lute.FormatNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  105. if nil != err {
  106. root := TreeRoot(node)
  107. logging.LogFatalf(logging.ExitCodeFatal, "format node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  108. }
  109. return markdown
  110. }
  111. func ExportNodeStdMd(node *ast.Node, luteEngine *lute.Lute) string {
  112. markdown, err := lute.ProtyleExportMdNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  113. if nil != err {
  114. root := TreeRoot(node)
  115. logging.LogFatalf(logging.ExitCodeFatal, "export markdown for node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  116. }
  117. return markdown
  118. }
  119. func IsNodeOCRed(node *ast.Node) (ret bool) {
  120. if !util.TesseractEnabled || nil == node {
  121. return true
  122. }
  123. ret = true
  124. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  125. if !entering {
  126. return ast.WalkContinue
  127. }
  128. if ast.NodeImage == n.Type {
  129. linkDest := n.ChildByType(ast.NodeLinkDest)
  130. if nil == linkDest {
  131. return ast.WalkContinue
  132. }
  133. linkDestStr := linkDest.TokensStr()
  134. if !cache.ExistAsset(linkDestStr) {
  135. return ast.WalkContinue
  136. }
  137. if !util.ExistsAssetText(linkDestStr) {
  138. ret = false
  139. return ast.WalkStop
  140. }
  141. }
  142. return ast.WalkContinue
  143. })
  144. return
  145. }
  146. func GetNodeSrcTokens(n *ast.Node) (ret string) {
  147. if index := bytes.Index(n.Tokens, []byte("src=\"")); 0 < index {
  148. src := n.Tokens[index+len("src=\""):]
  149. if index = bytes.Index(src, []byte("\"")); 0 < index {
  150. src = src[:bytes.Index(src, []byte("\""))]
  151. if !IsRelativePath(src) {
  152. return
  153. }
  154. ret = strings.TrimSpace(string(src))
  155. return
  156. }
  157. logging.LogWarnf("src is missing the closing double quote in tree [%s] ", n.Box+n.Path)
  158. }
  159. return
  160. }
  161. func IsRelativePath(dest []byte) bool {
  162. if 1 > len(dest) {
  163. return false
  164. }
  165. if '/' == dest[0] {
  166. return false
  167. }
  168. return !bytes.Contains(dest, []byte(":"))
  169. }
  170. func FirstLeafBlock(node *ast.Node) (ret *ast.Node) {
  171. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  172. if !entering || n.IsMarker() {
  173. return ast.WalkContinue
  174. }
  175. if !n.IsContainerBlock() {
  176. ret = n
  177. return ast.WalkStop
  178. }
  179. return ast.WalkContinue
  180. })
  181. return
  182. }
  183. func CountBlockNodes(node *ast.Node) (ret int) {
  184. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  185. if !entering || !n.IsBlock() || ast.NodeList == n.Type || ast.NodeBlockquote == n.Type || ast.NodeSuperBlock == n.Type {
  186. return ast.WalkContinue
  187. }
  188. if "1" == n.IALAttr("fold") {
  189. ret++
  190. return ast.WalkSkipChildren
  191. }
  192. ret++
  193. return ast.WalkContinue
  194. })
  195. return
  196. }
  197. // ParentNodesWithHeadings 返回所有父级节点。
  198. // 注意:返回的父级节点包括了标题节点,并且不保证父级层次顺序。
  199. func ParentNodesWithHeadings(node *ast.Node) (parents []*ast.Node) {
  200. const maxDepth = 255
  201. i := 0
  202. headingIDs := hashset.New()
  203. for n := node; nil != n; n = n.Parent {
  204. parent := n.Parent
  205. if maxDepth < i {
  206. logging.LogWarnf("parent nodes of node [%s] is too deep", node.ID)
  207. return
  208. }
  209. i++
  210. if nil == parent {
  211. return
  212. }
  213. // 标题下方块编辑后刷新标题块更新时间
  214. // The heading block update time is refreshed after editing the blocks under the heading https://github.com/siyuan-note/siyuan/issues/11374
  215. parentHeadingLevel := 7
  216. for prev := n.Previous; nil != prev; prev = prev.Previous {
  217. if ast.NodeHeading == prev.Type && prev.HeadingLevel < parentHeadingLevel && !headingIDs.Contains(prev.ID) {
  218. parents = append(parents, prev)
  219. headingIDs.Add(prev.ID)
  220. }
  221. }
  222. parents = append(parents, parent)
  223. if ast.NodeDocument == parent.Type {
  224. return
  225. }
  226. }
  227. return
  228. }
  229. func ChildBlockNodes(node *ast.Node) (children []*ast.Node) {
  230. children = []*ast.Node{}
  231. if !node.IsContainerBlock() || ast.NodeDocument == node.Type {
  232. children = append(children, node)
  233. return
  234. }
  235. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  236. if !entering || !n.IsBlock() {
  237. return ast.WalkContinue
  238. }
  239. children = append(children, n)
  240. return ast.WalkContinue
  241. })
  242. return
  243. }
  244. func ParentBlock(node *ast.Node) *ast.Node {
  245. for p := node.Parent; nil != p; p = p.Parent {
  246. if "" != p.ID && p.IsBlock() {
  247. return p
  248. }
  249. }
  250. return nil
  251. }
  252. func PreviousBlock(node *ast.Node) *ast.Node {
  253. for n := node.Previous; nil != n; n = n.Previous {
  254. if "" != n.ID && n.IsBlock() {
  255. return n
  256. }
  257. }
  258. return nil
  259. }
  260. func NextBlock(node *ast.Node) *ast.Node {
  261. for n := node.Next; nil != n; n = n.Next {
  262. if "" != n.ID && n.IsBlock() {
  263. return n
  264. }
  265. }
  266. return nil
  267. }
  268. func FirstChildBlock(node *ast.Node) (ret *ast.Node) {
  269. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  270. if !entering {
  271. return ast.WalkContinue
  272. }
  273. if n.IsBlock() {
  274. ret = n
  275. return ast.WalkStop
  276. }
  277. return ast.WalkContinue
  278. })
  279. return
  280. }
  281. func GetNodeInTree(tree *parse.Tree, id string) (ret *ast.Node) {
  282. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  283. if !entering {
  284. return ast.WalkContinue
  285. }
  286. if id == n.ID {
  287. ret = n
  288. ret.Box = tree.Box
  289. ret.Path = tree.Path
  290. return ast.WalkStop
  291. }
  292. return ast.WalkContinue
  293. })
  294. return
  295. }
  296. func GetDocTitleImgPath(root *ast.Node) (ret string) {
  297. if nil == root {
  298. return
  299. }
  300. const background = "background-image: url("
  301. titleImg := root.IALAttr("title-img")
  302. titleImg = strings.TrimSpace(titleImg)
  303. titleImg = html.UnescapeString(titleImg)
  304. titleImg = strings.ReplaceAll(titleImg, "background-image:url(", background)
  305. if !strings.Contains(titleImg, background) {
  306. return
  307. }
  308. start := strings.Index(titleImg, background) + len(background)
  309. end := strings.LastIndex(titleImg, ")")
  310. ret = titleImg[start:end]
  311. ret = strings.TrimPrefix(ret, "\"")
  312. ret = strings.TrimPrefix(ret, "'")
  313. ret = strings.TrimSuffix(ret, "\"")
  314. ret = strings.TrimSuffix(ret, "'")
  315. return ret
  316. }
  317. var typeAbbrMap = map[string]string{
  318. // 块级元素
  319. "NodeDocument": "d",
  320. "NodeHeading": "h",
  321. "NodeList": "l",
  322. "NodeListItem": "i",
  323. "NodeCodeBlock": "c",
  324. "NodeMathBlock": "m",
  325. "NodeTable": "t",
  326. "NodeBlockquote": "b",
  327. "NodeSuperBlock": "s",
  328. "NodeParagraph": "p",
  329. "NodeHTMLBlock": "html",
  330. "NodeBlockQueryEmbed": "query_embed",
  331. "NodeAttributeView": "av",
  332. "NodeKramdownBlockIAL": "ial",
  333. "NodeIFrame": "iframe",
  334. "NodeWidget": "widget",
  335. "NodeThematicBreak": "tb",
  336. "NodeVideo": "video",
  337. "NodeAudio": "audio",
  338. // 行级元素
  339. "NodeText": "text",
  340. "NodeImage": "img",
  341. "NodeLinkText": "link_text",
  342. "NodeLinkDest": "link_dest",
  343. "NodeTextMark": "textmark",
  344. }
  345. var abbrTypeMap = map[string]string{}
  346. func init() {
  347. for typ, abbr := range typeAbbrMap {
  348. abbrTypeMap[abbr] = typ
  349. }
  350. }
  351. func TypeAbbr(nodeType string) string {
  352. return typeAbbrMap[nodeType]
  353. }
  354. func FromAbbrType(abbrType string) string {
  355. return abbrTypeMap[abbrType]
  356. }
  357. func SubTypeAbbr(n *ast.Node) string {
  358. switch n.Type {
  359. case ast.NodeList, ast.NodeListItem:
  360. if 0 == n.ListData.Typ {
  361. return "u"
  362. }
  363. if 1 == n.ListData.Typ {
  364. return "o"
  365. }
  366. if 3 == n.ListData.Typ {
  367. return "t"
  368. }
  369. case ast.NodeHeading:
  370. if 1 == n.HeadingLevel {
  371. return "h1"
  372. }
  373. if 2 == n.HeadingLevel {
  374. return "h2"
  375. }
  376. if 3 == n.HeadingLevel {
  377. return "h3"
  378. }
  379. if 4 == n.HeadingLevel {
  380. return "h4"
  381. }
  382. if 5 == n.HeadingLevel {
  383. return "h5"
  384. }
  385. if 6 == n.HeadingLevel {
  386. return "h6"
  387. }
  388. }
  389. return ""
  390. }
  391. var DynamicRefTexts = sync.Map{}
  392. func SetDynamicBlockRefText(blockRef *ast.Node, refText string) {
  393. if !IsBlockRef(blockRef) {
  394. return
  395. }
  396. blockRef.TextMarkBlockRefSubtype = "d"
  397. blockRef.TextMarkTextContent = refText
  398. // 偶发编辑文档标题后引用处的动态锚文本不更新 https://github.com/siyuan-note/siyuan/issues/5891
  399. DynamicRefTexts.Store(blockRef.TextMarkBlockRefID, refText)
  400. }
  401. func IsChartCodeBlockCode(code *ast.Node) bool {
  402. if nil == code.Previous || ast.NodeCodeBlockFenceInfoMarker != code.Previous.Type || 1 > len(code.Previous.CodeBlockInfo) {
  403. return false
  404. }
  405. language := gulu.Str.FromBytes(code.Previous.CodeBlockInfo)
  406. language = strings.ReplaceAll(language, editor.Caret, "")
  407. return render.NoHighlight(language)
  408. }