Elffuss BraidHub

utopia-ia/elffuss-code public

main · 24.0 KiBRawPermalink
1// Lo que una extensión con código le pide al usuario, pintado por Code.
2//
3// Avisos (toasts), diálogo modal, selector rápido, cuadro de texto, progreso
4// y escribir en el portapapeles. Todo texto que viene del recinto entra con
5// textContent: un enlace se queda en texto y un botón solo devuelve cuál se
6// pulsó. Hay topes: 3 avisos a la vez y 20 por minuto, un diálogo y un
7// selector (o cuadro) a la vez; lo que se pasa se contesta «nada» al momento
8// y se cuenta. Escribir en el portapapeles solo con un gesto reciente del
9// usuario (navigator.userActivation).
10//
11// Todo cuelga de #x2-* / .x2-* (web/css/ext2.css): nada del CSS de VS Code
12// entra en la página.
13import { tx } from '../ext/i18n.js';
14import './strings.js';
15
16const MAX_TOASTS = 3;
17const TOASTS_PER_MINUTE = 20;
18const TOAST_AUTOCLOSE = 9000;
19
20const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
21const button = (txt, cls = 'x2-btn') => { const b = el('button', cls, txt); b.type = 'button'; return b; };
22let nId = 0;
23const uid = p => `${p}-${++nId}`;
24
25export const userActive = () => {
26 try { return !!globalThis.navigator?.userActivation?.isActive; } catch { return false; }
27};
28
29// Code cierra el panel de ajustes/extensiones con cualquier clic fuera de él
30// (main.js, en captura sobre document). Un clic DENTRO de estos diálogos y
31// avisos no es «fuera»: se para aquí, en captura sobre window, que va antes.
32let guarda = false;
33function guardaPanel() {
34 if (guarda) return;
35 guarda = true;
36 window.addEventListener('pointerdown', e => {
37 if (e.target instanceof Element && e.target.closest('.x2-backdrop, .x2-pick, #x2-toasts')) e.stopPropagation();
38 }, true);
39}
40
41export function loadCss() {
42 guardaPanel();
43 if (document.getElementById('x2-css')) return;
44 const l = document.createElement('link');
45 l.id = 'x2-css';
46 l.rel = 'stylesheet';
47 l.href = new URL('../../css/ext2.css', import.meta.url).href;
48 document.head.appendChild(l);
49}
50
51// Modal genérico: título, cuerpo, una caja opcional en monoespaciado (una
52// dirección, una orden; con su propio scroll si es larga), lo que vaya tras
53// ella (`after`) y botones. Escape y fuera = el botón por defecto (el de
54// cancelar). Abre por arriba: el foco no lo desplaza. Devuelve el `value` del
55// botón pulsado.
56const abiertos = new Set(); // cierres de los modales abiertos
57export function closeModals() { for (const c of [...abiertos]) c(); }
58export function modal({ id = 'x2-dialog', title, body = [], code = null, after = [], buttons, cancelValue = null, focus = 0, labelledBy = null }) {
59 return new Promise(resolve => {
60 loadCss();
61 document.getElementById(id)?.remove();
62 const previo = document.activeElement;
63 const fondo = el('div', 'x2-backdrop');
64 fondo.id = id;
65 const caja = el('div', 'x2-modal');
66 caja.setAttribute('role', 'dialog');
67 caja.setAttribute('aria-modal', 'true');
68 const h = el('h2', 'x2-modal-title', title);
69 h.id = uid('x2-title');
70 caja.setAttribute('aria-labelledby', labelledBy || h.id);
71 caja.appendChild(h);
72 const desc = [];
73 for (const p of [].concat(body).filter(x => x != null && x !== '')) {
74 const n = typeof p === 'string' ? el('p', 'x2-modal-text', p) : p;
75 if (!n.id) n.id = uid('x2-desc');
76 desc.push(n.id);
77 caja.appendChild(n);
78 }
79 if (code != null) {
80 const c = typeof code === 'string' ? el('div', 'x2-code', code) : code;
81 if (!c.id) c.id = uid('x2-desc');
82 desc.push(c.id);
83 // con teclado también se puede recorrer (y leer) entera
84 c.tabIndex = 0;
85 caja.appendChild(c);
86 }
87 for (const n of [].concat(after).filter(Boolean)) caja.appendChild(n);
88 if (desc.length) caja.setAttribute('aria-describedby', desc.join(' '));
89 const fila = el('div', 'x2-modal-buttons');
90 const botones = buttons.map(b => {
91 const x = button(b.label, 'x2-btn' + (b.primary ? ' x2-primary' : ''));
92 if (b.className) x.classList.add(b.className);
93 if (b.disabled) { x.setAttribute('aria-disabled', 'true'); x.title = b.disabled; }
94 x.onclick = async () => {
95 if (x.getAttribute('aria-disabled') === 'true') return;
96 if (typeof b.onClick === 'function') { const keep = await b.onClick(x); if (keep) return; }
97 cerrar(b.value);
98 };
99 fila.appendChild(x);
100 return x;
101 });
102 caja.appendChild(fila);
103 fondo.appendChild(caja);
104 let hecho = false;
105 function cerrar(v) {
106 if (hecho) return;
107 hecho = true;
108 abiertos.delete(cancelar);
109 fondo.remove();
110 document.removeEventListener('keydown', teclas, true);
111 if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
112 resolve(v);
113 }
114 const cancelar = () => cerrar(cancelValue);
115 abiertos.add(cancelar);
116 // el foco no sale del diálogo (Tab da la vuelta) y Escape cancela
117 function teclas(e) {
118 if (!fondo.isConnected) return;
119 if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(cancelValue); return; }
120 if (e.key === 'Tab') {
121 const fs = [...caja.querySelectorAll('button, input, textarea, [tabindex="0"]')].filter(x => !x.disabled);
122 if (!fs.length) return;
123 const i = fs.indexOf(document.activeElement);
124 const j = e.shiftKey ? (i <= 0 ? fs.length - 1 : i - 1) : (i === fs.length - 1 ? 0 : i + 1);
125 e.preventDefault();
126 fs[j].focus();
127 }
128 }
129 document.addEventListener('keydown', teclas, true);
130 fondo.addEventListener('mousedown', e => { if (e.target === fondo) cerrar(cancelValue); });
131 document.body.appendChild(fondo);
132 (botones[focus] || botones[0])?.focus({ preventScroll: true });
133 caja.scrollTop = 0;
134 });
135}
136
137// Atrapa Tab dentro de `caja` (da la vuelta) y cierra con Escape desde
138// cualquier sitio de ella, no solo desde su campo de texto.
139function atrapa(caja, cerrar) {
140 caja.addEventListener('keydown', e => {
141 if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(); return; }
142 if (e.key !== 'Tab') return;
143 const fs = [...caja.querySelectorAll('button, input, textarea, [tabindex="0"]')].filter(x => !x.disabled && !x.hidden && x.getClientRects().length);
144 if (!fs.length) return;
145 const i = fs.indexOf(document.activeElement);
146 e.preventDefault();
147 fs[e.shiftKey ? (i <= 0 ? fs.length - 1 : i - 1) : (i === fs.length - 1 ? 0 : i + 1)].focus();
148 });
149}
150
151// La tecla que lleva a los avisos (y vuelve de ellos): desde el editor, el
152// chat o el panel, como F6 en VS Code. Solo se usa mientras hay alguno.
153export const TOAST_KEY = 'F6';
154
155export class ExtUI {
156 constructor({ nameOf = id => id, log = () => {}, statusbar = () => document.getElementById('statusbar') } = {}) {
157 this.nameOf = nameOf;
158 this.log = log;
159 this.statusbar = statusbar;
160 this.toasts = []; // { el, resolve }
161 this.sent = []; // instantes de los últimos avisos (para el tope por minuto)
162 this.dialogBusy = false;
163 this.pickBusy = null; // { req, close }
164 this.progress = new Map(); // id → texto
165 this.dropped = { notify: 0, dialog: 0, pick: 0, clipboard: 0 };
166 this.closers = new Set();
167 this.volver = null; // dónde estaba el foco antes de ir a un aviso
168 this.tecla = null; // el oyente de F6
169 this.entrada = null; // la entrada de la paleta de Code
170 }
171
172 origin(source) {
173 const n = source ? this.nameOf(source) : null;
174 return n ? tx('x2From', { name: n }) : tx('x2FromAny');
175 }
176
177 // ── llegar a los avisos con el teclado: F6 y la paleta de Code ──
178 focusToast() {
179 const t = this.toasts.at(-1)?.el;
180 if (!t) return false;
181 if (!t.contains(document.activeElement)) this.volver = document.activeElement;
182 t.querySelector('.x2-toast-buttons button')?.focus();
183 return true;
184 }
185 backFromToast() {
186 const v = this.volver;
187 this.volver = null;
188 if (v && v.isConnected && v !== document.body && v.getClientRects().length && typeof v.focus === 'function') { v.focus(); return; }
189 const ed = globalThis.monaco?.editor?.getEditors?.().find(e => document.getElementById('editor')?.contains(e.getContainerDomNode()));
190 if (ed) ed.focus(); else document.getElementById('prompt')?.focus();
191 }
192 keyboard(on) {
193 if (on && !this.tecla) {
194 this.tecla = e => {
195 // (con un diálogo abierto, su foco no se suelta: primero se contesta él)
196 if (e.key !== TOAST_KEY || e.altKey || e.ctrlKey || e.metaKey || !this.toasts.length || document.querySelector('.x2-backdrop')) return;
197 e.preventDefault();
198 e.stopPropagation();
199 if (document.getElementById('x2-toasts')?.contains(document.activeElement)) this.backFromToast();
200 else this.focusToast();
201 };
202 document.addEventListener('keydown', this.tecla, true);
203 } else if (!on && this.tecla) { document.removeEventListener('keydown', this.tecla, true); this.tecla = null; }
204 // en la paleta de Code (window.elffussClaw.commands), mientras haya avisos
205 const lista = globalThis.window?.elffussClaw?.commands;
206 if (on && !this.entrada && Array.isArray(lista)) {
207 this.entrada = { label: tx('x2FocusToast'), hint: TOAST_KEY, x2: 'ui', run: () => { const p = document.getElementById('palette'); if (p) p.hidden = true; this.focusToast(); } };
208 lista.push(this.entrada);
209 } else if (!on && this.entrada) {
210 const i = Array.isArray(lista) ? lista.indexOf(this.entrada) : -1;
211 if (i >= 0) lista.splice(i, 1);
212 this.entrada = null;
213 }
214 }
215
216 // ── avisos ──
217 notify({ sev = 'info', text, actions = [], source }) {
218 const now = Date.now();
219 this.sent = this.sent.filter(t => now - t < 60000);
220 if (this.toasts.length >= MAX_TOASTS || this.sent.length >= TOASTS_PER_MINUTE) {
221 this.dropped.notify++;
222 this.log('warn', `a notification was not shown (more than ${MAX_TOASTS} on screen or ${TOASTS_PER_MINUTE} a minute): ${String(text).slice(0, 120)}`, source);
223 return Promise.resolve(null);
224 }
225 this.sent.push(now);
226 loadCss();
227 let box = document.getElementById('x2-toasts');
228 if (!box) {
229 box = el('div');
230 box.id = 'x2-toasts';
231 box.setAttribute('aria-live', 'polite');
232 document.body.appendChild(box);
233 }
234 return new Promise(resolve => {
235 const t = el('div', 'x2-toast x2-' + (['info', 'warning', 'error'].includes(sev) ? sev : 'info'));
236 t.setAttribute('role', sev === 'error' ? 'alert' : 'status');
237 t.appendChild(el('div', 'x2-toast-from', this.origin(source)));
238 t.appendChild(el('div', 'x2-toast-text', String(text)));
239 // (para el lector de pantalla: cómo llegar a sus botones desde el editor)
240 if (actions.length) t.appendChild(el('span', 'x2-sr', tx('x2ToastHint', { key: TOAST_KEY })));
241 const fila = el('div', 'x2-toast-buttons');
242 let hecho = false, reloj = null, encima = false, antes = null;
243 const entry = { el: t, resolve: null };
244 // sin botones se va solo, pero no mientras el ratón o el foco estén en él
245 const arma = () => { clearTimeout(reloj); if (!actions.length && !encima && !t.contains(document.activeElement)) reloj = setTimeout(() => fin(null), TOAST_AUTOCLOSE); };
246 const fin = v => {
247 if (hecho) return;
248 hecho = true;
249 clearTimeout(reloj);
250 const conFoco = t.contains(document.activeElement);
251 t.remove();
252 this.toasts = this.toasts.filter(x => x !== entry);
253 this.closers.delete(entry.resolve);
254 // el foco vuelve a donde estaba (nunca se queda en <body>)
255 if (conFoco) { if (antes && antes.isConnected && antes.getClientRects().length) { this.volver = null; antes.focus(); } else this.backFromToast(); }
256 if (!this.toasts.length) this.keyboard(false);
257 resolve(v);
258 };
259 entry.resolve = () => fin(null);
260 this.closers.add(entry.resolve);
261 actions.forEach((a, i) => { const b = button(a, 'x2-btn' + (i === 0 ? ' x2-primary' : '')); b.onclick = () => fin(i); fila.appendChild(b); });
262 const x = button('×', 'x2-toast-close');
263 x.setAttribute('aria-label', tx('x2Dismiss'));
264 x.onclick = () => fin(null);
265 fila.appendChild(x);
266 t.appendChild(fila);
267 t.addEventListener('mouseenter', () => { encima = true; clearTimeout(reloj); });
268 t.addEventListener('mouseleave', () => { encima = false; arma(); });
269 t.addEventListener('focusin', e => { clearTimeout(reloj); if (!t.contains(e.relatedTarget)) antes = this.volver || e.relatedTarget || antes; });
270 t.addEventListener('focusout', e => { if (!t.contains(e.relatedTarget)) setTimeout(arma, 0); });
271 t.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); fin(null); } });
272 box.appendChild(t);
273 this.toasts.push(entry);
274 this.keyboard(true);
275 arma();
276 });
277 }
278
279 // ── diálogo modal (showXMessage con {modal: true}) ──
280 async dialog({ sev = 'info', text, detail, buttons = [], cancel, source }) {
281 if (this.dialogBusy) { this.dropped.dialog++; this.log('warn', 'a second dialog was refused while one is open', source); return null; }
282 this.dialogBusy = true;
283 try {
284 const v = await modal({
285 title: this.origin(source),
286 body: [el('p', 'x2-modal-text x2-' + sev, String(text)), detail ? el('p', 'x2-modal-detail', String(detail)) : null].filter(Boolean),
287 buttons: [...buttons.map((label, i) => ({ label, value: i, primary: i === 0 })), { label: cancel || tx('x2Cancel'), value: null }],
288 cancelValue: null,
289 focus: buttons.length, // el foco empieza en cancelar
290 });
291 return v;
292 } finally { this.dialogBusy = false; }
293 }
294
295 // ── selector rápido (showQuickPick) ──
296 pick({ req, items, options = {}, source }) {
297 if (this.pickBusy) { this.dropped.pick++; this.log('warn', 'a second quick pick was refused while one is open', source); return Promise.resolve(null); }
298 loadCss();
299 return new Promise(resolve => {
300 const previo = document.activeElement;
301 const many = options.canPickMany === true;
302 const caja = el('div', 'x2-pick');
303 caja.id = 'x2-pick';
304 caja.setAttribute('role', 'dialog');
305 caja.setAttribute('aria-modal', 'true');
306 const titulo = el('div', 'x2-pick-title', options.title || this.origin(source));
307 titulo.id = uid('x2-pick-t');
308 caja.setAttribute('aria-labelledby', titulo.id);
309 const inp = el('input', 'x2-pick-input');
310 inp.type = 'text';
311 inp.autocomplete = 'off';
312 inp.spellcheck = false;
313 inp.placeholder = options.placeHolder || (many ? tx('x2PickMany') : tx('x2PickOne'));
314 inp.setAttribute('role', 'combobox');
315 inp.setAttribute('aria-expanded', 'true');
316 inp.setAttribute('aria-autocomplete', 'list');
317 const lista = el('div', 'x2-pick-list');
318 lista.id = uid('x2-pick-l');
319 lista.setAttribute('role', 'listbox');
320 if (many) lista.setAttribute('aria-multiselectable', 'true');
321 inp.setAttribute('aria-controls', lista.id);
322 inp.setAttribute('aria-label', options.title || options.placeHolder || tx('x2PickOne'));
323 const pie = el('div', 'x2-pick-foot');
324 const ok = button(tx('x2Ok'), 'x2-btn x2-primary');
325 const no = button(tx('x2Cancel'));
326 pie.append(no, ok);
327 if (!many) ok.hidden = true;
328 caja.append(titulo, inp, lista, pie);
329 document.body.appendChild(caja);
330
331 const marcados = new Set(items.map((it, i) => (it && !it.sep && it.picked ? i : -1)).filter(i => i >= 0));
332 let visibles = [], sel = 0, hecho = false;
333 const fin = v => {
334 if (hecho) return;
335 hecho = true;
336 caja.remove();
337 document.removeEventListener('mousedown', fuera, true);
338 this.pickBusy = null;
339 this.closers.delete(cerrarYa);
340 if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
341 resolve(v);
342 };
343 const cerrarYa = () => fin(null);
344 this.closers.add(cerrarYa);
345 this.pickBusy = { req, close: cerrarYa };
346 const fuera = e => { if (!caja.contains(e.target)) fin(null); };
347 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
348 const coincide = (it, q) => !q || [it.label, options.matchOnDescription ? it.description : '', options.matchOnDetail ? it.detail : '']
349 .some(s => typeof s === 'string' && s.toLowerCase().includes(q));
350 const pinta = () => {
351 const q = inp.value.trim().toLowerCase();
352 lista.replaceChildren();
353 visibles = [];
354 let grupo = null;
355 items.forEach((it, i) => {
356 if (!it) return;
357 if (it.sep !== undefined) { grupo = it.sep; return; }
358 if (!coincide(it, q)) return;
359 if (grupo !== null) {
360 const g = el('div', 'x2-pick-sep', grupo);
361 g.setAttribute('role', 'presentation');
362 lista.appendChild(g);
363 grupo = null;
364 }
365 const n = visibles.length;
366 const row = el('div', 'x2-pick-item');
367 row.id = `${lista.id}-${n}`;
368 row.setAttribute('role', 'option');
369 row.dataset.i = String(i);
370 if (many) { const c = el('span', 'x2-check', marcados.has(i) ? '☑' : '☐'); c.setAttribute('aria-hidden', 'true'); row.appendChild(c); }
371 const t = el('span', 'x2-pick-label', it.label);
372 row.appendChild(t);
373 if (it.description) row.appendChild(el('span', 'x2-pick-desc', it.description));
374 if (it.detail) row.appendChild(el('div', 'x2-pick-detail', it.detail));
375 row.onclick = () => { sel = n; if (many) { alterna(i); } else fin(i); };
376 lista.appendChild(row);
377 visibles.push(i);
378 });
379 if (!visibles.length) lista.appendChild(el('div', 'x2-pick-empty', tx('x2PickNone')));
380 sel = Math.min(sel, Math.max(0, visibles.length - 1));
381 marca();
382 };
383 const marca = () => {
384 const filas = [...lista.querySelectorAll('.x2-pick-item')];
385 filas.forEach((r, n) => {
386 const i = Number(r.dataset.i);
387 r.classList.toggle('sel', n === sel);
388 r.setAttribute('aria-selected', String(many ? marcados.has(i) : n === sel));
389 if (many) r.setAttribute('aria-checked', String(marcados.has(i)));
390 });
391 if (filas[sel]) { inp.setAttribute('aria-activedescendant', filas[sel].id); filas[sel].scrollIntoView({ block: 'nearest' }); }
392 else inp.removeAttribute('aria-activedescendant');
393 };
394 const alterna = i => {
395 if (marcados.has(i)) marcados.delete(i); else marcados.add(i);
396 const fila = lista.querySelector(`.x2-pick-item[data-i="${i}"] .x2-check`);
397 if (fila) fila.textContent = marcados.has(i) ? '☑' : '☐';
398 marca();
399 };
400 ok.onclick = () => fin([...marcados].sort((a, b) => a - b));
401 no.onclick = () => fin(null);
402 inp.oninput = () => { sel = 0; pinta(); };
403 // Tab no sale del selector y Escape lo cierra desde cualquier parte
404 atrapa(caja, () => fin(null));
405 inp.onkeydown = e => {
406 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
407 e.preventDefault();
408 if (!visibles.length) return;
409 sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + visibles.length) % visibles.length;
410 marca();
411 // con varias a elegir, Espacio marca la resaltada aunque haya filtro
412 // (el filtro se escribe sin espacios; lo dice el texto de ayuda)
413 } else if (e.key === ' ' && many) { e.preventDefault(); if (visibles.length) alterna(visibles[sel]); }
414 else if (e.key === 'Enter') {
415 e.preventDefault();
416 if (many) fin([...marcados].sort((a, b) => a - b));
417 else if (visibles.length) fin(visibles[sel]);
418 }
419 };
420 pinta();
421 inp.focus();
422 });
423 }
424
425 // ── cuadro de texto (showInputBox) ──
426 input({ req, options = {}, source }) {
427 if (this.pickBusy) { this.dropped.pick++; this.log('warn', 'an input box was refused while another one is open', source); return Promise.resolve(null); }
428 loadCss();
429 return new Promise(resolve => {
430 const previo = document.activeElement;
431 const caja = el('div', 'x2-pick x2-inputbox');
432 caja.id = 'x2-input';
433 caja.setAttribute('role', 'dialog');
434 caja.setAttribute('aria-modal', 'true');
435 const titulo = el('div', 'x2-pick-title', options.title || this.origin(source));
436 titulo.id = uid('x2-input-t');
437 caja.setAttribute('aria-labelledby', titulo.id);
438 const inp = el('input', 'x2-pick-input');
439 inp.type = options.password ? 'password' : 'text';
440 inp.autocomplete = 'off';
441 inp.spellcheck = false;
442 inp.placeholder = options.placeHolder || '';
443 inp.value = typeof options.value === 'string' ? options.value : '';
444 const ayuda = el('div', 'x2-input-prompt', options.prompt || tx('x2InputHint'));
445 ayuda.id = uid('x2-input-p');
446 const error = el('div', 'x2-input-error', options.validation || '');
447 error.id = uid('x2-input-e');
448 error.setAttribute('role', 'alert');
449 error.hidden = !options.validation;
450 inp.setAttribute('aria-describedby', ayuda.id + ' ' + error.id);
451 inp.setAttribute('aria-label', options.title || options.prompt || tx('x2InputHint'));
452 if (options.validation) inp.setAttribute('aria-invalid', 'true');
453 const pie = el('div', 'x2-pick-foot');
454 const ok = button(tx('x2Ok'), 'x2-btn x2-primary');
455 const no = button(tx('x2Cancel'));
456 pie.append(no, ok);
457 caja.append(titulo, inp, ayuda, error, pie);
458 document.body.appendChild(caja);
459 let hecho = false;
460 const fin = v => {
461 if (hecho) return;
462 hecho = true;
463 caja.remove();
464 document.removeEventListener('mousedown', fuera, true);
465 this.pickBusy = null;
466 this.closers.delete(cerrarYa);
467 if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
468 resolve(v);
469 };
470 const cerrarYa = () => fin(null);
471 this.closers.add(cerrarYa);
472 this.pickBusy = { req, close: cerrarYa };
473 const fuera = e => { if (!caja.contains(e.target)) fin(null); };
474 setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
475 ok.onclick = () => fin(inp.value);
476 no.onclick = () => fin(null);
477 atrapa(caja, () => fin(null));
478 inp.onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); fin(inp.value); } };
479 inp.focus();
480 inp.select();
481 });
482 }
483
484 // la extensión canceló su selector o su cuadro (token)
485 cancel(req) { if (this.pickBusy && this.pickBusy.req === req) this.pickBusy.close(); }
486
487 // ── progreso, en la barra de estado ──
488 setProgress({ id, text, done }) {
489 if (done) this.progress.delete(id); else this.progress.set(id, text);
490 const bar = this.statusbar();
491 if (!bar) return;
492 let p = document.getElementById('x2-progress');
493 if (!this.progress.size) { p?.remove(); return; }
494 if (!p) {
495 loadCss();
496 p = el('span', 'x2-progress');
497 p.id = 'x2-progress';
498 p.setAttribute('role', 'status');
499 bar.appendChild(p);
500 } else if (p.parentNode !== bar) bar.appendChild(p);
501 const textos = [...this.progress.values()].filter(Boolean);
502 p.textContent = '⟳ ' + (textos[textos.length - 1] || tx('x2Working')) + (this.progress.size > 1 ? ` (+${this.progress.size - 1})` : '');
503 }
504
505 // ── portapapeles: solo con un gesto reciente del usuario ──
506 async clipboard(text, source) {
507 if (typeof text !== 'string') return false;
508 if (!userActive()) {
509 this.dropped.clipboard++;
510 this.log('warn', 'a clipboard write without a recent click or key press was dropped', source);
511 return false;
512 }
513 try { await navigator.clipboard.writeText(text.slice(0, 500000)); return true; }
514 catch { this.log('warn', 'the browser refused the clipboard write', source); return false; }
515 }
516
517 dispose() {
518 for (const c of [...this.closers]) { try { c(); } catch { /* — */ } }
519 this.closers.clear();
520 for (const t of [...this.toasts]) { try { t.resolve(); } catch { /* — */ } }
521 this.keyboard(false);
522 document.getElementById('x2-toasts')?.remove();
523 closeModals();
524 this.progress.clear();
525 document.getElementById('x2-progress')?.remove();
526 }
527}