pinafore/src/routes/_store/LocalStorageStore.js

50 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-01-28 21:09:39 +00:00
import { Store } from 'svelte/store'
import { safeLocalStorage as LS } from '../_utils/safeLocalStorage'
import { lifecycle } from '../_utils/lifecycle'
import { safeParse } from '../_utils/safeParse'
2018-01-28 22:56:25 +00:00
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 = {}
2019-08-03 20:49:37 +00:00
const newState = {}
2018-01-28 21:09:39 +00:00
for (let i = 0, len = LS.length; i < len; i++) {
2019-08-03 20:49:37 +00:00
const key = LS.key(i)
2018-01-28 21:09:39 +00:00
if (key.startsWith('store_')) {
2019-08-03 20:49:37 +00:00
const 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)
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) {
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 => {
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
}