Skip to content

Commit d23b993

Browse files
authored
Merge pull request #1448 from rust-lang/senekor/kyxwqporuzux
Add system theme setting
2 parents cfb4ce8 + e9d73d4 commit d23b993

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

static/scripts/theme-switch.js

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
"use strict";
22

33
function changeThemeTo(val) {
4-
document.documentElement.setAttribute("data-theme", val);
5-
// save theme prefs in the browser
6-
if (storageAvailable("localStorage")) {
7-
localStorage.setItem("blog-rust-lang-org-theme", val);
4+
if (val === "system") {
5+
setThemeToSystemPref();
6+
// delete explicit theme pref from browser storage
7+
if (storageAvailable("localStorage")) {
8+
localStorage.removeItem("blog-rust-lang-org-theme");
9+
}
10+
} else {
11+
document.documentElement.setAttribute("data-theme", val);
12+
// save theme prefs in the browser
13+
if (storageAvailable("localStorage")) {
14+
localStorage.setItem("blog-rust-lang-org-theme", val);
15+
}
816
}
917
// the theme dropdown will close itself when returning to the dropdown() caller
1018
}
@@ -44,6 +52,14 @@ function handleBlur(event) {
4452
}
4553
}
4654

55+
function setThemeToSystemPref() {
56+
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
57+
document.documentElement.setAttribute("data-theme", "dark");
58+
} else {
59+
document.documentElement.setAttribute("data-theme", "light");
60+
}
61+
}
62+
4763
// close the theme dropdown if clicking somewhere else
4864
document.querySelector('.theme-icon').onblur = handleBlur;
4965

@@ -54,9 +70,8 @@ if (storageAvailable("localStorage")) {
5470
}
5571
if (savedTheme) {
5672
document.documentElement.setAttribute("data-theme", savedTheme);
57-
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
58-
document.documentElement.setAttribute("data-theme", "dark");
59-
localStorage.setItem("blog-rust-lang-org-theme", "dark");
73+
} else {
74+
setThemeToSystemPref();
6075
}
6176

6277
// show the theme selector only if JavaScript is enabled/available

templates/nav.hbs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
<ul id="theme-choice">
1818
<li class="theme-item" onclick="changeThemeTo('light');">Light</li>
1919
<li class="theme-item" onclick="changeThemeTo('dark');">Dark</li>
20+
<li class="theme-item" onclick="changeThemeTo('system');">System</li>
2021
</ul>
2122
</button>
2223
<script src="{{root}}scripts/theme-switch.js"></script>

0 commit comments

Comments
 (0)