2021-07-05 05:19:04 +02:00
|
|
|
import { safeLocalStorage as LS } from '../_utils/safeLocalStorage.js'
|
|
|
|
import { lifecycle } from '../_utils/lifecycle.js'
|
|
|
|
import { safeParse } from '../_utils/safeParse.js'
|
|
|
|
import * as storePackage from 'svelte/store.umd.js'
|
|
|
|
|
|
|
|
const { Store } = storePackage
|
2018-01-28 23:56:25 +01:00
|
|
|
|
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 = {}
|
2019-08-03 22:49:37 +02:00
|
|
|
const newState = {}
|
2018-01-28 22:09:39 +01:00
|
|
|
for (let i = 0, len = LS.length; i < len; i++) {
|
2019-08-03 22:49:37 +02:00
|
|
|
const key = LS.key(i)
|
2018-01-28 22:09:39 +01:00
|
|
|
if (key.startsWith('store_')) {
|
2019-08-03 22:49:37 +02:00
|
|
|
const 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)
|
2018-08-30 06:42:57 +02:00
|
|
|
this.on('state', ({ changed }) => {
|
2018-01-28 22:09:39 +01:00
|
|
|
Object.keys(changed).forEach(change => {
|
|
|
|
if (this._keysToWatch.has(change)) {
|
|
|
|
this._keysToSave[change] = true
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
2018-02-28 08:38:33 +01:00
|
|
|
if (process.browser) {
|
2019-05-09 04:58:32 +02:00
|
|
|
lifecycle.addEventListener('statechange', e => {
|
|
|
|
if (e.newState === 'passive') {
|
|
|
|
console.log('saving LocalStorageStore...')
|
|
|
|
this.save()
|
|
|
|
}
|
2018-08-16 19:23:26 +02:00
|
|
|
})
|
2018-02-28 08:38:33 +01:00
|
|
|
}
|
2018-01-28 22:09:39 +01:00
|
|
|
}
|
|
|
|
|
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 => {
|
2018-04-20 06:38:11 +02:00
|
|
|
LS.setItem(`store_${key}`, JSON.stringify(this.get()[key]))
|
2018-01-28 22:09:39 +01:00
|
|
|
})
|
|
|
|
this._keysToSave = {}
|
|
|
|
}
|
2018-02-09 07:29:29 +01:00
|
|
|
}
|