Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add system theme setting #1448

Merged
merged 1 commit into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
senekor marked this conversation as resolved.
Show resolved Hide resolved
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>
</ul>
Expand Down
Loading