quit.go

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