${_title}
${_description || 'No description available.'}
`;
}
return output;
}
function getSearchResult(list, keys, searchKey) {
const defaultOptions = {
shouldSort: true,
threshold: 0.4,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: keys
};
const options = { ...defaultOptions };
// eslint-disable-next-line no-undef
const searchIndex = Fuse.createIndex(options.keys, list);
// eslint-disable-next-line no-undef
const fuse = new Fuse(list, options, searchIndex);
const result = fuse.search(searchKey);
if (result.length > 20) {
return result.slice(0, 20);
}
return result;
}
function debounce(func, wait, immediate) {
let timeout;
return function() {
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) {
// eslint-disable-next-line consistent-this, no-invalid-this
func.apply(this, args);
}
}, wait);
if (immediate && !timeout) {
// eslint-disable-next-line consistent-this, no-invalid-this
func.apply(this, args);
}
};
}
let searchData;
async function search(event) {
const value = event.target.value;
const keys = ['title', 'description'];
if (!resultBox) {
console.error('Search result container not found');
return;
}
if (!value) {
showResultText('Type anything to view search result');
return;
}
if (!searchData) {
showResultText('Loading...');
try {
// eslint-disable-next-line require-atomic-updates
searchData = await fetchAllData();
} catch (e) {
console.log(e);
showResultText('Failed to load result.');
return;
}
}
const result = getSearchResult(searchData, keys, value);
if (!result.length) {
showResultText('No result found! Try some different combination.');
return;
}
// eslint-disable-next-line require-atomic-updates
resultBox.innerHTML = buildSearchResult(result);
}
function onDomContentLoaded() {
const searchButton = document.querySelectorAll('.search-button');
const debouncedSearch = debounce(search, 300);
if (searchCloseButton) {
searchCloseButton.addEventListener('click', hideSearch);
}
if (searchButton) {
searchButton.forEach(function(item) {
item.addEventListener('click', showSearch);
});
}
if (searchContainer) {
searchContainer.addEventListener('click', hideSearch);
}
if (searchWrapper) {
searchWrapper.addEventListener('click', function(event) {
event.stopPropagation();
});
}
if (searchInput) {
searchInput.addEventListener('keyup', debouncedSearch);
}
// eslint-disable-next-line no-undef
if (window.location.hash === searchHash) {
showSearch();
}
}
// eslint-disable-next-line no-undef
window.addEventListener('DOMContentLoaded', onDomContentLoaded);
// eslint-disable-next-line no-undef
window.addEventListener('hashchange', function() {
// eslint-disable-next-line no-undef
if (window.location.hash === searchHash) {
showSearch();
}
});