-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
380 lines (320 loc) Β· 12 KB
/
Copy pathscript.js
File metadata and controls
380 lines (320 loc) Β· 12 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
const PROXY_URL = 'https://20.199.160.8.nip.io/webhook/71b8173a-b959-4881-9302-5525e8320363/chat'
// ββ DOM REFS ββ
const sidebar = document.getElementById('sidebar');
const menuToggle = document.getElementById('menuToggle');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const messageList = document.getElementById('messageList');
const chatWindow = document.getElementById('chatWindow');
const welcomeScreen = document.getElementById('welcomeScreen');
const historyList = document.getElementById('chatHistory');
const currentTitle = document.getElementById('currentTitle');
let chats = JSON.parse(localStorage.getItem('nami_chats') || '[]');
let activeChatId = null;
let isLoading = false;
// ββ FILE UPLOAD ββ
let attachedFile = null;
document.getElementById('attachBtn').onclick = () => document.getElementById('fileInput').click();
document.getElementById('fileInput').addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
if (file.size > 5 * 1024 * 1024) {
alert('File too large. Max size is 5MB.');
e.target.value = '';
return;
}
attachedFile = file;
document.getElementById('fileName').textContent = file.name;
document.getElementById('fileBadge').style.display = 'flex';
});
function clearFile() {
attachedFile = null;
document.getElementById('fileInput').value = '';
document.getElementById('fileBadge').style.display = 'none';
document.getElementById('fileName').textContent = '';
}
// ββ INIT ββ
window.onload = () => {
renderHistory();
if (chats.length > 0) loadChat(chats[0].id);
};
// ββ SIDEBAR ββ
menuToggle.onclick = () => sidebar.classList.toggle('open');
document.addEventListener('click', (e) => {
if (window.innerWidth <= 768 &&
sidebar.classList.contains('open') &&
!sidebar.contains(e.target) &&
e.target !== menuToggle) {
sidebar.classList.remove('open');
}
});
// ββ INPUT ββ
userInput.addEventListener('input', function () {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 100) + 'px';
});
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
});
sendBtn.onclick = handleSendMessage;
document.getElementById('newChatBtn').onclick = newChat;
// ββ NEW CHAT ββ
function newChat() {
activeChatId = null;
messageList.innerHTML = '';
welcomeScreen.style.display = 'block';
currentTitle.innerText = 'New Chat';
sidebar.classList.remove('open');
renderHistory();
}
// ββ LOAD CHAT ββ
function loadChat(id) {
activeChatId = id;
const chat = chats.find(c => c.id === id);
if (!chat) return;
messageList.innerHTML = '';
welcomeScreen.style.display = 'none';
currentTitle.innerText = chat.title;
chat.messages.forEach(msg => appendMessageEl(msg.role, msg.text));
chatWindow.scrollTop = chatWindow.scrollHeight;
sidebar.classList.remove('open');
renderHistory();
}
// ββ DELETE CHAT ββ
function deleteChat(e, id) {
e.stopPropagation();
chats = chats.filter(c => c.id !== id);
saveChats();
if (activeChatId === id) newChat();
renderHistory();
}
// ββ RENDER HISTORY ββ
function renderHistory() {
if (chats.length === 0) {
historyList.innerHTML = `<div style="padding:12px;font-size:11px;color:var(--text-dim);text-align:center">No chats yet</div>`;
return;
}
historyList.innerHTML = chats.map(chat => `
<div class="history-item ${chat.id === activeChatId ? 'active' : ''}" onclick="loadChat(${chat.id})">
<div class="title-text">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
${escapeHtml(chat.title)}
</div>
<button class="delete-btn" onclick="deleteChat(event, ${chat.id})" title="Delete">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
</button>
</div>
`).join('');
}
// ββ SAVE ββ
function saveChats() {
localStorage.setItem('nami_chats', JSON.stringify(chats));
}
// ββ DETECT IMAGE REQUEST ββ
function isImageRequest(text) {
const lower = text.toLowerCase();
const triggers = ['generate', 'create', 'draw', 'design', 'make', 'sawwer', 'generate image', 'Ψ΅ΩΨ±', 'Ψ±Ψ³Ω
', 'Ψ΅Ω
Ω
', 'génère', 'crée', 'dessine', 'image', 'picture', 'photo', 'logo', 'illustration', 'visual'];
return triggers.some(t => lower.includes(t));
}
// ββ SEND MESSAGE ββ
async function handleSendMessage() {
const text = userInput.value.trim();
if ((!text && !attachedFile) || isLoading) return;
if (!activeChatId) {
activeChatId = Date.now();
const title = text.length > 36 ? text.slice(0, 36) + 'β¦' : (attachedFile ? attachedFile.name : 'File');
chats.unshift({ id: activeChatId, title, messages: [] });
currentTitle.innerText = title;
}
const chat = chats.find(c => c.id === activeChatId);
if (!chat) return;
userInput.value = '';
userInput.style.height = 'auto';
welcomeScreen.style.display = 'none';
isLoading = true;
sendBtn.disabled = true;
const displayText = text + (attachedFile ? `\nπ ${attachedFile.name}` : '');
chat.messages.push({ role: 'user', text: displayText });
saveChats();
appendMessageEl('user', displayText);
renderHistory();
const looksLikeImage = isImageRequest(text);
showTyping(looksLikeImage ? 'π¨ Generating image, this may take ~30s...' : null);
const timeoutMs = looksLikeImage ? 90000 : 30000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
let body, fetchHeaders = {};
if (attachedFile) {
const formData = new FormData();
formData.append('action', 'sendMessage');
formData.append('chatInput', text);
formData.append('sessionId', String(activeChatId));
formData.append('files', attachedFile);
clearFile();
body = formData;
} else {
body = JSON.stringify({ action: 'sendMessage', chatInput: text, sessionId: String(activeChatId) });
fetchHeaders = { 'Content-Type': 'application/json' };
}
const response = await fetch(PROXY_URL, {
method: 'POST',
headers: fetchHeaders,
body,
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) throw new Error(`Server error: ${response.status}`);
const data = await response.json();
// π DEBUG β open DevTools Console to see the raw response shape
console.log('[Nami] raw response:', JSON.stringify(data, null, 2));
const arr = Array.isArray(data) ? data[0] : data;
const allValues = [
arr?.output,
arr?.text,
arr?.message,
arr?.response,
arr?.chatOutput,
arr?.url,
arr?.secure_url,
arr?.imageUrl,
arr?.image_url,
arr?.result,
arr?.data?.url,
arr?.data?.secure_url,
// deep search: any string value that looks like a Cloudinary URL
...Object.values(arr || {}).filter(v => typeof v === 'string' && v.includes('cloudinary.com')),
].filter(Boolean);
const reply = allValues[0] || `β οΈ Could not parse response. Check console for raw data.\n\`\`\`\n${JSON.stringify(data, null, 2).slice(0, 400)}\n\`\`\``;
removeTyping();
chat.messages.push({ role: 'bot', text: reply });
saveChats();
appendMessageEl('bot', reply);
} catch (err) {
clearTimeout(timeoutId);
removeTyping();
let errMsg;
if (err.name === 'AbortError') {
errMsg = looksLikeImage
? `β±οΈ Image generation timed out. Please try again.`
: `β±οΈ Request timed out. Please try again.`;
} else {
errMsg = `β οΈ Could not reach Nami AI. Please try again.\n\nError: ${err.message}`;
}
chat.messages.push({ role: 'bot', text: errMsg });
saveChats();
appendMessageEl('bot', errMsg);
}
isLoading = false;
sendBtn.disabled = false;
userInput.focus();
}
// ββ BLOB TO DATA URL ββ
function blobToDataUrl(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
// ββ APPEND MESSAGE ββ
function appendMessageEl(role, text) {
const div = document.createElement('div');
div.className = `message ${role}`;
div.innerHTML = `
<div class="avatar">${role === 'bot' ? 'N' : 'You'}</div>
<div class="bubble">${formatText(text)}</div>
`;
messageList.appendChild(div);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
// ββ TYPING INDICATOR ββ
function showTyping(label) {
const div = document.createElement('div');
div.className = 'message bot';
div.id = 'typingIndicator';
div.innerHTML = `
<div class="avatar">N</div>
<div class="bubble">
${label ? `<div style="font-size:11px;color:var(--text-dim);margin-bottom:6px">${label}</div>` : ''}
<div class="typing"><span></span><span></span><span></span></div>
</div>
`;
messageList.appendChild(div);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
function removeTyping() {
const el = document.getElementById('typingIndicator');
if (el) el.remove();
}
// ββ CHIP CLICK ββ
function handleChipClick(chip) {
userInput.value = chip.querySelector('div').innerText;
handleSendMessage();
}
// ββ EXTRACT IMAGE URLS FROM TEXT ββ
function extractImageUrls(text) {
// Matches Cloudinary URLs (with or without file extension) and standard image URLs
const pattern = /https?:\/\/(?:res\.cloudinary\.com\/[^\s"'<>]+|[^\s"'<>]+\.(?:png|jpg|jpeg|gif|webp)(?:\?[^\s"'<>]*)?)/gi;
return [...text.matchAll(pattern)].map(m => ({ url: m[0], index: m.index }));
}
function renderImageTag(url) {
return `<img
src="${escapeHtml(url)}"
alt="Generated image"
style="width:100%;max-width:360px;height:auto;border-radius:14px;margin-top:10px;display:block;box-shadow:0 4px 24px rgba(0,0,0,0.4);"
onload="document.getElementById('chatWindow').scrollTop = document.getElementById('chatWindow').scrollHeight"
onerror="this.style.display='none'"
/>`;
}
// ββ FORMAT TEXT ββ
function formatText(text) {
if (typeof text !== 'string') return '';
// 1. Render base64 data URL images
if (text.startsWith('data:image/')) {
return renderImageTag(text);
}
// 2. Render raw base64 strings (JPEG / PNG)
if (text.startsWith('/9j/') || text.startsWith('iVBOR')) {
const mime = text.startsWith('/9j/') ? 'image/jpeg' : 'image/png';
return renderImageTag(`data:${mime};base64,${text}`);
}
// 3. Check for image URLs (Cloudinary or standard) anywhere in the text
const imageMatches = extractImageUrls(text);
if (imageMatches.length > 0) {
// Replace each image URL in the text with an <img> tag
let result = '';
let lastIndex = 0;
for (const { url, index } of imageMatches) {
// Add any text before the URL (markdown-rendered)
const before = text.slice(lastIndex, index);
if (before) result += renderMarkdown(before);
// Add the image tag
result += renderImageTag(url);
lastIndex = index + url.length;
}
// Add any remaining text after the last URL
const after = text.slice(lastIndex);
if (after) result += renderMarkdown(after);
return result;
}
// 4. Default: markdown-lite rendering
return renderMarkdown(text);
}
// ββ MARKDOWN-LITE RENDERER ββ
function renderMarkdown(text) {
return escapeHtml(text)
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code style="background:rgba(255,255,255,0.08);padding:1px 5px;border-radius:4px;font-size:12px">$1</code>')
.replace(/\n/g, '<br>');
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}