From 7e2f3fca091c08771486df0b870ce187f869d363 Mon Sep 17 00:00:00 2001 From: muqiuhan Date: Tue, 28 Feb 2023 09:58:51 +0000 Subject: deploy: b780169745c17f9fc971299e923e5ca5669b5a22 --- js/search.js | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 js/search.js (limited to 'js/search.js') diff --git a/js/search.js b/js/search.js new file mode 100644 index 00000000..2c7188af --- /dev/null +++ b/js/search.js @@ -0,0 +1,78 @@ +// Global searchConfig + +document.addEventListener('DOMContentLoaded', () => { + + const input = document.querySelector('.search-input'); + const container = document.querySelector('.search-result-container'); + + const localSearch = new LocalSearch({ + path : searchConfig.path, + top_n_per_article: searchConfig.top_n_per_article, + unescape : searchConfig.unescape + }); + + if (searchConfig.preload) { + // preload the search data when the page loads + console.log("loading page"); + localSearch.fetchData(); + } + + function openSearchPopup() { + document.querySelector('.search-popup').classList.add('search-activate'); + if (!localSearch.isfetched) { + localSearch.fetchData(); + } + } + + function closeSearchPopup() { + document.querySelector('.search-popup').classList.remove('search-activate'); + // refresh search box + input.value = ''; + container.innerHTML = `
`; + } + + // open search box + document.querySelector('.search-btn').addEventListener('click', openSearchPopup); + + // close search box + document.querySelector('.search-popup-overlay').addEventListener('click', closeSearchPopup); + document.querySelector('.search-close-btn').addEventListener('click', closeSearchPopup); + + function displaySearchResult() { + if (!localSearch.isfetched) return; + const searchText = input.value.trim().toLowerCase(); + const keywords = searchText.split(/[-\s]+/); + if (searchText.length > 0) { + resultItems = localSearch.getResultItems(keywords); + } + + if (keywords.length === 1 && keywords[0] === '') { + // no input + container.innerHTML = `
` + } else if (resultItems.length === 0) { + // no result + container.innerHTML = `
No result found
`; + } else { + // display result(s) + container.innerHTML = ` +
${resultItems.length} result(s) found
+ `; + } + + }; + + if (searchConfig.trigger == 'auto') { + // whenever there is input, update search result + input.addEventListener('input', displaySearchResult); + } else { + // update search result when press "enter" + input.addEventListener('keypress', event => { + if (event.key === 'Enter') { + displaySearchResult(); + } + }) + } + window.addEventListener('search:loaded', displaySearchResult); +}); + \ No newline at end of file -- cgit v1.2.3