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] || {};
192 results[i].ty = results[i].item.ty;
193 results[i].path = results[i].item.path;
195 // if there are no results then return to default and fail
196 if (results.length === 0) {
200 // sort by exact match
201 results.sort(function search_complete_sort0(aaa, bbb) {
202 if (aaa.word === valLower &&
203 bbb.word !== valLower) {
207 // first sorting attempt
208 // sort by item name length
209 results.sort(function search_complete_sort1(aaa, bbb) {
210 if (aaa.word.length > bbb.word.length) {
214 // second sorting attempt
216 results.sort(function search_complete_sort1(aaa, bbb) {
217 if (aaa.word.length === bbb.word.length &&
218 aaa.word > bbb.word) {
222 // third sorting attempt
223 // sort by index of keyword in item name
224 if (results[0].index !== -1) {
225 results.sort(function search_complete_sort1(aaa, bbb) {
226 if (aaa.index > bbb.index && bbb.index === 0) {
231 // fourth sorting attempt
233 results.sort(function search_complete_sort3(aaa, bbb) {
234 if (aaa.word === bbb.word &&
239 // fifth sorting attempt
241 results.sort(function search_complete_sort4(aaa, bbb) {
242 if (aaa.word === bbb.word &&
243 aaa.ty === bbb.ty && aaa.path > bbb.path) {
247 // sixth sorting attempt
248 // remove duplicates, according to the data provided
249 for (var i = results.length - 1; i > 0; i -= 1) {
250 if (results[i].word === results[i - 1].word &&
251 results[i].ty === results[i - 1].ty &&
252 results[i].path === results[i - 1].path)
257 for (var i = 0; i < results.length; i++) {
258 var result = results[i],
259 name = result.item.name.toLowerCase(),
260 path = result.item.path.toLowerCase(),
261 parent = result.item.parent;
263 var valid = validateResult(name, path, split, parent);
272 * Validate performs the following boolean logic. For example:
273 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
274 * exists in (name || path || parent) OR => ("file" && "open") exists in
277 * This could be written functionally, but I wanted to minimise
278 * functions on stack.
280 * @param {[string]} name [The name of the result]
281 * @param {[string]} path [The path of the result]
282 * @param {[string]} keys [The keys to be used (["file", "open"])]
283 * @param {[object]} parent [The parent of the result]
284 * @return {[boolean]} [Whether the result is valid or not]
286 function validateResult(name, path, keys, parent) {
289 //if there is a parent, then validate against parent
290 if (parent !== undefined) {
291 for (var i = 0; i < keys.length; i++) {
292 // if previous keys are valid and current key is in the
293 // path, name or parent
295 (name.toLowerCase().indexOf(keys[i]) > -1 ||
296 path.toLowerCase().indexOf(keys[i]) > -1 ||
297 parent.name.toLowerCase().indexOf(keys[i]) > -1))
305 for (var i = 0; i < keys.length; i++) {
306 // if previous keys are valid and current key is in the
309 (name.toLowerCase().indexOf(keys[i]) > -1 ||
310 path.toLowerCase().indexOf(keys[i]) > -1))
321 function getQuery() {
322 var matches, type, query = $('.search-input').val();
324 matches = query.match(/^(fn|mod|str(uct)?|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
326 type = matches[1].replace(/^td$/, 'typedef')
327 .replace(/^str$/, 'struct')
328 .replace(/^tdef$/, 'typedef')
329 .replace(/^typed$/, 'typedef');
330 query = query.substring(matches[0].length);
340 function initSearchNav() {
341 var hoverTimeout, $results = $('.search-results .result');
343 $results.on('click', function() {
344 var dst = $(this).find('a')[0];
345 if (window.location.pathname == dst.pathname) {
346 $('#search').addClass('hidden');
347 $('#main').removeClass('hidden');
349 document.location.href = dst.href;
350 }).on('mouseover', function() {
352 clearTimeout(hoverTimeout);
353 hoverTimeout = setTimeout(function() {
354 $results.removeClass('highlighted');
355 $el.addClass('highlighted');
359 $(document).off('keypress.searchnav');
360 $(document).on('keypress.searchnav', function(e) {
361 var $active = $results.filter('.highlighted');
363 if (e.keyCode === 38) { // up
365 if (!$active.length || !$active.prev()) {
369 $active.prev().addClass('highlighted');
370 $active.removeClass('highlighted');
371 } else if (e.keyCode === 40) { // down
373 if (!$active.length) {
374 $results.first().addClass('highlighted');
375 } else if ($active.next().length) {
376 $active.next().addClass('highlighted');
377 $active.removeClass('highlighted');
379 } else if (e.keyCode === 13) { // return
381 if ($active.length) {
382 document.location.href = $active.find('a').prop('href');
388 function showResults(results) {
389 var output, shown, query = getQuery();
391 currentResults = query.id;
392 output = '<h1>Results for ' + query.query +
393 (query.type ? ' (type: ' + query.type + ')' : '') + '</h1>';
394 output += '<table class="search-results">';
396 if (results.length > 0) {
399 results.forEach(function(item) {
402 if (shown.indexOf(item) !== -1) {
408 type = itemTypes[item.ty];
410 output += '<tr class="' + type + ' result"><td>';
412 if (type === 'mod') {
413 output += item.path +
414 '::<a href="' + rootPath +
415 item.path.replace(/::/g, '/') + '/' +
416 name + '/index.html" class="' +
417 type + '">' + name + '</a>';
418 } else if (type === 'static' || type === 'reexport') {
419 output += item.path +
420 '::<a href="' + rootPath +
421 item.path.replace(/::/g, '/') +
422 '/index.html" class="' + type +
423 '">' + name + '</a>';
424 } else if (item.parent !== undefined) {
425 var myparent = item.parent;
426 var anchor = '#' + type + '.' + name;
427 output += item.path + '::' + myparent.name +
428 '::<a href="' + rootPath +
429 item.path.replace(/::/g, '/') +
430 '/' + itemTypes[myparent.ty] +
431 '.' + myparent.name +
434 '">' + name + '</a>';
436 output += item.path +
437 '::<a href="' + rootPath +
438 item.path.replace(/::/g, '/') +
441 '.html" class="' + type +
442 '">' + name + '</a>';
445 output += '</td><td><span class="desc">' + item.desc +
449 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
450 encodeURIComponent('rust ' + query.query) +
451 '">Try on DuckDuckGo?</a>';
455 $('#main.content').addClass('hidden');
456 $('#search.content').removeClass('hidden').html(output);
457 $('#search .desc').width($('#search').width() - 40 -
458 $('#search td:first-child').first().width());
469 var params = getQueryStringParams();
476 if (!query.query || query.id === currentResults) {
480 // Because searching is incremental by character, only the most
481 // recent search query is added to the browser history.
482 if (browserSupportsHistoryApi()) {
483 if (!history.state && !params.search) {
484 history.pushState(query, "", "?search=" +
485 encodeURIComponent(query.query));
487 history.replaceState(query, "", "?search=" +
488 encodeURIComponent(query.query));
492 resultIndex = execQuery(query, 20000, index);
493 len = resultIndex.length;
494 for (i = 0; i < len; i += 1) {
495 if (resultIndex[i].id > -1) {
496 obj = searchIndex[resultIndex[i].id];
497 filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
500 if (results.length >= maxResults) {
505 showResults(results);
508 // This mapping table should match the discriminants of
509 // `rustdoc::html::item_type::ItemType` type in Rust.
510 var itemTypes = ["mod",
527 function itemTypeFromName(typename) {
528 for (var i = 0; i < itemTypes.length; ++i) {
529 if (itemTypes[i] === typename) return i;
534 function buildIndex(rawSearchIndex) {
536 var searchWords = [];
537 for (var crate in rawSearchIndex) {
538 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
540 // an array of [(Number) item type,
542 // (String) full path or empty string for previous path,
543 // (String) description,
544 // (optional Number) the parent path index to `paths`]
545 var items = rawSearchIndex[crate].items;
546 // an array of [(Number) item type,
548 var paths = rawSearchIndex[crate].paths;
550 // convert `paths` into an object form
551 var len = paths.length;
552 for (var i = 0; i < len; ++i) {
553 paths[i] = {ty: paths[i][0], name: paths[i][1]};
556 // convert `items` into an object form, and construct word indices.
558 // before any analysis is performed lets gather the search terms to
559 // search against apart from the rest of the data. This is a quick
560 // operation that is cached for the life of the page state so that
561 // all other search operations have access to this cached data for
562 // faster analysis operations
563 var len = items.length;
565 for (var i = 0; i < len; i += 1) {
566 var rawRow = items[i];
567 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
568 path: rawRow[2] || lastPath, desc: rawRow[3],
569 parent: paths[rawRow[4]]};
570 searchIndex.push(row);
571 if (typeof row.name === "string") {
572 var word = row.name.toLowerCase();
573 searchWords.push(word);
575 searchWords.push("");
583 function startSearch() {
585 $('.do-search').on('click', search);
586 $('.search-input').on('keyup', function() {
587 clearTimeout(keyUpTimeout);
588 keyUpTimeout = setTimeout(search, 100);
591 // Push and pop states are used to add search results to the browser
593 if (browserSupportsHistoryApi()) {
594 $(window).on('popstate', function(e) {
595 var params = getQueryStringParams();
596 // When browsing back from search results the main page
597 // visibility must be reset.
598 if (!params.search) {
599 $('#main.content').removeClass('hidden');
600 $('#search.content').addClass('hidden');
602 // When browsing forward to search results the previous
603 // search will be repeated, so the currentResults are
604 // cleared to ensure the search is successful.
605 currentResults = null;
606 // Synchronize search bar with query string state and
607 // perform the search, but don't empty the bar if there's
609 if (params.search !== undefined) {
610 $('.search-input').val(params.search);
612 // Some browsers fire 'onpopstate' for every page load
613 // (Chrome), while others fire the event only when actually
614 // popping a state (Firefox), which is why search() is
615 // called both here and at the end of the startSearch()
623 index = buildIndex(rawSearchIndex);
626 // Draw a convenient sidebar of known crates if we have a listing
627 if (rootPath == '../') {
628 var sidebar = $('.sidebar');
629 var div = $('<div>').attr('class', 'block crate');
630 div.append($('<h2>').text('Crates'));
633 for (var crate in rawSearchIndex) {
634 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
638 for (var i = 0; i < crates.length; i++) {
640 if (crates[i] == window.currentCrate) {
643 div.append($('<a>', {'href': '../' + crates[i] + '/index.html',
644 'class': klass}).text(crates[i]));
645 div.append($('<br>'));
651 window.initSearch = initSearch;