Elffuss BraidHub

utopia-ia/elffuss-code public

db6defa10cbc · 28.7 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';
11
12const $ = id => document.getElementById(id);
13const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
14const CATS = [['', 'catAll'], ['Themes', 'catThemes'], ['Snippets', 'catSnippets'], ['Programming Languages', 'catLangs']];
15
16let host = null;
17let cssPuesto = false;
18const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null };
19let temporizador = null;
20let desuscribe = null;
21let abridor = null; // quién tenía el foco al abrir el panel
22let focoPendiente = null; // control a recuperar tras repintar «Instaladas»
23let nDetalle = 0;
24
25function ponCss() {
26 if (cssPuesto) return;
27 cssPuesto = true;
28 const l = document.createElement('link');
29 l.rel = 'stylesheet';
30 l.href = new URL('../../css/ext.css', import.meta.url).href;
31 document.head.appendChild(l);
32}
33
34const visible = x => !!x && x.isConnected && x !== document.body && !x.disabled && x.getClientRects().length > 0;
35// El foco vuelve a donde estaba; si eso ya no existe o no se ve (un menú que
36// se cerró, la paleta), a lo primero que se vea de la lista.
37function devuelveFoco(previo, ...alternativas) {
38 for (const x of [previo, ...alternativas]) {
39 if (typeof x === 'function') { if (x()) return; continue; }
40 if (visible(x)) { x.focus(); return; }
41 }
42}
43const enfocaEditor = () => {
44 const ed = window.monaco?.editor?.getEditors?.()[0];
45 if (!ed || !visible(ed.getDomNode())) return false;
46 ed.focus();
47 return true;
48};
49
50export function open(h, { themes = false } = {}) {
51 host = h;
52 ponCss();
53 desuscribe?.();
54 desuscribe = h.onChange(() => { if ($('ext-panel')?.isConnected) pintaInstaladas(); });
55 if (themes) return openThemePicker(h);
56 const box = $('settings-panel');
57 if (!$('ext-panel')?.isConnected || box.hidden) abridor = document.activeElement;
58 estado.msg = null; // un aviso viejo no se repite al volver a abrir
59 pinta();
60}
61
62function cierraPanel() {
63 $('settings-panel').hidden = true;
64 devuelveFoco(abridor, $('act-ext'), document.querySelector('#menubar button[data-menu="view"]'), enfocaEditor, $('prompt'));
65}
66// Para el Escape global de main.js (la capa de más arriba): cerrar el panel de
67// extensiones es esto, no cerrar Ajustes, que no sabe quién lo abrió.
68export function close() { if ($('ext-panel')?.isConnected && !$('settings-panel').hidden) cierraPanel(); }
69
70// ── mensajes legibles (exportados para las pruebas en Node) ──
71const ERRORES = {
72 rate: 'errRate', sha: 'errSha', nothing: 'errNothing', notvsix: 'errNotVsix', notfound: 'errNotFound',
73 big: 'errBig', noname: 'errNoName', blocked: 'errBlocked',
74};
75export function textoError(e) {
76 const code = e?.code;
77 if (code === 'cancel' || e?.name === 'AbortError') return tx('cancelled');
78 if (e?.name === 'QuotaExceededError') return tx('errQuota');
79 if (typeof code === 'string' && Object.hasOwn(ERRORES, code)) return tx(ERRORES[code]);
80 switch (code) {
81 case 'net': return tx('errNet', { e: e.message });
82 case 'http': return tx('errHttp', { status: e.status ? ` (${e.status})` : '' });
83 case 'mismatch': return tx('errMismatch', { got: e.got, want: e.want });
84 case 'corrupt': case 'missing': return tx('errCorrupt', { entry: e.entry ? ` (${e.entry})` : '' });
85 case 'badmanifest': return tx('errBadManifest', { e: e.message });
86 case 'unreadable': return tx('errUnreadable', { w: e.warning ? textoAviso(e.warning) : '' }).trim();
87 }
88 return tx('err', { e: e?.message || String(e) });
89}
90// Una parte del paquete que no se pudo usar (vsix.js: { kind, name, code, detail }).
91const MOTIVOS = {
92 missing: 'whyMissing', corrupt: 'whyCorrupt', big: 'whyBig', json: 'whyJson', plist: 'whyPlist',
93 notgrammar: 'whyNotGrammar', notheme: 'whyNotTheme', scope: 'whyScope', outside: 'whyOutside',
94};
95const TIPOS_AVISO = new Set(['theme', 'grammar', 'snippets', 'config', 'regex']);
96export function textoAviso(w) {
97 if (typeof w === 'string') return w; // instaladas antes de que hubiera códigos
98 if (!w || typeof w !== 'object') return '';
99 const why = w.kind !== 'regex' && typeof w.code === 'string' && Object.hasOwn(MOTIVOS, w.code) ? tx(MOTIVOS[w.code], { e: w.detail }) : w.detail;
100 return TIPOS_AVISO.has(w.kind) ? tx('warn_' + w.kind, { name: w.name, why }) : `${w.name}: ${why}`;
101}
102
103// Los avisos que importan: la configuración de un lenguaje de serie no se
104// aplica, así que sus expresiones descartadas no cuentan (ya lo dice «No aplica»).
105const avisosVisibles = ws => (ws || []).filter(w => !(w?.kind === 'regex' && w.where === 'config' && host.builtinLanguage?.(w.name)));
106
107function aviso(texto, error = false) {
108 estado.msg = texto ? { texto, error } : null;
109 const m = $('ext-msg');
110 if (!m) return;
111 // vacío pero presente: una región viva que aparece a la vez que su texto
112 // no siempre se anuncia
113 m.setAttribute('role', error ? 'alert' : 'status');
114 m.setAttribute('aria-live', error ? 'assertive' : 'polite');
115 m.hidden = false;
116 m.textContent = texto || '';
117 m.classList.toggle('err', !!error);
118}
119// Estado de la búsqueda para el lector de pantalla (la cabecera visible se
120// rehace en cada repintado y no podría anunciarse).
121function anunciaBusqueda(texto) {
122 const s = $('ext-status');
123 if (s && s.textContent !== texto) s.textContent = texto;
124}
125
126// «Aplica: 2 temas · No aplica: commands (necesita su código)», con lo que de
127// verdad se aplicaría aquí: la gramática de un lenguaje de serie sin Monarch
128// (JSON) y la configuración de un lenguaje de serie no se aplican, y no cuentan.
129function resumen({ themes = 0, grammarLangs = [], languageList = [], snippetLangs = [], ignored = [], hasCode = false, pack = [] }) {
130 const saltaGram = l => !!l && !!host.grammarSkippedFor?.(l);
131 const deSerie = id => !!host.builtinLanguage?.(id);
132 const gramSaltadas = [...new Set(grammarLangs.filter(saltaGram))];
133 const confSaltadas = [...new Set(languageList.filter(l => l.config && deSerie(l.id)).map(l => l.id))];
134 const grammars = grammarLangs.filter(l => !saltaGram(l)).length;
135 const languages = languageList.filter(l => !deSerie(l.id)).length;
136 const aplica = [];
137 if (themes) aplica.push(tx('themes', { n: themes }));
138 if (grammars) aplica.push(tx('grammars', { n: grammars }));
139 if (languages) aplica.push(tx('languages', { n: languages }));
140 if (snippetLangs.length) aplica.push(tx('snippets', { langs: snippetLangs.slice(0, 6).join(', ') + (snippetLangs.length > 6 ? '…' : '') }));
141 const porMotivo = { code: [], later: [] };
142 for (const i of ignored) (porMotivo[i.why] || porMotivo.later).push(i.key);
143 const no = [...gramSaltadas.map(lang => tx('grammarNotApplied', { lang })), ...confSaltadas.map(lang => tx('settingsNotApplied', { lang }))];
144 if (porMotivo.code.length) no.push(`${porMotivo.code.join(', ')} (${tx('needsCode')})`);
145 if (porMotivo.later.length) no.push(`${porMotivo.later.join(', ')} (${tx('notYet')})`);
146 const lineas = [];
147 lineas.push(aplica.length ? { cls: 'ext-applies', t: tx('applies', { list: aplica.join(' · ') }) } : { cls: 'ext-nothing', t: tx('nothing') });
148 if (no.length) lineas.push({ cls: 'ext-ignored', t: tx('ignores', { list: no.join(' · ') }) });
149 if (hasCode) lineas.push({ cls: 'ext-ignored', t: tx('hasCode') });
150 if (pack.length) lineas.push({ cls: 'ext-ignored', t: tx('pack', { n: pack.length }) });
151 return { lineas, any: aplica.length > 0 };
152}
153
154// Botón de acción: texto visible y nombre accesible con la extensión
155// («Instalar Monokai»). Sin nombre accesible, el lector lee el texto visible
156// (el progreso de la descarga, por ejemplo).
157function rotula(b, texto, accesible = null) {
158 b.textContent = texto;
159 if (accesible) b.setAttribute('aria-label', accesible); else b.removeAttribute('aria-label');
160}
161// Ocupado o ya hecho, pero SIN disabled: un botón deshabilitado pierde el foco
162// y quien va con teclado se quedaría en ninguna parte.
163const inerte = (b, si) => { if (si) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); };
164const esInerte = b => b.getAttribute('aria-disabled') === 'true';
165
166// ── panel ──
167function pinta() {
168 const box = $('settings-panel');
169 box.hidden = false;
170 box.replaceChildren();
171 // Es un diálogo con su propio nombre. La caja la comparten Ajustes y Skills,
172 // y Ajustes le deja role=dialog con aria-labelledby a su título: abierto
173 // Ajustes antes, este panel quedaba como un diálogo sin nombre (ese título
174 // aquí no existe), y si no, sin rol de diálogo.
175 box.setAttribute('role', 'dialog');
176 box.setAttribute('aria-labelledby', 'ext-title');
177 box.dataset.kind = 'ext';
178 const cerrar = el('button', null, '✕');
179 cerrar.id = 'settings-close';
180 cerrar.type = 'button';
181 cerrar.title = tx('close');
182 cerrar.setAttribute('aria-label', tx('close'));
183 cerrar.onclick = cierraPanel;
184 const wrap = el('div', 'ext-panel');
185 wrap.id = 'ext-panel';
186 const conEscape = e => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); cierraPanel(); } };
187 wrap.addEventListener('keydown', conEscape);
188 cerrar.addEventListener('keydown', conEscape);
189 const h3 = el('h3', null, tx('title') + ' ');
190 h3.id = 'ext-title';
191 h3.appendChild(el('span', 'muted', '· ' + tx('sub')));
192 wrap.append(h3, el('p', 'muted ext-intro', tx('intro')));
193 if (host.paused) wrap.appendChild(el('p', 'ext-paused', tx('paused')));
194
195 const barra = el('div', 'ext-toolbar');
196 const fichero = el('input');
197 fichero.type = 'file';
198 fichero.accept = '.vsix,application/zip,application/vsix';
199 fichero.hidden = true;
200 fichero.id = 'ext-file';
201 fichero.onchange = async () => {
202 const f = fichero.files?.[0];
203 fichero.value = '';
204 if (f) await instala(f, null);
205 };
206 const bVsix = el('button', 'ghost', tx('vsix'));
207 bVsix.id = 'ext-install-vsix';
208 bVsix.onclick = () => fichero.click();
209 const bTema = el('button', 'ghost', tx('themeBtn'));
210 bTema.id = 'ext-theme-btn';
211 bTema.onclick = () => openThemePicker(host);
212 barra.append(bVsix, bTema, fichero);
213 wrap.appendChild(barra);
214
215 const busca = el('div', 'ext-search');
216 const inp = el('input');
217 inp.id = 'ext-q';
218 inp.type = 'search';
219 inp.placeholder = tx('searchPh');
220 inp.setAttribute('aria-label', tx('searchPh'));
221 inp.autocomplete = 'off';
222 inp.spellcheck = false;
223 inp.value = estado.q;
224 inp.oninput = () => { estado.q = inp.value.trim(); clearTimeout(temporizador); temporizador = setTimeout(() => busca_(), 350); };
225 inp.onkeydown = e => { if (e.key === 'Enter') { clearTimeout(temporizador); busca_(); } };
226 const chips = el('div', 'ext-chips');
227 for (const [cat, key] of CATS) {
228 const c = el('button', 'ext-chip' + (estado.cat === cat ? ' on' : ''), tx(key));
229 c.dataset.cat = cat;
230 c.setAttribute('aria-pressed', String(estado.cat === cat));
231 c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); };
232 chips.appendChild(c);
233 }
234 busca.append(inp, chips);
235 wrap.appendChild(busca);
236
237 const msg = el('div', 'ext-msg');
238 msg.id = 'ext-msg';
239 msg.setAttribute('role', 'status');
240 msg.setAttribute('aria-live', 'polite');
241 wrap.appendChild(msg);
242 const estadoBusqueda = el('div', 'ext-sr');
243 estadoBusqueda.id = 'ext-status';
244 estadoBusqueda.setAttribute('role', 'status');
245 estadoBusqueda.setAttribute('aria-live', 'polite');
246 wrap.appendChild(estadoBusqueda);
247 const res = el('div', 'ext-results');
248 res.id = 'ext-results';
249 wrap.appendChild(res);
250 const inst = el('div', 'ext-installed');
251 inst.id = 'ext-installed';
252 wrap.appendChild(inst);
253 box.append(cerrar, wrap);
254
255 if (estado.msg) aviso(estado.msg.texto, estado.msg.error);
256 pintaResultados();
257 pintaInstaladas();
258 inp.focus();
259}
260
261async function busca_({ mas = false } = {}) {
262 estado.ctl?.abort();
263 const ctl = new AbortController();
264 estado.ctl = ctl;
265 const ovsx = await import('./openvsx.js');
266 if (!estado.q && estado.cat == null) { estado.items = []; estado.total = 0; pintaResultados(); return; }
267 estado.cargando = true;
268 if (!mas) { estado.items = []; estado.total = 0; }
269 aviso(null);
270 pintaResultados();
271 // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip
272 for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip')) {
273 const on = c.dataset.cat === (estado.cat || '') && estado.cat != null;
274 c.classList.toggle('on', on);
275 c.setAttribute('aria-pressed', String(on));
276 }
277 try {
278 const r = await ovsx.search(estado.q, { category: estado.cat || '', offset: mas ? estado.items.length : 0, size: 20, signal: ctl.signal });
279 if (estado.ctl !== ctl) return;
280 estado.items = mas ? estado.items.concat(r.items) : r.items;
281 estado.total = r.total;
282 } catch (e) {
283 if (e.name === 'AbortError') return;
284 aviso(textoError(e), true);
285 } finally {
286 if (estado.ctl === ctl) { estado.cargando = false; pintaResultados(); }
287 }
288}
289
290function pintaResultados() {
291 const res = $('ext-results');
292 if (!res) return;
293 res.replaceChildren();
294 if (estado.cargando && !estado.items.length) {
295 res.appendChild(el('div', 'muted ext-hint', tx('searching')));
296 anunciaBusqueda(tx('searching'));
297 return;
298 }
299 if (!estado.items.length) {
300 if (estado.q || estado.cat != null) {
301 const t = estado.cargando ? tx('searching') : tx('noResults');
302 res.appendChild(el('div', 'muted ext-hint', t));
303 anunciaBusqueda(t);
304 } else anunciaBusqueda('');
305 return;
306 }
307 res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular')));
308 anunciaBusqueda(tx('results', { n: estado.total }));
309 const instaladas = new Map(host.list().map(e => [e.id, e]));
310 for (const it of estado.items) res.appendChild(filaResultado(it, instaladas.get(`${it.namespace}.${it.name}`.toLowerCase())));
311 if (estado.items.length < estado.total) {
312 const mas = el('button', 'ghost ext-more', tx('more'));
313 mas.onclick = () => busca_({ mas: true });
314 res.appendChild(mas);
315 }
316}
317
318function icono(url, nombre) {
319 if (url) {
320 const img = el('img', 'ext-ico');
321 img.alt = '';
322 img.loading = 'lazy';
323 img.referrerPolicy = 'no-referrer';
324 img.src = url;
325 img.onerror = () => img.replaceWith(icono(null, nombre));
326 return img;
327 }
328 const letra = el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase());
329 letra.setAttribute('aria-hidden', 'true');
330 return letra;
331}
332
333function filaResultado(it, instalada) {
334 const row = el('div', 'ext-row');
335 row.dataset.id = `${it.namespace}.${it.name}`;
336 const main = el('div', 'ext-main');
337 const det = el('div', 'ext-detail');
338 det.id = 'ext-det-' + (++nDetalle);
339 det.hidden = true;
340 // el nombre es el botón que despliega el detalle (qué aplicaría y qué no):
341 // antes de instalar, también con teclado
342 const t = el('div', 'ext-title');
343 const nombre = el('button', 'ext-name', it.displayName);
344 nombre.type = 'button';
345 nombre.title = tx('details');
346 nombre.setAttribute('aria-expanded', 'false');
347 nombre.setAttribute('aria-controls', det.id);
348 nombre.onclick = e => { e.stopPropagation(); detalle(it, det, nombre); };
349 t.append(nombre, el('span', 'muted', ` ${it.namespace} · v${it.version}`));
350 if (it.verified) t.appendChild(el('span', 'ext-badge', '✓'));
351 main.append(t, el('div', 'ext-desc', it.description));
352 main.appendChild(el('div', 'ext-meta muted', tx('downloads', { n: it.downloadCount.toLocaleString() })));
353 main.appendChild(det);
354 main.onclick = e => { if (!e.target.closest('button, a, summary')) detalle(it, det, nombre); };
355
356 const acc = el('div', 'ext-actions');
357 const b = el('button', 'primary ext-install');
358 b.type = 'button';
359 if (instalada && instalada.version === it.version) {
360 rotula(b, tx('installedOk'), tx('installedNamed', { name: it.displayName }));
361 b.className = 'ghost ext-install';
362 inerte(b, true);
363 } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version }));
364 else rotula(b, tx('install'), tx('installNamed', { name: it.displayName }));
365 b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b); };
366 acc.appendChild(b);
367 row.append(icono(it.icon, it.displayName), main, acc);
368 return row;
369}
370
371async function detalle(it, det, boton) {
372 det.hidden = !det.hidden;
373 boton?.setAttribute('aria-expanded', String(!det.hidden));
374 if (det.hidden || det.dataset.listo) return;
375 det.replaceChildren(el('div', 'muted', tx('loadingDetails')));
376 try {
377 const ovsx = await import('./openvsx.js');
378 const { analyzeManifest } = await import('./vsix.js');
379 const meta = await ovsx.metadata(it.namespace, it.name, it.version);
380 const a = analyzeManifest(await ovsx.manifest(meta));
381 const r = resumen({ themes: a.applies.themes, grammarLangs: a.grammarLangs, languageList: a.languageList, snippetLangs: a.snippetLangs, ignored: a.ignored, hasCode: a.hasCode, pack: a.pack });
382 det.replaceChildren();
383 for (const l of r.lineas) det.appendChild(el('div', l.cls, l.t));
384 const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' ');
385 if (meta.files.license) {
386 const a2 = el('a', null, tx('viewLicense'));
387 a2.href = meta.files.license;
388 a2.target = '_blank';
389 a2.rel = 'noopener noreferrer';
390 lic.appendChild(a2);
391 }
392 det.appendChild(lic);
393 det.dataset.listo = '1';
394 // nada aplicable: instalarla solo daría un error, mejor decirlo en el botón
395 const inst = det.closest('.ext-row')?.querySelector('.ext-install');
396 if (!r.any && inst && !esInerte(inst)) { inerte(inst, true); inst.title = tx('nothing'); inst.className = 'ghost ext-install'; }
397 } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); }
398}
399
400async function instala(src, boton) {
401 const nombre = src instanceof Blob ? src.name : src.displayName;
402 const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null;
403 if (boton) { inerte(boton, true); rotula(boton, tx('installing')); }
404 aviso(null);
405 try {
406 const rec = await host.install(src instanceof Blob ? src : { namespace: src.namespace, name: src.name, version: src.version }, {
407 onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); },
408 confirmLarge: async mb => confirm(tx('bigConfirm', { mb })),
409 });
410 if (boton) { rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ext-install'; }
411 const nAvisos = avisosVisibles(rec.warnings).length;
412 aviso(tx('installedMsg', { name: rec.displayName || nombre }) + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
413 } catch (e) {
414 if (boton) { inerte(boton, false); rotula(boton, original.texto, original.accesible); }
415 aviso(textoError(e), true);
416 }
417}
418
419// ── instaladas ──
420function claveFoco(x) {
421 const k = x?.closest?.('[data-k]')?.dataset.k;
422 const id = x?.closest?.('.ext-row')?.dataset.id;
423 return k && id ? { id, k } : null;
424}
425function recuperaFoco(box, f) {
426 if (!f) return;
427 if (f.heading) { $('ext-installed-h')?.focus(); return; }
428 const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id);
429 const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]'));
430 if (x) x.focus(); else $('ext-installed-h')?.focus();
431}
432
433function pintaInstaladas() {
434 const box = $('ext-installed');
435 if (!box) return;
436 // se rehace entera: lo que tenía el foco aquí dentro lo recupera después
437 const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null);
438 focoPendiente = null;
439 // …y los avisos que estaban desplegados siguen desplegados
440 const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id));
441 const lista = host.list();
442 const cab = el('div', 'sk-h', tx('installedH', { n: lista.length }));
443 cab.id = 'ext-installed-h';
444 cab.tabIndex = -1;
445 box.replaceChildren(cab);
446 if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; }
447 for (const e of lista.slice().reverse()) {
448 const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off'));
449 row.dataset.id = e.id;
450 const main = el('div', 'ext-main');
451 const t = el('div', 'ext-title');
452 t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`));
453 main.append(t);
454 if (e.description) main.appendChild(el('div', 'ext-desc', e.description));
455 const r = resumen({
456 themes: e.themes?.length || 0,
457 grammarLangs: (e.grammars || []).map(g => g.language ?? null),
458 languageList: (e.languages || []).map(l => ({ id: l.id, config: !!l.configKey })),
459 snippetLangs: [...new Set((e.snippets || []).map(s => s.language))],
460 ignored: e.ignored || [], hasCode: e.hasCode, pack: e.pack || [],
461 });
462 for (const l of r.lineas) main.appendChild(el('div', l.cls, l.t));
463 // lo que el paquete declaraba y no se pudo usar: plegado, sin esconderlo
464 const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean);
465 if (avisos.length) {
466 const d = el('details', 'ext-warn');
467 d.open = desplegados.has(e.id);
468 const s = el('summary', null, tx('warnSummary', { n: avisos.length }));
469 s.dataset.k = 'warn';
470 const ul = el('ul');
471 for (const a of avisos) ul.appendChild(el('li', null, a));
472 d.append(s, ul);
473 main.appendChild(d);
474 }
475 if (e.enabled && e.themes?.length) {
476 const chips = el('div', 'ext-chips ext-theme-chips');
477 for (const th of e.themes) {
478 const on = host.currentTheme() === th.themeId;
479 const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label);
480 c.type = 'button';
481 c.dataset.theme = th.themeId;
482 c.dataset.k = 'theme:' + th.themeId;
483 c.setAttribute('aria-pressed', String(on));
484 c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); };
485 chips.appendChild(c);
486 }
487 main.appendChild(chips);
488 }
489 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')) + ' ');
490 if (e.licenseKey) {
491 const ver = el('button', 'ext-link', tx('viewLicense'));
492 ver.type = 'button';
493 ver.dataset.k = 'license';
494 const pre = el('pre', 'ext-license');
495 pre.hidden = true;
496 pre.id = 'ext-lic-' + (++nDetalle);
497 ver.setAttribute('aria-expanded', 'false');
498 ver.setAttribute('aria-controls', pre.id);
499 ver.onclick = async () => {
500 if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id);
501 pre.hidden = !pre.hidden;
502 ver.setAttribute('aria-expanded', String(!pre.hidden));
503 };
504 meta.appendChild(ver);
505 main.append(meta, pre);
506 } else main.appendChild(meta);
507
508 const acc = el('div', 'ext-actions');
509 const bOn = el('button', 'ghost ext-toggle');
510 bOn.type = 'button';
511 bOn.dataset.k = 'toggle';
512 rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName }));
513 bOn.onclick = async () => {
514 focoPendiente = { id: e.id, k: 'toggle' };
515 bOn.disabled = true;
516 try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); }
517 pintaInstaladas();
518 };
519 const bDel = el('button', 'ghost ext-uninstall');
520 bDel.type = 'button';
521 bDel.dataset.k = 'uninstall';
522 rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName }));
523 bDel.onclick = async () => {
524 if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return;
525 // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título)
526 const filas = [...box.querySelectorAll('.ext-row')];
527 const i = filas.findIndex(f => f.dataset.id === e.id);
528 const otra = filas[i + 1] || filas[i - 1];
529 focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true };
530 bDel.disabled = true;
531 try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); }
532 pintaInstaladas();
533 pintaResultados();
534 };
535 acc.append(bOn, bDel);
536 row.append(icono(null, e.displayName), main, acc);
537 box.appendChild(row);
538 }
539 recuperaFoco(box, foco);
540}
541
542// ── selector de tema (estilo «Color Theme» de VS Code) ──
543// Un combobox con su lista: las flechas mueven la opción activa (y la
544// previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el
545// foco vuelve a donde estaba.
546export function openThemePicker(h) {
547 host = h;
548 ponCss();
549 $('ext-themepick')?.remove();
550 const previo = document.activeElement;
551 const original = h.currentTheme();
552 const caja = el('div');
553 caja.id = 'ext-themepick';
554 const inp = el('input');
555 inp.placeholder = tx('pickPh');
556 inp.autocomplete = 'off';
557 inp.spellcheck = false;
558 inp.setAttribute('role', 'combobox');
559 inp.setAttribute('aria-label', tx('pickPh'));
560 inp.setAttribute('aria-expanded', 'true');
561 inp.setAttribute('aria-autocomplete', 'list');
562 inp.setAttribute('aria-controls', 'ext-tp-list');
563 const lista = el('div', 'tp-list');
564 lista.id = 'ext-tp-list';
565 lista.setAttribute('role', 'listbox');
566 lista.setAttribute('aria-label', tx('themeList'));
567 caja.append(inp, lista);
568 document.body.appendChild(caja);
569
570 let items = [], sel = 0, cerrado = false;
571 const etiqueta = t => (t.builtin ? tx(t.labelKey) : t.label);
572 const cerrar = async aplicar => {
573 if (cerrado) return;
574 cerrado = true;
575 document.removeEventListener('mousedown', fuera, true);
576 caja.remove();
577 devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext'));
578 if (aplicar) await h.setTheme(aplicar);
579 else await h.previewTheme(original);
580 if ($('ext-panel')?.isConnected) pintaInstaladas();
581 };
582 const fuera = e => { if (!caja.contains(e.target)) cerrar(null); };
583 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
584
585 function pintaLista() {
586 const q = inp.value.trim().toLowerCase();
587 const todos = h.themes();
588 items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q));
589 lista.replaceChildren();
590 let grupo = null, caja2 = null;
591 items.forEach((t, i) => {
592 const g = t.builtin ? tx('builtinGroup') : t.extName;
593 if (g !== grupo || !caja2) {
594 grupo = g;
595 caja2 = el('div', 'tp-grupo');
596 caja2.setAttribute('role', 'group');
597 caja2.setAttribute('aria-label', g);
598 const cab = el('div', 'tp-group', g);
599 cab.setAttribute('aria-hidden', 'true');
600 caja2.appendChild(cab);
601 lista.appendChild(caja2);
602 }
603 const row = el('div', 'tp-item' + (i === sel ? ' sel' : ''));
604 row.id = 'ext-tp-' + i;
605 row.setAttribute('role', 'option');
606 row.setAttribute('aria-selected', String(i === sel));
607 row.dataset.theme = t.id;
608 row.append(el('span', null, etiqueta(t)));
609 if (t.id === original) row.appendChild(el('span', 'muted', tx('current')));
610 row.onclick = () => cerrar(t.id);
611 caja2.appendChild(row);
612 });
613 }
614 const marca = () => {
615 const filas = lista.querySelectorAll('.tp-item');
616 filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); });
617 const activa = filas[sel];
618 if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); }
619 else inp.removeAttribute('aria-activedescendant');
620 };
621 inp.oninput = () => { sel = 0; pintaLista(); marca(); };
622 inp.onkeydown = e => {
623 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
624 e.preventDefault();
625 if (!items.length) return;
626 sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
627 marca();
628 h.previewTheme(items[sel].id);
629 } else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) cerrar(items[sel].id); }
630 else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(null); }
631 };
632 pintaLista();
633 sel = Math.max(0, items.findIndex(t => t.id === original));
634 marca();
635 inp.focus();
636}