Skip to content
Myr

main.go

This file

Path

examples/timer/main.go

122 lines · 2.3 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take 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/timer"11	tea "charm.land/bubbletea/v2"12)1314const timeout = time.Second * 51516type model struct {17	timer    timer.Model18	keymap   keymap19	help     help.Model20	quitting bool21}2223type keymap struct {24	start key.Binding25	stop  key.Binding26	reset key.Binding27	quit  key.Binding28}2930func (m model) Init() tea.Cmd {31	return m.timer.Init()32}3334func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {35	switch msg := msg.(type) {36	case timer.TickMsg:37		var cmd tea.Cmd38		m.timer, cmd = m.timer.Update(msg)39		return m, cmd4041	case timer.StartStopMsg:42		var cmd tea.Cmd43		m.timer, cmd = m.timer.Update(msg)44		m.keymap.stop.SetEnabled(m.timer.Running())45		m.keymap.start.SetEnabled(!m.timer.Running())46		return m, cmd4748	case timer.TimeoutMsg:49		m.quitting = true50		return m, tea.Quit5152	case tea.KeyPressMsg:53		switch {54		case key.Matches(msg, m.keymap.quit):55			m.quitting = true56			return m, tea.Quit57		case key.Matches(msg, m.keymap.reset):58			m.timer.Timeout = timeout59		case key.Matches(msg, m.keymap.start, m.keymap.stop):60			return m, m.timer.Toggle()61		}62	}6364	return m, nil65}6667func (m model) helpView() string {68	return "\n" + m.help.ShortHelpView([]key.Binding{69		m.keymap.start,70		m.keymap.stop,71		m.keymap.reset,72		m.keymap.quit,73	})74}7576func (m model) View() tea.View {77	// For a more detailed timer view you could read m.timer.Timeout to get78	// the remaining time as a time.Duration and skip calling m.timer.View()79	// entirely.80	s := m.timer.View()8182	if m.timer.Timedout() {83		s = "All done!"84	}85	s += "\n"86	if !m.quitting {87		s = "Exiting in " + s88		s += m.helpView()89	}90	return tea.NewView(s)91}9293func main() {94	m := model{95		timer: timer.New(timeout, timer.WithInterval(time.Millisecond)),96		keymap: keymap{97			start: key.NewBinding(98				key.WithKeys("s"),99				key.WithHelp("s", "start"),100			),101			stop: key.NewBinding(102				key.WithKeys("s"),103				key.WithHelp("s", "stop"),104			),105			reset: key.NewBinding(106				key.WithKeys("r"),107				key.WithHelp("r", "reset"),108			),109			quit: key.NewBinding(110				key.WithKeys("q", "ctrl+c"),111				key.WithHelp("q", "quit"),112			),113		},114		help: help.New(),115	}116	m.keymap.start.SetEnabled(false)117118	if _, err := tea.NewProgram(m).Run(); err != nil {119		fmt.Println("Uh oh, we encountered an error:", err)120		os.Exit(1)121	}122}