Elffuss BraidHub

utopia-ia/elffuss-code public

The Mind is a real modal for the keyboard

The Mind declares role=dialog aria-modal=true and the elf is a button,
but openMind() never moved focus into the overlay, nothing kept Tab
inside, and closeMind() did not restore focus. From the keyboard, Tab went
behind the full-screen overlay into the tree, the editor tab and Monaco,
where each further Tab indented the open file without the user seeing it.

modal.js (the same helper as Claw's) makes the IDE behind inert while the
Mind is open, puts focus on its close button, and returns focus to the
opener on close. "Open in the editor" closes the Mind without returning
focus to the elf and leaves focus in the editor (ide.focusEditor()).

mind-consent.mjs, new part 6: Enter on the elf moves focus into the Mind
with the IDE inert, ten Tabs never leave it, the file behind is
unchanged, Escape returns focus to the elf, and "Open in the editor"
leaves focus in Monaco. The focus, inert and Tab checks fail on the
previous tree.
Changeset48bc21c757fd284e7e9790af564e470fffb5e872e8da77e03f374dea6d42154f
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 19:21 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:15 +02:00
Parents7995a3deb41d

Browse the files at this changeset

5 files changed

modified tests/mind-consent.mjs +35 −0
@@ -10,6 +10,9 @@
1010 // 4. «Abrir en el editor» cierra la Mente antes (antes abría DETRÁS) y las
1111 // rutas de la propuesta abren su fichero.
1212 // 5. La música no se carga sola: hay que pedirla, y se puede quitar.
13+// 6. Con el teclado es modal: el foco entra, Tab no sale, el IDE de detrás queda
14+// inerte, Escape devuelve el foco a la elfa y «Abrir en el editor» lo deja
15+// en el editor.
1316 // La red a SoundCloud va bloqueada: el test solo mira si la app la PIDE.
1417 //
1518 // BASE=http://127.0.0.1:8898 node tests/mind-consent.mjs
@@ -116,6 +119,38 @@
116119 const leyenda = await p.evaluate(() => [...document.querySelectorAll('#mind-legend .ml-item')].every(x => x.tagName === 'BUTTON'));
117120 ok('3 · la leyenda de perfiles son botones (teclado)', leyenda);
118121
122+// 6 · con el teclado la Mente es modal de verdad (antes Tab seguía DETRÁS, en el
123+// árbol, la pestaña y Monaco, y cada Tab sangraba el fichero abierto)
124+await p.keyboard.press('Escape');
125+const textoApp = () => p.evaluate(() => window.monaco.editor.getModels().find(m => /src\/app\.js$/.test(m.uri.path))?.getValue());
126+const antes6 = await textoApp();
127+await p.focus('#act-mind');
128+await p.keyboard.press('Enter');
129+await p.waitForFunction(() => getComputedStyle(document.getElementById('mind-overlay')).display !== 'none');
130+const r6 = await p.evaluate(() => ({ foco: document.activeElement?.id, ideInerte: document.getElementById('ide').inert }));
131+ok('6 · con Enter el foco entra en la Mente (✕ salir) y el IDE de detrás queda inerte', r6.foco === 'mind-close' && r6.ideInerte, JSON.stringify(r6));
132+const visitados = [];
133+for (let i = 0; i < 10; i++) {
134+ await p.keyboard.press('Tab');
135+ visitados.push(await p.evaluate(() => {
136+ const a = document.activeElement;
137+ return a?.closest('#mind-overlay') ? 'mente' : a === document.body || !a ? 'body' : (a.id || a.className || a.tagName);
138+ }));
139+}
140+ok('6 · Tab no sale de la Mente (nunca llega al árbol, las pestañas ni el editor)', visitados.every(v => v === 'mente' || v === 'body'), JSON.stringify(visitados));
141+ok('6 · …y el fichero abierto detrás no cambia', await textoApp() === antes6);
142+await p.keyboard.press('Escape');
143+const r6c = await p.evaluate(() => ({ cerrada: getComputedStyle(document.getElementById('mind-overlay')).display === 'none', foco: document.activeElement?.id, ideInerte: document.getElementById('ide').inert }));
144+ok('6 · Escape cierra, el IDE vuelve a estar vivo y el foco vuelve a la elfa', r6c.cerrada && !r6c.ideInerte && r6c.foco === 'act-mind', JSON.stringify(r6c));
145+await p.keyboard.press('Enter');
146+await p.waitForFunction(() => getComputedStyle(document.getElementById('mind-overlay')).display !== 'none');
147+await p.evaluate(() => [...document.querySelectorAll('.mind-node-label')].find(l => l.style.display !== 'none').click());
148+await p.waitForSelector('#mind-panel.show');
149+await p.click('#mp-open');
150+ok('6 · «Abrir en el editor» deja el foco EN el editor', await p.waitForFunction(() =>
151+ getComputedStyle(document.getElementById('mind-overlay')).display === 'none' && !!document.activeElement?.closest('.monaco-editor'), null, { timeout: 5000 }).then(() => true, () => false),
152+ await p.evaluate(() => document.activeElement?.className || document.activeElement?.tagName));
153+
119154 console.log('\n errores JS:', errs[0] || 'ninguno');
120155 ok('sin errores de página', errs.length === 0, errs.join(' | '));
121156 console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ LA MENTE PIDE PERMISO Y SE DEJA PULSAR');
modified web/js/ide.js +2 −0
@@ -72,6 +72,8 @@
7272 editor?.getAction(actionId)?.run();
7373 }
7474 export function hasEditor() { return !!editor; }
75+// Llevar el foco al editor (p. ej. tras «Abrir en el editor» desde la Mente).
76+export function focusEditor() { try { editor?.focus(); } catch { /* sin editor */ } }
7577 // La ruta del fichero activo (o null): el menú la usa para no lanzar acciones
7678 // del editor que no hacen nada sin un fichero abierto.
7779 export function activeFile() { return active; }
modified web/js/main.js +4 −2
@@ -4,7 +4,7 @@
44 import * as codeTools from './tools/code.js';
55 import * as db from './db.js';
66 import * as settings from './settings.js';
7-import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor, saveActive, activeFile } from './ide.js';
7+import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor, saveActive, activeFile, focusEditor } from './ide.js';
88 import { ACTIVITY, UI } from './icons.js';
99 import { renderMarkdown } from './md.js';
1010 import * as skills from './skills.js';
@@ -1677,7 +1677,9 @@
16771677 // Cuando NO estás pidiendo nada, la elfa trabaja: revisa el proyecto y propone
16781678 // mejoras (en elffuss-mind/, sin tocar tu código). Clic en la elfa → abre la
16791679 // «Mente» (mundo trance + pensamientos paralelos + música) y activa el cerebro.
1680-mind.setOpenFile(openFile);
1680+// «Abrir en el editor» de la Mente: abre el fichero y deja el foco en el editor
1681+// (la Mente cierra sin devolverlo a la elfa).
1682+mind.setOpenFile(async p => { await openFile(p); focusEditor(); });
16811683 mind.init({ buildCity: buildCityAdapter, loadThoughts: loadThoughtsAdapter });
16821684 // «Ejecutar esta propuesta»: la manda a la MISMA cola/agente del chat normal
16831685 // (mismas herramientas reales, mismo gate de Auto-edit) — no un auto-apply
modified web/js/mind.js +21 −4
@@ -18,12 +18,18 @@
1818 import * as db from './db.js';
1919 import { renderMarkdown } from './md.js';
2020 import { t } from './i18n.js';
21+import { abrirModal } from './modal.js';
2122
2223 const SOUNDCLOUD = 'https://soundcloud.com/dekel-official/dekel-baoba-festival-2023';
2324 const CEO_COLOR = '#ff4d8d';
2425
2526 let open = false, built = false, raf = null;
2627 let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {};
28+// La Mente es MODAL (role=dialog, aria-modal): mientras está abierta el IDE de
29+// detrás queda inerte, el foco entra en ella y al cerrarla vuelve a quien la
30+// abrió. Antes solo lo declaraba: Tab seguía detrás de la capa —el árbol, la
31+// pestaña, Monaco— y cada Tab más sangraba el fichero abierto sin verlo.
32+let cerrarModal = null;
2733 // Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos:
2834 // AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor
2935 // VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente
@@ -265,9 +271,11 @@
265271 // Abrir un fichero DESDE la Mente: primero se cierra la Mente. Antes la
266272 // pestaña se abría detrás de esta capa, que lo tapa todo, y parecía que el
267273 // botón no hacía nada.
274+// «Abrir en el editor»: el foco va al editor (lo pone la app anfitriona al
275+// abrir el fichero), no de vuelta a la elfa.
268276 function openInEditor(path) {
269277 document.getElementById('mind-panel')?.classList.remove('show');
270- closeMind();
278+ closeMind({ devolverFoco: false });
271279 onOpenFile(path);
272280 }
273281 // Las rutas `entre comillas invertidas` de una propuesta se pueden abrir.
@@ -537,7 +545,12 @@
537545 export async function openMind() {
538546 if (open) return;
539547 open = true;
540- if (built) { overlay.style.display = ''; if (musicOn) { try { widget?.play(); } catch {} } paintPlay(); startLoop(); return; }
548+ if (built) {
549+ overlay.style.display = '';
550+ cerrarModal = abrirModal(overlay, { foco: '#mind-close' });
551+ if (musicOn) { try { widget?.play(); } catch {} }
552+ paintPlay(); startLoop(); return;
553+ }
541554
542555 overlay = document.createElement('div');
543556 overlay.id = 'mind-overlay';
@@ -555,6 +568,7 @@
555568 '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' +
556569 `<div id="mind-log"><div class="ml-head">${escHtml(t('mindLogTitle'))}<button id="ml-x" aria-label="${escHtml(t('close'))}">✕</button></div><div id="mind-log-body" role="log"></div></div>`;
557570 document.body.appendChild(overlay);
571+ cerrarModal = abrirModal(overlay, { foco: '#mind-close' });
558572 wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay);
559573 mountMusic(overlay);
560574 anchors.length = 0; thoughtNodes = []; stars = []; lineBuf.clear();
@@ -584,7 +598,7 @@
584598 S.camera.aspect = w / h; S.camera.updateProjectionMatrix();
585599 };
586600 window.addEventListener('resize', onResize); S.onResize = onResize;
587- overlay.querySelector('#mind-close').addEventListener('click', closeMind);
601+ overlay.querySelector('#mind-close').addEventListener('click', () => closeMind());
588602 S.onKey = e => { if (e.key === 'Escape') closeMind(); };
589603 document.addEventListener('keydown', S.onKey);
590604 built = true;
@@ -685,12 +699,15 @@
685699 loop(performance.now());
686700 }
687701
688-export function closeMind() {
702+// `devolverFoco: false` cuando quien cierra lleva el foco a otro sitio (el editor).
703+export function closeMind({ devolverFoco = true } = {}) {
689704 open = false;
690705 if (raf) { cancelAnimationFrame(raf); raf = null; }
691706 lastMs = 0;
692707 try { widget?.pause(); } catch {}
693708 if (overlay) overlay.style.display = 'none';
709+ cerrarModal?.({ devolverFoco: devolverFoco !== false });
710+ cerrarModal = null;
694711 }
695712
696713 // para tests/depuración
added web/js/modal.js +39 −0
@@ -0,0 +1,39 @@
1+// Capas modales que no son <dialog> (la Mente): mientras están abiertas, lo de
2+// detrás queda INERTE —ni se enfoca con Tab ni lo lee un lector de pantalla— y
3+// al cerrarlas el foco vuelve a donde estaba. (El mismo módulo que en Claw.)
4+// ─────────────────────────────────────────────────────────────────────────────
5+// Antes eran un <div> encima de todo: se veían modales, pero el primer Tab caía
6+// en el selector de modelo de DETRÁS y se podía manejar la página tapada sin
7+// verla. Al cerrar, el foco se perdía en <body>.
8+//
9+// Los <dialog> se dejan en paz: se gestionan solos con showModal(), y uno inerte
10+// no se podría pulsar. Pasa de verdad: el cerebro puede pedir un permiso con la
11+// Mente abierta, y ese diálogo tiene que poder contestarse.
12+const FOCABLES = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), ' +
13+ 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
14+
15+// `dejar`: ids de hijos de <body> que siguen vivos encima de la capa (en Claw,
16+// la región viva de los avisos).
17+export function abrirModal(capa, { foco = null, dejar = [] } = {}) {
18+ const previo = document.activeElement;
19+ const marcados = [];
20+ for (const el of document.body.children) {
21+ if (el === capa || el.contains(capa) || el.inert) continue;
22+ if (el.tagName === 'SCRIPT' || el.tagName === 'DIALOG' || el.tagName === 'TEMPLATE') continue;
23+ if (el.id && dejar.includes(el.id)) continue;
24+ el.inert = true;
25+ marcados.push(el);
26+ }
27+ const destino = (typeof foco === 'string' ? capa.querySelector(foco) : foco) || capa.querySelector(FOCABLES);
28+ try { destino?.focus({ preventScroll: true }); } catch { /* sin foco posible */ }
29+ let cerrada = false;
30+ return function cerrar({ devolverFoco = true, a = null } = {}) {
31+ if (cerrada) return;
32+ cerrada = true;
33+ for (const el of marcados) el.inert = false;
34+ const vuelta = a || previo;
35+ if (devolverFoco && vuelta && document.contains(vuelta)) {
36+ try { vuelta.focus({ preventScroll: true }); } catch { /* — */ }
37+ }
38+ };
39+}