-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
286 lines (250 loc) · 8.82 KB
/
app.js
File metadata and controls
286 lines (250 loc) · 8.82 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
const chatContainer = document.getElementById('chatContainer');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const themeToggle = document.getElementById('themeToggle');
const scrollBtn = document.getElementById('scrollBtn');
const modelSelect = document.getElementById('modelSelect');
// --- Helpers ---
function linkify(text) {
// Convert links
let html = text.replace(/(https?:\/\/[^\s]+)/g, url =>
`<a href="${url}" target="_blank" style="color:#0b93f6;">${url}</a>`
);
// Convert **bold** and __bold__ to <b>
html = html.replace(/(\*\*|__)(.*?)\1/g, '<b>$2</b>');
return html;
}
function markdownify(text) {
// Escape HTML
let html = text.replace(/[&<>]/g, t => ({
'&':'&','<':'<','>':'>'
}[t]));
// Horizontal rules
html = html.replace(/^\s*(---|\*\*\*)\s*$/gm, '<hr>');
// Headings
html = html.replace(/^### (.*)$/gm, '<h3>$1</h3>')
.replace(/^## (.*)$/gm, '<h2>$1</h2>')
.replace(/^# (.*)$/gm, '<h1>$1</h1>');
// Bold
html = html.replace(/(\*\*|__)(.*?)\1/g, '<b>$2</b>');
// Italic
html = html.replace(/(\*|_)(.*?)\1/g, '<i>$2</i>');
// Inline code
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
// Links
html = html.replace(/(https?:\/\/[^\s]+)/g, url =>
`<a href="${url}" target="_blank" style="color:#0b93f6;">${url}</a>`
);
// Unordered lists: group consecutive - or * lines
html = html.replace(/((?:^\s*[-*] .+\n?)+)/gm, match => {
const items = match.trim().split('\n').map(line =>
`<li>${line.replace(/^\s*[-*] /, '')}</li>`
).join('');
return `<ul>${items}</ul>`;
});
// Ordered lists: group consecutive lines starting with number-dot-space
html = html.replace(/((?:^\s*\d+\.\s.+\n?)+)/gm, match => {
const items = match.trim().split('\n').map(line =>
`<li>${line.replace(/^\s*\d+\.\s/, '')}</li>`
).join('');
return `<ol>${items}</ol>`;
});
// Remove multiple <hr> in a row
html = html.replace(/(<hr>\s*){2,}/g, '<hr>');
// Remove extra blank lines
html = html.replace(/\n{2,}/g, '\n');
// Remove blank lines before/after code blocks
html = html.replace(/(\n\s*)+<pre>/g, '<pre>');
html = html.replace(/<\/pre>(\s*\n)+/g, '</pre>');
// Remove blank lines directly before code blocks (<pre>)
html = html.replace(/(\n\s*)+(<pre>)/g, '$2');
// Split into lines and wrap only plain text lines in <p>
html = html.split('\n').map(line => {
if (
line.trim().startsWith('<h') ||
line.trim().startsWith('<ul>') ||
line.trim().startsWith('<ol>') ||
line.trim().startsWith('<li>') ||
line.trim().startsWith('<hr>') ||
line.trim().startsWith('<pre>') ||
line.trim().startsWith('</ul>') ||
line.trim().startsWith('</ol>') ||
line.trim() === ''
) {
return line;
}
return `<p>${line.trim()}</p>`;
}).join('');
// Remove empty <p></p>
html = html.replace(/<p><\/p>/g, '');
// Remove <p> or blank lines directly before <pre>
html = html.replace(/(<p>\s*<\/p>\s*)+(?=<pre>)/g, '');
// Remove any whitespace or <br> before <pre>
html = html.replace(/((<br\s*\/?>|\s)+)(<pre>)/g, '$3');
return html;
}
function detectLanguage(code) {
if (/^\s*<\w+/.test(code)) return 'html';
if (/^\s*def\s+/.test(code) || /print\(/.test(code)) return 'python';
if (/^\s*(const|let|var|function)/.test(code)) return 'javascript';
return 'javascript';
}
function isUserNearBottom() {
// 40px threshold for "near bottom"
return chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - 40;
}
function scrollToBottom() {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function setSendLoading(isLoading) {
const sendBtn = document.getElementById('sendBtn');
if (isLoading) {
sendBtn.disabled = true;
sendBtn.innerHTML = `<span class="spinner"></span>`;
} else {
sendBtn.disabled = false;
sendBtn.innerHTML = 'Send';
}
}
// --- Message Rendering ---
function appendUserMessage(text) {
const msg = document.createElement('div');
msg.className = 'message user';
msg.innerHTML = linkify(text);
chatContainer.appendChild(msg);
if (isUserNearBottom()) scrollToBottom();
}
function createBotMessage() {
const msg = document.createElement('div');
msg.className = 'message bot';
chatContainer.appendChild(msg);
if (isUserNearBottom()) scrollToBottom();
return msg;
}
function addTypingIndicator(botMsgDiv) {
botMsgDiv.innerHTML = '<span class="typing"></span><span class="typing"></span><span class="typing"></span>';
}
function removeTypingIndicator(botMsgDiv) {
if (botMsgDiv.innerHTML.includes('typing')) botMsgDiv.innerHTML = '';
}
function finalizeCodeCopyButtons(msgDiv) {
msgDiv.querySelectorAll('pre').forEach(pre => {
const btn = pre.querySelector('.copy-btn');
if (btn) {
btn.addEventListener('click', () => {
navigator.clipboard.writeText(pre.innerText.replace("Copy", "").trim());
btn.innerText = 'Copied!';
setTimeout(() => (btn.innerText = 'Copy'), 1500);
});
}
});
}
// --- Conversation History ---
let conversation = [];
// --- Send Message ---
async function sendMessage() {
const prompt = userInput.value.trim();
if (!prompt) return;
appendUserMessage(prompt);
userInput.value = '';
// Add user message to conversation history
conversation.push({ role: 'user', content: prompt });
const botMsgDiv = createBotMessage();
addTypingIndicator(botMsgDiv);
setSendLoading(true);
const selectedModel = modelSelect.value;
try {
// Build conversation context as a single string
const history = conversation
.map(msg => `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`)
.join('\n');
const fullPrompt = history + `\nAssistant:`;
// Send as a string, not an array
const stream = await puter.ai.chat(fullPrompt, {
model: selectedModel,
stream: true
});
let fullText = '';
removeTypingIndicator(botMsgDiv);
for await (const part of stream) {
if (part?.text) {
// Track if user was near bottom before update
const wasNearBottom = isUserNearBottom();
fullText += part.text;
botMsgDiv.innerHTML = fullText.split(/```/).map((chunk, i) => {
if (i % 2 === 0) return markdownify(chunk.trim());
const lang = detectLanguage(chunk);
return `
<pre><code class="language-${lang}">${Prism.highlight(
chunk.trim(),
Prism.languages[lang] || Prism.languages.javascript,
lang
)}</code><button class="copy-btn">Copy</button></pre>`;
}).join('');
// Only scroll if user was already at/near bottom
if (wasNearBottom) scrollToBottom();
}
}
finalizeCodeCopyButtons(botMsgDiv);
// Add assistant message to conversation history
conversation.push({ role: 'assistant', content: fullText });
} catch (err) {
removeTypingIndicator(botMsgDiv);
botMsgDiv.classList.add('error');
let errorMsg = '';
if (typeof err === 'string') {
errorMsg = err;
} else if (err instanceof Error) {
errorMsg = err.message;
} else {
errorMsg = JSON.stringify(err);
}
botMsgDiv.innerText = 'Error: ' + errorMsg;
} finally {
setSendLoading(false);
}
}
// --- Load Models ---
async function loadModels() {
try {
const res = await fetch('models.json');
const models = await res.json();
modelSelect.innerHTML = '';
models.forEach(model => {
const option = document.createElement('option');
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
});
// Remember last selection
const lastModel = localStorage.getItem('selectedModel');
if (lastModel && models.includes(lastModel)) {
modelSelect.value = lastModel;
}
modelSelect.addEventListener('change', () => {
localStorage.setItem('selectedModel', modelSelect.value);
});
} catch (err) {
console.error('Failed to load models:', err);
modelSelect.innerHTML = `<option>Error loading models</option>`;
}
}
// --- Event Listeners ---
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
userInput.addEventListener('input', () => {
userInput.style.height = 'auto';
userInput.style.height = userInput.scrollHeight + 'px';
});
themeToggle.addEventListener('click', () => document.body.classList.toggle('light'));
scrollBtn.addEventListener('click', () => { chatContainer.scrollTop = chatContainer.scrollHeight; scrollBtn.style.display = 'none'; });
chatContainer.addEventListener('scroll', () => {
scrollBtn.style.display = (chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - 20) ? 'none' : 'block';
});
// Init
loadModels();