Skip to content

Commit

Permalink
perf: simplify mode toggle script (cotes2020#1692)
Browse files Browse the repository at this point in the history
Reduce conditional logic to speed up theme mode initialization and switching.
  • Loading branch information
cotes2020 authored Apr 20, 2024
1 parent 2cfa548 commit d4a6d64
Showing 1 changed file with 17 additions and 46 deletions.
63 changes: 17 additions & 46 deletions _includes/mode-toggle.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,56 +19,39 @@
}

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;
}

get isDarkMode() {
return this.mode === ModeToggle.DARK_MODE;
}

get isLightMode() {
return this.mode === ModeToggle.LIGHT_MODE;
}

get hasMode() {
return this.mode != null;
}
Expand All @@ -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;
}
}

Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit d4a6d64

Please sign in to comment.