Skip to content

Commit

Permalink
restore the previously chosen result
Browse files Browse the repository at this point in the history
  • Loading branch information
Fil committed Feb 23, 2024
1 parent 58baf85 commit 735af8d
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/client/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,27 @@ input.addEventListener("input", () => {
container.setAttribute("data-shortcut", ""); // prevent conflict with close button
sidebar.classList.add("observablehq-search-results"); // hide pages while showing search results
const results = index.search(currentValue, {boost: {title: 4, keywords: 4}, fuzzy: 0.15, prefix: true});
const previous = sessionStorage.getItem("observablehq-search-chosen");
resultsContainer.innerHTML =
results.length === 0
? "<div>no results</div>"
: `<div>${results.length.toLocaleString("en-US")} result${results.length === 1 ? "" : "s"}</div><ol>${results
.map(renderResult)
.map(({id, score, title}, i) => {
const href = import.meta.resolve(`../${id}`);
return `<li data-score="${Math.min(5, Math.round(0.6 * score))}" class="observablehq-link${
(previous === null ? i === 0 : href === previous) ? ` ${activeClass}` : ""
}"><a href="${escapeDoubleQuote(
href
)}" onclick='sessionStorage.setItem("observablehq-search-chosen",this.getAttribute("href"))'
>${escapeText(String(title ?? "—"))}</a></li>`;
})
.join("")}</ol>`;
if (previous !== null) {
resultsContainer.querySelector(`.${activeClass}`).scrollIntoView({block: "nearest"});
sessionStorage.removeItem("observablehq-search-chosen");
}
});

function renderResult({id, score, title}, i) {
return `<li data-score="${Math.min(5, Math.round(0.6 * score))}" class="observablehq-link${
i === 0 ? ` ${activeClass}` : ""
}"><a href="${escapeDoubleQuote(import.meta.resolve(`../${id}`))}">${escapeText(String(title ?? "—"))}</a></li>`;
}

function escapeDoubleQuote(text) {
return text.replace(/["&]/g, entity);
}
Expand Down

0 comments on commit 735af8d

Please sign in to comment.