2018-01-28 21:09:39 +00:00
|
|
|
import { Store } from 'svelte/store'
|
2018-08-16 17:23:26 +00:00
|
|
|
let lifecycle
|
|
|
|
if (process.browser) {
|
|
|
|
lifecycle = require('page-lifecycle/dist/lifecycle.mjs').default
|
|
|
|
}
|
2018-01-28 21:09:39 +00:00
|
|
|
|
|
|
|
const LS = process.browser && localStorage
|
|
|
|
|
2018-02-09 06:29:29 +00:00
|
|
|
function safeParse (str) {
|
2018-01-28 22:56:25 +00:00
|
|
|
return !str ? undefined : (str === 'undefined' ? undefined : JSON.parse(str))
|
|
|
|
}
|
|
|
|
|
2018-01-28 21:09:39 +00:00
|
|
|
export class LocalStorageStore extends Store {
|
2018-02-09 06:29:29 +00:00
|
|
|
constructor (state, keysToWatch) {
|
2018-01-28 21:09:39 +00:00
|
|
|
super(state)
|
|
|
|
if (!process.browser) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
this._keysToWatch = keysToWatch
|
|
|
|
this._keysToSave = {}
|
|
|
|
let newState = {}
|
|
|
|
for (let i = 0, len = LS.length; i < len; i++) {
|
|
|
|
let key = LS.key(i)
|
|
|
|
if (key.startsWith('store_')) {
|
|
|
|
let item = LS.getItem(key)
|
2018-01-28 22:56:25 +00:00
|
|
|
newState[key.substring(6)] = safeParse(item)
|
2018-01-28 21:09:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
this.set(newState)
|
2018-04-19 06:48:13 +00:00
|
|
|
this.on('state', ({changed}) => {
|
2018-01-28 21:09:39 +00:00
|
|
|
Object.keys(changed).forEach(change => {
|
|
|
|
if (this._keysToWatch.has(change)) {
|
|
|
|
this._keysToSave[change] = true
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
2018-02-28 07:38:33 +00:00
|
|
|
if (process.browser) {
|
2018-08-16 17:23:26 +00:00
|
|
|
lifecycle.addEventListener('statechange', e => {
|
|
|
|
if (e.newState === 'passive') {
|
|
|
|
console.log('saving LocalStorageStore...')
|
|
|
|
this.save()
|
|
|
|
}
|
|
|
|
})
|
2018-02-28 07:38:33 +00:00
|
|
|
}
|
2018-01-28 21:09:39 +00:00
|
|
|
}
|
|
|
|
|
2018-02-09 06:29:29 +00:00
|
|
|
save () {
|
2018-01-28 21:09:39 +00:00
|
|
|
if (!process.browser) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
Object.keys(this._keysToSave).forEach(key => {
|
2018-04-20 04:38:11 +00:00
|
|
|
LS.setItem(`store_${key}`, JSON.stringify(this.get()[key]))
|
2018-01-28 21:09:39 +00:00
|
|
|
})
|
|
|
|
this._keysToSave = {}
|
|
|
|
}
|
2018-02-09 06:29:29 +00:00
|
|
|
}
|