Skip to content

Commit d4a6d64

Browse files
authored
perf: simplify mode toggle script (cotes2020#1692)
Reduce conditional logic to speed up theme mode initialization and switching.
1 parent 2cfa548 commit d4a6d64

File tree

1 file changed

+17
-46
lines changed

1 file changed

+17
-46
lines changed

_includes/mode-toggle.html

+17-46
Original file line numberDiff line numberDiff line change
@@ -19,56 +19,39 @@
1919
}
2020

2121
constructor() {
22-
if (this.hasMode) {
23-
if (this.isDarkMode) {
24-
if (!this.isSysDarkPrefer) {
25-
this.setDark();
26-
}
27-
} else {
28-
if (this.isSysDarkPrefer) {
29-
this.setLight();
30-
}
31-
}
32-
}
33-
3422
let self = this;
3523

3624
{%- comment -%} always follow the system prefers {%- endcomment -%}
3725
this.sysDarkPrefers.addEventListener('change', () => {
3826
if (self.hasMode) {
39-
if (self.isDarkMode) {
40-
if (!self.isSysDarkPrefer) {
41-
self.setDark();
42-
}
43-
} else {
44-
if (self.isSysDarkPrefer) {
45-
self.setLight();
46-
}
47-
}
48-
4927
self.clearMode();
5028
}
51-
5229
self.notify();
5330
});
54-
} {%- comment -%} constructor() {%- endcomment -%}
31+
32+
if (!this.hasMode) {
33+
return;
34+
}
35+
36+
if (this.isDarkMode) {
37+
this.setDark();
38+
} else {
39+
this.setLight();
40+
}
41+
}
5542

5643
get sysDarkPrefers() {
5744
return window.matchMedia('(prefers-color-scheme: dark)');
5845
}
5946

60-
get isSysDarkPrefer() {
47+
get isPreferDark() {
6148
return this.sysDarkPrefers.matches;
6249
}
6350

6451
get isDarkMode() {
6552
return this.mode === ModeToggle.DARK_MODE;
6653
}
6754

68-
get isLightMode() {
69-
return this.mode === ModeToggle.LIGHT_MODE;
70-
}
71-
7255
get hasMode() {
7356
return this.mode != null;
7457
}
@@ -79,10 +62,10 @@
7962

8063
{%- comment -%} get the current mode on screen {%- endcomment -%}
8164
get modeStatus() {
82-
if (this.isDarkMode || (!this.hasMode && this.isSysDarkPrefer)) {
83-
return ModeToggle.DARK_MODE;
65+
if (this.hasMode) {
66+
return this.mode;
8467
} else {
85-
return ModeToggle.LIGHT_MODE;
68+
return this.isPreferDark ? ModeToggle.DARK_MODE : ModeToggle.LIGHT_MODE;
8669
}
8770
}
8871

@@ -116,21 +99,9 @@
11699

117100
flipMode() {
118101
if (this.hasMode) {
119-
if (this.isSysDarkPrefer) {
120-
if (this.isLightMode) {
121-
this.clearMode();
122-
} else {
123-
this.setLight();
124-
}
125-
} else {
126-
if (this.isDarkMode) {
127-
this.clearMode();
128-
} else {
129-
this.setDark();
130-
}
131-
}
102+
this.clearMode();
132103
} else {
133-
if (this.isSysDarkPrefer) {
104+
if (this.isPreferDark) {
134105
this.setLight();
135106
} else {
136107
this.setDark();

0 commit comments

Comments
 (0)