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