Skip to content

Commit

Permalink
chore: improve search bar shortcut display (#346)
Browse files Browse the repository at this point in the history
* chore: improve search bar shortcut display

* chore: remove focusout handler
  • Loading branch information
imfing authored Apr 1, 2024
1 parent 9f2b67c commit 5103da4
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion assets/js/flexsearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ document.addEventListener("DOMContentLoaded", function () {
el.addEventListener('focus', init);
el.addEventListener('keyup', search);
el.addEventListener('keydown', handleKeyDown);
el.addEventListener('input', handleInputChange);
}

const shortcutElements = document.querySelectorAll('.search-wrapper kbd');

function setShortcutElementsOpacity(opacity) {
shortcutElements.forEach(el => {
el.style.opacity = opacity;
});
}

function handleInputChange(e) {
const opacity = e.target.value.length > 0 ? 0 : 100;
setShortcutElementsOpacity(opacity);
}

// Get the search wrapper, input, and results elements.
Expand Down Expand Up @@ -79,6 +93,7 @@ document.addEventListener("DOMContentLoaded", function () {
e.target !== resultsElement &&
!resultsElement.contains(e.target)
) {
setShortcutElementsOpacity(100);
hideSearchResults();
}
});
Expand Down Expand Up @@ -157,6 +172,10 @@ document.addEventListener("DOMContentLoaded", function () {
case 'Escape':
e.preventDefault();
hideSearchResults();
// Clear the input when pressing escape
inputElement.value = '';
inputElement.dispatchEvent(new Event('input'));
// Remove focus from the input
inputElement.blur();
break;
}
Expand All @@ -170,7 +189,10 @@ document.addEventListener("DOMContentLoaded", function () {
}
}

// Preload the search index.
/**
* Preloads the search index by fetching data and adding it to the FlexSearch index.
* @returns {Promise<void>} A promise that resolves when the index is preloaded.
*/
async function preloadIndex() {
const tokenize = '{{- site.Params.search.flexsearch.tokenize | default "forward" -}}';
window.pageIndex = new FlexSearch.Document({
Expand Down Expand Up @@ -240,6 +262,10 @@ document.addEventListener("DOMContentLoaded", function () {
}
}

/**
* Performs a search based on the provided query and displays the results.
* @param {Event} e - The event object.
*/
function search(e) {
const query = e.target.value;
if (!e.target.value) {
Expand Down Expand Up @@ -308,6 +334,12 @@ document.addEventListener("DOMContentLoaded", function () {
displayResults(sortedResults, query);
}

/**
* Displays the search results on the page.
*
* @param {Array} results - The array of search results.
* @param {string} query - The search query.
*/
function displayResults(results, query) {
const { resultsElement } = getActiveSearchElement();
if (!resultsElement) return;
Expand Down

0 comments on commit 5103da4

Please sign in to comment.