academic-search.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /*************************************************
  2. * Academic
  3. * https://github.com/gcushen/hugo-academic
  4. *
  5. * In-built Fuse based search algorithm.
  6. **************************************************/
  7. /* ---------------------------------------------------------------------------
  8. * Configuration.
  9. * --------------------------------------------------------------------------- */
  10. // Configure Fuse.
  11. let fuseOptions = {
  12. shouldSort: true,
  13. includeMatches: true,
  14. tokenize: true,
  15. threshold: 0.0,
  16. location: 0,
  17. distance: 100,
  18. maxPatternLength: 32,
  19. minMatchCharLength: 2,
  20. keys: [
  21. {name:'title', weight:0.8},
  22. {name:'summary', weight:0.6},
  23. {name:'content', weight:0.5},
  24. {name:'tags', weight:0.3}
  25. ]
  26. };
  27. // Configure summary.
  28. let summaryLength = 60;
  29. /* ---------------------------------------------------------------------------
  30. * Functions.
  31. * --------------------------------------------------------------------------- */
  32. // Get query from URI.
  33. function getSearchQuery(name) {
  34. return decodeURIComponent((location.search.split(name + '=')[1] || '').split('&')[0]).replace(/\+/g, ' ');
  35. }
  36. // Set query in URI without reloading the page.
  37. function updateURL(url) {
  38. if (history.pushState) {
  39. window.history.pushState({path:url}, '', url);
  40. }
  41. }
  42. // Pre-process new search query.
  43. function initSearch(force, fuse) {
  44. let query = $("#search-query").val();
  45. // If query deleted, clear results.
  46. if ( query.length < 1) {
  47. $('#search-hits').empty();
  48. }
  49. // Check for timer event (enter key not pressed) and query less than minimum length required.
  50. if (!force && query.length < fuseOptions.minMatchCharLength)
  51. return;
  52. // Do search.
  53. $('#search-hits').empty();
  54. searchAcademic(query, fuse);
  55. let newURL = window.location.protocol + "//" + window.location.host + window.location.pathname + '?q=' + encodeURIComponent(query) + window.location.hash;
  56. updateURL(newURL);
  57. }
  58. // Perform search.
  59. function searchAcademic(query, fuse) {
  60. let results = fuse.search(query);
  61. // console.log({"results": results});
  62. if (results.length > 0) {
  63. $('#search-hits').append('<h3 class="mt-0">' + results.length + ' ' + i18n.results + '</h3>');
  64. parseResults(query, results);
  65. } else {
  66. $('#search-hits').append('<div class="search-no-results">' + i18n.no_results + '</div>');
  67. }
  68. }
  69. // Parse search results.
  70. function parseResults(query, results) {
  71. $.each( results, function(key, value) {
  72. let content = value.item.content;
  73. let snippet = "";
  74. let snippetHighlights = [];
  75. if ( fuseOptions.tokenize ) {
  76. snippetHighlights.push(query);
  77. } else {
  78. $.each( value.matches, function(matchKey, matchValue) {
  79. if (matchValue.key == "content") {
  80. let start = (matchValue.indices[0][0]-summaryLength>0) ? matchValue.indices[0][0]-summaryLength : 0;
  81. let end = (matchValue.indices[0][1]+summaryLength<content.length) ? matchValue.indices[0][1]+summaryLength : content.length;
  82. snippet += content.substring(start, end);
  83. snippetHighlights.push(matchValue.value.substring(matchValue.indices[0][0], matchValue.indices[0][1]-matchValue.indices[0][0]+1));
  84. }
  85. });
  86. }
  87. if (snippet.length < 1) {
  88. snippet += content.substring(0, summaryLength*2);
  89. }
  90. // Load template.
  91. var template = $('#search-hit-fuse-template').html();
  92. // Localize content types.
  93. let content_key = value.item.section;
  94. if (content_key in content_type) {
  95. content_key = content_type[content_key];
  96. }
  97. // Parse template.
  98. let templateData = {
  99. key: key,
  100. title: value.item.title,
  101. type: content_key,
  102. relpermalink: value.item.relpermalink,
  103. snippet: snippet
  104. };
  105. let output = render(template, templateData);
  106. $('#search-hits').append(output);
  107. // Highlight search terms in result.
  108. $.each( snippetHighlights, function(hlKey, hlValue){
  109. $("#summary-"+key).mark(hlValue);
  110. });
  111. });
  112. }
  113. function render(template, data) {
  114. // Replace placeholders with their values.
  115. let key, find, re;
  116. for (key in data) {
  117. find = '\\{\\{\\s*' + key + '\\s*\\}\\}'; // Expect placeholder in the form `{{x}}`.
  118. re = new RegExp(find, 'g');
  119. template = template.replace(re, data[key]);
  120. }
  121. return template;
  122. }
  123. /* ---------------------------------------------------------------------------
  124. * Initialize.
  125. * --------------------------------------------------------------------------- */
  126. // If Academic's in-built search is enabled and Fuse loaded, then initialize it.
  127. if (typeof Fuse === 'function') {
  128. // Wait for Fuse to initialize.
  129. $.getJSON(search_index_filename, function (search_index) {
  130. let fuse = new Fuse(search_index, fuseOptions);
  131. // On page load, check for search query in URL.
  132. if (query = getSearchQuery('q')) {
  133. $("body").addClass('searching');
  134. $('.search-results').css({opacity: 0, visibility: "visible"}).animate({opacity: 1},200);
  135. $("#search-query").val(query);
  136. $("#search-query").focus();
  137. initSearch(true, fuse);
  138. }
  139. // On search box key up, process query.
  140. $('#search-query').keyup(function (e) {
  141. clearTimeout($.data(this, 'searchTimer')); // Ensure only one timer runs!
  142. if (e.keyCode == 13) {
  143. initSearch(true, fuse);
  144. } else {
  145. $(this).data('searchTimer', setTimeout(function () {
  146. initSearch(false, fuse);
  147. }, 250));
  148. }
  149. });
  150. });
  151. }