academic-search.js 5.2 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.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. $('.docs-content .article').show();
  49. } else {
  50. $('.docs-content .article').hide();
  51. }
  52. // Check for timer event (enter key not pressed) and query less than minimum length required.
  53. if (!force && query.length < fuseOptions.minMatchCharLength)
  54. return;
  55. // Do search.
  56. $('#search-hits').empty();
  57. searchAcademic(query, fuse);
  58. let newURL = window.location.protocol + "//" + window.location.host + window.location.pathname + '?q=' + encodeURIComponent(query) + window.location.hash;
  59. updateURL(newURL);
  60. }
  61. // Perform search.
  62. function searchAcademic(query, fuse) {
  63. let results = fuse.search(query);
  64. // console.log({"results": results});
  65. if ($('.docs-content').length > 0)
  66. $('#search-hits').append('<h1>' + i18n.results + '</h1>');
  67. if (results.length > 0) {
  68. parseResults(query, results);
  69. } else {
  70. $('#search-hits').append('<div class="search-no-results">' + i18n.no_results + '</div>');
  71. }
  72. }
  73. // Parse search results.
  74. function parseResults(query, results) {
  75. $.each( results, function(key, value) {
  76. let content = value.item.content;
  77. let snippet = "";
  78. let snippetHighlights = [];
  79. if ( fuseOptions.tokenize ) {
  80. snippetHighlights.push(query);
  81. } else {
  82. $.each( value.matches, function(matchKey, matchValue) {
  83. if (matchValue.key == "content") {
  84. let start = (matchValue.indices[0][0]-summaryLength>0) ? matchValue.indices[0][0]-summaryLength : 0;
  85. let end = (matchValue.indices[0][1]+summaryLength<content.length) ? matchValue.indices[0][1]+summaryLength : content.length;
  86. snippet += content.substring(start, end);
  87. snippetHighlights.push(matchValue.value.substring(matchValue.indices[0][0], matchValue.indices[0][1]-matchValue.indices[0][0]+1));
  88. }
  89. });
  90. }
  91. if (snippet.length < 1) {
  92. snippet += content.substring(0, summaryLength*2);
  93. }
  94. // Load template.
  95. var template = $('#search-hit-fuse-template').html();
  96. // Localize content types.
  97. let content_key = value.item.section;
  98. if (content_key in content_type) {
  99. content_key = content_type[content_key];
  100. }
  101. // Parse template.
  102. let templateData = {
  103. key: key,
  104. title: value.item.title,
  105. type: content_key,
  106. relpermalink: value.item.relpermalink,
  107. snippet: snippet
  108. };
  109. let output = render(template, templateData);
  110. $('#search-hits').append(output);
  111. // Highlight search terms in result.
  112. $.each( snippetHighlights, function(hlKey, hlValue){
  113. $("#summary-"+key).mark(hlValue);
  114. });
  115. });
  116. }
  117. function render(template, data) {
  118. // Replace placeholders with their values.
  119. let key, find, re;
  120. for (key in data) {
  121. find = '\\{\\{\\s*' + key + '\\s*\\}\\}'; // Expect placeholder in the form `{{x}}`.
  122. re = new RegExp(find, 'g');
  123. template = template.replace(re, data[key]);
  124. }
  125. return template;
  126. }
  127. /* ---------------------------------------------------------------------------
  128. * Initialize.
  129. * --------------------------------------------------------------------------- */
  130. // If Academic's in-built search is enabled and Fuse loaded, then initialize it.
  131. if (typeof Fuse === 'function') {
  132. // Wait for Fuse to initialize.
  133. $.getJSON(search_index_filename, function (search_index) {
  134. let fuse = new Fuse(search_index, fuseOptions);
  135. // On page load, check for search query in URL.
  136. if (query = getSearchQuery('q')) {
  137. $("#search-query").val(query);
  138. initSearch(true, fuse);
  139. }
  140. // On search box key up, process query.
  141. $('#search-query').keyup(function (e) {
  142. clearTimeout($.data(this, 'searchTimer')); // Ensure only one timer runs!
  143. if (e.keyCode == 13) {
  144. initSearch(true, fuse);
  145. } else {
  146. $(this).data('searchTimer', setTimeout(function () {
  147. initSearch(false, fuse);
  148. }, 250));
  149. }
  150. });
  151. });
  152. }