Elffuss BraidHub

utopia-ia/elffuss-code public

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