main.go
This file
Path
examples/stopwatch/main.go
103 lines · 2.1 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"6 "time"78 "charm.land/bubbles/v2/help"9 "charm.land/bubbles/v2/key"10 "charm.land/bubbles/v2/stopwatch"11 tea "charm.land/bubbletea/v2"12)1314type model struct {15 stopwatch stopwatch.Model16 keymap keymap17 help help.Model18 quitting bool19}2021type keymap struct {22 start key.Binding23 stop key.Binding24 reset key.Binding25 quit key.Binding26}2728func (m model) Init() tea.Cmd {29 return m.stopwatch.Init()30}3132func (m model) View() tea.View {33 // Note: you could further customize the time output by getting the34 // duration from m.stopwatch.Elapsed(), which returns a time.Duration, and35 // skip m.stopwatch.View() altogether.36 s := m.stopwatch.View() + "\n"37 if !m.quitting {38 s = "Elapsed: " + s39 s += m.helpView()40 }41 return tea.NewView(s)42}4344func (m model) helpView() string {45 return "\n" + m.help.ShortHelpView([]key.Binding{46 m.keymap.start,47 m.keymap.stop,48 m.keymap.reset,49 m.keymap.quit,50 })51}5253func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {54 switch msg := msg.(type) {55 case tea.KeyPressMsg:56 switch {57 case key.Matches(msg, m.keymap.quit):58 m.quitting = true59 return m, tea.Quit60 case key.Matches(msg, m.keymap.reset):61 return m, m.stopwatch.Reset()62 case key.Matches(msg, m.keymap.start, m.keymap.stop):63 m.keymap.stop.SetEnabled(!m.stopwatch.Running())64 m.keymap.start.SetEnabled(m.stopwatch.Running())65 return m, m.stopwatch.Toggle()66 }67 }68 var cmd tea.Cmd69 m.stopwatch, cmd = m.stopwatch.Update(msg)70 return m, cmd71}7273func main() {74 m := model{75 stopwatch: stopwatch.New(stopwatch.WithInterval(time.Millisecond)),76 keymap: keymap{77 start: key.NewBinding(78 key.WithKeys("s"),79 key.WithHelp("s", "start"),80 ),81 stop: key.NewBinding(82 key.WithKeys("s"),83 key.WithHelp("s", "stop"),84 ),85 reset: key.NewBinding(86 key.WithKeys("r"),87 key.WithHelp("r", "reset"),88 ),89 quit: key.NewBinding(90 key.WithKeys("ctrl+c", "q"),91 key.WithHelp("q", "quit"),92 ),93 },94 help: help.New(),95 }9697 m.keymap.start.SetEnabled(false)9899 if _, err := tea.NewProgram(m).Run(); err != nil {100 fmt.Println("Oh no, it didn't work:", err)101 os.Exit(1)102 }103}