view.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package ui
  2. import (
  3. "github.com/gdamore/tcell/v2"
  4. "github.com/rivo/tview"
  5. )
  6. type FocusedID int
  7. const (
  8. guildsView FocusedID = iota
  9. channelsView
  10. messagesView
  11. inputView
  12. )
  13. type View struct {
  14. *tview.Flex
  15. GuildsView *GuildsView
  16. ChannelsView *ChannelsView
  17. MessagesView *MessagesView
  18. InputView *InputView
  19. app *Application
  20. focused FocusedID
  21. }
  22. func newView(app *Application) *View {
  23. v := &View{
  24. Flex: tview.NewFlex(),
  25. GuildsView: newGuildsView(app),
  26. ChannelsView: newChannelsView(app),
  27. MessagesView: newMessagesView(app),
  28. InputView: newInputView(app),
  29. app: app,
  30. }
  31. left := tview.NewFlex().
  32. SetDirection(tview.FlexRow).
  33. AddItem(v.GuildsView, 10, 1, false).
  34. AddItem(v.ChannelsView, 0, 1, false)
  35. right := tview.NewFlex().
  36. SetDirection(tview.FlexRow).
  37. AddItem(v.MessagesView, 0, 1, false).
  38. AddItem(v.InputView, 3, 1, false)
  39. v.AddItem(left, 0, 1, false)
  40. v.AddItem(right, 0, 4, false)
  41. v.SetInputCapture(v.onInputCapture)
  42. return v
  43. }
  44. func (v *View) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  45. switch event.Key() {
  46. case tcell.KeyEsc:
  47. v.focused = 0
  48. case tcell.KeyBacktab:
  49. // If the currently focused view is the guilds view (first), then focus the input view (last)
  50. if v.focused == 0 {
  51. v.focused = inputView
  52. } else {
  53. v.focused--
  54. }
  55. v.setFocus()
  56. case tcell.KeyTab:
  57. // If the currently focused view is the input view (last), then focus the guilds view (first)
  58. if v.focused == inputView {
  59. v.focused = guildsView
  60. } else {
  61. v.focused++
  62. }
  63. v.setFocus()
  64. }
  65. return event
  66. }
  67. func (v *View) setFocus() {
  68. var p tview.Primitive
  69. switch v.focused {
  70. case guildsView:
  71. p = v.GuildsView
  72. case channelsView:
  73. p = v.ChannelsView
  74. case messagesView:
  75. p = v.MessagesView
  76. case inputView:
  77. p = v.InputView
  78. }
  79. v.app.SetFocus(p)
  80. }