-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscript.v2.03.js
460 lines (384 loc) · 19 KB
/
script.v2.03.js
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
var chatContainer;
var printChatTitle;
var searchingIndicator;
var chatTitlesContainer;
var popup;
function waitForImagesToLoad(container, callback) {
const images = container.find('img');
let remaining = images.length;
if (remaining === 0) {
callback(); // No images to wait for
return;
}
images.each(function () {
if (this.complete) {
// Image is already loaded (cached)
remaining--;
if (remaining === 0) callback();
} else {
// Wait for the image to load
$(this).on('load error', function () {
remaining--;
if (remaining === 0) callback();
});
}
});
}
let scrollTimeout;
function debounceScroll() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(scrollToBottom, 100); // Adjust as needed
}
function scrollToBottom() {
chatContainer.scrollTop(chatContainer.prop("scrollHeight"));
}
$(document).ready(function() {
searchingIndicator = document.getElementById('searching-indicator');
chatTitlesContainer = document.querySelector('.chat-titles-container');
updatePlaceholder(); // update the placeholder text in the message window
// Run on page load
adjustChatTitlesHeight();
// Display all the chat titles
fetchAndUpdateChatTitles(search_term,0);
chatContainer = $(".chat-container");
var userMessage = $("#userMessage");
// Set focus on the message input
userMessage.focus();
// Initially load messages
loadMessages();
// Event listener for the Enter key press
userMessage.on("keydown", function (e) {
if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
$('#messageForm').submit();
}
});
$(document).on('click', '.edit-confirm-icon', function () {
var chatId = $(this).parent().prev().attr('id').split('-')[2];
submitEdit(chatId);
});
// Event listener for form submission
$('#messageForm').submit(function(e) {
e.preventDefault();
var rawMessageContent = userMessage.val().trim();
var sanitizedMessageContent = replaceNonAsciiCharacters(rawMessageContent);
// Optionally, show a warning if the message was modified
if (sanitizedMessageContent !== rawMessageContent) {
if (!confirm("Your message contains some special characters that might cause issues. Click OK to send the modified message or Cancel to edit your message.")) {
return;
}
}
var messageContent = base64EncodeUnicode(sanitizedMessageContent); // Encode in Base64 UTF-8
// Display the user message (prompt) immediately after submission
if (sanitizedMessageContent !== "") {
var userMessageDecoded = base64DecodeUnicode(messageContent);
var sanitizedPrompt = formatCodeBlocks(userMessageDecoded);
var userMessageElement = $('<div class="message user-message"></div>').html(sanitizedPrompt);
userMessageElement.prepend('<img src="images/user.png" class="user-icon" alt="User icon">');
chatContainer.append(userMessageElement);
// Apply syntax highlighting to code within the user message
userMessageElement.find('pre code').each(function(i, block) {
hljs.highlightElement(block);
});
// Apply MathJax typesetting to the user message
if (window.MathJax) {
MathJax.typesetPromise([userMessageElement[0]]).then(function () {
debounceScroll();
}).catch(function(err) {
console.error("MathJax typeset failed: " + err.message);
debounceScroll();
});
} else {
debounceScroll();
}
// Scroll to the bottom of the chat container
// (debounceScroll is already called in the MathJax success/error handlers)
// Clear the textarea and localStorage right after form submission
userMessage.val("");
localStorage.removeItem('chatDraft_' + chatId);
}
if (messageContent !== "") {
// **Retrieve the selected deployment (model)**
var deployment = $('#model_select select[name="model"]').val();
$.ajax({
type: "POST",
url: "ajax_handler.php",
data: {
message: messageContent,
chat_id: chatId,
user: user,
deployment: deployment // **Include the deployment here**
},
beforeSend: function() {
$('.waiting-indicator').show();
},
error: function() {
$('.waiting-indicator').hide();
},
success: function(response) {
$('.waiting-indicator').hide();
var jsonResponse = JSON.parse(response);
var eid = jsonResponse['eid']; // The Exchange record ID
var gpt_response = jsonResponse['gpt_response'];
var image_gen_name = jsonResponse['image_gen_name']; // Filename for the generated image
var deployment = jsonResponse['deployment'];
var error = jsonResponse['error'];
if (error) {
alert('Error: ' + gpt_response);
return;
}
var assistantMessageElement = $('<div class="message assistant-message" style="margin-bottom: 30px;"></div>');
// Prepend the assistant's icon
var imgSrc = 'images/' + deployments[deployment].image;
var imgAlt = deployments[deployment].image_alt;
assistantMessageElement.prepend('<img src="' + imgSrc + '" alt="' + imgAlt + '" class="openai-icon">');
// If an image was generated
if (image_gen_name) {
var imgElement = $('<img>')
.attr('class', 'image-message')
.attr('src', './image_gen/small/' + image_gen_name)
.attr('alt', 'Generated Image')
.on('load', function () {
// Scroll to the bottom only after the image is loaded
debounceScroll();
});
assistantMessageElement.append(imgElement);
// Add the download button for the full-size image
addDownloadButton(assistantMessageElement, './image_gen/fullsize/' + image_gen_name);
// Otherwise, display text
} else if (gpt_response) {
// Display the text response
gpt_response = formatCodeBlocks(gpt_response);
assistantMessageElement.append('<span>' + gpt_response + '</span>');
addCopyButton(assistantMessageElement, gpt_response); // Add copy button for text
}
// Append the message to the chat container
chatContainer.append(assistantMessageElement);
// Update chat titles
fetchAndUpdateChatTitles(search_term,0);
// Syntax highlighting + MathJax
if (!image_gen_name) {
// First highlight code
hljs.highlightAll();
// Then typeset the math in the newly added message
if (window.MathJax) {
MathJax.typesetPromise([assistantMessageElement[0]]).then(function () {
debounceScroll();
}).catch(function(err) {
console.error("MathJax typeset failed: " + err.message);
debounceScroll();
});
} else {
debounceScroll();
}
}
}
});
}
});
// Function to add the download button
function addDownloadButton(messageElement, fullImagePath) {
// Create the download button
var downloadButton = $(`
<button class="copy-chat-button" title="Download Full Image" aria-label="Download the full image">
<span style="font-size:12px;">Download Full Image</span>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<title>cloud-download</title>
<path d="M12.75 20.379v-10.573h-1.5v10.573l-2.432-2.432-1.061 1.061 4.243 4.243 4.243-4.243-1.061-1.061-2.432 2.432z"></path>
<path d="M18.75 7.555c0-3.722-3.028-6.75-6.75-6.75s-6.75 3.028-6.75 6.75c-2.485 0-4.5 2.015-4.5 4.5s2.015 4.5 4.5 4.5h3.75v-1.5h-3.75c-1.657 0-3-1.343-3-3s1.343-3 3-3v0h1.5v-1.5c0-2.899 2.351-5.25 5.25-5.25s5.25 2.351 5.25 5.25v0 1.5h1.5c1.657 0 3 1.343 3 3s-1.343 3-3 3v0h-3.75v1.5h3.75c2.485 0 4.5-2.015 4.5-4.5s-2.015-4.5-4.5-4.5v0z"></path>
</svg>
</button>
`);
// Append the button to the message element
messageElement.append(downloadButton);
// Set up the click handler to download the full-size image
downloadButton.on('click', function() {
var link = document.createElement('a');
link.href = fullImagePath;
link.download = 'GeneratedImage.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
// Copy button for text
function addCopyButton(messageElement, rawMessageContent) {
// Create the copy button without the onclick attribute
var copyButton = $(`
<button class="copy-chat-button" title="Copy Raw Reply" aria-label="Copy the current reply to clipboard">
<span style="font-size:12px;">Copy Raw Reply</span>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path>
</svg>
</button>
`);
// Append the copy button to the message element
messageElement.append(copyButton);
// Set the position of the message element to relative
messageElement.css('position', 'relative');
// Copy the raw content to clipboard on click
copyButton.on('click', function() {
// Use the rawMessageContent directly
navigator.clipboard.writeText(rawMessageContent).then(function() {
// Create a subtle popup message
var popup = $('<span class="copied-chat-popup show">Copied!</span>');
popup.css({
position: 'absolute',
top: copyButton.position().top + 4, // Adjust this value as needed
left: copyButton.position().left + 150,
});
// Append the popup to the message element
messageElement.append(popup);
// Remove the popup after 2 seconds
setTimeout(function() {
popup.remove();
}, 2000);
}, function(err) {
console.error('Could not copy text: ', err);
});
});
}
// Load old messages
function loadMessages() {
$.ajax({
url: "get_messages.php",
data: { chat_id: chatId, user: user },
dataType: 'json',
success: function(chatMessages) {
displayMessages(chatMessages);
//scrollToBottom();
debounceScroll();
}
});
}
// Show older chat messages
function displayMessages(chatMessages) {
chatMessages.forEach(function (message) {
//------------------------------------------------
// 1) USER PROMPT
//------------------------------------------------
// Apply formatCodeBlocks to the user's prompt
var sanitizedPrompt = formatCodeBlocks(message.prompt);
var userMessageElement = $('<div class="message user-message"></div>').html(sanitizedPrompt);
userMessageElement.prepend('<img src="images/user.png" class="user-icon">');
chatContainer.append(userMessageElement);
//------------------------------------------------
// 2) ASSISTANT REPLY
//------------------------------------------------
var assistantMessageElement = null;
if (message.deployment && deployments[message.deployment]) {
assistantMessageElement = $('<div class="message assistant-message"></div>');
// Prepend the assistant's icon
var imgSrc = 'images/' + deployments[message.deployment].image;
var imgAlt = deployments[message.deployment].image_alt;
assistantMessageElement.prepend('<img src="' + imgSrc + '" alt="' + imgAlt + '" class="openai-icon">');
chatContainer.append(assistantMessageElement);
// If there's a text reply, handle it
if (message.reply) {
var sanitizedReply = formatCodeBlocks(message.reply);
assistantMessageElement.append(sanitizedReply);
addCopyButton(assistantMessageElement, message.reply);
}
}
//------------------------------------------------
// 3) HANDLE GENERATED IMAGE (IF PRESENT)
//------------------------------------------------
if (message.image_gen_name) {
var genImg = $('<img>')
.attr('class', 'image-message')
.attr('src', './image_gen/small/' + message.image_gen_name)
.attr('alt', 'Generated Image')
.on('load', function () {
//scrollToBottom(); // Scroll after the image loads
debounceScroll();
});
if (assistantMessageElement) {
assistantMessageElement.append(genImg);
addDownloadButton(assistantMessageElement, './image_gen/fullsize/' + message.image_gen_name);
} else {
var imageContainer = $('<div class="message assistant-message"></div>');
imageContainer.append(genImg);
addDownloadButton(imageContainer, './image_gen/fullsize/' + message.image_gen_name);
chatContainer.append(imageContainer);
}
}
//------------------------------------------------
// 4) DOCUMENTS (USER OR ASSISTANT UPLOADED)
//------------------------------------------------
if (message.document_name && message.document_text && /^image\//.test(message.document_type)) {
var docImg = $('<img>')
.attr('class', 'image-message')
.attr('src', message.document_text)
.attr('alt', message.document_name || '');
if (message.document_source === 'assistant' && assistantMessageElement) {
assistantMessageElement.append(docImg);
addDownloadButton(assistantMessageElement, message.document_text);
} else if (message.document_source === 'user') {
userMessageElement.append(docImg);
}
}
});
// After appending all messages, do syntax highlighting and MathJax
hljs.highlightAll();
if (window.MathJax) {
MathJax.typesetPromise([chatContainer[0]]).then(function() {
debounceScroll();
}).catch(function(err) {
console.error("MathJax typeset failed: " + err.message);
debounceScroll();
});
} else {
debounceScroll();
}
}
// Identify and format code blocks with triple backticks
function formatCodeBlocks(reply) {
// 2) Hacky filter to replace `\left[ ... \right]` with `\left. ... \right|`
// so that MathJax doesn’t choke on sub/superscripts after square brackets:
reply = reply.replace(/\\left\s*\[/g, '\\left.');
reply = reply.replace(/\\right\s*\]/g, '\\right|');
reply = reply.replace(/E\[(.*?)\]/g, 'E($1)');
// Ensure LaTeX is preserved before other processing
reply = reply.replace(/\\\[([^\]]+)\\\]/g, function(match, latex) {
return `<div class="math-block">$$ ${latex} $$</div>`;
});
reply = reply.replace(/\\\(([^)]+)\\\)/g, function(match, latex) {
return `<span class="math-inline">$ ${latex} $</span>`;
});
// Rest of your existing formatCodeBlocks logic
let codeBlocks = [];
// Extract and replace code blocks with placeholders
reply = reply.replace(/```(\w*)\n([\s\S]*?)```/g, function(match, lang, code) {
// If language is specified, use it; otherwise default to plaintext
var languageClass = lang ? `language-${lang}` : 'plaintext';
// Escape the code content before inserting it
const sanitizedCode = sanitizeString(code);
// Save the code block in an array
codeBlocks.push(`
<div class="code-block">
<div class="language-label">${lang || 'code'}</div>
<button class="copy-button" title="Copy Code" aria-label="Copy code to clipboard" onclick="copyToClipboard(this)">
<span style="font-size:12px;">Copy Code</span>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path>
</svg>
</button>
<pre><code class="${languageClass}">${sanitizedCode}</code></pre>
</div>`);
// Return a placeholder to be replaced later
return `__CODE_BLOCK_${codeBlocks.length - 1}__`;
});
// Convert to HTML, but carefully
reply = marked.parse(reply, {
// Prevent escaped characters from being converted
sanitize: false,
// Preserve HTML-like syntax
breaks: false
});
// Replace placeholders with actual code block HTML
codeBlocks.forEach((block, index) => {
reply = reply.replace(`<strong>CODE_BLOCK_${index}</strong>`, block);
});
return reply;
}
});