Elffuss BraidHub

utopia-ia/elffuss-code public

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