From 4d62285b8cedd13f873357daa0b52170f8dc954a Mon Sep 17 00:00:00 2001 From: pitermarx Date: Tue, 15 Oct 2024 12:18:18 +0100 Subject: [PATCH] try spinner before search --- themes/congo/assets/js/search.js | 111 ++++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 31 deletions(-) diff --git a/themes/congo/assets/js/search.js b/themes/congo/assets/js/search.js index 9fc18d3..2f9698c 100644 --- a/themes/congo/assets/js/search.js +++ b/themes/congo/assets/js/search.js @@ -65,15 +65,69 @@ document.addEventListener("keydown", function (event) { } }); -// queue an update after each keypress. the last one after 250ms of idle time wins input.onkeyup = function (event) { - throttle(() => executeQuery(this.value)); + // queue an update after each keypress. the last one after some idle time wins + let isFirstRun = throttle(() => executeQuery(this.value)); + // on first run, show a spinner + if (isFirstRun) { + output.innerHTML = `
  • + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • `; + } }; -function throttle(func, time = 250) { - throttle.nextExec = func; - clearTimeout(throttle.timeout) - throttle.timeout = setTimeout(() => throttle.nextExec(), time) +function throttle(func, time = 750) { + let isFirstRun = throttle.timeout === undefined + if (!isFirstRun) { + clearTimeout(throttle.timeout) + } + throttle.timeout = setTimeout(() => { + func() + throttle.timeout = undefined + }, time) + return isFirstRun } function displaySearch() { @@ -136,32 +190,27 @@ function buildIndex() { function executeQuery(term) { let results = fuse.search(term); - let resultsHTML = ""; + hasResults = results.length > 0; - if (results.length > 0) { - // prettier-ignore - resultsHTML = results.map(function (value, key) { - return `
  • - -
    -
    ${value.item.title}
    -
    ${value.item.section}${value.item.date == null ? '' : `·${value.item.date}`}
    -
    ${value.item.summary}
    -
    -
    -
    -
    -
  • `; - }).join(""); - hasResults = true; - } else { - resultsHTML = ""; - hasResults = false; + if (!hasResults) { + output.innerHTML = "" + return } - output.innerHTML = resultsHTML; - if (results.length > 0) { - first = output.firstChild.firstElementChild; - last = output.lastChild.firstElementChild; - } + output.innerHTML = results.map(function (value) { + return `
  • + +
    +
    ${value.item.title}
    +
    ${value.item.section}${value.item.date == null ? '' : `·${value.item.date}`}
    +
    ${value.item.summary}
    +
    +
    +
    +
    +
  • `; + }).join(""); + + first = output.firstChild.firstElementChild; + last = output.lastChild.firstElementChild; }