forked from ab-613/OpenGravity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1868 lines (1632 loc) · 77.8 KB
/
Copy pathscript.js
File metadata and controls
1868 lines (1632 loc) · 77.8 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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ==========================================================================
VS CODE CLONE - FULLY INTERACTIVE LOGIC
========================================================================== */
/* --- 1. GLOBAL STATE --- */
const appState = {
activeTab: null,
openTabs: [],
files: {},
expandedFolders: new Set(),
isRootExpanded: true, // NEW: Tracks if the main workspace tree is visible
selectedPath: null, // NEW: Tracks clicked item in sidebar
isExplorerFocused: false, // NEW: Tracks if sidebar is active
creatingItem: null, // NEW: { type: 'file'|'folder', parentPath: string }
directories: new Set(), // NEW: Tracks all known directories for better creation logic
layout: { sidebarWidth: 250, aiPanelWidth: 350, terminalHeight: 300 },
aiMessages: [],
activePort: null, // NEW: Tracks running dev servers
activePreviewUrl: null, // NEW: Tracks the WebContainer preview URL
aiChangeFiles: new Set(), // NEW: Tracks files that have unaccepted AI changes
isSettingsModalOpen: false // NEW: Tracks settings modal visibility
};
/* --- AI PANEL CONSTANTS --- */
let monacoEditorInstance = null;
let isMonacoInitialized = false;
let isInternalChange = false;
/* --- 2. ENHANCED DOM HELPER (Now supports events!) --- */
function el(tag, attributes = {}, children = []) {
const element = document.createElement(tag);
for (const [key, value] of Object.entries(attributes)) {
if (key === 'class' || key === 'className') element.className = value;
else if (key === 'style') element.style.cssText = value;
// NEW: Properly attach event listeners (onclick, oninput, etc.)
else if (key.startsWith('on') && typeof value === 'function') element[key.toLowerCase()] = value;
else element.setAttribute(key, value);
}
if (!Array.isArray(children)) children = [children];
children.forEach(child => {
if (typeof child === 'string') element.appendChild(document.createTextNode(child));
else if (child instanceof HTMLElement) element.appendChild(child);
});
return element;
}
// Expanded Seti Icons Helper
// Enhanced File Icons Helper - Supports names and extensions
function getFileIcon(filename) {
if (!filename) return el('span', { class: 'file-icon txt-ext-file-icon ext-file-icon' });
if (filename === 'Live Preview') return el('i', { class: 'codicon codicon-browser', style: 'margin-right: 6px; font-size: 14px; color: #4fc1ff;' });
// Normalize path to just filename
const name = filename.split('/').pop();
const parts = name.split('.');
const ext = parts.length > 1 ? parts.pop().toLowerCase() : name.toLowerCase();
const nameLower = name.toLowerCase();
// Specific filename mapping
const nameMap = {
'dockerfile': 'dockerfile-lang-file-icon',
'makefile': 'makefile-lang-file-icon',
'package.json': 'json-lang-file-icon',
'gitconfig': 'gitconfig-ext-file-icon ext-file-icon',
'gitignore': 'ignore-lang-file-icon',
'gitattributes': 'gitattributes-ext-file-icon ext-file-icon',
'license': 'license-name-file-icon name-file-icon'
};
if (nameMap[nameLower]) return el('span', { class: `file-icon ${nameMap[nameLower]}` });
// Extension mapping
const extMap = {
'js': 'javascript-lang-file-icon',
'mjs': 'javascript-lang-file-icon',
'cjs': 'javascript-lang-file-icon',
'jsx': 'javascriptreact-lang-file-icon',
'ts': 'typescript-lang-file-icon',
'tsx': 'typescriptreact-lang-file-icon',
'html': 'html-lang-file-icon',
'htm': 'html-lang-file-icon',
'css': 'css-lang-file-icon',
'json': 'json-lang-file-icon',
'jsonc': 'json-lang-file-icon',
'py': 'python-lang-file-icon',
'cpp': 'cpp-lang-file-icon',
'cc': 'cpp-lang-file-icon',
'cxx': 'cpp-lang-file-icon',
'c': 'c-lang-file-icon',
'h': 'h-ext-file-icon ext-file-icon',
'hpp': 'hpp-ext-file-icon ext-file-icon',
'cs': 'csharp-lang-file-icon',
'java': 'java-lang-file-icon',
'class': 'class-ext-file-icon ext-file-icon',
'md': 'markdown-lang-file-icon',
'php': 'php-lang-file-icon',
'rb': 'ruby-lang-file-icon',
'go': 'go-lang-file-icon',
'rs': 'rust-lang-file-icon',
'sql': 'sql-lang-file-icon',
'yaml': 'yaml-lang-file-icon',
'yml': 'yaml-lang-file-icon',
'xml': 'xml-lang-file-icon',
'sh': 'shellscript-lang-file-icon',
'bat': 'bat-lang-file-icon',
'ps1': 'powershell-lang-file-icon',
'less': 'less-lang-file-icon',
'scss': 'scss-lang-file-icon',
'sass': 'sass-lang-file-icon',
'vue': 'vue-lang-file-icon',
'lua': 'lua-lang-file-icon',
'png': 'png-ext-file-icon ext-file-icon',
'jpg': 'jpg-ext-file-icon ext-file-icon',
'jpeg': 'jpeg-ext-file-icon ext-file-icon',
'gif': 'gif-ext-file-icon ext-file-icon',
'svg': 'svg-ext-file-icon ext-file-icon',
'pdf': 'pdf-ext-file-icon ext-file-icon',
'zip': 'zip-ext-file-icon ext-file-icon',
'txt': 'txt-ext-file-icon ext-file-icon',
'ico': 'ico-ext-file-icon ext-file-icon'
};
const iconClass = extMap[ext] || 'txt-ext-file-icon ext-file-icon';
return el('span', { class: `file-icon ${iconClass}` });
}
/* --- FILE SYSTEM & TERMINAL MANAGERS --- */
let webcontainerInstance = null;
let terminalProcess = null;
const FSManager = {
localDirHandle: null,
async init() {
if (typeof idbKeyval === 'undefined') {
console.error("idbKeyval is not defined. Script might have failed to load.");
return;
}
// 1. Try to load previously saved folder handle
try {
const savedHandle = await idbKeyval.get('workspace_handle');
if (savedHandle) {
// Verify permission
const permission = await savedHandle.queryPermission({ mode: 'readwrite' });
if (permission === 'granted') {
await this.loadWorkspace(savedHandle);
}
}
} catch (e) { console.log("No previous workspace found."); }
},
async requestWorkspace() {
try {
const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
await idbKeyval.set('workspace_handle', handle);
await this.loadWorkspace(handle);
} catch (err) { console.error("Folder selection cancelled.", err); }
},
async loadWorkspace(dirHandle) {
try {
this.localDirHandle = dirHandle;
appState.files = {};
appState.directories = new Set();
appState.openTabs = [];
appState.activeTab = null;
appState.isLoading = true;
updateUI();
console.log("🔍 Scanning directory...");
const wcTree = {};
await this.readDirectory(dirHandle, '', wcTree);
console.log(`✅ Scan complete. Found ${Object.keys(appState.files).length} files.`);
// Mount to WebContainer
if (webcontainerInstance) {
console.log("🚀 Mounting to WebContainer...");
try {
await webcontainerInstance.mount(wcTree);
console.log("✨ WebContainer mount successful.");
} catch (mountErr) {
console.error("❌ WebContainer mount failed:", mountErr);
}
}
// NEW: Auto-expand top level folders
for (const key of Object.keys(appState.files)) {
const parts = key.split('/');
if (parts.length > 1) {
appState.expandedFolders.add(parts[0]); // Expand first level
}
}
appState.isLoading = false;
console.log("🔄 Refreshing UI...");
updateUI();
} catch (err) {
console.error("❌ Workspace load failed:", err);
appState.isLoading = false;
updateUI();
}
},
async readDirectory(dirHandle, pathPrefix, wcTree) {
for await (const entry of dirHandle.values()) {
const fullPath = pathPrefix ? `${pathPrefix}/${entry.name}` : entry.name;
// Optimization: Skip known large/unnecessary folders
if (entry.kind === 'directory') {
if (/^(node_modules|\.git|\.next|dist|build)$/.test(entry.name)) continue;
appState.directories.add(fullPath);
wcTree[entry.name] = { directory: {} };
await this.readDirectory(entry, fullPath, wcTree[entry.name].directory);
} else if (entry.kind === 'file') {
try {
const file = await entry.getFile();
// Skip very large files or binary blobs to prevent hanging
if (file.size > 1024 * 1024) { // 1MB limit
console.warn(`Skipping large file: ${fullPath} (${(file.size / 1024).toFixed(1)}KB)`);
continue;
}
const content = await file.text();
wcTree[entry.name] = { file: { contents: content } };
const ext = entry.name.split('.').pop().toLowerCase();
appState.files[fullPath] = {
type: ext,
language: this.getLang(ext),
content: content,
baselineContent: content, // Initial content is the baseline
dirty: false,
handle: entry
};
} catch (fileErr) {
console.warn(`Could not read file ${fullPath}:`, fileErr);
}
}
}
},
async writeFile(filename, content, source = 'ui') {
let fileHandle = appState.files[filename] ? appState.files[filename].handle : null;
const oldFile = appState.files[filename];
// 1. If the AI is creating a brand new file, create it in the OS first
if (!fileHandle && this.localDirHandle) {
const parts = filename.split('/');
let currentHandle = this.localDirHandle;
for (let i = 0; i < parts.length - 1; i++) {
currentHandle = await currentHandle.getDirectoryHandle(parts[i], { create: true });
}
fileHandle = await currentHandle.getFileHandle(parts[parts.length - 1], { create: true });
}
// 2. Update UI State
appState.files[filename] = {
type: filename.split('.').pop(),
language: this.getLang(filename.split('.').pop()),
content: content,
baselineContent: oldFile ? oldFile.baselineContent : content,
dirty: false,
handle: fileHandle
};
// NEW: Track if AI made the change
if (source === 'ai') {
appState.aiChangeFiles.add(filename);
} else if (source === 'ui') {
// If user manually edits, we might want to keep the AI diff or clear it.
// Requirement says "it saves what the model does straight away, but still shows up... as green/red lines"
// If the user then edits it, we probably want to keep showing the diff against the last baseline.
}
// 3. Update WebContainer (Create parent directories if AI made them up)
if (webcontainerInstance) {
const parts = filename.split('/');
const dirPath = parts.slice(0, -1).join('/');
if (dirPath) await webcontainerInstance.fs.mkdir(`/${dirPath}`, { recursive: true });
await webcontainerInstance.fs.writeFile(`/${filename}`, content);
}
// 4. Save to actual Hard Drive
if (fileHandle) {
const writable = await fileHandle.createWritable();
await writable.write(content);
await writable.close();
}
// 5. Live update Editor if user is watching it
if (appState.activeTab === filename && monacoEditorInstance) {
const currentVal = monacoEditorInstance.getValue();
if (currentVal !== content) monacoEditorInstance.setValue(content);
}
updateUI();
},
// Start Inline Creation Process
startCreation(type) {
if (!this.localDirHandle) return alert("Please open a folder first.");
let parentPath = '';
if (appState.selectedPath) {
// Check if selected item is a folder
// Better check: is it in expandedFolders OR does it have children in files OR is it known to be a folder?
// Actually, we can check the DOM or just assume if it doesn't have an extension it's a folder (weak)
// Or better: check if it's the root header
const isFolder = appState.selectedPath === 'ROOT' ||
appState.directories.has(appState.selectedPath) ||
appState.expandedFolders.has(appState.selectedPath) ||
Object.keys(appState.files).some(f => f.startsWith(appState.selectedPath + '/'));
if (isFolder) {
if (appState.selectedPath === 'ROOT') {
parentPath = '';
} else {
parentPath = appState.selectedPath;
}
} else {
// If it's a file, get its parent folder
const parts = appState.selectedPath.split('/');
parts.pop();
parentPath = parts.join('/');
}
// CRITICAL: Ensure the parent folder is expanded so we can see the input!
if (parentPath) {
appState.expandedFolders.add(parentPath);
appState.isRootExpanded = true;
}
}
appState.creatingItem = { type, parentPath };
updateUI();
// Auto-focus the input box
setTimeout(() => {
const input = document.getElementById('explorer-creation-input');
if (input) input.focus();
}, 10);
},
// Handle typing in the input box
async handleCreationInput(e) {
if (!appState.creatingItem) return;
if (e.key === 'Escape') {
this.cancelCreation();
} else if (e.key === 'Enter') {
const val = e.target.value.trim();
if (!val) {
this.cancelCreation();
return;
}
const item = { ...appState.creatingItem };
appState.creatingItem = null; // Clear creation state immediately to prevent double-submit
const fullPath = item.parentPath ? `${item.parentPath}/${val}` : val;
try {
if (item.type === 'file') {
await this.executeCreateFile(fullPath);
} else {
await this.executeCreateFolder(fullPath);
}
} catch (err) {
console.error(`Failed to create ${item.type}:`, err);
alert(`Error: ${err.message}`);
updateUI(); // Refresh to remove the stuck input box
}
}
},
cancelCreation() {
if (!appState.creatingItem) return;
appState.creatingItem = null;
updateUI();
},
// Execute File Creation
async executeCreateFile(path) {
const parts = path.split('/').filter(p => p !== '');
let currentHandle = this.localDirHandle;
for (let i = 0; i < parts.length - 1; i++) {
currentHandle = await currentHandle.getDirectoryHandle(parts[i], { create: true });
}
const fileName = parts[parts.length - 1];
const fileHandle = await currentHandle.getFileHandle(fileName, { create: true });
const writable = await fileHandle.createWritable();
await writable.write('');
await writable.close();
if (webcontainerInstance) {
const dirPath = parts.slice(0, -1).join('/');
if (dirPath) await webcontainerInstance.fs.mkdir(dirPath, { recursive: true });
await webcontainerInstance.fs.writeFile(path, ''); // Removed leading slash!
}
appState.files[path] = {
type: path.split('.').pop(),
language: this.getLang(path.split('.').pop()),
content: '',
dirty: false,
handle: fileHandle
};
appState.selectedPath = path; // Select the new file
if (!appState.openTabs.includes(path)) appState.openTabs.push(path);
appState.activeTab = path;
updateUI();
if (monacoEditorInstance) {
isInternalChange = true;
monacoEditorInstance.setValue('');
isInternalChange = false;
}
},
// Execute Folder Creation
async executeCreateFolder(path) {
const parts = path.split('/').filter(p => p !== '');
let currentHandle = this.localDirHandle;
for (let i = 0; i < parts.length; i++) {
currentHandle = await currentHandle.getDirectoryHandle(parts[i], { create: true });
}
if (webcontainerInstance) {
await webcontainerInstance.fs.mkdir(path, { recursive: true }); // Removed leading slash!
}
appState.directories.add(path); // Update known directories
appState.expandedFolders.add(path); // Auto-expand new folder
appState.selectedPath = path; // Select the new folder
await this.refreshWorkspace(); // Re-read tree to display properly
},
async refreshWorkspace() {
if (!this.localDirHandle) return;
// Manually trigger the two-way sync
await this.syncWebContainerToOS();
},
async syncWebContainerToOS() {
if (!webcontainerInstance || !this.localDirHandle) return;
// Recursive function to read WebContainer and write to UI & OS
const scanWc = async (dirPath, localHandle) => {
const entries = await webcontainerInstance.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
// IMPORTANT: Never sync node_modules or .git back to the OS!
if (entry.name === 'node_modules' || entry.name === '.git') continue;
const fullWcPath = dirPath === '.' ? entry.name : `${dirPath}/${entry.name}`;
if (entry.isFile()) {
const content = await webcontainerInstance.fs.readFile(fullWcPath, 'utf-8');
// If file is NEW or has been MODIFIED by the terminal
if (!appState.files[fullWcPath] || appState.files[fullWcPath].content !== content) {
// 1. Save to OS Disk
const fileHandle = await localHandle.getFileHandle(entry.name, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(content);
await writable.close();
// 2. Save to UI State
appState.files[fullWcPath] = {
type: entry.name.split('.').pop(),
language: this.getLang(entry.name.split('.').pop()),
content: content,
dirty: false,
handle: fileHandle
};
}
} else if (entry.isDirectory()) {
// Ensure folder exists in OS and scan inside it
const newLocalHandle = await localHandle.getDirectoryHandle(entry.name, { create: true });
appState.expandedFolders.add(fullWcPath); // Auto expand new folders in UI
await scanWc(fullWcPath, newLocalHandle);
}
}
};
await scanWc('.', this.localDirHandle);
updateUI();
},
// Helper to build the WebContainer tree structure from our current appState.files
generateWCTree() {
const tree = {};
for (const [path, fileObj] of Object.entries(appState.files)) {
const parts = path.split('/');
let current = tree;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (i === parts.length - 1) {
current[part] = { file: { contents: fileObj.content } };
} else {
current[part] = current[part] || { directory: {} };
current = current[part].directory;
}
}
}
return tree;
},
getLang(ext) {
const map = { js: 'javascript', html: 'html', css: 'css', py: 'python', json: 'json', md: 'markdown' };
return map[ext] || 'plaintext';
}
};
const TerminalManager = {
xterm: null,
fitAddon: null,
async init() {
// Wait up to 2 seconds for the module script to attach WebContainer to window
let retries = 0;
while (typeof window.WebContainer === 'undefined' && retries < 40) {
await new Promise(resolve => setTimeout(resolve, 50));
retries++;
}
if (typeof window.WebContainer === 'undefined') {
console.error("WebContainer API is not loaded. Check COEP headers and network connection.");
return;
}
// Boot WebContainer and explicitly name the folder to remove the ugly random string
webcontainerInstance = await window.WebContainer.boot({ workdirName: 'workspace' });
// NEW: Listen for when the AI or User starts a Web Server
webcontainerInstance.on('server-ready', (port, url) => {
console.log(`Server started on port ${port}: ${url}`);
appState.activePort = port;
appState.activePreviewUrl = url;
updateUI(); // This will trigger the Status Bar to show the Preview button
});
// MOUNT ON RELOAD: If files were already loaded from indexedDB, mount them now
if (Object.keys(appState.files).length > 0) {
console.log("📦 Restoring files into WebContainer...");
const tree = FSManager.generateWCTree();
await webcontainerInstance.mount(tree);
}
// GLOBAL: Handle explorer unfocusing when clicking elsewhere
window.addEventListener('mousedown', (e) => {
// If click is NOT in sidebar and NOT in a dialog/alert
const sidebar = document.querySelector('.sidebar');
if (sidebar && !sidebar.contains(e.target)) {
if (appState.isExplorerFocused) {
appState.isExplorerFocused = false;
updateUI();
}
}
});
// Setup Xterm UI
const termContainer = document.querySelector('.panel-body');
termContainer.innerHTML = ''; // Clear hardcoded HTML
this.xterm = new window.Terminal({
fontFamily: "'Cascadia Code', Consolas, 'Courier New', monospace",
fontSize: 14, // Slightly larger to match your screenshot
lineHeight: 1.2, // Tighter line height, like real VS Code
fontWeight: '400',
cursorStyle: 'block', // Solid block cursor
cursorBlink: true,
theme: {
background: '#181818',
foreground: '#cccccc',
cursor: '#ffffff', // Crisp white cursor
selectionBackground: '#264f78', // Authentic VS Code selection blue
// VS Code Default Dark ANSI Colors
black: '#000000',
red: '#cd3131',
green: '#0dbc79',
yellow: '#e5e510',
blue: '#2472c8',
magenta: '#bc3fbc',
cyan: '#11a8cd',
white: '#e5e5e5',
brightBlack: '#666666',
brightRed: '#f14c4c',
brightGreen: '#23d18b',
brightYellow: '#f5f543',
brightBlue: '#3b8eea',
brightMagenta: '#d670d6',
brightCyan: '#29b8db',
brightWhite: '#e5e5e5'
}
});
this.fitAddon = new window.FitAddon.FitAddon();
this.xterm.loadAddon(this.fitAddon);
this.xterm.open(termContainer);
this.fitAddon.fit();
// Start Bash Shell (jsh)
terminalProcess = await webcontainerInstance.spawn('jsh', {
terminal: { cols: this.xterm.cols, rows: this.xterm.rows }
});
if (!terminalProcess) {
console.error("Failed to spawn terminal process.");
return;
}
// Pipe Shell Output -> UI Terminal
terminalProcess.output.pipeTo(new WritableStream({
write: (data) => this.xterm.write(data)
}));
// Pipe UI Terminal Input -> Shell
const terminalWriter = terminalProcess.input.getWriter();
this.xterm.onData((data) => {
terminalWriter.write(data);
// MAGIC: Every time you press "Enter" in the terminal, check for new files!
if (data === '\r') {
// Check 1.5 seconds later (for fast commands like touch, mkdir)
setTimeout(() => FSManager.syncWebContainerToOS(), 1500);
// Check 5 seconds later (for slower commands like npm install)
setTimeout(() => FSManager.syncWebContainerToOS(), 5000);
}
});
// Handle Resizing (Window AND Panel resize)
const resizeObserver = new ResizeObserver(() => {
this.fitAddon.fit();
if (terminalProcess) {
terminalProcess.resize({ cols: this.xterm.cols, rows: this.xterm.rows });
}
});
resizeObserver.observe(termContainer);
},
activeAgentProcess: null,
agentProcessOutput: "",
// Helper to strip Matrix/Spinner characters so the AI can actually read the text
stripAnsi(str) {
return str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '').replace(/\r/g, '\n');
},
async executeAgentCommand(command) {
if (!webcontainerInstance) return "Error: WebContainer not booted.";
return new Promise(async (resolve) => {
try {
this.agentProcessOutput = "";
const process = await webcontainerInstance.spawn('jsh', ['-c', command]);
this.activeAgentProcess = process;
let isDone = false;
let hasResolved = false;
process.output.pipeTo(new WritableStream({
write: (data) => {
this.agentProcessOutput += data;
if (this.xterm) this.xterm.write(data); // User sees colors
const cleanOutput = this.stripAnsi(this.agentProcessOutput);
// MAGIC 1: Detect Dev Server Success
if (!hasResolved && (cleanOutput.includes('Local: http') || cleanOutput.includes('ready in') || cleanOutput.includes('Accepts connections'))) {
hasResolved = true;
resolve(`Exit Code: 0 (Background Process)\nOutput:\n${cleanOutput}\n\n[SUCCESS: Server is running!]`);
}
// MAGIC 2: Detect Interactive Prompt (y/N)
if (!hasResolved && (cleanOutput.endsWith('(y) ') || cleanOutput.endsWith('(y/N) '))) {
hasResolved = true;
resolve(`[Process paused waiting for input]\nOutput:\n${cleanOutput}`);
}
}
}));
process.exit.then(code => {
isDone = true;
this.activeAgentProcess = null;
if (!hasResolved) {
hasResolved = true;
resolve(`Exit Code: ${code}\nOutput:\n${this.stripAnsi(this.agentProcessOutput)}`);
}
});
// MAGIC: Dynamic timeout. Give 'install' commands 25s before returning to AI.
const timeoutMs = (command.includes('install') || command.includes('create')) ? 5000 : 2000;
setTimeout(() => {
if (!isDone && !hasResolved) {
hasResolved = true;
resolve(`[Process running in background]\nOutput so far:\n${this.stripAnsi(this.agentProcessOutput)}`);
}
}, timeoutMs);
} catch (e) {
resolve(`Error: ${e.message}`);
}
});
},
async sendAgentInput(text) {
if (!this.activeAgentProcess) return "Error: No active process.";
try {
const writer = this.activeAgentProcess.input.getWriter();
await writer.write(text);
writer.releaseLock();
this.agentProcessOutput = "";
await new Promise(r => setTimeout(r, 2000));
return `Input sent successfully. New output:\n${this.stripAnsi(this.agentProcessOutput)}`;
} catch (e) {
return `Input Error: ${e.message}`;
}
},
async waitAgent(ms) {
this.agentProcessOutput = "";
await new Promise(r => setTimeout(r, ms));
if (this.activeAgentProcess) {
return `Waited ${ms}ms. New output:\n${this.stripAnsi(this.agentProcessOutput)}`;
}
return `Waited ${ms}ms. Process finished.`;
}
};
/* --- 3. ACTIONS (TAB & FILE MANAGEMENT) --- */
function switchFile(filename) {
if (appState.activeTab === filename) return;
// Save current Monaco content to state before switching (ignore if it's the preview)
if (monacoEditorInstance && appState.activeTab && appState.files[appState.activeTab]) {
appState.files[appState.activeTab].content = monacoEditorInstance.getValue();
}
appState.activeTab = filename;
const monacoContainer = document.getElementById('monaco-container');
let previewFrame = document.getElementById('preview-iframe');
if (filename === 'Live Preview') {
// Hide Monaco, Show/Create Iframe
if (monacoContainer) monacoContainer.style.display = 'none';
if (!previewFrame) {
previewFrame = el('iframe', {
id: 'preview-iframe',
src: appState.activePreviewUrl,
style: 'width: 100%; height: 100%; border: none; background: white;'
});
document.querySelector('.editor-body').appendChild(previewFrame);
} else {
previewFrame.style.display = 'block';
// Update URL if the server restarted on a new port
if (previewFrame.src !== appState.activePreviewUrl) {
previewFrame.src = appState.activePreviewUrl;
}
}
} else {
// Show Monaco, Hide Iframe
if (monacoContainer) monacoContainer.style.display = 'block';
if (previewFrame) previewFrame.style.display = 'none';
// Update Monaco with the selected file's content
if (monacoEditorInstance && appState.files[filename]) {
const file = appState.files[filename];
monaco.editor.setModelLanguage(monacoEditorInstance.getModel(), file.language);
isInternalChange = true;
monacoEditorInstance.setValue(file.content);
isInternalChange = false;
updateDiffDecorations();
}
}
updateUI();
}
function closeTab(event, filename) {
event.stopPropagation(); // Prevent the tab click event from firing
// Remove from openTabs array
appState.openTabs = appState.openTabs.filter(tab => tab !== filename);
// NEW: Destroy the iframe if we closed the preview
if (filename === 'Live Preview') {
const previewFrame = document.getElementById('preview-iframe');
if (previewFrame) previewFrame.remove();
}
// If we closed the active tab, we need to pick a new one
if (appState.activeTab === filename) {
if (appState.openTabs.length > 0) {
const nextTab = appState.openTabs[appState.openTabs.length - 1];
appState.activeTab = null;
switchFile(nextTab);
} else {
appState.activeTab = null;
// Show monaco again but empty it
const monacoContainer = document.getElementById('monaco-container');
if (monacoContainer) monacoContainer.style.display = 'block';
if (monacoEditorInstance) {
isInternalChange = true;
monacoEditorInstance.setValue('');
isInternalChange = false;
}
updateUI();
}
} else {
updateUI();
}
}
function openFileFromSidebar(filename) {
// Add to open tabs if it isn't already there
if (!appState.openTabs.includes(filename)) {
appState.openTabs.push(filename);
}
switchFile(filename);
}
function updateUI() {
try {
const tabsContainer = document.getElementById('tabs-container');
if (tabsContainer) tabsContainer.replaceWith(renderTabs());
const sidebar = document.querySelector('.sidebar');
if (sidebar) sidebar.replaceWith(renderSidebar());
const titleCenter = document.querySelector('.titlebar-center');
if (titleCenter) {
titleCenter.innerHTML = '';
if (appState.activeTab) {
titleCenter.appendChild(document.createTextNode(`vscode clone - Antigravity - ${appState.activeTab}`));
if (appState.files[appState.activeTab].dirty) {
titleCenter.appendChild(el('span', { class: 'title-dirty-dot' }, '•'));
}
} else {
titleCenter.appendChild(document.createTextNode('vscode clone - Antigravity'));
}
}
const statusbar = document.querySelector('.statusbar');
if (statusbar) statusbar.replaceWith(renderStatusBar());
// Handle Settings Modal
const existingModal = document.querySelector('.modal-overlay');
if (appState.isSettingsModalOpen) {
if (!existingModal) {
document.getElementById('root').appendChild(renderSettingsModal());
}
} else {
if (existingModal) existingModal.remove();
}
} catch (uiErr) {
console.error("Fatal UI update error:", uiErr);
}
}
/* --- 4. UI COMPONENTS --- */
function renderTabs() {
const tabs = appState.openTabs.map(filename => {
const isPreview = filename === 'Live Preview';
const file = isPreview ? null : appState.files[filename];
const isActive = filename === appState.activeTab;
const isDirty = file ? file.dirty : false;
// Tab Content
const icon = getFileIcon(filename);
const name = el('span', { class: 'tab-name' }, filename);
// Close Button & Dirty Dot
const actions = el('div', { class: 'tab-actions' }, [
el('i', {
class: 'codicon codicon-close',
onclick: (e) => closeTab(e, filename)
})
]);
if (isDirty) {
actions.appendChild(el('div', { class: 'tab-dirty-dot' }));
}
return el('div', {
class: `tab ${isActive ? 'active' : ''} ${isDirty ? 'dirty' : ''}`,
onclick: () => switchFile(filename)
}, [icon, name, actions]);
});
return el('div', { class: 'tabs-container', id: 'tabs-container' }, tabs);
}
// NEW: Toggles folder open/closed state
function toggleFolder(event, folderPath) {
if (event) event.stopPropagation();
appState.isExplorerFocused = true; // Focus explorer on click
appState.selectedPath = folderPath; // Select it
if (folderPath === 'ROOT') {
appState.isRootExpanded = !appState.isRootExpanded;
} else {
if (appState.expandedFolders.has(folderPath)) {
appState.expandedFolders.delete(folderPath);
} else {
appState.expandedFolders.add(folderPath);
}
}
updateUI();
}
function openFileFromSidebar(event, filename) {
if (event) event.stopPropagation();
appState.isExplorerFocused = true; // Focus explorer on click
appState.selectedPath = filename; // Select it
if (!appState.openTabs.includes(filename)) appState.openTabs.push(filename);
switchFile(filename);
updateUI(); // Ensure UI refreshes to show selection/focus
}
// UPDATED: Recursive File Tree Renderer
function renderFileTree() {
const tree = {};
// 1. Add directories to the tree structure
for (const path of appState.directories) {
const parts = path.split('/').filter(p => p !== '');
let current = tree;
for (const part of parts) {
if (!(part in current)) {
current[part] = {};
}
current = current[part];
}
}
// 2. Add files to the tree structure
for (const path of Object.keys(appState.files)) {
const parts = path.split('/').filter(p => p !== '');
let current = tree;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (i === parts.length - 1) {
current[part] = path; // string indicates file
} else {
current[part] = current[part] || {};
current = current[part];
}
}
}
function renderNode(node, currentPath = '', depth = 0) {
const elements = [];
const paddingLeft = 12 + (depth * 12);
const entries = Object.entries(node).sort((a, b) => {
const aIsFolder = typeof a[1] === 'object';
const bIsFolder = typeof b[1] === 'object';
if (aIsFolder && !bIsFolder) return -1;
if (!aIsFolder && bIsFolder) return 1;
return a[0].localeCompare(b[0]);
});
for (const [name, value] of entries) {
const fullFolderPath = currentPath ? `${currentPath}/${name}` : name;
const isSelected = appState.selectedPath === fullFolderPath;
if (typeof value === 'string') {
const file = appState.files[value];
elements.push(el('div', {
class: `file-item ${isSelected ? 'selected' : ''}`,
style: `padding-left: ${paddingLeft}px;`,
onmousedown: (e) => openFileFromSidebar(e, value)
}, [getFileIcon(name), el('span', { class: 'file-name' }, name)]));
} else {
const isExpanded = appState.expandedFolders.has(fullFolderPath);
elements.push(el('div', {
class: `file-item folder-item ${isSelected ? 'selected' : ''}`,
style: `padding-left: ${paddingLeft - 6}px;`,
onmousedown: (e) => toggleFolder(e, fullFolderPath)
}, [
el('i', { class: `codicon codicon-chevron-${isExpanded ? 'down' : 'right'}`, style: 'margin-right: 2px; font-size: 14px;' }),
el('span', { class: 'file-name' }, name)
]));
if (isExpanded) {
elements.push(...renderNode(value, fullFolderPath, depth + 1));