|
@@ -4,8 +4,12 @@ import { createObservable } from './observable'
|
|
|
const Spruce = {
|
|
|
stores: {},
|
|
|
|
|
|
+ persisted: [],
|
|
|
+
|
|
|
subscribers: [],
|
|
|
|
|
|
+ disableReactivity: false,
|
|
|
+
|
|
|
async start() {
|
|
|
await domReady()
|
|
|
|
|
@@ -14,7 +18,19 @@ const Spruce = {
|
|
|
document.addEventListener('turbolinks:render', this.attach)
|
|
|
|
|
|
this.stores = createObservable(this.stores, {
|
|
|
- set: this.updateSubscribers.bind(this)
|
|
|
+ set: () => {
|
|
|
+ if (this.disableReactivity) {
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ this.updateSubscribers()
|
|
|
+
|
|
|
+ this.disableReactivity = true
|
|
|
+
|
|
|
+ this.persisted.forEach(this.updateLocalStorage.bind(this))
|
|
|
+
|
|
|
+ this.disableReactivity = false
|
|
|
+ }
|
|
|
})
|
|
|
},
|
|
|
|
|
@@ -32,7 +48,13 @@ const Spruce = {
|
|
|
})
|
|
|
},
|
|
|
|
|
|
- store(name, state) {
|
|
|
+ store(name, state, persist = false) {
|
|
|
+ if (persist) {
|
|
|
+ this.stores[name] = this.retrieveFromLocalStorage(name)
|
|
|
+
|
|
|
+ this.persisted.push(name)
|
|
|
+ }
|
|
|
+
|
|
|
if (! this.stores[name]) {
|
|
|
this.stores[name] = state
|
|
|
}
|
|
@@ -56,6 +78,35 @@ const Spruce = {
|
|
|
this.subscribers.filter(el => !! el.__x).forEach(el => {
|
|
|
el.__x.updateElements(el)
|
|
|
})
|
|
|
+ },
|
|
|
+
|
|
|
+ retrieveFromLocalStorage(name) {
|
|
|
+ const storage = JSON.parse(window.localStorage.getItem(`__spruce:${name}`))
|
|
|
+
|
|
|
+ if (! storage) {
|
|
|
+ return null
|
|
|
+ }
|
|
|
+
|
|
|
+ return storage
|
|
|
+ },
|
|
|
+
|
|
|
+ updateLocalStorage(name) {
|
|
|
+ window.localStorage.setItem(
|
|
|
+ `__spruce:${name}`,
|
|
|
+ JSON.stringify(this.store(name))
|
|
|
+ )
|
|
|
+ },
|
|
|
+
|
|
|
+ persist(name) {
|
|
|
+ if (! this.persisted.includes(name)) {
|
|
|
+ this.persisted.push(name)
|
|
|
+ }
|
|
|
+
|
|
|
+ this.updateLocalStorage(name)
|
|
|
+ },
|
|
|
+
|
|
|
+ dontPersist(name) {
|
|
|
+ this.persisted = this.persisted.filter(_ => name !== _)
|
|
|
}
|
|
|
}
|
|
|
|