Elffuss BraidHub

utopia-ia/elffuss-code public

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