Modernise autosuggest code #25
@ -116,22 +116,33 @@ class AutoSuggest {
|
|||||||
fillContainer(response) {
|
fillContainer(response) {
|
||||||
this.selectedIndex = 0;
|
this.selectedIndex = 0;
|
||||||
|
|
||||||
|
let query = this.input.value.trim().replace(/[\-\[\]{}()*+?.,\\\/^\$|#]/g, ' ');
|
||||||
|
let query_tokens = query.split(/ +/).sort((a,b) => a.length - b.length);
|
||||||
|
|
||||||
response.items.forEach((item, i) => {
|
response.items.forEach((item, i) => {
|
||||||
let node = document.createElement('li');
|
let node = document.createElement('li');
|
||||||
let text = document.createTextNode(item.label);
|
node.innerHTML = this.highlightMatches(query_tokens, item.label);
|
||||||
node.jsondata = item;
|
node.jsondata = item;
|
||||||
node.addEventListener('click', event => {
|
node.addEventListener('click', event => {
|
||||||
this.appendCallback(event.target.jsondata);
|
this.appendCallback(event.target.jsondata);
|
||||||
this.closeContainer();
|
this.closeContainer();
|
||||||
this.clearInput();
|
this.clearInput();
|
||||||
});
|
});
|
||||||
node.appendChild(text);
|
|
||||||
this.container.appendChild(node);
|
this.container.appendChild(node);
|
||||||
if (this.container.children.length === 1) {
|
if (this.container.children.length === 1) {
|
||||||
node.className = 'selected';
|
node.className = 'selected';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
highlightMatches(query_tokens, item) {
|
||||||
|
let itemTokens = item.split(/ +/);
|
||||||
|
let queryTokens = new RegExp('(' + query_tokens.join('\|') + ')', 'i');
|
||||||
|
itemTokens.forEach((token, index) => {
|
||||||
|
item = item.replace(token, token.replace(queryTokens, ($1, match) => '<strong>' + match + '</strong>'));
|
||||||
|
});
|
||||||
|
return item;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
class TagAutoSuggest extends AutoSuggest {
|
class TagAutoSuggest extends AutoSuggest {
|
||||||
|
Loading…
Reference in New Issue
Block a user