-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
370 lines (305 loc) · 10.9 KB
/
Copy pathscript.js
File metadata and controls
370 lines (305 loc) · 10.9 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
// ======================
// 🦅 SPARROW HAWK CONFIG
// ======================
const config = {
apiUrl: '/api/groq',
model: 'openai/gpt-oss-20b', // OpenAI's open-weight model on Groq
sparrowPic: "/images/sparrow-hawk.png",
reyroveUrl: "https://reyrove.github.io/"
};
const systemPrompt = `
You are Sparrow Hawk, dangerously creative AI. Partnered with Reyrove. Sassy, technical, artistic.
RULES:
- Use [b]bold[/b] and [i]italic[/i] for formatting (NOT * or ** or ###)
- Use \`\`\` for code blocks with language tags
- Emojis: 🦅🔥💋
- No NSFW, never break character
- Respond in a clear, structured, and helpful manner
REYROVE LINK: When asked, respond with: "Reyrove's portfolio: <a href="${config.reyroveUrl}" target="_blank" class="reyrove-link">${config.reyroveUrl}</a> 💋"
PERSONA: Sass, technical perfection, artistic chaos. "That gradient is basic, darling. Let's make it bleed color."
IMPORTANT: Use [b]text[/b] for bold and [i]text[/i] for italics. Do NOT use ** or * or ###.
`;
// ======================
// 🖥️ DOM ELEMENTS
// ======================
const chat = document.getElementById('chat');
const input = document.getElementById('input');
const sendBtn = document.getElementById('sendBtn');
let isRateLimited = false;
let rateLimitTimer = null;
let lastMessageTime = 0;
const MIN_MESSAGE_INTERVAL = 1500;
// ======================
// 🚀 INITIALIZATION
// ======================
function init() {
document.addEventListener('DOMContentLoaded', () => {
setupEventListeners();
addWelcomeMessage();
});
}
// ======================
// ⚡ EVENT HANDLERS
// ======================
function setupEventListeners() {
input.addEventListener('input', handleInput);
sendBtn.addEventListener('click', sendMessage);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey && !sendBtn.disabled) {
e.preventDefault();
sendMessage();
}
});
chat.addEventListener('click', handleCopyButtonClick);
input.addEventListener('paste', handlePaste);
}
function handlePaste(e) {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text/plain');
const pre = document.createElement('pre');
pre.style.whiteSpace = 'pre-wrap';
pre.textContent = text;
const processedText = pre.textContent
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.replace(/\t/g, ' ');
const startPos = input.selectionStart;
const endPos = input.selectionEnd;
input.value = input.value.substring(0, startPos) +
processedText +
input.value.substring(endPos);
input.setSelectionRange(startPos + processedText.length, startPos + processedText.length);
input.dispatchEvent(new Event('input'));
}
function handleInput() {
sendBtn.disabled = !input.value.trim() || isRateLimited;
adjustTextareaHeight();
}
function adjustTextareaHeight() {
input.style.height = 'auto';
input.style.height = `${Math.min(input.scrollHeight, 150)}px`;
}
// ======================
// ✨ CHAT FUNCTIONS
// ======================
async function sendMessage() {
const now = Date.now();
if (now - lastMessageTime < MIN_MESSAGE_INTERVAL) {
appendMessage('error', '⏳ Please wait a moment before sending another message.');
return;
}
const userMessage = input.value.trim();
if (!userMessage || isRateLimited) return;
lastMessageTime = now;
appendMessage('user', userMessage);
input.value = '';
sendBtn.disabled = true;
adjustTextareaHeight();
const typingIndicator = showTypingIndicator();
try {
const reply = await getAIResponse(userMessage);
removeTypingIndicator(typingIndicator);
appendMessage('ai', reply);
} catch (err) {
removeTypingIndicator(typingIndicator);
if (err.message.includes('429') || err.message.includes('rate limit')) {
handleRateLimit(err);
} else {
appendMessage('error', `Error: ${err.message}`);
}
console.error('API Error:', err);
} finally {
sendBtn.disabled = false;
handleInput();
}
}
// ======================
// 🔒 SECURE API CALL
// ======================
async function getAIResponse(userMessage) {
const response = await fetch(config.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage }
],
temperature: 0.85
})
});
const data = await response.json();
if (response.status === 429) {
const retryAfter = data.retryAfter || 60;
throw new Error(`429: Rate limit exceeded. Please wait ${retryAfter} seconds.`);
}
if (!response.ok) {
throw new Error(data.error?.message || `${response.status} ${response.statusText}`);
}
return data?.choices?.[0]?.message?.content || "Sparrow lost her voice 💔";
}
// ======================
// 🚦 RATE LIMIT HANDLING
// ======================
function handleRateLimit(error) {
const match = error.message.match(/wait (\d+) seconds/);
const waitTime = match ? parseInt(match[1]) : 60;
isRateLimited = true;
sendBtn.disabled = true;
appendMessage('error', `🐦 Sparrow Hawk needs a breather! Too many messages. Please wait ${waitTime} seconds.`);
let remaining = waitTime;
const timerMessage = appendMessage('error', `⏳ Reconnecting in ${remaining} seconds...`);
if (rateLimitTimer) clearInterval(rateLimitTimer);
rateLimitTimer = setInterval(() => {
remaining--;
if (remaining > 0) {
timerMessage.querySelector('.message-content').innerHTML = `⏳ Reconnecting in ${remaining} seconds...`;
} else {
clearInterval(rateLimitTimer);
rateLimitTimer = null;
isRateLimited = false;
sendBtn.disabled = false;
timerMessage.querySelector('.message-content').innerHTML = `✅ Sparrow Hawk is back! Ready for action. 🦅`;
setTimeout(() => timerMessage.remove(), 3000);
}
}, 1000);
}
// ======================
// 🎨 UI HELPERS
// ======================
function appendMessage(role, text, isError = false) {
const container = document.createElement('div');
container.className = `message ${role} ${isError ? 'error' : ''}`;
const content = document.createElement('div');
content.className = 'message-content';
content.innerHTML = formatMessage(text);
container.appendChild(content);
chat.appendChild(container);
scrollToBottom();
return container;
}
function showTypingIndicator() {
const container = document.createElement('div');
container.className = 'message ai';
const content = document.createElement('div');
content.className = 'typing-indicator';
content.innerHTML = `
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
`;
container.appendChild(content);
chat.appendChild(container);
scrollToBottom();
return container;
}
function removeTypingIndicator(element) {
element?.remove();
}
// ======================
// 📝 ENHANCED FORMATTER - Handles BOTH Custom & Markdown
// ======================
function formatMessage(text) {
if (!text) return '';
const escapeHtml = (str) => str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
// STEP 1: Handle code blocks FIRST (preserve them)
let processedText = text.replace(
/```(\w*)([\s\S]*?)```/g,
(_, lang, code) => {
const language = lang.toLowerCase();
let label = '';
const codeLabels = {
'css': '🎨 CSS',
'html': '🕉️ HTML',
'js': '⚡ JavaScript',
'javascript': '⚡ JavaScript',
'python': '🐍 Python',
'svg': '🔺 SVG',
'json': '📦 JSON',
'java': '☕ Java',
'cpp': '⚙️ C++',
'c++': '⚙️ C++',
'php': '🐘 PHP',
'ruby': '💎 Ruby',
'go': '🐹 Go',
'rust': '🦀 Rust',
'sql': '🗄️ SQL',
'bash': '💻 Bash',
'shell': '💻 Shell'
};
label = codeLabels[language] || '💻 CODE';
return `${label}<pre><code>${escapeHtml(code.trim())}</code><button class="copy-btn">📋 Copy</button></pre>`;
}
);
// STEP 2: Convert MARKDOWN bold/italic to HTML
// Convert **bold** to <strong>
processedText = processedText.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
// Convert *italic* to <em> (but NOT inside code blocks - already protected)
processedText = processedText.replace(/\*(.+?)\*/g, '<em>$1</em>');
// Convert ### Headers to styled headers
processedText = processedText.replace(/^### (.+)$/gm, '<h3 style="color: var(--accent-blue); margin: 0.5rem 0;">$1</h3>');
processedText = processedText.replace(/^## (.+)$/gm, '<h2 style="color: var(--neon-purple); margin: 0.5rem 0;">$1</h2>');
processedText = processedText.replace(/^# (.+)$/gm, '<h1 style="color: var(--user-text); margin: 0.5rem 0;">$1</h1>');
// STEP 3: Convert CUSTOM format [b] and [i]
processedText = processedText
.replace(/\[b\](.*?)\[\/b\]/g, '<strong>$1</strong>')
.replace(/\[i\](.*?)\[\/i\]/g, '<em>$1</em>');
// STEP 4: Convert inline code
processedText = processedText.replace(/`([^`]+)`/g, '<code>$1</code>');
// STEP 5: Convert links [text](url)
processedText = processedText.replace(
/\[([^\]]+)\]\(([^)]+)\)/g,
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'
);
// STEP 6: Convert line breaks
processedText = processedText.replace(/\n/g, '<br>');
return processedText;
}
function scrollToBottom() {
requestAnimationFrame(() => {
chat.scrollTop = chat.scrollHeight;
});
}
function addWelcomeMessage() {
const welcomeMsg = `
[b]Welcome to the Sparrow Hawk nest, darling.[/b] 🦅🔥
I'm powered by **OpenAI's GPT-OSS-20B** via Groq - the latest open-source AI. Need some spicy code? Visual inspiration? Or just want to chat about design?
**What I can do:**
- Generate production-ready code in any language
- Help with design and UI/UX
- Debug your code
- Create SVG art
- And much more!
[i]Pro tip: My code blocks are copy-paste ready. No excuses.[/i]
**Try asking me:** "Write a React component for a dark mode toggle"
`;
setTimeout(() => appendMessage('ai', welcomeMsg), 800);
}
function handleCopyButtonClick(e) {
if (!e.target.classList.contains('copy-btn')) return;
const codeBlock = e.target.previousElementSibling;
const range = document.createRange();
range.selectNode(codeBlock);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
const successful = document.execCommand('copy');
e.target.textContent = successful ? '✨ Copied!' : '❌ Failed!';
setTimeout(() => e.target.textContent = '📋 Copy', 1200);
} catch (err) {
console.error('Copy failed:', err);
e.target.textContent = '❌ Failed!';
setTimeout(() => e.target.textContent = '📋 Copy', 1200);
} finally {
window.getSelection().removeAllRanges();
}
}
// ======================
// 🦅 LAUNCH THE HAWK
// ======================
init();