main.go
This file
Path
tutorials/basics/main.go
90 lines · 1.6 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23import (4 "fmt"5 "os"67 tea "charm.land/bubbletea/v2"8)910type model struct {11 cursor int12 choices []string13 selected map[int]struct{}14}1516func initialModel() model {17 return model{18 // Our to-do list is a grocery list19 choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"},2021 // A map which indicates which choices are selected. We're using22 // the map like a mathematical set. The keys refer to the indexes23 // of the `choices` slice, above.24 selected: make(map[int]struct{}),25 }26}2728func (m model) Init() tea.Cmd {29 return nil30}3132func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {33 switch msg := msg.(type) {34 case tea.KeyPressMsg:35 switch msg.String() {36 case "ctrl+c", "q":37 return m, tea.Quit38 case "up", "k":39 if m.cursor > 0 {40 m.cursor--41 }42 case "down", "j":43 if m.cursor < len(m.choices)-1 {44 m.cursor++45 }46 case "enter", "space":47 _, ok := m.selected[m.cursor]48 if ok {49 delete(m.selected, m.cursor)50 } else {51 m.selected[m.cursor] = struct{}{}52 }53 }54 }5556 return m, nil57}5859func (m model) View() tea.View {60 s := "What should we buy at the market?\n\n"6162 for i, choice := range m.choices {63 cursor := " "64 if m.cursor == i {65 cursor = ">"66 }6768 checked := " "69 if _, ok := m.selected[i]; ok {70 checked = "x"71 }7273 s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)74 }7576 s += "\nPress q to quit.\n"7778 v := tea.NewView(s)79 v.WindowTitle = "Grocery List"8081 return v82}8384func main() {85 p := tea.NewProgram(initialModel())86 if _, err := p.Run(); err != nil {87 fmt.Printf("Alas, there's been an error: %v", err)88 os.Exit(1)89 }90}