2020-05-25 19:26:40 -04:00
|
|
|
package tea
|
2020-05-14 10:49:08 -04:00
|
|
|
|
2020-10-12 10:57:06 -04:00
|
|
|
// Convenience commands. Not part of the Bubble Tea core, but potentially
|
2020-06-11 19:34:08 -04:00
|
|
|
// handy.
|
2020-05-17 19:28:12 -04:00
|
|
|
|
2020-05-14 10:49:08 -04:00
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Every is a command that ticks in sync with the system clock. So, if you
|
|
|
|
// wanted to tick with the system clock every second, minute or hour you
|
|
|
|
// could use this. It's also handy for having different things tick in sync.
|
|
|
|
//
|
2020-06-18 22:47:17 -04:00
|
|
|
// Because we're ticking with the system clock the tick will likely not run for
|
|
|
|
// the entire specified duration. For example, if we're ticking for one minute
|
|
|
|
// and the clock is at 12:34:20 then the next tick will happen at 12:35:00, 40
|
|
|
|
// seconds later.
|
2020-07-30 11:29:20 -04:00
|
|
|
//
|
2020-10-11 20:28:32 -04:00
|
|
|
// To produce the command, pass a duration and a function which returns
|
2020-07-30 11:29:20 -04:00
|
|
|
// a message containing the time at which the tick occurred.
|
|
|
|
//
|
|
|
|
// type TickMsg time.Time
|
|
|
|
//
|
|
|
|
// cmd := Every(time.Second, func(t time.Time) Msg {
|
|
|
|
// return TickMsg(t)
|
|
|
|
// })
|
2020-05-14 10:49:08 -04:00
|
|
|
func Every(duration time.Duration, fn func(time.Time) Msg) Cmd {
|
|
|
|
return func() Msg {
|
|
|
|
n := time.Now()
|
|
|
|
d := n.Truncate(duration).Add(duration).Sub(n)
|
|
|
|
t := time.NewTimer(d)
|
2020-05-25 08:12:30 -04:00
|
|
|
return fn(<-t.C)
|
2020-05-14 10:49:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-12 10:59:36 -04:00
|
|
|
// Tick produces a command at an interval independent of the system clock at
|
|
|
|
// the given duration. That is, the timer begins when precisely when invoked,
|
|
|
|
// and runs for its entire duration.
|
2020-07-30 11:29:20 -04:00
|
|
|
//
|
2020-10-11 20:28:32 -04:00
|
|
|
// To produce the command, pass a duration and a function which returns
|
2020-07-30 11:29:20 -04:00
|
|
|
// a message containing the time at which the tick occurred.
|
|
|
|
//
|
|
|
|
// type TickMsg time.Time
|
|
|
|
//
|
|
|
|
// cmd := Tick(time.Second, func(t time.Time) Msg {
|
|
|
|
// return TickMsg(t)
|
|
|
|
// })
|
2020-05-14 10:49:08 -04:00
|
|
|
func Tick(d time.Duration, fn func(time.Time) Msg) Cmd {
|
|
|
|
return func() Msg {
|
|
|
|
t := time.NewTimer(d)
|
2020-05-25 08:12:30 -04:00
|
|
|
return fn(<-t.C)
|
2020-05-14 10:49:08 -04:00
|
|
|
}
|
|
|
|
}
|