tag.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. ret = &tags
  195. return
  196. }
  197. func sortTags(tags Tags) {
  198. switch Conf.Tag.Sort {
  199. case util.SortModeNameASC:
  200. sort.Slice(tags, func(i, j int) bool {
  201. return util.PinYinCompare(util.RemoveEmojiInvisible(tags[i].Name), util.RemoveEmojiInvisible(tags[j].Name))
  202. })
  203. case util.SortModeNameDESC:
  204. sort.Slice(tags, func(j, i int) bool {
  205. return util.PinYinCompare(util.RemoveEmojiInvisible(tags[i].Name), util.RemoveEmojiInvisible(tags[j].Name))
  206. })
  207. case util.SortModeAlphanumASC:
  208. sort.Slice(tags, func(i, j int) bool {
  209. return natsort.Compare(util.RemoveEmojiInvisible((tags)[i].Name), util.RemoveEmojiInvisible((tags)[j].Name))
  210. })
  211. case util.SortModeAlphanumDESC:
  212. sort.Slice(tags, func(i, j int) bool {
  213. return natsort.Compare(util.RemoveEmojiInvisible((tags)[j].Name), util.RemoveEmojiInvisible((tags)[i].Name))
  214. })
  215. case util.SortModeRefCountASC:
  216. sort.Slice(tags, func(i, j int) bool { return (tags)[i].Count < (tags)[j].Count })
  217. case util.SortModeRefCountDESC:
  218. sort.Slice(tags, func(i, j int) bool { return (tags)[i].Count > (tags)[j].Count })
  219. default:
  220. sort.Slice(tags, func(i, j int) bool {
  221. return natsort.Compare(util.RemoveEmojiInvisible((tags)[i].Name), util.RemoveEmojiInvisible((tags)[j].Name))
  222. })
  223. }
  224. }
  225. func SearchTags(keyword string) (ret []string) {
  226. ret = []string{}
  227. defer logging.Recover() // 定位 无法添加题头图标签 https://github.com/siyuan-note/siyuan/issues/6756
  228. labels := labelBlocksByKeyword(keyword)
  229. for label, _ := range labels {
  230. _, t := search.MarkText(label, keyword, 1024, Conf.Search.CaseSensitive)
  231. ret = append(ret, t)
  232. }
  233. sort.Strings(ret)
  234. return
  235. }
  236. func labelBlocksByKeyword(keyword string) (ret map[string]TagBlocks) {
  237. ret = map[string]TagBlocks{}
  238. tags := sql.QueryTagSpansByKeyword(keyword, Conf.Search.Limit)
  239. set := hashset.New()
  240. for _, tag := range tags {
  241. set.Add(tag.BlockID)
  242. }
  243. var blockIDs []string
  244. for _, v := range set.Values() {
  245. blockIDs = append(blockIDs, v.(string))
  246. }
  247. sort.SliceStable(blockIDs, func(i, j int) bool {
  248. return blockIDs[i] > blockIDs[j]
  249. })
  250. sqlBlocks := sql.GetBlocks(blockIDs)
  251. blockMap := map[string]*sql.Block{}
  252. for _, block := range sqlBlocks {
  253. if nil == block {
  254. continue
  255. }
  256. blockMap[block.ID] = block
  257. }
  258. for _, tag := range tags {
  259. label := tag.Content
  260. parentSQLBlock := blockMap[tag.BlockID]
  261. block := fromSQLBlock(parentSQLBlock, "", 0)
  262. if blocks, ok := ret[label]; ok {
  263. blocks = append(blocks, block)
  264. ret[label] = blocks
  265. } else {
  266. ret[label] = []*Block{block}
  267. }
  268. }
  269. return
  270. }
  271. func labelTags() (ret map[string]Tags) {
  272. ret = map[string]Tags{}
  273. tagSpans := sql.QueryTagSpans("")
  274. for _, tagSpan := range tagSpans {
  275. label := tagSpan.Content
  276. if _, ok := ret[label]; ok {
  277. ret[label] = append(ret[label], &Tag{})
  278. } else {
  279. ret[label] = Tags{}
  280. }
  281. }
  282. return
  283. }
  284. func appendTagChildren(tags *Tags, labels map[string]Tags) {
  285. for _, tag := range *tags {
  286. tag.Label = tag.Name
  287. if _, ok := labels[tag.Label]; ok {
  288. tag.Count = len(labels[tag.Label]) + 1
  289. }
  290. appendChildren0(tag, labels)
  291. sortTags(tag.Children)
  292. }
  293. }
  294. func appendChildren0(tag *Tag, labels map[string]Tags) {
  295. sortTags(tag.tags)
  296. for _, t := range tag.tags {
  297. t.Label = tag.Label + "/" + t.Name
  298. if _, ok := labels[t.Label]; ok {
  299. t.Count = len(labels[t.Label]) + 1
  300. }
  301. tag.Children = append(tag.Children, t)
  302. }
  303. for _, child := range tag.tags {
  304. appendChildren0(child, labels)
  305. }
  306. }
  307. func buildTags(root Tags, labels []string, depth int) Tags {
  308. if 1 > len(labels) {
  309. return root
  310. }
  311. i := 0
  312. for ; i < len(root); i++ {
  313. if (root)[i].Name == labels[0] {
  314. break
  315. }
  316. }
  317. if i == len(root) {
  318. root = append(root, &Tag{Name: util.EscapeHTML(labels[0]), Type: "tag", Depth: depth})
  319. }
  320. depth++
  321. root[i].tags = buildTags(root[i].tags, labels[1:], depth)
  322. return root
  323. }