-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThemeController.ts
82 lines (68 loc) · 2.04 KB
/
ThemeController.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
73
74
75
76
77
78
79
80
81
82
import { ThemeList, } from './Interfaces'
export default class ThemeController {
Themes: ThemeList
CurrentTheme: string
updateThemeCallback: (x: string) => void
constructor(themeLists, updateThemeCallback = () => {},) {
this.Themes = themeLists
this.updateThemeCallback = updateThemeCallback
// Default theme
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)',).matches) {
this.CurrentTheme = 'dark'
} else {
this.CurrentTheme = 'light'
}
Object.keys(this.Themes[this.CurrentTheme],).forEach((el,) => {
document.documentElement.style.setProperty(`--${el}`, this.Themes[this.CurrentTheme][el],)
},)
}
doesThemeExist(theme,) {
return this.themeList.includes(theme,)
}
addNewTheme(theme,) {
const themeName = Object.keys(theme,)[0]
if (this.doesThemeExist(themeName,)) {
throw new Error(`Theme ${themeName} already exists`,)
}
this.Themes = { ...theme, ...this.Themes, }
}
deleteTheme(theme,) {
if (!this.doesThemeExist(theme,)) {
throw new Error(`Theme ${theme} does not exist`,)
}
delete this.Themes[theme]
}
updateTheme(theme,) {
const themeName = Object.keys(theme,)[0]
if (!this.doesThemeExist(themeName,)) {
throw new Error(`Theme ${themeName} does not exist`,)
}
this.Themes[themeName] = theme[themeName]
Object.keys(this.Themes[themeName],).forEach((el,) => {
document.documentElement.style.setProperty(`--${el}`, this.Themes[themeName][el],)
},)
this.theme = themeName
}
set theme(theme,) {
if (!this.doesThemeExist(theme,)) {
throw new Error(`Theme ${theme} does not exist`,)
}
Object.keys(this.Themes[theme],).forEach((el,) => {
document.documentElement.style.setProperty(`--${el}`, this.Themes[theme][el],)
},)
this.CurrentTheme = theme
this.updateThemeCallback(theme,)
// Create the event
const themeChange = new CustomEvent('themeChange', {
detail: { theme, },
},)
// Dispatch the event
document.dispatchEvent(themeChange,)
}
get theme() {
return this.CurrentTheme
}
get themeList() {
return Object.keys(this.Themes,)
}
}