Elffuss BraidHub

utopia-ia/elffuss-code public

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