-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
executable file
·808 lines (711 loc) · 27.9 KB
/
Copy patheditor.js
File metadata and controls
executable file
·808 lines (711 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
// the main state
const state = {
workspace: null, // root folder path
openFiles: [], // [{ path, name, content, modified }]
activeFile: null, // path string
aiOpen: false,
aiMessages: [], // [{ role, content }]
editor: null, // codemirror
suppressChange: false,
};
// all languages
const LANG_MAP = {
js: { mode: 'javascript', label: 'JavaScript' },
jsx: { mode: 'javascript', label: 'JSX' },
ts: { mode: 'javascript', label: 'TypeScript' },
tsx: { mode: 'javascript', label: 'TSX' },
json: { mode: { name: 'javascript', json: true }, label: 'JSON' },
py: { mode: 'python', label: 'Python' },
css: { mode: 'css', label: 'CSS' },
html: { mode: 'htmlmixed', label: 'HTML' },
xml: { mode: 'xml', label: 'XML' },
md: { mode: 'markdown', label: 'Markdown' },
sh: { mode: 'shell', label: 'Shell' },
bash: { mode: 'shell', label: 'Bash' },
txt: { mode: null, label: 'Text' },
};
function getLang(filename) {
const ext = filename.split('.').pop().toLowerCase();
return LANG_MAP[ext] || { mode: null, label: ext.toUpperCase() || 'Text' };
}
// icons (made using my own custom emojis/past icons btw)
function fileIcon(name, isDir) {
if (isDir) return '📁';
const ext = name.split('.').pop().toLowerCase();
const icons = {
js: '🟨', jsx: '⚛', ts: '🔷', tsx: '⚛',
json: '{}', py: '🐍', css: '🎨', html: '🌐',
md: '📝', sh: '💲', txt: '📄', xml: '🗂',
png: '🖼', jpg: '🖼', jpeg: '🖼', svg: '🖼',
gif: '🖼', pdf: '📕', zip: '📦', tar: '📦',
};
return icons[ext] || '📄';
}
// --- The "Get Started" window
function closeTutorial() {
const overlay = document.getElementById('tutorial-overlay');
overlay.style.animation = 'fadeIn 0.2s ease reverse';
setTimeout(() => overlay.remove(), 200);
}
// <<toast>> notifications
function toast(msg, type = 'info', duration = 3000) {
const icons = { success: '✓', error: '✕', info: '◈' };
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = `toast ${type}`;
el.innerHTML = `<span class="toast-icon">${icons[type]}</span><span>${msg}</span>`;
container.appendChild(el);
setTimeout(() => {
el.style.animation = 'toastIn 0.2s ease reverse';
setTimeout(() => el.remove(), 200);
}, duration);
}
// just the codemirror setup, pretty boring idk
function initEditor() {
state.editor = CodeMirror.fromTextArea(document.getElementById('cm-editor'), {
lineNumbers: true,
theme: 'default',
mode: 'javascript',
autoCloseBrackets: true,
matchBrackets: true,
styleActiveLine: true,
indentWithTabs: false,
indentUnit: 2,
tabSize: 2,
lineWrapping: false,
extraKeys: {
'Ctrl-S': saveCurrentFile,
'Cmd-S': saveCurrentFile,
'Ctrl-/': (cm) => cm.toggleComment(),
'Tab': (cm) => {
if (cm.somethingSelected()) cm.indentSelection('add');
else cm.replaceSelection(' ');
}
}
});
state.editor.on('change', () => {
if (state.suppressChange) return;
if (!state.activeFile) return;
const file = state.openFiles.find(f => f.path === state.activeFile);
if (file && !file.modified) {
file.modified = true;
renderTabs();
}
});
state.editor.on('cursorActivity', () => {
const cursor = state.editor.getCursor();
document.getElementById('status-cursor').textContent =
`Ln ${cursor.line + 1}, Col ${cursor.ch + 1}`;
});
// Resize observer
const resizeObserver = new ResizeObserver(() => state.editor.refresh());
resizeObserver.observe(document.getElementById('editor-container'));
}
// The important part of an editor:
// The file tree! obvious, right...right?
async function loadFileTree(dirPath, container, depth = 0) {
const result = await window.electron.readDir(dirPath);
if (!result.success) return;
const entries = result.entries.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.localeCompare(b.name);
});
for (const entry of entries) {
if (entry.name.startsWith('.') && entry.name !== '.env') continue;
const item = document.createElement('div');
item.className = `tree-item ${entry.isDirectory ? 'folder' : 'file'}`;
item.dataset.path = entry.path;
item.dataset.isDir = entry.isDirectory;
// the indent (as displayed in its name)
let indentHtml = '';
for (let i = 0; i < depth; i++) indentHtml += '<span class="tree-indent"></span>';
if (entry.isDirectory) {
item.innerHTML = `
${indentHtml}
<span class="tree-chevron">▶</span>
<span class="tree-icon">${fileIcon(entry.name, true)}</span>
<span class="tree-name">${entry.name}</span>
`;
const children = document.createElement('div');
children.className = 'tree-children';
item.addEventListener('click', async (e) => {
e.stopPropagation();
const isOpen = children.classList.contains('open');
const chevron = item.querySelector('.tree-chevron');
if (isOpen) {
children.classList.remove('open');
chevron.classList.remove('open');
item.classList.remove('open');
children.innerHTML = '';
} else {
children.classList.add('open');
chevron.classList.add('open');
item.classList.add('open');
await loadFileTree(entry.path, children, depth + 1);
}
});
item.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e, entry.path, true);
});
container.appendChild(item);
container.appendChild(children);
} else {
item.innerHTML = `
${indentHtml}
<span class="tree-chevron" style="visibility:hidden">▶</span>
<span class="tree-icon">${fileIcon(entry.name, false)}</span>
<span class="tree-name">${entry.name}</span>
`;
if (state.activeFile === entry.path) item.classList.add('active');
item.addEventListener('click', () => openFile(entry.path));
item.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e, entry.path, false);
});
container.appendChild(item);
}
}
}
async function refreshTree() {
if (!state.workspace) return;
const tree = document.getElementById('file-tree');
tree.innerHTML = '';
await loadFileTree(state.workspace, tree);
updateActiveInTree();
}
function updateActiveInTree() {
document.querySelectorAll('.tree-item.active').forEach(el => el.classList.remove('active'));
if (!state.activeFile) return;
const item = document.querySelector(`.tree-item[data-path="${CSS.escape(state.activeFile)}"]`);
if (item) item.classList.add('active');
}
// func to open a folder
async function openFolder() {
const folderPath = await window.electron.openFolder();
if (!folderPath) return;
state.workspace = folderPath;
const name = folderPath.split(/[\\/]/).pop();
document.getElementById('workspace-name').textContent = name;
document.getElementById('status-workspace').textContent = name;
await refreshTree();
toast(`Opened: ${name}`, 'success');
}
// file: open | close | save
async function openFile(filePath) {
// already open? then uh idk
const existing = state.openFiles.find(f => f.path === filePath);
if (existing) {
setActiveFile(filePath);
return;
}
const result = await window.electron.readFile(filePath);
if (!result.success) {
toast(`Cannot open file: ${result.error}`, 'error');
return;
}
const name = filePath.split(/[\\/]/).pop();
state.openFiles.push({ path: filePath, name, content: result.content, modified: false });
setActiveFile(filePath);
}
function setActiveFile(filePath) {
state.activeFile = filePath;
const file = state.openFiles.find(f => f.path === filePath);
if (!file) return;
// Show editor
document.getElementById('editor-empty').classList.add('hidden');
document.getElementById('editor-container').classList.remove('hidden');
// Update codemirror
state.suppressChange = true;
state.editor.setValue(file.content);
const lang = getLang(file.name);
state.editor.setOption('mode', lang.mode || 'null');
state.suppressChange = false;
state.editor.clearHistory();
state.editor.refresh();
// Status bar
document.getElementById('status-file').textContent = file.name;
document.getElementById('status-lang').textContent = lang.label;
// AI context (because yeah, people nowadays cant have editors without ai)
document.getElementById('ai-context-file').textContent = file.name;
renderTabs();
updateActiveInTree();
}
function closeFile(filePath, event) {
if (event) event.stopPropagation();
const idx = state.openFiles.findIndex(f => f.path === filePath);
if (idx === -1) return;
const file = state.openFiles[idx];
if (file.modified) {
if (!confirm(`Save changes to ${file.name}?`)) {
state.openFiles.splice(idx, 1);
} else {
saveFile(filePath).then(() => {
state.openFiles.splice(idx, 1);
afterCloseFile(idx);
});
return;
}
} else {
state.openFiles.splice(idx, 1);
}
afterCloseFile(idx);
}
function afterCloseFile(removedIdx) {
if (state.openFiles.length === 0) {
state.activeFile = null;
document.getElementById('editor-empty').classList.remove('hidden');
document.getElementById('editor-container').classList.add('hidden');
document.getElementById('status-file').textContent = 'No file';
document.getElementById('status-lang').textContent = '—';
document.getElementById('ai-context-file').textContent = 'No file open';
renderTabs();
return;
}
const newIdx = Math.min(removedIdx, state.openFiles.length - 1);
setActiveFile(state.openFiles[newIdx].path);
}
async function saveFile(filePath) {
const file = state.openFiles.find(f => f.path === filePath);
if (!file) return;
const content = state.editor.getValue();
file.content = content;
const result = await window.electron.writeFile(filePath, content);
if (result.success) {
file.modified = false;
renderTabs();
toast(`Saved ${file.name}`, 'success');
} else {
toast(`Save failed: ${result.error}`, 'error');
}
}
async function saveCurrentFile() {
if (!state.activeFile) return;
// Sync content from editor
const file = state.openFiles.find(f => f.path === state.activeFile);
if (file) file.content = state.editor.getValue();
await saveFile(state.activeFile);
}
// theee TABS!
function renderTabs() {
const container = document.getElementById('tabs-container');
container.innerHTML = '';
for (const file of state.openFiles) {
const tab = document.createElement('div');
tab.className = `tab ${file.path === state.activeFile ? 'active' : ''}`;
tab.innerHTML = `
<span class="tab-dot ${file.modified ? 'modified' : ''}"></span>
<span>${file.name}</span>
<span class="tab-close" data-path="${file.path}">×</span>
`;
tab.addEventListener('click', () => setActiveFile(file.path));
tab.querySelector('.tab-close').addEventListener('click', (e) => closeFile(file.path, e));
container.appendChild(tab);
}
}
// the new file/folder part
async function createNewFile() {
if (!state.workspace) { toast('Open a workspace first', 'error'); return; }
const name = prompt('New file name:');
if (!name) return;
const filePath = await window.electron.pathJoin(state.workspace, name);
const result = await window.electron.writeFile(filePath, '');
if (result.success) {
await refreshTree();
await openFile(filePath);
toast(`Created ${name}`, 'success');
} else {
toast(`Error: ${result.error}`, 'error');
}
}
async function createNewFolder() {
if (!state.workspace) { toast('Open a workspace first', 'error'); return; }
const name = prompt('New folder name:');
if (!name) return;
const folderPath = await window.electron.pathJoin(state.workspace, name);
const result = await window.electron.createFolder(folderPath);
if (result.success) {
await refreshTree();
toast(`Created ${name}/`, 'success');
} else {
toast(`Error: ${result.error}`, 'error');
}
}
// this caused me a lot of struggle and still doesnt work
function showContextMenu(e, itemPath, isDir) {
closeContextMenu();
const menu = document.createElement('div');
menu.className = 'context-menu';
menu.id = 'context-menu';
menu.style.left = e.clientX + 'px';
menu.style.top = e.clientY + 'px';
const items = isDir
? [
{ icon: '📄', label: 'New File Here', action: () => newItemInDir(itemPath, false) },
{ icon: '📁', label: 'New Folder Here', action: () => newItemInDir(itemPath, true) },
{ sep: true },
{ icon: '✏️', label: 'Rename', action: () => renameItem(itemPath) },
{ icon: '🗑', label: 'Delete', action: () => deleteItem(itemPath, isDir), danger: true },
]
: [
{ icon: '✏️', label: 'Rename', action: () => renameItem(itemPath) },
{ icon: '🗑', label: 'Delete', action: () => deleteItem(itemPath, isDir), danger: true },
];
for (const item of items) {
if (item.sep) {
const sep = document.createElement('div');
sep.className = 'context-menu-sep';
menu.appendChild(sep);
continue;
}
const el = document.createElement('div');
el.className = `context-menu-item ${item.danger ? 'danger' : ''}`;
el.innerHTML = `<span>${item.icon}</span><span>${item.label}</span>`;
el.addEventListener('click', () => { closeContextMenu(); item.action(); });
menu.appendChild(el);
}
document.body.appendChild(menu);
setTimeout(() => document.addEventListener('click', closeContextMenu, { once: true }), 0);
}
function closeContextMenu() {
const m = document.getElementById('context-menu');
if (m) m.remove();
}
async function newItemInDir(dirPath, isFolder) {
const name = prompt(`New ${isFolder ? 'folder' : 'file'} name:`);
if (!name) return;
const newPath = await window.electron.pathJoin(dirPath, name);
const result = isFolder
? await window.electron.createFolder(newPath)
: await window.electron.writeFile(newPath, '');
if (result.success) {
await refreshTree();
if (!isFolder) await openFile(newPath);
toast(`Created ${name}`, 'success');
} else {
toast(`Error: ${result.error}`, 'error');
}
}
async function renameItem(itemPath) {
const oldName = itemPath.split(/[\\/]/).pop();
const newName = prompt('New name:', oldName);
if (!newName || newName === oldName) return;
const dirPath = await window.electron.pathDirname(itemPath);
const newPath = await window.electron.pathJoin(dirPath, newName);
const result = await window.electron.rename(itemPath, newPath);
if (result.success) {
// Update open files
const openIdx = state.openFiles.findIndex(f => f.path === itemPath);
if (openIdx !== -1) {
state.openFiles[openIdx].path = newPath;
state.openFiles[openIdx].name = newName;
if (state.activeFile === itemPath) state.activeFile = newPath;
}
await refreshTree();
renderTabs();
toast(`Renamed to ${newName}`, 'success');
} else {
toast(`Error: ${result.error}`, 'error');
}
}
async function deleteItem(itemPath, isDir) {
const name = itemPath.split(/[\\/]/).pop();
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
const result = await window.electron.delete(itemPath);
if (result.success) {
// Close if open
const openIdx = state.openFiles.findIndex(f => f.path === itemPath);
if (openIdx !== -1) {
state.openFiles.splice(openIdx, 1);
if (state.activeFile === itemPath) {
if (state.openFiles.length > 0) setActiveFile(state.openFiles[0].path);
else afterCloseFile(0);
}
}
await refreshTree();
renderTabs();
toast(`Deleted ${name}`, 'success');
} else {
toast(`Error: ${result.error}`, 'error');
}
}
// THIS PART MADE ME CRY
function toggleAI() {
state.aiOpen = !state.aiOpen;
const app = document.getElementById('app');
const panel = document.getElementById('ai-panel');
const btn = document.getElementById('toggle-ai-btn');
if (state.aiOpen) {
app.classList.add('ai-open');
panel.classList.remove('hidden');
btn.classList.add('active');
document.getElementById('ai-input').focus();
} else {
app.classList.remove('ai-open');
panel.classList.add('hidden');
btn.classList.remove('active');
}
setTimeout(() => state.editor && state.editor.refresh(), 310);
}
// This was easy but hurt my hands
function buildSystemPrompt() {
const workspaceName = state.workspace
? state.workspace.split(/[\\/]/).pop()
: 'no workspace';
const currentFile = state.activeFile
? state.activeFile.split(/[\\/]/).pop()
: 'none';
const currentCode = state.activeFile && state.editor
? state.editor.getValue().slice(0, 4000)
: '';
return `You are an expert coding assistant embedded in Codex, a code editor.
Current workspace: ${workspaceName}
Current open file: ${currentFile}
${currentCode ? `\nCurrent file content (truncated):\n\`\`\`\n${currentCode}\n\`\`\`` : ''}
You can create or modify files and folders in the workspace. To do so, output one or more special JSON blocks anywhere in your response, each on its own line, wrapped in <CODEX_ACTION> tags:
<CODEX_ACTION>
{
"type": "file",
"name": "filename.js",
"content": "file content here",
"parent": "workspace"
}
</CODEX_ACTION>
Or for folders:
<CODEX_ACTION>
{
"type": "folder",
"name": "components",
"parent": "workspace"
}
</CODEX_ACTION>
Rules for actions:
- "parent" can be "workspace" (root) or any folder name relative to root.
- For files, always include "content".
- You can output multiple <CODEX_ACTION> blocks.
- Actions are shown to the user as a preview card before they apply them.
- Write clear, clean, production-quality code.
Always be concise and helpful. If the user asks for code, give them the code.`;
}
// parse the actions if it returns valid json
function parseAIActions(text) {
const actions = [];
const regex = /<CODEX_ACTION>([\s\S]*?)<\/CODEX_ACTION>/g;
let match;
while ((match = regex.exec(text)) !== null) {
try {
const action = JSON.parse(match[1].trim());
actions.push(action);
} catch (e) { /* just ignore malformed */ }
}
return actions;
}
function stripActions(text) {
return text.replace(/<CODEX_ACTION>[\s\S]*?<\/CODEX_ACTION>/g, '').trim();
}
// render the ai messages we dont want it to talk to a wall
function renderMessage(role, content, actions = []) {
const container = document.getElementById('ai-messages');
const msgEl = document.createElement('div');
msgEl.className = `ai-message ${role}`;
const roleLabel = role === 'user' ? '▸ You' : '✦ Assistant';
const cleanContent = stripActions(content);
msgEl.innerHTML = `
<div class="ai-message-role">${roleLabel}</div>
<div class="ai-message-content">${escapeHtml(cleanContent)}</div>
`;
container.appendChild(msgEl);
// Render action cards
if (actions.length > 0) {
const card = document.createElement('div');
card.className = 'ai-message ai-action-card-wrapper';
card.innerHTML = `
<div class="ai-message-role">✦ Proposed changes</div>
<div class="ai-action-card">
<div class="ai-action-card-header">
<span>📦</span>
<span>${actions.length} operation${actions.length > 1 ? 's' : ''}</span>
</div>
${actions.map(a => `
<div class="ai-action-item">
<span class="ai-action-item-icon">${a.type === 'folder' ? '📁' : '📄'}</span>
<span class="ai-action-item-type">${a.type}</span>
<span>${a.parent !== 'workspace' ? a.parent + '/' : ''}${a.name}</span>
</div>
`).join('')}
<div style="margin-top:10px">
<button class="ai-action-apply-btn" id="apply-btn-${Date.now()}">Apply All</button>
</div>
</div>
`;
container.appendChild(card);
const btn = card.querySelector('.ai-action-apply-btn');
btn.addEventListener('click', () => applyActions(actions, btn));
}
container.scrollTop = container.scrollHeight;
}
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/\n/g, '<br>')
.replace(/`([^`]+)`/g, '<code>$1</code>');
}
function renderThinking() {
const container = document.getElementById('ai-messages');
const el = document.createElement('div');
el.className = 'ai-thinking';
el.id = 'ai-thinking';
el.innerHTML = `
<span>Thinking</span>
<span class="thinking-dots">
<span></span><span></span><span></span>
</span>
`;
container.appendChild(el);
container.scrollTop = container.scrollHeight;
}
function removeThinking() {
const el = document.getElementById('ai-thinking');
if (el) el.remove();
}
// apply the actions
async function applyActions(actions, btn) {
if (!state.workspace) {
toast('No workspace open — open a folder first', 'error');
return;
}
btn.disabled = true;
btn.textContent = 'Applying…';
let successCount = 0;
for (const action of actions) {
try {
let basePath;
if (!action.parent || action.parent === 'workspace') {
basePath = state.workspace;
} else {
basePath = await window.electron.pathJoin(state.workspace, action.parent);
}
if (action.type === 'folder') {
const folderPath = await window.electron.pathJoin(basePath, action.name);
const result = await window.electron.createFolder(folderPath);
if (result.success) successCount++;
else toast(`Folder error: ${result.error}`, 'error');
} else if (action.type === 'file') {
const filePath = await window.electron.pathJoin(basePath, action.name);
const result = await window.electron.writeFile(filePath, action.content || '');
if (result.success) {
successCount++;
await openFile(filePath);
} else {
toast(`File error: ${result.error}`, 'error');
}
}
} catch (e) {
toast(`Action error: ${e.message}`, 'error');
}
}
await refreshTree();
btn.textContent = `✓ Applied ${successCount}/${actions.length}`;
btn.style.background = 'var(--accent2-soft)';
btn.style.borderColor = 'var(--accent2)';
btn.style.color = 'var(--accent2)';
if (successCount > 0) toast(`Applied ${successCount} operation${successCount > 1 ? 's' : ''}`, 'success');
}
// send to the ai
async function sendToAI() {
const input = document.getElementById('ai-input');
const sendBtn = document.getElementById('ai-send-btn');
const message = input.value.trim();
if (!message) return;
// sync the editor to the file state
if (state.activeFile) {
const file = state.openFiles.find(f => f.path === state.activeFile);
if (file) file.content = state.editor.getValue();
}
input.value = '';
input.style.height = 'auto';
sendBtn.disabled = true;
state.aiMessages.push({ role: 'user', content: message });
renderMessage('user', message);
renderThinking();
const model = document.getElementById('ai-model-select').value;
try {
const response = await puter.ai.chat(
state.aiMessages.map(m => ({ role: m.role, content: m.content })),
{
model: model,
systemPrompt: buildSystemPrompt(),
}
);
removeThinking();
const assistantText = response?.message?.content?.[0]?.text
|| response?.text
|| response?.content
|| (typeof response === 'string' ? response : JSON.stringify(response));
state.aiMessages.push({ role: 'assistant', content: assistantText });
const actions = parseAIActions(assistantText);
renderMessage('assistant', assistantText, actions);
} catch (err) {
removeThinking();
const errMsg = `Error: ${err.message || 'Unknown error'}`;
renderMessage('assistant', errMsg);
toast(errMsg, 'error');
}
sendBtn.disabled = false;
input.focus();
}
// resize the textarea automatically
function autoResize(el) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 120) + 'px';
}
// main init
document.addEventListener('DOMContentLoaded', () => {
initEditor();
// Toolbar buttons
document.getElementById('toggle-ai-btn').addEventListener('click', toggleAI);
document.getElementById('open-folder-btn').addEventListener('click', openFolder);
document.getElementById('new-file-btn').addEventListener('click', createNewFile);
document.getElementById('new-folder-btn').addEventListener('click', createNewFolder);
document.getElementById('refresh-btn').addEventListener('click', refreshTree);
// AI send
document.getElementById('ai-send-btn').addEventListener('click', sendToAI);
document.getElementById('ai-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendToAI();
}
});
document.getElementById('ai-input').addEventListener('input', (e) => {
autoResize(e.target);
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
saveCurrentFile();
}
if ((e.ctrlKey || e.metaKey) && e.key === '\\') {
e.preventDefault();
toggleAI();
}
if (e.key === 'Escape') {
closeContextMenu();
}
});
// welcome message in AI for vibe coders
setTimeout(() => {
if (document.getElementById('ai-messages').children.length === 0) {
renderMessage('assistant',
'Hi! I\'m your AI coding assistant.\n\nI can help you:\n• Write and explain code\n• Create files and folders in your workspace\n• Debug and refactor\n\nOpen a workspace and start chatting. Try: "Create a React component called Button"'
);
}
}, 500);
});
// This code is friking 806 lines long
// coded by: Soso
// next upd: gonn fix ai