academic-search.js 5.4 KB

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