Elffuss BraidHub

utopia-ia/elffuss-code public

Keyboard, Escape and working menus across the IDE

- Escape closes the topmost layer, one per press, and returns focus to
  what opened it: the composer menu, the File/Edit/View/Git menus, Modes,
  History, Settings and the Architecture/City view (the editor and the
  terminal keep their own Escape). Before, only the palette, the Mind and
  the @ menu reacted.
- The menubar follows the menubar/menu pattern: ↓/Enter/Space open a menu
  with focus on its first item, ←/→ move between menus, ↑/↓/Home/End move
  inside, Escape returns to the menubar button, Tab leaves. Its labels
  follow the interface language (Archivo/Editar/Ver/Git).
- Git menu: "Rama" opens the branch on the remote and "Último" shows the
  short SHA and opens that commit (no credentials, no e-mail); without a
  remote they are shown disabled instead of looking clickable and doing
  nothing. "Pídele a Elffuss que commitee" becomes "Redactar el mensaje de
  commit", which is what the agent can do.
- History and Settings are dialogs: focus moves in on open and back on
  close; History rows are buttons with the active conversation marked
  (aria-current) and a named delete button.
- Conversation tabs are a tablist (roving focus, ←/→ switch, Delete
  closes, Shift+F10 or right click opens Rename / Close / Close others),
  the × is a labelled button, and a busy tab says so in its name.
  conversations.rename() stores a custom title.
- Modes: the Modes button shows what is on (Revisar, 🎯, ⛏) and says it in
  its label; toggles are menuitemcheckbox with aria-checked and no longer
  close the menu; the prompt placeholder warns in Goal mode.
- Palette: a "#" mode searches inside the files with code.search and lists
  file:line results that open at that line; Edit › Search the code and the
  palette command use it (they only prefilled "busca " in the chat), and
  the activity-bar search button opens the palette, as its title says. The
  input is a combobox over a listbox with aria-activedescendant. Clicks on
  menu items no longer bubble to the outside-click handlers, which closed
  the palette in the same click that opened it.
- The context meter no longer points to a 🧹 button that does not exist,
  "/clear" (which opened a new conversation) is "/new", the + and / menus
  take focus with arrow keys inside, ↑/↓ in a multi-line draft move the
  caret instead of replacing it with history, and the terminal splitter is
  a focusable separator resized with ↑/↓.

tests/keyboard-ux.mjs (?test-opfs, seeded project and .git with a remote
carrying credentials): every point above. Against the previous code it
fails from the first check.
Changeset3a61a03117fab74d6774bb899b2816113af430ee1f1d33ad38c16bb125ce73d9
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 16:38 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:15 +02:00
Parents21d6a5c0c099

Browse the files at this changeset

5 files changed

