forked from cotes2020/jekyll-theme-chirpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mode-toggle.html
118 lines (90 loc) · 2.7 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
<!--
Switch the mode between dark and light.
v2.1
https://github.com/cotes2020/jekyll-theme-chirpy
© 2020 Cotes Chung
MIT License
-->
<i class="mode-toggle fas fa-sun" dark-mode-invisible></i>
<i class="mode-toggle fas fa-moon" light-mode-invisible></i>
<script type="text/javascript">
class ModeToggle {
static get MODE_KEY() { return "mode"; }
static get DARK_MODE() { return "dark"; }
static get LIGHT_MODE() { return "light"; }
constructor() {
if (this.mode != null) {
if (this.mode == ModeToggle.DARK_MODE) {
if (!this.isSysDarkPrefer) {
this.setDark();
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
}
}
}
var self = this;
/* always follow the system prefers */
this.sysDarkPrefers.addListener(function() {
if (self.mode != null) {
if (self.mode == ModeToggle.DARK_MODE) {
if (!self.isSysDarkPrefer) {
self.setDark();
}
} else {
if (self.isSysDarkPrefer) {
self.setLight();
}
}
self.clearMode();
}
});
} /* constructor() */
setDark() {
$('html').attr(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
}
setLight() {
$('html').attr(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
}
clearMode() {
$('html').removeAttr(ModeToggle.MODE_KEY);
sessionStorage.removeItem(ModeToggle.MODE_KEY);
}
get sysDarkPrefers() { return window.matchMedia("(prefers-color-scheme: dark)"); }
get isSysDarkPrefer() { return this.sysDarkPrefers.matches; }
get isDarkMode() { return this.mode == ModeToggle.DARK_MODE; }
get isLightkMode() { return this.mode == ModeToggle.LIGHT_MODE; }
get hasMode() { return this.mode != null; }
get mode() { return sessionStorage.getItem(ModeToggle.MODE_KEY); }
flipMode() {
if (this.hasMode) {
if (this.isSysDarkPrefer) {
if (this.isLightkMode) {
this.clearMode();
} else {
this.setLight();
}
} else {
if (this.isDarkMode) {
this.clearMode();
} else {
this.setDark();
}
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
} else {
this.setDark();
}
}
} /* flipMode() */
} /* ModeToggle */
let toggle = new ModeToggle();
$(".mode-toggle").click(function() {
toggle.flipMode();
});
</script>