| 1 | // Panel de extensiones: buscar en Open VSX, ver qué aplicaría cada una, |
| 2 | // instalar (o un .vsix suelto), activar/desactivar, desinstalar, licencia, y |
| 3 | // el selector de tema de color. Mismo patrón que el panel de Skills: se pinta |
| 4 | // dentro de #settings-panel. Todo texto que viene de una extensión entra con |
| 5 | // textContent, nunca como HTML. |
| 6 | // |
| 7 | // Teclado y lector de pantalla: todo lo que se pulsa es un botón (o un |
| 8 | // <summary>), los resultados y avisos se anuncian (role=status/alert), el |
| 9 | // foco no se pierde al repintar ni al cerrar, y Escape cierra el panel. |
| 10 | import { tx } from './i18n.js'; |
| 11 | import { uiLang } from '../i18n.js'; |
| 12 | import { describe, lista, listaO, works, languageName, languageExts, factsFromManifest, factsFromRecord } from './verdict.js'; |
| 13 | |
| 14 | const $ = id => document.getElementById(id); |
| 15 | const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; }; |
| 16 | const CATS = [['', 'catAll'], ['Themes', 'catThemes'], ['Snippets', 'catSnippets'], ['Programming Languages', 'catLangs']]; |
| 17 | |
| 18 | let host = null; |
| 19 | let cssPuesto = false; |
| 20 | const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null, solo: leeSolo(), objetivo: 0, auto: 0 }; |
| 21 | // «Solo las que funcionan en Code»: encendido salvo que quien usa el panel lo |
| 22 | // apagara (se recuerda en este navegador, si se puede) |
| 23 | const CLAVE_SOLO = 'elffusscode.ext.onlyWorks'; |
| 24 | function leeSolo() { try { return localStorage.getItem(CLAVE_SOLO) !== '0'; } catch { return true; } } |
| 25 | function guardaSolo(v) { try { localStorage.setItem(CLAVE_SOLO, v ? '1' : '0'); } catch { /* sin almacenamiento: solo esta sesión */ } } |
| 26 | const POR_PAGINA = 20; // filas que se quieren ver por tanda |
| 27 | const MAX_AUTO = 3; // páginas que se piden solas para llenarla |
| 28 | |
| 29 | let temporizador = null; |
| 30 | let desuscribe = null; |
| 31 | let abridor = null; // quién tenía el foco al abrir el panel |
| 32 | let focoPendiente = null; // control a recuperar tras repintar «Instaladas» |
| 33 | let nDetalle = 0; |
| 34 | let ideCargado = null; // ../ide.js, para contar pestañas al pintar «Instaladas» |
| 35 | |
| 36 | function ponCss() { |
| 37 | if (cssPuesto) return; |
| 38 | cssPuesto = true; |
| 39 | const l = document.createElement('link'); |
| 40 | l.rel = 'stylesheet'; |
| 41 | l.href = new URL('../../css/ext.css', import.meta.url).href; |
| 42 | document.head.appendChild(l); |
| 43 | } |
| 44 | |
| 45 | const visible = x => !!x && x.isConnected && x !== document.body && !x.disabled && x.getClientRects().length > 0; |
| 46 | // El foco vuelve a donde estaba; si eso ya no existe o no se ve (un menú que |
| 47 | // se cerró, la paleta), a lo primero que se vea de la lista. |
| 48 | function devuelveFoco(previo, ...alternativas) { |
| 49 | for (const x of [previo, ...alternativas]) { |
| 50 | if (typeof x === 'function') { if (x()) return; continue; } |
| 51 | if (visible(x)) { x.focus(); return; } |
| 52 | } |
| 53 | } |
| 54 | const enfocaEditor = () => { |
| 55 | const ed = window.monaco?.editor?.getEditors?.()[0]; |
| 56 | if (!ed || !visible(ed.getDomNode())) return false; |
| 57 | ed.focus(); |
| 58 | return true; |
| 59 | }; |
| 60 | |
| 61 | export function open(h, { themes = false } = {}) { |
| 62 | host = h; |
| 63 | ponCss(); |
| 64 | desuscribe?.(); |
| 65 | desuscribe = h.onChange(() => { if ($('ext-panel')?.isConnected) pintaInstaladas(); }); |
| 66 | if (themes) return openThemePicker(h); |
| 67 | const box = $('settings-panel'); |
| 68 | if (!$('ext-panel')?.isConnected || box.hidden) abridor = document.activeElement; |
| 69 | estado.msg = null; // un aviso viejo no se repite al volver a abrir |
| 70 | pinta(); |
| 71 | if (!ideCargado) ide().then(m => { ideCargado = m; if ($('ext-panel')?.isConnected) pintaInstaladas(); }); |
| 72 | } |
| 73 | |
| 74 | function cierraPanel() { |
| 75 | $('settings-panel').hidden = true; |
| 76 | devuelveFoco(abridor, $('act-ext'), document.querySelector('#menubar button[data-menu="view"]'), enfocaEditor, $('prompt')); |
| 77 | } |
| 78 | // Para el Escape global de main.js (la capa de más arriba): cerrar el panel de |
| 79 | // extensiones es esto, no cerrar Ajustes, que no sabe quién lo abrió. |
| 80 | export function close() { if ($('ext-panel')?.isConnected && !$('settings-panel').hidden) cierraPanel(); } |
| 81 | |
| 82 | // ── mensajes legibles (exportados para las pruebas en Node) ── |
| 83 | const ERRORES = { |
| 84 | rate: 'errRate', sha: 'errSha', nothing: 'errNothing', notvsix: 'errNotVsix', notfound: 'errNotFound', |
| 85 | big: 'errBig', noname: 'errNoName', blocked: 'errBlocked', codeonly: 'notHere', |
| 86 | }; |
| 87 | export function textoError(e) { |
| 88 | const code = e?.code; |
| 89 | if (code === 'cancel' || e?.name === 'AbortError') return tx('cancelled'); |
| 90 | if (e?.name === 'QuotaExceededError') return tx('errQuota'); |
| 91 | if (typeof code === 'string' && Object.hasOwn(ERRORES, code)) return tx(ERRORES[code]); |
| 92 | switch (code) { |
| 93 | case 'net': return tx('errNet', { e: e.message }); |
| 94 | case 'http': return tx('errHttp', { status: e.status ? ` (${e.status})` : '' }); |
| 95 | case 'mismatch': return tx('errMismatch', { got: e.got, want: e.want }); |
| 96 | case 'corrupt': case 'missing': return tx('errCorrupt', { entry: e.entry ? ` (${e.entry})` : '' }); |
| 97 | case 'badmanifest': return tx('errBadManifest', { e: e.message }); |
| 98 | case 'unreadable': return tx('errUnreadable', { w: e.warning ? textoAviso(e.warning) : '' }).trim(); |
| 99 | } |
| 100 | return tx('err', { e: e?.message || String(e) }); |
| 101 | } |
| 102 | // Una parte del paquete que no se pudo usar (vsix.js: { kind, name, code, detail }). |
| 103 | const MOTIVOS = { |
| 104 | missing: 'whyMissing', corrupt: 'whyCorrupt', big: 'whyBig', json: 'whyJson', plist: 'whyPlist', |
| 105 | notgrammar: 'whyNotGrammar', notheme: 'whyNotTheme', scope: 'whyScope', outside: 'whyOutside', |
| 106 | }; |
| 107 | const TIPOS_AVISO = new Set(['theme', 'grammar', 'snippets', 'config', 'regex']); |
| 108 | export function textoAviso(w) { |
| 109 | if (typeof w === 'string') return w; // instaladas antes de que hubiera códigos |
| 110 | if (!w || typeof w !== 'object') return ''; |
| 111 | const why = w.kind !== 'regex' && typeof w.code === 'string' && Object.hasOwn(MOTIVOS, w.code) ? tx(MOTIVOS[w.code], { e: w.detail }) : w.detail; |
| 112 | return TIPOS_AVISO.has(w.kind) ? tx('warn_' + w.kind, { name: w.name, why }) : `${w.name}: ${why}`; |
| 113 | } |
| 114 | |
| 115 | // Los avisos que importan: la configuración de un lenguaje de serie no se |
| 116 | // aplica, así que sus expresiones descartadas no cuentan (ya lo dice «No aplica»). |
| 117 | const avisosVisibles = ws => (ws || []).filter(w => !(w?.kind === 'regex' && w.where === 'config' && host.builtinLanguage?.(w.name))); |
| 118 | |
| 119 | function aviso(texto, error = false) { |
| 120 | estado.msg = texto ? { texto, error } : null; |
| 121 | const m = $('ext-msg'); |
| 122 | if (!m) return; |
| 123 | // vacío pero presente: una región viva que aparece a la vez que su texto |
| 124 | // no siempre se anuncia |
| 125 | m.setAttribute('role', error ? 'alert' : 'status'); |
| 126 | m.setAttribute('aria-live', error ? 'assertive' : 'polite'); |
| 127 | m.hidden = false; |
| 128 | m.textContent = texto || ''; |
| 129 | m.classList.toggle('err', !!error); |
| 130 | m.classList.remove('ext-msg-sr'); |
| 131 | } |
| 132 | // Estado de la búsqueda para el lector de pantalla (la cabecera visible se |
| 133 | // rehace en cada repintado y no podría anunciarse). |
| 134 | function anunciaBusqueda(texto) { |
| 135 | const s = $('ext-status'); |
| 136 | if (s && s.textContent !== texto) s.textContent = texto; |
| 137 | } |
| 138 | |
| 139 | // «Aplica: 2 temas · No aplica: commands (necesita su código)», con lo que de |
| 140 | // verdad se aplicaría aquí: la gramática de un lenguaje de serie sin Monarch |
| 141 | // (JSON) y la configuración de un lenguaje de serie no se aplican, y no cuentan. |
| 142 | // ── qué hace cada extensión, en llano (verdict.js) ── |
| 143 | const nombreLenguaje = (id, langs = []) => languageName(host, id, langs); |
| 144 | const extsDe = (id, langs = []) => languageExts(host, id, langs); |
| 145 | const hechosDeManifiesto = a => factsFromManifest(host, a); |
| 146 | const hechosDeRegistro = e => factsFromRecord(host, e); |
| 147 | // El bloque del veredicto: primero la frase que decide, luego el detalle. |
| 148 | function bloqueVeredicto(f, v, { principal = true } = {}) { |
| 149 | const box = el('div', 'ext-verdict ext-v-' + v.kind); |
| 150 | box.id = 'ext-v-' + (++nDetalle); |
| 151 | if (principal || v.kind === 'code' || v.kind === 'nothing') box.appendChild(el('div', 'ext-v-main', v.verdict)); |
| 152 | for (const l of v.lines) box.appendChild(el('div', 'ext-v-more', l)); |
| 153 | if (f.keepsBuiltin?.length) box.appendChild(el('div', 'ext-v-more', tx('keepsBuiltin', { list: lista(f.keepsBuiltin) }))); |
| 154 | if (f.pack?.length) box.appendChild(el('div', 'ext-v-more', tx('pack', { n: f.pack.length }))); |
| 155 | return box; |
| 156 | } |
| 157 | // El botón de instalar dice lo que vas a tener; si no se ve nada, no se ofrece. |
| 158 | function botonSegunVeredicto(b, v, nombre) { |
| 159 | const texto = tx(v.button.key); |
| 160 | rotula(b, texto, v.button.key === 'install' ? tx('installNamed', { name: nombre }) : `${texto}: ${nombre}`); |
| 161 | b.className = (v.button.style === 'primary' ? 'primary' : 'ghost') + ' ext-install'; |
| 162 | inerte(b, v.button.disabled); |
| 163 | } |
| 164 | |
| 165 | function rotula(b, texto, accesible = null) { |
| 166 | b.textContent = texto; |
| 167 | if (accesible) b.setAttribute('aria-label', accesible); else b.removeAttribute('aria-label'); |
| 168 | } |
| 169 | // Ocupado o ya hecho, pero SIN disabled: un botón deshabilitado pierde el foco |
| 170 | // y quien va con teclado se quedaría en ninguna parte. |
| 171 | const inerte = (b, si) => { if (si) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); }; |
| 172 | const esInerte = b => b.getAttribute('aria-disabled') === 'true'; |
| 173 | |
| 174 | // ── panel ── |
| 175 | function pinta() { |
| 176 | const box = $('settings-panel'); |
| 177 | box.hidden = false; |
| 178 | box.replaceChildren(); |
| 179 | // Es un diálogo con su propio nombre. La caja la comparten Ajustes y Skills, |
| 180 | // y Ajustes le deja role=dialog con aria-labelledby a su título: abierto |
| 181 | // Ajustes antes, este panel quedaba como un diálogo sin nombre (ese título |
| 182 | // aquí no existe), y si no, sin rol de diálogo. |
| 183 | box.setAttribute('role', 'dialog'); |
| 184 | box.setAttribute('aria-labelledby', 'ext-title'); |
| 185 | box.dataset.kind = 'ext'; |
| 186 | const cerrar = el('button', null, '✕'); |
| 187 | cerrar.id = 'settings-close'; |
| 188 | cerrar.type = 'button'; |
| 189 | cerrar.title = tx('close'); |
| 190 | cerrar.setAttribute('aria-label', tx('close')); |
| 191 | cerrar.onclick = cierraPanel; |
| 192 | const wrap = el('div', 'ext-panel'); |
| 193 | wrap.id = 'ext-panel'; |
| 194 | const conEscape = e => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); cierraPanel(); } }; |
| 195 | wrap.addEventListener('keydown', conEscape); |
| 196 | cerrar.addEventListener('keydown', conEscape); |
| 197 | const h3 = el('h3', null, tx('title') + ' '); |
| 198 | h3.id = 'ext-title'; |
| 199 | h3.appendChild(el('span', 'muted', '· ' + tx('sub'))); |
| 200 | wrap.append(h3, el('p', 'muted ext-intro', tx('intro'))); |
| 201 | if (host.paused) wrap.appendChild(el('p', 'ext-paused', tx('paused'))); |
| 202 | |
| 203 | const barra = el('div', 'ext-toolbar'); |
| 204 | const fichero = el('input'); |
| 205 | fichero.type = 'file'; |
| 206 | fichero.accept = '.vsix,application/zip,application/vsix'; |
| 207 | fichero.hidden = true; |
| 208 | fichero.id = 'ext-file'; |
| 209 | fichero.onchange = async () => { |
| 210 | const f = fichero.files?.[0]; |
| 211 | fichero.value = ''; |
| 212 | if (f) await instala(f, null); |
| 213 | }; |
| 214 | const bVsix = el('button', 'ghost', tx('vsix')); |
| 215 | bVsix.id = 'ext-install-vsix'; |
| 216 | bVsix.onclick = () => fichero.click(); |
| 217 | const bTema = el('button', 'ghost', tx('themeBtn')); |
| 218 | bTema.id = 'ext-theme-btn'; |
| 219 | bTema.onclick = () => openThemePicker(host); |
| 220 | barra.append(bVsix, bTema, fichero); |
| 221 | wrap.appendChild(barra); |
| 222 | |
| 223 | const busca = el('div', 'ext-search'); |
| 224 | const inp = el('input'); |
| 225 | inp.id = 'ext-q'; |
| 226 | inp.type = 'search'; |
| 227 | inp.placeholder = tx('searchPh'); |
| 228 | inp.setAttribute('aria-label', tx('searchPh')); |
| 229 | inp.autocomplete = 'off'; |
| 230 | inp.spellcheck = false; |
| 231 | inp.value = estado.q; |
| 232 | inp.oninput = () => { estado.q = inp.value.trim(); clearTimeout(temporizador); temporizador = setTimeout(() => busca_(), 350); }; |
| 233 | inp.onkeydown = e => { if (e.key === 'Enter') { clearTimeout(temporizador); busca_(); } }; |
| 234 | const chips = el('div', 'ext-chips'); |
| 235 | for (const [cat, key] of CATS) { |
| 236 | const c = el('button', 'ext-chip' + (estado.cat === cat ? ' on' : ''), tx(key)); |
| 237 | c.dataset.cat = cat; |
| 238 | c.setAttribute('aria-pressed', String(estado.cat === cat)); |
| 239 | c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); }; |
| 240 | chips.appendChild(c); |
| 241 | } |
| 242 | busca.append(inp, chips); |
| 243 | wrap.appendChild(busca); |
| 244 | const filtro = el('label', 'ext-filter'); |
| 245 | const solo = el('input'); |
| 246 | solo.type = 'checkbox'; |
| 247 | solo.id = 'ext-only-works'; |
| 248 | solo.checked = estado.solo; |
| 249 | solo.onchange = () => ponSolo(solo.checked); |
| 250 | filtro.append(solo, el('span', null, tx('onlyWorks'))); |
| 251 | wrap.appendChild(filtro); |
| 252 | |
| 253 | const msg = el('div', 'ext-msg'); |
| 254 | msg.id = 'ext-msg'; |
| 255 | msg.setAttribute('role', 'status'); |
| 256 | msg.setAttribute('aria-live', 'polite'); |
| 257 | wrap.appendChild(msg); |
| 258 | const estadoBusqueda = el('div', 'ext-sr'); |
| 259 | estadoBusqueda.id = 'ext-status'; |
| 260 | estadoBusqueda.setAttribute('role', 'status'); |
| 261 | estadoBusqueda.setAttribute('aria-live', 'polite'); |
| 262 | wrap.appendChild(estadoBusqueda); |
| 263 | const res = el('div', 'ext-results'); |
| 264 | res.id = 'ext-results'; |
| 265 | wrap.appendChild(res); |
| 266 | const inst = el('div', 'ext-installed'); |
| 267 | inst.id = 'ext-installed'; |
| 268 | wrap.appendChild(inst); |
| 269 | box.append(cerrar, wrap); |
| 270 | |
| 271 | if (estado.msg) aviso(estado.msg.texto, estado.msg.error); |
| 272 | pintaResultados(); |
| 273 | pintaInstaladas(); |
| 274 | inp.focus(); |
| 275 | } |
| 276 | |
| 277 | async function busca_({ mas = false } = {}) { |
| 278 | estado.ctl?.abort(); |
| 279 | const ctl = new AbortController(); |
| 280 | estado.ctl = ctl; |
| 281 | // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip |
| 282 | for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip')) { |
| 283 | const on = c.dataset.cat === (estado.cat || '') && estado.cat != null; |
| 284 | c.classList.toggle('on', on); |
| 285 | c.setAttribute('aria-pressed', String(on)); |
| 286 | } |
| 287 | if (!mas) { estado.objetivo = POR_PAGINA; estado.auto = 0; } |
| 288 | // sin buscar nada: la lista de populares que funcionan, ya calculada |
| 289 | if (mostrandoPopulares()) { estado.items = []; estado.total = 0; estado.cargando = false; pintaResultados(); return; } |
| 290 | const ovsx = await import('./openvsx.js'); |
| 291 | if (estado.ctl !== ctl) return; |
| 292 | estado.cargando = true; |
| 293 | if (!mas) { estado.items = []; estado.total = 0; } |
| 294 | aviso(null); |
| 295 | if (mas) pintaPie(); else pintaResultados(); |
| 296 | let nuevos = null; |
| 297 | try { |
| 298 | const r = await ovsx.search(estado.q, { category: estado.cat || '', offset: mas ? estado.items.length : 0, size: POR_PAGINA, signal: ctl.signal }); |
| 299 | if (estado.ctl !== ctl) return; |
| 300 | // (una extensión puede repetirse entre páginas si cambia el orden) |
| 301 | const ya = new Set(estado.items.map(claveDe)); |
| 302 | nuevos = mas ? r.items.filter(it => !ya.has(claveDe(it))) : r.items; |
| 303 | estado.items = mas ? estado.items.concat(nuevos) : r.items; |
| 304 | estado.total = mas && !r.items.length ? estado.items.length : r.total; |
| 305 | } catch (e) { |
| 306 | if (e.name === 'AbortError') return; |
| 307 | aviso(textoError(e), true); |
| 308 | } finally { |
| 309 | if (estado.ctl === ctl) { |
| 310 | estado.cargando = false; |
| 311 | if (mas && $('ext-list')) { if (nuevos) añadeFilas(nuevos); pintaPie(); } else pintaResultados(); |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | const mostrandoPopulares = () => !estado.q && !estado.cat; |
| 316 | |
| 317 | // ── «Solo las que funcionan en Code» ── |
| 318 | // Lo que se sabe de cada resultado: true (funciona), false (no hace nada aquí), |
| 319 | // null (no se pudo leer su package.json: se enseña, sin veredicto). Sin |
| 320 | // entrada: todavía se está mirando. |
| 321 | const veredictos = new Map(); |
| 322 | function ponSolo(v) { |
| 323 | estado.solo = v; |
| 324 | guardaSolo(v); |
| 325 | const cb = $('ext-only-works'); |
| 326 | if (cb) cb.checked = v; |
| 327 | for (const row of document.querySelectorAll('#ext-list .ext-row')) filtraFila(row); |
| 328 | pintaPie(); |
| 329 | } |
| 330 | function filtraFila(row) { |
| 331 | const w = veredictos.get(row.dataset.key); |
| 332 | row.hidden = estado.solo && !row.dataset.popular && (w === undefined || w === false); |
| 333 | } |
| 334 | function cuentas() { |
| 335 | let pendientes = 0, ocultas = 0, visibles = 0; |
| 336 | for (const it of estado.items) { |
| 337 | const w = veredictos.get(claveDe(it)); |
| 338 | if (w === undefined) pendientes++; |
| 339 | else if (w === false) ocultas++; |
| 340 | else visibles++; |
| 341 | } |
| 342 | return { pendientes, ocultas, visibles: estado.solo ? visibles : estado.items.length }; |
| 343 | } |
| 344 | let piePendiente = false; |
| 345 | function programaPie() { |
| 346 | if (piePendiente) return; |
| 347 | piePendiente = true; |
| 348 | queueMicrotask(() => { piePendiente = false; pintaPie(); }); |
| 349 | } |
| 350 | // Debajo de la lista: cuántas se ocultaron (con «mostrar»), «comprobando…», |
| 351 | // «más resultados»; y si faltan filas para llenar la tanda, pide otra página. |
| 352 | function pintaPie() { |
| 353 | const pie = $('ext-foot'), ocultasBox = $('ext-hidden'); |
| 354 | if (!pie || !ocultasBox || mostrandoPopulares()) return; |
| 355 | const teniaFoco = pie.contains(document.activeElement) || ocultasBox.contains(document.activeElement); |
| 356 | const { pendientes, ocultas, visibles } = cuentas(); |
| 357 | const quedan = estado.items.length < estado.total; |
| 358 | ocultasBox.replaceChildren(); |
| 359 | ocultasBox.hidden = !(estado.solo && ocultas); |
| 360 | if (estado.solo && ocultas) { |
| 361 | ocultasBox.append(tx('hiddenN', { n: ocultas }) + ' · '); |
| 362 | const b = el('button', 'ext-link', tx('showHidden')); |
| 363 | b.type = 'button'; |
| 364 | b.id = 'ext-show-hidden'; |
| 365 | b.setAttribute('aria-label', tx('showHiddenNamed', { n: ocultas })); |
| 366 | b.onclick = () => { ponSolo(false); $('ext-only-works')?.focus(); }; |
| 367 | ocultasBox.appendChild(b); |
| 368 | } |
| 369 | // ¿llenar la tanda? solo con el filtro, cuando ya se sabe todo lo pedido |
| 370 | const llenando = estado.solo && !pendientes && visibles < estado.objetivo && quedan && !estado.cargando && estado.auto < MAX_AUTO; |
| 371 | pie.replaceChildren(); |
| 372 | if (estado.cargando || (estado.solo && pendientes) || llenando) pie.appendChild(el('div', 'muted ext-hint', tx(estado.solo ? 'checking' : 'searching'))); |
| 373 | else if (estado.solo && !visibles && estado.items.length) pie.appendChild(el('div', 'muted ext-hint', tx(quedan ? 'noneWorkYet' : 'noneWork', { n: estado.items.length }))); |
| 374 | if (!estado.cargando && !llenando && quedan) { |
| 375 | const mas = el('button', 'ghost ext-more', tx('more')); |
| 376 | mas.type = 'button'; |
| 377 | mas.id = 'ext-more'; |
| 378 | mas.onclick = () => { estado.objetivo = cuentas().visibles + POR_PAGINA; estado.auto = 0; busca_({ mas: true }); }; |
| 379 | pie.appendChild(mas); |
| 380 | if (teniaFoco) mas.focus(); |
| 381 | } else if (teniaFoco && !ocultasBox.contains(document.activeElement)) { |
| 382 | // el botón que tenía el foco ya no está: a la primera fila que se ve |
| 383 | ([...document.querySelectorAll('#ext-list .ext-row:not([hidden]) .ext-name')].pop() || $('ext-only-works'))?.focus(); |
| 384 | } |
| 385 | if (!pendientes && !estado.cargando) { |
| 386 | anunciaBusqueda(tx('results', { n: estado.total }) + (estado.solo && ocultas ? ' · ' + tx('hiddenN', { n: ocultas }) : '')); |
| 387 | } |
| 388 | if (llenando) { estado.auto++; busca_({ mas: true }); } |
| 389 | } |
| 390 | |
| 391 | // ── populares: una lista corta, ya comprobada (popular.json, generada por |
| 392 | // tests/ext_popular_build.mjs), que se pinta al instante y sin pedir nada a |
| 393 | // Open VSX: el veredicto de cada una va dentro ── |
| 394 | let populares = null, cargaPop = null; |
| 395 | function cargaPopulares() { |
| 396 | cargaPop ||= fetch(new URL('./popular.json', import.meta.url)).then(r => { if (!r.ok) throw new Error(String(r.status)); return r.json(); }) |
| 397 | .then(j => { populares = (j.items || []).map(p => ({ ...p, it: itemPopular(p) })); for (const p of populares) analisis.set(claveDe(p.it), Promise.resolve(p.analysis)); }) |
| 398 | .catch(e => { cargaPop = null; throw e; }); |
| 399 | return cargaPop; |
| 400 | } |
| 401 | function itemPopular(p) { |
| 402 | return { |
| 403 | namespace: p.namespace, name: p.name, version: p.version, displayName: p.displayName, |
| 404 | description: p.description?.[uiLang()] || p.description?.en || '', downloadCount: p.downloads || 0, verified: !!p.verified, icon: null, |
| 405 | }; |
| 406 | } |
| 407 | function pintaPopulares(res) { |
| 408 | if (!populares) { |
| 409 | res.appendChild(el('div', 'muted ext-hint', tx('searching'))); |
| 410 | cargaPopulares().then(() => { if (mostrandoPopulares()) pintaResultados(); }) |
| 411 | .catch(() => { if (mostrandoPopulares()) { res.replaceChildren(el('div', 'muted ext-hint', tx('popularFailed'))); } }); |
| 412 | return; |
| 413 | } |
| 414 | const h = el('div', 'sk-h', tx('popularH')); |
| 415 | h.id = 'ext-popular-h'; |
| 416 | res.append(h, el('p', 'muted ext-pop-note', tx('popularNote'))); |
| 417 | const lista = el('div', 'ext-list ext-popular'); |
| 418 | lista.id = 'ext-list'; |
| 419 | lista.setAttribute('aria-labelledby', 'ext-popular-h'); |
| 420 | const instaladas = new Map(host.list().map(e => [e.id, e])); |
| 421 | for (const p of populares) { |
| 422 | const row = filaResultado(p.it, instaladas.get(p.id.toLowerCase()), { kind: p.kind }); |
| 423 | row.dataset.popular = '1'; |
| 424 | lista.appendChild(row); |
| 425 | } |
| 426 | res.appendChild(lista); |
| 427 | anunciaBusqueda(tx('popularCount', { n: populares.length })); |
| 428 | } |
| 429 | |
| 430 | function pintaResultados() { |
| 431 | const res = $('ext-results'); |
| 432 | if (!res) return; |
| 433 | res.replaceChildren(); |
| 434 | if (mostrandoPopulares()) { pintaPopulares(res); return; } |
| 435 | if (estado.cargando && !estado.items.length) { |
| 436 | res.appendChild(el('div', 'muted ext-hint', tx('searching'))); |
| 437 | anunciaBusqueda(tx('searching')); |
| 438 | return; |
| 439 | } |
| 440 | if (!estado.items.length) { |
| 441 | if (estado.q || estado.cat != null) { |
| 442 | const t = estado.cargando ? tx('searching') : tx('noResults'); |
| 443 | res.appendChild(el('div', 'muted ext-hint', t)); |
| 444 | anunciaBusqueda(t); |
| 445 | } else anunciaBusqueda(''); |
| 446 | return; |
| 447 | } |
| 448 | res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular'))); |
| 449 | const lista = el('div', 'ext-list'); |
| 450 | lista.id = 'ext-list'; |
| 451 | const ocultas = el('div', 'muted ext-hidden'); |
| 452 | ocultas.id = 'ext-hidden'; |
| 453 | ocultas.hidden = true; |
| 454 | const pie = el('div', 'ext-foot'); |
| 455 | pie.id = 'ext-foot'; |
| 456 | res.append(ocultas, lista, pie); |
| 457 | añadeFilas(estado.items); |
| 458 | pintaPie(); |
| 459 | } |
| 460 | function añadeFilas(items) { |
| 461 | const lista = $('ext-list'); |
| 462 | if (!lista) return; |
| 463 | const instaladas = new Map(host.list().map(e => [e.id, e])); |
| 464 | for (const it of items) { |
| 465 | const row = filaResultado(it, instaladas.get(`${it.namespace}.${it.name}`.toLowerCase())); |
| 466 | filtraFila(row); |
| 467 | lista.appendChild(row); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | function icono(url, nombre) { |
| 472 | if (url) { |
| 473 | const img = el('img', 'ext-ico'); |
| 474 | img.alt = ''; |
| 475 | img.loading = 'lazy'; |
| 476 | img.referrerPolicy = 'no-referrer'; |
| 477 | img.src = url; |
| 478 | img.onerror = () => img.replaceWith(icono(null, nombre)); |
| 479 | return img; |
| 480 | } |
| 481 | const letra = el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase()); |
| 482 | letra.setAttribute('aria-hidden', 'true'); |
| 483 | return letra; |
| 484 | } |
| 485 | |
| 486 | // ── análisis previo de cada resultado: su package.json (una petición por fila, |
| 487 | // cuatro a la vez, en caché) para dar el veredicto ANTES de instalar ── |
| 488 | const analisis = new Map(); |
| 489 | const colaAnalisis = []; |
| 490 | let analizando = 0; |
| 491 | const claveDe = it => `${it.namespace}.${it.name}@${it.version}`; |
| 492 | function bombea() { |
| 493 | while (analizando < 4 && colaAnalisis.length) { |
| 494 | const { it, res, rej } = colaAnalisis.shift(); |
| 495 | analizando++; |
| 496 | (async () => { |
| 497 | const ovsx = await import('./openvsx.js'); |
| 498 | const { analyzeManifest } = await import('./vsix.js'); |
| 499 | return analyzeManifest(await ovsx.manifestOf(it)); |
| 500 | })().then(res, rej).finally(() => { analizando--; bombea(); }); |
| 501 | } |
| 502 | } |
| 503 | function analiza(it) { |
| 504 | const k = claveDe(it); |
| 505 | if (!analisis.has(k)) { |
| 506 | const p = new Promise((res, rej) => { colaAnalisis.push({ it, res, rej }); bombea(); }); |
| 507 | analisis.set(k, p); |
| 508 | p.catch(() => analisis.delete(k)); // se reintenta la próxima vez |
| 509 | } |
| 510 | return analisis.get(k); |
| 511 | } |
| 512 | function pintaVeredictoFila(row, it, a, instalada) { |
| 513 | const f = hechosDeManifiesto(a); |
| 514 | const v = describe(f); |
| 515 | const sitio = row.querySelector('.ext-verdict-slot'); |
| 516 | if (!sitio) return v; |
| 517 | const bloque = bloqueVeredicto(f, v); |
| 518 | sitio.replaceChildren(bloque); |
| 519 | const b = row.querySelector('.ext-install'); |
| 520 | if (b && !instalada && !b.dataset.ocupado) { |
| 521 | botonSegunVeredicto(b, v, it.displayName); |
| 522 | if (v.button.disabled) { b.setAttribute('aria-describedby', bloque.id); b.title = v.verdict; } else { b.removeAttribute('aria-describedby'); b.removeAttribute('title'); } |
| 523 | } |
| 524 | return v; |
| 525 | } |
| 526 | |
| 527 | function filaResultado(it, instalada, { kind = null } = {}) { |
| 528 | const row = el('div', 'ext-row'); |
| 529 | row.dataset.id = `${it.namespace}.${it.name}`; |
| 530 | row.dataset.key = claveDe(it); |
| 531 | const main = el('div', 'ext-main'); |
| 532 | const det = el('div', 'ext-detail'); |
| 533 | det.id = 'ext-det-' + (++nDetalle); |
| 534 | det.hidden = true; |
| 535 | const t = el('div', 'ext-title'); |
| 536 | const nombre = el('button', 'ext-name', it.displayName); |
| 537 | nombre.type = 'button'; |
| 538 | nombre.title = tx('details'); |
| 539 | nombre.setAttribute('aria-expanded', 'false'); |
| 540 | nombre.setAttribute('aria-controls', det.id); |
| 541 | nombre.onclick = e => { e.stopPropagation(); detalle(it, det, nombre); }; |
| 542 | t.append(nombre, el('span', 'muted', ` ${it.namespace} · v${it.version}`)); |
| 543 | if (it.verified) t.appendChild(el('span', 'ext-badge', '✓')); |
| 544 | if (kind) { row.dataset.kind = kind; t.appendChild(el('span', 'ext-kind ext-kind-' + kind, tx('kind_' + kind))); } |
| 545 | main.append(t, el('div', 'ext-desc', it.description)); |
| 546 | main.appendChild(el('div', 'ext-verdict-slot')); |
| 547 | main.appendChild(el('div', 'ext-meta muted', tx('downloads', { n: it.downloadCount.toLocaleString() }))); |
| 548 | main.appendChild(det); |
| 549 | main.onclick = e => { if (!e.target.closest('button, a, summary')) detalle(it, det, nombre); }; |
| 550 | |
| 551 | const acc = el('div', 'ext-actions'); |
| 552 | const b = el('button', 'primary ext-install'); |
| 553 | b.type = 'button'; |
| 554 | if (instalada && instalada.version === it.version) { |
| 555 | rotula(b, tx('installedOk'), tx('installedNamed', { name: it.displayName })); |
| 556 | b.className = 'ghost ext-install'; |
| 557 | inerte(b, true); |
| 558 | } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version })); |
| 559 | else rotula(b, tx('install'), tx('installNamed', { name: it.displayName })); |
| 560 | b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b); }; |
| 561 | acc.appendChild(b); |
| 562 | row.append(icono(it.icon, it.displayName), main, acc); |
| 563 | const k = claveDe(it); |
| 564 | analiza(it).then(a => { veredictos.set(k, works(pintaVeredictoFila(row, it, a, instalada))); }) |
| 565 | .catch(() => { if (!veredictos.has(k)) veredictos.set(k, null); }) // sin veredicto: el botón de siempre |
| 566 | .finally(() => { filtraFila(row); programaPie(); }); |
| 567 | return row; |
| 568 | } |
| 569 | |
| 570 | async function detalle(it, det, boton) { |
| 571 | det.hidden = !det.hidden; |
| 572 | boton?.setAttribute('aria-expanded', String(!det.hidden)); |
| 573 | if (det.hidden || det.dataset.listo) return; |
| 574 | det.replaceChildren(el('div', 'muted', tx('loadingDetails'))); |
| 575 | try { |
| 576 | const ovsx = await import('./openvsx.js'); |
| 577 | const meta = await ovsx.metadata(it.namespace, it.name, it.version); |
| 578 | const a = await analiza(it); |
| 579 | const f = hechosDeManifiesto(a); |
| 580 | const v = describe(f); |
| 581 | det.replaceChildren(); |
| 582 | // el veredicto ya va en la fila; aquí, además, todo lo que no funcionaría |
| 583 | if (v.missing.length && v.kind !== 'partial') det.appendChild(el('div', 'ext-v-more', tx(v.future === 'next' ? 'vMissingNext' : 'vMissingNever', { list: lista(v.missing) }))); |
| 584 | const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' '); |
| 585 | if (meta.files.license) { |
| 586 | const a2 = el('a', null, tx('viewLicense')); |
| 587 | a2.href = meta.files.license; |
| 588 | a2.target = '_blank'; |
| 589 | a2.rel = 'noopener noreferrer'; |
| 590 | lic.appendChild(a2); |
| 591 | } |
| 592 | det.appendChild(lic); |
| 593 | det.dataset.listo = '1'; |
| 594 | const fila = det.closest('.ext-row'); |
| 595 | if (fila) pintaVeredictoFila(fila, it, a, host.list().find(e => e.id === `${it.namespace}.${it.name}`.toLowerCase())); |
| 596 | } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); } |
| 597 | } |
| 598 | |
| 599 | // «No se ha instalado», con el porqué en llano. |
| 600 | function textoNoInstalada(nombre, a) { |
| 601 | const v = describe(hechosDeManifiesto(a)); |
| 602 | return [tx('errCodeOnly', { name: nombre }), v.verdict, ...v.lines].join(' '); |
| 603 | } |
| 604 | |
| 605 | async function instala(src, boton) { |
| 606 | const esFichero = src instanceof Blob; |
| 607 | const nombre = esFichero ? src.name : src.displayName; |
| 608 | if (!esFichero) { |
| 609 | // sin veredicto todavía (red lenta): se pide ahora, y si no se vería nada, no se baja |
| 610 | const a = await analiza(src).catch(() => null); |
| 611 | if (a) { |
| 612 | const fila = boton?.closest('.ext-row'); |
| 613 | const v = fila ? pintaVeredictoFila(fila, src, a, null) : describe(hechosDeManifiesto(a)); |
| 614 | if (v.button.disabled) { aviso(textoNoInstalada(nombre, a), true); return; } |
| 615 | } |
| 616 | } |
| 617 | const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null; |
| 618 | if (boton) { inerte(boton, true); boton.dataset.ocupado = '1'; rotula(boton, tx('installing')); } |
| 619 | aviso(null); |
| 620 | $('ext-done')?.remove(); |
| 621 | const temaAntes = host.currentTheme(); |
| 622 | try { |
| 623 | const rec = await host.install(esFichero ? src : { namespace: src.namespace, name: src.name, version: src.version }, { |
| 624 | onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); }, |
| 625 | confirmLarge: async mb => confirm(tx('bigConfirm', { mb })), |
| 626 | }); |
| 627 | if (boton) { delete boton.dataset.ocupado; rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ext-install'; } |
| 628 | // una extensión que solo trae temas se ve al instante: se aplica el primero |
| 629 | // (con «Deshacer» en el aviso) |
| 630 | const soloTemas = rec.themes?.length && !rec.grammars?.length && !rec.snippets?.length && !(rec.languages || []).some(l => l.configKey && !host.builtinLanguage?.(l.id)); |
| 631 | let auto = false; |
| 632 | if (soloTemas && !rec.themes.some(t => t.themeId === host.currentTheme()) && rec.enabled !== false && !host.paused) { |
| 633 | await host.setTheme(rec.themes[0].themeId); |
| 634 | auto = true; |
| 635 | } |
| 636 | const nAvisos = avisosVisibles(rec.warnings).length; |
| 637 | const primera = auto ? ' ' + tx('cThemeApplied', { name: rec.themes[0].label }) : ''; |
| 638 | aviso(tx('installedMsg', { name: rec.displayName || nombre }) + primera + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : '')); |
| 639 | await pintaTarjeta(rec, { previo: auto ? temaAntes : null }); |
| 640 | pintaInstaladas(); |
| 641 | } catch (e) { |
| 642 | if (boton) { delete boton.dataset.ocupado; inerte(boton, false); rotula(boton, original.texto, original.accesible); } |
| 643 | if (e?.code === 'codeonly') { |
| 644 | aviso(textoNoInstalada(e.displayName || nombre, e.analysis), true); |
| 645 | if (boton) { const v = describe(hechosDeManifiesto(e.analysis)); botonSegunVeredicto(boton, v, nombre); } |
| 646 | } else aviso(textoError(e), true); |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | // ── después de instalar: qué cambió, dónde verlo y un botón para probarlo ── |
| 651 | const baseName = p => String(p).split('/').pop(); |
| 652 | const cita = x => tx('quoted', { x }); |
| 653 | async function ide() { try { return await import('../ide.js'); } catch { return null; } } |
| 654 | async function ficherosDelProyecto() { try { return await (await import('../tools/code.js')).fileList(); } catch { return []; } } |
| 655 | function pestañasCon(ideMod, langs) { |
| 656 | const ids = new Set(langs); |
| 657 | return (ideMod?.openTabs?.() || []).filter(t => ids.has(t.language) || ids.has(host.languageForPath?.(t.path))); |
| 658 | } |
| 659 | async function ficheroCon(ideMod, langs) { |
| 660 | const ids = new Set(langs); |
| 661 | const abiertas = pestañasCon(ideMod, langs); |
| 662 | if (abiertas.length) return { path: (abiertas.find(t => t.active) || abiertas[0]).path, abierta: true }; |
| 663 | for (const f of await ficherosDelProyecto()) if (ids.has(host.languageForPath?.(f) || ideMod?.languageOfPath?.(f))) return { path: f, abierta: false }; |
| 664 | return null; |
| 665 | } |
| 666 | async function irA(path, { foco = true } = {}) { |
| 667 | const m = await ide(); |
| 668 | cierraPanel(); |
| 669 | await m?.openFile(path); |
| 670 | if (foco) m?.focusEditor(); |
| 671 | } |
| 672 | async function pruebaSnippets(rec, objetivo) { |
| 673 | const prefijos = await host.snippetPrefixes(rec.id).catch(() => []); |
| 674 | const pista = tx('statusTrySnippets', { prefixes: listaO(prefijos.map(cita)) }); |
| 675 | if (!objetivo) { aviso(pista); return; } |
| 676 | await irA(objetivo); |
| 677 | const sb = document.getElementById('statusbar'); |
| 678 | if (sb) sb.textContent = pista; |
| 679 | } |
| 680 | async function pruebaResaltado(langs) { |
| 681 | const m = await ide(); |
| 682 | const f = await ficheroCon(m, langs); |
| 683 | if (f) { await irA(f.path); return; } |
| 684 | aviso(tx('cHighlightTry', { exts: lista(langs.flatMap(l => extsDe(l)).slice(0, 4)) })); |
| 685 | } |
| 686 | function resumenAjustes(conf) { |
| 687 | if (!conf || typeof conf !== 'object') return []; |
| 688 | const que = []; |
| 689 | const lc = conf.comments?.lineComment, bc = conf.comments?.blockComment; |
| 690 | if (typeof lc === 'string') que.push(tx('sComment', { c: lc })); |
| 691 | else if (Array.isArray(bc) && bc.length === 2) que.push(tx('sComment', { c: bc.join(' … ') })); |
| 692 | const par = p => (Array.isArray(p) ? p[0] + p[1] : p && typeof p.open === 'string' ? p.open + p.close : null); |
| 693 | if (Array.isArray(conf.brackets) && conf.brackets.length) que.push(tx('sBrackets', { b: conf.brackets.map(par).filter(Boolean).slice(0, 4).join(' ') })); |
| 694 | if (Array.isArray(conf.autoClosingPairs) && conf.autoClosingPairs.length) que.push(tx('sAutoClose', { p: conf.autoClosingPairs.map(par).filter(Boolean).slice(0, 5).join(' ') })); |
| 695 | return que; |
| 696 | } |
| 697 | |
| 698 | async function pintaTarjeta(rec, { previo = null } = {}) { |
| 699 | const sitio = $('ext-msg'); |
| 700 | if (!sitio) return; |
| 701 | const m = await ide(); |
| 702 | const f = hechosDeRegistro(rec); |
| 703 | const v = describe(f); |
| 704 | const box = el('section', 'ext-done'); |
| 705 | box.id = 'ext-done'; |
| 706 | box.setAttribute('aria-labelledby', 'ext-done-h'); |
| 707 | const h = el('div', 'ext-done-h', tx('installedMsg', { name: rec.displayName })); |
| 708 | h.id = 'ext-done-h'; |
| 709 | box.appendChild(h); |
| 710 | const parte = () => { const p = el('div', 'ext-done-part'); box.appendChild(p); return p; }; |
| 711 | const botones = p => { const x = el('div', 'ext-done-acts'); p.appendChild(x); return x; }; |
| 712 | const boton = (fila, texto, act, fn, accesible = null) => { |
| 713 | const b = el('button', 'ghost', texto); |
| 714 | b.type = 'button'; |
| 715 | b.dataset.act = act; |
| 716 | if (accesible) b.setAttribute('aria-label', accesible); |
| 717 | b.onclick = fn; |
| 718 | fila.appendChild(b); |
| 719 | return b; |
| 720 | }; |
| 721 | |
| 722 | if (rec.themes?.length) { |
| 723 | const p = parte(); |
| 724 | const pinta = (enfoca = null) => { |
| 725 | p.replaceChildren(); |
| 726 | const activo = rec.themes.find(t => t.themeId === host.currentTheme()); |
| 727 | p.appendChild(el('div', null, activo ? tx('cThemeApplied', { name: activo.label }) |
| 728 | : rec.themes.length === 1 ? tx('cThemeReady', { name: rec.themes[0].label }) : tx('cThemesReady', { n: rec.themes.length, list: lista(rec.themes.map(t => cita(t.label))) }))); |
| 729 | const fila = botones(p); |
| 730 | if (activo && previo && previo !== activo.themeId) boton(fila, tx('bUndo'), 'undo-theme', async () => { await host.setTheme(previo); pinta('apply-theme'); pintaInstaladas(); }); |
| 731 | if (!activo) boton(fila, tx('bApplyNow'), 'apply-theme', async () => { await host.setTheme(rec.themes[0].themeId); pinta('undo-theme'); pintaInstaladas(); }); |
| 732 | boton(fila, tx('bPickTheme'), 'pick-theme', () => openThemePicker(host)); |
| 733 | if (enfoca) (fila.querySelector(`[data-act="${enfoca}"]`) || fila.querySelector('button'))?.focus(); |
| 734 | }; |
| 735 | pinta(); |
| 736 | } |
| 737 | |
| 738 | if (f.highlight.length) { |
| 739 | const p = parte(); |
| 740 | const ids = f.highlight.map(x => x.id); |
| 741 | p.appendChild(el('div', null, tx('cHighlight', { list: lista(f.highlight.map(x => x.name + (x.exts.length ? ` (${x.exts.slice(0, 3).join(', ')})` : ''))) }))); |
| 742 | const abiertas = pestañasCon(m, ids); |
| 743 | if (abiertas.length) { |
| 744 | p.appendChild(el('div', null, tx('cHighlightOpen', { n: abiertas.length, files: lista(abiertas.slice(0, 3).map(t => baseName(t.path))) }))); |
| 745 | const destino = abiertas.find(t => t.active) || abiertas[0]; |
| 746 | boton(botones(p), tx('bGoto', { file: baseName(destino.path) }), 'goto', () => irA(destino.path)); |
| 747 | } else { |
| 748 | const fich = await ficheroCon(m, ids); |
| 749 | if (fich) boton(botones(p), tx('bOpenFile', { file: baseName(fich.path) }), 'open-example', () => irA(fich.path)); |
| 750 | else p.appendChild(el('div', 'muted', tx('cHighlightTry', { exts: lista(f.highlight.flatMap(x => x.exts).slice(0, 4)) }))); |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | for (const l of rec.languages || []) { |
| 755 | if (!l.configKey || host.builtinLanguage?.(l.id)) continue; |
| 756 | const que = resumenAjustes(await host.languageConfig(rec.id, l.id).catch(() => null)); |
| 757 | if (que.length) parte().appendChild(el('div', null, tx('cSettings', { lang: nombreLenguaje(l.id, [{ id: l.id, name: l.aliases?.[0] }]), what: lista(que) }))); |
| 758 | } |
| 759 | |
| 760 | if (f.snippets.length) { |
| 761 | const p = parte(); |
| 762 | const n = f.snippets.reduce((a, s) => a + (s.count || 0), 0); |
| 763 | p.appendChild(el('div', null, tx('cSnippets', { n, list: lista(f.snippets.map(s => s.name)) }))); |
| 764 | const prefijos = await host.snippetPrefixes(rec.id).catch(() => []); |
| 765 | if (prefijos.length) p.appendChild(el('div', null, tx('cSnippetsTry', { prefixes: listaO(prefijos.map(cita)) }))); |
| 766 | const destino = await ficheroCon(m, f.snippets.map(s => s.id)); |
| 767 | if (destino) boton(botones(p), tx('bTryIn', { file: baseName(destino.path) }), 'try-snippet', () => pruebaSnippets(rec, destino.path)); |
| 768 | } |
| 769 | |
| 770 | for (const l of v.lines) box.appendChild(el('div', 'ext-done-part ext-v-more', l)); |
| 771 | if (f.keepsBuiltin.length) box.appendChild(el('div', 'ext-done-part ext-v-more', tx('keepsBuiltin', { list: lista(f.keepsBuiltin) }))); |
| 772 | $('ext-done')?.remove(); |
| 773 | sitio.after(box); |
| 774 | // la región viva sigue anunciándolo; a la vista basta con la tarjeta |
| 775 | if (!sitio.classList.contains('err')) sitio.classList.add('ext-msg-sr'); |
| 776 | } |
| 777 | |
| 778 | function claveFoco(x) { |
| 779 | const k = x?.closest?.('[data-k]')?.dataset.k; |
| 780 | const id = x?.closest?.('.ext-row')?.dataset.id; |
| 781 | return k && id ? { id, k } : null; |
| 782 | } |
| 783 | function recuperaFoco(box, f) { |
| 784 | if (!f) return; |
| 785 | if (f.heading) { $('ext-installed-h')?.focus(); return; } |
| 786 | const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id); |
| 787 | const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]')); |
| 788 | if (x) x.focus(); else $('ext-installed-h')?.focus(); |
| 789 | } |
| 790 | |
| 791 | // Lo que esta extensión está haciendo AHORA, con un botón para verlo. |
| 792 | function lineasAhora(e, f) { |
| 793 | const box = el('div', 'ext-now'); |
| 794 | const linea = (texto, act = null, accesible = null, fn = null) => { |
| 795 | const d = el('div', 'ext-now-line', texto + ' '); |
| 796 | if (act) { |
| 797 | const b = el('button', 'ext-link', tx('bTry')); |
| 798 | b.type = 'button'; |
| 799 | b.dataset.act = act; |
| 800 | b.dataset.k = act; |
| 801 | if (accesible) b.setAttribute('aria-label', accesible); |
| 802 | b.onclick = fn; |
| 803 | d.appendChild(b); |
| 804 | } |
| 805 | box.appendChild(d); |
| 806 | }; |
| 807 | if (e.themes?.length) { |
| 808 | const activo = e.themes.find(t => t.themeId === host.currentTheme()); |
| 809 | linea(activo ? tx('nThemeActive', { name: activo.label }) : tx('nThemeIdle')); |
| 810 | } |
| 811 | if (f.highlight.length) { |
| 812 | const ids = f.highlight.map(x => x.id); |
| 813 | const abiertas = pestañasCon(ideCargado, ids); |
| 814 | const nombres = lista(f.highlight.map(x => x.name)); |
| 815 | linea(abiertas.length ? tx('nHighlighting', { n: abiertas.length, list: nombres }) |
| 816 | : tx('nHighlightIdle', { list: lista(f.highlight.map(x => x.name + (x.exts.length ? ` (${x.exts.slice(0, 3).join(', ')})` : ''))) }), |
| 817 | 'try-highlight', tx('tryHighlightNamed', { name: nombres }), () => pruebaResaltado(ids)); |
| 818 | } |
| 819 | if (f.settingsOnly.length) linea(tx('nSettings', { list: lista(f.settingsOnly) })); |
| 820 | if (f.snippets.length) { |
| 821 | const n = f.snippets.reduce((a, s) => a + (s.count || 0), 0); |
| 822 | const langs = lista(f.snippets.map(s => s.name)); |
| 823 | linea(tx('nSnippets', { n, list: langs }), 'try-snippet', tx('trySnippetsNamed', { name: e.displayName }), async () => { |
| 824 | const destino = await ficheroCon(await ide(), f.snippets.map(s => s.id)); |
| 825 | await pruebaSnippets(e, destino?.path); |
| 826 | }); |
| 827 | } |
| 828 | return box.childNodes.length ? box : null; |
| 829 | } |
| 830 | |
| 831 | function pintaInstaladas() { |
| 832 | const box = $('ext-installed'); |
| 833 | if (!box) return; |
| 834 | // se rehace entera: lo que tenía el foco aquí dentro lo recupera después |
| 835 | const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null); |
| 836 | focoPendiente = null; |
| 837 | // …y los avisos que estaban desplegados siguen desplegados |
| 838 | const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id)); |
| 839 | const lista = host.list(); |
| 840 | const cab = el('div', 'sk-h', tx('installedH', { n: lista.length })); |
| 841 | cab.id = 'ext-installed-h'; |
| 842 | cab.tabIndex = -1; |
| 843 | box.replaceChildren(cab); |
| 844 | if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; } |
| 845 | for (const e of lista.slice().reverse()) { |
| 846 | const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off')); |
| 847 | row.dataset.id = e.id; |
| 848 | const main = el('div', 'ext-main'); |
| 849 | const t = el('div', 'ext-title'); |
| 850 | t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`)); |
| 851 | main.append(t); |
| 852 | if (e.description) main.appendChild(el('div', 'ext-desc', e.description)); |
| 853 | const f = hechosDeRegistro(e); |
| 854 | const v = describe(f); |
| 855 | if (e.enabled && !host.paused) { |
| 856 | const ahora = lineasAhora(e, f); |
| 857 | if (ahora) main.appendChild(ahora); |
| 858 | } else main.appendChild(el('div', 'ext-now muted', tx('nOff'))); |
| 859 | main.appendChild(bloqueVeredicto(f, v, { principal: false })); |
| 860 | const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean); |
| 861 | if (avisos.length) { |
| 862 | const d = el('details', 'ext-warn'); |
| 863 | d.open = desplegados.has(e.id); |
| 864 | const s = el('summary', null, tx('warnSummary', { n: avisos.length })); |
| 865 | s.dataset.k = 'warn'; |
| 866 | const ul = el('ul'); |
| 867 | for (const a of avisos) ul.appendChild(el('li', null, a)); |
| 868 | d.append(s, ul); |
| 869 | main.appendChild(d); |
| 870 | } |
| 871 | if (e.enabled && e.themes?.length) { |
| 872 | const chips = el('div', 'ext-chips ext-theme-chips'); |
| 873 | for (const th of e.themes) { |
| 874 | const on = host.currentTheme() === th.themeId; |
| 875 | const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label); |
| 876 | c.type = 'button'; |
| 877 | c.dataset.theme = th.themeId; |
| 878 | c.dataset.k = 'theme:' + th.themeId; |
| 879 | c.setAttribute('aria-pressed', String(on)); |
| 880 | c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); }; |
| 881 | chips.appendChild(c); |
| 882 | } |
| 883 | main.appendChild(chips); |
| 884 | } |
| 885 | const meta = el('div', 'ext-meta muted', tx('license', { l: e.license || tx('noLicense') }) + ' · ' + (e.source === 'file' ? tx('fromFile') : e.verified ? tx('verified') : tx('unverified')) + ' '); |
| 886 | if (e.licenseKey) { |
| 887 | const ver = el('button', 'ext-link', tx('viewLicense')); |
| 888 | ver.type = 'button'; |
| 889 | ver.dataset.k = 'license'; |
| 890 | const pre = el('pre', 'ext-license'); |
| 891 | pre.hidden = true; |
| 892 | pre.id = 'ext-lic-' + (++nDetalle); |
| 893 | ver.setAttribute('aria-expanded', 'false'); |
| 894 | ver.setAttribute('aria-controls', pre.id); |
| 895 | ver.onclick = async () => { |
| 896 | if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id); |
| 897 | pre.hidden = !pre.hidden; |
| 898 | ver.setAttribute('aria-expanded', String(!pre.hidden)); |
| 899 | }; |
| 900 | meta.appendChild(ver); |
| 901 | main.append(meta, pre); |
| 902 | } else main.appendChild(meta); |
| 903 | |
| 904 | const acc = el('div', 'ext-actions'); |
| 905 | const bOn = el('button', 'ghost ext-toggle'); |
| 906 | bOn.type = 'button'; |
| 907 | bOn.dataset.k = 'toggle'; |
| 908 | rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName })); |
| 909 | bOn.onclick = async () => { |
| 910 | focoPendiente = { id: e.id, k: 'toggle' }; |
| 911 | bOn.disabled = true; |
| 912 | try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); } |
| 913 | pintaInstaladas(); |
| 914 | }; |
| 915 | const bDel = el('button', 'ghost ext-uninstall'); |
| 916 | bDel.type = 'button'; |
| 917 | bDel.dataset.k = 'uninstall'; |
| 918 | rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName })); |
| 919 | bDel.onclick = async () => { |
| 920 | if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return; |
| 921 | // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título) |
| 922 | const filas = [...box.querySelectorAll('.ext-row')]; |
| 923 | const i = filas.findIndex(f => f.dataset.id === e.id); |
| 924 | const otra = filas[i + 1] || filas[i - 1]; |
| 925 | focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true }; |
| 926 | bDel.disabled = true; |
| 927 | try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); } |
| 928 | pintaInstaladas(); |
| 929 | pintaResultados(); |
| 930 | }; |
| 931 | acc.append(bOn, bDel); |
| 932 | row.append(icono(null, e.displayName), main, acc); |
| 933 | box.appendChild(row); |
| 934 | } |
| 935 | recuperaFoco(box, foco); |
| 936 | } |
| 937 | |
| 938 | // ── selector de tema (estilo «Color Theme» de VS Code) ── |
| 939 | // Un combobox con su lista: las flechas mueven la opción activa (y la |
| 940 | // previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el |
| 941 | // foco vuelve a donde estaba. |
| 942 | export function openThemePicker(h) { |
| 943 | host = h; |
| 944 | ponCss(); |
| 945 | $('ext-themepick')?.remove(); |
| 946 | const previo = document.activeElement; |
| 947 | const original = h.currentTheme(); |
| 948 | const caja = el('div'); |
| 949 | caja.id = 'ext-themepick'; |
| 950 | const inp = el('input'); |
| 951 | inp.placeholder = tx('pickPh'); |
| 952 | inp.autocomplete = 'off'; |
| 953 | inp.spellcheck = false; |
| 954 | inp.setAttribute('role', 'combobox'); |
| 955 | inp.setAttribute('aria-label', tx('pickPh')); |
| 956 | inp.setAttribute('aria-expanded', 'true'); |
| 957 | inp.setAttribute('aria-autocomplete', 'list'); |
| 958 | inp.setAttribute('aria-controls', 'ext-tp-list'); |
| 959 | const lista = el('div', 'tp-list'); |
| 960 | lista.id = 'ext-tp-list'; |
| 961 | lista.setAttribute('role', 'listbox'); |
| 962 | lista.setAttribute('aria-label', tx('themeList')); |
| 963 | caja.append(inp, lista); |
| 964 | document.body.appendChild(caja); |
| 965 | |
| 966 | let items = [], sel = 0, cerrado = false; |
| 967 | const etiqueta = t => (t.builtin ? tx(t.labelKey) : t.label); |
| 968 | const cerrar = async aplicar => { |
| 969 | if (cerrado) return; |
| 970 | cerrado = true; |
| 971 | document.removeEventListener('mousedown', fuera, true); |
| 972 | caja.remove(); |
| 973 | devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext')); |
| 974 | if (aplicar) await h.setTheme(aplicar); |
| 975 | else await h.previewTheme(original); |
| 976 | if ($('ext-panel')?.isConnected) pintaInstaladas(); |
| 977 | }; |
| 978 | const fuera = e => { if (!caja.contains(e.target)) cerrar(null); }; |
| 979 | setTimeout(() => document.addEventListener('mousedown', fuera, true), 0); |
| 980 | |
| 981 | function pintaLista() { |
| 982 | const q = inp.value.trim().toLowerCase(); |
| 983 | const todos = h.themes(); |
| 984 | items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q)); |
| 985 | lista.replaceChildren(); |
| 986 | let grupo = null, caja2 = null; |
| 987 | items.forEach((t, i) => { |
| 988 | const g = t.builtin ? tx('builtinGroup') : t.extName; |
| 989 | if (g !== grupo || !caja2) { |
| 990 | grupo = g; |
| 991 | caja2 = el('div', 'tp-grupo'); |
| 992 | caja2.setAttribute('role', 'group'); |
| 993 | caja2.setAttribute('aria-label', g); |
| 994 | const cab = el('div', 'tp-group', g); |
| 995 | cab.setAttribute('aria-hidden', 'true'); |
| 996 | caja2.appendChild(cab); |
| 997 | lista.appendChild(caja2); |
| 998 | } |
| 999 | const row = el('div', 'tp-item' + (i === sel ? ' sel' : '')); |
| 1000 | row.id = 'ext-tp-' + i; |
| 1001 | row.setAttribute('role', 'option'); |
| 1002 | row.setAttribute('aria-selected', String(i === sel)); |
| 1003 | row.dataset.theme = t.id; |
| 1004 | row.append(el('span', null, etiqueta(t))); |
| 1005 | if (t.id === original) row.appendChild(el('span', 'muted', tx('current'))); |
| 1006 | row.onclick = () => cerrar(t.id); |
| 1007 | caja2.appendChild(row); |
| 1008 | }); |
| 1009 | } |
| 1010 | const marca = () => { |
| 1011 | const filas = lista.querySelectorAll('.tp-item'); |
| 1012 | filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); }); |
| 1013 | const activa = filas[sel]; |
| 1014 | if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); } |
| 1015 | else inp.removeAttribute('aria-activedescendant'); |
| 1016 | }; |
| 1017 | inp.oninput = () => { sel = 0; pintaLista(); marca(); }; |
| 1018 | inp.onkeydown = e => { |
| 1019 | if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { |
| 1020 | e.preventDefault(); |
| 1021 | if (!items.length) return; |
| 1022 | sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length; |
| 1023 | marca(); |
| 1024 | h.previewTheme(items[sel].id); |
| 1025 | } else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) cerrar(items[sel].id); } |
| 1026 | else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(null); } |
| 1027 | }; |
| 1028 | pintaLista(); |
| 1029 | sel = Math.max(0, items.findIndex(t => t.id === original)); |
| 1030 | marca(); |
| 1031 | inp.focus(); |
| 1032 | } |