Skip to content

Commit

Permalink
Autocomplete fallback (#215)
Browse files Browse the repository at this point in the history
* autocomplete: fallback to fetch if local returns no results

* fix: don't show autocomplete if by the time fetch is complete value had already changed

* autocomplete tag controller: lower images count req from 4 to 1
  • Loading branch information
mdashlw authored Mar 24, 2024
1 parent f5642d1 commit 921ad0c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
13 changes: 10 additions & 3 deletions assets/js/autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,19 @@ function listenAutocomplete() {
document.addEventListener('input', event => {
removeParent();
fetchLocalAutocomplete(event);
window.clearTimeout(timeout);

if (localAc !== null && 'ac' in event.target.dataset) {
inputField = event.target;
originalTerm = `${inputField.value}`.toLowerCase();

const suggestions = localAc.topK(originalTerm, 5).map(({ name, imageCount }) => ({ label: `${name} (${imageCount})`, value: name }));
return showAutocomplete(suggestions, originalTerm, event.target);

if (suggestions.length) {
return showAutocomplete(suggestions, originalTerm, event.target);
}
}

window.clearTimeout(timeout);
// Use a timeout to delay requests until the user has stopped typing
timeout = window.setTimeout(() => {
inputField = event.target;
Expand All @@ -158,7 +161,11 @@ function listenAutocomplete() {
}
else {
// inputField could get overwritten while the suggestions are being fetched - use event.target
getSuggestions(fetchedTerm).then(suggestions => showAutocomplete(suggestions, fetchedTerm, event.target));
getSuggestions(fetchedTerm).then(suggestions => {
if (fetchedTerm === event.target.value) {
showAutocomplete(suggestions, fetchedTerm, event.target);
}
});
}
}
}, 300);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ defmodule PhilomenaWeb.Autocomplete.TagController do
|> Elasticsearch.search_records(preload(Tag, :aliased_tag))
|> Enum.map(&(&1.aliased_tag || &1))
|> Enum.uniq_by(& &1.id)
|> Enum.filter(&(&1.images_count > 3))
|> Enum.filter(&(&1.images_count > 0))
|> Enum.sort_by(&(-&1.images_count))
|> Enum.take(5)
|> Enum.map(&%{label: "#{&1.name} (#{&1.images_count})", value: &1.name})
Expand Down

0 comments on commit 921ad0c

Please sign in to comment.