/
timer.go
68 lines (55 loc) 路 1.43 KB
/
timer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Package timer provides a simple timeout component.
package timer
import (
"time"
tea "github.com/charmbracelet/bubbletea"
)
// TickMsg is a message that is sent on every timer tick.
type TickMsg struct{}
// TimeoutMsg is a message that is sent once when the timer times out.
type TimeoutMsg struct{}
// Model of the timer component.
type Model struct {
// How long until the timer expires.
Timeout 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(timeout, interval time.Duration) Model {
return Model{
Timeout: timeout,
TickEvery: interval,
}
}
// New creates a new timer with the given timeout and default 1s interval.
func New(timeout time.Duration) Model {
return NewWithInterval(timeout, 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.Timeout -= m.TickEvery
if m.Timeout <= 0 {
return m, func() tea.Msg {
return TimeoutMsg{}
}
}
return m, tick(m.TickEvery)
}
return m, nil
}
// View of the timer component.
func (m Model) View() string {
return m.Timeout.String()
}
func tick(d time.Duration) tea.Cmd {
return tea.Tick(d, func(_ time.Time) tea.Msg {
return TickMsg{}
})
}