/* Pencarian cepat (Ctrl/⌘ + K): MK, mahasiswa, CPL, dan halaman — sesuai hak akses.
Data dari GET /cari?q= ; navigasi keyboard ↑ ↓ Enter, Esc menutup. */
(function () {
"use strict";
var modalEl = document.getElementById("modal-cari");
if (!modalEl) return;
var input = document.getElementById("cari-input");
var daftar = document.getElementById("cari-hasil");
var hasil = [], pilih = 0, timer = null, nomor = 0;
var IKON = { "Halaman": "layout-grid", "Mata Kuliah": "books", "Mahasiswa": "school", "CPL": "target" };
function esc(t) {
var d = document.createElement("div");
d.textContent = t || "";
return d.innerHTML;
}
function gambar() {
if (!hasil.length) {
daftar.innerHTML = '
Tidak ada yang cocok.
';
return;
}
daftar.innerHTML = hasil.map(function (h, i) {
return '' +
'' +
'' + esc(h.label) + "" +
(h.sub ? '' + esc(h.sub) + "" : "") + "" +
'' + esc(h.jenis) + "";
}).join("");
var aktif = document.getElementById("cari-" + pilih);
if (aktif) aktif.scrollIntoView({ block: "nearest" });
}
function muat() {
var ke = ++nomor;
fetch("/cari?q=" + encodeURIComponent(input.value), { headers: { Accept: "application/json" } })
.then(function (r) { return r.json(); })
.then(function (d) {
if (ke !== nomor) return; // abaikan respons lama
hasil = d.hasil || [];
pilih = 0;
gambar();
})
.catch(function () {});
}
input.addEventListener("input", function () {
clearTimeout(timer);
timer = setTimeout(muat, 150);
});
input.addEventListener("keydown", function (e) {
if (e.key === "ArrowDown") { pilih = Math.min(pilih + 1, hasil.length - 1); gambar(); e.preventDefault(); }
else if (e.key === "ArrowUp") { pilih = Math.max(pilih - 1, 0); gambar(); e.preventDefault(); }
else if (e.key === "Enter" && hasil[pilih]) { location.href = hasil[pilih].href; e.preventDefault(); }
});
// kosongkan & fokus SEKETIKA saat modal mulai dibuka (bukan setelah animasi),
// agar huruf yang langsung diketik setelah Ctrl+K tidak jatuh ke isian form di belakang
modalEl.addEventListener("show.bs.modal", function () {
input.value = "";
hasil = []; pilih = 0;
daftar.innerHTML = "";
input.focus();
muat();
});
modalEl.addEventListener("shown.bs.modal", function () {
if (document.activeElement !== input) input.focus();
});
document.addEventListener("keydown", function (e) {
if ((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "K")) {
e.preventDefault();
if (document.activeElement && document.activeElement !== input) document.activeElement.blur();
bootstrap.Modal.getOrCreateInstance(modalEl).show();
input.focus();
}
});
})();