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