Autocomplete fallback (#215)

* 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
This commit is contained in:
mdashlw 2024-03-24 18:38:23 +03:00 committed by GitHub
parent f5642d1d39
commit 921ad0c59a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 4 deletions

View file

@ -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 }));
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;
@ -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);

View file

@ -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})