chore: improve search bar shortcut display (#346)

* chore: improve search bar shortcut display

* chore: remove focusout handler
This commit is contained in:
Xin 2024-04-01 20:34:57 +02:00 committed by GitHub
parent 9f2b67c08c
commit 5103da4cd5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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.
@ -79,6 +93,7 @@ document.addEventListener("DOMContentLoaded", function () {
e.target !== resultsElement &&
!resultsElement.contains(e.target)
) {
setShortcutElementsOpacity(100);
hideSearchResults();
}
});
@ -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;
}
@ -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({
@ -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) {
@ -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;