Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
6603 lines (6145 loc) · 285 KB
/
Copy pathscript.js
File metadata and controls
6603 lines (6145 loc) · 285 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
/* ==========================================================================
LITECODE — FEATHERWEIGHT DESKTOP & BROWSER IDE
Pure Vanilla JS • Monaco Editor • xterm.js • Native Desktop + WebContainer
========================================================================== */
/* --- 1. GLOBAL APPLICATION STATE --- */
const appState = {
runtimeMode: 'browser', // 'desktop' (server.py/native) | 'browser' (WebContainer + File System API)
workspaceName: 'WORKSPACE',
workspaceRoot: '',
gitBranch: 'main',
activeActivity: 'files', // 'files' | 'search' | 'scm' | 'run' | 'extensions'
activeTab: null,
openTabs: [],
openEditorsExpanded: false,
outlineExpanded: false,
timelineExpanded: false,
isRootExpanded: true,
files: {}, // path -> { type, language, content, baselineContent, dirty, handle }
directories: new Set(),
expandedFolders: new Set(),
selectedPath: null,
isExplorerFocused: false,
// Inline creation or rename in Explorer: { mode: 'create'|'rename', type: 'file'|'folder', parentPath, targetPath, initialValue }
inlineInput: null,
// Search view state
searchQuery: '',
replaceQuery: '',
searchReplaceExpanded: true,
searchCaseSensitive: false,
searchWholeWord: false,
searchRegex: false,
searchPreserveCase: false,
searchCollapsedFiles: new Set(),
searchResults: [],
// Source Control & GitHub Auth state
commitMessage: '',
scmInitializedInSession: false,
scmChangesExpanded: true,
scmStagedExpanded: true,
scmSubChangesExpanded: true,
scmGraphExpanded: true,
gitIsRepo: false,
gitBranches: ['main'],
gitRemoteUrl: localStorage.getItem('litecode_gh_remote') || '',
gitAhead: 0,
gitBehind: 0,
gitStaged: [], // [{ path, status }]
gitUnstaged: [], // [{ path, status }]
gitUserName: 'ab-613',
gitUserEmail: '',
githubAuthenticatedUser: localStorage.getItem('litecode_gh_user') || '',
githubToken: localStorage.getItem('litecode_gh_token') || '',
githubRepos: [],
gitCommits: [
{ hash: '1d08d22', message: 'rebrand project to LiteCode and remove old branding', author: 'ab-613' },
{ hash: '4c2e10b', message: 'first commit', author: 'ab-613' }
],
// Extensions Marketplace state
extSearchQuery: '',
extInstalledExpanded: false,
extPopularExpanded: true,
extRecommendedExpanded: true,
installedExtensions: new Set(['python', 'prettier']),
// Layout & Panels
layout: {
sidebarVisible: true,
sidebarWidth: 220,
panelVisible: true,
terminalHeight: 190,
panelMaximized: false,
aiPanelVisible: true,
aiPanelWidth: 285
},
activePanelTab: 'Terminal', // 'Problems' | 'Output' | 'Terminal' | 'Ports'
outputLogs: [],
// Editor settings & live cursor/diagnostics
editorSettings: {
theme: localStorage.getItem('litecode_theme') || 'vs-dark',
fontSize: parseInt(localStorage.getItem('litecode_editor_fontsize') || '12', 10),
wordWrap: localStorage.getItem('litecode_wordwrap') || 'off',
minimap: localStorage.getItem('litecode_minimap') === 'true',
lineNumbers: 'on',
tabSize: 4
},
cursorPos: { lineNumber: 1, column: 1, selectedChars: 0 },
diagnostics: [], // { path, message, severity, startLineNumber, startColumn }
// Dev server & preview
activePort: null,
activePreviewUrl: null,
// AI & Modals
aiChangeFiles: new Set(),
attachedFiles: new Set(),
closedTabsHistory: [],
fileClipboard: null, // { mode: 'copy'|'cut', path, isFolder }
activeMenuDropdown: null, // 'File' | 'Edit' | ...
paletteMode: 'files', // 'files' (Ctrl+P) | 'commands' (Ctrl+Shift+P)
paletteFilter: '',
paletteSelectedIndex: 0
};
let monacoEditorInstance = null;
let isMonacoInitialized = false;
let isInternalChange = false;
const monacoModels = new Map(); // path -> ITextModel
const monacoViewStates = new Map(); // path -> ICodeEditorViewState
let activeDecorations = [];
let webcontainerInstance = null;
let terminalProcess = null;
function logOutput(msg, category = 'IDE') {
const time = new Date().toLocaleTimeString();
appState.outputLogs.push(`[${time}] [${category}] ${msg}`);
if (appState.outputLogs.length > 300) appState.outputLogs.shift();
if (appState.activePanelTab === 'Output') renderPanelBodyContent();
}
/* --- 2. DOM HELPER & LIGHT-DISMISS DIALOG HELPER --- */
function el(tag, attributes = {}, children = []) {
const element = document.createElement(tag);
for (const [key, value] of Object.entries(attributes)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class' || key === 'className') element.className = value;
else if (key === 'style') element.style.cssText = value;
else if (key.startsWith('on') && typeof value === 'function') element[key.toLowerCase()] = value;
else if (value === true) element.setAttribute(key, '');
else element.setAttribute(key, value);
}
if (!Array.isArray(children)) children = [children];
children.forEach(child => {
if (child === null || child === undefined || child === false) return;
if (typeof child === 'string' || typeof child === 'number') {
element.appendChild(document.createTextNode(String(child)));
} else if (child instanceof Node) {
element.appendChild(child);
}
});
return element;
}
// Modern <dialog closedby="any"> fallback for browsers without native closedBy support
function attachDialogLightDismissFallback(dialog) {
if (!dialog || dialog._hasLightDismissFallback) return;
dialog._hasLightDismissFallback = true;
if (!('closedBy' in HTMLDialogElement.prototype)) {
dialog.addEventListener('click', (event) => {
if (event.target !== dialog) return;
const rect = dialog.getBoundingClientRect();
const isDialogContent = (
rect.top <= event.clientY &&
event.clientY <= rect.top + rect.height &&
rect.left <= event.clientX &&
event.clientX <= rect.left + rect.width
);
if (isDialogContent) return;
dialog.close();
});
}
}
/* --- 3. FILE ICONS & LANGUAGE DETECTION --- */
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-globe', style: 'margin-right: 6px; font-size: 14px; color: #4fc1ff;' });
}
const name = filename.split('/').pop();
const parts = name.split('.');
const ext = parts.length > 1 ? parts.pop().toLowerCase() : name.toLowerCase();
const nameLower = name.toLowerCase();
const nameMap = {
'dockerfile': 'dockerfile-lang-file-icon',
'makefile': 'makefile-lang-file-icon',
'package.json': 'json-lang-file-icon',
'tsconfig.json': 'json-lang-file-icon',
'.gitignore': 'ignore-lang-file-icon',
'gitignore': 'ignore-lang-file-icon',
'license': 'license-name-file-icon name-file-icon'
};
if (nameMap[nameLower]) return el('span', { class: `file-icon ${nameMap[nameLower]}` });
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',
'scss': 'scss-lang-file-icon',
'less': 'less-lang-file-icon',
'json': 'json-lang-file-icon',
'py': 'python-lang-file-icon',
'cpp': 'cpp-lang-file-icon',
'c': 'c-lang-file-icon',
'h': 'h-ext-file-icon ext-file-icon',
'cs': 'csharp-lang-file-icon',
'java': 'java-lang-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',
'svg': 'svg-ext-file-icon ext-file-icon',
'sh': 'shellscript-lang-file-icon',
'bat': 'bat-lang-file-icon',
'ps1': 'powershell-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',
'txt': 'txt-ext-file-icon ext-file-icon'
};
const iconClass = extMap[ext] || 'txt-ext-file-icon ext-file-icon';
return el('span', { class: `file-icon ${iconClass}` });
}
function getLangForFilename(filename) {
if (!filename) return 'plaintext';
const name = filename.split('/').pop().toLowerCase();
if (name === 'dockerfile') return 'dockerfile';
if (name === 'makefile') return 'makefile';
const ext = name.includes('.') ? name.split('.').pop() : '';
const map = {
js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript',
ts: 'typescript', tsx: 'typescript',
html: 'html', htm: 'html', svg: 'xml', xml: 'xml',
css: 'css', scss: 'scss', less: 'less',
py: 'python', json: 'json', jsonc: 'json',
md: 'markdown', markdown: 'markdown',
rs: 'rust', go: 'go', cpp: 'cpp', cc: 'cpp', c: 'c', h: 'cpp', hpp: 'cpp',
cs: 'csharp', java: 'java', php: 'php', rb: 'ruby',
sh: 'shell', bash: 'shell', zsh: 'shell', ps1: 'powershell', bat: 'bat',
yaml: 'yaml', yml: 'yaml', toml: 'ini', ini: 'ini',
sql: 'sql', lua: 'lua'
};
return map[ext] || 'plaintext';
}
function getPrettyLanguageName(lang) {
const names = {
javascript: 'JavaScript', typescript: 'TypeScript', html: 'HTML', css: 'CSS',
scss: 'SCSS', less: 'Less', python: 'Python', json: 'JSON', markdown: 'Markdown',
rust: 'Rust', go: 'Go', cpp: 'C/C++', c: 'C', csharp: 'C#', java: 'Java',
php: 'PHP', ruby: 'Ruby', shell: 'Shell Script', powershell: 'PowerShell',
bat: 'Batch', yaml: 'YAML', xml: 'XML', sql: 'SQL', dockerfile: 'Dockerfile',
plaintext: 'Plain Text'
};
return names[lang] || lang;
}
/* --- 4. DUAL-MODE FILE SYSTEM MANAGER (DESKTOP + BROWSER) --- */
const STARTER_FILES = {
'README.md': `# Welcome to LiteCode ⚡\n\nLiteCode is an ultra-fast, zero-bloat IDE built with pure Vanilla JS, Monaco Editor, and xterm.js.\n\n## Key Shortcuts\n- **Quick Open File:** \`Ctrl+P\`\n- **Command Palette:** \`Ctrl+Shift+P\` or \`F1\`\n- **Save File:** \`Ctrl+S\`\n- **Open Live Preview:** \`Ctrl+Shift+V\`\n- **Toggle Sidebar:** \`Ctrl+B\`\n- **Toggle Terminal:** \`Ctrl+\`\`\n- **Toggle AI Assistant:** \`Ctrl+Alt+B\`\n`,
'examples/web-app/index.html': `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8" />\n <title>LiteCode Live Preview Demo</title>\n <link rel="stylesheet" href="styles.css" />\n</head>\n<body>\n <h1>Hello from LiteCode ⚡</h1>\n <script src="app.js"></script>\n</body>\n</html>\n`,
'examples/web-app/styles.css': `body {\n font-family: system-ui, -apple-system, sans-serif;\n background: #0f1117;\n color: #e6edf3;\n margin: 0;\n padding: 2rem;\n}\n`,
'examples/web-app/app.js': `console.log('⚡ LiteCode Web App Example Ready');\n`,
'examples/node-quickstart.js': `console.log('⚡ LiteCode Node.js Runner:', process.version);\n`
};
const FSManager = {
localDirHandle: null,
applyGitInfo(git) {
if (!git) return;
if (typeof git.isRepo === 'boolean') appState.gitIsRepo = git.isRepo;
if (git.branch) appState.gitBranch = git.branch;
if (Array.isArray(git.branches) && git.branches.length > 0) appState.gitBranches = git.branches;
if (typeof git.remoteUrl === 'string') appState.gitRemoteUrl = git.remoteUrl;
if (typeof git.ahead === 'number') appState.gitAhead = git.ahead;
if (typeof git.behind === 'number') appState.gitBehind = git.behind;
if (Array.isArray(git.staged)) appState.gitStaged = git.staged;
if (Array.isArray(git.unstaged)) appState.gitUnstaged = git.unstaged;
if (git.userName) appState.gitUserName = git.userName;
if (git.userEmail) appState.gitUserEmail = git.userEmail;
if (Array.isArray(git.commits)) {
appState.gitCommits = git.commits;
}
},
async init() {
// 1. Check if Desktop Native Backend (server.py) is active
try {
const pingRes = await fetch('/api/ping', { cache: 'no-store' });
if (pingRes.ok) {
const pingData = await pingRes.json();
if (pingData && pingData.mode === 'desktop') {
appState.runtimeMode = 'desktop';
appState.workspaceName = pingData.workspaceName || 'WORKSPACE';
appState.workspaceRoot = pingData.workspaceRoot || '';
this.applyGitInfo(pingData.git);
logOutput(`Connected to Native Desktop Backend (${pingData.platform})`, 'System');
await this.loadDesktopWorkspace();
return;
}
}
} catch (e) {
// Not running desktop server.py; use Browser mode
}
appState.runtimeMode = 'browser';
logOutput('Running in Browser Mode (File System API + WebContainer)', 'System');
// 2. Try restoring saved FileSystemDirectoryHandle from IndexedDB
if (typeof idbKeyval !== 'undefined') {
try {
const savedHandle = await idbKeyval.get('litecode_workspace_handle');
if (savedHandle && savedHandle.queryPermission) {
const perm = await savedHandle.queryPermission({ mode: 'readwrite' });
if (perm === 'granted') {
await this.loadBrowserDirectoryHandle(savedHandle);
return;
}
}
} catch (e) { /* Ignore handle restore error */ }
// 3. Otherwise load Virtual IndexedDB Workspace (or seed starter files)
try {
const virtualFiles = await idbKeyval.get('litecode_virtual_files');
const virtualDirs = await idbKeyval.get('litecode_virtual_dirs');
if (virtualFiles && Object.keys(virtualFiles).length > 0) {
this.populateStateFromMap(virtualFiles, virtualDirs || ['src'], 'VIRTUAL WORKSPACE');
return;
}
} catch (e) { /* Ignore */ }
}
// 4. First boot in browser: load starter files immediately so editor works out of the box!
this.populateStateFromMap(STARTER_FILES, ['src'], 'LITECODE-STARTER');
await this.persistVirtualWorkspace();
},
populateStateFromMap(fileMap, dirs = [], workspaceName = 'WORKSPACE') {
appState.files = {};
appState.directories = new Set(dirs);
appState.workspaceName = workspaceName;
for (const [path, raw] of Object.entries(fileMap)) {
const content = typeof raw === 'string' ? raw : (raw.content ?? '');
const isLazy = Boolean(typeof raw === 'object' && raw && raw.lazy);
const lang = getLangForFilename(path);
appState.files[path] = {
type: path.split('.').pop(),
language: lang,
content,
baselineContent: content,
dirty: false,
lazy: isLazy,
handle: null
};
const parts = path.split('/');
for (let i = 1; i < parts.length; i++) {
appState.directories.add(parts.slice(0, i).join('/'));
}
if (parts.length > 1) appState.expandedFolders.add(parts[0]);
}
const firstFile = appState.files['README.md'] ? 'README.md' : Object.keys(appState.files)[0];
if (firstFile && appState.openTabs.length === 0) {
appState.openTabs = [firstFile];
switchFile(firstFile);
} else {
updateUI();
}
},
async ensureFileLoaded(path) {
const entry = appState.files[path];
if (!entry || !entry.lazy || appState.runtimeMode !== 'desktop') return;
try {
const res = await fetch(`/api/read?path=${encodeURIComponent(path)}`, { cache: 'no-store' });
if (!res.ok) return;
const data = await res.json();
if (data && data.ok && typeof data.content === 'string') {
entry.content = data.content;
entry.baselineContent = data.content;
entry.lazy = false;
EditorManager.syncModelContent(path, data.content);
updateUI();
}
} catch (err) {
logOutput(`Failed to lazy-load ${path}: ${err.message}`, 'Error');
}
},
async persistVirtualWorkspace() {
if (appState.runtimeMode !== 'browser' || this.localDirHandle || typeof idbKeyval === 'undefined') return;
const plainFiles = {};
for (const [k, v] of Object.entries(appState.files)) {
plainFiles[k] = v.content;
}
await idbKeyval.set('litecode_virtual_files', plainFiles);
await idbKeyval.set('litecode_virtual_dirs', Array.from(appState.directories));
},
async loadDesktopWorkspace() {
try {
appState.isLoading = true;
updateUI();
const res = await fetch('/api/workspace', { cache: 'no-store' });
const data = await res.json();
appState.workspaceName = data.workspaceName || 'WORKSPACE';
appState.workspaceRoot = data.workspaceRoot || '';
this.applyGitInfo(data.git);
EditorManager.disposeAllModels();
appState.openTabs = [];
appState.activeTab = null;
this.populateStateFromMap(data.files || {}, data.directories || [], appState.workspaceName);
appState.isLoading = false;
logOutput(`Loaded ${Object.keys(appState.files).length} files from ${appState.workspaceRoot}`, 'FS');
updateUI();
} catch (err) {
appState.isLoading = false;
logOutput(`Failed to load desktop workspace: ${err.message}`, 'Error');
updateUI();
}
},
async syncDesktopWorkspaceSilent() {
try {
const res = await fetch('/api/workspace', { cache: 'no-store' });
if (!res.ok) return;
const data = await res.json();
this.applyGitInfo(data.git);
const diskFiles = data.files || {};
const diskDirs = new Set(data.directories || []);
let treeChanged = false;
// 1. Add or update files from disk without closing tabs or resetting models
for (const [path, raw] of Object.entries(diskFiles)) {
const content = typeof raw === 'string' ? raw : (raw.content ?? '');
const isLazy = Boolean(typeof raw === 'object' && raw && raw.lazy);
const existing = appState.files[path];
if (!existing) {
treeChanged = true;
appState.files[path] = {
type: path.split('.').pop(),
language: getLangForFilename(path),
content,
baselineContent: content,
dirty: false,
lazy: isLazy,
handle: null
};
const parts = path.split('/');
for (let i = 1; i < parts.length; i++) {
diskDirs.add(parts.slice(0, i).join('/'));
}
} else if (!existing.dirty && !isLazy && existing.content !== content) {
existing.content = content;
existing.baselineContent = content;
existing.lazy = false;
EditorManager.syncModelContent(path, content);
}
}
// 2. Remove deleted files from state (only closing a tab if that specific file was deleted)
for (const oldPath of Object.keys(appState.files)) {
if (!(oldPath in diskFiles)) {
treeChanged = true;
delete appState.files[oldPath];
EditorManager.disposeModel(oldPath);
if (appState.openTabs.includes(oldPath)) {
appState.openTabs = appState.openTabs.filter(t => t !== oldPath);
if (appState.activeTab === oldPath) {
appState.activeTab = appState.openTabs[appState.openTabs.length - 1] || null;
if (appState.activeTab && appState.files[appState.activeTab]) {
EditorManager.activateFileModel(appState.activeTab);
}
updateEditorVisibility();
}
}
}
}
if (diskDirs.size !== appState.directories.size) treeChanged = true;
appState.directories = diskDirs;
if (treeChanged) {
updateSidebarContentOnly();
const tabsContainer = document.getElementById('tabs-container');
if (tabsContainer) tabsContainer.replaceWith(renderTabs());
}
updateStatusBarOnly();
} catch (err) {
// Silent background sync ignore
}
},
async requestWorkspace() {
if (appState.runtimeMode === 'desktop') {
try {
const res = await fetch('/api/set_workspace', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pick: true })
});
const data = await res.json();
if (data.cancelled) return;
if (data.ok) {
appState.workspaceName = data.workspaceName || 'WORKSPACE';
appState.workspaceRoot = data.workspaceRoot || '';
if (data.git && data.git.branch) appState.gitBranch = data.git.branch;
EditorManager.disposeAllModels();
appState.openTabs = [];
appState.activeTab = null;
this.populateStateFromMap(data.files || {}, data.directories || [], appState.workspaceName);
logOutput(`Switched workspace to ${appState.workspaceRoot}`, 'FS');
updateUI();
return;
}
} catch (e) {
console.warn('Desktop folder picker fallback:', e);
}
}
// Browser File System Access API
if (typeof window.showDirectoryPicker === 'function') {
try {
const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
if (typeof idbKeyval !== 'undefined') {
await idbKeyval.set('litecode_workspace_handle', handle);
}
await this.loadBrowserDirectoryHandle(handle);
} catch (err) {
if (err.name !== 'AbortError') logOutput(`Folder open cancelled: ${err.message}`, 'FS');
}
} else {
alert('Your browser does not support showDirectoryPicker. Using built-in persistent virtual workspace.');
}
},
async loadBrowserDirectoryHandle(dirHandle) {
try {
this.localDirHandle = dirHandle;
EditorManager.disposeAllModels();
appState.files = {};
appState.directories = new Set();
appState.openTabs = [];
appState.activeTab = null;
appState.workspaceName = dirHandle.name || 'WORKSPACE';
appState.isLoading = true;
updateUI();
const wcTree = {};
await this.readBrowserDirectory(dirHandle, '', wcTree);
if (webcontainerInstance) {
try { await webcontainerInstance.mount(wcTree); } catch (e) { console.warn(e); }
}
for (const key of Object.keys(appState.files)) {
const parts = key.split('/');
if (parts.length > 1) appState.expandedFolders.add(parts[0]);
}
appState.isLoading = false;
logOutput(`Mounted local folder "${dirHandle.name}" (${Object.keys(appState.files).length} files)`, 'FS');
updateUI();
} catch (err) {
appState.isLoading = false;
logOutput(`Workspace load error: ${err.message}`, 'Error');
updateUI();
}
},
async readBrowserDirectory(dirHandle, pathPrefix, wcTree) {
for await (const entry of dirHandle.values()) {
const fullPath = pathPrefix ? `${pathPrefix}/${entry.name}` : entry.name;
if (entry.kind === 'directory') {
if (/^(node_modules|\.git|\.next|dist|build|__pycache__|target)$/.test(entry.name)) continue;
appState.directories.add(fullPath);
wcTree[entry.name] = { directory: {} };
await this.readBrowserDirectory(entry, fullPath, wcTree[entry.name].directory);
} else if (entry.kind === 'file') {
try {
const file = await entry.getFile();
if (file.size > 2 * 1024 * 1024) 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: getLangForFilename(fullPath),
content,
baselineContent: content,
dirty: false,
handle: entry
};
} catch (e) { /* Skip unreadable binary/locked file */ }
}
}
},
async writeFile(filename, content, source = 'ui') {
const cleanPath = filename.replace(/^\/+/, '');
const safeContent = content === undefined || content === null ? '' : String(content);
const oldFile = appState.files[cleanPath];
let fileHandle = oldFile ? oldFile.handle : null;
// Ensure parent folders are tracked in appState.directories
const parts = cleanPath.split('/');
for (let i = 1; i < parts.length; i++) {
const dir = parts.slice(0, i).join('/');
appState.directories.add(dir);
appState.expandedFolders.add(dir);
}
// 1. Desktop Mode: Write directly to disk via server.py
if (appState.runtimeMode === 'desktop') {
await fetch('/api/write', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: cleanPath, content: safeContent })
});
} else {
// 2. Browser Mode with Local Directory Handle
if (!fileHandle && this.localDirHandle) {
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 });
}
if (fileHandle) {
const writable = await fileHandle.createWritable();
await writable.write(safeContent);
await writable.close();
}
// 3. Update WebContainer if running
if (webcontainerInstance) {
try {
const dirPath = parts.slice(0, -1).join('/');
if (dirPath) await webcontainerInstance.fs.mkdir(`/${dirPath}`, { recursive: true });
await webcontainerInstance.fs.writeFile(`/${cleanPath}`, safeContent);
} catch (e) { /* Ignore WC write error */ }
}
}
appState.files[cleanPath] = {
type: cleanPath.split('.').pop(),
language: getLangForFilename(cleanPath),
content: safeContent,
baselineContent: oldFile ? oldFile.baselineContent : safeContent,
dirty: false,
handle: fileHandle
};
if (source === 'ai') {
appState.aiChangeFiles.add(cleanPath);
}
await this.persistVirtualWorkspace();
// Sync Monaco model content
EditorManager.syncModelContent(cleanPath, safeContent);
logOutput(`Saved ${cleanPath}`, 'FS');
updateUI();
},
async createFolder(folderPath) {
const cleanPath = folderPath.replace(/^\/+|\/+$/g, '');
if (!cleanPath) return;
const parts = cleanPath.split('/');
for (let i = 1; i <= parts.length; i++) {
const sub = parts.slice(0, i).join('/');
appState.directories.add(sub);
appState.expandedFolders.add(sub);
}
if (appState.runtimeMode === 'desktop') {
await fetch('/api/mkdir', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: cleanPath })
});
} else {
if (this.localDirHandle) {
let currentHandle = this.localDirHandle;
for (const part of parts) {
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
}
}
if (webcontainerInstance) {
try { await webcontainerInstance.fs.mkdir(`/${cleanPath}`, { recursive: true }); } catch (e) {}
}
await this.persistVirtualWorkspace();
}
appState.selectedPath = cleanPath;
logOutput(`Created folder ${cleanPath}`, 'FS');
updateUI();
},
async deleteItem(targetPath) {
const cleanPath = targetPath.replace(/^\/+/, '');
if (!cleanPath) return;
const isFolder = appState.directories.has(cleanPath) ||
Object.keys(appState.files).some(f => f.startsWith(cleanPath + '/'));
if (appState.runtimeMode === 'desktop') {
await fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: cleanPath })
});
} else {
if (this.localDirHandle) {
try {
const parts = cleanPath.split('/');
let currentHandle = this.localDirHandle;
for (let i = 0; i < parts.length - 1; i++) {
currentHandle = await currentHandle.getDirectoryHandle(parts[i]);
}
await currentHandle.removeEntry(parts[parts.length - 1], { recursive: true });
} catch (e) { console.warn('OS delete warning:', e); }
}
if (webcontainerInstance) {
try { await webcontainerInstance.fs.rm(`/${cleanPath}`, { recursive: true, force: true }); } catch (e) {}
}
}
// Remove from appState & Monaco models
if (isFolder) {
for (const dir of Array.from(appState.directories)) {
if (dir === cleanPath || dir.startsWith(cleanPath + '/')) {
appState.directories.delete(dir);
appState.expandedFolders.delete(dir);
}
}
for (const file of Object.keys(appState.files)) {
if (file.startsWith(cleanPath + '/')) {
delete appState.files[file];
EditorManager.disposeModel(file);
appState.openTabs = appState.openTabs.filter(t => t !== file);
if (appState.activeTab === file) appState.activeTab = appState.openTabs[0] || null;
}
}
} else {
delete appState.files[cleanPath];
EditorManager.disposeModel(cleanPath);
appState.openTabs = appState.openTabs.filter(t => t !== cleanPath);
if (appState.activeTab === cleanPath) {
const next = appState.openTabs[appState.openTabs.length - 1] || null;
appState.activeTab = null;
if (next) switchFile(next);
}
}
await this.persistVirtualWorkspace();
logOutput(`Deleted ${cleanPath}`, 'FS');
updateUI();
},
async renameItem(oldPath, newPath) {
const cleanOld = oldPath.replace(/^\/+/, '');
const cleanNew = newPath.replace(/^\/+/, '');
if (!cleanOld || !cleanNew || cleanOld === cleanNew) return;
const isFolder = appState.directories.has(cleanOld);
if (appState.runtimeMode === 'desktop') {
await fetch('/api/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ oldPath: cleanOld, newPath: cleanNew })
});
await this.loadDesktopWorkspace();
return;
}
if (isFolder) {
await this.createFolder(cleanNew);
for (const [filePath, fileObj] of Object.entries({ ...appState.files })) {
if (filePath.startsWith(cleanOld + '/')) {
const sub = cleanNew + filePath.slice(cleanOld.length);
await this.writeFile(sub, fileObj.content);
}
}
await this.deleteItem(cleanOld);
} else if (appState.files[cleanOld]) {
const content = appState.files[cleanOld].content;
const wasActive = appState.activeTab === cleanOld;
const tabIdx = appState.openTabs.indexOf(cleanOld);
await this.writeFile(cleanNew, content);
if (tabIdx !== -1) appState.openTabs[tabIdx] = cleanNew;
await this.deleteItem(cleanOld);
if (wasActive) switchFile(cleanNew);
}
updateUI();
},
startInlineCreate(type, explicitFolder = null) {
let parentPath = '';
if (explicitFolder !== null) {
parentPath = explicitFolder === 'ROOT' ? '' : explicitFolder;
} else if (appState.selectedPath && appState.selectedPath !== 'ROOT') {
if (appState.directories.has(appState.selectedPath)) {
parentPath = appState.selectedPath;
} else {
const parts = appState.selectedPath.split('/');
parts.pop();
parentPath = parts.join('/');
}
}
if (parentPath) {
appState.expandedFolders.add(parentPath);
appState.isRootExpanded = true;
}
appState.activeActivity = 'files';
appState.layout.sidebarVisible = true;
appState.inlineInput = {
mode: 'create',
type,
parentPath,
initialValue: ''
};
updateUI();
setTimeout(() => {
const input = document.getElementById('explorer-inline-input');
if (input) input.focus();
}, 15);
},
startInlineRename(targetPath) {
if (!targetPath || targetPath === 'ROOT') return;
const isFolder = appState.directories.has(targetPath);
const parts = targetPath.split('/');
const baseName = parts.pop();
const parentPath = parts.join('/');
appState.inlineInput = {
mode: 'rename',
type: isFolder ? 'folder' : 'file',
parentPath,
targetPath,
initialValue: baseName
};
updateUI();
setTimeout(() => {
const input = document.getElementById('explorer-inline-input');
if (input) {
input.focus();
const dotIdx = baseName.lastIndexOf('.');
input.setSelectionRange(0, dotIdx > 0 ? dotIdx : baseName.length);
}
}, 15);
},
async commitInlineInput(value) {
if (!appState.inlineInput) return;
const info = { ...appState.inlineInput };
appState.inlineInput = null;
const trimmed = (value || '').trim();
if (!trimmed) {
updateUI();
return;
}
const fullNewPath = info.parentPath ? `${info.parentPath}/${trimmed}` : trimmed;
try {
if (info.mode === 'create') {
if (info.type === 'file') {
await this.writeFile(fullNewPath, '');
openFileFromSidebar(null, fullNewPath);
} else {
await this.createFolder(fullNewPath);
}
} else if (info.mode === 'rename') {
if (fullNewPath !== info.targetPath) {
await this.renameItem(info.targetPath, fullNewPath);
} else {
updateUI();
}
}
} catch (err) {
logOutput(`File operation error: ${err.message}`, 'Error');
updateUI();
}
},
cancelInlineInput() {
if (!appState.inlineInput) return;
appState.inlineInput = null;
updateUI();
},
async refreshWorkspace() {
if (appState.runtimeMode === 'desktop') {
await this.syncDesktopWorkspaceSilent();
} else {
await this.syncRuntimeToState();
}
},
async syncRuntimeToState() {
if (appState.runtimeMode === 'desktop') {
await this.syncDesktopWorkspaceSilent();
return;
}
if (!webcontainerInstance) return;
const scanWc = async (dirPath, localHandle) => {
let entries = [];
try {
entries = await webcontainerInstance.fs.readdir(dirPath, { withFileTypes: true });
} catch (e) { return; }
for (const entry of entries) {
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 (!appState.files[fullWcPath] || appState.files[fullWcPath].content !== content) {
let fileHandle = null;
if (localHandle) {
fileHandle = await localHandle.getFileHandle(entry.name, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(content);
await writable.close();
}
appState.files[fullWcPath] = {
type: entry.name.split('.').pop(),
language: getLangForFilename(fullWcPath),
content,
baselineContent: content,
dirty: false,
handle: fileHandle
};
EditorManager.syncModelContent(fullWcPath, content);
}
} else if (entry.isDirectory()) {
appState.directories.add(fullWcPath);
let nextHandle = null;
if (localHandle) {
nextHandle = await localHandle.getDirectoryHandle(entry.name, { create: true });
}
await scanWc(fullWcPath, nextHandle);
}
}
};
await scanWc('.', this.localDirHandle);
await this.persistVirtualWorkspace();
updateUI();
},
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;
}
};
/* --- 5. MULTI-MODEL MONACO EDITOR MANAGER --- */
const EditorManager = {
init() {
if (isMonacoInitialized) return;
isMonacoInitialized = true;
require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
require(['vs/editor/editor.main'], () => {