guilds_tree.go 14 KB

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