1 // Local js definitions:
2 /* global addClass, getSettingValue, hasClass, searchState */
3 /* global onEach, onEachLazy, removeClass */
7 // Get a value from the rustdoc-vars div, which is used to convey data from
8 // Rust to the JS. If there is no such element, return null.
9 function getVar(name) {
10 const el = document.getElementById("rustdoc-vars");
12 return el.attributes["data-" + name].value;
18 // Given a basename (e.g. "storage") and an extension (e.g. ".js"), return a URL
19 // for a resource under the root-path, with the resource-suffix.
20 function resourcePath(basename, extension) {
21 return getVar("root-path") + basename + getVar("resource-suffix") + extension;
25 addClass(document.getElementById(MAIN_ID), "hidden");
29 removeClass(document.getElementById(MAIN_ID), "hidden");
32 function elemIsInParent(elem, parent) {
33 while (elem && elem !== document.body) {
34 if (elem === parent) {
37 elem = elem.parentElement;
42 function blurHandler(event, parentElem, hideCallback) {
43 if (!elemIsInParent(document.activeElement, parentElem) &&
44 !elemIsInParent(event.relatedTarget, parentElem)
50 window.rootPath = getVar("root-path");
51 window.currentCrate = getVar("current-crate");
53 function setMobileTopbar() {
54 // FIXME: It would be nicer to generate this text content directly in HTML,
55 // but with the current code it's hard to get the right information in the right place.
56 const mobileLocationTitle = document.querySelector(".mobile-topbar h2");
57 const locationTitle = document.querySelector(".sidebar h2.location");
58 if (mobileLocationTitle && locationTitle) {
59 mobileLocationTitle.innerHTML = locationTitle.innerHTML;
63 // Gets the human-readable string for the virtual-key code of the
64 // given KeyboardEvent, ev.
66 // This function is meant as a polyfill for KeyboardEvent#key,
67 // since it is not supported in IE 11 or Chrome for Android. We also test for
68 // KeyboardEvent#keyCode because the handleShortcut handler is
69 // also registered for the keydown event, because Blink doesn't fire
70 // keypress on hitting the Escape key.
72 // So I guess you could say things are getting pretty interoperable.
73 function getVirtualKey(ev) {
74 if ("key" in ev && typeof ev.key !== "undefined") {
78 const c = ev.charCode || ev.keyCode;
82 return String.fromCharCode(c);
85 const MAIN_ID = "main-content";
86 const SETTINGS_BUTTON_ID = "settings-menu";
87 const ALTERNATIVE_DISPLAY_ID = "alternative-display";
88 const NOT_DISPLAYED_ID = "not-displayed";
89 const HELP_BUTTON_ID = "help-button";
91 function getSettingsButton() {
92 return document.getElementById(SETTINGS_BUTTON_ID);
95 function getHelpButton() {
96 return document.getElementById(HELP_BUTTON_ID);
99 // Returns the current URL without any query parameter or hash.
100 function getNakedUrl() {
101 return window.location.href.split("?")[0].split("#")[0];
105 * This function inserts `newNode` after `referenceNode`. It doesn't work if `referenceNode`
106 * doesn't have a parent node.
108 * @param {HTMLElement} newNode
109 * @param {HTMLElement} referenceNode
111 function insertAfter(newNode, referenceNode) {
112 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
116 * This function creates a new `<section>` with the given `id` and `classes` if it doesn't already
119 * More information about this in `switchDisplayedElement` documentation.
122 * @param {string} classes
124 function getOrCreateSection(id, classes) {
125 let el = document.getElementById(id);
128 el = document.createElement("section");
130 el.className = classes;
131 insertAfter(el, document.getElementById(MAIN_ID));
137 * Returns the `<section>` element which contains the displayed element.
139 * @return {HTMLElement}
141 function getAlternativeDisplayElem() {
142 return getOrCreateSection(ALTERNATIVE_DISPLAY_ID, "content hidden");
146 * Returns the `<section>` element which contains the not-displayed elements.
148 * @return {HTMLElement}
150 function getNotDisplayedElem() {
151 return getOrCreateSection(NOT_DISPLAYED_ID, "hidden");
155 * To nicely switch between displayed "extra" elements (such as search results or settings menu)
156 * and to alternate between the displayed and not displayed elements, we hold them in two different
157 * `<section>` elements. They work in pair: one holds the hidden elements while the other
158 * contains the displayed element (there can be only one at the same time!). So basically, we switch
159 * elements between the two `<section>` elements.
161 * @param {HTMLElement} elemToDisplay
163 function switchDisplayedElement(elemToDisplay) {
164 const el = getAlternativeDisplayElem();
166 if (el.children.length > 0) {
167 getNotDisplayedElem().appendChild(el.firstElementChild);
169 if (elemToDisplay === null) {
170 addClass(el, "hidden");
174 el.appendChild(elemToDisplay);
176 removeClass(el, "hidden");
179 function browserSupportsHistoryApi() {
180 return window.history && typeof window.history.pushState === "function";
183 // eslint-disable-next-line no-unused-vars
184 function loadCss(cssUrl) {
185 const link = document.createElement("link");
187 link.type = "text/css";
188 link.rel = "stylesheet";
189 document.getElementsByTagName("head")[0].appendChild(link);
193 const isHelpPage = window.location.pathname.endsWith("/help.html");
195 function loadScript(url) {
196 const script = document.createElement("script");
198 document.head.append(script);
201 getSettingsButton().onclick = event => {
202 if (event.ctrlKey || event.altKey || event.metaKey) {
205 window.hideAllModals(false);
206 addClass(getSettingsButton(), "rotate");
207 event.preventDefault();
208 // Sending request for the CSS and the JS files at the same time so it will
209 // hopefully be loaded when the JS will generate the settings content.
210 loadCss(getVar("static-root-path") + getVar("settings-css"));
211 loadScript(getVar("static-root-path") + getVar("settings-js"));
214 window.searchState = {
215 loadingText: "Loading search results...",
216 input: document.getElementsByClassName("search-input")[0],
217 outputElement: () => {
218 let el = document.getElementById("search");
220 el = document.createElement("section");
222 getNotDisplayedElem().appendChild(el);
226 title: document.title,
227 titleBeforeSearch: document.title,
229 // On the search screen, so you remain on the last tab you opened.
232 // 1 for "In Parameters"
233 // 2 for "In Return Types"
235 // tab and back preserves the element that was focused.
236 focusedByTab: [null, null, null],
237 clearInputTimeout: () => {
238 if (searchState.timeout !== null) {
239 clearTimeout(searchState.timeout);
240 searchState.timeout = null;
243 isDisplayed: () => searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID,
244 // Sets the focus on the search bar at the top of the page
246 searchState.input.focus();
248 // Removes the focus from the search bar.
250 searchState.input.blur();
252 showResults: search => {
253 if (search === null || typeof search === "undefined") {
254 search = searchState.outputElement();
256 switchDisplayedElement(search);
257 searchState.mouseMovedAfterSearch = false;
258 document.title = searchState.title;
261 switchDisplayedElement(null);
262 document.title = searchState.titleBeforeSearch;
263 // We also remove the query parameter from the URL.
264 if (browserSupportsHistoryApi()) {
265 history.replaceState(null, window.currentCrate + " - Rust",
266 getNakedUrl() + window.location.hash);
269 getQueryStringParams: () => {
271 window.location.search.substring(1).split("&").
273 const pair = s.split("=");
274 params[decodeURIComponent(pair[0])] =
275 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
280 const search_input = searchState.input;
281 if (!searchState.input) {
284 let searchLoaded = false;
285 function loadSearch() {
288 loadScript(getVar("static-root-path") + getVar("search-js"));
289 loadScript(resourcePath("search-index", ".js"));
293 search_input.addEventListener("focus", () => {
294 search_input.origPlaceholder = search_input.placeholder;
295 search_input.placeholder = "Type your search here.";
299 if (search_input.value !== "") {
303 const params = searchState.getQueryStringParams();
304 if (params.search !== undefined) {
305 searchState.setLoadingSearch();
309 setLoadingSearch: () => {
310 const search = searchState.outputElement();
311 search.innerHTML = "<h3 class=\"search-loading\">" + searchState.loadingText + "</h3>";
312 searchState.showResults(search);
316 function getPageId() {
317 if (window.location.hash) {
318 const tmp = window.location.hash.replace(/^#/, "");
319 if (tmp.length > 0) {
326 const toggleAllDocsId = "toggle-all-docs";
329 function handleHashes(ev) {
330 if (ev !== null && searchState.isDisplayed() && ev.newURL) {
331 // This block occurs when clicking on an element in the navbar while
333 switchDisplayedElement(null);
334 const hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
335 if (browserSupportsHistoryApi()) {
336 // `window.location.search`` contains all the query parameters, not just `search`.
337 history.replaceState(null, "",
338 getNakedUrl() + window.location.search + "#" + hash);
340 const elem = document.getElementById(hash);
342 elem.scrollIntoView();
345 // This part is used in case an element is not visible.
346 if (savedHash !== window.location.hash) {
347 savedHash = window.location.hash;
348 if (savedHash.length === 0) {
351 expandSection(savedHash.slice(1)); // we remove the '#'
355 function onHashChange(ev) {
356 // If we're in mobile mode, we should hide the sidebar in any case.
361 function openParentDetails(elem) {
363 if (elem.tagName === "DETAILS") {
366 elem = elem.parentNode;
370 function expandSection(id) {
371 openParentDetails(document.getElementById(id));
374 function handleEscape(ev) {
375 searchState.clearInputTimeout();
376 switchDisplayedElement(null);
377 if (browserSupportsHistoryApi()) {
378 history.replaceState(null, window.currentCrate + " - Rust",
379 getNakedUrl() + window.location.hash);
382 searchState.defocus();
383 window.hideAllModals(true); // true = reset focus for notable traits
386 function handleShortcut(ev) {
387 // Don't interfere with browser shortcuts
388 const disableShortcuts = getSettingValue("disable-shortcuts") === "true";
389 if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts) {
393 if (document.activeElement.tagName === "INPUT" &&
394 document.activeElement.type !== "checkbox") {
395 switch (getVirtualKey(ev)) {
401 switch (getVirtualKey(ev)) {
431 document.addEventListener("keypress", handleShortcut);
432 document.addEventListener("keydown", handleShortcut);
434 function addSidebarItems() {
435 if (!window.SIDEBAR_ITEMS) {
438 const sidebar = document.getElementsByClassName("sidebar-elems")[0];
441 * Append to the sidebar a "block" of links - a heading along with a list (`<ul>`) of items.
443 * @param {string} shortty - A short type name, like "primitive", "mod", or "macro"
444 * @param {string} id - The HTML id of the corresponding section on the module page.
445 * @param {string} longty - A long, capitalized, plural name, like "Primitive Types",
446 * "Modules", or "Macros".
448 function block(shortty, id, longty) {
449 const filtered = window.SIDEBAR_ITEMS[shortty];
454 const h3 = document.createElement("h3");
455 h3.innerHTML = `<a href="index.html#${id}">${longty}</a>`;
456 const ul = document.createElement("ul");
457 ul.className = "block " + shortty;
459 for (const item of filtered) {
460 const name = item[0];
461 const desc = item[1]; // can be null
464 if (shortty === "mod") {
465 path = name + "/index.html";
467 path = shortty + "." + name + ".html";
469 const current_page = document.location.href.split("/").pop();
470 const link = document.createElement("a");
473 if (path === current_page) {
474 link.className = "current";
476 link.textContent = name;
477 const li = document.createElement("li");
478 li.appendChild(link);
481 sidebar.appendChild(h3);
482 sidebar.appendChild(ul);
486 block("primitive", "primitives", "Primitive Types");
487 block("mod", "modules", "Modules");
488 block("macro", "macros", "Macros");
489 block("struct", "structs", "Structs");
490 block("enum", "enums", "Enums");
491 block("union", "unions", "Unions");
492 block("constant", "constants", "Constants");
493 block("static", "static", "Statics");
494 block("trait", "traits", "Traits");
495 block("fn", "functions", "Functions");
496 block("type", "types", "Type Definitions");
497 block("foreigntype", "foreign-types", "Foreign Types");
498 block("keyword", "keywords", "Keywords");
499 block("traitalias", "trait-aliases", "Trait Aliases");
503 window.register_implementors = imp => {
504 const implementors = document.getElementById("implementors-list");
505 const synthetic_implementors = document.getElementById("synthetic-implementors-list");
506 const inlined_types = new Set();
509 const SYNTHETIC_IDX = 1;
512 if (synthetic_implementors) {
513 // This `inlined_types` variable is used to avoid having the same implementation
514 // showing up twice. For example "String" in the "Sync" doc page.
516 // By the way, this is only used by and useful for traits implemented automatically
517 // (like "Send" and "Sync").
518 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), el => {
519 const aliases = el.getAttribute("data-aliases");
523 aliases.split(",").forEach(alias => {
524 inlined_types.add(alias);
529 let currentNbImpls = implementors.getElementsByClassName("impl").length;
530 const traitName = document.querySelector("h1.fqn > .trait").textContent;
531 const baseIdName = "impl-" + traitName + "-";
532 const libs = Object.getOwnPropertyNames(imp);
533 // We don't want to include impls from this JS file, when the HTML already has them.
534 // The current crate should always be ignored. Other crates that should also be
535 // ignored are included in the attribute `data-ignore-extern-crates`.
536 const script = document
537 .querySelector("script[data-ignore-extern-crates]");
538 const ignoreExternCrates = script ? script.getAttribute("data-ignore-extern-crates") : "";
539 for (const lib of libs) {
540 if (lib === window.currentCrate || ignoreExternCrates.indexOf(lib) !== -1) {
543 const structs = imp[lib];
546 for (const struct of structs) {
547 const list = struct[SYNTHETIC_IDX] ? synthetic_implementors : implementors;
549 // The types list is only used for synthetic impls.
550 // If this changes, `main.js` and `write_shared.rs` both need changed.
551 if (struct[SYNTHETIC_IDX]) {
552 for (const struct_type of struct[TYPES_IDX]) {
553 if (inlined_types.has(struct_type)) {
554 continue struct_loop;
556 inlined_types.add(struct_type);
560 const code = document.createElement("h3");
561 code.innerHTML = struct[TEXT_IDX];
562 addClass(code, "code-header");
564 onEachLazy(code.getElementsByTagName("a"), elem => {
565 const href = elem.getAttribute("href");
567 if (href && href.indexOf("http") !== 0) {
568 elem.setAttribute("href", window.rootPath + href);
572 const currentId = baseIdName + currentNbImpls;
573 const anchor = document.createElement("a");
574 anchor.href = "#" + currentId;
575 addClass(anchor, "anchor");
577 const display = document.createElement("div");
578 display.id = currentId;
579 addClass(display, "impl");
580 display.appendChild(anchor);
581 display.appendChild(code);
582 list.appendChild(display);
587 if (window.pending_implementors) {
588 window.register_implementors(window.pending_implementors);
591 function addSidebarCrates() {
592 if (!window.ALL_CRATES) {
595 const sidebarElems = document.getElementsByClassName("sidebar-elems")[0];
599 // Draw a convenient sidebar of known crates if we have a listing
600 const h3 = document.createElement("h3");
601 h3.innerHTML = "Crates";
602 const ul = document.createElement("ul");
603 ul.className = "block crate";
605 for (const crate of window.ALL_CRATES) {
606 const link = document.createElement("a");
607 link.href = window.rootPath + crate + "/index.html";
608 if (window.rootPath !== "./" && crate === window.currentCrate) {
609 link.className = "current";
611 link.textContent = crate;
613 const li = document.createElement("li");
614 li.appendChild(link);
617 sidebarElems.appendChild(h3);
618 sidebarElems.appendChild(ul);
621 function expandAllDocs() {
622 const innerToggle = document.getElementById(toggleAllDocsId);
623 removeClass(innerToggle, "will-expand");
624 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
625 if (!hasClass(e, "type-contents-toggle")) {
629 innerToggle.title = "collapse all docs";
630 innerToggle.children[0].innerText = "\u2212"; // "\u2212" is "−" minus sign
633 function collapseAllDocs() {
634 const innerToggle = document.getElementById(toggleAllDocsId);
635 addClass(innerToggle, "will-expand");
636 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
637 if (e.parentNode.id !== "implementations-list" ||
638 (!hasClass(e, "implementors-toggle") &&
639 !hasClass(e, "type-contents-toggle"))
644 innerToggle.title = "expand all docs";
645 innerToggle.children[0].innerText = "+";
648 function toggleAllDocs() {
649 const innerToggle = document.getElementById(toggleAllDocsId);
653 if (hasClass(innerToggle, "will-expand")) {
661 const toggles = document.getElementById(toggleAllDocsId);
663 toggles.onclick = toggleAllDocs;
666 const hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
667 const hideImplementations = getSettingValue("auto-hide-trait-implementations") === "true";
668 const hideLargeItemContents = getSettingValue("auto-hide-large-items") !== "false";
670 function setImplementorsTogglesOpen(id, open) {
671 const list = document.getElementById(id);
673 onEachLazy(list.getElementsByClassName("implementors-toggle"), e => {
679 if (hideImplementations) {
680 setImplementorsTogglesOpen("trait-implementations-list", false);
681 setImplementorsTogglesOpen("blanket-implementations-list", false);
684 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
685 if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) {
688 if (hideMethodDocs && hasClass(e, "method-toggle")) {
694 const pageId = getPageId();
695 if (pageId !== null) {
696 expandSection(pageId);
700 window.rustdoc_add_line_numbers_to_examples = () => {
701 onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
702 const parent = x.parentNode;
703 const line_numbers = parent.querySelectorAll(".example-line-numbers");
704 if (line_numbers.length > 0) {
707 const count = x.textContent.split("\n").length;
709 for (let i = 0; i < count; ++i) {
712 const node = document.createElement("pre");
713 addClass(node, "example-line-numbers");
714 node.innerHTML = elems.join("\n");
715 parent.insertBefore(node, x);
719 window.rustdoc_remove_line_numbers_from_examples = () => {
720 onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
721 const parent = x.parentNode;
722 const line_numbers = parent.querySelectorAll(".example-line-numbers");
723 for (const node of line_numbers) {
724 parent.removeChild(node);
729 if (getSettingValue("line-numbers") === "true") {
730 window.rustdoc_add_line_numbers_to_examples();
733 let oldSidebarScrollPosition = null;
735 // Scroll locking used both here and in source-script.js
737 window.rustdocMobileScrollLock = function() {
738 const mobile_topbar = document.querySelector(".mobile-topbar");
739 if (window.innerWidth <= window.RUSTDOC_MOBILE_BREAKPOINT) {
740 // This is to keep the scroll position on mobile.
741 oldSidebarScrollPosition = window.scrollY;
742 document.body.style.width = `${document.body.offsetWidth}px`;
743 document.body.style.position = "fixed";
744 document.body.style.top = `-${oldSidebarScrollPosition}px`;
746 mobile_topbar.style.top = `${oldSidebarScrollPosition}px`;
747 mobile_topbar.style.position = "relative";
750 oldSidebarScrollPosition = null;
754 window.rustdocMobileScrollUnlock = function() {
755 const mobile_topbar = document.querySelector(".mobile-topbar");
756 if (oldSidebarScrollPosition !== null) {
757 // This is to keep the scroll position on mobile.
758 document.body.style.width = "";
759 document.body.style.position = "";
760 document.body.style.top = "";
762 mobile_topbar.style.top = "";
763 mobile_topbar.style.position = "";
765 // The scroll position is lost when resetting the style, hence why we store it in
766 // `oldSidebarScrollPosition`.
767 window.scrollTo(0, oldSidebarScrollPosition);
768 oldSidebarScrollPosition = null;
772 function showSidebar() {
773 window.hideAllModals(false);
774 window.rustdocMobileScrollLock();
775 const sidebar = document.getElementsByClassName("sidebar")[0];
776 addClass(sidebar, "shown");
779 function hideSidebar() {
780 window.rustdocMobileScrollUnlock();
781 const sidebar = document.getElementsByClassName("sidebar")[0];
782 removeClass(sidebar, "shown");
785 window.addEventListener("resize", () => {
786 if (window.innerWidth > window.RUSTDOC_MOBILE_BREAKPOINT &&
787 oldSidebarScrollPosition !== null) {
788 // If the user opens the sidebar in "mobile" mode, and then grows the browser window,
789 // we need to switch away from mobile mode and make the main content area scrollable.
792 if (window.CURRENT_NOTABLE_ELEMENT) {
793 // As a workaround to the behavior of `contains: layout` used in doc togglers, the
794 // notable traits popup is positioned using javascript.
796 // This means when the window is resized, we need to redo the layout.
797 const base = window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE;
798 const force_visible = base.NOTABLE_FORCE_VISIBLE;
802 base.NOTABLE_FORCE_VISIBLE = true;
807 function handleClick(id, f) {
808 const elem = document.getElementById(id);
810 elem.addEventListener("click", f);
813 handleClick(MAIN_ID, () => {
817 onEachLazy(document.getElementsByTagName("a"), el => {
818 // For clicks on internal links (<A> tags with a hash property), we expand the section we're
819 // jumping to *before* jumping there. We can't do this in onHashChange, because it changes
820 // the height of the document so we wind up scrolled to the wrong place.
822 el.addEventListener("click", () => {
823 expandSection(el.hash.slice(1));
829 onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"), el => {
830 el.addEventListener("click", e => {
831 if (e.target.tagName !== "SUMMARY" && e.target.tagName !== "A") {
837 function showNotable(e) {
838 if (!window.NOTABLE_TRAITS) {
839 const data = document.getElementById("notable-traits-data");
841 window.NOTABLE_TRAITS = JSON.parse(data.innerText);
843 throw new Error("showNotable() called on page without any notable traits!");
846 if (window.CURRENT_NOTABLE_ELEMENT && window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE === e) {
847 // Make this function idempotent.
850 window.hideAllModals(false);
851 const ty = e.getAttribute("data-ty");
852 const wrapper = document.createElement("div");
853 wrapper.innerHTML = "<div class=\"docblock\">" + window.NOTABLE_TRAITS[ty] + "</div>";
854 wrapper.className = "notable popover";
855 const focusCatcher = document.createElement("div");
856 focusCatcher.setAttribute("tabindex", "0");
857 focusCatcher.onfocus = hideNotable;
858 wrapper.appendChild(focusCatcher);
859 const pos = e.getBoundingClientRect();
860 // 5px overlap so that the mouse can easily travel from place to place
861 wrapper.style.top = (pos.top + window.scrollY + pos.height) + "px";
862 wrapper.style.left = 0;
863 wrapper.style.right = "auto";
864 wrapper.style.visibility = "hidden";
865 const body = document.getElementsByTagName("body")[0];
866 body.appendChild(wrapper);
867 const wrapperPos = wrapper.getBoundingClientRect();
868 // offset so that the arrow points at the center of the "(i)"
869 const finalPos = pos.left + window.scrollX - wrapperPos.width + 24;
871 wrapper.style.left = finalPos + "px";
873 wrapper.style.setProperty(
874 "--popover-arrow-offset",
875 (wrapperPos.right - pos.right + 4) + "px"
878 wrapper.style.visibility = "";
879 window.CURRENT_NOTABLE_ELEMENT = wrapper;
880 window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE = e;
881 wrapper.onpointerleave = function(ev) {
882 // If this is a synthetic touch event, ignore it. A click event will be along shortly.
883 if (ev.pointerType !== "mouse") {
886 if (!e.NOTABLE_FORCE_VISIBLE && !elemIsInParent(event.relatedTarget, e)) {
892 function notableBlurHandler(event) {
893 if (window.CURRENT_NOTABLE_ELEMENT &&
894 !elemIsInParent(document.activeElement, window.CURRENT_NOTABLE_ELEMENT) &&
895 !elemIsInParent(event.relatedTarget, window.CURRENT_NOTABLE_ELEMENT) &&
896 !elemIsInParent(document.activeElement, window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE) &&
897 !elemIsInParent(event.relatedTarget, window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE)
899 // Work around a difference in the focus behaviour between Firefox, Chrome, and Safari.
900 // When I click the button on an already-opened notable trait popover, Safari
901 // hides the popover and then immediately shows it again, while everyone else hides it
902 // and it stays hidden.
904 // To work around this, make sure the click finishes being dispatched before
905 // hiding the popover. Since `hideNotable()` is idempotent, this makes Safari behave
906 // consistently with the other two.
907 setTimeout(() => hideNotable(false), 0);
911 function hideNotable(focus) {
912 if (window.CURRENT_NOTABLE_ELEMENT) {
913 if (window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE.NOTABLE_FORCE_VISIBLE) {
915 window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE.focus();
917 window.CURRENT_NOTABLE_ELEMENT.NOTABLE_BASE.NOTABLE_FORCE_VISIBLE = false;
919 const body = document.getElementsByTagName("body")[0];
920 body.removeChild(window.CURRENT_NOTABLE_ELEMENT);
921 window.CURRENT_NOTABLE_ELEMENT = null;
925 onEachLazy(document.getElementsByClassName("notable-traits"), e => {
926 e.onclick = function() {
927 this.NOTABLE_FORCE_VISIBLE = this.NOTABLE_FORCE_VISIBLE ? false : true;
928 if (window.CURRENT_NOTABLE_ELEMENT && !this.NOTABLE_FORCE_VISIBLE) {
932 window.CURRENT_NOTABLE_ELEMENT.setAttribute("tabindex", "0");
933 window.CURRENT_NOTABLE_ELEMENT.focus();
934 window.CURRENT_NOTABLE_ELEMENT.onblur = notableBlurHandler;
938 e.onpointerenter = function(ev) {
939 // If this is a synthetic touch event, ignore it. A click event will be along shortly.
940 if (ev.pointerType !== "mouse") {
945 e.onpointerleave = function(ev) {
946 // If this is a synthetic touch event, ignore it. A click event will be along shortly.
947 if (ev.pointerType !== "mouse") {
950 if (!this.NOTABLE_FORCE_VISIBLE &&
951 !elemIsInParent(event.relatedTarget, window.CURRENT_NOTABLE_ELEMENT)) {
957 const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0];
958 if (sidebar_menu_toggle) {
959 sidebar_menu_toggle.addEventListener("click", () => {
960 const sidebar = document.getElementsByClassName("sidebar")[0];
961 if (!hasClass(sidebar, "shown")) {
969 function helpBlurHandler(event) {
970 blurHandler(event, getHelpButton(), window.hidePopoverMenus);
973 function buildHelpMenu() {
974 const book_info = document.createElement("span");
975 book_info.className = "top";
976 book_info.innerHTML = "You can find more information in \
977 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
980 ["?", "Show this help dialog"],
981 ["S", "Focus the search field"],
982 ["↑", "Move up in search results"],
983 ["↓", "Move down in search results"],
984 ["← / →", "Switch result tab (when results focused)"],
985 ["⏎", "Go to active search result"],
986 ["+", "Expand all sections"],
987 ["-", "Collapse all sections"],
990 .map((y, index) => ((index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " "))
991 .join("") + "</dt><dd>" + x[1] + "</dd>").join("");
992 const div_shortcuts = document.createElement("div");
993 addClass(div_shortcuts, "shortcuts");
994 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
997 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
998 restrict the search to a given item kind.",
999 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
1000 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
1001 and <code>const</code>.",
1002 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
1003 <code>-> vec</code>)",
1004 "Search multiple things at once by splitting your query with comma (e.g., \
1005 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
1006 "You can look for items with an exact name by putting double quotes around \
1007 your request: <code>\"string\"</code>",
1008 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
1009 ].map(x => "<p>" + x + "</p>").join("");
1010 const div_infos = document.createElement("div");
1011 addClass(div_infos, "infos");
1012 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
1014 const rustdoc_version = document.createElement("span");
1015 rustdoc_version.className = "bottom";
1016 const rustdoc_version_code = document.createElement("code");
1017 rustdoc_version_code.innerText = "rustdoc " + getVar("rustdoc-version");
1018 rustdoc_version.appendChild(rustdoc_version_code);
1020 const container = document.createElement("div");
1022 container.className = "popover";
1024 container.id = "help";
1025 container.style.display = "none";
1027 const side_by_side = document.createElement("div");
1028 side_by_side.className = "side-by-side";
1029 side_by_side.appendChild(div_shortcuts);
1030 side_by_side.appendChild(div_infos);
1032 container.appendChild(book_info);
1033 container.appendChild(side_by_side);
1034 container.appendChild(rustdoc_version);
1037 const help_section = document.createElement("section");
1038 help_section.appendChild(container);
1039 document.getElementById("main-content").appendChild(help_section);
1040 container.style.display = "block";
1042 const help_button = getHelpButton();
1043 help_button.appendChild(container);
1045 container.onblur = helpBlurHandler;
1046 container.onclick = event => {
1047 event.preventDefault();
1049 help_button.onblur = helpBlurHandler;
1050 help_button.children[0].onblur = helpBlurHandler;
1057 * Hide popover menus, notable trait tooltips, and the sidebar (if applicable).
1059 * Pass "true" to reset focus for notable traits.
1061 window.hideAllModals = function(switchFocus) {
1063 window.hidePopoverMenus();
1064 hideNotable(switchFocus);
1068 * Hide all the popover menus.
1070 window.hidePopoverMenus = function() {
1071 onEachLazy(document.querySelectorAll(".search-form .popover"), elem => {
1072 elem.style.display = "none";
1077 * Returns the help menu element (not the button).
1079 * @param {boolean} buildNeeded - If this argument is `false`, the help menu element won't be
1080 * built if it doesn't exist.
1082 * @return {HTMLElement}
1084 function getHelpMenu(buildNeeded) {
1085 let menu = getHelpButton().querySelector(".popover");
1086 if (!menu && buildNeeded) {
1087 menu = buildHelpMenu();
1093 * Show the help popup menu.
1095 function showHelp() {
1096 const menu = getHelpMenu(true);
1097 if (menu.style.display === "none") {
1098 window.hideAllModals();
1099 menu.style.display = "";
1105 document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
1106 // Already on the help page, make help button a no-op.
1107 const target = event.target;
1108 if (target.tagName !== "A" ||
1109 target.parentElement.id !== HELP_BUTTON_ID ||
1115 event.preventDefault();
1118 document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
1119 // By default, have help button open docs in a popover.
1120 // If user clicks with a moderator, though, use default browser behavior,
1121 // probably opening in a new window or tab.
1122 const target = event.target;
1123 if (target.tagName !== "A" ||
1124 target.parentElement.id !== HELP_BUTTON_ID ||
1130 event.preventDefault();
1131 const menu = getHelpMenu(true);
1132 const shouldShowHelp = menu.style.display === "none";
1133 if (shouldShowHelp) {
1136 window.hidePopoverMenus();
1145 window.addEventListener("hashchange", onHashChange);
1146 searchState.setup();
1150 let reset_button_timeout = null;
1152 window.copy_path = but => {
1153 const parent = but.parentElement;
1156 onEach(parent.childNodes, child => {
1157 if (child.tagName === "A") {
1158 path.push(child.textContent);
1162 const el = document.createElement("textarea");
1163 el.value = path.join("::");
1164 el.setAttribute("readonly", "");
1165 // To not make it appear on the screen.
1166 el.style.position = "absolute";
1167 el.style.left = "-9999px";
1169 document.body.appendChild(el);
1171 document.execCommand("copy");
1172 document.body.removeChild(el);
1174 // There is always one children, but multiple childNodes.
1175 but.children[0].style.display = "none";
1178 if (but.childNodes.length < 2) {
1179 tmp = document.createTextNode("✓");
1180 but.appendChild(tmp);
1182 onEachLazy(but.childNodes, e => {
1183 if (e.nodeType === Node.TEXT_NODE) {
1188 tmp.textContent = "✓";
1191 if (reset_button_timeout !== null) {
1192 window.clearTimeout(reset_button_timeout);
1195 function reset_button() {
1196 tmp.textContent = "";
1197 reset_button_timeout = null;
1198 but.children[0].style.display = "";
1201 reset_button_timeout = window.setTimeout(reset_button, 1000);