Elffuss BraidHub

utopia-ia/elffuss-code public

da97708d0aaf · 39.0 KiBRawPermalink
1// Panel de extensiones: buscar en Open VSX, ver qué aplicaría cada una,
2// instalar (o un .vsix suelto), activar/desactivar, desinstalar, licencia, y
3// el selector de tema de color. Mismo patrón que el panel de Skills: se pinta
4// dentro de #settings-panel. Todo texto que viene de una extensión entra con
5// textContent, nunca como HTML.
6//
7// Teclado y lector de pantalla: todo lo que se pulsa es un botón (o un
8// <summary>), los resultados y avisos se anuncian (role=status/alert), el
9// foco no se pierde al repintar ni al cerrar, y Escape cierra el panel.
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).
15import { tx } from './i18n.js';
16
17const $ = id => document.getElementById(id);
18const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
19const CATS = [['', 'catAll'], ['Themes', 'catThemes'], ['Snippets', 'catSnippets'], ['Programming Languages', 'catLangs']];
20const PAGINAS_FILTRO = 5; // con «Funciona en Code», como mucho 5 páginas para llenar una
21const gestor = () => import('../ext2/manage.js');
22
23let host = null;
24let cssPuesto = false;
25const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null, works: false, checked: 0, cls: new Map() };
26let bajas = []; // suscripciones de los mandos de código (se sueltan al repintar)
27let temporizador = null;
28let desuscribe = null;
29let abridor = null; // quién tenía el foco al abrir el panel
30let focoPendiente = null; // control a recuperar tras repintar «Instaladas»
31let nDetalle = 0;
32
33function ponCss() {
34 if (cssPuesto) return;
35 cssPuesto = true;
36 const l = document.createElement('link');
37 l.rel = 'stylesheet';
38 l.href = new URL('../../css/ext.css', import.meta.url).href;
39 document.head.appendChild(l);
40}
41
42const visible = x => !!x && x.isConnected && x !== document.body && !x.disabled && x.getClientRects().length > 0;
43// El foco vuelve a donde estaba; si eso ya no existe o no se ve (un menú que
44// se cerró, la paleta), a lo primero que se vea de la lista.
45function devuelveFoco(previo, ...alternativas) {
46 for (const x of [previo, ...alternativas]) {
47 if (typeof x === 'function') { if (x()) return; continue; }
48 if (visible(x)) { x.focus(); return; }
49 }
50}
51const enfocaEditor = () => {
52 const ed = window.monaco?.editor?.getEditors?.()[0];
53 if (!ed || !visible(ed.getDomNode())) return false;
54 ed.focus();
55 return true;
56};
57
58export async function open(h, { themes = false } = {}) {
59 host = h;
60 ponCss();
61 desuscribe?.();
62 desuscribe = h.onChange(() => { if ($('ext-panel')?.isConnected) pintaInstaladas(); });
63 if (themes) return openThemePicker(h);
64 const box = $('settings-panel');
65 if (!$('ext-panel')?.isConnected || box.hidden) abridor = document.activeElement;
66 estado.msg = null; // un aviso viejo no se repite al volver a abrir
67 // con alguna extensión con código instalada, sus mandos se pintan ya
68 if (!m2 && h.list().some(e => e.code || e.browser)) { try { m2 = await gestor(); } catch { /* sin mandos de código */ } }
69 pinta();
70}
71
72function cierraPanel() {
73 $('settings-panel').hidden = true;
74 devuelveFoco(abridor, $('act-ext'), document.querySelector('#menubar button[data-menu="view"]'), enfocaEditor, $('prompt'));
75}
76// Para el Escape global de main.js (la capa de más arriba): cerrar el panel de
77// extensiones es esto, no cerrar Ajustes, que no sabe quién lo abrió.
78export function close() { if ($('ext-panel')?.isConnected && !$('settings-panel').hidden) cierraPanel(); }
79
80// ── mensajes legibles (exportados para las pruebas en Node) ──
81const ERRORES = {
82 rate: 'errRate', sha: 'errSha', nothing: 'errNothing', notvsix: 'errNotVsix', notfound: 'errNotFound',
83 big: 'errBig', noname: 'errNoName', blocked: 'errBlocked',
84 nosha: 'errNosha', nocode: 'errNocode', noentry: 'errNoentry', codeonly: 'errCodeonly',
85 'x2-site': 'x2Unavail_site', 'x2-browser': 'x2Unavail_browser', 'x2-off': 'x2Unavail_off', 'x2-url': 'x2Unavail_url',
86};
87export function textoError(e) {
88 const code = e?.code;
89 if (code === 'cancel' || e?.name === 'AbortError') return tx('cancelled');
90 if (e?.name === 'QuotaExceededError') return tx('errQuota');
91 if (typeof code === 'string' && Object.hasOwn(ERRORES, code)) return tx(ERRORES[code]);
92 switch (code) {
93 case 'net': return tx('errNet', { e: e.message });
94 case 'http': return tx('errHttp', { status: e.status ? ` (${e.status})` : '' });
95 case 'mismatch': return tx('errMismatch', { got: e.got, want: e.want });
96 case 'corrupt': case 'missing': return tx('errCorrupt', { entry: e.entry ? ` (${e.entry})` : '' });
97 case 'badmanifest': return tx('errBadManifest', { e: e.message });
98 case 'unreadable': return tx('errUnreadable', { w: e.warning ? textoAviso(e.warning) : '' }).trim();
99 }
100 if (m2?.isRuntimeError(e)) return m2.runtimeErrorText(e);
101 return tx('err', { e: e?.message || String(e) });
102}
103// Una parte del paquete que no se pudo usar (vsix.js: { kind, name, code, detail }).
104const MOTIVOS = {
105 missing: 'whyMissing', corrupt: 'whyCorrupt', big: 'whyBig', json: 'whyJson', plist: 'whyPlist',
106 notgrammar: 'whyNotGrammar', notheme: 'whyNotTheme', scope: 'whyScope', outside: 'whyOutside',
107};
108const TIPOS_AVISO = new Set(['theme', 'grammar', 'snippets', 'config', 'regex']);
109export function textoAviso(w) {
110 if (typeof w === 'string') return w; // instaladas antes de que hubiera códigos
111 if (!w || typeof w !== 'object') return '';
112 const why = w.kind !== 'regex' && typeof w.code === 'string' && Object.hasOwn(MOTIVOS, w.code) ? tx(MOTIVOS[w.code], { e: w.detail }) : w.detail;
113 return TIPOS_AVISO.has(w.kind) ? tx('warn_' + w.kind, { name: w.name, why }) : `${w.name}: ${why}`;
114}
115
116// Los avisos que importan: la configuración de un lenguaje de serie no se
117// aplica, así que sus expresiones descartadas no cuentan (ya lo dice «No aplica»).
118const avisosVisibles = ws => (ws || []).filter(w => !(w?.kind === 'regex' && w.where === 'config' && host.builtinLanguage?.(w.name)));
119
120function aviso(texto, error = false) {
121 estado.msg = texto ? { texto, error } : null;
122 const m = $('ext-msg');
123 if (!m) return;
124 // vacío pero presente: una región viva que aparece a la vez que su texto
125 // no siempre se anuncia
126 m.setAttribute('role', error ? 'alert' : 'status');
127 m.setAttribute('aria-live', error ? 'assertive' : 'polite');
128 m.hidden = false;
129 m.textContent = texto || '';
130 m.classList.toggle('err', !!error);
131}
132// Estado de la búsqueda para el lector de pantalla (la cabecera visible se
133// rehace en cada repintado y no podría anunciarse).
134function anunciaBusqueda(texto) {
135 const s = $('ext-status');
136 if (s && s.textContent !== texto) s.textContent = texto;
137}
138
139// «Aplica: 2 temas · No aplica: commands (necesita su código)», con lo que de
140// verdad se aplicaría aquí: la gramática de un lenguaje de serie sin Monarch
141// (JSON) y la configuración de un lenguaje de serie no se aplican, y no cuentan.
142// Con `code` (trae código para el navegador y el nivel 2 lo cuenta debajo) no
143// se dice «nada se puede aplicar» ni se listan las partes que son de su código.
144function resumen({ themes = 0, grammarLangs = [], languageList = [], snippetLangs = [], ignored = [], hasCode = false, pack = [], code = false }) {
145 const saltaGram = l => !!l && !!host.grammarSkippedFor?.(l);
146 const deSerie = id => !!host.builtinLanguage?.(id);
147 const gramSaltadas = [...new Set(grammarLangs.filter(saltaGram))];
148 const confSaltadas = [...new Set(languageList.filter(l => l.config && deSerie(l.id)).map(l => l.id))];
149 const grammars = grammarLangs.filter(l => !saltaGram(l)).length;
150 const languages = languageList.filter(l => !deSerie(l.id)).length;
151 const aplica = [];
152 if (themes) aplica.push(tx('themes', { n: themes }));
153 if (grammars) aplica.push(tx('grammars', { n: grammars }));
154 if (languages) aplica.push(tx('languages', { n: languages }));
155 if (snippetLangs.length) aplica.push(tx('snippets', { langs: snippetLangs.slice(0, 6).join(', ') + (snippetLangs.length > 6 ? '…' : '') }));
156 const porMotivo = { code: [], later: [] };
157 for (const i of ignored) (porMotivo[i.why] || porMotivo.later).push(i.key);
158 const no = [...gramSaltadas.map(lang => tx('grammarNotApplied', { lang })), ...confSaltadas.map(lang => tx('settingsNotApplied', { lang }))];
159 if (porMotivo.code.length && !code) no.push(`${porMotivo.code.join(', ')} (${tx('needsCode')})`);
160 if (porMotivo.later.length) no.push(`${porMotivo.later.join(', ')} (${tx('notYet')})`);
161 const lineas = [];
162 if (aplica.length) lineas.push({ cls: 'ext-applies', t: tx('applies', { list: aplica.join(' · ') }) });
163 else if (!code) lineas.push({ cls: 'ext-nothing', t: tx('nothing') });
164 if (no.length) lineas.push({ cls: 'ext-ignored', t: tx('ignores', { list: no.join(' · ') }) });
165 if (hasCode) lineas.push({ cls: 'ext-ignored', t: tx('hasCode') });
166 if (pack.length) lineas.push({ cls: 'ext-ignored', t: tx('pack', { n: pack.length }) });
167 return { lineas, any: aplica.length > 0 };
168}
169
170// Botón de acción: texto visible y nombre accesible con la extensión
171// («Instalar Monokai»). Sin nombre accesible, el lector lee el texto visible
172// (el progreso de la descarga, por ejemplo).
173function rotula(b, texto, accesible = null) {
174 b.textContent = texto;
175 if (accesible) b.setAttribute('aria-label', accesible); else b.removeAttribute('aria-label');
176}
177// Ocupado o ya hecho, pero SIN disabled: un botón deshabilitado pierde el foco
178// y quien va con teclado se quedaría en ninguna parte.
179const inerte = (b, si) => { if (si) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); };
180const esInerte = b => b.getAttribute('aria-disabled') === 'true';
181
182// ── panel ──
183function pinta() {
184 const box = $('settings-panel');
185 box.hidden = false;
186 box.replaceChildren();
187 // Es un diálogo con su propio nombre. La caja la comparten Ajustes y Skills,
188 // y Ajustes le deja role=dialog con aria-labelledby a su título: abierto
189 // Ajustes antes, este panel quedaba como un diálogo sin nombre (ese título
190 // aquí no existe), y si no, sin rol de diálogo.
191 box.setAttribute('role', 'dialog');
192 box.setAttribute('aria-labelledby', 'ext-title');
193 const cerrar = el('button', null, '✕');
194 cerrar.id = 'settings-close';
195 cerrar.type = 'button';
196 cerrar.title = tx('close');
197 cerrar.setAttribute('aria-label', tx('close'));
198 cerrar.onclick = cierraPanel;
199 const wrap = el('div', 'ext-panel');
200 wrap.id = 'ext-panel';
201 const conEscape = e => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); cierraPanel(); } };
202 wrap.addEventListener('keydown', conEscape);
203 cerrar.addEventListener('keydown', conEscape);
204 const h3 = el('h3', null, tx('title') + ' ');
205 h3.id = 'ext-title';
206 h3.appendChild(el('span', 'muted', '· ' + tx('sub')));
207 // con alguna extensión con código instalada, la explicación cambia
208 const conCodigo = host.list().some(e => e.code);
209 wrap.append(h3, el('p', 'muted ext-intro', tx(conCodigo ? 'introCode' : 'intro')));
210 const iso = el('details', 'ext-iso');
211 const isoS = el('summary', null, tx('isoTitle'));
212 isoS.dataset.k = 'iso';
213 iso.appendChild(isoS);
214 const isoUl = el('ul');
215 for (const k of ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6']) isoUl.appendChild(el('li', null, tx(k)));
216 iso.appendChild(isoUl);
217 wrap.appendChild(iso);
218 if (host.paused) wrap.appendChild(el('p', 'ext-paused', tx('paused')));
219
220 const barra = el('div', 'ext-toolbar');
221 const fichero = el('input');
222 fichero.type = 'file';
223 fichero.accept = '.vsix,application/zip,application/vsix';
224 fichero.hidden = true;
225 fichero.id = 'ext-file';
226 fichero.onchange = async () => {
227 const f = fichero.files?.[0];
228 fichero.value = '';
229 if (f) await instala(f, null);
230 };
231 const bVsix = el('button', 'ghost', tx('vsix'));
232 bVsix.id = 'ext-install-vsix';
233 bVsix.onclick = () => fichero.click();
234 const bTema = el('button', 'ghost', tx('themeBtn'));
235 bTema.id = 'ext-theme-btn';
236 bTema.onclick = () => openThemePicker(host);
237 barra.append(bVsix, bTema, fichero);
238 wrap.appendChild(barra);
239
240 const busca = el('div', 'ext-search');
241 const inp = el('input');
242 inp.id = 'ext-q';
243 inp.type = 'search';
244 inp.placeholder = tx('searchPh');
245 inp.setAttribute('aria-label', tx('searchPh'));
246 inp.autocomplete = 'off';
247 inp.spellcheck = false;
248 inp.value = estado.q;
249 inp.oninput = () => { estado.q = inp.value.trim(); clearTimeout(temporizador); temporizador = setTimeout(() => busca_(), 350); };
250 inp.onkeydown = e => { if (e.key === 'Enter') { clearTimeout(temporizador); busca_(); } };
251 const chips = el('div', 'ext-chips');
252 for (const [cat, key] of CATS) {
253 const c = el('button', 'ext-chip' + (estado.cat === cat ? ' on' : ''), tx(key));
254 c.dataset.cat = cat;
255 c.setAttribute('aria-pressed', String(estado.cat === cat));
256 c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); };
257 chips.appendChild(c);
258 }
259 // «Funciona en Code»: esconde lo que no funcionaría aquí (mira el manifiesto
260 // de cada resultado: Open VSX ve esas consultas, y se dice debajo)
261 const works = el('button', 'ext-chip ext-works' + (estado.works ? ' on' : ''), tx('chipWorks'));
262 works.type = 'button';
263 works.id = 'ext-works';
264 works.setAttribute('aria-pressed', String(estado.works));
265 works.onclick = () => {
266 estado.works = !estado.works;
267 works.classList.toggle('on', estado.works);
268 works.setAttribute('aria-pressed', String(estado.works));
269 $('ext-works-note').hidden = !estado.works;
270 busca_();
271 };
272 chips.appendChild(works);
273 busca.append(inp, chips);
274 wrap.appendChild(busca);
275 const nota = el('p', 'muted ext-works-note', tx('worksPrivacy'));
276 nota.id = 'ext-works-note';
277 nota.hidden = !estado.works;
278 wrap.appendChild(nota);
279
280 const msg = el('div', 'ext-msg');
281 msg.id = 'ext-msg';
282 msg.setAttribute('role', 'status');
283 msg.setAttribute('aria-live', 'polite');
284 wrap.appendChild(msg);
285 const estadoBusqueda = el('div', 'ext-sr');
286 estadoBusqueda.id = 'ext-status';
287 estadoBusqueda.setAttribute('role', 'status');
288 estadoBusqueda.setAttribute('aria-live', 'polite');
289 wrap.appendChild(estadoBusqueda);
290 const res = el('div', 'ext-results');
291 res.id = 'ext-results';
292 wrap.appendChild(res);
293 const inst = el('div', 'ext-installed');
294 inst.id = 'ext-installed';
295 wrap.appendChild(inst);
296 box.append(cerrar, wrap);
297
298 if (estado.msg) aviso(estado.msg.texto, estado.msg.error);
299 pintaResultados();
300 pintaInstaladas();
301 inp.focus();
302}
303
304async function busca_({ mas = false } = {}) {
305 estado.ctl?.abort();
306 const ctl = new AbortController();
307 estado.ctl = ctl;
308 const ovsx = await import('./openvsx.js');
309 if (!estado.q && estado.cat == null) { estado.items = []; estado.total = 0; pintaResultados(); return; }
310 estado.cargando = true;
311 if (!mas) { estado.items = []; estado.total = 0; }
312 aviso(null);
313 pintaResultados();
314 // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip
315 for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip[data-cat]')) {
316 const on = c.dataset.cat === (estado.cat || '') && estado.cat != null;
317 c.classList.toggle('on', on);
318 c.setAttribute('aria-pressed', String(on));
319 }
320 if (!mas) estado.checked = 0;
321 try {
322 // con «Funciona en Code» se llena una página de las que funcionan, mirando
323 // como mucho PAGINAS_FILTRO páginas de resultados
324 const objetivo = (mas ? estado.items.filter(seVe).length : 0) + 20;
325 for (let paginas = 0; ;) {
326 const r = await ovsx.search(estado.q, { category: estado.cat || '', offset: estado.items.length, size: 20, signal: ctl.signal });
327 if (estado.ctl !== ctl) return;
328 estado.items = estado.items.concat(r.items);
329 estado.total = r.total;
330 paginas++;
331 if (!estado.works) break;
332 const m = m2 ??= await gestor();
333 const store = await import('./store.js');
334 pintaResultados();
335 await m.classifyResults(r.items, {
336 ovsx, store, host, signal: ctl.signal, installedIds: new Set(host.list().map(e => e.id)),
337 onEach: (it, c) => { if (estado.ctl !== ctl) return; estado.cls.set(clave(it), c); estado.checked++; pintaResultadosPronto(); },
338 });
339 if (estado.ctl !== ctl) return;
340 if (estado.items.filter(seVe).length >= objetivo || estado.items.length >= estado.total || !r.items.length || paginas >= PAGINAS_FILTRO) break;
341 }
342 } catch (e) {
343 if (e.name === 'AbortError') return;
344 aviso(textoError(e), true);
345 } finally {
346 if (estado.ctl === ctl) { estado.cargando = false; pintaResultados(); }
347 }
348}
349
350const clave = it => `${it.namespace}.${it.name}@${it.version}`.toLowerCase();
351// con el filtro: solo lo que funcionaría (lo que no se pudo comprobar se enseña)
352const seVe = it => {
353 if (!estado.works) return true;
354 const c = estado.cls.get(clave(it));
355 return c === null || (c !== undefined && c.works);
356};
357let pintaPendiente = null;
358const pintaResultadosPronto = () => { pintaPendiente ??= setTimeout(() => { pintaPendiente = null; pintaResultados(); }, 150); };
359
360function pintaResultados() {
361 const res = $('ext-results');
362 if (!res) return;
363 // el foco no se pierde al repintar (el filtro repinta según comprueba)
364 const foco = res.contains(document.activeElement) ? document.activeElement.closest('.ext-row')?.dataset.id : null;
365 res.replaceChildren();
366 if (estado.cargando && !estado.items.length) {
367 res.appendChild(el('div', 'muted ext-hint', tx('searching')));
368 anunciaBusqueda(tx('searching'));
369 return;
370 }
371 const vistos = estado.items.filter(seVe);
372 if (!vistos.length) {
373 if (estado.q || estado.cat != null) {
374 const t = estado.cargando ? tx('searching') : estado.works && estado.items.length ? tx('worksNone', { n: estado.checked, total: estado.total }) : tx('noResults');
375 res.appendChild(el('div', 'muted ext-hint', t));
376 anunciaBusqueda(t);
377 } else anunciaBusqueda('');
378 return;
379 }
380 if (estado.works) {
381 const t = tx('worksChecked', { k: vistos.length, n: estado.checked, total: estado.total });
382 res.appendChild(el('div', 'sk-h', t));
383 anunciaBusqueda(estado.cargando ? tx('searching') : t);
384 } else {
385 res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular')));
386 anunciaBusqueda(tx('results', { n: estado.total }));
387 }
388 const instaladas = new Map(host.list().map(e => [e.id, e]));
389 for (const it of vistos) res.appendChild(filaResultado(it, instaladas.get(`${it.namespace}.${it.name}`.toLowerCase())));
390 if (estado.items.length < estado.total && !estado.cargando) {
391 const mas = el('button', 'ghost ext-more', tx('more'));
392 mas.onclick = () => busca_({ mas: true });
393 res.appendChild(mas);
394 }
395 if (foco) [...res.querySelectorAll('.ext-row')].find(r => r.dataset.id === foco)?.querySelector('.ext-name')?.focus();
396}
397
398function icono(url, nombre) {
399 if (url) {
400 const img = el('img', 'ext-ico');
401 img.alt = '';
402 img.loading = 'lazy';
403 img.referrerPolicy = 'no-referrer';
404 img.src = url;
405 img.onerror = () => img.replaceWith(icono(null, nombre));
406 return img;
407 }
408 const letra = el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase());
409 letra.setAttribute('aria-hidden', 'true');
410 return letra;
411}
412
413function filaResultado(it, instalada) {
414 const row = el('div', 'ext-row');
415 row.dataset.id = `${it.namespace}.${it.name}`;
416 const main = el('div', 'ext-main');
417 const det = el('div', 'ext-detail');
418 det.id = 'ext-det-' + (++nDetalle);
419 det.hidden = true;
420 // el nombre es el botón que despliega el detalle (qué aplicaría y qué no):
421 // antes de instalar, también con teclado
422 const t = el('div', 'ext-title');
423 const nombre = el('button', 'ext-name', it.displayName);
424 nombre.type = 'button';
425 nombre.title = tx('details');
426 nombre.setAttribute('aria-expanded', 'false');
427 nombre.setAttribute('aria-controls', det.id);
428 nombre.onclick = e => { e.stopPropagation(); detalle(it, det, nombre); };
429 t.append(nombre, el('span', 'muted', ` ${it.namespace} · v${it.version}`));
430 if (it.verified) t.appendChild(el('span', 'ext-badge', '✓'));
431 main.append(t, el('div', 'ext-desc', it.description));
432 main.appendChild(el('div', 'ext-meta muted', tx('downloads', { n: it.downloadCount.toLocaleString() })));
433 main.appendChild(det);
434 main.onclick = e => { if (!e.target.closest('button, a, summary')) detalle(it, det, nombre); };
435
436 const acc = el('div', 'ext-actions');
437 const b = el('button', 'primary ext-install');
438 b.type = 'button';
439 if (instalada && instalada.version === it.version) {
440 rotula(b, tx('installedOk'), tx('installedNamed', { name: it.displayName }));
441 b.className = 'ghost ext-install';
442 inerte(b, true);
443 } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version }));
444 else rotula(b, tx('install'), tx('installNamed', { name: it.displayName }));
445 // actualizar una que corre su código la trae con su código (y su suma)
446 b.onclick = async e => {
447 e.stopPropagation();
448 if (esInerte(b)) return;
449 if (!instalada) { inerte(b, true); const sigue = await antesDeInstalar(it); inerte(b, false); if (!sigue) return; }
450 instala(it, b, { withCode: !!instalada?.code });
451 };
452 acc.appendChild(b);
453 // nivel 2: si ya se sabe qué funcionará (filtro o detalle), se dice en la fila
454 const c = estado.cls.get(clave(it));
455 if (c && m2) {
456 const lineas = el('div', 'ext-x2-lines');
457 for (const l of m2.linesFor(c)) lineas.appendChild(el('div', l.cls, l.t));
458 main.insertBefore(lineas, det);
459 ponBotonCodigo(acc, it, c, instalada);
460 }
461 row.append(icono(it.icon, it.displayName), main, acc);
462 return row;
463}
464
465// Instalar con su código (el botón, el consentimiento y la instalación): en
466// ../ext2/manage.js, que se carga con el detalle, el filtro o si hay alguna.
467let m2 = null; // ../ext2/manage.js, una vez cargado
468let conCodigo = null;
469const codigo = () => (conCodigo ??= m2.codeInstall({ host: () => host, aviso, instala, rotula, inerte, esInerte }));
470const ponBotonCodigo = (...a) => { if (m2) codigo().button(...a); };
471
472async function detalle(it, det, boton) {
473 det.hidden = !det.hidden;
474 boton?.setAttribute('aria-expanded', String(!det.hidden));
475 if (det.hidden || det.dataset.listo) return;
476 det.replaceChildren(el('div', 'muted', tx('loadingDetails')));
477 try {
478 const ovsx = await import('./openvsx.js');
479 const { analyzeManifest } = await import('./vsix.js');
480 const meta = await ovsx.metadata(it.namespace, it.name, it.version);
481 const manifest = await ovsx.manifest(meta);
482 const a = analyzeManifest(manifest);
483 m2 ??= await gestor();
484 const d2 = await m2.describe(manifest, { installedIds: new Set(host.list().map(e => e.id)), host });
485 estado.cls.set(clave(it), d2.cls);
486 // «Funciona ya (sin código)» del nivel 2 en vez del «Aplica» de siempre (lo
487 // mismo), luego lo que no se aplica y por qué, y luego lo de su código
488 const r = resumen({ themes: a.applies.themes, grammarLangs: a.grammarLangs, languageList: a.languageList, snippetLangs: a.snippetLangs, ignored: a.ignored, hasCode: false, pack: a.pack, code: true });
489 const ya = d2.lines.filter(l => l.cls === 'ext-applies');
490 det.replaceChildren(...[...ya, ...r.lineas.filter(l => l.cls !== 'ext-applies' || !ya.length), ...d2.lines.filter(l => !ya.includes(l))].map(l => el('div', l.cls, l.t)));
491 const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' ');
492 if (meta.files.license) {
493 const a2 = el('a', null, tx('viewLicense'));
494 a2.href = meta.files.license;
495 a2.target = '_blank';
496 a2.rel = 'noopener noreferrer';
497 lic.appendChild(a2);
498 }
499 det.appendChild(lic);
500 det.dataset.listo = '1';
501 const fila = det.closest('.ext-row');
502 // nada aplicable: instalarla solo daría un error, mejor decirlo en el botón
503 const inst = fila?.querySelector('.ext-install');
504 if (!d2.cls.hasDeclarative && !d2.cls.eligible && inst && !esInerte(inst)) { inerte(inst, true); inst.title = tx('nothing'); inst.className = 'ghost ext-install'; }
505 const acc = fila?.querySelector('.ext-actions');
506 if (acc) ponBotonCodigo(acc, it, d2.cls, host.list().find(e => e.id === `${it.namespace}.${it.name}`.toLowerCase()));
507 } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); }
508}
509
510// «Instalar» sin detalle visto: su manifiesto antes que el .vsix (si algo se
511// aplica, sin cargar el nivel 2); si solo trae código, su botón, con el foco
512async function antesDeInstalar(it) {
513 if (!estado.cls.get(clave(it))) {
514 try {
515 const ovsx = await import('./openvsx.js');
516 const man = await ovsx.manifest(await ovsx.metadata(it.namespace, it.name, it.version));
517 const a = (await import('./vsix.js')).analyzeManifest(man);
518 if (resumen({ ...a, themes: a.applies.themes }).any) return true;
519 m2 ??= await gestor();
520 estado.cls.set(clave(it), (await m2.describe(man, { installedIds: new Set(host.list().map(e => e.id)), host })).cls);
521 } catch { return true; }
522 }
523 if (estado.cls.get(clave(it)).hasDeclarative) return true;
524 pintaResultados();
525 const fila = [...document.querySelectorAll('#ext-results .ext-row')].find(r => r.dataset.id === `${it.namespace}.${it.name}`);
526 const cod = fila?.querySelector('.ext-install-code');
527 aviso(!cod ? tx('nothing') : esInerte(cod) ? cod.title : tx('errCodeonly'), true);
528 (cod || fila?.querySelector('.ext-name'))?.focus();
529 return false;
530}
531
532async function instala(src, boton, { withCode = false } = {}) {
533 const nombre = src instanceof Blob ? src.name : src.displayName;
534 const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null;
535 if (boton) { inerte(boton, true); rotula(boton, tx('installing')); }
536 aviso(null);
537 try {
538 const rec = await host.install(src instanceof Blob ? src : { namespace: src.namespace, name: src.name, version: src.version }, {
539 onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); },
540 confirmLarge: async mb => confirm(tx('bigConfirm', { mb })),
541 withCode,
542 });
543 if (boton) { rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ' + (withCode ? 'ext-install-code' : 'ext-install'); }
544 const nAvisos = avisosVisibles(rec.warnings).length;
545 aviso(tx(withCode ? 'installedCodeMsg' : 'installedMsg', { name: rec.displayName || nombre }) + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
546 // un .vsix con temas o snippets Y código para el navegador: se ofrece
547 // también su código (desde un fichero no hay otra forma de traerlo luego)
548 if (src instanceof Blob && !withCode && rec.browser && !rec.code) return instalaFicheroConCodigo(src, { yaInstalada: true });
549 } catch (e) {
550 if (boton) { inerte(boton, false); rotula(boton, original.texto, original.accesible); }
551 // un .vsix con solo código: se ofrece ejecutarlo (con su consentimiento)
552 if (e?.code === 'codeonly' && src instanceof Blob) return instalaFicheroConCodigo(src);
553 if (e?.code === 'codeonly' && !(await antesDeInstalar(src))) return;
554 aviso(textoError(e), true);
555 }
556}
557
558const instalaFicheroConCodigo = async (file, opts) => { m2 ??= await gestor(); return codigo().file(file, opts); };
559
560// ── instaladas ──
561function claveFoco(x) {
562 if (x?.id === 'ext-installed-h') return { heading: true };
563 const k = x?.closest?.('[data-k]')?.dataset.k;
564 const id = x?.closest?.('.ext-row')?.dataset.id;
565 return k && id ? { id, k } : null;
566}
567function recuperaFoco(box, f) {
568 if (!f) return;
569 if (f.heading) { $('ext-installed-h')?.focus(); return; }
570 const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id);
571 const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]'));
572 if (x) x.focus(); else $('ext-installed-h')?.focus();
573}
574
575function pintaInstaladas() {
576 const box = $('ext-installed');
577 if (!box) return;
578 // se rehace entera: lo que tenía el foco aquí dentro lo recupera después
579 const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null);
580 focoPendiente = null;
581 // …y los avisos que estaban desplegados siguen desplegados
582 const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id));
583 // (y los plegables de los mandos de código, con lo que se estaba escribiendo)
584 const abiertos = new Set([...box.querySelectorAll('.ext-x2 details[open]')].map(d => d.closest('.ext-row')?.dataset.id + '|' + d.className));
585 const borradores = new Map([...box.querySelectorAll('.ext-x2-json')].map(t => [t.closest('.ext-row')?.dataset.id, t.value]));
586 for (const b of bajas) { try { b(); } catch { /* — */ } }
587 bajas = [];
588 const lista = host.list();
589 // la explicación del panel cambia con la primera extensión con código (y vuelve sin ninguna)
590 const intro = document.querySelector('#ext-panel .ext-intro');
591 if (intro) intro.textContent = tx(lista.some(e => e.code) ? 'introCode' : 'intro');
592 const cab = el('div', 'sk-h', tx('installedH', { n: lista.length }));
593 cab.id = 'ext-installed-h';
594 cab.tabIndex = -1;
595 box.replaceChildren(cab);
596 if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; }
597 // con código en marcha: una línea con su estado y un botón para apagarlo todo
598 if (lista.some(e => e.runs && e.enabled) && m2) {
599 box.appendChild(m2.runtimeLine(host, { register: f => bajas.push(f), onUnblock: () => { aviso(tx('x2Unblocked')); $('ext-installed-h')?.focus(); } }));
600 const todo = el('button', 'ghost ext-x2-alloff', tx('allCodeOff'));
601 todo.type = 'button';
602 todo.onclick = async () => { focoPendiente = { heading: true }; for (const e of host.list()) if (e.runs) await host.setRuns(e.id, false); aviso(tx('allCodeOffDone')); };
603 box.appendChild(todo);
604 }
605 if ((lista.some(e => e.code || e.browser)) && !m2) gestor().then(m => { m2 = m; pintaInstaladas(); }).catch(() => {});
606 for (const e of lista.slice().reverse()) {
607 const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off'));
608 row.dataset.id = e.id;
609 const main = el('div', 'ext-main');
610 const t = el('div', 'ext-title');
611 t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`));
612 main.append(t);
613 if (e.description) main.appendChild(el('div', 'ext-desc', e.description));
614 const r = resumen({
615 themes: e.themes?.length || 0,
616 grammarLangs: (e.grammars || []).map(g => g.language ?? null),
617 languageList: (e.languages || []).map(l => ({ id: l.id, config: !!l.configKey })),
618 snippetLangs: [...new Set((e.snippets || []).map(s => s.language))],
619 // (el código para el navegador lo cuentan los mandos de abajo)
620 ignored: e.ignored || [], hasCode: e.hasCode && !e.code && !e.browser, pack: e.pack || [], code: !!(e.code || e.browser),
621 });
622 for (const l of r.lineas) main.appendChild(el('div', l.cls, l.t));
623 // mandos del código (nivel 2): ejecutar o no, estado, comandos, ajustes…
624 if ((e.code || e.browser) && m2) {
625 const b = m2.codeBlock(e, {
626 host,
627 onGetCode: rec => codigo().installed(rec),
628 onMessage: (t, error) => aviso(typeof t === 'string' ? t : textoError(t), error),
629 register: f => bajas.push(f),
630 });
631 for (const d of b.querySelectorAll('details')) if (abiertos.has(e.id + '|' + d.className)) d.open = true;
632 const ta = b.querySelector('.ext-x2-json');
633 if (ta && borradores.has(e.id)) ta.value = borradores.get(e.id);
634 main.appendChild(b);
635 }
636 // lo que el paquete declaraba y no se pudo usar: plegado, sin esconderlo
637 const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean);
638 if (avisos.length) {
639 const d = el('details', 'ext-warn');
640 d.open = desplegados.has(e.id);
641 const s = el('summary', null, tx('warnSummary', { n: avisos.length }));
642 s.dataset.k = 'warn';
643 const ul = el('ul');
644 for (const a of avisos) ul.appendChild(el('li', null, a));
645 d.append(s, ul);
646 main.appendChild(d);
647 }
648 if (e.enabled && e.themes?.length) {
649 const chips = el('div', 'ext-chips ext-theme-chips');
650 for (const th of e.themes) {
651 const on = host.currentTheme() === th.themeId;
652 const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label);
653 c.type = 'button';
654 c.dataset.theme = th.themeId;
655 c.dataset.k = 'theme:' + th.themeId;
656 c.setAttribute('aria-pressed', String(on));
657 c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); };
658 chips.appendChild(c);
659 }
660 main.appendChild(chips);
661 }
662 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')) + ' ');
663 if (e.licenseKey) {
664 const ver = el('button', 'ext-link', tx('viewLicense'));
665 ver.type = 'button';
666 ver.dataset.k = 'license';
667 const pre = el('pre', 'ext-license');
668 pre.hidden = true;
669 pre.id = 'ext-lic-' + (++nDetalle);
670 ver.setAttribute('aria-expanded', 'false');
671 ver.setAttribute('aria-controls', pre.id);
672 ver.onclick = async () => {
673 if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id);
674 pre.hidden = !pre.hidden;
675 ver.setAttribute('aria-expanded', String(!pre.hidden));
676 };
677 meta.appendChild(ver);
678 main.append(meta, pre);
679 } else main.appendChild(meta);
680
681 const acc = el('div', 'ext-actions');
682 const bOn = el('button', 'ghost ext-toggle');
683 bOn.type = 'button';
684 bOn.dataset.k = 'toggle';
685 rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName }));
686 bOn.onclick = async () => {
687 focoPendiente = { id: e.id, k: 'toggle' };
688 bOn.disabled = true;
689 try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); }
690 pintaInstaladas();
691 };
692 const bDel = el('button', 'ghost ext-uninstall');
693 bDel.type = 'button';
694 bDel.dataset.k = 'uninstall';
695 rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName }));
696 bDel.onclick = async () => {
697 if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return;
698 // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título)
699 const filas = [...box.querySelectorAll('.ext-row')];
700 const i = filas.findIndex(f => f.dataset.id === e.id);
701 const otra = filas[i + 1] || filas[i - 1];
702 focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true };
703 bDel.disabled = true;
704 try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); }
705 pintaInstaladas();
706 pintaResultados();
707 };
708 acc.append(bOn, bDel);
709 row.append(icono(null, e.displayName), main, acc);
710 box.appendChild(row);
711 }
712 recuperaFoco(box, foco);
713}
714
715// ── selector de tema (estilo «Color Theme» de VS Code) ──
716// Un combobox con su lista: las flechas mueven la opción activa (y la
717// previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el
718// foco vuelve a donde estaba.
719export function openThemePicker(h) {
720 host = h;
721 ponCss();
722 $('ext-themepick')?.remove();
723 const previo = document.activeElement;
724 const original = h.currentTheme();
725 const caja = el('div');
726 caja.id = 'ext-themepick';
727 const inp = el('input');
728 inp.placeholder = tx('pickPh');
729 inp.autocomplete = 'off';
730 inp.spellcheck = false;
731 inp.setAttribute('role', 'combobox');
732 inp.setAttribute('aria-label', tx('pickPh'));
733 inp.setAttribute('aria-expanded', 'true');
734 inp.setAttribute('aria-autocomplete', 'list');
735 inp.setAttribute('aria-controls', 'ext-tp-list');
736 const lista = el('div', 'tp-list');
737 lista.id = 'ext-tp-list';
738 lista.setAttribute('role', 'listbox');
739 lista.setAttribute('aria-label', tx('themeList'));
740 caja.append(inp, lista);
741 document.body.appendChild(caja);
742
743 let items = [], sel = 0, cerrado = false;
744 const etiqueta = t => (t.builtin ? tx(t.labelKey) : t.label);
745 const cerrar = async aplicar => {
746 if (cerrado) return;
747 cerrado = true;
748 document.removeEventListener('mousedown', fuera, true);
749 caja.remove();
750 devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext'));
751 if (aplicar) await h.setTheme(aplicar);
752 else await h.previewTheme(original);
753 if ($('ext-panel')?.isConnected) pintaInstaladas();
754 };
755 const fuera = e => { if (!caja.contains(e.target)) cerrar(null); };
756 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
757
758 function pintaLista() {
759 const q = inp.value.trim().toLowerCase();
760 const todos = h.themes();
761 items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q));
762 lista.replaceChildren();
763 let grupo = null, caja2 = null;
764 items.forEach((t, i) => {
765 const g = t.builtin ? tx('builtinGroup') : t.extName;
766 if (g !== grupo || !caja2) {
767 grupo = g;
768 caja2 = el('div', 'tp-grupo');
769 caja2.setAttribute('role', 'group');
770 caja2.setAttribute('aria-label', g);
771 const cab = el('div', 'tp-group', g);
772 cab.setAttribute('aria-hidden', 'true');
773 caja2.appendChild(cab);
774 lista.appendChild(caja2);
775 }
776 const row = el('div', 'tp-item' + (i === sel ? ' sel' : ''));
777 row.id = 'ext-tp-' + i;
778 row.setAttribute('role', 'option');
779 row.setAttribute('aria-selected', String(i === sel));
780 row.dataset.theme = t.id;
781 row.append(el('span', null, etiqueta(t)));
782 if (t.id === original) row.appendChild(el('span', 'muted', tx('current')));
783 row.onclick = () => cerrar(t.id);
784 caja2.appendChild(row);
785 });
786 }
787 const marca = () => {
788 const filas = lista.querySelectorAll('.tp-item');
789 filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); });
790 const activa = filas[sel];
791 if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); }
792 else inp.removeAttribute('aria-activedescendant');
793 };
794 inp.oninput = () => { sel = 0; pintaLista(); marca(); };
795 inp.onkeydown = e => {
796 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
797 e.preventDefault();
798 if (!items.length) return;
799 sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
800 marca();
801 h.previewTheme(items[sel].id);
802 } else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) cerrar(items[sel].id); }
803 else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(null); }
804 };
805 pintaLista();
806 sel = Math.max(0, items.findIndex(t => t.id === original));
807 marca();
808 inp.focus();
809}