search.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 horseyList = horsey($("#search-by").get(0), {
  56. suggestions: function (value, done) {
  57. var query = $("#search-by").val();
  58. var results = search(query);
  59. done(results);
  60. },
  61. filter: function (q, suggestion) {
  62. return true;
  63. },
  64. set: function (value) {
  65. location.href=value.uri;
  66. },
  67. render: function (li, suggestion) {
  68. var uri = suggestion.uri.substring(1,suggestion.uri.length);
  69. suggestion.href = baseurl + uri;
  70. var query = $("#search-by").val();
  71. var numWords = 2;
  72. var text = suggestion.content.match("(?:\\s?(?:[\\w]+)\\s?){0,"+numWords+"}"+query+"(?:\\s?(?:[\\w]+)\\s?){0,"+numWords+"}");
  73. suggestion.context = text;
  74. var image = '<div>' + '» ' + suggestion.title + '</div><div style="font-size:12px">' + (suggestion.context || '') +'</div>';
  75. li.innerHTML = image;
  76. },
  77. limit: 10
  78. });
  79. horseyList.refreshPosition();
  80. });