forked from Mirrors/bubbletea
Add 'Every' subscription for ticking with the system clock
This commit is contained in:
parent
b50ee76165
commit
ac67237eab
|
@ -55,10 +55,7 @@ func update(message tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {
|
|||
|
||||
func subscriptions(_ tea.Model) tea.Subs {
|
||||
return tea.Subs{
|
||||
"tick": func() tea.Msg {
|
||||
time.Sleep(time.Second)
|
||||
return tickMsg{}
|
||||
},
|
||||
"tick": tea.Every(time.Second, tickMsg{}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -39,6 +39,8 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
|
|||
m, _ := model.(Model)
|
||||
|
||||
switch msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
return m, tea.Quit
|
||||
case TickMsg:
|
||||
m -= 1
|
||||
if m <= 0 {
|
||||
|
@ -52,16 +54,13 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
|
|||
// to the terminal.
|
||||
func view(model tea.Model) string {
|
||||
m, _ := model.(Model)
|
||||
return fmt.Sprintf("Hi. This program will exit in %d seconds...", m)
|
||||
return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.", m)
|
||||
}
|
||||
|
||||
// This is a subscription which we setup in NewProgram(). It waits for one
|
||||
// second, sends a tick, and then restarts.
|
||||
func subscriptions(_ tea.Model) tea.Subs {
|
||||
return tea.Subs{
|
||||
"tick": func() tea.Msg {
|
||||
time.Sleep(time.Second)
|
||||
return TickMsg{}
|
||||
},
|
||||
"tick": tea.Every(time.Second, TickMsg{}),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -50,24 +50,14 @@ func subscriptions(model tea.Model) tea.Subs {
|
|||
m, _ := model.(Model)
|
||||
if !m.Chosen || m.Loaded {
|
||||
return tea.Subs{
|
||||
"tick": tick,
|
||||
"tick": tea.Every(time.Second, tickMsg{}),
|
||||
}
|
||||
}
|
||||
return tea.Subs{
|
||||
"frame": frame,
|
||||
"frame": tea.Every(time.Second/60, frameMsg{}),
|
||||
}
|
||||
}
|
||||
|
||||
func tick() tea.Msg {
|
||||
time.Sleep(time.Second)
|
||||
return tickMsg{}
|
||||
}
|
||||
|
||||
func frame() tea.Msg {
|
||||
time.Sleep(time.Second / 60)
|
||||
return frameMsg{}
|
||||
}
|
||||
|
||||
// UPDATES
|
||||
|
||||
func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Every is a subscription that ticks with the system clock at the given
|
||||
// duration
|
||||
//
|
||||
// TODO: make it cancelable
|
||||
func Every(duration time.Duration, msg Msg) Sub {
|
||||
return func() Msg {
|
||||
n := time.Now()
|
||||
d := n.Truncate(duration).Add(duration).Sub(n)
|
||||
t := time.NewTimer(d)
|
||||
select {
|
||||
case <-t.C:
|
||||
return msg
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue