filter + map -> for of & requestAnimationFrame shenanigans

This commit is contained in:
Cade Scroggins
2022-07-25 08:49:17 -07:00
parent 8a97ddf2c1
commit eb543ac985
+24 -19
View File
@@ -429,7 +429,6 @@
this.#refs.form = clone.querySelector('.form'); this.#refs.form = clone.querySelector('.form');
this.#refs.input = clone.querySelector('.input'); this.#refs.input = clone.querySelector('.input');
this.#refs.suggestionsContainer = clone.querySelector('.suggestions'); this.#refs.suggestionsContainer = clone.querySelector('.suggestions');
this.#refs.input.addEventListener('focus', this.#onFocusInput);
this.#refs.input.addEventListener('input', this.#onInput); this.#refs.input.addEventListener('input', this.#onInput);
const onSubmit = () => this.#execute(this.#refs.input.value); const onSubmit = () => this.#execute(this.#refs.input.value);
this.#refs.form.addEventListener('submit', onSubmit, false); this.#refs.form.addEventListener('submit', onSubmit, false);
@@ -448,12 +447,16 @@
static #fetchDuckDuckGoSuggestions(search) { static #fetchDuckDuckGoSuggestions(search) {
return new Promise((resolve) => { return new Promise((resolve) => {
window.autocompleteCallback = (res) => window.autocompleteCallback = (res) => {
resolve( const suggestions = [];
res
.filter((item) => item.phrase !== search.toLowerCase()) for (const item of res) {
.map((item) => item.phrase) if (item.phrase === search.toLowerCase()) continue;
); suggestions.push(item.phrase);
}
resolve(suggestions);
};
const script = document.createElement('script'); const script = document.createElement('script');
document.querySelector('head').appendChild(script); document.querySelector('head').appendChild(script);
@@ -561,16 +564,14 @@
else this.#refs.input.focus(); else this.#refs.input.focus();
} }
#onFocusInput = (e) => { #onInput = async () => {
const target = e.currentTarget; const q = SearchComponent.#parseQuery(this.#refs.input.value);
requestAnimationFrame(() => { if (!q.query) {
if (!target.value) this.#close(); this.#close();
}); return;
}; }
#onInput = async (e) => {
const q = SearchComponent.#parseQuery(e.currentTarget.value);
let suggestions = CONFIG.suggestions[q.query] ?? []; let suggestions = CONFIG.suggestions[q.query] ?? [];
if (q.search && suggestions.length < SearchComponent.#SUGGESTION_LIMIT) { if (q.search && suggestions.length < SearchComponent.#SUGGESTION_LIMIT) {
@@ -586,13 +587,17 @@
if (!this.#refs.dialog.open) { if (!this.#refs.dialog.open) {
this.#refs.dialog.showModal(); this.#refs.dialog.showModal();
this.#refs.input.focus(); this.#refs.input.focus();
requestAnimationFrame(() => {
// close the search dialog before the next repaint if a character is
// not produced (e.g. if you type shift, control, alt etc.)
if (!this.#refs.input.value) this.#close();
});
return; return;
} }
if ( if (e.key === 'Escape') {
e.key === 'Escape' ||
(e.key === 'Backspace' && !this.#refs.input.value)
) {
this.#close(); this.#close();
return; return;
} }