From 51e8f361183dbd908c7ea7b25901423f9dab45d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Rivi=C3=A8re?= Date: Fri, 23 Feb 2024 14:46:51 +0100 Subject: [PATCH] highlight the current page if present in the search results --- src/client/search.js | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/client/search.js b/src/client/search.js index 4a8b68efb..acf20b0b8 100644 --- a/src/client/search.js +++ b/src/client/search.js @@ -41,15 +41,32 @@ input.addEventListener("input", () => { resultsContainer.innerHTML = results.length === 0 ? "
no results
" - : `
${results.length.toLocaleString("en-US")} result${results.length === 1 ? "" : "s"}
    ${results - .map(renderResult) - .join("")}
`; + : `
${results.length.toLocaleString("en-US")} result${ + results.length === 1 ? "" : "s" + }
    ${renderResults(results)}
`; + resultsContainer.querySelector(`.${activeClass}`).scrollIntoView({block: "nearest"}); }); -function renderResult({id, score, title}, i) { - return `
  • ${escapeText(String(title ?? "—"))}
  • `; +function renderResults(results) { + const me = document.location.href.replace(/[?].*/, ""); + let found; + results = results.map(({id, score, title}) => { + const href = import.meta.resolve(`../${id}`); + return { + title: String(title ?? "—"), + href, + score: Math.min(5, Math.round(0.6 * score)), + active: me === href && (found = true) + }; + }); + if (!found) results[0].active = true; + return results.map(renderResult).join(""); +} + +function renderResult({href, score, title, active}) { + return `
  • ${escapeText(title)}
  • `; } function escapeDoubleQuote(text) {