Elffuss BraidHub

utopia-ia/elffuss-code public

e0009187e422 · 34.9 KiBRawPermalink
1// IDE: Monaco (el editor de VS Code) + árbol de archivos + pestañas.
2import * as code from './tools/code.js';
3import * as db from './db.js';
4import { fileIcon, folderIcon } from './icons.js';
5import { renderMarkdown } from './md.js';
6import { t } from './i18n.js';
7
8let editor = null;
9let monacoRef = null;
10let ext = null; // extensiones de VS Code (js/ext/host.js), ver loadExt()
11const tabs = []; // { path, model, dirty, preview }
12let active = null;
13let onDirtyChange = () => {};
14
15const LANG = {
16 js: 'javascript', mjs: 'javascript', ts: 'typescript', tsx: 'typescript',
17 jsx: 'javascript', json: 'json', html: 'html', css: 'css', md: 'markdown',
18 py: 'python', rs: 'rust', go: 'go', java: 'java', c: 'c', h: 'c',
19 cpp: 'cpp', sh: 'shell', yml: 'yaml', yaml: 'yaml', toml: 'ini',
20 svg: 'xml', xml: 'xml', sql: 'sql', txt: 'plaintext',
21};
22// las extensiones instaladas mandan (p. ej. .toml → toml en vez de ini)
23const porNombre = p => ext?.languageForPath(p) || LANG[p.split('.').pop().toLowerCase()] || null;
24const langOf = p => porNombre(p) || 'plaintext';
25// …y, como en VS Code, la primera línea (firstLine de una extensión) solo
26// cuenta si nadie reclama el fichero por su nombre. Va en un Worker con tiempo
27// tope: una expresión de un paquete puede no terminar nunca.
28const langDe = async (p, primeraLinea) => porNombre(p) || (ext && primeraLinea ? await ext.languageForFirstLine(primeraLinea) : null) || 'plaintext';
29const $ = id => document.getElementById(id);
30
31export async function initEditor() {
32 await new Promise(res => {
33 const s = document.createElement('script');
34 s.src = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs/loader.js';
35 s.onload = res;
36 document.head.appendChild(s);
37 });
38 window.require.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs' } });
39 await new Promise(res => window.require(['vs/editor/editor.main'], res));
40 monacoRef = window.monaco;
41 ext = await loadExt(false);
42 editor = monacoRef.editor.create($('editor'), {
43 theme: ext ? ext.themeId() : 'vs-dark',
44 automaticLayout: true,
45 fontSize: 13,
46 minimap: { enabled: false },
47 padding: { top: 8 },
48 });
49 editor.addCommand(monacoRef.KeyMod.CtrlCmd | monacoRef.KeyCode.KeyS, saveActive);
50 editor.onDidChangeModelContent(() => {
51 const tab = tabs.find(t => t.path === active);
52 if (tab && !tab.dirty) { tab.dirty = true; renderTabs(); }
53 });
54 // los cambios del agente se reflejan al instante en el editor
55 code.setOnFileWritten((path, content) => {
56 const tab = tabs.find(t => t.path === path);
57 if (tab && tab.model.getValue() !== content) {
58 tab.model.setValue(content);
59 tab.dirty = false;
60 renderTabs();
61 if (path === active) applyView();
62 }
63 refreshTree();
64 });
65}
66
67export function gotoLine(n) {
68 if (!editor || !n) return;
69 editor.revealLineInCenter(n);
70 editor.setPosition({ lineNumber: n, column: 1 });
71 editor.focus();
72}
73export function triggerEditor(actionId) {
74 // El foco va ANTES de lanzar la acción, no después. Muchas acciones de Monaco
75 // abren un widget que toma el foco (quickOutline, por ejemplo), así que un
76 // `focus()` posterior se lo quitaba y lo cerraba al instante: «Go to symbol»
77 // no hacía nada visible. Y además varias acciones necesitan que el editor
78 // tenga el foco para ejecutarse, cosa que no pasa si vienes de pulsar un
79 // item de menú.
80 editor?.focus();
81 editor?.getAction(actionId)?.run();
82}
83export function hasEditor() { return !!editor; }
84// Llevar el foco al editor (p. ej. tras «Abrir en el editor» desde la Mente).
85export function focusEditor() { try { editor?.focus(); } catch { /* sin editor */ } }
86// La ruta del fichero activo (o null): el menú la usa para no lanzar acciones
87// del editor que no hacen nada sin un fichero abierto.
88export function activeFile() { return active; }
89// Las pestañas abiertas y su lenguaje, y el lenguaje que tendría una ruta: el
90// panel de extensiones los usa para decir qué ficheros ya se ven distintos.
91export function openTabs() {
92 return tabs.filter(t => !t.model.isDisposed()).map(t => ({ path: t.path, language: t.model.getLanguageId(), active: t.path === active }));
93}
94export const languageOfPath = p => langOf(p);
95
96export async function openFile(path) {
97 let tab = tabs.find(t => t.path === path);
98 if (!tab) {
99 let content;
100 try { content = await code.read({ path }); }
101 catch (e) {
102 // la ruta exacta no existe (típico: un enlace del chat solo mencionaba
103 // el NOMBRE, «config.py», y el fichero real vive en una subcarpeta) →
104 // si hay una única coincidencia por nombre en el proyecto, ábrela ella
105 // en vez de rendirte; con varias o ninguna, el error de siempre.
106 const base = path.split('/').pop();
107 const hits = await code.findByName?.(base, 2).catch(() => []) || [];
108 if (hits.length === 1 && hits[0] !== path) return openFile(hits[0]);
109 return alertBar(t('openFailed', { path, e: e.message }));
110 }
111 const lang = await langDe(path, content.slice(0, 500).split('\n')[0]);
112 await ext?.prepareLanguage(lang); // la gramática, antes de que exista el modelo
113 tab = tabs.find(t => t.path === path); // otra llamada pudo abrirla mientras tanto
114 if (!tab) {
115 tab = { path, model: monacoRef.editor.createModel(content, lang), dirty: false, preview: false };
116 tabs.push(tab);
117 }
118 }
119 active = path;
120 code.setCurrentFile(path);
121 editor.setModel(tab.model);
122 setEmptyState(false);
123 renderTabs();
124 await applyView();
125}
126
127// modo «Vista previa» de un tab .md/.html: en vez del código fuente en
128// Monaco, muestra el markdown renderizado (mismo motor que el chat y la
129// Mente) o el HTML en un iframe real.
130const PREVIEWABLE = new Set(['markdown', 'html']);
131
132// resuelve una ruta relativa (href/src) contra la carpeta del propio fichero
133function resolveRelative(ownPath, rel) {
134 if (/^([a-z][\w+.-]*:)?\/\//i.test(rel) || rel.startsWith('data:') || rel.startsWith('#')) return null; // externa/absoluta: no tocar
135 const baseDir = ownPath.includes('/') ? ownPath.slice(0, ownPath.lastIndexOf('/')) : '';
136 const segs = (baseDir ? baseDir.split('/') : []).concat(rel.split('/'));
137 const out = [];
138 for (const s of segs) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
139 return out.join('/');
140}
141// un iframe con srcdoc no tiene base URL propia: <link href="style.css"> o
142// <script src="app.js"> del proyecto real NUNCA se resuelven (por eso salía
143// sin CSS) — se leen del proyecto de verdad y se incrustan antes de mostrarlo.
144// El iframe de Vista previa va con sandbox="allow-scripts" A PROPÓSITO, SIN
145// allow-same-origin (aislado de tu proyecto real — ver applyView). Pero eso
146// hace que referenciar `localStorage`/`sessionStorage` LANCE una excepción
147// síncrona — y como suele ser la primera línea de un script (guardar datos
148// es de lo más común), el resto del fichero entero se queda sin ejecutar,
149// sin aviso: los botones no hacen nada y parece que la app está rota. Se
150// incrusta un shim en memoria (nunca toca almacenamiento real, se pierde al
151// cerrar la vista previa) SOLO si de verdad hace falta — si el sandbox
152// permitiera acceso real, no se toca nada.
153const STORAGE_SHIM = `<script>(()=>{try{window.localStorage;return}catch(e){}` +
154 `const m=()=>{const d=new Map();return{getItem:k=>d.has(''+k)?d.get(''+k):null,` +
155 `setItem:(k,v)=>{d.set(''+k,''+v)},removeItem:k=>{d.delete(''+k)},clear:()=>{d.clear()},` +
156 `key:i=>[...d.keys()][i]??null,get length(){return d.size}}};` +
157 `for(const p of ['localStorage','sessionStorage'])` +
158 `try{Object.defineProperty(window,p,{value:m(),configurable:true})}catch(e){}})()<\/script>`;
159
160async function inlineLocalAssets(html, ownPath) {
161 const doc = new DOMParser().parseFromString(html, 'text/html');
162 (doc.head || doc.documentElement).insertAdjacentHTML('afterbegin', STORAGE_SHIM);
163 for (const link of doc.querySelectorAll('link[rel~="stylesheet"][href]')) {
164 const path = resolveRelative(ownPath, link.getAttribute('href'));
165 if (!path) continue;
166 try {
167 const style = doc.createElement('style');
168 style.textContent = await code.read({ path });
169 link.replaceWith(style);
170 } catch { /* no se pudo leer: se deja el link (el navegador lo ignorará sin más) */ }
171 }
172 for (const script of doc.querySelectorAll('script[src]')) {
173 const path = resolveRelative(ownPath, script.getAttribute('src'));
174 if (!path) continue;
175 try {
176 const inline = doc.createElement('script');
177 if (script.type) inline.type = script.type;
178 inline.textContent = await code.read({ path });
179 script.replaceWith(inline);
180 } catch { /* deja el script tal cual */ }
181 }
182 return '<!doctype html>\n' + doc.documentElement.outerHTML;
183}
184
185async function applyView() {
186 const tab = tabs.find(t => t.path === active);
187 const lang = tab ? langOf(tab.path) : null;
188 const showPreview = !!(tab && tab.preview && PREVIEWABLE.has(lang));
189 $('editor').style.display = showPreview ? 'none' : '';
190 let pane = document.getElementById('md-preview-pane');
191 if (showPreview) {
192 if (!pane) {
193 pane = document.createElement('div');
194 pane.id = 'md-preview-pane';
195 $('editor').parentElement.appendChild(pane);
196 }
197 pane.classList.toggle('html-preview', lang === 'html');
198 if (lang === 'html') {
199 pane.replaceChildren();
200 const frame = document.createElement('iframe');
201 frame.sandbox = 'allow-scripts'; // sin allow-same-origin: aislado de tu proyecto real
202 frame.srcdoc = await inlineLocalAssets(tab.model.getValue(), tab.path);
203 pane.appendChild(frame);
204 } else {
205 pane.innerHTML = renderMarkdown(tab.model.getValue());
206 }
207 pane.style.display = '';
208 } else if (pane) {
209 pane.style.display = 'none';
210 }
211}
212async function togglePreview(path) {
213 // el fichero puede no tener pestaña abierta todavía (p.ej. desde el menú
214 // del EXPLORADOR, no el de una pestaña ya abierta) — se abre primero.
215 if (active !== path || !tabs.find(t => t.path === path)) await openFile(path);
216 const tab = tabs.find(t => t.path === path);
217 if (!tab) return; // openFile no pudo (fichero borrado, etc.)
218 tab.preview = !tab.preview;
219 renderTabs();
220 await applyView();
221}
222
223// Guardar lo que TÚ has escrito va directo al fichero, no por code.write: esa
224// es la vía del agente, con su aprobación («Elffuss quiere escribir…», que
225// salía al guardar tu propio fichero con Auto apagado) y sus guardas contra
226// reescrituras que recortan medio fichero, que bloqueaban un guardado tuyo
227// legítimo sin decir nada.
228async function writeOwn(path, content) {
229 const parts = path.split('/').filter(Boolean);
230 const name = parts.pop();
231 let dir = code.handle();
232 for (const s of parts) dir = await dir.getDirectoryHandle(s, { create: true });
233 const w = await (await dir.getFileHandle(name, { create: true })).createWritable();
234 await w.write(content);
235 await w.close();
236 code.invalidateFileList?.();
237}
238async function saveTab(tab) {
239 const recreado = !!tab.deleted;
240 try {
241 await writeOwn(tab.path, tab.model.getValue());
242 } catch (e) {
243 alertBar(t('saveFailed', { path: tab.path, e: e?.message || e }));
244 return false;
245 }
246 tab.dirty = false;
247 tab.deleted = false;
248 renderTabs();
249 // Guardar una pestaña cuyo fichero se había borrado lo vuelve a crear, y el
250 // explorador tiene que enseñarlo: writeOwn no pasa por code.write, que era
251 // quien avisaba al árbol (onFileWritten → refreshTree).
252 if (recreado) await refreshTree();
253 alertBar(t('saved', { path: tab.path }));
254 return true;
255}
256// Exportada: la usan el menú File › Guardar y la paleta. Antes ellos lanzaban
257// la acción 'workbench.action.files.save', que no existe en el Monaco suelto,
258// y no pasaba nada.
259export async function saveActive() {
260 const tab = tabs.find(t => t.path === active);
261 if (!tab) { alertBar(t('noFileOpen')); return false; }
262 return saveTab(tab);
263}
264
265// Cerrar una pestaña con cambios sin guardar PREGUNTA: Guardar, No guardar o
266// Cancelar. Antes se cerraba y los cambios se perdían sin aviso.
267function askDirty(tab) {
268 return new Promise(resolve => {
269 const dlg = document.createElement('dialog');
270 dlg.id = 'dirty-dialog';
271 dlg.setAttribute('aria-labelledby', 'dirty-title');
272 const h = document.createElement('p'); h.id = 'dirty-title'; h.className = 'dd-title';
273 h.textContent = t('dirtyTitle', { name: baseOf(tab.path) });
274 const sub = document.createElement('p'); sub.className = 'dd-sub'; sub.textContent = t('dirtyBody');
275 const row = document.createElement('div'); row.className = 'dd-row';
276 let answer = 'cancel';
277 const mk = (label, val, cls) => {
278 const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.dataset.val = val;
279 if (cls) b.className = cls;
280 b.onclick = () => { answer = val; dlg.close(); };
281 row.appendChild(b); return b;
282 };
283 const save = mk(t('dirtySave'), 'save', 'dd-primary');
284 mk(t('dirtyDiscard'), 'discard');
285 mk(t('dirtyCancel'), 'cancel');
286 dlg.append(h, sub, row);
287 dlg.addEventListener('close', () => { dlg.remove(); resolve(answer); }, { once: true });
288 document.body.appendChild(dlg);
289 dlg.showModal();
290 save.focus();
291 });
292}
293
294// Devuelve false si el usuario canceló (la pestaña sigue abierta).
295async function closeTab(path) {
296 const i = tabs.findIndex(t => t.path === path);
297 if (i < 0) return true;
298 if (tabs[i].dirty) {
299 const r = await askDirty(tabs[i]);
300 if (r === 'cancel') return false;
301 if (r === 'save' && !(await saveTab(tabs[i]))) return false;
302 }
303 const j = tabs.findIndex(t => t.path === path); // el diálogo es asíncrono
304 if (j < 0) return true;
305 closeTabNow(j);
306 renderTabs();
307 await applyView();
308 return true;
309}
310// Cerrar desde la barra de pestañas (Supr, Cmd/Ctrl+W, la ✕, o «No guardar» en
311// el diálogo): el foco va a la pestaña que queda activa, o al aviso de «sin
312// ficheros abiertos» si no queda ninguna. Antes caía a <body> (las pestañas de
313// conversación ya lo hacían bien; las del editor no).
314async function closeTabYEnfoca(path) {
315 if (!(await closeTab(path))) return false; // cancelado: el diálogo devuelve el foco a la pestaña
316 const activa = $('tabs-bar')?.querySelector('.tab.active');
317 if (activa) activa.focus();
318 else {
319 const vacio = document.getElementById('editor-empty');
320 if (vacio) { vacio.tabIndex = -1; vacio.focus(); } else editor?.focus();
321 }
322 return true;
323}
324// Varias seguidas («Cerrar otras/todas»): se para en la primera que cancelas.
325async function closeTabs(paths) {
326 for (const p of paths) if (!(await closeTab(p))) return false;
327 return true;
328}
329
330function closeTabNow(i) {
331 const path = tabs[i].path;
332 tabs[i].model.dispose();
333 tabs.splice(i, 1);
334 if (active === path) {
335 active = tabs[i - 1]?.path || tabs[0]?.path || null;
336 code.setCurrentFile(active);
337 if (active) { editor.setModel(tabs.find(t => t.path === active).model); setEmptyState(false); }
338 else { editor.setModel(monacoRef.editor.createModel('', 'plaintext')); setEmptyState(true); }
339 }
340}
341
342// Estado vacío: cuando no hay ningún fichero abierto, en vez de dejar el Monaco
343// en blanco con un «1», mostramos un placeholder limpio.
344export function setEmptyState(on) {
345 let el = document.getElementById('editor-empty');
346 if (!el) {
347 el = document.createElement('div');
348 el.id = 'editor-empty';
349 el.innerHTML = '<img src="img/elffuss-code.svg" alt=""><p></p>';
350 el.querySelector('p').textContent = t('editorEmpty');
351 $('editor').parentElement.appendChild(el);
352 }
353 el.style.display = on ? 'flex' : 'none';
354}
355
356function renderTabs() {
357 const bar = $('tabs-bar');
358 bar.replaceChildren();
359 bar.setAttribute('role', 'tablist');
360 bar.setAttribute('aria-label', t('editorTabs'));
361 for (const tb of tabs) {
362 const el = document.createElement('div');
363 const on = tb.path === active;
364 el.className = 'tab' + (on ? ' active' : '') + (tb.preview ? ' tab-preview' : '');
365 el.dataset.path = tb.path;
366 // Pestañas de verdad para el teclado y los lectores de pantalla: antes eran
367 // <div> sin foco. La activa entra con Tab; ←/→ se mueven entre ellas.
368 el.setAttribute('role', 'tab');
369 el.setAttribute('aria-selected', on ? 'true' : 'false');
370 // Nombre propio: sin él, el de la pestaña era el fichero MÁS el botón × que
371 // lleva dentro («app.js Cerrar app.js»).
372 el.setAttribute('aria-label', baseOf(tb.path) + (tb.dirty ? ' ' + t('tabUnsaved') : '') + (tb.deleted ? ' — ' + t('fileDeletedDirty') : ''));
373 el.tabIndex = on ? 0 : -1;
374 const ico = document.createElement('span');
375 ico.className = 'tab-ico';
376 ico.innerHTML = fileIcon(tb.path.split('/').pop());
377 const name = document.createElement('span');
378 name.className = 'tab-name';
379 name.textContent = tb.path.split('/').pop();
380 name.title = tb.deleted ? tb.path + ' · ' + t('fileDeletedDirty') : tb.path;
381 if (tb.deleted) name.classList.add('deleted');
382 // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón.
383 // Un <button> con nombre accesible (antes un <b> que no recibía el foco).
384 const x = document.createElement('button');
385 x.type = 'button';
386 x.className = 'tab-x' + (tb.dirty ? ' dirty' : '');
387 x.textContent = tb.dirty ? '●' : '×';
388 x.tabIndex = -1;
389 x.setAttribute('aria-label', t(tb.dirty ? 'closeFileDirty' : 'closeFile', { name: baseOf(tb.path) }));
390 x.title = x.getAttribute('aria-label');
391 x.onclick = e => { e.stopPropagation(); closeTabYEnfoca(tb.path); };
392 el.append(ico, name, x);
393 el.onclick = () => openFile(tb.path);
394 el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, tb.path); };
395 el.onkeydown = e => {
396 const i = tabs.indexOf(tb);
397 if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
398 e.preventDefault();
399 const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
400 if (next) openFile(next.path).then(() => bar.querySelector('.tab.active')?.focus());
401 } else if (e.key === 'Delete' || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'w')) {
402 e.preventDefault(); closeTabYEnfoca(tb.path);
403 } else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
404 e.preventDefault(); const r = el.getBoundingClientRect(); openTabMenu(r.left, r.bottom, tb.path);
405 }
406 };
407 bar.appendChild(el);
408 }
409 markActive();
410}
411
412// ---------- menús contextuales (pestañas y árbol): teclado y Escape ----------
413// Escape los cierra y el foco vuelve a donde estaba; ↑/↓ recorren las opciones.
414function wireMenu(menu, returnFocus) {
415 menu.setAttribute('role', 'menu');
416 const items = () => [...menu.querySelectorAll('[role="menuitem"]')];
417 const close = () => { menu.remove(); document.removeEventListener('mousedown', outside); returnFocus?.focus?.(); };
418 const outside = ev => { if (!menu.contains(ev.target)) close(); };
419 menu.addEventListener('keydown', e => {
420 const list = items(), i = list.indexOf(document.activeElement);
421 if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
422 else if (e.key === 'ArrowDown') { e.preventDefault(); list[(i + 1) % list.length]?.focus(); }
423 else if (e.key === 'ArrowUp') { e.preventDefault(); list[(i - 1 + list.length) % list.length]?.focus(); }
424 });
425 setTimeout(() => document.addEventListener('mousedown', outside), 0);
426 // dentro de la ventana aunque se abra pegado al borde
427 const r = menu.getBoundingClientRect();
428 if (r.right > innerWidth) menu.style.left = Math.max(4, innerWidth - r.width - 4) + 'px';
429 if (r.bottom > innerHeight) menu.style.top = Math.max(4, innerHeight - r.height - 4) + 'px';
430 items()[0]?.focus();
431 return close;
432}
433function menuButton(label, fn, cls) {
434 const b = document.createElement('button');
435 b.type = 'button';
436 b.className = 'tm-item' + (cls ? ' ' + cls : '');
437 b.setAttribute('role', 'menuitem');
438 b.textContent = label;
439 b.dataset.run = '1';
440 b._run = fn;
441 return b;
442}
443
444// ---------- menú contextual de las pestañas (botón derecho, estilo VS Code) ----------
445function openTabMenu(x, y, path) {
446 document.getElementById('tab-menu')?.remove();
447 const volver = document.activeElement;
448 const menu = document.createElement('div');
449 menu.id = 'tab-menu';
450 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
451 const i = tabs.findIndex(tb => tb.path === path);
452 const tab = tabs[i];
453 const items = [];
454 items.push([t('tmClose'), () => closeTab(path)]);
455 items.push([t('tmCloseOthers'), () => closeTabs(tabs.filter(tb => tb.path !== path).map(tb => tb.path))]);
456 const toTheRight = tabs.slice(i + 1).map(tb => tb.path);
457 if (toTheRight.length) items.push([t('tmCloseRight'), () => closeTabs(toTheRight)]);
458 items.push([t('tmCloseAll'), () => closeTabs(tabs.map(tb => tb.path))]);
459 items.push(['sep']);
460 items.push([t('tmCopyPath'), () => copyPath(path)]);
461 if (PREVIEWABLE.has(langOf(path))) {
462 items.push([tab?.preview ? t('tmViewSource') : t('tmPreview'), () => togglePreview(path)]);
463 }
464 let close = () => menu.remove();
465 for (const item of items) {
466 if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep', role: 'separator' })); continue; }
467 const [label, fn] = item;
468 const b = menuButton(label, fn);
469 b.onclick = () => { close(); fn(); };
470 menu.appendChild(b);
471 }
472 document.body.appendChild(menu);
473 close = wireMenu(menu, volver);
474}
475
476// Copiar ruta: antes copiaba sin decir nada.
477function copyPath(path) {
478 const done = () => alertBar(t('pathCopied', { path }));
479 if (navigator.clipboard?.writeText) navigator.clipboard.writeText(path).then(done, () => alertBar(t('pathCopyFailed')));
480 else alertBar(t('pathCopyFailed'));
481}
482
483let alertTimer;
484function alertBar(msg) {
485 const el = $('statusbar');
486 el.textContent = msg;
487 clearTimeout(alertTimer);
488 alertTimer = setTimeout(() => { el.textContent = ''; }, 4000);
489}
490
491// ---------- árbol lateral ----------
492const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
493
494// Carpetas abiertas, por ruta. refreshTree() reconstruye el árbol entero (cada
495// escritura del agente, cada orden del terminal que toca ficheros, crear,
496// renombrar o borrar) y antes lo dejaba TODO plegado: perdías el sitio tras
497// cada edición. Ahora se vuelven a abrir las que lo estaban.
498const openDirs = new Set();
499
500export async function refreshTree(handle = null) {
501 const rootHandle = handle || window.__elffussProject;
502 if (!rootHandle) return;
503 if (handle) openDirs.clear(); // otro proyecto: empieza plegado
504 window.__elffussProject = rootHandle;
505 const cont = $('tree');
506 const scroll = cont.scrollTop;
507 const conFoco = cont.contains(document.activeElement) ? document.activeElement.dataset?.path : null;
508 const ul = await renderDir(rootHandle, '');
509 ul.setAttribute('role', 'tree');
510 ul.setAttribute('aria-label', t('explorer'));
511 cont.replaceChildren(ul);
512 cont.scrollTop = scroll;
513 markActive();
514 if (conFoco != null) {
515 const f = cont.querySelector(`[data-path="${CSS.escape(conFoco)}"]`);
516 if (f) { setRoving(f); f.focus(); }
517 }
518 setupTreeMenu();
519}
520
521// El fichero abierto se marca en el árbol (antes no había forma de saber cuál
522// era), y es la fila por la que entra el foco con Tab.
523function markActive() {
524 const cont = $('tree');
525 if (!cont) return;
526 let fila = null;
527 for (const f of cont.querySelectorAll('.file')) {
528 const on = f.dataset.path === active;
529 f.classList.toggle('active', on);
530 f.setAttribute('aria-selected', on ? 'true' : 'false');
531 if (on) fila = f;
532 }
533 if (!cont.querySelector('[tabindex="0"]') || fila) setRoving(fila || cont.querySelector('summary, .file'));
534}
535function setRoving(row) {
536 if (!row) return;
537 for (const r of $('tree').querySelectorAll('[tabindex="0"]')) if (r !== row) r.tabIndex = -1;
538 row.tabIndex = 0;
539}
540const visibleRows = () => [...$('tree').querySelectorAll('summary, .file')].filter(r => r.offsetParent !== null);
541
542// ---------- menú contextual del árbol (botón derecho, estilo VS Code) ----------
543let treeMenuWired = false;
544function setupTreeMenu() {
545 if (treeMenuWired) return;
546 treeMenuWired = true;
547 const tree = $('tree');
548 tree.addEventListener('contextmenu', e => {
549 e.preventDefault();
550 const node = e.target.closest('[data-path]');
551 const path = node ? node.dataset.path : '';
552 const kind = node ? node.dataset.kind : 'directory'; // vacío = raíz
553 openTreeMenu(e.clientX, e.clientY, path, kind);
554 });
555 // Teclado, como un árbol de verdad: ↑/↓ entre filas visibles, → abre una
556 // carpeta, ← la cierra (o sube a la carpeta madre), Enter abre el fichero,
557 // Shift+F10 o la tecla de menú abren el menú contextual. Antes las filas de
558 // fichero eran <span> sin foco y el árbol solo se usaba con el ratón.
559 tree.addEventListener('keydown', e => {
560 const row = e.target.closest?.('summary, .file');
561 if (!row) return;
562 const rows = visibleRows(), i = rows.indexOf(row);
563 const go = r => { if (r) { e.preventDefault(); setRoving(r); r.focus(); } };
564 const det = row.tagName === 'SUMMARY' ? row.parentElement : null;
565 if (e.key === 'ArrowDown') go(rows[i + 1]);
566 else if (e.key === 'ArrowUp') go(rows[i - 1]);
567 else if (e.key === 'Home') go(rows[0]);
568 else if (e.key === 'End') go(rows[rows.length - 1]);
569 else if (e.key === 'ArrowRight' && det) { e.preventDefault(); if (!det.open) det.open = true; else go(rows[i + 1]); }
570 else if (e.key === 'ArrowLeft') {
571 if (det && det.open) { e.preventDefault(); det.open = false; }
572 else go(row.closest('li')?.parentElement?.closest('details')?.querySelector(':scope > summary'));
573 }
574 else if (e.key === 'Enter' && !det) { e.preventDefault(); openFile(row.dataset.path); }
575 else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
576 e.preventDefault();
577 const r = row.getBoundingClientRect();
578 openTreeMenu(r.left + 12, r.bottom, row.dataset.path, row.dataset.kind);
579 }
580 });
581 tree.addEventListener('focusin', e => { const row = e.target.closest?.('summary, .file'); if (row) setRoving(row); });
582}
583
584// resuelve el handle de un directorio por su ruta (segmentos desde la raíz)
585async function dirByPath(path) {
586 let dir = code.handle();
587 for (const s of (path || '').split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(s);
588 return dir;
589}
590const parentOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
591const baseOf = p => p.split('/').pop();
592
593async function fsCreate(parentPath, name, isDir) {
594 const dir = await dirByPath(parentPath);
595 if (isDir) await dir.getDirectoryHandle(name, { create: true });
596 else { const fh = await dir.getFileHandle(name, { create: true }); const w = await fh.createWritable(); await w.close(); }
597}
598async function fsDelete(path, kind) {
599 const dir = await dirByPath(parentOf(path));
600 await dir.removeEntry(baseOf(path), { recursive: kind === 'directory' });
601}
602// copia recursiva (la File System API no tiene rename nativo). El fichero se
603// copia como Blob, no como texto: pasarlo por .text() estropeaba cualquier
604// binario (una imagen, un .zip) al renombrarlo.
605async function fsCopy(srcDir, name, dstDir, newName) {
606 const src = await (srcDir.getDirectoryHandle(name).catch(() => null));
607 if (src) { // directorio
608 const nd = await dstDir.getDirectoryHandle(newName, { create: true });
609 for await (const e of src.values()) await fsCopy(src, e.name, nd, e.name);
610 } else { // fichero
611 const file = await (await srcDir.getFileHandle(name)).getFile();
612 const fh = await dstDir.getFileHandle(newName, { create: true });
613 const w = await fh.createWritable(); await w.write(file); await w.close();
614 }
615}
616async function fsRename(path, kind, newName) {
617 const parent = await dirByPath(parentOf(path));
618 await fsCopy(parent, baseOf(path), parent, newName);
619 await parent.removeEntry(baseOf(path), { recursive: kind === 'directory' });
620}
621
622// Lo que cuelga de `path` (el fichero o todo lo que hay dentro de la carpeta).
623const under = (p, path, kind) => kind === 'directory' ? p.startsWith(path + '/') : p === path;
624
625// Renombrar mueve también las pestañas abiertas: antes seguían apuntando a la
626// ruta vieja, y guardar recreaba el fichero con el nombre antiguo.
627function renameTabs(path, nuevo, kind) {
628 for (const tb of tabs) if (under(tb.path, path, kind)) {
629 const np = kind === 'directory' ? nuevo + tb.path.slice(path.length) : nuevo;
630 if (active === tb.path) { active = np; code.setCurrentFile(np); }
631 tb.path = np;
632 }
633 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) { openDirs.delete(d); openDirs.add(nuevo + d.slice(path.length)); }
634 renderTabs();
635}
636// Borrar cierra sus pestañas. Si una tenía cambios sin guardar no se tira: se
637// queda abierta y marcada (guardarla vuelve a crear el fichero).
638function dropTabs(path, kind) {
639 for (let i = tabs.length - 1; i >= 0; i--) {
640 if (!under(tabs[i].path, path, kind)) continue;
641 if (tabs[i].dirty) tabs[i].deleted = true;
642 else closeTabNow(i);
643 }
644 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) openDirs.delete(d);
645 renderTabs();
646 applyView();
647}
648
649function openTreeMenu(x, y, path, kind) {
650 document.getElementById('tree-menu')?.remove();
651 const volver = document.activeElement;
652 const menu = document.createElement('div');
653 menu.id = 'tree-menu';
654 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
655 // en un fichero, el "aquí dentro" es su carpeta; en carpeta/raíz, ella misma
656 const container = kind === 'file' ? parentOf(path) : path;
657 const items = [];
658 items.push([t('tmNewFile'), async () => {
659 const name = prompt(t('promptNewFile')); if (!name?.trim()) return;
660 if (container) openDirs.add(container);
661 await fsCreate(container, name.trim(), false); code.invalidateFileList?.();
662 await refreshTree(); openFile(container ? container + '/' + name.trim() : name.trim());
663 }]);
664 items.push([t('tmNewFolder'), async () => {
665 const name = prompt(t('promptNewFolder')); if (!name?.trim()) return;
666 if (container) openDirs.add(container);
667 await fsCreate(container, name.trim(), true); code.invalidateFileList?.(); await refreshTree();
668 alertBar(t('created', { name: name.trim() }));
669 }]);
670 if (path) {
671 if (kind === 'file') items.push([t('tmOpen'), () => openFile(path)]);
672 if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push([t('tmPreview'), () => togglePreview(path)]);
673 items.push([t('tmRename'), async () => {
674 const name = prompt(t('promptRename'), baseOf(path))?.trim(); if (!name || name === baseOf(path)) return;
675 const nuevo = (parentOf(path) ? parentOf(path) + '/' : '') + name;
676 await fsRename(path, kind, name); code.invalidateFileList?.();
677 renameTabs(path, nuevo, kind);
678 await refreshTree();
679 alertBar(t('renamed', { from: baseOf(path), to: name }));
680 }]);
681 items.push([t('tmDelete'), async () => {
682 if (!confirm(t('confirmDelete', { name: baseOf(path) }))) return;
683 await fsDelete(path, kind); code.invalidateFileList?.();
684 dropTabs(path, kind);
685 await refreshTree();
686 alertBar(t('deleted', { name: baseOf(path) }));
687 }, 'danger']);
688 }
689 let close = () => menu.remove();
690 for (const [label, fn, cls] of items) {
691 const b = menuButton(label, fn, cls);
692 b.onclick = async () => { close(); try { await fn(); } catch (err) { alert(t('opFailed', { e: err.message })); } };
693 menu.appendChild(b);
694 }
695 document.body.appendChild(menu);
696 close = wireMenu(menu, volver);
697}
698
699const TREE_MAX_ENTRIES = 200;
700async function renderDir(dir, prefix) {
701 const ul = document.createElement('ul');
702 if (prefix) ul.setAttribute('role', 'group');
703 const entries = [];
704 for await (const e of dir.values()) if (!IGNORE.has(e.name)) entries.push(e);
705 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
706 for (const e of entries.slice(0, TREE_MAX_ENTRIES)) {
707 const li = document.createElement('li');
708 li.setAttribute('role', 'none');
709 const p = prefix ? prefix + '/' + e.name : e.name;
710 if (e.kind === 'directory') {
711 const det = document.createElement('details');
712 const sum = document.createElement('summary');
713 sum.innerHTML = folderIcon();
714 sum.appendChild(document.createTextNode(e.name));
715 sum.dataset.path = p; sum.dataset.kind = 'directory';
716 sum.setAttribute('role', 'treeitem');
717 sum.setAttribute('aria-expanded', 'false');
718 sum.tabIndex = -1;
719 det.appendChild(sum);
720 det.addEventListener('toggle', async () => {
721 sum.setAttribute('aria-expanded', det.open ? 'true' : 'false');
722 if (det.open) openDirs.add(p); else openDirs.delete(p);
723 if (det.open && det.children.length === 1) {
724 det.appendChild(await renderDir(e, p));
725 markActive();
726 }
727 });
728 // Estaba abierta antes del repintado: se reabre ya con su contenido.
729 if (openDirs.has(p)) {
730 det.appendChild(await renderDir(e, p));
731 det.open = true;
732 sum.setAttribute('aria-expanded', 'true');
733 }
734 li.appendChild(det);
735 } else {
736 const a = document.createElement('span');
737 a.className = 'file';
738 a.innerHTML = fileIcon(e.name);
739 a.appendChild(document.createTextNode(e.name));
740 a.dataset.path = p; a.dataset.kind = 'file';
741 a.setAttribute('role', 'treeitem');
742 a.tabIndex = -1;
743 a.onclick = () => openFile(p);
744 li.appendChild(a);
745 }
746 ul.appendChild(li);
747 }
748 // Una carpeta con más de 200 entradas se cortaba sin decirlo.
749 if (entries.length > TREE_MAX_ENTRIES) {
750 const li = document.createElement('li');
751 li.className = 'tree-more';
752 li.setAttribute('role', 'none');
753 li.textContent = t('treeMore', { n: entries.length - TREE_MAX_ENTRIES });
754 ul.appendChild(li);
755 }
756 return ul;
757}
758
759// ---------- extensiones de VS Code (js/ext/) ----------
760// Temas de color, gramáticas TextMate, snippets y lenguajes. El host solo se
761// carga si hay alguna extensión activa o un tema elegido, o al abrir el panel
762// de extensiones: sin ellas, Code arranca exactamente igual que siempre.
763let extCarga = null;
764async function hayExtensiones() {
765 try { const p = localStorage.getItem('elffusscode.theme'); if (p && p !== 'vs-dark') return true; } catch { /* sin almacenamiento */ }
766 const lista = await db.get('kv', 'extensions').catch(() => null);
767 return Array.isArray(lista) && lista.some(e => e && e.enabled);
768}
769export async function loadExt(force = true) {
770 if (ext) return ext;
771 if (!monacoRef || (!force && !(await hayExtensiones()))) return null;
772 extCarga ??= import('./ext/host.js').then(m => m.init(monacoRef, { onLanguagesChanged: refreshLanguages }));
773 try { ext = await extCarga; }
774 catch (e) { extCarga = null; console.warn('[elffuss] extensiones no disponibles:', e?.message || e); }
775 return ext;
776}
777// Tras instalar, activar o desactivar: cada pestaña abierta, con su lenguaje y
778// su gramática al día (o de vuelta a lo de serie).
779async function refreshLanguages() {
780 for (const tab of [...tabs]) {
781 if (tab.model.isDisposed()) continue;
782 const lang = await langDe(tab.path, tab.model.getLineContent(1));
783 await ext?.prepareLanguage(lang);
784 if (!tab.model.isDisposed() && tab.model.getLanguageId() !== lang) monacoRef.editor.setModelLanguage(tab.model, lang);
785 }
786}