-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
43 lines (38 loc) · 1.19 KB
/
index.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
type DarkModeStateType = 'dark' | 'light'
type DarkModeSubscriberType = (mode: DarkModeStateType) => void
class DarkModeHandler {
isNode: boolean = false;
media?: MediaQueryList
state: DarkModeStateType = 'light'
subscribers: DarkModeSubscriberType[] = []
constructor() {
if (typeof window === 'undefined') {
this.isNode = true;
return;
}
this.media = window.matchMedia('(prefers-color-scheme: dark)')
this.media.addListener(this.handleUiChange)
this.handleUiChange(this.media)
}
public isDarkMode = () => {
if (this.isNode) return false;
return this.state === 'dark'
}
public subscribeToColorScheme = (method: DarkModeSubscriberType) => {
this.subscribers.push(method)
}
public clearSubscribers = () => {
this.subscribers = []
}
private handleUiChange = (e: MediaQueryList | MediaQueryListEvent) => {
this.state = e.matches ? 'dark' : 'light'
if (this.subscribers.length > 0) {
this.subscribers.forEach((subscriber: DarkModeSubscriberType) => {
subscriber(this.state)
})
}
}
}
const dm = new DarkModeHandler()
export default dm.isDarkMode
export const subscribeToColorScheme = dm.subscribeToColorScheme