Improved theme mode switching logic.

This commit is contained in:
Cotes Chung 2020-04-02 00:30:00 +08:00
parent a9245494c9
commit ad992db75f

View file

@ -20,11 +20,11 @@
constructor() { constructor() {
if (this.mode != null) { if (this.mode != null) {
if (this.mode == ModeToggle.DARK_MODE) { if (this.mode == ModeToggle.DARK_MODE) {
if (!this.isDarkPrefer) { if (!this.isSysDarkPrefer) {
this.setDark(); this.setDark();
} }
} else { } else {
if (this.isDarkPrefer) { if (this.isSysDarkPrefer) {
this.setLight(); this.setLight();
} }
} }
@ -34,15 +34,14 @@
/* always follow the system prefers */ /* always follow the system prefers */
this.sysDarkPrefers.addListener(function() { this.sysDarkPrefers.addListener(function() {
if (self.mode != null) { if (self.mode != null) {
if (self.mode == ModeToggle.DARK_MODE) { if (self.mode == ModeToggle.DARK_MODE) {
if (!self.isDarkPrefer) { if (!self.isSysDarkPrefer) {
self.setDark(); self.setDark();
} }
} else { } else {
if (self.isDarkPrefer) { if (self.isSysDarkPrefer) {
self.setLight(); self.setLight();
} }
} }
@ -69,27 +68,44 @@
sessionStorage.removeItem(ModeToggle.MODE_KEY); sessionStorage.removeItem(ModeToggle.MODE_KEY);
} }
get sysDarkPrefers() { get sysDarkPrefers() { return window.matchMedia("(prefers-color-scheme: dark)"); }
return window.matchMedia("(prefers-color-scheme: dark)");
}
get isDarkPrefer() { get isSysDarkPrefer() { return this.sysDarkPrefers.matches; }
return this.sysDarkPrefers.matches;
}
get mode() { get isDarkMode() { return this.mode == ModeToggle.DARK_MODE; }
return sessionStorage.getItem(ModeToggle.MODE_KEY);
} get isLightkMode() { return this.mode == ModeToggle.LIGHT_MODE; }
get hasMode() { return this.mode != null; }
get mode() { return sessionStorage.getItem(ModeToggle.MODE_KEY); }
flipMode() { flipMode() {
if ((this.mode == null && this.isDarkPrefer) || if (this.hasMode) {
this.mode == ModeToggle.DARK_MODE) { if (this.isSysDarkPrefer) {
this.setLight(); if (this.isLightkMode) {
this.clearMode();
} else {
this.setLight();
}
} else { /* light mode or default-light */ } else {
this.setDark(); if (this.isDarkMode) {
this.clearMode();
} else {
this.setDark();
}
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
} else {
this.setDark();
}
} }
}
} /* flipMode() */
} /* ModeToggle */ } /* ModeToggle */