search.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. require([
  2. base_url + '/mkdocs/js/mustache.min.js',
  3. base_url + '/mkdocs/js/lunr-0.5.7.min.js',
  4. 'text!search-results-template.mustache',
  5. 'text!../search_index.json',
  6. ], function (Mustache, lunr, results_template, data) {
  7. "use strict";
  8. function getSearchTerm()
  9. {
  10. var sPageURL = window.location.search.substring(1);
  11. var sURLVariables = sPageURL.split('&');
  12. for (var i = 0; i < sURLVariables.length; i++)
  13. {
  14. var sParameterName = sURLVariables[i].split('=');
  15. if (sParameterName[0] == 'q')
  16. {
  17. return decodeURIComponent(sParameterName[1].replace(/\+/g, '%20'));
  18. }
  19. }
  20. }
  21. var index = lunr(function () {
  22. this.field('title', {boost: 10});
  23. this.field('text');
  24. this.ref('location');
  25. });
  26. data = JSON.parse(data);
  27. var documents = {};
  28. for (var i=0; i < data.docs.length; i++){
  29. var doc = data.docs[i];
  30. doc.location = base_url + doc.location;
  31. index.add(doc);
  32. documents[doc.location] = doc;
  33. }
  34. var search = function(){
  35. var query = document.getElementById('mkdocs-search-query').value;
  36. var search_results = document.getElementById("mkdocs-search-results");
  37. while (search_results.firstChild) {
  38. search_results.removeChild(search_results.firstChild);
  39. }
  40. if(query === ''){
  41. return;
  42. }
  43. var results = index.search(query);
  44. if (results.length > 0){
  45. for (var i=0; i < results.length; i++){
  46. var result = results[i];
  47. doc = documents[result.ref];
  48. doc.base_url = base_url;
  49. doc.summary = doc.text.substring(0, 200);
  50. var html = Mustache.to_html(results_template, doc);
  51. search_results.insertAdjacentHTML('beforeend', html);
  52. }
  53. } else {
  54. search_results.insertAdjacentHTML('beforeend', "<p>No results found</p>");
  55. }
  56. if(jQuery){
  57. /*
  58. * We currently only automatically hide bootstrap models. This
  59. * requires jQuery to work.
  60. */
  61. jQuery('#mkdocs_search_modal a').click(function(){
  62. jQuery('#mkdocs_search_modal').modal('hide');
  63. })
  64. }
  65. };
  66. var search_input = document.getElementById('mkdocs-search-query');
  67. var term = getSearchTerm();
  68. if (term){
  69. search_input.value = term;
  70. search();
  71. }
  72. search_input.addEventListener("keyup", search);
  73. });