Remove event listeners when no longer needed to prevent memory leaks
mql.addEventListener("change", updateTheme);
1// storage.js is loaded in the `<head>` of all rustdoc pages and doesn't2// use `async` or `defer`. That means it blocks further parsing and rendering3// 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 of5// the page, so we don't see major layout changes during the load of the page.6"use strict";78/**9 * @import * as rustdoc from "./rustdoc.d.ts";10 * @import * as stringdex from "./stringdex.d.ts";11 */1213const builtinThemes = ["light", "dark", "ayu"];14const darkThemes = ["dark", "ayu"];15window.currentTheme = (function() {16 const currentTheme = document.getElementById("themeStyle");17 return currentTheme instanceof HTMLLinkElement ? currentTheme : null;18})();1920const settingsDataset = (function() {21 const settingsElement = document.getElementById("default-settings");22 return settingsElement && settingsElement.dataset ? settingsElement.dataset : null;23})();2425/**26 * Assert that the passed value is nonnull, then return it.27 *28 * Takes an optional error message argument.29 *30 * Must be defined in this file, as it is loaded before all others.31 *32 * @template T33 * @param {T|null} x34 * @param {string=} msg35 * @returns T36 */37// used in other files, not yet used in this one.38// eslint-disable-next-line no-unused-vars39function nonnull(x, msg) {40 if (x === null) {41 throw (msg || "unexpected null value!");42 } else {43 return x;44 }45}4647/**48 * Assert that the passed value is not undefined, then return it.49 *50 * Takes an optional error message argument.51 *52 * Must be defined in this file, as it is loaded before all others.53 *54 * @template T55 * @param {T|undefined} x56 * @param {string=} msg57 * @returns T58 */59// used in other files, not yet used in this one.60// eslint-disable-next-line no-unused-vars61function nonundef(x, msg) {62 if (x === undefined) {63 throw (msg || "unexpected null value!");64 } else {65 return x;66 }67}6869/**70 * Get a configuration value. If it's not set, get the default.71 *72 * @param {string} settingName73 * @returns74 */75function getSettingValue(settingName) {76 const current = getCurrentValue(settingName);77 if (current === null && settingsDataset !== null) {78 // See the comment for `default_settings.into_iter()` etc. in79 // `Options::from_matches` in `librustdoc/config.rs`.80 const def = settingsDataset[settingName.replace(/-/g,"_")];81 if (def !== undefined) {82 return def;83 }84 }85 return current;86}8788const localStoredTheme = getSettingValue("theme");8990/**91 * Check if a DOM Element has the given class set.92 * If `elem` is null, returns false.93 *94 * @param {HTMLElement|null} elem95 * @param {string} className96 * @returns {boolean}97 */98// eslint-disable-next-line no-unused-vars99function hasClass(elem, className) {100 return !!elem && !!elem.classList && elem.classList.contains(className);101}102103/**104 * Add a class to a DOM Element. If `elem` is null,105 * does nothing. This function is idempotent.106 *107 * @param {Element|null} elem108 * @param {string} className109 */110function addClass(elem, className) {111 if (elem && elem.classList) {112 elem.classList.add(className);113 }114}115116/**117 * Remove a class from a DOM Element. If `elem` is null,118 * does nothing. This function is idempotent.119 *120 * @param {Element|null|undefined} elem121 * @param {string} className122 */123// eslint-disable-next-line no-unused-vars124function removeClass(elem, className) {125 if (elem && elem.classList) {126 elem.classList.remove(className);127 }128}129130/**131 * Run a callback for every element of an Array.132 * @param {Array<?>} arr - The array to iterate over133 * @param {function(?): boolean|void} func - The callback134 */135function onEach(arr, func) {136 for (const elem of arr) {137 if (func(elem)) {138 return true;139 }140 }141 return false;142}143144/**145 * Turn an HTMLCollection or a NodeList into an Array, then run a callback146 * for every element. This is useful because iterating over an HTMLCollection147 * or a "live" NodeList while modifying it can be very slow.148 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection149 * https://developer.mozilla.org/en-US/docs/Web/API/NodeList150 * @param {NodeList|HTMLCollection} lazyArray - An array to iterate over151 * @param {function(?): boolean|void} func - The callback152 */153// eslint-disable-next-line no-unused-vars154function onEachLazy(lazyArray, func) {155 return onEach(156 Array.prototype.slice.call(lazyArray),157 func);158}159160/**161 * Set a configuration value. This uses localstorage,162 * with a `rustdoc-` prefix, to avoid clashing with other163 * web apps that may be running in the same domain (for example, mdBook).164 * If localStorage is disabled, this function does nothing.165 *166 * @param {string} name167 * @param {string|null} value168 */169function updateLocalStorage(name, value) {170 try {171 if (value === null) {172 window.localStorage.removeItem("rustdoc-" + name);173 } else {174 window.localStorage.setItem("rustdoc-" + name, value);175 }176 } catch {177 // localStorage is not accessible, do nothing178 }179}180181/**182 * Get a configuration value. If localStorage is disabled,183 * this function returns null. If the setting was never184 * changed by the user, it also returns null; if you want to185 * be able to use a default value, call `getSettingValue` instead.186 *187 * @param {string} name188 * @returns {string|null}189 */190function getCurrentValue(name) {191 try {192 return window.localStorage.getItem("rustdoc-" + name);193 } catch {194 return null;195 }196}197198/**199 * Get a value from the rustdoc-vars div, which is used to convey data from200 * Rust to the JS. If there is no such element, return null.201 *202 * @param {rustdoc.VarName} name203 * @returns {string}204 */205function getVar(name) {206 const el = document.querySelector("head > meta[name='rustdoc-vars']");207 const v = el ? el.getAttribute("data-" + name) : null;208 if (v !== null) {209 return v;210 }211 throw `rustdoc var "${name}" is missing`;212}213214/**215 * Change the current theme.216 * @param {string|null} newThemeName217 * @param {boolean} saveTheme218 */219function switchTheme(newThemeName, saveTheme) {220 const themeNames = (getVar("themes") || "").split(",").filter(t => t);221 themeNames.push(...builtinThemes);222223 // Ensure that the new theme name is among the defined themes224 if (newThemeName === null || themeNames.indexOf(newThemeName) === -1) {225 return;226 }227228 // If this new value comes from a system setting or from the previously229 // saved theme, no need to save it.230 if (saveTheme) {231 updateLocalStorage("theme", newThemeName);232 }233234 document.documentElement.setAttribute("data-theme", newThemeName);235236 if (builtinThemes.indexOf(newThemeName) !== -1) {237 if (window.currentTheme && window.currentTheme.parentNode) {238 window.currentTheme.parentNode.removeChild(window.currentTheme);239 window.currentTheme = null;240 }241 } else {242 const newHref = getVar("root-path") + encodeURIComponent(newThemeName) +243 getVar("resource-suffix") + ".css";244 if (!window.currentTheme) {245 // If we're in the middle of loading, document.write blocks246 // rendering, but if we are done, it would blank the page.247 if (document.readyState === "loading") {248 document.write(`<link rel="stylesheet" id="themeStyle" href="${newHref}">`);249 window.currentTheme = (function() {250 const currentTheme = document.getElementById("themeStyle");251 return currentTheme instanceof HTMLLinkElement ? currentTheme : null;252 })();253 } else {254 window.currentTheme = document.createElement("link");255 window.currentTheme.rel = "stylesheet";256 window.currentTheme.id = "themeStyle";257 window.currentTheme.href = newHref;258 document.documentElement.appendChild(window.currentTheme);259 }260 } else if (newHref !== window.currentTheme.href) {261 window.currentTheme.href = newHref;262 }263 }264}265266const updateTheme = (function() {267 // only listen to (prefers-color-scheme: dark) because light is the default268 const mql = window.matchMedia("(prefers-color-scheme: dark)");269270 /**271 * Update the current theme to match whatever the current combination of272 * * the preference for using the system theme273 * (if this is the case, the value of preferred-light-theme, if the274 * system theme is light, otherwise if dark, the value of275 * preferred-dark-theme.)276 * * the preferred theme277 * … dictates that it should be.278 */279 function updateTheme() {280 // maybe the user has disabled the setting in the meantime!281 if (getSettingValue("use-system-theme") !== "false") {282 const lightTheme = getSettingValue("preferred-light-theme") || "light";283 const darkTheme = getSettingValue("preferred-dark-theme") || "dark";284 updateLocalStorage("use-system-theme", "true");285286 // use light theme if user prefers it, or has no preference287 switchTheme(mql.matches ? darkTheme : lightTheme, true);288 // note: we save the theme so that it doesn't suddenly change when289 // the user disables "use-system-theme" and reloads the page or290 // navigates to another page291 } else {292 switchTheme(getSettingValue("theme"), false);293 }294 }295296 mql.addEventListener("change", updateTheme);297298 return updateTheme;299})();300301// typescript thinks we're forgetting to call window.matchMedia,302// but we're checking browser support of media queries.303// @ts-ignore304if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {305 // update the preferred dark theme if the user is already using a dark theme306 // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732307 if (getSettingValue("use-system-theme") === null308 && getSettingValue("preferred-dark-theme") === null309 && localStoredTheme !== null310 && darkThemes.indexOf(localStoredTheme) >= 0) {311 updateLocalStorage("preferred-dark-theme", localStoredTheme);312 }313}314315updateTheme();316317// Hide, show, and resize the sidebar at page load time318//319// This needs to be done here because this JS is render-blocking,320// so that the sidebar doesn't "jump" after appearing on screen.321// The user interaction to change this is set up in main.js.322//323// At this point in page load, `document.body` is not available yet.324// Set a class on the `<html>` element instead.325if (getSettingValue("source-sidebar-show") === "true") {326 addClass(document.documentElement, "src-sidebar-expanded");327}328(function() {329 const settings = [330 "hide-sidebar",331 "hide-toc",332 "hide-modnav",333 "word-wrap-source-code",334 "hide-deprecated-items",335 "sans-serif-fonts",336 ];337 for (const setting of settings) {338 if (getSettingValue(setting) === "true") {339 addClass(document.documentElement, setting);340 }341 }342})();343344function updateSidebarWidth() {345 const desktopSidebarWidth = getSettingValue("desktop-sidebar-width");346 if (desktopSidebarWidth && desktopSidebarWidth !== "null") {347 document.documentElement.style.setProperty(348 "--desktop-sidebar-width",349 desktopSidebarWidth + "px",350 );351 }352 const srcSidebarWidth = getSettingValue("src-sidebar-width");353 if (srcSidebarWidth && srcSidebarWidth !== "null") {354 document.documentElement.style.setProperty(355 "--src-sidebar-width",356 srcSidebarWidth + "px",357 );358 }359}360updateSidebarWidth();361362// If we navigate away (for example to a settings page), and then use the back or363// forward button to get back to a page, the theme may have changed in the meantime.364// But scripts may not be re-loaded in such a case due to the bfcache365// (https://web.dev/bfcache/). The "pageshow" event triggers on such navigations.366// Use that opportunity to update the theme.367// We use a setTimeout with a 0 timeout here to put the change on the event queue.368// For some reason, if we try to change the theme while the `pageshow` event is369// running, it sometimes fails to take effect. The problem manifests on Chrome,370// specifically when talking to a remote website with no caching.371window.addEventListener("pageshow", ev => {372 if (ev.persisted) {373 setTimeout(updateTheme, 0);374 setTimeout(updateSidebarWidth, 0);375 }376});377378// Custom elements are used to insert some JS-dependent features into Rustdoc,379// because the [parser] runs the connected callback380// synchronously. It needs to be added synchronously so that nothing below it381// becomes visible until after it's done. Otherwise, you get layout jank.382//383// That's also why this is in storage.js and not main.js.384//385// [parser]: https://html.spec.whatwg.org/multipage/parsing.html386class RustdocToolbarElement extends HTMLElement {387 constructor() {388 super();389 }390 connectedCallback() {391 // Avoid replacing the children after they're already here.392 if (this.firstElementChild) {393 return;394 }395 const rootPath = getVar("root-path");396 const currentUrl = window.location.href.split("?")[0].split("#")[0];397 this.innerHTML = `398 <div id="search-button" tabindex="-1">399 <a href="${currentUrl}?search="><span class="label">Search</span></a>400 </div>401 <div class="settings-menu" tabindex="-1">402 <a href="${rootPath}settings.html"><span class="label">Settings</span></a>403 </div>404 <div class="help-menu" tabindex="-1">405 <a href="${rootPath}help.html"><span class="label">Help</span></a>406 </div>407 <button id="toggle-all-docs"408title="Collapse sections (shift-click to also collapse impl blocks)"><span409class="label">Summary</span></button>`;410 }411}412window.customElements.define("rustdoc-toolbar", RustdocToolbarElement);413class RustdocTopBarElement extends HTMLElement {414 constructor() {415 super();416 }417 connectedCallback() {418 const rootPath = getVar("root-path");419 const tmplt = document.createElement("template");420 tmplt.innerHTML = `421 <slot name="sidebar-menu-toggle"></slot>422 <slot></slot>423 <slot name="settings-menu"></slot>424 <slot name="help-menu"></slot>425 `;426 const shadow = this.attachShadow({ mode: "open" });427 shadow.appendChild(tmplt.content.cloneNode(true));428 this.innerHTML += `429 <button class="sidebar-menu-toggle" slot="sidebar-menu-toggle" title="show sidebar">430 </button>431 <div class="settings-menu" slot="settings-menu" tabindex="-1">432 <a href="${rootPath}settings.html"><span class="label">Settings</span></a>433 </div>434 <div class="help-menu" slot="help-menu" tabindex="-1">435 <a href="${rootPath}help.html"><span class="label">Help</span></a>436 </div>437 `;438 }439}440window.customElements.define("rustdoc-topbar", RustdocTopBarElement);
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.