node.go 11 KB

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