guilds_tree.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. guildState *guildState
  28. cachedCollapseNode *tview.TreeNode
  29. cachedCollapseResult bool
  30. }
  31. var _ help.KeyMap = (*guildsTree)(nil)
  32. func newGuildsTree(cfg *config.Config, chatView *Model) *guildsTree {
  33. gt := &guildsTree{
  34. TreeView: tview.NewTreeView(),
  35. cfg: cfg,
  36. chat: chatView,
  37. guildNodeByID: make(map[discord.GuildID]*tview.TreeNode),
  38. channelNodeByID: make(map[discord.ChannelID]*tview.TreeNode),
  39. guildState: loadGuildState(),
  40. }
  41. gt.Box = ui.ConfigureBox(gt.Box, &cfg.Theme)
  42. gt.
  43. SetRoot(tview.NewTreeNode("")).
  44. SetTopLevel(1).
  45. SetMarkers(tview.TreeMarkers{
  46. Expanded: cfg.Sidebar.Markers.Expanded,
  47. Collapsed: cfg.Sidebar.Markers.Collapsed,
  48. Leaf: cfg.Sidebar.Markers.Leaf,
  49. }).
  50. SetGraphics(cfg.Theme.GuildsTree.Graphics).
  51. SetGraphicsColor(tcell.GetColor(cfg.Theme.GuildsTree.GraphicsColor)).
  52. SetTitle("Guilds")
  53. return gt
  54. }
  55. func (gt *guildsTree) selectActionDesc() string {
  56. desc := "select"
  57. if node := gt.GetCurrentNode(); node != nil {
  58. if len(node.GetChildren()) > 0 {
  59. if node.IsExpanded() {
  60. desc = "collapse"
  61. } else {
  62. desc = "expand"
  63. }
  64. } else {
  65. switch node.GetReference().(type) {
  66. case discord.GuildID, dmNode:
  67. desc = "expand"
  68. }
  69. }
  70. }
  71. return desc
  72. }
  73. func (gt *guildsTree) ShortHelp() []keybind.Keybind {
  74. cfg := gt.cfg.Keybinds.GuildsTree
  75. selectCurrent := cfg.SelectCurrent.Keybind
  76. collapseParent := cfg.CollapseParentNode.Keybind
  77. selectHelp := selectCurrent.Help()
  78. selectCurrent.SetHelp(selectHelp.Key, gt.selectActionDesc())
  79. collapseHelp := collapseParent.Help()
  80. collapseParent.SetHelp(collapseHelp.Key, "collapse parent")
  81. shortHelp := []keybind.Keybind{cfg.Up.Keybind, cfg.Down.Keybind, selectCurrent}
  82. if gt.canCollapseParentCached() {
  83. shortHelp = append(shortHelp, collapseParent)
  84. }
  85. return shortHelp
  86. }
  87. func (gt *guildsTree) FullHelp() [][]keybind.Keybind {
  88. cfg := gt.cfg.Keybinds.GuildsTree
  89. selectCurrent := cfg.SelectCurrent.Keybind
  90. collapseParent := cfg.CollapseParentNode.Keybind
  91. selectHelp := selectCurrent.Help()
  92. selectCurrent.SetHelp(selectHelp.Key, gt.selectActionDesc())
  93. collapseHelp := collapseParent.Help()
  94. collapseParent.SetHelp(collapseHelp.Key, "collapse parent")
  95. actions := []keybind.Keybind{selectCurrent, cfg.MoveToParentNode.Keybind}
  96. if gt.canCollapseParentCached() {
  97. actions = append(actions, collapseParent)
  98. }
  99. return [][]keybind.Keybind{
  100. {cfg.Up.Keybind, cfg.Down.Keybind, cfg.Top.Keybind, cfg.Bottom.Keybind},
  101. actions,
  102. {cfg.YankID.Keybind},
  103. }
  104. }
  105. func (gt *guildsTree) canCollapseParent(node *tview.TreeNode) bool {
  106. if node == nil {
  107. return false
  108. }
  109. path := gt.GetPath(node)
  110. // Path layout is [root, ..., node]. A non-root parent means at least 3 nodes.
  111. if len(path) < 3 {
  112. return false
  113. }
  114. parent := path[len(path)-2]
  115. return parent != nil && parent.GetLevel() != 0
  116. }
  117. func (gt *guildsTree) canCollapseParentCached() bool {
  118. node := gt.GetCurrentNode()
  119. if node == gt.cachedCollapseNode {
  120. return gt.cachedCollapseResult
  121. }
  122. gt.cachedCollapseNode = node
  123. gt.cachedCollapseResult = gt.canCollapseParent(node)
  124. return gt.cachedCollapseResult
  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. gt.cachedCollapseNode = 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.chat.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.chat.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. expanded := gt.guildState.isExpanded(guild.ID)
  173. guildNode := tview.NewTreeNode(guild.Name).
  174. SetReference(guild.ID).
  175. SetExpandable(true).
  176. SetExpanded(expanded).
  177. SetIndent(gt.cfg.Theme.GuildsTree.Indents.Guild)
  178. gt.setNodeLineStyle(guildNode, gt.getGuildNodeStyle(guild.ID))
  179. n.AddChild(guildNode)
  180. gt.guildNodeByID[guild.ID] = guildNode
  181. }
  182. func (gt *guildsTree) createChannelNode(node *tview.TreeNode, channel discord.Channel) {
  183. if channel.Type != discord.DirectMessage && channel.Type != discord.GroupDM && channel.Type != discord.GuildCategory && !gt.chat.state.HasPermissions(channel.ID, discord.PermissionViewChannel) {
  184. return
  185. }
  186. channelNode := tview.NewTreeNode(ui.ChannelToString(channel, gt.cfg.Icons, gt.chat.state)).SetReference(channel.ID)
  187. gt.setNodeLineStyle(channelNode, gt.getChannelNodeStyle(channel.ID))
  188. switch channel.Type {
  189. case discord.DirectMessage:
  190. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.DM)
  191. case discord.GroupDM:
  192. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.GroupDM)
  193. case discord.GuildCategory:
  194. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Category)
  195. channelNode.SetExpandable(true).SetExpanded(gt.guildState.isChannelExpanded(channel.ID, true))
  196. case discord.GuildForum:
  197. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Forum)
  198. channelNode.SetExpandable(true).SetExpanded(gt.guildState.isChannelExpanded(channel.ID, false))
  199. default:
  200. channelNode.SetIndent(gt.cfg.Theme.GuildsTree.Indents.Channel)
  201. }
  202. node.AddChild(channelNode)
  203. gt.channelNodeByID[channel.ID] = channelNode
  204. gt.setNodeLineStyle(channelNode, gt.getChannelNodeStyle(channel.ID))
  205. }
  206. func (gt *guildsTree) setNodeLineStyle(node *tview.TreeNode, style tcell.Style) {
  207. line := node.GetLine()
  208. for i := range line {
  209. line[i].Style = style
  210. }
  211. node.SetLine(line)
  212. }
  213. func (gt *guildsTree) createChannelNodes(node *tview.TreeNode, channels []discord.Channel) {
  214. // Preserve exact ordering semantics:
  215. // 1) top-level non-categories (in input order),
  216. // 2) categories that have at least one child in the source slice (in input order),
  217. // 3) parented channels under already-created categories (in input order).
  218. //
  219. // We precompute parent presence once to avoid the O(n^2) category-child scan.
  220. hasChildByParentID := make(map[discord.ChannelID]struct{}, len(channels))
  221. for _, channel := range channels {
  222. if channel.ParentID.IsValid() {
  223. hasChildByParentID[channel.ParentID] = struct{}{}
  224. }
  225. }
  226. for _, channel := range channels {
  227. if channel.Type != discord.GuildCategory && !channel.ParentID.IsValid() {
  228. gt.createChannelNode(node, channel)
  229. }
  230. }
  231. for _, channel := range channels {
  232. if channel.Type == discord.GuildCategory {
  233. if _, ok := hasChildByParentID[channel.ID]; ok {
  234. gt.createChannelNode(node, channel)
  235. }
  236. }
  237. }
  238. for _, channel := range channels {
  239. if channel.ParentID.IsValid() {
  240. // Parent categories are inserted earlier in this function, so this
  241. // lookup is O(1) and avoids per-channel subtree walks.
  242. parent := gt.channelNodeByID[channel.ParentID]
  243. if parent != nil {
  244. gt.createChannelNode(parent, channel)
  245. }
  246. }
  247. }
  248. }
  249. func (gt *guildsTree) persistExpandState(ref any, expanded bool) {
  250. switch ref := ref.(type) {
  251. case discord.GuildID:
  252. go gt.guildState.setExpanded(ref, expanded)
  253. case discord.ChannelID:
  254. go gt.guildState.setChannelExpanded(ref, expanded)
  255. }
  256. }
  257. func (gt *guildsTree) onSelected(node *tview.TreeNode) tview.Command {
  258. if len(node.GetChildren()) != 0 {
  259. node.SetExpanded(!node.IsExpanded())
  260. gt.persistExpandState(node.GetReference(), node.IsExpanded())
  261. return nil
  262. }
  263. switch ref := node.GetReference().(type) {
  264. case discord.GuildID:
  265. go gt.chat.state.MemberState.Subscribe(ref)
  266. channels, err := gt.chat.state.Cabinet.Channels(ref)
  267. if err != nil {
  268. slog.Error("failed to get channels", "err", err, "guild_id", ref)
  269. return nil
  270. }
  271. ui.SortGuildChannels(channels)
  272. gt.createChannelNodes(node, channels)
  273. node.Expand()
  274. go gt.guildState.setExpanded(ref, true)
  275. return nil
  276. case discord.ChannelID:
  277. channel, err := gt.chat.state.Cabinet.Channel(ref)
  278. if err != nil {
  279. slog.Error("failed to get channel from state", "err", err, "channel_id", ref)
  280. return nil
  281. }
  282. // Handle forum channels differently - they contain threads, not direct messages
  283. if channel.Type == discord.GuildForum {
  284. // Get all channels from the guild - this includes active threads from GuildCreateEvent
  285. allChannels, err := gt.chat.state.Cabinet.Channels(channel.GuildID)
  286. if err != nil {
  287. slog.Error("failed to get channels for forum threads", "err", err, "guild_id", channel.GuildID)
  288. return nil
  289. }
  290. // Filter for threads that belong to this forum channel
  291. var forumThreads []discord.Channel
  292. for _, ch := range allChannels {
  293. if ch.ParentID == channel.ID && (ch.Type == discord.GuildPublicThread ||
  294. ch.Type == discord.GuildPrivateThread ||
  295. ch.Type == discord.GuildAnnouncementThread) {
  296. forumThreads = append(forumThreads, ch)
  297. }
  298. }
  299. // Add threads as child nodes
  300. for _, thread := range forumThreads {
  301. gt.createChannelNode(node, thread)
  302. }
  303. node.Expand()
  304. return nil
  305. }
  306. return gt.loadChannel(*channel)
  307. case dmNode: // Direct messages folder
  308. channels, err := gt.chat.state.PrivateChannels()
  309. if err != nil {
  310. slog.Error("failed to get private channels", "err", err)
  311. return nil
  312. }
  313. ui.SortPrivateChannels(channels)
  314. for _, c := range channels {
  315. gt.createChannelNode(node, c)
  316. }
  317. node.Expand()
  318. return nil
  319. }
  320. return nil
  321. }
  322. func (gt *guildsTree) loadChannel(channel discord.Channel) tview.Command {
  323. limit := uint(gt.cfg.MessagesLimit)
  324. return func() tview.Event {
  325. messages, err := gt.chat.state.Messages(channel.ID, limit)
  326. if err != nil {
  327. slog.Error("failed to get messages", "err", err, "channel_id", channel.ID, "limit", limit)
  328. return nil
  329. }
  330. // Use the newest fetched message ID for MarkRead — channel.LastMessageID
  331. // can be stale in the cabinet cache, causing some channels to remain unread.
  332. // Messages are snowflake-ordered, so the last element is the newest.
  333. lastMsgID := channel.LastMessageID
  334. if len(messages) > 0 {
  335. if newest := messages[len(messages)-1].ID; newest > lastMsgID {
  336. lastMsgID = newest
  337. }
  338. }
  339. if lastMsgID.IsValid() {
  340. go gt.chat.state.ReadState.MarkRead(channel.ID, lastMsgID)
  341. }
  342. if guildID := channel.GuildID; guildID.IsValid() {
  343. gt.chat.messagesList.requestGuildMembers(guildID, messages)
  344. }
  345. return newChannelLoadedEvent(channel, messages)
  346. }
  347. }
  348. func (gt *guildsTree) collapseParentNode(node *tview.TreeNode) {
  349. path := gt.GetPath(node)
  350. if len(path) < 3 {
  351. return
  352. }
  353. parent := path[len(path)-2]
  354. if parent == nil || parent.GetLevel() == 0 {
  355. return
  356. }
  357. parent.Collapse()
  358. gt.persistExpandState(parent.GetReference(), false)
  359. gt.SetCurrentNode(parent)
  360. }
  361. func (gt *guildsTree) HandleEvent(event tview.Event) tview.Command {
  362. switch event := event.(type) {
  363. case *tview.TreeViewSelectedEvent:
  364. return gt.onSelected(event.Node)
  365. case *tview.KeyEvent:
  366. handler := gt.TreeView.HandleEvent
  367. switch {
  368. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.CollapseParentNode.Keybind):
  369. gt.collapseParentNode(gt.GetCurrentNode())
  370. return nil
  371. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.MoveToParentNode.Keybind):
  372. return handler(tcell.NewEventKey(tcell.KeyRune, "K", tcell.ModNone))
  373. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Up.Keybind),
  374. keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.ArrowUp.Keybind):
  375. return handler(tcell.NewEventKey(tcell.KeyUp, "", tcell.ModNone))
  376. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Down.Keybind),
  377. keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.ArrowDown.Keybind):
  378. return handler(tcell.NewEventKey(tcell.KeyDown, "", tcell.ModNone))
  379. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Top.Keybind):
  380. gt.Move(gt.GetRowCount() * -1)
  381. return nil
  382. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.Bottom.Keybind):
  383. gt.Move(gt.GetRowCount())
  384. return nil
  385. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.SelectCurrent.Keybind):
  386. return handler(tcell.NewEventKey(tcell.KeyEnter, "", tcell.ModNone))
  387. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.YankID.Keybind):
  388. return gt.yankID()
  389. case event.Key() == tcell.KeyEsc:
  390. // ESC cycles: input → messages → guilds → input
  391. if cmd := gt.chat.focusMessageInput(); cmd != nil {
  392. return cmd
  393. }
  394. return gt.chat.focusMessagesList()
  395. case keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.ArrowLeft.Keybind),
  396. keybind.Matches(event, gt.cfg.Keybinds.GuildsTree.ArrowRight.Keybind):
  397. return gt.chat.focusMessagesList()
  398. }
  399. // Do not fall through to TreeView defaults for unmatched keys.
  400. return nil
  401. }
  402. return gt.TreeView.HandleEvent(event)
  403. }
  404. func (gt *guildsTree) yankID() tview.Command {
  405. node := gt.GetCurrentNode()
  406. if node == nil {
  407. return nil
  408. }
  409. // Reference of a tree node in the guilds tree is its ID.
  410. // discord.Snowflake (discord.GuildID and discord.ChannelID) have the String method.
  411. if id, ok := node.GetReference().(fmt.Stringer); ok {
  412. return func() tview.Event {
  413. if err := clipboard.Write(clipboard.FmtText, []byte(id.String())); err != nil {
  414. slog.Error("failed to copy node id", "err", err)
  415. }
  416. return nil
  417. }
  418. }
  419. return nil
  420. }
  421. func (gt *guildsTree) findNodeByReference(reference any) *tview.TreeNode {
  422. switch ref := reference.(type) {
  423. case discord.GuildID:
  424. return gt.guildNodeByID[ref]
  425. case discord.ChannelID:
  426. return gt.channelNodeByID[ref]
  427. case dmNode:
  428. return gt.dmRootNode
  429. default:
  430. // Fallback keeps this helper safe for non-indexed custom references.
  431. var found *tview.TreeNode
  432. gt.GetRoot().Walk(func(node, _ *tview.TreeNode) bool {
  433. if node.GetReference() == reference {
  434. found = node
  435. return false
  436. }
  437. return true
  438. })
  439. return found
  440. }
  441. }
  442. func (gt *guildsTree) findNodeByChannelID(channelID discord.ChannelID) *tview.TreeNode {
  443. channel, err := gt.chat.state.Cabinet.Channel(channelID)
  444. if err != nil {
  445. slog.Error("failed to get channel", "channel_id", channelID, "err", err)
  446. return nil
  447. }
  448. var reference any
  449. if guildID := channel.GuildID; guildID.IsValid() {
  450. reference = guildID
  451. } else {
  452. reference = dmNode{}
  453. }
  454. if parentNode := gt.findNodeByReference(reference); parentNode != nil {
  455. if len(parentNode.GetChildren()) == 0 {
  456. gt.onSelected(parentNode)
  457. }
  458. }
  459. node := gt.findNodeByReference(channelID)
  460. return node
  461. }
  462. func (gt *guildsTree) expandPathToNode(node *tview.TreeNode) {
  463. if node == nil {
  464. return
  465. }
  466. for _, n := range gt.GetPath(node) {
  467. n.Expand()
  468. }
  469. }