forked from 0xNyk/council-of-high-intelligence
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
460 lines (370 loc) · 15.2 KB
/
Copy pathapp.js
File metadata and controls
460 lines (370 loc) · 15.2 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
194
195
196
197
198
199
200
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
const VERCEL_API_URL = "https://cohi-p46b.vercel.app/api/chat";
let userManuallySelected = false;
let currentMode = 'full';
const MAX_MEMBERS_FULL = 3;
const MAX_MEMBERS_DUO = 2;
const DEFAULT_TRIAD = ['socrates', 'aurelius', 'kahneman'];
function setMode(mode) {
currentMode = mode;
const btnFull = document.getElementById('mode-full');
const btnDuo = document.getElementById('mode-duo');
const triadsSection = document.getElementById('triads-section');
const warningText = document.getElementById('selection-warning-text');
if (mode === 'full') {
btnFull.classList.add('active');
btnFull.classList.remove('dimmed');
btnDuo.classList.remove('active');
btnDuo.classList.add('dimmed');
triadsSection.style.display = 'block';
warningText.textContent = 'En fazla 3 seçim yapılabilir !';
} else {
btnFull.classList.remove('active');
btnFull.classList.add('dimmed');
btnDuo.classList.add('active');
btnDuo.classList.remove('dimmed');
triadsSection.style.display = 'none';
warningText.textContent = 'En fazla 2 seçim yapılabilir !';
}
document.querySelectorAll('input[name="council-member"]').forEach(cb => cb.checked = false);
userManuallySelected = false;
hideTriadSelection();
hideSelectionWarning();
updateSelectionCount();
}
function getMaxMembers() {
return currentMode === 'duo' ? MAX_MEMBERS_DUO : MAX_MEMBERS_FULL;
}
function selectTriad(memberIds) {
if (currentMode === 'duo') return;
const allCheckboxes = document.querySelectorAll('input[name="council-member"]');
allCheckboxes.forEach(cb => cb.checked = false);
memberIds.forEach(id => {
const checkbox = document.getElementById(id);
if (checkbox) checkbox.checked = true;
});
const allTriadBtns = document.querySelectorAll('.triad-btn');
allTriadBtns.forEach(btn => btn.classList.remove('selected'));
const clickedBtn = Array.from(allTriadBtns).find(btn => {
const btnMemberIds = btn.getAttribute('data-members');
if (!btnMemberIds) return false;
const parsed = JSON.parse(btnMemberIds);
if (parsed.length !== memberIds.length) return false;
return parsed.every((id, index) => id === memberIds[index]);
});
if (clickedBtn) clickedBtn.classList.add('selected');
userManuallySelected = false;
hideSelectionWarning();
updateSelectionCount();
}
function hideTriadSelection() {
const allTriadBtns = document.querySelectorAll('.triad-btn');
allTriadBtns.forEach(btn => btn.classList.remove('selected'));
}
function showSelectionWarning() {
const warning = document.getElementById('selection-warning');
if (warning) {
warning.classList.remove('hidden');
setTimeout(() => {
warning.classList.add('hidden');
}, 3000);
}
}
function hideSelectionWarning() {
const warning = document.getElementById('selection-warning');
if (warning) {
warning.classList.add('hidden');
}
}
function updateSelectionCount() {
const checked = document.querySelectorAll('input[name="council-member"]:checked').length;
const max = getMaxMembers();
const countEl = document.getElementById('selection-count');
if (countEl) {
if (currentMode === 'duo') {
countEl.textContent = `${checked}/2 üye seçildi`;
} else {
countEl.textContent = `${checked}/3 üye seçildi`;
}
}
}
function handleMemberCheckboxClick(event) {
const checkbox = event.target;
if (!checkbox.classList.contains('member-checkbox')) return;
const checked = document.querySelectorAll('input[name="council-member"]:checked');
const max = getMaxMembers();
if (checked.length > max) {
checkbox.checked = false;
showSelectionWarning();
return;
}
if (checkbox.checked) {
userManuallySelected = true;
hideTriadSelection();
}
updateSelectionCount();
}
const DAILY_LIMIT = 5;
const STORAGE_KEY_COUNT = 'cohi_daily_count';
const STORAGE_KEY_DATE = 'cohi_daily_date';
function updateQueryCountDisplay() {
const limitCheck = checkDailyLimit();
const queryCountEl = document.getElementById('query-count');
if (limitCheck.reached) {
queryCountEl.textContent = 'Günlük soru sayınız bitti !';
queryCountEl.classList.add('exhausted');
document.getElementById('submit-btn').disabled = true;
} else {
queryCountEl.textContent = `(${limitCheck.remaining} sorgu hakkınız bulunmakta)`;
queryCountEl.classList.remove('exhausted');
}
}
function checkDailyLimit() {
const today = new Date().toDateString();
const storedDate = localStorage.getItem(STORAGE_KEY_DATE);
const count = parseInt(localStorage.getItem(STORAGE_KEY_COUNT) || '0', 10);
if (storedDate !== today) {
localStorage.setItem(STORAGE_KEY_DATE, today);
localStorage.setItem(STORAGE_KEY_COUNT, '0');
return { remaining: DAILY_LIMIT, reached: false };
}
return { remaining: DAILY_LIMIT - count, reached: count >= DAILY_LIMIT };
}
function incrementDailyCount() {
const today = new Date().toDateString();
const storedDate = localStorage.getItem(STORAGE_KEY_DATE);
if (storedDate !== today) {
localStorage.setItem(STORAGE_KEY_DATE, today);
localStorage.setItem(STORAGE_KEY_COUNT, '1');
} else {
const count = parseInt(localStorage.getItem(STORAGE_KEY_COUNT) || '0', 10);
localStorage.setItem(STORAGE_KEY_COUNT, String(count + 1));
}
}
function showLimitReachedMessage() {
const responseBox = document.getElementById("response-box");
const loading = document.getElementById("loading");
responseBox.innerHTML = '';
loading.classList.add("hidden");
const div = document.createElement('div');
div.className = 'limit-warning';
div.innerHTML = '<strong>Konsey dinlenmeye çekildi !</strong><br>Bugünlük 5 tartışma hakkınız doldu. Yarın tekrar bekleriz.';
responseBox.appendChild(div);
const queryCountEl = document.getElementById('query-count');
queryCountEl.textContent = 'Günlük soru sayınız bitti !';
queryCountEl.classList.add('exhausted');
document.getElementById('submit-btn').disabled = true;
}
function showRateLimitMessage(seconds) {
const responseBox = document.getElementById("response-box");
const loading = document.getElementById("loading");
responseBox.innerHTML = '';
loading.classList.add("hidden");
const div = document.createElement('div');
div.className = 'limit-warning';
div.innerHTML = `<strong>Çok fazla istek !</strong><br>Lütfen ${seconds} saniye bekleyin.`;
responseBox.appendChild(div);
}
async function askCouncil() {
const submitBtn = document.getElementById("submit-btn");
const userInput = document.getElementById("user-input").value;
const checkedCheckboxes = document.querySelectorAll('input[name="council-member"]:checked');
const selectedMembers = Array.from(checkedCheckboxes).map(cb => cb.value);
const responseBox = document.getElementById("response-box");
const loading = document.getElementById("loading");
const max = getMaxMembers();
const min = currentMode === 'duo' ? 2 : 1;
if (selectedMembers.length < min) {
alert(`Lütfen en az ${min} üye seçin.`);
return;
}
if (!userInput.trim()) {
alert("Lütfen bir fikir yazın.");
return;
}
const limitCheck = checkDailyLimit();
if (limitCheck.reached) {
showLimitReachedMessage();
return;
}
submitBtn.disabled = true;
const isMobile = window.innerWidth <= 768;
const scrollTarget = isMobile ? document.body.scrollHeight : 0;
window.scrollTo({ top: scrollTarget, behavior: "smooth" });
loading.classList.remove("hidden");
responseBox.innerHTML = "";
try {
const response = await fetch(VERCEL_API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: userInput,
members: selectedMembers,
mode: currentMode
})
});
if (response.status === 429) {
const data = await response.json().catch(() => ({}));
loading.classList.add("hidden");
submitBtn.disabled = false;
const waitSeconds = data.reset
? Math.ceil((new Date(data.reset) - Date.now()) / 1000)
: 60;
showRateLimitMessage(Math.max(waitSeconds, 60));
return;
}
if (!response.ok) {
throw new Error("Sunucu yanıt vermedi.");
}
const data = await response.json();
incrementDailyCount();
displayResults(data);
updateQueryCountDisplay();
} catch (error) {
console.error("Hata Detayı:", error);
responseBox.innerHTML = '';
const p = document.createElement('p');
p.className = 'error';
p.textContent = 'Bir sorun oluştu: ' + error.message;
responseBox.appendChild(p);
} finally {
loading.classList.add("hidden");
submitBtn.disabled = false;
}
}
function parseMarkdown(text) {
if (!text) return '';
let html = text
.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
.replace(/^### (.+)$/gm, '<h4>$1</h4>')
.replace(/^## (.+)$/gm, '<h3>$1</h3>')
.replace(/^# (.+)$/gm, '<h2>$1</h2>')
.replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>')
.replace(/^(\d+)\. (.+)$/gm, '<li><span class="list-number">$1.</span> $2</li>')
.replace(/^- (.+)$/gm, '<li>$1</li>');
html = html.replace(/(<li>[\s\S]*?<\/li>)/g, '<ul>$1</ul>');
html = html.replace(/\n/g, '<br>');
html = html.replace(/<\/li>(\s*)<br>/g, '</li>$1');
html = html.replace(/<br>(\s*)<ul>/g, '<ul>');
html = html.replace(/<\/ul>(\s*)<br>/g, '</ul>$1');
html = html.replace(/<\/h[34]>(\s*)<br>/g, '</h4>');
html = html.replace(/<br>(\s*)<h[34]>/g, '<h4>');
html = html.replace(/<br>(\s*)<blockquote>/g, '<blockquote>');
html = html.replace(/<\/blockquote>(\s*)<br>/g, '</blockquote>');
return html;
}
function displayResults(data) {
const responseBox = document.getElementById("response-box");
responseBox.innerHTML = '';
if (!data) {
const p = document.createElement('p');
p.className = 'error';
p.textContent = 'Sunucu yanıt vermedi.';
responseBox.appendChild(p);
return;
}
const hasRound1AndRound2 = Array.isArray(data.round1) && Array.isArray(data.round2);
const hasResponses = Array.isArray(data.responses);
if (hasRound1AndRound2) {
const round1Div = document.createElement('div');
round1Div.className = 'deliberation-round';
const round1Title = document.createElement('h4');
round1Title.textContent = '1. Tur: Bağımsız Analiz';
round1Div.appendChild(round1Title);
data.round1.forEach(res => {
const memberDiv = document.createElement('div');
memberDiv.className = 'member-response';
const h3 = document.createElement('h3');
h3.textContent = (res.member || '').toUpperCase();
const content = document.createElement('div');
content.className = 'member-content';
content.innerHTML = parseMarkdown(res.answer || '');
memberDiv.appendChild(h3);
memberDiv.appendChild(content);
round1Div.appendChild(memberDiv);
});
responseBox.appendChild(round1Div);
const round2Div = document.createElement('div');
round2Div.className = 'deliberation-round cross-exam';
const round2Title = document.createElement('h4');
round2Title.textContent = '2. Tur: Karşılıklı Tartışma';
round2Div.appendChild(round2Title);
data.round2.forEach(res => {
const memberDiv = document.createElement('div');
memberDiv.className = 'member-response cross-exam';
const h3 = document.createElement('h3');
h3.textContent = (res.member || '').toUpperCase();
const content = document.createElement('div');
content.className = 'member-content';
content.innerHTML = parseMarkdown(res.answer || '');
memberDiv.appendChild(h3);
memberDiv.appendChild(content);
round2Div.appendChild(memberDiv);
});
responseBox.appendChild(round2Div);
const verdictDiv = document.createElement('div');
verdictDiv.className = 'final-verdict';
const verdictH3 = document.createElement('h3');
verdictH3.textContent = 'Nihai Karar';
const verdictContent = document.createElement('div');
verdictContent.className = 'verdict-content';
verdictContent.innerHTML = parseMarkdown(data.verdict || '');
verdictDiv.appendChild(verdictH3);
verdictDiv.appendChild(verdictContent);
responseBox.appendChild(verdictDiv);
} else if (hasResponses) {
data.responses.forEach(res => {
const div = document.createElement('div');
div.className = 'member-response';
const h3 = document.createElement('h3');
h3.textContent = (res.member || '').toUpperCase();
const content = document.createElement('div');
content.className = 'member-content';
content.innerHTML = parseMarkdown(res.answer || '');
div.appendChild(h3);
div.appendChild(content);
responseBox.appendChild(div);
});
const verdictDiv = document.createElement('div');
verdictDiv.className = 'final-verdict';
const verdictH3 = document.createElement('h3');
verdictH3.textContent = 'Nihai Karar';
const verdictContent = document.createElement('div');
verdictContent.className = 'verdict-content';
verdictContent.innerHTML = parseMarkdown(data.verdict || '');
verdictDiv.appendChild(verdictH3);
verdictDiv.appendChild(verdictContent);
responseBox.appendChild(verdictDiv);
} else {
const p = document.createElement('p');
p.className = 'error';
p.textContent = 'Beklenmeyen sunucu yanıtı.';
responseBox.appendChild(p);
}
}
function closeIntroBox() {
const introBox = document.getElementById("intro-box");
introBox.classList.add("hidden");
localStorage.setItem("cohi_intro_shown", "true");
}
function showIntroBoxIfNeeded() {
const introBox = document.getElementById("intro-box");
const shown = localStorage.getItem("cohi_intro_shown");
if (!shown) {
introBox.classList.remove("hidden");
}
}
function initMemberCheckboxes() {
const checkboxes = document.querySelectorAll('.member-checkbox');
checkboxes.forEach(cb => {
cb.addEventListener('click', handleMemberCheckboxClick);
});
}
window.addEventListener("DOMContentLoaded", () => {
showIntroBoxIfNeeded();
updateQueryCountDisplay();
initMemberCheckboxes();
setMode('full');
});