-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
StateStorage.js
55 lines (47 loc) · 1.56 KB
/
StateStorage.js
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
const STATE_KEY_PREFIX = `@@scroll|`
const GATSBY_ROUTER_SCROLL_STATE = `___GATSBY_REACT_ROUTER_SCROLL`
export default class SessionStorage {
read(location, key) {
const stateKey = this.getStateKey(location, key)
try {
const value = sessionStorage.getItem(stateKey)
return JSON.parse(value)
} catch (e) {
console.warn(
`[gatsby-react-router-scroll] Unable to access sessionStorage; sessionStorage is not available.`
)
if (
window &&
window[GATSBY_ROUTER_SCROLL_STATE] &&
window[GATSBY_ROUTER_SCROLL_STATE][stateKey]
) {
return window[GATSBY_ROUTER_SCROLL_STATE][stateKey]
}
return {}
}
}
save(location, key, value) {
const stateKey = this.getStateKey(location, key)
const storedValue = JSON.stringify(value)
try {
sessionStorage.setItem(stateKey, storedValue)
} catch (e) {
if (window && window[GATSBY_ROUTER_SCROLL_STATE]) {
window[GATSBY_ROUTER_SCROLL_STATE][stateKey] = JSON.parse(storedValue)
} else {
window[GATSBY_ROUTER_SCROLL_STATE] = {}
window[GATSBY_ROUTER_SCROLL_STATE][stateKey] = JSON.parse(storedValue)
}
console.warn(
`[gatsby-react-router-scroll] Unable to save state in sessionStorage; sessionStorage is not available.`
)
}
}
getStateKey(location, key) {
const locationKey = location.key
const stateKeyBase = `${STATE_KEY_PREFIX}${locationKey}`
return key === null || typeof key === `undefined`
? stateKeyBase
: `${stateKeyBase}|${key}`
}
}