-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy paththeme-control.js
More file actions
65 lines (53 loc) · 1.89 KB
/
Copy paththeme-control.js
File metadata and controls
65 lines (53 loc) · 1.89 KB
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
const darkThemeCSSTagId = 'dark-theme-css';
export default class ThemeControl {
constructor(darkThemeCssFilePath) {
this.darkThemeCssFilePath = darkThemeCssFilePath;
}
initialize = () => {
this.isDarkMode = false; // true: dark mode; false: light mode
if (window.matchMedia) {
const darkThemeMq = window.matchMedia('(prefers-color-scheme: dark)');
this.isDarkMode = darkThemeMq.matches;
// Toggle theme upon theme change
darkThemeMq.addEventListener("change", e => {
this.#setThemeTo(e.matches)
});
}
this.#setThemeTo(this.isDarkMode);
return this.isDarkMode;
}
toggleTheme = () => this.#setThemeTo(!this.isDarkMode); // Flip the result;
#addDarkModeStyleSheet = () => {
// Already added.
const darkThemeCssTag = document.getElementById(darkThemeCSSTagId);
if (!!darkThemeCssTag) {
console.log(`dark theme css with id ${darkThemeCSSTagId} already exists`);
return;
}
const head = document.getElementsByTagName('head')[0];
// Creating link element
const style = document.createElement('link')
style.href = this.darkThemeCssFilePath;
style.type = 'text/css';
style.rel = 'stylesheet';
style.id = darkThemeCSSTagId;
head.append(style);
};
#removeDarkThemeStyleSheet() {
const darkThemeCssTag = document.getElementById(darkThemeCSSTagId);
if (!!darkThemeCssTag) {
console.log('dark theme css exists');
darkThemeCssTag.remove();
}
}
#setThemeTo = (isDarkMode) => {
if (isDarkMode) {
this.#addDarkModeStyleSheet();
}
else {
this.#removeDarkThemeStyleSheet();
}
this.isDarkMode = isDarkMode;
return this.isDarkMode;
}
}