ui.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package util
  2. import (
  3. "strings"
  4. "github.com/ayntgl/discordgo"
  5. "github.com/rivo/tview"
  6. )
  7. // GetNodeByReference walks the root `*TreeNode` of the given `*TreeView` *treeView* and returns the TreeNode whose reference is equal to the given reference *r*. If the `*TreeNode` is not found, `nil` is returned instead.
  8. func GetNodeByReference(treeView *tview.TreeView, r interface{}) (mn *tview.TreeNode) {
  9. treeView.GetRoot().Walk(func(n, _ *tview.TreeNode) bool {
  10. if n.GetReference() == r {
  11. mn = n
  12. return false
  13. }
  14. return true
  15. })
  16. return
  17. }
  18. // ChannelToString constructs a string representation of the given channel. The string representation may vary for different channel types.
  19. func ChannelToString(c *discordgo.Channel) string {
  20. var repr string
  21. if c.Name != "" {
  22. repr = "#" + c.Name
  23. } else if len(c.Recipients) == 1 {
  24. rp := c.Recipients[0]
  25. repr = rp.Username + "#" + rp.Discriminator
  26. } else {
  27. rps := make([]string, len(c.Recipients))
  28. for i, r := range c.Recipients {
  29. rps[i] = r.Username + "#" + r.Discriminator
  30. }
  31. repr = strings.Join(rps, ", ")
  32. }
  33. return repr
  34. }
  35. // CreateChannelNode builds (encorporates unread channels in bold tag, otherwise dim, etc.) and returns a node according to the type of the given channel *c*.
  36. func CreateChannelNode(s *discordgo.State, c *discordgo.Channel) *tview.TreeNode {
  37. var cn *tview.TreeNode
  38. switch c.Type {
  39. case discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews:
  40. tag := "[::d]"
  41. if ChannelIsUnread(s, c) {
  42. tag = "[::b]"
  43. }
  44. cn = tview.NewTreeNode(tag + ChannelToString(c) + "[::-]").
  45. SetReference(c.ID)
  46. case discordgo.ChannelTypeGuildCategory:
  47. cn = tview.NewTreeNode(c.Name).
  48. SetReference(c.ID)
  49. }
  50. return cn
  51. }
  52. // HasKeybinding returns a boolean that indicates whether the given keybinding string representation *k* is in the slice *ks*.
  53. func HasKeybinding(ks []string, k string) bool {
  54. for _, repr := range ks {
  55. if repr == k {
  56. return true
  57. }
  58. }
  59. return false
  60. }