Elffuss BraidHub

utopia-ia/elffuss-code public

Editor saves for real, asks before dropping changes, keeps the tree open

Closing a tab with unsaved changes (●) discarded them with no question. It
now opens a dialog with Save / Don't save / Cancel (Escape cancels); "Close
others", "Close to the right" and "Close all" ask per file and stop at the
first Cancel. File › Save and the palette's Save ran the Monaco action
'workbench.action.files.save', which standalone Monaco does not have, so
nothing happened; both call the exported saveActive(), and every palette
command now closes the palette. Your own saves write the file directly
instead of going through code.write, which is the agent's path: it asked
"Elffuss quiere escribir…" for your own file with Auto off and its guards
could refuse a legitimate save silently. Shortcut hints follow the platform
(⌘S / Ctrl+S), and Go to symbol with no file open says so.

The explorer remembers which folders are open, so the refresh after every
agent write, rename or delete no longer collapses it. Rename moves the open
tabs to the new path and says so; delete closes the file's tabs (a tab with
unsaved changes stays, marked as deleted); Copy path confirms; renaming copies
the file as a Blob, so binary files survive it. Tree rows and editor tabs are
keyboard reachable (roving tabindex, arrows, Enter, Shift+F10 / menu key),
with tree/treeitem and tablist/tab roles, the open file is highlighted, a
folder cut at 200 entries says how many are hidden, the tab × is a labelled
button, the context menus close with Escape and return focus, and their
labels, prompts and messages are localized. #statusbar is a polite live
region.

tests/editor-save.mjs (?test-opfs, seeded project, real Monaco): the dialog
and its three answers against the file on disk, File › Save and the palette,
the platform hint, the tree staying open after an agent write, rename/copy
path/delete, tree keyboard and Escape, and Go to symbol without a file.
Against the previous code it fails at the first close. tabmenu, ctxmenu,
htmlpreview, htmlpreview_css and previewstorage pin locale es-ES, since the
menus now follow the browser language.
Changesetd66cee4fc9038aeb4d9a69d0b610653428437946c19ec1f21de798f5f9953628
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 15:51 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:12 +02:00
Parentsac1cc0187932

Browse the files at this changeset

11 files changed

