master
  1// from <https://github.com/charmbracelet/bubbletea/blob/master/examples/stopwatch/main.go>
  2package stopwatch
  3
  4import (
  5	"fmt"
  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
 14type model struct {
 15	stopwatch stopwatch.Model
 16	keymap    keymap
 17	help      help.Model
 18	quitting  bool
 19}
 20
 21type keymap struct {
 22	start key.Binding
 23	stop  key.Binding
 24	reset key.Binding
 25	quit  key.Binding
 26}
 27
 28func (m model) Init() tea.Cmd {
 29	return m.stopwatch.Init()
 30}
 31
 32func (m model) View() string {
 33	// Note: you could further customize the time output by getting the
 34	// duration from m.stopwatch.Elapsed(), which returns a time.Duration, and
 35	// skip m.stopwatch.View() altogether.
 36	s := m.stopwatch.View() + "\n"
 37	if !m.quitting {
 38		s = "Elapsed: " + s
 39		s += m.helpView()
 40	}
 41	return s
 42}
 43
 44func (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
 53func (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 = true
 59			return m, tea.Quit
 60		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.Cmd
 69	m.stopwatch, cmd = m.stopwatch.Update(msg)
 70	return m, cmd
 71}
 72
 73func Stopwatch() error {
 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.New(),
 95	}
 96
 97	m.keymap.start.SetEnabled(false)
 98
 99	if _, err := tea.NewProgram(m).Run(); err != nil {
100		return fmt.Errorf("stopwatch error: %w", err)
101	}
102	return nil
103}