pleroma-fe/src/lib/persisted_state.js

104 lines
2.9 KiB
JavaScript
Raw Normal View History

import merge from 'lodash.merge'
import objectPath from 'object-path'
import localforage from 'localforage'
2018-09-08 01:17:17 +10: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-08 01:17:17 +10:00
const saveImmedeatelyActions = [
'markNotificationsAsSeen',
'clearCurrentUser',
'setCurrentUser',
'setOption'
]
const defaultStorage = (() => {
return localforage
})()
export default function createPersistedState ({
key = 'vuex-lz',
paths = [],
getState = (key, storage) => {
2017-02-21 04:54:09 +11:00
let value = storage.getItem(key)
return value
},
2018-09-08 01:17:17 +10: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)
} = {}) {
return store => {
getState(key, storage).then((savedState) => {
try {
if (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-09 03:59:12 +11: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
})
}
if (store.state.users.lastLoginName) {
store.dispatch('loginUser', {username: store.state.users.lastLoginName, password: 'xxx'})
}
loaded = true
} catch (e) {
console.log("Couldn't load state")
loaded = true
}
})
subscriber(store)((mutation, state) => {
try {
2018-09-08 01:17:17 +10:00
if (saveImmedeatelyActions.includes(mutation.type)) {
setState(key, reducer(state, paths), storage)
.then(success => {
if (typeof success !== 'undefined') {
if (mutation.type === 'setOption') {
store.dispatch('settingsSaved', { success })
}
}
}, error => {
if (mutation.type === 'setOption') {
store.dispatch('settingsSaved', { error })
}
})
} else {
console.warn(`Not saving to localStorage for: ${mutation.type}`)
}
} catch (e) {
console.log("Couldn't persist state:")
console.log(e)
}
})
}
}