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