logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://hacktivis.me/git/pleroma-fe.git

persisted_state.js (2648B)


  1. import merge from 'lodash.merge'
  2. import localforage from 'localforage'
  3. import { each, get, set, cloneDeep } from 'lodash'
  4. let loaded = false
  5. const defaultReducer = (state, paths) => (
  6. paths.length === 0
  7. ? state
  8. : paths.reduce((substate, path) => {
  9. set(substate, path, get(state, path))
  10. return substate
  11. }, {})
  12. )
  13. const saveImmedeatelyActions = [
  14. 'markNotificationsAsSeen',
  15. 'clearCurrentUser',
  16. 'setCurrentUser',
  17. 'setServerSideStorage',
  18. 'setHighlight',
  19. 'setOption',
  20. 'setClientData',
  21. 'setToken',
  22. 'clearToken'
  23. ]
  24. const defaultStorage = (() => {
  25. return localforage
  26. })()
  27. export default function createPersistedState ({
  28. key = 'vuex-lz',
  29. paths = [],
  30. getState = (key, storage) => {
  31. const value = storage.getItem(key)
  32. return value
  33. },
  34. setState = (key, state, storage) => {
  35. if (!loaded) {
  36. console.info('waiting for old state to be loaded...')
  37. return Promise.resolve()
  38. } else {
  39. return storage.setItem(key, state)
  40. }
  41. },
  42. reducer = defaultReducer,
  43. storage = defaultStorage,
  44. subscriber = store => handler => store.subscribe(handler)
  45. } = {}) {
  46. return getState(key, storage).then((savedState) => {
  47. return store => {
  48. try {
  49. if (savedState !== null && typeof savedState === 'object') {
  50. // build user cache
  51. const usersState = savedState.users || {}
  52. usersState.usersObject = {}
  53. const users = usersState.users || []
  54. each(users, (user) => { usersState.usersObject[user.id] = user })
  55. savedState.users = usersState
  56. store.replaceState(
  57. merge({}, store.state, savedState)
  58. )
  59. }
  60. loaded = true
  61. } catch (e) {
  62. console.error("Couldn't load state")
  63. console.error(e)
  64. loaded = true
  65. }
  66. subscriber(store)((mutation, state) => {
  67. try {
  68. if (saveImmedeatelyActions.includes(mutation.type)) {
  69. setState(key, reducer(cloneDeep(state), paths), storage)
  70. .then(success => {
  71. if (typeof success !== 'undefined') {
  72. if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
  73. store.dispatch('settingsSaved', { success })
  74. }
  75. }
  76. }, error => {
  77. if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
  78. store.dispatch('settingsSaved', { error })
  79. }
  80. })
  81. }
  82. } catch (e) {
  83. console.error("Couldn't persist state:")
  84. console.error(e)
  85. }
  86. })
  87. }
  88. })
  89. }