added tests/keyboard-ux.mjs +193 −0
@@ -0,0 +1,193 @@
1+// Teclado, Escape, menús y búsqueda: lo que antes solo iba con ratón o no iba.
2+//
3+// 1. Escape cierra la capa de arriba (menú de la barra, Modos, Historial,
4+// Ajustes, vista 3D) y el foco vuelve a quien la abrió.
5+// 2. Barra de menús con teclado (↓ abre, →/← cambian de menú) y en el idioma
6+// de la interfaz.
7+// 3. Git: «Último» enseña el SHA corto y enlaza el commit en el remoto (sin
8+// credenciales); la rama enlaza su árbol; `git log` del terminal da el SHA.
9+// 4. Historial: filas que son botones, la activa marcada.
10+// 5. Pestañas de conversación: ←/→ cambian, Supr cierra, el menú renombra.
11+// 6. Modos: el botón dice qué está encendido, el menú no se cierra al tocar un
12+// modo, y el texto del prompt avisa en modo Objetivo.
13+// 7. Paleta «#»: Edit › Buscar en el código busca DENTRO de los ficheros y
14+// abre el resultado en su línea; la lupa de la barra abre la paleta.
15+// 8. Detalles: el medidor de contexto no promete un 🧹 que no existe, ↑ en
16+// un borrador de varias líneas no lo pisa con el historial, «/new» en vez
17+// de «/clear», y el terminal se redimensiona con ↑/↓.
18+//
19+// BASE=http://127.0.0.1:8898 node tests/keyboard-ux.mjs
20+import { chromium } from 'playwright';
21+const BASE = process.env.BASE || 'http://localhost:8799';
22+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
23+
24+const b = await chromium.launch();
25+const ctx = await b.newContext({ locale: 'es-ES' });
26+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
27+const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } });
28+const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
29+
30+const SHA = '3f9c2a17b04e5d6c8a9b0c1d2e3f405162738495';
31+await p.goto(BASE + '/manifest.json');
32+await p.evaluate(async (SHA) => {
33+ const root = await navigator.storage.getDirectory();
34+ const escribe = async (path, txt) => {
35+ const parts = path.split('/'); const name = parts.pop(); let d = root;
36+ for (const x of parts) d = await d.getDirectoryHandle(x, { create: true });
37+ const w = await (await d.getFileHandle(name, { create: true })).createWritable(); await w.write(txt); await w.close();
38+ };
39+ await escribe('src/app.js', 'export const a = 1;\n// aquí está la palabraSecretaDePrueba\nexport const b = 2;\n');
40+ await escribe('README.md', '# Demo\n');
41+ await escribe('.git/HEAD', 'ref: refs/heads/main\n');
42+ await escribe('.git/logs/HEAD', `0000000000000000000000000000000000000000 ${SHA} Ana Prueba <ana@example.com> 1760000000 +0200\tcommit: arregla el login\n`);
43+ await escribe('.git/config', '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://usuario:token123@github.com/demo-org/demo-repo.git\n');
44+}, SHA);
45+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
46+await p.waitForFunction(() => window.monaco && document.querySelector('#tree [data-path]') && window.elffussClaw?.conv?.getActive?.(), null, { timeout: 30000 });
47+await p.evaluate(() => { window.__abiertas = []; window.open = (u) => { window.__abiertas.push(String(u)); return null; }; });
48+const foco = () => p.evaluate(() => document.activeElement?.id || document.activeElement?.className || document.activeElement?.tagName);
49+
50+// 2 · barra de menús
51+const nombres = await p.evaluate(() => [...document.querySelectorAll('#menubar button')].map(b => b.textContent));
52+ok('2 · la barra de menús habla el idioma de la interfaz', JSON.stringify(nombres) === '["Archivo","Editar","Ver","Git"]', JSON.stringify(nombres));
53+await p.locator('#menubar button[data-menu="file"]').focus();
54+await p.keyboard.press('ArrowDown');
55+await p.waitForTimeout(150);
56+const enMenu = await p.evaluate(() => ({ abierto: !document.getElementById('topmenu').hidden, dentro: document.getElementById('topmenu').contains(document.activeElement), expanded: document.querySelector('#menubar button[data-menu="file"]').getAttribute('aria-expanded') }));
57+ok('2 · ↓ en «Archivo» abre el menú con el foco en su primera opción', enMenu.abierto && enMenu.dentro && enMenu.expanded === 'true', JSON.stringify(enMenu));
58+await p.keyboard.press('ArrowRight');
59+await p.waitForTimeout(150);
60+const editar = await p.evaluate(() => document.querySelector('#menubar button.open')?.dataset.menu);
61+ok('2 · → pasa al menú «Editar»', editar === 'edit', editar);
62+await p.keyboard.press('Escape');
63+await p.waitForTimeout(100);
64+const trasEsc = await p.evaluate(() => ({ cerrado: document.getElementById('topmenu').hidden, foco: document.activeElement?.dataset?.menu }));
65+ok('1 · Escape cierra el menú y devuelve el foco a «Editar»', trasEsc.cerrado && trasEsc.foco === 'edit', JSON.stringify(trasEsc));
66+
67+// 3 · Git
68+await p.click('#menubar button[data-menu="git"]');
69+await p.waitForTimeout(250);
70+const git = await p.evaluate(() => [...document.querySelectorAll('#topmenu .menu-item')].map(r => ({ txt: r.textContent, title: r.title, off: r.getAttribute('aria-disabled') })));
71+const ultimo = git.find(g => /Último/.test(g.txt));
72+ok('3 · «Último» enseña el SHA corto', /3f9c2a1 · commit: arregla el login/.test(ultimo?.txt || ''), JSON.stringify(git));
73+ok('3 · …y enlaza el commit en el remoto, sin credenciales ni correo', ultimo?.title === `https://github.com/demo-org/demo-repo/commit/${SHA}` && !/token123|usuario|ana@/.test(JSON.stringify(git)), JSON.stringify(ultimo));
74+await p.locator('#topmenu .menu-item', { hasText: 'Rama: main' }).click();
75+ok('3 · la rama abre su árbol en el remoto', (await p.evaluate(() => window.__abiertas.at(-1))) === 'https://github.com/demo-org/demo-repo/tree/main');
76+ok('3 · «Redactar el mensaje de commit» en vez de prometer un commit', git.some(g => /Redactar el mensaje de commit/.test(g.txt)) && !git.some(g => /commitee/.test(g.txt)));
77+const logTxt = await p.evaluate(async () => { const sh = await import('/js/shell.js'); return sh.stripAnsi(await sh.exec('git log', { record: false })); });
78+ok('3 · `git log` del terminal da el SHA, no la rama', logTxt.includes('commit ' + SHA) && !/correo|@example/.test(logTxt), logTxt.slice(0, 120));
79+
80+// 4 · Historial
81+await p.fill('#prompt', 'hola');
82+await p.press('#prompt', 'Enter');
83+await p.waitForTimeout(400);
84+await p.click('#btn-history');
85+await p.waitForTimeout(300);
86+const hist = await p.evaluate(() => ({ botones: document.querySelectorAll('#history-panel button.hp-open').length, actual: document.querySelectorAll('#history-panel .hp-open[aria-current="true"]').length, foco: document.activeElement?.className, dialog: document.getElementById('history-panel').getAttribute('role') }));
87+ok('4 · el Historial es un diálogo con filas-botón y la conversación activa marcada', hist.botones >= 1 && hist.actual === 1 && hist.dialog === 'dialog' && /hp-open/.test(hist.foco || ''), JSON.stringify(hist));
88+await p.keyboard.press('Escape');
89+await p.waitForTimeout(100);
90+ok('1 · Escape cierra el Historial y vuelve al botón', await p.evaluate(() => document.getElementById('history-panel').hidden && document.activeElement?.id === 'btn-history'));
91+
92+// 1 · Ajustes
93+await p.click('#btn-settings');
94+await p.waitForTimeout(300);
95+ok('1 · Ajustes es un diálogo y el foco entra en él', await p.evaluate(() => document.getElementById('settings-panel').getAttribute('role') === 'dialog' && document.getElementById('settings-panel').contains(document.activeElement)));
96+await p.keyboard.press('Escape');
97+await p.waitForTimeout(100);
98+ok('1 · Escape cierra Ajustes y el foco vuelve al engranaje', await p.evaluate(() => document.getElementById('settings-panel').hidden && document.activeElement?.id === 'btn-settings'));
99+
100+// 1 · vista 3D (arquitectura)
101+await p.click('#act-arch');
102+await p.waitForTimeout(800);
103+await p.keyboard.press('Escape');
104+await p.waitForTimeout(150);
105+ok('1 · Escape cierra la vista de Arquitectura', await p.evaluate(() => document.getElementById('view-overlay').hidden));
106+
107+// 6 · Modos
108+await p.click('#btn-modos');
109+await p.waitForTimeout(100);
110+await p.click('#btn-goal');
111+await p.waitForTimeout(100);
112+const modos = await p.evaluate(() => ({ abierto: !document.getElementById('modos-menu').hidden, boton: document.getElementById('btn-modos').textContent, aria: document.getElementById('btn-goal').getAttribute('aria-checked'), ph: document.getElementById('prompt').placeholder }));
113+ok('6 · tocar un modo no cierra el menú y marca aria-checked', modos.abierto && modos.aria === 'true', JSON.stringify(modos));
114+ok('6 · el botón «Modos» enseña 🎯 y el prompt avisa del modo Objetivo', /🎯/.test(modos.boton) && /objetivo/i.test(modos.ph), JSON.stringify(modos));
115+await p.keyboard.press('Escape');
116+await p.waitForTimeout(100);
117+ok('1 · Escape cierra Modos', await p.evaluate(() => document.getElementById('modos-menu').hidden));
118+await p.click('#btn-modos'); await p.click('#btn-goal'); await p.keyboard.press('Escape');
119+
120+// 5 · pestañas de conversación
121+await p.locator('#conv-tabs .tab-add').dispatchEvent('click');
122+await p.waitForTimeout(200);
123+const antes = await p.evaluate(() => window.elffussClaw.conv.getActive().id);
124+await p.locator('#conv-tabs .tab.active').focus();
125+await p.keyboard.press('ArrowLeft');
126+await p.waitForTimeout(150);
127+const tras = await p.evaluate(() => ({ activa: window.elffussClaw.conv.getActive().id, role: document.querySelector('#conv-tabs .tab').getAttribute('role'), foco: document.activeElement?.getAttribute('role') }));
128+ok('5 · ← cambia de conversación y las pestañas son role=tab', tras.activa !== antes && tras.role === 'tab' && tras.foco === 'tab', JSON.stringify(tras));
129+await p.evaluate(() => { window.prompt = () => 'Mi conversación'; });
130+await p.keyboard.press('Shift+F10');
131+await p.waitForTimeout(100);
132+await p.locator('#conv-menu .tm-item', { hasText: 'Renombrar' }).click();
133+await p.waitForTimeout(250);
134+ok('5 · el menú de la pestaña la renombra', await p.evaluate(() => document.querySelector('#conv-tabs .tab.active .tab-name')?.textContent === 'Mi conversación'));
135+
136+// 7 · paleta «#»
137+await p.click('#menubar button[data-menu="edit"]');
138+await p.locator('#topmenu .menu-item', { hasText: 'Buscar en el código' }).click();
139+await p.waitForTimeout(150);
140+const pal = await p.evaluate(() => ({ abierta: !document.getElementById('palette').hidden, valor: document.getElementById('pal-input').value, rol: document.getElementById('pal-input').getAttribute('role') }));
141+ok('7 · Edit › Buscar en el código abre la paleta en modo «#» (y no se cierra sola)', pal.abierta && pal.valor === '#' && pal.rol === 'combobox', JSON.stringify(pal));
142+await p.fill('#pal-input', '#palabraSecreta');
143+await p.waitForSelector('#pal-list .pal-item', { timeout: 5000 }).catch(() => {});
144+const hits = await p.evaluate(() => [...document.querySelectorAll('#pal-list .pal-item')].map(r => r.querySelector('.pi-hint').textContent));
145+ok('7 · encuentra la palabra dentro de los ficheros, como fichero:línea', hits.includes('src/app.js:2'), JSON.stringify(hits));
146+await p.press('#pal-input', 'Enter');
147+await p.waitForTimeout(500);
148+const abierto = await p.evaluate(() => ({ activa: document.querySelector('#tabs-bar .tab.active')?.dataset.path, linea: window.monaco?.editor?.getEditors?.()[0]?.getPosition()?.lineNumber }));
149+ok('7 · Enter abre el fichero en esa línea', abierto.activa === 'src/app.js' && abierto.linea === 2, JSON.stringify(abierto));
150+await p.click('#act-search');
151+await p.waitForTimeout(200);
152+ok('7 · la lupa de la barra abre la paleta (y se queda abierta)', await p.evaluate(() => !document.getElementById('palette').hidden));
153+await p.keyboard.press('Escape');
154+
155+// 8 · detalles
156+const ctxTitulo = await p.evaluate(async () => {
157+ const m = await import('/js/main.js');
158+ m.setCtxBudget(4100); // 100 tokens: casi lleno
159+ window.elffussClaw.send('x'.repeat(600));
160+ await new Promise(r => setTimeout(r, 400));
161+ return document.getElementById('ctx-meter').title;
162+});
163+ok('8 · el medidor de contexto lleno manda a «+» y no a un 🧹 que no existe', !/🧹/.test(ctxTitulo) && /«\+»/.test(ctxTitulo), ctxTitulo);
164+await p.click('#prompt');
165+await p.fill('#prompt', '');
166+await p.keyboard.type('linea uno');
167+await p.keyboard.press('Shift+Enter');
168+await p.keyboard.type('linea dos');
169+await p.keyboard.press('ArrowUp');
170+ok('8 · ↑ en un borrador de varias líneas no lo cambia por el historial', (await p.inputValue('#prompt')) === 'linea uno\nlinea dos');
171+await p.fill('#prompt', '');
172+await p.click('#btn-slash');
173+await p.waitForTimeout(200);
174+const slash = await p.evaluate(() => ({ items: [...document.querySelectorAll('#menu .menu-item b')].map(b => b.textContent), foco: document.activeElement?.classList.contains('menu-item') }));
175+ok('8 · «/new» en vez de «/clear», y el foco entra en el menú', slash.items.includes('/new') && !slash.items.includes('/clear') && slash.foco, JSON.stringify(slash));
176+await p.keyboard.press('ArrowDown');
177+ok('8 · ↓ recorre el menú de comandos', await p.evaluate(() => document.activeElement?.textContent.startsWith('/search')));
178+await p.keyboard.press('Escape');
179+await p.waitForTimeout(100);
180+ok('1 · Escape cierra el menú de comandos y vuelve a la caja de texto', await p.evaluate(() => document.getElementById('menu').hidden && document.activeElement?.id === 'prompt'));
181+await p.click('#act-term');
182+await p.waitForTimeout(400);
183+const alto0 = await p.evaluate(() => document.getElementById('terminal-panel').offsetHeight);
184+await p.locator('#term-resize').focus();
185+await p.keyboard.press('ArrowUp');
186+const alto1 = await p.evaluate(() => document.getElementById('terminal-panel').offsetHeight);
187+ok('8 · el terminal se redimensiona con ↑ desde su separador', alto1 > alto0, `${alto0} → ${alto1}`);
188+
189+console.log('\n errores JS:', errs[0] || 'ninguno');
190+ok('sin errores de página', errs.length === 0, errs.join(' | '));
191+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ TECLADO, ESCAPE, MENÚS Y BÚSQUEDA OK');
192+await b.close();
193+process.exit(fails ? 1 : 0);
modified web/css/code.css +9 −1
@@ -240,7 +240,7 @@
240240 @media (max-width: 820px) { #mind-log { width: 88vw; right: -90vw; } .mind-music { width: 180px; } }
241241
242242 /* menú contextual del árbol y de las pestañas (botón derecho) */
243-#tree-menu, #tab-menu { background: var(--bg2); border: 1px solid var(--line); border-radius: 8px; padding: 4px; min-width: 168px; box-shadow: 0 10px 34px rgba(0,0,0,.5); display: flex; flex-direction: column; }
243+#tree-menu, #tab-menu, #conv-menu { background: var(--bg2); border: 1px solid var(--line); border-radius: 8px; padding: 4px; min-width: 168px; box-shadow: 0 10px 34px rgba(0,0,0,.5); display: flex; flex-direction: column; }
244244 .tm-item { text-align: left; background: none; border: none; color: var(--fg); font-size: .82rem; padding: 6px 10px; border-radius: 6px; cursor: pointer; }
245245 .tm-item:hover { background: var(--bg3); }
246246 .tm-item.danger { color: #ff6b8b; }
@@ -310,6 +310,11 @@
310310 .hp-empty { padding: 16px; color: var(--muted); font-size: .8rem; text-align: center; }
311311 .hp-row { display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
312312 .hp-row:hover { background: var(--bg3); }
313+/* la fila es un botón (abrir) más el de borrar */
314+.hp-row:has(.hp-open) { display: flex; padding: 0 6px 0 0; }
315+.hp-open { flex: 1; min-width: 0; display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 8px; background: none; border: none; color: inherit; font: inherit; text-align: left; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
316+.hp-open[aria-current="true"] .hp-title { color: var(--accent); }
317+.hp-open:focus-visible, .hp-del:focus-visible, .hp-head button:focus-visible { outline: 2px solid var(--accent2); outline-offset: -2px; }
313318 .hp-title { font-size: .82rem; color: var(--fg); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
314319 .hp-date { font-size: .68rem; color: var(--muted); white-space: nowrap; }
315320 .hp-del { background: none; border: none; cursor: pointer; font-size: .8rem; opacity: .6; }
@@ -511,6 +516,9 @@
511516 #topmenu .menu-item { display: flex; justify-content: space-between; gap: 12px; width: 100%; text-align: left; background: none; border: none; color: var(--fg); padding: 7px 10px; border-radius: 6px; cursor: pointer; font-size: .82rem; }
512517 #topmenu .menu-item:hover { background: #ffffff10; }
513518 #topmenu .menu-item span { color: var(--muted); font-size: .74rem; }
519+#topmenu .menu-item.disabled { opacity: .55; cursor: default; }
520+#topmenu .menu-item.disabled:hover { background: none; }
521+#topmenu .menu-item:focus-visible, #menubar button:focus-visible { outline: 2px solid var(--accent2); outline-offset: -2px; }
514522
515523 /* chip de rama git */
516524 .chip { display: inline-flex; align-items: center; gap: 4px; background: var(--bg3); border: 1px solid var(--line); color: var(--muted); border-radius: 999px; padding: 3px 10px; font-size: .74rem; cursor: pointer; white-space: nowrap; }
modified web/js/conversations.js +10 −0
@@ -196,6 +196,16 @@
196196 await persistConv(c);
197197 }
198198
199+// Ponerle nombre a una conversación (menú de su pestaña). Vacío vuelve al
200+// título automático (el primer mensaje).
201+export async function rename(id, title) {
202+ const c = convs.get(id);
203+ if (!c) return;
204+ c.title = cleanTitle(title || '').slice(0, 80) || null;
205+ await persistConv(c);
206+ onChange('tabs', activeId);
207+}
208+
199209 // quita la pestaña de la vista — la conversación sigue viva en la Historial
200210 //
201211 // Si la pestaña cerrada era la ACTIVA, se avisa con 'switch' y no con 'tabs':
modified web/js/i18n.js +30 −4
@@ -16,7 +16,7 @@
1616 tagline2: 'Editor tipo VS Code + agente <b>en tu navegador</b>. Nada sale de tu máquina. 😉',
1717 openProject: '📁 Abrir carpeta de código', resume: 'Reanudar', discard: 'Descartar', cloneOpen: 'Descargar y abrir',
1818 clonePh: 'pega la URL de un repo público (GitHub/Bitbucket)…',
19- searchPh: 'Buscar archivos por nombre (: para ir a línea, @ para símbolo, > para comandos)',
19+ searchPh: 'Buscar archivos por nombre (: ir a línea, @ símbolo, > comandos, # buscar en el código)',
2020 tFiles: 'Explorador', tSearch: 'Buscar (Cmd/Ctrl+P)', tArch: 'Arquitectura (grafo de dependencias)',
2121 tCity: 'Ciudad 3D', tTerm: 'Terminal (Ctrl+`)', tSkills: 'Skills', tActSettings: 'Ajustes y modelo',
2222 tGitBranch: 'rama actual', tHistory: 'Historial de conversaciones', tTopSettings: 'Ajustes, modelo y API keys',
@@ -44,7 +44,7 @@
4444 mNewFile: 'Nuevo archivo…', promptNewPath: 'Ruta del nuevo archivo:', mSave: 'Guardar', mOpenFolder: 'Abrir carpeta…',
4545 mSearchCode: 'Buscar en el código', mGotoFile: 'Ir a archivo…', mGotoSym: 'Ir a símbolo…',
4646 mTerminal: 'Terminal', mArch: 'Arquitectura', mAbout: 'Acerca de Elffuss Code (GitHub)',
47- gNotRepo: 'No es un repositorio git', gBranch: 'Rama: {b}', gLast: 'Último: {m}', gCommit: 'Pídele a Elffuss que commitee',
47+ gNotRepo: 'No es un repositorio git', gBranch: 'Rama: {b}', gLast: 'Último: {m}', gCommit: 'Redactar el mensaje de commit',
4848 nExec: '▶ Ejecutar', nView: 'Ver en la Mente',
4949 fallbackToast: 'Ese Gemma no cargó (memoria/GPU) — uso el ligero…',
5050 setStoreTitle: 'Modelo descargado (se cachea en tu navegador)', setClear: 'Vaciar caché', setClearing: 'Vaciando…',
@@ -193,6 +193,19 @@
193193 provToggle: "Activar {name}", setModelLoadingCard: "cargando…",
194194 modelDot: "Modelo: {name} · {state} — clic para cambiarlo", modelDotBasic: "Modo básico, sin modelo de IA — clic para elegir uno",
195195 modelState_off: "sin cargar", modelState_loading: "cargando…", modelState_on: "listo", modelState_error: "no se pudo cargar",
196+ // teclado, menús y pestañas
197+ menubarLabel: "Menú", menu_file: "Archivo", menu_edit: "Editar", menu_view: "Ver", menu_git: "Git",
198+ gNoRemote: "sin remoto",
199+ modesLabel: "Modos de trabajo", modesBtn: "Modos", modesNone: "ninguno activo",
200+ modeReview: "revisar antes de escribir", modeGoal: "objetivo", modeHard: "Hard Work",
201+ goalPlaceholder: "🎯 Describe el objetivo: lo descompongo en tareas y las hago una a una…",
202+ convTabs: "Conversaciones abiertas", convBusy: "trabajando", tabCloseNamed: "Cerrar la pestaña «{title}» (no borra la conversación)",
203+ convRename: "Renombrar…", convRenamePrompt: "Nombre de la conversación (vacío = el automático):",
204+ histDelNamed: "Eliminar para siempre «{title}»",
205+ palSearchHint: "Escribe al menos 2 letras para buscar dentro del código",
206+ termResizeLabel: "Altura del terminal (↑/↓)",
207+ ctxFull: "Contexto casi lleno ({pct}%). Los mensajes viejos se comprimen solos; para empezar limpio, abre una conversación nueva con «+».",
208+ ctxUse: "Contexto: {tok} de ~{max} tokens ({free}% libre)",
196209 clearModelsConfirm: "Vas a borrar {size} de modelos guardados en este navegador.\n\nNo se pierde nada tuyo: solo los pesos descargados. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?",
197210 clearModelsShared: "Ojo: el almacén compartido de Elffuss no se pudo consultar desde aquí; puede quedar algo guardado ahí.",
198211 clearModelsDone: "💾 Liberados {size}.", clearModelsFailed: "No se pudo vaciar: {what}.",
@@ -211,7 +224,7 @@
211224 tagline2: 'VS Code–style editor + agent <b>in your browser</b>. Nothing leaves your machine. 😉',
212225 openProject: '📁 Open code folder', resume: 'Resume', discard: 'Discard', cloneOpen: 'Download & open',
213226 clonePh: 'paste the URL of a public repo (GitHub/Bitbucket)…',
214- searchPh: 'Search files by name (: to go to line, @ for symbol, > for commands)',
227+ searchPh: 'Search files by name (: go to line, @ symbol, > commands, # search in code)',
215228 tFiles: 'Explorer', tSearch: 'Search (Cmd/Ctrl+P)', tArch: 'Architecture (dependency graph)',
216229 tCity: '3D City', tTerm: 'Terminal (Ctrl+`)', tSkills: 'Skills', tActSettings: 'Settings & model',
217230 tGitBranch: 'current branch', tHistory: 'Conversation history', tTopSettings: 'Settings, model & API keys',
@@ -238,7 +251,7 @@
238251 mNewFile: 'New file…', promptNewPath: 'New file path:', mSave: 'Save', mOpenFolder: 'Open folder…',
239252 mSearchCode: 'Search the code', mGotoFile: 'Go to file…', mGotoSym: 'Go to symbol…',
240253 mTerminal: 'Terminal', mArch: 'Architecture', mAbout: 'About Elffuss Code (GitHub)',
241- gNotRepo: 'Not a git repository', gBranch: 'Branch: {b}', gLast: 'Latest: {m}', gCommit: 'Ask Elffuss to commit',
254+ gNotRepo: 'Not a git repository', gBranch: 'Branch: {b}', gLast: 'Latest: {m}', gCommit: 'Draft the commit message',
242255 nExec: '▶ Run', nView: 'View in the Mind',
243256 fallbackToast: 'That Gemma didn’t load (memory/GPU) — using the light one…',
244257 setStoreTitle: 'Downloaded model (cached in your browser)', setClear: 'Clear cache', setClearing: 'Clearing…',
@@ -387,6 +400,19 @@
387400 provToggle: "Turn on {name}", setModelLoadingCard: "loading…",
388401 modelDot: "Model: {name} · {state} — click to change it", modelDotBasic: "Basic mode, no AI model — click to pick one",
389402 modelState_off: "not loaded", modelState_loading: "loading…", modelState_on: "ready", modelState_error: "couldn't load",
403+ // keyboard, menus and tabs
404+ menubarLabel: "Menu", menu_file: "File", menu_edit: "Edit", menu_view: "View", menu_git: "Git",
405+ gNoRemote: "no remote",
406+ modesLabel: "Work modes", modesBtn: "Modes", modesNone: "none on",
407+ modeReview: "review before writing", modeGoal: "goal", modeHard: "Hard Work",
408+ goalPlaceholder: "🎯 Describe the goal: I'll break it into tasks and do them one by one…",
409+ convTabs: "Open conversations", convBusy: "working", tabCloseNamed: "Close the “{title}” tab (doesn't delete the conversation)",
410+ convRename: "Rename…", convRenamePrompt: "Conversation name (empty = automatic):",
411+ histDelNamed: "Delete “{title}” forever",
412+ palSearchHint: "Type at least 2 letters to search inside the code",
413+ termResizeLabel: "Terminal height (↑/↓)",
414+ ctxFull: "Context almost full ({pct}%). Old messages are compressed automatically; to start clean, open a new conversation with “+”.",
415+ ctxUse: "Context: {tok} of ~{max} tokens ({free}% free)",
390416 clearModelsConfirm: "You are about to delete {size} of models stored in this browser.\n\nNothing of yours is lost: only the downloaded weights. Next time they will be downloaded again.\n\nContinue?",
391417 clearModelsShared: "Note: Elffuss's shared store could not be checked from here; something may remain stored there.",
392418 clearModelsDone: "💾 Freed {size}.", clearModelsFailed: "Couldn't clear: {what}.",
modified web/js/main.js +422 −61
@@ -333,45 +333,116 @@
333333 else conv.send(active.id, text);
334334 }
335335
336+// Pestañas de conversación con semántica de pestañas: la activa entra con Tab,
337+// ←/→ se mueven, Supr cierra, Shift+F10 abre su menú (Renombrar, Cerrar,
338+// Cerrar otras). Antes eran <div> sin foco y la × un <b>; el punto de
339+// «trabajando» se anuncia también en el nombre accesible.
336340 function renderTabsBar() {
337341 const bar = $('conv-tabs');
338342 if (!bar) return;
343+ const teniaFoco = bar.contains(document.activeElement);
339344 bar.replaceChildren();
345+ bar.setAttribute('role', 'tablist');
346+ bar.setAttribute('aria-label', t('convTabs'));
340347 const active = conv.getActive();
341- for (const c of conv.getOpenTabs()) {
348+ const abiertas = conv.getOpenTabs();
349+ for (const c of abiertas) {
342350 const el = document.createElement('div');
343- el.className = 'tab' + (active && c.id === active.id ? ' active' : '') + (c.pumping ? ' tab-busy' : '');
351+ const on = !!active && c.id === active.id;
352+ el.className = 'tab' + (on ? ' active' : '') + (c.pumping ? ' tab-busy' : '');
344353 el.dataset.id = c.id;
354+ el.setAttribute('role', 'tab');
355+ el.setAttribute('aria-selected', on ? 'true' : 'false');
356+ el.tabIndex = on ? 0 : -1;
345357 const name = document.createElement('span');
346358 name.className = 'tab-name';
347359 const title = conv.titleFor(c);
348360 name.textContent = title;
349361 name.title = title;
350- const x = document.createElement('b');
362+ el.setAttribute('aria-label', title + (c.pumping ? ' · ' + t('convBusy') : ''));
363+ const x = document.createElement('button');
364+ x.type = 'button';
365+ x.className = 'tab-x';
366+ x.tabIndex = -1;
351367 x.textContent = '×';
352368 x.title = t('tabClose');
369+ x.setAttribute('aria-label', t('tabCloseNamed', { title }));
353370 x.onclick = e => { e.stopPropagation(); conv.closeTab(c.id); };
354371 el.append(name, x);
355372 el.onclick = () => conv.switchTo(c.id);
373+ el.oncontextmenu = e => { e.preventDefault(); menuConversacion(c, e.clientX, e.clientY, el); };
374+ el.onkeydown = e => {
375+ const i = abiertas.indexOf(c);
376+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
377+ e.preventDefault();
378+ const n = abiertas[(i + (e.key === 'ArrowRight' ? 1 : abiertas.length - 1)) % abiertas.length];
379+ conv.switchTo(n.id);
380+ $('conv-tabs').querySelector(`.tab[data-id="${n.id}"]`)?.focus();
381+ } else if (e.key === 'Delete') { e.preventDefault(); conv.closeTab(c.id); $('conv-tabs').querySelector('.tab.active')?.focus(); }
382+ else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) { e.preventDefault(); const r = el.getBoundingClientRect(); menuConversacion(c, r.left, r.bottom, el); }
383+ };
356384 bar.appendChild(el);
357385 }
358386 const plus = document.createElement('button');
359387 plus.className = 'tab-add';
360388 plus.title = t('newConv');
389+ plus.setAttribute('aria-label', t('newConv'));
361390 plus.textContent = '+';
362391 plus.onclick = () => conv.create();
363392 bar.appendChild(plus);
393+ if (teniaFoco) bar.querySelector('.tab.active')?.focus();
394+}
395+
396+// Menú de una pestaña de conversación (botón derecho / Shift+F10).
397+function menuConversacion(c, x, y, volver) {
398+ document.getElementById('conv-menu')?.remove();
399+ const menu = document.createElement('div');
400+ menu.id = 'conv-menu';
401+ menu.className = 'conv-menu';
402+ menu.setAttribute('role', 'menu');
403+ menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
404+ const cerrar = () => { menu.remove(); document.removeEventListener('mousedown', fuera, true); volver?.focus?.(); };
405+ const fuera = ev => { if (!menu.contains(ev.target)) cerrar(); };
406+ const opciones = [
407+ [t('convRename'), async () => {
408+ const nuevo = prompt(t('convRenamePrompt'), conv.titleFor(c));
409+ if (nuevo != null) await conv.rename(c.id, nuevo);
410+ }],
411+ [t('tmClose'), () => conv.closeTab(c.id)],
412+ [t('tmCloseOthers'), () => { for (const o of conv.getOpenTabs()) if (o.id !== c.id) conv.closeTab(o.id); conv.switchTo(c.id); }],
413+ ];
414+ for (const [label, fn] of opciones) {
415+ const b = document.createElement('button');
416+ b.type = 'button'; b.className = 'tm-item'; b.setAttribute('role', 'menuitem'); b.textContent = label;
417+ b.onclick = () => { cerrar(); fn(); };
418+ menu.appendChild(b);
419+ }
420+ menu.addEventListener('keydown', e => {
421+ const l = [...menu.querySelectorAll('[role="menuitem"]')], i = l.indexOf(document.activeElement);
422+ if (e.key === 'Escape') { e.preventDefault(); cerrar(); }
423+ else if (e.key === 'ArrowDown') { e.preventDefault(); l[(i + 1) % l.length].focus(); }
424+ else if (e.key === 'ArrowUp') { e.preventDefault(); l[(i - 1 + l.length) % l.length].focus(); }
425+ });
426+ document.body.appendChild(menu);
427+ setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
428+ menu.querySelector('button')?.focus();
364429 }
365430
366431 async function renderHistoryPanel() {
367432 const panel = $('history-panel');
368433 panel.replaceChildren();
434+ // Un diálogo con filas que son botones: antes eran <div> y solo se usaban
435+ // con el ratón. La conversación activa se marca (aria-current).
436+ panel.setAttribute('role', 'dialog');
437+ panel.setAttribute('aria-labelledby', 'hp-title');
369438 const head = document.createElement('div');
370439 head.className = 'hp-head';
371- head.append(document.createTextNode(t('tHistory')));
440+ const tit = document.createElement('span'); tit.id = 'hp-title'; tit.textContent = t('tHistory');
441+ head.append(tit);
372442 const xBtn = document.createElement('button');
373443 xBtn.textContent = '✕';
374- xBtn.onclick = () => { panel.hidden = true; };
444+ xBtn.setAttribute('aria-label', t('close'));
445+ xBtn.onclick = () => cierraHistorial();
375446 head.appendChild(xBtn);
376447 panel.appendChild(head);
377448 const list = document.createElement('div');
@@ -385,28 +456,37 @@
385456 list.appendChild(empty);
386457 return;
387458 }
459+ const activa = conv.getActive()?.id;
388460 for (const c of all) {
389461 const row = document.createElement('div');
390462 row.className = 'hp-row';
391- const titEl = document.createElement('div');
463+ const abrir = document.createElement('button');
464+ abrir.type = 'button';
465+ abrir.className = 'hp-open';
466+ if (c.id === activa) abrir.setAttribute('aria-current', 'true');
467+ const titEl = document.createElement('span');
392468 titEl.className = 'hp-title';
393469 titEl.textContent = c.title || t('newConv');
394470 const d = new Date(c.updatedAt);
395- const date = document.createElement('div');
471+ const date = document.createElement('span');
396472 date.className = 'hp-date';
397473 date.textContent = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
474+ abrir.append(titEl, date);
475+ abrir.onclick = async () => { await conv.open(c.id); cierraHistorial({ foco: false }); $('prompt').focus(); };
398476 const del = document.createElement('button');
477+ del.type = 'button';
399478 del.className = 'hp-del';
400479 del.title = t('histDel');
480+ del.setAttribute('aria-label', t('histDelNamed', { title: c.title || t('thisConv') }));
401481 del.textContent = '🗑';
402482 del.onclick = async e => {
403483 e.stopPropagation();
404484 if (!confirm(t('confirmDel', { title: c.title || t('thisConv') }))) return;
405485 await conv.remove(c.id);
406- renderHistoryPanel();
486+ await renderHistoryPanel();
487+ ($('history-panel').querySelector('.hp-open') || $('history-panel').querySelector('.hp-head button'))?.focus();
407488 };
408- row.append(titEl, date, del);
409- row.onclick = async () => { await conv.open(c.id); panel.hidden = true; };
489+ row.append(abrir, del);
410490 list.appendChild(row);
411491 }
412492 }
@@ -743,15 +823,33 @@
743823 // ---------- panel ⚙️ Ajustes: modelo (cerebro) + API keys ----------
744824 const el = (t, cls, txt) => { const e = document.createElement(t); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
745825
826+// Ajustes (y el panel de skills, que usa el mismo sitio) es un diálogo: se
827+// anuncia como tal, el foco entra en él al abrirse y vuelve a quien lo abrió
828+// al cerrarse (también con Escape). Antes el foco se quedaba en el engranaje.
829+let volverDeAjustes = null;
746830 function settingsShell(title) {
747831 const box = $('settings-panel');
832+ const yaAbierto = !box.hidden && box.contains(document.activeElement);
833+ if (box.hidden || !volverDeAjustes) volverDeAjustes = document.activeElement;
748834 box.hidden = false;
749835 box.replaceChildren();
836+ box.setAttribute('role', 'dialog');
837+ box.setAttribute('aria-labelledby', 'settings-title');
750838 const close = el('button', 'panel-close'); close.innerHTML = UI.close; close.title = t("close");
751- close.onclick = () => { box.hidden = true; };
752- box.append(close, el('h3', 'panel-title', title));
839+ close.setAttribute('aria-label', t('close'));
840+ close.onclick = () => cierraAjustes();
841+ const h = el('h3', 'panel-title', title); h.id = 'settings-title'; h.tabIndex = -1;
842+ box.append(close, h);
843+ if (!yaAbierto) requestAnimationFrame(() => h.focus());
753844 return box;
754845 }
846+function cierraAjustes() {
847+ const box = $('settings-panel');
848+ if (box.hidden) return;
849+ box.hidden = true;
850+ const v = volverDeAjustes; volverDeAjustes = null;
851+ if (v && document.body.contains(v)) v.focus();
852+}
755853
756854 function showBridgeMsg(card, text, isErr) {
757855 let el2 = card.querySelector('.br-msg');
@@ -1335,6 +1433,12 @@
13351433 $('prompt').addEventListener('keydown', e => {
13361434 if (!$('menu').hidden) return; // el menú «/» ya usa ↑/↓
13371435 const inp = e.target;
1436+ // En un borrador de varias líneas, ↑/↓ mueven el cursor como siempre: el
1437+ // historial solo salta desde la primera línea (↑) o la última (↓). Antes ↑
1438+ // en un texto largo lo sustituía entero por el mensaje anterior.
1439+ const antes = inp.value.slice(0, inp.selectionStart), despues = inp.value.slice(inp.selectionEnd);
1440+ if (e.key === 'ArrowUp' && antes.includes('\n')) return;
1441+ if (e.key === 'ArrowDown' && despues.includes('\n')) return;
13381442 if (e.key === 'ArrowUp') {
13391443 if (!promptHistory.length) return;
13401444 if (promptHistIdx === -1) { promptDraft = inp.value; promptHistIdx = promptHistory.length; }
@@ -1413,7 +1517,7 @@
14131517 anuncioPendiente = setTimeout(() => { r.textContent = texto; }, 50);
14141518 }
14151519 $('model-select').addEventListener('change', e => changeModel(e.target.value));
1416-$('model-dot').addEventListener('click', () => { $('settings-panel').hidden = false; renderSettings(); $('settings-panel').querySelector('.model-card')?.focus(); });
1520+$('model-dot').addEventListener('click', () => { renderSettings(); requestAnimationFrame(() => $('settings-panel').querySelector('.model-card.active, .model-card')?.focus()); });
14171521 pintaDot('off', 'rules');
14181522 // móvil: conmutar chat ↔ editor
14191523 $('code-flip').addEventListener('click', () => {
@@ -1445,15 +1549,17 @@
14451549 else { const m = await import('./city.js'); await m.renderCity(body, p => { closeView(); openFile(p); }); }
14461550 } catch (e) { body.innerHTML = '<div class="view-loading">No pude construir la vista: ' + (e?.message || e) + '</div>'; }
14471551 }
1448-function closeView() {
1552+function closeView({ foco = false } = {}) {
1553+ const abierta = [...document.querySelectorAll('#act-arch.on, #act-city.on')][0];
14491554 $('view-overlay').hidden = true;
14501555 import('./city.js').then(m => m.disposeCity()).catch(() => {});
14511556 import('./arch.js').then(m => m.disposeArch()).catch(() => {});
14521557 document.querySelectorAll('#activity button').forEach(b => b.classList.toggle('on', b.id === 'act-files'));
1558+ if (foco) abierta?.focus();
14531559 }
14541560 $('act-arch').addEventListener('click', () => openView('arch'));
14551561 $('act-city').addEventListener('click', () => openView('city'));
1456-$('view-close').addEventListener('click', closeView);
1562+$('view-close').addEventListener('click', () => closeView({ foco: true }));
14571563
14581564 // ── Cerebro CEO autónomo + Mente de Elffuss ───────────────────────────────
14591565 // Cuando NO estás pidiendo nada, la elfa trabaja: revisa el proyecto y propone
@@ -1635,7 +1741,23 @@
16351741 (() => {
16361742 const panel = $('terminal-panel'), handle = $('term-resize');
16371743 let sy = 0, sh = 0;
1638- const move = e => { const h = Math.max(120, Math.min(window.innerHeight - 160, sh + (sy - e.clientY))); panel.style.height = h + 'px'; terminal.refit(); };
1744+ // También con el teclado: es un separador con foco, ↑/↓ cambian la altura.
1745+ const ajusta = h => {
1746+ h = Math.max(120, Math.min(window.innerHeight - 160, h));
1747+ panel.style.height = h + 'px';
1748+ handle.setAttribute('aria-valuenow', String(Math.round(h)));
1749+ terminal.refit();
1750+ };
1751+ handle.setAttribute('role', 'separator');
1752+ handle.setAttribute('aria-orientation', 'horizontal');
1753+ handle.setAttribute('aria-label', t('termResizeLabel'));
1754+ handle.setAttribute('aria-valuemin', '120');
1755+ handle.tabIndex = 0;
1756+ handle.addEventListener('keydown', e => {
1757+ if (e.key === 'ArrowUp') { e.preventDefault(); ajusta(panel.offsetHeight + 24); }
1758+ else if (e.key === 'ArrowDown') { e.preventDefault(); ajusta(panel.offsetHeight - 24); }
1759+ });
1760+ const move = e => ajusta(sh + (sy - e.clientY));
16391761 const up = () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
16401762 handle.addEventListener('mousedown', e => { sy = e.clientY; sh = panel.offsetHeight; document.addEventListener('mousemove', move); document.addEventListener('mouseup', up); e.preventDefault(); });
16411763 })();
@@ -1658,36 +1780,69 @@
16581780 document.body.classList.toggle('hide-tree');
16591781 $('act-files').classList.toggle('on');
16601782 });
1661-$('act-search').addEventListener('click', () => {
1662- $('prompt').value = 'busca ';
1663- $('prompt').focus();
1664-});
1783+// Lo que promete su título: buscar ficheros (la paleta, como Cmd/Ctrl+P). Antes
1784+// escribía «busca » en el chat. Buscar DENTRO del código es «#» en la paleta.
1785+$('act-search').addEventListener('click', (e) => { e.stopPropagation(); openPalette(''); });
16651786 $('act-settings').addEventListener('click', () => $('btn-settings').click());
16661787
16671788 $('btn-history').addEventListener('click', () => {
16681789 const panel = $('history-panel');
1669- panel.hidden = !panel.hidden;
1670- if (!panel.hidden) renderHistoryPanel();
1790+ if (!panel.hidden) return cierraHistorial();
1791+ panel.hidden = false;
1792+ $('btn-history').setAttribute('aria-expanded', 'true');
1793+ renderHistoryPanel().then(() => (panel.querySelector('.hp-open') || panel.querySelector('.hp-head button'))?.focus());
16711794 });
1795+function cierraHistorial({ foco = true } = {}) {
1796+ const panel = $('history-panel');
1797+ if (panel.hidden) return;
1798+ panel.hidden = true;
1799+ $('btn-history').setAttribute('aria-expanded', 'false');
1800+ if (foco) $('btn-history').focus();
1801+}
16721802 document.addEventListener('pointerdown', e => {
16731803 const p = $('history-panel');
16741804 if (p.hidden) return;
16751805 if (p.contains(e.target) || e.target.closest('#btn-history')) return;
1676- p.hidden = true;
1806+ cierraHistorial({ foco: false });
16771807 }, true);
16781808 $('btn-settings').addEventListener('click', () => {
16791809 const p = $('settings-panel');
1680- p.hidden = !p.hidden;
1681- if (!p.hidden) renderSettings();
1810+ if (!p.hidden) return cierraAjustes();
1811+ renderSettings();
16821812 });
16831813 // clic fuera del panel (o ir a Archivo/chat) lo cierra — antes solo la X lo hacía
16841814 document.addEventListener('pointerdown', e => {
16851815 const p = $('settings-panel');
16861816 if (p.hidden) return;
1687- if (p.contains(e.target) || e.target.closest('#btn-settings, #act-settings')) return;
1817+ if (p.contains(e.target) || e.target.closest('#btn-settings, #act-settings, #model-dot')) return;
16881818 p.hidden = true;
1819+ volverDeAjustes = null;
16891820 }, true);
16901821
1822+// ── Escape cierra la capa de más arriba ─────────────────────────────────────
1823+// Una por pulsación, y el foco vuelve a quien la abrió. Antes solo la paleta,
1824+// la Mente y el menú @ hacían caso: menús de arriba, modos, historial,
1825+// ajustes y la vista 3D se quedaban abiertos.
1826+const CAPAS = [
1827+ { abierta: () => !$('menu').hidden, cerrar: () => { $('menu').hidden = true; $('prompt').focus(); } },
1828+ { abierta: () => !$('topmenu').hidden, cerrar: () => cierraMenuBarra({ foco: true }) },
1829+ { abierta: () => !$('modos-menu')?.hidden, cerrar: () => cierraModos({ foco: true }) },
1830+ { abierta: () => !$('history-panel').hidden, cerrar: () => cierraHistorial() },
1831+ { abierta: () => !$('settings-panel').hidden, cerrar: () => cierraAjustes() },
1832+ { abierta: () => !$('view-overlay').hidden, cerrar: () => closeView({ foco: true }) },
1833+];
1834+document.addEventListener('keydown', e => {
1835+ if (e.key !== 'Escape' || e.defaultPrevented || e.isComposing) return;
1836+ if (mind.isOpen() || !$('palette').hidden) return; // tienen su propio Escape
1837+ if (document.querySelector('dialog[open], #tree-menu, #tab-menu, #conv-menu')) return;
1838+ if (e.target.closest?.('.monaco-editor, #terminal-host')) {
1839+ // El editor y el terminal usan Escape para lo suyo; solo se cierra una capa
1840+ // si no hay nada que cerrar dentro de ellos.
1841+ if (!CAPAS.some(c => c.abierta())) return;
1842+ }
1843+ for (const c of CAPAS) if (c.abierta()) { e.preventDefault(); c.cerrar(); return; }
1844+});
1845+
16911846 // ---------- composer estilo plugin: +, /, medidor de contexto, Auto ----------
16921847
16931848 // medidor de contexto: chars del historial / presupuesto (~4 chars/token)
@@ -1716,9 +1871,11 @@
17161871 $('ctx-text').textContent = `ctx ${k(tok)} / ${k(CTX_BUDGET_TOK)}`;
17171872 $('ctx-bar').style.width = pct + '%';
17181873 $('ctx-bar').className = pct > 85 ? 'hot' : '';
1874+ // Decía «usa 🧹 para empezar limpio», y no hay ningún 🧹: lo que empieza
1875+ // limpio es «+» (nueva conversación) en la barra de pestañas del chat.
17191876 $('ctx-meter').title = pct > 85
1720- ? `Contexto casi lleno (${pct}%). Los mensajes viejos se comprimen solos; usa 🧹 para empezar limpio.`
1721- : `Contexto: ${tok} de ~${CTX_BUDGET_TOK} tokens (${100 - pct}% libre)`;
1877+ ? t('ctxFull', { pct })
1878+ : t('ctxUse', { tok, max: CTX_BUDGET_TOK, free: 100 - pct });
17221879 }
17231880 const _origAdd = addMsg; // refrescar el medidor cuando cambia la conversación
17241881 addMsg = (...a) => { const r = _origAdd(...a); updateCtxMeter(); return r; };
@@ -1777,8 +1934,32 @@
17771934 { label: '/search', hint: t('slSearch'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } },
17781935 { label: '/skills', hint: t('slSkills'), run: () => openSkillsPanel() },
17791936 { label: '/model', hint: t('slModel'), run: () => $('btn-settings').click() },
1780- { label: '/clear', hint: t('slClear'), run: () => conv.create() },
1937+ // «/clear» abría una conversación NUEVA (no limpiaba la actual): se llama
1938+ // por lo que hace.
1939+ { label: '/new', hint: t('slClear'), run: () => conv.create() },
17811940 ]));
1941+// Abierto con el ratón desde + o /, el foco pasa al menú (antes se quedaba en
1942+// el botón y las flechas no hacían nada); dentro, ↑/↓ recorren las opciones y
1943+// Escape vuelve a la caja de texto.
1944+function enfocaMenuAlAbrir() {
1945+ let n = 0;
1946+ const mira = () => {
1947+ const primero = $('menu').hidden ? null : $('menu').querySelector('.menu-item');
1948+ if (primero) return primero.focus();
1949+ if (++n < 60) requestAnimationFrame(mira);
1950+ };
1951+ requestAnimationFrame(mira);
1952+}
1953+$('btn-slash').addEventListener('click', enfocaMenuAlAbrir);
1954+$('btn-plus').addEventListener('click', enfocaMenuAlAbrir);
1955+$('menu').addEventListener('keydown', e => {
1956+ const l = [...$('menu').querySelectorAll('.menu-item')], i = l.indexOf(document.activeElement);
1957+ if (i < 0) return;
1958+ if (e.key === 'ArrowDown') { e.preventDefault(); l[(i + 1) % l.length].focus(); }
1959+ else if (e.key === 'ArrowUp') { e.preventDefault(); l[(i - 1 + l.length) % l.length].focus(); }
1960+ else if (e.key === 'Home') { e.preventDefault(); l[0].focus(); }
1961+ else if (e.key === 'End') { e.preventDefault(); l.at(-1).focus(); }
1962+});
17821963
17831964 // [+] adjuntar archivo del proyecto como @ruta
17841965 // El menú de ficheros, en una función: lo abren el botón `+` Y escribir `@` en
@@ -1896,11 +2077,16 @@
18962077
18972078 // </> Auto (Edit automatically): si off, pide confirmación antes de escribir
18982079 let autoEdit = localStorage.getItem('elffusscode.autoedit') !== '0';
2080+// Los tres modos se declaran juntos y antes de pintar nada: pintaModos() los
2081+// lee todos y se llama ya al pintar Auto.
2082+let goalMode = localStorage.getItem('elffusscode.goalmode') === '1';
2083+let hardMode = false;
18992084 function paintAuto() {
19002085 const b = $('btn-autoedit');
19012086 b.classList.toggle('on', autoEdit);
19022087 b.querySelector('.ae-txt').textContent = autoEdit ? t('autoTxt') : t('reviewTxt');
19032088 b.title = autoEdit ? t('autoOn') : t('autoOff');
2089+ pintaModos();
19042090 }
19052091 $('btn-autoedit').addEventListener('click', () => {
19062092 autoEdit = !autoEdit;
@@ -1913,13 +2099,38 @@
19132099 return confirm(`Elffuss quiere escribir en «${path}» (${content.split('\n').length} líneas).\n\n¿Aplicar el cambio?`);
19142100 });
19152101
2102+function cierraModos({ foco = false } = {}) {
2103+ const menu = $('modos-menu');
2104+ if (!menu || menu.hidden) return;
2105+ menu.hidden = true;
2106+ $('btn-modos')?.setAttribute('aria-expanded', 'false');
2107+ if (foco) $('btn-modos')?.focus();
2108+}
2109+// El botón «Modos» lleva los que están encendidos (y el texto del prompt dice
2110+// qué va a pasar con lo que escribas).
2111+function pintaModos() {
2112+ const b = $('btn-modos');
2113+ if (!b) return;
2114+ const activos = [];
2115+ if (!autoEdit) activos.push(['Revisar', t('modeReview')]);
2116+ if (goalMode) activos.push(['🎯', t('modeGoal')]);
2117+ if (hardMode) activos.push(['⛏', t('modeHard')]);
2118+ b.textContent = '⚙︎ ' + t('modesBtn') + (activos.length ? ' · ' + activos.map(a => a[0] === 'Revisar' ? t('reviewTxt') : a[0]).join(' ') : '') + ' ▾';
2119+ b.setAttribute('aria-label', t('modesBtn') + (activos.length ? ': ' + activos.map(a => a[1]).join(', ') : ': ' + t('modesNone')));
2120+ b.classList.toggle('on', activos.length > 0);
2121+ $('btn-autoedit')?.setAttribute('aria-checked', autoEdit ? 'true' : 'false');
2122+ $('btn-goal')?.setAttribute('aria-checked', goalMode ? 'true' : 'false');
2123+ $('btn-hardwork')?.setAttribute('aria-checked', hardMode ? 'true' : 'false');
2124+ $('prompt').placeholder = hardMode ? t('hwPlaceholder') : goalMode ? t('goalPlaceholder') : t('ph');
2125+}
2126+
19162127 // 🎯 Goal: el siguiente mensaje que mandes se trata como un OBJETIVO — se
19172128 // planifica en tareas y se ejecutan una a una (goal.js), en vez del turno de
19182129 // chat normal. Mismo patrón (interruptor persistente en localStorage) que
19192130 // </> Auto de arriba.
1920-let goalMode = localStorage.getItem('elffusscode.goalmode') === '1';
19212131 function paintGoal() {
19222132 $('btn-goal').classList.toggle('on', goalMode);
2133+ pintaModos();
19232134 }
19242135 $('btn-goal').addEventListener('click', () => {
19252136 goalMode = !goalMode;
@@ -1929,13 +2140,12 @@
19292140 paintGoal();
19302141
19312142 // ── Hard Work (RLM): lee el proyecto ENTERO por partes ──
1932-let hardMode = false;
19332143 $('btn-hardwork').addEventListener('click', () => {
19342144 hardMode = !hardMode;
19352145 $('btn-hardwork').classList.toggle('on', hardMode);
19362146 // Al apagarlo vuelve el texto de siempre, en el idioma de la interfaz: antes
19372147 // quedaba un «Pídele código a Elffuss…» fijo y en español.
1938- $('prompt').placeholder = hardMode ? t("hwPlaceholder") : t('ph');
2148+ pintaModos();
19392149 });
19402150
19412151 // Trabaja el proyecto abierto por partes: trocea, pregunta a cada parte y funde.
@@ -2108,7 +2318,7 @@
21082318 const COMMANDS = [
21092319 { label: t('newConv'), run: () => conv.create() },
21102320 { label: t('tHistory'), run: () => $('btn-history').click() },
2111- { label: t('pSearchCode'), run: () => { closePalette(); $('prompt').value = t('pSearch'); $('prompt').focus(); } },
2321+ { label: t('pSearchCode'), run: () => openPalette('#') },
21122322 { label: t('pManageSkills'), run: () => { closePalette(); openSkillsPanel(); } },
21132323 { label: t('tActSettings'), run: () => { closePalette(); renderSettings(); } },
21142324 { label: t('pToggleExplorer'), run: () => $('act-files').click() },
@@ -2121,14 +2331,29 @@
21212331 // dejar a medias lo que tengas aquí.
21222332 function abrirLab() { window.open('lab.html', '_blank', 'noopener'); }
21232333
2334+// La paleta es un combobox con su lista (role=listbox, opción activa en
2335+// aria-activedescendant), así un lector de pantalla sigue la selección.
2336+let volverDePaleta = null;
21242337 function openPalette(prefix = '') {
2338+ if ($('palette').hidden) volverDePaleta = document.activeElement;
21252339 $('palette').hidden = false;
21262340 const inp = $('pal-input');
2341+ inp.setAttribute('role', 'combobox');
2342+ inp.setAttribute('aria-controls', 'pal-list');
2343+ inp.setAttribute('aria-expanded', 'true');
2344+ inp.setAttribute('aria-autocomplete', 'list');
2345+ $('pal-list').setAttribute('role', 'listbox');
21272346 inp.value = prefix;
21282347 inp.focus();
21292348 renderPalette();
21302349 }
2131-function closePalette() { $('palette').hidden = true; }
2350+function closePalette() {
2351+ if ($('palette').hidden) return;
2352+ $('palette').hidden = true;
2353+ $('pal-input').setAttribute('aria-expanded', 'false');
2354+ const v = volverDePaleta; volverDePaleta = null;
2355+ if (v && document.body.contains(v) && document.activeElement === $('pal-input')) v.focus?.();
2356+}
21322357
21332358 function fuzzy(q, s) {
21342359 q = q.toLowerCase(); s = s.toLowerCase();
@@ -2140,13 +2365,41 @@
21402365 return i === q.length ? score + (s.endsWith(q) ? 20 : 0) : -1;
21412366 }
21422367
2368+// «#texto»: busca DENTRO de los ficheros (code.search) y lista cada resultado
2369+// como fichero:línea; Enter lo abre en esa línea. Es lo que hace ahora Edit ›
2370+// Buscar en el código (antes solo escribía «busca » en el chat).
2371+let palSeq = 0, palBusca = null;
2372+async function resultadosBusqueda(q) {
2373+ const out = await codeTools.search({ query: q }).catch(e => 'ERROR: ' + e.message);
2374+ const items = [];
2375+ for (const linea of String(out).split('\n')) {
2376+ const m = linea.match(/^(.+?):(\d+): (.*)$/);
2377+ if (m) items.push({ label: m[3] || '·', hint: `${m[1]}:${m[2]}`, run: () => { closePalette(); openFile(m[1]).then(() => gotoLine(+m[2])); } });
2378+ }
2379+ const nota = String(out).split('\n').find(l => l.startsWith('…') || l.startsWith('Sin resultados') || l.startsWith('ERROR'));
2380+ return { items, nota };
2381+}
2382+
21432383 async function renderPalette() {
21442384 const raw = $('pal-input').value;
21452385 const list = $('pal-list');
2146- list.replaceChildren();
2386+ const seq = ++palSeq;
21472387 palItems = [];
2148-
2149- if (raw.startsWith('>')) { // comandos
2388+ let nota = '';
2389+
2390+ if (raw.startsWith('#')) { // buscar en el código
2391+ const q = raw.slice(1).trim();
2392+ if (q.length < 2) nota = t('palSearchHint');
2393+ else {
2394+ clearTimeout(palBusca);
2395+ await new Promise(r => { palBusca = setTimeout(r, 180); });
2396+ if (seq !== palSeq) return; // se siguió escribiendo
2397+ const r = await resultadosBusqueda(q);
2398+ if (seq !== palSeq) return;
2399+ palItems = r.items.slice(0, 60);
2400+ nota = r.nota || '';
2401+ }
2402+ } else if (raw.startsWith('>')) { // comandos
21502403 const q = raw.slice(1).trim().toLowerCase();
21512404 // Todo comando cierra la paleta al ejecutarse: «Nueva conversación», por
21522405 // ejemplo, la dejaba abierta encima.
@@ -2164,19 +2417,32 @@
21642417 run: () => { closePalette(); openFile(f); if (lineQ && +lineQ) setTimeout(() => gotoLine(+lineQ), 300); },
21652418 }));
21662419 }
2420+ if (seq !== palSeq) return;
2421+ list.replaceChildren();
21672422 palSel = 0;
21682423 palItems.forEach((it, i) => {
21692424 const row = el('button', 'pal-item' + (i === 0 ? ' sel' : ''));
2170- row.innerHTML = `<span class="pi-name">${it.label}</span><span class="pi-hint">${it.hint || ''}</span>`;
2425+ row.type = 'button';
2426+ row.id = 'pal-opt-' + i;
2427+ row.setAttribute('role', 'option');
2428+ row.setAttribute('aria-selected', i === 0 ? 'true' : 'false');
2429+ row.tabIndex = -1;
2430+ row.innerHTML = '<span class="pi-name"></span><span class="pi-hint"></span>';
2431+ row.querySelector('.pi-name').textContent = it.label;
2432+ row.querySelector('.pi-hint').textContent = it.hint || '';
21712433 row.onmouseenter = () => { palSel = i; paintPalSel(); };
21722434 row.onclick = () => it.run();
21732435 list.appendChild(row);
21742436 });
2175- if (!palItems.length) list.appendChild(el('div', 'pal-empty', t('palEmpty')));
2437+ if (!palItems.length) list.appendChild(el('div', 'pal-empty', nota || t('palEmpty')));
2438+ else if (nota) list.appendChild(el('div', 'pal-empty', nota));
2439+ paintPalSel();
21762440 }
21772441 function paintPalSel() {
2178- [...$('pal-list').children].forEach((c, i) => c.classList.toggle('sel', i === palSel));
2179- $('pal-list').children[palSel]?.scrollIntoView({ block: 'nearest' });
2442+ [...$('pal-list').querySelectorAll('.pal-item')].forEach((c, i) => { c.classList.toggle('sel', i === palSel); c.setAttribute('aria-selected', i === palSel ? 'true' : 'false'); });
2443+ const opt = $('pal-list').querySelector('#pal-opt-' + palSel);
2444+ if (opt) { $('pal-input').setAttribute('aria-activedescendant', opt.id); opt.scrollIntoView({ block: 'nearest' }); }
2445+ else $('pal-input').removeAttribute('aria-activedescendant');
21802446 }
21812447 $('pal-input').addEventListener('input', renderPalette);
21822448 $('pal-input').addEventListener('keydown', e => {
@@ -2215,7 +2481,7 @@
22152481 } },
22162482 ];
22172483 if (which === 'edit') return [
2218- { label: t('mSearchCode'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } },
2484+ { label: t('mSearchCode'), hint: '#', run: () => openPalette('#') },
22192485 { label: t('mGotoFile'), hint: atajo('P'), run: () => openPalette('') },
22202486 { label: t('mGotoSym'), run: conFichero(() => triggerEditor('editor.action.quickOutline')) },
22212487 ];
@@ -2230,41 +2496,117 @@
22302496 { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') },
22312497 ];
22322498 if (which === 'git') {
2499+ // Rama y último commit enlazan al remoto (sin credenciales) cuando lo hay;
2500+ // si no, se ven como texto desactivado. Antes parecían opciones y no hacían
2501+ // nada. El commit enseña su SHA corto; el correo del autor, nunca.
22332502 const g = await codeTools.gitInfo();
2234- if (!g.isRepo) return [{ label: t('gNotRepo'), hint: '', run: () => {} }];
2235- const items = [{ label: t('gBranch', { b: g.branch }), hint: 'git', run: () => {} }];
2236- if (g.lastCommit) items.push({ label: t('gLast', { m: g.lastCommit.msg.slice(0, 40) }), hint: g.lastCommit.author, run: () => {} });
2503+ if (!g.isRepo) return [{ label: t('gNotRepo'), disabled: true }];
2504+ const abre = url => () => window.open(url, '_blank', 'noopener,noreferrer');
2505+ const items = [g.web
2506+ ? { label: t('gBranch', { b: g.branch }), hint: '↗', title: g.web.branch(g.branch), run: abre(g.web.branch(g.branch)) }
2507+ : { label: t('gBranch', { b: g.branch }), hint: t('gNoRemote'), disabled: true }];
2508+ if (g.lastCommit) {
2509+ const corto = g.lastCommit.sha ? g.lastCommit.sha.slice(0, 7) + ' · ' : '';
2510+ const label = t('gLast', { m: corto + g.lastCommit.msg.slice(0, 40) });
2511+ items.push(g.web && g.lastCommit.sha
2512+ ? { label, hint: '↗', title: g.web.commit(g.lastCommit.sha), run: abre(g.web.commit(g.lastCommit.sha)) }
2513+ : { label, hint: g.lastCommit.author, disabled: true });
2514+ }
2515+ // Pide al agente el MENSAJE de commit: commitear de verdad no puede (el git
2516+ // de aquí es de solo lectura), y la etiqueta vieja lo prometía.
22372517 items.push({ label: t('gCommit'), run: () => { $('prompt').value = t('pCommit'); $('prompt').focus(); } });
22382518 return items;
22392519 }
22402520 return [];
22412521 }
2242-document.querySelectorAll('#menubar button').forEach(b => {
2243- b.addEventListener('click', async () => {
2244- document.querySelectorAll('#menubar button').forEach(x => x.classList.toggle('open', x === b));
2245- openMenuAt(await menuFor(b.dataset.menu), b);
2522+// La barra de menús se usa con el teclado como una de verdad (patrón
2523+// menubar/menu): ↓, Enter o Espacio abren el menú con el foco en su primera
2524+// opción; ←/→ pasan al menú de al lado; ↑/↓ recorren; Escape cierra y devuelve
2525+// el foco; Tab sale. Antes ↓ no entraba en el menú y Escape no lo cerraba. Los
2526+// nombres salen en el idioma de la interfaz.
2527+const barraMenus = () => [...document.querySelectorAll('#menubar button')];
2528+let menuBarraAbierto = null;
2529+{
2530+ const bar = $('menubar');
2531+ bar.setAttribute('role', 'menubar');
2532+ bar.setAttribute('aria-label', t('menubarLabel'));
2533+ barraMenus().forEach((b, i) => {
2534+ b.setAttribute('role', 'menuitem');
2535+ b.setAttribute('aria-haspopup', 'menu');
2536+ b.setAttribute('aria-expanded', 'false');
2537+ b.textContent = t('menu_' + b.dataset.menu);
2538+ b.tabIndex = i === 0 ? 0 : -1;
2539+ b.addEventListener('click', () => (menuBarraAbierto === b ? cierraMenuBarra({ foco: true }) : abreMenuBarra(b)));
2540+ b.addEventListener('keydown', e => {
2541+ const lista = barraMenus(), j = lista.indexOf(b);
2542+ const mueve = k => { const n = lista[(j + k + lista.length) % lista.length]; lista.forEach(x => { x.tabIndex = x === n ? 0 : -1; }); n.focus(); if (menuBarraAbierto) abreMenuBarra(n, { foco: true }); };
2543+ if (e.key === 'ArrowRight') { e.preventDefault(); mueve(1); }
2544+ else if (e.key === 'ArrowLeft') { e.preventDefault(); mueve(-1); }
2545+ else if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); abreMenuBarra(b, { foco: true }); }
2546+ });
22462547 });
2247-});
2548+}
2549+async function abreMenuBarra(b, { foco = false } = {}) {
2550+ barraMenus().forEach(x => { x.classList.toggle('open', x === b); x.setAttribute('aria-expanded', x === b ? 'true' : 'false'); });
2551+ menuBarraAbierto = b;
2552+ openMenuAt(await menuFor(b.dataset.menu), b);
2553+ if (menuBarraAbierto !== b) return; // otro menú se abrió mientras tanto
2554+ if (foco) $('topmenu').querySelector('[role="menuitem"]:not([aria-disabled="true"])')?.focus();
2555+}
2556+function cierraMenuBarra({ foco = false } = {}) {
2557+ const b = menuBarraAbierto;
2558+ $('topmenu').hidden = true;
2559+ barraMenus().forEach(x => { x.classList.remove('open'); x.setAttribute('aria-expanded', 'false'); });
2560+ menuBarraAbierto = null;
2561+ if (foco && b) b.focus();
2562+}
22482563 function openMenuAt(items, anchor) {
22492564 const menu = $('topmenu');
22502565 const r = anchor.getBoundingClientRect();
22512566 menu.style.left = r.left + 'px';
22522567 menu.style.top = (r.bottom + 3) + 'px';
22532568 menu.replaceChildren();
2569+ menu.setAttribute('role', 'menu');
2570+ menu.setAttribute('aria-label', anchor.textContent);
22542571 for (const it of items) {
22552572 const row = el('button', 'menu-item');
2256- row.innerHTML = `<b>${it.label}</b>${it.hint ? `<span>${it.hint}</span>` : ''}`;
2257- row.onclick = () => { menu.hidden = true; it.run(); };
2573+ row.type = 'button';
2574+ row.setAttribute('role', 'menuitem');
2575+ row.tabIndex = -1;
2576+ row.innerHTML = `<b></b>${it.hint ? '<span></span>' : ''}`;
2577+ row.querySelector('b').textContent = it.label;
2578+ if (it.hint) row.querySelector('span').textContent = it.hint;
2579+ if (it.title) row.title = it.title;
2580+ if (it.disabled) { row.setAttribute('aria-disabled', 'true'); row.classList.add('disabled'); }
2581+ // stopPropagation: el clic no debe seguir hasta los «clic fuera» del
2582+ // documento, que cerraban al instante lo que la opción acababa de abrir
2583+ // (la paleta con «Ir a archivo…» o «Buscar en el código»).
2584+ row.onclick = (e) => { e.stopPropagation(); if (it.disabled) return; cierraMenuBarra(); it.run(); };
22582585 menu.appendChild(row);
22592586 }
22602587 menu.hidden = false;
22612588 }
2262-document.addEventListener('click', e => {
2263- if (!e.target.closest('#menubar, #topmenu')) {
2264- document.querySelectorAll('#menubar button').forEach(x => x.classList.remove('open'));
2265- $('topmenu').hidden = true;
2589+$('topmenu').addEventListener('keydown', e => {
2590+ const filas = [...$('topmenu').querySelectorAll('[role="menuitem"]')];
2591+ const i = filas.indexOf(document.activeElement);
2592+ const ve = k => { e.preventDefault(); filas[(i + k + filas.length) % filas.length]?.focus(); };
2593+ if (e.key === 'ArrowDown') ve(1);
2594+ else if (e.key === 'ArrowUp') ve(-1);
2595+ else if (e.key === 'Home') { e.preventDefault(); filas[0]?.focus(); }
2596+ else if (e.key === 'End') { e.preventDefault(); filas.at(-1)?.focus(); }
2597+ else if (e.key === 'Escape') { e.preventDefault(); cierraMenuBarra({ foco: true }); }
2598+ else if (e.key === 'Tab') cierraMenuBarra();
2599+ else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
2600+ e.preventDefault();
2601+ const lista = barraMenus(), j = lista.indexOf(menuBarraAbierto);
2602+ const n = lista[(j + (e.key === 'ArrowRight' ? 1 : -1) + lista.length) % lista.length];
2603+ lista.forEach(x => { x.tabIndex = x === n ? 0 : -1; });
2604+ abreMenuBarra(n, { foco: true });
22662605 }
22672606 });
2607+document.addEventListener('click', e => {
2608+ if (!e.target.closest('#menubar, #topmenu') && !$('topmenu').hidden) cierraMenuBarra();
2609+});
22682610
22692611 // ---------- git en el header ----------
22702612 async function refreshGit() {
@@ -2395,13 +2737,32 @@
23952737 // Ya está a la vista: dejar el title duplicaría el texto en un tooltip.
23962738 b.removeAttribute('title');
23972739 }
2398- modos.addEventListener('click', (e) => { e.stopPropagation(); menu.hidden = !menu.hidden; });
2399- // Cerrar al elegir y al pulsar fuera. Sin lo segundo, el menú se queda
2400- // abierto tapando la conversación y hay que adivinar cómo cerrarlo.
2401- menu.addEventListener('click', () => { menu.hidden = true; });
2740+ // Menú con casillas: cada modo dice si está encendido (aria-checked) y el
2741+ // botón «Modos» enseña cuáles lo están, también cerrado. Antes cualquier
2742+ // clic dentro cerraba el menú y desde fuera no había forma de saber que
2743+ // Goal o Hard Work seguían activos (y las preguntas normales se volvían
2744+ // planes sin avisar). Ahora pulsar un modo lo cambia y el menú se queda
2745+ // abierto para verlo; se cierra al pulsar fuera o con Escape.
2746+ modos.setAttribute('aria-haspopup', 'menu');
2747+ modos.setAttribute('aria-expanded', 'false');
2748+ menu.setAttribute('role', 'menu');
2749+ menu.setAttribute('aria-label', t('modesLabel'));
2750+ for (const b of menu.querySelectorAll('.cbtn')) b.setAttribute('role', 'menuitemcheckbox');
2751+ modos.addEventListener('click', (e) => {
2752+ e.stopPropagation();
2753+ if (menu.hidden) { menu.hidden = false; modos.setAttribute('aria-expanded', 'true'); menu.querySelector('.cbtn')?.focus(); }
2754+ else cierraModos({ foco: false });
2755+ });
2756+ menu.addEventListener('keydown', (e) => {
2757+ const opciones = [...menu.querySelectorAll('.cbtn')], i = opciones.indexOf(document.activeElement);
2758+ if (e.key === 'ArrowDown') { e.preventDefault(); opciones[(i + 1) % opciones.length]?.focus(); }
2759+ else if (e.key === 'ArrowUp') { e.preventDefault(); opciones[(i - 1 + opciones.length) % opciones.length]?.focus(); }
2760+ else if (e.key === 'Tab') cierraModos({ foco: false });
2761+ });
24022762 document.addEventListener('click', (e) => {
2403- if (!e.target.closest('#modos')) menu.hidden = true;
2763+ if (!e.target.closest('#modos') && !menu.hidden) cierraModos({ foco: false });
24042764 });
2765+ pintaModos();
24052766 }
24062767
24072768 // El chat a toda la ventana. Al editor se le da cero de ancho en vez de