guilds_tree.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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).SetReference(guild.ID).SetExpandable(true)
  172. gt.setNodeLineStyle(guildNode, gt.getGuildNodeStyle(guild.ID))
  173. n.AddChild(guildNode)
  174. gt.guildNodeByID[guild.ID] = guildNode
  175. }
  176. func (gt *guildsTree) createChannelNode(node *tview.TreeNode, channel discord.Channel) {
  177. if channel.Type != discord.DirectMessage && channel.Type != discord.GroupDM && !gt.chatView.state.HasPermissions(channel.ID, discord.PermissionViewChannel) {
  178. return
  179. }
  180. channelNode := tview.NewTreeNode(ui.ChannelToString(channel, gt.cfg.Icons)).SetReference(channel.ID)
  181. if channel.Type == discord.GuildForum {
  182. channelNode.SetExpandable(true)
  183. }
  184. gt.setNodeLineStyle(channelNode, gt.getChannelNodeStyle(channel.ID))
  185. node.AddChild(channelNode)
  186. gt.channelNodeByID[channel.ID] = channelNode
  187. }
  188. func (gt *guildsTree) setNodeLineStyle(node *tview.TreeNode, style tcell.Style) {
  189. line := node.GetLine()
  190. for i := range line {
  191. line[i].Style = style
  192. }
  193. node.SetLine(line)
  194. }
  195. func (gt *guildsTree) createChannelNodes(node *tview.TreeNode, channels []discord.Channel) {
  196. // Preserve exact ordering semantics:
  197. // 1) top-level non-categories (in input order),
  198. // 2) categories that have at least one child in the source slice (in input order),
  199. // 3) parented channels under already-created categories (in input order).
  200. //
  201. // We precompute parent presence once to avoid the O(n^2) category-child scan.
  202. hasChildByParentID := make(map[discord.ChannelID]struct{}, len(channels))
  203. for _, channel := range channels {
  204. if channel.ParentID.IsValid() {
  205. hasChildByParentID[channel.ParentID] = struct{}{}
  206. }
  207. }
  208. for _, channel := range channels {
  209. if channel.Type != discord.GuildCategory && !channel.ParentID.IsValid() {
  210. gt.createChannelNode(node, channel)
  211. }
  212. }
  213. for _, channel := range channels {
  214. if channel.Type == discord.GuildCategory {
  215. if _, ok := hasChildByParentID[channel.ID]; ok {
  216. gt.createChannelNode(node, channel)
  217. }
  218. }
  219. }
  220. for _, channel := range channels {
  221. if channel.ParentID.IsValid() {
  222. // Parent categories are inserted earlier in this function, so this
  223. // lookup is O(1) and avoids per-channel subtree walks.
  224. parent := gt.channelNodeByID[channel.ParentID]
  225. if parent != nil {
  226. gt.createChannelNode(parent, channel)
  227. }
  228. }
  229. }
  230. }
  231. func (gt *guildsTree) onSelected(node *tview.TreeNode) {
  232. if len(node.GetChildren()) != 0 {
  233. node.SetExpanded(!node.IsExpanded())
  234. return
  235. }
  236. switch ref := node.GetReference().(type) {
  237. case discord.GuildID:
  238. go gt.chatView.state.MemberState.Subscribe(ref)
  239. channels, err := gt.chatView.state.Cabinet.Channels(ref)
  240. if err != nil {
  241. slog.Error("failed to get channels", "err", err, "guild_id", ref)
  242. return
  243. }
  244. ui.SortGuildChannels(channels)
  245. gt.createChannelNodes(node, channels)
  246. case discord.ChannelID:
  247. channel, err := gt.chatView.state.Cabinet.Channel(ref)
  248. if err != nil {
  249. slog.Error("failed to get channel from state", "channel_id", ref)
  250. return
  251. }
  252. // Handle forum channels differently - they contain threads, not direct messages
  253. if channel.Type == discord.GuildForum {
  254. // Get all channels from the guild - this includes active threads from GuildCreateEvent
  255. allChannels, err := gt.chatView.state.Cabinet.Channels(channel.GuildID)
  256. if err != nil {
  257. slog.Error("failed to get channels for forum threads", "err", err, "guild_id", channel.GuildID)
  258. return
  259. }
  260. // Filter for threads that belong to this forum channel
  261. var forumThreads []discord.Channel
  262. for _, ch := range allChannels {
  263. if ch.ParentID == channel.ID && (ch.Type == discord.GuildPublicThread ||
  264. ch.Type == discord.GuildPrivateThread ||
  265. ch.Type == discord.GuildAnnouncementThread) {
  266. forumThreads = append(forumThreads, ch)
  267. }
  268. }
  269. // Add threads as child nodes
  270. for _, thread := range forumThreads {
  271. gt.createChannelNode(node, thread)
  272. }
  273. return
  274. }
  275. go gt.chatView.state.ReadState.MarkRead(channel.ID, channel.LastMessageID)
  276. limit := gt.cfg.MessagesLimit
  277. messages, err := gt.chatView.state.Messages(channel.ID, uint(limit))
  278. if err != nil {
  279. slog.Error("failed to get messages", "err", err, "channel_id", channel.ID, "limit", limit)
  280. return
  281. }
  282. if guildID := channel.GuildID; guildID.IsValid() {
  283. gt.chatView.messagesList.requestGuildMembers(guildID, messages)
  284. }
  285. gt.chatView.SetSelectedChannel(channel)
  286. gt.chatView.clearTypers()
  287. gt.chatView.messageInput.stopTypingTimer()
  288. gt.chatView.messagesList.reset()
  289. gt.chatView.messagesList.setTitle(*channel)
  290. gt.chatView.messagesList.setMessages(messages)
  291. gt.chatView.messagesList.ScrollToEnd()
  292. hasNoPerm := channel.Type != discord.DirectMessage && channel.Type != discord.GroupDM && !gt.chatView.state.HasPermissions(channel.ID, discord.PermissionSendMessages)
  293. gt.chatView.messageInput.SetDisabled(hasNoPerm)
  294. var text string
  295. if hasNoPerm {
  296. text = "You do not have permission to send messages in this channel."
  297. } else {
  298. text = "Message..."
  299. if gt.cfg.AutoFocus {
  300. gt.chatView.app.SetFocus(gt.chatView.messageInput)
  301. }
  302. }
  303. gt.chatView.messageInput.SetPlaceholder(tview.NewLine(tview.NewSegment(text, tcell.StyleDefault.Dim(true))))
  304. case dmNode: // Direct messages folder
  305. channels, err := gt.chatView.state.PrivateChannels()
  306. if err != nil {
  307. slog.Error("failed to get private channels", "err", err)
  308. return
  309. }
  310. ui.SortPrivateChannels(channels)
  311. for _, c := range channels {
  312. gt.createChannelNode(node, c)
  313. }
  314. }
  315. }
  316. func (gt *guildsTree) collapseParentNode(node *tview.TreeNode) {
  317. gt.
  318. GetRoot().
  319. Walk(func(n, parent *tview.TreeNode) bool {
  320. if n == node && parent.GetLevel() != 0 {
  321. parent.Collapse()
  322. gt.SetCurrentNode(parent)
  323. return false
  324. }
  325. return true
  326. })
  327. }
  328. func (gt *guildsTree) handleInput(event *tcell.EventKey) *tcell.EventKey {
  329. switch {
  330. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.CollapseParentNode.Keybind):
  331. gt.collapseParentNode(gt.GetCurrentNode())
  332. return nil
  333. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.MoveToParentNode.Keybind):
  334. return tcell.NewEventKey(tcell.KeyRune, "K", tcell.ModNone)
  335. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Up.Keybind):
  336. return tcell.NewEventKey(tcell.KeyUp, "", tcell.ModNone)
  337. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Down.Keybind):
  338. return tcell.NewEventKey(tcell.KeyDown, "", tcell.ModNone)
  339. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Top.Keybind):
  340. gt.Move(gt.GetRowCount() * -1)
  341. // return tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)
  342. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Bottom.Keybind):
  343. gt.Move(gt.GetRowCount())
  344. // return tcell.NewEventKey(tcell.KeyEnd, 0, tcell.ModNone)
  345. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.SelectCurrent.Keybind):
  346. return tcell.NewEventKey(tcell.KeyEnter, "", tcell.ModNone)
  347. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.YankID.Keybind):
  348. gt.yankID()
  349. }
  350. return nil
  351. }
  352. func (gt *guildsTree) InputHandler(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
  353. event = gt.handleInput(event)
  354. if event == nil {
  355. return
  356. }
  357. gt.TreeView.InputHandler(event, setFocus)
  358. }
  359. func (gt *guildsTree) yankID() {
  360. node := gt.GetCurrentNode()
  361. if node == nil {
  362. return
  363. }
  364. // Reference of a tree node in the guilds tree is its ID.
  365. // discord.Snowflake (discord.GuildID and discord.ChannelID) have the String method.
  366. if id, ok := node.GetReference().(fmt.Stringer); ok {
  367. go clipboard.Write(clipboard.FmtText, []byte(id.String()))
  368. }
  369. }
  370. func (gt *guildsTree) findNodeByReference(reference any) *tview.TreeNode {
  371. switch ref := reference.(type) {
  372. case discord.GuildID:
  373. return gt.guildNodeByID[ref]
  374. case discord.ChannelID:
  375. return gt.channelNodeByID[ref]
  376. case dmNode:
  377. return gt.dmRootNode
  378. default:
  379. // Fallback keeps this helper safe for non-indexed custom references.
  380. var found *tview.TreeNode
  381. gt.GetRoot().Walk(func(node, _ *tview.TreeNode) bool {
  382. if node.GetReference() == reference {
  383. found = node
  384. return false
  385. }
  386. return true
  387. })
  388. return found
  389. }
  390. }
  391. func (gt *guildsTree) findNodeByChannelID(channelID discord.ChannelID) *tview.TreeNode {
  392. channel, err := gt.chatView.state.Cabinet.Channel(channelID)
  393. if err != nil {
  394. slog.Error("failed to get channel", "channel_id", channelID, "err", err)
  395. return nil
  396. }
  397. var reference any
  398. if guildID := channel.GuildID; guildID.IsValid() {
  399. reference = guildID
  400. } else {
  401. reference = dmNode{}
  402. }
  403. if parentNode := gt.findNodeByReference(reference); parentNode != nil {
  404. if len(parentNode.GetChildren()) == 0 {
  405. gt.onSelected(parentNode)
  406. }
  407. }
  408. node := gt.findNodeByReference(channelID)
  409. return node
  410. }
  411. func (gt *guildsTree) expandPathToNode(node *tview.TreeNode) {
  412. if node == nil {
  413. return
  414. }
  415. for _, n := range gt.GetPath(node) {
  416. n.Expand()
  417. }
  418. }