shimatta-kenkyusho/shimatta_kenkyusho/static/js/autocomplete.js

95 lines
3.4 KiB
JavaScript
Raw Normal View History

const autocomplete_query_delay_ms = 60;
class AutocompleteCustomUi {
constructor(text_id, dropdown_id, query_function)
{
this.text_id = text_id;
this.dropdown_id = dropdown_id;
this.query_callback = query_function.bind(this);
document.getElementById(text_id).addEventListener("keyup", this.ac_delay(function(event) {
this.query_callback(document.getElementById(this.text_id).value, this);
}, autocomplete_query_delay_ms).bind(this));
2021-11-08 23:11:05 +01:00
this.dropdown_data = {};
}
/**
*
* @param {*} nodes_to_add A liust of dictionaries containing the shown objects and the data called when clicked.
*
* The list: {{'ui': <nodes>, 'data': 'my_data'}, {}, ...}
*
*/
show_results(nodes_to_add, data_clicked_callback) {
var ul = document.getElementById(this.dropdown_id);
ul.innerHTML = '';
this.select_data = {};
2021-11-08 23:11:05 +01:00
this.dropdown_data = {};
for (var i = 0; i < nodes_to_add.length; i++) {
var ui = nodes_to_add[i]['ui'];
var data = nodes_to_add[i]['data']
var dropdown_node = document.createElement('li');
2021-11-08 23:11:05 +01:00
dropdown_node.dataset.ac_clicked = i;
this.dropdown_data[i] = data;
dropdown_node.addEventListener('click',
(e) => {
2021-11-08 23:11:05 +01:00
data_clicked_callback(this.dropdown_data[e.currentTarget.dataset.ac_clicked]);
var text_box = document.getElementById(this.text_id);
var dropdown = bootstrap.Dropdown.getOrCreateInstance(text_box);
dropdown.hide();
});
dropdown_node.setAttribute('class', 'dropdown-item');
dropdown_node.appendChild(ui);
ul.appendChild(dropdown_node);
}
var dropdown = bootstrap.Dropdown.getOrCreateInstance(document.getElementById(this.text_id));
dropdown.show();
}
ac_delay(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
callback.apply(context, args);
}, ms || 0);
};
}
}
class AutocompleteText extends AutocompleteCustomUi {
show_results(results) {
var ul = document.getElementById(this.dropdown_id);
ul.innerHTML = '';
for (var i = 0; i < results.length; i++) {
var node = document.createElement('li');
node.setAttribute('class', 'dropdown-item');
node.appendChild(document.createTextNode(results[i]));
ul.appendChild(node);
node.addEventListener('click',
(e) => {
var element = e.target;
var text_box = document.getElementById(this.text_id);
text_box.value = element.innerHTML;
var dropdown = bootstrap.Dropdown.getOrCreateInstance(text_box);
dropdown.hide();
}
);
}
if (results.length == 0) {
var node = document.createElement('li');
node.setAttribute('class', 'dropdown-item text-danger');
node.appendChild(document.createTextNode('No results'));
ul.appendChild(node);
}
var dropdown = bootstrap.Dropdown.getOrCreateInstance(document.getElementById(this.text_id));
dropdown.show();
}
}