]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/js/storage.js
Auto merge of #107443 - cjgillot:generator-less-query, r=compiler-errors
[rust.git] / src / librustdoc / html / static / js / storage.js
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.
6 "use strict";
7
8 const darkThemes = ["dark", "ayu"];
9 window.currentTheme = document.getElementById("themeStyle");
10 window.mainTheme = document.getElementById("mainThemeStyle");
11
12 // WARNING: RUSTDOC_MOBILE_BREAKPOINT MEDIA QUERY
13 // If you update this line, then you also need to update the media query with the same
14 // warning in rustdoc.css
15 window.RUSTDOC_MOBILE_BREAKPOINT = 700;
16
17 const settingsDataset = (function() {
18     const settingsElement = document.getElementById("default-settings");
19     if (settingsElement === null) {
20         return null;
21     }
22     const dataset = settingsElement.dataset;
23     if (dataset === undefined) {
24         return null;
25     }
26     return dataset;
27 })();
28
29 function getSettingValue(settingName) {
30     const current = getCurrentValue(settingName);
31     if (current !== null) {
32         return current;
33     }
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) {
39             return def;
40         }
41     }
42     return null;
43 }
44
45 const localStoredTheme = getSettingValue("theme");
46
47 const savedHref = [];
48
49 // eslint-disable-next-line no-unused-vars
50 function hasClass(elem, className) {
51     return elem && elem.classList && elem.classList.contains(className);
52 }
53
54 // eslint-disable-next-line no-unused-vars
55 function addClass(elem, className) {
56     if (!elem || !elem.classList) {
57         return;
58     }
59     elem.classList.add(className);
60 }
61
62 // eslint-disable-next-line no-unused-vars
63 function removeClass(elem, className) {
64     if (!elem || !elem.classList) {
65         return;
66     }
67     elem.classList.remove(className);
68 }
69
70 /**
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
75  */
76 function onEach(arr, func, reversed) {
77     if (arr && arr.length > 0 && func) {
78         if (reversed) {
79             const length = arr.length;
80             for (let i = length - 1; i >= 0; --i) {
81                 if (func(arr[i])) {
82                     return true;
83                 }
84             }
85         } else {
86             for (const elem of arr) {
87                 if (func(elem)) {
88                     return true;
89                 }
90             }
91         }
92     }
93     return false;
94 }
95
96 /**
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
105  */
106 function onEachLazy(lazyArray, func, reversed) {
107     return onEach(
108         Array.prototype.slice.call(lazyArray),
109         func,
110         reversed);
111 }
112
113 function updateLocalStorage(name, value) {
114     try {
115         window.localStorage.setItem("rustdoc-" + name, value);
116     } catch (e) {
117         // localStorage is not accessible, do nothing
118     }
119 }
120
121 function getCurrentValue(name) {
122     try {
123         return window.localStorage.getItem("rustdoc-" + name);
124     } catch (e) {
125         return null;
126     }
127 }
128
129 function switchTheme(styleElem, mainStyleElem, newThemeName, saveTheme) {
130     // If this new value comes from a system setting or from the previously
131     // saved theme, no need to save it.
132     if (saveTheme) {
133         updateLocalStorage("theme", newThemeName);
134     }
135
136     if (savedHref.length === 0) {
137         onEachLazy(document.getElementsByTagName("link"), el => {
138             savedHref.push(el.href);
139         });
140     }
141     const newHref = savedHref.find(url => {
142         const m = url.match(/static\.files\/(.*)-[a-f0-9]{16}\.css$/);
143         if (m && m[1] === newThemeName) {
144             return true;
145         }
146         const m2 = url.match(/\/([^/]*)\.css$/);
147         if (m2 && m2[1].startsWith(newThemeName)) {
148             return true;
149         }
150     });
151     if (newHref && newHref !== styleElem.href) {
152         styleElem.href = newHref;
153     }
154 }
155
156 const updateTheme = (function() {
157     /**
158      * Update the current theme to match whatever the current combination of
159      * * the preference for using the system theme
160      *   (if this is the case, the value of preferred-light-theme, if the
161      *   system theme is light, otherwise if dark, the value of
162      *   preferred-dark-theme.)
163      * * the preferred theme
164      * … dictates that it should be.
165      */
166     function updateTheme() {
167         const use = (theme, saveTheme) => {
168             switchTheme(window.currentTheme, window.mainTheme, theme, saveTheme);
169         };
170
171         // maybe the user has disabled the setting in the meantime!
172         if (getSettingValue("use-system-theme") !== "false") {
173             const lightTheme = getSettingValue("preferred-light-theme") || "light";
174             const darkTheme = getSettingValue("preferred-dark-theme") || "dark";
175
176             if (isDarkMode()) {
177                 use(darkTheme, true);
178             } else {
179                 // prefers a light theme, or has no preference
180                 use(lightTheme, true);
181             }
182             // note: we save the theme so that it doesn't suddenly change when
183             // the user disables "use-system-theme" and reloads the page or
184             // navigates to another page
185         } else {
186             use(getSettingValue("theme"), false);
187         }
188     }
189
190     // This is always updated below to a function () => bool.
191     let isDarkMode;
192
193     // Determine the function for isDarkMode, and if we have
194     // `window.matchMedia`, set up an event listener on the preferred color
195     // scheme.
196     //
197     // Otherwise, fall back to the prefers-color-scheme value CSS captured in
198     // the "content" property.
199     if (window.matchMedia) {
200         // only listen to (prefers-color-scheme: dark) because light is the default
201         const mql = window.matchMedia("(prefers-color-scheme: dark)");
202
203         isDarkMode = () => mql.matches;
204
205         if (mql.addEventListener) {
206             mql.addEventListener("change", updateTheme);
207         } else {
208             // This is deprecated, see:
209             // https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener
210             mql.addListener(updateTheme);
211         }
212     } else {
213         // fallback to the CSS computed value
214         const cssContent = getComputedStyle(document.documentElement)
215             .getPropertyValue("content");
216         // (Note: the double-quotes come from that this is a CSS value, which
217         // might be a length, string, etc.)
218         const cssColorScheme = cssContent || "\"light\"";
219         isDarkMode = () => (cssColorScheme === "\"dark\"");
220     }
221
222     return updateTheme;
223 })();
224
225 if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
226     // update the preferred dark theme if the user is already using a dark theme
227     // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
228     if (getSettingValue("use-system-theme") === null
229         && getSettingValue("preferred-dark-theme") === null
230         && darkThemes.indexOf(localStoredTheme) >= 0) {
231         updateLocalStorage("preferred-dark-theme", localStoredTheme);
232     }
233 }
234
235 updateTheme();
236
237 if (getSettingValue("source-sidebar-show") === "true") {
238     // At this point in page load, `document.body` is not available yet.
239     // Set a class on the `<html>` element instead.
240     addClass(document.documentElement, "source-sidebar-expanded");
241 }
242
243 // If we navigate away (for example to a settings page), and then use the back or
244 // forward button to get back to a page, the theme may have changed in the meantime.
245 // But scripts may not be re-loaded in such a case due to the bfcache
246 // (https://web.dev/bfcache/). The "pageshow" event triggers on such navigations.
247 // Use that opportunity to update the theme.
248 // We use a setTimeout with a 0 timeout here to put the change on the event queue.
249 // For some reason, if we try to change the theme while the `pageshow` event is
250 // running, it sometimes fails to take effect. The problem manifests on Chrome,
251 // specifically when talking to a remote website with no caching.
252 window.addEventListener("pageshow", ev => {
253     if (ev.persisted) {
254         setTimeout(updateTheme, 0);
255     }
256 });