]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/static/main.js
New upstream version 1.20.0+dfsg1
[rustc.git] / src / librustdoc / html / static / main.js
1 /*!
2 * Copyright 2014 The Rust Project Developers. See the COPYRIGHT
3 * file at the top-level directory of this distribution and at
4 * http://rust-lang.org/COPYRIGHT.
5 *
6 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 * option. This file may not be copied, modified, or distributed
10 * except according to those terms.
11 */
12
13 /*jslint browser: true, es5: true */
14 /*globals $: true, rootPath: true */
15
16 (function() {
17 "use strict";
18
19 // This mapping table should match the discriminants of
20 // `rustdoc::html::item_type::ItemType` type in Rust.
21 var itemTypes = ["mod",
22 "externcrate",
23 "import",
24 "struct",
25 "enum",
26 "fn",
27 "type",
28 "static",
29 "trait",
30 "impl",
31 "tymethod",
32 "method",
33 "structfield",
34 "variant",
35 "macro",
36 "primitive",
37 "associatedtype",
38 "constant",
39 "associatedconstant",
40 "union"];
41
42 function hasClass(elem, className) {
43 if (elem && className && elem.className) {
44 var elemClass = elem.className;
45 var start = elemClass.indexOf(className);
46 if (start == -1) {
47 return false;
48 } else if (elemClass.length == className.length) {
49 return true;
50 } else {
51 if (start > 0 && elemClass[start - 1] != ' ') {
52 return false;
53 }
54 var end = start + className.length;
55 if (end < elemClass.length && elemClass[end] != ' ') {
56 return false;
57 }
58 return true;
59 }
60 }
61 return false;
62 }
63
64 function addClass(elem, className) {
65 if (elem && className && !hasClass(elem, className)) {
66 if (elem.className && elem.className.length > 0) {
67 elem.className += ' ' + className;
68 } else {
69 elem.className = className;
70 }
71 }
72 }
73
74 function removeClass(elem, className) {
75 if (elem && className && elem.className) {
76 elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
77 .trim();
78 }
79 }
80
81 function onEach(arr, func) {
82 if (arr && arr.length > 0 && func) {
83 for (var i = 0; i < arr.length; i++) {
84 func(arr[i]);
85 }
86 }
87 }
88
89 function isHidden(elem) {
90 return (elem.offsetParent === null)
91 }
92
93 // used for special search precedence
94 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
95
96 onEach(document.getElementsByClassName('js-only'), function(e) {
97 removeClass(e, 'js-only');
98 });
99
100 function getQueryStringParams() {
101 var params = {};
102 window.location.search.substring(1).split("&").
103 map(function(s) {
104 var pair = s.split("=");
105 params[decodeURIComponent(pair[0])] =
106 typeof pair[1] === "undefined" ?
107 null : decodeURIComponent(pair[1]);
108 });
109 return params;
110 }
111
112 function browserSupportsHistoryApi() {
113 return document.location.protocol != "file:" &&
114 window.history && typeof window.history.pushState === "function";
115 }
116
117 function highlightSourceLines(ev) {
118 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
119 if (match) {
120 from = parseInt(match[1], 10);
121 to = Math.min(50000, parseInt(match[2] || match[1], 10));
122 from = Math.min(from, to);
123 var elem = document.getElementById(from);
124 if (!elem) {
125 return;
126 }
127 if (ev === null) {
128 var x = document.getElementById(from);
129 if (x) {
130 x.scrollIntoView();
131 }
132 };
133 onEach(document.getElementsByClassName('line-numbers'), function(e) {
134 onEach(e.getElementsByTagName('span'), function(i_e) {
135 removeClass(i_e, 'line-highlighted');
136 });
137 })
138 for (i = from; i <= to; ++i) {
139 addClass(document.getElementById(i), 'line-highlighted');
140 }
141 }
142 }
143 highlightSourceLines(null);
144 window.onhashchange = highlightSourceLines;
145
146 // Gets the human-readable string for the virtual-key code of the
147 // given KeyboardEvent, ev.
148 //
149 // This function is meant as a polyfill for KeyboardEvent#key,
150 // since it is not supported in Trident. We also test for
151 // KeyboardEvent#keyCode because the handleShortcut handler is
152 // also registered for the keydown event, because Blink doesn't fire
153 // keypress on hitting the Escape key.
154 //
155 // So I guess you could say things are getting pretty interoperable.
156 function getVirtualKey(ev) {
157 if ("key" in ev && typeof ev.key != "undefined")
158 return ev.key;
159
160 var c = ev.charCode || ev.keyCode;
161 if (c == 27)
162 return "Escape";
163 return String.fromCharCode(c);
164 }
165
166 function handleShortcut(ev) {
167 if (document.activeElement.tagName === "INPUT")
168 return;
169
170 // Don't interfere with browser shortcuts
171 if (ev.ctrlKey || ev.altKey || ev.metaKey)
172 return;
173
174 var help = document.getElementById("help");
175 switch (getVirtualKey(ev)) {
176 case "Escape":
177 var search = document.getElementById("search");
178 if (!hasClass(help, "hidden")) {
179 ev.preventDefault();
180 addClass(help, "hidden");
181 removeClass(document.body, "blur");
182 } else if (!hasClass(search, "hidden")) {
183 ev.preventDefault();
184 addClass(search, "hidden");
185 removeClass(document.getElementById("main"), "hidden");
186 }
187 break;
188
189 case "s":
190 case "S":
191 ev.preventDefault();
192 focusSearchBar();
193 break;
194
195 case "+":
196 ev.preventDefault();
197 toggleAllDocs();
198 break;
199
200 case "?":
201 if (ev.shiftKey && hasClass(help, "hidden")) {
202 ev.preventDefault();
203 removeClass(help, "hidden");
204 addClass(document.body, "blur");
205 }
206 break;
207 }
208 }
209
210 document.onkeypress = handleShortcut;
211 document.onkeydown = handleShortcut;
212 document.onclick = function(ev) {
213 if (hasClass(ev.target, 'collapse-toggle')) {
214 collapseDocs(ev.target);
215 } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
216 collapseDocs(ev.target.parentNode);
217 } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
218 var prev_id = 0;
219
220 var set_fragment = function (name) {
221 if (browserSupportsHistoryApi()) {
222 history.replaceState(null, null, '#' + name);
223 window.hashchange();
224 } else {
225 location.replace('#' + name);
226 }
227 };
228
229 var cur_id = parseInt(ev.target.id, 10);
230
231 if (ev.shiftKey && prev_id) {
232 if (prev_id > cur_id) {
233 var tmp = prev_id;
234 prev_id = cur_id;
235 cur_id = tmp;
236 }
237
238 set_fragment(prev_id + '-' + cur_id);
239 } else {
240 prev_id = cur_id;
241
242 set_fragment(cur_id);
243 }
244 } else if (!hasClass(document.getElementById("help"), "hidden")) {
245 addClass(document.getElementById("help"), "hidden");
246 removeClass(document.body, "blur");
247 }
248 };
249
250 var x = document.getElementsByClassName('version-selector');
251 if (x.length > 0) {
252 x[0].onchange = function() {
253 var i, match,
254 url = document.location.href,
255 stripped = '',
256 len = rootPath.match(/\.\.\//g).length + 1;
257
258 for (i = 0; i < len; ++i) {
259 match = url.match(/\/[^\/]*$/);
260 if (i < len - 1) {
261 stripped = match[0] + stripped;
262 }
263 url = url.substring(0, url.length - match[0].length);
264 }
265
266 url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
267
268 document.location.href = url;
269 };
270 }
271
272 /**
273 * A function to compute the Levenshtein distance between two strings
274 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
275 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
276 * This code is an unmodified version of the code written by Marco de Wit
277 * and was found at http://stackoverflow.com/a/18514751/745719
278 */
279 var levenshtein = (function() {
280 var row2 = [];
281 return function(s1, s2) {
282 if (s1 === s2) {
283 return 0;
284 }
285 var s1_len = s1.length, s2_len = s2.length;
286 if (s1_len && s2_len) {
287 var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
288 while (i1 < s1_len) {
289 row[i1] = ++i1;
290 }
291 while (i2 < s2_len) {
292 c2 = s2.charCodeAt(i2);
293 a = i2;
294 ++i2;
295 b = i2;
296 for (i1 = 0; i1 < s1_len; ++i1) {
297 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
298 a = row[i1];
299 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
300 row[i1] = b;
301 }
302 }
303 return b;
304 }
305 return s1_len + s2_len;
306 };
307 })();
308
309 function initSearch(rawSearchIndex) {
310 var currentResults, index, searchIndex;
311 var MAX_LEV_DISTANCE = 3;
312 var params = getQueryStringParams();
313
314 // Populate search bar with query string search term when provided,
315 // but only if the input bar is empty. This avoid the obnoxious issue
316 // where you start trying to do a search, and the index loads, and
317 // suddenly your search is gone!
318 if (document.getElementsByClassName("search-input")[0].value === "") {
319 document.getElementsByClassName("search-input")[0].value = params.search || '';
320 }
321
322 /**
323 * Executes the query and builds an index of results
324 * @param {[Object]} query [The user query]
325 * @param {[type]} max [The maximum results returned]
326 * @param {[type]} searchWords [The list of search words to query
327 * against]
328 * @return {[type]} [A search index of results]
329 */
330 function execQuery(query, max, searchWords) {
331 var valLower = query.query.toLowerCase(),
332 val = valLower,
333 typeFilter = itemTypeFromName(query.type),
334 results = [],
335 split = valLower.split("::");
336
337 // remove empty keywords
338 for (var j = 0; j < split.length; ++j) {
339 split[j].toLowerCase();
340 if (split[j] === "") {
341 split.splice(j, 1);
342 }
343 }
344
345 function typePassesFilter(filter, type) {
346 // No filter
347 if (filter < 0) return true;
348
349 // Exact match
350 if (filter === type) return true;
351
352 // Match related items
353 var name = itemTypes[type];
354 switch (itemTypes[filter]) {
355 case "constant":
356 return (name == "associatedconstant");
357 case "fn":
358 return (name == "method" || name == "tymethod");
359 case "type":
360 return (name == "primitive");
361 }
362
363 // No match
364 return false;
365 }
366
367 // quoted values mean literal search
368 var nSearchWords = searchWords.length;
369 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
370 val.charAt(val.length - 1) === val.charAt(0))
371 {
372 val = val.substr(1, val.length - 2);
373 for (var i = 0; i < nSearchWords; ++i) {
374 if (searchWords[i] === val) {
375 // filter type: ... queries
376 if (typePassesFilter(typeFilter, searchIndex[i].ty)) {
377 results.push({id: i, index: -1});
378 }
379 }
380 if (results.length === max) {
381 break;
382 }
383 }
384 // searching by type
385 } else if (val.search("->") > -1) {
386 var trimmer = function (s) { return s.trim(); };
387 var parts = val.split("->").map(trimmer);
388 var input = parts[0];
389 // sort inputs so that order does not matter
390 var inputs = input.split(",").map(trimmer).sort().toString();
391 var output = parts[1];
392
393 for (var i = 0; i < nSearchWords; ++i) {
394 var type = searchIndex[i].type;
395 if (!type) {
396 continue;
397 }
398
399 // sort index inputs so that order does not matter
400 var typeInputs = type.inputs.map(function (input) {
401 return input.name;
402 }).sort();
403
404 // allow searching for void (no output) functions as well
405 var typeOutput = type.output ? type.output.name : "";
406 if ((inputs === "*" || inputs === typeInputs.toString()) &&
407 (output === "*" || output == typeOutput)) {
408 results.push({id: i, index: -1, dontValidate: true});
409 }
410 }
411 } else {
412 // gather matching search results up to a certain maximum
413 val = val.replace(/\_/g, "");
414 for (var i = 0; i < split.length; ++i) {
415 for (var j = 0; j < nSearchWords; ++j) {
416 var lev_distance;
417 if (searchWords[j].indexOf(split[i]) > -1 ||
418 searchWords[j].indexOf(val) > -1 ||
419 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
420 {
421 // filter type: ... queries
422 if (typePassesFilter(typeFilter, searchIndex[j].ty)) {
423 results.push({
424 id: j,
425 index: searchWords[j].replace(/_/g, "").indexOf(val),
426 lev: 0,
427 });
428 }
429 } else if (
430 (lev_distance = levenshtein(searchWords[j], val)) <=
431 MAX_LEV_DISTANCE) {
432 if (typePassesFilter(typeFilter, searchIndex[j].ty)) {
433 results.push({
434 id: j,
435 index: 0,
436 // we want lev results to go lower than others
437 lev: lev_distance,
438 });
439 }
440 }
441 if (results.length === max) {
442 break;
443 }
444 }
445 }
446 }
447
448 var nresults = results.length;
449 for (var i = 0; i < nresults; ++i) {
450 results[i].word = searchWords[results[i].id];
451 results[i].item = searchIndex[results[i].id] || {};
452 }
453 // if there are no results then return to default and fail
454 if (results.length === 0) {
455 return [];
456 }
457
458 results.sort(function sortResults(aaa, bbb) {
459 var a, b;
460
461 // Sort by non levenshtein results and then levenshtein results by the distance
462 // (less changes required to match means higher rankings)
463 a = (aaa.lev);
464 b = (bbb.lev);
465 if (a !== b) { return a - b; }
466
467 // sort by crate (non-current crate goes later)
468 a = (aaa.item.crate !== window.currentCrate);
469 b = (bbb.item.crate !== window.currentCrate);
470 if (a !== b) { return a - b; }
471
472 // sort by exact match (mismatch goes later)
473 a = (aaa.word !== valLower);
474 b = (bbb.word !== valLower);
475 if (a !== b) { return a - b; }
476
477 // sort by item name length (longer goes later)
478 a = aaa.word.length;
479 b = bbb.word.length;
480 if (a !== b) { return a - b; }
481
482 // sort by item name (lexicographically larger goes later)
483 a = aaa.word;
484 b = bbb.word;
485 if (a !== b) { return (a > b ? +1 : -1); }
486
487 // sort by index of keyword in item name (no literal occurrence goes later)
488 a = (aaa.index < 0);
489 b = (bbb.index < 0);
490 if (a !== b) { return a - b; }
491 // (later literal occurrence, if any, goes later)
492 a = aaa.index;
493 b = bbb.index;
494 if (a !== b) { return a - b; }
495
496 // special precedence for primitive pages
497 if ((aaa.item.ty === TY_PRIMITIVE) && (bbb.item.ty !== TY_PRIMITIVE)) {
498 return -1;
499 }
500 if ((bbb.item.ty === TY_PRIMITIVE) && (aaa.item.ty !== TY_PRIMITIVE)) {
501 return 1;
502 }
503
504 // sort by description (no description goes later)
505 a = (aaa.item.desc === '');
506 b = (bbb.item.desc === '');
507 if (a !== b) { return a - b; }
508
509 // sort by type (later occurrence in `itemTypes` goes later)
510 a = aaa.item.ty;
511 b = bbb.item.ty;
512 if (a !== b) { return a - b; }
513
514 // sort by path (lexicographically larger goes later)
515 a = aaa.item.path;
516 b = bbb.item.path;
517 if (a !== b) { return (a > b ? +1 : -1); }
518
519 // que sera, sera
520 return 0;
521 });
522
523 // remove duplicates, according to the data provided
524 for (var i = results.length - 1; i > 0; i -= 1) {
525 if (results[i].word === results[i - 1].word &&
526 results[i].item.ty === results[i - 1].item.ty &&
527 results[i].item.path === results[i - 1].item.path &&
528 (results[i].item.parent || {}).name === (results[i - 1].item.parent || {}).name)
529 {
530 results[i].id = -1;
531 }
532 }
533 for (var i = 0; i < results.length; ++i) {
534 var result = results[i],
535 name = result.item.name.toLowerCase(),
536 path = result.item.path.toLowerCase(),
537 parent = result.item.parent;
538
539 // this validation does not make sense when searching by types
540 if (result.dontValidate) {
541 continue;
542 }
543
544 var valid = validateResult(name, path, split, parent);
545 if (!valid) {
546 result.id = -1;
547 }
548 }
549 return results;
550 }
551
552 /**
553 * Validate performs the following boolean logic. For example:
554 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
555 * exists in (name || path || parent) OR => ("file" && "open") exists in
556 * (name || path )
557 *
558 * This could be written functionally, but I wanted to minimise
559 * functions on stack.
560 *
561 * @param {[string]} name [The name of the result]
562 * @param {[string]} path [The path of the result]
563 * @param {[string]} keys [The keys to be used (["file", "open"])]
564 * @param {[object]} parent [The parent of the result]
565 * @return {[boolean]} [Whether the result is valid or not]
566 */
567 function validateResult(name, path, keys, parent) {
568 for (var i = 0; i < keys.length; ++i) {
569 // each check is for validation so we negate the conditions and invalidate
570 if (!(
571 // check for an exact name match
572 name.toLowerCase().indexOf(keys[i]) > -1 ||
573 // then an exact path match
574 path.toLowerCase().indexOf(keys[i]) > -1 ||
575 // next if there is a parent, check for exact parent match
576 (parent !== undefined &&
577 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
578 // lastly check to see if the name was a levenshtein match
579 levenshtein(name.toLowerCase(), keys[i]) <=
580 MAX_LEV_DISTANCE)) {
581 return false;
582 }
583 }
584 return true;
585 }
586
587 function getQuery() {
588 var matches, type, query, raw =
589 document.getElementsByClassName('search-input')[0].value;
590 query = raw;
591
592 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
593 if (matches) {
594 type = matches[1].replace(/^const$/, 'constant');
595 query = query.substring(matches[0].length);
596 }
597
598 return {
599 raw: raw,
600 query: query,
601 type: type,
602 id: query + type
603 };
604 }
605
606 function initSearchNav() {
607 var hoverTimeout;
608
609 var click_func = function(e) {
610 var el = e.target;
611 // to retrieve the real "owner" of the event.
612 while (el.tagName !== 'TR') {
613 el = el.parentNode;
614 }
615 var dst = e.target.getElementsByTagName('a');
616 if (dst.length < 1) {
617 return;
618 }
619 dst = dst[0];
620 if (window.location.pathname === dst.pathname) {
621 addClass(document.getElementById('search'), 'hidden');
622 removeClass(document.getElementById('main'), 'hidden');
623 document.location.href = dst.href;
624 }
625 };
626 var mouseover_func = function(e) {
627 var el = e.target;
628 // to retrieve the real "owner" of the event.
629 while (el.tagName !== 'TR') {
630 el = el.parentNode;
631 }
632 clearTimeout(hoverTimeout);
633 hoverTimeout = setTimeout(function() {
634 onEach(document.getElementsByClassName('search-results'), function(e) {
635 onEach(e.getElementsByClassName('result'), function(i_e) {
636 removeClass(i_e, 'highlighted');
637 });
638 });
639 addClass(el, 'highlighted');
640 }, 20);
641 };
642 onEach(document.getElementsByClassName('search-results'), function(e) {
643 onEach(e.getElementsByClassName('result'), function(i_e) {
644 i_e.onclick = click_func;
645 i_e.onmouseover = mouseover_func;
646 });
647 });
648
649 var search_input = document.getElementsByClassName('search-input')[0];
650 search_input.onkeydown = null;
651 search_input.onkeydown = function(e) {
652 var actives = [];
653 onEach(document.getElementsByClassName('search-results'), function(e) {
654 onEach(document.getElementsByClassName('highlighted'), function(e) {
655 actives.push(e);
656 });
657 });
658
659 if (e.which === 38) { // up
660 if (!actives.length || !actives[0].previousElementSibling) {
661 return;
662 }
663
664 addClass(actives[0].previousElementSibling, 'highlighted');
665 removeClass(actives[0], 'highlighted');
666 } else if (e.which === 40) { // down
667 if (!actives.length) {
668 var results = document.getElementsByClassName('search-results');
669 if (results.length > 0) {
670 var res = results[0].getElementsByClassName('result');
671 if (res.length > 0) {
672 addClass(res[0], 'highlighted');
673 }
674 }
675 } else if (actives[0].nextElementSibling) {
676 addClass(actives[0].nextElementSibling, 'highlighted');
677 removeClass(actives[0], 'highlighted');
678 }
679 } else if (e.which === 13) { // return
680 if (actives.length) {
681 document.location.href = actives[0].getElementsByTagName('a')[0].href;
682 }
683 } else if (actives.length > 0) {
684 removeClass(actives[0], 'highlighted');
685 }
686 };
687 }
688
689 function escape(content) {
690 var h1 = document.createElement('h1');
691 h1.textContent = content;
692 return h1.innerHTML;
693 }
694
695 function showResults(results) {
696 var output, shown, query = getQuery();
697
698 currentResults = query.id;
699 output = '<h1>Results for ' + escape(query.query) +
700 (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>';
701 output += '<table class="search-results">';
702
703 if (results.length > 0) {
704 shown = [];
705
706 results.forEach(function(item) {
707 var name, type, href, displayPath;
708
709 if (shown.indexOf(item) !== -1) {
710 return;
711 }
712
713 shown.push(item);
714 name = item.name;
715 type = itemTypes[item.ty];
716
717 if (type === 'mod') {
718 displayPath = item.path + '::';
719 href = rootPath + item.path.replace(/::/g, '/') + '/' +
720 name + '/index.html';
721 } else if (type === "primitive") {
722 displayPath = "";
723 href = rootPath + item.path.replace(/::/g, '/') +
724 '/' + type + '.' + name + '.html';
725 } else if (type === "externcrate") {
726 displayPath = "";
727 href = rootPath + name + '/index.html';
728 } else if (item.parent !== undefined) {
729 var myparent = item.parent;
730 var anchor = '#' + type + '.' + name;
731 var parentType = itemTypes[myparent.ty];
732 if (parentType === "primitive") {
733 displayPath = myparent.name + '::';
734 } else {
735 displayPath = item.path + '::' + myparent.name + '::';
736 }
737 href = rootPath + item.path.replace(/::/g, '/') +
738 '/' + parentType +
739 '.' + myparent.name +
740 '.html' + anchor;
741 } else {
742 displayPath = item.path + '::';
743 href = rootPath + item.path.replace(/::/g, '/') +
744 '/' + type + '.' + name + '.html';
745 }
746
747 output += '<tr class="' + type + ' result"><td>' +
748 '<a href="' + href + '">' +
749 displayPath + '<span class="' + type + '">' +
750 name + '</span></a></td><td>' +
751 '<a href="' + href + '">' +
752 '<span class="desc">' + escape(item.desc) +
753 '&nbsp;</span></a></td></tr>';
754 });
755 } else {
756 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
757 encodeURIComponent('rust ' + query.query) +
758 '">Try on DuckDuckGo?</a>';
759 }
760
761 output += "</p>";
762 addClass(document.getElementById('main'), 'hidden');
763 var search = document.getElementById('search');
764 removeClass(search, 'hidden');
765 search.innerHTML = output;
766 var tds = search.getElementsByTagName('td');
767 var td_width = 0;
768 if (tds.length > 0) {
769 td_width = tds[0].offsetWidth;
770 }
771 var width = search.offsetWidth - 40 - td_width;
772 onEach(search.getElementsByClassName('desc'), function(e) {
773 e.style.width = width + 'px';
774 });
775 initSearchNav();
776 }
777
778 function search(e) {
779 var query,
780 filterdata = [],
781 obj, i, len,
782 results = [],
783 maxResults = 200,
784 resultIndex;
785 var params = getQueryStringParams();
786
787 query = getQuery();
788 if (e) {
789 e.preventDefault();
790 }
791
792 if (!query.query || query.id === currentResults) {
793 return;
794 }
795
796 // Update document title to maintain a meaningful browser history
797 document.title = "Results for " + query.query + " - Rust";
798
799 // Because searching is incremental by character, only the most
800 // recent search query is added to the browser history.
801 if (browserSupportsHistoryApi()) {
802 if (!history.state && !params.search) {
803 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
804 } else {
805 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
806 }
807 }
808
809 resultIndex = execQuery(query, 20000, index);
810 len = resultIndex.length;
811 for (i = 0; i < len; ++i) {
812 if (resultIndex[i].id > -1) {
813 obj = searchIndex[resultIndex[i].id];
814 filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
815 results.push(obj);
816 }
817 if (results.length >= maxResults) {
818 break;
819 }
820 }
821
822 showResults(results);
823 }
824
825 function itemTypeFromName(typename) {
826 for (var i = 0; i < itemTypes.length; ++i) {
827 if (itemTypes[i] === typename) { return i; }
828 }
829 return -1;
830 }
831
832 function buildIndex(rawSearchIndex) {
833 searchIndex = [];
834 var searchWords = [];
835 for (var crate in rawSearchIndex) {
836 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
837
838 searchWords.push(crate);
839 searchIndex.push({
840 crate: crate,
841 ty: 1, // == ExternCrate
842 name: crate,
843 path: "",
844 desc: rawSearchIndex[crate].doc,
845 type: null,
846 });
847
848 // an array of [(Number) item type,
849 // (String) name,
850 // (String) full path or empty string for previous path,
851 // (String) description,
852 // (Number | null) the parent path index to `paths`]
853 // (Object | null) the type of the function (if any)
854 var items = rawSearchIndex[crate].items;
855 // an array of [(Number) item type,
856 // (String) name]
857 var paths = rawSearchIndex[crate].paths;
858
859 // convert `paths` into an object form
860 var len = paths.length;
861 for (var i = 0; i < len; ++i) {
862 paths[i] = {ty: paths[i][0], name: paths[i][1]};
863 }
864
865 // convert `items` into an object form, and construct word indices.
866 //
867 // before any analysis is performed lets gather the search terms to
868 // search against apart from the rest of the data. This is a quick
869 // operation that is cached for the life of the page state so that
870 // all other search operations have access to this cached data for
871 // faster analysis operations
872 var len = items.length;
873 var lastPath = "";
874 for (var i = 0; i < len; ++i) {
875 var rawRow = items[i];
876 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
877 path: rawRow[2] || lastPath, desc: rawRow[3],
878 parent: paths[rawRow[4]], type: rawRow[5]};
879 searchIndex.push(row);
880 if (typeof row.name === "string") {
881 var word = row.name.toLowerCase();
882 searchWords.push(word);
883 } else {
884 searchWords.push("");
885 }
886 lastPath = row.path;
887 }
888 }
889 return searchWords;
890 }
891
892 function startSearch() {
893 var searchTimeout;
894 var callback = function() {
895 var search_input = document.getElementsByClassName('search-input');
896 if (search_input.length < 1) { return; }
897 search_input = search_input[0];
898 clearTimeout(searchTimeout);
899 if (search_input.value.length === 0) {
900 if (browserSupportsHistoryApi()) {
901 history.replaceState("", "std - Rust", "?search=");
902 }
903 var main = document.getElementById('main');
904 if (hasClass(main, 'content')) {
905 removeClass(main, 'hidden');
906 }
907 var search_c = document.getElementById('search');
908 if (hasClass(search_c, 'content')) {
909 addClass(search_c, 'hidden');
910 }
911 } else {
912 searchTimeout = setTimeout(search, 500);
913 }
914 };
915 var search_input = document.getElementsByClassName("search-input")[0];
916 search_input.onkeyup = callback;
917 search_input.oninput = callback;
918 document.getElementsByClassName("search-form")[0].onsubmit = function(e){
919 e.preventDefault();
920 clearTimeout(searchTimeout);
921 search();
922 };
923 search_input.onchange = function(e) {
924 // Do NOT e.preventDefault() here. It will prevent pasting.
925 clearTimeout(searchTimeout);
926 // zero-timeout necessary here because at the time of event handler execution the
927 // pasted content is not in the input field yet. Shouldn’t make any difference for
928 // change, though.
929 setTimeout(search, 0);
930 };
931 search_input.onpaste = search_input.onchange;
932
933 // Push and pop states are used to add search results to the browser
934 // history.
935 if (browserSupportsHistoryApi()) {
936 // Store the previous <title> so we can revert back to it later.
937 var previousTitle = document.title;
938
939 window.onpopstate = function(e) {
940 var params = getQueryStringParams();
941 // When browsing back from search results the main page
942 // visibility must be reset.
943 if (!params.search) {
944 var main = document.getElementById('main');
945 if (hasClass(main, 'content')) {
946 removeClass(main, 'hidden');
947 }
948 var search_c = document.getElementById('search');
949 if (hasClass(search_c, 'content')) {
950 addClass(search_c, 'hidden');
951 }
952 }
953 // Revert to the previous title manually since the History
954 // API ignores the title parameter.
955 document.title = previousTitle;
956 // When browsing forward to search results the previous
957 // search will be repeated, so the currentResults are
958 // cleared to ensure the search is successful.
959 currentResults = null;
960 // Synchronize search bar with query string state and
961 // perform the search. This will empty the bar if there's
962 // nothing there, which lets you really go back to a
963 // previous state with nothing in the bar.
964 if (params.search) {
965 document.getElementsByClassName('search-input')[0].value = params.search;
966 } else {
967 document.getElementsByClassName('search-input')[0].value = '';
968 }
969 // Some browsers fire 'onpopstate' for every page load
970 // (Chrome), while others fire the event only when actually
971 // popping a state (Firefox), which is why search() is
972 // called both here and at the end of the startSearch()
973 // function.
974 search();
975 };
976 }
977 search();
978 }
979
980 index = buildIndex(rawSearchIndex);
981 startSearch();
982
983 // Draw a convenient sidebar of known crates if we have a listing
984 if (rootPath === '../') {
985 var sidebar = document.getElementsByClassName('sidebar')[0];
986 var div = document.createElement('div');
987 div.className = 'block crate';
988 div.innerHTML = '<h3>Crates</h3>';
989 var ul = document.createElement('ul');
990 div.appendChild(ul);
991
992 var crates = [];
993 for (var crate in rawSearchIndex) {
994 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
995 crates.push(crate);
996 }
997 crates.sort();
998 for (var i = 0; i < crates.length; ++i) {
999 var klass = 'crate';
1000 if (crates[i] === window.currentCrate) {
1001 klass += ' current';
1002 }
1003 var link = document.createElement('a');
1004 link.href = '../' + crates[i] + '/index.html';
1005 link.title = rawSearchIndex[crates[i]].doc;
1006 link.className = klass;
1007 link.textContent = crates[i];
1008
1009 var li = document.createElement('li');
1010 li.appendChild(link);
1011 ul.appendChild(li);
1012 }
1013 sidebar.appendChild(div);
1014 }
1015 }
1016
1017 window.initSearch = initSearch;
1018
1019 // delayed sidebar rendering.
1020 function initSidebarItems(items) {
1021 var sidebar = document.getElementsByClassName('sidebar')[0];
1022 var current = window.sidebarCurrent;
1023
1024 function block(shortty, longty) {
1025 var filtered = items[shortty];
1026 if (!filtered) { return; }
1027
1028 var div = document.createElement('div');
1029 div.className = 'block ' + shortty;
1030 var h3 = document.createElement('h3');
1031 h3.textContent = longty;
1032 div.appendChild(h3);
1033 var ul = document.createElement('ul');
1034
1035 for (var i = 0; i < filtered.length; ++i) {
1036 var item = filtered[i];
1037 var name = item[0];
1038 var desc = item[1]; // can be null
1039
1040 var klass = shortty;
1041 if (name === current.name && shortty === current.ty) {
1042 klass += ' current';
1043 }
1044 var path;
1045 if (shortty === 'mod') {
1046 path = name + '/index.html';
1047 } else {
1048 path = shortty + '.' + name + '.html';
1049 }
1050 var link = document.createElement('a');
1051 link.href = current.relpath + path;
1052 link.title = desc;
1053 link.className = klass;
1054 link.textContent = name;
1055 var li = document.createElement('li');
1056 li.appendChild(link);
1057 ul.appendChild(li);
1058 }
1059 div.appendChild(ul);
1060 sidebar.appendChild(div);
1061 }
1062
1063 block("primitive", "Primitive Types");
1064 block("mod", "Modules");
1065 block("macro", "Macros");
1066 block("struct", "Structs");
1067 block("enum", "Enums");
1068 block("constant", "Constants");
1069 block("static", "Statics");
1070 block("trait", "Traits");
1071 block("fn", "Functions");
1072 block("type", "Type Definitions");
1073 }
1074
1075 window.initSidebarItems = initSidebarItems;
1076
1077 window.register_implementors = function(imp) {
1078 var list = document.getElementById('implementors-list');
1079 var libs = Object.getOwnPropertyNames(imp);
1080 for (var i = 0; i < libs.length; ++i) {
1081 if (libs[i] === currentCrate) { continue; }
1082 var structs = imp[libs[i]];
1083 for (var j = 0; j < structs.length; ++j) {
1084 var code = document.createElement('code');
1085 code.innerHTML = structs[j];
1086
1087 var x = code.getElementsByTagName('a');
1088 for (var k = 0; k < x.length; k++) {
1089 var href = x[k].getAttribute('href');
1090 if (href && href.indexOf('http') !== 0) {
1091 x[k].setAttribute('href', rootPath + href);
1092 }
1093 }
1094 var li = document.createElement('li');
1095 li.appendChild(code);
1096 list.appendChild(li);
1097 }
1098 }
1099 };
1100 if (window.pending_implementors) {
1101 window.register_implementors(window.pending_implementors);
1102 }
1103
1104 function labelForToggleButton(sectionIsCollapsed) {
1105 if (sectionIsCollapsed) {
1106 // button will expand the section
1107 return "+";
1108 }
1109 // button will collapse the section
1110 // note that this text is also set in the HTML template in render.rs
1111 return "\u2212"; // "\u2212" is '−' minus sign
1112 }
1113
1114 function onEveryMatchingChild(elem, className, func) {
1115 if (elem && className && func) {
1116 for (var i = 0; i < elem.childNodes.length; i++) {
1117 if (hasClass(elem.childNodes[i], className)) {
1118 func(elem.childNodes[i]);
1119 } else {
1120 onEveryMatchingChild(elem.childNodes[i], className, func);
1121 }
1122 }
1123 }
1124 }
1125
1126 function toggleAllDocs() {
1127 var toggle = document.getElementById("toggle-all-docs");
1128 if (hasClass(toggle, "will-expand")) {
1129 removeClass(toggle, "will-expand");
1130 onEveryMatchingChild(toggle, "inner", function(e) {
1131 e.innerHTML = labelForToggleButton(false);
1132 });
1133 toggle.title = "collapse all docs";
1134 onEach(document.getElementsByClassName("docblock"), function(e) {
1135 e.style.display = 'block';
1136 });
1137 onEach(document.getElementsByClassName("toggle-label"), function(e) {
1138 e.style.display = 'none';
1139 });
1140 onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
1141 removeClass(e, "collapsed");
1142 });
1143 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1144 onEveryMatchingChild(e, "inner", function(i_e) {
1145 i_e.innerHTML = labelForToggleButton(false);
1146 });
1147 });
1148 } else {
1149 addClass(toggle, "will-expand");
1150 onEveryMatchingChild(toggle, "inner", function(e) {
1151 e.innerHTML = labelForToggleButton(true);
1152 });
1153 toggle.title = "expand all docs";
1154 onEach(document.getElementsByClassName("docblock"), function(e) {
1155 e.style.display = 'none';
1156 });
1157 onEach(document.getElementsByClassName("toggle-label"), function(e) {
1158 e.style.display = 'inline-block';
1159 });
1160 onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
1161 addClass(e, "collapsed");
1162 });
1163 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1164 onEveryMatchingChild(e, "inner", function(i_e) {
1165 i_e.innerHTML = labelForToggleButton(true);
1166 });
1167 });
1168 }
1169 }
1170
1171 function collapseDocs(toggle) {
1172 if (!toggle || !toggle.parentNode) {
1173 return;
1174 }
1175 var relatedDoc = toggle.parentNode.nextElementSibling;
1176 if (hasClass(relatedDoc, "stability")) {
1177 relatedDoc = relatedDoc.nextElementSibling;
1178 }
1179 if (hasClass(relatedDoc, "docblock")) {
1180 if (!isHidden(relatedDoc)) {
1181 relatedDoc.style.display = 'none';
1182 onEach(toggle.childNodes, function(e) {
1183 if (hasClass(e, 'toggle-label')) {
1184 e.style.display = 'inline-block';
1185 }
1186 if (hasClass(e, 'inner')) {
1187 e.innerHTML = labelForToggleButton(true);
1188 }
1189 });
1190 addClass(toggle.parentNode, 'collapsed');
1191 } else {
1192 relatedDoc.style.display = 'block';
1193 removeClass(toggle.parentNode, 'collapsed');
1194 onEach(toggle.childNodes, function(e) {
1195 if (hasClass(e, 'toggle-label')) {
1196 e.style.display = 'none';
1197 }
1198 if (hasClass(e, 'inner')) {
1199 e.innerHTML = labelForToggleButton(false);
1200 }
1201 });
1202 }
1203 }
1204 }
1205
1206 var x = document.getElementById('toggle-all-docs');
1207 if (x) {
1208 x.onclick = toggleAllDocs;
1209 }
1210
1211 function insertAfter(newNode, referenceNode) {
1212 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
1213 }
1214
1215 var toggle = document.createElement('a');
1216 toggle.href = 'javascript:void(0)';
1217 toggle.className = 'collapse-toggle';
1218 toggle.innerHTML = "[<span class='inner'>"+labelForToggleButton(false)+"</span>]";
1219
1220 var func = function(e) {
1221 var next = e.nextElementSibling;
1222 if (!next) {
1223 return;
1224 }
1225 if (hasClass(next, 'docblock') ||
1226 (hasClass(next, 'stability') &&
1227 hasClass(next.nextElementSibling, 'docblock'))) {
1228 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
1229 }
1230 }
1231 onEach(document.getElementsByClassName('method'), func);
1232 onEach(document.getElementsByClassName('impl-items'), function(e) {
1233 onEach(e.getElementsByClassName('associatedconstant'), func);
1234 });
1235
1236 function createToggle() {
1237 var span = document.createElement('span');
1238 span.className = 'toggle-label';
1239 span.style.display = 'none';
1240 span.innerHTML = '&nbsp;Expand&nbsp;description';
1241
1242 var mainToggle = toggle.cloneNode(true);
1243 mainToggle.appendChild(span);
1244
1245 var wrapper = document.createElement('div');
1246 wrapper.className = 'toggle-wrapper';
1247 wrapper.appendChild(mainToggle);
1248 return wrapper;
1249 }
1250
1251 onEach(document.getElementById('main').getElementsByClassName('docblock'), function(e) {
1252 if (e.parentNode.id === "main") {
1253 e.parentNode.insertBefore(createToggle(), e);
1254 }
1255 });
1256
1257 onEach(document.getElementsByClassName('docblock'), function(e) {
1258 if (hasClass(e, 'autohide')) {
1259 var wrap = e.previousElementSibling;
1260 if (wrap && hasClass(wrap, 'toggle-wrapper')) {
1261 var toggle = wrap.childNodes[0];
1262 if (e.childNodes[0].tagName === 'H3') {
1263 onEach(toggle.getElementsByClassName('toggle-label'), function(i_e) {
1264 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
1265 });
1266 }
1267 e.style.display = 'none';
1268 addClass(wrap, 'collapsed');
1269 onEach(toggle.getElementsByClassName('inner'), function(e) {
1270 e.innerHTML = labelForToggleButton(true);
1271 });
1272 onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
1273 e.style.display = 'block';
1274 });
1275 }
1276 }
1277 })
1278
1279 function createToggleWrapper() {
1280 var span = document.createElement('span');
1281 span.className = 'toggle-label';
1282 span.style.display = 'none';
1283 span.innerHTML = '&nbsp;Expand&nbsp;attributes';
1284 toggle.appendChild(span);
1285
1286 var wrapper = document.createElement('div');
1287 wrapper.className = 'toggle-wrapper toggle-attributes';
1288 wrapper.appendChild(toggle);
1289 return wrapper;
1290 }
1291
1292 onEach(document.getElementById('main').getElementsByTagName('pre'), function(e) {
1293 onEach(e.getElementsByClassName('attributes'), function(i_e) {
1294 i_e.parentNode.insertBefore(createToggleWrapper(), i_e);
1295 collapseDocs(i_e.previousSibling.childNodes[0]);
1296 });
1297 });
1298 }());
1299
1300 // Sets the focus on the search bar at the top of the page
1301 function focusSearchBar() {
1302 document.getElementsByClassName('search-input')[0].focus();
1303 }