Elffuss BraidHub

utopia-ia/elffuss-code public

fc9a8dba96f6 · 38.8 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 solo
511// trae código, la fila enseña su botón de código, 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 manifest = await ovsx.manifest(await ovsx.metadata(it.namespace, it.name, it.version));
517 m2 ??= await gestor();
518 estado.cls.set(clave(it), (await m2.describe(manifest, { installedIds: new Set(host.list().map(e => e.id)), host })).cls);
519 } catch { return true; }
520 }
521 if (estado.cls.get(clave(it)).hasDeclarative) return true;
522 pintaResultados();
523 const fila = [...document.querySelectorAll('#ext-results .ext-row')].find(r => r.dataset.id === `${it.namespace}.${it.name}`);
524 const cod = fila?.querySelector('.ext-install-code');
525 aviso(!cod ? tx('nothing') : esInerte(cod) ? cod.title : tx('errCodeonly'), true);
526 (cod || fila?.querySelector('.ext-name'))?.focus();
527 return false;
528}
529
530async function instala(src, boton, { withCode = false } = {}) {
531 const nombre = src instanceof Blob ? src.name : src.displayName;
532 const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null;
533 if (boton) { inerte(boton, true); rotula(boton, tx('installing')); }
534 aviso(null);
535 try {
536 const rec = await host.install(src instanceof Blob ? src : { namespace: src.namespace, name: src.name, version: src.version }, {
537 onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); },
538 confirmLarge: async mb => confirm(tx('bigConfirm', { mb })),
539 withCode,
540 });
541 if (boton) { rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ' + (withCode ? 'ext-install-code' : 'ext-install'); }
542 const nAvisos = avisosVisibles(rec.warnings).length;
543 aviso(tx(withCode ? 'installedCodeMsg' : 'installedMsg', { name: rec.displayName || nombre }) + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
544 // un .vsix con temas o snippets Y código para el navegador: se ofrece
545 // también su código (desde un fichero no hay otra forma de traerlo luego)
546 if (src instanceof Blob && !withCode && rec.browser && !rec.code) return instalaFicheroConCodigo(src, { yaInstalada: true });
547 } catch (e) {
548 if (boton) { inerte(boton, false); rotula(boton, original.texto, original.accesible); }
549 // un .vsix con solo código: se ofrece ejecutarlo (con su consentimiento)
550 if (e?.code === 'codeonly' && src instanceof Blob) return instalaFicheroConCodigo(src);
551 if (e?.code === 'codeonly' && !(await antesDeInstalar(src))) return;
552 aviso(textoError(e), true);
553 }
554}
555
556const instalaFicheroConCodigo = async (file, opts) => { m2 ??= await gestor(); return codigo().file(file, opts); };
557
558// ── instaladas ──
559function claveFoco(x) {
560 if (x?.id === 'ext-installed-h') return { heading: true };
561 const k = x?.closest?.('[data-k]')?.dataset.k;
562 const id = x?.closest?.('.ext-row')?.dataset.id;
563 return k && id ? { id, k } : null;
564}
565function recuperaFoco(box, f) {
566 if (!f) return;
567 if (f.heading) { $('ext-installed-h')?.focus(); return; }
568 const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id);
569 const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]'));
570 if (x) x.focus(); else $('ext-installed-h')?.focus();
571}
572
573function pintaInstaladas() {
574 const box = $('ext-installed');
575 if (!box) return;
576 // se rehace entera: lo que tenía el foco aquí dentro lo recupera después
577 const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null);
578 focoPendiente = null;
579 // …y los avisos que estaban desplegados siguen desplegados
580 const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id));
581 // (y los plegables de los mandos de código, con lo que se estaba escribiendo)
582 const abiertos = new Set([...box.querySelectorAll('.ext-x2 details[open]')].map(d => d.closest('.ext-row')?.dataset.id + '|' + d.className));
583 const borradores = new Map([...box.querySelectorAll('.ext-x2-json')].map(t => [t.closest('.ext-row')?.dataset.id, t.value]));
584 for (const b of bajas) { try { b(); } catch { /* — */ } }
585 bajas = [];
586 const lista = host.list();
587 // la explicación del panel cambia con la primera extensión con código (y vuelve sin ninguna)
588 const intro = document.querySelector('#ext-panel .ext-intro');
589 if (intro) intro.textContent = tx(lista.some(e => e.code) ? 'introCode' : 'intro');
590 const cab = el('div', 'sk-h', tx('installedH', { n: lista.length }));
591 cab.id = 'ext-installed-h';
592 cab.tabIndex = -1;
593 box.replaceChildren(cab);
594 if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; }
595 // con código en marcha: una línea con su estado y un botón para apagarlo todo
596 if (lista.some(e => e.runs && e.enabled) && m2) {
597 box.appendChild(m2.runtimeLine(host, { register: f => bajas.push(f), onUnblock: () => { aviso(tx('x2Unblocked')); $('ext-installed-h')?.focus(); } }));
598 const todo = el('button', 'ghost ext-x2-alloff', tx('allCodeOff'));
599 todo.type = 'button';
600 todo.onclick = async () => { focoPendiente = { heading: true }; for (const e of host.list()) if (e.runs) await host.setRuns(e.id, false); aviso(tx('allCodeOffDone')); };
601 box.appendChild(todo);
602 }
603 if ((lista.some(e => e.code || e.browser)) && !m2) gestor().then(m => { m2 = m; pintaInstaladas(); }).catch(() => {});
604 for (const e of lista.slice().reverse()) {
605 const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off'));
606 row.dataset.id = e.id;
607 const main = el('div', 'ext-main');
608 const t = el('div', 'ext-title');
609 t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`));
610 main.append(t);
611 if (e.description) main.appendChild(el('div', 'ext-desc', e.description));
612 const r = resumen({
613 themes: e.themes?.length || 0,
614 grammarLangs: (e.grammars || []).map(g => g.language ?? null),
615 languageList: (e.languages || []).map(l => ({ id: l.id, config: !!l.configKey })),
616 snippetLangs: [...new Set((e.snippets || []).map(s => s.language))],
617 // (el código para el navegador lo cuentan los mandos de abajo)
618 ignored: e.ignored || [], hasCode: e.hasCode && !e.code && !e.browser, pack: e.pack || [], code: !!(e.code || e.browser),
619 });
620 for (const l of r.lineas) main.appendChild(el('div', l.cls, l.t));
621 // mandos del código (nivel 2): ejecutar o no, estado, comandos, ajustes…
622 if ((e.code || e.browser) && m2) {
623 const b = m2.codeBlock(e, {
624 host,
625 onGetCode: rec => codigo().installed(rec),
626 onMessage: (t, error) => aviso(typeof t === 'string' ? t : textoError(t), error),
627 register: f => bajas.push(f),
628 });
629 for (const d of b.querySelectorAll('details')) if (abiertos.has(e.id + '|' + d.className)) d.open = true;
630 const ta = b.querySelector('.ext-x2-json');
631 if (ta && borradores.has(e.id)) ta.value = borradores.get(e.id);
632 main.appendChild(b);
633 }
634 // lo que el paquete declaraba y no se pudo usar: plegado, sin esconderlo
635 const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean);
636 if (avisos.length) {
637 const d = el('details', 'ext-warn');
638 d.open = desplegados.has(e.id);
639 const s = el('summary', null, tx('warnSummary', { n: avisos.length }));
640 s.dataset.k = 'warn';
641 const ul = el('ul');
642 for (const a of avisos) ul.appendChild(el('li', null, a));
643 d.append(s, ul);
644 main.appendChild(d);
645 }
646 if (e.enabled && e.themes?.length) {
647 const chips = el('div', 'ext-chips ext-theme-chips');
648 for (const th of e.themes) {
649 const on = host.currentTheme() === th.themeId;
650 const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label);
651 c.type = 'button';
652 c.dataset.theme = th.themeId;
653 c.dataset.k = 'theme:' + th.themeId;
654 c.setAttribute('aria-pressed', String(on));
655 c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); };
656 chips.appendChild(c);
657 }
658 main.appendChild(chips);
659 }
660 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')) + ' ');
661 if (e.licenseKey) {
662 const ver = el('button', 'ext-link', tx('viewLicense'));
663 ver.type = 'button';
664 ver.dataset.k = 'license';
665 const pre = el('pre', 'ext-license');
666 pre.hidden = true;
667 pre.id = 'ext-lic-' + (++nDetalle);
668 ver.setAttribute('aria-expanded', 'false');
669 ver.setAttribute('aria-controls', pre.id);
670 ver.onclick = async () => {
671 if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id);
672 pre.hidden = !pre.hidden;
673 ver.setAttribute('aria-expanded', String(!pre.hidden));
674 };
675 meta.appendChild(ver);
676 main.append(meta, pre);
677 } else main.appendChild(meta);
678
679 const acc = el('div', 'ext-actions');
680 const bOn = el('button', 'ghost ext-toggle');
681 bOn.type = 'button';
682 bOn.dataset.k = 'toggle';
683 rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName }));
684 bOn.onclick = async () => {
685 focoPendiente = { id: e.id, k: 'toggle' };
686 bOn.disabled = true;
687 try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); }
688 pintaInstaladas();
689 };
690 const bDel = el('button', 'ghost ext-uninstall');
691 bDel.type = 'button';
692 bDel.dataset.k = 'uninstall';
693 rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName }));
694 bDel.onclick = async () => {
695 if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return;
696 // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título)
697 const filas = [...box.querySelectorAll('.ext-row')];
698 const i = filas.findIndex(f => f.dataset.id === e.id);
699 const otra = filas[i + 1] || filas[i - 1];
700 focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true };
701 bDel.disabled = true;
702 try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); }
703 pintaInstaladas();
704 pintaResultados();
705 };
706 acc.append(bOn, bDel);
707 row.append(icono(null, e.displayName), main, acc);
708 box.appendChild(row);
709 }
710 recuperaFoco(box, foco);
711}
712
713// ── selector de tema (estilo «Color Theme» de VS Code) ──
714// Un combobox con su lista: las flechas mueven la opción activa (y la
715// previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el
716// foco vuelve a donde estaba.
717export function openThemePicker(h) {
718 host = h;
719 ponCss();
720 $('ext-themepick')?.remove();
721 const previo = document.activeElement;
722 const original = h.currentTheme();
723 const caja = el('div');
724 caja.id = 'ext-themepick';
725 const inp = el('input');
726 inp.placeholder = tx('pickPh');
727 inp.autocomplete = 'off';
728 inp.spellcheck = false;
729 inp.setAttribute('role', 'combobox');
730 inp.setAttribute('aria-label', tx('pickPh'));
731 inp.setAttribute('aria-expanded', 'true');
732 inp.setAttribute('aria-autocomplete', 'list');
733 inp.setAttribute('aria-controls', 'ext-tp-list');
734 const lista = el('div', 'tp-list');
735 lista.id = 'ext-tp-list';
736 lista.setAttribute('role', 'listbox');
737 lista.setAttribute('aria-label', tx('themeList'));
738 caja.append(inp, lista);
739 document.body.appendChild(caja);
740
741 let items = [], sel = 0, cerrado = false;
742 const etiqueta = t => (t.builtin ? tx(t.labelKey) : t.label);
743 const cerrar = async aplicar => {
744 if (cerrado) return;
745 cerrado = true;
746 document.removeEventListener('mousedown', fuera, true);
747 caja.remove();
748 devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext'));
749 if (aplicar) await h.setTheme(aplicar);
750 else await h.previewTheme(original);
751 if ($('ext-panel')?.isConnected) pintaInstaladas();
752 };
753 const fuera = e => { if (!caja.contains(e.target)) cerrar(null); };
754 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
755
756 function pintaLista() {
757 const q = inp.value.trim().toLowerCase();
758 const todos = h.themes();
759 items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q));
760 lista.replaceChildren();
761 let grupo = null, caja2 = null;
762 items.forEach((t, i) => {
763 const g = t.builtin ? tx('builtinGroup') : t.extName;
764 if (g !== grupo || !caja2) {
765 grupo = g;
766 caja2 = el('div', 'tp-grupo');
767 caja2.setAttribute('role', 'group');
768 caja2.setAttribute('aria-label', g);
769 const cab = el('div', 'tp-group', g);
770 cab.setAttribute('aria-hidden', 'true');
771 caja2.appendChild(cab);
772 lista.appendChild(caja2);
773 }
774 const row = el('div', 'tp-item' + (i === sel ? ' sel' : ''));
775 row.id = 'ext-tp-' + i;
776 row.setAttribute('role', 'option');
777 row.setAttribute('aria-selected', String(i === sel));
778 row.dataset.theme = t.id;
779 row.append(el('span', null, etiqueta(t)));
780 if (t.id === original) row.appendChild(el('span', 'muted', tx('current')));
781 row.onclick = () => cerrar(t.id);
782 caja2.appendChild(row);
783 });
784 }
785 const marca = () => {
786 const filas = lista.querySelectorAll('.tp-item');
787 filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); });
788 const activa = filas[sel];
789 if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); }
790 else inp.removeAttribute('aria-activedescendant');
791 };
792 inp.oninput = () => { sel = 0; pintaLista(); marca(); };
793 inp.onkeydown = e => {
794 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
795 e.preventDefault();
796 if (!items.length) return;
797 sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
798 marca();
799 h.previewTheme(items[sel].id);
800 } else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) cerrar(items[sel].id); }
801 else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(null); }
802 };
803 pintaLista();
804 sel = Math.max(0, items.findIndex(t => t.id === original));
805 marca();
806 inp.focus();
807}