search.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var lunrIndex, pagesIndex;
  2. function endsWith(str, suffix) {
  3. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  4. }
  5. // Initialize lunrjs using our generated index file
  6. function initLunr() {
  7. if (!endsWith(baseurl,"/")){
  8. baseurl = baseurl+'/'
  9. };
  10. // First retrieve the index file
  11. $.getJSON(baseurl +"index.json")
  12. .done(function(index) {
  13. pagesIndex = index;
  14. // Set up lunrjs by declaring the fields we use
  15. // Also provide their boost level for the ranking
  16. lunrIndex = new lunr.Index
  17. lunrIndex.ref("uri");
  18. lunrIndex.field('title', {
  19. boost: 15
  20. });
  21. lunrIndex.field('tags', {
  22. boost: 10
  23. });
  24. lunrIndex.field("content", {
  25. boost: 5
  26. });
  27. // Feed lunr with each file and let lunr actually index them
  28. pagesIndex.forEach(function(page) {
  29. lunrIndex.add(page);
  30. });
  31. lunrIndex.pipeline.remove(lunrIndex.stemmer)
  32. })
  33. .fail(function(jqxhr, textStatus, error) {
  34. var err = textStatus + ", " + error;
  35. console.error("Error getting Hugo index flie:", err);
  36. });
  37. }
  38. /**
  39. * Trigger a search in lunr and transform the result
  40. *
  41. * @param {String} query
  42. * @return {Array} results
  43. */
  44. function search(query) {
  45. // Find the item in our index corresponding to the lunr one to have more info
  46. return lunrIndex.search(query).map(function(result) {
  47. return pagesIndex.filter(function(page) {
  48. return page.uri === result.ref;
  49. })[0];
  50. });
  51. }
  52. // Let's get started
  53. initLunr();
  54. $( document ).ready(function() {
  55. var searchList = new autoComplete({
  56. /* selector for the search box element */
  57. selector: $("#search-by").get(0),
  58. /* source is the callback to perform the search */
  59. source: function(term, response) {
  60. response(search(term));
  61. },
  62. /* renderItem displays individual search results */
  63. renderItem: function(item, term) {
  64. var numContextWords = 2;
  65. var text = item.content.match(
  66. "(?:\\s?(?:[\\w]+)\\s?){0,"+numContextWords+"}" +
  67. term+"(?:\\s?(?:[\\w]+)\\s?){0,"+numContextWords+"}");
  68. item.context = text;
  69. return '<div class="autocomplete-suggestion" ' +
  70. 'data-term="' + term + '" ' +
  71. 'data-title="' + item.title + '" ' +
  72. 'data-uri="'+ item.uri + '" ' +
  73. 'data-context="' + item.context + '">' +
  74. '» ' + item.title +
  75. '<div class="context">' +
  76. (item.context || '') +'</div>' +
  77. '</div>';
  78. },
  79. /* onSelect callback fires when a search suggestion is chosen */
  80. onSelect: function(e, term, item) {
  81. location.href = item.getAttribute('data-uri');
  82. }
  83. });
  84. });