Skip to content

Commit a6e75f7

Browse files
committed
ENH: Set default theme based on browser preference
1 parent 23d3425 commit a6e75f7

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

toggle.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
// Replicated from https://github.com/quarto-dev/quarto-cli/blob/84d4659/src/resources/formats/html/templates/quarto-html.ejs
55
const getColorSchemeSentinel = () => {
6-
const localAlternateSentinel = 'alternate';
6+
const localAlternateSentinel = 'default';
77
if (window.location.protocol !== 'file:') {
88
const storageValue = window.localStorage.getItem('quarto-color-scheme');
99
return storageValue != null ? storageValue : localAlternateSentinel;
@@ -26,8 +26,23 @@ const toggleColorSchemeElements = () => {
2626
}
2727
};
2828

29-
// Add event listener for when the readyState is complete (and default toggler is set)
29+
// Function to check if the user's browser prefers dark themes
30+
const prefersDarkTheme = () => {
31+
if (window.matchMedia) {
32+
return window.matchMedia('(prefers-color-scheme: dark)').matches;
33+
}
34+
return false;
35+
};
36+
3037
document.addEventListener('readystatechange', function() {
38+
// Set the default color scheme based on browser preference
39+
if (document.readyState === 'interactive' && window.location.protocol !== 'file:') {
40+
const storageValue = window.localStorage.getItem('quarto-color-scheme');
41+
if (storageValue == null && prefersDarkTheme()) {
42+
window.localStorage.setItem('quarto-color-scheme', 'alternate');
43+
}
44+
}
45+
// Add event listener for when the readyState is complete (and default toggler is set)
3146
if (document.readyState === 'complete') {
3247
// Toggle scheme once
3348
toggleColorSchemeElements();
@@ -39,4 +54,5 @@ document.addEventListener('readystatechange', function() {
3954
}
4055
}
4156
});
57+
4258
</script>

0 commit comments

Comments
 (0)