]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/js/main.js
rustdoc: use a more compact encoding for implementors/trait.*.js
[rust.git] / src / librustdoc / html / static / js / main.js
1 // Local js definitions:
2 /* global addClass, getSettingValue, hasClass, searchState */
3 /* global onEach, onEachLazy, removeClass */
4
5 "use strict";
6
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");
11     if (el) {
12         return el.attributes["data-" + name].value;
13     } else {
14         return null;
15     }
16 }
17
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;
22 }
23
24 function hideMain() {
25     addClass(document.getElementById(MAIN_ID), "hidden");
26 }
27
28 function showMain() {
29     removeClass(document.getElementById(MAIN_ID), "hidden");
30 }
31
32 function elemIsInParent(elem, parent) {
33     while (elem && elem !== document.body) {
34         if (elem === parent) {
35             return true;
36         }
37         elem = elem.parentElement;
38     }
39     return false;
40 }
41
42 function blurHandler(event, parentElem, hideCallback) {
43     if (!elemIsInParent(document.activeElement, parentElem) &&
44         !elemIsInParent(event.relatedTarget, parentElem)
45     ) {
46         hideCallback();
47     }
48 }
49
50 (function() {
51     window.rootPath = getVar("root-path");
52     window.currentCrate = getVar("current-crate");
53 }());
54
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;
62     }
63 }
64
65 // Gets the human-readable string for the virtual-key code of the
66 // given KeyboardEvent, ev.
67 //
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.
73 //
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") {
77         return ev.key;
78     }
79
80     const c = ev.charCode || ev.keyCode;
81     if (c === 27) {
82         return "Escape";
83     }
84     return String.fromCharCode(c);
85 }
86
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";
92
93 function getSettingsButton() {
94     return document.getElementById(SETTINGS_BUTTON_ID);
95 }
96
97 function getHelpButton() {
98     return document.getElementById(HELP_BUTTON_ID);
99 }
100
101 // Returns the current URL without any query parameter or hash.
102 function getNakedUrl() {
103     return window.location.href.split("?")[0].split("#")[0];
104 }
105
106 /**
107  * This function inserts `newNode` after `referenceNode`. It doesn't work if `referenceNode`
108  * doesn't have a parent node.
109  *
110  * @param {HTMLElement} newNode
111  * @param {HTMLElement} referenceNode
112  */
113 function insertAfter(newNode, referenceNode) {
114     referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
115 }
116
117 /**
118  * This function creates a new `<section>` with the given `id` and `classes` if it doesn't already
119  * exist.
120  *
121  * More information about this in `switchDisplayedElement` documentation.
122  *
123  * @param {string} id
124  * @param {string} classes
125  */
126 function getOrCreateSection(id, classes) {
127     let el = document.getElementById(id);
128
129     if (!el) {
130         el = document.createElement("section");
131         el.id = id;
132         el.className = classes;
133         insertAfter(el, document.getElementById(MAIN_ID));
134     }
135     return el;
136 }
137
138 /**
139  * Returns the `<section>` element which contains the displayed element.
140  *
141  * @return {HTMLElement}
142  */
143 function getAlternativeDisplayElem() {
144     return getOrCreateSection(ALTERNATIVE_DISPLAY_ID, "content hidden");
145 }
146
147 /**
148  * Returns the `<section>` element which contains the not-displayed elements.
149  *
150  * @return {HTMLElement}
151  */
152 function getNotDisplayedElem() {
153     return getOrCreateSection(NOT_DISPLAYED_ID, "hidden");
154 }
155
156 /**
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.
162  *
163  * @param {HTMLElement} elemToDisplay
164  */
165 function switchDisplayedElement(elemToDisplay) {
166     const el = getAlternativeDisplayElem();
167
168     if (el.children.length > 0) {
169         getNotDisplayedElem().appendChild(el.firstElementChild);
170     }
171     if (elemToDisplay === null) {
172         addClass(el, "hidden");
173         showMain();
174         return;
175     }
176     el.appendChild(elemToDisplay);
177     hideMain();
178     removeClass(el, "hidden");
179 }
180
181 function browserSupportsHistoryApi() {
182     return window.history && typeof window.history.pushState === "function";
183 }
184
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);
192 }
193
194 (function() {
195     function loadScript(url) {
196         const script = document.createElement("script");
197         script.src = url;
198         document.head.append(script);
199     }
200
201     getSettingsButton().onclick = event => {
202         addClass(getSettingsButton(), "rotate");
203         event.preventDefault();
204         // Sending request for the CSS and the JS files at the same time so it will
205         // hopefully be loaded when the JS will generate the settings content.
206         loadCss("settings");
207         loadScript(resourcePath("settings", ".js"));
208     };
209
210     window.searchState = {
211         loadingText: "Loading search results...",
212         input: document.getElementsByClassName("search-input")[0],
213         outputElement: () => {
214             let el = document.getElementById("search");
215             if (!el) {
216                 el = document.createElement("section");
217                 el.id = "search";
218                 getNotDisplayedElem().appendChild(el);
219             }
220             return el;
221         },
222         title: document.title,
223         titleBeforeSearch: document.title,
224         timeout: null,
225         // On the search screen, so you remain on the last tab you opened.
226         //
227         // 0 for "In Names"
228         // 1 for "In Parameters"
229         // 2 for "In Return Types"
230         currentTab: 0,
231         // tab and back preserves the element that was focused.
232         focusedByTab: [null, null, null],
233         clearInputTimeout: () => {
234             if (searchState.timeout !== null) {
235                 clearTimeout(searchState.timeout);
236                 searchState.timeout = null;
237             }
238         },
239         isDisplayed: () => searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID,
240         // Sets the focus on the search bar at the top of the page
241         focus: () => {
242             searchState.input.focus();
243         },
244         // Removes the focus from the search bar.
245         defocus: () => {
246             searchState.input.blur();
247         },
248         showResults: search => {
249             if (search === null || typeof search === "undefined") {
250                 search = searchState.outputElement();
251             }
252             switchDisplayedElement(search);
253             searchState.mouseMovedAfterSearch = false;
254             document.title = searchState.title;
255         },
256         hideResults: () => {
257             switchDisplayedElement(null);
258             document.title = searchState.titleBeforeSearch;
259             // We also remove the query parameter from the URL.
260             if (browserSupportsHistoryApi()) {
261                 history.replaceState(null, window.currentCrate + " - Rust",
262                     getNakedUrl() + window.location.hash);
263             }
264         },
265         getQueryStringParams: () => {
266             const params = {};
267             window.location.search.substring(1).split("&").
268                 map(s => {
269                     const pair = s.split("=");
270                     params[decodeURIComponent(pair[0])] =
271                         typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
272                 });
273             return params;
274         },
275         setup: () => {
276             const search_input = searchState.input;
277             if (!searchState.input) {
278                 return;
279             }
280             let searchLoaded = false;
281             function loadSearch() {
282                 if (!searchLoaded) {
283                     searchLoaded = true;
284                     loadScript(resourcePath("search", ".js"));
285                     loadScript(resourcePath("search-index", ".js"));
286                 }
287             }
288
289             search_input.addEventListener("focus", () => {
290                 search_input.origPlaceholder = search_input.placeholder;
291                 search_input.placeholder = "Type your search here.";
292                 loadSearch();
293             });
294
295             if (search_input.value !== "") {
296                 loadSearch();
297             }
298
299             const params = searchState.getQueryStringParams();
300             if (params.search !== undefined) {
301                 const search = searchState.outputElement();
302                 search.innerHTML = "<h3 class=\"search-loading\">" +
303                     searchState.loadingText + "</h3>";
304                 searchState.showResults(search);
305                 loadSearch();
306             }
307         },
308     };
309
310     function getPageId() {
311         if (window.location.hash) {
312             const tmp = window.location.hash.replace(/^#/, "");
313             if (tmp.length > 0) {
314                 return tmp;
315             }
316         }
317         return null;
318     }
319
320     const toggleAllDocsId = "toggle-all-docs";
321     let savedHash = "";
322
323     function handleHashes(ev) {
324         if (ev !== null && searchState.isDisplayed() && ev.newURL) {
325             // This block occurs when clicking on an element in the navbar while
326             // in a search.
327             switchDisplayedElement(null);
328             const hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
329             if (browserSupportsHistoryApi()) {
330                 // `window.location.search`` contains all the query parameters, not just `search`.
331                 history.replaceState(null, "",
332                     getNakedUrl() + window.location.search + "#" + hash);
333             }
334             const elem = document.getElementById(hash);
335             if (elem) {
336                 elem.scrollIntoView();
337             }
338         }
339         // This part is used in case an element is not visible.
340         if (savedHash !== window.location.hash) {
341             savedHash = window.location.hash;
342             if (savedHash.length === 0) {
343                 return;
344             }
345             expandSection(savedHash.slice(1)); // we remove the '#'
346         }
347     }
348
349     function onHashChange(ev) {
350         // If we're in mobile mode, we should hide the sidebar in any case.
351         const sidebar = document.getElementsByClassName("sidebar")[0];
352         removeClass(sidebar, "shown");
353         handleHashes(ev);
354     }
355
356     function openParentDetails(elem) {
357         while (elem) {
358             if (elem.tagName === "DETAILS") {
359                 elem.open = true;
360             }
361             elem = elem.parentNode;
362         }
363     }
364
365     function expandSection(id) {
366         openParentDetails(document.getElementById(id));
367     }
368
369     function handleEscape(ev) {
370         searchState.clearInputTimeout();
371         switchDisplayedElement(null);
372         if (browserSupportsHistoryApi()) {
373             history.replaceState(null, window.currentCrate + " - Rust",
374                 getNakedUrl() + window.location.hash);
375         }
376         ev.preventDefault();
377         searchState.defocus();
378         window.hidePopoverMenus();
379     }
380
381     function handleShortcut(ev) {
382         // Don't interfere with browser shortcuts
383         const disableShortcuts = getSettingValue("disable-shortcuts") === "true";
384         if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts) {
385             return;
386         }
387
388         if (document.activeElement.tagName === "INPUT" &&
389             document.activeElement.type !== "checkbox") {
390             switch (getVirtualKey(ev)) {
391             case "Escape":
392                 handleEscape(ev);
393                 break;
394             }
395         } else {
396             switch (getVirtualKey(ev)) {
397             case "Escape":
398                 handleEscape(ev);
399                 break;
400
401             case "s":
402             case "S":
403                 ev.preventDefault();
404                 searchState.focus();
405                 break;
406
407             case "+":
408             case "-":
409                 ev.preventDefault();
410                 toggleAllDocs();
411                 break;
412
413             case "?":
414                 showHelp();
415                 break;
416
417             default:
418                 break;
419             }
420         }
421     }
422
423     document.addEventListener("keypress", handleShortcut);
424     document.addEventListener("keydown", handleShortcut);
425
426     function addSidebarItems() {
427         if (!window.SIDEBAR_ITEMS) {
428             return;
429         }
430         const sidebar = document.getElementsByClassName("sidebar-elems")[0];
431
432         /**
433          * Append to the sidebar a "block" of links - a heading along with a list (`<ul>`) of items.
434          *
435          * @param {string} shortty - A short type name, like "primitive", "mod", or "macro"
436          * @param {string} id - The HTML id of the corresponding section on the module page.
437          * @param {string} longty - A long, capitalized, plural name, like "Primitive Types",
438          *                          "Modules", or "Macros".
439          */
440         function block(shortty, id, longty) {
441             const filtered = window.SIDEBAR_ITEMS[shortty];
442             if (!filtered) {
443                 return;
444             }
445
446             const div = document.createElement("div");
447             div.className = "block " + shortty;
448             const h3 = document.createElement("h3");
449             h3.innerHTML = `<a href="index.html#${id}">${longty}</a>`;
450             div.appendChild(h3);
451             const ul = document.createElement("ul");
452
453             for (const item of filtered) {
454                 const name = item[0];
455                 const desc = item[1]; // can be null
456
457                 let klass = shortty;
458                 let path;
459                 if (shortty === "mod") {
460                     path = name + "/index.html";
461                 } else {
462                     path = shortty + "." + name + ".html";
463                 }
464                 const current_page = document.location.href.split("/").pop();
465                 if (path === current_page) {
466                     klass += " current";
467                 }
468                 const link = document.createElement("a");
469                 link.href = path;
470                 link.title = desc;
471                 link.className = klass;
472                 link.textContent = name;
473                 const li = document.createElement("li");
474                 li.appendChild(link);
475                 ul.appendChild(li);
476             }
477             div.appendChild(ul);
478             sidebar.appendChild(div);
479         }
480
481         if (sidebar) {
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");
496         }
497     }
498
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();
503
504         const TEXT_IDX = 0;
505         const SYNTHETIC_IDX = 1;
506         const TYPES_IDX = 2;
507
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.
511             //
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");
516                 if (!aliases) {
517                     return;
518                 }
519                 aliases.split(",").forEach(alias => {
520                     inlined_types.add(alias);
521                 });
522             });
523         }
524
525         let currentNbImpls = implementors.getElementsByClassName("impl").length;
526         const traitName = document.querySelector("h1.fqn > .in-band > .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 ignoreExternCrates = document
533             .querySelector("script[data-ignore-extern-crates]")
534             .getAttribute("data-ignore-extern-crates");
535         for (const lib of libs) {
536             if (lib === window.currentCrate || ignoreExternCrates.indexOf(lib) !== -1) {
537                 continue;
538             }
539             const structs = imp[lib];
540
541             struct_loop:
542             for (const struct of structs) {
543                 const list = struct[SYNTHETIC_IDX] ? synthetic_implementors : implementors;
544
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;
551                         }
552                         inlined_types.add(struct_type);
553                     }
554                 }
555
556                 const code = document.createElement("h3");
557                 code.innerHTML = struct[TEXT_IDX];
558                 addClass(code, "code-header");
559                 addClass(code, "in-band");
560
561                 onEachLazy(code.getElementsByTagName("a"), elem => {
562                     const href = elem.getAttribute("href");
563
564                     if (href && href.indexOf("http") !== 0) {
565                         elem.setAttribute("href", window.rootPath + href);
566                     }
567                 });
568
569                 const currentId = baseIdName + currentNbImpls;
570                 const anchor = document.createElement("a");
571                 anchor.href = "#" + currentId;
572                 addClass(anchor, "anchor");
573
574                 const display = document.createElement("div");
575                 display.id = currentId;
576                 addClass(display, "impl");
577                 display.appendChild(anchor);
578                 display.appendChild(code);
579                 list.appendChild(display);
580                 currentNbImpls += 1;
581             }
582         }
583     };
584     if (window.pending_implementors) {
585         window.register_implementors(window.pending_implementors);
586     }
587
588     function addSidebarCrates() {
589         if (!window.ALL_CRATES) {
590             return;
591         }
592         const sidebarElems = document.getElementsByClassName("sidebar-elems")[0];
593         if (!sidebarElems) {
594             return;
595         }
596         // Draw a convenient sidebar of known crates if we have a listing
597         const div = document.createElement("div");
598         div.className = "block crate";
599         div.innerHTML = "<h3>Crates</h3>";
600         const ul = document.createElement("ul");
601         div.appendChild(ul);
602
603         for (const crate of window.ALL_CRATES) {
604             let klass = "crate";
605             if (window.rootPath !== "./" && crate === window.currentCrate) {
606                 klass += " current";
607             }
608             const link = document.createElement("a");
609             link.href = window.rootPath + crate + "/index.html";
610             link.className = klass;
611             link.textContent = crate;
612
613             const li = document.createElement("li");
614             li.appendChild(link);
615             ul.appendChild(li);
616         }
617         sidebarElems.appendChild(div);
618     }
619
620
621     function labelForToggleButton(sectionIsCollapsed) {
622         if (sectionIsCollapsed) {
623             // button will expand the section
624             return "+";
625         }
626         // button will collapse the section
627         // note that this text is also set in the HTML template in ../render/mod.rs
628         return "\u2212"; // "\u2212" is "−" minus sign
629     }
630
631     function toggleAllDocs() {
632         const innerToggle = document.getElementById(toggleAllDocsId);
633         if (!innerToggle) {
634             return;
635         }
636         let sectionIsCollapsed = false;
637         if (hasClass(innerToggle, "will-expand")) {
638             removeClass(innerToggle, "will-expand");
639             onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
640                 if (!hasClass(e, "type-contents-toggle")) {
641                     e.open = true;
642                 }
643             });
644             innerToggle.title = "collapse all docs";
645         } else {
646             addClass(innerToggle, "will-expand");
647             onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
648                 if (e.parentNode.id !== "implementations-list" ||
649                     (!hasClass(e, "implementors-toggle") &&
650                      !hasClass(e, "type-contents-toggle"))
651                 ) {
652                     e.open = false;
653                 }
654             });
655             sectionIsCollapsed = true;
656             innerToggle.title = "expand all docs";
657         }
658         innerToggle.children[0].innerText = labelForToggleButton(sectionIsCollapsed);
659     }
660
661     (function() {
662         const toggles = document.getElementById(toggleAllDocsId);
663         if (toggles) {
664             toggles.onclick = toggleAllDocs;
665         }
666
667         const hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
668         const hideImplementations = getSettingValue("auto-hide-trait-implementations") === "true";
669         const hideLargeItemContents = getSettingValue("auto-hide-large-items") !== "false";
670
671         function setImplementorsTogglesOpen(id, open) {
672             const list = document.getElementById(id);
673             if (list !== null) {
674                 onEachLazy(list.getElementsByClassName("implementors-toggle"), e => {
675                     e.open = open;
676                 });
677             }
678         }
679
680         if (hideImplementations) {
681             setImplementorsTogglesOpen("trait-implementations-list", false);
682             setImplementorsTogglesOpen("blanket-implementations-list", false);
683         }
684
685         onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
686             if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) {
687                 e.open = true;
688             }
689             if (hideMethodDocs && hasClass(e, "method-toggle")) {
690                 e.open = false;
691             }
692
693         });
694
695         const pageId = getPageId();
696         if (pageId !== null) {
697             expandSection(pageId);
698         }
699     }());
700
701     (function() {
702         // To avoid checking on "rustdoc-line-numbers" value on every loop...
703         let lineNumbersFunc = () => {};
704         if (getSettingValue("line-numbers") === "true") {
705             lineNumbersFunc = x => {
706                 const count = x.textContent.split("\n").length;
707                 const elems = [];
708                 for (let i = 0; i < count; ++i) {
709                     elems.push(i + 1);
710                 }
711                 const node = document.createElement("pre");
712                 addClass(node, "line-number");
713                 node.innerHTML = elems.join("\n");
714                 x.parentNode.insertBefore(node, x);
715             };
716         }
717         onEachLazy(document.getElementsByClassName("rust-example-rendered"), e => {
718             if (hasClass(e, "compile_fail")) {
719                 e.addEventListener("mouseover", function() {
720                     this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
721                 });
722                 e.addEventListener("mouseout", function() {
723                     this.parentElement.previousElementSibling.childNodes[0].style.color = "";
724                 });
725             } else if (hasClass(e, "ignore")) {
726                 e.addEventListener("mouseover", function() {
727                     this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
728                 });
729                 e.addEventListener("mouseout", function() {
730                     this.parentElement.previousElementSibling.childNodes[0].style.color = "";
731                 });
732             }
733             lineNumbersFunc(e);
734         });
735     }());
736
737     function hideSidebar() {
738         const sidebar = document.getElementsByClassName("sidebar")[0];
739         removeClass(sidebar, "shown");
740     }
741
742     function handleClick(id, f) {
743         const elem = document.getElementById(id);
744         if (elem) {
745             elem.addEventListener("click", f);
746         }
747     }
748     handleClick(MAIN_ID, () => {
749         hideSidebar();
750     });
751
752     onEachLazy(document.getElementsByTagName("a"), el => {
753         // For clicks on internal links (<A> tags with a hash property), we expand the section we're
754         // jumping to *before* jumping there. We can't do this in onHashChange, because it changes
755         // the height of the document so we wind up scrolled to the wrong place.
756         if (el.hash) {
757             el.addEventListener("click", () => {
758                 expandSection(el.hash.slice(1));
759                 hideSidebar();
760             });
761         }
762     });
763
764     onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"), el => {
765         el.addEventListener("click", e => {
766             if (e.target.tagName !== "SUMMARY" && e.target.tagName !== "A") {
767                 e.preventDefault();
768             }
769         });
770     });
771
772     onEachLazy(document.getElementsByClassName("notable-traits"), e => {
773         e.onclick = function() {
774             this.getElementsByClassName("notable-traits-tooltiptext")[0]
775                 .classList.toggle("force-tooltip");
776         };
777     });
778
779     const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0];
780     if (sidebar_menu_toggle) {
781         sidebar_menu_toggle.addEventListener("click", () => {
782             const sidebar = document.getElementsByClassName("sidebar")[0];
783             if (!hasClass(sidebar, "shown")) {
784                 addClass(sidebar, "shown");
785             } else {
786                 removeClass(sidebar, "shown");
787             }
788         });
789     }
790
791     function helpBlurHandler(event) {
792         blurHandler(event, getHelpButton(), window.hidePopoverMenus);
793     }
794
795     function buildHelpMenu() {
796         const book_info = document.createElement("span");
797         book_info.className = "top";
798         book_info.innerHTML = "You can find more information in \
799             <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
800
801         const shortcuts = [
802             ["?", "Show this help dialog"],
803             ["S", "Focus the search field"],
804             ["↑", "Move up in search results"],
805             ["↓", "Move down in search results"],
806             ["← / →", "Switch result tab (when results focused)"],
807             ["&#9166;", "Go to active search result"],
808             ["+", "Expand all sections"],
809             ["-", "Collapse all sections"],
810         ].map(x => "<dt>" +
811             x[0].split(" ")
812                 .map((y, index) => ((index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " "))
813                 .join("") + "</dt><dd>" + x[1] + "</dd>").join("");
814         const div_shortcuts = document.createElement("div");
815         addClass(div_shortcuts, "shortcuts");
816         div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
817
818         const infos = [
819             "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
820              restrict the search to a given item kind.",
821             "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
822              <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
823              and <code>const</code>.",
824             "Search functions by type signature (e.g., <code>vec -&gt; usize</code> or \
825              <code>-&gt; vec</code>)",
826             "Search multiple things at once by splitting your query with comma (e.g., \
827              <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
828             "You can look for items with an exact name by putting double quotes around \
829              your request: <code>\"string\"</code>",
830             "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
831         ].map(x => "<p>" + x + "</p>").join("");
832         const div_infos = document.createElement("div");
833         addClass(div_infos, "infos");
834         div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
835
836         const rustdoc_version = document.createElement("span");
837         rustdoc_version.className = "bottom";
838         const rustdoc_version_code = document.createElement("code");
839         rustdoc_version_code.innerText = "rustdoc " + getVar("rustdoc-version");
840         rustdoc_version.appendChild(rustdoc_version_code);
841
842         const container = document.createElement("div");
843         container.className = "popover";
844         container.style.display = "none";
845
846         const side_by_side = document.createElement("div");
847         side_by_side.className = "side-by-side";
848         side_by_side.appendChild(div_shortcuts);
849         side_by_side.appendChild(div_infos);
850
851         container.appendChild(book_info);
852         container.appendChild(side_by_side);
853         container.appendChild(rustdoc_version);
854
855         const help_button = getHelpButton();
856         help_button.appendChild(container);
857
858         container.onblur = helpBlurHandler;
859         container.onclick = event => {
860             event.preventDefault();
861         };
862         help_button.onblur = helpBlurHandler;
863         help_button.children[0].onblur = helpBlurHandler;
864
865         return container;
866     }
867
868     /**
869      * Hide all the popover menus.
870      */
871     window.hidePopoverMenus = function() {
872         onEachLazy(document.querySelectorAll(".search-container .popover"), elem => {
873             elem.style.display = "none";
874         });
875     };
876
877     /**
878      * Returns the help menu element (not the button).
879      *
880      * @param {boolean} buildNeeded - If this argument is `false`, the help menu element won't be
881      *                                built if it doesn't exist.
882      *
883      * @return {HTMLElement}
884      */
885     function getHelpMenu(buildNeeded) {
886         let menu = getHelpButton().querySelector(".popover");
887         if (!menu && buildNeeded) {
888             menu = buildHelpMenu();
889         }
890         return menu;
891     }
892
893     /**
894      * Show the help popup menu.
895      */
896     function showHelp() {
897         const menu = getHelpMenu(true);
898         if (menu.style.display === "none") {
899             window.hidePopoverMenus();
900             menu.style.display = "";
901         }
902     }
903
904     document.querySelector(`#${HELP_BUTTON_ID} > button`).addEventListener("click", event => {
905         const target = event.target;
906         if (target.tagName !== "BUTTON" || target.parentElement.id !== HELP_BUTTON_ID) {
907             return;
908         }
909         const menu = getHelpMenu(true);
910         const shouldShowHelp = menu.style.display === "none";
911         if (shouldShowHelp) {
912             showHelp();
913         } else {
914             window.hidePopoverMenus();
915         }
916     });
917
918     setMobileTopbar();
919     addSidebarItems();
920     addSidebarCrates();
921     onHashChange(null);
922     window.addEventListener("hashchange", onHashChange);
923     searchState.setup();
924 }());
925
926 (function() {
927     let reset_button_timeout = null;
928
929     window.copy_path = but => {
930         const parent = but.parentElement;
931         const path = [];
932
933         onEach(parent.childNodes, child => {
934             if (child.tagName === "A") {
935                 path.push(child.textContent);
936             }
937         });
938
939         const el = document.createElement("textarea");
940         el.value = path.join("::");
941         el.setAttribute("readonly", "");
942         // To not make it appear on the screen.
943         el.style.position = "absolute";
944         el.style.left = "-9999px";
945
946         document.body.appendChild(el);
947         el.select();
948         document.execCommand("copy");
949         document.body.removeChild(el);
950
951         // There is always one children, but multiple childNodes.
952         but.children[0].style.display = "none";
953
954         let tmp;
955         if (but.childNodes.length < 2) {
956             tmp = document.createTextNode("✓");
957             but.appendChild(tmp);
958         } else {
959             onEachLazy(but.childNodes, e => {
960                 if (e.nodeType === Node.TEXT_NODE) {
961                     tmp = e;
962                     return true;
963                 }
964             });
965             tmp.textContent = "✓";
966         }
967
968         if (reset_button_timeout !== null) {
969             window.clearTimeout(reset_button_timeout);
970         }
971
972         function reset_button() {
973             tmp.textContent = "";
974             reset_button_timeout = null;
975             but.children[0].style.display = "";
976         }
977
978         reset_button_timeout = window.setTimeout(reset_button, 1000);
979     };
980 }());