guilds_tree.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "github.com/ayn2op/discordo/internal/clipboard"
  6. "github.com/ayn2op/discordo/internal/config"
  7. "github.com/ayn2op/discordo/internal/ui"
  8. "github.com/ayn2op/tview"
  9. "github.com/ayn2op/tview/help"
  10. "github.com/ayn2op/tview/keybind"
  11. "github.com/diamondburned/arikawa/v3/discord"
  12. "github.com/diamondburned/arikawa/v3/gateway"
  13. "github.com/diamondburned/ningen/v3"
  14. "github.com/gdamore/tcell/v3"
  15. )
  16. type dmNode struct{}
  17. type guildsTree struct {
  18. *tview.TreeView
  19. chat *Model
  20. cfg *config.Config
  21. // Fast-path indexes for frequent event handlers (read updates, picker
  22. // navigation). They mirror the current rendered tree and are rebuilt on
  23. // READY before nodes are added.
  24. guildNodeByID map[discord.GuildID]*tview.TreeNode
  25. channelNodeByID map[discord.ChannelID]*tview.TreeNode
  26. dmRootNode *tview.TreeNode
  27. }
  28. var _ help.KeyMap = (*guildsTree)(nil)
  29. func newGuildsTree(cfg *config.Config, chatView *Model) *guildsTree {
  30. gt := &guildsTree{
  31. TreeView: tview.NewTreeView(),
  32. cfg: cfg,
  33. chat: chatView,
  34. guildNodeByID: make(map[discord.GuildID]*tview.TreeNode),
  35. channelNodeByID: make(map[discord.ChannelID]*tview.TreeNode),
  36. }
  37. gt.Box = ui.ConfigureBox(gt.Box, &cfg.Theme)
  38. gt.
  39. SetRoot(tview.NewTreeNode("")).
  40. SetTopLevel(1).
  41. SetMarkers(tview.TreeMarkers{
  42. Expanded: cfg.Sidebar.Markers.Expanded,
  43. Collapsed: cfg.Sidebar.Markers.Collapsed,
  44. Leaf: cfg.Sidebar.Markers.Leaf,
  45. }).
  46. SetGraphics(cfg.Theme.GuildsTree.Graphics).
  47. SetGraphicsColor(tcell.GetColor(cfg.Theme.GuildsTree.GraphicsColor)).
  48. SetTitle("Guilds")
  49. return gt
  50. }
  51. func (gt *guildsTree) ShortHelp() []keybind.Keybind {
  52. cfg := gt.cfg.Keybinds.GuildsTree
  53. selectCurrent := cfg.SelectCurrent.Keybind
  54. collapseParent := cfg.CollapseParentNode.Keybind
  55. selectHelp := selectCurrent.Help()
  56. selectDesc := selectHelp.Desc
  57. if node := gt.GetCurrentNode(); node != nil {
  58. if len(node.GetChildren()) > 0 {
  59. if node.IsExpanded() {
  60. selectDesc = "collapse"
  61. } else {
  62. selectDesc = "expand"
  63. }
  64. } else {
  65. switch node.GetReference().(type) {
  66. case discord.GuildID, dmNode:
  67. selectDesc = "expand"
  68. }
  69. }
  70. }
  71. selectCurrent.SetHelp(selectHelp.Key, selectDesc)
  72. collapseHelp := collapseParent.Help()
  73. collapseParent.SetHelp(collapseHelp.Key, "collapse parent")
  74. shortHelp := []keybind.Keybind{cfg.Up.Keybind, cfg.Down.Keybind, selectCurrent}
  75. if gt.canCollapseParent(gt.GetCurrentNode()) {
  76. shortHelp = append(shortHelp, collapseParent)
  77. }
  78. return shortHelp
  79. }
  80. func (gt *guildsTree) FullHelp() [][]keybind.Keybind {
  81. cfg := gt.cfg.Keybinds.GuildsTree
  82. selectCurrent := cfg.SelectCurrent.Keybind
  83. collapseParent := cfg.CollapseParentNode.Keybind
  84. selectHelp := selectCurrent.Help()
  85. selectDesc := selectHelp.Desc
  86. if node := gt.GetCurrentNode(); node != nil {
  87. if len(node.GetChildren()) > 0 {
  88. if node.IsExpanded() {
  89. selectDesc = "collapse"
  90. } else {
  91. selectDesc = "expand"
  92. }
  93. } else {
  94. switch node.GetReference().(type) {
  95. case discord.GuildID, dmNode:
  96. selectDesc = "expand"
  97. }
  98. }
  99. }
  100. selectCurrent.SetHelp(selectHelp.Key, selectDesc)
  101. collapseHelp := collapseParent.Help()
  102. collapseParent.SetHelp(collapseHelp.Key, "collapse parent")
  103. actions := []keybind.Keybind{selectCurrent, cfg.MoveToParentNode.Keybind}
  104. if gt.canCollapseParent(gt.GetCurrentNode()) {
  105. actions = append(actions, collapseParent)
  106. }
  107. return [][]keybind.Keybind{
  108. {cfg.Up.Keybind, cfg.Down.Keybind, cfg.Top.Keybind, cfg.Bottom.Keybind},
  109. actions,
  110. {cfg.YankID.Keybind},
  111. }
  112. }
  113. func (gt *guildsTree) canCollapseParent(node *tview.TreeNode) bool {
  114. if node == nil {
  115. return false
  116. }
  117. path := gt.GetPath(node)
  118. // Path layout is [root, ..., node]. A non-root parent means at least 3 nodes.
  119. if len(path) < 3 {
  120. return false
  121. }
  122. parent := path[len(path)-2]
  123. return parent != nil && parent.GetLevel() != 0
  124. }
  125. func (gt *guildsTree) resetNodeIndex() {
  126. // Keep allocated map capacity; READY can rebuild often during reconnects.
  127. clear(gt.guildNodeByID)
  128. clear(gt.channelNodeByID)
  129. gt.dmRootNode = nil
  130. }
  131. func (gt *guildsTree) createFolderNode(folder gateway.GuildFolder, guildsByID map[discord.GuildID]*gateway.GuildCreateEvent) {
  132. name := "Folder"
  133. if folder.Name != "" {
  134. name = folder.Name
  135. }
  136. folderNode := tview.NewTreeNode(name).SetExpanded(gt.cfg.Theme.GuildsTree.AutoExpandFolders)
  137. if folder.Color != 0 {
  138. folderStyle := tcell.StyleDefault.Foreground(tcell.NewHexColor(int32(folder.Color)))
  139. gt.setNodeLineStyle(folderNode, folderStyle)
  140. }
  141. gt.GetRoot().AddChild(folderNode)
  142. for _, guildID := range folder.GuildIDs {
  143. if guildEvent, ok := guildsByID[guildID]; ok {
  144. gt.createGuildNode(folderNode, guildEvent.Guild)
  145. }
  146. }
  147. }
  148. func (gt *guildsTree) unreadStyle(indication ningen.UnreadIndication) tcell.Style {
  149. var style tcell.Style
  150. switch indication {
  151. case ningen.ChannelRead:
  152. style = style.Dim(true)
  153. case ningen.ChannelMentioned:
  154. style = style.Underline(true)
  155. fallthrough
  156. case ningen.ChannelUnread:
  157. style = style.Bold(true)
  158. }
  159. return style
  160. }
  161. func (gt *guildsTree) getGuildNodeStyle(guildID discord.GuildID) tcell.Style {
  162. indication := gt.chat.state.GuildIsUnread(guildID, ningen.GuildUnreadOpts{UnreadOpts: ningen.UnreadOpts{IncludeMutedCategories: true}})
  163. return gt.unreadStyle(indication)
  164. }
  165. func (gt *guildsTree) getChannelNodeStyle(channelID discord.ChannelID) tcell.Style {
  166. indication := gt.chat.state.ChannelIsUnread(channelID, ningen.UnreadOpts{IncludeMutedCategories: true})
  167. return gt.unreadStyle(indication)
  168. }
  169. func (gt *guildsTree) createGuildNode(n *tview.TreeNode, guild discord.Guild) {
  170. guildNode := tview.NewTreeNode(guild.Name).
  171. SetReference(guild.ID).
  172. SetExpandable(true).
  173. SetExpanded(false).
  174. SetIndent(gt.cfg.Theme.GuildsTree.Indents.Guild)
  175. gt.setNodeLineStyle(guildNode, gt.getGuildNodeStyle(guild.ID))
  176. n.AddChild(guildNode)
  177. gt.guildNodeByID[guild.ID] = guildNode
  178. }
  179. func (gt *guildsTree) createChannelNode(node *tview.TreeNode, channel discord.Channel) {
  180. if channel.Type != discord.DirectMessage && channel.Type != discord.GroupDM && channel.Type != discord.GuildCategory && !gt.chat.state.HasPermissions(channel.ID, discord.PermissionViewChannel) {
  181. return
  182. }
  183. channelNode := tview.NewTreeNode(ui.ChannelToString(channel, gt.cfg.Icons, gt.chat.state)).SetReference(channel.ID)
  184. gt.setNodeLineStyle(channelNode, gt.getChannelNodeStyle(channel.ID))
  185. switch channel.Type {
  186. case discord.DirectMessage:
  187. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.DM)
  188. case discord.GroupDM:
  189. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.GroupDM)
  190. case discord.GuildCategory:
  191. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Category)
  192. channelNode.SetExpandable(true).SetExpanded(true)
  193. case discord.GuildForum:
  194. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Forum)
  195. channelNode.SetExpandable(true).SetExpanded(false)
  196. default:
  197. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Channel)
  198. }
  199. node.AddChild(channelNode)
  200. gt.channelNodeByID[channel.ID] = channelNode
  201. gt.setNodeLineStyle(channelNode, gt.getChannelNodeStyle(channel.ID))
  202. }
  203. func (gt *guildsTree) setNodeLineStyle(node *tview.TreeNode, style tcell.Style) {
  204. line := node.GetLine()
  205. for i := range line {
  206. line[i].Style = style
  207. }
  208. node.SetLine(line)
  209. }
  210. func (gt *guildsTree) createChannelNodes(node *tview.TreeNode, channels []discord.Channel) {
  211. // Preserve exact ordering semantics:
  212. // 1) top-level non-categories (in input order),
  213. // 2) categories that have at least one child in the source slice (in input order),
  214. // 3) parented channels under already-created categories (in input order).
  215. //
  216. // We precompute parent presence once to avoid the O(n^2) category-child scan.
  217. hasChildByParentID := make(map[discord.ChannelID]struct{}, len(channels))
  218. for _, channel := range channels {
  219. if channel.ParentID.IsValid() {
  220. hasChildByParentID[channel.ParentID] = struct{}{}
  221. }
  222. }
  223. for _, channel := range channels {
  224. if channel.Type != discord.GuildCategory && !channel.ParentID.IsValid() {
  225. gt.createChannelNode(node, channel)
  226. }
  227. }
  228. for _, channel := range channels {
  229. if channel.Type == discord.GuildCategory {
  230. if _, ok := hasChildByParentID[channel.ID]; ok {
  231. gt.createChannelNode(node, channel)
  232. }
  233. }
  234. }
  235. for _, channel := range channels {
  236. if channel.ParentID.IsValid() {
  237. // Parent categories are inserted earlier in this function, so this
  238. // lookup is O(1) and avoids per-channel subtree walks.
  239. parent := gt.channelNodeByID[channel.ParentID]
  240. if parent != nil {
  241. gt.createChannelNode(parent, channel)
  242. }
  243. }
  244. }
  245. }
  246. func (gt *guildsTree) onSelected(node *tview.TreeNode) {
  247. if len(node.GetChildren()) != 0 {
  248. node.SetExpanded(!node.IsExpanded())
  249. return
  250. }
  251. switch ref := node.GetReference().(type) {
  252. case discord.GuildID:
  253. go gt.chat.state.MemberState.Subscribe(ref)
  254. channels, err := gt.chat.state.Cabinet.Channels(ref)
  255. if err != nil {
  256. slog.Error("failed to get channels", "err", err, "guild_id", ref)
  257. return
  258. }
  259. ui.SortGuildChannels(channels)
  260. gt.createChannelNodes(node, channels)
  261. node.Expand()
  262. case discord.ChannelID:
  263. channel, err := gt.chat.state.Cabinet.Channel(ref)
  264. if err != nil {
  265. slog.Error("failed to get channel from state", "err", err, "channel_id", ref)
  266. return
  267. }
  268. // Handle forum channels differently - they contain threads, not direct messages
  269. if channel.Type == discord.GuildForum {
  270. // Get all channels from the guild - this includes active threads from GuildCreateEvent
  271. allChannels, err := gt.chat.state.Cabinet.Channels(channel.GuildID)
  272. if err != nil {
  273. slog.Error("failed to get channels for forum threads", "err", err, "guild_id", channel.GuildID)
  274. return
  275. }
  276. // Filter for threads that belong to this forum channel
  277. var forumThreads []discord.Channel
  278. for _, ch := range allChannels {
  279. if ch.ParentID == channel.ID && (ch.Type == discord.GuildPublicThread ||
  280. ch.Type == discord.GuildPrivateThread ||
  281. ch.Type == discord.GuildAnnouncementThread) {
  282. forumThreads = append(forumThreads, ch)
  283. }
  284. }
  285. // Add threads as child nodes
  286. for _, thread := range forumThreads {
  287. gt.createChannelNode(node, thread)
  288. }
  289. node.Expand()
  290. return
  291. }
  292. limit := gt.cfg.MessagesLimit
  293. messages, err := gt.chat.state.Messages(channel.ID, uint(limit))
  294. if err != nil {
  295. slog.Error("failed to get messages", "err", err, "channel_id", channel.ID, "limit", limit)
  296. return
  297. }
  298. go gt.chat.state.ReadState.MarkRead(channel.ID, channel.LastMessageID)
  299. if guildID := channel.GuildID; guildID.IsValid() {
  300. gt.chat.messagesList.requestGuildMembers(guildID, messages)
  301. }
  302. gt.chat.SetSelectedChannel(channel)
  303. gt.chat.clearTypers()
  304. gt.chat.messageInput.stopTypingTimer()
  305. gt.chat.messagesList.reset()
  306. gt.chat.messagesList.setTitle(*channel)
  307. gt.chat.messagesList.setMessages(messages)
  308. gt.chat.messagesList.ScrollToEnd()
  309. hasNoPerm := channel.Type != discord.DirectMessage && channel.Type != discord.GroupDM && !gt.chat.state.HasPermissions(channel.ID, discord.PermissionSendMessages)
  310. gt.chat.messageInput.SetDisabled(hasNoPerm)
  311. var text string
  312. if hasNoPerm {
  313. text = "You do not have permission to send messages in this channel."
  314. } else {
  315. text = "Message..."
  316. if gt.cfg.AutoFocus {
  317. gt.chat.app.SetFocus(gt.chat.messageInput)
  318. }
  319. }
  320. gt.chat.messageInput.SetPlaceholder(tview.NewLine(tview.NewSegment(text, tcell.StyleDefault.Dim(true))))
  321. case dmNode: // Direct messages folder
  322. channels, err := gt.chat.state.PrivateChannels()
  323. if err != nil {
  324. slog.Error("failed to get private channels", "err", err)
  325. return
  326. }
  327. ui.SortPrivateChannels(channels)
  328. for _, c := range channels {
  329. gt.createChannelNode(node, c)
  330. }
  331. node.Expand()
  332. }
  333. }
  334. func (gt *guildsTree) collapseParentNode(node *tview.TreeNode) {
  335. gt.
  336. GetRoot().
  337. Walk(func(n, parent *tview.TreeNode) bool {
  338. if n == node && parent.GetLevel() != 0 {
  339. parent.Collapse()
  340. gt.SetCurrentNode(parent)
  341. return false
  342. }
  343. return true
  344. })
  345. }
  346. func (gt *guildsTree) HandleEvent(event tview.Event) tview.Command {
  347. switch event := event.(type) {
  348. case *tview.TreeViewSelectedEvent:
  349. gt.onSelected(event.Node)
  350. return nil
  351. case *tview.KeyEvent:
  352. handler := gt.TreeView.HandleEvent
  353. switch {
  354. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.CollapseParentNode.Keybind):
  355. gt.collapseParentNode(gt.GetCurrentNode())
  356. return nil
  357. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.MoveToParentNode.Keybind):
  358. return handler(tcell.NewEventKey(tcell.KeyRune, "K", tcell.ModNone))
  359. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Up.Keybind):
  360. return handler(tcell.NewEventKey(tcell.KeyUp, "", tcell.ModNone))
  361. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Down.Keybind):
  362. return handler(tcell.NewEventKey(tcell.KeyDown, "", tcell.ModNone))
  363. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Top.Keybind):
  364. gt.Move(gt.GetRowCount() * -1)
  365. return nil
  366. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Bottom.Keybind):
  367. gt.Move(gt.GetRowCount())
  368. return nil
  369. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.SelectCurrent.Keybind):
  370. return handler(tcell.NewEventKey(tcell.KeyEnter, "", tcell.ModNone))
  371. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.YankID.Keybind):
  372. return gt.yankID()
  373. }
  374. // Do not fall through to TreeView defaults for unmatched keys.
  375. return nil
  376. }
  377. return gt.TreeView.HandleEvent(event)
  378. }
  379. func (gt *guildsTree) yankID() tview.Command {
  380. node := gt.GetCurrentNode()
  381. if node == nil {
  382. return nil
  383. }
  384. // Reference of a tree node in the guilds tree is its ID.
  385. // discord.Snowflake (discord.GuildID and discord.ChannelID) have the String method.
  386. if id, ok := node.GetReference().(fmt.Stringer); ok {
  387. return func() tview.Event {
  388. if err := clipboard.Write(clipboard.FmtText, []byte(id.String())); err != nil {
  389. slog.Error("failed to copy node id", "err", err)
  390. }
  391. return nil
  392. }
  393. }
  394. return nil
  395. }
  396. func (gt *guildsTree) findNodeByReference(reference any) *tview.TreeNode {
  397. switch ref := reference.(type) {
  398. case discord.GuildID:
  399. return gt.guildNodeByID[ref]
  400. case discord.ChannelID:
  401. return gt.channelNodeByID[ref]
  402. case dmNode:
  403. return gt.dmRootNode
  404. default:
  405. // Fallback keeps this helper safe for non-indexed custom references.
  406. var found *tview.TreeNode
  407. gt.GetRoot().Walk(func(node, _ *tview.TreeNode) bool {
  408. if node.GetReference() == reference {
  409. found = node
  410. return false
  411. }
  412. return true
  413. })
  414. return found
  415. }
  416. }
  417. func (gt *guildsTree) findNodeByChannelID(channelID discord.ChannelID) *tview.TreeNode {
  418. channel, err := gt.chat.state.Cabinet.Channel(channelID)
  419. if err != nil {
  420. slog.Error("failed to get channel", "channel_id", channelID, "err", err)
  421. return nil
  422. }
  423. var reference any
  424. if guildID := channel.GuildID; guildID.IsValid() {
  425. reference = guildID
  426. } else {
  427. reference = dmNode{}
  428. }
  429. if parentNode := gt.findNodeByReference(reference); parentNode != nil {
  430. if len(parentNode.GetChildren()) == 0 {
  431. gt.onSelected(parentNode)
  432. }
  433. }
  434. node := gt.findNodeByReference(channelID)
  435. return node
  436. }
  437. func (gt *guildsTree) expandPathToNode(node *tview.TreeNode) {
  438. if node == nil {
  439. return
  440. }
  441. for _, n := range gt.GetPath(node) {
  442. n.Expand()
  443. }
  444. }