akkoma-fe/src/lib/persisted_state.js

105 lines
3 KiB
JavaScript
Raw Normal View History

import merge from 'lodash.merge'
import objectPath from 'object-path'
import localforage from 'localforage'
2018-09-07 15:17:17 +00:00
import { each } from 'lodash'
let loaded = false
const defaultReducer = (state, paths) => (
paths.length === 0 ? state : paths.reduce((substate, path) => {
objectPath.set(substate, path, objectPath.get(state, path))
return substate
}, {})
)
2018-09-07 15:17:17 +00:00
const saveImmedeatelyActions = [
'markNotificationsAsSeen',
'clearCurrentUser',
'setCurrentUser',
'setHighlight',
2018-10-26 13:16:23 +00:00
'setOption',
'setClientData',
'setToken'
2018-09-07 15:17:17 +00:00
]
const defaultStorage = (() => {
return localforage
})()
export default function createPersistedState ({
key = 'vuex-lz',
paths = [],
getState = (key, storage) => {
2017-02-20 17:54:09 +00:00
let value = storage.getItem(key)
return value
},
2018-09-07 15:17:17 +00:00
setState = (key, state, storage) => {
if (!loaded) {
console.log('waiting for old state to be loaded...')
return Promise.resolve()
} else {
return storage.setItem(key, state)
}
},
reducer = defaultReducer,
storage = defaultStorage,
subscriber = store => handler => store.subscribe(handler)
} = {}) {
2018-10-26 13:16:23 +00:00
return getState(key, storage).then((savedState) => {
return store => {
try {
if (savedState !== null && typeof savedState === 'object') {
// build user cache
const usersState = savedState.users || {}
usersState.usersObject = {}
const users = usersState.users || []
each(users, (user) => { usersState.usersObject[user.id] = user })
savedState.users = usersState
2017-03-08 16:59:12 +00:00
store.replaceState(
merge({}, store.state, savedState)
)
}
if (store.state.config.customTheme) {
// This is a hack to deal with async loading of config.json and themes
// See: style_setter.js, setPreset()
window.themeLoaded = true
store.dispatch('setOption', {
name: 'customTheme',
value: store.state.config.customTheme
})
}
2018-10-26 13:16:23 +00:00
if (store.state.oauth.token) {
store.dispatch('loginUser', store.state.oauth.token)
}
loaded = true
} catch (e) {
console.log("Couldn't load state")
console.error(e)
loaded = true
}
2018-10-26 13:16:23 +00:00
subscriber(store)((mutation, state) => {
try {
if (saveImmedeatelyActions.includes(mutation.type)) {
setState(key, reducer(state, paths), storage)
.then(success => {
if (typeof success !== 'undefined') {
if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
2018-10-26 13:16:23 +00:00
store.dispatch('settingsSaved', { success })
}
}
}, error => {
if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
2018-10-26 13:16:23 +00:00
store.dispatch('settingsSaved', { error })
2018-09-07 15:17:17 +00:00
}
2018-10-26 13:16:23 +00:00
})
}
} catch (e) {
console.log("Couldn't persist state:")
console.log(e)
2018-09-07 15:17:17 +00:00
}
2018-10-26 13:16:23 +00:00
})
}
})
}