]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
auto merge of #13511 : Meyermagic/rust/enum_typeid, r=alexcrichton
[rust.git] / src / librustdoc / html / static / main.js
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.
4 //
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.
10
11 /*jslint browser: true, es5: true */
12 /*globals $: true, rootPath: true */
13
14 (function() {
15     "use strict";
16     var resizeTimeout, interval;
17
18     $('.js-only').removeClass('js-only');
19
20     function getQueryStringParams() {
21         var params = {};
22         window.location.search.substring(1).split("&").
23             map(function(s) {
24                 var pair = s.split("=");
25                 params[decodeURIComponent(pair[0])] =
26                     typeof pair[1] === "undefined" ?
27                             null : decodeURIComponent(pair[1]);
28             });
29         return params;
30     }
31
32     function browserSupportsHistoryApi() {
33         return window.history && typeof window.history.pushState === "function";
34     }
35
36     function resizeShortBlocks() {
37         if (resizeTimeout) {
38             clearTimeout(resizeTimeout);
39         }
40         resizeTimeout = setTimeout(function() {
41             var contentWidth = $('.content').width();
42             $('.docblock.short').width(function() {
43                 return contentWidth - 40 - $(this).prev().width();
44             }).addClass('nowrap');
45         }, 150);
46     }
47     resizeShortBlocks();
48     $(window).on('resize', resizeShortBlocks);
49
50     function highlightSourceLines() {
51         var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
52         if (match) {
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) {
57                 return;
58             }
59             $('#' + from)[0].scrollIntoView();
60             $('.line-numbers span').removeClass('line-highlighted');
61             for (i = from; i <= to; i += 1) {
62                 $('#' + i).addClass('line-highlighted');
63             }
64         }
65     }
66     highlightSourceLines();
67     $(window).on('hashchange', highlightSourceLines);
68
69     $(document).on('keyup', function(e) {
70         if (document.activeElement.tagName === 'INPUT') {
71             return;
72         }
73
74         if (e.keyCode === 188 && $('#help').hasClass('hidden')) { // question mark
75             e.preventDefault();
76             $('#help').removeClass('hidden');
77         } else if (e.keyCode === 27) { // esc
78             if (!$('#help').hasClass('hidden')) {
79                 e.preventDefault();
80                 $('#help').addClass('hidden');
81             } else if (!$('#search').hasClass('hidden')) {
82                 e.preventDefault();
83                 $('#search').addClass('hidden');
84                 $('#main').removeClass('hidden');
85             }
86         } else if (e.keyCode === 83) { // S
87             e.preventDefault();
88             $('.search-input').focus();
89         }
90     }).on('click', function(e) {
91         if (!$(e.target).closest('#help').length) {
92             $('#help').addClass('hidden');
93         }
94     });
95
96     $('.version-selector').on('change', function() {
97         var i, match,
98             url = document.location.href,
99             stripped = '',
100             len = rootPath.match(/\.\.\//g).length + 1;
101
102         for (i = 0; i < len; i += 1) {
103             match = url.match(/\/[^\/]*$/);
104             if (i < len - 1) {
105                 stripped = match[0] + stripped;
106             }
107             url = url.substring(0, url.length - match[0].length);
108         }
109
110         url += '/' + $('.version-selector').val() + stripped;
111
112         document.location.href = url;
113     });
114
115     function initSearch(rawSearchIndex) {
116         var currentResults, index, searchIndex;
117         var params = getQueryStringParams();
118
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 || '';
125         }
126
127         /**
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
132          *                               against]
133          * @return {[type]}             [A search index of results]
134          */
135         function execQuery(query, max, searchWords) {
136             var valLower = query.query.toLowerCase(),
137                 val = valLower,
138                 typeFilter = itemTypeFromName(query.type),
139                 results = [],
140                 split = valLower.split("::");
141
142             //remove empty keywords
143             for (var j = 0; j < split.length; j++) {
144                 split[j].toLowerCase();
145                 if (split[j] === "") {
146                     split.splice(j, 1);
147                 }
148             }
149
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))
154             {
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});
161                         }
162                     }
163                     if (results.length === max) {
164                         break;
165                     }
166                 }
167             } else {
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)
175                         {
176                             // filter type: ... queries
177                             if (typeFilter < 0 || typeFilter === searchIndex[j].ty) {
178                                 results.push({id: j, index: searchWords[j].replace(/_/g, "").indexOf(val)});
179                             }
180                         }
181                         if (results.length === max) {
182                             break;
183                         }
184                     }
185                 }
186             }
187
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;
194             }
195             // if there are no results then return to default and fail
196             if (results.length === 0) {
197                 return [];
198             }
199
200             // sort by exact match
201             results.sort(function search_complete_sort0(aaa, bbb) {
202                 if (aaa.word === valLower &&
203                     bbb.word !== valLower) {
204                     return 1;
205                 }
206             });
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) {
211                     return 1;
212                 }
213             });
214             // second sorting attempt
215             // sort by item name
216             results.sort(function search_complete_sort1(aaa, bbb) {
217                 if (aaa.word.length === bbb.word.length &&
218                     aaa.word > bbb.word) {
219                     return 1;
220                 }
221             });
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) {
227                         return 1;
228                     }
229                 });
230             }
231             // fourth sorting attempt
232             // sort by type
233             results.sort(function search_complete_sort3(aaa, bbb) {
234                 if (aaa.word === bbb.word &&
235                     aaa.ty > bbb.ty) {
236                     return 1;
237                 }
238             });
239             // fifth sorting attempt
240             // sort by path
241             results.sort(function search_complete_sort4(aaa, bbb) {
242                 if (aaa.word === bbb.word &&
243                     aaa.ty === bbb.ty && aaa.path > bbb.path) {
244                     return 1;
245                 }
246             });
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)
253                 {
254                     results[i].id = -1;
255                 }
256             }
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;
262
263                 var valid = validateResult(name, path, split, parent);
264                 if (!valid) {
265                     result.id = -1;
266                 }
267             }
268             return results;
269         }
270
271         /**
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
275          * (name || path )
276          *
277          * This could be written functionally, but I wanted to minimise
278          * functions on stack.
279          *
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]
285          */
286         function validateResult(name, path, keys, parent) {
287             //initially valid
288             var validate = true;
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
294                     if ((validate) &&
295                         (name.toLowerCase().indexOf(keys[i]) > -1 ||
296                          path.toLowerCase().indexOf(keys[i]) > -1 ||
297                          parent.name.toLowerCase().indexOf(keys[i]) > -1))
298                     {
299                         validate = true;
300                     } else {
301                         validate = false;
302                     }
303                 }
304             } else {
305                 for (var i = 0; i < keys.length; i++) {
306                     // if previous keys are valid and current key is in the
307                     // path, name
308                     if ((validate) &&
309                         (name.toLowerCase().indexOf(keys[i]) > -1 ||
310                          path.toLowerCase().indexOf(keys[i]) > -1))
311                     {
312                         validate = true;
313                     } else {
314                         validate = false;
315                     }
316                 }
317             }
318             return validate;
319         }
320
321         function getQuery() {
322             var matches, type, query = $('.search-input').val();
323
324             matches = query.match(/^(fn|mod|str(uct)?|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
325             if (matches) {
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);
331             }
332
333             return {
334                 query: query,
335                 type: type,
336                 id: query + type,
337             };
338         }
339
340         function initSearchNav() {
341             var hoverTimeout, $results = $('.search-results .result');
342
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');
348                 }
349                 document.location.href = dst.href;
350             }).on('mouseover', function() {
351                 var $el = $(this);
352                 clearTimeout(hoverTimeout);
353                 hoverTimeout = setTimeout(function() {
354                     $results.removeClass('highlighted');
355                     $el.addClass('highlighted');
356                 }, 20);
357             });
358
359             $(document).off('keypress.searchnav');
360             $(document).on('keypress.searchnav', function(e) {
361                 var $active = $results.filter('.highlighted');
362
363                 if (e.keyCode === 38) { // up
364                     e.preventDefault();
365                     if (!$active.length || !$active.prev()) {
366                         return;
367                     }
368
369                     $active.prev().addClass('highlighted');
370                     $active.removeClass('highlighted');
371                 } else if (e.keyCode === 40) { // down
372                     e.preventDefault();
373                     if (!$active.length) {
374                         $results.first().addClass('highlighted');
375                     } else if ($active.next().length) {
376                         $active.next().addClass('highlighted');
377                         $active.removeClass('highlighted');
378                     }
379                 } else if (e.keyCode === 13) { // return
380                     e.preventDefault();
381                     if ($active.length) {
382                         document.location.href = $active.find('a').prop('href');
383                     }
384                 }
385             });
386         }
387
388         function showResults(results) {
389             var output, shown, query = getQuery();
390
391             currentResults = query.id;
392             output = '<h1>Results for ' + query.query +
393                     (query.type ? ' (type: ' + query.type + ')' : '') + '</h1>';
394             output += '<table class="search-results">';
395
396             if (results.length > 0) {
397                 shown = [];
398
399                 results.forEach(function(item) {
400                     var name, type;
401
402                     if (shown.indexOf(item) !== -1) {
403                         return;
404                     }
405
406                     shown.push(item);
407                     name = item.name;
408                     type = itemTypes[item.ty];
409
410                     output += '<tr class="' + type + ' result"><td>';
411
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 +
432                             '.html' + anchor +
433                             '" class="' + type +
434                             '">' + name + '</a>';
435                     } else {
436                         output += item.path +
437                             '::<a href="' + rootPath +
438                             item.path.replace(/::/g, '/') +
439                             '/' + type +
440                             '.' + name +
441                             '.html" class="' + type +
442                             '">' + name + '</a>';
443                     }
444
445                     output += '</td><td><span class="desc">' + item.desc +
446                         '</span></td></tr>';
447                 });
448             } else {
449                 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
450                     encodeURIComponent('rust ' + query.query) +
451                     '">Try on DuckDuckGo?</a>';
452             }
453
454             output += "</p>";
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());
459             initSearchNav();
460         }
461
462         function search(e) {
463             var query,
464                 filterdata = [],
465                 obj, i, len,
466                 results = [],
467                 maxResults = 200,
468                 resultIndex;
469             var params = getQueryStringParams();
470
471             query = getQuery();
472             if (e) {
473                 e.preventDefault();
474             }
475
476             if (!query.query || query.id === currentResults) {
477                 return;
478             }
479
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));
486                 } else {
487                     history.replaceState(query, "", "?search=" +
488                                                 encodeURIComponent(query.query));
489                 }
490             }
491
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]);
498                     results.push(obj);
499                 }
500                 if (results.length >= maxResults) {
501                     break;
502                 }
503             }
504
505             showResults(results);
506         }
507
508         // This mapping table should match the discriminants of
509         // `rustdoc::html::item_type::ItemType` type in Rust.
510         var itemTypes = ["mod",
511                          "struct",
512                          "enum",
513                          "fn",
514                          "typedef",
515                          "static",
516                          "trait",
517                          "impl",
518                          "viewitem",
519                          "tymethod",
520                          "method",
521                          "structfield",
522                          "variant",
523                          "ffi",
524                          "ffs",
525                          "macro"];
526
527         function itemTypeFromName(typename) {
528             for (var i = 0; i < itemTypes.length; ++i) {
529                 if (itemTypes[i] === typename) return i;
530             }
531             return -1;
532         }
533
534         function buildIndex(rawSearchIndex) {
535             searchIndex = [];
536             var searchWords = [];
537             for (var crate in rawSearchIndex) {
538                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
539
540                 // an array of [(Number) item type,
541                 //              (String) name,
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,
547                 //              (String) name]
548                 var paths = rawSearchIndex[crate].paths;
549
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]};
554                 }
555
556                 // convert `items` into an object form, and construct word indices.
557                 //
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;
564                 var lastPath = "";
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);
574                     } else {
575                         searchWords.push("");
576                     }
577                     lastPath = row.path;
578                 }
579             }
580             return searchWords;
581         }
582
583         function startSearch() {
584             var keyUpTimeout;
585             $('.do-search').on('click', search);
586             $('.search-input').on('keyup', function() {
587                 clearTimeout(keyUpTimeout);
588                 keyUpTimeout = setTimeout(search, 100);
589             });
590
591             // Push and pop states are used to add search results to the browser
592             // history.
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');
601                     }
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
608                     // nothing there.
609                     if (params.search !== undefined) {
610                         $('.search-input').val(params.search);
611                     }
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()
616                     // function.
617                     search();
618                 });
619             }
620             search();
621         }
622
623         index = buildIndex(rawSearchIndex);
624         startSearch();
625
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'));
631
632             var crates = [];
633             for (var crate in rawSearchIndex) {
634                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue }
635                 crates.push(crate);
636             }
637             crates.sort();
638             for (var i = 0; i < crates.length; i++) {
639                 var klass = 'crate';
640                 if (crates[i] == window.currentCrate) {
641                     klass += ' current';
642                 }
643                 div.append($('<a>', {'href': '../' + crates[i] + '/index.html',
644                                     'class': klass}).text(crates[i]));
645                 div.append($('<br>'));
646             }
647             sidebar.append(div);
648         }
649     }
650
651     window.initSearch = initSearch;
652 }());
653