Elffuss BraidHub

utopia-ia/elffuss-code public

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