algolia-search.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*************************************************
  2. * Wowchemy
  3. * https://github.com/wowchemy/wowchemy-hugo-modules
  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. if (helper.state.query === '') {
  23. searchResults.style.display = 'none';
  24. return;
  25. }
  26. helper.search();
  27. searchResults.style.display = 'block';
  28. },
  29. };
  30. const search = instantsearch(options);
  31. // Initialize search box.
  32. search.addWidget(
  33. instantsearch.widgets.searchBox({
  34. container: '#search-box',
  35. autofocus: false,
  36. reset: true,
  37. poweredBy: algoliaConfig.poweredBy,
  38. placeholder: i18n.placeholder,
  39. }),
  40. );
  41. // Initialize search results.
  42. search.addWidget(
  43. instantsearch.widgets.infiniteHits({
  44. container: '#search-hits',
  45. escapeHits: true,
  46. templates: {
  47. empty: '<div class="search-no-results">' + i18n.no_results + '</div>',
  48. item: getTemplate('search-hit-algolia'),
  49. },
  50. cssClasses: {
  51. showmoreButton: 'btn btn-outline-primary',
  52. },
  53. }),
  54. );
  55. // On render search results, localize the content type metadata.
  56. search.on('render', function () {
  57. $('.search-hit-type').each(function () {
  58. let content_key = $(this).text();
  59. if (content_key in content_type) {
  60. $(this).text(content_type[content_key]);
  61. }
  62. });
  63. });
  64. // Start search.
  65. search.start();
  66. }