| 1 | // Teclado, menú de comandos y chips. |
| 2 | // · «/» (botón): menú de verdad (aria-haspopup/expanded, role=menu), el foco |
| 3 | // entra, ↑/↓ se mueven, Escape cierra y devuelve el foco. |
| 4 | // · Escribiendo «/sk» filtra, Enter ejecuta el marcado y la caja queda limpia y |
| 5 | // con el foco; un «/» suelto no se manda nunca; /modelo lleva al selector. |
| 6 | // · Escribiendo, la caja es un combobox (aria-controls, aria-expanded) y el |
| 7 | // menú una lista con su opción marcada (aria-selected), que la caja señala |
| 8 | // con aria-activedescendant; con el botón, el menú es un role=menu. |
| 9 | // · En inglés los comandos se llaman en inglés (/settings, /tasks, /clear…) y |
| 10 | // los nombres en español siguen valiendo; si ningún nombre empieza así, se |
| 11 | // busca en lo que hace cada uno. |
| 12 | // · «?» fuera de la caja enseña los atajos; «/» fuera de la caja abre el menú. |
| 13 | // · Chips: botones, seis, sin repetidos, en el idioma de la página; «Autoriza |
| 14 | // una carpeta» abre el selector en el propio clic. En modo Básico, en inglés, |
| 15 | // francés y alemán cada chip hace lo que dice (antes casi todos caían en el |
| 16 | // texto de ayuda: el modo Básico entiende órdenes en español). |
| 17 | // |
| 18 | // BASE=http://localhost:8743 node tests/ux-teclado.mjs |
| 19 | import { navegador, contexto, pagina, ok, hasta, espera, fin } from './ux-comun.mjs'; |
| 20 | |
| 21 | const b = await navegador(); |
| 22 | const { ctx } = await contexto(b, { grants: ['fs', 'apps'] }); |
| 23 | await ctx.addInitScript(() => { |
| 24 | window.__picker = 0; |
| 25 | window.showDirectoryPicker = async () => { |
| 26 | window.__picker++; |
| 27 | const r = await navigator.storage.getDirectory(); |
| 28 | return r.getDirectoryHandle('mi-carpeta', { create: true }); |
| 29 | }; |
| 30 | }); |
| 31 | const { p, errores } = await pagina(ctx); |
| 32 | const menuAbierto = () => p.evaluate(() => !document.getElementById('cmd-menu').hidden); |
| 33 | const foco = () => p.evaluate(() => document.activeElement?.id || document.activeElement?.className || document.activeElement?.tagName); |
| 34 | |
| 35 | // ── el botón «/» ──────────────────────────────────────────────────────────── |
| 36 | const slash = p.locator('#btn-slash'); |
| 37 | ok('el botón «/» anuncia un menú y tiene nombre', await slash.getAttribute('aria-haspopup') === 'menu' |
| 38 | && await slash.getAttribute('aria-expanded') === 'false' && await slash.getAttribute('aria-label') === 'Comandos y skills'); |
| 39 | await slash.click(); |
| 40 | ok('al abrirlo: aria-expanded, role=menu y el foco en la primera opción', await menuAbierto() && await slash.getAttribute('aria-expanded') === 'true' |
| 41 | && await p.evaluate(() => document.getElementById('cmd-menu').getAttribute('role') === 'menu' && document.activeElement?.getAttribute('role') === 'menuitem' |
| 42 | && document.activeElement.textContent.startsWith('/reloj'))); |
| 43 | await p.keyboard.press('ArrowDown'); |
| 44 | ok('↓ pasa a la siguiente opción', await p.evaluate(() => document.activeElement?.textContent.startsWith('/carpeta'))); |
| 45 | await p.keyboard.press('Escape'); |
| 46 | ok('Escape cierra el menú y devuelve el foco al botón', !(await menuAbierto()) && await foco() === 'btn-slash'); |
| 47 | ok('…abierto con el botón, la caja de texto no se da por desplegada', await p.getAttribute('#prompt', 'aria-expanded') === 'false'); |
| 48 | |
| 49 | // ── escribiendo «/» ───────────────────────────────────────────────────────── |
| 50 | await p.focus('#prompt'); |
| 51 | const aria = () => p.evaluate(() => { |
| 52 | const c = document.getElementById('prompt'), m = document.getElementById('cmd-menu'); |
| 53 | const ad = c.getAttribute('aria-activedescendant'); |
| 54 | const sel = ad ? document.getElementById(ad) : null; |
| 55 | return { role: c.getAttribute('role'), expanded: c.getAttribute('aria-expanded'), controls: c.getAttribute('aria-controls'), |
| 56 | autocomplete: c.getAttribute('aria-autocomplete'), menu: m.getAttribute('role'), ad, |
| 57 | dentro: !!sel && m.contains(sel), opcion: sel?.getAttribute('role'), elegida: sel?.getAttribute('aria-selected'), |
| 58 | otras: [...m.querySelectorAll('[role=option]')].filter(o => o !== sel && o.getAttribute('aria-selected') !== 'false').length, |
| 59 | texto: sel?.querySelector('b')?.textContent }; |
| 60 | }); |
| 61 | ok('en reposo la caja es un combobox plegado que controla el menú', await aria().then(a => a.role === 'combobox' && a.expanded === 'false' |
| 62 | && a.controls === 'cmd-menu' && a.autocomplete === 'list' && !a.ad)); |
| 63 | await p.keyboard.type('/'); |
| 64 | const a1 = await aria(); |
| 65 | ok('escribiendo «/»: la caja se despliega y señala una opción de la lista (listbox/option, aria-selected)', a1.expanded === 'true' |
| 66 | && a1.menu === 'listbox' && a1.dentro && a1.opcion === 'option' && a1.elegida === 'true' && a1.otras === 0 && a1.texto === '/reloj', JSON.stringify(a1)); |
| 67 | await p.keyboard.press('ArrowDown'); |
| 68 | const a2 = await aria(); |
| 69 | ok('…↓ mueve la opción señalada y su aria-selected', a2.texto === '/carpeta' && a2.elegida === 'true' && a2.otras === 0 && a2.ad !== a1.ad, JSON.stringify(a2)); |
| 70 | await p.keyboard.press('Escape'); |
| 71 | ok('…y Escape la pliega (sin opción señalada)', await aria().then(a => a.expanded === 'false' && !a.ad), JSON.stringify(await aria())); |
| 72 | await p.fill('#prompt', ''); |
| 73 | await p.keyboard.type('/sk'); |
| 74 | ok('«/sk» filtra: solo /skills', await hasta(async () => (await p.locator('#cmd-menu .cmd-item b').allTextContents()).join(',') === '/skills')); |
| 75 | await p.keyboard.press('Enter'); |
| 76 | ok('Enter ejecuta el comando marcado (abre Skills)', await hasta(() => p.evaluate(() => document.getElementById('panel-skills').classList.contains('active')))); |
| 77 | ok('…la caja queda vacía y con el foco, y no se mandó «/sk» al modelo', await p.inputValue('#prompt') === '' && await foco() === 'prompt' |
| 78 | && await p.locator('#log .msg.user').count() === 0); |
| 79 | await p.keyboard.type('/'); |
| 80 | await p.keyboard.press('Escape'); |
| 81 | ok('Escape con «/» escrito cierra el menú', !(await menuAbierto())); |
| 82 | await p.keyboard.press('Enter'); |
| 83 | await espera(300); |
| 84 | ok('un «/» suelto con Enter no se manda nunca', await p.locator('#log .msg.user').count() === 0); |
| 85 | await p.fill('#prompt', ''); |
| 86 | await p.keyboard.type('/mod'); |
| 87 | await p.keyboard.press('Enter'); |
| 88 | ok('/modelo lleva al selector de modelo', await hasta(async () => await foco() === 'model-select')); |
| 89 | |
| 90 | // ── atajos fuera de la caja ───────────────────────────────────────────────── |
| 91 | await p.click('#tabs button[data-tab="vista"]'); |
| 92 | await p.keyboard.press('?'); |
| 93 | ok('«?» fuera de la caja enseña los atajos', await hasta(() => p.evaluate(() => document.getElementById('atajos')?.open))); |
| 94 | await p.keyboard.press('Escape'); |
| 95 | ok('…y Escape los cierra', await hasta(() => p.evaluate(() => !document.getElementById('atajos').open))); |
| 96 | await p.click('#tabs button[data-tab="vista"]'); |
| 97 | await p.keyboard.press('/'); |
| 98 | ok('«/» fuera de la caja va a la caja con el menú abierto', await hasta(async () => await foco() === 'prompt' && await menuAbierto())); |
| 99 | await p.keyboard.press('Escape'); |
| 100 | await p.fill('#prompt', ''); |
| 101 | |
| 102 | // ── chips ─────────────────────────────────────────────────────────────────── |
| 103 | const chips = await p.$$eval('#chips .chip', cs => cs.map(c => ({ tag: c.tagName, t: c.textContent, a: c.dataset.accion || '' }))); |
| 104 | ok('seis chips, botones, sin repetidos', chips.length === 6 && chips.every(c => c.tag === 'BUTTON') && new Set(chips.map(c => c.t)).size === 6, JSON.stringify(chips)); |
| 105 | ok('…incluidas las de skill e imágenes', chips.some(c => /skill/.test(c.t)) && chips.some(c => /auroras/.test(c.t))); |
| 106 | await p.locator('#chips .chip[data-accion="carpeta"]').click(); |
| 107 | ok('«Autoriza una carpeta» abre el selector en el propio clic (sin esperar al modelo)', await hasta(() => p.evaluate(() => window.__picker === 1))); |
| 108 | ok('…y la carpeta queda autorizada y dicha en el chat', await hasta(async () => /Carpeta «mi-carpeta» autorizada/.test(await p.locator('#log').innerText()))); |
| 109 | await p.locator('#chips .chip', { hasText: 'Hazme un reloj' }).click(); |
| 110 | ok('un chip normal se manda como mensaje', await hasta(async () => /Hazme un reloj/.test(await p.locator('#log .msg.user').allInnerTexts().then(a => a.join(' '))))); |
| 111 | { |
| 112 | const { ctx: c2 } = await contexto(b, { locale: 'en-US' }); |
| 113 | const { p: e } = await pagina(c2); |
| 114 | const en = await e.$$eval('#chips .chip', cs => cs.map(c => c.textContent)); |
| 115 | const es = ['Hazme un reloj', 'Crea una app de notas', 'Autoriza una carpeta', 'Créame una skill para organizar mis descargas', 'Busca fotos de auroras boreales', 'Abre https://example.com']; |
| 116 | ok('en inglés: seis chips en inglés', en.length === 6 && !en.some(t => es.includes(t)) && en[0] === 'Make me a clock', JSON.stringify(en)); |
| 117 | ok('en inglés el botón «/» se llama «Commands and skills»', await e.getAttribute('#btn-slash', 'aria-label') === 'Commands and skills'); |
| 118 | const busca = async q => { |
| 119 | await e.fill('#prompt', ''); |
| 120 | await e.focus('#prompt'); |
| 121 | await e.keyboard.type(q); |
| 122 | await espera(100); |
| 123 | const r = await e.$$eval('#cmd-menu .cmd-item b', bs => bs.map(x => x.textContent)); |
| 124 | await e.keyboard.press('Escape'); |
| 125 | return r; |
| 126 | }; |
| 127 | const r = { settings: await busca('/settings'), tasks: await busca('/tasks'), clear: await busca('/clear'), ajustes: await busca('/ajustes'), |
| 128 | todos: await busca('/'), teclado: await busca('/keyb') }; |
| 129 | ok('en inglés los comandos se llaman en inglés y /settings, /tasks y /clear los encuentran', r.settings.join() === '/settings' |
| 130 | && r.tasks.join() === '/tasks' && r.clear.join() === '/clear' && r.todos.includes('/clock') && !r.todos.includes('/reloj'), JSON.stringify(r)); |
| 131 | ok('…el nombre en español sigue valiendo (/ajustes → /settings)', r.ajustes.join() === '/settings', JSON.stringify(r.ajustes)); |
| 132 | ok('…y si ningún nombre empieza así, busca en lo que hace cada uno (/keyb → /shortcuts)', r.teclado.join() === '/shortcuts', JSON.stringify(r.teclado)); |
| 133 | await e.fill('#prompt', ''); |
| 134 | await e.focus('#prompt'); |
| 135 | await e.keyboard.type('/settings'); |
| 136 | await e.keyboard.press('Enter'); |
| 137 | ok('…y Enter en /settings abre Settings', await hasta(() => e.evaluate(() => document.getElementById('panel-ajustes').classList.contains('active')))); |
| 138 | await c2.close(); |
| 139 | } |
| 140 | |
| 141 | // ── chips en modo Básico, en otros idiomas ─────────────────────────────────── |
| 142 | // La red se corta: example.com contesta aquí y el proxy del servidor no se usa. |
| 143 | const ESPERADO = [/app\.create \(name=reloj/, /app\.create \(name=notas/, null, /skill\.create/, /web\.images/, /web\.fetch \(url=https:\/\/example\.com/]; |
| 144 | for (const locale of ['en-US', 'fr-FR', 'de-DE']) { |
| 145 | const { ctx: c3 } = await contexto(b, { locale, grants: ['apps', 'web', 'fs', 'memory', 'tasks', 'vault'], |
| 146 | rutas: async (url, route) => { |
| 147 | if (!/^https:\/\/example\.com\//.test(url)) return false; |
| 148 | await route.fulfill({ status: 200, contentType: 'text/html', body: '<h1>Example</h1>' }); return true; |
| 149 | } }); |
| 150 | const { p: q, errores: err3 } = await pagina(c3); |
| 151 | await q.route('**/proxy?url=**', r => r.fulfill({ status: 502, body: 'sin red en la prueba' })); |
| 152 | const textos = await q.$$eval('#chips .chip', cs => cs.map(c => c.textContent.trim())); |
| 153 | const malos = []; |
| 154 | for (let i = 0; i < textos.length; i++) { |
| 155 | if (!ESPERADO[i]) continue; // «Autoriza una carpeta» abre el selector |
| 156 | const antes = await q.locator('#log .msg').count(); |
| 157 | await q.locator('#chips .chip').nth(i).click(); |
| 158 | await hasta(() => q.evaluate(n => document.querySelectorAll('#log .msg').length > n + 1 |
| 159 | && !document.querySelector('#log .msg.thinking') && !document.getElementById('send').classList.contains('is-stop'), antes)); |
| 160 | const nuevos = await q.evaluate(n => [...document.querySelectorAll('#log .msg')].slice(n).map(m => m.className + ' | ' + m.textContent.trim().slice(0, 90)), antes); |
| 161 | const ayuda = nuevos.some(x => /Basic mode|mode Basique|Basismodus|modo básico/i.test(x)); |
| 162 | if (ayuda || !nuevos.some(x => /\btool\b/.test(x.split(' | ')[0]) && ESPERADO[i].test(x))) malos.push({ chip: textos[i], nuevos: nuevos.slice(0, 3) }); |
| 163 | } |
| 164 | ok(`${locale}: en modo Básico cada chip hace lo que dice (ninguno cae en el texto de ayuda)`, !malos.length, JSON.stringify(malos).slice(0, 400)); |
| 165 | ok(`${locale}: …sin errores de página`, err3.length === 0, err3.slice(0, 3).join(' | ')); |
| 166 | await c3.close(); |
| 167 | } |
| 168 | |
| 169 | ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); |
| 170 | await fin(b, 'TECLADO: menú «/» navegable y filtrable, atajos, chips que son botones'); |