1 // storage.js is loaded in the `<head>` of all rustdoc pages and doesn't
2 // use `async` or `defer`. That means it blocks further parsing and rendering
3 // of the page: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script.
4 // This makes it the correct place to act on settings that affect the display of
5 // the page, so we don't see major layout changes during the load of the page.
8 const darkThemes
= ["dark", "ayu"];
9 window
.currentTheme
= document
.getElementById("themeStyle");
10 window
.mainTheme
= document
.getElementById("mainThemeStyle");
12 // WARNING: RUSTDOC_MOBILE_BREAKPOINT MEDIA QUERY
13 // If you update this line, then you also need to update the two media queries with the same
14 // warning in rustdoc.css
15 window
.RUSTDOC_MOBILE_BREAKPOINT
= 701;
17 const settingsDataset
= (function() {
18 const settingsElement
= document
.getElementById("default-settings");
19 if (settingsElement
=== null) {
22 const dataset
= settingsElement
.dataset
;
23 if (dataset
=== undefined) {
29 function getSettingValue(settingName
) {
30 const current
= getCurrentValue(settingName
);
31 if (current
!== null) {
34 if (settingsDataset
!== null) {
35 // See the comment for `default_settings.into_iter()` etc. in
36 // `Options::from_matches` in `librustdoc/config.rs`.
37 const def
= settingsDataset
[settingName
.replace(/-/g
,"_")];
38 if (def
!== undefined) {
45 const localStoredTheme
= getSettingValue("theme");
49 // eslint-disable-next-line no-unused-vars
50 function hasClass(elem
, className
) {
51 return elem
&& elem
.classList
&& elem
.classList
.contains(className
);
54 // eslint-disable-next-line no-unused-vars
55 function addClass(elem
, className
) {
56 if (!elem
|| !elem
.classList
) {
59 elem
.classList
.add(className
);
62 // eslint-disable-next-line no-unused-vars
63 function removeClass(elem
, className
) {
64 if (!elem
|| !elem
.classList
) {
67 elem
.classList
.remove(className
);
71 * Run a callback for every element of an Array.
72 * @param {Array<?>} arr - The array to iterate over
73 * @param {function(?)} func - The callback
74 * @param {boolean} [reversed] - Whether to iterate in reverse
76 function onEach(arr
, func
, reversed
) {
77 if (arr
&& arr
.length
> 0 && func
) {
79 const length
= arr
.length
;
80 for (let i
= length
- 1; i
>= 0; --i
) {
86 for (const elem
of arr
) {
97 * Turn an HTMLCollection or a NodeList into an Array, then run a callback
98 * for every element. This is useful because iterating over an HTMLCollection
99 * or a "live" NodeList while modifying it can be very slow.
100 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
101 * https://developer.mozilla.org/en-US/docs/Web/API/NodeList
102 * @param {NodeList<?>|HTMLCollection<?>} lazyArray - An array to iterate over
103 * @param {function(?)} func - The callback
104 * @param {boolean} [reversed] - Whether to iterate in reverse
106 function onEachLazy(lazyArray
, func
, reversed
) {
108 Array
.prototype.slice
.call(lazyArray
),
113 function updateLocalStorage(name
, value
) {
115 window
.localStorage
.setItem("rustdoc-" + name
, value
);
117 // localStorage is not accessible, do nothing
121 function getCurrentValue(name
) {
123 return window
.localStorage
.getItem("rustdoc-" + name
);
129 function switchTheme(styleElem
, mainStyleElem
, newTheme
, saveTheme
) {
130 const newHref
= mainStyleElem
.href
.replace(
131 /\/rustdoc([^/]*)\.css
/, "/" + newTheme + "$1" + ".css
");
133 // If this new value comes from a system setting or from the previously
134 // saved theme, no need to save it.
136 updateLocalStorage("theme
", newTheme);
139 if (styleElem.href === newHref) {
144 if (savedHref.length === 0) {
145 onEachLazy(document.getElementsByTagName("link
"), el => {
146 savedHref.push(el.href);
149 onEach(savedHref, el => {
150 if (el === newHref) {
156 styleElem.href = newHref;
160 // This function is called from "main
.js
".
161 // eslint-disable-next-line no-unused-vars
162 function useSystemTheme(value) {
163 if (value === undefined) {
167 updateLocalStorage("use-system
-theme
", value);
169 // update the toggle if we're on the settings page
170 const toggle = document.getElementById("use-system
-theme
");
171 if (toggle && toggle instanceof HTMLInputElement) {
172 toggle.checked = value;
176 const updateSystemTheme = (function() {
177 if (!window.matchMedia) {
178 // fallback to the CSS computed value
180 const cssTheme = getComputedStyle(document.documentElement)
181 .getPropertyValue("content
");
186 JSON.parse(cssTheme) || "light
",
192 // only listen to (prefers-color-scheme: dark) because light is the default
193 const mql = window.matchMedia("(prefers
-color
-scheme
: dark
)");
195 function handlePreferenceChange(mql) {
196 const use = theme => {
197 switchTheme(window.currentTheme, window.mainTheme, theme, true);
199 // maybe the user has disabled the setting in the meantime!
200 if (getSettingValue("use-system
-theme
") !== "false") {
201 const lightTheme = getSettingValue("preferred
-light
-theme
") || "light
";
202 const darkTheme = getSettingValue("preferred
-dark
-theme
") || "dark
";
207 // prefers a light theme, or has no preference
210 // note: we save the theme so that it doesn't suddenly change when
211 // the user disables "use-system
-theme
" and reloads the page or
212 // navigates to another page
214 use(getSettingValue("theme
"));
218 mql.addListener(handlePreferenceChange);
221 handlePreferenceChange(mql);
225 function switchToSavedTheme() {
229 getSettingValue("theme
") || "light
",
234 if (getSettingValue("use-system
-theme
") !== "false" && window.matchMedia) {
235 // update the preferred dark theme if the user is already using a dark theme
236 // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
237 if (getSettingValue("use-system
-theme
") === null
238 && getSettingValue("preferred
-dark
-theme
") === null
239 && darkThemes.indexOf(localStoredTheme) >= 0) {
240 updateLocalStorage("preferred
-dark
-theme
", localStoredTheme);
243 // call the function to initialize the theme at least once!
246 switchToSavedTheme();
249 if (getSettingValue("source
-sidebar
-show
") === "true") {
250 // At this point in page load, `document.body` is not available yet.
251 // Set a class on the `<html>` element instead.
252 addClass(document.documentElement, "source
-sidebar
-expanded
");
255 // If we navigate away (for example to a settings page), and then use the back or
256 // forward button to get back to a page, the theme may have changed in the meantime.
257 // But scripts may not be re-loaded in such a case due to the bfcache
258 // (https://web.dev/bfcache/). The "pageshow
" event triggers on such navigations.
259 // Use that opportunity to update the theme.
260 // We use a setTimeout with a 0 timeout here to put the change on the event queue.
261 // For some reason, if we try to change the theme while the `pageshow` event is
262 // running, it sometimes fails to take effect. The problem manifests on Chrome,
263 // specifically when talking to a remote website with no caching.
264 window.addEventListener("pageshow
", ev => {
266 setTimeout(switchToSavedTheme, 0);