added:examples/stopwatch/main.go+103 added
1+package main2+3+import (4+ "fmt"5+ "os"6+ "time"7+8+ "github.com/charmbracelet/bubbles/help"9+ "github.com/charmbracelet/bubbles/key"10+ "github.com/charmbracelet/bubbles/stopwatch"11+ tea "github.com/charmbracelet/bubbletea"12+)13+14+type model struct {15+ stopwatch stopwatch.Model16+ keymap keymap17+ help help.Model18+ quitting bool19+}20+21+type keymap struct {22+ start key.Binding23+ stop key.Binding24+ reset key.Binding25+ quit key.Binding26+}27+28+func (m model) Init() tea.Cmd {29+ return m.stopwatch.Init()30+}31+32+func (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+}43+44+func (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+}52+53+func (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+}72+73+func 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+ }96+97+ m.keymap.start.SetEnabled(false)98+99+ if err := tea.NewProgram(m).Start(); err != nil {100+ fmt.Println("Oh no, it didn't work:", err)101+ os.Exit(1)102+ }103+}