Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: stopwatch #68

Merged
merged 3 commits into from Sep 9, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 63 additions & 0 deletions stopwatch/stopwatch.go
@@ -0,0 +1,63 @@
// Package stopwatch provides a simple stopwatch component.
package stopwatch

import (
"time"

tea "github.com/charmbracelet/bubbletea"
)

// TickMsg is a message that is sent on every timer tick.
type TickMsg struct{}

// StopMsg is a message that can be send to stop the watch.
type StopMsg struct{}

// Model of the timer component.
type Model struct {
caarlos0 marked this conversation as resolved.
Show resolved Hide resolved
d time.Duration

// How long to wait before every tick. Defaults to 1 second.
TickEvery time.Duration
}

// NewWithInterval creates a new timer with the given timeout and tick interval.
func NewWithInterval(interval time.Duration) Model {
return Model{
TickEvery: interval,
}
}

// New creates a new timer with the given timeout and default 1s interval.
func New(timeout time.Duration) Model {
meowgorithm marked this conversation as resolved.
Show resolved Hide resolved
return NewWithInterval(time.Second)
}

// Init starts the timer.
func (m Model) Init() tea.Cmd {
return tick(m.TickEvery)
}

// Update handles the timer tick.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
switch msg.(type) {
case TickMsg:
m.d += m.TickEvery
return m, tick(m.TickEvery)
case StopMsg:
return m, nil
}

return m, nil
}

// View of the timer component.
func (m Model) View() string {
return m.d.String()
}

func tick(d time.Duration) tea.Cmd {
return tea.Tick(d, func(_ time.Time) tea.Msg {
return TickMsg{}
})
}