Skip to content
Myr

Add stopwatch example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent 03d1aa6 · Browse files · 1 file+103 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+103 added−0 removed

  • other:+103 added−0 removed

1 file+103 added−0 removed

added:examples/stopwatch/main.go+103 added
1package main23import (4 "fmt"5 "os"6 "time"78 "github.com/charmbracelet/bubbles/help"9 "github.com/charmbracelet/bubbles/key"10 "github.com/charmbracelet/bubbles/stopwatch"11 tea "github.com/charmbracelet/bubbletea"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() string {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 s42}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.KeyMsg: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.NewWithInterval(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.NewModel(),95 }9697 m.keymap.start.SetEnabled(false)9899 if err := tea.NewProgram(m).Start(); err != nil {100 fmt.Println("Oh no, it didn't work:", err)101 os.Exit(1)102 }103}