algolia-search.js 1.9 KB

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