utopia-ia/elffuss-claw public
Changesets · Branches · Tags · Compare
| Changeset | ab79fa6b790fe63035abfb83dc8d2c6ca30ca8b9079d6f45d19035847ce92dc2 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 15:53 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 17:45 +02:00 |
| Parents | 06bd031f65c7 |
6 files changed
added tests/ux-comun.mjs +86 −0
| @@ -0,0 +1,86 @@ | ||
| 1 | +// Utilidades comunes de los tests de UX (tests/ux-*.mjs). Sin modelo ni GPU: | |
| 2 | +// modo básico, determinista. Las peticiones a terceros se cortan aquí para que | |
| 3 | +// ningún test dependa de la red ni toque producción; three.js (la Mente) es lo | |
| 4 | +// único que se deja pasar, y solo si un test abre la Mente. | |
| 5 | +// | |
| 6 | +// python3 server/serve.py 8743 & BASE=http://localhost:8743 node tests/ux-<algo>.mjs | |
| 7 | +import { chromium } from 'playwright'; | |
| 8 | + | |
| 9 | +export const BASE = process.env.BASE || 'http://localhost:8743'; | |
| 10 | +export const OUT = process.env.SCRATCH || ''; | |
| 11 | + | |
| 12 | +let fails = 0; | |
| 13 | +export const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 14 | +export const fallos = () => fails; | |
| 15 | +export const espera = ms => new Promise(r => setTimeout(r, ms)); | |
| 16 | +export async function hasta(cond, { veces = 200, cada = 50 } = {}) { | |
| 17 | + for (let i = 0; i < veces; i++) { if (await cond()) return true; await espera(cada); } | |
| 18 | + return false; | |
| 19 | +} | |
| 20 | + | |
| 21 | +// Lo que NO puede salir de la máquina en un test: el modelo grande, el broker, | |
| 22 | +// SoundCloud, Hugging Face, GitHub (salvo que el test lo stubee), producción. | |
| 23 | +const CORTAR = [ | |
| 24 | + /^https:\/\/([a-z0-9-]+\.)?soundcloud\.com\//, | |
| 25 | + /^https:\/\/([a-z0-9-]+\.)?huggingface\.co\//, | |
| 26 | + /^https:\/\/([a-z0-9-]+\.)?hf\.co\//, | |
| 27 | + /^https:\/\/(m\d+|models)\.elffuss\.(com|utopiaia\.com)\//, | |
| 28 | + /^https:\/\/([a-z0-9-]+\.)?elffuss\.com\//, | |
| 29 | + /^https:\/\/([a-z0-9-]+\.)?openverse\.org\//, | |
| 30 | + /^https:\/\/([a-z0-9-]+\.)?duckduckgo\.com\//, | |
| 31 | + /^https:\/\/cdn\.sheetjs\.com\//, | |
| 32 | + /^https:\/\/cdn\.jsdelivr\.net\/npm\/@huggingface\//, | |
| 33 | + /^https:\/\/cdn\.jsdelivr\.net\/npm\/@mlc-ai\//, | |
| 34 | + /^https:\/\/cdn\.jsdelivr\.net\/npm\/@litert/, | |
| 35 | + /^https:\/\/([a-z0-9-]+\.)?googleapis\.com\//, | |
| 36 | + /^https:\/\/(api\.github\.com|raw\.githubusercontent\.com)\//, | |
| 37 | +]; | |
| 38 | + | |
| 39 | +export async function navegador() { return chromium.launch(); } | |
| 40 | + | |
| 41 | +// Contexto con Claw en modo básico, ya «bienvenido» y con los permisos que se | |
| 42 | +// pidan. `rutas` permite stubear una URL externa: (url, route) → true si la | |
| 43 | +// atendió. | |
| 44 | +export async function contexto(b, { locale = 'es-ES', viewport = { width: 1400, height: 900 }, welcomed = true, | |
| 45 | + model = 'rules', grants = null, rutas = null, isMobile = false, hasTouch = false, extraInit = null } = {}) { | |
| 46 | + const ctx = await b.newContext({ locale, viewport, acceptDownloads: true, isMobile, hasTouch }); | |
| 47 | + const fuera = []; | |
| 48 | + await ctx.route('**/*', async route => { | |
| 49 | + const url = route.request().url(); | |
| 50 | + if (url.startsWith(BASE) || url.startsWith('data:') || url.startsWith('blob:')) return route.continue(); | |
| 51 | + if (rutas && await rutas(url, route)) return; | |
| 52 | + fuera.push(route.request().method() + ' ' + url.slice(0, 140)); | |
| 53 | + if (CORTAR.some(rx => rx.test(url))) return route.abort(); | |
| 54 | + return route.continue(); | |
| 55 | + }); | |
| 56 | + await ctx.addInitScript(({ welcomed, model, grants, extraInit }) => { | |
| 57 | + try { | |
| 58 | + if (welcomed) localStorage.setItem('elffuss.welcomed', '1'); | |
| 59 | + if (model) localStorage.setItem('elffuss.model', model); | |
| 60 | + if (grants) localStorage.setItem('elffuss.grants', JSON.stringify(grants)); | |
| 61 | + if (extraInit) for (const [k, v] of Object.entries(extraInit)) localStorage.setItem(k, v); | |
| 62 | + } catch { /* */ } | |
| 63 | + }, { welcomed, model, grants, extraInit }); | |
| 64 | + return { ctx, fuera }; | |
| 65 | +} | |
| 66 | + | |
| 67 | +export async function pagina(ctx, ruta = '/') { | |
| 68 | + const p = await ctx.newPage(); | |
| 69 | + const errores = []; | |
| 70 | + p.on('pageerror', e => { if (!/allow-same-origin/.test(e.message)) errores.push(e.message); }); | |
| 71 | + p.on('dialog', d => { p.__dialogos = (p.__dialogos || []).concat(d.message()); (p.__aceptar === false ? d.dismiss() : d.accept()).catch(() => {}); }); | |
| 72 | + await p.goto(BASE + ruta, { waitUntil: 'domcontentloaded' }); | |
| 73 | + await p.waitForFunction(() => !!window.elffuss?.agent, null, { timeout: 15000 }); | |
| 74 | + return { p, errores }; | |
| 75 | +} | |
| 76 | + | |
| 77 | +export const kv = (p, key) => p.evaluate(async k => (await import('/js/db.js')).get('kv', k), key); | |
| 78 | +export const avisos = p => p.$$eval('#toasts .toast .toast-txt', ts => ts.map(t => t.textContent)); | |
| 79 | +export async function escribir(p, texto) { await p.fill('#prompt', texto); await p.press('#prompt', 'Enter'); } | |
| 80 | +export const reposo = p => hasta(() => p.evaluate(() => !document.getElementById('send').classList.contains('is-stop') | |
| 81 | + && !document.querySelector('#log .msg.thinking'))); | |
| 82 | + | |
| 83 | +export function fin(b, titulo) { | |
| 84 | + console.log(fails ? `\n❌ ${fails} FALLO(S)` : `\n✅ ${titulo}`); | |
| 85 | + return b.close().then(() => process.exit(fails ? 1 : 0)); | |
| 86 | +} |
added tests/ux-dialogos.mjs +96 −0
| @@ -0,0 +1,96 @@ | ||
| 1 | +// Diálogo de permisos y avisos (toasts), con el teclado y con el ratón. | |
| 2 | +// · Escape en el diálogo de permisos DENIEGA: el turno termina y la cola sigue | |
| 3 | +// (antes la promesa no se resolvía nunca y todo se quedaba colgado). | |
| 4 | +// · Dos peticiones a la vez van en cola: la segunda no pisa a la primera. | |
| 5 | +// · Un permiso pedido desde un Enter no se deniega con esa misma pulsación. | |
| 6 | +// · Los avisos se cierran, pueden llevar acción y se anuncian (región viva). | |
| 7 | +// | |
| 8 | +// BASE=http://localhost:8743 node tests/ux-dialogos.mjs | |
| 9 | +import { navegador, contexto, pagina, ok, hasta, espera, escribir, reposo, avisos, fin, OUT } from './ux-comun.mjs'; | |
| 10 | + | |
| 11 | +const b = await navegador(); | |
| 12 | +const { ctx } = await contexto(b, { grants: [] }); | |
| 13 | +const { p, errores } = await pagina(ctx); | |
| 14 | + | |
| 15 | +// ── 1 · Escape = Denegar, y el turno no se cuelga ─────────────────────────── | |
| 16 | +await escribir(p, 'hazme un reloj'); | |
| 17 | +ok('el modo básico pide permiso de Apps', await hasta(() => p.evaluate(() => document.getElementById('perm-dialog').open))); | |
| 18 | +if (OUT) await p.screenshot({ path: OUT + '/ux-permiso.png' }); | |
| 19 | +await p.keyboard.press('Escape'); | |
| 20 | +ok('Escape cierra el diálogo', await hasta(() => p.evaluate(() => !document.getElementById('perm-dialog').open))); | |
| 21 | +ok('…y cuenta como «Denegar» (la herramienta recibe el permiso denegado)', await hasta(async () => | |
| 22 | + /denegado por el usuario/.test(await p.locator('#log').innerText()))); | |
| 23 | +ok('el turno termina: el botón vuelve a ➤ y no queda la burbuja de «usando…»', await reposo(p)); | |
| 24 | +await escribir(p, 'hola'); | |
| 25 | +ok('lo siguiente que escribes se procesa (la cola no se ha quedado atascada)', await hasta(async () => | |
| 26 | + (await p.locator('#log .msg.assistant').allTextContents()).some(t => /modo básico/.test(t)))); | |
| 27 | +ok('no queda nada esperando en la cola', await p.locator('.msg.user.queued').count() === 0); | |
| 28 | + | |
| 29 | +// ── 2 · dos peticiones a la vez: en cola, una detrás de otra ──────────────── | |
| 30 | +await p.evaluate(() => { | |
| 31 | + window.__r = {}; | |
| 32 | + import('/js/permissions.js').then(pm => { | |
| 33 | + pm.require('web', 'primera').then(() => { window.__r.web = 'ok'; }, () => { window.__r.web = 'no'; }); | |
| 34 | + pm.require('tasks', 'segunda').then(() => { window.__r.tasks = 'ok'; }, () => { window.__r.tasks = 'no'; }); | |
| 35 | + }); | |
| 36 | +}); | |
| 37 | +ok('se abre la primera petición', await hasta(() => p.evaluate(() => | |
| 38 | + document.getElementById('perm-dialog').open && /Internet/.test(document.getElementById('perm-title').textContent)))); | |
| 39 | +await p.click('#perm-allow'); | |
| 40 | +ok('al contestarla, se abre la segunda (no se pisaron)', await hasta(() => p.evaluate(() => | |
| 41 | + document.getElementById('perm-dialog').open && /Tareas/.test(document.getElementById('perm-title').textContent)))); | |
| 42 | +await p.click('#perm-deny'); | |
| 43 | +ok('cada una recibe SU respuesta', await hasta(() => p.evaluate(() => window.__r.web === 'ok' && window.__r.tasks === 'no')), | |
| 44 | + JSON.stringify(await p.evaluate(() => window.__r))); | |
| 45 | + | |
| 46 | +// ── 3 · un Enter que pide permiso no lo deniega con la misma pulsación ────── | |
| 47 | +await p.evaluate(() => { | |
| 48 | + const i = document.createElement('input'); | |
| 49 | + i.id = 'campo-prueba'; | |
| 50 | + document.body.appendChild(i); | |
| 51 | + i.addEventListener('keydown', e => { | |
| 52 | + if (e.key !== 'Enter') return; | |
| 53 | + window.__mem = 'pendiente'; | |
| 54 | + import('/js/permissions.js').then(pm => pm.require('memory', 'desde un Enter') | |
| 55 | + .then(() => { window.__mem = 'concedido'; }, () => { window.__mem = 'denegado'; })); | |
| 56 | + }); | |
| 57 | + i.focus(); | |
| 58 | +}); | |
| 59 | +await p.keyboard.press('Enter'); | |
| 60 | +await espera(500); | |
| 61 | +ok('el diálogo sigue abierto tras el Enter que lo pidió', await p.evaluate(() => document.getElementById('perm-dialog').open && window.__mem === 'pendiente'), | |
| 62 | + await p.evaluate(() => window.__mem)); | |
| 63 | +ok('el foco está dentro del diálogo', await p.evaluate(() => document.getElementById('perm-dialog').contains(document.activeElement))); | |
| 64 | +await p.click('#perm-allow'); | |
| 65 | +ok('y contestar con el ratón lo concede', await hasta(() => p.evaluate(() => window.__mem === 'concedido'))); | |
| 66 | +ok('al cerrarse, el foco vuelve al campo de donde salió', await p.evaluate(() => document.activeElement?.id === 'campo-prueba')); | |
| 67 | + | |
| 68 | +// ── 4 · avisos: región viva, se cierran, llevan acción ────────────────────── | |
| 69 | +const vivo = await p.evaluate(() => ({ | |
| 70 | + toasts: document.getElementById('toasts').getAttribute('role'), | |
| 71 | + log: document.getElementById('log').getAttribute('role'), | |
| 72 | + dialogo: document.getElementById('perm-dialog').getAttribute('aria-labelledby'), | |
| 73 | +})); | |
| 74 | +ok('#toasts y #log son regiones vivas; el diálogo tiene título', vivo.toasts === 'status' && vivo.log === 'log' && vivo.dialogo === 'perm-title', JSON.stringify(vivo)); | |
| 75 | +await p.evaluate(async () => { | |
| 76 | + const ui = await import('/js/ui.js'); | |
| 77 | + window.__accion = 0; | |
| 78 | + ui.toast('aviso con acción', { accion: { label: 'Hazlo', run: () => { window.__accion++; } } }); | |
| 79 | + ui.toast('aviso para cerrar'); | |
| 80 | +}); | |
| 81 | +const conAccion = p.locator('#toasts .toast', { hasText: 'aviso con acción' }); | |
| 82 | +await conAccion.locator('.toast-accion').click(); | |
| 83 | +ok('la acción del aviso se ejecuta y el aviso se va', await p.evaluate(() => window.__accion) === 1 && await conAccion.count() === 0); | |
| 84 | +const paraCerrar = p.locator('#toasts .toast', { hasText: 'aviso para cerrar' }); | |
| 85 | +ok('el ✕ tiene nombre accesible', /Cerrar/.test(await paraCerrar.locator('.toast-x').getAttribute('aria-label'))); | |
| 86 | +await paraCerrar.locator('.toast-x').click(); | |
| 87 | +ok('✕ cierra el aviso', await paraCerrar.count() === 0); | |
| 88 | +await p.evaluate(async () => (await import('/js/ui.js')).toast('aviso con el ratón encima', { ms: 600 })); | |
| 89 | +await p.hover('#toasts .toast:last-child'); | |
| 90 | +await espera(1100); | |
| 91 | +ok('con el ratón encima, el aviso no se va', await p.locator('#toasts .toast', { hasText: 'aviso con el ratón encima' }).count() === 1); | |
| 92 | +await p.mouse.move(5, 5); | |
| 93 | +ok('y al quitarlo, sí', await hasta(async () => await p.locator('#toasts .toast', { hasText: 'aviso con el ratón encima' }).count() === 0)); | |
| 94 | + | |
| 95 | +ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); | |
| 96 | +await fin(b, 'DIÁLOGOS Y AVISOS: Escape deniega, la cola sigue, sin pisarse y sin denegar por un Enter'); |
modified web/css/elffuss.css +13 −0
| @@ -351,8 +351,21 @@ | ||
| 351 | 351 | max-width: 340px; |
| 352 | 352 | box-shadow: 0 8px 30px rgba(0, 0, 0, .5); |
| 353 | 353 | animation: slidein .2s ease-out; |
| 354 | + display: flex; align-items: flex-start; gap: 8px; | |
| 354 | 355 | } |
| 355 | 356 | @keyframes slidein { from { transform: translateX(20px); opacity: 0; } } |
| 357 | +.toast .toast-txt { flex: 1; min-width: 0; } | |
| 358 | +.toast .toast-accion { | |
| 359 | + flex: none; background: none; border: 1px solid var(--accent); color: var(--fg); | |
| 360 | + border-radius: 6px; padding: 2px 8px; font-size: .8rem; cursor: pointer; white-space: nowrap; | |
| 361 | +} | |
| 362 | +.toast .toast-accion:hover { background: color-mix(in srgb, var(--accent) 20%, transparent); } | |
| 363 | +.toast .toast-x { | |
| 364 | + flex: none; background: none; border: none; color: var(--muted); cursor: pointer; | |
| 365 | + font-size: .8rem; padding: 0 2px; line-height: 1.4; | |
| 366 | +} | |
| 367 | +.toast .toast-x:hover { color: var(--fg); } | |
| 368 | +@media (prefers-reduced-motion: reduce) { .toast { animation: none; } } | |
| 356 | 369 | #model-progress { |
| 357 | 370 | position: fixed; bottom: 18px; left: 18px; z-index: 50; |
| 358 | 371 | background: var(--bg3); border: 1px solid var(--line); border-radius: 10px; |
modified web/index.html +3 −3
| @@ -52,7 +52,7 @@ | ||
| 52 | 52 | |
| 53 | 53 | <main> |
| 54 | 54 | <section id="chat"> |
| 55 | - <div id="log"> | |
| 55 | + <div id="log" role="log" aria-live="polite" aria-relevant="additions"> | |
| 56 | 56 | <div class="msg sys"><img class="avatar" src="img/elffuss.svg" alt=""><b>Hola, soy Elffuss.</b> |
| 57 | 57 | Un sistema operativo con alma que vive en tu navegador. |
| 58 | 58 | Aquí las apps no se instalan: <i>se crean</i> cuando las pides y aparecen a la derecha. |
| @@ -105,7 +105,7 @@ | ||
| 105 | 105 | </section> |
| 106 | 106 | </main> |
| 107 | 107 | |
| 108 | -<dialog id="perm-dialog"> | |
| 108 | +<dialog id="perm-dialog" aria-labelledby="perm-title" aria-describedby="perm-desc perm-detail"> | |
| 109 | 109 | <h3 id="perm-title"></h3> |
| 110 | 110 | <p id="perm-desc"></p> |
| 111 | 111 | <p id="perm-detail" class="muted"></p> |
| @@ -116,7 +116,7 @@ | ||
| 116 | 116 | </dialog> |
| 117 | 117 | |
| 118 | 118 | <button id="btn-flip" title="cambiar entre chat y vista">Vista</button> |
| 119 | -<div id="toasts"></div> | |
| 119 | +<div id="toasts" role="status" aria-live="polite" aria-relevant="additions"></div> | |
| 120 | 120 | <div id="model-progress" hidden> |
| 121 | 121 | <div class="track"><div id="model-bar"></div></div> |
| 122 | 122 | <span id="model-progress-text"></span> |
modified web/js/i18n.js +4 −0
| @@ -99,6 +99,8 @@ | ||
| 99 | 99 | useNoRam: "no medible en este navegador", |
| 100 | 100 | extTitle: "Modelos externos (avanzado)", |
| 101 | 101 | extDesc: "Elffuss corre en TU máquina y nada sale de ella. Estas opciones son la excepción: mandan tus mensajes a un servidor de fuera. Solo si tú lo activas a mano. Las claves se guardan en este navegador y las llamadas van directas al proveedor.", |
| 102 | + // ── arreglos de UX (ronda 20261010) ── | |
| 103 | + close: 'Cerrar', undo: 'Deshacer', | |
| 102 | 104 | }, |
| 103 | 105 | en: { |
| 104 | 106 | welcome: 'An operating system with a soul that lives in your browser. Here apps aren’t installed: they’re created when you ask, appearing on the right. I can use your folders (with permission), store encrypted secrets, schedule tasks and browse for you. Everything stays on your machine.', |
| @@ -194,6 +196,8 @@ | ||
| 194 | 196 | useNoRam: "not measurable in this browser", |
| 195 | 197 | extTitle: "External models (advanced)", |
| 196 | 198 | extDesc: "Elffuss runs on YOUR machine and nothing leaves it. These options are the exception: they send your messages to an outside server. Only if you turn them on yourself. Keys stay in this browser and calls go straight to the provider.", |
| 199 | + // ── UX fixes (round 20261010) ── | |
| 200 | + close: 'Close', undo: 'Undo', | |
| 197 | 201 | }, |
| 198 | 202 | uk: { |
| 199 | 203 | welcome: "Операційна система з душею, що живе у твоєму браузері. Тут застосунки не встановлюють — їх створюють на твій запит, і вони з’являються праворуч. Можу працювати з твоїми теками (за дозволом), зберігати зашифровані секрети, планувати завдання й гортати за тебе. Усе лишається на твоєму пристрої.", |
modified web/js/ui.js +95 −26
| @@ -88,6 +88,11 @@ | ||
| 88 | 88 | const gen = document.createElement('div'); |
| 89 | 89 | gen.className = 'gen'; |
| 90 | 90 | div.append(img, label, dots, gen); |
| 91 | + // #log es una región viva (role=log en index.html). La burbuja se oculta a los | |
| 92 | + // lectores de pantalla: cambia de texto con cada token y se leería sin parar. | |
| 93 | + // Mientras trabaja, el log queda «ocupado» y lo que llegue se anuncia al final. | |
| 94 | + div.setAttribute('aria-hidden', 'true'); | |
| 95 | + $('log').setAttribute('aria-busy', 'true'); | |
| 91 | 96 | $('log').appendChild(div); |
| 92 | 97 | $('log').scrollTop = $('log').scrollHeight; |
| 93 | 98 | // Barra del PREFILL. El prefill es la espera larga —leer el prompt antes de |
| @@ -152,7 +157,7 @@ | ||
| 152 | 157 | // Lo que llegó a escribir, si era texto para el usuario (no una herramienta |
| 153 | 158 | // a medias, que se enseña como «creando app…»): lo que se conserva al parar. |
| 154 | 159 | partial() { return humanizeStreamPreview(buf) ? '' : buf.trim(); }, |
| 155 | - remove() { div.remove(); }, | |
| 160 | + remove() { div.remove(); if (!document.querySelector('#log .msg.thinking')) $('log').removeAttribute('aria-busy'); }, | |
| 156 | 161 | }; |
| 157 | 162 | } |
| 158 | 163 | |
| @@ -187,49 +192,113 @@ | ||
| 187 | 192 | for (const el of [...$('log').children]) if (!el.classList.contains('sys')) el.remove(); |
| 188 | 193 | } |
| 189 | 194 | |
| 190 | -export function toast(text, ms = 4500) { | |
| 195 | +// Avisos. Antes se iban a los 4,5 s pasara lo que pasara: uno de 184 caracteres | |
| 196 | +// (el de Hard Work) no daba tiempo a leerlo, no había forma de quitarlos ni de | |
| 197 | +// pararlos, y ninguno llevaba a ningún sitio. Ahora: | |
| 198 | +// · duran según lo que hay que leer, y se paran con el ratón o el foco encima; | |
| 199 | +// · se cierran con ✕; | |
| 200 | +// · pueden llevar UNA acción («Deshacer», «Ver tarea», «Elegir ahora»…); | |
| 201 | +// · #toasts es una región viva (index.html): un lector de pantalla los anuncia. | |
| 202 | +// `opts` admite un número (ms), como antes, o { ms, accion: { label, run } }. | |
| 203 | +export function toast(text, opts = {}) { | |
| 204 | + if (typeof opts === 'number') opts = { ms: opts }; | |
| 205 | + const { accion = null, ms = null } = opts || {}; | |
| 191 | 206 | const t = document.createElement('div'); |
| 192 | 207 | t.className = 'toast'; |
| 193 | - t.textContent = text; | |
| 208 | + const txt = document.createElement('span'); | |
| 209 | + txt.className = 'toast-txt'; | |
| 210 | + txt.textContent = text; | |
| 211 | + t.appendChild(txt); | |
| 212 | + let timer = null, restante = 0, desde = 0, parado = false; | |
| 213 | + const quitar = () => { clearTimeout(timer); t.remove(); }; | |
| 214 | + if (accion?.label && typeof accion.run === 'function') { | |
| 215 | + const b = document.createElement('button'); | |
| 216 | + b.type = 'button'; | |
| 217 | + b.className = 'toast-accion'; | |
| 218 | + b.textContent = accion.label; | |
| 219 | + b.onclick = () => { quitar(); try { accion.run(); } catch (e) { console.warn('[elffuss] acción del aviso:', e); } }; | |
| 220 | + t.appendChild(b); | |
| 221 | + } | |
| 222 | + const x = document.createElement('button'); | |
| 223 | + x.type = 'button'; | |
| 224 | + x.className = 'toast-x'; | |
| 225 | + x.textContent = '✕'; | |
| 226 | + x.title = tr('close'); | |
| 227 | + x.setAttribute('aria-label', tr('close')); | |
| 228 | + x.onclick = quitar; | |
| 229 | + t.appendChild(x); | |
| 194 | 230 | $('toasts').appendChild(t); |
| 195 | - setTimeout(() => t.remove(), ms); | |
| 231 | + // ~50 ms por carácter, entre 4 y 12 s; con acción, unos segundos más para | |
| 232 | + // que dé tiempo a decidir. | |
| 233 | + restante = ms ?? (Math.min(12000, Math.max(4000, 1500 + String(text).length * 50)) + (accion ? 4000 : 0)); | |
| 234 | + const arrancar = () => { desde = Date.now(); clearTimeout(timer); timer = setTimeout(quitar, restante); }; | |
| 235 | + const pausar = () => { if (parado) return; parado = true; clearTimeout(timer); restante = Math.max(1500, restante - (Date.now() - desde)); }; | |
| 236 | + const seguir = () => { if (!parado || t.matches(':hover') || t.contains(document.activeElement)) return; parado = false; arrancar(); }; | |
| 237 | + t.addEventListener('mouseenter', pausar); | |
| 238 | + t.addEventListener('mouseleave', seguir); | |
| 239 | + t.addEventListener('focusin', pausar); | |
| 240 | + t.addEventListener('focusout', () => setTimeout(seguir, 0)); | |
| 241 | + arrancar(); | |
| 242 | + return t; | |
| 196 | 243 | } |
| 197 | 244 | |
| 198 | 245 | // ---------- modal de permisos ---------- |
| 199 | -// Contesta SIEMPRE, también si el diálogo se cierra sin pulsar nada (Escape): | |
| 200 | -// cerrar es «no». Antes Escape lo cerraba sin contestar, y la herramienta que | |
| 201 | -// lo pidió esperaba para siempre —y con ella el turno, la cola de detrás y el | |
| 202 | -// cerebro CEO, que no arrancaba otro ciclo—. | |
| 203 | -// Las peticiones llegan de una en una (permissions.js las pone en fila). Si | |
| 204 | -// aun así entrara otra con el diálogo abierto, la que se estaba enseñando se | |
| 205 | -// da por denegada en vez de quedarse sin respuesta: los botones son unos. | |
| 206 | -let permEnCurso = null; // done() de la petición que enseña el diálogo | |
| 246 | +// Tres cosas que fallaban, las tres con el teclado: | |
| 247 | +// · Escape cerraba el diálogo SIN contestar: la promesa no se resolvía nunca, | |
| 248 | +// el turno se quedaba colgado en «Elffuss está usando…» y todo lo que | |
| 249 | +// escribieras después esperaba en la cola hasta recargar —y con ella el | |
| 250 | +// cerebro CEO, que no arrancaba otro ciclo—. Ahora Escape (y cualquier otro | |
| 251 | +// cierre) es «Denegar». | |
| 252 | +// · Dos peticiones a la vez se pisaban los botones: la segunda reasignaba los | |
| 253 | +// onclick de la primera, que ya no se podía contestar. Ahora van en cola, | |
| 254 | +// una detrás de otra (permissions.js ya las pone en fila por ámbito; esta | |
| 255 | +// cola cubre además a quien llame aquí directamente). | |
| 256 | +// · Si la petición nacía de un Enter (p. ej. en la contraseña de la Bóveda), | |
| 257 | +// el diálogo se abría DENTRO de ese mismo evento, el foco caía en «Denegar» | |
| 258 | +// y la misma pulsación lo activaba: denegado sin haberlo visto. Ahora se | |
| 259 | +// abre en la tarea siguiente, cuando esa tecla ya ha terminado. | |
| 260 | +let colaPermisos = Promise.resolve(); | |
| 207 | 261 | export function askPermission(scope, meta, detail) { |
| 262 | + const turno = colaPermisos.then(() => mostrarPermiso(scope, meta, detail)); | |
| 263 | + colaPermisos = turno.catch(() => {}); | |
| 264 | + return turno; | |
| 265 | +} | |
| 266 | + | |
| 267 | +function mostrarPermiso(scope, meta, detail) { | |
| 208 | 268 | return new Promise(resolve => { |
| 209 | 269 | const dlg = $('perm-dialog'); |
| 210 | - permEnCurso?.(false); | |
| 211 | - let contestada = false; | |
| 270 | + $('perm-title').textContent = `${meta?.icon || '❓'} ${tr('permWord')}: ${meta?.label || scope}`; | |
| 271 | + $('perm-desc').textContent = meta?.desc || ''; | |
| 272 | + $('perm-detail').textContent = detail || ''; | |
| 273 | + const previo = document.activeElement; | |
| 274 | + let hecho = false, mostrado = false; | |
| 212 | 275 | const done = ok => { |
| 213 | - if (contestada) return; | |
| 214 | - contestada = true; | |
| 215 | - if (permEnCurso === done) permEnCurso = null; | |
| 276 | + if (hecho) return; | |
| 277 | + hecho = true; | |
| 278 | + $('perm-allow').onclick = null; | |
| 279 | + $('perm-deny').onclick = null; | |
| 280 | + dlg.removeEventListener('cancel', alCancelar); | |
| 216 | 281 | dlg.removeEventListener('close', alCerrar); |
| 217 | 282 | if (dlg.open) dlg.close(); |
| 218 | 283 | refreshPerms(); |
| 284 | + if (previo && previo !== document.body && document.contains(previo)) { | |
| 285 | + try { previo.focus({ preventScroll: true }); } catch { /* — */ } | |
| 286 | + } | |
| 219 | 287 | resolve(ok); |
| 220 | 288 | }; |
| 221 | - // El evento «close» llega DESPUÉS de cerrarse, ya en otra tarea: si para | |
| 222 | - // entonces el diálogo vuelve a estar abierto, es el cierre de la petición | |
| 223 | - // anterior y no va con esta. | |
| 224 | - const alCerrar = () => { if (!dlg.open) done(false); }; | |
| 225 | - permEnCurso = done; | |
| 226 | - $('perm-title').textContent = `${meta?.icon || '❓'} ${tr('permWord')}: ${meta?.label || scope}`; | |
| 227 | - $('perm-desc').textContent = meta?.desc || ''; | |
| 228 | - $('perm-detail').textContent = detail || ''; | |
| 289 | + const alCancelar = e => { e.preventDefault(); done(false); }; // Escape = Denegar | |
| 290 | + // Cualquier otro cierre, también. Pero solo el de ESTE diálogo: el evento | |
| 291 | + // «close» de la petición anterior llega en una tarea aparte, cuando esta ya | |
| 292 | + // ha empezado a escuchar, y sin la guarda la denegaba antes de enseñarla. | |
| 293 | + const alCerrar = () => { if (mostrado && !dlg.open) done(false); }; | |
| 229 | 294 | $('perm-allow').onclick = () => done(true); |
| 230 | 295 | $('perm-deny').onclick = () => done(false); |
| 296 | + dlg.addEventListener('cancel', alCancelar); | |
| 231 | 297 | dlg.addEventListener('close', alCerrar); |
| 232 | - if (!dlg.open) dlg.showModal(); | |
| 298 | + setTimeout(() => { | |
| 299 | + if (hecho) return; | |
| 300 | + try { dlg.showModal(); mostrado = true; } catch { done(false); } | |
| 301 | + }, 0); | |
| 233 | 302 | }); |
| 234 | 303 | } |
| 235 | 304 |