Add a setting to use the system theme
This commit is contained in:
parent
790d19cd25
commit
45f6762529
4 changed files with 233 additions and 37 deletions
|
@ -118,11 +118,71 @@ function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) {
|
|||
}
|
||||
}
|
||||
|
||||
function getSystemValue() {
|
||||
var property = getComputedStyle(document.documentElement).getPropertyValue('content');
|
||||
return property.replace(/[\"\']/g, "");
|
||||
function useSystemTheme(value) {
|
||||
if (value === undefined) {
|
||||
value = true;
|
||||
}
|
||||
|
||||
updateLocalStorage("rustdoc-use-system-theme", value);
|
||||
|
||||
// update the toggle if we're on the settings page
|
||||
var toggle = document.getElementById("use-system-theme");
|
||||
if (toggle && toggle instanceof HTMLInputElement) {
|
||||
toggle.checked = value;
|
||||
}
|
||||
}
|
||||
|
||||
switchTheme(currentTheme, mainTheme,
|
||||
getCurrentValue("rustdoc-theme") || getSystemValue() || "light",
|
||||
false);
|
||||
var updateSystemTheme = (function() {
|
||||
if (!window.matchMedia) {
|
||||
// fallback to the CSS computed value
|
||||
return function() {
|
||||
let cssTheme = getComputedStyle(document.documentElement)
|
||||
.getPropertyValue('content');
|
||||
|
||||
switchTheme(
|
||||
currentTheme,
|
||||
mainTheme,
|
||||
JSON.parse(cssTheme) || light,
|
||||
true
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
// only listen to (prefers-color-scheme: dark) because light is the default
|
||||
var mql = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
|
||||
function handlePreferenceChange(mql) {
|
||||
// maybe the user has disabled the setting in the meantime!
|
||||
if (getCurrentValue("rustdoc-use-system-theme") !== "false") {
|
||||
var lightTheme = getCurrentValue("rustdoc-preferred-light-theme") || "light";
|
||||
var darkTheme = getCurrentValue("rustdoc-preferred-dark-theme") || "dark";
|
||||
|
||||
if (mql.matches) {
|
||||
// prefers a dark theme
|
||||
switchTheme(currentTheme, mainTheme, darkTheme, true);
|
||||
} else {
|
||||
// prefers a light theme, or has no preference
|
||||
switchTheme(currentTheme, mainTheme, lightTheme, true);
|
||||
}
|
||||
|
||||
// note: we save the theme so that it doesn't suddenly change when
|
||||
// the user disables "use-system-theme" and reloads the page or
|
||||
// navigates to another page
|
||||
}
|
||||
}
|
||||
|
||||
mql.addListener(handlePreferenceChange);
|
||||
|
||||
return function() {
|
||||
handlePreferenceChange(mql);
|
||||
};
|
||||
})();
|
||||
|
||||
if (getCurrentValue("rustdoc-use-system-theme") !== "false" && window.matchMedia) {
|
||||
// call the function to initialize the theme at least once!
|
||||
updateSystemTheme();
|
||||
} else {
|
||||
switchTheme(currentTheme, mainTheme,
|
||||
getCurrentValue("rustdoc-theme") || "light",
|
||||
false);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue