aboutsummaryrefslogtreecommitdiff
path: root/src/lib/persisted_state.js
blob: 006107e207ac7f6d8875b70590406e3dd4e3e0ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import merge from 'lodash.merge'
import objectPath from 'object-path'
import localforage from 'localforage'
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
  }, {})
)

const saveImmedeatelyActions = [
  'markNotificationsAsSeen',
  'clearCurrentUser',
  'setCurrentUser',
  'setHighlight',
  'setOption'
]

const defaultStorage = (() => {
  return localforage
})()

export default function createPersistedState ({
  key = 'vuex-lz',
  paths = [],
  getState = (key, storage) => {
    let value = storage.getItem(key)
    return value
  },
  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

          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 {
        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 })
              }
            })
        }
      } catch (e) {
        console.log("Couldn't persist state:")
        console.log(e)
      }
    })
  }
}