-
Notifications
You must be signed in to change notification settings - Fork 18
/
useGraphSetting.tsx
85 lines (72 loc) · 1.7 KB
/
useGraphSetting.tsx
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
import { useReducer } from 'react'
import { DEFAULT_BLOCK_SHAPE, DEFAULT_SIZE, DEFAULT_THEME } from './constants'
import type { GraphSettings } from './types'
type State = GraphSettings
type Action =
| {
type: 'size'
payload: State['size']
}
| {
type: 'yearRange'
payload: State['yearRange']
}
| {
type: 'daysLabel'
payload: State['daysLabel']
}
| {
type: 'showAttribution'
payload: State['showAttribution']
}
| {
type: 'blockShape'
payload: State['blockShape']
}
| {
type: 'theme'
payload: State['theme']
}
| {
type: 'reset'
payload?: never
}
| {
/** Replace all existing settings. */
type: 'replace'
payload?: State
}
const initialState: State = {
size: DEFAULT_SIZE,
theme: DEFAULT_THEME,
blockShape: DEFAULT_BLOCK_SHAPE,
daysLabel: false,
showAttribution: true,
}
export function useGraphSetting() {
return useReducer((state: State, { type, payload }: Action): State => {
switch (type) {
case 'size':
return { ...state, size: payload }
case 'yearRange':
return { ...state, yearRange: payload }
case 'daysLabel':
return { ...state, daysLabel: payload }
case 'showAttribution':
return { ...state, showAttribution: payload }
case 'blockShape':
return { ...state, blockShape: payload }
case 'theme':
return { ...state, theme: payload }
case 'reset':
return initialState
case 'replace':
if (payload) {
return payload
}
return state
default:
throw new Error(`Not a valid action type.`)
}
}, initialState)
}