From d4a6d640bd6d4ab185faf96c0255369a9903ee1d Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Sun, 21 Apr 2024 00:39:12 +0800 Subject: [PATCH] perf: simplify mode toggle script (#1692) Reduce conditional logic to speed up theme mode initialization and switching. --- _includes/mode-toggle.html | 63 ++++++++++---------------------------- 1 file changed, 17 insertions(+), 46 deletions(-) diff --git a/_includes/mode-toggle.html b/_includes/mode-toggle.html index ab202341978..113ec375467 100644 --- a/_includes/mode-toggle.html +++ b/_includes/mode-toggle.html @@ -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();