Skip to content

Commit

Permalink
fix: delays in search box usage (#744)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenFluin authored Feb 13, 2024
1 parent f1f242e commit b670594
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/scripts/search.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
const loadSearch = async () => {
document.querySelector("#search")?.removeEventListener("click", loadSearch);
document.querySelector("#search")?.removeEventListener("keydown", loadSearch);
const algoliasearch = (await import("algoliasearch/lite")).default;
const instantsearch = (await import("instantsearch.js")).default;
const { searchBox, hits } = await import("instantsearch.js/es/widgets");

console.log(algoliasearch);

const searchClient = algoliasearch(
"ECUG3H1E0M",
"79f21d06bc68b25fa46dda5e23318a3f"
);

/* Save search state so it's not lost with widget load */
const typed = (<HTMLInputElement>document.querySelector("#search input"))
.value;

const search = instantsearch({
indexName: "documentation",
searchClient,
Expand All @@ -19,6 +23,11 @@ const loadSearch = async () => {
},
},
onStateChange: stateChange,
initialUiState: {
documentation: {
query: typed,
},
},
});

let timerId = 0;
Expand All @@ -29,20 +38,22 @@ const loadSearch = async () => {
container: "#search",
// Debounce the search for 300ms
queryHook(query, refine) {
clearTimeout(timerId)
timerId = window.setTimeout(() => refine(query), debounceTime)
clearTimeout(timerId);
timerId = window.setTimeout(() => refine(query), debounceTime);
},
placeholder: typed,
}),

hits({
container: "#search-results",
templates: {
item(hit, { html, components, sendEvent }) {
// Link directly to matched content
const matched = null;// = hit._highlightResult?.contents?.matchedWords[0];
const matched = null; // = hit._highlightResult?.contents?.matchedWords[0];
return html`
<a
href="${hit.url + (matched ? '#:~:text=' + encodeURIComponent(matched) : '')}"
href="${hit.url +
(matched ? "#:~:text=" + encodeURIComponent(matched) : "")}"
onClick="${() => {
sendEvent("click", hit, "Search result clicked");
}}"
Expand Down Expand Up @@ -76,3 +87,4 @@ const loadSearch = async () => {
};

document.getElementById("search")?.addEventListener("click", loadSearch);
document.getElementById("search")?.addEventListener("keydown", loadSearch);

0 comments on commit b670594

Please sign in to comment.