guilds_tree.go 15 KB

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