0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-02-20 22:06:07 -05:00
penpot/frontend/src/app/util/storage.cljs

55 lines
1.5 KiB
Text
Raw Normal View History

;; 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
(ns app.util.storage
2020-10-05 18:20:39 +02:00
(:require
[app.util.transit :as t]
[app.util.timers :as tm]
[app.util.globals :as g]
2020-10-05 18:20:39 +02:00
[app.common.exceptions :as ex]))
(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)))
(defn- persist
[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)))))
(defn- load
[storage]
(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"))))
(add-watch storage :persistence #(persist js/localStorage %3 %4))