algolia-search.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*************************************************
  2. * Wowchemy
  3. * https://github.com/wowchemy/wowchemy-hugo-themes
  4. *
  5. * Algolia based search algorithm.
  6. **************************************************/
  7. import {algoliaConfig, i18n, content_type} from '@params';
  8. function getTemplate(templateName) {
  9. return document.querySelector(`#${templateName}-template`).innerHTML;
  10. }
  11. if (typeof instantsearch === 'function' && $('#search-box').length) {
  12. const options = {
  13. appId: algoliaConfig.appId,
  14. apiKey: algoliaConfig.apiKey,
  15. indexName: algoliaConfig.indexName,
  16. routing: true,
  17. searchParameters: {
  18. hitsPerPage: 10,
  19. },
  20. searchFunction: function (helper) {
  21. let searchResults = document.querySelector('#search-hits');
  22. let commonQueries = document.querySelector('#search-common-queries');
  23. if (helper.state.query === '') {
  24. searchResults.style.display = 'none';
  25. commonQueries.style.display = 'block';
  26. return;
  27. }
  28. helper.search();
  29. commonQueries.style.display = 'none';
  30. searchResults.style.display = 'block';
  31. },
  32. };
  33. const search = instantsearch(options);
  34. // Initialize search box.
  35. search.addWidget(
  36. instantsearch.widgets.searchBox({
  37. container: '#search-box',
  38. autofocus: true,
  39. reset: true,
  40. poweredBy: algoliaConfig.poweredBy,
  41. placeholder: i18n.placeholder,
  42. }),
  43. );
  44. // Initialize search results.
  45. search.addWidget(
  46. instantsearch.widgets.infiniteHits({
  47. container: '#search-hits',
  48. escapeHits: true,
  49. templates: {
  50. empty: '<div class="search-no-results">' + i18n.no_results + '</div>',
  51. item: getTemplate('search-hit-algolia'),
  52. },
  53. cssClasses: {
  54. showmoreButton: 'btn btn-outline-primary',
  55. },
  56. }),
  57. );
  58. // On render search results, localize the content type metadata.
  59. search.on('render', function () {
  60. $('.search-hit-type').each(function () {
  61. let content_key = $(this).text();
  62. if (content_key in content_type) {
  63. $(this).text(content_type[content_key]);
  64. }
  65. });
  66. });
  67. // Start search.
  68. search.start();
  69. }