Elffuss BraidHub

utopia-ia/elffuss-code public

08a4eae756d0 · 34.2 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 el.tabIndex = on ? 0 : -1;
365 const ico = document.createElement('span');
366 ico.className = 'tab-ico';
367 ico.innerHTML = fileIcon(tb.path.split('/').pop());
368 const name = document.createElement('span');
369 name.className = 'tab-name';
370 name.textContent = tb.path.split('/').pop();
371 name.title = tb.deleted ? tb.path + ' · ' + t('fileDeletedDirty') : tb.path;
372 if (tb.deleted) name.classList.add('deleted');
373 // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón.
374 // Un <button> con nombre accesible (antes un <b> que no recibía el foco).
375 const x = document.createElement('button');
376 x.type = 'button';
377 x.className = 'tab-x' + (tb.dirty ? ' dirty' : '');
378 x.textContent = tb.dirty ? '●' : '×';
379 x.tabIndex = -1;
380 x.setAttribute('aria-label', t(tb.dirty ? 'closeFileDirty' : 'closeFile', { name: baseOf(tb.path) }));
381 x.title = x.getAttribute('aria-label');
382 x.onclick = e => { e.stopPropagation(); closeTabYEnfoca(tb.path); };
383 el.append(ico, name, x);
384 el.onclick = () => openFile(tb.path);
385 el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, tb.path); };
386 el.onkeydown = e => {
387 const i = tabs.indexOf(tb);
388 if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
389 e.preventDefault();
390 const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
391 if (next) openFile(next.path).then(() => bar.querySelector('.tab.active')?.focus());
392 } else if (e.key === 'Delete' || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'w')) {
393 e.preventDefault(); closeTabYEnfoca(tb.path);
394 } else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
395 e.preventDefault(); const r = el.getBoundingClientRect(); openTabMenu(r.left, r.bottom, tb.path);
396 }
397 };
398 bar.appendChild(el);
399 }
400 markActive();
401}
402
403// ---------- menús contextuales (pestañas y árbol): teclado y Escape ----------
404// Escape los cierra y el foco vuelve a donde estaba; ↑/↓ recorren las opciones.
405function wireMenu(menu, returnFocus) {
406 menu.setAttribute('role', 'menu');
407 const items = () => [...menu.querySelectorAll('[role="menuitem"]')];
408 const close = () => { menu.remove(); document.removeEventListener('mousedown', outside); returnFocus?.focus?.(); };
409 const outside = ev => { if (!menu.contains(ev.target)) close(); };
410 menu.addEventListener('keydown', e => {
411 const list = items(), i = list.indexOf(document.activeElement);
412 if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
413 else if (e.key === 'ArrowDown') { e.preventDefault(); list[(i + 1) % list.length]?.focus(); }
414 else if (e.key === 'ArrowUp') { e.preventDefault(); list[(i - 1 + list.length) % list.length]?.focus(); }
415 });
416 setTimeout(() => document.addEventListener('mousedown', outside), 0);
417 // dentro de la ventana aunque se abra pegado al borde
418 const r = menu.getBoundingClientRect();
419 if (r.right > innerWidth) menu.style.left = Math.max(4, innerWidth - r.width - 4) + 'px';
420 if (r.bottom > innerHeight) menu.style.top = Math.max(4, innerHeight - r.height - 4) + 'px';
421 items()[0]?.focus();
422 return close;
423}
424function menuButton(label, fn, cls) {
425 const b = document.createElement('button');
426 b.type = 'button';
427 b.className = 'tm-item' + (cls ? ' ' + cls : '');
428 b.setAttribute('role', 'menuitem');
429 b.textContent = label;
430 b.dataset.run = '1';
431 b._run = fn;
432 return b;
433}
434
435// ---------- menú contextual de las pestañas (botón derecho, estilo VS Code) ----------
436function openTabMenu(x, y, path) {
437 document.getElementById('tab-menu')?.remove();
438 const volver = document.activeElement;
439 const menu = document.createElement('div');
440 menu.id = 'tab-menu';
441 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
442 const i = tabs.findIndex(tb => tb.path === path);
443 const tab = tabs[i];
444 const items = [];
445 items.push([t('tmClose'), () => closeTab(path)]);
446 items.push([t('tmCloseOthers'), () => closeTabs(tabs.filter(tb => tb.path !== path).map(tb => tb.path))]);
447 const toTheRight = tabs.slice(i + 1).map(tb => tb.path);
448 if (toTheRight.length) items.push([t('tmCloseRight'), () => closeTabs(toTheRight)]);
449 items.push([t('tmCloseAll'), () => closeTabs(tabs.map(tb => tb.path))]);
450 items.push(['sep']);
451 items.push([t('tmCopyPath'), () => copyPath(path)]);
452 if (PREVIEWABLE.has(langOf(path))) {
453 items.push([tab?.preview ? t('tmViewSource') : t('tmPreview'), () => togglePreview(path)]);
454 }
455 let close = () => menu.remove();
456 for (const item of items) {
457 if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep', role: 'separator' })); continue; }
458 const [label, fn] = item;
459 const b = menuButton(label, fn);
460 b.onclick = () => { close(); fn(); };
461 menu.appendChild(b);
462 }
463 document.body.appendChild(menu);
464 close = wireMenu(menu, volver);
465}
466
467// Copiar ruta: antes copiaba sin decir nada.
468function copyPath(path) {
469 const done = () => alertBar(t('pathCopied', { path }));
470 if (navigator.clipboard?.writeText) navigator.clipboard.writeText(path).then(done, () => alertBar(t('pathCopyFailed')));
471 else alertBar(t('pathCopyFailed'));
472}
473
474let alertTimer;
475function alertBar(msg) {
476 const el = $('statusbar');
477 el.textContent = msg;
478 clearTimeout(alertTimer);
479 alertTimer = setTimeout(() => { el.textContent = ''; }, 4000);
480}
481
482// ---------- árbol lateral ----------
483const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
484
485// Carpetas abiertas, por ruta. refreshTree() reconstruye el árbol entero (cada
486// escritura del agente, cada orden del terminal que toca ficheros, crear,
487// renombrar o borrar) y antes lo dejaba TODO plegado: perdías el sitio tras
488// cada edición. Ahora se vuelven a abrir las que lo estaban.
489const openDirs = new Set();
490
491export async function refreshTree(handle = null) {
492 const rootHandle = handle || window.__elffussProject;
493 if (!rootHandle) return;
494 if (handle) openDirs.clear(); // otro proyecto: empieza plegado
495 window.__elffussProject = rootHandle;
496 const cont = $('tree');
497 const scroll = cont.scrollTop;
498 const conFoco = cont.contains(document.activeElement) ? document.activeElement.dataset?.path : null;
499 const ul = await renderDir(rootHandle, '');
500 ul.setAttribute('role', 'tree');
501 ul.setAttribute('aria-label', t('explorer'));
502 cont.replaceChildren(ul);
503 cont.scrollTop = scroll;
504 markActive();
505 if (conFoco != null) {
506 const f = cont.querySelector(`[data-path="${CSS.escape(conFoco)}"]`);
507 if (f) { setRoving(f); f.focus(); }
508 }
509 setupTreeMenu();
510}
511
512// El fichero abierto se marca en el árbol (antes no había forma de saber cuál
513// era), y es la fila por la que entra el foco con Tab.
514function markActive() {
515 const cont = $('tree');
516 if (!cont) return;
517 let fila = null;
518 for (const f of cont.querySelectorAll('.file')) {
519 const on = f.dataset.path === active;
520 f.classList.toggle('active', on);
521 f.setAttribute('aria-selected', on ? 'true' : 'false');
522 if (on) fila = f;
523 }
524 if (!cont.querySelector('[tabindex="0"]') || fila) setRoving(fila || cont.querySelector('summary, .file'));
525}
526function setRoving(row) {
527 if (!row) return;
528 for (const r of $('tree').querySelectorAll('[tabindex="0"]')) if (r !== row) r.tabIndex = -1;
529 row.tabIndex = 0;
530}
531const visibleRows = () => [...$('tree').querySelectorAll('summary, .file')].filter(r => r.offsetParent !== null);
532
533// ---------- menú contextual del árbol (botón derecho, estilo VS Code) ----------
534let treeMenuWired = false;
535function setupTreeMenu() {
536 if (treeMenuWired) return;
537 treeMenuWired = true;
538 const tree = $('tree');
539 tree.addEventListener('contextmenu', e => {
540 e.preventDefault();
541 const node = e.target.closest('[data-path]');
542 const path = node ? node.dataset.path : '';
543 const kind = node ? node.dataset.kind : 'directory'; // vacío = raíz
544 openTreeMenu(e.clientX, e.clientY, path, kind);
545 });
546 // Teclado, como un árbol de verdad: ↑/↓ entre filas visibles, → abre una
547 // carpeta, ← la cierra (o sube a la carpeta madre), Enter abre el fichero,
548 // Shift+F10 o la tecla de menú abren el menú contextual. Antes las filas de
549 // fichero eran <span> sin foco y el árbol solo se usaba con el ratón.
550 tree.addEventListener('keydown', e => {
551 const row = e.target.closest?.('summary, .file');
552 if (!row) return;
553 const rows = visibleRows(), i = rows.indexOf(row);
554 const go = r => { if (r) { e.preventDefault(); setRoving(r); r.focus(); } };
555 const det = row.tagName === 'SUMMARY' ? row.parentElement : null;
556 if (e.key === 'ArrowDown') go(rows[i + 1]);
557 else if (e.key === 'ArrowUp') go(rows[i - 1]);
558 else if (e.key === 'Home') go(rows[0]);
559 else if (e.key === 'End') go(rows[rows.length - 1]);
560 else if (e.key === 'ArrowRight' && det) { e.preventDefault(); if (!det.open) det.open = true; else go(rows[i + 1]); }
561 else if (e.key === 'ArrowLeft') {
562 if (det && det.open) { e.preventDefault(); det.open = false; }
563 else go(row.closest('li')?.parentElement?.closest('details')?.querySelector(':scope > summary'));
564 }
565 else if (e.key === 'Enter' && !det) { e.preventDefault(); openFile(row.dataset.path); }
566 else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
567 e.preventDefault();
568 const r = row.getBoundingClientRect();
569 openTreeMenu(r.left + 12, r.bottom, row.dataset.path, row.dataset.kind);
570 }
571 });
572 tree.addEventListener('focusin', e => { const row = e.target.closest?.('summary, .file'); if (row) setRoving(row); });
573}
574
575// resuelve el handle de un directorio por su ruta (segmentos desde la raíz)
576async function dirByPath(path) {
577 let dir = code.handle();
578 for (const s of (path || '').split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(s);
579 return dir;
580}
581const parentOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
582const baseOf = p => p.split('/').pop();
583
584async function fsCreate(parentPath, name, isDir) {
585 const dir = await dirByPath(parentPath);
586 if (isDir) await dir.getDirectoryHandle(name, { create: true });
587 else { const fh = await dir.getFileHandle(name, { create: true }); const w = await fh.createWritable(); await w.close(); }
588}
589async function fsDelete(path, kind) {
590 const dir = await dirByPath(parentOf(path));
591 await dir.removeEntry(baseOf(path), { recursive: kind === 'directory' });
592}
593// copia recursiva (la File System API no tiene rename nativo). El fichero se
594// copia como Blob, no como texto: pasarlo por .text() estropeaba cualquier
595// binario (una imagen, un .zip) al renombrarlo.
596async function fsCopy(srcDir, name, dstDir, newName) {
597 const src = await (srcDir.getDirectoryHandle(name).catch(() => null));
598 if (src) { // directorio
599 const nd = await dstDir.getDirectoryHandle(newName, { create: true });
600 for await (const e of src.values()) await fsCopy(src, e.name, nd, e.name);
601 } else { // fichero
602 const file = await (await srcDir.getFileHandle(name)).getFile();
603 const fh = await dstDir.getFileHandle(newName, { create: true });
604 const w = await fh.createWritable(); await w.write(file); await w.close();
605 }
606}
607async function fsRename(path, kind, newName) {
608 const parent = await dirByPath(parentOf(path));
609 await fsCopy(parent, baseOf(path), parent, newName);
610 await parent.removeEntry(baseOf(path), { recursive: kind === 'directory' });
611}
612
613// Lo que cuelga de `path` (el fichero o todo lo que hay dentro de la carpeta).
614const under = (p, path, kind) => kind === 'directory' ? p.startsWith(path + '/') : p === path;
615
616// Renombrar mueve también las pestañas abiertas: antes seguían apuntando a la
617// ruta vieja, y guardar recreaba el fichero con el nombre antiguo.
618function renameTabs(path, nuevo, kind) {
619 for (const tb of tabs) if (under(tb.path, path, kind)) {
620 const np = kind === 'directory' ? nuevo + tb.path.slice(path.length) : nuevo;
621 if (active === tb.path) { active = np; code.setCurrentFile(np); }
622 tb.path = np;
623 }
624 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) { openDirs.delete(d); openDirs.add(nuevo + d.slice(path.length)); }
625 renderTabs();
626}
627// Borrar cierra sus pestañas. Si una tenía cambios sin guardar no se tira: se
628// queda abierta y marcada (guardarla vuelve a crear el fichero).
629function dropTabs(path, kind) {
630 for (let i = tabs.length - 1; i >= 0; i--) {
631 if (!under(tabs[i].path, path, kind)) continue;
632 if (tabs[i].dirty) tabs[i].deleted = true;
633 else closeTabNow(i);
634 }
635 for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) openDirs.delete(d);
636 renderTabs();
637 applyView();
638}
639
640function openTreeMenu(x, y, path, kind) {
641 document.getElementById('tree-menu')?.remove();
642 const volver = document.activeElement;
643 const menu = document.createElement('div');
644 menu.id = 'tree-menu';
645 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
646 // en un fichero, el "aquí dentro" es su carpeta; en carpeta/raíz, ella misma
647 const container = kind === 'file' ? parentOf(path) : path;
648 const items = [];
649 items.push([t('tmNewFile'), async () => {
650 const name = prompt(t('promptNewFile')); if (!name?.trim()) return;
651 if (container) openDirs.add(container);
652 await fsCreate(container, name.trim(), false); code.invalidateFileList?.();
653 await refreshTree(); openFile(container ? container + '/' + name.trim() : name.trim());
654 }]);
655 items.push([t('tmNewFolder'), async () => {
656 const name = prompt(t('promptNewFolder')); if (!name?.trim()) return;
657 if (container) openDirs.add(container);
658 await fsCreate(container, name.trim(), true); code.invalidateFileList?.(); await refreshTree();
659 alertBar(t('created', { name: name.trim() }));
660 }]);
661 if (path) {
662 if (kind === 'file') items.push([t('tmOpen'), () => openFile(path)]);
663 if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push([t('tmPreview'), () => togglePreview(path)]);
664 items.push([t('tmRename'), async () => {
665 const name = prompt(t('promptRename'), baseOf(path))?.trim(); if (!name || name === baseOf(path)) return;
666 const nuevo = (parentOf(path) ? parentOf(path) + '/' : '') + name;
667 await fsRename(path, kind, name); code.invalidateFileList?.();
668 renameTabs(path, nuevo, kind);
669 await refreshTree();
670 alertBar(t('renamed', { from: baseOf(path), to: name }));
671 }]);
672 items.push([t('tmDelete'), async () => {
673 if (!confirm(t('confirmDelete', { name: baseOf(path) }))) return;
674 await fsDelete(path, kind); code.invalidateFileList?.();
675 dropTabs(path, kind);
676 await refreshTree();
677 alertBar(t('deleted', { name: baseOf(path) }));
678 }, 'danger']);
679 }
680 let close = () => menu.remove();
681 for (const [label, fn, cls] of items) {
682 const b = menuButton(label, fn, cls);
683 b.onclick = async () => { close(); try { await fn(); } catch (err) { alert(t('opFailed', { e: err.message })); } };
684 menu.appendChild(b);
685 }
686 document.body.appendChild(menu);
687 close = wireMenu(menu, volver);
688}
689
690const TREE_MAX_ENTRIES = 200;
691async function renderDir(dir, prefix) {
692 const ul = document.createElement('ul');
693 if (prefix) ul.setAttribute('role', 'group');
694 const entries = [];
695 for await (const e of dir.values()) if (!IGNORE.has(e.name)) entries.push(e);
696 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
697 for (const e of entries.slice(0, TREE_MAX_ENTRIES)) {
698 const li = document.createElement('li');
699 li.setAttribute('role', 'none');
700 const p = prefix ? prefix + '/' + e.name : e.name;
701 if (e.kind === 'directory') {
702 const det = document.createElement('details');
703 const sum = document.createElement('summary');
704 sum.innerHTML = folderIcon();
705 sum.appendChild(document.createTextNode(e.name));
706 sum.dataset.path = p; sum.dataset.kind = 'directory';
707 sum.setAttribute('role', 'treeitem');
708 sum.setAttribute('aria-expanded', 'false');
709 sum.tabIndex = -1;
710 det.appendChild(sum);
711 det.addEventListener('toggle', async () => {
712 sum.setAttribute('aria-expanded', det.open ? 'true' : 'false');
713 if (det.open) openDirs.add(p); else openDirs.delete(p);
714 if (det.open && det.children.length === 1) {
715 det.appendChild(await renderDir(e, p));
716 markActive();
717 }
718 });
719 // Estaba abierta antes del repintado: se reabre ya con su contenido.
720 if (openDirs.has(p)) {
721 det.appendChild(await renderDir(e, p));
722 det.open = true;
723 sum.setAttribute('aria-expanded', 'true');
724 }
725 li.appendChild(det);
726 } else {
727 const a = document.createElement('span');
728 a.className = 'file';
729 a.innerHTML = fileIcon(e.name);
730 a.appendChild(document.createTextNode(e.name));
731 a.dataset.path = p; a.dataset.kind = 'file';
732 a.setAttribute('role', 'treeitem');
733 a.tabIndex = -1;
734 a.onclick = () => openFile(p);
735 li.appendChild(a);
736 }
737 ul.appendChild(li);
738 }
739 // Una carpeta con más de 200 entradas se cortaba sin decirlo.
740 if (entries.length > TREE_MAX_ENTRIES) {
741 const li = document.createElement('li');
742 li.className = 'tree-more';
743 li.setAttribute('role', 'none');
744 li.textContent = t('treeMore', { n: entries.length - TREE_MAX_ENTRIES });
745 ul.appendChild(li);
746 }
747 return ul;
748}
749
750// ---------- extensiones de VS Code (js/ext/) ----------
751// Temas de color, gramáticas TextMate, snippets y lenguajes. El host solo se
752// carga si hay alguna extensión activa o un tema elegido, o al abrir el panel
753// de extensiones: sin ellas, Code arranca exactamente igual que siempre.
754let extCarga = null;
755async function hayExtensiones() {
756 try { const p = localStorage.getItem('elffusscode.theme'); if (p && p !== 'vs-dark') return true; } catch { /* sin almacenamiento */ }
757 const lista = await db.get('kv', 'extensions').catch(() => null);
758 return Array.isArray(lista) && lista.some(e => e && e.enabled);
759}
760export async function loadExt(force = true) {
761 if (ext) return ext;
762 if (!monacoRef || (!force && !(await hayExtensiones()))) return null;
763 extCarga ??= import('./ext/host.js').then(m => m.init(monacoRef, { onLanguagesChanged: refreshLanguages }));
764 try { ext = await extCarga; }
765 catch (e) { extCarga = null; console.warn('[elffuss] extensiones no disponibles:', e?.message || e); }
766 return ext;
767}
768// Tras instalar, activar o desactivar: cada pestaña abierta, con su lenguaje y
769// su gramática al día (o de vuelta a lo de serie).
770async function refreshLanguages() {
771 for (const tab of [...tabs]) {
772 if (tab.model.isDisposed()) continue;
773 const lang = await langDe(tab.path, tab.model.getLineContent(1));
774 await ext?.prepareLanguage(lang);
775 if (!tab.model.isDisposed() && tab.model.getLanguageId() !== lang) monacoRef.editor.setModelLanguage(tab.model, lang);
776 }
777}