Elffuss BraidHub

utopia-ia/elffuss-code public

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