blockinfo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 model
  17. import (
  18. "os"
  19. "path/filepath"
  20. "sort"
  21. "strings"
  22. "unicode/utf8"
  23. "github.com/88250/gulu"
  24. "github.com/88250/lute/ast"
  25. "github.com/88250/lute/editor"
  26. "github.com/88250/lute/parse"
  27. "github.com/siyuan-note/logging"
  28. "github.com/siyuan-note/siyuan/kernel/av"
  29. "github.com/siyuan-note/siyuan/kernel/sql"
  30. "github.com/siyuan-note/siyuan/kernel/treenode"
  31. "github.com/siyuan-note/siyuan/kernel/util"
  32. )
  33. type BlockInfo struct {
  34. ID string `json:"id"`
  35. RootID string `json:"rootID"`
  36. Name string `json:"name"`
  37. RefCount int `json:"refCount"`
  38. SubFileCount int `json:"subFileCount"`
  39. RefIDs []string `json:"refIDs"`
  40. IAL map[string]string `json:"ial"`
  41. Icon string `json:"icon"`
  42. AttrViews []*AttrView `json:"attrViews"`
  43. }
  44. type AttrView struct {
  45. ID string `json:"id"`
  46. Name string `json:"name"`
  47. }
  48. func GetDocInfo(blockID string) (ret *BlockInfo) {
  49. WaitForWritingFiles()
  50. tree, err := LoadTreeByBlockID(blockID)
  51. if nil != err {
  52. logging.LogErrorf("load tree by root id [%s] failed: %s", blockID, err)
  53. return
  54. }
  55. title := tree.Root.IALAttr("title")
  56. ret = &BlockInfo{ID: blockID, RootID: tree.Root.ID, Name: title}
  57. ret.IAL = parse.IAL2Map(tree.Root.KramdownIAL)
  58. scrollData := ret.IAL["scroll"]
  59. if 0 < len(scrollData) {
  60. scroll := map[string]interface{}{}
  61. if parseErr := gulu.JSON.UnmarshalJSON([]byte(scrollData), &scroll); nil != parseErr {
  62. logging.LogWarnf("parse scroll data [%s] failed: %s", scrollData, parseErr)
  63. delete(ret.IAL, "scroll")
  64. } else {
  65. if zoomInId := scroll["zoomInId"]; nil != zoomInId {
  66. if nil == treenode.GetBlockTree(zoomInId.(string)) {
  67. delete(ret.IAL, "scroll")
  68. }
  69. } else {
  70. if startId := scroll["startId"]; nil != startId {
  71. if nil == treenode.GetBlockTree(startId.(string)) {
  72. delete(ret.IAL, "scroll")
  73. }
  74. }
  75. if endId := scroll["endId"]; nil != endId {
  76. if nil == treenode.GetBlockTree(endId.(string)) {
  77. delete(ret.IAL, "scroll")
  78. }
  79. }
  80. }
  81. }
  82. }
  83. ret.RefIDs, _ = sql.QueryRefIDsByDefID(blockID, false)
  84. ret.RefCount = len(ret.RefIDs) // 填充块引计数
  85. // 填充属性视图角标 Display the database title on the block superscript https://github.com/siyuan-note/siyuan/issues/10545
  86. avIDs := strings.Split(ret.IAL[av.NodeAttrNameAvs], ",")
  87. for _, avID := range avIDs {
  88. avName, getErr := av.GetAttributeViewName(avID)
  89. if nil != getErr {
  90. continue
  91. }
  92. if "" == avName {
  93. avName = Conf.language(105)
  94. }
  95. attrView := &AttrView{ID: avID, Name: avName}
  96. ret.AttrViews = append(ret.AttrViews, attrView)
  97. }
  98. var subFileCount int
  99. boxLocalPath := filepath.Join(util.DataDir, tree.Box)
  100. subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
  101. if nil == err {
  102. for _, subFile := range subFiles {
  103. if strings.HasSuffix(subFile.Name(), ".sy") {
  104. subFileCount++
  105. }
  106. }
  107. }
  108. ret.SubFileCount = subFileCount
  109. ret.Icon = tree.Root.IALAttr("icon")
  110. return
  111. }
  112. func GetBlockRefText(id string) string {
  113. bt := treenode.GetBlockTree(id)
  114. if nil == bt {
  115. return ErrBlockNotFound.Error()
  116. }
  117. tree, err := LoadTreeByBlockID(id)
  118. if nil != err {
  119. return ErrTreeNotFound.Error()
  120. }
  121. node := treenode.GetNodeInTree(tree, id)
  122. if nil == node {
  123. return ErrBlockNotFound.Error()
  124. }
  125. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  126. if !entering {
  127. return ast.WalkContinue
  128. }
  129. if n.IsTextMarkType("inline-memo") {
  130. // Block ref anchor text no longer contains contents of inline-level memos https://github.com/siyuan-note/siyuan/issues/9363
  131. n.TextMarkInlineMemoContent = ""
  132. return ast.WalkContinue
  133. }
  134. return ast.WalkContinue
  135. })
  136. return getNodeRefText(node)
  137. }
  138. func GetDOMText(dom string) (ret string) {
  139. luteEngine := NewLute()
  140. tree := luteEngine.BlockDOM2Tree(dom)
  141. ret = renderBlockText(tree.Root.FirstChild, nil)
  142. return
  143. }
  144. func getBlockRefText(id string, tree *parse.Tree) (ret string) {
  145. node := treenode.GetNodeInTree(tree, id)
  146. if nil == node {
  147. return
  148. }
  149. ret = getNodeRefText(node)
  150. ret = maxContent(ret, Conf.Editor.BlockRefDynamicAnchorTextMaxLen)
  151. return
  152. }
  153. func getNodeRefText(node *ast.Node) string {
  154. if nil == node {
  155. return ""
  156. }
  157. if ret := node.IALAttr("name"); "" != ret {
  158. ret = strings.TrimSpace(ret)
  159. ret = util.EscapeHTML(ret)
  160. return ret
  161. }
  162. return getNodeRefText0(node)
  163. }
  164. func getNodeRefText0(node *ast.Node) string {
  165. switch node.Type {
  166. case ast.NodeBlockQueryEmbed:
  167. return "Query Embed Block..."
  168. case ast.NodeIFrame:
  169. return "IFrame..."
  170. case ast.NodeThematicBreak:
  171. return "Thematic Break..."
  172. case ast.NodeVideo:
  173. return "Video..."
  174. case ast.NodeAudio:
  175. return "Audio..."
  176. case ast.NodeAttributeView:
  177. ret, _ := av.GetAttributeViewName(node.AttributeViewID)
  178. if "" == ret {
  179. ret = "Database..."
  180. }
  181. return ret
  182. }
  183. if ast.NodeDocument != node.Type && node.IsContainerBlock() {
  184. node = treenode.FirstLeafBlock(node)
  185. }
  186. ret := renderBlockText(node, nil)
  187. if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(ret) {
  188. ret = gulu.Str.SubStr(ret, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."
  189. }
  190. return ret
  191. }
  192. func GetBlockRefIDs(id string) (refIDs, refTexts, defIDs []string) {
  193. refIDs = []string{}
  194. refTexts = []string{}
  195. defIDs = []string{}
  196. bt := treenode.GetBlockTree(id)
  197. if nil == bt {
  198. return
  199. }
  200. isDoc := bt.ID == bt.RootID
  201. refIDs, refTexts = sql.QueryRefIDsByDefID(id, isDoc)
  202. if isDoc {
  203. defIDs = sql.QueryChildDefIDsByRootDefID(id)
  204. } else {
  205. defIDs = append(defIDs, id)
  206. }
  207. return
  208. }
  209. func GetBlockRefIDsByFileAnnotationID(id string) (refIDs, refTexts []string) {
  210. refIDs, refTexts = sql.QueryRefIDsByAnnotationID(id)
  211. return
  212. }
  213. func GetBlockDefIDsByRefText(refText string, excludeIDs []string) (ret []string) {
  214. ret = sql.QueryBlockDefIDsByRefText(refText, excludeIDs)
  215. sort.Sort(sort.Reverse(sort.StringSlice(ret)))
  216. if 1 > len(ret) {
  217. ret = []string{}
  218. }
  219. return
  220. }
  221. func GetBlockIndex(id string) (ret int) {
  222. tree, _ := LoadTreeByBlockID(id)
  223. if nil == tree {
  224. return
  225. }
  226. node := treenode.GetNodeInTree(tree, id)
  227. if nil == node {
  228. return
  229. }
  230. rootChild := node
  231. for ; nil != rootChild.Parent && ast.NodeDocument != rootChild.Parent.Type; rootChild = rootChild.Parent {
  232. }
  233. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  234. if !entering {
  235. return ast.WalkContinue
  236. }
  237. if !n.IsChildBlockOf(tree.Root, 1) {
  238. return ast.WalkContinue
  239. }
  240. ret++
  241. if n.ID == rootChild.ID {
  242. return ast.WalkStop
  243. }
  244. return ast.WalkContinue
  245. })
  246. return
  247. }
  248. func GetBlocksIndexes(ids []string) (ret map[string]int) {
  249. ret = map[string]int{}
  250. if 1 > len(ids) {
  251. return
  252. }
  253. tree, _ := LoadTreeByBlockID(ids[0])
  254. if nil == tree {
  255. return
  256. }
  257. idx := 0
  258. nodesIndexes := map[string]int{}
  259. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  260. if !entering {
  261. return ast.WalkContinue
  262. }
  263. if !n.IsChildBlockOf(tree.Root, 1) {
  264. if n.IsBlock() {
  265. nodesIndexes[n.ID] = idx
  266. }
  267. return ast.WalkContinue
  268. }
  269. idx++
  270. nodesIndexes[n.ID] = idx
  271. return ast.WalkContinue
  272. })
  273. for _, id := range ids {
  274. ret[id] = nodesIndexes[id]
  275. }
  276. return
  277. }
  278. type BlockPath struct {
  279. ID string `json:"id"`
  280. Name string `json:"name"`
  281. Type string `json:"type"`
  282. SubType string `json:"subType"`
  283. Children []*BlockPath `json:"children"`
  284. }
  285. func BuildBlockBreadcrumb(id string, excludeTypes []string) (ret []*BlockPath, err error) {
  286. ret = []*BlockPath{}
  287. tree, err := LoadTreeByBlockID(id)
  288. if nil == tree {
  289. err = nil
  290. return
  291. }
  292. node := treenode.GetNodeInTree(tree, id)
  293. if nil == node {
  294. return
  295. }
  296. ret = buildBlockBreadcrumb(node, excludeTypes)
  297. return
  298. }
  299. func buildBlockBreadcrumb(node *ast.Node, excludeTypes []string) (ret []*BlockPath) {
  300. ret = []*BlockPath{}
  301. if nil == node {
  302. return
  303. }
  304. box := Conf.Box(node.Box)
  305. if nil == box {
  306. return
  307. }
  308. headingLevel := 16
  309. maxNameLen := 1024
  310. var hPath string
  311. baseBlock := treenode.GetBlockTreeRootByPath(node.Box, node.Path)
  312. if nil != baseBlock {
  313. hPath = baseBlock.HPath
  314. }
  315. for parent := node; nil != parent; parent = parent.Parent {
  316. if "" == parent.ID {
  317. continue
  318. }
  319. id := parent.ID
  320. fc := parent.FirstChild
  321. if nil != fc && ast.NodeTaskListItemMarker == fc.Type {
  322. fc = fc.Next
  323. }
  324. name := parent.IALAttr("name")
  325. if ast.NodeDocument == parent.Type {
  326. name = box.Name + hPath
  327. } else if ast.NodeAttributeView == parent.Type {
  328. name, _ = av.GetAttributeViewName(parent.AttributeViewID)
  329. } else {
  330. if "" == name {
  331. if ast.NodeListItem == parent.Type {
  332. name = gulu.Str.SubStr(renderBlockText(fc, excludeTypes), maxNameLen)
  333. } else {
  334. name = gulu.Str.SubStr(renderBlockText(parent, excludeTypes), maxNameLen)
  335. }
  336. }
  337. if ast.NodeHeading == parent.Type {
  338. headingLevel = parent.HeadingLevel
  339. }
  340. }
  341. add := true
  342. if ast.NodeList == parent.Type || ast.NodeSuperBlock == parent.Type || ast.NodeBlockquote == parent.Type {
  343. add = false
  344. }
  345. if ast.NodeParagraph == parent.Type && nil != parent.Parent && ast.NodeListItem == parent.Parent.Type && nil == parent.Next && (nil == parent.Previous || ast.NodeTaskListItemMarker == parent.Previous.Type) {
  346. add = false
  347. }
  348. if ast.NodeListItem == parent.Type {
  349. if "" == name {
  350. name = gulu.Str.SubStr(renderBlockText(fc, excludeTypes), maxNameLen)
  351. }
  352. }
  353. name = strings.ReplaceAll(name, editor.Caret, "")
  354. name = util.EscapeHTML(name)
  355. if add {
  356. ret = append([]*BlockPath{{
  357. ID: id,
  358. Name: name,
  359. Type: parent.Type.String(),
  360. SubType: treenode.SubTypeAbbr(parent),
  361. }}, ret...)
  362. }
  363. for prev := parent.Previous; nil != prev; prev = prev.Previous {
  364. b := prev
  365. if ast.NodeSuperBlock == prev.Type {
  366. // 超级块中包含标题块时下方块面包屑计算不正确 https://github.com/siyuan-note/siyuan/issues/6675
  367. b = treenode.SuperBlockLastHeading(prev)
  368. if nil == b {
  369. // 超级块下方块被作为嵌入块时设置显示面包屑后不渲染 https://github.com/siyuan-note/siyuan/issues/6690
  370. b = prev
  371. }
  372. }
  373. if ast.NodeHeading == b.Type && headingLevel > b.HeadingLevel {
  374. name = gulu.Str.SubStr(renderBlockText(b, excludeTypes), maxNameLen)
  375. name = util.EscapeHTML(name)
  376. ret = append([]*BlockPath{{
  377. ID: b.ID,
  378. Name: name,
  379. Type: b.Type.String(),
  380. SubType: treenode.SubTypeAbbr(b),
  381. }}, ret...)
  382. headingLevel = b.HeadingLevel
  383. }
  384. }
  385. }
  386. return
  387. }