From e8b3f0ecb43086849203eb36b189d6b6d640ed5d Mon Sep 17 00:00:00 2001 From: Miloslav Nenadal Date: Thu, 10 Aug 2023 20:39:54 +0200 Subject: [PATCH] Show time of changes --- src/app/events.cljs | 32 +++++++++++++++++++++++++++++++- src/app/util.cljs | 7 +++++++ src/app/views.cljs | 8 +++++--- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/app/events.cljs b/src/app/events.cljs index 50b9efb..5e448df 100644 --- a/src/app/events.cljs +++ b/src/app/events.cljs @@ -1,9 +1,38 @@ (ns app.events + (:refer-clojure :exclude [time]) (:require [clojure.edn :as edn] [re-frame.core :as re-frame] + [reagent.core :as reagent] [app.util :as u])) +(defn- animation-interval + "https://gist.github.com/jakearchibald/cb03f15670817001b1157e62a076fe95" + [ms signal f] + (let [start (.-currentTime js/document.timeline)] + (letfn [(frame [time] + (when-not (.-aborted signal) + (f time) + (schedule-frame time))) + (schedule-frame [time] + (let [elapsed (- time start) + rounded-elapsed (* (js/Math.round (/ elapsed ms)) ms) + target-next (+ start rounded-elapsed ms) + delay (- target-next (js/performance.now))] + (js/setTimeout #(js/requestAnimationFrame frame) delay)))] + (schedule-frame start)))) + +(def time (reagent/atom 0)) + +(re-frame/reg-fx + :update-time + (fn [interval-ms] + (animation-interval + interval-ms + (.-signal (js/AbortController.)) + (fn [_] + (reset! time (.getTime (js/Date.))))))) + (re-frame/reg-cofx :time (fn [coeffects _] @@ -96,7 +125,8 @@ (let [db (reset-game {:settings (merge default-settings settings) :profiles (if (seq profiles) profiles default-profiles) :app-info {:version app-version}})] - (cond-> {:db db} + (cond-> {:db db + :update-time 1000} (not= profiles (:profiles db)) (assoc :profiles (:profiles db)))))) (re-frame/reg-event-db diff --git a/src/app/util.cljs b/src/app/util.cljs index c4ff617..8701048 100644 --- a/src/app/util.cljs +++ b/src/app/util.cljs @@ -15,6 +15,13 @@ (str/lower-case x) (str/lower-case y))) +(defn format-elapsed [ms] + (let [s (js/Math.trunc (/ ms 1000)) + m (js/Math.trunc (/ s 60))] + (if (== 0 m) + (str s "s") + (str m "m")))) + (defn merge-close "Merges close inputs next to each other diff --git a/src/app/views.cljs b/src/app/views.cljs index b4518f4..090038f 100644 --- a/src/app/views.cljs +++ b/src/app/views.cljs @@ -2,6 +2,7 @@ (:require [reagent.core :as reagent] [re-frame.core :as re-frame] + [app.util :as u] [app.subs :as subs] [app.events :as events] [app.components.icons.views :as i])) @@ -58,9 +59,10 @@ "Update"]]]])))) (defn amount-history [{:keys [history]}] - [:div.life-input--amount-history - (for [{:keys [time amount]} history] - ^{:key time} [:div (str (when (< 0 amount) "+")) amount])]) + (let [now @events/time] + [:div.life-input--amount-history + (for [{:keys [time amount]} history] + ^{:key time} [:div (str (when (< 0 amount) "+")) amount " (" (u/format-elapsed (- now time)) ")"])])) (defn life-input [_] (let [event (reagent/atom nil)