perf: simplify mode toggle script (#1692)

Reduce conditional logic to speed up theme mode initialization and switching.
This commit is contained in:
Cotes Chung 2024-04-21 00:39:12 +08:00 committed by GitHub
parent 2cfa54847a
commit d4a6d640bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -19,45 +19,32 @@
}
constructor() {
if (this.hasMode) {
if (this.isDarkMode) {
if (!this.isSysDarkPrefer) {
this.setDark();
}
} else {
if (this.isSysDarkPrefer) {
this.setLight();
}
}
}
let self = this;
{%- comment -%} always follow the system prefers {%- endcomment -%}
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();
});
} {%- comment -%} constructor() {%- endcomment -%}
if (!this.hasMode) {
return;
}
if (this.isDarkMode) {
this.setDark();
} else {
this.setLight();
}
}
get sysDarkPrefers() {
return window.matchMedia('(prefers-color-scheme: dark)');
}
get isSysDarkPrefer() {
get isPreferDark() {
return this.sysDarkPrefers.matches;
}
@ -65,10 +52,6 @@
return this.mode === ModeToggle.DARK_MODE;
}
get isLightMode() {
return this.mode === ModeToggle.LIGHT_MODE;
}
get hasMode() {
return this.mode != null;
}
@ -79,10 +62,10 @@
{%- comment -%} get the current mode on screen {%- endcomment -%}
get modeStatus() {
if (this.isDarkMode || (!this.hasMode && this.isSysDarkPrefer)) {
return ModeToggle.DARK_MODE;
if (this.hasMode) {
return this.mode;
} else {
return ModeToggle.LIGHT_MODE;
return this.isPreferDark ? ModeToggle.DARK_MODE : ModeToggle.LIGHT_MODE;
}
}
@ -116,21 +99,9 @@
flipMode() {
if (this.hasMode) {
if (this.isSysDarkPrefer) {
if (this.isLightMode) {
this.clearMode();
} else {
this.setLight();
}
} else {
if (this.isDarkMode) {
this.clearMode();
} else {
this.setDark();
}
}
this.clearMode();
} else {
if (this.isSysDarkPrefer) {
if (this.isPreferDark) {
this.setLight();
} else {
this.setDark();