From 465712c1e4c91780dc34be9849e154f1b853bdfe Mon Sep 17 00:00:00 2001 From: Daniel Compton Date: Fri, 25 Aug 2017 11:00:36 +1200 Subject: [PATCH] Add local-store get default value, save ls keys with a safe prefix --- src/day8/re_frame/trace.cljs | 3 +-- src/day8/re_frame/trace/localstorage.cljs | 26 +++++++++++++++-------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/day8/re_frame/trace.cljs b/src/day8/re_frame/trace.cljs index 896e274..ddf9343 100644 --- a/src/day8/re_frame/trace.cljs +++ b/src/day8/re_frame/trace.cljs @@ -188,8 +188,7 @@ (defn render-trace-panel [] (let [filter-input (r/atom "") - filter-items (r/atom (or (localstorage/get "filter-items") - [])) + filter-items (r/atom (localstorage/get "filter-items" [])) filter-type (r/atom :contains) input-error (r/atom false) trace-detail-expansions (r/atom {:show-all? false :overrides {}})] diff --git a/src/day8/re_frame/trace/localstorage.cljs b/src/day8/re_frame/trace/localstorage.cljs index df6cf08..c1ff29c 100644 --- a/src/day8/re_frame/trace/localstorage.cljs +++ b/src/day8/re_frame/trace/localstorage.cljs @@ -4,15 +4,23 @@ [cljs.reader :as reader]) (:refer-clojure :exclude [get])) -(def mech (goog.storage.mechanism.HTML5LocalStorage.)) +(def storage (goog.storage.Storage. (goog.storage.mechanism.HTML5LocalStorage.))) -(defn- storage [] - (goog.storage.Storage. mech)) +(defn- safe-key [key] + "Adds a unique prefix to keys to ensure they don't collide with the host application" + (str "day8.re-frame.trace." key)) -(defn get [key] - (when-let [value (.get (storage) key)] - (cljs.reader/read-string value))) +(defn get + "Gets a re-frame-trace value from local storage." + ([key] + (get key nil)) + ([key not-found] + (let [value (.get storage (safe-key key))] + (if (undefined? value) + not-found + (reader/read-string value))))) -(defn save! [key value] - (let [store (storage)] - (.set store key (pr-str value)))) +(defn save! + "Saves a re-frame-trace value to local storage." + [key value] + (.set storage (safe-key key) (pr-str value)))