guilds_tree.go 14 KB

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