|
// retoor <retoor@molodetz.nl>
|
|
|
|
import { Http } from "./Http.js";
|
|
import { Avatar } from "./Avatar.js";
|
|
import { DomUtils } from "./DomUtils.js";
|
|
import { ListNav } from "./ListNav.js";
|
|
|
|
export class MessageSearch {
|
|
constructor() {
|
|
this.initMessageSearch();
|
|
}
|
|
|
|
initMessageSearch() {
|
|
const searchInput = document.getElementById("message-search");
|
|
if (!searchInput) {
|
|
return;
|
|
}
|
|
|
|
const wrap = searchInput.parentElement;
|
|
const dropdown = document.createElement("div");
|
|
dropdown.className = "search-dropdown";
|
|
dropdown.setAttribute("role", "listbox");
|
|
wrap.appendChild(dropdown);
|
|
|
|
const hide = () => {
|
|
DomUtils.hide(dropdown);
|
|
nav.closed();
|
|
};
|
|
|
|
const nav = new ListNav(searchInput, dropdown, {
|
|
itemSelector: ".search-dropdown-item",
|
|
activeClass: "active",
|
|
chooseOnTab: false,
|
|
isOpen: () => DomUtils.isShown(dropdown),
|
|
onChoose: (item) => { window.location.href = item.href; },
|
|
onEscape: hide,
|
|
});
|
|
|
|
let debounceTimer = null;
|
|
|
|
searchInput.addEventListener("input", () => {
|
|
clearTimeout(debounceTimer);
|
|
const q = searchInput.value.trim();
|
|
if (q.length < 1) {
|
|
dropdown.innerHTML = "";
|
|
hide();
|
|
return;
|
|
}
|
|
debounceTimer = setTimeout(async () => {
|
|
try {
|
|
const data = await Http.getJson(`/messages/search?q=${encodeURIComponent(q)}`);
|
|
const results = data.results || [];
|
|
if (results.length === 0) {
|
|
hide();
|
|
return;
|
|
}
|
|
dropdown.innerHTML = "";
|
|
for (const r of results) {
|
|
const item = document.createElement("a");
|
|
item.className = "search-dropdown-item";
|
|
item.href = `/messages?with_uid=${r.uid}`;
|
|
const label = document.createElement("span");
|
|
label.textContent = r.username;
|
|
item.append(Avatar.imgElement(r.username), label);
|
|
dropdown.appendChild(item);
|
|
}
|
|
DomUtils.show(dropdown);
|
|
nav.opened();
|
|
} catch (e) {
|
|
hide();
|
|
}
|
|
}, 200);
|
|
});
|
|
|
|
document.addEventListener("click", (e) => {
|
|
if (!wrap.contains(e.target)) {
|
|
hide();
|
|
}
|
|
});
|
|
}
|
|
}
|