choice.go

 1package tui
 2
 3import (
 4	"fmt"
 5	"strings"
 6
 7	tea "github.com/charmbracelet/bubbletea"
 8	"github.com/charmbracelet/lipgloss"
 9)
10
11var (
12	// A more beautiful style for the main menu
13	docStyle = lipgloss.NewStyle().Margin(1, 2)
14
15	titleStyle = lipgloss.NewStyle().
16			Foreground(lipgloss.Color("#FFFDF5")).
17			Background(lipgloss.Color("#25A065")).
18			Padding(0, 1)
19
20	helpStyle = lipgloss.NewStyle().
21			Foreground(lipgloss.Color("241"))
22
23	// Styling for the choice list
24	listHeader = lipgloss.NewStyle().
25			Foreground(lipgloss.Color("241")).
26			PaddingBottom(1)
27
28	// Custom item styles
29	itemStyle         = lipgloss.NewStyle().PaddingLeft(2)
30	selectedItemStyle = lipgloss.NewStyle().PaddingLeft(2).Foreground(lipgloss.Color("205"))
31)
32
33type Choice struct {
34	cursor int
35}
36
37func NewChoice() Choice {
38	return Choice{cursor: 0}
39}
40
41func (m Choice) Init() tea.Cmd {
42	return nil
43}
44
45func (m Choice) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
46	switch msg := msg.(type) {
47	case tea.KeyMsg:
48		switch msg.String() {
49		case "up", "k":
50			if m.cursor > 0 {
51				m.cursor--
52			}
53		case "down", "j":
54			if m.cursor < 1 { // We have two choices
55				m.cursor++
56			}
57		case "enter":
58			if m.cursor == 0 {
59				return m, func() tea.Msg { return GoToInboxMsg{} }
60			} else if m.cursor == 1 {
61				return m, func() tea.Msg { return GoToSendMsg{} }
62			}
63		}
64	}
65	return m, nil
66}
67
68func (m Choice) View() string {
69	var b strings.Builder
70
71	// Title
72	b.WriteString(titleStyle.Render("Email CLI") + "\n\n")
73
74	// Header
75	b.WriteString(listHeader.Render("What would you like to do?"))
76	b.WriteString("\n\n")
77
78	// Choices
79	choices := []string{"View Inbox", "Compose Email"}
80	for i, choice := range choices {
81		if m.cursor == i {
82			b.WriteString(selectedItemStyle.Render(fmt.Sprintf("> %s", choice)))
83		} else {
84			b.WriteString(itemStyle.Render(fmt.Sprintf("  %s", choice)))
85		}
86		b.WriteString("\n")
87	}
88
89	// Help
90	b.WriteString("\n\n")
91	b.WriteString(helpStyle.Render("Use ↑/↓ to navigate, enter to select, and q to quit."))
92
93	return docStyle.Render(b.String())
94}