Skip to content

Commit

Permalink
Merge pull request #2146 from 10up/feature/2143
Browse files Browse the repository at this point in the history
Allow filtering the HTML of Autosuggest items.
  • Loading branch information
brandwaffle authored Apr 13, 2021
2 parents 40f3e8e + ab72184 commit 9dfe833
Showing 1 changed file with 12 additions and 22 deletions.
34 changes: 12 additions & 22 deletions assets/js/autosuggest.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ async function esSearch(query, searchTerm) {
/**
* Update the auto suggest box with new options or hide if none
*
* @param {Array} options - formatted results
* @param {Array} options - search results
* @param {string} input - search string
* @returns {boolean} return true
*/
Expand Down Expand Up @@ -242,7 +242,8 @@ function updateAutosuggestBox(options, input) {
// create markup for list items
// eslint-disable-next-line
for ( i = 0; resultsLimit > i; ++i ) {
const { text, url } = options[i];
const text = options[i]._source.post_title;
const url = options[i]._source.permalink;
const escapedText = escapeDoubleQuotes(text);

const searchParts = value.trim().split(' ');
Expand All @@ -258,11 +259,17 @@ function updateAutosuggestBox(options, input) {
);
}

itemString += `<li class="autosuggest-item" role="option" aria-selected="false" id="autosuggest-option-${i}">
let itemHTML = `<li class="autosuggest-item" role="option" aria-selected="false" id="autosuggest-option-${i}">
<a href="${url}" class="autosuggest-link" data-search="${escapedText}" data-url="${url}" tabindex="-1">
${resultsText}
</a>
</li>`;

if (typeof window.epAutosuggestItemHTMLFilter !== 'undefined') {
itemHTML = window.epAutosuggestItemHTMLFilter(itemHTML, options[i], i, value);
}

itemString += itemHTML;
}

// append list items to the list
Expand Down Expand Up @@ -431,22 +438,6 @@ function init() {
);
}

/**
* Helper function to format search results for consumption
* by the updateAutosuggestBox function
*
* @param {object} hits - results from ES
* @returns {Array} formatted hits
*/
const formatSearchResults = (hits) => {
return hits.map((hit) => {
const text = hit._source.post_title;
const url = hit._source.permalink;

return { text, url };
});
};

// to be used by the handleUpDown function
// to keep track of the currently selected result
let currentIndex;
Expand Down Expand Up @@ -581,12 +572,11 @@ function init() {

if (response && response._shards && response._shards.successful > 0) {
const hits = checkForOrderedPosts(response.hits.hits, searchText);
const formattedResults = formatSearchResults(hits);

if (formattedResults.length === 0) {
if (hits.length === 0) {
hideAutosuggestBox();
} else {
updateAutosuggestBox(formattedResults, input);
updateAutosuggestBox(hits, input);
}
} else {
hideAutosuggestBox();
Expand Down

0 comments on commit 9dfe833

Please sign in to comment.