Elffuss BraidHub

utopia-ia/elffuss-code public

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