Elffuss BraidHub

utopia-ia/elffuss-code public

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