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