xenux4u commited on
Commit
e67e6d1
·
verified ·
1 Parent(s): 1d42604

Update static/js/script.js

Browse files
Files changed (1) hide show
  1. static/js/script.js +80 -62
static/js/script.js CHANGED
@@ -1,6 +1,6 @@
1
  /**
2
  * ORBIT – Educational Research Assistant
3
- * FULL V-MASTER SCRIPT - WITH "THINKING PROCESS" ILLUSION & ELEGANT UI
4
  */
5
 
6
  document.addEventListener('DOMContentLoaded', () => {
@@ -12,7 +12,9 @@ document.addEventListener('DOMContentLoaded', () => {
12
  let sessions = {};
13
  let appSettings = null;
14
  let isBusy = false;
15
- let pdfText = ""; let pdfFilename = "";
 
 
16
 
17
  const DEFAULT_OR_MODELS = [
18
  "baidu/cobuddy:free",
@@ -29,7 +31,7 @@ document.addEventListener('DOMContentLoaded', () => {
29
  "meta-llama/llama-3.3-70b-instruct:free"
30
  ];
31
 
32
- // TOAST NOTIFICATION (DIJAMIN MUNCUL - MURNI VANILLA CSS)
33
  function showToast(message, isError = false) {
34
  let toast = $('orbit-toast');
35
  if (!toast) {
@@ -48,25 +50,16 @@ document.addEventListener('DOMContentLoaded', () => {
48
  toast.style.backgroundColor = isError ? '#ef4444' : '#10b981';
49
  toast.innerHTML = isError ? `<span>❌</span> <span>${message}</span>` : `<span>✅</span> <span>${message}</span>`;
50
 
51
- setTimeout(() => {
52
- toast.style.opacity = '1';
53
- toast.style.transform = 'translate(-50%, 0)';
54
- }, 10);
55
-
56
- setTimeout(() => {
57
- toast.style.opacity = '0';
58
- toast.style.transform = 'translate(-50%, -20px)';
59
- }, 3000);
60
  }
61
 
62
- // 1. DATA RECOVERY
63
  try {
64
  const stored = localStorage.getItem('orbit_sessions_v14');
65
  sessions = stored ? JSON.parse(stored) : {};
66
  if (typeof sessions !== 'object' || Array.isArray(sessions)) sessions = {};
67
  } catch(e) { sessions = {}; }
68
 
69
- // 2. PWA INSTALL LOGIC
70
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
71
  let deferredPrompt;
72
 
@@ -89,7 +82,6 @@ document.addEventListener('DOMContentLoaded', () => {
89
  }
90
  });
91
 
92
- // 3. BOOT & INIT
93
  async function init() {
94
  try {
95
  const me = await fetch('/api/me', { cache: 'no-store' });
@@ -112,12 +104,7 @@ document.addEventListener('DOMContentLoaded', () => {
112
  if (!localStorage.getItem('orbit_force_free_v6')) {
113
  appSettings.models_openrouter = [...DEFAULT_OR_MODELS];
114
  localStorage.setItem('orbit_force_free_v6', 'true');
115
-
116
- fetch('/api/settings', {
117
- method: 'POST',
118
- headers: {'Content-Type': 'application/json'},
119
- body: JSON.stringify(appSettings)
120
- }).catch(err => console.error("Auto-save failed", err));
121
  } else {
122
  appSettings.models_openrouter = safeArr(appSettings.models_openrouter);
123
  }
@@ -131,7 +118,6 @@ document.addEventListener('DOMContentLoaded', () => {
131
  }
132
  }
133
 
134
- // 4. SESSIONS & HISTORY
135
  function save() { try { localStorage.setItem('orbit_sessions_v14', JSON.stringify(sessions)); } catch(e){} }
136
  function newSession() { const id = Date.now().toString(); sessions[id] = { title: "New Chat", messages: [] }; loadSession(id); }
137
  addEvt('btn-new-chat', 'click', newSession);
@@ -140,9 +126,7 @@ document.addEventListener('DOMContentLoaded', () => {
140
  if(!sessions[id]) return;
141
  currentSid = id;
142
 
143
- const cm = $('chat-messages');
144
- const ws = $('welcome-msg');
145
-
146
  if(cm) cm.innerHTML = '';
147
 
148
  if(sessions[id].messages && sessions[id].messages.length > 0) {
@@ -153,8 +137,7 @@ document.addEventListener('DOMContentLoaded', () => {
153
  }
154
 
155
  renderHistory();
156
- const ca = $('chat-area');
157
- if(ca) ca.scrollTop = ca.scrollHeight;
158
  }
159
 
160
  function renderHistory() {
@@ -168,7 +151,6 @@ document.addEventListener('DOMContentLoaded', () => {
168
  }
169
  window.ls = id => { loadSession(id); if(window.innerWidth < 768) toggleSidebar(); };
170
 
171
- // 5. CHAT UI
172
  function renderBubble(role, content) {
173
  const isUser = (role === 'user');
174
  const wrap = document.createElement('div');
@@ -188,40 +170,53 @@ document.addEventListener('DOMContentLoaded', () => {
188
  async function sendChat() {
189
  if(isBusy) return;
190
  const raw = $('chat-textarea').value.trim();
191
- if(!raw && !pdfText) return;
192
 
193
  $('chat-textarea').value = ''; $('chat-textarea').style.height = 'auto';
194
  if($('welcome-msg')) $('welcome-msg').classList.add('hidden');
195
 
196
  let full = raw; let display = raw.replace(/\n/g, '<br>');
197
- if(pdfText) { full = `[PDF: ${pdfFilename}]\n${pdfText}\n\nUser: ${raw}`; display = `<div class="bg-blue-500 text-white text-[10px] px-2 py-1 rounded w-fit mb-1 font-bold">📄 ${pdfFilename}</div>${display}`; pdfText = ""; $('attach-badge').classList.add('hidden'); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  if(!sessions[currentSid].messages || !sessions[currentSid].messages.length) sessions[currentSid].title = raw.slice(0, 20) || "New Chat";
200
- sessions[currentSid].messages.push({ role: 'user', content: full, displayContent: display });
201
  renderBubble('user', display);
202
 
203
  isBusy = true; $('btn-send').disabled = true;
204
 
205
- // --- ANIMASI KERANGKA BERPIKIR DIMULAI ---
206
  const loadId = 'load-' + Date.now();
207
  const textId = 'text-' + Date.now();
208
-
209
  const thinkingSteps = [
210
- "Memahami konteks pertanyaan akademis...",
211
  "Memindai literatur dan referensi yang relevan...",
212
- "Mengekstrak poin-poin penting dari data...",
213
- "Menyusun kerangka sintesis dan argumen...",
214
- "Memvalidasi struktur logika...",
215
- "Menyempurnakan tata bahasa dan penyajian akhir..."
216
  ];
217
 
218
  if($('chat-messages')) {
219
  $('chat-messages').insertAdjacentHTML('beforeend', `
220
  <div id="${loadId}" class="flex mb-8 gap-4 items-start">
221
- <div class="w-9 h-9 rounded-2xl bg-white shadow-sm border border-gray-200 flex items-center justify-center shrink-0 overflow-hidden mt-1">
222
- <img src="/static/icon.png" class="w-5 h-5 object-contain" onerror="this.style.display='none'">
223
- </div>
224
- <div class="bg-white border border-gray-200 px-5 py-4 rounded-[24px] rounded-tl-[8px] shadow-sm flex flex-col gap-2 min-w-[220px] md:min-w-[300px]">
225
  <div class="flex items-center gap-3 text-accent text-sm font-bold">
226
  <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>
227
  Thinking Process
@@ -241,17 +236,20 @@ document.addEventListener('DOMContentLoaded', () => {
241
  stepIndex++;
242
  }
243
  }, 2200);
244
- // --- ILUSI SELESAI ---
245
 
246
  try {
247
  const res = await fetch('/api/chat', {
248
  method: 'POST',
249
  headers: { 'Content-Type': 'application/json' },
250
- body: JSON.stringify({ prompt: full, model: $('model-select').value, messages: sessions[currentSid].messages.slice(0,-1) })
 
 
 
 
 
251
  });
252
  const data = await res.json();
253
 
254
- // Hentikan animasi saat API merespons
255
  clearInterval(thinkingInterval);
256
  if($(loadId)) $(loadId).remove();
257
 
@@ -260,20 +258,16 @@ document.addEventListener('DOMContentLoaded', () => {
260
  renderBubble('assistant', data.reply);
261
  save(); renderHistory();
262
  } catch(e) {
263
- // Pastikan animasi juga berhenti jika error
264
  clearInterval(thinkingInterval);
265
  if($(loadId)) $(loadId).remove();
266
  renderBubble('assistant', `**Error:** ${e.message}`);
267
- } finally {
268
- isBusy = false; $('btn-send').disabled = false;
269
- }
270
  }
271
 
272
  addEvt('btn-send', 'click', sendChat);
273
  addEvt('chat-textarea', 'keydown', e => { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); } });
274
  if($('chat-textarea')) $('chat-textarea').addEventListener('input', function() { this.style.height = 'auto'; this.style.height = Math.min(this.scrollHeight, 160) + 'px'; });
275
 
276
- // 6. SETTINGS MODAL
277
  const provMap = { "OpenRouter": "or", "Nvidia NIM": "nv", "Google Gemini": "gem", "AgentRouter": "ar", "Custom OpenAI": "oai" };
278
 
279
  function syncProviderUI() {
@@ -350,7 +344,6 @@ document.addEventListener('DOMContentLoaded', () => {
350
  bindAdd('btn-add-ar', 'inp-ar', 'models_agentrouter');
351
  bindAdd('btn-add-oai', 'inp-oai', 'models_openai');
352
 
353
- // MANTAP: TYPO 'CLICK' UDAH DIBENERIN DI SINI !!!
354
  addEvt('btn-save-settings', 'click', async () => {
355
  const btn = $('btn-save-settings');
356
  const originalText = btn.textContent;
@@ -393,10 +386,7 @@ document.addEventListener('DOMContentLoaded', () => {
393
  console.error(e);
394
  showToast(`Error: ${e.message}`, true);
395
  } finally {
396
- setTimeout(() => {
397
- btn.textContent = originalText;
398
- btn.disabled = false;
399
- }, 300);
400
  }
401
  });
402
 
@@ -431,7 +421,6 @@ document.addEventListener('DOMContentLoaded', () => {
431
  }
432
  });
433
 
434
- // 8. MISC
435
  function toggleSidebar() { $('sidebar').classList.toggle('-translate-x-full'); $('sidebar-overlay').classList.toggle('hidden'); }
436
  addEvt('btn-hamburger', 'click', toggleSidebar); addEvt('btn-close-sidebar', 'click', toggleSidebar); addEvt('sidebar-overlay', 'click', toggleSidebar);
437
 
@@ -440,17 +429,46 @@ document.addEventListener('DOMContentLoaded', () => {
440
  }
441
  addEvt('btn-clear-chat-top', 'click', clr); addEvt('btn-clear-chat-mobile', 'click', clr);
442
 
 
443
  addEvt('btn-attach', 'click', () => $('pdf-input').click());
444
- addEvt('btn-remove-attach', 'click', () => { pdfText = ""; $('attach-badge').classList.add('hidden'); });
 
445
  if($('pdf-input')) {
446
  $('pdf-input').addEventListener('change', async e => {
447
- const f = e.target.files[0]; if(!f) return; const fd = new FormData(); fd.append('file', f);
448
- $('attach-badge').classList.remove('hidden'); $('attach-name').textContent = "Extracting...";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  try {
450
- const res = await fetch('/api/upload_pdf', { method: 'POST', body: fd });
 
451
  const d = await res.json();
452
- if(res.ok) { pdfText = d.text; pdfFilename = d.filename; $('attach-name').textContent = d.filename; } else { alert(d.error); $('attach-badge').classList.add('hidden'); }
453
- } catch(e) { alert(e.message); $('attach-badge').classList.add('hidden'); }
 
 
 
 
 
 
 
 
 
 
 
 
454
  });
455
  }
456
 
 
1
  /**
2
  * ORBIT – Educational Research Assistant
3
+ * FULL V-MASTER SCRIPT - WITH VISION (IMAGE), DOCX SUPPORT & THINKING ILLUSION
4
  */
5
 
6
  document.addEventListener('DOMContentLoaded', () => {
 
12
  let sessions = {};
13
  let appSettings = null;
14
  let isBusy = false;
15
+
16
+ // Penampung File Universal
17
+ let attachedFile = null;
18
 
19
  const DEFAULT_OR_MODELS = [
20
  "baidu/cobuddy:free",
 
31
  "meta-llama/llama-3.3-70b-instruct:free"
32
  ];
33
 
34
+ // TOAST NOTIFICATION
35
  function showToast(message, isError = false) {
36
  let toast = $('orbit-toast');
37
  if (!toast) {
 
50
  toast.style.backgroundColor = isError ? '#ef4444' : '#10b981';
51
  toast.innerHTML = isError ? `<span>❌</span> <span>${message}</span>` : `<span>✅</span> <span>${message}</span>`;
52
 
53
+ setTimeout(() => { toast.style.opacity = '1'; toast.style.transform = 'translate(-50%, 0)'; }, 10);
54
+ setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translate(-50%, -20px)'; }, 4000);
 
 
 
 
 
 
 
55
  }
56
 
 
57
  try {
58
  const stored = localStorage.getItem('orbit_sessions_v14');
59
  sessions = stored ? JSON.parse(stored) : {};
60
  if (typeof sessions !== 'object' || Array.isArray(sessions)) sessions = {};
61
  } catch(e) { sessions = {}; }
62
 
 
63
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
64
  let deferredPrompt;
65
 
 
82
  }
83
  });
84
 
 
85
  async function init() {
86
  try {
87
  const me = await fetch('/api/me', { cache: 'no-store' });
 
104
  if (!localStorage.getItem('orbit_force_free_v6')) {
105
  appSettings.models_openrouter = [...DEFAULT_OR_MODELS];
106
  localStorage.setItem('orbit_force_free_v6', 'true');
107
+ fetch('/api/settings', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(appSettings) }).catch(err => console.error("Auto-save failed", err));
 
 
 
 
 
108
  } else {
109
  appSettings.models_openrouter = safeArr(appSettings.models_openrouter);
110
  }
 
118
  }
119
  }
120
 
 
121
  function save() { try { localStorage.setItem('orbit_sessions_v14', JSON.stringify(sessions)); } catch(e){} }
122
  function newSession() { const id = Date.now().toString(); sessions[id] = { title: "New Chat", messages: [] }; loadSession(id); }
123
  addEvt('btn-new-chat', 'click', newSession);
 
126
  if(!sessions[id]) return;
127
  currentSid = id;
128
 
129
+ const cm = $('chat-messages'); const ws = $('welcome-msg');
 
 
130
  if(cm) cm.innerHTML = '';
131
 
132
  if(sessions[id].messages && sessions[id].messages.length > 0) {
 
137
  }
138
 
139
  renderHistory();
140
+ const ca = $('chat-area'); if(ca) ca.scrollTop = ca.scrollHeight;
 
141
  }
142
 
143
  function renderHistory() {
 
151
  }
152
  window.ls = id => { loadSession(id); if(window.innerWidth < 768) toggleSidebar(); };
153
 
 
154
  function renderBubble(role, content) {
155
  const isUser = (role === 'user');
156
  const wrap = document.createElement('div');
 
170
  async function sendChat() {
171
  if(isBusy) return;
172
  const raw = $('chat-textarea').value.trim();
173
+ if(!raw && !attachedFile) return;
174
 
175
  $('chat-textarea').value = ''; $('chat-textarea').style.height = 'auto';
176
  if($('welcome-msg')) $('welcome-msg').classList.add('hidden');
177
 
178
  let full = raw; let display = raw.replace(/\n/g, '<br>');
179
+ let payloadImage = null;
180
+ let historyContent = raw; // Khusus buat disimpen di memori lokal biar ga overload
181
+
182
+ // JIKA ADA FILE ATTACHED
183
+ if (attachedFile) {
184
+ if (attachedFile.type === 'document') {
185
+ full = `[Document: ${attachedFile.filename}]\n${attachedFile.text}\n\nUser: ${raw}`;
186
+ historyContent = full;
187
+ display = `<div class="bg-emerald-500 text-white text-[10px] px-2 py-1 rounded w-fit mb-2 font-bold flex items-center gap-1"><svg class="w-3 h-3" 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>${attachedFile.filename}</div>${display}`;
188
+ } else if (attachedFile.type === 'image') {
189
+ payloadImage = { base64: attachedFile.base64, mime: attachedFile.mime };
190
+ historyContent = `[Gambar Diunggah: ${attachedFile.filename}]\n\n${raw}`; // Base64 ga kita simpen ke localstorage biar ga crash HP user
191
+ display = `<div class="mb-2"><img src="data:${attachedFile.mime};base64,${attachedFile.base64}" class="max-h-[200px] rounded-xl border border-gray-200 shadow-sm bg-white" /></div>${display}`;
192
+ }
193
+ attachedFile = null;
194
+ $('attach-badge').classList.add('hidden');
195
+ $('pdf-input').value = '';
196
+ }
197
 
198
  if(!sessions[currentSid].messages || !sessions[currentSid].messages.length) sessions[currentSid].title = raw.slice(0, 20) || "New Chat";
199
+ sessions[currentSid].messages.push({ role: 'user', content: historyContent, displayContent: display });
200
  renderBubble('user', display);
201
 
202
  isBusy = true; $('btn-send').disabled = true;
203
 
204
+ // --- ANIMASI KERANGKA BERPIKIR ---
205
  const loadId = 'load-' + Date.now();
206
  const textId = 'text-' + Date.now();
 
207
  const thinkingSteps = [
208
+ "Memahami konteks pertanyaan...",
209
  "Memindai literatur dan referensi yang relevan...",
210
+ "Mengekstrak poin-poin penting...",
211
+ "Menyusun kerangka sintesis...",
212
+ "Menyempurnakan tata bahasa..."
 
213
  ];
214
 
215
  if($('chat-messages')) {
216
  $('chat-messages').insertAdjacentHTML('beforeend', `
217
  <div id="${loadId}" class="flex mb-8 gap-4 items-start">
218
+ <img src="/static/icon.png" class="w-8 h-8 rounded-full shadow-sm shrink-0">
219
+ <div class="bg-white border border-gray-200 px-5 py-4 rounded-[24px] rounded-tl-[8px] shadow-sm flex flex-col gap-2 min-w-[220px]">
 
 
220
  <div class="flex items-center gap-3 text-accent text-sm font-bold">
221
  <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>
222
  Thinking Process
 
236
  stepIndex++;
237
  }
238
  }, 2200);
 
239
 
240
  try {
241
  const res = await fetch('/api/chat', {
242
  method: 'POST',
243
  headers: { 'Content-Type': 'application/json' },
244
+ body: JSON.stringify({
245
+ prompt: full,
246
+ model: $('model-select').value,
247
+ messages: sessions[currentSid].messages.slice(0,-1),
248
+ image: payloadImage // Ngirim payload ke backend
249
+ })
250
  });
251
  const data = await res.json();
252
 
 
253
  clearInterval(thinkingInterval);
254
  if($(loadId)) $(loadId).remove();
255
 
 
258
  renderBubble('assistant', data.reply);
259
  save(); renderHistory();
260
  } catch(e) {
 
261
  clearInterval(thinkingInterval);
262
  if($(loadId)) $(loadId).remove();
263
  renderBubble('assistant', `**Error:** ${e.message}`);
264
+ } finally { isBusy = false; $('btn-send').disabled = false; }
 
 
265
  }
266
 
267
  addEvt('btn-send', 'click', sendChat);
268
  addEvt('chat-textarea', 'keydown', e => { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); } });
269
  if($('chat-textarea')) $('chat-textarea').addEventListener('input', function() { this.style.height = 'auto'; this.style.height = Math.min(this.scrollHeight, 160) + 'px'; });
270
 
 
271
  const provMap = { "OpenRouter": "or", "Nvidia NIM": "nv", "Google Gemini": "gem", "AgentRouter": "ar", "Custom OpenAI": "oai" };
272
 
273
  function syncProviderUI() {
 
344
  bindAdd('btn-add-ar', 'inp-ar', 'models_agentrouter');
345
  bindAdd('btn-add-oai', 'inp-oai', 'models_openai');
346
 
 
347
  addEvt('btn-save-settings', 'click', async () => {
348
  const btn = $('btn-save-settings');
349
  const originalText = btn.textContent;
 
386
  console.error(e);
387
  showToast(`Error: ${e.message}`, true);
388
  } finally {
389
+ setTimeout(() => { btn.textContent = originalText; btn.disabled = false; }, 300);
 
 
 
390
  }
391
  });
392
 
 
421
  }
422
  });
423
 
 
424
  function toggleSidebar() { $('sidebar').classList.toggle('-translate-x-full'); $('sidebar-overlay').classList.toggle('hidden'); }
425
  addEvt('btn-hamburger', 'click', toggleSidebar); addEvt('btn-close-sidebar', 'click', toggleSidebar); addEvt('sidebar-overlay', 'click', toggleSidebar);
426
 
 
429
  }
430
  addEvt('btn-clear-chat-top', 'click', clr); addEvt('btn-clear-chat-mobile', 'click', clr);
431
 
432
+ // 8. LOGIKA UPLOAD MULTI-FILE
433
  addEvt('btn-attach', 'click', () => $('pdf-input').click());
434
+ addEvt('btn-remove-attach', 'click', () => { attachedFile = null; $('attach-badge').classList.add('hidden'); $('pdf-input').value = ''; });
435
+
436
  if($('pdf-input')) {
437
  $('pdf-input').addEventListener('change', async e => {
438
+ const f = e.target.files[0]; if(!f) return;
439
+
440
+ // VALIDASI EKSTENSI (GUE TAMBAHIN DISINI SESUAI MINTA LU)
441
+ const allowed = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
442
+ const ext = f.name.split('.').pop().toLowerCase();
443
+
444
+ if(!allowed.includes(ext)) {
445
+ showToast("Error: Ekstensi file tidak valid atau tidak diterima!", true);
446
+ $('pdf-input').value = ''; // Reset inputnya
447
+ return;
448
+ }
449
+
450
+ const fd = new FormData(); fd.append('file', f);
451
+ $('attach-badge').classList.remove('hidden');
452
+ $('attach-name').textContent = "Memproses file...";
453
+
454
  try {
455
+ // Tembak ke endpoint yang udah gue update di app.py
456
+ const res = await fetch('/api/upload_file', { method: 'POST', body: fd });
457
  const d = await res.json();
458
+
459
+ if(res.ok) {
460
+ attachedFile = d; // Nampung data (text atau gambar base64)
461
+ $('attach-name').textContent = d.filename;
462
+ } else {
463
+ showToast(d.error || "Gagal mengunggah file.", true);
464
+ $('attach-badge').classList.add('hidden');
465
+ $('pdf-input').value = '';
466
+ }
467
+ } catch(e) {
468
+ showToast(e.message, true);
469
+ $('attach-badge').classList.add('hidden');
470
+ $('pdf-input').value = '';
471
+ }
472
  });
473
  }
474