]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/js/storage.js
Rollup merge of #98643 - voidc:valtree-ref-pretty, r=lcnr
[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 const settingsDataset = (function() {
13     const settingsElement = document.getElementById("default-settings");
14     if (settingsElement === null) {
15         return null;
16     }
17     const dataset = settingsElement.dataset;
18     if (dataset === undefined) {
19         return null;
20     }
21     return dataset;
22 })();
23
24 function getSettingValue(settingName) {
25     const current = getCurrentValue(settingName);
26     if (current !== null) {
27         return current;
28     }
29     if (settingsDataset !== null) {
30         // See the comment for `default_settings.into_iter()` etc. in
31         // `Options::from_matches` in `librustdoc/config.rs`.
32         const def = settingsDataset[settingName.replace(/-/g,"_")];
33         if (def !== undefined) {
34             return def;
35         }
36     }
37     return null;
38 }
39
40 const localStoredTheme = getSettingValue("theme");
41
42 const savedHref = [];
43
44 // eslint-disable-next-line no-unused-vars
45 function hasClass(elem, className) {
46     return elem && elem.classList && elem.classList.contains(className);
47 }
48
49 // eslint-disable-next-line no-unused-vars
50 function addClass(elem, className) {
51     if (!elem || !elem.classList) {
52         return;
53     }
54     elem.classList.add(className);
55 }
56
57 // eslint-disable-next-line no-unused-vars
58 function removeClass(elem, className) {
59     if (!elem || !elem.classList) {
60         return;
61     }
62     elem.classList.remove(className);
63 }
64
65 /**
66  * Run a callback for every element of an Array.
67  * @param {Array<?>}    arr        - The array to iterate over
68  * @param {function(?)} func       - The callback
69  * @param {boolean}     [reversed] - Whether to iterate in reverse
70  */
71 function onEach(arr, func, reversed) {
72     if (arr && arr.length > 0 && func) {
73         if (reversed) {
74             const length = arr.length;
75             for (let i = length - 1; i >= 0; --i) {
76                 if (func(arr[i])) {
77                     return true;
78                 }
79             }
80         } else {
81             for (const elem of arr) {
82                 if (func(elem)) {
83                     return true;
84                 }
85             }
86         }
87     }
88     return false;
89 }
90
91 /**
92  * Turn an HTMLCollection or a NodeList into an Array, then run a callback
93  * for every element. This is useful because iterating over an HTMLCollection
94  * or a "live" NodeList while modifying it can be very slow.
95  * https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
96  * https://developer.mozilla.org/en-US/docs/Web/API/NodeList
97  * @param {NodeList<?>|HTMLCollection<?>} lazyArray  - An array to iterate over
98  * @param {function(?)}                   func       - The callback
99  * @param {boolean}                       [reversed] - Whether to iterate in reverse
100  */
101 function onEachLazy(lazyArray, func, reversed) {
102     return onEach(
103         Array.prototype.slice.call(lazyArray),
104         func,
105         reversed);
106 }
107
108 function updateLocalStorage(name, value) {
109     try {
110         window.localStorage.setItem("rustdoc-" + name, value);
111     } catch (e) {
112         // localStorage is not accessible, do nothing
113     }
114 }
115
116 function getCurrentValue(name) {
117     try {
118         return window.localStorage.getItem("rustdoc-" + name);
119     } catch (e) {
120         return null;
121     }
122 }
123
124 function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) {
125     const newHref = mainStyleElem.href.replace(
126         /\/rustdoc([^/]*)\.css/, "/" + newTheme + "$1" + ".css");
127
128     // If this new value comes from a system setting or from the previously
129     // saved theme, no need to save it.
130     if (saveTheme) {
131         updateLocalStorage("theme", newTheme);
132     }
133
134     if (styleElem.href === newHref) {
135         return;
136     }
137
138     let found = false;
139     if (savedHref.length === 0) {
140         onEachLazy(document.getElementsByTagName("link"), el => {
141             savedHref.push(el.href);
142         });
143     }
144     onEach(savedHref, el => {
145         if (el === newHref) {
146             found = true;
147             return true;
148         }
149     });
150     if (found) {
151         styleElem.href = newHref;
152     }
153 }
154
155 // This function is called from "main.js".
156 // eslint-disable-next-line no-unused-vars
157 function useSystemTheme(value) {
158     if (value === undefined) {
159         value = true;
160     }
161
162     updateLocalStorage("use-system-theme", value);
163
164     // update the toggle if we're on the settings page
165     const toggle = document.getElementById("use-system-theme");
166     if (toggle && toggle instanceof HTMLInputElement) {
167         toggle.checked = value;
168     }
169 }
170
171 const updateSystemTheme = (function() {
172     if (!window.matchMedia) {
173         // fallback to the CSS computed value
174         return () => {
175             const cssTheme = getComputedStyle(document.documentElement)
176                 .getPropertyValue("content");
177
178             switchTheme(
179                 window.currentTheme,
180                 window.mainTheme,
181                 JSON.parse(cssTheme) || "light",
182                 true
183             );
184         };
185     }
186
187     // only listen to (prefers-color-scheme: dark) because light is the default
188     const mql = window.matchMedia("(prefers-color-scheme: dark)");
189
190     function handlePreferenceChange(mql) {
191         const use = theme => {
192             switchTheme(window.currentTheme, window.mainTheme, theme, true);
193         };
194         // maybe the user has disabled the setting in the meantime!
195         if (getSettingValue("use-system-theme") !== "false") {
196             const lightTheme = getSettingValue("preferred-light-theme") || "light";
197             const darkTheme = getSettingValue("preferred-dark-theme") || "dark";
198
199             if (mql.matches) {
200                 use(darkTheme);
201             } else {
202                 // prefers a light theme, or has no preference
203                 use(lightTheme);
204             }
205             // note: we save the theme so that it doesn't suddenly change when
206             // the user disables "use-system-theme" and reloads the page or
207             // navigates to another page
208         } else {
209             use(getSettingValue("theme"));
210         }
211     }
212
213     mql.addListener(handlePreferenceChange);
214
215     return () => {
216         handlePreferenceChange(mql);
217     };
218 })();
219
220 function switchToSavedTheme() {
221     switchTheme(
222         window.currentTheme,
223         window.mainTheme,
224         getSettingValue("theme") || "light",
225         false
226     );
227 }
228
229 if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
230     // update the preferred dark theme if the user is already using a dark theme
231     // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
232     if (getSettingValue("use-system-theme") === null
233         && getSettingValue("preferred-dark-theme") === null
234         && darkThemes.indexOf(localStoredTheme) >= 0) {
235         updateLocalStorage("preferred-dark-theme", localStoredTheme);
236     }
237
238     // call the function to initialize the theme at least once!
239     updateSystemTheme();
240 } else {
241     switchToSavedTheme();
242 }
243
244 if (getSettingValue("source-sidebar-show") === "true") {
245     // At this point in page load, `document.body` is not available yet.
246     // Set a class on the `<html>` element instead.
247     addClass(document.documentElement, "source-sidebar-expanded");
248 }
249
250 // If we navigate away (for example to a settings page), and then use the back or
251 // forward button to get back to a page, the theme may have changed in the meantime.
252 // But scripts may not be re-loaded in such a case due to the bfcache
253 // (https://web.dev/bfcache/). The "pageshow" event triggers on such navigations.
254 // Use that opportunity to update the theme.
255 // We use a setTimeout with a 0 timeout here to put the change on the event queue.
256 // For some reason, if we try to change the theme while the `pageshow` event is
257 // running, it sometimes fails to take effect. The problem manifests on Chrome,
258 // specifically when talking to a remote website with no caching.
259 window.addEventListener("pageshow", ev => {
260     if (ev.persisted) {
261         setTimeout(switchToSavedTheme, 0);
262     }
263 });