Elffuss BraidHub

utopia-ia/elffuss-code public

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