Skip to content

Commit

Permalink
Autosave feature
Browse files Browse the repository at this point in the history
- prevents losing state when app is accidentally closed
  • Loading branch information
nenadalm committed Jan 6, 2024
1 parent 9380762 commit ef74f93
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 6 deletions.
51 changes: 51 additions & 0 deletions src/app/autosave.cljs
Original file line number Diff line number Diff line change
@@ -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))))
4 changes: 3 additions & 1 deletion src/app/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -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!)
Expand Down Expand Up @@ -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))

Expand Down
12 changes: 7 additions & 5 deletions src/app/events.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -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))))))

Expand Down

0 comments on commit ef74f93

Please sign in to comment.