feat(search): return results at typing

This commit is contained in:
Jimmy Cai 2020-10-04 15:53:27 +02:00
parent 8aeb562bb3
commit 84a15e1604
No known key found for this signature in database
GPG Key ID: 3EA408E527F37B18

View File

@ -63,7 +63,8 @@ const tagsToReplace = {
'&': '&', '&': '&',
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;',
'"': '&quot;' '"': '&quot;',
'…': '&hellip;'
}; };
function replaceTag(tag) { function replaceTag(tag) {
@ -84,7 +85,7 @@ async function getData() {
return data; return data;
} }
function updateQueryString(keywords: string) { function updateQueryString(keywords: string, replaceState = false) {
const pageURL = new URL(window.location.toString()); const pageURL = new URL(window.location.toString());
if (keywords === '') { if (keywords === '') {
@ -94,7 +95,12 @@ function updateQueryString(keywords: string) {
pageURL.searchParams.set('keyword', keywords); pageURL.searchParams.set('keyword', keywords);
} }
if (replaceState) {
window.history.replaceState('', '', pageURL.toString());
}
else {
window.history.pushState('', '', pageURL.toString()); window.history.pushState('', '', pageURL.toString());
}
} }
function bindQueryStringChange() { function bindQueryStringChange() {
@ -118,11 +124,12 @@ function handleQueryString() {
function bindSearchForm() { function bindSearchForm() {
let lastSearch = ''; let lastSearch = '';
searchForm.addEventListener('submit', async (e) => {
const eventHandler = (e) => {
e.preventDefault(); e.preventDefault();
const keywords = searchInput.value; const keywords = searchInput.value;
updateQueryString(keywords); updateQueryString(keywords, true);
if (keywords === '') { if (keywords === '') {
return clear(); return clear();
@ -132,7 +139,10 @@ function bindSearchForm() {
lastSearch = keywords; lastSearch = keywords;
doSearch(keywords.split(' ')); doSearch(keywords.split(' '));
}) }
searchInput.addEventListener('input', eventHandler);
searchInput.addEventListener('compositionend', eventHandler);
} }
function clear() { function clear() {