quit.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package dialog
  2. import (
  3. "github.com/charmbracelet/bubbles/key"
  4. tea "github.com/charmbracelet/bubbletea"
  5. "github.com/kujtimiihoxha/termai/internal/tui/components/core"
  6. "github.com/kujtimiihoxha/termai/internal/tui/layout"
  7. "github.com/kujtimiihoxha/termai/internal/tui/styles"
  8. "github.com/kujtimiihoxha/termai/internal/tui/util"
  9. "github.com/charmbracelet/huh"
  10. )
  11. const question = "Are you sure you want to quit?"
  12. type QuitDialog interface {
  13. tea.Model
  14. layout.Sizeable
  15. layout.Bindings
  16. }
  17. type quitDialogCmp struct {
  18. form *huh.Form
  19. width int
  20. height int
  21. }
  22. func (q *quitDialogCmp) Init() tea.Cmd {
  23. return nil
  24. }
  25. func (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  26. var cmds []tea.Cmd
  27. form, cmd := q.form.Update(msg)
  28. if f, ok := form.(*huh.Form); ok {
  29. q.form = f
  30. cmds = append(cmds, cmd)
  31. }
  32. if q.form.State == huh.StateCompleted {
  33. v := q.form.GetBool("quit")
  34. if v {
  35. return q, tea.Quit
  36. }
  37. cmds = append(cmds, util.CmdHandler(core.DialogCloseMsg{}))
  38. }
  39. return q, tea.Batch(cmds...)
  40. }
  41. func (q *quitDialogCmp) View() string {
  42. return q.form.View()
  43. }
  44. func (q *quitDialogCmp) GetSize() (int, int) {
  45. return q.width, q.height
  46. }
  47. func (q *quitDialogCmp) SetSize(width int, height int) {
  48. q.width = width
  49. q.height = height
  50. q.form = q.form.WithWidth(width).WithHeight(height)
  51. }
  52. func (q *quitDialogCmp) BindingKeys() []key.Binding {
  53. return q.form.KeyBinds()
  54. }
  55. func newQuitDialogCmp() QuitDialog {
  56. confirm := huh.NewConfirm().
  57. Title(question).
  58. Affirmative("Yes!").
  59. Key("quit").
  60. Negative("No.")
  61. theme := styles.HuhTheme()
  62. theme.Focused.FocusedButton = theme.Focused.FocusedButton.Background(styles.Warning)
  63. theme.Blurred.FocusedButton = theme.Blurred.FocusedButton.Background(styles.Warning)
  64. form := huh.NewForm(huh.NewGroup(confirm)).
  65. WithShowHelp(false).
  66. WithWidth(0).
  67. WithHeight(0).
  68. WithTheme(theme).
  69. WithShowErrors(false)
  70. confirm.Focus()
  71. return &quitDialogCmp{
  72. form: form,
  73. }
  74. }
  75. func NewQuitDialogCmd() tea.Cmd {
  76. content := layout.NewSinglePane(
  77. newQuitDialogCmp().(*quitDialogCmp),
  78. layout.WithSinglePaneBordered(true),
  79. layout.WithSinglePaneFocusable(true),
  80. layout.WithSinglePaneActiveColor(styles.Warning),
  81. )
  82. content.Focus()
  83. return util.CmdHandler(core.DialogMsg{
  84. Content: content,
  85. WidthRatio: 0.2,
  86. HeightRatio: 0.1,
  87. MinWidth: 40,
  88. MinHeight: 5,
  89. })
  90. }