forked from jbx-protocol/juice-interface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJuiceTheme.tsx
71 lines (60 loc) · 2.02 KB
/
JuiceTheme.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
import type { ThemeContextType } from 'contexts/themeContext'
import { useEffect, useState } from 'react'
import { juiceTheme } from 'constants/theme'
import { ThemeOption } from 'constants/theme/theme-option'
const flattenNestedObject = (
nestedObj: Record<string, any>,
prefix?: string,
): Record<string, string> =>
Object.keys(nestedObj).reduce((acc, key) => {
const name = prefix ? prefix + '-' + key : key
return {
...acc,
...(typeof nestedObj[key] === 'string'
? { [name]: nestedObj[key] }
: flattenNestedObject(nestedObj[key], name)),
}
}, {})
export function useJuiceTheme(
storageKey: string = 'jb_theme',
): ThemeContextType {
const initialThemeOption =
(localStorage.getItem(storageKey) as ThemeOption) || ThemeOption.light
const [currentThemeOption, setCurrentThemeOption] =
useState<ThemeOption>(initialThemeOption)
const [isDarkMode, setIsDarkMode] = useState<boolean>(
initialThemeOption === ThemeOption.dark,
)
const setRootVarsForThemeOption = (themeOption: ThemeOption) => {
Object.entries(flattenNestedObject(juiceTheme(themeOption).colors)).forEach(
([key, value]) =>
document.documentElement.style.setProperty('--' + key, value),
)
Object.entries(juiceTheme(themeOption).radii).forEach(([key, value]) => {
if (!value) return
document.documentElement.style.setProperty(
'--radius-' + key,
value.toString(),
)
})
}
useEffect(
() => setRootVarsForThemeOption(initialThemeOption),
[initialThemeOption],
)
useEffect(
() => setIsDarkMode(currentThemeOption === ThemeOption.dark),
[currentThemeOption],
)
return {
themeOption: currentThemeOption,
theme: juiceTheme(currentThemeOption),
isDarkMode: isDarkMode,
forThemeOption: map => map[currentThemeOption],
setThemeOption: (themeOption: ThemeOption) => {
setRootVarsForThemeOption(themeOption)
setCurrentThemeOption(themeOption)
localStorage.setItem(storageKey, themeOption)
},
}
}