PageRenderTime 49ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/librustdoc/html/static/main.js

https://github.com/nickdesaulniers/rust
JavaScript | 1046 lines | 789 code | 114 blank | 143 comment | 181 complexity | 27de887477274b79a8f8074f674ef4ae MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MIT, BSD-2-Clause
  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. /*jslint browser: true, es5: true */
  11. /*globals $: true, rootPath: true */
  12. (function() {
  13. "use strict";
  14. // This mapping table should match the discriminants of
  15. // `rustdoc::html::item_type::ItemType` type in Rust.
  16. var itemTypes = ["mod",
  17. "externcrate",
  18. "import",
  19. "struct",
  20. "enum",
  21. "fn",
  22. "type",
  23. "static",
  24. "trait",
  25. "impl",
  26. "tymethod",
  27. "method",
  28. "structfield",
  29. "variant",
  30. "macro",
  31. "primitive",
  32. "associatedtype",
  33. "constant",
  34. "associatedconstant",
  35. "union"];
  36. // used for special search precedence
  37. var TY_PRIMITIVE = itemTypes.indexOf("primitive");
  38. $('.js-only').removeClass('js-only');
  39. function getQueryStringParams() {
  40. var params = {};
  41. window.location.search.substring(1).split("&").
  42. map(function(s) {
  43. var pair = s.split("=");
  44. params[decodeURIComponent(pair[0])] =
  45. typeof pair[1] === "undefined" ?
  46. null : decodeURIComponent(pair[1]);
  47. });
  48. return params;
  49. }
  50. function browserSupportsHistoryApi() {
  51. return document.location.protocol != "file:" &&
  52. window.history && typeof window.history.pushState === "function";
  53. }
  54. function highlightSourceLines(ev) {
  55. var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
  56. if (match) {
  57. from = parseInt(match[1], 10);
  58. to = Math.min(50000, parseInt(match[2] || match[1], 10));
  59. from = Math.min(from, to);
  60. if ($('#' + from).length === 0) {
  61. return;
  62. }
  63. if (ev === null) { $('#' + from)[0].scrollIntoView(); };
  64. $('.line-numbers span').removeClass('line-highlighted');
  65. for (i = from; i <= to; ++i) {
  66. $('#' + i).addClass('line-highlighted');
  67. }
  68. }
  69. }
  70. highlightSourceLines(null);
  71. $(window).on('hashchange', highlightSourceLines);
  72. // Gets the human-readable string for the virtual-key code of the
  73. // given KeyboardEvent, ev.
  74. //
  75. // This function is meant as a polyfill for KeyboardEvent#key,
  76. // since it is not supported in Trident. We also test for
  77. // KeyboardEvent#keyCode because the handleShortcut handler is
  78. // also registered for the keydown event, because Blink doesn't fire
  79. // keypress on hitting the Escape key.
  80. //
  81. // So I guess you could say things are getting pretty interoperable.
  82. function getVirtualKey(ev) {
  83. if ("key" in ev && typeof ev.key != "undefined")
  84. return ev.key;
  85. var c = ev.charCode || ev.keyCode;
  86. if (c == 27)
  87. return "Escape";
  88. return String.fromCharCode(c);
  89. }
  90. function handleShortcut(ev) {
  91. if (document.activeElement.tagName == "INPUT")
  92. return;
  93. // Don't interfere with browser shortcuts
  94. if (ev.ctrlKey || ev.altKey || ev.metaKey)
  95. return;
  96. switch (getVirtualKey(ev)) {
  97. case "Escape":
  98. if (!$("#help").hasClass("hidden")) {
  99. ev.preventDefault();
  100. $("#help").addClass("hidden");
  101. $("body").removeClass("blur");
  102. } else if (!$("#search").hasClass("hidden")) {
  103. ev.preventDefault();
  104. $("#search").addClass("hidden");
  105. $("#main").removeClass("hidden");
  106. }
  107. break;
  108. case "s":
  109. case "S":
  110. ev.preventDefault();
  111. focusSearchBar();
  112. break;
  113. case "+":
  114. ev.preventDefault();
  115. toggleAllDocs();
  116. break;
  117. case "?":
  118. if (ev.shiftKey && $("#help").hasClass("hidden")) {
  119. ev.preventDefault();
  120. $("#help").removeClass("hidden");
  121. $("body").addClass("blur");
  122. }
  123. break;
  124. }
  125. }
  126. $(document).on("keypress", handleShortcut);
  127. $(document).on("keydown", handleShortcut);
  128. $(document).on("click", function(ev) {
  129. if (!$(ev.target).closest("#help > div").length) {
  130. $("#help").addClass("hidden");
  131. $("body").removeClass("blur");
  132. }
  133. });
  134. $('.version-selector').on('change', function() {
  135. var i, match,
  136. url = document.location.href,
  137. stripped = '',
  138. len = rootPath.match(/\.\.\//g).length + 1;
  139. for (i = 0; i < len; ++i) {
  140. match = url.match(/\/[^\/]*$/);
  141. if (i < len - 1) {
  142. stripped = match[0] + stripped;
  143. }
  144. url = url.substring(0, url.length - match[0].length);
  145. }
  146. url += '/' + $('.version-selector').val() + stripped;
  147. document.location.href = url;
  148. });
  149. /**
  150. * A function to compute the Levenshtein distance between two strings
  151. * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
  152. * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
  153. * This code is an unmodified version of the code written by Marco de Wit
  154. * and was found at http://stackoverflow.com/a/18514751/745719
  155. */
  156. var levenshtein = (function() {
  157. var row2 = [];
  158. return function(s1, s2) {
  159. if (s1 === s2) {
  160. return 0;
  161. }
  162. var s1_len = s1.length, s2_len = s2.length;
  163. if (s1_len && s2_len) {
  164. var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
  165. while (i1 < s1_len) {
  166. row[i1] = ++i1;
  167. }
  168. while (i2 < s2_len) {
  169. c2 = s2.charCodeAt(i2);
  170. a = i2;
  171. ++i2;
  172. b = i2;
  173. for (i1 = 0; i1 < s1_len; ++i1) {
  174. c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
  175. a = row[i1];
  176. b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
  177. row[i1] = b;
  178. }
  179. }
  180. return b;
  181. }
  182. return s1_len + s2_len;
  183. };
  184. })();
  185. function initSearch(rawSearchIndex) {
  186. var currentResults, index, searchIndex;
  187. var MAX_LEV_DISTANCE = 3;
  188. var params = getQueryStringParams();
  189. // Populate search bar with query string search term when provided,
  190. // but only if the input bar is empty. This avoid the obnoxious issue
  191. // where you start trying to do a search, and the index loads, and
  192. // suddenly your search is gone!
  193. if ($(".search-input")[0].value === "") {
  194. $(".search-input")[0].value = params.search || '';
  195. }
  196. /**
  197. * Executes the query and builds an index of results
  198. * @param {[Object]} query [The user query]
  199. * @param {[type]} max [The maximum results returned]
  200. * @param {[type]} searchWords [The list of search words to query
  201. * against]
  202. * @return {[type]} [A search index of results]
  203. */
  204. function execQuery(query, max, searchWords) {
  205. var valLower = query.query.toLowerCase(),
  206. val = valLower,
  207. typeFilter = itemTypeFromName(query.type),
  208. results = [],
  209. split = valLower.split("::");
  210. // remove empty keywords
  211. for (var j = 0; j < split.length; ++j) {
  212. split[j].toLowerCase();
  213. if (split[j] === "") {
  214. split.splice(j, 1);
  215. }
  216. }
  217. function typePassesFilter(filter, type) {
  218. // No filter
  219. if (filter < 0) return true;
  220. // Exact match
  221. if (filter === type) return true;
  222. // Match related items
  223. var name = itemTypes[type];
  224. switch (itemTypes[filter]) {
  225. case "constant":
  226. return (name == "associatedconstant");
  227. case "fn":
  228. return (name == "method" || name == "tymethod");
  229. case "type":
  230. return (name == "primitive");
  231. }
  232. // No match
  233. return false;
  234. }
  235. // quoted values mean literal search
  236. var nSearchWords = searchWords.length;
  237. if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
  238. val.charAt(val.length - 1) === val.charAt(0))
  239. {
  240. val = val.substr(1, val.length - 2);
  241. for (var i = 0; i < nSearchWords; ++i) {
  242. if (searchWords[i] === val) {
  243. // filter type: ... queries
  244. if (typePassesFilter(typeFilter, searchIndex[i].ty)) {
  245. results.push({id: i, index: -1});
  246. }
  247. }
  248. if (results.length === max) {
  249. break;
  250. }
  251. }
  252. // searching by type
  253. } else if (val.search("->") > -1) {
  254. var trimmer = function (s) { return s.trim(); };
  255. var parts = val.split("->").map(trimmer);
  256. var input = parts[0];
  257. // sort inputs so that order does not matter
  258. var inputs = input.split(",").map(trimmer).sort().toString();
  259. var output = parts[1];
  260. for (var i = 0; i < nSearchWords; ++i) {
  261. var type = searchIndex[i].type;
  262. if (!type) {
  263. continue;
  264. }
  265. // sort index inputs so that order does not matter
  266. var typeInputs = type.inputs.map(function (input) {
  267. return input.name;
  268. }).sort();
  269. // allow searching for void (no output) functions as well
  270. var typeOutput = type.output ? type.output.name : "";
  271. if ((inputs === "*" || inputs === typeInputs.toString()) &&
  272. (output === "*" || output == typeOutput)) {
  273. results.push({id: i, index: -1, dontValidate: true});
  274. }
  275. }
  276. } else {
  277. // gather matching search results up to a certain maximum
  278. val = val.replace(/\_/g, "");
  279. for (var i = 0; i < split.length; ++i) {
  280. for (var j = 0; j < nSearchWords; ++j) {
  281. var lev_distance;
  282. if (searchWords[j].indexOf(split[i]) > -1 ||
  283. searchWords[j].indexOf(val) > -1 ||
  284. searchWords[j].replace(/_/g, "").indexOf(val) > -1)
  285. {
  286. // filter type: ... queries
  287. if (typePassesFilter(typeFilter, searchIndex[j].ty)) {
  288. results.push({
  289. id: j,
  290. index: searchWords[j].replace(/_/g, "").indexOf(val),
  291. lev: 0,
  292. });
  293. }
  294. } else if (
  295. (lev_distance = levenshtein(searchWords[j], val)) <=
  296. MAX_LEV_DISTANCE) {
  297. if (typePassesFilter(typeFilter, searchIndex[j].ty)) {
  298. results.push({
  299. id: j,
  300. index: 0,
  301. // we want lev results to go lower than others
  302. lev: lev_distance,
  303. });
  304. }
  305. }
  306. if (results.length === max) {
  307. break;
  308. }
  309. }
  310. }
  311. }
  312. var nresults = results.length;
  313. for (var i = 0; i < nresults; ++i) {
  314. results[i].word = searchWords[results[i].id];
  315. results[i].item = searchIndex[results[i].id] || {};
  316. }
  317. // if there are no results then return to default and fail
  318. if (results.length === 0) {
  319. return [];
  320. }
  321. results.sort(function sortResults(aaa, bbb) {
  322. var a, b;
  323. // Sort by non levenshtein results and then levenshtein results by the distance
  324. // (less changes required to match means higher rankings)
  325. a = (aaa.lev);
  326. b = (bbb.lev);
  327. if (a !== b) { return a - b; }
  328. // sort by crate (non-current crate goes later)
  329. a = (aaa.item.crate !== window.currentCrate);
  330. b = (bbb.item.crate !== window.currentCrate);
  331. if (a !== b) { return a - b; }
  332. // sort by exact match (mismatch goes later)
  333. a = (aaa.word !== valLower);
  334. b = (bbb.word !== valLower);
  335. if (a !== b) { return a - b; }
  336. // sort by item name length (longer goes later)
  337. a = aaa.word.length;
  338. b = bbb.word.length;
  339. if (a !== b) { return a - b; }
  340. // sort by item name (lexicographically larger goes later)
  341. a = aaa.word;
  342. b = bbb.word;
  343. if (a !== b) { return (a > b ? +1 : -1); }
  344. // sort by index of keyword in item name (no literal occurrence goes later)
  345. a = (aaa.index < 0);
  346. b = (bbb.index < 0);
  347. if (a !== b) { return a - b; }
  348. // (later literal occurrence, if any, goes later)
  349. a = aaa.index;
  350. b = bbb.index;
  351. if (a !== b) { return a - b; }
  352. // special precedence for primitive pages
  353. if ((aaa.item.ty === TY_PRIMITIVE) && (bbb.item.ty !== TY_PRIMITIVE)) {
  354. return -1;
  355. }
  356. if ((bbb.item.ty === TY_PRIMITIVE) && (aaa.item.ty !== TY_PRIMITIVE)) {
  357. return 1;
  358. }
  359. // sort by description (no description goes later)
  360. a = (aaa.item.desc === '');
  361. b = (bbb.item.desc === '');
  362. if (a !== b) { return a - b; }
  363. // sort by type (later occurrence in `itemTypes` goes later)
  364. a = aaa.item.ty;
  365. b = bbb.item.ty;
  366. if (a !== b) { return a - b; }
  367. // sort by path (lexicographically larger goes later)
  368. a = aaa.item.path;
  369. b = bbb.item.path;
  370. if (a !== b) { return (a > b ? +1 : -1); }
  371. // que sera, sera
  372. return 0;
  373. });
  374. // remove duplicates, according to the data provided
  375. for (var i = results.length - 1; i > 0; i -= 1) {
  376. if (results[i].word === results[i - 1].word &&
  377. results[i].item.ty === results[i - 1].item.ty &&
  378. results[i].item.path === results[i - 1].item.path &&
  379. (results[i].item.parent || {}).name === (results[i - 1].item.parent || {}).name)
  380. {
  381. results[i].id = -1;
  382. }
  383. }
  384. for (var i = 0; i < results.length; ++i) {
  385. var result = results[i],
  386. name = result.item.name.toLowerCase(),
  387. path = result.item.path.toLowerCase(),
  388. parent = result.item.parent;
  389. // this validation does not make sense when searching by types
  390. if (result.dontValidate) {
  391. continue;
  392. }
  393. var valid = validateResult(name, path, split, parent);
  394. if (!valid) {
  395. result.id = -1;
  396. }
  397. }
  398. return results;
  399. }
  400. /**
  401. * Validate performs the following boolean logic. For example:
  402. * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
  403. * exists in (name || path || parent) OR => ("file" && "open") exists in
  404. * (name || path )
  405. *
  406. * This could be written functionally, but I wanted to minimise
  407. * functions on stack.
  408. *
  409. * @param {[string]} name [The name of the result]
  410. * @param {[string]} path [The path of the result]
  411. * @param {[string]} keys [The keys to be used (["file", "open"])]
  412. * @param {[object]} parent [The parent of the result]
  413. * @return {[boolean]} [Whether the result is valid or not]
  414. */
  415. function validateResult(name, path, keys, parent) {
  416. for (var i = 0; i < keys.length; ++i) {
  417. // each check is for validation so we negate the conditions and invalidate
  418. if (!(
  419. // check for an exact name match
  420. name.toLowerCase().indexOf(keys[i]) > -1 ||
  421. // then an exact path match
  422. path.toLowerCase().indexOf(keys[i]) > -1 ||
  423. // next if there is a parent, check for exact parent match
  424. (parent !== undefined &&
  425. parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
  426. // lastly check to see if the name was a levenshtein match
  427. levenshtein(name.toLowerCase(), keys[i]) <=
  428. MAX_LEV_DISTANCE)) {
  429. return false;
  430. }
  431. }
  432. return true;
  433. }
  434. function getQuery() {
  435. var matches, type, query, raw = $('.search-input').val();
  436. query = raw;
  437. matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
  438. if (matches) {
  439. type = matches[1].replace(/^const$/, 'constant');
  440. query = query.substring(matches[0].length);
  441. }
  442. return {
  443. raw: raw,
  444. query: query,
  445. type: type,
  446. id: query + type
  447. };
  448. }
  449. function initSearchNav() {
  450. var hoverTimeout, $results = $('.search-results .result');
  451. $results.on('click', function() {
  452. var dst = $(this).find('a')[0];
  453. if (window.location.pathname === dst.pathname) {
  454. $('#search').addClass('hidden');
  455. $('#main').removeClass('hidden');
  456. document.location.href = dst.href;
  457. }
  458. }).on('mouseover', function() {
  459. var $el = $(this);
  460. clearTimeout(hoverTimeout);
  461. hoverTimeout = setTimeout(function() {
  462. $results.removeClass('highlighted');
  463. $el.addClass('highlighted');
  464. }, 20);
  465. });
  466. $(document).off('keydown.searchnav');
  467. $(document).on('keydown.searchnav', function(e) {
  468. var $active = $results.filter('.highlighted');
  469. if (e.which === 38) { // up
  470. if (!$active.length || !$active.prev()) {
  471. return;
  472. }
  473. $active.prev().addClass('highlighted');
  474. $active.removeClass('highlighted');
  475. } else if (e.which === 40) { // down
  476. if (!$active.length) {
  477. $results.first().addClass('highlighted');
  478. } else if ($active.next().length) {
  479. $active.next().addClass('highlighted');
  480. $active.removeClass('highlighted');
  481. }
  482. } else if (e.which === 13) { // return
  483. if ($active.length) {
  484. document.location.href = $active.find('a').prop('href');
  485. }
  486. } else {
  487. $active.removeClass('highlighted');
  488. }
  489. });
  490. }
  491. function escape(content) {
  492. return $('<h1/>').text(content).html();
  493. }
  494. function showResults(results) {
  495. var output, shown, query = getQuery();
  496. currentResults = query.id;
  497. output = '<h1>Results for ' + escape(query.query) +
  498. (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>';
  499. output += '<table class="search-results">';
  500. if (results.length > 0) {
  501. shown = [];
  502. results.forEach(function(item) {
  503. var name, type, href, displayPath;
  504. if (shown.indexOf(item) !== -1) {
  505. return;
  506. }
  507. shown.push(item);
  508. name = item.name;
  509. type = itemTypes[item.ty];
  510. if (type === 'mod') {
  511. displayPath = item.path + '::';
  512. href = rootPath + item.path.replace(/::/g, '/') + '/' +
  513. name + '/index.html';
  514. } else if (type === "primitive") {
  515. displayPath = "";
  516. href = rootPath + item.path.replace(/::/g, '/') +
  517. '/' + type + '.' + name + '.html';
  518. } else if (type === "externcrate") {
  519. displayPath = "";
  520. href = rootPath + name + '/index.html';
  521. } else if (item.parent !== undefined) {
  522. var myparent = item.parent;
  523. var anchor = '#' + type + '.' + name;
  524. var parentType = itemTypes[myparent.ty];
  525. if (parentType === "primitive") {
  526. displayPath = myparent.name + '::';
  527. } else {
  528. displayPath = item.path + '::' + myparent.name + '::';
  529. }
  530. href = rootPath + item.path.replace(/::/g, '/') +
  531. '/' + parentType +
  532. '.' + myparent.name +
  533. '.html' + anchor;
  534. } else {
  535. displayPath = item.path + '::';
  536. href = rootPath + item.path.replace(/::/g, '/') +
  537. '/' + type + '.' + name + '.html';
  538. }
  539. output += '<tr class="' + type + ' result"><td>' +
  540. '<a href="' + href + '">' +
  541. displayPath + '<span class="' + type + '">' +
  542. name + '</span></a></td><td>' +
  543. '<a href="' + href + '">' +
  544. '<span class="desc">' + item.desc +
  545. '&nbsp;</span></a></td></tr>';
  546. });
  547. } else {
  548. output += 'No results :( <a href="https://duckduckgo.com/?q=' +
  549. encodeURIComponent('rust ' + query.query) +
  550. '">Try on DuckDuckGo?</a>';
  551. }
  552. output += "</p>";
  553. $('#main.content').addClass('hidden');
  554. $('#search.content').removeClass('hidden').html(output);
  555. $('#search .desc').width($('#search').width() - 40 -
  556. $('#search td:first-child').first().width());
  557. initSearchNav();
  558. }
  559. function search(e) {
  560. var query,
  561. filterdata = [],
  562. obj, i, len,
  563. results = [],
  564. maxResults = 200,
  565. resultIndex;
  566. var params = getQueryStringParams();
  567. query = getQuery();
  568. if (e) {
  569. e.preventDefault();
  570. }
  571. if (!query.query || query.id === currentResults) {
  572. return;
  573. }
  574. // Update document title to maintain a meaningful browser history
  575. $(document).prop("title", "Results for " + query.query + " - Rust");
  576. // Because searching is incremental by character, only the most
  577. // recent search query is added to the browser history.
  578. if (browserSupportsHistoryApi()) {
  579. if (!history.state && !params.search) {
  580. history.pushState(query, "", "?search=" +
  581. encodeURIComponent(query.raw));
  582. } else {
  583. history.replaceState(query, "", "?search=" +
  584. encodeURIComponent(query.raw));
  585. }
  586. }
  587. resultIndex = execQuery(query, 20000, index);
  588. len = resultIndex.length;
  589. for (i = 0; i < len; ++i) {
  590. if (resultIndex[i].id > -1) {
  591. obj = searchIndex[resultIndex[i].id];
  592. filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
  593. results.push(obj);
  594. }
  595. if (results.length >= maxResults) {
  596. break;
  597. }
  598. }
  599. showResults(results);
  600. }
  601. function itemTypeFromName(typename) {
  602. for (var i = 0; i < itemTypes.length; ++i) {
  603. if (itemTypes[i] === typename) { return i; }
  604. }
  605. return -1;
  606. }
  607. function buildIndex(rawSearchIndex) {
  608. searchIndex = [];
  609. var searchWords = [];
  610. for (var crate in rawSearchIndex) {
  611. if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
  612. searchWords.push(crate);
  613. searchIndex.push({
  614. crate: crate,
  615. ty: 1, // == ExternCrate
  616. name: crate,
  617. path: "",
  618. desc: rawSearchIndex[crate].doc,
  619. type: null,
  620. });
  621. // an array of [(Number) item type,
  622. // (String) name,
  623. // (String) full path or empty string for previous path,
  624. // (String) description,
  625. // (Number | null) the parent path index to `paths`]
  626. // (Object | null) the type of the function (if any)
  627. var items = rawSearchIndex[crate].items;
  628. // an array of [(Number) item type,
  629. // (String) name]
  630. var paths = rawSearchIndex[crate].paths;
  631. // convert `paths` into an object form
  632. var len = paths.length;
  633. for (var i = 0; i < len; ++i) {
  634. paths[i] = {ty: paths[i][0], name: paths[i][1]};
  635. }
  636. // convert `items` into an object form, and construct word indices.
  637. //
  638. // before any analysis is performed lets gather the search terms to
  639. // search against apart from the rest of the data. This is a quick
  640. // operation that is cached for the life of the page state so that
  641. // all other search operations have access to this cached data for
  642. // faster analysis operations
  643. var len = items.length;
  644. var lastPath = "";
  645. for (var i = 0; i < len; ++i) {
  646. var rawRow = items[i];
  647. var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
  648. path: rawRow[2] || lastPath, desc: rawRow[3],
  649. parent: paths[rawRow[4]], type: rawRow[5]};
  650. searchIndex.push(row);
  651. if (typeof row.name === "string") {
  652. var word = row.name.toLowerCase();
  653. searchWords.push(word);
  654. } else {
  655. searchWords.push("");
  656. }
  657. lastPath = row.path;
  658. }
  659. }
  660. return searchWords;
  661. }
  662. function startSearch() {
  663. var searchTimeout;
  664. $(".search-input").on("keyup input",function() {
  665. clearTimeout(searchTimeout);
  666. if ($(this).val().length === 0) {
  667. if (browserSupportsHistoryApi()) {
  668. history.replaceState("", "std - Rust", "?search=");
  669. }
  670. $('#main.content').removeClass('hidden');
  671. $('#search.content').addClass('hidden');
  672. } else {
  673. searchTimeout = setTimeout(search, 500);
  674. }
  675. });
  676. $('.search-form').on('submit', function(e){
  677. e.preventDefault();
  678. clearTimeout(searchTimeout);
  679. search();
  680. });
  681. $('.search-input').on('change paste', function(e) {
  682. // Do NOT e.preventDefault() here. It will prevent pasting.
  683. clearTimeout(searchTimeout);
  684. // zero-timeout necessary here because at the time of event handler execution the
  685. // pasted content is not in the input field yet. Shouldn’t make any difference for
  686. // change, though.
  687. setTimeout(search, 0);
  688. });
  689. // Push and pop states are used to add search results to the browser
  690. // history.
  691. if (browserSupportsHistoryApi()) {
  692. // Store the previous <title> so we can revert back to it later.
  693. var previousTitle = $(document).prop("title");
  694. $(window).on('popstate', function(e) {
  695. var params = getQueryStringParams();
  696. // When browsing back from search results the main page
  697. // visibility must be reset.
  698. if (!params.search) {
  699. $('#main.content').removeClass('hidden');
  700. $('#search.content').addClass('hidden');
  701. }
  702. // Revert to the previous title manually since the History
  703. // API ignores the title parameter.
  704. $(document).prop("title", previousTitle);
  705. // When browsing forward to search results the previous
  706. // search will be repeated, so the currentResults are
  707. // cleared to ensure the search is successful.
  708. currentResults = null;
  709. // Synchronize search bar with query string state and
  710. // perform the search. This will empty the bar if there's
  711. // nothing there, which lets you really go back to a
  712. // previous state with nothing in the bar.
  713. $('.search-input').val(params.search);
  714. // Some browsers fire 'onpopstate' for every page load
  715. // (Chrome), while others fire the event only when actually
  716. // popping a state (Firefox), which is why search() is
  717. // called both here and at the end of the startSearch()
  718. // function.
  719. search();
  720. });
  721. }
  722. search();
  723. }
  724. function plainSummaryLine(markdown) {
  725. markdown.replace(/\n/g, ' ')
  726. .replace(/'/g, "\'")
  727. .replace(/^#+? (.+?)/, "$1")
  728. .replace(/\[(.*?)\]\(.*?\)/g, "$1")
  729. .replace(/\[(.*?)\]\[.*?\]/g, "$1");
  730. }
  731. index = buildIndex(rawSearchIndex);
  732. startSearch();
  733. // Draw a convenient sidebar of known crates if we have a listing
  734. if (rootPath === '../') {
  735. var sidebar = $('.sidebar');
  736. var div = $('<div>').attr('class', 'block crate');
  737. div.append($('<h3>').text('Crates'));
  738. var ul = $('<ul>').appendTo(div);
  739. var crates = [];
  740. for (var crate in rawSearchIndex) {
  741. if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
  742. crates.push(crate);
  743. }
  744. crates.sort();
  745. for (var i = 0; i < crates.length; ++i) {
  746. var klass = 'crate';
  747. if (crates[i] === window.currentCrate) {
  748. klass += ' current';
  749. }
  750. if (rawSearchIndex[crates[i]].items[0]) {
  751. var desc = rawSearchIndex[crates[i]].items[0][3];
  752. var link = $('<a>', {'href': '../' + crates[i] + '/index.html',
  753. 'title': plainSummaryLine(desc),
  754. 'class': klass}).text(crates[i]);
  755. ul.append($('<li>').append(link));
  756. }
  757. }
  758. sidebar.append(div);
  759. }
  760. }
  761. window.initSearch = initSearch;
  762. // delayed sidebar rendering.
  763. function initSidebarItems(items) {
  764. var sidebar = $('.sidebar');
  765. var current = window.sidebarCurrent;
  766. function block(shortty, longty) {
  767. var filtered = items[shortty];
  768. if (!filtered) { return; }
  769. var div = $('<div>').attr('class', 'block ' + shortty);
  770. div.append($('<h3>').text(longty));
  771. var ul = $('<ul>').appendTo(div);
  772. for (var i = 0; i < filtered.length; ++i) {
  773. var item = filtered[i];
  774. var name = item[0];
  775. var desc = item[1]; // can be null
  776. var klass = shortty;
  777. if (name === current.name && shortty === current.ty) {
  778. klass += ' current';
  779. }
  780. var path;
  781. if (shortty === 'mod') {
  782. path = name + '/index.html';
  783. } else {
  784. path = shortty + '.' + name + '.html';
  785. }
  786. var link = $('<a>', {'href': current.relpath + path,
  787. 'title': desc,
  788. 'class': klass}).text(name);
  789. ul.append($('<li>').append(link));
  790. }
  791. sidebar.append(div);
  792. }
  793. block("primitive", "Primitive Types");
  794. block("mod", "Modules");
  795. block("macro", "Macros");
  796. block("struct", "Structs");
  797. block("enum", "Enums");
  798. block("constant", "Constants");
  799. block("static", "Statics");
  800. block("trait", "Traits");
  801. block("fn", "Functions");
  802. block("type", "Type Definitions");
  803. }
  804. window.initSidebarItems = initSidebarItems;
  805. window.register_implementors = function(imp) {
  806. var list = $('#implementors-list');
  807. var libs = Object.getOwnPropertyNames(imp);
  808. for (var i = 0; i < libs.length; ++i) {
  809. if (libs[i] === currentCrate) { continue; }
  810. var structs = imp[libs[i]];
  811. for (var j = 0; j < structs.length; ++j) {
  812. var code = $('<code>').append(structs[j]);
  813. $.each(code.find('a'), function(idx, a) {
  814. var href = $(a).attr('href');
  815. if (href && href.indexOf('http') !== 0) {
  816. $(a).attr('href', rootPath + href);
  817. }
  818. });
  819. var li = $('<li>').append(code);
  820. list.append(li);
  821. }
  822. }
  823. };
  824. if (window.pending_implementors) {
  825. window.register_implementors(window.pending_implementors);
  826. }
  827. // See documentation in html/render.rs for what this is doing.
  828. var query = getQueryStringParams();
  829. if (query['gotosrc']) {
  830. window.location = $('#src-' + query['gotosrc']).attr('href');
  831. }
  832. if (query['gotomacrosrc']) {
  833. window.location = $('.srclink').attr('href');
  834. }
  835. function labelForToggleButton(sectionIsCollapsed) {
  836. if (sectionIsCollapsed) {
  837. // button will expand the section
  838. return "+";
  839. }
  840. // button will collapse the section
  841. // note that this text is also set in the HTML template in render.rs
  842. return "\u2212"; // "\u2212" is '−' minus sign
  843. }
  844. function toggleAllDocs() {
  845. var toggle = $("#toggle-all-docs");
  846. if (toggle.hasClass("will-expand")) {
  847. toggle.removeClass("will-expand");
  848. toggle.children(".inner").text(labelForToggleButton(false));
  849. toggle.attr("title", "collapse all docs");
  850. $(".docblock").show();
  851. $(".toggle-label").hide();
  852. $(".toggle-wrapper").removeClass("collapsed");
  853. $(".collapse-toggle").children(".inner").text(labelForToggleButton(false));
  854. } else {
  855. toggle.addClass("will-expand");
  856. toggle.children(".inner").text(labelForToggleButton(true));
  857. toggle.attr("title", "expand all docs");
  858. $(".docblock").hide();
  859. $(".toggle-label").show();
  860. $(".toggle-wrapper").addClass("collapsed");
  861. $(".collapse-toggle").children(".inner").text(labelForToggleButton(true));
  862. }
  863. }
  864. $("#toggle-all-docs").on("click", toggleAllDocs);
  865. $(document).on("click", ".collapse-toggle", function() {
  866. var toggle = $(this);
  867. var relatedDoc = toggle.parent().next();
  868. if (relatedDoc.is(".stability")) {
  869. relatedDoc = relatedDoc.next();
  870. }
  871. if (relatedDoc.is(".docblock")) {
  872. if (relatedDoc.is(":visible")) {
  873. relatedDoc.slideUp({duration: 'fast', easing: 'linear'});
  874. toggle.parent(".toggle-wrapper").addClass("collapsed");
  875. toggle.children(".inner").text(labelForToggleButton(true));
  876. toggle.children(".toggle-label").fadeIn();
  877. } else {
  878. relatedDoc.slideDown({duration: 'fast', easing: 'linear'});
  879. toggle.parent(".toggle-wrapper").removeClass("collapsed");
  880. toggle.children(".inner").text(labelForToggleButton(false));
  881. toggle.children(".toggle-label").hide();
  882. }
  883. }
  884. });
  885. $(function() {
  886. var toggle = $("<a/>", {'href': 'javascript:void(0)', 'class': 'collapse-toggle'})
  887. .html("[<span class='inner'></span>]");
  888. toggle.children(".inner").text(labelForToggleButton(false));
  889. $(".method").each(function() {
  890. if ($(this).next().is(".docblock") ||
  891. ($(this).next().is(".stability") && $(this).next().next().is(".docblock"))) {
  892. $(this).children().last().after(toggle.clone());
  893. }
  894. });
  895. var mainToggle =
  896. $(toggle).append(
  897. $('<span/>', {'class': 'toggle-label'})
  898. .css('display', 'none')
  899. .html('&nbsp;Expand&nbsp;description'));
  900. var wrapper = $("<div class='toggle-wrapper'>").append(mainToggle);
  901. $("#main > .docblock").before(wrapper);
  902. });
  903. $('pre.line-numbers').on('click', 'span', function() {
  904. var prev_id = 0;
  905. function set_fragment(name) {
  906. if (browserSupportsHistoryApi()) {
  907. history.replaceState(null, null, '#' + name);
  908. $(window).trigger('hashchange');
  909. } else {
  910. location.replace('#' + name);
  911. }
  912. }
  913. return function(ev) {
  914. var cur_id = parseInt(ev.target.id, 10);
  915. if (ev.shiftKey && prev_id) {
  916. if (prev_id > cur_id) {
  917. var tmp = prev_id;
  918. prev_id = cur_id;
  919. cur_id = tmp;
  920. }
  921. set_fragment(prev_id + '-' + cur_id);
  922. } else {
  923. prev_id = cur_id;
  924. set_fragment(cur_id);
  925. }
  926. };
  927. }());
  928. }());
  929. // Sets the focus on the search bar at the top of the page
  930. function focusSearchBar() {
  931. $('.search-input').focus();
  932. }