heading.go 10 KB

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