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)
51 window.rootPath = getVar("root-path");
52 window.currentCrate = getVar("current-crate");
55 function setMobileTopbar() {
56 // FIXME: It would be nicer to generate this text content directly in HTML,
57 // but with the current code it's hard to get the right information in the right place.
58 const mobileLocationTitle = document.querySelector(".mobile-topbar h2.location");
59 const locationTitle = document.querySelector(".sidebar h2.location");
60 if (mobileLocationTitle && locationTitle) {
61 mobileLocationTitle.innerHTML = locationTitle.innerHTML;
65 // Gets the human-readable string for the virtual-key code of the
66 // given KeyboardEvent, ev.
68 // This function is meant as a polyfill for KeyboardEvent#key,
69 // since it is not supported in IE 11 or Chrome for Android. We also test for
70 // KeyboardEvent#keyCode because the handleShortcut handler is
71 // also registered for the keydown event, because Blink doesn't fire
72 // keypress on hitting the Escape key.
74 // So I guess you could say things are getting pretty interoperable.
75 function getVirtualKey(ev) {
76 if ("key" in ev && typeof ev.key !== "undefined") {
80 const c = ev.charCode || ev.keyCode;
84 return String.fromCharCode(c);
87 const MAIN_ID = "main-content";
88 const SETTINGS_BUTTON_ID = "settings-menu";
89 const ALTERNATIVE_DISPLAY_ID = "alternative-display";
90 const NOT_DISPLAYED_ID = "not-displayed";
91 const HELP_BUTTON_ID = "help-button";
93 function getSettingsButton() {
94 return document.getElementById(SETTINGS_BUTTON_ID);
97 function getHelpButton() {
98 return document.getElementById(HELP_BUTTON_ID);
101 // Returns the current URL without any query parameter or hash.
102 function getNakedUrl() {
103 return window.location.href.split("?")[0].split("#")[0];
107 * This function inserts `newNode` after `referenceNode`. It doesn't work if `referenceNode`
108 * doesn't have a parent node.
110 * @param {HTMLElement} newNode
111 * @param {HTMLElement} referenceNode
113 function insertAfter(newNode, referenceNode) {
114 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
118 * This function creates a new `<section>` with the given `id` and `classes` if it doesn't already
121 * More information about this in `switchDisplayedElement` documentation.
124 * @param {string} classes
126 function getOrCreateSection(id, classes) {
127 let el = document.getElementById(id);
130 el = document.createElement("section");
132 el.className = classes;
133 insertAfter(el, document.getElementById(MAIN_ID));
139 * Returns the `<section>` element which contains the displayed element.
141 * @return {HTMLElement}
143 function getAlternativeDisplayElem() {
144 return getOrCreateSection(ALTERNATIVE_DISPLAY_ID, "content hidden");
148 * Returns the `<section>` element which contains the not-displayed elements.
150 * @return {HTMLElement}
152 function getNotDisplayedElem() {
153 return getOrCreateSection(NOT_DISPLAYED_ID, "hidden");
157 * To nicely switch between displayed "extra" elements (such as search results or settings menu)
158 * and to alternate between the displayed and not displayed elements, we hold them in two different
159 * `<section>` elements. They work in pair: one holds the hidden elements while the other
160 * contains the displayed element (there can be only one at the same time!). So basically, we switch
161 * elements between the two `<section>` elements.
163 * @param {HTMLElement} elemToDisplay
165 function switchDisplayedElement(elemToDisplay) {
166 const el = getAlternativeDisplayElem();
168 if (el.children.length > 0) {
169 getNotDisplayedElem().appendChild(el.firstElementChild);
171 if (elemToDisplay === null) {
172 addClass(el, "hidden");
176 el.appendChild(elemToDisplay);
178 removeClass(el, "hidden");
181 function browserSupportsHistoryApi() {
182 return window.history && typeof window.history.pushState === "function";
185 // eslint-disable-next-line no-unused-vars
186 function loadCss(cssFileName) {
187 const link = document.createElement("link");
188 link.href = resourcePath(cssFileName, ".css");
189 link.type = "text/css";
190 link.rel = "stylesheet";
191 document.getElementsByTagName("head")[0].appendChild(link);
195 const isHelpPage = window.location.pathname.endsWith("/help.html");
197 function loadScript(url) {
198 const script = document.createElement("script");
200 document.head.append(script);
203 getSettingsButton().onclick = event => {
204 if (event.ctrlKey || event.altKey || event.metaKey) {
207 addClass(getSettingsButton(), "rotate");
208 event.preventDefault();
209 // Sending request for the CSS and the JS files at the same time so it will
210 // hopefully be loaded when the JS will generate the settings content.
212 loadScript(resourcePath("settings", ".js"));
215 window.searchState = {
216 loadingText: "Loading search results...",
217 input: document.getElementsByClassName("search-input")[0],
218 outputElement: () => {
219 let el = document.getElementById("search");
221 el = document.createElement("section");
223 getNotDisplayedElem().appendChild(el);
227 title: document.title,
228 titleBeforeSearch: document.title,
230 // On the search screen, so you remain on the last tab you opened.
233 // 1 for "In Parameters"
234 // 2 for "In Return Types"
236 // tab and back preserves the element that was focused.
237 focusedByTab: [null, null, null],
238 clearInputTimeout: () => {
239 if (searchState.timeout !== null) {
240 clearTimeout(searchState.timeout);
241 searchState.timeout = null;
244 isDisplayed: () => searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID,
245 // Sets the focus on the search bar at the top of the page
247 searchState.input.focus();
249 // Removes the focus from the search bar.
251 searchState.input.blur();
253 showResults: search => {
254 if (search === null || typeof search === "undefined") {
255 search = searchState.outputElement();
257 switchDisplayedElement(search);
258 searchState.mouseMovedAfterSearch = false;
259 document.title = searchState.title;
262 switchDisplayedElement(null);
263 document.title = searchState.titleBeforeSearch;
264 // We also remove the query parameter from the URL.
265 if (browserSupportsHistoryApi()) {
266 history.replaceState(null, window.currentCrate + " - Rust",
267 getNakedUrl() + window.location.hash);
270 getQueryStringParams: () => {
272 window.location.search.substring(1).split("&").
274 const pair = s.split("=");
275 params[decodeURIComponent(pair[0])] =
276 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
281 const search_input = searchState.input;
282 if (!searchState.input) {
285 let searchLoaded = false;
286 function loadSearch() {
289 loadScript(resourcePath("search", ".js"));
290 loadScript(resourcePath("search-index", ".js"));
294 search_input.addEventListener("focus", () => {
295 search_input.origPlaceholder = search_input.placeholder;
296 search_input.placeholder = "Type your search here.";
300 if (search_input.value !== "") {
304 const params = searchState.getQueryStringParams();
305 if (params.search !== undefined) {
306 const search = searchState.outputElement();
307 search.innerHTML = "<h3 class=\"search-loading\">" +
308 searchState.loadingText + "</h3>";
309 searchState.showResults(search);
315 function getPageId() {
316 if (window.location.hash) {
317 const tmp = window.location.hash.replace(/^#/, "");
318 if (tmp.length > 0) {
325 const toggleAllDocsId = "toggle-all-docs";
328 function handleHashes(ev) {
329 if (ev !== null && searchState.isDisplayed() && ev.newURL) {
330 // This block occurs when clicking on an element in the navbar while
332 switchDisplayedElement(null);
333 const hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
334 if (browserSupportsHistoryApi()) {
335 // `window.location.search`` contains all the query parameters, not just `search`.
336 history.replaceState(null, "",
337 getNakedUrl() + window.location.search + "#" + hash);
339 const elem = document.getElementById(hash);
341 elem.scrollIntoView();
344 // This part is used in case an element is not visible.
345 if (savedHash !== window.location.hash) {
346 savedHash = window.location.hash;
347 if (savedHash.length === 0) {
350 expandSection(savedHash.slice(1)); // we remove the '#'
354 function onHashChange(ev) {
355 // If we're in mobile mode, we should hide the sidebar in any case.
360 function openParentDetails(elem) {
362 if (elem.tagName === "DETAILS") {
365 elem = elem.parentNode;
369 function expandSection(id) {
370 openParentDetails(document.getElementById(id));
373 function handleEscape(ev) {
374 searchState.clearInputTimeout();
375 switchDisplayedElement(null);
376 if (browserSupportsHistoryApi()) {
377 history.replaceState(null, window.currentCrate + " - Rust",
378 getNakedUrl() + window.location.hash);
381 searchState.defocus();
382 window.hidePopoverMenus();
385 function handleShortcut(ev) {
386 // Don't interfere with browser shortcuts
387 const disableShortcuts = getSettingValue("disable-shortcuts") === "true";
388 if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts) {
392 if (document.activeElement.tagName === "INPUT" &&
393 document.activeElement.type !== "checkbox") {
394 switch (getVirtualKey(ev)) {
400 switch (getVirtualKey(ev)) {
427 document.addEventListener("keypress", handleShortcut);
428 document.addEventListener("keydown", handleShortcut);
430 function addSidebarItems() {
431 if (!window.SIDEBAR_ITEMS) {
434 const sidebar = document.getElementsByClassName("sidebar-elems")[0];
437 * Append to the sidebar a "block" of links - a heading along with a list (`<ul>`) of items.
439 * @param {string} shortty - A short type name, like "primitive", "mod", or "macro"
440 * @param {string} id - The HTML id of the corresponding section on the module page.
441 * @param {string} longty - A long, capitalized, plural name, like "Primitive Types",
442 * "Modules", or "Macros".
444 function block(shortty, id, longty) {
445 const filtered = window.SIDEBAR_ITEMS[shortty];
450 const h3 = document.createElement("h3");
451 h3.innerHTML = `<a href="index.html#${id}">${longty}</a>`;
452 const ul = document.createElement("ul");
453 ul.className = "block " + shortty;
455 for (const item of filtered) {
456 const name = item[0];
457 const desc = item[1]; // can be null
460 if (shortty === "mod") {
461 path = name + "/index.html";
463 path = shortty + "." + name + ".html";
465 const current_page = document.location.href.split("/").pop();
466 const link = document.createElement("a");
469 if (path === current_page) {
470 link.className = "current";
472 link.textContent = name;
473 const li = document.createElement("li");
474 li.appendChild(link);
477 sidebar.appendChild(h3);
478 sidebar.appendChild(ul);
482 block("primitive", "primitives", "Primitive Types");
483 block("mod", "modules", "Modules");
484 block("macro", "macros", "Macros");
485 block("struct", "structs", "Structs");
486 block("enum", "enums", "Enums");
487 block("union", "unions", "Unions");
488 block("constant", "constants", "Constants");
489 block("static", "static", "Statics");
490 block("trait", "traits", "Traits");
491 block("fn", "functions", "Functions");
492 block("type", "types", "Type Definitions");
493 block("foreigntype", "foreign-types", "Foreign Types");
494 block("keyword", "keywords", "Keywords");
495 block("traitalias", "trait-aliases", "Trait Aliases");
499 window.register_implementors = imp => {
500 const implementors = document.getElementById("implementors-list");
501 const synthetic_implementors = document.getElementById("synthetic-implementors-list");
502 const inlined_types = new Set();
505 const SYNTHETIC_IDX = 1;
508 if (synthetic_implementors) {
509 // This `inlined_types` variable is used to avoid having the same implementation
510 // showing up twice. For example "String" in the "Sync" doc page.
512 // By the way, this is only used by and useful for traits implemented automatically
513 // (like "Send" and "Sync").
514 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), el => {
515 const aliases = el.getAttribute("data-aliases");
519 aliases.split(",").forEach(alias => {
520 inlined_types.add(alias);
525 let currentNbImpls = implementors.getElementsByClassName("impl").length;
526 const traitName = document.querySelector("h1.fqn > .trait").textContent;
527 const baseIdName = "impl-" + traitName + "-";
528 const libs = Object.getOwnPropertyNames(imp);
529 // We don't want to include impls from this JS file, when the HTML already has them.
530 // The current crate should always be ignored. Other crates that should also be
531 // ignored are included in the attribute `data-ignore-extern-crates`.
532 const script = document
533 .querySelector("script[data-ignore-extern-crates]");
534 const ignoreExternCrates = script ? script.getAttribute("data-ignore-extern-crates") : "";
535 for (const lib of libs) {
536 if (lib === window.currentCrate || ignoreExternCrates.indexOf(lib) !== -1) {
539 const structs = imp[lib];
542 for (const struct of structs) {
543 const list = struct[SYNTHETIC_IDX] ? synthetic_implementors : implementors;
545 // The types list is only used for synthetic impls.
546 // If this changes, `main.js` and `write_shared.rs` both need changed.
547 if (struct[SYNTHETIC_IDX]) {
548 for (const struct_type of struct[TYPES_IDX]) {
549 if (inlined_types.has(struct_type)) {
550 continue struct_loop;
552 inlined_types.add(struct_type);
556 const code = document.createElement("h3");
557 code.innerHTML = struct[TEXT_IDX];
558 addClass(code, "code-header");
560 onEachLazy(code.getElementsByTagName("a"), elem => {
561 const href = elem.getAttribute("href");
563 if (href && href.indexOf("http") !== 0) {
564 elem.setAttribute("href", window.rootPath + href);
568 const currentId = baseIdName + currentNbImpls;
569 const anchor = document.createElement("a");
570 anchor.href = "#" + currentId;
571 addClass(anchor, "anchor");
573 const display = document.createElement("div");
574 display.id = currentId;
575 addClass(display, "impl");
576 display.appendChild(anchor);
577 display.appendChild(code);
578 list.appendChild(display);
583 if (window.pending_implementors) {
584 window.register_implementors(window.pending_implementors);
587 function addSidebarCrates() {
588 if (!window.ALL_CRATES) {
591 const sidebarElems = document.getElementsByClassName("sidebar-elems")[0];
595 // Draw a convenient sidebar of known crates if we have a listing
596 const h3 = document.createElement("h3");
597 h3.innerHTML = "Crates";
598 const ul = document.createElement("ul");
599 ul.className = "block crate";
601 for (const crate of window.ALL_CRATES) {
602 const link = document.createElement("a");
603 link.href = window.rootPath + crate + "/index.html";
604 if (window.rootPath !== "./" && crate === window.currentCrate) {
605 link.className = "current";
607 link.textContent = crate;
609 const li = document.createElement("li");
610 li.appendChild(link);
613 sidebarElems.appendChild(h3);
614 sidebarElems.appendChild(ul);
618 function labelForToggleButton(sectionIsCollapsed) {
619 if (sectionIsCollapsed) {
620 // button will expand the section
623 // button will collapse the section
624 // note that this text is also set in the HTML template in ../render/mod.rs
625 return "\u2212"; // "\u2212" is "−" minus sign
628 function toggleAllDocs() {
629 const innerToggle = document.getElementById(toggleAllDocsId);
633 let sectionIsCollapsed = false;
634 if (hasClass(innerToggle, "will-expand")) {
635 removeClass(innerToggle, "will-expand");
636 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
637 if (!hasClass(e, "type-contents-toggle")) {
641 innerToggle.title = "collapse all docs";
643 addClass(innerToggle, "will-expand");
644 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
645 if (e.parentNode.id !== "implementations-list" ||
646 (!hasClass(e, "implementors-toggle") &&
647 !hasClass(e, "type-contents-toggle"))
652 sectionIsCollapsed = true;
653 innerToggle.title = "expand all docs";
655 innerToggle.children[0].innerText = labelForToggleButton(sectionIsCollapsed);
659 const toggles = document.getElementById(toggleAllDocsId);
661 toggles.onclick = toggleAllDocs;
664 const hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
665 const hideImplementations = getSettingValue("auto-hide-trait-implementations") === "true";
666 const hideLargeItemContents = getSettingValue("auto-hide-large-items") !== "false";
668 function setImplementorsTogglesOpen(id, open) {
669 const list = document.getElementById(id);
671 onEachLazy(list.getElementsByClassName("implementors-toggle"), e => {
677 if (hideImplementations) {
678 setImplementorsTogglesOpen("trait-implementations-list", false);
679 setImplementorsTogglesOpen("blanket-implementations-list", false);
682 onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
683 if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) {
686 if (hideMethodDocs && hasClass(e, "method-toggle")) {
692 const pageId = getPageId();
693 if (pageId !== null) {
694 expandSection(pageId);
698 window.rustdoc_add_line_numbers_to_examples = () => {
699 onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
700 const parent = x.parentNode;
701 const line_numbers = parent.querySelectorAll(".example-line-numbers");
702 if (line_numbers.length > 0) {
705 const count = x.textContent.split("\n").length;
707 for (let i = 0; i < count; ++i) {
710 const node = document.createElement("pre");
711 addClass(node, "example-line-numbers");
712 node.innerHTML = elems.join("\n");
713 parent.insertBefore(node, x);
717 window.rustdoc_remove_line_numbers_from_examples = () => {
718 onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
719 const parent = x.parentNode;
720 const line_numbers = parent.querySelectorAll(".example-line-numbers");
721 for (const node of line_numbers) {
722 parent.removeChild(node);
728 // To avoid checking on "rustdoc-line-numbers" value on every loop...
729 if (getSettingValue("line-numbers") === "true") {
730 window.rustdoc_add_line_numbers_to_examples();
734 let oldSidebarScrollPosition = null;
736 // Scroll locking used both here and in source-script.js
738 window.rustdocMobileScrollLock = function() {
739 const mobile_topbar = document.querySelector(".mobile-topbar");
740 if (window.innerWidth < window.RUSTDOC_MOBILE_BREAKPOINT) {
741 // This is to keep the scroll position on mobile.
742 oldSidebarScrollPosition = window.scrollY;
743 document.body.style.width = `${document.body.offsetWidth}px`;
744 document.body.style.position = "fixed";
745 document.body.style.top = `-${oldSidebarScrollPosition}px`;
747 mobile_topbar.style.top = `${oldSidebarScrollPosition}px`;
748 mobile_topbar.style.position = "relative";
751 oldSidebarScrollPosition = null;
755 window.rustdocMobileScrollUnlock = function() {
756 const mobile_topbar = document.querySelector(".mobile-topbar");
757 if (oldSidebarScrollPosition !== null) {
758 // This is to keep the scroll position on mobile.
759 document.body.style.width = "";
760 document.body.style.position = "";
761 document.body.style.top = "";
763 mobile_topbar.style.top = "";
764 mobile_topbar.style.position = "";
766 // The scroll position is lost when resetting the style, hence why we store it in
767 // `oldSidebarScrollPosition`.
768 window.scrollTo(0, oldSidebarScrollPosition);
769 oldSidebarScrollPosition = null;
773 function showSidebar() {
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.
794 function handleClick(id, f) {
795 const elem = document.getElementById(id);
797 elem.addEventListener("click", f);
800 handleClick(MAIN_ID, () => {
804 onEachLazy(document.getElementsByTagName("a"), el => {
805 // For clicks on internal links (<A> tags with a hash property), we expand the section we're
806 // jumping to *before* jumping there. We can't do this in onHashChange, because it changes
807 // the height of the document so we wind up scrolled to the wrong place.
809 el.addEventListener("click", () => {
810 expandSection(el.hash.slice(1));
816 onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"), el => {
817 el.addEventListener("click", e => {
818 if (e.target.tagName !== "SUMMARY" && e.target.tagName !== "A") {
824 onEachLazy(document.getElementsByClassName("notable-traits"), e => {
825 e.onclick = function() {
826 this.getElementsByClassName("notable-traits-tooltiptext")[0]
827 .classList.toggle("force-tooltip");
831 const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0];
832 if (sidebar_menu_toggle) {
833 sidebar_menu_toggle.addEventListener("click", () => {
834 const sidebar = document.getElementsByClassName("sidebar")[0];
835 if (!hasClass(sidebar, "shown")) {
843 function helpBlurHandler(event) {
844 blurHandler(event, getHelpButton(), window.hidePopoverMenus);
847 function buildHelpMenu() {
848 const book_info = document.createElement("span");
849 book_info.className = "top";
850 book_info.innerHTML = "You can find more information in \
851 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
854 ["?", "Show this help dialog"],
855 ["S", "Focus the search field"],
856 ["↑", "Move up in search results"],
857 ["↓", "Move down in search results"],
858 ["← / →", "Switch result tab (when results focused)"],
859 ["⏎", "Go to active search result"],
860 ["+", "Expand all sections"],
861 ["-", "Collapse all sections"],
864 .map((y, index) => ((index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " "))
865 .join("") + "</dt><dd>" + x[1] + "</dd>").join("");
866 const div_shortcuts = document.createElement("div");
867 addClass(div_shortcuts, "shortcuts");
868 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
871 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
872 restrict the search to a given item kind.",
873 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
874 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
875 and <code>const</code>.",
876 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
877 <code>-> vec</code>)",
878 "Search multiple things at once by splitting your query with comma (e.g., \
879 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
880 "You can look for items with an exact name by putting double quotes around \
881 your request: <code>\"string\"</code>",
882 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
883 ].map(x => "<p>" + x + "</p>").join("");
884 const div_infos = document.createElement("div");
885 addClass(div_infos, "infos");
886 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
888 const rustdoc_version = document.createElement("span");
889 rustdoc_version.className = "bottom";
890 const rustdoc_version_code = document.createElement("code");
891 rustdoc_version_code.innerText = "rustdoc " + getVar("rustdoc-version");
892 rustdoc_version.appendChild(rustdoc_version_code);
894 const container = document.createElement("div");
896 container.className = "popover";
898 container.id = "help";
899 container.style.display = "none";
901 const side_by_side = document.createElement("div");
902 side_by_side.className = "side-by-side";
903 side_by_side.appendChild(div_shortcuts);
904 side_by_side.appendChild(div_infos);
906 container.appendChild(book_info);
907 container.appendChild(side_by_side);
908 container.appendChild(rustdoc_version);
911 const help_section = document.createElement("section");
912 help_section.appendChild(container);
913 document.getElementById("main-content").appendChild(help_section);
914 container.style.display = "block";
916 const help_button = getHelpButton();
917 help_button.appendChild(container);
919 container.onblur = helpBlurHandler;
920 container.onclick = event => {
921 event.preventDefault();
923 help_button.onblur = helpBlurHandler;
924 help_button.children[0].onblur = helpBlurHandler;
931 * Hide all the popover menus.
933 window.hidePopoverMenus = function() {
934 onEachLazy(document.querySelectorAll(".search-container .popover"), elem => {
935 elem.style.display = "none";
940 * Returns the help menu element (not the button).
942 * @param {boolean} buildNeeded - If this argument is `false`, the help menu element won't be
943 * built if it doesn't exist.
945 * @return {HTMLElement}
947 function getHelpMenu(buildNeeded) {
948 let menu = getHelpButton().querySelector(".popover");
949 if (!menu && buildNeeded) {
950 menu = buildHelpMenu();
956 * Show the help popup menu.
958 function showHelp() {
959 const menu = getHelpMenu(true);
960 if (menu.style.display === "none") {
961 window.hidePopoverMenus();
962 menu.style.display = "";
968 document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
969 // Already on the help page, make help button a no-op.
970 const target = event.target;
971 if (target.tagName !== "A" ||
972 target.parentElement.id !== HELP_BUTTON_ID ||
978 event.preventDefault();
981 document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
982 // By default, have help button open docs in a popover.
983 // If user clicks with a moderator, though, use default browser behavior,
984 // probably opening in a new window or tab.
985 const target = event.target;
986 if (target.tagName !== "A" ||
987 target.parentElement.id !== HELP_BUTTON_ID ||
993 event.preventDefault();
994 const menu = getHelpMenu(true);
995 const shouldShowHelp = menu.style.display === "none";
996 if (shouldShowHelp) {
999 window.hidePopoverMenus();
1008 window.addEventListener("hashchange", onHashChange);
1009 searchState.setup();
1013 let reset_button_timeout = null;
1015 window.copy_path = but => {
1016 const parent = but.parentElement;
1019 onEach(parent.childNodes, child => {
1020 if (child.tagName === "A") {
1021 path.push(child.textContent);
1025 const el = document.createElement("textarea");
1026 el.value = path.join("::");
1027 el.setAttribute("readonly", "");
1028 // To not make it appear on the screen.
1029 el.style.position = "absolute";
1030 el.style.left = "-9999px";
1032 document.body.appendChild(el);
1034 document.execCommand("copy");
1035 document.body.removeChild(el);
1037 // There is always one children, but multiple childNodes.
1038 but.children[0].style.display = "none";
1041 if (but.childNodes.length < 2) {
1042 tmp = document.createTextNode("✓");
1043 but.appendChild(tmp);
1045 onEachLazy(but.childNodes, e => {
1046 if (e.nodeType === Node.TEXT_NODE) {
1051 tmp.textContent = "✓";
1054 if (reset_button_timeout !== null) {
1055 window.clearTimeout(reset_button_timeout);
1058 function reset_button() {
1059 tmp.textContent = "";
1060 reset_button_timeout = null;
1061 but.children[0].style.display = "";
1064 reset_button_timeout = window.setTimeout(reset_button, 1000);