Skip to content

Commit

Permalink
fix: searchbar focus on Esc key press (#393)
Browse files Browse the repository at this point in the history
  • Loading branch information
shanpriyan committed Dec 26, 2022
1 parent 52f9eb5 commit 6091d76
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/assets/js/search.js
Expand Up @@ -108,7 +108,7 @@ function maintainScrollVisibility(activeElement, scrollParent) {
else if (isBelow) {
scrollParent.scrollTo(0, offsetTop - parentOffsetHeight + offsetHeight);
}

}
function debounce(callback, delay) {
let timerId;
Expand All @@ -134,16 +134,16 @@ const debouncedFetchSearchResults = debounce((query) => {
searchInput.addEventListener('keyup', function (e) {
const query = searchInput.value;

if(query === searchQuery) return;
if (query === searchQuery) return;

if (query.length) searchClearBtn.removeAttribute('hidden');
else searchClearBtn.setAttribute('hidden', '');

if (query.length > 2) {
debouncedFetchSearchResults(query);

document.addEventListener('click', function(e) {
if(e.target !== resultsElement) clearSearchResults();
document.addEventListener('click', function (e) {
if (e.target !== resultsElement) clearSearchResults();
});
} else {
clearSearchResults();
Expand All @@ -152,28 +152,33 @@ searchInput.addEventListener('keyup', function (e) {
searchQuery = query
});

searchClearBtn.addEventListener('click', function(e) {
searchClearBtn.addEventListener('click', function (e) {
searchInput.value = '';
searchInput.focus();
clearSearchResults();
searchClearBtn.setAttribute('hidden', '');
});

document.addEventListener('keydown', function(e) {
document.addEventListener('keydown', function (e) {

const searchResults = Array.from(document.querySelectorAll('.search-results__item'));

if(e.key === 'Escape'){
if (e.key === 'Escape') {
e.preventDefault();
clearSearchResults();
searchInput.focus();
if (searchResults.length) {
clearSearchResults();
searchInput.focus();
} else if (!searchResults.length && document.activeElement === searchInput) {
searchInput.blur();
}
}

if((e.metaKey || e.ctrlKey) && e.key === 'k'){
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
searchInput.focus();
document.querySelector('.search').scrollIntoView({behaviour:"smooth",block: "start"});
document.querySelector('.search').scrollIntoView({ behaviour: "smooth", block: "start" });
}

const searchResults = Array.from(document.querySelectorAll('.search-results__item'));
if (!searchResults.length) return;

switch (e.key) {
Expand Down

0 comments on commit 6091d76

Please sign in to comment.