node.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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/lute"
  22. "github.com/88250/lute/ast"
  23. "github.com/88250/lute/editor"
  24. "github.com/88250/lute/html"
  25. "github.com/88250/lute/lex"
  26. "github.com/88250/lute/parse"
  27. "github.com/88250/lute/render"
  28. "github.com/88250/lute/util"
  29. "github.com/siyuan-note/logging"
  30. )
  31. func GetBlockRef(n *ast.Node) (blockRefID, blockRefText, blockRefSubtype string) {
  32. if !IsBlockRef(n) {
  33. return
  34. }
  35. blockRefID = n.TextMarkBlockRefID
  36. blockRefText = n.TextMarkTextContent
  37. blockRefSubtype = n.TextMarkBlockRefSubtype
  38. return
  39. }
  40. func IsBlockRef(n *ast.Node) bool {
  41. if nil == n {
  42. return false
  43. }
  44. return ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref")
  45. }
  46. func NodeStaticMdContent(node *ast.Node, luteEngine *lute.Lute) (md, content string) {
  47. md = ExportNodeStdMd(node, luteEngine)
  48. content = NodeStaticContent(node)
  49. return
  50. }
  51. func FormatNode(node *ast.Node, luteEngine *lute.Lute) string {
  52. markdown, err := lute.FormatNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  53. if nil != err {
  54. root := TreeRoot(node)
  55. logging.LogFatalf("format node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  56. }
  57. return markdown
  58. }
  59. func ExportNodeStdMd(node *ast.Node, luteEngine *lute.Lute) string {
  60. markdown, err := lute.ProtyleExportMdNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions)
  61. if nil != err {
  62. root := TreeRoot(node)
  63. logging.LogFatalf("export markdown for node [%s] in tree [%s] failed: %s", node.ID, root.ID, err)
  64. }
  65. return markdown
  66. }
  67. func NodeStaticContent(node *ast.Node) string {
  68. if nil == node {
  69. return ""
  70. }
  71. if ast.NodeDocument == node.Type {
  72. return node.IALAttr("title")
  73. }
  74. buf := bytes.Buffer{}
  75. buf.Grow(4096)
  76. lastSpace := false
  77. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  78. if !entering {
  79. return ast.WalkContinue
  80. }
  81. if n.IsContainerBlock() {
  82. if !lastSpace {
  83. buf.WriteString(" ")
  84. lastSpace = true
  85. }
  86. return ast.WalkContinue
  87. }
  88. switch n.Type {
  89. case ast.NodeLinkText:
  90. buf.Write(n.Tokens)
  91. buf.WriteByte(' ')
  92. case ast.NodeLinkDest:
  93. buf.Write(n.Tokens)
  94. buf.WriteByte(' ')
  95. case ast.NodeLinkTitle:
  96. buf.Write(n.Tokens)
  97. case ast.NodeText, ast.NodeCodeBlockCode, ast.NodeMathBlockContent, ast.NodeHTMLBlock:
  98. tokens := n.Tokens
  99. if IsChartCodeBlockCode(n) {
  100. // 图表块的内容在数据库 `blocks` 表 `content` 字段中被转义 https://github.com/siyuan-note/siyuan/issues/6326
  101. tokens = html.UnescapeHTML(tokens)
  102. }
  103. buf.Write(tokens)
  104. case ast.NodeTextMark:
  105. if n.IsTextMarkType("tag") {
  106. buf.WriteByte('#')
  107. }
  108. buf.WriteString(n.Content())
  109. if n.IsTextMarkType("tag") {
  110. buf.WriteByte('#')
  111. }
  112. case ast.NodeBackslash:
  113. buf.WriteByte(lex.ItemBackslash)
  114. case ast.NodeBackslashContent:
  115. buf.Write(n.Tokens)
  116. }
  117. lastSpace = false
  118. return ast.WalkContinue
  119. })
  120. return strings.TrimSpace(buf.String())
  121. }
  122. func FirstLeafBlock(node *ast.Node) (ret *ast.Node) {
  123. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  124. if !entering || n.IsMarker() {
  125. return ast.WalkContinue
  126. }
  127. if !n.IsContainerBlock() {
  128. ret = n
  129. return ast.WalkStop
  130. }
  131. return ast.WalkContinue
  132. })
  133. return
  134. }
  135. func CountBlockNodes(node *ast.Node) (ret int) {
  136. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  137. if !entering || !n.IsBlock() || ast.NodeList == n.Type || ast.NodeBlockquote == n.Type || ast.NodeSuperBlock == n.Type {
  138. return ast.WalkContinue
  139. }
  140. if "1" == n.IALAttr("fold") {
  141. ret++
  142. return ast.WalkSkipChildren
  143. }
  144. ret++
  145. return ast.WalkContinue
  146. })
  147. return
  148. }
  149. func ParentNodes(node *ast.Node) (parents []*ast.Node) {
  150. const maxDepth = 256
  151. i := 0
  152. for n := node.Parent; nil != n; n = n.Parent {
  153. i++
  154. parents = append(parents, n)
  155. if ast.NodeDocument == n.Type {
  156. return
  157. }
  158. if maxDepth < i {
  159. logging.LogWarnf("parent nodes of node [%s] is too deep", node.ID)
  160. return
  161. }
  162. }
  163. return
  164. }
  165. func ParentBlock(node *ast.Node) *ast.Node {
  166. for p := node.Parent; nil != p; p = p.Parent {
  167. if "" != p.ID && p.IsBlock() {
  168. return p
  169. }
  170. }
  171. return nil
  172. }
  173. func GetNodeInTree(tree *parse.Tree, id string) (ret *ast.Node) {
  174. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  175. if !entering {
  176. return ast.WalkContinue
  177. }
  178. if id == n.ID {
  179. ret = n
  180. ret.Box = tree.Box
  181. ret.Path = tree.Path
  182. return ast.WalkStop
  183. }
  184. return ast.WalkContinue
  185. })
  186. return
  187. }
  188. func GetDocTitleImgPath(root *ast.Node) (ret string) {
  189. if nil == root {
  190. return
  191. }
  192. const background = "background-image: url("
  193. titleImg := root.IALAttr("title-img")
  194. titleImg = strings.TrimSpace(titleImg)
  195. titleImg = html.UnescapeString(titleImg)
  196. titleImg = strings.ReplaceAll(titleImg, "background-image:url(", background)
  197. if !strings.Contains(titleImg, background) {
  198. return
  199. }
  200. start := strings.Index(titleImg, background) + len(background)
  201. end := strings.LastIndex(titleImg, ")")
  202. ret = titleImg[start:end]
  203. ret = strings.TrimPrefix(ret, "\"")
  204. ret = strings.TrimPrefix(ret, "'")
  205. ret = strings.TrimSuffix(ret, "\"")
  206. ret = strings.TrimSuffix(ret, "'")
  207. return ret
  208. }
  209. var typeAbbrMap = map[string]string{
  210. // 块级元素
  211. "NodeDocument": "d",
  212. "NodeHeading": "h",
  213. "NodeList": "l",
  214. "NodeListItem": "i",
  215. "NodeCodeBlock": "c",
  216. "NodeMathBlock": "m",
  217. "NodeTable": "t",
  218. "NodeBlockquote": "b",
  219. "NodeSuperBlock": "s",
  220. "NodeParagraph": "p",
  221. "NodeHTMLBlock": "html",
  222. "NodeBlockQueryEmbed": "query_embed",
  223. "NodeKramdownBlockIAL": "ial",
  224. "NodeIFrame": "iframe",
  225. "NodeWidget": "widget",
  226. "NodeThematicBreak": "tb",
  227. "NodeVideo": "video",
  228. "NodeAudio": "audio",
  229. // 行级元素 TODO: 移除旧版中的行级元素实现代码 https://github.com/siyuan-note/siyuan/issues/6819
  230. "NodeText": "text",
  231. "NodeImage": "img",
  232. "NodeLinkText": "link_text",
  233. "NodeLinkDest": "link_dest",
  234. "NodeTextMark": "textmark",
  235. }
  236. var abbrTypeMap = map[string]string{}
  237. func init() {
  238. for typ, abbr := range typeAbbrMap {
  239. abbrTypeMap[abbr] = typ
  240. }
  241. }
  242. func TypeAbbr(nodeType string) string {
  243. return typeAbbrMap[nodeType]
  244. }
  245. func FromAbbrType(abbrType string) string {
  246. return abbrTypeMap[abbrType]
  247. }
  248. func SubTypeAbbr(n *ast.Node) string {
  249. switch n.Type {
  250. case ast.NodeList, ast.NodeListItem:
  251. if 0 == n.ListData.Typ {
  252. return "u"
  253. }
  254. if 1 == n.ListData.Typ {
  255. return "o"
  256. }
  257. if 3 == n.ListData.Typ {
  258. return "t"
  259. }
  260. case ast.NodeHeading:
  261. if 1 == n.HeadingLevel {
  262. return "h1"
  263. }
  264. if 2 == n.HeadingLevel {
  265. return "h2"
  266. }
  267. if 3 == n.HeadingLevel {
  268. return "h3"
  269. }
  270. if 4 == n.HeadingLevel {
  271. return "h4"
  272. }
  273. if 5 == n.HeadingLevel {
  274. return "h5"
  275. }
  276. if 6 == n.HeadingLevel {
  277. return "h6"
  278. }
  279. }
  280. return ""
  281. }
  282. var DynamicRefTexts = sync.Map{}
  283. func SetDynamicBlockRefText(blockRef *ast.Node, refText string) {
  284. if !IsBlockRef(blockRef) {
  285. return
  286. }
  287. blockRef.TextMarkBlockRefSubtype = "d"
  288. blockRef.TextMarkTextContent = refText
  289. // 偶发编辑文档标题后引用处的动态锚文本不更新 https://github.com/siyuan-note/siyuan/issues/5891
  290. DynamicRefTexts.Store(blockRef.TextMarkBlockRefID, refText)
  291. }
  292. func IsChartCodeBlockCode(code *ast.Node) bool {
  293. if nil == code.Previous || ast.NodeCodeBlockFenceInfoMarker != code.Previous.Type || 1 > len(code.Previous.CodeBlockInfo) {
  294. return false
  295. }
  296. language := util.BytesToStr(code.Previous.CodeBlockInfo)
  297. language = strings.ReplaceAll(language, editor.Caret, "")
  298. return render.NoHighlight(language)
  299. }