SpreadQuiz/js/hintbox.js
2024-03-05 16:07:47 +01:00

70 lines
2.1 KiB
JavaScript

function explode_sanitize_string_list(list, explodeAt = ",") {
let elements = list.split(explodeAt);
let sanitized = [];
elements.forEach((e) => {
if (e.trim() !== "") {
sanitized.push(e);
}
});
return sanitized;
}
const HINTBOX_ID = "HINTBOX";
function close_hintbox(close_if_focused = false) {
setTimeout(() => {
if (close_if_focused || (document.getElementById(HINTBOX_ID).firstChild !== document.activeElement)) {
hide(HINTBOX_ID);
}
}, 20);
}
function open_hintbox(x, y, contents, print_fun, insert_fun) {
let hbw = document.getElementById(HINTBOX_ID);
if (hbw === null) {
hbw = document.createElement("section");
hbw.id = HINTBOX_ID;
hbw.classList.add("hintbox-window");
let lb = document.createElement("select");
lb.size = 5;
lb.style.width = "100%";
hbw.appendChild(lb);
document.body.appendChild(hbw);
}
let lb = hbw.firstChild;
hbw.style.left = `${x}px`;
hbw.style.top = `${y}px`;
lb.innerHTML = "";
contents.forEach((record) => {
let line = print_fun(record);
let opt = document.createElement("option");
opt.value = line;
opt.innerText = line;
lb.appendChild(opt);
});
lb.ondblclick = () => {
insert_fun(lb.value);
};
show(HINTBOX_ID);
}
function open_hintbox_at(target_element_id, req_data, print_fn, insert_fn) {
let targetF = document.getElementById(target_element_id);
let bbox = targetF.getBoundingClientRect();
let list_str = targetF.value.trim().split(",");
if (list_str.length > 0) {
let last_le_str = list_str[list_str.length - 1].trim();
if (last_le_str.length > 2) {
req_data["needle"] = last_le_str; // auto-insert needle
request(req_data).then(resp => {
let groups = JSON.parse(resp);
let x = bbox.x + bbox.width;
let y = bbox.y;
open_hintbox(x, y, groups, print_fn, insert_fn);
});
}
}
}