-
Notifications
You must be signed in to change notification settings - Fork 0
/
mode-toggle.html
129 lines (101 loc) · 2.95 KB
/
mode-toggle.html
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<!--
Switch the mode between dark and light.
-->
<script type="text/javascript">
class ModeToggle {
static get MODE_KEY() { return "mode"; }
static get MODE_ATTR() { return "data-mode"; }
static get DARK_MODE() { return "dark"; }
static get LIGHT_MODE() { return "light"; }
static get ID() { return "mode-toggle"; }
constructor() {
if (this.hasMode) {
if (this.isDarkMode) {
if (!this.isSysDarkPrefer) {
this.setDark();
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
}
}
}
let self = this;
/* always follow the system prefers */
this.sysDarkPrefers.addEventListener("change", () => {
if (self.hasMode) {
if (self.isDarkMode) {
if (!self.isSysDarkPrefer) {
self.setDark();
}
} else {
if (self.isSysDarkPrefer) {
self.setLight();
}
}
self.clearMode();
}
self.notify();
});
} /* constructor() */
get sysDarkPrefers() { return window.matchMedia("(prefers-color-scheme: dark)"); }
get isSysDarkPrefer() { return this.sysDarkPrefers.matches; }
get isDarkMode() { return this.mode === ModeToggle.DARK_MODE; }
get isLightMode() { return this.mode === ModeToggle.LIGHT_MODE; }
get hasMode() { return this.mode != null; }
get mode() { return sessionStorage.getItem(ModeToggle.MODE_KEY); }
/* get the current mode on screen */
get modeStatus() {
if (this.isDarkMode
|| (!this.hasMode && this.isSysDarkPrefer)) {
return ModeToggle.DARK_MODE;
} else {
return ModeToggle.LIGHT_MODE;
}
}
setDark() {
$('html').attr(ModeToggle.MODE_ATTR, ModeToggle.DARK_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
}
setLight() {
$('html').attr(ModeToggle.MODE_ATTR, ModeToggle.LIGHT_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
}
clearMode() {
$('html').removeAttr(ModeToggle.MODE_ATTR);
sessionStorage.removeItem(ModeToggle.MODE_KEY);
}
/* Notify another plugins that the theme mode has changed */
notify() {
window.postMessage({
direction: ModeToggle.ID,
message: this.modeStatus
}, "*");
}
} /* ModeToggle */
const toggle = new ModeToggle();
function flipMode() {
if (toggle.hasMode) {
if (toggle.isSysDarkPrefer) {
if (toggle.isLightMode) {
toggle.clearMode();
} else {
toggle.setLight();
}
} else {
if (toggle.isDarkMode) {
toggle.clearMode();
} else {
toggle.setDark();
}
}
} else {
if (toggle.isSysDarkPrefer) {
toggle.setLight();
} else {
toggle.setDark();
}
}
toggle.notify();
} /* flipMode() */
</script>