update examples. fix bugs

This commit is contained in:
2026-02-03 12:53:52 -05:00
parent 9150c90ad1
commit 426a0c4715
15 changed files with 867 additions and 1148 deletions
+20 -18
View File
@@ -1,7 +1,8 @@
(ns examples.timer
"Countdown timer example - demonstrates async commands.
Mirrors bubbletea's stopwatch/timer examples."
(:require [tui.core :as tui]))
(:require [tui.core :as tui]
[tui.events :as ev]))
;; === Model ===
(def initial-model
@@ -10,37 +11,38 @@
:done false})
;; === Update ===
(defn update-model [model msg]
(defn update-fn [{:keys [model event]}]
(cond
;; Quit
(or (tui/key= msg "q")
(tui/key= msg [:ctrl \c]))
[model tui/quit]
(or (ev/key= event \q)
(ev/key= event \c #{:ctrl}))
{:model model :events [(ev/quit)]}
;; Timer tick - decrement timer
(= msg :timer-tick)
(= (:type event) :timer-tick)
(if (:running model)
(let [new-seconds (dec (:seconds model))]
(if (<= new-seconds 0)
;; Timer done
[(assoc model :seconds 0 :done true :running false) nil]
{:model (assoc model :seconds 0 :done true :running false)}
;; Continue countdown
[(assoc model :seconds new-seconds) (tui/after 1000 :timer-tick)]))
[model nil])
{:model (assoc model :seconds new-seconds)
:events [(ev/delayed-event 1000 {:type :timer-tick})]}))
{:model model})
;; Space - pause/resume
(tui/key= msg " ")
(ev/key= event \space)
(let [new-running (not (:running model))]
[(assoc model :running new-running)
(when new-running (tui/after 1000 :timer-tick))])
{:model (assoc model :running new-running)
:events (when new-running [(ev/delayed-event 1000 {:type :timer-tick})])})
;; r - reset
(tui/key= msg "r")
[(assoc model :seconds 10 :done false :running true)
(tui/after 1000 :timer-tick)]
(ev/key= event \r)
{:model (assoc model :seconds 10 :done false :running true)
:events [(ev/delayed-event 1000 {:type :timer-tick})]}
:else
[model nil]))
{:model model}))
;; === View ===
(defn format-time [seconds]
@@ -74,8 +76,8 @@
(defn -main [& _args]
(println "Starting timer...")
(let [final-model (tui/run {:init initial-model
:update update-model
:update update-fn
:view view
:init-cmd (tui/after 1000 :timer-tick)})]
:init-events [(ev/delayed-event 1000 {:type :timer-tick})]})]
(when (:done final-model)
(println "Timer completed!"))))