diff --git a/src/app/autosave.cljs b/src/app/autosave.cljs new file mode 100644 index 0000000..737e3ce --- /dev/null +++ b/src/app/autosave.cljs @@ -0,0 +1,51 @@ +(ns app.autosave + (:require + [re-frame.core :as re-frame] + [clojure.edn :as edn])) + +(defn init [autosave-key] + (re-frame/reg-cofx + ::autosave + (fn [coeffects _] + (assoc coeffects + :autosave + (edn/read-string + (js/window.localStorage.getItem autosave-key))))) + + (re-frame/reg-fx + ::autosave + (fn [db] + (js/window.localStorage.setItem autosave-key (pr-str db)))) + + (re-frame/reg-fx + ::autosave-remove + (fn [_] + (js/window.localStorage.removeItem autosave-key))) + + (re-frame/reg-event-fx + ::autosave + (fn [{:keys [db]}] + {::autosave db})) + + (re-frame/reg-event-fx + ::autosave-remove + (fn [_] + {::autosave-remove nil})) + + (re-frame/reg-event-fx + ::autosave-load + [(re-frame/inject-cofx ::autosave)] + (fn [cofx] + (if-let [autosave (:autosave cofx)] + {:db autosave + ::autosave-remove nil} + {}))) + + (re-frame/dispatch [::autosave-load]) + (js/document.addEventListener + "visibilitychange" + (fn [] + (case (.-visibilityState js/document) + "visible" (re-frame/dispatch [::autosave-remove]) + "hidden" (re-frame/dispatch [::autosave]) + nil)))) diff --git a/src/app/core.cljs b/src/app/core.cljs index d29e356..605f659 100644 --- a/src/app/core.cljs +++ b/src/app/core.cljs @@ -4,7 +4,8 @@ [reagent.dom :as reagent-dom] [app.config :as config] [app.views :as views] - [app.events :as events])) + [app.events :as events] + [app.autosave :as autosave])) (defn mount-root [] (re-frame/clear-subscription-cache!) @@ -42,6 +43,7 @@ (dev-setup) (prod-setup) (prevent-screen-lock) + (autosave/init "nenadalm.life-counter/autosave") (re-frame/dispatch-sync [::events/init]) (mount-root)) diff --git a/src/app/events.cljs b/src/app/events.cljs index 5e448df..d5b61c3 100644 --- a/src/app/events.cljs +++ b/src/app/events.cljs @@ -121,11 +121,13 @@ [(re-frame/inject-cofx :app-version) (re-frame/inject-cofx :settings) (re-frame/inject-cofx :profiles)] - (fn [{:keys [app-version settings profiles]} _] - (let [db (reset-game {:settings (merge default-settings settings) - :profiles (if (seq profiles) profiles default-profiles) - :app-info {:version app-version}})] - (cond-> {:db db + (fn [{:keys [app-version settings profiles db]} _] + (let [data {:settings (merge default-settings settings) + :profiles (if (seq profiles) profiles default-profiles) + :app-info {:version app-version}}] + (cond-> {:db (if (seq db) + (merge db data) + (reset-game data)) :update-time 1000} (not= profiles (:profiles db)) (assoc :profiles (:profiles db))))))