export function autocomplete (inputField, path) { const input = inputField.querySelector('input'); const inputId = input.id; input.autocomplete = 'off'; const results = document.createElement('ul'); results.className="autocomplete-results"; let selectedLi = null; let inputValue = ''; let clickOccured = false; const leaveSelectedLi = () => { if (selectedLi !== null) { selectedLi.classList.remove('selected'); selectedLi = null; } } const selectLi = (element) => { leaveSelectedLi(); selectedLi = element; if (element !== null) { selectedLi.classList.add('selected'); } return selectedLi; } /*input.addEventListener('blur', () => { setTimeout(() => { if (!clickOccured) { results.hidden = true; } },500); clickOccured = false; });*/ document.addEventListener('click', () => { results.hidden = true; }) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); if (selectedLi !== null) { selectedLi.click(); } } const liste = results.querySelectorAll('li'); if(liste.length === 0) { return; } else { results.hidden = false; } if (e.key === 'ArrowDown') { e.preventDefault(); if (selectedLi === null) { input.value = selectLi(results.querySelector('li')).innerText; } else { selectLi(results.querySelector('#' + inputId + '-ui-' + (Number(selectedLi.dataset.id) + 1))); input.value = selectedLi !== null ? selectedLi.innerText : inputValue } } if(e.key === 'ArrowUp') { e.preventDefault(); if (selectedLi === null) { input.value = selectLi(liste[liste.length - 1]).innerText; } else { selectLi(results.querySelector('#' + inputId + '-ui-' + (Number(selectedLi.dataset.id) - 1))); input.value = selectedLi !== null ? selectedLi.innerText : inputValue } } }) const clearResults = () => { results.innerText = ''; results.hidden = true; } input.addEventListener('input', (e) => { const term = input.value.trim(); if (term.length === 0) { // Ne pas envoyer de requête si le champ est vide clearResults(); return; } // Envoyer une requête Fetch fetch(path+ '?query=' + encodeURIComponent(term), { headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(response => { if (!response.ok) { throw new Error('Erreur lors de la récupération des suggestions'); } return response.json(); }) .then(data => { showResults(data); return true; }) .catch(error => { console.error(error); return false; }); }); const showResults = (data) => { inputValue = input.value; results.hidden = false; results.innerHTML = ''; let i = 0; leaveSelectedLi(); data.forEach(element => { const li = document.createElement('li'); li.innerText = element; li.classList.add('autocomplete-item'); li.id = inputId + '-ui-' + (++i); li.dataset.id = i; results.appendChild(li); li.addEventListener('mouseover', (e) => { selectLi(e.target); }); li.addEventListener('click', (e) => { clickOccured = true; leaveSelectedLi(); input.value = e.target.innerText; clearResults(); },true) }) if (data.length > 0) { input.after(results); } } }