web/_includes/mode-toggle.html

118 lines
2.7 KiB
HTML
Raw Normal View History

<!--
Switch the mode between dark and light.
v2.1
https://github.com/cotes2020/jekyll-theme-chirpy
© 2020 Cotes Chung
MIT License
-->
2020-04-21 16:22:49 +03:00
<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) {
2020-04-01 19:30:00 +03:00
if (!this.isSysDarkPrefer) {
2020-02-14 18:36:38 +03:00
this.setDark();
}
} else {
2020-04-01 19:30:00 +03:00
if (this.isSysDarkPrefer) {
2020-02-14 18:36:38 +03:00
this.setLight();
}
}
}
var self = this;
2020-02-14 18:36:38 +03:00
/* always follow the system prefers */
this.sysDarkPrefers.addListener(function() {
2020-02-14 18:36:38 +03:00
if (self.mode != null) {
if (self.mode == ModeToggle.DARK_MODE) {
2020-04-01 19:30:00 +03:00
if (!self.isSysDarkPrefer) {
2020-02-14 18:36:38 +03:00
self.setDark();
}
} else {
2020-04-01 19:30:00 +03:00
if (self.isSysDarkPrefer) {
2020-02-14 18:36:38 +03:00
self.setLight();
}
}
self.clearMode();
}
});
} /* constructor() */
2020-02-14 18:36:38 +03:00
setDark() {
$('html').attr(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
}
2020-02-14 18:36:38 +03:00
setLight() {
$('html').attr(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
}
2020-02-14 18:36:38 +03:00
clearMode() {
$('html').removeAttr(ModeToggle.MODE_KEY);
sessionStorage.removeItem(ModeToggle.MODE_KEY);
}
2020-04-01 19:30:00 +03:00
get sysDarkPrefers() { return window.matchMedia("(prefers-color-scheme: dark)"); }
2020-04-01 19:30:00 +03:00
get isSysDarkPrefer() { return this.sysDarkPrefers.matches; }
2020-04-01 19:30:00 +03:00
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() {
2020-04-01 19:30:00 +03:00
if (this.hasMode) {
if (this.isSysDarkPrefer) {
if (this.isLightkMode) {
this.clearMode();
} else {
this.setLight();
}
2020-02-14 18:36:38 +03:00
2020-04-01 19:30:00 +03:00
} else {
if (this.isDarkMode) {
this.clearMode();
} else {
this.setDark();
}
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
} else {
this.setDark();
}
}
2020-04-01 19:30:00 +03:00
} /* flipMode() */
} /* ModeToggle */
let toggle = new ModeToggle();
2020-02-14 18:36:38 +03:00
$(".mode-toggle").click(function() {
toggle.flipMode();
});
</script>