|
@@ -1,11 +1,15 @@
|
|
|
-import { domReady } from './utils'
|
|
|
+import { domReady, getMethods } from './utils'
|
|
|
import { createObservable } from './observable'
|
|
|
|
|
|
const Spruce = {
|
|
|
stores: {},
|
|
|
|
|
|
+ persisted: [],
|
|
|
+
|
|
|
subscribers: [],
|
|
|
|
|
|
+ disableReactivity: false,
|
|
|
+
|
|
|
async start() {
|
|
|
await domReady()
|
|
|
|
|
@@ -14,7 +18,17 @@ 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 +46,15 @@ const Spruce = {
|
|
|
})
|
|
|
},
|
|
|
|
|
|
- store(name, state) {
|
|
|
+ store(name, state, persist = false) {
|
|
|
+ if (persist) {
|
|
|
+ this.stores[name] = this.retrieveFromLocalStorage(name, getMethods(state))
|
|
|
+
|
|
|
+ if (! this.persisted.includes(name)) {
|
|
|
+ this.persisted.push(name)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
if (! this.stores[name]) {
|
|
|
this.stores[name] = state
|
|
|
}
|
|
@@ -56,6 +78,16 @@ const Spruce = {
|
|
|
this.subscribers.filter(el => !! el.__x).forEach(el => {
|
|
|
el.__x.updateElements(el)
|
|
|
})
|
|
|
+ },
|
|
|
+
|
|
|
+ retrieveFromLocalStorage(name, methods = {}) {
|
|
|
+ const storage = JSON.parse(window.localStorage.getItem(`__spruce:${name}`))
|
|
|
+
|
|
|
+ return storage ? Object.assign(methods, storage) : null
|
|
|
+ },
|
|
|
+
|
|
|
+ updateLocalStorage(name) {
|
|
|
+ window.localStorage.setItem(`__spruce:${name}`, JSON.stringify(this.store(name)))
|
|
|
}
|
|
|
}
|
|
|
|