Update static/js/script.js
Browse files- static/js/script.js +318 -595
static/js/script.js
CHANGED
|
@@ -1,634 +1,357 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
//
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
//
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
const $ = id => document.getElementById(id);
|
| 33 |
-
const chatMessages = $("chat-messages");
|
| 34 |
-
const chatTextarea = $("chat-textarea");
|
| 35 |
-
const btnSend = $("btn-send");
|
| 36 |
-
const sendIcon = $("send-icon");
|
| 37 |
-
const loadingIcon = $("loading-icon");
|
| 38 |
-
const welcomeScreen = $("welcome-screen");
|
| 39 |
-
const attachBadge = $("attach-badge");
|
| 40 |
-
const attachNameEl = $("attach-name");
|
| 41 |
-
const modelSelect = $("model-select");
|
| 42 |
-
const historyList = $("history-list");
|
| 43 |
-
const chatTitle = $("chat-title");
|
| 44 |
-
|
| 45 |
-
// ─────────────────────────────────────
|
| 46 |
-
// LocalStorage
|
| 47 |
-
// ─────────────────────────────────────
|
| 48 |
-
function saveSessions() {
|
| 49 |
-
try { localStorage.setItem(sessionsKey, JSON.stringify(sessions)); } catch (_) {}
|
| 50 |
-
}
|
| 51 |
-
function loadSessions() {
|
| 52 |
-
try { sessions = JSON.parse(localStorage.getItem(sessionsKey) || "{}"); }
|
| 53 |
-
catch (_) { sessions = {}; }
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
// ─────────────────────────────────────
|
| 57 |
-
// Session Management
|
| 58 |
-
// ─────────────────────────────────────
|
| 59 |
-
function newSession() {
|
| 60 |
-
const id = String(Date.now());
|
| 61 |
-
sessions[id] = { title: "New Chat", messages: [] };
|
| 62 |
-
currentSid = id;
|
| 63 |
-
saveSessions();
|
| 64 |
-
return id;
|
| 65 |
-
}
|
| 66 |
-
function getMessages() {
|
| 67 |
-
if (!currentSid || !sessions[currentSid]) newSession();
|
| 68 |
-
return sessions[currentSid].messages;
|
| 69 |
-
}
|
| 70 |
-
function appendMessage(role, content) {
|
| 71 |
-
const msgs = getMessages();
|
| 72 |
-
msgs.push({ role, content });
|
| 73 |
-
if (role === "user" && msgs.filter(m => m.role === "user").length === 1) {
|
| 74 |
-
sessions[currentSid].title = content.split(" ").slice(0, 7).join(" ") + "…";
|
| 75 |
-
chatTitle.textContent = sessions[currentSid].title;
|
| 76 |
-
renderSidebar();
|
| 77 |
-
}
|
| 78 |
-
saveSessions();
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
// ─────────────────────────────────────
|
| 82 |
-
// Sidebar
|
| 83 |
-
// ─────────────────────────────────────
|
| 84 |
-
function renderSidebar() {
|
| 85 |
-
historyList.innerHTML = "";
|
| 86 |
-
const entries = Object.entries(sessions).sort(([a], [b]) => Number(b) - Number(a));
|
| 87 |
-
entries.forEach(([id, s]) => {
|
| 88 |
-
const btn = document.createElement("button");
|
| 89 |
-
const isActive = id === currentSid;
|
| 90 |
-
btn.className = `sidebar-item w-full text-left px-3 py-2 rounded-xl text-xs truncate transition-all ${
|
| 91 |
-
isActive
|
| 92 |
-
? "bg-accent-light text-accent font-semibold"
|
| 93 |
-
: "text-gray-600 hover:bg-white hover:shadow-sm font-medium"
|
| 94 |
-
}`;
|
| 95 |
-
btn.textContent = s.title || "New Chat";
|
| 96 |
-
btn.addEventListener("click", () => loadSession(id));
|
| 97 |
-
historyList.appendChild(btn);
|
| 98 |
-
});
|
| 99 |
}
|
| 100 |
|
| 101 |
-
function
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
}
|
| 115 |
|
| 116 |
-
//
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
function populateModelSelect() {
|
| 120 |
-
if (!appSettings) return;
|
| 121 |
-
const list = appSettings.provider === "Nvidia NIM"
|
| 122 |
-
? (appSettings.models_nvidia || [])
|
| 123 |
-
: (appSettings.models_openrouter || []);
|
| 124 |
-
|
| 125 |
-
modelSelect.innerHTML = "";
|
| 126 |
-
list.forEach(m => {
|
| 127 |
-
const opt = document.createElement("option");
|
| 128 |
-
opt.value = m;
|
| 129 |
-
opt.textContent = m.length > 30 ? m.slice(0, 28) + "…" : m;
|
| 130 |
-
if (m === appSettings.current_model) opt.selected = true;
|
| 131 |
-
modelSelect.appendChild(opt);
|
| 132 |
-
});
|
| 133 |
-
// fallback: if current_model not in list, select first
|
| 134 |
-
if (modelSelect.options.length && !modelSelect.value) {
|
| 135 |
-
modelSelect.selectedIndex = 0;
|
| 136 |
-
}
|
| 137 |
-
}
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
try {
|
| 143 |
-
await fetch("/api/settings", {
|
| 144 |
-
method: "POST",
|
| 145 |
-
headers: { "Content-Type": "application/json" },
|
| 146 |
-
body: JSON.stringify({ current_model: modelSelect.value }),
|
| 147 |
-
});
|
| 148 |
-
} catch (_) {}
|
| 149 |
-
});
|
| 150 |
-
|
| 151 |
-
// ─────────────────────────────────────
|
| 152 |
-
// Chat UI Helpers
|
| 153 |
-
// ─────────────────────────────────────
|
| 154 |
-
function showWelcome() {
|
| 155 |
-
welcomeScreen.style.display = "";
|
| 156 |
-
welcomeScreen.style.opacity = "1";
|
| 157 |
-
}
|
| 158 |
-
function hideWelcome() {
|
| 159 |
-
welcomeScreen.style.display = "none";
|
| 160 |
-
}
|
| 161 |
-
function clearChatView() {
|
| 162 |
-
chatMessages.innerHTML = "";
|
| 163 |
-
}
|
| 164 |
-
function scrollBottom() {
|
| 165 |
-
chatMessages.scrollTop = chatMessages.scrollHeight;
|
| 166 |
}
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
).join("\n");
|
| 194 |
-
return h;
|
| 195 |
}
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
const wrap = document.createElement("div");
|
| 200 |
-
wrap.className = `flex ${isUser ? "justify-end" : "justify-start"} px-4 md:px-16 py-2${animate ? " " + (isUser ? "bubble-user" : "bubble-ai") : ""}`;
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
}
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
<span class="typing-dot w-2 h-2 rounded-full bg-gray-400 inline-block"></span>
|
| 231 |
-
<span class="typing-dot w-2 h-2 rounded-full bg-gray-400 inline-block"></span>
|
| 232 |
-
</div>`;
|
| 233 |
-
chatMessages.appendChild(w);
|
| 234 |
-
scrollBottom();
|
| 235 |
-
}
|
| 236 |
-
function removeTyping() {
|
| 237 |
-
const e = $("typing-indicator");
|
| 238 |
-
if (e) e.remove();
|
| 239 |
}
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
chatMessages.appendChild(d);
|
| 248 |
-
scrollBottom();
|
| 249 |
}
|
| 250 |
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
}
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
setBusy(true);
|
| 280 |
-
|
| 281 |
-
renderBubble("user", raw);
|
| 282 |
-
appendMessage("user", fullPrompt);
|
| 283 |
-
renderTyping();
|
| 284 |
-
|
| 285 |
-
try {
|
| 286 |
-
const res = await fetch("/api/chat", {
|
| 287 |
-
method: "POST",
|
| 288 |
-
headers: { "Content-Type": "application/json" },
|
| 289 |
-
body: JSON.stringify({
|
| 290 |
-
prompt: fullPrompt,
|
| 291 |
-
model: modelSelect.value || appSettings?.current_model || "",
|
| 292 |
-
messages: getMessages().slice(0, -1),
|
| 293 |
-
}),
|
| 294 |
});
|
| 295 |
-
const data = await res.json();
|
| 296 |
-
removeTyping();
|
| 297 |
-
if (!res.ok || data.error) {
|
| 298 |
-
renderSys(data.error || "Unknown error.", true);
|
| 299 |
-
} else {
|
| 300 |
-
renderBubble("assistant", data.reply);
|
| 301 |
-
appendMessage("assistant", data.reply);
|
| 302 |
-
}
|
| 303 |
-
} catch (err) {
|
| 304 |
-
removeTyping();
|
| 305 |
-
renderSys(`Network error: ${err.message}`, true);
|
| 306 |
-
} finally {
|
| 307 |
-
setBusy(false);
|
| 308 |
-
chatTextarea.focus();
|
| 309 |
-
}
|
| 310 |
}
|
| 311 |
|
| 312 |
-
//
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
});
|
| 323 |
-
btnSend.addEventListener("click", sendChat);
|
| 324 |
-
|
| 325 |
-
// ─────────────────────────────────────
|
| 326 |
-
// PDF Attachment
|
| 327 |
-
// ─────────────────────────────────────
|
| 328 |
-
function clearAttachment() {
|
| 329 |
-
attachment = null;
|
| 330 |
-
attachBadge.classList.add("hidden");
|
| 331 |
-
attachNameEl.textContent = "";
|
| 332 |
}
|
| 333 |
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
attachBadge.classList.remove("hidden");
|
| 355 |
-
renderSys(`"${data.filename}" attached — ${data.word_count} words extracted.`);
|
| 356 |
-
} catch (err) {
|
| 357 |
-
renderSys(`Upload failed: ${err.message}`, true);
|
| 358 |
-
}
|
| 359 |
-
});
|
| 360 |
-
|
| 361 |
-
// ─────────────────────────────────────
|
| 362 |
-
// DOI Modal
|
| 363 |
-
// ─────────────────────────────────────
|
| 364 |
-
$("btn-doi").addEventListener("click", () => {
|
| 365 |
-
$("doi-modal").classList.remove("hidden");
|
| 366 |
-
$("doi-input").focus();
|
| 367 |
-
});
|
| 368 |
-
$("btn-close-doi").addEventListener("click", () => $("doi-modal").classList.add("hidden"));
|
| 369 |
-
$("doi-modal").addEventListener("click", e => {
|
| 370 |
-
if (e.target === $("doi-modal")) $("doi-modal").classList.add("hidden");
|
| 371 |
-
});
|
| 372 |
-
$("doi-input").addEventListener("keydown", e => {
|
| 373 |
-
if (e.key === "Enter") $("btn-validate-doi").click();
|
| 374 |
-
});
|
| 375 |
-
|
| 376 |
-
$("btn-validate-doi").addEventListener("click", async () => {
|
| 377 |
-
const doi = $("doi-input").value.trim();
|
| 378 |
-
if (!doi) return;
|
| 379 |
-
$("doi-spinner").classList.remove("hidden");
|
| 380 |
-
$("doi-btn-text").textContent = "Validating…";
|
| 381 |
-
$("btn-validate-doi").disabled = true;
|
| 382 |
-
$("doi-result").classList.add("hidden");
|
| 383 |
-
|
| 384 |
-
try {
|
| 385 |
-
const res = await fetch("/api/validate_doi", {
|
| 386 |
-
method: "POST",
|
| 387 |
-
headers: { "Content-Type": "application/json" },
|
| 388 |
-
body: JSON.stringify({ doi }),
|
| 389 |
});
|
| 390 |
-
const data = await res.json();
|
| 391 |
-
$("doi-result").classList.remove("hidden");
|
| 392 |
-
if (!res.ok || data.error) {
|
| 393 |
-
$("doi-result").innerHTML = `<p class="text-red-500">${data.error}</p>`;
|
| 394 |
-
} else {
|
| 395 |
-
$("doi-result").innerHTML = `
|
| 396 |
-
<div class="space-y-2">
|
| 397 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">Title</p>
|
| 398 |
-
<p class="font-medium text-gray-800 text-sm">${data.title}</p></div>
|
| 399 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">Authors</p>
|
| 400 |
-
<p class="text-sm text-gray-700">${data.authors}</p></div>
|
| 401 |
-
<div class="flex gap-6">
|
| 402 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">Year</p>
|
| 403 |
-
<p class="text-sm text-gray-700">${data.year}</p></div>
|
| 404 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">Type</p>
|
| 405 |
-
<p class="text-sm text-gray-700">${data.type}</p></div>
|
| 406 |
-
</div>
|
| 407 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">Source</p>
|
| 408 |
-
<p class="text-sm text-gray-700">${data.journal}</p></div>
|
| 409 |
-
<div><p class="text-[10px] font-semibold text-gray-400 uppercase">DOI</p>
|
| 410 |
-
<p><a href="https://doi.org/${data.doi}" target="_blank" class="text-accent hover:underline text-sm">${data.doi}</a></p></div>
|
| 411 |
-
</div>`;
|
| 412 |
-
renderSys(`DOI validated: ${data.title} (${data.year})`);
|
| 413 |
-
}
|
| 414 |
-
} catch (err) {
|
| 415 |
-
$("doi-result").classList.remove("hidden");
|
| 416 |
-
$("doi-result").innerHTML = `<p class="text-red-500">${err.message}</p>`;
|
| 417 |
-
} finally {
|
| 418 |
-
$("doi-spinner").classList.add("hidden");
|
| 419 |
-
$("doi-btn-text").textContent = "Validate";
|
| 420 |
-
$("btn-validate-doi").disabled = false;
|
| 421 |
-
}
|
| 422 |
-
});
|
| 423 |
-
|
| 424 |
-
// ─────────────────────────────────────
|
| 425 |
-
// Settings Modal
|
| 426 |
-
// ─────────────────────────────────────
|
| 427 |
-
function renderModelList(containerId, models, provider) {
|
| 428 |
-
const list = $(containerId);
|
| 429 |
-
list.innerHTML = "";
|
| 430 |
-
(models || []).forEach((m, i) => {
|
| 431 |
-
const row = document.createElement("div");
|
| 432 |
-
row.className = "flex items-center justify-between px-2 py-1.5 rounded-lg hover:bg-white group transition-colors";
|
| 433 |
-
row.innerHTML = `
|
| 434 |
-
<span class="text-xs text-gray-700 truncate flex-1">${m}</span>
|
| 435 |
-
<button data-i="${i}" data-prov="${provider}"
|
| 436 |
-
class="btn-del-model text-gray-300 hover:text-red-400 ml-2 text-xs font-bold opacity-0 group-hover:opacity-100 transition-opacity">✕</button>`;
|
| 437 |
-
list.appendChild(row);
|
| 438 |
-
});
|
| 439 |
-
list.querySelectorAll(".btn-del-model").forEach(btn => {
|
| 440 |
-
btn.addEventListener("click", () => {
|
| 441 |
-
const idx = Number(btn.dataset.i);
|
| 442 |
-
const prov = btn.dataset.prov;
|
| 443 |
-
if (prov === "OpenRouter") {
|
| 444 |
-
appSettings.models_openrouter.splice(idx, 1);
|
| 445 |
-
renderModelList("models-list-openrouter", appSettings.models_openrouter, "OpenRouter");
|
| 446 |
-
} else {
|
| 447 |
-
appSettings.models_nvidia.splice(idx, 1);
|
| 448 |
-
renderModelList("models-list-nvidia", appSettings.models_nvidia, "Nvidia NIM");
|
| 449 |
-
}
|
| 450 |
-
});
|
| 451 |
-
});
|
| 452 |
}
|
| 453 |
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
}
|
| 466 |
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
$("btn-toggle-key").addEventListener("click", () => {
|
| 473 |
-
const inp = $("settings-apikey");
|
| 474 |
-
inp.type = inp.type === "password" ? "text" : "password";
|
| 475 |
-
});
|
| 476 |
-
|
| 477 |
-
// Add-model handlers
|
| 478 |
-
function addModelHandler(inputId, listKey, containerId, provLabel, btnSuffix) {
|
| 479 |
-
function doAdd() {
|
| 480 |
-
const val = $(inputId).value.trim();
|
| 481 |
-
if (!val || !appSettings) return;
|
| 482 |
-
if (!appSettings[listKey].includes(val)) {
|
| 483 |
-
appSettings[listKey].push(val);
|
| 484 |
-
$(inputId).value = "";
|
| 485 |
-
renderModelList(containerId, appSettings[listKey], provLabel);
|
| 486 |
-
}
|
| 487 |
-
}
|
| 488 |
-
$(`btn-add-model-${btnSuffix}`).addEventListener("click", doAdd);
|
| 489 |
-
$(inputId).addEventListener("keydown", e => { if (e.key === "Enter") { e.preventDefault(); doAdd(); } });
|
| 490 |
}
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
| 507 |
});
|
| 508 |
-
appSettings = await res.json();
|
| 509 |
-
populateModelSelect();
|
| 510 |
-
closeSettings();
|
| 511 |
-
renderSys("Settings saved successfully.");
|
| 512 |
-
} catch (err) {
|
| 513 |
-
renderSys(`Could not save settings: ${err.message}`, true);
|
| 514 |
-
}
|
| 515 |
-
});
|
| 516 |
-
|
| 517 |
-
$("btn-settings").addEventListener("click", openSettings);
|
| 518 |
-
$("btn-close-settings").addEventListener("click", closeSettings);
|
| 519 |
-
$("btn-cancel-settings").addEventListener("click", closeSettings);
|
| 520 |
-
$("settings-modal").addEventListener("click", e => {
|
| 521 |
-
if (e.target === $("settings-modal")) closeSettings();
|
| 522 |
-
});
|
| 523 |
-
|
| 524 |
-
// ─────────────────────────────────────
|
| 525 |
-
// Sidebar / Nav Buttons
|
| 526 |
-
// ─────────────────────────────────────
|
| 527 |
-
$("btn-new-chat").addEventListener("click", () => {
|
| 528 |
-
newSession();
|
| 529 |
-
clearChatView();
|
| 530 |
-
showWelcome();
|
| 531 |
-
clearAttachment();
|
| 532 |
-
chatTitle.textContent = "New Chat";
|
| 533 |
-
renderSidebar();
|
| 534 |
-
chatTextarea.focus();
|
| 535 |
-
});
|
| 536 |
-
|
| 537 |
-
$("btn-clear-chat").addEventListener("click", handleClear);
|
| 538 |
-
$("btn-clear-chat-mobile").addEventListener("click", handleClear);
|
| 539 |
-
|
| 540 |
-
function handleClear() {
|
| 541 |
-
if (!currentSid) return;
|
| 542 |
-
sessions[currentSid].messages = [];
|
| 543 |
-
sessions[currentSid].title = "New Chat";
|
| 544 |
-
saveSessions();
|
| 545 |
-
clearChatView();
|
| 546 |
-
showWelcome();
|
| 547 |
-
chatTitle.textContent = "New Chat";
|
| 548 |
-
renderSidebar();
|
| 549 |
}
|
| 550 |
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
}
|
| 569 |
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
$("sidebar-overlay").addEventListener("click", toggleSidebar);
|
| 573 |
-
|
| 574 |
-
// ─────────────────────────────────────
|
| 575 |
-
// Boot
|
| 576 |
-
// ─────────────────────────────────────
|
| 577 |
-
async function init() {
|
| 578 |
-
try {
|
| 579 |
-
// 1. Load current user
|
| 580 |
-
const meRes = await fetch("/api/me");
|
| 581 |
-
if (meRes.status === 401) { window.location.href = "/login"; return; }
|
| 582 |
-
currentUser = await meRes.json();
|
| 583 |
-
|
| 584 |
-
// 2. Populate sidebar profile
|
| 585 |
-
const avatar = $("user-avatar");
|
| 586 |
-
if (currentUser.picture) {
|
| 587 |
-
avatar.src = currentUser.picture;
|
| 588 |
-
avatar.alt = currentUser.name;
|
| 589 |
-
} else {
|
| 590 |
-
avatar.style.background = "#1a73e8";
|
| 591 |
-
}
|
| 592 |
-
$("user-name").textContent = currentUser.name || currentUser.email || "User";
|
| 593 |
-
|
| 594 |
-
// 3. Scope sessions to user
|
| 595 |
-
sessionsKey = `orbit_sessions_${currentUser.id}`;
|
| 596 |
-
loadSessions();
|
| 597 |
-
|
| 598 |
-
// 4. Load server settings
|
| 599 |
-
const setRes = await fetch("/api/settings");
|
| 600 |
-
if (!setRes.ok) throw new Error("Failed to load settings");
|
| 601 |
-
appSettings = await setRes.json();
|
| 602 |
-
populateModelSelect();
|
| 603 |
-
|
| 604 |
-
// 5. Restore or create chat session
|
| 605 |
-
const ids = Object.keys(sessions).sort((a, b) => Number(b) - Number(a));
|
| 606 |
-
if (ids.length) {
|
| 607 |
-
currentSid = ids[0];
|
| 608 |
-
const msgs = sessions[currentSid]?.messages || [];
|
| 609 |
-
if (msgs.length) {
|
| 610 |
-
hideWelcome();
|
| 611 |
-
msgs.forEach(m => renderBubble(m.role, m.content, false));
|
| 612 |
-
const t = sessions[currentSid]?.title || "New Chat";
|
| 613 |
-
chatTitle.textContent = t;
|
| 614 |
-
scrollBottom();
|
| 615 |
-
} else {
|
| 616 |
-
showWelcome();
|
| 617 |
-
}
|
| 618 |
-
} else {
|
| 619 |
-
newSession();
|
| 620 |
-
showWelcome();
|
| 621 |
-
}
|
| 622 |
-
renderSidebar();
|
| 623 |
-
|
| 624 |
-
// 6. First-run hint if no API key
|
| 625 |
-
if (!appSettings.api_key) {
|
| 626 |
-
setTimeout(() => renderSys("Welcome to ORBIT! Open Settings to add your API key."), 500);
|
| 627 |
-
}
|
| 628 |
-
} catch (err) {
|
| 629 |
-
renderSys(`Startup error: ${err.message}`, true);
|
| 630 |
-
}
|
| 631 |
-
chatTextarea.focus();
|
| 632 |
-
}
|
| 633 |
|
| 634 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
let chatHistory = [];
|
| 2 |
+
let currentSettings = null;
|
| 3 |
+
let modelsOR = [];
|
| 4 |
+
let modelsNV = [];
|
| 5 |
+
let pdfText = "";
|
| 6 |
+
let pdfFilename = "";
|
| 7 |
+
let savedSessions = JSON.parse(localStorage.getItem('orbit_sessions')) || [];
|
| 8 |
+
|
| 9 |
+
// 1. Inisialisasi Aplikasi (Load User & Settings)
|
| 10 |
+
async function initApp() {
|
| 11 |
+
try {
|
| 12 |
+
const userRes = await fetch('/api/me');
|
| 13 |
+
if (!userRes.ok) throw new Error('Not logged in');
|
| 14 |
+
const userData = await userRes.json();
|
| 15 |
+
|
| 16 |
+
// Render Profil
|
| 17 |
+
document.getElementById('user-name').textContent = userData.name || userData.email;
|
| 18 |
+
if (userData.picture) document.getElementById('user-avatar').src = userData.picture;
|
| 19 |
+
|
| 20 |
+
// Render Settings
|
| 21 |
+
const setRes = await fetch('/api/settings');
|
| 22 |
+
if (setRes.ok) {
|
| 23 |
+
currentSettings = await setRes.json();
|
| 24 |
+
modelsOR = currentSettings.models_openrouter || [];
|
| 25 |
+
modelsNV = currentSettings.models_nvidia || [];
|
| 26 |
+
populateModelDropdown(currentSettings);
|
| 27 |
+
}
|
| 28 |
+
renderHistoryList();
|
| 29 |
+
} catch (error) {
|
| 30 |
+
window.location.href = '/login';
|
| 31 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
+
function populateModelDropdown(settings) {
|
| 35 |
+
const select = document.getElementById('model-select');
|
| 36 |
+
select.innerHTML = '';
|
| 37 |
+
let models = [];
|
| 38 |
+
if (settings.provider === 'Google Gemini') models = ['gemini-1.5-pro-latest', 'gemini-1.5-flash-latest'];
|
| 39 |
+
else if (settings.provider === 'OpenRouter') models = settings.models_openrouter || [];
|
| 40 |
+
else if (settings.provider === 'Nvidia NIM') models = settings.models_nvidia || [];
|
| 41 |
+
else models = [settings.current_model || 'default-model'];
|
| 42 |
+
|
| 43 |
+
models.forEach(m => {
|
| 44 |
+
let opt = document.createElement('option');
|
| 45 |
+
opt.value = m;
|
| 46 |
+
opt.textContent = m;
|
| 47 |
+
if(m === settings.current_model) opt.selected = true;
|
| 48 |
+
select.appendChild(opt);
|
| 49 |
+
});
|
| 50 |
}
|
| 51 |
|
| 52 |
+
// 2. Sidebar & Clear Chat Logic
|
| 53 |
+
const sidebar = document.getElementById('sidebar');
|
| 54 |
+
const overlay = document.getElementById('sidebar-overlay');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
function toggleSidebar() {
|
| 57 |
+
sidebar.classList.toggle('-translate-x-full');
|
| 58 |
+
overlay.classList.toggle('hidden');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
}
|
| 60 |
|
| 61 |
+
// Pasang event listener secara aman
|
| 62 |
+
const btnHamburger = document.getElementById('btn-hamburger');
|
| 63 |
+
if(btnHamburger) btnHamburger.addEventListener('click', toggleSidebar);
|
| 64 |
+
|
| 65 |
+
const btnCloseSidebar = document.getElementById('btn-close-sidebar');
|
| 66 |
+
if(btnCloseSidebar) btnCloseSidebar.addEventListener('click', toggleSidebar);
|
| 67 |
+
|
| 68 |
+
if(overlay) overlay.addEventListener('click', toggleSidebar);
|
| 69 |
+
|
| 70 |
+
function clearChat() {
|
| 71 |
+
chatHistory = [];
|
| 72 |
+
removeAttach();
|
| 73 |
+
const chatBox = document.getElementById('chat-messages');
|
| 74 |
+
if(chatBox) {
|
| 75 |
+
chatBox.innerHTML = `
|
| 76 |
+
<div id="welcome-msg" class="flex flex-col items-center justify-center h-full text-center px-4">
|
| 77 |
+
<img src="/static/icon.png" class="w-16 h-16 mb-4 shadow-sm rounded-2xl" onerror="this.style.display='none'">
|
| 78 |
+
<h2 class="text-2xl font-bold text-gray-800 mb-2">Welcome to ORBIT</h2>
|
| 79 |
+
<p class="text-gray-500 text-sm max-w-md">Your AI-powered Educational Research Assistant. Upload a document or type a prompt below to begin.</p>
|
| 80 |
+
</div>
|
| 81 |
+
`;
|
| 82 |
+
}
|
| 83 |
+
if(window.innerWidth < 768 && !sidebar.classList.contains('-translate-x-full')) {
|
| 84 |
+
toggleSidebar();
|
| 85 |
+
}
|
|
|
|
|
|
|
| 86 |
}
|
| 87 |
|
| 88 |
+
const btnNewChat = document.getElementById('btn-new-chat');
|
| 89 |
+
if(btnNewChat) btnNewChat.addEventListener('click', clearChat);
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
const btnClearTop = document.getElementById('btn-clear-chat-top');
|
| 92 |
+
if(btnClearTop) btnClearTop.addEventListener('click', clearChat);
|
| 93 |
|
| 94 |
+
// 3. LocalStorage History
|
| 95 |
+
function renderHistoryList() {
|
| 96 |
+
const list = document.getElementById('history-list');
|
| 97 |
+
if(!list) return;
|
| 98 |
+
if(savedSessions.length === 0) {
|
| 99 |
+
list.innerHTML = `<p class="text-xs text-gray-400 px-3 py-2 italic">No recent chats.</p>`;
|
| 100 |
+
return;
|
| 101 |
+
}
|
| 102 |
+
list.innerHTML = savedSessions.map(s => `
|
| 103 |
+
<button class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-gray-600 hover:bg-white hover:text-accent hover:shadow-sm transition-all text-left truncate">
|
| 104 |
+
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path></svg>
|
| 105 |
+
<span class="truncate">${s.title}</span>
|
| 106 |
+
</button>
|
| 107 |
+
`).join('');
|
| 108 |
+
}
|
| 109 |
|
| 110 |
+
function saveSessionTitle(prompt) {
|
| 111 |
+
if(chatHistory.length === 1) {
|
| 112 |
+
const title = prompt.length > 25 ? prompt.substring(0, 25) + "..." : prompt;
|
| 113 |
+
savedSessions.unshift({ id: Date.now(), title: title });
|
| 114 |
+
if(savedSessions.length > 10) savedSessions.pop(); // Max 10 histori
|
| 115 |
+
localStorage.setItem('orbit_sessions', JSON.stringify(savedSessions));
|
| 116 |
+
renderHistoryList();
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
|
| 120 |
+
// 4. Modal Settings
|
| 121 |
+
const setModal = document.getElementById('settings-modal');
|
| 122 |
|
| 123 |
+
function renderModelLists() {
|
| 124 |
+
const listOR = document.getElementById('models-list-openrouter');
|
| 125 |
+
const listNV = document.getElementById('models-list-nvidia');
|
| 126 |
+
if(listOR) {
|
| 127 |
+
listOR.innerHTML = modelsOR.map((m, i) => `<div class="flex justify-between items-center p-1.5 border-b border-gray-100 text-sm text-gray-600"><span>${m}</span><button onclick="modelsOR.splice(${i},1);renderModelLists()" class="text-red-400 hover:text-red-600 hover:bg-red-50 rounded px-2 font-bold transition-colors">×</button></div>`).join('');
|
| 128 |
+
}
|
| 129 |
+
if(listNV) {
|
| 130 |
+
listNV.innerHTML = modelsNV.map((m, i) => `<div class="flex justify-between items-center p-1.5 border-b border-gray-100 text-sm text-gray-600"><span>${m}</span><button onclick="modelsNV.splice(${i},1);renderModelLists()" class="text-red-400 hover:text-red-600 hover:bg-red-50 rounded px-2 font-bold transition-colors">×</button></div>`).join('');
|
| 131 |
+
}
|
| 132 |
}
|
| 133 |
|
| 134 |
+
const btnAddOR = document.getElementById('btn-add-model-or');
|
| 135 |
+
if(btnAddOR) {
|
| 136 |
+
btnAddOR.addEventListener('click', () => {
|
| 137 |
+
const val = document.getElementById('new-model-or').value.trim();
|
| 138 |
+
if(val && !modelsOR.includes(val)) { modelsOR.push(val); document.getElementById('new-model-or').value=''; renderModelLists(); }
|
| 139 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
|
| 142 |
+
const btnAddNV = document.getElementById('btn-add-model-nv');
|
| 143 |
+
if(btnAddNV) {
|
| 144 |
+
btnAddNV.addEventListener('click', () => {
|
| 145 |
+
const val = document.getElementById('new-model-nv').value.trim();
|
| 146 |
+
if(val && !modelsNV.includes(val)) { modelsNV.push(val); document.getElementById('new-model-nv').value=''; renderModelLists(); }
|
| 147 |
+
});
|
|
|
|
|
|
|
| 148 |
}
|
| 149 |
|
| 150 |
+
const btnOpenSettings = document.getElementById('btn-open-settings');
|
| 151 |
+
if(btnOpenSettings) {
|
| 152 |
+
btnOpenSettings.addEventListener('click', () => {
|
| 153 |
+
if(currentSettings) {
|
| 154 |
+
document.getElementById('settings-provider').value = currentSettings.provider;
|
| 155 |
+
document.getElementById('settings-url').value = currentSettings.base_url;
|
| 156 |
+
document.getElementById('settings-apikey').value = currentSettings.api_key;
|
| 157 |
+
modelsOR = [...currentSettings.models_openrouter];
|
| 158 |
+
modelsNV = [...currentSettings.models_nvidia];
|
| 159 |
+
renderModelLists();
|
| 160 |
+
}
|
| 161 |
+
if(setModal) setModal.classList.remove('hidden');
|
| 162 |
+
if(window.innerWidth < 768) toggleSidebar();
|
| 163 |
+
});
|
| 164 |
}
|
| 165 |
|
| 166 |
+
if(document.getElementById('btn-close-settings')) document.getElementById('btn-close-settings').addEventListener('click', () => setModal.classList.add('hidden'));
|
| 167 |
+
if(document.getElementById('btn-cancel-settings')) document.getElementById('btn-cancel-settings').addEventListener('click', () => setModal.classList.add('hidden'));
|
| 168 |
+
|
| 169 |
+
const btnSaveSettings = document.getElementById('btn-save-settings');
|
| 170 |
+
if(btnSaveSettings) {
|
| 171 |
+
btnSaveSettings.addEventListener('click', async () => {
|
| 172 |
+
const payload = {
|
| 173 |
+
provider: document.getElementById('settings-provider').value,
|
| 174 |
+
base_url: document.getElementById('settings-url').value,
|
| 175 |
+
api_key: document.getElementById('settings-apikey').value,
|
| 176 |
+
models_openrouter: modelsOR,
|
| 177 |
+
models_nvidia: modelsNV,
|
| 178 |
+
current_model: document.getElementById('model-select').value
|
| 179 |
+
};
|
| 180 |
+
await fetch('/api/settings', { method: 'POST', body: JSON.stringify(payload) });
|
| 181 |
+
if(setModal) setModal.classList.add('hidden');
|
| 182 |
+
initApp(); // Refresh settingan dropdown
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
}
|
| 185 |
|
| 186 |
+
// 5. Modal DOI
|
| 187 |
+
const doiModal = document.getElementById('doi-modal');
|
| 188 |
+
const btnOpenDoi = document.getElementById('btn-open-doi');
|
| 189 |
+
if(btnOpenDoi) {
|
| 190 |
+
btnOpenDoi.addEventListener('click', () => {
|
| 191 |
+
if(doiModal) doiModal.classList.remove('hidden');
|
| 192 |
+
const resDiv = document.getElementById('doi-result');
|
| 193 |
+
if(resDiv) resDiv.classList.add('hidden');
|
| 194 |
+
if(window.innerWidth < 768) toggleSidebar();
|
| 195 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
}
|
| 197 |
|
| 198 |
+
if(document.getElementById('btn-close-doi')) document.getElementById('btn-close-doi').addEventListener('click', () => doiModal.classList.add('hidden'));
|
| 199 |
+
|
| 200 |
+
const btnValDoi = document.getElementById('btn-validate-doi-submit');
|
| 201 |
+
if(btnValDoi) {
|
| 202 |
+
btnValDoi.addEventListener('click', async () => {
|
| 203 |
+
const doi = document.getElementById('doi-input').value;
|
| 204 |
+
const resDiv = document.getElementById('doi-result');
|
| 205 |
+
if(!doi) return;
|
| 206 |
+
|
| 207 |
+
resDiv.classList.remove('hidden');
|
| 208 |
+
resDiv.innerHTML = `<div class="flex items-center gap-2 text-blue-600"><svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> Validating...</div>`;
|
| 209 |
+
|
| 210 |
+
const res = await fetch('/api/validate_doi', { method: 'POST', body: JSON.stringify({doi: doi}) });
|
| 211 |
+
const data = await res.json();
|
| 212 |
+
|
| 213 |
+
if(data.error) {
|
| 214 |
+
resDiv.innerHTML = `<span class="text-red-500 font-medium">Error: ${data.error}</span>`;
|
| 215 |
+
} else {
|
| 216 |
+
resDiv.innerHTML = `<strong class="text-gray-800">${data.title}</strong><br><span class="text-xs text-gray-500 block mt-1">${data.authors} (${data.year})</span><span class="inline-block mt-2 px-2 py-1 bg-blue-50 text-blue-600 text-[10px] rounded border border-blue-100 uppercase tracking-wide font-bold">${data.type}</span>`;
|
| 217 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
}
|
| 220 |
|
| 221 |
+
// 6. PDF Attachment
|
| 222 |
+
const btnAttach = document.getElementById('btn-attach');
|
| 223 |
+
const pdfInput = document.getElementById('pdf-input');
|
| 224 |
+
|
| 225 |
+
if(btnAttach && pdfInput) {
|
| 226 |
+
btnAttach.addEventListener('click', () => pdfInput.click());
|
| 227 |
+
|
| 228 |
+
pdfInput.addEventListener('change', async (e) => {
|
| 229 |
+
const file = e.target.files[0];
|
| 230 |
+
if(!file) return;
|
| 231 |
+
const formData = new FormData();
|
| 232 |
+
formData.append('file', file);
|
| 233 |
+
|
| 234 |
+
document.getElementById('attach-name').textContent = "Extracting...";
|
| 235 |
+
document.getElementById('attach-badge').classList.remove('hidden');
|
| 236 |
+
|
| 237 |
+
try {
|
| 238 |
+
const res = await fetch('/api/upload_pdf', { method: 'POST', body: formData });
|
| 239 |
+
const data = await res.json();
|
| 240 |
+
if(res.ok) {
|
| 241 |
+
pdfText = data.text;
|
| 242 |
+
pdfFilename = data.filename;
|
| 243 |
+
document.getElementById('attach-name').textContent = pdfFilename;
|
| 244 |
+
} else {
|
| 245 |
+
throw new Error(data.error);
|
| 246 |
+
}
|
| 247 |
+
} catch (err) {
|
| 248 |
+
alert("Upload failed: " + err.message);
|
| 249 |
+
removeAttach();
|
| 250 |
+
}
|
| 251 |
+
});
|
| 252 |
}
|
| 253 |
|
| 254 |
+
function removeAttach() {
|
| 255 |
+
pdfText = ""; pdfFilename = "";
|
| 256 |
+
if(document.getElementById('pdf-input')) document.getElementById('pdf-input').value = "";
|
| 257 |
+
if(document.getElementById('attach-badge')) document.getElementById('attach-badge').classList.add('hidden');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
}
|
| 259 |
+
|
| 260 |
+
const btnRemoveAttach = document.getElementById('btn-remove-attach');
|
| 261 |
+
if(btnRemoveAttach) btnRemoveAttach.addEventListener('click', removeAttach);
|
| 262 |
+
|
| 263 |
+
// 7. Chat Logic
|
| 264 |
+
const tx = document.getElementById('chat-textarea');
|
| 265 |
+
const btnSend = document.getElementById('btn-send');
|
| 266 |
+
|
| 267 |
+
if(tx) {
|
| 268 |
+
tx.addEventListener("input", function() {
|
| 269 |
+
this.style.height = 'auto';
|
| 270 |
+
this.style.height = (this.scrollHeight) + 'px';
|
| 271 |
+
});
|
| 272 |
+
|
| 273 |
+
tx.addEventListener('keydown', function(e) {
|
| 274 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
| 275 |
+
e.preventDefault();
|
| 276 |
+
if(btnSend) btnSend.click();
|
| 277 |
+
}
|
| 278 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
}
|
| 280 |
|
| 281 |
+
if(btnSend) {
|
| 282 |
+
btnSend.addEventListener('click', async () => {
|
| 283 |
+
let prompt = tx.value.trim();
|
| 284 |
+
if(!prompt && !pdfText) return;
|
| 285 |
+
|
| 286 |
+
const chatBox = document.getElementById('chat-messages');
|
| 287 |
+
const welcomeMsg = document.getElementById('welcome-msg');
|
| 288 |
+
if(welcomeMsg) welcomeMsg.remove();
|
| 289 |
+
|
| 290 |
+
tx.value = '';
|
| 291 |
+
tx.style.height = 'auto';
|
| 292 |
+
btnSend.disabled = true;
|
| 293 |
+
|
| 294 |
+
let displayPrompt = prompt;
|
| 295 |
+
let systemPrompt = prompt;
|
| 296 |
+
|
| 297 |
+
// Inject PDF context
|
| 298 |
+
if (pdfText) {
|
| 299 |
+
displayPrompt = `<div class="flex items-center gap-1.5 bg-blue-500/30 text-white text-xs px-2.5 py-1.5 rounded-lg mb-2 font-medium w-fit"><svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg> ${pdfFilename}</div>${prompt}`;
|
| 300 |
+
systemPrompt = `[Attached Document: ${pdfFilename}]\n${pdfText}\n\nUser Question: ${prompt}`;
|
| 301 |
+
removeAttach();
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// Tampilkan pesan User
|
| 305 |
+
chatHistory.push({ role: "user", content: systemPrompt });
|
| 306 |
+
saveSessionTitle(prompt || pdfFilename);
|
| 307 |
+
|
| 308 |
+
chatBox.innerHTML += `<div class="flex justify-end mb-6"><div class="bg-accent text-white p-4 rounded-2xl rounded-tr-none max-w-[85%] shadow-sm text-[15px] leading-relaxed">${displayPrompt.replace(/\n/g, '<br>')}</div></div>`;
|
| 309 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
| 310 |
+
|
| 311 |
+
// Tampilkan loading AI
|
| 312 |
+
const loadId = 'load-' + Date.now();
|
| 313 |
+
chatBox.innerHTML += `<div id="${loadId}" class="flex mb-6 gap-4 items-start"><img src="/static/icon.png" class="w-8 h-8 rounded-full border border-slate-200 mt-1 shadow-sm shrink-0" onerror="this.style.display='none'"><div class="bg-[#f8f9fa] border border-slate-200 p-4 rounded-2xl rounded-tl-none text-gray-500 flex items-center gap-2"><svg class="w-4 h-4 animate-spin text-accent" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> Analyzing...</div></div>`;
|
| 314 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
| 315 |
+
|
| 316 |
+
try {
|
| 317 |
+
// Tembak API
|
| 318 |
+
const res = await fetch('/api/chat', {
|
| 319 |
+
method: 'POST',
|
| 320 |
+
headers: { 'Content-Type': 'application/json' },
|
| 321 |
+
body: JSON.stringify({
|
| 322 |
+
prompt: systemPrompt,
|
| 323 |
+
messages: chatHistory.slice(0, -1),
|
| 324 |
+
model: document.getElementById('model-select').value
|
| 325 |
+
})
|
| 326 |
+
});
|
| 327 |
+
const data = await res.json();
|
| 328 |
+
|
| 329 |
+
document.getElementById(loadId).remove();
|
| 330 |
+
|
| 331 |
+
if(!res.ok) throw new Error(data.error || 'Server error');
|
| 332 |
+
|
| 333 |
+
chatHistory.push({ role: "assistant", content: data.reply });
|
| 334 |
+
|
| 335 |
+
// Render format Markdown pakai library Marked.js
|
| 336 |
+
const renderedMarkdown = marked.parse(data.reply);
|
| 337 |
+
chatBox.innerHTML += `<div class="flex mb-6 gap-4 items-start"><img src="/static/icon.png" class="w-8 h-8 rounded-full border border-slate-200 mt-1 shadow-sm shrink-0" onerror="this.style.display='none'"><div class="bg-[#f8f9fa] border border-slate-200 p-5 rounded-2xl rounded-tl-none max-w-[90%] md:max-w-[85%] prose-orbit shadow-sm">${renderedMarkdown}</div></div>`;
|
| 338 |
+
|
| 339 |
+
} catch (e) {
|
| 340 |
+
if(document.getElementById(loadId)) document.getElementById(loadId).remove();
|
| 341 |
+
chatBox.innerHTML += `<div class="flex mb-6 gap-4 items-start"><div class="bg-red-50 text-red-600 p-4 rounded-2xl rounded-tl-none border border-red-100 max-w-[85%] text-[15px] shadow-sm"><strong class="block mb-1">Error processing request:</strong>${e.message}</div></div>`;
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
btnSend.disabled = false;
|
| 345 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
| 346 |
+
});
|
| 347 |
}
|
| 348 |
|
| 349 |
+
// 8. Boot & Service Worker
|
| 350 |
+
initApp();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
+
if ('serviceWorker' in navigator) {
|
| 353 |
+
window.addEventListener('load', () => {
|
| 354 |
+
navigator.serviceWorker.register('/sw.js', { scope: '/' })
|
| 355 |
+
.catch(err => console.error('PWA SW failed:', err));
|
| 356 |
+
});
|
| 357 |
+
}
|