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, searchIndex: true, rootPath: true, allPaths: true */
16 var resizeTimeout, interval;
18 $('.js-only').removeClass('js-only');
20 function getQueryStringParams() {
22 window.location.search.substring(1).split("&").
24 var pair = s.split("=");
25 params[decodeURIComponent(pair[0])] =
26 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
31 function browserSupportsHistoryApi() {
32 return window.history && typeof window.history.pushState === "function";
35 function resizeShortBlocks() {
37 clearTimeout(resizeTimeout);
39 resizeTimeout = setTimeout(function() {
40 var contentWidth = $('.content').width();
41 $('.docblock.short').width(function() {
42 return contentWidth - 40 - $(this).prev().width();
43 }).addClass('nowrap');
47 $(window).on('resize', resizeShortBlocks);
49 function highlightSourceLines() {
50 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
52 from = parseInt(match[1], 10);
53 to = Math.min(50000, parseInt(match[2] || match[1], 10));
54 from = Math.min(from, to);
55 if ($('#' + from).length === 0) {
58 $('#' + from)[0].scrollIntoView();
59 $('.line-numbers span').removeClass('line-highlighted');
60 for (i = from; i <= to; i += 1) {
61 $('#' + i).addClass('line-highlighted');
65 highlightSourceLines();
66 $(window).on('hashchange', highlightSourceLines);
68 $(document).on('keyup', function(e) {
69 if (document.activeElement.tagName === 'INPUT') {
73 if (e.keyCode === 188 && $('#help').hasClass('hidden')) { // question mark
75 $('#help').removeClass('hidden');
76 } else if (e.keyCode === 27) { // esc
77 if (!$('#help').hasClass('hidden')) {
79 $('#help').addClass('hidden');
80 } else if (!$('#search').hasClass('hidden')) {
82 $('#search').addClass('hidden');
83 $('#main').removeClass('hidden');
85 } else if (e.keyCode === 83) { // S
87 $('.search-input').focus();
89 }).on('click', function(e) {
90 if (!$(e.target).closest('#help').length) {
91 $('#help').addClass('hidden');
95 $('.version-selector').on('change', function() {
97 url = document.location.href,
99 len = rootPath.match(/\.\.\//g).length + 1;
101 for (i = 0; i < len; i += 1) {
102 match = url.match(/\/[^\/]*$/);
104 stripped = match[0] + stripped;
106 url = url.substring(0, url.length - match[0].length);
109 url += '/' + $('.version-selector').val() + stripped;
111 document.location.href = url;
114 function initSearch(searchIndex) {
115 var currentResults, index, params = getQueryStringParams();
117 // Populate search bar with query string search term when provided,
118 // but only if the input bar is empty. This avoid the obnoxious issue
119 // where you start trying to do a search, and the index loads, and
120 // suddenly your search is gone!
121 if ($(".search-input")[0].value === "") {
122 $(".search-input")[0].value = params.search || '';
126 * Executes the query and builds an index of results
127 * @param {[Object]} query [The user query]
128 * @param {[type]} max [The maximum results returned]
129 * @param {[type]} searchWords [The list of search words to query against]
130 * @return {[type]} [A search index of results]
132 function execQuery(query, max, searchWords) {
133 var valLower = query.query.toLowerCase(),
135 typeFilter = query.type,
139 split = valLower.split("::");
141 //remove empty keywords
142 for (var j = 0; j < split.length; j++) {
143 split[j].toLowerCase();
144 if (split[j] === "") {
149 // quoted values mean literal search
150 bb = searchWords.length;
151 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") && val.charAt(val.length - 1) === val.charAt(0)) {
152 val = val.substr(1, val.length - 2);
153 for (aa = 0; aa < bb; aa += 1) {
154 if (searchWords[aa] === val) {
155 // filter type: ... queries
156 if (!typeFilter || typeFilter === searchIndex[aa].ty) {
157 results.push([aa, -1]);
160 if (results.length === max) {
165 // gather matching search results up to a certain maximum
166 val = val.replace(/\_/g, "");
167 for (var i = 0; i < split.length; i++) {
168 for (aa = 0; aa < bb; aa += 1) {
169 if (searchWords[aa].indexOf(split[i]) > -1 || searchWords[aa].indexOf(val) > -1 || searchWords[aa].replace(/_/g, "").indexOf(val) > -1) {
170 // filter type: ... queries
171 if (!typeFilter || typeFilter === searchIndex[aa].ty) {
172 results.push([aa, searchWords[aa].replace(/_/g, "").indexOf(val)]);
175 if (results.length === max) {
183 for (aa = 0; aa < bb; aa += 1) {
184 results[aa].push(searchIndex[results[aa][0]].ty);
185 results[aa].push(searchIndex[results[aa][0]].path);
186 results[aa].push(searchIndex[results[aa][0]].name);
187 results[aa].push(searchIndex[results[aa][0]].parent);
189 // if there are no results then return to default and fail
190 if (results.length === 0) {
194 // sort by exact match
195 results.sort(function search_complete_sort0(aaa, bbb) {
196 if (searchWords[aaa[0]] === valLower && searchWords[bbb[0]] !== valLower) {
200 // first sorting attempt
201 // sort by item name length
202 results.sort(function search_complete_sort1(aaa, bbb) {
203 if (searchWords[aaa[0]].length > searchWords[bbb[0]].length) {
207 // second sorting attempt
209 results.sort(function search_complete_sort1(aaa, bbb) {
210 if (searchWords[aaa[0]].length === searchWords[bbb[0]].length && searchWords[aaa[0]] > searchWords[bbb[0]]) {
214 // third sorting attempt
215 // sort by index of keyword in item name
216 if (results[0][1] !== -1) {
217 results.sort(function search_complete_sort1(aaa, bbb) {
218 if (aaa[1] > bbb[1] && bbb[1] === 0) {
223 // fourth sorting attempt
225 results.sort(function search_complete_sort3(aaa, bbb) {
226 if (searchWords[aaa[0]] === searchWords[bbb[0]] && aaa[2] > bbb[2]) {
230 // fifth sorting attempt
232 results.sort(function search_complete_sort4(aaa, bbb) {
233 if (searchWords[aaa[0]] === searchWords[bbb[0]] && aaa[2] === bbb[2] && aaa[3] > bbb[3]) {
237 // sixth sorting attempt
238 // remove duplicates, according to the data provided
239 for (aa = results.length - 1; aa > 0; aa -= 1) {
240 if (searchWords[results[aa][0]] === searchWords[results[aa - 1][0]] && results[aa][2] === results[aa - 1][2] && results[aa][3] === results[aa - 1][3]) {
244 for (var i = 0; i < results.length; i++) {
245 var result = results[i],
246 name = result[4].toLowerCase(),
247 path = result[3].toLowerCase(),
248 parent = allPaths[result[5]];
250 var valid = validateResult(name, path, split, parent);
259 * Validate performs the following boolean logic. For example: "File::open" will give
260 * IF A PARENT EXISTS => ("file" && "open") exists in (name || path || parent)
261 * OR => ("file" && "open") exists in (name || path )
263 * This could be written functionally, but I wanted to minimise functions on stack.
264 * @param {[string]} name [The name of the result]
265 * @param {[string]} path [The path of the result]
266 * @param {[string]} keys [The keys to be used (["file", "open"])]
267 * @param {[object]} parent [The parent of the result]
268 * @return {[boolean]} [Whether the result is valid or not]
270 function validateResult(name, path, keys, parent) {
273 //if there is a parent, then validate against parent
274 if (parent !== undefined) {
275 for (var i = 0; i < keys.length; i++) {
276 // if previous keys are valid and current key is in the path, name or parent
277 if ((validate) && (name.toLowerCase().indexOf(keys[i]) > -1 || path.toLowerCase().indexOf(keys[i]) > -1 || parent.name.toLowerCase().indexOf(keys[i]) > -1)) {
284 for (var i = 0; i < keys.length; i++) {
285 // if previous keys are valid and current key is in the path, name
286 if ((validate) && (name.toLowerCase().indexOf(keys[i]) > -1 || path.toLowerCase().indexOf(keys[i]) > -1)) {
296 function getQuery() {
297 var matches, type, query = $('.search-input').val();
299 matches = query.match(/^(fn|mod|str(uct)?|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
301 type = matches[1].replace(/^td$/, 'typedef').replace(/^str$/, 'struct').replace(/^tdef$/, 'typedef').replace(/^typed$/, 'typedef');
302 query = query.substring(matches[0].length);
312 function initSearchNav() {
313 var hoverTimeout, $results = $('.search-results .result');
315 $results.on('click', function() {
316 var dst = $(this).find('a')[0];
317 console.log(window.location.pathname, dst.pathname);
318 if (window.location.pathname == dst.pathname) {
319 $('#search').addClass('hidden');
320 $('#main').removeClass('hidden');
322 document.location.href = dst.href;
323 }).on('mouseover', function() {
325 clearTimeout(hoverTimeout);
326 hoverTimeout = setTimeout(function() {
327 $results.removeClass('highlighted');
328 $el.addClass('highlighted');
332 $(document).off('keypress.searchnav');
333 $(document).on('keypress.searchnav', function(e) {
334 var $active = $results.filter('.highlighted');
336 if (e.keyCode === 38) { // up
338 if (!$active.length || !$active.prev()) {
342 $active.prev().addClass('highlighted');
343 $active.removeClass('highlighted');
344 } else if (e.keyCode === 40) { // down
346 if (!$active.length) {
347 $results.first().addClass('highlighted');
348 } else if ($active.next().length) {
349 $active.next().addClass('highlighted');
350 $active.removeClass('highlighted');
352 } else if (e.keyCode === 13) { // return
354 if ($active.length) {
355 document.location.href = $active.find('a').prop('href');
361 function showResults(results) {
362 var output, shown, query = getQuery();
364 currentResults = query.id;
365 output = '<h1>Results for ' + query.query + (query.type ? ' (type: ' + query.type + ')' : '') + '</h1>';
366 output += '<table class="search-results">';
368 if (results.length > 0) {
371 results.forEach(function(item) {
374 if (shown.indexOf(item) !== -1) {
382 output += '<tr class="' + type + ' result"><td>';
384 if (type === 'mod') {
385 output += item.path +
386 '::<a href="' + rootPath +
387 item.path.replace(/::/g, '/') + '/' +
388 name + '/index.html" class="' +
389 type + '">' + name + '</a>';
390 } else if (type === 'static' || type === 'reexport') {
391 output += item.path +
392 '::<a href="' + rootPath +
393 item.path.replace(/::/g, '/') +
394 '/index.html" class="' + type +
395 '">' + name + '</a>';
396 } else if (item.parent !== undefined) {
397 var myparent = allPaths[item.parent];
398 var anchor = '#' + type + '.' + name;
399 output += item.path + '::' + myparent.name +
400 '::<a href="' + rootPath +
401 item.path.replace(/::/g, '/') +
402 '/' + myparent.type +
403 '.' + myparent.name +
406 '">' + name + '</a>';
408 output += item.path +
409 '::<a href="' + rootPath +
410 item.path.replace(/::/g, '/') +
413 '.html" class="' + type +
414 '">' + name + '</a>';
417 output += '</td><td><span class="desc">' + item.desc +
421 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
422 encodeURIComponent('rust ' + query.query) +
423 '">Try on DuckDuckGo?</a>';
427 $('#main.content').addClass('hidden');
428 $('#search.content').removeClass('hidden').html(output);
429 $('#search .desc').width($('#search').width() - 40 -
430 $('#search td:first-child').first().width());
441 var params = getQueryStringParams();
448 if (!query.query || query.id === currentResults) {
452 // Because searching is incremental by character, only the most recent search query
453 // is added to the browser history.
454 if (browserSupportsHistoryApi()) {
455 if (!history.state && !params.search) {
456 history.pushState(query, "", "?search=" + encodeURIComponent(query.query));
458 history.replaceState(query, "", "?search=" + encodeURIComponent(query.query));
462 resultIndex = execQuery(query, 20000, index);
463 len = resultIndex.length;
464 for (i = 0; i < len; i += 1) {
465 if (resultIndex[i][0] > -1) {
466 obj = searchIndex[resultIndex[i][0]];
467 filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
470 if (results.length >= maxResults) {
475 // TODO add sorting capability through this function?
477 // // the handler for the table heading filtering
478 // filterdraw = function search_complete_filterdraw(node) {
482 // tbody = node.parentNode.parentNode.nextSibling,
492 // // the 4 following conditions set the rules for each
494 // if (node === ths[0]) {
497 // ths[1].innerHTML = ths[1].innerHTML.split(" ")[0];
498 // ths[2].innerHTML = ths[2].innerHTML.split(" ")[0];
499 // ths[3].innerHTML = ths[3].innerHTML.split(" ")[0];
501 // if (node === ths[1]) {
504 // ths[0].innerHTML = ths[0].innerHTML.split(" ")[0];
505 // ths[2].innerHTML = ths[2].innerHTML.split(" ")[0];
506 // ths[3].innerHTML = ths[3].innerHTML.split(" ")[0];
508 // if (node === ths[2]) {
511 // ths[0].innerHTML = ths[0].innerHTML.split(" ")[0];
512 // ths[1].innerHTML = ths[1].innerHTML.split(" ")[0];
513 // ths[3].innerHTML = ths[3].innerHTML.split(" ")[0];
515 // if (node === ths[3]) {
517 // name = "description";
518 // ths[0].innerHTML = ths[0].innerHTML.split(" ")[0];
519 // ths[1].innerHTML = ths[1].innerHTML.split(" ")[0];
520 // ths[2].innerHTML = ths[2].innerHTML.split(" ")[0];
523 // // ascending or descending search
524 // arrow = node.innerHTML.split(" ")[1];
525 // if (arrow === undefined || arrow === "\u25b2") {
531 // // filter the data
532 // filterdata.sort(function search_complete_filterDraw_sort(xx, yy) {
533 // if ((arrow === "\u25b2" && xx[op].toLowerCase() < yy[op].toLowerCase()) || (arrow === "\u25bc" && xx[op].toLowerCase() > yy[op].toLowerCase())) {
539 showResults(results);
542 function buildIndex(searchIndex) {
543 var len = searchIndex.length,
547 // before any analysis is performed lets gather the search terms to
548 // search against apart from the rest of the data. This is a quick
549 // operation that is cached for the life of the page state so that
550 // all other search operations have access to this cached data for
551 // faster analysis operations
552 for (i = 0; i < len; i += 1) {
553 if (typeof searchIndex[i].name === "string") {
554 searchWords.push(searchIndex[i].name.toLowerCase());
556 searchWords.push("");
563 function startSearch() {
565 $('.do-search').on('click', search);
566 $('.search-input').on('keyup', function() {
567 clearTimeout(keyUpTimeout);
568 keyUpTimeout = setTimeout(search, 100);
570 // Push and pop states are used to add search results to the browser history.
571 if (browserSupportsHistoryApi()) {
572 $(window).on('popstate', function(e) {
573 var params = getQueryStringParams();
574 // When browsing back from search results the main page visibility must be reset.
575 if (!params.search) {
576 $('#main.content').removeClass('hidden');
577 $('#search.content').addClass('hidden');
579 // When browsing forward to search results the previous search will be repeated,
580 // so the currentResults are cleared to ensure the search is successful.
581 currentResults = null;
582 // Synchronize search bar with query string state and
583 // perform the search, but don't empty the bar if there's
585 if (params.search !== undefined) {
586 $('.search-input').val(params.search);
588 // Some browsers fire 'onpopstate' for every page load (Chrome), while others fire the
589 // event only when actually popping a state (Firefox), which is why search() is called
590 // both here and at the end of the startSearch() function.
597 index = buildIndex(searchIndex);
601 initSearch(searchIndex);