]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/html/static/js/storage.js
New upstream version 1.68.2+dfsg1
[rustc.git] / src / librustdoc / html / static / js / storage.js
CommitLineData
923072b8
FG
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.
04454e1e
FG
6"use strict";
7
8const darkThemes = ["dark", "ayu"];
cdc7bbd5
XL
9window.currentTheme = document.getElementById("themeStyle");
10window.mainTheme = document.getElementById("mainThemeStyle");
2c00a5a8 11
064997fb 12// WARNING: RUSTDOC_MOBILE_BREAKPOINT MEDIA QUERY
2b03887a 13// If you update this line, then you also need to update the media query with the same
064997fb 14// warning in rustdoc.css
2b03887a 15window.RUSTDOC_MOBILE_BREAKPOINT = 700;
064997fb 16
923072b8 17const settingsDataset = (function() {
04454e1e 18 const settingsElement = document.getElementById("default-settings");
29967ef6
XL
19 if (settingsElement === null) {
20 return null;
21 }
04454e1e 22 const dataset = settingsElement.dataset;
29967ef6
XL
23 if (dataset === undefined) {
24 return null;
25 }
26 return dataset;
27})();
28
29function getSettingValue(settingName) {
04454e1e 30 const current = getCurrentValue(settingName);
29967ef6
XL
31 if (current !== null) {
32 return current;
33 }
34 if (settingsDataset !== null) {
136023e0
XL
35 // See the comment for `default_settings.into_iter()` etc. in
36 // `Options::from_matches` in `librustdoc/config.rs`.
04454e1e 37 const def = settingsDataset[settingName.replace(/-/g,"_")];
29967ef6
XL
38 if (def !== undefined) {
39 return def;
40 }
41 }
42 return null;
43}
44
04454e1e 45const localStoredTheme = getSettingValue("theme");
29967ef6 46
04454e1e 47const savedHref = [];
0531ce1d 48
5869c6ff 49// eslint-disable-next-line no-unused-vars
a1dfa0c6 50function hasClass(elem, className) {
0731742a 51 return elem && elem.classList && elem.classList.contains(className);
a1dfa0c6
XL
52}
53
5869c6ff 54// eslint-disable-next-line no-unused-vars
a1dfa0c6 55function addClass(elem, className) {
0731742a
XL
56 if (!elem || !elem.classList) {
57 return;
a1dfa0c6 58 }
0731742a 59 elem.classList.add(className);
a1dfa0c6
XL
60}
61
5869c6ff 62// eslint-disable-next-line no-unused-vars
a1dfa0c6 63function removeClass(elem, className) {
0731742a
XL
64 if (!elem || !elem.classList) {
65 return;
a1dfa0c6 66 }
0731742a 67 elem.classList.remove(className);
a1dfa0c6
XL
68}
69
a2a8927a
XL
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 */
a1dfa0c6 76function onEach(arr, func, reversed) {
0531ce1d 77 if (arr && arr.length > 0 && func) {
17df50a5 78 if (reversed) {
04454e1e
FG
79 const length = arr.length;
80 for (let i = length - 1; i >= 0; --i) {
17df50a5 81 if (func(arr[i])) {
a1dfa0c6
XL
82 return true;
83 }
84 }
85 } else {
04454e1e
FG
86 for (const elem of arr) {
87 if (func(elem)) {
a1dfa0c6
XL
88 return true;
89 }
0531ce1d
XL
90 }
91 }
92 }
83c7162d 93 return false;
0531ce1d
XL
94}
95
a2a8927a
XL
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 */
0731742a
XL
106function onEachLazy(lazyArray, func, reversed) {
107 return onEach(
108 Array.prototype.slice.call(lazyArray),
109 func,
110 reversed);
111}
112
2c00a5a8 113function updateLocalStorage(name, value) {
6a06907d 114 try {
5099ac24 115 window.localStorage.setItem("rustdoc-" + name, value);
923072b8 116 } catch (e) {
6a06907d 117 // localStorage is not accessible, do nothing
2c00a5a8
XL
118 }
119}
120
121function getCurrentValue(name) {
6a06907d 122 try {
5099ac24 123 return window.localStorage.getItem("rustdoc-" + name);
923072b8 124 } catch (e) {
6a06907d 125 return null;
2c00a5a8 126 }
2c00a5a8
XL
127}
128
487cf647 129function switchTheme(styleElem, mainStyleElem, newThemeName, saveTheme) {
29967ef6
XL
130 // If this new value comes from a system setting or from the previously
131 // saved theme, no need to save it.
17df50a5 132 if (saveTheme) {
487cf647 133 updateLocalStorage("theme", newThemeName);
0531ce1d
XL
134 }
135
0531ce1d 136 if (savedHref.length === 0) {
04454e1e 137 onEachLazy(document.getElementsByTagName("link"), el => {
0531ce1d
XL
138 savedHref.push(el.href);
139 });
140 }
487cf647
FG
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)) {
0531ce1d
XL
148 return true;
149 }
150 });
487cf647 151 if (newHref && newHref !== styleElem.href) {
0531ce1d 152 styleElem.href = newHref;
0531ce1d 153 }
2c00a5a8
XL
154}
155
cdc7bbd5 156// This function is called from "main.js".
5869c6ff 157// eslint-disable-next-line no-unused-vars
29967ef6
XL
158function useSystemTheme(value) {
159 if (value === undefined) {
160 value = true;
161 }
162
5099ac24 163 updateLocalStorage("use-system-theme", value);
29967ef6
XL
164
165 // update the toggle if we're on the settings page
04454e1e 166 const toggle = document.getElementById("use-system-theme");
29967ef6
XL
167 if (toggle && toggle instanceof HTMLInputElement) {
168 toggle.checked = value;
169 }
e1599b0c
XL
170}
171
923072b8 172const updateSystemTheme = (function() {
29967ef6
XL
173 if (!window.matchMedia) {
174 // fallback to the CSS computed value
04454e1e
FG
175 return () => {
176 const cssTheme = getComputedStyle(document.documentElement)
177 .getPropertyValue("content");
29967ef6
XL
178
179 switchTheme(
cdc7bbd5
XL
180 window.currentTheme,
181 window.mainTheme,
5869c6ff 182 JSON.parse(cssTheme) || "light",
29967ef6
XL
183 true
184 );
185 };
186 }
187
188 // only listen to (prefers-color-scheme: dark) because light is the default
04454e1e 189 const mql = window.matchMedia("(prefers-color-scheme: dark)");
29967ef6
XL
190
191 function handlePreferenceChange(mql) {
04454e1e 192 const use = theme => {
5099ac24
FG
193 switchTheme(window.currentTheme, window.mainTheme, theme, true);
194 };
29967ef6
XL
195 // maybe the user has disabled the setting in the meantime!
196 if (getSettingValue("use-system-theme") !== "false") {
04454e1e
FG
197 const lightTheme = getSettingValue("preferred-light-theme") || "light";
198 const darkTheme = getSettingValue("preferred-dark-theme") || "dark";
29967ef6
XL
199
200 if (mql.matches) {
5099ac24 201 use(darkTheme);
29967ef6
XL
202 } else {
203 // prefers a light theme, or has no preference
5099ac24 204 use(lightTheme);
29967ef6 205 }
29967ef6
XL
206 // note: we save the theme so that it doesn't suddenly change when
207 // the user disables "use-system-theme" and reloads the page or
208 // navigates to another page
5099ac24
FG
209 } else {
210 use(getSettingValue("theme"));
29967ef6
XL
211 }
212 }
213
214 mql.addListener(handlePreferenceChange);
215
04454e1e 216 return () => {
29967ef6
XL
217 handlePreferenceChange(mql);
218 };
219})();
220
5099ac24
FG
221function switchToSavedTheme() {
222 switchTheme(
223 window.currentTheme,
224 window.mainTheme,
225 getSettingValue("theme") || "light",
226 false
227 );
228}
229
29967ef6
XL
230if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
231 // update the preferred dark theme if the user is already using a dark theme
232 // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
233 if (getSettingValue("use-system-theme") === null
234 && getSettingValue("preferred-dark-theme") === null
235 && darkThemes.indexOf(localStoredTheme) >= 0) {
5099ac24 236 updateLocalStorage("preferred-dark-theme", localStoredTheme);
29967ef6
XL
237 }
238
239 // call the function to initialize the theme at least once!
240 updateSystemTheme();
241} else {
5099ac24 242 switchToSavedTheme();
29967ef6 243}
5099ac24 244
923072b8
FG
245if (getSettingValue("source-sidebar-show") === "true") {
246 // At this point in page load, `document.body` is not available yet.
247 // Set a class on the `<html>` element instead.
248 addClass(document.documentElement, "source-sidebar-expanded");
249}
250
5099ac24
FG
251// If we navigate away (for example to a settings page), and then use the back or
252// forward button to get back to a page, the theme may have changed in the meantime.
253// But scripts may not be re-loaded in such a case due to the bfcache
254// (https://web.dev/bfcache/). The "pageshow" event triggers on such navigations.
255// Use that opportunity to update the theme.
256// We use a setTimeout with a 0 timeout here to put the change on the event queue.
257// For some reason, if we try to change the theme while the `pageshow` event is
258// running, it sometimes fails to take effect. The problem manifests on Chrome,
259// specifically when talking to a remote website with no caching.
04454e1e 260window.addEventListener("pageshow", ev => {
5099ac24
FG
261 if (ev.persisted) {
262 setTimeout(switchToSavedTheme, 0);
263 }
264});