]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
Merge remote-tracking branch 'brson/ratcher'
[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, searchIndex: true, rootPath: true, allPaths: 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" ? null : decodeURIComponent(pair[1]);
27             });
28         return params;
29     }
30
31     function browserSupportsHistoryApi() {
32         return window.history && typeof window.history.pushState === "function";
33     }
34
35     function resizeShortBlocks() {
36         if (resizeTimeout) {
37             clearTimeout(resizeTimeout);
38         }
39         resizeTimeout = setTimeout(function() {
40             var contentWidth = $('.content').width();
41             $('.docblock.short').width(function() {
42                 return contentWidth - 40 - $(this).prev().width();
43             }).addClass('nowrap');
44         }, 150);
45     }
46     resizeShortBlocks();
47     $(window).on('resize', resizeShortBlocks);
48
49     function highlightSourceLines() {
50         var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
51         if (match) {
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) {
56                 return;
57             }
58             $('#' + from)[0].scrollIntoView();
59             $('.line-numbers span').removeClass('line-highlighted');
60             for (i = from; i <= to; i += 1) {
61                 $('#' + i).addClass('line-highlighted');
62             }
63         }
64     }
65     highlightSourceLines();
66     $(window).on('hashchange', highlightSourceLines);
67
68     $(document).on('keyup', function(e) {
69         if (document.activeElement.tagName === 'INPUT') {
70             return;
71         }
72
73         if (e.keyCode === 188 && $('#help').hasClass('hidden')) { // question mark
74             e.preventDefault();
75             $('#help').removeClass('hidden');
76         } else if (e.keyCode === 27) { // esc
77             if (!$('#help').hasClass('hidden')) {
78                 e.preventDefault();
79                 $('#help').addClass('hidden');
80             } else if (!$('#search').hasClass('hidden')) {
81                 e.preventDefault();
82                 $('#search').addClass('hidden');
83                 $('#main').removeClass('hidden');
84             }
85         } else if (e.keyCode === 83) { // S
86             e.preventDefault();
87             $('.search-input').focus();
88         }
89     }).on('click', function(e) {
90         if (!$(e.target).closest('#help').length) {
91             $('#help').addClass('hidden');
92         }
93     });
94
95     $('.version-selector').on('change', function() {
96         var i, match,
97             url = document.location.href,
98             stripped = '',
99             len = rootPath.match(/\.\.\//g).length + 1;
100
101         for (i = 0; i < len; i += 1) {
102             match = url.match(/\/[^\/]*$/);
103             if (i < len - 1) {
104                 stripped = match[0] + stripped;
105             }
106             url = url.substring(0, url.length - match[0].length);
107         }
108
109         url += '/' + $('.version-selector').val() + stripped;
110
111         document.location.href = url;
112     });
113
114     function initSearch(searchIndex) {
115         var currentResults, index, params = getQueryStringParams();
116
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 || '';
123         }
124
125         /**
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]
131          */
132         function execQuery(query, max, searchWords) {
133             var valLower = query.query.toLowerCase(),
134                 val = valLower,
135                 typeFilter = query.type,
136                 results = [],
137                 aa = 0,
138                 bb = 0,
139                 split = valLower.split("::");
140
141             //remove empty keywords
142             for (var j = 0; j < split.length; j++) {
143                 split[j].toLowerCase();
144                 if (split[j] === "") {
145                     split.splice(j, 1);
146                 }
147             }
148
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]);
158                         }
159                     }
160                     if (results.length === max) {
161                         break;
162                     }
163                 }
164             } else {
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)]);
173                             }
174                         }
175                         if (results.length === max) {
176                             break;
177                         }
178                     }
179                 }
180             }
181
182             bb = results.length;
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);
188             }
189             // if there are no results then return to default and fail
190             if (results.length === 0) {
191                 return [];
192             }
193
194             // sort by exact match
195             results.sort(function search_complete_sort0(aaa, bbb) {
196                 if (searchWords[aaa[0]] === valLower && searchWords[bbb[0]] !== valLower) {
197                     return 1;
198                 }
199             });
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) {
204                     return 1;
205                 }
206             });
207             // second sorting attempt
208             // sort by item name
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]]) {
211                     return 1;
212                 }
213             });
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) {
219                         return 1;
220                     }
221                 });
222             }
223             // fourth sorting attempt
224             // sort by type
225             results.sort(function search_complete_sort3(aaa, bbb) {
226                 if (searchWords[aaa[0]] === searchWords[bbb[0]] && aaa[2] > bbb[2]) {
227                     return 1;
228                 }
229             });
230             // fifth sorting attempt
231             // sort by path
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]) {
234                     return 1;
235                 }
236             });
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]) {
241                     results[aa][0] = -1;
242                 }
243             }
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]];
249
250                 var valid = validateResult(name, path, split, parent);
251                 if (!valid) {
252                     result[0] = -1;
253                 }
254             }
255             return results;
256         }
257
258         /**
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 )
262          *
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]
269          */
270         function validateResult(name, path, keys, parent) {
271             //initially valid
272             var validate = true;
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)) {
278                         validate = true;
279                     } else {
280                         validate = false;
281                     }
282                 }
283             } else {
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)) {
287                         validate = true;
288                     } else {
289                         validate = false;
290                     }
291                 }
292             }
293             return validate;
294         }
295
296         function getQuery() {
297             var matches, type, query = $('.search-input').val();
298
299             matches = query.match(/^(fn|mod|str(uct)?|enum|trait|t(ype)?d(ef)?)\s*:\s*/i);
300             if (matches) {
301                 type = matches[1].replace(/^td$/, 'typedef').replace(/^str$/, 'struct').replace(/^tdef$/, 'typedef').replace(/^typed$/, 'typedef');
302                 query = query.substring(matches[0].length);
303             }
304
305             return {
306                 query: query,
307                 type: type,
308                 id: query + type,
309             };
310         }
311
312         function initSearchNav() {
313             var hoverTimeout, $results = $('.search-results .result');
314
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');
321                 }
322                 document.location.href = dst.href;
323             }).on('mouseover', function() {
324                 var $el = $(this);
325                 clearTimeout(hoverTimeout);
326                 hoverTimeout = setTimeout(function() {
327                     $results.removeClass('highlighted');
328                     $el.addClass('highlighted');
329                 }, 20);
330             });
331
332             $(document).off('keypress.searchnav');
333             $(document).on('keypress.searchnav', function(e) {
334                 var $active = $results.filter('.highlighted');
335
336                 if (e.keyCode === 38) { // up
337                     e.preventDefault();
338                     if (!$active.length || !$active.prev()) {
339                         return;
340                     }
341
342                     $active.prev().addClass('highlighted');
343                     $active.removeClass('highlighted');
344                 } else if (e.keyCode === 40) { // down
345                     e.preventDefault();
346                     if (!$active.length) {
347                         $results.first().addClass('highlighted');
348                     } else if ($active.next().length) {
349                         $active.next().addClass('highlighted');
350                         $active.removeClass('highlighted');
351                     }
352                 } else if (e.keyCode === 13) { // return
353                     e.preventDefault();
354                     if ($active.length) {
355                         document.location.href = $active.find('a').prop('href');
356                     }
357                 }
358             });
359         }
360
361         function showResults(results) {
362             var output, shown, query = getQuery();
363
364             currentResults = query.id;
365             output = '<h1>Results for ' + query.query + (query.type ? ' (type: ' + query.type + ')' : '') + '</h1>';
366             output += '<table class="search-results">';
367
368             if (results.length > 0) {
369                 shown = [];
370
371                 results.forEach(function(item) {
372                     var name, type;
373
374                     if (shown.indexOf(item) !== -1) {
375                         return;
376                     }
377
378                     shown.push(item);
379                     name = item.name;
380                     type = item.ty;
381
382                     output += '<tr class="' + type + ' result"><td>';
383
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 +
404                             '.html' + anchor +
405                             '" class="' + type +
406                             '">' + name + '</a>';
407                     } else {
408                         output += item.path +
409                             '::<a href="' + rootPath +
410                             item.path.replace(/::/g, '/') +
411                             '/' + type +
412                             '.' + name +
413                             '.html" class="' + type +
414                             '">' + name + '</a>';
415                     }
416
417                     output += '</td><td><span class="desc">' + item.desc +
418                         '</span></td></tr>';
419                 });
420             } else {
421                 output += 'No results :( <a href="https://duckduckgo.com/?q=' +
422                     encodeURIComponent('rust ' + query.query) +
423                     '">Try on DuckDuckGo?</a>';
424             }
425
426             output += "</p>";
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());
431             initSearchNav();
432         }
433
434         function search(e) {
435             var query,
436                 filterdata = [],
437                 obj, i, len,
438                 results = [],
439                 maxResults = 200,
440                 resultIndex;
441             var params = getQueryStringParams();
442
443             query = getQuery();
444             if (e) {
445                 e.preventDefault();
446             }
447
448             if (!query.query || query.id === currentResults) {
449                 return;
450             }
451
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));
457                 } else {
458                     history.replaceState(query, "", "?search=" + encodeURIComponent(query.query));
459                 }
460             }
461
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]);
468                     results.push(obj);
469                 }
470                 if (results.length >= maxResults) {
471                     break;
472                 }
473             }
474
475             // TODO add sorting capability through this function?
476             //
477             //            // the handler for the table heading filtering
478             //            filterdraw = function search_complete_filterdraw(node) {
479             //                var name = "",
480             //                    arrow = "",
481             //                    op = 0,
482             //                    tbody = node.parentNode.parentNode.nextSibling,
483             //                    anchora = {},
484             //                    tra = {},
485             //                    tha = {},
486             //                    td1a = {},
487             //                    td2a = {},
488             //                    td3a = {},
489             //                    aaa = 0,
490             //                    bbb = 0;
491             //
492             //                // the 4 following conditions set the rules for each
493             //                // table heading
494             //                if (node === ths[0]) {
495             //                    op = 0;
496             //                    name = "name";
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];
500             //                }
501             //                if (node === ths[1]) {
502             //                    op = 1;
503             //                    name = "type";
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];
507             //                }
508             //                if (node === ths[2]) {
509             //                    op = 2;
510             //                    name = "path";
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];
514             //                }
515             //                if (node === ths[3]) {
516             //                    op = 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];
521             //                }
522             //
523             //                // ascending or descending search
524             //                arrow = node.innerHTML.split(" ")[1];
525             //                if (arrow === undefined || arrow === "\u25b2") {
526             //                    arrow = "\u25bc";
527             //                } else {
528             //                    arrow = "\u25b2";
529             //                }
530             //
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())) {
534             //                        return 1;
535             //                    }
536             //                });
537             //            };
538
539             showResults(results);
540         }
541
542         function buildIndex(searchIndex) {
543             var len = searchIndex.length,
544                 i = 0,
545                 searchWords = [];
546
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());
555                 } else {
556                     searchWords.push("");
557                 }
558             }
559
560             return searchWords;
561         }
562
563         function startSearch() {
564             var keyUpTimeout;
565             $('.do-search').on('click', search);
566             $('.search-input').on('keyup', function() {
567                 clearTimeout(keyUpTimeout);
568                 keyUpTimeout = setTimeout(search, 100);
569             });
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');
578                     }
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
584                     // nothing there.
585                     if (params.search !== undefined) {
586                         $('.search-input').val(params.search);
587                     }
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.
591                     search();
592                 });
593             }
594             search();
595         }
596
597         index = buildIndex(searchIndex);
598         startSearch();
599     }
600
601     initSearch(searchIndex);
602 }());