56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
function _codigoparallevar_enable_search_box(selector, options) {
|
|
const element = document.querySelector(selector);
|
|
if ('placeholder' in options) {
|
|
element.setAttribute('placeholder', options.placeholder);
|
|
}
|
|
|
|
// Prepare backdrop
|
|
const resultsBoxBackdrop = document.createElement('div');
|
|
resultsBoxBackdrop.setAttribute('class', 'results-box-container hidden');
|
|
const resultsBox = document.createElement('div');
|
|
resultsBox.setAttribute('class', 'results-box');
|
|
|
|
resultsBoxBackdrop.appendChild(resultsBox);
|
|
document.body.appendChild(resultsBoxBackdrop);
|
|
|
|
|
|
const DEBOUNCE_TIME = 500; // Milliseconds
|
|
const MIN_LENGTH = 3;
|
|
const SEARCH_ENDPOINT = 'http://localhost:3001/api/search';
|
|
|
|
let debounceWaiter = null;
|
|
let currentQuery = null;
|
|
|
|
let lastVal = null;
|
|
const doQuery = () => {
|
|
const val = element.value.trim();
|
|
if ((val.length < MIN_LENGTH) || (val === lastVal)) {
|
|
return;
|
|
}
|
|
lastVal = val;
|
|
|
|
const uri = SEARCH_ENDPOINT + '?q=' + encodeURIComponent(val);
|
|
let query = fetch(uri);
|
|
currentQuery = query;
|
|
query
|
|
.then(res => res.json())
|
|
.then((body) => {
|
|
if (query !== currentQuery) {
|
|
console.log("Query out-raced 🤷");
|
|
return;
|
|
}
|
|
|
|
console.log('=>', body);
|
|
});
|
|
};
|
|
element.removeAttribute('disabled');
|
|
|
|
element.onkeyup = (ev) => {
|
|
if (debounceWaiter !== null) {
|
|
clearTimeout(debounceWaiter);
|
|
}
|
|
debounceWaiter = setTimeout(doQuery, DEBOUNCE_TIME);
|
|
|
|
};
|
|
}
|