Elffuss BraidHub

utopia-ia/elffuss-code public

152be91d1268 · 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 const cerrar = el('button', null, '✕');
178 cerrar.id = 'settings-close';
179 cerrar.type = 'button';
180 cerrar.title = tx('close');
181 cerrar.setAttribute('aria-label', tx('close'));
182 cerrar.onclick = cierraPanel;
183 const wrap = el('div', 'ext-panel');
184 wrap.id = 'ext-panel';
185 const conEscape = e => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); cierraPanel(); } };
186 wrap.addEventListener('keydown', conEscape);
187 cerrar.addEventListener('keydown', conEscape);
188 const h3 = el('h3', null, tx('title') + ' ');
189 h3.id = 'ext-title';
190 h3.appendChild(el('span', 'muted', '· ' + tx('sub')));
191 wrap.append(h3, el('p', 'muted ext-intro', tx('intro')));
192 if (host.paused) wrap.appendChild(el('p', 'ext-paused', tx('paused')));
193
194 const barra = el('div', 'ext-toolbar');
195 const fichero = el('input');
196 fichero.type = 'file';
197 fichero.accept = '.vsix,application/zip,application/vsix';
198 fichero.hidden = true;
199 fichero.id = 'ext-file';
200 fichero.onchange = async () => {
201 const f = fichero.files?.[0];
202 fichero.value = '';
203 if (f) await instala(f, null);
204 };
205 const bVsix = el('button', 'ghost', tx('vsix'));
206 bVsix.id = 'ext-install-vsix';
207 bVsix.onclick = () => fichero.click();
208 const bTema = el('button', 'ghost', tx('themeBtn'));
209 bTema.id = 'ext-theme-btn';
210 bTema.onclick = () => openThemePicker(host);
211 barra.append(bVsix, bTema, fichero);
212 wrap.appendChild(barra);
213
214 const busca = el('div', 'ext-search');
215 const inp = el('input');
216 inp.id = 'ext-q';
217 inp.type = 'search';
218 inp.placeholder = tx('searchPh');
219 inp.setAttribute('aria-label', tx('searchPh'));
220 inp.autocomplete = 'off';
221 inp.spellcheck = false;
222 inp.value = estado.q;
223 inp.oninput = () => { estado.q = inp.value.trim(); clearTimeout(temporizador); temporizador = setTimeout(() => busca_(), 350); };
224 inp.onkeydown = e => { if (e.key === 'Enter') { clearTimeout(temporizador); busca_(); } };
225 const chips = el('div', 'ext-chips');
226 for (const [cat, key] of CATS) {
227 const c = el('button', 'ext-chip' + (estado.cat === cat ? ' on' : ''), tx(key));
228 c.dataset.cat = cat;
229 c.setAttribute('aria-pressed', String(estado.cat === cat));
230 c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); };
231 chips.appendChild(c);
232 }
233 busca.append(inp, chips);
234 wrap.appendChild(busca);
235
236 const msg = el('div', 'ext-msg');
237 msg.id = 'ext-msg';
238 msg.setAttribute('role', 'status');
239 msg.setAttribute('aria-live', 'polite');
240 wrap.appendChild(msg);
241 const estadoBusqueda = el('div', 'ext-sr');
242 estadoBusqueda.id = 'ext-status';
243 estadoBusqueda.setAttribute('role', 'status');
244 estadoBusqueda.setAttribute('aria-live', 'polite');
245 wrap.appendChild(estadoBusqueda);
246 const res = el('div', 'ext-results');
247 res.id = 'ext-results';
248 wrap.appendChild(res);
249 const inst = el('div', 'ext-installed');
250 inst.id = 'ext-installed';
251 wrap.appendChild(inst);
252 box.append(cerrar, wrap);
253
254 if (estado.msg) aviso(estado.msg.texto, estado.msg.error);
255 pintaResultados();
256 pintaInstaladas();
257 inp.focus();
258}
259
260async function busca_({ mas = false } = {}) {
261 estado.ctl?.abort();
262 const ctl = new AbortController();
263 estado.ctl = ctl;
264 const ovsx = await import('./openvsx.js');
265 if (!estado.q && estado.cat == null) { estado.items = []; estado.total = 0; pintaResultados(); return; }
266 estado.cargando = true;
267 if (!mas) { estado.items = []; estado.total = 0; }
268 aviso(null);
269 pintaResultados();
270 // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip
271 for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip')) {
272 const on = c.dataset.cat === (estado.cat || '') && estado.cat != null;
273 c.classList.toggle('on', on);
274 c.setAttribute('aria-pressed', String(on));
275 }
276 try {
277 const r = await ovsx.search(estado.q, { category: estado.cat || '', offset: mas ? estado.items.length : 0, size: 20, signal: ctl.signal });
278 if (estado.ctl !== ctl) return;
279 estado.items = mas ? estado.items.concat(r.items) : r.items;
280 estado.total = r.total;
281 } catch (e) {
282 if (e.name === 'AbortError') return;
283 aviso(textoError(e), true);
284 } finally {
285 if (estado.ctl === ctl) { estado.cargando = false; pintaResultados(); }
286 }
287}
288
289function pintaResultados() {
290 const res = $('ext-results');
291 if (!res) return;
292 res.replaceChildren();
293 if (estado.cargando && !estado.items.length) {
294 res.appendChild(el('div', 'muted ext-hint', tx('searching')));
295 anunciaBusqueda(tx('searching'));
296 return;
297 }
298 if (!estado.items.length) {
299 if (estado.q || estado.cat != null) {
300 const t = estado.cargando ? tx('searching') : tx('noResults');
301 res.appendChild(el('div', 'muted ext-hint', t));
302 anunciaBusqueda(t);
303 } else anunciaBusqueda('');
304 return;
305 }
306 res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular')));
307 anunciaBusqueda(tx('results', { n: estado.total }));
308 const instaladas = new Map(host.list().map(e => [e.id, e]));
309 for (const it of estado.items) res.appendChild(filaResultado(it, instaladas.get(`${it.namespace}.${it.name}`.toLowerCase())));
310 if (estado.items.length < estado.total) {
311 const mas = el('button', 'ghost ext-more', tx('more'));
312 mas.onclick = () => busca_({ mas: true });
313 res.appendChild(mas);
314 }
315}
316
317function icono(url, nombre) {
318 if (url) {
319 const img = el('img', 'ext-ico');
320 img.alt = '';
321 img.loading = 'lazy';
322 img.referrerPolicy = 'no-referrer';
323 img.src = url;
324 img.onerror = () => img.replaceWith(icono(null, nombre));
325 return img;
326 }
327 const letra = el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase());
328 letra.setAttribute('aria-hidden', 'true');
329 return letra;
330}
331
332function filaResultado(it, instalada) {
333 const row = el('div', 'ext-row');
334 row.dataset.id = `${it.namespace}.${it.name}`;
335 const main = el('div', 'ext-main');
336 const det = el('div', 'ext-detail');
337 det.id = 'ext-det-' + (++nDetalle);
338 det.hidden = true;
339 // el nombre es el botón que despliega el detalle (qué aplicaría y qué no):
340 // antes de instalar, también con teclado
341 const t = el('div', 'ext-title');
342 const nombre = el('button', 'ext-name', it.displayName);
343 nombre.type = 'button';
344 nombre.title = tx('details');
345 nombre.setAttribute('aria-expanded', 'false');
346 nombre.setAttribute('aria-controls', det.id);
347 nombre.onclick = e => { e.stopPropagation(); detalle(it, det, nombre); };
348 t.append(nombre, el('span', 'muted', ` ${it.namespace} · v${it.version}`));
349 if (it.verified) t.appendChild(el('span', 'ext-badge', '✓'));
350 main.append(t, el('div', 'ext-desc', it.description));
351 main.appendChild(el('div', 'ext-meta muted', tx('downloads', { n: it.downloadCount.toLocaleString() })));
352 main.appendChild(det);
353 main.onclick = e => { if (!e.target.closest('button, a, summary')) detalle(it, det, nombre); };
354
355 const acc = el('div', 'ext-actions');
356 const b = el('button', 'primary ext-install');
357 b.type = 'button';
358 if (instalada && instalada.version === it.version) {
359 rotula(b, tx('installedOk'), tx('installedNamed', { name: it.displayName }));
360 b.className = 'ghost ext-install';
361 inerte(b, true);
362 } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version }));
363 else rotula(b, tx('install'), tx('installNamed', { name: it.displayName }));
364 b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b); };
365 acc.appendChild(b);
366 row.append(icono(it.icon, it.displayName), main, acc);
367 return row;
368}
369
370async function detalle(it, det, boton) {
371 det.hidden = !det.hidden;
372 boton?.setAttribute('aria-expanded', String(!det.hidden));
373 if (det.hidden || det.dataset.listo) return;
374 det.replaceChildren(el('div', 'muted', tx('loadingDetails')));
375 try {
376 const ovsx = await import('./openvsx.js');
377 const { analyzeManifest } = await import('./vsix.js');
378 const meta = await ovsx.metadata(it.namespace, it.name, it.version);
379 const a = analyzeManifest(await ovsx.manifest(meta));
380 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 });
381 det.replaceChildren();
382 for (const l of r.lineas) det.appendChild(el('div', l.cls, l.t));
383 const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' ');
384 if (meta.files.license) {
385 const a2 = el('a', null, tx('viewLicense'));
386 a2.href = meta.files.license;
387 a2.target = '_blank';
388 a2.rel = 'noopener noreferrer';
389 lic.appendChild(a2);
390 }
391 det.appendChild(lic);
392 det.dataset.listo = '1';
393 // nada aplicable: instalarla solo daría un error, mejor decirlo en el botón
394 const inst = det.closest('.ext-row')?.querySelector('.ext-install');
395 if (!r.any && inst && !esInerte(inst)) { inerte(inst, true); inst.title = tx('nothing'); inst.className = 'ghost ext-install'; }
396 } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); }
397}
398
399async function instala(src, boton) {
400 const nombre = src instanceof Blob ? src.name : src.displayName;
401 const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null;
402 if (boton) { inerte(boton, true); rotula(boton, tx('installing')); }
403 aviso(null);
404 try {
405 const rec = await host.install(src instanceof Blob ? src : { namespace: src.namespace, name: src.name, version: src.version }, {
406 onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); },
407 confirmLarge: async mb => confirm(tx('bigConfirm', { mb })),
408 });
409 if (boton) { rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ext-install'; }
410 const nAvisos = avisosVisibles(rec.warnings).length;
411 aviso(tx('installedMsg', { name: rec.displayName || nombre }) + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
412 } catch (e) {
413 if (boton) { inerte(boton, false); rotula(boton, original.texto, original.accesible); }
414 aviso(textoError(e), true);
415 }
416}
417
418// ── instaladas ──
419function claveFoco(x) {
420 const k = x?.closest?.('[data-k]')?.dataset.k;
421 const id = x?.closest?.('.ext-row')?.dataset.id;
422 return k && id ? { id, k } : null;
423}
424function recuperaFoco(box, f) {
425 if (!f) return;
426 if (f.heading) { $('ext-installed-h')?.focus(); return; }
427 const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id);
428 const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]'));
429 if (x) x.focus(); else $('ext-installed-h')?.focus();
430}
431
432function pintaInstaladas() {
433 const box = $('ext-installed');
434 if (!box) return;
435 // se rehace entera: lo que tenía el foco aquí dentro lo recupera después
436 const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null);
437 focoPendiente = null;
438 // …y los avisos que estaban desplegados siguen desplegados
439 const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id));
440 const lista = host.list();
441 const cab = el('div', 'sk-h', tx('installedH', { n: lista.length }));
442 cab.id = 'ext-installed-h';
443 cab.tabIndex = -1;
444 box.replaceChildren(cab);
445 if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; }
446 for (const e of lista.slice().reverse()) {
447 const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off'));
448 row.dataset.id = e.id;
449 const main = el('div', 'ext-main');
450 const t = el('div', 'ext-title');
451 t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`));
452 main.append(t);
453 if (e.description) main.appendChild(el('div', 'ext-desc', e.description));
454 const r = resumen({
455 themes: e.themes?.length || 0,
456 grammarLangs: (e.grammars || []).map(g => g.language ?? null),
457 languageList: (e.languages || []).map(l => ({ id: l.id, config: !!l.configKey })),
458 snippetLangs: [...new Set((e.snippets || []).map(s => s.language))],
459 ignored: e.ignored || [], hasCode: e.hasCode, pack: e.pack || [],
460 });
461 for (const l of r.lineas) main.appendChild(el('div', l.cls, l.t));
462 // lo que el paquete declaraba y no se pudo usar: plegado, sin esconderlo
463 const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean);
464 if (avisos.length) {
465 const d = el('details', 'ext-warn');
466 d.open = desplegados.has(e.id);
467 const s = el('summary', null, tx('warnSummary', { n: avisos.length }));
468 s.dataset.k = 'warn';
469 const ul = el('ul');
470 for (const a of avisos) ul.appendChild(el('li', null, a));
471 d.append(s, ul);
472 main.appendChild(d);
473 }
474 if (e.enabled && e.themes?.length) {
475 const chips = el('div', 'ext-chips ext-theme-chips');
476 for (const th of e.themes) {
477 const on = host.currentTheme() === th.themeId;
478 const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label);
479 c.type = 'button';
480 c.dataset.theme = th.themeId;
481 c.dataset.k = 'theme:' + th.themeId;
482 c.setAttribute('aria-pressed', String(on));
483 c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); };
484 chips.appendChild(c);
485 }
486 main.appendChild(chips);
487 }
488 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')) + ' ');
489 if (e.licenseKey) {
490 const ver = el('button', 'ext-link', tx('viewLicense'));
491 ver.type = 'button';
492 ver.dataset.k = 'license';
493 const pre = el('pre', 'ext-license');
494 pre.hidden = true;
495 pre.id = 'ext-lic-' + (++nDetalle);
496 ver.setAttribute('aria-expanded', 'false');
497 ver.setAttribute('aria-controls', pre.id);
498 ver.onclick = async () => {
499 if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id);
500 pre.hidden = !pre.hidden;
501 ver.setAttribute('aria-expanded', String(!pre.hidden));
502 };
503 meta.appendChild(ver);
504 main.append(meta, pre);
505 } else main.appendChild(meta);
506
507 const acc = el('div', 'ext-actions');
508 const bOn = el('button', 'ghost ext-toggle');
509 bOn.type = 'button';
510 bOn.dataset.k = 'toggle';
511 rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName }));
512 bOn.onclick = async () => {
513 focoPendiente = { id: e.id, k: 'toggle' };
514 bOn.disabled = true;
515 try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); }
516 pintaInstaladas();
517 };
518 const bDel = el('button', 'ghost ext-uninstall');
519 bDel.type = 'button';
520 bDel.dataset.k = 'uninstall';
521 rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName }));
522 bDel.onclick = async () => {
523 if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return;
524 // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título)
525 const filas = [...box.querySelectorAll('.ext-row')];
526 const i = filas.findIndex(f => f.dataset.id === e.id);
527 const otra = filas[i + 1] || filas[i - 1];
528 focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true };
529 bDel.disabled = true;
530 try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); }
531 pintaInstaladas();
532 pintaResultados();
533 };
534 acc.append(bOn, bDel);
535 row.append(icono(null, e.displayName), main, acc);
536 box.appendChild(row);
537 }
538 recuperaFoco(box, foco);
539}
540
541// ── selector de tema (estilo «Color Theme» de VS Code) ──
542// Un combobox con su lista: las flechas mueven la opción activa (y la
543// previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el
544// foco vuelve a donde estaba.
545export function openThemePicker(h) {
546 host = h;
547 ponCss();
548 $('ext-themepick')?.remove();
549 const previo = document.activeElement;
550 const original = h.currentTheme();
551 const caja = el('div');
552 caja.id = 'ext-themepick';
553 const inp = el('input');
554 inp.placeholder = tx('pickPh');
555 inp.autocomplete = 'off';
556 inp.spellcheck = false;
557 inp.setAttribute('role', 'combobox');
558 inp.setAttribute('aria-label', tx('pickPh'));
559 inp.setAttribute('aria-expanded', 'true');
560 inp.setAttribute('aria-autocomplete', 'list');
561 inp.setAttribute('aria-controls', 'ext-tp-list');
562 const lista = el('div', 'tp-list');
563 lista.id = 'ext-tp-list';
564 lista.setAttribute('role', 'listbox');
565 lista.setAttribute('aria-label', tx('themeList'));
566 caja.append(inp, lista);
567 document.body.appendChild(caja);
568
569 let items = [], sel = 0, cerrado = false;
570 const etiqueta = t => (t.builtin ? tx(t.labelKey) : t.label);
571 const cerrar = async aplicar => {
572 if (cerrado) return;
573 cerrado = true;
574 document.removeEventListener('mousedown', fuera, true);
575 caja.remove();
576 devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext'));
577 if (aplicar) await h.setTheme(aplicar);
578 else await h.previewTheme(original);
579 if ($('ext-panel')?.isConnected) pintaInstaladas();
580 };
581 const fuera = e => { if (!caja.contains(e.target)) cerrar(null); };
582 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
583
584 function pintaLista() {
585 const q = inp.value.trim().toLowerCase();
586 const todos = h.themes();
587 items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q));
588 lista.replaceChildren();
589 let grupo = null, caja2 = null;
590 items.forEach((t, i) => {
591 const g = t.builtin ? tx('builtinGroup') : t.extName;
592 if (g !== grupo || !caja2) {
593 grupo = g;
594 caja2 = el('div', 'tp-grupo');
595 caja2.setAttribute('role', 'group');
596 caja2.setAttribute('aria-label', g);
597 const cab = el('div', 'tp-group', g);
598 cab.setAttribute('aria-hidden', 'true');
599 caja2.appendChild(cab);
600 lista.appendChild(caja2);
601 }
602 const row = el('div', 'tp-item' + (i === sel ? ' sel' : ''));
603 row.id = 'ext-tp-' + i;
604 row.setAttribute('role', 'option');
605 row.setAttribute('aria-selected', String(i === sel));
606 row.dataset.theme = t.id;
607 row.append(el('span', null, etiqueta(t)));
608 if (t.id === original) row.appendChild(el('span', 'muted', tx('current')));
609 row.onclick = () => cerrar(t.id);
610 caja2.appendChild(row);
611 });
612 }
613 const marca = () => {
614 const filas = lista.querySelectorAll('.tp-item');
615 filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); });
616 const activa = filas[sel];
617 if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); }
618 else inp.removeAttribute('aria-activedescendant');
619 };
620 inp.oninput = () => { sel = 0; pintaLista(); marca(); };
621 inp.onkeydown = e => {
622 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
623 e.preventDefault();
624 if (!items.length) return;
625 sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
626 marca();
627 h.previewTheme(items[sel].id);
628 } else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) cerrar(items[sel].id); }
629 else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(null); }
630 };
631 pintaLista();
632 sel = Math.max(0, items.findIndex(t => t.id === original));
633 marca();
634 inp.focus();
635}