1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /*jslint browser: true, es5: true */
12 /*globals $: true, rootPath: true */
16 var resizeTimeout, interval;
18 // This mapping table should match the discriminants of
19 // `rustdoc::html::item_type::ItemType` type in Rust.
20 var itemTypes = ["mod",
39 $('.js-only').removeClass('js-only');
41 function getQueryStringParams() {
43 window.location.search.substring(1).split("&").
45 var pair = s.split("=");
46 params[decodeURIComponent(pair[0])] =
47 typeof pair[1] === "undefined" ?
48 null : decodeURIComponent(pair[1]);
53 function browserSupportsHistoryApi() {
54 return window.history && typeof window.history.pushState === "function";
57 function highlightSourceLines(ev) {
58 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
60 from = parseInt(match[1], 10);
61 to = Math.min(50000, parseInt(match[2] || match[1], 10));
62 from = Math.min(from, to);
63 if ($('#' + from).length === 0) {
66 if (ev === null) $('#' + from)[0].scrollIntoView();
67 $('.line-numbers span').removeClass('line-highlighted');
68 for (i = from; i <= to; ++i) {
69 $('#' + i).addClass('line-highlighted');
73 highlightSourceLines(null);
74 $(window).on('hashchange', highlightSourceLines);
76 $(document).on('keyup', function(e) {
77 if (document.activeElement.tagName === 'INPUT') {
81 if (e.which === 191) { // question mark
82 if (e.shiftKey && $('#help').hasClass('hidden')) {
84 $('#help').removeClass('hidden');
86 } else if (e.which === 27) { // esc
87 if (!$('#help').hasClass('hidden')) {
89 $('#help').addClass('hidden');
90 } else if (!$('#search').hasClass('hidden')) {
92 $('#search').addClass('hidden');
93 $('#main').removeClass('hidden');
95 } else if (e.which === 83) { // S
97 $('.search-input').focus();
99 }).on('click', function(e) {
100 if (!$(e.target).closest('#help').length) {
101 $('#help').addClass('hidden');
105 $('.version-selector').on('change', function() {
107 url = document.location.href,
109 len = rootPath.match(/\.\.\//g).length + 1;
111 for (i = 0; i < len; ++i) {
112 match = url.match(/\/[^\/]*$/);
114 stripped = match[0] + stripped;
116 url = url.substring(0, url.length - match[0].length);
119 url += '/' + $('.version-selector').val() + stripped;
121 document.location.href = url;
124 * A function to compute the Levenshtein distance between two strings
125 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
126 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
127 * This code is an unmodified version of the code written by Marco de Wit
128 * and was found at http://stackoverflow.com/a/18514751/745719
130 var levenshtein = (function() {
132 return function(s1, s2) {
136 var s1_len = s1.length, s2_len = s2.length;
137 if (s1_len && s2_len) {
138 var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
141 while (i2 < s2_len) {
142 c2 = s2.charCodeAt(i2);
146 for (i1 = 0; i1 < s1_len; ++i1) {
147 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
149 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
155 return s1_len + s2_len;
161 function initSearch(rawSearchIndex) {
162 var currentResults, index, searchIndex;
163 var MAX_LEV_DISTANCE = 3;
164 var params = getQueryStringParams();
166 // Populate search bar with query string search term when provided,
167 // but only if the input bar is empty. This avoid the obnoxious issue
168 // where you start trying to do a search, and the index loads, and
169 // suddenly your search is gone!
170 if ($(".search-input")[0].value === "") {
171 $(".search-input")[0].value = params.search || '';
175 * Executes the query and builds an index of results
176 * @param {[Object]} query [The user query]
177 * @param {[type]} max [The maximum results returned]
178 * @param {[type]} searchWords [The list of search words to query
180 * @return {[type]} [A search index of results]
182 function execQuery(query, max, searchWords) {
183 var valLower = query.query.toLowerCase(),
185 typeFilter = itemTypeFromName(query.type),
187 split = valLower.split("::");
189 //remove empty keywords
190 for (var j = 0; j < split.length; ++j) {
191 split[j].toLowerCase();
192 if (split[j] === "") {
197 // quoted values mean literal search
198 var nSearchWords = searchWords.length;
199 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
200 val.charAt(val.length - 1) === val.charAt(0))
202 val = val.substr(1, val.length - 2);
203 for (var i = 0; i < nSearchWords; ++i) {
204 if (searchWords[i] === val) {
205 // filter type: ... queries
206 if (typeFilter < 0 || typeFilter === searchIndex[i].ty) {
207 results.push({id: i, index: -1});
210 if (results.length === max) {
215 } else if (val.search("->") > -1) {
216 var trimmer = function (s) { return s.trim(); };
217 var parts = val.split("->").map(trimmer);
218 var input = parts[0];
219 // sort inputs so that order does not matter
220 var inputs = input.split(",").map(trimmer).sort();
221 var output = parts[1];
223 for (var i = 0; i < nSearchWords; ++i) {
224 var type = searchIndex[i].type;
229 // sort index inputs so that order does not matter
230 var typeInputs = type.inputs.map(function (input) {
234 // allow searching for void (no output) functions as well
235 var typeOutput = type.output ? type.output.name : "";
236 if (inputs.toString() === typeInputs.toString() &&
237 output == typeOutput) {
238 results.push({id: i, index: -1, dontValidate: true});
242 // gather matching search results up to a certain maximum
243 val = val.replace(/\_/g, "");
244 for (var i = 0; i < split.length; ++i) {
245 for (var j = 0; j < nSearchWords; ++j) {
247 if (searchWords[j].indexOf(split[i]) > -1 ||
248 searchWords[j].indexOf(val) > -1 ||
249 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
251 // filter type: ... queries
252 if (typeFilter < 0 || typeFilter === searchIndex[j].ty) {
255 index: searchWords[j].replace(/_/g, "").indexOf(val),
260 (lev_distance = levenshtein(searchWords[j], val)) <=
262 if (typeFilter < 0 || typeFilter === searchIndex[j].ty) {
266 // we want lev results to go lower than others
271 if (results.length === max) {
278 var nresults = results.length;
279 for (var i = 0; i < nresults; ++i) {
280 results[i].word = searchWords[results[i].id];
281 results[i].item = searchIndex[results[i].id] || {};
283 // if there are no results then return to default and fail
284 if (results.length === 0) {
288 results.sort(function(aaa, bbb) {
291 // Sort by non levenshtein results and then levenshtein results by the distance
292 // (less changes required to match means higher rankings)
295 if (a !== b) return a - b;
297 // sort by crate (non-current crate goes later)
298 a = (aaa.item.crate !== window.currentCrate);
299 b = (bbb.item.crate !== window.currentCrate);
300 if (a !== b) return a - b;
302 // sort by exact match (mismatch goes later)
303 a = (aaa.word !== valLower);
304 b = (bbb.word !== valLower);
305 if (a !== b) return a - b;
307 // sort by item name length (longer goes later)
310 if (a !== b) return a - b;
312 // sort by item name (lexicographically larger goes later)
315 if (a !== b) return (a > b ? +1 : -1);
317 // sort by index of keyword in item name (no literal occurrence goes later)
320 if (a !== b) return a - b;
321 // (later literal occurrence, if any, goes later)
324 if (a !== b) return a - b;
326 // sort by description (no description goes later)
327 a = (aaa.item.desc === '');
328 b = (bbb.item.desc === '');
329 if (a !== b) return a - b;
331 // sort by type (later occurrence in `itemTypes` goes later)
334 if (a !== b) return a - b;
336 // sort by path (lexicographically larger goes later)
339 if (a !== b) return (a > b ? +1 : -1);
345 // remove duplicates, according to the data provided
346 for (var i = results.length - 1; i > 0; i -= 1) {
347 if (results[i].word === results[i - 1].word &&
348 results[i].item.ty === results[i - 1].item.ty &&
349 results[i].item.path === results[i - 1].item.path &&
350 (results[i].item.parent || {}).name === (results[i - 1].item.parent || {}).name)
355 for (var i = 0; i < results.length; ++i) {
356 var result = results[i],
357 name = result.item.name.toLowerCase(),
358 path = result.item.path.toLowerCase(),
359 parent = result.item.parent;
361 // this validation does not make sense when searching by types
362 if (result.dontValidate) {
366 var valid = validateResult(name, path, split, parent);
375 * Validate performs the following boolean logic. For example:
376 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
377 * exists in (name || path || parent) OR => ("file" && "open") exists in
380 * This could be written functionally, but I wanted to minimise
381 * functions on stack.
383 * @param {[string]} name [The name of the result]
384 * @param {[string]} path [The path of the result]
385 * @param {[string]} keys [The keys to be used (["file", "open"])]
386 * @param {[object]} parent [The parent of the result]
387 * @return {[boolean]} [Whether the result is valid or not]
389 function validateResult(name, path, keys, parent) {
390 for (var i=0; i < keys.length; ++i) {
391 // each check is for validation so we negate the conditions and invalidate
393 // check for an exact name match
394 name.toLowerCase().indexOf(keys[i]) > -1 ||
395 // then an exact path match
396 path.toLowerCase().indexOf(keys[i]) > -1 ||
397 // next if there is a parent, check for exact parent match
398 (parent !== undefined &&
399 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
400 // lastly check to see if the name was a levenshtein match
401 levenshtein(name.toLowerCase(), keys[i]) <=
409 function getQuery() {
410 var matches, type, query, raw = $('.search-input').val();
413 matches = query.match(/^(fn|mod|struct|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
415 type = matches[1].replace(/^td$/, 'typedef')
416 .replace(/^tdef$/, 'typedef')
417 .replace(/^typed$/, 'typedef');
418 query = query.substring(matches[0].length);
429 function initSearchNav() {
430 var hoverTimeout, $results = $('.search-results .result');
432 $results.on('click', function() {
433 var dst = $(this).find('a')[0];
434 if (window.location.pathname == dst.pathname) {
435 $('#search').addClass('hidden');
436 $('#main').removeClass('hidden');
437 document.location.href = dst.href;
439 }).on('mouseover', function() {
441 clearTimeout(hoverTimeout);
442 hoverTimeout = setTimeout(function() {
443 $results.removeClass('highlighted');
444 $el.addClass('highlighted');
448 $(document).off('keydown.searchnav');
449 $(document).on('keydown.searchnav', function(e) {
450 var $active = $results.filter('.highlighted');
452 if (e.which === 38) { // up
454 if (!$active.length || !$active.prev()) {
458 $active.prev().addClass('highlighted');
459 $active.removeClass('highlighted');
460 } else if (e.which === 40) { // down
462 if (!$active.length) {
463 $results.first().addClass('highlighted');
464 } else if ($active.next().length) {
465 $active.next().addClass('highlighted');
466 $active.removeClass('highlighted');
468 } else if (e.which === 13) { // return
470 if ($active.length) {
471 document.location.href = $active.find('a').prop('href');
474 $active.removeClass('highlighted');
479 function escape(content) {
480 return $('<h1/>').text(content).html();
483 function showResults(results) {
484 var output, shown, query = getQuery();
486 currentResults = query.id;
487 output = '<h1>Results for ' + escape(query.query) +
488 (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>';
489 output += '<table class="search-results">';
491 if (results.length > 0) {
494 results.forEach(function(item) {
495 var name, type, href, displayPath;
497 if (shown.indexOf(item) !== -1) {
503 type = itemTypes[item.ty];
505 if (type === 'mod') {
506 displayPath = item.path + '::';
507 href = rootPath + item.path.replace(/::/g, '/') + '/' +
508 name + '/index.html';
509 } else if (type === 'static' || type === 'reexport') {
510 displayPath = item.path + '::';
511 href = rootPath + item.path.replace(/::/g, '/') +
513 } else if (item.parent !== undefined) {
514 var myparent = item.parent;
515 var anchor = '#' + type + '.' + name;
516 displayPath = item.path + '::' + myparent.name + '::';
517 href = rootPath + item.path.replace(/::/g, '/') +
518 '/' + itemTypes[myparent.ty] +
519 '.' + myparent.name +
522 displayPath = item.path + '::';
523 href = rootPath + item.path.replace(/::/g, '/') +
524 '/' + type + '.' + name + '.html';
527 output += '<tr class="' + type + ' result"><td>' +
528 '<a href="' + href + '">' +
529 displayPath + '<span class="' + type + '">' +
530 name + '</span></a></td><td>' +
531 '<a href="' + href + '">' +
532 '<span class="desc">' + item.desc +
533 ' </span></a></td></tr>';
536 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
537 encodeURIComponent('rust ' + query.query) +
538 '">Try on DuckDuckGo?</a>';
542 $('#main.content').addClass('hidden');
543 $('#search.content').removeClass('hidden').html(output);
544 $('#search .desc').width($('#search').width() - 40 -
545 $('#search td:first-child').first().width());
556 var params = getQueryStringParams();
563 if (!query.query || query.id === currentResults) {
567 // Because searching is incremental by character, only the most
568 // recent search query is added to the browser history.
569 if (browserSupportsHistoryApi()) {
570 if (!history.state && !params.search) {
571 history.pushState(query, "", "?search=" +
572 encodeURIComponent(query.raw));
574 history.replaceState(query, "", "?search=" +
575 encodeURIComponent(query.raw));
579 resultIndex = execQuery(query, 20000, index);
580 len = resultIndex.length;
581 for (i = 0; i < len; ++i) {
582 if (resultIndex[i].id > -1) {
583 obj = searchIndex[resultIndex[i].id];
584 filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
587 if (results.length >= maxResults) {
592 showResults(results);
595 function itemTypeFromName(typename) {
596 for (var i = 0; i < itemTypes.length; ++i) {
597 if (itemTypes[i] === typename) return i;
602 function buildIndex(rawSearchIndex) {
604 var searchWords = [];
605 for (var crate in rawSearchIndex) {
606 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
608 // an array of [(Number) item type,
610 // (String) full path or empty string for previous path,
611 // (String) description,
612 // (Number | null) the parent path index to `paths`]
613 // (Object | null) the type of the function (if any)
614 var items = rawSearchIndex[crate].items;
615 // an array of [(Number) item type,
617 var paths = rawSearchIndex[crate].paths;
619 // convert `paths` into an object form
620 var len = paths.length;
621 for (var i = 0; i < len; ++i) {
622 paths[i] = {ty: paths[i][0], name: paths[i][1]};
625 // convert `items` into an object form, and construct word indices.
627 // before any analysis is performed lets gather the search terms to
628 // search against apart from the rest of the data. This is a quick
629 // operation that is cached for the life of the page state so that
630 // all other search operations have access to this cached data for
631 // faster analysis operations
632 var len = items.length;
634 for (var i = 0; i < len; ++i) {
635 var rawRow = items[i];
636 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
637 path: rawRow[2] || lastPath, desc: rawRow[3],
638 parent: paths[rawRow[4]], type: rawRow[5]};
639 searchIndex.push(row);
640 if (typeof row.name === "string") {
641 var word = row.name.toLowerCase();
642 searchWords.push(word);
644 searchWords.push("");
652 function startSearch() {
654 $('.do-search').on('click', search);
655 $('.search-input').on('keyup', function() {
656 clearTimeout(keyUpTimeout);
657 keyUpTimeout = setTimeout(search, 500);
660 // Push and pop states are used to add search results to the browser
662 if (browserSupportsHistoryApi()) {
663 $(window).on('popstate', function(e) {
664 var params = getQueryStringParams();
665 // When browsing back from search results the main page
666 // visibility must be reset.
667 if (!params.search) {
668 $('#main.content').removeClass('hidden');
669 $('#search.content').addClass('hidden');
671 // When browsing forward to search results the previous
672 // search will be repeated, so the currentResults are
673 // cleared to ensure the search is successful.
674 currentResults = null;
675 // Synchronize search bar with query string state and
676 // perform the search. This will empty the bar if there's
677 // nothing there, which lets you really go back to a
678 // previous state with nothing in the bar.
679 $('.search-input').val(params.search);
680 // Some browsers fire 'onpopstate' for every page load
681 // (Chrome), while others fire the event only when actually
682 // popping a state (Firefox), which is why search() is
683 // called both here and at the end of the startSearch()
691 function plainSummaryLine(markdown) {
692 var str = markdown.replace(/\n/g, ' ')
693 str = str.replace(/'/g, "\'")
694 str = str.replace(/^#+? (.+?)/, "$1")
695 str = str.replace(/\[(.*?)\]\(.*?\)/g, "$1")
696 str = str.replace(/\[(.*?)\]\[.*?\]/g, "$1")
700 index = buildIndex(rawSearchIndex);
703 // Draw a convenient sidebar of known crates if we have a listing
704 if (rootPath == '../') {
705 var sidebar = $('.sidebar');
706 var div = $('<div>').attr('class', 'block crate');
707 div.append($('<h2>').text('Crates'));
710 for (var crate in rawSearchIndex) {
711 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
715 for (var i = 0; i < crates.length; ++i) {
717 if (crates[i] == window.currentCrate) {
720 if (rawSearchIndex[crates[i]].items[0]) {
721 var desc = rawSearchIndex[crates[i]].items[0][3];
722 div.append($('<a>', {'href': '../' + crates[i] + '/index.html',
723 'title': plainSummaryLine(desc),
724 'class': klass}).text(crates[i]));
731 window.initSearch = initSearch;
733 // delayed sidebar rendering.
734 function initSidebarItems(items) {
735 var sidebar = $('.sidebar');
736 var current = window.sidebarCurrent;
738 function block(shortty, longty) {
739 var filtered = items[shortty];
740 if (!filtered) return;
742 var div = $('<div>').attr('class', 'block ' + shortty);
743 div.append($('<h2>').text(longty));
745 for (var i = 0; i < filtered.length; ++i) {
746 var item = filtered[i];
748 var desc = item[1]; // can be null
751 if (name === current.name && shortty == current.ty) {
755 if (shortty === 'mod') {
756 path = name + '/index.html';
758 path = shortty + '.' + name + '.html';
760 div.append($('<a>', {'href': current.relpath + path,
762 'class': klass}).text(name));
767 block("mod", "Modules");
768 block("struct", "Structs");
769 block("enum", "Enums");
770 block("trait", "Traits");
771 block("fn", "Functions");
772 block("macro", "Macros");
775 window.initSidebarItems = initSidebarItems;
777 window.register_implementors = function(imp) {
778 var list = $('#implementors-list');
779 var libs = Object.getOwnPropertyNames(imp);
780 for (var i = 0; i < libs.length; ++i) {
781 if (libs[i] == currentCrate) continue;
782 var structs = imp[libs[i]];
783 for (var j = 0; j < structs.length; ++j) {
784 var code = $('<code>').append(structs[j]);
785 $.each(code.find('a'), function(idx, a) {
786 var href = $(a).attr('href');
787 if (href && href.indexOf('http') !== 0) {
788 $(a).attr('href', rootPath + href);
791 var li = $('<li>').append(code);
796 if (window.pending_implementors) {
797 window.register_implementors(window.pending_implementors);
800 // See documentation in html/render.rs for what this is doing.
801 var query = getQueryStringParams();
802 if (query['gotosrc']) {
803 window.location = $('#src-' + query['gotosrc']).attr('href');
805 if (query['gotomacrosrc']) {
806 window.location = $('.srclink').attr('href');
809 $("#toggle-all-docs").on("click", function() {
810 var toggle = $("#toggle-all-docs");
811 if (toggle.html() == "[-]") {
813 toggle.attr("title", "expand all docs");
814 $(".docblock").hide();
815 $(".toggle-label").show();
816 $(".toggle-wrapper").addClass("collapsed");
817 $(".collapse-toggle").children(".inner").html("+");
820 toggle.attr("title", "collapse all docs");
821 $(".docblock").show();
822 $(".toggle-label").hide();
823 $(".toggle-wrapper").removeClass("collapsed");
824 $(".collapse-toggle").children(".inner").html("-");
828 $(document).on("click", ".collapse-toggle", function() {
829 var toggle = $(this);
830 var relatedDoc = toggle.parent().next();
831 if (relatedDoc.is(".stability")) {
832 relatedDoc = relatedDoc.next();
834 if (relatedDoc.is(".docblock")) {
835 if (relatedDoc.is(":visible")) {
836 relatedDoc.slideUp({duration:'fast', easing:'linear'});
837 toggle.parent(".toggle-wrapper").addClass("collapsed");
838 toggle.children(".inner").html("+");
839 toggle.children(".toggle-label").fadeIn();
841 relatedDoc.slideDown({duration:'fast', easing:'linear'});
842 toggle.parent(".toggle-wrapper").removeClass("collapsed");
843 toggle.children(".inner").html("-");
844 toggle.children(".toggle-label").hide();
850 var toggle = $("<a/>", {'href': 'javascript:void(0)', 'class': 'collapse-toggle'})
851 .html("[<span class='inner'>-</span>]");
853 $(".method").each(function() {
854 if ($(this).next().is(".docblock") ||
855 ($(this).next().is(".stability") && $(this).next().next().is(".docblock"))) {
856 $(this).children().first().after(toggle.clone());
862 $('<span/>', {'class': 'toggle-label'})
863 .css('display', 'none')
864 .html(' Expand description'));
865 var wrapper = $("<div class='toggle-wrapper'>").append(mainToggle);
866 $("#main > .docblock").before(wrapper);
869 $('pre.line-numbers').on('click', 'span', function() {
872 function set_fragment(name) {
873 if (history.replaceState) {
874 history.replaceState(null, null, '#' + name);
875 $(window).trigger('hashchange');
877 location.replace('#' + name);
881 return function(ev) {
882 var cur_id = parseInt(ev.target.id);
884 if (ev.shiftKey && prev_id) {
885 if (prev_id > cur_id) {
891 set_fragment(prev_id + '-' + cur_id);
895 set_fragment(cur_id);