-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
color-mode.utils.ts
72 lines (63 loc) · 2.12 KB
/
color-mode.utils.ts
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
import { ColorMode } from "./color-mode-types"
const classNames = {
light: "chakra-ui-light",
dark: "chakra-ui-dark",
}
type UtilOptions = {
preventTransition?: boolean
}
export function getColorModeUtils(options: UtilOptions = {}) {
const { preventTransition = true } = options
const utils = {
setDataset: (value: ColorMode) => {
const cleanup = preventTransition ? utils.preventTransition() : undefined
document.documentElement.dataset.theme = value
document.documentElement.style.colorScheme = value
cleanup?.()
},
setClassName(dark: boolean) {
document.body.classList.add(dark ? classNames.dark : classNames.light)
document.body.classList.remove(dark ? classNames.light : classNames.dark)
},
query() {
return window.matchMedia("(prefers-color-scheme: dark)")
},
getSystemTheme(fallback?: ColorMode) {
const dark = utils.query().matches ?? fallback === "dark"
return dark ? "dark" : "light"
},
addListener(fn: (cm: ColorMode) => unknown) {
const mql = utils.query()
const listener = (e: MediaQueryListEvent) => {
fn(e.matches ? "dark" : "light")
}
if (typeof mql.addListener === "function") mql.addListener(listener)
else mql.addEventListener("change", listener)
return () => {
if (typeof mql.removeListener === "function")
mql.removeListener(listener)
else mql.removeEventListener("change", listener)
}
},
preventTransition() {
const css = document.createElement("style")
css.appendChild(
document.createTextNode(
`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`,
),
)
document.head.appendChild(css)
return () => {
// force a reflow
;(() => window.getComputedStyle(document.body))()
// wait for next tick
requestAnimationFrame(() => {
requestAnimationFrame(() => {
document.head.removeChild(css)
})
})
}
},
}
return utils
}