Elffuss BraidHub

utopia-ia/elffuss-code public

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