pinafore/routes/_store/LocalStorageStore.js

45 lines
1.1 KiB
JavaScript
Raw Normal View History

2018-01-28 22:09:39 +01:00
import { Store } from 'svelte/store'
const LS = process.browser && localStorage
2018-02-09 07:29:29 +01:00
function safeParse (str) {
2018-01-28 23:56:25 +01:00
return !str ? undefined : (str === 'undefined' ? undefined : JSON.parse(str))
}
2018-01-28 22:09:39 +01:00
export class LocalStorageStore extends Store {
2018-02-09 07:29:29 +01:00
constructor (state, keysToWatch) {
2018-01-28 22:09:39 +01: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 23:56:25 +01:00
newState[key.substring(6)] = safeParse(item)
2018-01-28 22:09:39 +01:00
}
}
this.set(newState)
this.onchange((state, changed) => {
Object.keys(changed).forEach(change => {
if (this._keysToWatch.has(change)) {
this._keysToSave[change] = true
}
})
})
}
2018-02-09 07:29:29 +01:00
save () {
2018-01-28 22:09:39 +01:00
if (!process.browser) {
return
}
Object.keys(this._keysToSave).forEach(key => {
LS.setItem(`store_${key}`, JSON.stringify(this.get(key)))
})
this._keysToSave = {}
}
2018-02-09 07:29:29 +01:00
}