semaphore/routes/_utils/store.js

59 lines
1.5 KiB
JavaScript
Raw Normal View History

import { Store } from 'svelte/store.js'
2018-01-13 06:05:57 +00:00
const LS = process.browser && localStorage
class LocalStorageStore extends Store {
2018-01-13 06:05:57 +00:00
constructor(state) {
super(state)
if (process.browser) {
2018-01-13 06:05:57 +00:00
this.lastChanged = {}
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)
newState[key.substring(6)] = item === 'undefined' ? undefined : JSON.parse(item)
}
}
2018-01-13 06:05:57 +00:00
this.set(newState)
this.onchange((state, changed) => {
Object.keys(changed).forEach(change => {
if (!this._computed[change]) { // TODO: better way to ignore computed values?
this.lastChanged[change] = true
}
})
})
}
}
save() {
if (process.browser) {
2018-01-13 06:05:57 +00:00
Object.keys(this.lastChanged).forEach(key => {
LS.setItem(`store_${key}`, JSON.stringify(this.get(key)))
})
this.lastChanged = {}
}
}
}
const store = new LocalStorageStore({
2018-01-13 06:24:54 +00:00
instanceNameInSearch: '',
currentRegisteredInstance: null,
currentRegisteredInstanceName: '',
currentInstance: null,
loggedInInstances: {},
loggedInInstancesInOrder: [],
instanceThemes: {}
})
2018-01-09 02:14:21 +00:00
store.compute(
'isUserLoggedIn',
2018-01-13 06:24:54 +00:00
['currentInstance', 'loggedInInstances'],
(currentInstance, loggedInInstances) => !!(currentInstance && Object.keys(loggedInInstances).includes(currentInstance))
2018-01-09 02:14:21 +00:00
)
if (process.browser && process.env.NODE_ENV !== 'production') {
window.store = store // for debugging
}
export { store }