mentions_list.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package chat
  2. import (
  3. "github.com/ayn2op/discordo/internal/config"
  4. "github.com/ayn2op/discordo/internal/ui"
  5. "github.com/ayn2op/tview"
  6. "github.com/ayn2op/tview/list"
  7. "github.com/gdamore/tcell/v3"
  8. )
  9. type mentionsListItem struct {
  10. insertText string
  11. displayText string
  12. style tcell.Style
  13. }
  14. type mentionsList struct {
  15. *list.Model
  16. items []mentionsListItem
  17. }
  18. func newMentionsList(cfg *config.Config) *mentionsList {
  19. m := &mentionsList{
  20. Model: list.NewModel(),
  21. }
  22. m.SetKeybinds(list.Keybinds{
  23. SelectUp: cfg.Keybinds.MentionsList.Up.Keybind,
  24. SelectDown: cfg.Keybinds.MentionsList.Down.Keybind,
  25. })
  26. m.Box = ui.ConfigureBox(m.Box, &cfg.Theme)
  27. m.SetSnapToItems(true).SetTitle("Mentions")
  28. b := m.GetBorderSet()
  29. b.BottomLeft, b.BottomRight = b.BottomT, b.BottomT
  30. m.SetBorderSet(b)
  31. return m
  32. }
  33. func (m *mentionsList) append(item mentionsListItem) {
  34. m.items = append(m.items, item)
  35. }
  36. func (m *mentionsList) clear() {
  37. m.items = nil
  38. m.Clear()
  39. }
  40. func (m *mentionsList) rebuild() {
  41. m.SetBuilder(func(index int, cursor int) list.Item {
  42. if index < 0 || index >= len(m.items) {
  43. return nil
  44. }
  45. item := m.items[index]
  46. style := item.style
  47. if index == cursor {
  48. style = style.Reverse(true)
  49. }
  50. line := tview.NewLine(tview.NewSegment(item.displayText, style))
  51. return tview.NewTextView().
  52. SetScrollable(false).
  53. SetWrap(false).
  54. SetWordWrap(false).
  55. SetTextStyle(style).
  56. SetLines([]tview.Line{line})
  57. })
  58. if len(m.items) == 0 {
  59. m.SetCursor(-1)
  60. return
  61. }
  62. m.SetCursor(0)
  63. }
  64. func (m *mentionsList) itemCount() int {
  65. return len(m.items)
  66. }
  67. func (m *mentionsList) selectedInsertText() (string, bool) {
  68. index := m.Cursor()
  69. if index < 0 || index >= len(m.items) {
  70. return "", false
  71. }
  72. return m.items[index].insertText, true
  73. }
  74. func (m *mentionsList) maxDisplayWidth() int {
  75. width := 0
  76. for _, item := range m.items {
  77. width = max(width, tview.TaggedStringWidth(item.displayText))
  78. }
  79. return width
  80. }