Elffuss BraidHub

utopia-ia/elffuss-code public

88b3f553b4fc · 30.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 try {
220 await writeOwn(tab.path, tab.model.getValue());
221 } catch (e) {
222 alertBar(t('saveFailed', { path: tab.path, e: e?.message || e }));
223 return false;
224 }
225 tab.dirty = false;
226 tab.deleted = false;
227 renderTabs();
228 alertBar(t('saved', { path: tab.path }));
229 return true;
230}
231// Exportada: la usan el menú File › Guardar y la paleta. Antes ellos lanzaban
232// la acción 'workbench.action.files.save', que no existe en el Monaco suelto,
233// y no pasaba nada.
234export async function saveActive() {
235 const tab = tabs.find(t => t.path === active);
236 if (!tab) { alertBar(t('noFileOpen')); return false; }
237 return saveTab(tab);
238}
239
240// Cerrar una pestaña con cambios sin guardar PREGUNTA: Guardar, No guardar o
241// Cancelar. Antes se cerraba y los cambios se perdían sin aviso.
242function askDirty(tab) {
243 return new Promise(resolve => {
244 const dlg = document.createElement('dialog');
245 dlg.id = 'dirty-dialog';
246 dlg.setAttribute('aria-labelledby', 'dirty-title');
247 const h = document.createElement('p'); h.id = 'dirty-title'; h.className = 'dd-title';
248 h.textContent = t('dirtyTitle', { name: baseOf(tab.path) });
249 const sub = document.createElement('p'); sub.className = 'dd-sub'; sub.textContent = t('dirtyBody');
250 const row = document.createElement('div'); row.className = 'dd-row';
251 let answer = 'cancel';
252 const mk = (label, val, cls) => {
253 const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.dataset.val = val;
254 if (cls) b.className = cls;
255 b.onclick = () => { answer = val; dlg.close(); };
256 row.appendChild(b); return b;
257 };
258 const save = mk(t('dirtySave'), 'save', 'dd-primary');
259 mk(t('dirtyDiscard'), 'discard');
260 mk(t('dirtyCancel'), 'cancel');
261 dlg.append(h, sub, row);
262 dlg.addEventListener('close', () => { dlg.remove(); resolve(answer); }, { once: true });
263 document.body.appendChild(dlg);
264 dlg.showModal();
265 save.focus();
266 });
267}
268
269// Devuelve false si el usuario canceló (la pestaña sigue abierta).
270async function closeTab(path) {
271 const i = tabs.findIndex(t => t.path === path);
272 if (i < 0) return true;
273 if (tabs[i].dirty) {
274 const r = await askDirty(tabs[i]);
275 if (r === 'cancel') return false;
276 if (r === 'save' && !(await saveTab(tabs[i]))) return false;
277 }
278 const j = tabs.findIndex(t => t.path === path); // el diálogo es asíncrono
279 if (j < 0) return true;
280 closeTabNow(j);
281 renderTabs();
282 await applyView();
283 return true;
284}
285// Varias seguidas («Cerrar otras/todas»): se para en la primera que cancelas.
286async function closeTabs(paths) {
287 for (const p of paths) if (!(await closeTab(p))) return false;
288 return true;
289}
290
291function closeTabNow(i) {
292 const path = tabs[i].path;
293 tabs[i].model.dispose();
294 tabs.splice(i, 1);
295 if (active === path) {
296 active = tabs[i - 1]?.path || tabs[0]?.path || null;
297 code.setCurrentFile(active);
298 if (active) { editor.setModel(tabs.find(t => t.path === active).model); setEmptyState(false); }
299 else { editor.setModel(monacoRef.editor.createModel('', 'plaintext')); setEmptyState(true); }
300 }
301}
302
303// Estado vacío: cuando no hay ningún fichero abierto, en vez de dejar el Monaco
304// en blanco con un «1», mostramos un placeholder limpio.
305export function setEmptyState(on) {
306 let el = document.getElementById('editor-empty');
307 if (!el) {
308 el = document.createElement('div');
309 el.id = 'editor-empty';
310 el.innerHTML = '<img src="img/elffuss-code.svg" alt=""><p></p>';
311 el.querySelector('p').textContent = t('editorEmpty');
312 $('editor').parentElement.appendChild(el);
313 }
314 el.style.display = on ? 'flex' : 'none';
315}
316
317function renderTabs() {
318 const bar = $('tabs-bar');
319 bar.replaceChildren();
320 bar.setAttribute('role', 'tablist');
321 bar.setAttribute('aria-label', t('editorTabs'));
322 for (const tb of tabs) {
323 const el = document.createElement('div');
324 const on = tb.path === active;
325 el.className = 'tab' + (on ? ' active' : '') + (tb.preview ? ' tab-preview' : '');
326 el.dataset.path = tb.path;
327 // Pestañas de verdad para el teclado y los lectores de pantalla: antes eran
328 // <div> sin foco. La activa entra con Tab; ←/→ se mueven entre ellas.
329 el.setAttribute('role', 'tab');
330 el.setAttribute('aria-selected', on ? 'true' : 'false');
331 el.tabIndex = on ? 0 : -1;
332 const ico = document.createElement('span');
333 ico.className = 'tab-ico';
334 ico.innerHTML = fileIcon(tb.path.split('/').pop());
335 const name = document.createElement('span');
336 name.className = 'tab-name';
337 name.textContent = tb.path.split('/').pop();
338 name.title = tb.deleted ? tb.path + ' · ' + t('fileDeletedDirty') : tb.path;
339 if (tb.deleted) name.classList.add('deleted');
340 // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón.
341 // Un <button> con nombre accesible (antes un <b> que no recibía el foco).
342 const x = document.createElement('button');
343 x.type = 'button';
344 x.className = 'tab-x' + (tb.dirty ? ' dirty' : '');
345 x.textContent = tb.dirty ? '●' : '×';
346 x.tabIndex = -1;
347 x.setAttribute('aria-label', t(tb.dirty ? 'closeFileDirty' : 'closeFile', { name: baseOf(tb.path) }));
348 x.title = x.getAttribute('aria-label');
349 x.onclick = e => { e.stopPropagation(); closeTab(tb.path); };
350 el.append(ico, name, x);
351 el.onclick = () => openFile(tb.path);
352 el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, tb.path); };
353 el.onkeydown = e => {
354 const i = tabs.indexOf(tb);
355 if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
356 e.preventDefault();
357 const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
358 if (next) openFile(next.path).then(() => bar.querySelector('.tab.active')?.focus());
359 } else if (e.key === 'Delete' || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'w')) {
360 e.preventDefault(); closeTab(tb.path);
361 } else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
362 e.preventDefault(); const r = el.getBoundingClientRect(); openTabMenu(r.left, r.bottom, tb.path);
363 }
364 };
365 bar.appendChild(el);
366 }
367 markActive();
368}
369
370// ---------- menús contextuales (pestañas y árbol): teclado y Escape ----------
371// Escape los cierra y el foco vuelve a donde estaba; ↑/↓ recorren las opciones.
372function wireMenu(menu, returnFocus) {
373 menu.setAttribute('role', 'menu');
374 const items = () => [...menu.querySelectorAll('[role="menuitem"]')];
375 const close = () => { menu.remove(); document.removeEventListener('mousedown', outside); returnFocus?.focus?.(); };
376 const outside = ev => { if (!menu.contains(ev.target)) close(); };
377 menu.addEventListener('keydown', e => {
378 const list = items(), i = list.indexOf(document.activeElement);
379 if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
380 else if (e.key === 'ArrowDown') { e.preventDefault(); list[(i + 1) % list.length]?.focus(); }
381 else if (e.key === 'ArrowUp') { e.preventDefault(); list[(i - 1 + list.length) % list.length]?.focus(); }
382 });
383 setTimeout(() => document.addEventListener('mousedown', outside), 0);
384 // dentro de la ventana aunque se abra pegado al borde
385 const r = menu.getBoundingClientRect();
386 if (r.right > innerWidth) menu.style.left = Math.max(4, innerWidth - r.width - 4) + 'px';
387 if (r.bottom > innerHeight) menu.style.top = Math.max(4, innerHeight - r.height - 4) + 'px';
388 items()[0]?.focus();
389 return close;
390}
391function menuButton(label, fn, cls) {
392 const b = document.createElement('button');
393 b.type = 'button';
394 b.className = 'tm-item' + (cls ? ' ' + cls : '');
395 b.setAttribute('role', 'menuitem');
396 b.textContent = label;
397 b.dataset.run = '1';
398 b._run = fn;
399 return b;
400}
401
402// ---------- menú contextual de las pestañas (botón derecho, estilo VS Code) ----------
403function openTabMenu(x, y, path) {
404 document.getElementById('tab-menu')?.remove();
405 const volver = document.activeElement;
406 const menu = document.createElement('div');
407 menu.id = 'tab-menu';
408 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
409 const i = tabs.findIndex(tb => tb.path === path);
410 const tab = tabs[i];
411 const items = [];
412 items.push([t('tmClose'), () => closeTab(path)]);
413 items.push([t('tmCloseOthers'), () => closeTabs(tabs.filter(tb => tb.path !== path).map(tb => tb.path))]);
414 const toTheRight = tabs.slice(i + 1).map(tb => tb.path);
415 if (toTheRight.length) items.push([t('tmCloseRight'), () => closeTabs(toTheRight)]);
416 items.push([t('tmCloseAll'), () => closeTabs(tabs.map(tb => tb.path))]);
417 items.push(['sep']);
418 items.push([t('tmCopyPath'), () => copyPath(path)]);
419 if (PREVIEWABLE.has(langOf(path))) {
420 items.push([tab?.preview ? t('tmViewSource') : t('tmPreview'), () => togglePreview(path)]);
421 }
422 let close = () => menu.remove();
423 for (const item of items) {
424 if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep', role: 'separator' })); continue; }
425 const [label, fn] = item;
426 const b = menuButton(label, fn);
427 b.onclick = () => { close(); fn(); };
428 menu.appendChild(b);
429 }
430 document.body.appendChild(menu);
431 close = wireMenu(menu, volver);
432}
433
434// Copiar ruta: antes copiaba sin decir nada.
435function copyPath(path) {
436 const done = () => alertBar(t('pathCopied', { path }));
437 if (navigator.clipboard?.writeText) navigator.clipboard.writeText(path).then(done, () => alertBar(t('pathCopyFailed')));
438 else alertBar(t('pathCopyFailed'));
439}
440
441let alertTimer;
442function alertBar(msg) {
443 const el = $('statusbar');
444 el.textContent = msg;
445 clearTimeout(alertTimer);
446 alertTimer = setTimeout(() => { el.textContent = ''; }, 4000);
447}
448
449// ---------- árbol lateral ----------
450const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
451
452// Carpetas abiertas, por ruta. refreshTree() reconstruye el árbol entero (cada
453// escritura del agente, cada orden del terminal que toca ficheros, crear,
454// renombrar o borrar) y antes lo dejaba TODO plegado: perdías el sitio tras
455// cada edición. Ahora se vuelven a abrir las que lo estaban.
456const openDirs = new Set();
457
458export async function refreshTree(handle = null) {
459 const rootHandle = handle || window.__elffussProject;
460 if (!rootHandle) return;
461 if (handle) openDirs.clear(); // otro proyecto: empieza plegado
462 window.__elffussProject = rootHandle;
463 const cont = $('tree');
464 const scroll = cont.scrollTop;
465 const conFoco = cont.contains(document.activeElement) ? document.activeElement.dataset?.path : null;
466 const ul = await renderDir(rootHandle, '');
467 ul.setAttribute('role', 'tree');
468 ul.setAttribute('aria-label', t('explorer'));
469 cont.replaceChildren(ul);
470 cont.scrollTop = scroll;
471 markActive();
472 if (conFoco != null) {
473 const f = cont.querySelector(`[data-path="${CSS.escape(conFoco)}"]`);
474 if (f) { setRoving(f); f.focus(); }
475 }
476 setupTreeMenu();
477}
478
479// El fichero abierto se marca en el árbol (antes no había forma de saber cuál
480// era), y es la fila por la que entra el foco con Tab.
481function markActive() {
482 const cont = $('tree');
483 if (!cont) return;
484 let fila = null;
485 for (const f of cont.querySelectorAll('.file')) {
486 const on = f.dataset.path === active;
487 f.classList.toggle('active', on);
488 f.setAttribute('aria-selected', on ? 'true' : 'false');
489 if (on) fila = f;
490 }
491 if (!cont.querySelector('[tabindex="0"]') || fila) setRoving(fila || cont.querySelector('summary, .file'));
492}
493function setRoving(row) {
494 if (!row) return;
495 for (const r of $('tree').querySelectorAll('[tabindex="0"]')) if (r !== row) r.tabIndex = -1;
496 row.tabIndex = 0;
497}
498const visibleRows = () => [...$('tree').querySelectorAll('summary, .file')].filter(r => r.offsetParent !== null);
499
500// ---------- menú contextual del árbol (botón derecho, estilo VS Code) ----------
501let treeMenuWired = false;
502function setupTreeMenu() {
503 if (treeMenuWired) return;
504 treeMenuWired = true;
505 const tree = $('tree');
506 tree.addEventListener('contextmenu', e => {
507 e.preventDefault();
508 const node = e.target.closest('[data-path]');
509 const path = node ? node.dataset.path : '';
510 const kind = node ? node.dataset.kind : 'directory'; // vacío = raíz
511 openTreeMenu(e.clientX, e.clientY, path, kind);
512 });
513 // Teclado, como un árbol de verdad: ↑/↓ entre filas visibles, → abre una
514 // carpeta, ← la cierra (o sube a la carpeta madre), Enter abre el fichero,
515 // Shift+F10 o la tecla de menú abren el menú contextual. Antes las filas de
516 // fichero eran <span> sin foco y el árbol solo se usaba con el ratón.
517 tree.addEventListener('keydown', e => {
518 const row = e.target.closest?.('summary, .file');
519 if (!row) return;
520 const rows = visibleRows(), i = rows.indexOf(row);
521 const go = r => { if (r) { e.preventDefault(); setRoving(r); r.focus(); } };
522 const det = row.tagName === 'SUMMARY' ? row.parentElement : null;
523 if (e.key === 'ArrowDown') go(rows[i + 1]);
524 else if (e.key === 'ArrowUp') go(rows[i - 1]);
525 else if (e.key === 'Home') go(rows[0]);
526 else if (e.key === 'End') go(rows[rows.length - 1]);
527 else if (e.key === 'ArrowRight' && det) { e.preventDefault(); if (!det.open) det.open = true; else go(rows[i + 1]); }
528 else if (e.key === 'ArrowLeft') {
529 if (det && det.open) { e.preventDefault(); det.open = false; }
530 else go(row.closest('li')?.parentElement?.closest('details')?.querySelector(':scope > summary'));
531 }
532 else if (e.key === 'Enter' && !det) { e.preventDefault(); openFile(row.dataset.path); }
533 else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
534 e.preventDefault();
535 const r = row.getBoundingClientRect();
536 openTreeMenu(r.left + 12, r.bottom, row.dataset.path, row.dataset.kind);
537 }
538 });
539 tree.addEventListener('focusin', e => { const row = e.target.closest?.('summary, .file'); if (row) setRoving(row); });
540}
541
542// resuelve el handle de un directorio por su ruta (segmentos desde la raíz)
543async function dirByPath(path) {
544 let dir = code.handle();
545 for (const s of (path || '').split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(s);
546 return dir;
547}
548const parentOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
549const baseOf = p => p.split('/').pop();
550
551async function fsCreate(parentPath, name, isDir) {
552 const dir = await dirByPath(parentPath);
553 if (isDir) await dir.getDirectoryHandle(name, { create: true });
554 else { const fh = await dir.getFileHandle(name, { create: true }); const w = await fh.createWritable(); await w.close(); }
555}
556async function fsDelete(path, kind) {
557 const dir = await dirByPath(parentOf(path));
558 await dir.removeEntry(baseOf(path), { recursive: kind === 'directory' });
559}
560// copia recursiva (la File System API no tiene rename nativo). El fichero se
561// copia como Blob, no como texto: pasarlo por .text() estropeaba cualquier
562// binario (una imagen, un .zip) al renombrarlo.
563async function fsCopy(srcDir, name, dstDir, newName) {
564 const src = await (srcDir.getDirectoryHandle(name).catch(() => null));
565 if (src) { // directorio
566 const nd = await dstDir.getDirectoryHandle(newName, { create: true });
567 for await (const e of src.values()) await fsCopy(src, e.name, nd, e.name);
568 } else { // fichero
569 const file = await (await srcDir.getFileHandle(name)).getFile();
570 const fh = await dstDir.getFileHandle(newName, { create: true });
571 const w = await fh.createWritable(); await w.write(file); await w.close();
572 }
573}
574async function fsRename(path, kind, newName) {
575 const parent = await dirByPath(parentOf(path));
576 await fsCopy(parent, baseOf(path), parent, newName);
577 await parent.removeEntry(baseOf(path), { recursive: kind === 'directory' });
578}
579
580// Lo que cuelga de `path` (el fichero o todo lo que hay dentro de la carpeta).
581const under = (p, path, kind) => kind === 'directory' ? p.startsWith(path + '/') : p === path;
582
583// Renombrar mueve también las pestañas abiertas: antes seguían apuntando a la
584// ruta vieja, y guardar recreaba el fichero con el nombre antiguo.
585function renameTabs(path, nuevo, kind) {
586 for (const tb of tabs) if (under(tb.path, path, kind)) {
587 const np = kind === 'directory' ? nuevo + tb.path.slice(path.length) : nuevo;
588 if (active === tb.path) { active = np; code.setCurrentFile(np); }
589 tb.path = np;
590 }
591 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) { openDirs.delete(d); openDirs.add(nuevo + d.slice(path.length)); }
592 renderTabs();
593}
594// Borrar cierra sus pestañas. Si una tenía cambios sin guardar no se tira: se
595// queda abierta y marcada (guardarla vuelve a crear el fichero).
596function dropTabs(path, kind) {
597 for (let i = tabs.length - 1; i >= 0; i--) {
598 if (!under(tabs[i].path, path, kind)) continue;
599 if (tabs[i].dirty) tabs[i].deleted = true;
600 else closeTabNow(i);
601 }
602 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) openDirs.delete(d);
603 renderTabs();
604 applyView();
605}
606
607function openTreeMenu(x, y, path, kind) {
608 document.getElementById('tree-menu')?.remove();
609 const volver = document.activeElement;
610 const menu = document.createElement('div');
611 menu.id = 'tree-menu';
612 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
613 // en un fichero, el "aquí dentro" es su carpeta; en carpeta/raíz, ella misma
614 const container = kind === 'file' ? parentOf(path) : path;
615 const items = [];
616 items.push([t('tmNewFile'), async () => {
617 const name = prompt(t('promptNewFile')); if (!name?.trim()) return;
618 if (container) openDirs.add(container);
619 await fsCreate(container, name.trim(), false); code.invalidateFileList?.();
620 await refreshTree(); openFile(container ? container + '/' + name.trim() : name.trim());
621 }]);
622 items.push([t('tmNewFolder'), async () => {
623 const name = prompt(t('promptNewFolder')); if (!name?.trim()) return;
624 if (container) openDirs.add(container);
625 await fsCreate(container, name.trim(), true); code.invalidateFileList?.(); await refreshTree();
626 alertBar(t('created', { name: name.trim() }));
627 }]);
628 if (path) {
629 if (kind === 'file') items.push([t('tmOpen'), () => openFile(path)]);
630 if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push([t('tmPreview'), () => togglePreview(path)]);
631 items.push([t('tmRename'), async () => {
632 const name = prompt(t('promptRename'), baseOf(path))?.trim(); if (!name || name === baseOf(path)) return;
633 const nuevo = (parentOf(path) ? parentOf(path) + '/' : '') + name;
634 await fsRename(path, kind, name); code.invalidateFileList?.();
635 renameTabs(path, nuevo, kind);
636 await refreshTree();
637 alertBar(t('renamed', { from: baseOf(path), to: name }));
638 }]);
639 items.push([t('tmDelete'), async () => {
640 if (!confirm(t('confirmDelete', { name: baseOf(path) }))) return;
641 await fsDelete(path, kind); code.invalidateFileList?.();
642 dropTabs(path, kind);
643 await refreshTree();
644 alertBar(t('deleted', { name: baseOf(path) }));
645 }, 'danger']);
646 }
647 let close = () => menu.remove();
648 for (const [label, fn, cls] of items) {
649 const b = menuButton(label, fn, cls);
650 b.onclick = async () => { close(); try { await fn(); } catch (err) { alert(t('opFailed', { e: err.message })); } };
651 menu.appendChild(b);
652 }
653 document.body.appendChild(menu);
654 close = wireMenu(menu, volver);
655}
656
657const TREE_MAX_ENTRIES = 200;
658async function renderDir(dir, prefix) {
659 const ul = document.createElement('ul');
660 if (prefix) ul.setAttribute('role', 'group');
661 const entries = [];
662 for await (const e of dir.values()) if (!IGNORE.has(e.name)) entries.push(e);
663 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
664 for (const e of entries.slice(0, TREE_MAX_ENTRIES)) {
665 const li = document.createElement('li');
666 li.setAttribute('role', 'none');
667 const p = prefix ? prefix + '/' + e.name : e.name;
668 if (e.kind === 'directory') {
669 const det = document.createElement('details');
670 const sum = document.createElement('summary');
671 sum.innerHTML = folderIcon();
672 sum.appendChild(document.createTextNode(e.name));
673 sum.dataset.path = p; sum.dataset.kind = 'directory';
674 sum.setAttribute('role', 'treeitem');
675 sum.setAttribute('aria-expanded', 'false');
676 sum.tabIndex = -1;
677 det.appendChild(sum);
678 det.addEventListener('toggle', async () => {
679 sum.setAttribute('aria-expanded', det.open ? 'true' : 'false');
680 if (det.open) openDirs.add(p); else openDirs.delete(p);
681 if (det.open && det.children.length === 1) {
682 det.appendChild(await renderDir(e, p));
683 markActive();
684 }
685 });
686 // Estaba abierta antes del repintado: se reabre ya con su contenido.
687 if (openDirs.has(p)) {
688 det.appendChild(await renderDir(e, p));
689 det.open = true;
690 sum.setAttribute('aria-expanded', 'true');
691 }
692 li.appendChild(det);
693 } else {
694 const a = document.createElement('span');
695 a.className = 'file';
696 a.innerHTML = fileIcon(e.name);
697 a.appendChild(document.createTextNode(e.name));
698 a.dataset.path = p; a.dataset.kind = 'file';
699 a.setAttribute('role', 'treeitem');
700 a.tabIndex = -1;
701 a.onclick = () => openFile(p);
702 li.appendChild(a);
703 }
704 ul.appendChild(li);
705 }
706 // Una carpeta con más de 200 entradas se cortaba sin decirlo.
707 if (entries.length > TREE_MAX_ENTRIES) {
708 const li = document.createElement('li');
709 li.className = 'tree-more';
710 li.setAttribute('role', 'none');
711 li.textContent = t('treeMore', { n: entries.length - TREE_MAX_ENTRIES });
712 ul.appendChild(li);
713 }
714 return ul;
715}