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