tag.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. "fmt"
  20. "sort"
  21. "strings"
  22. "github.com/88250/lute/ast"
  23. "github.com/emirpasic/gods/sets/hashset"
  24. "github.com/facette/natsort"
  25. "github.com/siyuan-note/logging"
  26. "github.com/siyuan-note/siyuan/kernel/search"
  27. "github.com/siyuan-note/siyuan/kernel/sql"
  28. "github.com/siyuan-note/siyuan/kernel/treenode"
  29. "github.com/siyuan-note/siyuan/kernel/util"
  30. )
  31. func RemoveTag(label string) (err error) {
  32. if "" == label {
  33. return
  34. }
  35. util.PushEndlessProgress(Conf.Language(116))
  36. util.RandomSleep(1000, 2000)
  37. tags := sql.QueryTagSpansByLabel(label)
  38. treeBlocks := map[string][]string{}
  39. for _, tag := range tags {
  40. if blocks, ok := treeBlocks[tag.RootID]; !ok {
  41. treeBlocks[tag.RootID] = []string{tag.BlockID}
  42. } else {
  43. treeBlocks[tag.RootID] = append(blocks, tag.BlockID)
  44. }
  45. }
  46. for treeID, blocks := range treeBlocks {
  47. util.PushEndlessProgress("[" + treeID + "]")
  48. tree, e := LoadTreeByBlockID(treeID)
  49. if nil != e {
  50. util.ClearPushProgress(100)
  51. return e
  52. }
  53. var unlinks []*ast.Node
  54. for _, blockID := range blocks {
  55. node := treenode.GetNodeInTree(tree, blockID)
  56. if nil == node {
  57. continue
  58. }
  59. if ast.NodeDocument == node.Type {
  60. if docTagsVal := node.IALAttr("tags"); strings.Contains(docTagsVal, label) {
  61. docTags := strings.Split(docTagsVal, ",")
  62. var tmp []string
  63. for _, docTag := range docTags {
  64. if docTag != label {
  65. tmp = append(tmp, docTag)
  66. continue
  67. }
  68. }
  69. node.SetIALAttr("tags", strings.Join(tmp, ","))
  70. }
  71. continue
  72. }
  73. nodeTags := node.ChildrenByType(ast.NodeTextMark)
  74. for _, nodeTag := range nodeTags {
  75. if nodeTag.IsTextMarkType("tag") {
  76. if label == nodeTag.TextMarkTextContent {
  77. unlinks = append(unlinks, nodeTag)
  78. }
  79. }
  80. }
  81. }
  82. for _, n := range unlinks {
  83. n.Unlink()
  84. }
  85. util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))
  86. if err = writeTreeUpsertQueue(tree); nil != err {
  87. util.ClearPushProgress(100)
  88. return
  89. }
  90. util.RandomSleep(50, 150)
  91. }
  92. util.ReloadUI()
  93. return
  94. }
  95. func RenameTag(oldLabel, newLabel string) (err error) {
  96. if invalidChar := treenode.ContainsMarker(newLabel); "" != invalidChar {
  97. return errors.New(fmt.Sprintf(Conf.Language(112), invalidChar))
  98. }
  99. newLabel = strings.TrimSpace(newLabel)
  100. newLabel = strings.TrimPrefix(newLabel, "/")
  101. newLabel = strings.TrimSuffix(newLabel, "/")
  102. newLabel = strings.TrimSpace(newLabel)
  103. if "" == newLabel {
  104. return errors.New(Conf.Language(114))
  105. }
  106. if oldLabel == newLabel {
  107. return
  108. }
  109. util.PushEndlessProgress(Conf.Language(110))
  110. util.RandomSleep(500, 1000)
  111. tags := sql.QueryTagSpansByLabel(oldLabel)
  112. treeBlocks := map[string][]string{}
  113. for _, tag := range tags {
  114. if blocks, ok := treeBlocks[tag.RootID]; !ok {
  115. treeBlocks[tag.RootID] = []string{tag.BlockID}
  116. } else {
  117. treeBlocks[tag.RootID] = append(blocks, tag.BlockID)
  118. }
  119. }
  120. for treeID, blocks := range treeBlocks {
  121. util.PushEndlessProgress("[" + treeID + "]")
  122. tree, e := LoadTreeByBlockID(treeID)
  123. if nil != e {
  124. util.ClearPushProgress(100)
  125. return e
  126. }
  127. for _, blockID := range blocks {
  128. node := treenode.GetNodeInTree(tree, blockID)
  129. if nil == node {
  130. continue
  131. }
  132. if ast.NodeDocument == node.Type {
  133. if docTagsVal := node.IALAttr("tags"); strings.Contains(docTagsVal, oldLabel) {
  134. docTags := strings.Split(docTagsVal, ",")
  135. var tmp []string
  136. for _, docTag := range docTags {
  137. if strings.HasPrefix(docTag, oldLabel+"/") || docTag == oldLabel {
  138. docTag = strings.Replace(docTag, oldLabel, newLabel, 1)
  139. tmp = append(tmp, docTag)
  140. } else {
  141. tmp = append(tmp, docTag)
  142. }
  143. }
  144. node.SetIALAttr("tags", strings.Join(tmp, ","))
  145. }
  146. continue
  147. }
  148. nodeTags := node.ChildrenByType(ast.NodeTextMark)
  149. for _, nodeTag := range nodeTags {
  150. if nodeTag.IsTextMarkType("tag") {
  151. if strings.HasPrefix(nodeTag.TextMarkTextContent, oldLabel+"/") || nodeTag.TextMarkTextContent == oldLabel {
  152. nodeTag.TextMarkTextContent = strings.Replace(nodeTag.TextMarkTextContent, oldLabel, newLabel, 1)
  153. }
  154. }
  155. }
  156. }
  157. util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))
  158. if err = writeTreeUpsertQueue(tree); nil != err {
  159. util.ClearPushProgress(100)
  160. return
  161. }
  162. util.RandomSleep(50, 150)
  163. }
  164. util.ReloadUI()
  165. return
  166. }
  167. type TagBlocks []*Block
  168. func (s TagBlocks) Len() int { return len(s) }
  169. func (s TagBlocks) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  170. func (s TagBlocks) Less(i, j int) bool { return s[i].ID < s[j].ID }
  171. type Tag struct {
  172. Name string `json:"name"`
  173. Label string `json:"label"`
  174. Children Tags `json:"children"`
  175. Type string `json:"type"` // "tag"
  176. Depth int `json:"depth"`
  177. Count int `json:"count"`
  178. tags Tags
  179. }
  180. type Tags []*Tag
  181. func BuildTags() (ret *Tags) {
  182. WaitForWritingFiles()
  183. if !sql.IsEmptyQueue() {
  184. sql.WaitForWritingDatabase()
  185. }
  186. ret = &Tags{}
  187. labels := labelTags()
  188. tags := Tags{}
  189. for label, _ := range labels {
  190. tags = buildTags(tags, strings.Split(label, "/"), 0)
  191. }
  192. appendTagChildren(&tags, labels)
  193. sortTags(tags)
  194. var total int
  195. tmp := &Tags{}
  196. for _, tag := range tags {
  197. *tmp = append(*tmp, tag)
  198. countTag(tag, &total)
  199. if Conf.FileTree.MaxListCount < total {
  200. util.PushMsg(fmt.Sprintf(Conf.Language(243), Conf.FileTree.MaxListCount), 7000)
  201. break
  202. }
  203. }
  204. ret = tmp
  205. return
  206. }
  207. func countTag(tag *Tag, total *int) {
  208. *total += 1
  209. for _, child := range tag.tags {
  210. countTag(child, total)
  211. }
  212. }
  213. func sortTags(tags Tags) {
  214. switch Conf.Tag.Sort {
  215. case util.SortModeNameASC:
  216. sort.Slice(tags, func(i, j int) bool {
  217. return util.PinYinCompare(util.RemoveEmojiInvisible(tags[i].Name), util.RemoveEmojiInvisible(tags[j].Name))
  218. })
  219. case util.SortModeNameDESC:
  220. sort.Slice(tags, func(j, i int) bool {
  221. return util.PinYinCompare(util.RemoveEmojiInvisible(tags[i].Name), util.RemoveEmojiInvisible(tags[j].Name))
  222. })
  223. case util.SortModeAlphanumASC:
  224. sort.Slice(tags, func(i, j int) bool {
  225. return natsort.Compare(util.RemoveEmojiInvisible((tags)[i].Name), util.RemoveEmojiInvisible((tags)[j].Name))
  226. })
  227. case util.SortModeAlphanumDESC:
  228. sort.Slice(tags, func(i, j int) bool {
  229. return natsort.Compare(util.RemoveEmojiInvisible((tags)[j].Name), util.RemoveEmojiInvisible((tags)[i].Name))
  230. })
  231. case util.SortModeRefCountASC:
  232. sort.Slice(tags, func(i, j int) bool { return (tags)[i].Count < (tags)[j].Count })
  233. case util.SortModeRefCountDESC:
  234. sort.Slice(tags, func(i, j int) bool { return (tags)[i].Count > (tags)[j].Count })
  235. default:
  236. sort.Slice(tags, func(i, j int) bool {
  237. return natsort.Compare(util.RemoveEmojiInvisible((tags)[i].Name), util.RemoveEmojiInvisible((tags)[j].Name))
  238. })
  239. }
  240. }
  241. func SearchTags(keyword string) (ret []string) {
  242. ret = []string{}
  243. defer logging.Recover() // 定位 无法添加题头图标签 https://github.com/siyuan-note/siyuan/issues/6756
  244. labels := labelBlocksByKeyword(keyword)
  245. for label, _ := range labels {
  246. _, t := search.MarkText(label, keyword, 1024, Conf.Search.CaseSensitive)
  247. ret = append(ret, t)
  248. }
  249. sort.Strings(ret)
  250. return
  251. }
  252. func labelBlocksByKeyword(keyword string) (ret map[string]TagBlocks) {
  253. ret = map[string]TagBlocks{}
  254. tags := sql.QueryTagSpansByKeyword(keyword, Conf.Search.Limit)
  255. set := hashset.New()
  256. for _, tag := range tags {
  257. set.Add(tag.BlockID)
  258. }
  259. var blockIDs []string
  260. for _, v := range set.Values() {
  261. blockIDs = append(blockIDs, v.(string))
  262. }
  263. sort.SliceStable(blockIDs, func(i, j int) bool {
  264. return blockIDs[i] > blockIDs[j]
  265. })
  266. sqlBlocks := sql.GetBlocks(blockIDs)
  267. blockMap := map[string]*sql.Block{}
  268. for _, block := range sqlBlocks {
  269. if nil == block {
  270. continue
  271. }
  272. blockMap[block.ID] = block
  273. }
  274. for _, tag := range tags {
  275. label := tag.Content
  276. parentSQLBlock := blockMap[tag.BlockID]
  277. block := fromSQLBlock(parentSQLBlock, "", 0)
  278. if blocks, ok := ret[label]; ok {
  279. blocks = append(blocks, block)
  280. ret[label] = blocks
  281. } else {
  282. ret[label] = []*Block{block}
  283. }
  284. }
  285. return
  286. }
  287. func labelTags() (ret map[string]Tags) {
  288. ret = map[string]Tags{}
  289. tagSpans := sql.QueryTagSpans("")
  290. for _, tagSpan := range tagSpans {
  291. label := tagSpan.Content
  292. if _, ok := ret[label]; ok {
  293. ret[label] = append(ret[label], &Tag{})
  294. } else {
  295. ret[label] = Tags{}
  296. }
  297. }
  298. return
  299. }
  300. func appendTagChildren(tags *Tags, labels map[string]Tags) {
  301. for _, tag := range *tags {
  302. tag.Label = tag.Name
  303. if _, ok := labels[tag.Label]; ok {
  304. tag.Count = len(labels[tag.Label]) + 1
  305. }
  306. appendChildren0(tag, labels)
  307. sortTags(tag.Children)
  308. }
  309. }
  310. func appendChildren0(tag *Tag, labels map[string]Tags) {
  311. sortTags(tag.tags)
  312. for _, t := range tag.tags {
  313. t.Label = tag.Label + "/" + t.Name
  314. if _, ok := labels[t.Label]; ok {
  315. t.Count = len(labels[t.Label]) + 1
  316. }
  317. tag.Children = append(tag.Children, t)
  318. }
  319. for _, child := range tag.tags {
  320. appendChildren0(child, labels)
  321. }
  322. }
  323. func buildTags(root Tags, labels []string, depth int) Tags {
  324. if 1 > len(labels) {
  325. return root
  326. }
  327. i := 0
  328. for ; i < len(root); i++ {
  329. if (root)[i].Name == labels[0] {
  330. break
  331. }
  332. }
  333. if i == len(root) {
  334. root = append(root, &Tag{Name: util.EscapeHTML(labels[0]), Type: "tag", Depth: depth})
  335. }
  336. depth++
  337. root[i].tags = buildTags(root[i].tags, labels[1:], depth)
  338. return root
  339. }