command_input.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package chat
  2. import (
  3. "github.com/ayn2op/tview"
  4. "github.com/ayn2op/tview/keybind"
  5. "github.com/ayn2op/tview/layers"
  6. )
  7. const commandInputLayerName = "commandInput"
  8. type commandInput struct {
  9. *tview.InputField
  10. chatView *Model
  11. }
  12. func newCommandInput(chatView *Model) *commandInput {
  13. ci := &commandInput{
  14. InputField: tview.NewInputField(),
  15. chatView: chatView,
  16. }
  17. ci.SetLabel(":")
  18. ci.SetFieldWidth(0)
  19. return ci
  20. }
  21. func (ci *commandInput) HandleEvent(event tview.Event) tview.Command {
  22. switch event := event.(type) {
  23. case *tview.KeyEvent:
  24. switch {
  25. case keybind.Matches(event, keybind.NewKeybind(keybind.WithKeys("enter"))):
  26. text := ci.GetText()
  27. ci.SetText("")
  28. ci.chatView.closeCommandInput()
  29. return ci.execute(text)
  30. case keybind.Matches(event, keybind.NewKeybind(keybind.WithKeys("esc"))):
  31. ci.SetText("")
  32. ci.chatView.closeCommandInput()
  33. return nil
  34. }
  35. }
  36. return ci.InputField.HandleEvent(event)
  37. }
  38. func (ci *commandInput) execute(cmd string) tview.Command {
  39. switch cmd {
  40. case "q", "quit":
  41. return func() tview.Event {
  42. return &QuitEvent{}
  43. }
  44. case "logout":
  45. return tview.Batch(ci.chatView.closeState(), ci.chatView.logout())
  46. default:
  47. return nil
  48. }
  49. }
  50. func (m *Model) openCommandInput() {
  51. m.AddLayer(
  52. m.commandInput,
  53. layers.WithName(commandInputLayerName),
  54. layers.WithResize(true),
  55. layers.WithVisible(true),
  56. layers.WithOverlay(),
  57. ).SendToFront(commandInputLayerName)
  58. m.app.SetFocus(m.commandInput)
  59. }
  60. func (m *Model) closeCommandInput() {
  61. m.RemoveLayer(commandInputLayerName)
  62. }