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 $('.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" ?
27 null : decodeURIComponent(pair[1]);
32 function browserSupportsHistoryApi() {
33 return window.history && typeof window.history.pushState === "function";
36 function resizeShortBlocks() {
38 clearTimeout(resizeTimeout);
40 resizeTimeout = setTimeout(function() {
41 var contentWidth = $('.content').width();
42 $('.docblock.short').width(function() {
43 return contentWidth - 40 - $(this).prev().width();
44 }).addClass('nowrap');
48 $(window).on('resize', resizeShortBlocks);
50 function highlightSourceLines() {
51 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
53 from = parseInt(match[1], 10);
54 to = Math.min(50000, parseInt(match[2] || match[1], 10));
55 from = Math.min(from, to);
56 if ($('#' + from).length === 0) {
59 $('#' + from)[0].scrollIntoView();
60 $('.line-numbers span').removeClass('line-highlighted');
61 for (i = from; i <= to; i += 1) {
62 $('#' + i).addClass('line-highlighted');
66 highlightSourceLines();
67 $(window).on('hashchange', highlightSourceLines);
69 $(document).on('keyup', function(e) {
70 if (document.activeElement.tagName === 'INPUT') {
74 if (e.keyCode === 188 && $('#help').hasClass('hidden')) { // question mark
76 $('#help').removeClass('hidden');
77 } else if (e.keyCode === 27) { // esc
78 if (!$('#help').hasClass('hidden')) {
80 $('#help').addClass('hidden');
81 } else if (!$('#search').hasClass('hidden')) {
83 $('#search').addClass('hidden');
84 $('#main').removeClass('hidden');
86 } else if (e.keyCode === 83) { // S
88 $('.search-input').focus();
90 }).on('click', function(e) {
91 if (!$(e.target).closest('#help').length) {
92 $('#help').addClass('hidden');
96 $('.version-selector').on('change', function() {
98 url = document.location.href,
100 len = rootPath.match(/\.\.\//g).length + 1;
102 for (i = 0; i < len; i += 1) {
103 match = url.match(/\/[^\/]*$/);
105 stripped = match[0] + stripped;
107 url = url.substring(0, url.length - match[0].length);
110 url += '/' + $('.version-selector').val() + stripped;
112 document.location.href = url;
115 function initSearch(rawSearchIndex) {
116 var currentResults, index, searchIndex;
117 var params = getQueryStringParams();
119 // Populate search bar with query string search term when provided,
120 // but only if the input bar is empty. This avoid the obnoxious issue
121 // where you start trying to do a search, and the index loads, and
122 // suddenly your search is gone!
123 if ($(".search-input")[0].value === "") {
124 $(".search-input")[0].value = params.search || '';
128 * Executes the query and builds an index of results
129 * @param {[Object]} query [The user query]
130 * @param {[type]} max [The maximum results returned]
131 * @param {[type]} searchWords [The list of search words to query
133 * @return {[type]} [A search index of results]
135 function execQuery(query, max, searchWords) {
136 var valLower = query.query.toLowerCase(),
138 typeFilter = itemTypeFromName(query.type),
140 split = valLower.split("::");
142 //remove empty keywords
143 for (var j = 0; j < split.length; j++) {
144 split[j].toLowerCase();
145 if (split[j] === "") {
150 // quoted values mean literal search
151 var nSearchWords = searchWords.length;
152 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
153 val.charAt(val.length - 1) === val.charAt(0))
155 val = val.substr(1, val.length - 2);
156 for (var i = 0; i < nSearchWords; i += 1) {
157 if (searchWords[i] === val) {
158 // filter type: ... queries
159 if (typeFilter < 0 || typeFilter === searchIndex[i].ty) {
160 results.push({id: i, index: -1});
163 if (results.length === max) {
168 // gather matching search results up to a certain maximum
169 val = val.replace(/\_/g, "");
170 for (var i = 0; i < split.length; i++) {
171 for (var j = 0; j < nSearchWords; j += 1) {
172 if (searchWords[j].indexOf(split[i]) > -1 ||
173 searchWords[j].indexOf(val) > -1 ||
174 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
176 // filter type: ... queries
177 if (typeFilter < 0 || typeFilter === searchIndex[j].ty) {
178 results.push({id: j, index: searchWords[j].replace(/_/g, "").indexOf(val)});
181 if (results.length === max) {
188 var nresults = results.length;
189 for (var i = 0; i < nresults; i += 1) {
190 results[i].word = searchWords[results[i].id];
191 results[i].item = searchIndex[results[i].id] || {};
193 // if there are no results then return to default and fail
194 if (results.length === 0) {
198 results.sort(function(aaa, bbb) {
201 // sort by crate (non-current crate goes later)
202 a = (aaa.item.crate !== window.currentCrate);
203 b = (bbb.item.crate !== window.currentCrate);
204 if (a !== b) return a - b;
206 // sort by exact match (mismatch goes later)
207 a = (aaa.word !== valLower);
208 b = (bbb.word !== valLower);
209 if (a !== b) return a - b;
211 // sort by item name length (longer goes later)
214 if (a !== b) return a - b;
216 // sort by item name (lexicographically larger goes later)
219 if (a !== b) return (a > b ? +1 : -1);
221 // sort by index of keyword in item name (no literal occurrence goes later)
224 if (a !== b) return a - b;
225 // (later literal occurrence, if any, goes later)
228 if (a !== b) return a - b;
230 // sort by description (no description goes later)
231 a = (aaa.item.desc === '');
232 b = (bbb.item.desc === '');
233 if (a !== b) return a - b;
235 // sort by type (later occurrence in `itemTypes` goes later)
238 if (a !== b) return a - b;
240 // sort by path (lexicographically larger goes later)
243 if (a !== b) return (a > b ? +1 : -1);
249 // remove duplicates, according to the data provided
250 for (var i = results.length - 1; i > 0; i -= 1) {
251 if (results[i].word === results[i - 1].word &&
252 results[i].item.ty === results[i - 1].item.ty &&
253 results[i].item.path === results[i - 1].item.path)
258 for (var i = 0; i < results.length; i++) {
259 var result = results[i],
260 name = result.item.name.toLowerCase(),
261 path = result.item.path.toLowerCase(),
262 parent = result.item.parent;
264 var valid = validateResult(name, path, split, parent);
273 * Validate performs the following boolean logic. For example:
274 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
275 * exists in (name || path || parent) OR => ("file" && "open") exists in
278 * This could be written functionally, but I wanted to minimise
279 * functions on stack.
281 * @param {[string]} name [The name of the result]
282 * @param {[string]} path [The path of the result]
283 * @param {[string]} keys [The keys to be used (["file", "open"])]
284 * @param {[object]} parent [The parent of the result]
285 * @return {[boolean]} [Whether the result is valid or not]
287 function validateResult(name, path, keys, parent) {
290 //if there is a parent, then validate against parent
291 if (parent !== undefined) {
292 for (var i = 0; i < keys.length; i++) {
293 // if previous keys are valid and current key is in the
294 // path, name or parent
296 (name.toLowerCase().indexOf(keys[i]) > -1 ||
297 path.toLowerCase().indexOf(keys[i]) > -1 ||
298 parent.name.toLowerCase().indexOf(keys[i]) > -1))
306 for (var i = 0; i < keys.length; i++) {
307 // if previous keys are valid and current key is in the
310 (name.toLowerCase().indexOf(keys[i]) > -1 ||
311 path.toLowerCase().indexOf(keys[i]) > -1))
322 function getQuery() {
323 var matches, type, query = $('.search-input').val();
325 matches = query.match(/^(fn|mod|str(uct)?|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
327 type = matches[1].replace(/^td$/, 'typedef')
328 .replace(/^str$/, 'struct')
329 .replace(/^tdef$/, 'typedef')
330 .replace(/^typed$/, 'typedef');
331 query = query.substring(matches[0].length);
341 function initSearchNav() {
342 var hoverTimeout, $results = $('.search-results .result');
344 $results.on('click', function() {
345 var dst = $(this).find('a')[0];
346 if (window.location.pathname == dst.pathname) {
347 $('#search').addClass('hidden');
348 $('#main').removeClass('hidden');
350 document.location.href = dst.href;
351 }).on('mouseover', function() {
353 clearTimeout(hoverTimeout);
354 hoverTimeout = setTimeout(function() {
355 $results.removeClass('highlighted');
356 $el.addClass('highlighted');
360 $(document).off('keypress.searchnav');
361 $(document).on('keypress.searchnav', function(e) {
362 var $active = $results.filter('.highlighted');
364 if (e.keyCode === 38) { // up
366 if (!$active.length || !$active.prev()) {
370 $active.prev().addClass('highlighted');
371 $active.removeClass('highlighted');
372 } else if (e.keyCode === 40) { // down
374 if (!$active.length) {
375 $results.first().addClass('highlighted');
376 } else if ($active.next().length) {
377 $active.next().addClass('highlighted');
378 $active.removeClass('highlighted');
380 } else if (e.keyCode === 13) { // return
382 if ($active.length) {
383 document.location.href = $active.find('a').prop('href');
389 function showResults(results) {
390 var output, shown, query = getQuery();
392 currentResults = query.id;
393 output = '<h1>Results for ' + query.query +
394 (query.type ? ' (type: ' + query.type + ')' : '') + '</h1>';
395 output += '<table class="search-results">';
397 if (results.length > 0) {
400 results.forEach(function(item) {
403 if (shown.indexOf(item) !== -1) {
409 type = itemTypes[item.ty];
411 output += '<tr class="' + type + ' result"><td>';
413 if (type === 'mod') {
414 output += item.path +
415 '::<a href="' + rootPath +
416 item.path.replace(/::/g, '/') + '/' +
417 name + '/index.html" class="' +
418 type + '">' + name + '</a>';
419 } else if (type === 'static' || type === 'reexport') {
420 output += item.path +
421 '::<a href="' + rootPath +
422 item.path.replace(/::/g, '/') +
423 '/index.html" class="' + type +
424 '">' + name + '</a>';
425 } else if (item.parent !== undefined) {
426 var myparent = item.parent;
427 var anchor = '#' + type + '.' + name;
428 output += item.path + '::' + myparent.name +
429 '::<a href="' + rootPath +
430 item.path.replace(/::/g, '/') +
431 '/' + itemTypes[myparent.ty] +
432 '.' + myparent.name +
435 '">' + name + '</a>';
437 output += item.path +
438 '::<a href="' + rootPath +
439 item.path.replace(/::/g, '/') +
442 '.html" class="' + type +
443 '">' + name + '</a>';
446 output += '</td><td><span class="desc">' + item.desc +
450 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
451 encodeURIComponent('rust ' + query.query) +
452 '">Try on DuckDuckGo?</a>';
456 $('#main.content').addClass('hidden');
457 $('#search.content').removeClass('hidden').html(output);
458 $('#search .desc').width($('#search').width() - 40 -
459 $('#search td:first-child').first().width());
470 var params = getQueryStringParams();
477 if (!query.query || query.id === currentResults) {
481 // Because searching is incremental by character, only the most
482 // recent search query is added to the browser history.
483 if (browserSupportsHistoryApi()) {
484 if (!history.state && !params.search) {
485 history.pushState(query, "", "?search=" +
486 encodeURIComponent(query.query));
488 history.replaceState(query, "", "?search=" +
489 encodeURIComponent(query.query));
493 resultIndex = execQuery(query, 20000, index);
494 len = resultIndex.length;
495 for (i = 0; i < len; i += 1) {
496 if (resultIndex[i].id > -1) {
497 obj = searchIndex[resultIndex[i].id];
498 filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
501 if (results.length >= maxResults) {
506 showResults(results);
509 // This mapping table should match the discriminants of
510 // `rustdoc::html::item_type::ItemType` type in Rust.
511 var itemTypes = ["mod",
528 function itemTypeFromName(typename) {
529 for (var i = 0; i < itemTypes.length; ++i) {
530 if (itemTypes[i] === typename) return i;
535 function buildIndex(rawSearchIndex) {
537 var searchWords = [];
538 for (var crate in rawSearchIndex) {
539 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
541 // an array of [(Number) item type,
543 // (String) full path or empty string for previous path,
544 // (String) description,
545 // (optional Number) the parent path index to `paths`]
546 var items = rawSearchIndex[crate].items;
547 // an array of [(Number) item type,
549 var paths = rawSearchIndex[crate].paths;
551 // convert `paths` into an object form
552 var len = paths.length;
553 for (var i = 0; i < len; ++i) {
554 paths[i] = {ty: paths[i][0], name: paths[i][1]};
557 // convert `items` into an object form, and construct word indices.
559 // before any analysis is performed lets gather the search terms to
560 // search against apart from the rest of the data. This is a quick
561 // operation that is cached for the life of the page state so that
562 // all other search operations have access to this cached data for
563 // faster analysis operations
564 var len = items.length;
566 for (var i = 0; i < len; i += 1) {
567 var rawRow = items[i];
568 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
569 path: rawRow[2] || lastPath, desc: rawRow[3],
570 parent: paths[rawRow[4]]};
571 searchIndex.push(row);
572 if (typeof row.name === "string") {
573 var word = row.name.toLowerCase();
574 searchWords.push(word);
576 searchWords.push("");
584 function startSearch() {
586 $('.do-search').on('click', search);
587 $('.search-input').on('keyup', function() {
588 clearTimeout(keyUpTimeout);
589 keyUpTimeout = setTimeout(search, 100);
592 // Push and pop states are used to add search results to the browser
594 if (browserSupportsHistoryApi()) {
595 $(window).on('popstate', function(e) {
596 var params = getQueryStringParams();
597 // When browsing back from search results the main page
598 // visibility must be reset.
599 if (!params.search) {
600 $('#main.content').removeClass('hidden');
601 $('#search.content').addClass('hidden');
603 // When browsing forward to search results the previous
604 // search will be repeated, so the currentResults are
605 // cleared to ensure the search is successful.
606 currentResults = null;
607 // Synchronize search bar with query string state and
608 // perform the search, but don't empty the bar if there's
610 if (params.search !== undefined) {
611 $('.search-input').val(params.search);
613 // Some browsers fire 'onpopstate' for every page load
614 // (Chrome), while others fire the event only when actually
615 // popping a state (Firefox), which is why search() is
616 // called both here and at the end of the startSearch()
624 index = buildIndex(rawSearchIndex);
627 // Draw a convenient sidebar of known crates if we have a listing
628 if (rootPath == '../') {
629 var sidebar = $('.sidebar');
630 var div = $('<div>').attr('class', 'block crate');
631 div.append($('<h2>').text('Crates'));
634 for (var crate in rawSearchIndex) {
635 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
639 for (var i = 0; i < crates.length; i++) {
641 if (crates[i] == window.currentCrate) {
644 div.append($('<a>', {'href': '../' + crates[i] + '/index.html',
645 'class': klass}).text(crates[i]));
646 div.append($('<br>'));
652 window.initSearch = initSearch;