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