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/.
|
|
|
|
;;
|
|
|
|
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>
|
|
|
|
|
|
|
|
(ns uxbox.util.storage
|
|
|
|
(:require [uxbox.util.transit :as t]))
|
|
|
|
|
|
|
|
(defn- persist
|
|
|
|
[alias value]
|
2020-04-30 08:19:40 +02:00
|
|
|
(when-not (or (= *target* "nodejs")
|
|
|
|
(not (exists? js/window)))
|
|
|
|
(let [key (name alias)
|
|
|
|
value (t/encode value)]
|
|
|
|
(.setItem js/localStorage key value))))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
|
|
|
(defn- load
|
|
|
|
[alias]
|
2020-04-30 08:19:40 +02:00
|
|
|
(when-not (or (= *target* "nodejs")
|
|
|
|
(not (exists? js/window)))
|
2016-04-15 23:39:04 +03:00
|
|
|
(let [data (.getItem js/localStorage (name alias))]
|
2020-04-30 08:19:40 +02:00
|
|
|
(try
|
2016-04-15 23:23:48 +03:00
|
|
|
(t/decode data)
|
2020-04-30 08:19:40 +02:00
|
|
|
(catch :default e
|
|
|
|
(js/console.error "Error on loading data from local storage." e)
|
|
|
|
nil)))))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
2020-04-30 08:19:40 +02:00
|
|
|
(defn- make-storage
|
2016-04-15 23:23:48 +03:00
|
|
|
[alias]
|
|
|
|
(let [data (atom (load alias))]
|
2020-04-30 08:19:40 +02:00
|
|
|
(add-watch data :sub #(persist alias %4))
|
2016-04-15 23:23:48 +03:00
|
|
|
(reify
|
2019-07-24 00:48:24 +02:00
|
|
|
Object
|
|
|
|
(toString [_]
|
|
|
|
(str "Storage" (pr-str @data)))
|
|
|
|
|
2016-04-15 23:23:48 +03:00
|
|
|
ICounted
|
|
|
|
(-count [_]
|
|
|
|
(count @data))
|
|
|
|
|
|
|
|
ISeqable
|
|
|
|
(-seq [_]
|
|
|
|
(seq @data))
|
|
|
|
|
|
|
|
IReset
|
|
|
|
(-reset! [self newval]
|
2019-07-24 00:48:24 +02:00
|
|
|
(reset! data newval))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
|
|
|
ISwap
|
|
|
|
(-swap! [self f]
|
2016-04-15 23:39:04 +03:00
|
|
|
(swap! data f))
|
2016-04-15 23:23:48 +03:00
|
|
|
(-swap! [self f x]
|
2016-04-15 23:39:04 +03:00
|
|
|
(swap! data f x))
|
2016-04-15 23:23:48 +03:00
|
|
|
(-swap! [self f x y]
|
2016-04-15 23:39:04 +03:00
|
|
|
(swap! data f x y))
|
2016-04-15 23:23:48 +03:00
|
|
|
(-swap! [self f x y more]
|
2016-04-15 23:39:04 +03:00
|
|
|
(apply swap! data f x y more))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
|
|
|
ILookup
|
|
|
|
(-lookup [_ key]
|
2020-04-30 08:19:40 +02:00
|
|
|
(get @data key nil))
|
2016-04-15 23:23:48 +03:00
|
|
|
(-lookup [_ key not-found]
|
2020-04-30 08:19:40 +02:00
|
|
|
(get @data key not-found)))))
|
2016-04-15 23:23:48 +03:00
|
|
|
|
2020-04-30 08:19:40 +02:00
|
|
|
(def storage
|
|
|
|
(make-storage "uxbox"))
|