-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy paththeme.js
45 lines (39 loc) · 1.03 KB
/
theme.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
import { EventEmitter } from 'events'
class ThemeManager extends EventEmitter {
constructor() {
super()
this.theme = null
this.loadTheme()
window.addEventListener('storage', evt => {
if (evt.key === 'theme') {
this.loadTheme()
}
})
}
loadTheme() {
const oldTheme = this.theme
this.theme = window.localStorage.getItem('theme')
if (this.theme !== oldTheme) {
this.emit('themeChange', this.theme)
}
}
isDark() {
return this.theme
? this.theme === 'dark'
: window.matchMedia('(prefers-color-scheme: dark)').matches
}
setTheme(theme) {
if (this.theme !== theme) {
window.localStorage.setItem('theme', theme)
// Set so the server can know what layout to send so we don't get a "flash of white"
// experience
document.cookie = `theme=${theme}; expires=Fri, 31 Dec 9999 23:59:59 GMT`
this.theme = theme
this.emit('themeChange', this.theme)
}
}
getTheme() {
return this.theme
}
}
export default new ThemeManager()