Elffuss BraidHub

utopia-ia/elffuss-code public

bd3b0b4729be · 18.5 KiBRawPermalink
1// IDE: Monaco (el editor de VS Code) + árbol de archivos + pestañas.
2import * as code from './tools/code.js';
3import { fileIcon, folderIcon } from './icons.js';
4import { renderMarkdown } from './md.js';
5
6let editor = null;
7let monacoRef = null;
8const tabs = []; // { path, model, dirty, preview }
9let active = null;
10let onDirtyChange = () => {};
11
12const LANG = {
13 js: 'javascript', mjs: 'javascript', ts: 'typescript', tsx: 'typescript',
14 jsx: 'javascript', json: 'json', html: 'html', css: 'css', md: 'markdown',
15 py: 'python', rs: 'rust', go: 'go', java: 'java', c: 'c', h: 'c',
16 cpp: 'cpp', sh: 'shell', yml: 'yaml', yaml: 'yaml', toml: 'ini',
17 svg: 'xml', xml: 'xml', sql: 'sql', txt: 'plaintext',
18};
19const langOf = p => LANG[p.split('.').pop().toLowerCase()] || 'plaintext';
20const $ = id => document.getElementById(id);
21
22export async function initEditor() {
23 await new Promise(res => {
24 const s = document.createElement('script');
25 s.src = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs/loader.js';
26 s.onload = res;
27 document.head.appendChild(s);
28 });
29 window.require.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs' } });
30 await new Promise(res => window.require(['vs/editor/editor.main'], res));
31 monacoRef = window.monaco;
32 editor = monacoRef.editor.create($('editor'), {
33 theme: 'vs-dark',
34 automaticLayout: true,
35 fontSize: 13,
36 minimap: { enabled: false },
37 padding: { top: 8 },
38 });
39 editor.addCommand(monacoRef.KeyMod.CtrlCmd | monacoRef.KeyCode.KeyS, saveActive);
40 editor.onDidChangeModelContent(() => {
41 const tab = tabs.find(t => t.path === active);
42 if (tab && !tab.dirty) { tab.dirty = true; renderTabs(); }
43 });
44 // los cambios del agente se reflejan al instante en el editor
45 code.setOnFileWritten((path, content) => {
46 const tab = tabs.find(t => t.path === path);
47 if (tab && tab.model.getValue() !== content) {
48 tab.model.setValue(content);
49 tab.dirty = false;
50 renderTabs();
51 if (path === active) applyView();
52 }
53 refreshTree();
54 });
55}
56
57export function gotoLine(n) {
58 if (!editor || !n) return;
59 editor.revealLineInCenter(n);
60 editor.setPosition({ lineNumber: n, column: 1 });
61 editor.focus();
62}
63export function triggerEditor(actionId) {
64 // El foco va ANTES de lanzar la acción, no después. Muchas acciones de Monaco
65 // abren un widget que toma el foco (quickOutline, por ejemplo), así que un
66 // `focus()` posterior se lo quitaba y lo cerraba al instante: «Go to symbol»
67 // no hacía nada visible. Y además varias acciones necesitan que el editor
68 // tenga el foco para ejecutarse, cosa que no pasa si vienes de pulsar un
69 // item de menú.
70 editor?.focus();
71 editor?.getAction(actionId)?.run();
72}
73export function hasEditor() { return !!editor; }
74
75export async function openFile(path) {
76 let tab = tabs.find(t => t.path === path);
77 if (!tab) {
78 let content;
79 try { content = await code.read({ path }); }
80 catch (e) {
81 // la ruta exacta no existe (típico: un enlace del chat solo mencionaba
82 // el NOMBRE, «config.py», y el fichero real vive en una subcarpeta) →
83 // si hay una única coincidencia por nombre en el proyecto, ábrela ella
84 // en vez de rendirte; con varias o ninguna, el error de siempre.
85 const base = path.split('/').pop();
86 const hits = await code.findByName?.(base, 2).catch(() => []) || [];
87 if (hits.length === 1 && hits[0] !== path) return openFile(hits[0]);
88 return alertBar('No pude abrir ' + path + ': ' + e.message);
89 }
90 tab = { path, model: monacoRef.editor.createModel(content, langOf(path)), dirty: false, preview: false };
91 tabs.push(tab);
92 }
93 active = path;
94 code.setCurrentFile(path);
95 editor.setModel(tab.model);
96 setEmptyState(false);
97 renderTabs();
98 await applyView();
99}
100
101// modo «Vista previa» de un tab .md/.html: en vez del código fuente en
102// Monaco, muestra el markdown renderizado (mismo motor que el chat y la
103// Mente) o el HTML en un iframe real.
104const PREVIEWABLE = new Set(['markdown', 'html']);
105
106// resuelve una ruta relativa (href/src) contra la carpeta del propio fichero
107function resolveRelative(ownPath, rel) {
108 if (/^([a-z][\w+.-]*:)?\/\//i.test(rel) || rel.startsWith('data:') || rel.startsWith('#')) return null; // externa/absoluta: no tocar
109 const baseDir = ownPath.includes('/') ? ownPath.slice(0, ownPath.lastIndexOf('/')) : '';
110 const segs = (baseDir ? baseDir.split('/') : []).concat(rel.split('/'));
111 const out = [];
112 for (const s of segs) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
113 return out.join('/');
114}
115// un iframe con srcdoc no tiene base URL propia: <link href="style.css"> o
116// <script src="app.js"> del proyecto real NUNCA se resuelven (por eso salía
117// sin CSS) — se leen del proyecto de verdad y se incrustan antes de mostrarlo.
118// El iframe de Vista previa va con sandbox="allow-scripts" A PROPÓSITO, SIN
119// allow-same-origin (aislado de tu proyecto real — ver applyView). Pero eso
120// hace que referenciar `localStorage`/`sessionStorage` LANCE una excepción
121// síncrona — y como suele ser la primera línea de un script (guardar datos
122// es de lo más común), el resto del fichero entero se queda sin ejecutar,
123// sin aviso: los botones no hacen nada y parece que la app está rota. Se
124// incrusta un shim en memoria (nunca toca almacenamiento real, se pierde al
125// cerrar la vista previa) SOLO si de verdad hace falta — si el sandbox
126// permitiera acceso real, no se toca nada.
127const STORAGE_SHIM = `<script>(()=>{try{window.localStorage;return}catch(e){}` +
128 `const m=()=>{const d=new Map();return{getItem:k=>d.has(''+k)?d.get(''+k):null,` +
129 `setItem:(k,v)=>{d.set(''+k,''+v)},removeItem:k=>{d.delete(''+k)},clear:()=>{d.clear()},` +
130 `key:i=>[...d.keys()][i]??null,get length(){return d.size}}};` +
131 `for(const p of ['localStorage','sessionStorage'])` +
132 `try{Object.defineProperty(window,p,{value:m(),configurable:true})}catch(e){}})()<\/script>`;
133
134async function inlineLocalAssets(html, ownPath) {
135 const doc = new DOMParser().parseFromString(html, 'text/html');
136 (doc.head || doc.documentElement).insertAdjacentHTML('afterbegin', STORAGE_SHIM);
137 for (const link of doc.querySelectorAll('link[rel~="stylesheet"][href]')) {
138 const path = resolveRelative(ownPath, link.getAttribute('href'));
139 if (!path) continue;
140 try {
141 const style = doc.createElement('style');
142 style.textContent = await code.read({ path });
143 link.replaceWith(style);
144 } catch { /* no se pudo leer: se deja el link (el navegador lo ignorará sin más) */ }
145 }
146 for (const script of doc.querySelectorAll('script[src]')) {
147 const path = resolveRelative(ownPath, script.getAttribute('src'));
148 if (!path) continue;
149 try {
150 const inline = doc.createElement('script');
151 if (script.type) inline.type = script.type;
152 inline.textContent = await code.read({ path });
153 script.replaceWith(inline);
154 } catch { /* deja el script tal cual */ }
155 }
156 return '<!doctype html>\n' + doc.documentElement.outerHTML;
157}
158
159async function applyView() {
160 const tab = tabs.find(t => t.path === active);
161 const lang = tab ? langOf(tab.path) : null;
162 const showPreview = !!(tab && tab.preview && PREVIEWABLE.has(lang));
163 $('editor').style.display = showPreview ? 'none' : '';
164 let pane = document.getElementById('md-preview-pane');
165 if (showPreview) {
166 if (!pane) {
167 pane = document.createElement('div');
168 pane.id = 'md-preview-pane';
169 $('editor').parentElement.appendChild(pane);
170 }
171 pane.classList.toggle('html-preview', lang === 'html');
172 if (lang === 'html') {
173 pane.replaceChildren();
174 const frame = document.createElement('iframe');
175 frame.sandbox = 'allow-scripts'; // sin allow-same-origin: aislado de tu proyecto real
176 frame.srcdoc = await inlineLocalAssets(tab.model.getValue(), tab.path);
177 pane.appendChild(frame);
178 } else {
179 pane.innerHTML = renderMarkdown(tab.model.getValue());
180 }
181 pane.style.display = '';
182 } else if (pane) {
183 pane.style.display = 'none';
184 }
185}
186async function togglePreview(path) {
187 // el fichero puede no tener pestaña abierta todavía (p.ej. desde el menú
188 // del EXPLORADOR, no el de una pestaña ya abierta) — se abre primero.
189 if (active !== path || !tabs.find(t => t.path === path)) await openFile(path);
190 const tab = tabs.find(t => t.path === path);
191 if (!tab) return; // openFile no pudo (fichero borrado, etc.)
192 tab.preview = !tab.preview;
193 renderTabs();
194 await applyView();
195}
196
197async function saveActive() {
198 const tab = tabs.find(t => t.path === active);
199 if (!tab) return;
200 await code.write({ path: tab.path, content: tab.model.getValue() });
201 tab.dirty = false;
202 renderTabs();
203 alertBar('💾 ' + tab.path + ' guardado');
204}
205
206async function closeTab(path) {
207 const i = tabs.findIndex(t => t.path === path);
208 if (i < 0) return;
209 tabs[i].model.dispose();
210 tabs.splice(i, 1);
211 if (active === path) {
212 active = tabs[i - 1]?.path || tabs[0]?.path || null;
213 code.setCurrentFile(active);
214 if (active) { editor.setModel(tabs.find(t => t.path === active).model); setEmptyState(false); }
215 else { editor.setModel(monacoRef.editor.createModel('', 'plaintext')); setEmptyState(true); }
216 }
217 renderTabs();
218 await applyView();
219}
220
221// Estado vacío: cuando no hay ningún fichero abierto, en vez de dejar el Monaco
222// en blanco con un «1», mostramos un placeholder limpio.
223export function setEmptyState(on) {
224 let el = document.getElementById('editor-empty');
225 if (!el) {
226 el = document.createElement('div');
227 el.id = 'editor-empty';
228 el.innerHTML = '<img src="img/elffuss-code.svg" alt=""><p>Abre un fichero del explorador,<br>o pídele algo a la elfa.</p>';
229 $('editor').parentElement.appendChild(el);
230 }
231 el.style.display = on ? 'flex' : 'none';
232}
233
234function renderTabs() {
235 const bar = $('tabs-bar');
236 bar.replaceChildren();
237 for (const t of tabs) {
238 const el = document.createElement('div');
239 el.className = 'tab' + (t.path === active ? ' active' : '') + (t.preview ? ' tab-preview' : '');
240 el.dataset.path = t.path;
241 const ico = document.createElement('span');
242 ico.className = 'tab-ico';
243 ico.innerHTML = fileIcon(t.path.split('/').pop());
244 const name = document.createElement('span');
245 name.className = 'tab-name';
246 name.textContent = t.path.split('/').pop();
247 name.title = t.path;
248 // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón
249 const x = document.createElement('b');
250 x.className = t.dirty ? 'dirty' : '';
251 x.textContent = t.dirty ? '●' : '×';
252 x.onclick = e => { e.stopPropagation(); closeTab(t.path); };
253 el.append(ico, name, x);
254 el.onclick = () => openFile(t.path);
255 el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, t.path); };
256 bar.appendChild(el);
257 }
258}
259
260// ---------- menú contextual de las pestañas (botón derecho, estilo VS Code) ----------
261function openTabMenu(x, y, path) {
262 document.getElementById('tab-menu')?.remove();
263 const menu = document.createElement('div');
264 menu.id = 'tab-menu';
265 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
266 const i = tabs.findIndex(t => t.path === path);
267 const tab = tabs[i];
268 const items = [];
269 items.push(['Cerrar', () => closeTab(path)]);
270 items.push(['Cerrar otras', () => { for (const t of tabs.filter(t => t.path !== path)) closeTab(t.path); }]);
271 const toTheRight = tabs.slice(i + 1).map(t => t.path);
272 if (toTheRight.length) items.push(['Cerrar las de la derecha', () => { for (const p of toTheRight) closeTab(p); }]);
273 items.push(['Cerrar todas', () => { for (const t of [...tabs]) closeTab(t.path); }]);
274 items.push(['sep']);
275 items.push(['Copiar ruta', () => navigator.clipboard?.writeText(path).catch(() => {})]);
276 if (PREVIEWABLE.has(langOf(path))) {
277 items.push([tab?.preview ? 'Ver código fuente' : 'Vista previa', () => togglePreview(path)]);
278 }
279 for (const item of items) {
280 if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep' })); continue; }
281 const [label, fn] = item;
282 const b = document.createElement('button');
283 b.className = 'tm-item';
284 b.textContent = label;
285 b.onclick = () => { menu.remove(); fn(); };
286 menu.appendChild(b);
287 }
288 document.body.appendChild(menu);
289 const close = ev => { if (!menu.contains(ev.target)) { menu.remove(); document.removeEventListener('mousedown', close); } };
290 setTimeout(() => document.addEventListener('mousedown', close), 0);
291}
292
293let alertTimer;
294function alertBar(msg) {
295 const el = $('statusbar');
296 el.textContent = msg;
297 clearTimeout(alertTimer);
298 alertTimer = setTimeout(() => { el.textContent = ''; }, 4000);
299}
300
301// ---------- árbol lateral ----------
302const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
303
304export async function refreshTree(handle = null) {
305 const rootHandle = handle || window.__elffussProject;
306 if (!rootHandle) return;
307 window.__elffussProject = rootHandle;
308 const cont = $('tree');
309 cont.replaceChildren(await renderDir(rootHandle, ''));
310 setupTreeMenu();
311}
312
313// ---------- menú contextual del árbol (botón derecho, estilo VS Code) ----------
314let treeMenuWired = false;
315function setupTreeMenu() {
316 if (treeMenuWired) return;
317 treeMenuWired = true;
318 const tree = $('tree');
319 tree.addEventListener('contextmenu', e => {
320 e.preventDefault();
321 const node = e.target.closest('[data-path]');
322 const path = node ? node.dataset.path : '';
323 const kind = node ? node.dataset.kind : 'directory'; // vacío = raíz
324 openTreeMenu(e.clientX, e.clientY, path, kind);
325 });
326}
327
328// resuelve el handle de un directorio por su ruta (segmentos desde la raíz)
329async function dirByPath(path) {
330 let dir = code.handle();
331 for (const s of (path || '').split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(s);
332 return dir;
333}
334const parentOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
335const baseOf = p => p.split('/').pop();
336
337async function fsCreate(parentPath, name, isDir) {
338 const dir = await dirByPath(parentPath);
339 if (isDir) await dir.getDirectoryHandle(name, { create: true });
340 else { const fh = await dir.getFileHandle(name, { create: true }); const w = await fh.createWritable(); await w.close(); }
341}
342async function fsDelete(path, kind) {
343 const dir = await dirByPath(parentOf(path));
344 await dir.removeEntry(baseOf(path), { recursive: kind === 'directory' });
345}
346// copia recursiva (la File System API no tiene rename nativo)
347async function fsCopy(srcDir, name, dstDir, newName) {
348 const src = await (srcDir.getDirectoryHandle(name).catch(() => null));
349 if (src) { // directorio
350 const nd = await dstDir.getDirectoryHandle(newName, { create: true });
351 for await (const e of src.values()) await fsCopy(src, e.name, nd, e.name);
352 } else { // fichero
353 const text = await (await (await srcDir.getFileHandle(name)).getFile()).text();
354 const fh = await dstDir.getFileHandle(newName, { create: true });
355 const w = await fh.createWritable(); await w.write(text); await w.close();
356 }
357}
358async function fsRename(path, kind, newName) {
359 const parent = await dirByPath(parentOf(path));
360 await fsCopy(parent, baseOf(path), parent, newName);
361 await parent.removeEntry(baseOf(path), { recursive: kind === 'directory' });
362}
363
364function openTreeMenu(x, y, path, kind) {
365 document.getElementById('tree-menu')?.remove();
366 const menu = document.createElement('div');
367 menu.id = 'tree-menu';
368 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
369 // en un fichero, el "aquí dentro" es su carpeta; en carpeta/raíz, ella misma
370 const container = kind === 'file' ? parentOf(path) : path;
371 const items = [];
372 items.push(['Nuevo archivo…', async () => {
373 const name = prompt('Nombre del nuevo archivo:'); if (!name) return;
374 await fsCreate(container, name.trim(), false); code.invalidateFileList?.();
375 await refreshTree(); openFile(container ? container + '/' + name.trim() : name.trim());
376 }]);
377 items.push(['Nueva carpeta…', async () => {
378 const name = prompt('Nombre de la nueva carpeta:'); if (!name) return;
379 await fsCreate(container, name.trim(), true); code.invalidateFileList?.(); await refreshTree();
380 }]);
381 if (path) {
382 if (kind === 'file') items.push(['Abrir', () => openFile(path)]);
383 if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push(['Vista previa', () => togglePreview(path)]);
384 items.push(['Renombrar…', async () => {
385 const name = prompt('Nuevo nombre:', baseOf(path)); if (!name || name === baseOf(path)) return;
386 await fsRename(path, kind, name.trim()); code.invalidateFileList?.(); await refreshTree();
387 }]);
388 items.push(['Eliminar', async () => {
389 if (!confirm(`¿Eliminar «${baseOf(path)}»?`)) return;
390 await fsDelete(path, kind); code.invalidateFileList?.(); await refreshTree();
391 }, 'danger']);
392 }
393 for (const [label, fn, cls] of items) {
394 const b = document.createElement('button');
395 b.className = 'tm-item' + (cls ? ' ' + cls : '');
396 b.textContent = label;
397 b.onclick = async () => { menu.remove(); try { await fn(); } catch (err) { alert('No se pudo: ' + err.message); } };
398 menu.appendChild(b);
399 }
400 document.body.appendChild(menu);
401 const close = ev => { if (!menu.contains(ev.target)) { menu.remove(); document.removeEventListener('mousedown', close); } };
402 setTimeout(() => document.addEventListener('mousedown', close), 0);
403}
404
405async function renderDir(dir, prefix) {
406 const ul = document.createElement('ul');
407 const entries = [];
408 for await (const e of dir.values()) if (!IGNORE.has(e.name)) entries.push(e);
409 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
410 for (const e of entries.slice(0, 200)) {
411 const li = document.createElement('li');
412 const p = prefix ? prefix + '/' + e.name : e.name;
413 if (e.kind === 'directory') {
414 const det = document.createElement('details');
415 const sum = document.createElement('summary');
416 sum.innerHTML = folderIcon();
417 sum.appendChild(document.createTextNode(e.name));
418 sum.dataset.path = p; sum.dataset.kind = 'directory';
419 det.appendChild(sum);
420 det.addEventListener('toggle', async () => {
421 if (det.open && det.children.length === 1)
422 det.appendChild(await renderDir(e, p));
423 }, { once: false });
424 li.appendChild(det);
425 } else {
426 const a = document.createElement('span');
427 a.className = 'file';
428 a.innerHTML = fileIcon(e.name);
429 a.appendChild(document.createTextNode(e.name));
430 a.dataset.path = p; a.dataset.kind = 'file';
431 a.onclick = () => openFile(p);
432 li.appendChild(a);
433 }
434 ul.appendChild(li);
435 }
436 return ul;
437}