2016-04-15 23:23:48 +03:00
|
|
|
;; This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
;;
|
2021-04-10 09:43:04 +02:00
|
|
|
;; Copyright (c) UXBOX Labs SL
|
2016-04-15 23:23:48 +03:00
|
|
|
|
2020-08-18 19:26:37 +02:00
|
|
|
(ns app.util.storage
|
2020-10-05 18:20:39 +02:00
|
|
|
(:require
|
|
|
|
[app.util.transit :as t]
|
|
|
|
[app.util.timers :as tm]
|
2021-05-07 16:17:38 +02:00
|
|
|
[app.util.globals :as g]
|
2020-10-05 18:20:39 +02:00
|
|
|
[app.common.exceptions :as ex]))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
2020-04-30 12:25:55 +02:00
|
|
|
(defn- ^boolean is-worker?
|
|
|
|
[]
|
|
|
|
(or (= *target* "nodejs")
|
|
|
|
(not (exists? js/window))))
|
|
|
|
|
2020-10-05 18:20:39 +02:00
|
|
|
(defn- decode
|
|
|
|
[v]
|
|
|
|
(ex/ignoring (t/decode v)))
|
|
|
|
|
|
|
|
|
2016-04-15 23:23:48 +03:00
|
|
|
(defn- persist
|
2021-05-04 15:19:07 +02:00
|
|
|
[storage prev curr]
|
|
|
|
(run! (fn [key]
|
|
|
|
(let [prev* (get prev key)
|
|
|
|
curr* (get curr key)]
|
|
|
|
(when (not= curr* prev*)
|
|
|
|
(tm/schedule-on-idle
|
|
|
|
#(if (some? curr*)
|
|
|
|
(.setItem ^js storage (t/encode key) (t/encode curr*))
|
|
|
|
(.removeItem ^js storage (t/encode key)))))))
|
|
|
|
|
|
|
|
(into #{} (concat (keys curr)
|
|
|
|
(keys prev)))))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
|
|
|
(defn- load
|
2021-05-04 15:19:07 +02:00
|
|
|
[storage]
|
2021-05-07 16:17:38 +02:00
|
|
|
(when storage
|
|
|
|
(let [len (.-length ^js storage)]
|
|
|
|
(reduce (fn [res index]
|
|
|
|
(let [key (.key ^js storage index)
|
|
|
|
val (.getItem ^js storage key)]
|
|
|
|
(try
|
|
|
|
(assoc res (t/decode key) (t/decode val))
|
|
|
|
(catch :default e
|
|
|
|
res))))
|
|
|
|
{}
|
|
|
|
(range len)))))
|
|
|
|
|
|
|
|
|
|
|
|
(defonce storage (atom (load (unchecked-get g/global "localStorage"))))
|
2021-05-04 15:19:07 +02:00
|
|
|
(add-watch storage :persistence #(persist js/localStorage %3 %4))
|