-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
937 lines (782 loc) · 37.2 KB
/
Copy pathscript.js
File metadata and controls
937 lines (782 loc) · 37.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
'use strict';
// Wait for DOM to load
window.onload = function() {
// Add passive event listeners to improve performance
document.addEventListener('touchstart', function(){}, {passive: true});
document.addEventListener('touchmove', function(){}, {passive: true});
document.addEventListener('wheel', function(){}, {passive: true});
document.addEventListener('mousewheel', function(){}, {passive: true});
window.addEventListener('load', refreshAllEditors);
// LLM API Configuration
let apiConfig = {
endpoint: localStorage.getItem('apiEndpoint') || '',
apiKey: localStorage.getItem('apiKey') || '',
model: localStorage.getItem('modelName') || 'gpt-3.5-turbo',
autoApply: localStorage.getItem('autoApply') === 'true' || false,
includeCodeContext: localStorage.getItem('includeCodeContext') !== 'false' // Default true
};
// Initialize flag for API ready state
let isApiConfigured = !!(apiConfig.endpoint && apiConfig.apiKey && apiConfig.model);
// Undo/Redo history tracking
const editorHistory = {
html: { undoStack: [], redoStack: [], currentState: null },
css: { undoStack: [], redoStack: [], currentState: null },
js: { undoStack: [], redoStack: [], currentState: null }
};
// Maximum history size to prevent memory issues
const MAX_HISTORY_SIZE = 50;
// Initial editor values for reset functionality
const INITIAL_HTML = "<!DOCTYPE html>\n<html>\n<head>\n <title>My Page</title>\n</head>\n<body>\n <h1>Hello World</h1>\n <p>Start coding here...</p>\n</body>\n</html>";
const INITIAL_CSS = "body {\n font-family: Arial, sans-serif;\n margin: 20px;\n}\n\nh1 {\n color: #333;\n}";
const INITIAL_JS = "console.log('Page loaded!');";
// Set up elements for easy access
const sendButton = document.getElementById("sendButton");
const chatInput = document.getElementById("chatInput");
const messagesContainer = document.getElementById("messages");
// Enable or disable chat based on API configuration
function updateChatAvailability() {
const apiKeyInvalid = localStorage.getItem('apiKeyInvalid') === 'true';
isApiConfigured = !!(apiConfig.endpoint && apiConfig.apiKey && apiConfig.model); // Re-evaluate
messagesContainer.innerHTML = ''; // Clear previous messages
if (apiKeyInvalid) {
addSystemMessage("There might be an issue with your API key or endpoint. Please verify your settings and save the configuration again.");
sendButton.disabled = true;
} else if (!isApiConfigured) {
addSystemMessage("Please configure the API settings to start chatting with the LLM.");
sendButton.disabled = true;
} else {
addMessage("Hello! I'm here to help you with your code. What would you like to work on today?", false);
sendButton.disabled = false;
}
}
// Call initially to set correct state
updateChatAvailability();
// Initialize editors
const htmlEditor = CodeMirror(document.getElementById("htmlEditor"), {
mode: "htmlmixed",
theme: "dracula",
lineNumbers: true,
lineWrapping: false,
scrollbarStyle: "native",
viewportMargin: Infinity,
value: INITIAL_HTML
});
const cssEditor = CodeMirror(document.getElementById("cssEditor"), {
mode: "css",
theme: "dracula",
lineNumbers: true,
lineWrapping: false,
scrollbarStyle: "native",
viewportMargin: Infinity,
value: INITIAL_CSS
});
const jsEditor = CodeMirror(document.getElementById("jsEditor"), {
mode: "javascript",
theme: "dracula",
lineNumbers: true,
lineWrapping: false,
scrollbarStyle: "native",
viewportMargin: Infinity,
value: INITIAL_JS
});
// Initialize editor history with current values
editorHistory.html.currentState = htmlEditor.getValue();
editorHistory.css.currentState = cssEditor.getValue();
editorHistory.js.currentState = jsEditor.getValue();
// Tab switching
document.getElementById("htmlTab").onclick = function() {
setActiveTab("html");
};
document.getElementById("cssTab").onclick = function() {
setActiveTab("css");
};
document.getElementById("jsTab").onclick = function() {
setActiveTab("js");
};
function setActiveTab(tabName) {
// Update tab styles
const tabs = document.querySelectorAll(".tab");
for (let i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
}
document.getElementById(tabName + "Tab").classList.add("active");
// Show correct editor
const panes = document.querySelectorAll(".editor-pane");
for (let i = 0; i < panes.length; i++) {
panes[i].classList.remove("active");
}
document.getElementById(tabName + "Editor").classList.add("active");
// Add a small delay before refreshing the editor for more reliable results
setTimeout(function() {
if (tabName === "html") htmlEditor.refresh();
if (tabName === "css") cssEditor.refresh();
if (tabName === "js") jsEditor.refresh();
// Update undo/redo button states when switching tabs
updateUndoRedoButtons();
}, 50);
}
// Function to create combined HTML
function createCombinedHTML() {
const htmlContent = htmlEditor.getValue();
const cssContent = cssEditor.getValue();
const jsContent = jsEditor.getValue();
// Create combined HTML with string concatenation
const step1 = htmlContent.replace("</head>", "<style>\n" + cssContent + "\n</style>\n</head>");
const combined = step1.replace("</body>", "<script>\n" + jsContent + "\n<\/script>\n</body>");
return combined;
}
// Preview handling
document.getElementById("renderButton").onclick = function() {
const combined = createCombinedHTML();
// Show modal first
document.getElementById("previewModal").style.display = "block";
// Get the iframe and set proper content
const iframe = document.getElementById("previewFrame");
try {
// Use data URI to avoid cross-origin issues
iframe.src = "data:text/html;charset=utf-8," + encodeURIComponent(combined);
} catch (e) {
console.error("Error setting iframe content:", e);
}
};
// Download functionality
document.getElementById("downloadButton").onclick = function() {
const combined = createCombinedHTML();
// Create a blob with the content
const blob = new Blob([combined], {type: "text/html;charset=utf-8"});
// Create a temporary download link
const downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(blob);
// Set a default filename
let filename = "webpage.html";
// Look for title tag in HTML to use as filename
const titleMatch = combined.match(/<title>(.*?)<\/title>/i);
if (titleMatch && titleMatch[1]) {
// Clean up the title to make it suitable for a filename
filename = titleMatch[1].trim()
.replace(/[^a-z0-9]/gi, '_') // Replace non-alphanumeric chars with underscores
.replace(/_+/g, '_') // Replace multiple underscores with a single one
.toLowerCase() + ".html";
}
downloadLink.download = filename;
// Trigger the download
document.body.appendChild(downloadLink);
downloadLink.click();
// Clean up
document.body.removeChild(downloadLink);
URL.revokeObjectURL(downloadLink.href);
// Show a confirmation
addSystemMessage("Downloaded file: " + filename);
};
// Close preview modal
document.getElementById("closePreview").onclick = function() {
document.getElementById("previewModal").style.display = "none";
// Clear iframe source when closing
document.getElementById("previewFrame").src = "";
};
// Close modal on outside click and escape key
window.onclick = function(event) {
const previewModal = document.getElementById("previewModal");
const configModal = document.getElementById("configModal");
if (event.target === previewModal) {
previewModal.style.display = "none";
// Clear iframe source when closing
document.getElementById("previewFrame").src = "";
}
if (event.target === configModal) {
configModal.style.display = "none";
}
};
// Close modal on Escape key
window.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
document.getElementById("previewModal").style.display = "none";
document.getElementById("configModal").style.display = "none";
// Clear iframe source when closing
document.getElementById("previewFrame").src = "";
}
});
// Helper function to escape HTML
function escapeHTML(html) {
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
// Function to show notification
function showNotification(message, type = 'success') {
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.textContent = message;
document.body.appendChild(notification);
// Fade in
setTimeout(() => notification.classList.add('show'), 10);
// Fade out and remove
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Function to apply code to editor
function applyCodeToEditor(code, language) {
let editor;
let tabName;
let editorType;
if (language === 'html' || language === 'htmlmixed') {
editor = htmlEditor;
tabName = 'HTML';
editorType = 'html';
} else if (language === 'css') {
editor = cssEditor;
tabName = 'CSS';
editorType = 'css';
} else if (language === 'javascript' || language === 'js') {
editor = jsEditor;
tabName = 'JavaScript';
editorType = 'js';
} else {
showNotification(`Unknown language: ${language}. Please use html, css, or javascript.`, 'error');
return;
}
// Save current state before applying new code
saveEditorState(editorType);
editor.setValue(code);
showNotification(`Code applied to ${tabName} editor!`, 'success');
// Switch to the updated tab
setActiveTab(editorType);
}
// Chat functionality
function addMessage(text, isUser) {
const messageDiv = document.createElement("div");
messageDiv.className = "message " + (isUser ? "user-message" : "assistant-message");
// Process code blocks with ```
if (!isUser && text.includes("```")) {
let parts = text.split("```");
let processedText = "";
for (let i = 0; i < parts.length; i++) {
if (i % 2 === 0) {
// Regular text
processedText += escapeHTML(parts[i]);
} else {
// Code block
let codeContent = parts[i];
let language = "";
// Check if there's a language specified
if (codeContent.indexOf("\n") > 0) {
language = codeContent.substring(0, codeContent.indexOf("\n")).trim();
codeContent = codeContent.substring(codeContent.indexOf("\n") + 1);
}
const codeId = 'code-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
const trimmedCode = codeContent.trim();
// Only show apply button for supported languages
const supportedLanguages = ['html', 'css', 'javascript', 'js', 'htmlmixed'];
const showApplyButton = supportedLanguages.includes(language.toLowerCase());
processedText += `
<div class="code-block-wrapper">
${showApplyButton ? `
<div class="code-header">
<span class="code-language">${escapeHTML(language)}</span>
<button class="apply-code-btn" data-code-id="${codeId}" data-language="${escapeHTML(language)}">
Apply to ${language.toUpperCase()} Editor
</button>
</div>
` : (language ? `<div class="code-header"><span class="code-language">${escapeHTML(language)}</span></div>` : '')}
<div class="code-block" id="${codeId}">${escapeHTML(trimmedCode)}</div>
</div>
`;
}
}
messageDiv.innerHTML = processedText;
// Add click handlers for apply buttons
const applyButtons = messageDiv.querySelectorAll('.apply-code-btn');
applyButtons.forEach(button => {
button.addEventListener('click', function() {
const codeId = this.getAttribute('data-code-id');
const language = this.getAttribute('data-language');
const codeBlock = document.getElementById(codeId);
if (codeBlock) {
const code = codeBlock.textContent;
applyCodeToEditor(code, language);
}
});
});
} else {
messageDiv.textContent = text;
}
messagesContainer.appendChild(messageDiv);
// Scroll to bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
function addSystemMessage(text) {
const messageDiv = document.createElement("div");
messageDiv.className = "message system-message";
messageDiv.textContent = text;
messagesContainer.appendChild(messageDiv);
// Scroll to bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Create conversation history array
let conversationHistory = [];
// Function to save editor state to history
function saveEditorState(editorType) {
let editor, history;
if (editorType === 'html') {
editor = htmlEditor;
history = editorHistory.html;
} else if (editorType === 'css') {
editor = cssEditor;
history = editorHistory.css;
} else if (editorType === 'js') {
editor = jsEditor;
history = editorHistory.js;
}
const currentValue = editor.getValue();
// Only save if different from current state
if (history.currentState !== currentValue) {
// Save current state to undo stack
if (history.currentState !== null) {
history.undoStack.push(history.currentState);
// Limit history size
if (history.undoStack.length > MAX_HISTORY_SIZE) {
history.undoStack.shift();
}
}
// Update current state
history.currentState = currentValue;
// Clear redo stack when new change is made
history.redoStack = [];
updateUndoRedoButtons();
}
}
// Function to undo changes
function undo(editorType) {
let editor, history, tabName;
if (editorType === 'html') {
editor = htmlEditor;
history = editorHistory.html;
tabName = 'HTML';
} else if (editorType === 'css') {
editor = cssEditor;
history = editorHistory.css;
tabName = 'CSS';
} else if (editorType === 'js') {
editor = jsEditor;
history = editorHistory.js;
tabName = 'JavaScript';
}
if (history.undoStack.length === 0) {
showNotification('Nothing to undo in ' + tabName, 'error');
return;
}
// Push current state to redo stack
if (history.currentState !== null) {
history.redoStack.push(history.currentState);
}
// Pop from undo stack and apply
const previousState = history.undoStack.pop();
history.currentState = previousState;
editor.setValue(previousState);
showNotification('Undo in ' + tabName, 'success');
updateUndoRedoButtons();
}
// Function to redo changes
function redo(editorType) {
let editor, history, tabName;
if (editorType === 'html') {
editor = htmlEditor;
history = editorHistory.html;
tabName = 'HTML';
} else if (editorType === 'css') {
editor = cssEditor;
history = editorHistory.css;
tabName = 'CSS';
} else if (editorType === 'js') {
editor = jsEditor;
history = editorHistory.js;
tabName = 'JavaScript';
}
if (history.redoStack.length === 0) {
showNotification('Nothing to redo in ' + tabName, 'error');
return;
}
// Push current state to undo stack
if (history.currentState !== null) {
history.undoStack.push(history.currentState);
}
// Pop from redo stack and apply
const nextState = history.redoStack.pop();
history.currentState = nextState;
editor.setValue(nextState);
showNotification('Redo in ' + tabName, 'success');
updateUndoRedoButtons();
}
// Function to get active editor type
function getActiveEditorType() {
if (document.getElementById('htmlTab').classList.contains('active')) {
return 'html';
} else if (document.getElementById('cssTab').classList.contains('active')) {
return 'css';
} else if (document.getElementById('jsTab').classList.contains('active')) {
return 'js';
}
return 'html';
}
// Function to update undo/redo button states
function updateUndoRedoButtons() {
const activeEditorType = getActiveEditorType();
const history = editorHistory[activeEditorType];
const undoBtn = document.getElementById('undoButton');
const redoBtn = document.getElementById('redoButton');
if (undoBtn && redoBtn) {
undoBtn.disabled = history.undoStack.length === 0;
redoBtn.disabled = history.redoStack.length === 0;
}
}
// Function to generate a unique message ID (not used in current code, but good practice to keep if potentially needed)
/* function generateMessageId() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
} */
// Function to get current code context
function getCurrentCodeContext() {
return {
html: htmlEditor.getValue(),
css: cssEditor.getValue(),
javascript: jsEditor.getValue()
};
}
// Function to send message to OpenAI API with streaming
async function sendToLLM(userMessage) {
// Disable send button and show loading state
sendButton.disabled = true;
sendButton.innerHTML = '<div class="spinner"></div>Sending...';
// Create a message element for the assistant response that we'll update
const responseDiv = document.createElement("div");
responseDiv.className = "message assistant-message";
messagesContainer.appendChild(responseDiv);
let responseFromAPI; // To store the response object for status check
try {
// Add system message with code context if enabled
if (apiConfig.includeCodeContext && conversationHistory.length === 0) {
const codeContext = getCurrentCodeContext();
const systemMessage = {
role: "system",
content: `You are a helpful AI assistant for web development. You can help users write and modify HTML, CSS, and JavaScript code.
When providing code suggestions, always use code blocks with language tags like this:
\`\`\`html
<your html code here>
\`\`\`
\`\`\`css
<your css code here>
\`\`\`
\`\`\`javascript
<your javascript code here>
\`\`\`
The user can click "Apply to Editor" buttons to automatically apply your suggested code to their editor tabs.
Current code in the user's editor:
--- HTML ---
${codeContext.html}
--- CSS ---
${codeContext.css}
--- JavaScript ---
${codeContext.javascript}`
};
conversationHistory.push(systemMessage);
}
// Add user message to history
conversationHistory.push({
role: "user",
content: userMessage
});
responseFromAPI = await fetch(apiConfig.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiConfig.apiKey}`
},
body: JSON.stringify({
model: apiConfig.model,
messages: conversationHistory,
temperature: 0.7,
stream: true // Enable streaming
})
});
if (!responseFromAPI.ok) {
const errorData = await responseFromAPI.json().catch(() => ({ error: { message: 'Failed to parse error response from API.' } }));
// Throw an error that includes the status and the message from the API
const err = new Error(errorData.error?.message || `API request failed with status ${responseFromAPI.status}`);
err.status = responseFromAPI.status; // Attach status to the error object
throw err;
}
// Set up the streaming response reader
const reader = responseFromAPI.body.getReader();
const decoder = new TextDecoder("utf-8");
let fullMessage = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Decode the chunk
const chunk = decoder.decode(value, { stream: true });
// Process the SSE format
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
// Check for the "[DONE]" message
if (data === '[DONE]') continue;
try {
const parsedData = JSON.parse(data);
const contentDelta = parsedData.choices[0]?.delta?.content || '';
if (contentDelta) {
fullMessage += contentDelta;
// Process code blocks with ``` for display
let displayText = fullMessage;
if (displayText.includes("```")) {
let parts = displayText.split("```");
let processedText = "";
for (let i = 0; i < parts.length; i++) {
if (i % 2 === 0) {
// Regular text
processedText += escapeHTML(parts[i]);
} else {
// Code block
let codeContent = parts[i];
let language = "";
// Check if there's a language specified
if (codeContent.indexOf("\n") > 0) {
language = codeContent.substring(0, codeContent.indexOf("\n")).trim();
codeContent = codeContent.substring(codeContent.indexOf("\n") + 1);
}
const codeId = 'code-' + Date.now() + '-' + i + '-' + Math.random().toString(36).substr(2, 9);
const trimmedCode = codeContent.trim();
// Only show apply button for supported languages
const supportedLanguages = ['html', 'css', 'javascript', 'js', 'htmlmixed'];
const showApplyButton = supportedLanguages.includes(language.toLowerCase());
processedText += `
<div class="code-block-wrapper">
${showApplyButton ? `
<div class="code-header">
<span class="code-language">${escapeHTML(language)}</span>
<button class="apply-code-btn" data-code-id="${codeId}" data-language="${escapeHTML(language)}">
Apply to ${language.toUpperCase()} Editor
</button>
</div>
` : (language ? `<div class="code-header"><span class="code-language">${escapeHTML(language)}</span></div>` : '')}
<div class="code-block" id="${codeId}">${escapeHTML(trimmedCode)}</div>
</div>
`;
}
}
responseDiv.innerHTML = processedText;
// Add click handlers for apply buttons
const applyButtons = responseDiv.querySelectorAll('.apply-code-btn');
applyButtons.forEach(button => {
// Remove existing listener to avoid duplicates
button.replaceWith(button.cloneNode(true));
});
// Re-select and add new listeners
const newApplyButtons = responseDiv.querySelectorAll('.apply-code-btn');
newApplyButtons.forEach(button => {
button.addEventListener('click', function() {
const codeId = this.getAttribute('data-code-id');
const language = this.getAttribute('data-language');
const codeBlock = document.getElementById(codeId);
if (codeBlock) {
const code = codeBlock.textContent;
applyCodeToEditor(code, language);
}
});
});
} else {
responseDiv.textContent = displayText;
}
// Scroll to bottom as text appears
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
} catch (error) {
console.error('Error parsing streaming data:', error, data);
}
}
}
}
// After streaming completes, add assistant's complete response to history
conversationHistory.push({
role: "assistant",
content: fullMessage
});
localStorage.removeItem('apiKeyInvalid'); // Clear flag on successful call
// Auto-apply code if enabled
if (apiConfig.autoApply && fullMessage.includes("```")) {
const parts = fullMessage.split("```");
for (let i = 1; i < parts.length; i += 2) {
let codeContent = parts[i];
let language = "";
// Check if there's a language specified
if (codeContent.indexOf("\n") > 0) {
language = codeContent.substring(0, codeContent.indexOf("\n")).trim();
codeContent = codeContent.substring(codeContent.indexOf("\n") + 1);
}
const supportedLanguages = ['html', 'css', 'javascript', 'js', 'htmlmixed'];
if (supportedLanguages.includes(language.toLowerCase())) {
applyCodeToEditor(codeContent.trim(), language);
}
}
}
return fullMessage;
} catch (error) {
console.error('Error calling LLM API:', error);
responseDiv.remove(); // Remove the empty response div
const status = error.status || (responseFromAPI ? responseFromAPI.status : null);
const errorMessage = error.message || "An unknown error occurred.";
if (status === 401 ||
errorMessage.toLowerCase().includes('api key') ||
errorMessage.toLowerCase().includes('auth') ||
errorMessage.toLowerCase().includes('token')) {
addSystemMessage("API request failed. Please check your API key and endpoint configuration. It seems there might be an authentication issue.");
localStorage.setItem('apiKeyInvalid', 'true');
} else if (status) {
addSystemMessage(`Error: API request failed with status ${status}. ${errorMessage}`);
}
else {
addSystemMessage(`Error: ${errorMessage}`);
}
updateChatAvailability(); // Refresh UI based on new error state
return null;
} finally {
// Reset send button
sendButton.disabled = false;
sendButton.textContent = 'Send';
}
}
// Send button click handler
document.getElementById("sendButton").onclick = async function() {
const message = chatInput.value.trim();
if (message) {
// Add user message
addMessage(message, true);
chatInput.value = "";
// Get AI response using streaming
await sendToLLM(message);
}
};
// Send message on Enter key
chatInput.onkeydown = function(e) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendButton.click();
}
};
// New Chat functionality
document.getElementById("newChatButton").onclick = function() {
const apiKeyInvalid = localStorage.getItem('apiKeyInvalid') === 'true';
if (isApiConfigured && !apiKeyInvalid) {
// Clear conversation history
conversationHistory = [];
// Clear messages in the UI
messagesContainer.innerHTML = '';
// Reset all editors to initial values
htmlEditor.setValue(INITIAL_HTML);
cssEditor.setValue(INITIAL_CSS);
jsEditor.setValue(INITIAL_JS);
// Clear undo/redo history for all editors
editorHistory.html.undoStack = [];
editorHistory.html.redoStack = [];
editorHistory.html.currentState = INITIAL_HTML;
editorHistory.css.undoStack = [];
editorHistory.css.redoStack = [];
editorHistory.css.currentState = INITIAL_CSS;
editorHistory.js.undoStack = [];
editorHistory.js.redoStack = [];
editorHistory.js.currentState = INITIAL_JS;
// Update undo/redo button states
updateUndoRedoButtons();
// Add a new welcome message
addMessage("Starting a new conversation. How can I help you today?", false);
// Show notification
showNotification("Editors and chat have been reset!", "success");
} else if (apiKeyInvalid) {
addSystemMessage("Cannot start a new chat. There might be an issue with your API key or endpoint. Please verify your settings.");
}
else {
// If API is not configured, show a reminder
addSystemMessage("Please configure the API settings first to start a new chat.");
}
};
// Config modal functionality
document.getElementById("configButton").onclick = function() {
// Pre-fill form with current values
document.getElementById("apiEndpoint").value = apiConfig.endpoint;
document.getElementById("apiKey").value = apiConfig.apiKey;
document.getElementById("modelName").value = apiConfig.model;
document.getElementById("includeCodeContext").checked = apiConfig.includeCodeContext;
document.getElementById("autoApply").checked = apiConfig.autoApply;
// Show modal
document.getElementById("configModal").style.display = "block";
};
// Close config modal
document.getElementById("closeConfig").onclick = function() {
document.getElementById("configModal").style.display = "none";
};
// Form submission
document.getElementById("configForm").onsubmit = function(e) {
e.preventDefault();
// Update config object
apiConfig.endpoint = document.getElementById("apiEndpoint").value.trim();
apiConfig.apiKey = document.getElementById("apiKey").value.trim();
apiConfig.model = document.getElementById("modelName").value.trim();
apiConfig.includeCodeContext = document.getElementById("includeCodeContext").checked;
apiConfig.autoApply = document.getElementById("autoApply").checked;
// Save to localStorage
localStorage.setItem('apiEndpoint', apiConfig.endpoint);
localStorage.setItem('apiKey', apiConfig.apiKey);
localStorage.setItem('modelName', apiConfig.model);
localStorage.setItem('includeCodeContext', apiConfig.includeCodeContext);
localStorage.setItem('autoApply', apiConfig.autoApply);
// Clear the invalid key flag as user is trying a new config
localStorage.removeItem('apiKeyInvalid');
// Update API state and reset conversation
isApiConfigured = !!(apiConfig.endpoint && apiConfig.apiKey && apiConfig.model);
conversationHistory = []; // Clear conversation history
updateChatAvailability(); // This will now show the appropriate message
// Close modal
document.getElementById("configModal").style.display = "none";
// Show notification about settings
if (apiConfig.autoApply) {
showNotification("Auto-apply enabled! AI code suggestions will be automatically applied.", "success");
}
};
function refreshAllEditors() {
// Add a small delay to ensure the DOM has updated
setTimeout(function() {
htmlEditor.refresh();
cssEditor.refresh();
jsEditor.refresh();
}, 50);
}
// Initialize editors on window resize
window.onresize = refreshAllEditors;
// Undo/Redo button handlers
document.getElementById("undoButton").onclick = function() {
const activeEditorType = getActiveEditorType();
undo(activeEditorType);
};
document.getElementById("redoButton").onclick = function() {
const activeEditorType = getActiveEditorType();
redo(activeEditorType);
};
// Keyboard shortcuts for undo/redo
document.addEventListener('keydown', function(e) {
// Ctrl+Z or Cmd+Z for undo
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
const activeEditorType = getActiveEditorType();
undo(activeEditorType);
}
// Ctrl+Shift+Z or Cmd+Shift+Z for redo (also Ctrl+Y)
else if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
e.preventDefault();
const activeEditorType = getActiveEditorType();
redo(activeEditorType);
}
});
// Initialize undo/redo button states
updateUndoRedoButtons();
};