heading.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. "errors"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "strings"
  23. "github.com/88250/gulu"
  24. "github.com/88250/lute/ast"
  25. "github.com/88250/lute/parse"
  26. "github.com/siyuan-note/logging"
  27. "github.com/siyuan-note/siyuan/kernel/cache"
  28. "github.com/siyuan-note/siyuan/kernel/sql"
  29. "github.com/siyuan-note/siyuan/kernel/treenode"
  30. "github.com/siyuan-note/siyuan/kernel/util"
  31. )
  32. func (tx *Transaction) doFoldHeading(operation *Operation) (ret *TxErr) {
  33. headingID := operation.ID
  34. tree, err := tx.loadTree(headingID)
  35. if nil != err {
  36. return &TxErr{code: TxErrCodeBlockNotFound, id: headingID}
  37. }
  38. childrenIDs := []string{} // 这里不能用 nil,否则折叠下方没内容的标题时会内核中断 https://github.com/siyuan-note/siyuan/issues/3643
  39. heading := treenode.GetNodeInTree(tree, headingID)
  40. if nil == heading {
  41. return &TxErr{code: TxErrCodeBlockNotFound, id: headingID}
  42. }
  43. children := treenode.HeadingChildren(heading)
  44. for _, child := range children {
  45. childrenIDs = append(childrenIDs, child.ID)
  46. ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {
  47. if !entering || !n.IsBlock() {
  48. return ast.WalkContinue
  49. }
  50. n.SetIALAttr("heading-fold", "1")
  51. return ast.WalkContinue
  52. })
  53. }
  54. heading.SetIALAttr("fold", "1")
  55. if err = tx.writeTree(tree); nil != err {
  56. return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: headingID}
  57. }
  58. IncSync()
  59. cache.PutBlockIAL(headingID, parse.IAL2Map(heading.KramdownIAL))
  60. for _, child := range children {
  61. cache.PutBlockIAL(child.ID, parse.IAL2Map(child.KramdownIAL))
  62. }
  63. sql.UpsertTreeQueue(tree)
  64. operation.RetData = childrenIDs
  65. return
  66. }
  67. func (tx *Transaction) doUnfoldHeading(operation *Operation) (ret *TxErr) {
  68. headingID := operation.ID
  69. tree, err := tx.loadTree(headingID)
  70. if nil != err {
  71. return &TxErr{code: TxErrCodeBlockNotFound, id: headingID}
  72. }
  73. heading := treenode.GetNodeInTree(tree, headingID)
  74. if nil == heading {
  75. return &TxErr{code: TxErrCodeBlockNotFound, id: headingID}
  76. }
  77. children := treenode.HeadingChildren(heading)
  78. for _, child := range children {
  79. ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {
  80. if !entering {
  81. return ast.WalkContinue
  82. }
  83. n.RemoveIALAttr("heading-fold")
  84. n.RemoveIALAttr("fold")
  85. return ast.WalkContinue
  86. })
  87. }
  88. heading.RemoveIALAttr("fold")
  89. heading.RemoveIALAttr("heading-fold")
  90. if err = tx.writeTree(tree); nil != err {
  91. return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: headingID}
  92. }
  93. IncSync()
  94. cache.PutBlockIAL(headingID, parse.IAL2Map(heading.KramdownIAL))
  95. for _, child := range children {
  96. cache.PutBlockIAL(child.ID, parse.IAL2Map(child.KramdownIAL))
  97. }
  98. sql.UpsertTreeQueue(tree)
  99. luteEngine := NewLute()
  100. operation.RetData = renderBlockDOMByNodes(children, luteEngine)
  101. return
  102. }
  103. func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath string, err error) {
  104. srcTree, _ := LoadTreeByBlockID(srcID)
  105. if nil == srcTree {
  106. err = ErrBlockNotFound
  107. return
  108. }
  109. subDir := filepath.Join(util.DataDir, srcTree.Box, strings.TrimSuffix(srcTree.Path, ".sy"))
  110. if gulu.File.IsDir(subDir) {
  111. if !util.IsEmptyDir(subDir) {
  112. err = errors.New(Conf.Language(20))
  113. return
  114. }
  115. if removeErr := os.Remove(subDir); nil != removeErr { // 移除空文件夹不会有副作用
  116. logging.LogWarnf("remove empty dir [%s] failed: %s", subDir, removeErr)
  117. }
  118. }
  119. targetTree, _ := LoadTreeByBlockID(targetID)
  120. if nil == targetTree {
  121. err = ErrBlockNotFound
  122. return
  123. }
  124. pivot := treenode.GetNodeInTree(targetTree, targetID)
  125. if nil == pivot {
  126. err = ErrBlockNotFound
  127. return
  128. }
  129. // 移动前先删除引用 https://github.com/siyuan-note/siyuan/issues/7819
  130. sql.DeleteRefsTreeQueue(srcTree)
  131. sql.DeleteRefsTreeQueue(targetTree)
  132. if ast.NodeListItem == pivot.Type {
  133. pivot = pivot.LastChild
  134. }
  135. pivotLevel := treenode.HeadingLevel(pivot)
  136. deltaLevel := pivotLevel - treenode.TopHeadingLevel(srcTree) + 1
  137. headingLevel := pivotLevel
  138. if ast.NodeHeading == pivot.Type { // 平级插入
  139. children := treenode.HeadingChildren(pivot)
  140. if after {
  141. if length := len(children); 0 < length {
  142. pivot = children[length-1]
  143. }
  144. }
  145. } else { // 子节点插入
  146. headingLevel++
  147. deltaLevel++
  148. }
  149. if 6 < headingLevel {
  150. headingLevel = 6
  151. }
  152. srcTree.Root.RemoveIALAttr("scroll") // Remove `scroll` attribute when converting the document to a heading https://github.com/siyuan-note/siyuan/issues/9297
  153. srcTree.Root.RemoveIALAttr("type")
  154. tagIAL := srcTree.Root.IALAttr("tags")
  155. tags := strings.Split(tagIAL, ",")
  156. srcTree.Root.RemoveIALAttr("tags")
  157. heading := &ast.Node{ID: srcTree.Root.ID, Type: ast.NodeHeading, HeadingLevel: headingLevel, KramdownIAL: srcTree.Root.KramdownIAL}
  158. heading.SetIALAttr("updated", util.CurrentTimeSecondsStr())
  159. heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(srcTree.Root.IALAttr("title"))})
  160. heading.Box, heading.Path = targetTree.Box, targetTree.Path
  161. if "" != tagIAL && 0 < len(tags) {
  162. // 带标签的文档块转换为标题块时将标签移动到标题块下方 https://github.com/siyuan-note/siyuan/issues/6550
  163. tagPara := treenode.NewParagraph()
  164. for i, tag := range tags {
  165. if "" == tag {
  166. continue
  167. }
  168. tagPara.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: tag})
  169. if i < len(tags)-1 {
  170. tagPara.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
  171. }
  172. }
  173. if nil != tagPara.FirstChild {
  174. srcTree.Root.PrependChild(tagPara)
  175. }
  176. }
  177. var nodes []*ast.Node
  178. if after {
  179. for c := srcTree.Root.LastChild; nil != c; c = c.Previous {
  180. nodes = append(nodes, c)
  181. }
  182. } else {
  183. for c := srcTree.Root.FirstChild; nil != c; c = c.Next {
  184. nodes = append(nodes, c)
  185. }
  186. }
  187. if !after {
  188. pivot.InsertBefore(heading)
  189. }
  190. for _, n := range nodes {
  191. if ast.NodeHeading == n.Type {
  192. n.HeadingLevel = n.HeadingLevel + deltaLevel
  193. if 6 < n.HeadingLevel {
  194. n.HeadingLevel = 6
  195. }
  196. }
  197. n.Box = targetTree.Box
  198. n.Path = targetTree.Path
  199. if after {
  200. pivot.InsertAfter(n)
  201. } else {
  202. pivot.InsertBefore(n)
  203. }
  204. }
  205. if after {
  206. pivot.InsertAfter(heading)
  207. }
  208. if contentPivot := treenode.GetNodeInTree(targetTree, targetID); nil != contentPivot && ast.NodeParagraph == contentPivot.Type && nil == contentPivot.FirstChild { // 插入到空的段落块下
  209. contentPivot.Unlink()
  210. }
  211. box := Conf.Box(srcTree.Box)
  212. if removeErr := box.Remove(srcTree.Path); nil != removeErr {
  213. logging.LogWarnf("remove tree [%s] failed: %s", srcTree.Path, removeErr)
  214. }
  215. box.removeSort([]string{srcTree.ID})
  216. RemoveRecentDoc([]string{srcTree.ID})
  217. evt := util.NewCmdResult("removeDoc", 0, util.PushModeBroadcast)
  218. evt.Data = map[string]interface{}{
  219. "ids": []string{srcTree.ID},
  220. }
  221. util.PushEvent(evt)
  222. srcTreeBox, srcTreePath = srcTree.Box, srcTree.Path // 返回旧的文档块位置,前端后续会删除旧的文档块
  223. targetTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
  224. treenode.RemoveBlockTreesByRootID(srcTree.ID)
  225. treenode.RemoveBlockTreesByRootID(targetTree.ID)
  226. err = indexWriteTreeUpsertQueue(targetTree)
  227. IncSync()
  228. RefreshBacklink(srcTree.ID)
  229. RefreshBacklink(targetTree.ID)
  230. return
  231. }
  232. func Heading2Doc(srcHeadingID, targetBoxID, targetPath string) (srcRootBlockID, newTargetPath string, err error) {
  233. srcTree, _ := LoadTreeByBlockID(srcHeadingID)
  234. if nil == srcTree {
  235. err = ErrBlockNotFound
  236. return
  237. }
  238. srcRootBlockID = srcTree.Root.ID
  239. headingBlock, err := getBlock(srcHeadingID, srcTree)
  240. if nil != err {
  241. return
  242. }
  243. if nil == headingBlock {
  244. err = ErrBlockNotFound
  245. return
  246. }
  247. headingNode := treenode.GetNodeInTree(srcTree, srcHeadingID)
  248. if nil == headingNode {
  249. err = ErrBlockNotFound
  250. return
  251. }
  252. box := Conf.Box(targetBoxID)
  253. headingText := getNodeRefText0(headingNode)
  254. headingText = util.FilterFileName(headingText)
  255. moveToRoot := "/" == targetPath
  256. toHP := path.Join("/", headingText)
  257. toFolder := "/"
  258. if !moveToRoot {
  259. toBlock := treenode.GetBlockTreeRootByPath(targetBoxID, targetPath)
  260. if nil == toBlock {
  261. err = ErrBlockNotFound
  262. return
  263. }
  264. toHP = path.Join(toBlock.HPath, headingText)
  265. toFolder = path.Join(path.Dir(targetPath), toBlock.ID)
  266. }
  267. newTargetPath = path.Join(toFolder, srcHeadingID+".sy")
  268. if !box.Exist(toFolder) {
  269. if err = box.MkdirAll(toFolder); nil != err {
  270. return
  271. }
  272. }
  273. // 折叠标题转换为文档时需要自动展开下方块 https://github.com/siyuan-note/siyuan/issues/2947
  274. children := treenode.HeadingChildren(headingNode)
  275. for _, child := range children {
  276. ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {
  277. if !entering {
  278. return ast.WalkContinue
  279. }
  280. n.RemoveIALAttr("heading-fold")
  281. n.RemoveIALAttr("fold")
  282. return ast.WalkContinue
  283. })
  284. }
  285. headingNode.RemoveIALAttr("fold")
  286. headingNode.RemoveIALAttr("heading-fold")
  287. luteEngine := util.NewLute()
  288. newTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument, ID: srcHeadingID}, Context: &parse.Context{ParseOption: luteEngine.ParseOptions}}
  289. for _, c := range children {
  290. newTree.Root.AppendChild(c)
  291. }
  292. newTree.ID = srcHeadingID
  293. newTree.Path = newTargetPath
  294. newTree.HPath = toHP
  295. headingNode.SetIALAttr("type", "doc")
  296. headingNode.SetIALAttr("id", srcHeadingID)
  297. headingNode.SetIALAttr("title", headingText)
  298. newTree.Root.KramdownIAL = headingNode.KramdownIAL
  299. topLevel := treenode.TopHeadingLevel(newTree)
  300. for c := newTree.Root.FirstChild; nil != c; c = c.Next {
  301. if ast.NodeHeading == c.Type {
  302. c.HeadingLevel = c.HeadingLevel - topLevel + 1
  303. if 6 < c.HeadingLevel {
  304. c.HeadingLevel = 6
  305. }
  306. }
  307. }
  308. headingNode.Unlink()
  309. srcTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
  310. if nil == srcTree.Root.FirstChild {
  311. srcTree.Root.AppendChild(treenode.NewParagraph())
  312. }
  313. treenode.RemoveBlockTreesByRootID(srcTree.ID)
  314. if err = indexWriteTreeUpsertQueue(srcTree); nil != err {
  315. return "", "", err
  316. }
  317. newTree.Box, newTree.Path = targetBoxID, newTargetPath
  318. newTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
  319. newTree.Root.Spec = "1"
  320. box.addMinSort(path.Dir(newTargetPath), newTree.ID)
  321. if err = indexWriteTreeUpsertQueue(newTree); nil != err {
  322. return "", "", err
  323. }
  324. IncSync()
  325. RefreshBacklink(srcTree.ID)
  326. RefreshBacklink(newTree.ID)
  327. return
  328. }