logo

pleroma-fe

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

persisted_state.js (2706B)


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