Skip to content

Commit 2b8d235

Browse files
committed
infer dark theme preference from user's system
1 parent de27779 commit 2b8d235

File tree

1 file changed

+17
-2
lines changed
  • scaladoc/resources/dotty_res/scripts

1 file changed

+17
-2
lines changed

scaladoc/resources/dotty_res/scripts/theme.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,24 @@
99
}
1010
})();
1111

12+
const settingKey = "use-dark-theme";
13+
1214
function toggleDarkTheme(isDark) {
1315
currentlyDark = isDark
1416
// this triggers the `:root.theme-dark` rule from scalastyle.css,
1517
// which changes the values of a bunch of CSS color variables
1618
document.documentElement.classList.toggle("theme-dark", isDark);
17-
supportsLocalStorage && localStorage.setItem("use-dark-theme", isDark);
19+
supportsLocalStorage && localStorage.setItem(settingKey, isDark);
1820
}
1921

22+
/* Infer a dark/light theme preference from the user's system */
23+
const colorSchemePrefMql = window.matchMedia("(prefers-color-scheme: dark)");
24+
2025
/* This needs to happen ASAP so we don't get a FOUC of bright colors before the dark theme is applied */
21-
const initiallyDark = supportsLocalStorage && (localStorage.getItem("use-dark-theme") === "true");
26+
const initiallyDark = (() => {
27+
const storedSetting = supportsLocalStorage && localStorage.getItem(settingKey);
28+
return (storedSetting === null) ? colorSchemePrefMql.matches : storedSetting === "true";
29+
})();
2230
let currentlyDark = initiallyDark;
2331
toggleDarkTheme(initiallyDark);
2432

@@ -29,5 +37,12 @@
2937
themeToggler.addEventListener("change", e => {
3038
toggleDarkTheme(!e.target.checked);
3139
});
40+
41+
/* Auto-swap the dark/light theme if the user changes it in their system */
42+
colorSchemePrefMql.addEventListener('change', e => {
43+
const preferDark = e.matches
44+
themeToggler.checked = !preferDark
45+
toggleDarkTheme(preferDark)
46+
})
3247
});
3348
})();

0 commit comments

Comments
 (0)