102 lines
No EOL
2.2 KiB
HTML
102 lines
No EOL
2.2 KiB
HTML
<!--
|
|
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" light-mode-invisible></i>
|
|
<i class="mode-toggle fas fa-moon" dark-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.isDarkPrefer) {
|
|
this.setDark();
|
|
}
|
|
} else {
|
|
if (this.isDarkPrefer) {
|
|
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.isDarkPrefer) {
|
|
self.setDark();
|
|
}
|
|
|
|
} else {
|
|
if (self.isDarkPrefer) {
|
|
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 isDarkPrefer() {
|
|
return this.sysDarkPrefers.matches;
|
|
}
|
|
|
|
get mode() {
|
|
return sessionStorage.getItem(ModeToggle.MODE_KEY);
|
|
}
|
|
|
|
flipMode() {
|
|
if ((this.mode == null && this.isDarkPrefer) ||
|
|
this.mode == ModeToggle.DARK_MODE) {
|
|
this.setLight();
|
|
|
|
} else { /* light mode or default-light */
|
|
this.setDark();
|
|
}
|
|
}
|
|
|
|
} /* ModeToggle */
|
|
|
|
let toggle = new ModeToggle();
|
|
|
|
$(".mode-toggle").click(function() {
|
|
toggle.flipMode();
|
|
});
|
|
|
|
</script> |