Elffuss BraidHub

utopia-ia/elffuss-code public

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