From 968e22473df003144970dc009dff30c831052649 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Thu, 16 May 2024 16:10:35 +0200 Subject: [PATCH] feat: Add `AlgoliaIndex/SearchAsYouType` filter --- source/js/algolia-index-js-searchpage.js | 24 ++++++++++++++++++++---- source/php/App.php | 1 + 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/source/js/algolia-index-js-searchpage.js b/source/js/algolia-index-js-searchpage.js index 22b2090..52ec8b8 100644 --- a/source/js/algolia-index-js-searchpage.js +++ b/source/js/algolia-index-js-searchpage.js @@ -32,14 +32,29 @@ document.addEventListener('DOMContentLoaded', function() { /* Searchbox */ const renderSearchBox = (renderOptions, isFirstRender) => { - const { query, refine, clear, isSearchStalled, widgetParams } = renderOptions; + const { query, refine, clear, isSearchStalled, widgetParams: { searchAsYouType = true } = {} } = renderOptions; if (isFirstRender) { const searchInput = document.getElementById('input_searchboxfield'); searchInput.value = algoliaSearchData.searchQuery; refine(algoliaSearchData.searchQuery); - searchInput.addEventListener('input', event => { - refine(event.target.value); - }); + if (searchAsYouType) { + searchInput.addEventListener('input', event => { + refine(event.target.value); + }); + } else { + // Detect Enter key press + searchInput.addEventListener('keypress', (event) => { + if (event.key === 'Enter') { + refine(event.target.value); + } + }); + // Detect clear action (when input value changes to empty) + searchInput.addEventListener('input', (event) => { + if (event.target.value === '') { + refine(event.target.value); + } + }); + } } }; const customSearchBox = connectSearchBox( @@ -64,6 +79,7 @@ document.addEventListener('DOMContentLoaded', function() { //Do search search(query); }, + searchAsYouType: Boolean(algoliaSearchData.searchAsYouType), }), diff --git a/source/php/App.php b/source/php/App.php index 8eec103..4153536 100644 --- a/source/php/App.php +++ b/source/php/App.php @@ -76,6 +76,7 @@ public function enqueueScripts() 'applicationId' => \AlgoliaIndex\Helper\Options::applicationId(), 'indexName' => \AlgoliaIndex\Helper\Options::indexName(), 'searchQuery' => get_search_query(), + 'searchAsYouType' => apply_filters('AlgoliaIndex/SearchAsYouType', true), ]); //UI settings