demarches-normaliennes/app/javascript/shared/autocomplete.js
clemkeirua 4373cb22cb Revert "Merge pull request #4552 from tchak/champ-communes"
This reverts commit 4cec26f73a, reversing
changes made to 0ef25ef36c.
2020-01-13 16:26:27 +01:00

51 lines
1.3 KiB
JavaScript

import autocomplete from 'autocomplete.js';
import { getJSON, fire } from '@utils';
const sources = [
{
type: 'address',
url: '/address/suggestions'
}
];
const options = {
autoselect: true,
minLength: 1
};
function selector(type) {
return `[data-autocomplete=${type}]`;
}
function source(url) {
return {
source(query, callback) {
getJSON(url, { request: query }).then(callback);
},
templates: {
suggestion({ label, mine }) {
const mineClass = `path-mine-${mine ? 'true' : 'false'}`;
const openTag = `<div class="aa-suggestion ${mineClass}">`;
return autocomplete.escapeHighlightedString(label, openTag, '</div>');
}
},
debounce: 300
};
}
addEventListener('ds:page:update', function() {
for (let { type, url } of sources) {
for (let element of document.querySelectorAll(selector(type))) {
element.removeAttribute('data-autocomplete');
autocompleteInitializeElement(element, url);
}
}
});
function autocompleteInitializeElement(element, url) {
const select = autocomplete(element, options, [source(url)]);
select.on('autocomplete:selected', ({ target }, suggestion) => {
fire(target, 'autocomplete:select', suggestion);
select.autocomplete.setVal(suggestion.label);
});
}