modified tests/ctxmenu.mjs +1 −1
@@ -1,7 +1,7 @@
11 import { chromium } from 'playwright';
22 const BASE = process.env.BASE || 'https://code.elffuss.com';
33 let fails = 0; const ok = (n,c,e='')=>{console.log((c?'✅':'❌')+' '+n+(e?' — '+e:''));if(!c)fails++};
4-const b = await chromium.launch(); const ctx = await b.newContext();
4+const b = await chromium.launch(); const ctx = await b.newContext({ locale: 'es-ES' }); // los menús hablan el idioma del navegador; este test mira los textos en español
55 await ctx.addInitScript(()=>{try{localStorage.setItem('elffusscode.model','rules')}catch{}});
66 const p = await ctx.newPage();
77 await p.goto(BASE+'/',{waitUntil:'domcontentloaded'});
added tests/editor-save.mjs +171 −0
@@ -0,0 +1,171 @@
1+// Editor: guardar de verdad, no perder cambios al cerrar, y el árbol que no se
2+// pliega solo.
3+//
4+// 1. Cerrar una pestaña con cambios (●) pregunta: Cancelar la deja abierta,
5+// «No guardar» la cierra sin tocar el disco, «Guardar» escribe y cierra.
6+// Antes se cerraba y los cambios se perdían sin aviso.
7+// 2. File › Guardar y «Guardar» de la paleta guardan (antes lanzaban una
8+// acción que el Monaco suelto no tiene: no pasaba nada) y la paleta se
9+// cierra.
10+// 3. El atajo anunciado es el de esta máquina (⌘S en Mac, Ctrl+S si no).
11+// 4. Una escritura del agente repinta el árbol sin plegar lo que estaba
12+// abierto.
13+// 5. Renombrar mueve la pestaña abierta y lo dice; borrar cierra la pestaña;
14+// «Copiar ruta» lo dice.
15+// 6. El árbol se usa con el teclado (↓ y Enter) y Escape cierra su menú.
16+// 7. «Ir a símbolo» sin fichero abierto lo dice en vez de no hacer nada.
17+//
18+// BASE=http://127.0.0.1:8898 node tests/editor-save.mjs
19+import { chromium } from 'playwright';
20+const BASE = process.env.BASE || 'http://localhost:8799';
21+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
22+
23+const b = await chromium.launch();
24+const ctx = await b.newContext({ locale: 'es-ES' });
25+await ctx.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: BASE });
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+// proyecto sembrado ANTES de arrancar el IDE
31+await p.goto(BASE + '/manifest.json');
32+await p.evaluate(async () => {
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('README.md', '# Proyecto\n');
40+ await escribe('src/app.js', 'export const a = 1;\n');
41+ await escribe('src/util.js', 'export const u = 2;\n');
42+ await escribe('notes/todo.md', '- tarea\n');
43+});
44+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
45+await p.waitForFunction(() => window.monaco && document.querySelector('#tree .file'), null, { timeout: 30000 });
46+
47+const disco = (path) => p.evaluate(async (path) => {
48+ const parts = path.split('/'); const name = parts.pop(); let d = await navigator.storage.getDirectory();
49+ try { for (const x of parts) d = await d.getDirectoryHandle(x); return await (await (await d.getFileHandle(name)).getFile()).text(); }
50+ catch { return null; }
51+}, path);
52+const pestañas = () => p.evaluate(() => [...document.querySelectorAll('#tabs-bar .tab')].map(t => ({ path: t.dataset.path, dirty: !!t.querySelector('.dirty'), active: t.classList.contains('active') })));
53+const estado = () => p.evaluate(() => document.getElementById('statusbar').textContent);
54+const abre = async (path) => { await p.evaluate((path) => window.elffussClaw.openFile(path), path); await p.waitForTimeout(200); };
55+const escribeEnEditor = async (txt) => {
56+ await p.click('#editor .view-lines');
57+ await p.keyboard.press(process.platform === 'darwin' ? 'Meta+End' : 'Control+End');
58+ await p.keyboard.type(txt);
59+ await p.waitForTimeout(100);
60+};
61+const cerrarActiva = () => p.locator('#tabs-bar .tab.active').locator('.tab-x, b').first().click();
62+const dialogo = (val) => p.locator(`#dirty-dialog button[data-val="${val}"]`).click();
63+
64+// 1 · cerrar con cambios
65+await abre('src/app.js');
66+await escribeEnEditor('// cambio 1\n');
67+let tb = await pestañas();
68+ok('1 · la pestaña queda marcada con cambios (●)', tb.find(t => t.path === 'src/app.js')?.dirty, JSON.stringify(tb));
69+await cerrarActiva();
70+await p.waitForTimeout(150);
71+const hayDialogo = await p.locator('#dirty-dialog').isVisible().catch(() => false);
72+ok('1 · cerrar una pestaña con cambios pregunta', hayDialogo);
73+await dialogo('cancel');
74+tb = await pestañas();
75+ok('1 · Cancelar: la pestaña sigue abierta y con sus cambios', tb.some(t => t.path === 'src/app.js' && t.dirty), JSON.stringify(tb));
76+await cerrarActiva();
77+await dialogo('discard');
78+await p.waitForTimeout(150);
79+tb = await pestañas();
80+ok('1 · No guardar: se cierra y el disco no cambia', !tb.some(t => t.path === 'src/app.js') && (await disco('src/app.js')) === 'export const a = 1;\n', JSON.stringify(tb));
81+await abre('src/app.js');
82+await escribeEnEditor('// cambio 2\n');
83+await cerrarActiva();
84+await dialogo('save');
85+await p.waitForTimeout(250);
86+tb = await pestañas();
87+const tras = await disco('src/app.js');
88+ok('1 · Guardar: escribe en disco y cierra', !tb.some(t => t.path === 'src/app.js') && tras.includes('// cambio 2'), JSON.stringify({ tb, tras }));
89+
90+// 2 · File › Guardar
91+await abre('README.md');
92+await escribeEnEditor('linea nueva\n');
93+await p.click('#menubar button[data-menu="file"]');
94+const hint = await p.locator('#topmenu .menu-item', { hasText: 'Guardar' }).locator('span').textContent();
95+await p.locator('#topmenu .menu-item', { hasText: 'Guardar' }).click();
96+await p.waitForTimeout(250);
97+tb = await pestañas();
98+ok('2 · File › Guardar escribe el fichero', (await disco('README.md')).includes('linea nueva'));
99+ok('2 · …la pestaña deja de estar marcada y la barra de estado lo dice', !tb.find(t => t.path === 'README.md')?.dirty && /guardado/.test(await estado()), JSON.stringify(tb) + ' · ' + await estado());
100+const esMac = await p.evaluate(() => /Mac|iPhone|iPad/.test(navigator.platform || ''));
101+ok('3 · el atajo anunciado es el de esta máquina', hint === (esMac ? '⌘S' : 'Ctrl+S'), hint);
102+
103+// 2 · paleta › Guardar
104+await escribeEnEditor('otra linea\n');
105+await p.keyboard.press(process.platform === 'darwin' ? 'Meta+Shift+P' : 'Control+Shift+P');
106+await p.waitForSelector('#palette:not([hidden])');
107+await p.fill('#pal-input', '>Guardar');
108+await p.waitForTimeout(100);
109+await p.press('#pal-input', 'Enter');
110+await p.waitForTimeout(250);
111+ok('2 · la paleta › Guardar escribe el fichero', (await disco('README.md')).includes('otra linea'));
112+ok('2 · …y la paleta se cierra', await p.locator('#palette').isHidden());
113+
114+// 4 · el árbol no se pliega tras una escritura del agente
115+await p.locator('#tree summary', { hasText: 'src' }).click();
116+await p.locator('#tree summary', { hasText: 'notes' }).click();
117+await p.waitForTimeout(200);
118+await p.evaluate(async () => { const code = await import('/js/tools/code.js'); await code.write({ path: 'src/nuevo.js', content: 'export {}\n' }); });
119+await p.waitForTimeout(400);
120+const abiertas = await p.evaluate(() => [...document.querySelectorAll('#tree details[open] > summary')].map(s => s.dataset.path));
121+ok('4 · tras escribir el agente, src y notes siguen abiertas', abiertas.includes('src') && abiertas.includes('notes'), JSON.stringify(abiertas));
122+ok('4 · …y el fichero nuevo aparece dentro', await p.locator('#tree .file[data-path="src/nuevo.js"]').count() === 1);
123+
124+// 5 · renombrar, copiar ruta y borrar
125+await abre('src/util.js');
126+await p.evaluate(() => { window.prompt = () => 'util2.js'; window.confirm = () => true; });
127+await p.locator('#tree .file[data-path="src/util.js"]').click({ button: 'right' });
128+await p.locator('#tree-menu .tm-item', { hasText: 'Renombrar' }).click();
129+await p.waitForTimeout(400);
130+tb = await pestañas();
131+ok('5 · renombrar mueve la pestaña abierta a la ruta nueva', tb.some(t => t.path === 'src/util2.js') && !tb.some(t => t.path === 'src/util.js'), JSON.stringify(tb));
132+ok('5 · …y lo dice en la barra de estado', /Renombrado/.test(await estado()), await estado());
133+await p.locator('#tabs-bar .tab[data-path="src/util2.js"]').click({ button: 'right' });
134+await p.locator('#tab-menu .tm-item', { hasText: 'Copiar ruta' }).click();
135+await p.waitForTimeout(200);
136+ok('5 · «Copiar ruta» lo dice', /Ruta copiada|No pude copiar/.test(await estado()), await estado());
137+await p.locator('#tree .file[data-path="src/util2.js"]').click({ button: 'right' });
138+await p.locator('#tree-menu .tm-item', { hasText: 'Eliminar' }).click();
139+await p.waitForTimeout(400);
140+tb = await pestañas();
141+ok('5 · borrar el fichero cierra su pestaña', !tb.some(t => t.path === 'src/util2.js'), JSON.stringify(tb));
142+
143+// 6 · teclado en el árbol y Escape en su menú
144+await p.locator('#tree .file[data-path="README.md"]').focus();
145+await p.keyboard.press('ArrowUp');
146+const enfocado = await p.evaluate(() => document.activeElement?.dataset?.path);
147+ok('6 · ↑ mueve el foco por las filas del árbol', !!enfocado && enfocado !== 'README.md', enfocado);
148+await p.locator('#tree .file[data-path="src/app.js"]').focus();
149+await p.keyboard.press('Enter');
150+await p.waitForTimeout(250);
151+ok('6 · Enter en una fila de fichero lo abre', (await pestañas()).some(t => t.path === 'src/app.js' && t.active));
152+await p.keyboard.press('Shift+F10');
153+await p.waitForTimeout(100);
154+const menuAbierto = await p.locator('#tree-menu').count();
155+await p.keyboard.press('Escape');
156+await p.waitForTimeout(100);
157+ok('6 · Shift+F10 abre el menú del árbol y Escape lo cierra', menuAbierto === 1 && await p.locator('#tree-menu').count() === 0);
158+
159+// 7 · Ir a símbolo sin fichero abierto
160+await p.evaluate(() => { for (const x of document.querySelectorAll('#tabs-bar .tab-x')) x.click(); });
161+await p.waitForTimeout(300);
162+await p.click('#menubar button[data-menu="edit"]');
163+await p.locator('#topmenu .menu-item', { hasText: 'Ir a símbolo' }).click();
164+await p.waitForTimeout(150);
165+ok('7 · «Ir a símbolo» sin fichero abierto lo dice', /Abre un fichero primero/.test(await estado()), await estado());
166+
167+console.log('\n errores JS:', errs[0] || 'ninguno');
168+ok('sin errores de página', errs.length === 0, errs.join(' | '));
169+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ EDITOR: GUARDAR, CERRAR CON CAMBIOS Y ÁRBOL OK');
170+await b.close();
171+process.exit(fails ? 1 : 0);
modified tests/htmlpreview.mjs +1 −1
@@ -6,7 +6,7 @@
66 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
77
88 const b = await chromium.launch();
9-const ctx = await b.newContext();
9+const ctx = await b.newContext({ locale: 'es-ES' }); // los menús hablan el idioma del navegador; este test mira los textos en español
1010 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
1111 const p = await ctx.newPage();
1212 await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
modified tests/htmlpreview_css.mjs +1 −1
@@ -7,7 +7,7 @@
77 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
88
99 const b = await chromium.launch();
10-const ctx = await b.newContext();
10+const ctx = await b.newContext({ locale: 'es-ES' }); // los menús hablan el idioma del navegador; este test mira los textos en español
1111 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
1212 const p = await ctx.newPage();
1313 await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
modified tests/previewstorage.mjs +1 −1
@@ -10,7 +10,7 @@
1010 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
1111
1212 const b = await chromium.launch();
13-const ctx = await b.newContext();
13+const ctx = await b.newContext({ locale: 'es-ES' }); // los menús hablan el idioma del navegador; este test mira los textos en español
1414 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
1515 const p = await ctx.newPage();
1616 const pageErrors = [];
modified tests/tabmenu.mjs +1 −1
@@ -5,7 +5,7 @@
55 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
66
77 const b = await chromium.launch();
8-const ctx = await b.newContext();
8+const ctx = await b.newContext({ locale: 'es-ES' }); // los menús hablan el idioma del navegador; este test mira los textos en español
99 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
1010 const p = await ctx.newPage();
1111 await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
modified web/css/code.css +19 −3
@@ -112,6 +112,10 @@
112112 #tree .chevron { transition: transform .12s; }
113113 #tree summary:hover, #tree .file:hover { color: #fff; background: #ffffff0a; border-radius: 4px; }
114114 #tree .file { cursor: pointer; display: flex; align-items: center; gap: 5px; padding: 2px 0 2px 16px; color: #b8c0d4; }
115+#tree .file.active { color: #fff; background: #ffffff12; border-radius: 4px; }
116+#tree summary:focus-visible, #tree .file:focus-visible { outline: 2px solid var(--accent2); outline-offset: -2px; border-radius: 4px; }
117+#tree .tree-more { color: var(--muted); font-size: .74rem; padding: 2px 0 2px 16px; font-style: italic; }
118+.tm-item:focus-visible { outline: 2px solid var(--accent2); outline-offset: -2px; }
115119 .fico { flex: 0 0 auto; vertical-align: -3px; }
116120
117121 #editor-wrap { display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
@@ -120,10 +124,22 @@
120124 .tab.active { background: var(--bg); color: var(--fg); box-shadow: inset 0 2px 0 var(--accent); }
121125 .tab.tab-preview .tab-name { font-style: italic; }
122126 .tab .tab-ico { display: flex; }
123-.tab b { cursor: pointer; opacity: .55; width: 14px; text-align: center; }
124-.tab b:hover { opacity: 1; color: var(--accent); }
125-.tab b.dirty { opacity: 1; color: var(--fg); }
127+.tab b, .tab .tab-x { cursor: pointer; opacity: .55; width: 16px; text-align: center; }
128+.tab .tab-x { background: none; border: none; color: inherit; padding: 0; font: inherit; line-height: 1; border-radius: 4px; }
129+.tab b:hover, .tab .tab-x:hover { opacity: 1; color: var(--accent); }
130+.tab b.dirty, .tab .tab-x.dirty { opacity: 1; color: var(--fg); }
126131 .tab b.dirty:hover::before { content: ''; }
132+.tab:focus-visible, .tab .tab-x:focus-visible { outline: 2px solid var(--accent2); outline-offset: -2px; }
133+.tab .tab-name.deleted { text-decoration: line-through; }
134+/* «¿Guardar los cambios?» al cerrar una pestaña con cambios sin guardar */
135+#dirty-dialog { background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 12px; padding: 16px 18px; max-width: min(420px, 92vw); box-shadow: 0 18px 50px rgba(0,0,0,.6); }
136+#dirty-dialog::backdrop { background: rgba(0,0,0,.45); }
137+#dirty-dialog .dd-title { margin: 0 0 4px; font-weight: 600; }
138+#dirty-dialog .dd-sub { margin: 0 0 14px; color: var(--muted); font-size: .85rem; }
139+#dirty-dialog .dd-row { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
140+#dirty-dialog button { background: var(--bg3); color: var(--fg); border: 1px solid var(--line); border-radius: 8px; padding: 7px 14px; cursor: pointer; font: inherit; font-size: .85rem; }
141+#dirty-dialog button.dd-primary { background: linear-gradient(135deg, var(--accent), var(--accent2)); color: #fff; border: none; }
142+#dirty-dialog button:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
127143 #editor { flex: 1; min-height: 0; }
128144 #editor-empty { position: absolute; inset: 34px 0 22px 0; display: none; flex-direction: column; align-items: center; justify-content: center; gap: 14px; background: var(--bg); color: var(--muted); z-index: 2; text-align: center; }
129145 #editor-empty img { width: 84px; opacity: .5; }
modified web/index.html +1 −1
@@ -118,7 +118,7 @@
118118 </div>
119119 <div id="terminal-host"></div>
120120 </div>
121- <div id="statusbar"></div>
121+ <div id="statusbar" role="status" aria-live="polite"></div>
122122 </section>
123123 <section id="chat">
124124 <button type="button" id="btn-ancho" title="Ensanchar el chat a toda la ventana (vuelve a pulsar para recuperar el editor)">⇔</button>
modified web/js/i18n.js +36 −2
@@ -39,7 +39,7 @@
3939 autoOn: 'Editar archivos automáticamente (clic para revisar antes)',
4040 autoOff: 'Pedir confirmación antes de escribir (clic para automático)',
4141 pSearchCode: 'Buscar en el código…', pManageSkills: 'Gestionar skills', pToggleExplorer: 'Alternar explorador',
42- pToggleTerm: 'Alternar terminal', pSave: 'Guardar (Ctrl+S)', palCmd: 'comando',
42+ pToggleTerm: 'Alternar terminal', pSave: 'Guardar ({k})', palCmd: 'comando',
4343 palGotoSym: 'Ir a símbolo en el editor…', palEmpty: 'Sin resultados',
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…',
@@ -131,6 +131,23 @@
131131 hwPhaseGroup: "Hard Work · fundiendo {g}/{n}",
132132 hwResult: "⛏ Hard Work (RLM): {n} partes, {k} con señal.",
133133 hwFailed: "Hard Work falló: {e}",
134+ // editor: guardar, cerrar con cambios, pestañas y árbol
135+ saved: "💾 {path} guardado", saveFailed: "No pude guardar {path}: {e}", noFileOpen: "Abre un fichero primero",
136+ openFailed: "No pude abrir {path}: {e}",
137+ dirtyTitle: "¿Guardar los cambios de «{name}»?", dirtyBody: "Si no los guardas, se pierden.",
138+ dirtySave: "Guardar", dirtyDiscard: "No guardar", dirtyCancel: "Cancelar",
139+ editorTabs: "Ficheros abiertos", closeFile: "Cerrar {name}", closeFileDirty: "Cerrar {name} (cambios sin guardar)",
140+ fileDeletedDirty: "borrado del disco; guárdalo para recrearlo",
141+ tmClose: "Cerrar", tmCloseOthers: "Cerrar otras", tmCloseRight: "Cerrar las de la derecha", tmCloseAll: "Cerrar todas",
142+ tmCopyPath: "Copiar ruta", tmViewSource: "Ver código fuente", tmPreview: "Vista previa",
143+ tmNewFile: "Nuevo archivo…", tmNewFolder: "Nueva carpeta…", tmOpen: "Abrir", tmRename: "Renombrar…", tmDelete: "Eliminar",
144+ promptNewFile: "Nombre del nuevo archivo:", promptNewFolder: "Nombre de la nueva carpeta:", promptRename: "Nuevo nombre:",
145+ confirmDelete: "¿Eliminar «{name}»?", opFailed: "No se pudo: {e}",
146+ created: "Creado «{name}»", renamed: "Renombrado «{from}» → «{to}»", deleted: "Eliminado «{name}»",
147+ pathCopied: "Ruta copiada: {path}", pathCopyFailed: "No pude copiar la ruta (el navegador no dejó usar el portapapeles)",
148+ explorer: "Explorador del proyecto", treeMore: "… y {n} más (no se muestran)",
149+ editorEmpty: "Abre un fichero del explorador, o pídele algo a la elfa.",
150+ mPalette: "Paleta de comandos",
134151 },
135152 en: {
136153 ph: 'Type here… (@ attaches a file)',
@@ -165,7 +182,7 @@
165182 autoOn: 'Edit files automatically (click to review first)',
166183 autoOff: 'Ask before writing (click for automatic)',
167184 pSearchCode: 'Search the code…', pManageSkills: 'Manage skills', pToggleExplorer: 'Toggle explorer',
168- pToggleTerm: 'Toggle terminal', pSave: 'Save (Ctrl+S)', palCmd: 'command',
185+ pToggleTerm: 'Toggle terminal', pSave: 'Save ({k})', palCmd: 'command',
169186 palGotoSym: 'Go to symbol in editor…', palEmpty: 'No results',
170187 mNewFile: 'New file…', promptNewPath: 'New file path:', mSave: 'Save', mOpenFolder: 'Open folder…',
171188 mSearchCode: 'Search the code', mGotoFile: 'Go to file…', mGotoSym: 'Go to symbol…',
@@ -257,6 +274,23 @@
257274 hwPhaseGroup: "Hard Work · merging {g}/{n}",
258275 hwResult: "⛏ Hard Work (RLM): {n} chunks, {k} with signal.",
259276 hwFailed: "Hard Work failed: {e}",
277+ // editor: save, close with changes, tabs and tree
278+ saved: "💾 {path} saved", saveFailed: "Couldn't save {path}: {e}", noFileOpen: "Open a file first",
279+ openFailed: "Couldn't open {path}: {e}",
280+ dirtyTitle: "Save the changes to “{name}”?", dirtyBody: "If you don't save them, they are lost.",
281+ dirtySave: "Save", dirtyDiscard: "Don't save", dirtyCancel: "Cancel",
282+ editorTabs: "Open files", closeFile: "Close {name}", closeFileDirty: "Close {name} (unsaved changes)",
283+ fileDeletedDirty: "deleted from disk; save it to recreate it",
284+ tmClose: "Close", tmCloseOthers: "Close others", tmCloseRight: "Close to the right", tmCloseAll: "Close all",
285+ tmCopyPath: "Copy path", tmViewSource: "View source", tmPreview: "Preview",
286+ tmNewFile: "New file…", tmNewFolder: "New folder…", tmOpen: "Open", tmRename: "Rename…", tmDelete: "Delete",
287+ promptNewFile: "Name of the new file:", promptNewFolder: "Name of the new folder:", promptRename: "New name:",
288+ confirmDelete: "Delete “{name}”?", opFailed: "Couldn't do it: {e}",
289+ created: "Created “{name}”", renamed: "Renamed “{from}” → “{to}”", deleted: "Deleted “{name}”",
290+ pathCopied: "Path copied: {path}", pathCopyFailed: "Couldn't copy the path (the browser blocked the clipboard)",
291+ explorer: "Project explorer", treeMore: "… and {n} more (not shown)",
292+ editorEmpty: "Open a file from the explorer, or ask the elf for something.",
293+ mPalette: "Command palette",
260294 },
261295 };
262296
modified web/js/ide.js +339 −63
@@ -2,6 +2,7 @@
22 import * as code from './tools/code.js';
33 import { fileIcon, folderIcon } from './icons.js';
44 import { renderMarkdown } from './md.js';
5+import { t } from './i18n.js';
56
67 let editor = null;
78 let monacoRef = null;
@@ -71,6 +72,9 @@
7172 editor?.getAction(actionId)?.run();
7273 }
7374 export function hasEditor() { return !!editor; }
75+// La ruta del fichero activo (o null): el menú la usa para no lanzar acciones
76+// del editor que no hacen nada sin un fichero abierto.
77+export function activeFile() { return active; }
7478
7579 export async function openFile(path) {
7680 let tab = tabs.find(t => t.path === path);
@@ -85,7 +89,7 @@
8589 const base = path.split('/').pop();
8690 const hits = await code.findByName?.(base, 2).catch(() => []) || [];
8791 if (hits.length === 1 && hits[0] !== path) return openFile(hits[0]);
88- return alertBar('No pude abrir ' + path + ': ' + e.message);
92+ return alertBar(t('openFailed', { path, e: e.message }));
8993 }
9094 tab = { path, model: monacoRef.editor.createModel(content, langOf(path)), dirty: false, preview: false };
9195 tabs.push(tab);
@@ -194,18 +198,96 @@
194198 await applyView();
195199 }
196200
197-async function saveActive() {
198- const tab = tabs.find(t => t.path === active);
199- if (!tab) return;
200- await code.write({ path: tab.path, content: tab.model.getValue() });
201+// Guardar lo que TÚ has escrito va directo al fichero, no por code.write: esa
202+// es la vía del agente, con su aprobación («Elffuss quiere escribir…», que
203+// salía al guardar tu propio fichero con Auto apagado) y sus guardas contra
204+// reescrituras que recortan medio fichero, que bloqueaban un guardado tuyo
205+// legítimo sin decir nada.
206+async function writeOwn(path, content) {
207+ const parts = path.split('/').filter(Boolean);
208+ const name = parts.pop();
209+ let dir = code.handle();
210+ for (const s of parts) dir = await dir.getDirectoryHandle(s, { create: true });
211+ const w = await (await dir.getFileHandle(name, { create: true })).createWritable();
212+ await w.write(content);
213+ await w.close();
214+ code.invalidateFileList?.();
215+}
216+async function saveTab(tab) {
217+ try {
218+ await writeOwn(tab.path, tab.model.getValue());
219+ } catch (e) {
220+ alertBar(t('saveFailed', { path: tab.path, e: e?.message || e }));
221+ return false;
222+ }
201223 tab.dirty = false;
224+ tab.deleted = false;
202225 renderTabs();
203- alertBar('💾 ' + tab.path + ' guardado');
226+ alertBar(t('saved', { path: tab.path }));
227+ return true;
228+}
229+// Exportada: la usan el menú File › Guardar y la paleta. Antes ellos lanzaban
230+// la acción 'workbench.action.files.save', que no existe en el Monaco suelto,
231+// y no pasaba nada.
232+export async function saveActive() {
233+ const tab = tabs.find(t => t.path === active);
234+ if (!tab) { alertBar(t('noFileOpen')); return false; }
235+ return saveTab(tab);
236+}
237+
238+// Cerrar una pestaña con cambios sin guardar PREGUNTA: Guardar, No guardar o
239+// Cancelar. Antes se cerraba y los cambios se perdían sin aviso.
240+function askDirty(tab) {
241+ return new Promise(resolve => {
242+ const dlg = document.createElement('dialog');
243+ dlg.id = 'dirty-dialog';
244+ dlg.setAttribute('aria-labelledby', 'dirty-title');
245+ const h = document.createElement('p'); h.id = 'dirty-title'; h.className = 'dd-title';
246+ h.textContent = t('dirtyTitle', { name: baseOf(tab.path) });
247+ const sub = document.createElement('p'); sub.className = 'dd-sub'; sub.textContent = t('dirtyBody');
248+ const row = document.createElement('div'); row.className = 'dd-row';
249+ let answer = 'cancel';
250+ const mk = (label, val, cls) => {
251+ const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.dataset.val = val;
252+ if (cls) b.className = cls;
253+ b.onclick = () => { answer = val; dlg.close(); };
254+ row.appendChild(b); return b;
255+ };
256+ const save = mk(t('dirtySave'), 'save', 'dd-primary');
257+ mk(t('dirtyDiscard'), 'discard');
258+ mk(t('dirtyCancel'), 'cancel');
259+ dlg.append(h, sub, row);
260+ dlg.addEventListener('close', () => { dlg.remove(); resolve(answer); }, { once: true });
261+ document.body.appendChild(dlg);
262+ dlg.showModal();
263+ save.focus();
264+ });
204265 }
205266
267+// Devuelve false si el usuario canceló (la pestaña sigue abierta).
206268 async function closeTab(path) {
207269 const i = tabs.findIndex(t => t.path === path);
208- if (i < 0) return;
270+ if (i < 0) return true;
271+ if (tabs[i].dirty) {
272+ const r = await askDirty(tabs[i]);
273+ if (r === 'cancel') return false;
274+ if (r === 'save' && !(await saveTab(tabs[i]))) return false;
275+ }
276+ const j = tabs.findIndex(t => t.path === path); // el diálogo es asíncrono
277+ if (j < 0) return true;
278+ closeTabNow(j);
279+ renderTabs();
280+ await applyView();
281+ return true;
282+}
283+// Varias seguidas («Cerrar otras/todas»): se para en la primera que cancelas.
284+async function closeTabs(paths) {
285+ for (const p of paths) if (!(await closeTab(p))) return false;
286+ return true;
287+}
288+
289+function closeTabNow(i) {
290+ const path = tabs[i].path;
209291 tabs[i].model.dispose();
210292 tabs.splice(i, 1);
211293 if (active === path) {
@@ -214,8 +296,6 @@
214296 if (active) { editor.setModel(tabs.find(t => t.path === active).model); setEmptyState(false); }
215297 else { editor.setModel(monacoRef.editor.createModel('', 'plaintext')); setEmptyState(true); }
216298 }
217- renderTabs();
218- await applyView();
219299 }
220300
221301 // Estado vacío: cuando no hay ningún fichero abierto, en vez de dejar el Monaco
@@ -225,7 +305,8 @@
225305 if (!el) {
226306 el = document.createElement('div');
227307 el.id = 'editor-empty';
228- el.innerHTML = '<img src="img/elffuss-code.svg" alt=""><p>Abre un fichero del explorador,<br>o pídele algo a la elfa.</p>';
308+ el.innerHTML = '<img src="img/elffuss-code.svg" alt=""><p></p>';
309+ el.querySelector('p').textContent = t('editorEmpty');
229310 $('editor').parentElement.appendChild(el);
230311 }
231312 el.style.display = on ? 'flex' : 'none';
@@ -234,60 +315,125 @@
234315 function renderTabs() {
235316 const bar = $('tabs-bar');
236317 bar.replaceChildren();
237- for (const t of tabs) {
318+ bar.setAttribute('role', 'tablist');
319+ bar.setAttribute('aria-label', t('editorTabs'));
320+ for (const tb of tabs) {
238321 const el = document.createElement('div');
239- el.className = 'tab' + (t.path === active ? ' active' : '') + (t.preview ? ' tab-preview' : '');
240- el.dataset.path = t.path;
322+ const on = tb.path === active;
323+ el.className = 'tab' + (on ? ' active' : '') + (tb.preview ? ' tab-preview' : '');
324+ el.dataset.path = tb.path;
325+ // Pestañas de verdad para el teclado y los lectores de pantalla: antes eran
326+ // <div> sin foco. La activa entra con Tab; ←/→ se mueven entre ellas.
327+ el.setAttribute('role', 'tab');
328+ el.setAttribute('aria-selected', on ? 'true' : 'false');
329+ el.tabIndex = on ? 0 : -1;
241330 const ico = document.createElement('span');
242331 ico.className = 'tab-ico';
243- ico.innerHTML = fileIcon(t.path.split('/').pop());
332+ ico.innerHTML = fileIcon(tb.path.split('/').pop());
244333 const name = document.createElement('span');
245334 name.className = 'tab-name';
246- name.textContent = t.path.split('/').pop();
247- name.title = t.path;
248- // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón
249- const x = document.createElement('b');
250- x.className = t.dirty ? 'dirty' : '';
251- x.textContent = t.dirty ? '●' : '×';
252- x.onclick = e => { e.stopPropagation(); closeTab(t.path); };
335+ name.textContent = tb.path.split('/').pop();
336+ name.title = tb.deleted ? tb.path + ' · ' + t('fileDeletedDirty') : tb.path;
337+ if (tb.deleted) name.classList.add('deleted');
338+ // como VS Code: punto ● si hay cambios sin guardar; × al pasar el ratón.
339+ // Un <button> con nombre accesible (antes un <b> que no recibía el foco).
340+ const x = document.createElement('button');
341+ x.type = 'button';
342+ x.className = 'tab-x' + (tb.dirty ? ' dirty' : '');
343+ x.textContent = tb.dirty ? '●' : '×';
344+ x.tabIndex = -1;
345+ x.setAttribute('aria-label', t(tb.dirty ? 'closeFileDirty' : 'closeFile', { name: baseOf(tb.path) }));
346+ x.title = x.getAttribute('aria-label');
347+ x.onclick = e => { e.stopPropagation(); closeTab(tb.path); };
253348 el.append(ico, name, x);
254- el.onclick = () => openFile(t.path);
255- el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, t.path); };
349+ el.onclick = () => openFile(tb.path);
350+ el.oncontextmenu = e => { e.preventDefault(); openTabMenu(e.clientX, e.clientY, tb.path); };
351+ el.onkeydown = e => {
352+ const i = tabs.indexOf(tb);
353+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
354+ e.preventDefault();
355+ const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
356+ if (next) openFile(next.path).then(() => bar.querySelector('.tab.active')?.focus());
357+ } else if (e.key === 'Delete' || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'w')) {
358+ e.preventDefault(); closeTab(tb.path);
359+ } else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
360+ e.preventDefault(); const r = el.getBoundingClientRect(); openTabMenu(r.left, r.bottom, tb.path);
361+ }
362+ };
256363 bar.appendChild(el);
257364 }
365+ markActive();
366+}
367+
368+// ---------- menús contextuales (pestañas y árbol): teclado y Escape ----------
369+// Escape los cierra y el foco vuelve a donde estaba; ↑/↓ recorren las opciones.
370+function wireMenu(menu, returnFocus) {
371+ menu.setAttribute('role', 'menu');
372+ const items = () => [...menu.querySelectorAll('[role="menuitem"]')];
373+ const close = () => { menu.remove(); document.removeEventListener('mousedown', outside); returnFocus?.focus?.(); };
374+ const outside = ev => { if (!menu.contains(ev.target)) close(); };
375+ menu.addEventListener('keydown', e => {
376+ const list = items(), i = list.indexOf(document.activeElement);
377+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
378+ else if (e.key === 'ArrowDown') { e.preventDefault(); list[(i + 1) % list.length]?.focus(); }
379+ else if (e.key === 'ArrowUp') { e.preventDefault(); list[(i - 1 + list.length) % list.length]?.focus(); }
380+ });
381+ setTimeout(() => document.addEventListener('mousedown', outside), 0);
382+ // dentro de la ventana aunque se abra pegado al borde
383+ const r = menu.getBoundingClientRect();
384+ if (r.right > innerWidth) menu.style.left = Math.max(4, innerWidth - r.width - 4) + 'px';
385+ if (r.bottom > innerHeight) menu.style.top = Math.max(4, innerHeight - r.height - 4) + 'px';
386+ items()[0]?.focus();
387+ return close;
388+}
389+function menuButton(label, fn, cls) {
390+ const b = document.createElement('button');
391+ b.type = 'button';
392+ b.className = 'tm-item' + (cls ? ' ' + cls : '');
393+ b.setAttribute('role', 'menuitem');
394+ b.textContent = label;
395+ b.dataset.run = '1';
396+ b._run = fn;
397+ return b;
258398 }
259399
260400 // ---------- menú contextual de las pestañas (botón derecho, estilo VS Code) ----------
261401 function openTabMenu(x, y, path) {
262402 document.getElementById('tab-menu')?.remove();
403+ const volver = document.activeElement;
263404 const menu = document.createElement('div');
264405 menu.id = 'tab-menu';
265406 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
266- const i = tabs.findIndex(t => t.path === path);
407+ const i = tabs.findIndex(tb => tb.path === path);
267408 const tab = tabs[i];
268409 const items = [];
269- items.push(['Cerrar', () => closeTab(path)]);
270- items.push(['Cerrar otras', () => { for (const t of tabs.filter(t => t.path !== path)) closeTab(t.path); }]);
271- const toTheRight = tabs.slice(i + 1).map(t => t.path);
272- if (toTheRight.length) items.push(['Cerrar las de la derecha', () => { for (const p of toTheRight) closeTab(p); }]);
273- items.push(['Cerrar todas', () => { for (const t of [...tabs]) closeTab(t.path); }]);
410+ items.push([t('tmClose'), () => closeTab(path)]);
411+ items.push([t('tmCloseOthers'), () => closeTabs(tabs.filter(tb => tb.path !== path).map(tb => tb.path))]);
412+ const toTheRight = tabs.slice(i + 1).map(tb => tb.path);
413+ if (toTheRight.length) items.push([t('tmCloseRight'), () => closeTabs(toTheRight)]);
414+ items.push([t('tmCloseAll'), () => closeTabs(tabs.map(tb => tb.path))]);
274415 items.push(['sep']);
275- items.push(['Copiar ruta', () => navigator.clipboard?.writeText(path).catch(() => {})]);
416+ items.push([t('tmCopyPath'), () => copyPath(path)]);
276417 if (PREVIEWABLE.has(langOf(path))) {
277- items.push([tab?.preview ? 'Ver código fuente' : 'Vista previa', () => togglePreview(path)]);
418+ items.push([tab?.preview ? t('tmViewSource') : t('tmPreview'), () => togglePreview(path)]);
278419 }
420+ let close = () => menu.remove();
279421 for (const item of items) {
280- if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep' })); continue; }
422+ if (item[0] === 'sep') { menu.appendChild(Object.assign(document.createElement('div'), { className: 'tm-sep', role: 'separator' })); continue; }
281423 const [label, fn] = item;
282- const b = document.createElement('button');
283- b.className = 'tm-item';
284- b.textContent = label;
285- b.onclick = () => { menu.remove(); fn(); };
424+ const b = menuButton(label, fn);
425+ b.onclick = () => { close(); fn(); };
286426 menu.appendChild(b);
287427 }
288428 document.body.appendChild(menu);
289- const close = ev => { if (!menu.contains(ev.target)) { menu.remove(); document.removeEventListener('mousedown', close); } };
290- setTimeout(() => document.addEventListener('mousedown', close), 0);
429+ close = wireMenu(menu, volver);
430+}
431+
432+// Copiar ruta: antes copiaba sin decir nada.
433+function copyPath(path) {
434+ const done = () => alertBar(t('pathCopied', { path }));
435+ if (navigator.clipboard?.writeText) navigator.clipboard.writeText(path).then(done, () => alertBar(t('pathCopyFailed')));
436+ else alertBar(t('pathCopyFailed'));
291437 }
292438
293439 let alertTimer;
@@ -301,15 +447,54 @@
301447 // ---------- árbol lateral ----------
302448 const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
303449
450+// Carpetas abiertas, por ruta. refreshTree() reconstruye el árbol entero (cada
451+// escritura del agente, cada orden del terminal que toca ficheros, crear,
452+// renombrar o borrar) y antes lo dejaba TODO plegado: perdías el sitio tras
453+// cada edición. Ahora se vuelven a abrir las que lo estaban.
454+const openDirs = new Set();
455+
304456 export async function refreshTree(handle = null) {
305457 const rootHandle = handle || window.__elffussProject;
306458 if (!rootHandle) return;
459+ if (handle) openDirs.clear(); // otro proyecto: empieza plegado
307460 window.__elffussProject = rootHandle;
308461 const cont = $('tree');
309- cont.replaceChildren(await renderDir(rootHandle, ''));
462+ const scroll = cont.scrollTop;
463+ const conFoco = cont.contains(document.activeElement) ? document.activeElement.dataset?.path : null;
464+ const ul = await renderDir(rootHandle, '');
465+ ul.setAttribute('role', 'tree');
466+ ul.setAttribute('aria-label', t('explorer'));
467+ cont.replaceChildren(ul);
468+ cont.scrollTop = scroll;
469+ markActive();
470+ if (conFoco != null) {
471+ const f = cont.querySelector(`[data-path="${CSS.escape(conFoco)}"]`);
472+ if (f) { setRoving(f); f.focus(); }
473+ }
310474 setupTreeMenu();
311475 }
312476
477+// El fichero abierto se marca en el árbol (antes no había forma de saber cuál
478+// era), y es la fila por la que entra el foco con Tab.
479+function markActive() {
480+ const cont = $('tree');
481+ if (!cont) return;
482+ let fila = null;
483+ for (const f of cont.querySelectorAll('.file')) {
484+ const on = f.dataset.path === active;
485+ f.classList.toggle('active', on);
486+ f.setAttribute('aria-selected', on ? 'true' : 'false');
487+ if (on) fila = f;
488+ }
489+ if (!cont.querySelector('[tabindex="0"]') || fila) setRoving(fila || cont.querySelector('summary, .file'));
490+}
491+function setRoving(row) {
492+ if (!row) return;
493+ for (const r of $('tree').querySelectorAll('[tabindex="0"]')) if (r !== row) r.tabIndex = -1;
494+ row.tabIndex = 0;
495+}
496+const visibleRows = () => [...$('tree').querySelectorAll('summary, .file')].filter(r => r.offsetParent !== null);
497+
313498 // ---------- menú contextual del árbol (botón derecho, estilo VS Code) ----------
314499 let treeMenuWired = false;
315500 function setupTreeMenu() {
@@ -323,6 +508,33 @@
323508 const kind = node ? node.dataset.kind : 'directory'; // vacío = raíz
324509 openTreeMenu(e.clientX, e.clientY, path, kind);
325510 });
511+ // Teclado, como un árbol de verdad: ↑/↓ entre filas visibles, → abre una
512+ // carpeta, ← la cierra (o sube a la carpeta madre), Enter abre el fichero,
513+ // Shift+F10 o la tecla de menú abren el menú contextual. Antes las filas de
514+ // fichero eran <span> sin foco y el árbol solo se usaba con el ratón.
515+ tree.addEventListener('keydown', e => {
516+ const row = e.target.closest?.('summary, .file');
517+ if (!row) return;
518+ const rows = visibleRows(), i = rows.indexOf(row);
519+ const go = r => { if (r) { e.preventDefault(); setRoving(r); r.focus(); } };
520+ const det = row.tagName === 'SUMMARY' ? row.parentElement : null;
521+ if (e.key === 'ArrowDown') go(rows[i + 1]);
522+ else if (e.key === 'ArrowUp') go(rows[i - 1]);
523+ else if (e.key === 'Home') go(rows[0]);
524+ else if (e.key === 'End') go(rows[rows.length - 1]);
525+ else if (e.key === 'ArrowRight' && det) { e.preventDefault(); if (!det.open) det.open = true; else go(rows[i + 1]); }
526+ else if (e.key === 'ArrowLeft') {
527+ if (det && det.open) { e.preventDefault(); det.open = false; }
528+ else go(row.closest('li')?.parentElement?.closest('details')?.querySelector(':scope > summary'));
529+ }
530+ else if (e.key === 'Enter' && !det) { e.preventDefault(); openFile(row.dataset.path); }
531+ else if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
532+ e.preventDefault();
533+ const r = row.getBoundingClientRect();
534+ openTreeMenu(r.left + 12, r.bottom, row.dataset.path, row.dataset.kind);
535+ }
536+ });
537+ tree.addEventListener('focusin', e => { const row = e.target.closest?.('summary, .file'); if (row) setRoving(row); });
326538 }
327539
328540 // resuelve el handle de un directorio por su ruta (segmentos desde la raíz)
@@ -343,16 +555,18 @@
343555 const dir = await dirByPath(parentOf(path));
344556 await dir.removeEntry(baseOf(path), { recursive: kind === 'directory' });
345557 }
346-// copia recursiva (la File System API no tiene rename nativo)
558+// copia recursiva (la File System API no tiene rename nativo). El fichero se
559+// copia como Blob, no como texto: pasarlo por .text() estropeaba cualquier
560+// binario (una imagen, un .zip) al renombrarlo.
347561 async function fsCopy(srcDir, name, dstDir, newName) {
348562 const src = await (srcDir.getDirectoryHandle(name).catch(() => null));
349563 if (src) { // directorio
350564 const nd = await dstDir.getDirectoryHandle(newName, { create: true });
351565 for await (const e of src.values()) await fsCopy(src, e.name, nd, e.name);
352566 } else { // fichero
353- const text = await (await (await srcDir.getFileHandle(name)).getFile()).text();
567+ const file = await (await srcDir.getFileHandle(name)).getFile();
354568 const fh = await dstDir.getFileHandle(newName, { create: true });
355- const w = await fh.createWritable(); await w.write(text); await w.close();
569+ const w = await fh.createWritable(); await w.write(file); await w.close();
356570 }
357571 }
358572 async function fsRename(path, kind, newName) {
@@ -361,54 +575,93 @@
361575 await parent.removeEntry(baseOf(path), { recursive: kind === 'directory' });
362576 }
363577
578+// Lo que cuelga de `path` (el fichero o todo lo que hay dentro de la carpeta).
579+const under = (p, path, kind) => kind === 'directory' ? p.startsWith(path + '/') : p === path;
580+
581+// Renombrar mueve también las pestañas abiertas: antes seguían apuntando a la
582+// ruta vieja, y guardar recreaba el fichero con el nombre antiguo.
583+function renameTabs(path, nuevo, kind) {
584+ for (const tb of tabs) if (under(tb.path, path, kind)) {
585+ const np = kind === 'directory' ? nuevo + tb.path.slice(path.length) : nuevo;
586+ if (active === tb.path) { active = np; code.setCurrentFile(np); }
587+ tb.path = np;
588+ }
589+ for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) { openDirs.delete(d); openDirs.add(nuevo + d.slice(path.length)); }
590+ renderTabs();
591+}
592+// Borrar cierra sus pestañas. Si una tenía cambios sin guardar no se tira: se
593+// queda abierta y marcada (guardarla vuelve a crear el fichero).
594+function dropTabs(path, kind) {
595+ for (let i = tabs.length - 1; i >= 0; i--) {
596+ if (!under(tabs[i].path, path, kind)) continue;
597+ if (tabs[i].dirty) tabs[i].deleted = true;
598+ else closeTabNow(i);
599+ }
600+ for (const d of [...openDirs]) if (d === path || d.startsWith(path + '/')) openDirs.delete(d);
601+ renderTabs();
602+ applyView();
603+}
604+
364605 function openTreeMenu(x, y, path, kind) {
365606 document.getElementById('tree-menu')?.remove();
607+ const volver = document.activeElement;
366608 const menu = document.createElement('div');
367609 menu.id = 'tree-menu';
368610 menu.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:200`;
369611 // en un fichero, el "aquí dentro" es su carpeta; en carpeta/raíz, ella misma
370612 const container = kind === 'file' ? parentOf(path) : path;
371613 const items = [];
372- items.push(['Nuevo archivo…', async () => {
373- const name = prompt('Nombre del nuevo archivo:'); if (!name) return;
614+ items.push([t('tmNewFile'), async () => {
615+ const name = prompt(t('promptNewFile')); if (!name?.trim()) return;
616+ if (container) openDirs.add(container);
374617 await fsCreate(container, name.trim(), false); code.invalidateFileList?.();
375618 await refreshTree(); openFile(container ? container + '/' + name.trim() : name.trim());
376619 }]);
377- items.push(['Nueva carpeta…', async () => {
378- const name = prompt('Nombre de la nueva carpeta:'); if (!name) return;
620+ items.push([t('tmNewFolder'), async () => {
621+ const name = prompt(t('promptNewFolder')); if (!name?.trim()) return;
622+ if (container) openDirs.add(container);
379623 await fsCreate(container, name.trim(), true); code.invalidateFileList?.(); await refreshTree();
624+ alertBar(t('created', { name: name.trim() }));
380625 }]);
381626 if (path) {
382- if (kind === 'file') items.push(['Abrir', () => openFile(path)]);
383- if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push(['Vista previa', () => togglePreview(path)]);
384- items.push(['Renombrar…', async () => {
385- const name = prompt('Nuevo nombre:', baseOf(path)); if (!name || name === baseOf(path)) return;
386- await fsRename(path, kind, name.trim()); code.invalidateFileList?.(); await refreshTree();
627+ if (kind === 'file') items.push([t('tmOpen'), () => openFile(path)]);
628+ if (kind === 'file' && PREVIEWABLE.has(langOf(path))) items.push([t('tmPreview'), () => togglePreview(path)]);
629+ items.push([t('tmRename'), async () => {
630+ const name = prompt(t('promptRename'), baseOf(path))?.trim(); if (!name || name === baseOf(path)) return;
631+ const nuevo = (parentOf(path) ? parentOf(path) + '/' : '') + name;
632+ await fsRename(path, kind, name); code.invalidateFileList?.();
633+ renameTabs(path, nuevo, kind);
634+ await refreshTree();
635+ alertBar(t('renamed', { from: baseOf(path), to: name }));
387636 }]);
388- items.push(['Eliminar', async () => {
389- if (!confirm(`¿Eliminar «${baseOf(path)}»?`)) return;
390- await fsDelete(path, kind); code.invalidateFileList?.(); await refreshTree();
637+ items.push([t('tmDelete'), async () => {
638+ if (!confirm(t('confirmDelete', { name: baseOf(path) }))) return;
639+ await fsDelete(path, kind); code.invalidateFileList?.();
640+ dropTabs(path, kind);
641+ await refreshTree();
642+ alertBar(t('deleted', { name: baseOf(path) }));
391643 }, 'danger']);
392644 }
645+ let close = () => menu.remove();
393646 for (const [label, fn, cls] of items) {
394- const b = document.createElement('button');
395- b.className = 'tm-item' + (cls ? ' ' + cls : '');
396- b.textContent = label;
397- b.onclick = async () => { menu.remove(); try { await fn(); } catch (err) { alert('No se pudo: ' + err.message); } };
647+ const b = menuButton(label, fn, cls);
648+ b.onclick = async () => { close(); try { await fn(); } catch (err) { alert(t('opFailed', { e: err.message })); } };
398649 menu.appendChild(b);
399650 }
400651 document.body.appendChild(menu);
401- const close = ev => { if (!menu.contains(ev.target)) { menu.remove(); document.removeEventListener('mousedown', close); } };
402- setTimeout(() => document.addEventListener('mousedown', close), 0);
652+ close = wireMenu(menu, volver);
403653 }
404654
655+const TREE_MAX_ENTRIES = 200;
405656 async function renderDir(dir, prefix) {
406657 const ul = document.createElement('ul');
658+ if (prefix) ul.setAttribute('role', 'group');
407659 const entries = [];
408660 for await (const e of dir.values()) if (!IGNORE.has(e.name)) entries.push(e);
409661 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
410- for (const e of entries.slice(0, 200)) {
662+ for (const e of entries.slice(0, TREE_MAX_ENTRIES)) {
411663 const li = document.createElement('li');
664+ li.setAttribute('role', 'none');
412665 const p = prefix ? prefix + '/' + e.name : e.name;
413666 if (e.kind === 'directory') {
414667 const det = document.createElement('details');
@@ -416,11 +669,24 @@
416669 sum.innerHTML = folderIcon();
417670 sum.appendChild(document.createTextNode(e.name));
418671 sum.dataset.path = p; sum.dataset.kind = 'directory';
672+ sum.setAttribute('role', 'treeitem');
673+ sum.setAttribute('aria-expanded', 'false');
674+ sum.tabIndex = -1;
419675 det.appendChild(sum);
420676 det.addEventListener('toggle', async () => {
421- if (det.open && det.children.length === 1)
677+ sum.setAttribute('aria-expanded', det.open ? 'true' : 'false');
678+ if (det.open) openDirs.add(p); else openDirs.delete(p);
679+ if (det.open && det.children.length === 1) {
422680 det.appendChild(await renderDir(e, p));
423- }, { once: false });
681+ markActive();
682+ }
683+ });
684+ // Estaba abierta antes del repintado: se reabre ya con su contenido.
685+ if (openDirs.has(p)) {
686+ det.appendChild(await renderDir(e, p));
687+ det.open = true;
688+ sum.setAttribute('aria-expanded', 'true');
689+ }
424690 li.appendChild(det);
425691 } else {
426692 const a = document.createElement('span');
@@ -428,10 +694,20 @@
428694 a.innerHTML = fileIcon(e.name);
429695 a.appendChild(document.createTextNode(e.name));
430696 a.dataset.path = p; a.dataset.kind = 'file';
697+ a.setAttribute('role', 'treeitem');
698+ a.tabIndex = -1;
431699 a.onclick = () => openFile(p);
432700 li.appendChild(a);
433701 }
434702 ul.appendChild(li);
435703 }
704+ // Una carpeta con más de 200 entradas se cortaba sin decirlo.
705+ if (entries.length > TREE_MAX_ENTRIES) {
706+ const li = document.createElement('li');
707+ li.className = 'tree-more';
708+ li.setAttribute('role', 'none');
709+ li.textContent = t('treeMore', { n: entries.length - TREE_MAX_ENTRIES });
710+ ul.appendChild(li);
711+ }
436712 return ul;
437713 }
modified web/js/main.js +18 −8
@@ -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 } from './ide.js';
7+import { initEditor, refreshTree, openFile, gotoLine, triggerEditor, hasEditor, saveActive, activeFile } from './ide.js';
88 import { ACTIVITY, UI } from './icons.js';
99 import { renderMarkdown } from './md.js';
1010 import * as skills from './skills.js';
@@ -80,6 +80,14 @@
8080 import * as telemetry from './telemetry.js';
8181
8282 const $ = id => document.getElementById(id);
83+// Atajos tal y como se pulsan en ESTA máquina: en un Mac el editor guarda con
84+// ⌘S y Ctrl+S no hace nada, así que anunciar «Ctrl+S» era mandar a pulsar algo
85+// que no funciona.
86+const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');
87+const atajo = (k, shift = false) => IS_MAC ? '⌘' + (shift ? '⇧' : '') + k : 'Ctrl+' + (shift ? 'Shift+' : '') + k;
88+// Acciones del editor que no hacen nada sin un fichero abierto: se dice en vez
89+// de no hacer nada.
90+const conFichero = fn => () => { if (!activeFile()) { $('statusbar').textContent = t('noFileOpen'); return; } fn(); };
8391 telemetry.init('elffuss-code'); // opt-in, apagado por defecto — ver Ajustes
8492 conv.setProvider(rules); // proveedor por defecto para cualquier conversación que se cree
8593 let activeModel = 'rules';
@@ -1968,7 +1976,7 @@
19681976 { label: t('tActSettings'), run: () => { closePalette(); renderSettings(); } },
19691977 { label: t('pToggleExplorer'), run: () => $('act-files').click() },
19701978 { label: t('pToggleTerm'), hint: 'Ctrl+`', run: () => { closePalette(); toggleTerminal(); } },
1971- { label: t('pSave'), run: () => triggerEditor('') || (hasEditor() && triggerEditor('workbench.action.files.save')) },
1979+ { label: t('pSave', { k: atajo('S') }), run: () => saveActive() },
19721980 ];
19731981
19741982 function openPalette(prefix = '') {
@@ -1998,9 +2006,11 @@
19982006
19992007 if (raw.startsWith('>')) { // comandos
20002008 const q = raw.slice(1).trim().toLowerCase();
2001- palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: c.run }));
2009+ // Todo comando cierra la paleta al ejecutarse: «Nueva conversación», por
2010+ // ejemplo, la dejaba abierta encima.
2011+ palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: () => { closePalette(); c.run(); } }));
20022012 } else if (raw.startsWith('@')) { // símbolos del archivo abierto (Monaco)
2003- palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); triggerEditor('editor.action.quickOutline'); } }];
2013+ palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); conFichero(() => triggerEditor('editor.action.quickOutline'))(); } }];
20042014 } else { // archivos (con :línea opcional)
20052015 const [pathQ, lineQ] = raw.split(':');
20062016 const files = await codeTools.fileList().catch(() => []);
@@ -2051,20 +2061,20 @@
20512061 async function menuFor(which) {
20522062 if (which === 'file') return [
20532063 { label: t('mNewFile'), run: () => { const p = prompt(t('promptNewPath')); if (p) codeTools.write({ path: p, content: '' }).then(() => { openFile(p); refreshTree(); }); } },
2054- { label: t('mSave'), hint: 'Ctrl+S', run: () => triggerEditor('workbench.action.files.save') },
2064+ { label: t('mSave'), hint: atajo('S'), run: () => saveActive() },
20552065 { label: t('mOpenFolder'), run: async () => { try { await enterIDE(await window.showDirectoryPicker({ mode: 'readwrite' })); } catch {} } },
20562066 ];
20572067 if (which === 'edit') return [
20582068 { label: t('mSearchCode'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } },
2059- { label: t('mGotoFile'), hint: 'Cmd+P', run: () => openPalette('') },
2060- { label: t('mGotoSym'), run: () => triggerEditor('editor.action.quickOutline') },
2069+ { label: t('mGotoFile'), hint: atajo('P'), run: () => openPalette('') },
2070+ { label: t('mGotoSym'), run: conFichero(() => triggerEditor('editor.action.quickOutline')) },
20612071 ];
20622072 if (which === 'view') return [
20632073 { label: t('tFiles'), run: () => $('act-files').click() },
20642074 { label: t('mTerminal'), hint: 'Ctrl+`', run: () => toggleTerminal(true) },
20652075 { label: t('mArch'), run: () => openView('arch') },
20662076 { label: t('tCity'), run: () => openView('city') },
2067- { label: 'Command Palette', hint: 'Cmd+Shift+P', run: () => openPalette('>') },
2077+ { label: t('mPalette'), hint: atajo('P', true), run: () => openPalette('>') },
20682078 { label: 'Skills', run: () => openSkillsPanel() },
20692079 { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') },
20702080 ];