2 /* global ALIASES, currentCrate, rootPath */
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */
7 /* global hideThemeButtonState, showThemeButtonState */
9 if (!String.prototype.startsWith) {
10 String.prototype.startsWith = function(searchString, position) {
11 position = position || 0;
12 return this.indexOf(searchString, position) === position;
15 if (!String.prototype.endsWith) {
16 String.prototype.endsWith = function(suffix, length) {
17 var l = length || this.length;
18 return this.indexOf(suffix, l - suffix.length) !== -1;
22 if (!DOMTokenList.prototype.add) {
23 DOMTokenList.prototype.add = function(className) {
24 if (className && !hasClass(this, className)) {
25 if (this.className && this.className.length > 0) {
26 this.className += " " + className;
28 this.className = className;
34 if (!DOMTokenList.prototype.remove) {
35 DOMTokenList.prototype.remove = function(className) {
36 if (className && this.className) {
37 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
43 function getSearchInput() {
44 return document.getElementsByClassName("search-input")[0];
47 function getSearchElement() {
48 return document.getElementById("search");
51 function getThemesElement() {
52 return document.getElementById("theme-choices");
55 function getThemePickerElement() {
56 return document.getElementById("theme-picker");
59 // Sets the focus on the search bar at the top of the page
60 function focusSearchBar() {
61 getSearchInput().focus();
64 // Removes the focus from the search bar
65 function defocusSearchBar() {
66 getSearchInput().blur();
72 // This mapping table should match the discriminants of
73 // `rustdoc::html::item_type::ItemType` type in Rust.
74 var itemTypes = ["mod",
101 var disableShortcuts = getSettingValue("disable-shortcuts") === "true";
102 var search_input = getSearchInput();
103 var searchTimeout = null;
104 var toggleAllDocsId = "toggle-all-docs";
106 // On the search screen, so you remain on the last tab you opened.
109 // 1 for "In Parameters"
110 // 2 for "In Return Types"
113 var mouseMovedAfterSearch = true;
115 var titleBeforeSearch = document.title;
117 function clearInputTimeout() {
118 if (searchTimeout !== null) {
119 clearTimeout(searchTimeout);
120 searchTimeout = null;
124 function getPageId() {
125 if (window.location.hash) {
126 var tmp = window.location.hash.replace(/^#/, "");
127 if (tmp.length > 0) {
134 function showSidebar() {
135 var elems = document.getElementsByClassName("sidebar-elems")[0];
137 addClass(elems, "show-it");
139 var sidebar = document.getElementsByClassName("sidebar")[0];
141 addClass(sidebar, "mobile");
142 var filler = document.getElementById("sidebar-filler");
144 var div = document.createElement("div");
145 div.id = "sidebar-filler";
146 sidebar.appendChild(div);
151 function hideSidebar() {
152 var elems = document.getElementsByClassName("sidebar-elems")[0];
154 removeClass(elems, "show-it");
156 var sidebar = document.getElementsByClassName("sidebar")[0];
157 removeClass(sidebar, "mobile");
158 var filler = document.getElementById("sidebar-filler");
162 document.getElementsByTagName("body")[0].style.marginTop = "";
165 function showSearchResults(search) {
166 if (search === null || typeof search === 'undefined') {
167 search = getSearchElement();
169 addClass(main, "hidden");
170 removeClass(search, "hidden");
171 mouseMovedAfterSearch = false;
174 function hideSearchResults(search) {
175 if (search === null || typeof search === 'undefined') {
176 search = getSearchElement();
178 addClass(search, "hidden");
179 removeClass(main, "hidden");
182 // used for special search precedence
183 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
184 var TY_KEYWORD = itemTypes.indexOf("keyword");
186 function getQueryStringParams() {
188 window.location.search.substring(1).split("&").
190 var pair = s.split("=");
191 params[decodeURIComponent(pair[0])] =
192 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
197 function browserSupportsHistoryApi() {
198 return window.history && typeof window.history.pushState === "function";
201 function isHidden(elem) {
202 return elem.offsetHeight === 0;
205 var main = document.getElementById("main");
208 function handleHashes(ev) {
210 var search = getSearchElement();
211 if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
212 // This block occurs when clicking on an element in the navbar while
214 hideSearchResults(search);
215 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
216 if (browserSupportsHistoryApi()) {
217 history.replaceState(hash, "", "?search=#" + hash);
219 elem = document.getElementById(hash);
221 elem.scrollIntoView();
224 // This part is used in case an element is not visible.
225 if (savedHash !== window.location.hash) {
226 savedHash = window.location.hash;
227 if (savedHash.length === 0) {
230 elem = document.getElementById(savedHash.slice(1)); // we remove the '#'
231 if (!elem || !isHidden(elem)) {
234 var parent = elem.parentNode;
235 if (parent && hasClass(parent, "impl-items")) {
236 // In case this is a trait implementation item, we first need to toggle
237 // the "Show hidden undocumented items".
238 onEachLazy(parent.getElementsByClassName("collapsed"), function(e) {
239 if (e.parentNode === parent) {
240 // Only click on the toggle we're looking for.
245 if (isHidden(elem)) {
246 // The whole parent is collapsed. We need to click on its toggle as well!
247 if (hasClass(parent.lastElementChild, "collapse-toggle")) {
248 parent.lastElementChild.click();
255 function highlightSourceLines(match, ev) {
256 if (typeof match === "undefined") {
257 // If we're in mobile mode, we should hide the sidebar in any case.
259 match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
264 var from = parseInt(match[1], 10);
266 if (typeof match[2] !== "undefined") {
267 to = parseInt(match[2], 10);
274 var elem = document.getElementById(from);
279 var x = document.getElementById(from);
284 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
285 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
286 removeClass(i_e, "line-highlighted");
289 for (var i = from; i <= to; ++i) {
290 elem = document.getElementById(i);
294 addClass(elem, "line-highlighted");
298 function onHashChange(ev) {
299 // If we're in mobile mode, we should hide the sidebar in any case.
301 var match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
303 return highlightSourceLines(match, ev);
308 function expandSection(id) {
309 var elem = document.getElementById(id);
310 if (elem && isHidden(elem)) {
311 var h3 = elem.parentNode.previousElementSibling;
312 if (h3 && h3.tagName !== "H3") {
313 h3 = h3.previousElementSibling; // skip div.docblock
317 var collapses = h3.getElementsByClassName("collapse-toggle");
318 if (collapses.length > 0) {
319 // The element is not visible, we need to make it appear!
320 collapseDocs(collapses[0], "show");
326 // Gets the human-readable string for the virtual-key code of the
327 // given KeyboardEvent, ev.
329 // This function is meant as a polyfill for KeyboardEvent#key,
330 // since it is not supported in Trident. We also test for
331 // KeyboardEvent#keyCode because the handleShortcut handler is
332 // also registered for the keydown event, because Blink doesn't fire
333 // keypress on hitting the Escape key.
335 // So I guess you could say things are getting pretty interoperable.
336 function getVirtualKey(ev) {
337 if ("key" in ev && typeof ev.key != "undefined") {
341 var c = ev.charCode || ev.keyCode;
345 return String.fromCharCode(c);
348 function getHelpElement() {
350 return document.getElementById("help");
353 function displayHelp(display, ev, help) {
354 help = help ? help : getHelpElement();
355 if (display === true) {
356 if (hasClass(help, "hidden")) {
358 removeClass(help, "hidden");
359 addClass(document.body, "blur");
361 } else if (hasClass(help, "hidden") === false) {
363 addClass(help, "hidden");
364 removeClass(document.body, "blur");
368 function handleEscape(ev) {
369 var help = getHelpElement();
370 var search = getSearchElement();
371 if (hasClass(help, "hidden") === false) {
372 displayHelp(false, ev, help);
373 } else if (hasClass(search, "hidden") === false) {
376 hideSearchResults(search);
377 document.title = titleBeforeSearch;
380 hideThemeButtonState();
383 function handleShortcut(ev) {
384 // Don't interfere with browser shortcuts
385 if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts === true) {
389 if (document.activeElement.tagName === "INPUT") {
390 switch (getVirtualKey(ev)) {
396 switch (getVirtualKey(ev)) {
403 displayHelp(false, ev);
415 displayHelp(true, ev);
420 displayHelp(false, ev);
422 var themePicker = getThemePickerElement();
428 var themePicker = getThemePickerElement();
429 if (themePicker.parentNode.contains(ev.target)) {
430 handleThemeKeyDown(ev);
436 function handleThemeKeyDown(ev) {
437 var active = document.activeElement;
438 var themes = getThemesElement();
439 switch (getVirtualKey(ev)) {
442 if (active.previousElementSibling && ev.target.id !== "theme-picker") {
443 active.previousElementSibling.focus();
445 showThemeButtonState();
446 themes.lastElementChild.focus();
451 if (active.nextElementSibling && ev.target.id !== "theme-picker") {
452 active.nextElementSibling.focus();
454 showThemeButtonState();
455 themes.firstElementChild.focus();
461 if (ev.target.id === "theme-picker" && themes.style.display === "none") {
463 showThemeButtonState();
464 themes.firstElementChild.focus();
469 themes.firstElementChild.focus();
473 themes.lastElementChild.focus();
475 // The escape key is handled in handleEscape, not here,
476 // so that pressing escape will close the menu even if it isn't focused
480 function findParentElement(elem, tagName) {
482 if (elem && elem.tagName === tagName) {
485 elem = elem.parentNode;
490 document.addEventListener("keypress", handleShortcut);
491 document.addEventListener("keydown", handleShortcut);
493 function resetMouseMoved(ev) {
494 mouseMovedAfterSearch = true;
497 document.addEventListener("mousemove", resetMouseMoved);
499 var handleSourceHighlight = (function() {
500 var prev_line_id = 0;
502 var set_fragment = function(name) {
503 var x = window.scrollX,
505 if (browserSupportsHistoryApi()) {
506 history.replaceState(null, null, "#" + name);
507 highlightSourceLines();
509 location.replace("#" + name);
511 // Prevent jumps when selecting one or many lines
512 window.scrollTo(x, y);
515 return function(ev) {
516 var cur_line_id = parseInt(ev.target.id, 10);
519 if (ev.shiftKey && prev_line_id) {
520 // Swap selection if needed
521 if (prev_line_id > cur_line_id) {
522 var tmp = prev_line_id;
523 prev_line_id = cur_line_id;
527 set_fragment(prev_line_id + "-" + cur_line_id);
529 prev_line_id = cur_line_id;
531 set_fragment(cur_line_id);
536 document.addEventListener("click", function(ev) {
537 if (hasClass(ev.target, "help-button")) {
538 displayHelp(true, ev);
539 } else if (hasClass(ev.target, "collapse-toggle")) {
540 collapseDocs(ev.target, "toggle");
541 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
542 collapseDocs(ev.target.parentNode, "toggle");
543 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
544 handleSourceHighlight(ev);
545 } else if (hasClass(getHelpElement(), "hidden") === false) {
546 var help = getHelpElement();
547 var is_inside_help_popup = ev.target !== help && help.contains(ev.target);
548 if (is_inside_help_popup === false) {
549 addClass(help, "hidden");
550 removeClass(document.body, "blur");
553 // Making a collapsed element visible on onhashchange seems
555 var a = findParentElement(ev.target, "A");
557 expandSection(a.hash.replace(/^#/, ""));
563 var x = document.getElementsByClassName("version-selector");
565 x[0].onchange = function() {
567 url = document.location.href,
569 len = rootPath.match(/\.\.\//g).length + 1;
571 for (i = 0; i < len; ++i) {
572 match = url.match(/\/[^\/]*$/);
574 stripped = match[0] + stripped;
576 url = url.substring(0, url.length - match[0].length);
579 var selectedVersion = document.getElementsByClassName("version-selector")[0].value;
580 url += "/" + selectedVersion + stripped;
582 document.location.href = url;
588 * A function to compute the Levenshtein distance between two strings
589 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
590 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
591 * This code is an unmodified version of the code written by Marco de Wit
592 * and was found at http://stackoverflow.com/a/18514751/745719
594 var levenshtein_row2 = [];
595 function levenshtein(s1, s2) {
599 var s1_len = s1.length, s2_len = s2.length;
600 if (s1_len && s2_len) {
601 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
602 while (i1 < s1_len) {
605 while (i2 < s2_len) {
606 c2 = s2.charCodeAt(i2);
610 for (i1 = 0; i1 < s1_len; ++i1) {
611 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
613 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
619 return s1_len + s2_len;
622 window.initSearch = function(rawSearchIndex) {
623 var MAX_LEV_DISTANCE = 3;
624 var MAX_RESULTS = 200;
625 var GENERICS_DATA = 1;
629 var NO_TYPE_FILTER = -1;
630 var currentResults, index, searchIndex;
632 var params = getQueryStringParams();
634 // Populate search bar with query string search term when provided,
635 // but only if the input bar is empty. This avoid the obnoxious issue
636 // where you start trying to do a search, and the index loads, and
637 // suddenly your search is gone!
638 if (search_input.value === "") {
639 search_input.value = params.search || "";
643 * Executes the query and builds an index of results
644 * @param {[Object]} query [The user query]
645 * @param {[type]} searchWords [The list of search words to query
647 * @param {[type]} filterCrates [Crate to search in if defined]
648 * @return {[type]} [A search index of results]
650 function execQuery(query, searchWords, filterCrates) {
651 function itemTypeFromName(typename) {
652 var length = itemTypes.length;
653 for (var i = 0; i < length; ++i) {
654 if (itemTypes[i] === typename) {
658 return NO_TYPE_FILTER;
661 var valLower = query.query.toLowerCase(),
663 typeFilter = itemTypeFromName(query.type),
664 results = {}, results_in_args = {}, results_returned = {},
665 split = valLower.split("::");
667 var length = split.length;
668 for (var z = 0; z < length; ++z) {
669 if (split[z] === "") {
675 function transformResults(results, isType) {
677 var length = results.length;
678 for (var i = 0; i < length; ++i) {
679 if (results[i].id > -1) {
680 var obj = searchIndex[results[i].id];
681 obj.lev = results[i].lev;
682 if (isType !== true || obj.type) {
683 var res = buildHrefAndPath(obj);
684 obj.displayPath = pathSplitter(res[0]);
685 obj.fullPath = obj.displayPath + obj.name;
686 // To be sure than it some items aren't considered as duplicate.
687 obj.fullPath += "|" + obj.ty;
690 if (out.length >= MAX_RESULTS) {
699 function sortResults(results, isType) {
701 for (var entry in results) {
702 if (hasOwnProperty(results, entry)) {
703 ar.push(results[entry]);
708 var nresults = results.length;
709 for (i = 0; i < nresults; ++i) {
710 results[i].word = searchWords[results[i].id];
711 results[i].item = searchIndex[results[i].id] || {};
713 // if there are no results then return to default and fail
714 if (results.length === 0) {
718 results.sort(function(aaa, bbb) {
721 // sort by exact match with regard to the last word (mismatch goes later)
722 a = (aaa.word !== val);
723 b = (bbb.word !== val);
724 if (a !== b) { return a - b; }
726 // Sort by non levenshtein results and then levenshtein results by the distance
727 // (less changes required to match means higher rankings)
730 if (a !== b) { return a - b; }
732 // sort by crate (non-current crate goes later)
733 a = (aaa.item.crate !== window.currentCrate);
734 b = (bbb.item.crate !== window.currentCrate);
735 if (a !== b) { return a - b; }
737 // sort by item name length (longer goes later)
740 if (a !== b) { return a - b; }
742 // sort by item name (lexicographically larger goes later)
745 if (a !== b) { return (a > b ? +1 : -1); }
747 // sort by index of keyword in item name (no literal occurrence goes later)
750 if (a !== b) { return a - b; }
751 // (later literal occurrence, if any, goes later)
754 if (a !== b) { return a - b; }
756 // special precedence for primitive and keyword pages
757 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
758 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
761 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
762 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
766 // sort by description (no description goes later)
767 a = (aaa.item.desc === "");
768 b = (bbb.item.desc === "");
769 if (a !== b) { return a - b; }
771 // sort by type (later occurrence in `itemTypes` goes later)
774 if (a !== b) { return a - b; }
776 // sort by path (lexicographically larger goes later)
779 if (a !== b) { return (a > b ? +1 : -1); }
785 var length = results.length;
786 for (i = 0; i < length; ++i) {
787 var result = results[i];
789 // this validation does not make sense when searching by types
790 if (result.dontValidate) {
793 var name = result.item.name.toLowerCase(),
794 path = result.item.path.toLowerCase(),
795 parent = result.item.parent;
797 if (isType !== true &&
798 validateResult(name, path, split, parent) === false)
803 return transformResults(results);
806 function extractGenerics(val) {
807 val = val.toLowerCase();
808 if (val.indexOf("<") !== -1) {
809 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
811 name: val.substring(0, val.indexOf("<")),
812 generics: values.split(/\s*,\s*/),
821 function getObjectFromId(id) {
822 if (typeof id === "number") {
823 return searchIndex[id];
828 function checkGenerics(obj, val) {
829 // The names match, but we need to be sure that all generics kinda
831 var lev_distance = MAX_LEV_DISTANCE + 1;
832 if (val.generics.length > 0) {
833 if (obj.length > GENERICS_DATA &&
834 obj[GENERICS_DATA].length >= val.generics.length) {
835 var elems = obj[GENERICS_DATA].slice(0);
838 // We need to find the type that matches the most to remove it in order
840 var vlength = val.generics.length;
841 for (var y = 0; y < vlength; ++y) {
842 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
843 var elength = elems.length;
844 var firstGeneric = getObjectFromId(val.generics[y]).name;
845 for (var x = 0; x < elength; ++x) {
846 var tmp_lev = levenshtein(getObjectFromId(elems[x]).name,
848 if (tmp_lev < lev.lev) {
853 if (lev.pos !== -1) {
854 elems.splice(lev.pos, 1);
855 lev_distance = Math.min(lev.lev, lev_distance);
859 return MAX_LEV_DISTANCE + 1;
862 return Math.ceil(total / done);
865 return MAX_LEV_DISTANCE + 1;
868 // Check for type name and type generics (if any).
869 function checkType(obj, val, literalSearch) {
870 var lev_distance = MAX_LEV_DISTANCE + 1;
872 if (obj[NAME] === val.name) {
873 if (literalSearch === true) {
874 if (val.generics && val.generics.length !== 0) {
875 if (obj.length > GENERICS_DATA &&
876 obj[GENERICS_DATA].length >= val.generics.length) {
877 var elems = obj[GENERICS_DATA].slice(0);
880 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
882 var firstGeneric = getObjectFromId(val.generics[y]).name;
883 for (x = 0; allFound === false && x < elems.length; ++x) {
884 allFound = getObjectFromId(elems[x]).name === firstGeneric;
886 if (allFound === true) {
887 elems.splice(x - 1, 1);
890 if (allFound === true) {
899 // If the type has generics but don't match, then it won't return at this point.
900 // Otherwise, `checkGenerics` will return 0 and it'll return.
901 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
902 var tmp_lev = checkGenerics(obj, val);
903 if (tmp_lev <= MAX_LEV_DISTANCE) {
910 // Names didn't match so let's check if one of the generic types could.
911 if (literalSearch === true) {
912 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
913 var length = obj[GENERICS_DATA].length;
914 for (x = 0; x < length; ++x) {
915 if (obj[GENERICS_DATA][x] === val.name) {
922 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
923 if (lev_distance <= MAX_LEV_DISTANCE) {
924 // The generics didn't match but the name kinda did so we give it
925 // a levenshtein distance value that isn't *this* good so it goes
926 // into the search results but not too high.
927 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
928 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
929 // We can check if the type we're looking for is inside the generics!
930 var olength = obj[GENERICS_DATA].length;
931 for (x = 0; x < olength; ++x) {
932 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
936 // Now whatever happens, the returned distance is "less good" so we should mark it
937 // as such, and so we add 1 to the distance to make it "less good".
938 return lev_distance + 1;
941 function findArg(obj, val, literalSearch, typeFilter) {
942 var lev_distance = MAX_LEV_DISTANCE + 1;
944 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
945 var length = obj.type[INPUTS_DATA].length;
946 for (var i = 0; i < length; i++) {
947 var tmp = obj.type[INPUTS_DATA][i];
948 if (typePassesFilter(typeFilter, tmp[1]) === false) {
951 tmp = checkType(tmp, val, literalSearch);
952 if (literalSearch === true) {
958 lev_distance = Math.min(tmp, lev_distance);
959 if (lev_distance === 0) {
964 return literalSearch === true ? false : lev_distance;
967 function checkReturned(obj, val, literalSearch, typeFilter) {
968 var lev_distance = MAX_LEV_DISTANCE + 1;
970 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
971 var ret = obj.type[OUTPUT_DATA];
972 if (typeof ret[0] === "string") {
975 for (var x = 0; x < ret.length; ++x) {
977 if (typePassesFilter(typeFilter, tmp[1]) === false) {
980 tmp = checkType(tmp, val, literalSearch);
981 if (literalSearch === true) {
987 lev_distance = Math.min(tmp, lev_distance);
988 if (lev_distance === 0) {
993 return literalSearch === true ? false : lev_distance;
996 function checkPath(contains, lastElem, ty) {
997 if (contains.length === 0) {
1000 var ret_lev = MAX_LEV_DISTANCE + 1;
1001 var path = ty.path.split("::");
1003 if (ty.parent && ty.parent.name) {
1004 path.push(ty.parent.name.toLowerCase());
1007 var length = path.length;
1008 var clength = contains.length;
1009 if (clength > length) {
1010 return MAX_LEV_DISTANCE + 1;
1012 for (var i = 0; i < length; ++i) {
1013 if (i + clength > length) {
1017 var aborted = false;
1018 for (var x = 0; x < clength; ++x) {
1019 var lev = levenshtein(path[i + x], contains[x]);
1020 if (lev > MAX_LEV_DISTANCE) {
1026 if (aborted === false) {
1027 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1033 function typePassesFilter(filter, type) {
1035 if (filter <= NO_TYPE_FILTER) return true;
1038 if (filter === type) return true;
1040 // Match related items
1041 var name = itemTypes[type];
1042 switch (itemTypes[filter]) {
1044 return name === "associatedconstant";
1046 return name === "method" || name === "tymethod";
1048 return name === "primitive" || name === "associatedtype";
1050 return name === "traitalias";
1057 function generateId(ty) {
1058 if (ty.parent && ty.parent.name) {
1059 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
1061 return itemTypes[ty.ty] + ty.path + ty.name;
1064 function createAliasFromItem(item) {
1071 parent: item.parent,
1077 function handleAliases(ret, query, filterCrates) {
1078 // We separate aliases and crate aliases because we want to have current crate
1079 // aliases to be before the others in the displayed results.
1081 var crateAliases = [];
1083 if (filterCrates !== undefined) {
1084 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
1085 for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) {
1087 createAliasFromItem(
1088 searchIndex[ALIASES[filterCrates][query.search][i]]));
1092 Object.keys(ALIASES).forEach(function(crate) {
1093 if (ALIASES[crate][query.search]) {
1094 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
1095 for (i = 0; i < ALIASES[crate][query.search].length; ++i) {
1097 createAliasFromItem(
1098 searchIndex[ALIASES[crate][query.search][i]]));
1104 var sortFunc = function(aaa, bbb) {
1105 if (aaa.path < bbb.path) {
1107 } else if (aaa.path === bbb.path) {
1112 crateAliases.sort(sortFunc);
1113 aliases.sort(sortFunc);
1115 var pushFunc = function(alias) {
1116 alias.alias = query.raw;
1117 var res = buildHrefAndPath(alias);
1118 alias.displayPath = pathSplitter(res[0]);
1119 alias.fullPath = alias.displayPath + alias.name;
1120 alias.href = res[1];
1122 ret.others.unshift(alias);
1123 if (ret.others.length > MAX_RESULTS) {
1127 onEach(aliases, pushFunc);
1128 onEach(crateAliases, pushFunc);
1131 // quoted values mean literal search
1132 var nSearchWords = searchWords.length;
1138 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
1139 val.charAt(val.length - 1) === val.charAt(0))
1141 val = extractGenerics(val.substr(1, val.length - 2));
1142 for (i = 0; i < nSearchWords; ++i) {
1143 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1146 in_args = findArg(searchIndex[i], val, true, typeFilter);
1147 returned = checkReturned(searchIndex[i], val, true, typeFilter);
1148 ty = searchIndex[i];
1149 fullId = generateId(ty);
1151 if (searchWords[i] === val.name
1152 && typePassesFilter(typeFilter, searchIndex[i].ty)
1153 && results[fullId] === undefined) {
1160 if (in_args === true && results_in_args[fullId] === undefined) {
1161 results_in_args[fullId] = {
1167 if (returned === true && results_returned[fullId] === undefined) {
1168 results_returned[fullId] = {
1175 query.inputs = [val];
1178 // searching by type
1179 } else if (val.search("->") > -1) {
1180 var trimmer = function(s) { return s.trim(); };
1181 var parts = val.split("->").map(trimmer);
1182 var input = parts[0];
1183 // sort inputs so that order does not matter
1184 var inputs = input.split(",").map(trimmer).sort();
1185 for (i = 0; i < inputs.length; ++i) {
1186 inputs[i] = extractGenerics(inputs[i]);
1188 var output = extractGenerics(parts[1]);
1190 for (i = 0; i < nSearchWords; ++i) {
1191 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1194 var type = searchIndex[i].type;
1195 ty = searchIndex[i];
1199 fullId = generateId(ty);
1201 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
1202 if (output.name === "*" || returned === true) {
1204 var is_module = false;
1206 if (input === "*") {
1209 var allFound = true;
1210 for (var it = 0; allFound === true && it < inputs.length; it++) {
1211 allFound = checkType(type, inputs[it], true);
1215 if (in_args === true) {
1216 results_in_args[fullId] = {
1222 if (returned === true) {
1223 results_returned[fullId] = {
1229 if (is_module === true) {
1238 query.inputs = inputs.map(function(input) {
1241 query.output = output.name;
1243 query.inputs = [val];
1246 // gather matching search results up to a certain maximum
1247 val = val.replace(/\_/g, "");
1249 var valGenerics = extractGenerics(val);
1251 var paths = valLower.split("::");
1253 for (j = 0; j < paths.length; ++j) {
1254 if (paths[j] === "") {
1259 val = paths[paths.length - 1];
1260 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
1263 for (j = 0; j < nSearchWords; ++j) {
1264 ty = searchIndex[j];
1265 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1269 if (paths.length > 1) {
1270 lev = checkPath(contains, paths[paths.length - 1], ty);
1271 if (lev > MAX_LEV_DISTANCE) {
1273 } else if (lev > 0) {
1278 returned = MAX_LEV_DISTANCE + 1;
1279 in_args = MAX_LEV_DISTANCE + 1;
1281 // we want lev results to go lower than others
1282 lev = MAX_LEV_DISTANCE + 1;
1283 fullId = generateId(ty);
1285 if (searchWords[j].indexOf(split[i]) > -1 ||
1286 searchWords[j].indexOf(val) > -1 ||
1287 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1289 // filter type: ... queries
1290 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1291 index = searchWords[j].replace(/_/g, "").indexOf(val);
1294 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1295 if (typePassesFilter(typeFilter, ty.ty) === false) {
1296 lev = MAX_LEV_DISTANCE + 1;
1301 in_args = findArg(ty, valGenerics, false, typeFilter);
1302 returned = checkReturned(ty, valGenerics, false, typeFilter);
1305 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1306 if (val.length < 6) {
1312 if (in_args <= MAX_LEV_DISTANCE) {
1313 if (results_in_args[fullId] === undefined) {
1314 results_in_args[fullId] = {
1320 results_in_args[fullId].lev =
1321 Math.min(results_in_args[fullId].lev, in_args);
1323 if (returned <= MAX_LEV_DISTANCE) {
1324 if (results_returned[fullId] === undefined) {
1325 results_returned[fullId] = {
1331 results_returned[fullId].lev =
1332 Math.min(results_returned[fullId].lev, returned);
1334 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1335 if (index !== -1 && paths.length < 2) {
1338 if (results[fullId] === undefined) {
1345 results[fullId].lev = Math.min(results[fullId].lev, lev);
1351 "in_args": sortResults(results_in_args, true),
1352 "returned": sortResults(results_returned, true),
1353 "others": sortResults(results),
1355 handleAliases(ret, query, filterCrates);
1360 * Validate performs the following boolean logic. For example:
1361 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1362 * exists in (name || path || parent) OR => ("file" && "open") exists in
1365 * This could be written functionally, but I wanted to minimise
1366 * functions on stack.
1368 * @param {[string]} name [The name of the result]
1369 * @param {[string]} path [The path of the result]
1370 * @param {[string]} keys [The keys to be used (["file", "open"])]
1371 * @param {[object]} parent [The parent of the result]
1372 * @return {[boolean]} [Whether the result is valid or not]
1374 function validateResult(name, path, keys, parent) {
1375 for (var i = 0; i < keys.length; ++i) {
1376 // each check is for validation so we negate the conditions and invalidate
1378 // check for an exact name match
1379 name.indexOf(keys[i]) > -1 ||
1380 // then an exact path match
1381 path.indexOf(keys[i]) > -1 ||
1382 // next if there is a parent, check for exact parent match
1383 (parent !== undefined && parent.name !== undefined &&
1384 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1385 // lastly check to see if the name was a levenshtein match
1386 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1393 function getQuery(raw) {
1394 var matches, type, query;
1397 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1399 type = matches[1].replace(/^const$/, "constant");
1400 query = query.substring(matches[0].length);
1411 function initSearchNav() {
1414 var click_func = function(e) {
1416 // to retrieve the real "owner" of the event.
1417 while (el.tagName !== "TR") {
1420 var dst = e.target.getElementsByTagName("a");
1421 if (dst.length < 1) {
1425 if (window.location.pathname === dst.pathname) {
1426 hideSearchResults();
1427 document.location.href = dst.href;
1430 var mouseover_func = function(e) {
1431 if (mouseMovedAfterSearch) {
1433 // to retrieve the real "owner" of the event.
1434 while (el.tagName !== "TR") {
1437 clearTimeout(hoverTimeout);
1438 hoverTimeout = setTimeout(function() {
1439 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1440 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1441 removeClass(i_e, "highlighted");
1444 addClass(el, "highlighted");
1448 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1449 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1450 i_e.onclick = click_func;
1451 i_e.onmouseover = mouseover_func;
1455 search_input.onkeydown = function(e) {
1456 // "actives" references the currently highlighted item in each search tab.
1457 // Each array in "actives" represents a tab.
1458 var actives = [[], [], []];
1459 // "current" is used to know which tab we're looking into.
1461 onEachLazy(document.getElementById("results").childNodes, function(e) {
1462 onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
1463 actives[current].push(h_e);
1468 if (e.which === 38) { // up
1469 if (!actives[currentTab].length ||
1470 !actives[currentTab][0].previousElementSibling) {
1474 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1475 removeClass(actives[currentTab][0], "highlighted");
1477 } else if (e.which === 40) { // down
1478 if (!actives[currentTab].length) {
1479 var results = document.getElementById("results").childNodes;
1480 if (results.length > 0) {
1481 var res = results[currentTab].getElementsByClassName("result");
1482 if (res.length > 0) {
1483 addClass(res[0], "highlighted");
1486 } else if (actives[currentTab][0].nextElementSibling) {
1487 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1488 removeClass(actives[currentTab][0], "highlighted");
1491 } else if (e.which === 13) { // return
1492 if (actives[currentTab].length) {
1493 document.location.href =
1494 actives[currentTab][0].getElementsByTagName("a")[0].href;
1496 } else if (e.which === 9) { // tab
1498 printTab(currentTab > 0 ? currentTab - 1 : 2);
1500 printTab(currentTab > 1 ? 0 : currentTab + 1);
1503 } else if (e.which === 16) { // shift
1504 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1505 } else if (actives[currentTab].length > 0) {
1506 removeClass(actives[currentTab][0], "highlighted");
1511 function buildHrefAndPath(item) {
1514 var type = itemTypes[item.ty];
1515 var name = item.name;
1516 var path = item.path;
1518 if (type === "mod") {
1519 displayPath = path + "::";
1520 href = rootPath + path.replace(/::/g, "/") + "/" +
1521 name + "/index.html";
1522 } else if (type === "primitive" || type === "keyword") {
1524 href = rootPath + path.replace(/::/g, "/") +
1525 "/" + type + "." + name + ".html";
1526 } else if (type === "externcrate") {
1528 href = rootPath + name + "/index.html";
1529 } else if (item.parent !== undefined) {
1530 var myparent = item.parent;
1531 var anchor = "#" + type + "." + name;
1532 var parentType = itemTypes[myparent.ty];
1533 var pageType = parentType;
1534 var pageName = myparent.name;
1536 if (parentType === "primitive") {
1537 displayPath = myparent.name + "::";
1538 } else if (type === "structfield" && parentType === "variant") {
1539 // Structfields belonging to variants are special: the
1540 // final path element is the enum name.
1541 var splitPath = item.path.split("::");
1542 var enumName = splitPath.pop();
1543 path = splitPath.join("::");
1544 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1545 anchor = "#variant." + myparent.name + ".field." + name;
1547 pageName = enumName;
1549 displayPath = path + "::" + myparent.name + "::";
1551 href = rootPath + path.replace(/::/g, "/") +
1556 displayPath = item.path + "::";
1557 href = rootPath + item.path.replace(/::/g, "/") +
1558 "/" + type + "." + name + ".html";
1560 return [displayPath, href];
1563 function escape(content) {
1564 var h1 = document.createElement("h1");
1565 h1.textContent = content;
1566 return h1.innerHTML;
1569 function pathSplitter(path) {
1570 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1571 if (tmp.endsWith("<span>")) {
1572 return tmp.slice(0, tmp.length - 6);
1577 function addTab(array, query, display) {
1578 var extraStyle = "";
1579 if (display === false) {
1580 extraStyle = " style=\"display: none;\"";
1584 var duplicates = {};
1586 if (array.length > 0) {
1587 output = "<table class=\"search-results\"" + extraStyle + ">";
1589 array.forEach(function(item) {
1593 type = itemTypes[item.ty];
1595 if (item.is_alias !== true) {
1596 if (duplicates[item.fullPath]) {
1599 duplicates[item.fullPath] = true;
1603 output += "<tr class=\"" + type + " result\"><td>" +
1604 "<a href=\"" + item.href + "\">" +
1605 (item.is_alias === true ?
1606 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1607 "class=\"grey\"><i> - see </i></span>") : "") +
1608 item.displayPath + "<span class=\"" + type + "\">" +
1609 name + "</span></a></td><td>" +
1610 "<a href=\"" + item.href + "\">" +
1611 "<span class=\"desc\">" + escape(item.desc) +
1612 " </span></a></td></tr>";
1614 output += "</table>";
1616 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1617 "Try on <a href=\"https://duckduckgo.com/?q=" +
1618 encodeURIComponent("rust " + query.query) +
1619 "\">DuckDuckGo</a>?<br/><br/>" +
1620 "Or try looking in one of these:<ul><li>The <a " +
1621 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1622 " for technical details about the language.</li><li><a " +
1623 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1624 "Example</a> for expository code examples.</a></li><li>The <a " +
1625 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1626 "introductions to language features and the language itself.</li><li><a " +
1627 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1628 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1630 return [output, length];
1633 function makeTabHeader(tabNb, text, nbElems) {
1634 if (currentTab === tabNb) {
1635 return "<div class=\"selected\">" + text +
1636 " <div class=\"count\">(" + nbElems + ")</div></div>";
1638 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1641 function showResults(results) {
1642 var search = getSearchElement();
1643 if (results.others.length === 1
1644 && getSettingValue("go-to-only-result") === "true"
1645 // By default, the search DOM element is "empty" (meaning it has no children not
1646 // text content). Once a search has been run, it won't be empty, even if you press
1647 // ESC or empty the search input (which also "cancels" the search).
1648 && (!search.firstChild || search.firstChild.innerText !== getSearchLoadingText()))
1650 var elem = document.createElement("a");
1651 elem.href = results.others[0].href;
1652 elem.style.display = "none";
1653 // For firefox, we need the element to be in the DOM so it can be clicked.
1654 document.body.appendChild(elem);
1658 var query = getQuery(search_input.value);
1660 currentResults = query.id;
1662 var ret_others = addTab(results.others, query);
1663 var ret_in_args = addTab(results.in_args, query, false);
1664 var ret_returned = addTab(results.returned, query, false);
1666 var output = "<h1>Results for " + escape(query.query) +
1667 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1668 "<div id=\"titles\">" +
1669 makeTabHeader(0, "In Names", ret_others[1]) +
1670 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1671 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1672 "</div><div id=\"results\">" +
1673 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1675 search.innerHTML = output;
1676 showSearchResults(search);
1677 var tds = search.getElementsByTagName("td");
1679 if (tds.length > 0) {
1680 td_width = tds[0].offsetWidth;
1682 var width = search.offsetWidth - 40 - td_width;
1683 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1684 e.style.width = width + "px";
1687 var elems = document.getElementById("titles").childNodes;
1688 elems[0].onclick = function() { printTab(0); };
1689 elems[1].onclick = function() { printTab(1); };
1690 elems[2].onclick = function() { printTab(2); };
1691 printTab(currentTab);
1694 function execSearch(query, searchWords, filterCrates) {
1695 function getSmallest(arrays, positions, notDuplicates) {
1698 for (var it = 0; it < positions.length; ++it) {
1699 if (arrays[it].length > positions[it] &&
1700 (start === null || start > arrays[it][positions[it]].lev) &&
1701 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1702 start = arrays[it][positions[it]].lev;
1708 function mergeArrays(arrays) {
1711 var notDuplicates = {};
1713 for (var x = 0; x < arrays.length; ++x) {
1716 while (ret.length < MAX_RESULTS) {
1717 var smallest = getSmallest(arrays, positions, notDuplicates);
1719 if (smallest === null) {
1722 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1723 if (arrays[x].length > positions[x] &&
1724 arrays[x][positions[x]].lev === smallest &&
1725 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1726 ret.push(arrays[x][positions[x]]);
1727 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1735 var queries = query.raw.split(",");
1742 for (var i = 0; i < queries.length; ++i) {
1743 query = queries[i].trim();
1744 if (query.length !== 0) {
1745 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1747 results.in_args.push(tmp.in_args);
1748 results.returned.push(tmp.returned);
1749 results.others.push(tmp.others);
1752 if (queries.length > 1) {
1754 "in_args": mergeArrays(results.in_args),
1755 "returned": mergeArrays(results.returned),
1756 "others": mergeArrays(results.others),
1760 "in_args": results.in_args[0],
1761 "returned": results.returned[0],
1762 "others": results.others[0],
1766 function getFilterCrates() {
1767 var elem = document.getElementById("crate-search");
1769 if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1775 function search(e, forced) {
1776 var params = getQueryStringParams();
1777 var query = getQuery(search_input.value.trim());
1783 if (query.query.length === 0) {
1786 if (forced !== true && query.id === currentResults) {
1787 if (query.query.length > 0) {
1788 putBackSearch(search_input);
1793 // Update document title to maintain a meaningful browser history
1794 document.title = "Results for " + query.query + " - Rust";
1796 // Because searching is incremental by character, only the most
1797 // recent search query is added to the browser history.
1798 if (browserSupportsHistoryApi()) {
1799 if (!history.state && !params.search) {
1800 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1802 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1806 var filterCrates = getFilterCrates();
1807 showResults(execSearch(query, index, filterCrates));
1810 function buildIndex(rawSearchIndex) {
1812 var searchWords = [];
1814 var currentIndex = 0;
1816 for (var crate in rawSearchIndex) {
1817 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1821 searchWords.push(crate);
1824 ty: 1, // == ExternCrate
1827 desc: rawSearchIndex[crate].doc,
1832 // an array of [(Number) item type,
1834 // (String) full path or empty string for previous path,
1835 // (String) description,
1836 // (Number | null) the parent path index to `paths`]
1837 // (Object | null) the type of the function (if any)
1838 var items = rawSearchIndex[crate].i;
1839 // an array of [(Number) item type,
1841 var paths = rawSearchIndex[crate].p;
1842 // a array of [(String) alias name
1843 // [Number] index to items]
1844 var aliases = rawSearchIndex[crate].a;
1846 // convert `rawPaths` entries into object form
1847 var len = paths.length;
1848 for (i = 0; i < len; ++i) {
1849 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1852 // convert `items` into an object form, and construct word indices.
1854 // before any analysis is performed lets gather the search terms to
1855 // search against apart from the rest of the data. This is a quick
1856 // operation that is cached for the life of the page state so that
1857 // all other search operations have access to this cached data for
1858 // faster analysis operations
1861 for (i = 0; i < len; ++i) {
1862 var rawRow = items[i];
1864 rawRow[2] = lastPath;
1872 parent: paths[rawRow[4]],
1875 searchIndex.push(row);
1876 if (typeof row.name === "string") {
1877 var word = row.name.toLowerCase();
1878 searchWords.push(word);
1880 searchWords.push("");
1882 lastPath = row.path;
1887 ALIASES[crate] = {};
1888 var j, local_aliases;
1889 for (var alias_name in aliases) {
1890 if (!aliases.hasOwnProperty(alias_name)) { continue; }
1892 if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1893 ALIASES[crate][alias_name] = [];
1895 local_aliases = aliases[alias_name];
1896 for (j = 0; j < local_aliases.length; ++j) {
1897 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1901 currentIndex += crateSize;
1906 function startSearch() {
1907 var callback = function() {
1908 clearInputTimeout();
1909 if (search_input.value.length === 0) {
1910 if (browserSupportsHistoryApi()) {
1911 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1913 hideSearchResults();
1915 searchTimeout = setTimeout(search, 500);
1918 search_input.onkeyup = callback;
1919 search_input.oninput = callback;
1920 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1922 clearInputTimeout();
1925 search_input.onchange = function(e) {
1926 if (e.target !== document.activeElement) {
1927 // To prevent doing anything when it's from a blur event.
1930 // Do NOT e.preventDefault() here. It will prevent pasting.
1931 clearInputTimeout();
1932 // zero-timeout necessary here because at the time of event handler execution the
1933 // pasted content is not in the input field yet. Shouldn’t make any difference for
1935 setTimeout(search, 0);
1937 search_input.onpaste = search_input.onchange;
1939 var selectCrate = document.getElementById("crate-search");
1941 selectCrate.onchange = function() {
1942 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1943 search(undefined, true);
1947 // Push and pop states are used to add search results to the browser
1949 if (browserSupportsHistoryApi()) {
1950 // Store the previous <title> so we can revert back to it later.
1951 var previousTitle = document.title;
1953 window.addEventListener("popstate", function(e) {
1954 var params = getQueryStringParams();
1955 // Revert to the previous title manually since the History
1956 // API ignores the title parameter.
1957 document.title = previousTitle;
1958 // When browsing forward to search results the previous
1959 // search will be repeated, so the currentResults are
1960 // cleared to ensure the search is successful.
1961 currentResults = null;
1962 // Synchronize search bar with query string state and
1963 // perform the search. This will empty the bar if there's
1964 // nothing there, which lets you really go back to a
1965 // previous state with nothing in the bar.
1966 if (params.search && params.search.length > 0) {
1967 search_input.value = params.search;
1968 // Some browsers fire "onpopstate" for every page load
1969 // (Chrome), while others fire the event only when actually
1970 // popping a state (Firefox), which is why search() is
1971 // called both here and at the end of the startSearch()
1975 search_input.value = "";
1976 // When browsing back from search results the main page
1977 // visibility must be reset.
1978 hideSearchResults();
1985 index = buildIndex(rawSearchIndex);
1988 // Draw a convenient sidebar of known crates if we have a listing
1989 if (rootPath === "../" || rootPath === "./") {
1990 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1992 var div = document.createElement("div");
1993 div.className = "block crate";
1994 div.innerHTML = "<h3>Crates</h3>";
1995 var ul = document.createElement("ul");
1996 div.appendChild(ul);
1999 for (var crate in rawSearchIndex) {
2000 if (!hasOwnProperty(rawSearchIndex, crate)) {
2006 for (var i = 0; i < crates.length; ++i) {
2007 var klass = "crate";
2008 if (rootPath !== "./" && crates[i] === window.currentCrate) {
2009 klass += " current";
2011 var link = document.createElement("a");
2012 link.href = rootPath + crates[i] + "/index.html";
2013 link.title = rawSearchIndex[crates[i]].doc;
2014 link.className = klass;
2015 link.textContent = crates[i];
2017 var li = document.createElement("li");
2018 li.appendChild(link);
2021 sidebar.appendChild(div);
2027 // delayed sidebar rendering.
2028 window.initSidebarItems = function(items) {
2029 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
2030 var current = window.sidebarCurrent;
2032 function block(shortty, longty) {
2033 var filtered = items[shortty];
2038 var div = document.createElement("div");
2039 div.className = "block " + shortty;
2040 var h3 = document.createElement("h3");
2041 h3.textContent = longty;
2042 div.appendChild(h3);
2043 var ul = document.createElement("ul");
2045 var length = filtered.length;
2046 for (var i = 0; i < length; ++i) {
2047 var item = filtered[i];
2049 var desc = item[1]; // can be null
2051 var klass = shortty;
2052 if (name === current.name && shortty === current.ty) {
2053 klass += " current";
2056 if (shortty === "mod") {
2057 path = name + "/index.html";
2059 path = shortty + "." + name + ".html";
2061 var link = document.createElement("a");
2062 link.href = current.relpath + path;
2064 link.className = klass;
2065 link.textContent = name;
2066 var li = document.createElement("li");
2067 li.appendChild(link);
2070 div.appendChild(ul);
2072 sidebar.appendChild(div);
2076 block("primitive", "Primitive Types");
2077 block("mod", "Modules");
2078 block("macro", "Macros");
2079 block("struct", "Structs");
2080 block("enum", "Enums");
2081 block("union", "Unions");
2082 block("constant", "Constants");
2083 block("static", "Statics");
2084 block("trait", "Traits");
2085 block("fn", "Functions");
2086 block("type", "Type Definitions");
2087 block("foreigntype", "Foreign Types");
2088 block("keyword", "Keywords");
2089 block("traitalias", "Trait Aliases");
2092 window.register_implementors = function(imp) {
2093 var implementors = document.getElementById("implementors-list");
2094 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
2096 if (synthetic_implementors) {
2097 // This `inlined_types` variable is used to avoid having the same implementation
2098 // showing up twice. For example "String" in the "Sync" doc page.
2100 // By the way, this is only used by and useful for traits implemented automatically
2101 // (like "Send" and "Sync").
2102 var inlined_types = new Set();
2103 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) {
2104 var aliases = el.getAttribute("aliases");
2108 aliases.split(",").forEach(function(alias) {
2109 inlined_types.add(alias);
2114 var libs = Object.getOwnPropertyNames(imp);
2115 var llength = libs.length;
2116 for (var i = 0; i < llength; ++i) {
2117 if (libs[i] === currentCrate) { continue; }
2118 var structs = imp[libs[i]];
2120 var slength = structs.length;
2122 for (var j = 0; j < slength; ++j) {
2123 var struct = structs[j];
2125 var list = struct.synthetic ? synthetic_implementors : implementors;
2127 if (struct.synthetic) {
2128 var stlength = struct.types.length;
2129 for (var k = 0; k < stlength; k++) {
2130 if (inlined_types.has(struct.types[k])) {
2131 continue struct_loop;
2133 inlined_types.add(struct.types[k]);
2137 var code = document.createElement("code");
2138 code.innerHTML = struct.text;
2140 var x = code.getElementsByTagName("a");
2141 var xlength = x.length;
2142 for (var it = 0; it < xlength; it++) {
2143 var href = x[it].getAttribute("href");
2144 if (href && href.indexOf("http") !== 0) {
2145 x[it].setAttribute("href", rootPath + href);
2148 var display = document.createElement("h3");
2149 addClass(display, "impl");
2150 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
2151 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
2152 "</tbody></table></span>";
2153 list.appendChild(display);
2157 if (window.pending_implementors) {
2158 window.register_implementors(window.pending_implementors);
2161 function labelForToggleButton(sectionIsCollapsed) {
2162 if (sectionIsCollapsed) {
2163 // button will expand the section
2166 // button will collapse the section
2167 // note that this text is also set in the HTML template in render.rs
2168 return "\u2212"; // "\u2212" is "−" minus sign
2171 function onEveryMatchingChild(elem, className, func) {
2172 if (elem && className && func) {
2173 var length = elem.childNodes.length;
2174 var nodes = elem.childNodes;
2175 for (var i = 0; i < length; ++i) {
2176 if (hasClass(nodes[i], className)) {
2179 onEveryMatchingChild(nodes[i], className, func);
2185 function toggleAllDocs(pageId, fromAutoCollapse) {
2186 var innerToggle = document.getElementById(toggleAllDocsId);
2190 if (hasClass(innerToggle, "will-expand")) {
2191 updateLocalStorage("rustdoc-collapse", "false");
2192 removeClass(innerToggle, "will-expand");
2193 onEveryMatchingChild(innerToggle, "inner", function(e) {
2194 e.innerHTML = labelForToggleButton(false);
2196 innerToggle.title = "collapse all docs";
2197 if (fromAutoCollapse !== true) {
2198 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2199 collapseDocs(e, "show");
2203 updateLocalStorage("rustdoc-collapse", "true");
2204 addClass(innerToggle, "will-expand");
2205 onEveryMatchingChild(innerToggle, "inner", function(e) {
2206 var parent = e.parentNode;
2207 var superParent = null;
2210 superParent = parent.parentNode;
2212 if (!parent || !superParent || superParent.id !== "main" ||
2213 hasClass(parent, "impl") === false) {
2214 e.innerHTML = labelForToggleButton(true);
2217 innerToggle.title = "expand all docs";
2218 if (fromAutoCollapse !== true) {
2219 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2220 var parent = e.parentNode;
2221 var superParent = null;
2224 superParent = parent.parentNode;
2226 if (!parent || !superParent || superParent.id !== "main" ||
2227 hasClass(parent, "impl") === false) {
2228 collapseDocs(e, "hide", pageId);
2235 function collapseDocs(toggle, mode, pageId) {
2236 if (!toggle || !toggle.parentNode) {
2240 function adjustToggle(arg) {
2241 return function(e) {
2242 if (hasClass(e, "toggle-label")) {
2244 e.style.display = "inline-block";
2246 e.style.display = "none";
2249 if (hasClass(e, "inner")) {
2250 e.innerHTML = labelForToggleButton(arg);
2255 function implHider(addOrRemove, fullHide) {
2256 return function(n) {
2257 var is_method = hasClass(n, "method") || fullHide;
2258 if (is_method || hasClass(n, "type")) {
2259 if (is_method === true) {
2261 addClass(n, "hidden-by-impl-hider");
2263 removeClass(n, "hidden-by-impl-hider");
2266 var ns = n.nextElementSibling;
2267 while (ns && (hasClass(ns, "docblock") || hasClass(ns, "stability"))) {
2269 addClass(ns, "hidden-by-impl-hider");
2271 removeClass(ns, "hidden-by-impl-hider");
2273 ns = ns.nextElementSibling;
2281 if (hasClass(toggle.parentNode, "impl") === false) {
2282 relatedDoc = toggle.parentNode.nextElementSibling;
2283 if (hasClass(relatedDoc, "stability")) {
2284 relatedDoc = relatedDoc.nextElementSibling;
2286 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
2287 if (mode === "toggle") {
2288 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2294 if (action === "hide") {
2295 addClass(relatedDoc, "hidden-by-usual-hider");
2296 onEachLazy(toggle.childNodes, adjustToggle(true));
2297 addClass(toggle.parentNode, "collapsed");
2298 } else if (action === "show") {
2299 removeClass(relatedDoc, "hidden-by-usual-hider");
2300 removeClass(toggle.parentNode, "collapsed");
2301 onEachLazy(toggle.childNodes, adjustToggle(false));
2305 // we are collapsing the impl block(s).
2307 var parentElem = toggle.parentNode;
2308 relatedDoc = parentElem;
2309 var docblock = relatedDoc.nextElementSibling;
2311 while (hasClass(relatedDoc, "impl-items") === false) {
2312 relatedDoc = relatedDoc.nextElementSibling;
2315 if (!relatedDoc && hasClass(docblock, "docblock") === false) {
2319 // Hide all functions, but not associated types/consts.
2321 if (mode === "toggle") {
2322 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2323 hasClass(docblock, "hidden-by-impl-hider")) {
2330 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2331 if (action === "show") {
2332 removeClass(relatedDoc, "fns-now-collapsed");
2333 removeClass(docblock, "hidden-by-usual-hider");
2334 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2335 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2336 } else if (action === "hide") {
2337 addClass(relatedDoc, "fns-now-collapsed");
2338 addClass(docblock, "hidden-by-usual-hider");
2339 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2340 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2345 function collapser(pageId, e, collapse) {
2346 // inherent impl ids are like "impl" or impl-<number>'.
2347 // they will never be hidden by default.
2348 var n = e.parentElement;
2349 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2350 // Automatically minimize all non-inherent impls
2351 if (collapse || hasClass(n, "impl")) {
2352 collapseDocs(e, "hide", pageId);
2357 function autoCollapse(pageId, collapse) {
2359 toggleAllDocs(pageId, true);
2360 } else if (getSettingValue("auto-hide-trait-implementations") !== "false") {
2361 var impl_list = document.getElementById("trait-implementations-list");
2363 if (impl_list !== null) {
2364 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2365 collapser(pageId, e, collapse);
2369 var blanket_list = document.getElementById("blanket-implementations-list");
2371 if (blanket_list !== null) {
2372 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2373 collapser(pageId, e, collapse);
2379 function insertAfter(newNode, referenceNode) {
2380 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2383 function createSimpleToggle(sectionIsCollapsed) {
2384 var toggle = document.createElement("a");
2385 toggle.href = "javascript:void(0)";
2386 toggle.className = "collapse-toggle";
2387 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2392 function createToggle(toggle, otherMessage, fontSize, extraClass, show) {
2393 var span = document.createElement("span");
2394 span.className = "toggle-label";
2396 span.style.display = "none";
2398 if (!otherMessage) {
2399 span.innerHTML = " Expand description";
2401 span.innerHTML = otherMessage;
2405 span.style.fontSize = fontSize;
2408 var mainToggle = toggle.cloneNode(true);
2409 mainToggle.appendChild(span);
2411 var wrapper = document.createElement("div");
2412 wrapper.className = "toggle-wrapper";
2414 addClass(wrapper, "collapsed");
2415 var inner = mainToggle.getElementsByClassName("inner");
2416 if (inner && inner.length > 0) {
2417 inner[0].innerHTML = "+";
2421 addClass(wrapper, extraClass);
2423 wrapper.appendChild(mainToggle);
2428 var toggles = document.getElementById(toggleAllDocsId);
2430 toggles.onclick = toggleAllDocs;
2433 var toggle = createSimpleToggle(false);
2434 var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
2435 var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false";
2436 var pageId = getPageId();
2438 var func = function(e) {
2439 var next = e.nextElementSibling;
2443 if (hasClass(next, "docblock") === true ||
2444 (hasClass(next, "stability") === true &&
2445 hasClass(next.nextElementSibling, "docblock") === true)) {
2446 var newToggle = toggle.cloneNode(true);
2447 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2448 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2449 collapseDocs(newToggle, "hide", pageId);
2454 var funcImpl = function(e) {
2455 var next = e.nextElementSibling;
2456 if (next && hasClass(next, "docblock")) {
2457 next = next.nextElementSibling;
2462 if (hasClass(e, "impl") &&
2463 (next.getElementsByClassName("method").length > 0 ||
2464 next.getElementsByClassName("associatedconstant").length > 0)) {
2465 var newToggle = toggle.cloneNode(true);
2466 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2467 // In case the option "auto-collapse implementors" is not set to false, we collapse
2468 // all implementors.
2469 if (hideImplementors === true && e.parentNode.id === "implementors-list") {
2470 collapseDocs(newToggle, "hide", pageId);
2475 onEachLazy(document.getElementsByClassName("method"), func);
2476 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2477 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2478 var impl_call = function() {};
2479 if (hideMethodDocs === true) {
2480 impl_call = function(e, newToggle) {
2481 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2482 // Automatically minimize all non-inherent impls
2483 if (hasClass(e, "impl") === true) {
2484 collapseDocs(newToggle, "hide", pageId);
2489 var newToggle = document.createElement("a");
2490 newToggle.href = "javascript:void(0)";
2491 newToggle.className = "collapse-toggle hidden-default collapsed";
2492 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2493 "</span>] Show hidden undocumented items";
2494 function toggleClicked() {
2495 if (hasClass(this, "collapsed")) {
2496 removeClass(this, "collapsed");
2497 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2498 if (hasClass(x, "content") === false) {
2499 removeClass(x, "hidden");
2503 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2504 "</span>] Hide undocumented items";
2506 addClass(this, "collapsed");
2507 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2508 if (hasClass(x, "content") === false) {
2509 addClass(x, "hidden");
2510 removeClass(x, "x");
2513 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2514 "</span>] Show hidden undocumented items";
2517 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2518 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2519 var hiddenElems = e.getElementsByClassName("hidden");
2520 var needToggle = false;
2522 var hlength = hiddenElems.length;
2523 for (var i = 0; i < hlength; ++i) {
2524 if (hasClass(hiddenElems[i], "content") === false &&
2525 hasClass(hiddenElems[i], "docblock") === false) {
2530 if (needToggle === true) {
2531 var inner_toggle = newToggle.cloneNode(true);
2532 inner_toggle.onclick = toggleClicked;
2533 e.insertBefore(inner_toggle, e.firstChild);
2534 impl_call(e.previousSibling, inner_toggle);
2538 var currentType = document.getElementsByClassName("type-decl")[0];
2539 var className = null;
2541 currentType = currentType.getElementsByClassName("rust")[0];
2543 currentType.classList.forEach(function(item) {
2544 if (item !== "main") {
2551 var showItemDeclarations = getSettingValue("auto-hide-" + className);
2552 if (showItemDeclarations === null) {
2553 if (className === "enum" || className === "macro") {
2554 showItemDeclarations = "false";
2555 } else if (className === "struct" || className === "union" || className === "trait") {
2556 showItemDeclarations = "true";
2558 // In case we found an unknown type, we just use the "parent" value.
2559 showItemDeclarations = getSettingValue("auto-hide-declarations");
2562 showItemDeclarations = showItemDeclarations === "false";
2563 function buildToggleWrapper(e) {
2564 if (hasClass(e, "autohide")) {
2565 var wrap = e.previousElementSibling;
2566 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2567 var inner_toggle = wrap.childNodes[0];
2568 var extra = e.childNodes[0].tagName === "H3";
2570 e.style.display = "none";
2571 addClass(wrap, "collapsed");
2572 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2573 e.innerHTML = labelForToggleButton(true);
2575 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2576 e.style.display = "inline-block";
2577 if (extra === true) {
2578 e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2583 if (e.parentNode.id === "main") {
2584 var otherMessage = "";
2588 if (hasClass(e, "type-decl")) {
2590 otherMessage = " Show declaration";
2591 if (showItemDeclarations === false) {
2592 extraClass = "collapsed";
2594 } else if (hasClass(e, "sub-variant")) {
2595 otherMessage = " Show fields";
2596 } else if (hasClass(e, "non-exhaustive")) {
2597 otherMessage = " This ";
2598 if (hasClass(e, "non-exhaustive-struct")) {
2599 otherMessage += "struct";
2600 } else if (hasClass(e, "non-exhaustive-enum")) {
2601 otherMessage += "enum";
2602 } else if (hasClass(e, "non-exhaustive-variant")) {
2603 otherMessage += "enum variant";
2604 } else if (hasClass(e, "non-exhaustive-type")) {
2605 otherMessage += "type";
2607 otherMessage += " is marked as non-exhaustive";
2608 } else if (hasClass(e.childNodes[0], "impl-items")) {
2609 extraClass = "marg-left";
2612 e.parentNode.insertBefore(
2618 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2620 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2621 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2623 if (hasClass(e, "non-exhaustive") === true) {
2624 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2629 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2630 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2631 var pageId = getPageId();
2633 autoCollapse(pageId, getSettingValue("collapse") === "true");
2635 if (pageId !== null) {
2636 expandSection(pageId);
2640 function createToggleWrapper(tog) {
2641 var span = document.createElement("span");
2642 span.className = "toggle-label";
2643 span.style.display = "none";
2644 span.innerHTML = " Expand attributes";
2645 tog.appendChild(span);
2647 var wrapper = document.createElement("div");
2648 wrapper.className = "toggle-wrapper toggle-attributes";
2649 wrapper.appendChild(tog);
2654 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2655 var itemAttributesFunc = function() {};
2656 if (getSettingValue("auto-hide-attributes") !== "false") {
2657 itemAttributesFunc = function(x) {
2658 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2661 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2662 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2663 var attr_tog = attributesToggle.cloneNode(true);
2664 if (hasClass(i_e, "top-attr") === true) {
2665 addClass(attr_tog, "top-attr");
2667 i_e.parentNode.insertBefore(attr_tog, i_e);
2668 itemAttributesFunc(i_e);
2673 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2674 var lineNumbersFunc = function() {};
2675 if (getSettingValue("line-numbers") === "true") {
2676 lineNumbersFunc = function(x) {
2677 var count = x.textContent.split("\n").length;
2679 for (var i = 0; i < count; ++i) {
2682 var node = document.createElement("pre");
2683 addClass(node, "line-number");
2684 node.innerHTML = elems.join("\n");
2685 x.parentNode.insertBefore(node, x);
2688 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2689 if (hasClass(e, "compile_fail")) {
2690 e.addEventListener("mouseover", function() {
2691 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2693 e.addEventListener("mouseout", function() {
2694 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2696 } else if (hasClass(e, "ignore")) {
2697 e.addEventListener("mouseover", function() {
2698 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2700 e.addEventListener("mouseout", function() {
2701 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2708 onEachLazy(document.getElementsByClassName("notable-traits"), function(e) {
2709 e.onclick = function() {
2710 this.getElementsByClassName('notable-traits-tooltiptext')[0]
2711 .classList.toggle("force-tooltip");
2715 // In the search display, allows to switch between tabs.
2716 function printTab(nb) {
2717 if (nb === 0 || nb === 1 || nb === 2) {
2721 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2722 if (nb_copy === 0) {
2723 addClass(elem, "selected");
2725 removeClass(elem, "selected");
2729 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2731 elem.style.display = "";
2733 elem.style.display = "none";
2739 function putBackSearch(search_input) {
2740 var search = getSearchElement();
2741 if (search_input.value !== "" && hasClass(search, "hidden")) {
2742 showSearchResults(search);
2743 if (browserSupportsHistoryApi()) {
2744 history.replaceState(search_input.value,
2746 "?search=" + encodeURIComponent(search_input.value));
2751 function getSearchLoadingText() {
2752 return "Loading search results...";
2756 search_input.onfocus = function() {
2757 putBackSearch(this);
2761 var params = getQueryStringParams();
2762 if (params && params.search) {
2763 var search = getSearchElement();
2764 search.innerHTML = "<h3 style=\"text-align: center;\">" + getSearchLoadingText() + "</h3>";
2765 showSearchResults(search);
2768 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2770 sidebar_menu.onclick = function() {
2771 var sidebar = document.getElementsByClassName("sidebar")[0];
2772 if (hasClass(sidebar, "mobile") === true) {
2781 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2784 onEachLazy(main.childNodes, function(e) {
2785 // Unhide the actual content once loading is complete. Headers get
2786 // flex treatment for their horizontal layout, divs get block treatment
2787 // for vertical layout (column-oriented flex layout for divs caused
2788 // errors in mobile browsers).
2789 if (e.tagName === "H2" || e.tagName === "H3") {
2790 var nextTagName = e.nextElementSibling.tagName;
2791 if (nextTagName == "H2" || nextTagName == "H3") {
2792 e.nextElementSibling.style.display = "flex";
2794 e.nextElementSibling.style.display = "block";
2800 function enableSearchInput() {
2802 search_input.removeAttribute('disabled');
2806 window.addSearchOptions = function(crates) {
2807 var elem = document.getElementById("crate-search");
2810 enableSearchInput();
2813 var crates_text = [];
2814 if (Object.keys(crates).length > 1) {
2815 for (var crate in crates) {
2816 if (hasOwnProperty(crates, crate)) {
2817 crates_text.push(crate);
2821 crates_text.sort(function(a, b) {
2822 var lower_a = a.toLowerCase();
2823 var lower_b = b.toLowerCase();
2825 if (lower_a < lower_b) {
2827 } else if (lower_a > lower_b) {
2832 var savedCrate = getSettingValue("saved-filter-crate");
2833 for (var i = 0; i < crates_text.length; ++i) {
2834 var option = document.createElement("option");
2835 option.value = crates_text[i];
2836 option.innerText = crates_text[i];
2837 elem.appendChild(option);
2838 // Set the crate filter from saved storage, if the current page has the saved crate
2841 // If not, ignore the crate filter -- we want to support filtering for crates on sites
2842 // like doc.rust-lang.org where the crates may differ from page to page while on the
2844 if (crates_text[i] === savedCrate) {
2845 elem.value = savedCrate;
2848 enableSearchInput();
2851 function buildHelperPopup() {
2852 var popup = document.createElement("aside");
2853 addClass(popup, "hidden");
2856 var book_info = document.createElement("span");
2857 book_info.innerHTML = "You can find more information in \
2858 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
2860 var container = document.createElement("div");
2862 ["?", "Show this help dialog"],
2863 ["S", "Focus the search field"],
2864 ["T", "Focus the theme picker menu"],
2865 ["↑", "Move up in search results"],
2866 ["↓", "Move down in search results"],
2867 ["↹", "Switch tab"],
2868 ["⏎", "Go to active search result"],
2869 ["+", "Expand all sections"],
2870 ["-", "Collapse all sections"],
2871 ].map(x => "<dt><kbd>" + x[0] + "</kbd></dt><dd>" + x[1] + "</dd>").join("");
2872 var div_shortcuts = document.createElement("div");
2873 addClass(div_shortcuts, "shortcuts");
2874 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2877 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2878 restrict the search to a given item kind.",
2879 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
2880 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
2881 and <code>const</code>.",
2882 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
2883 <code>* -> vec</code>)",
2884 "Search multiple things at once by splitting your query with comma (e.g., \
2885 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
2886 "You can look for items with an exact name by putting double quotes around \
2887 your request: <code>\"string\"</code>",
2888 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
2889 ].map(x => "<p>" + x + "</p>").join("");
2890 var div_infos = document.createElement("div");
2891 addClass(div_infos, "infos");
2892 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2894 container.appendChild(book_info);
2895 container.appendChild(div_shortcuts);
2896 container.appendChild(div_infos);
2898 popup.appendChild(container);
2899 insertAfter(popup, getSearchElement());
2900 // So that it's only built once and then it'll do nothing when called!
2901 buildHelperPopup = function() {};
2905 window.onhashchange = onHashChange;
2908 // This is required in firefox. Explanations: when going back in the history, firefox doesn't re-run
2909 // the JS, therefore preventing rustdoc from setting a few things required to be able to reload the
2910 // previous search results (if you navigated to a search result with the keyboard, pressed enter on
2911 // it to navigate to that result, and then came back to this page).
2912 window.onunload = function(){};