Skip to content

Commit

Permalink
Merge pull request #1448 from rust-lang/senekor/kyxwqporuzux
Browse files Browse the repository at this point in the history
Add system theme setting
  • Loading branch information
senekor authored Dec 26, 2024
2 parents cfb4ce8 + e9d73d4 commit d23b993
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
29 changes: 22 additions & 7 deletions static/scripts/theme-switch.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
"use strict";

function changeThemeTo(val) {
document.documentElement.setAttribute("data-theme", val);
// save theme prefs in the browser
if (storageAvailable("localStorage")) {
localStorage.setItem("blog-rust-lang-org-theme", val);
if (val === "system") {
setThemeToSystemPref();
// delete explicit theme pref from browser storage
if (storageAvailable("localStorage")) {
localStorage.removeItem("blog-rust-lang-org-theme");
}
} else {
document.documentElement.setAttribute("data-theme", val);
// save theme prefs in the browser
if (storageAvailable("localStorage")) {
localStorage.setItem("blog-rust-lang-org-theme", val);
}
}
// the theme dropdown will close itself when returning to the dropdown() caller
}
Expand Down Expand Up @@ -44,6 +52,14 @@ function handleBlur(event) {
}
}

function setThemeToSystemPref() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.setAttribute("data-theme", "dark");
} else {
document.documentElement.setAttribute("data-theme", "light");
}
}

// close the theme dropdown if clicking somewhere else
document.querySelector('.theme-icon').onblur = handleBlur;

Expand All @@ -54,9 +70,8 @@ if (storageAvailable("localStorage")) {
}
if (savedTheme) {
document.documentElement.setAttribute("data-theme", savedTheme);
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.setAttribute("data-theme", "dark");
localStorage.setItem("blog-rust-lang-org-theme", "dark");
} else {
setThemeToSystemPref();
}

// show the theme selector only if JavaScript is enabled/available
Expand Down
1 change: 1 addition & 0 deletions templates/nav.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<ul id="theme-choice">
<li class="theme-item" onclick="changeThemeTo('light');">Light</li>
<li class="theme-item" onclick="changeThemeTo('dark');">Dark</li>
<li class="theme-item" onclick="changeThemeTo('system');">System</li>
</ul>
</button>
<script src="{{root}}scripts/theme-switch.js"></script>
Expand Down

0 comments on commit d23b993

Please sign in to comment.