diff --git a/examples/fullscreen/main.go b/examples/fullscreen/main.go index 8d7a18f..1c2cab3 100644 --- a/examples/fullscreen/main.go +++ b/examples/fullscreen/main.go @@ -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{}), } } diff --git a/examples/simple/main.go b/examples/simple/main.go index 6070821..93eabc9 100644 --- a/examples/simple/main.go +++ b/examples/simple/main.go @@ -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{}), } } diff --git a/examples/views/main.go b/examples/views/main.go index 485a627..387dbd7 100644 --- a/examples/views/main.go +++ b/examples/views/main.go @@ -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) { diff --git a/subscriptions.go b/subscriptions.go new file mode 100644 index 0000000..a6e128d --- /dev/null +++ b/subscriptions.go @@ -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 + } + } +}