-
Notifications
You must be signed in to change notification settings - Fork 606
/
Copy pathuse-storage.js
56 lines (48 loc) · 1.43 KB
/
use-storage.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
56
import { useEffect, useState } from 'react'
import { navigate } from '@reach/router'
import useDeck from './use-deck'
const keys = {
slide: 'mdx-deck-slide',
step: 'mdx-deck-step',
}
export const useStorage = () => {
const context = useDeck()
const [focused, setFocused] = useState(false)
const handleFocus = () => setFocused(true)
const handleBlur = () => setFocused(false)
const handleStorageChange = e => {
const n = parseInt(e.newValue, 10)
// if (focused) return
if (isNaN(n)) return
switch (e.key) {
case keys.slide:
navigate([context.slug, n].join('/'))
break
case keys.step:
context.setState({ step: n })
break
default:
break
}
}
useEffect(() => {
setFocused(document.hasFocus())
}, [])
useEffect(() => {
if (!focused) window.addEventListener('storage', handleStorageChange)
window.addEventListener('focus', handleFocus)
window.addEventListener('blur', handleBlur)
return () => {
if (!focused) window.removeEventListener('storage', handleStorageChange)
window.removeEventListener('focus', handleFocus)
window.removeEventListener('blur', handleBlur)
}
}, [focused])
// store changes
useEffect(() => {
if (!focused) return
localStorage.setItem(keys.slide, context.index)
localStorage.setItem(keys.step, context.step)
}, [focused, context.index, context.step])
}
export default useStorage