From 6ac36ae5ecb47ec1799ee52986e06c55ac5d4c34 Mon Sep 17 00:00:00 2001 From: denis Date: Fri, 16 Oct 2026 17:58:10 +0200 Subject: [PATCH] Editor: Tab indents, Shift+Tab dedents, Esc then Tab leaves the editor Co-Authored-By: Claude Sonnet 5.5 --- app/js/i18n/en.json | 2 +- app/js/i18n/fr.json | 2 +- app/js/ui/CodeEditor.js | 81 ++++++++++++++++++++++++++++++++++++++++- tests/e2e/e2e.test.mjs | 50 +++++++++++++++++++++++++ 4 files changed, 132 insertions(+), 3 deletions(-) diff --git a/app/js/i18n/en.json b/app/js/i18n/en.json index 14a6a0a..1c4a7f4 100644 --- a/app/js/i18n/en.json +++ b/app/js/i18n/en.json @@ -18,7 +18,7 @@ "cell.output_empty": "(nothing printed)", "cell.input_label": "Answer requested by the program", "cell.input_send": "Send", - "cell.shortcut": "Ctrl/Cmd + Enter to run", + "cell.shortcut": "Ctrl/Cmd + Enter to run · Tab indents, Esc then Tab leaves the editor", "cell.passed": "Well done, that's correct!", "cell.failed": "Not yet. Here is what is wrong:", "cell.line": "Line {line}", diff --git a/app/js/i18n/fr.json b/app/js/i18n/fr.json index e448a85..25a0f49 100644 --- a/app/js/i18n/fr.json +++ b/app/js/i18n/fr.json @@ -18,7 +18,7 @@ "cell.output_empty": "(aucun affichage)", "cell.input_label": "Réponse demandée par le programme", "cell.input_send": "Envoyer", - "cell.shortcut": "Ctrl/Cmd + Entrée pour exécuter", + "cell.shortcut": "Ctrl/Cmd + Entrée pour exécuter · Tab indente, Échap puis Tab pour quitter l'éditeur", "cell.passed": "Bravo, c'est correct !", "cell.failed": "Pas encore. Voici ce qui ne va pas :", "cell.line": "Ligne {line}", diff --git a/app/js/ui/CodeEditor.js b/app/js/ui/CodeEditor.js index f1f3e43..936e87a 100644 --- a/app/js/ui/CodeEditor.js +++ b/app/js/ui/CodeEditor.js @@ -5,11 +5,14 @@ import { el } from './dom.js'; import { tokenizePython } from './highlightPython.js'; const MIN_ROWS = 3; +const INDENT = ' '; // 4 espaces, convention du projet export class CodeEditor { #root; #textarea; #highlight; + // Échap suspend la capture de Tab : le clavier ne reste jamais piégé dans l'éditeur (WCAG 2.1.2). + #tabReleased = false; /** * @param {object} options @@ -29,7 +32,11 @@ export class CodeEditor { ...attrs, oninput: () => this.#render(), onscroll: () => this.#syncScroll(), - onkeydown: onKeyDown, + onkeydown: (event) => { + this.#onKeyDown(event); + onKeyDown(event); + }, + onblur: () => (this.#tabReleased = false), }); this.#root = el('div', { class: 'code-editor-wrap' }, this.#highlight, this.#textarea); this.value = value; @@ -52,6 +59,78 @@ export class CodeEditor { this.#textarea.focus(); } + /** Tab indente (Maj+Tab désindente) ; Échap puis Tab quitte l'éditeur. */ + #onKeyDown(event) { + if (event.key === 'Escape') { + this.#tabReleased = true; + return; + } + if (event.key !== 'Tab' || event.ctrlKey || event.metaKey || event.altKey) { + if (!['Shift', 'Control', 'Alt', 'Meta'].includes(event.key)) { + this.#tabReleased = false; + } + return; + } + if (this.#tabReleased) { + return; // Tab garde son rôle de navigation + } + event.preventDefault(); + const { selectionStart: start, selectionEnd: end, value } = this.#textarea; + const multiline = value.slice(start, end).includes('\n'); + if (event.shiftKey || multiline) { + this.#shiftLines(start, end, event.shiftKey ? -1 : 1); + } else { + // Complète jusqu'à la prochaine colonne multiple de 4. + const column = start - (value.lastIndexOf('\n', start - 1) + 1); + this.#replace(start, end, INDENT.slice(column % INDENT.length)); + } + } + + /** Indente (+1) ou désindente (-1) toutes les lignes touchées par la sélection. */ + #shiftLines(start, end, direction) { + const { value } = this.#textarea; + const from = value.lastIndexOf('\n', start - 1) + 1; + // Une sélection qui se termine en début de ligne ne touche pas cette dernière ligne. + const to = end > start && value[end - 1] === '\n' ? end - 1 : end; + const lines = value.slice(from, to).split('\n'); + let firstDelta = 0; + let total = 0; + const changed = lines.map((line, index) => { + let next = line; + if (direction > 0) { + next = line === '' ? line : INDENT + line; + } else { + const remove = /^ {1,4}|^\t/.exec(line)?.[0].length ?? 0; + next = line.slice(remove); + } + const delta = next.length - line.length; + if (index === 0) { + firstDelta = delta; + } + total += delta; + return next; + }); + this.#replace(from, to, changed.join('\n'), Math.max(from, start + firstDelta), Math.max(from, end + total)); + } + + /** Remplace [start, end) par `text` en conservant l'historique d'annulation quand le navigateur le permet. */ + #replace(start, end, text, selectionStart = start + text.length, selectionEnd = selectionStart) { + const area = this.#textarea; + area.setSelectionRange(start, end); + // execCommand est obsolète mais reste le seul moyen d'insérer en gardant Ctrl+Z ; repli : setRangeText. + let done = false; + try { + done = document.execCommand('insertText', false, text); + } catch { + done = false; + } + if (!done) { + area.setRangeText(text, start, end, 'end'); + this.#render(); + } + area.setSelectionRange(selectionStart, selectionEnd); + } + #render() { const code = this.#textarea.value; this.#textarea.rows = Math.max(MIN_ROWS, code.split('\n').length + 1); diff --git a/tests/e2e/e2e.test.mjs b/tests/e2e/e2e.test.mjs index 18ae4be..e3b408f 100644 --- a/tests/e2e/e2e.test.mjs +++ b/tests/e2e/e2e.test.mjs @@ -386,6 +386,56 @@ test('éditeur : coloration syntaxique, textarea réel, polices de la charte', { assert.deepEqual(errors, []); }); +test('éditeur : Tab indente, Maj+Tab désindente, Échap puis Tab quitte l\'éditeur', { skip, timeout: 120000 }, async () => { + const page = await (await browser.newContext()).newPage(); + await page.goto(`${base}#/levels/07-while`); + await page.waitForSelector('.explain', { timeout: 60000 }); + await page.locator('.notebook-action button').last().click(); + const area = page.locator('.cell').last().locator('textarea'); + const value = () => area.inputValue(); + await area.fill('while True:\nx = 1'); + + // Tab au début de la ligne 2 : 4 espaces (et non un changement de focus). + await area.evaluate((node) => node.setSelectionRange(12, 12)); + await area.focus(); + await page.keyboard.press('Tab'); + assert.equal(await value(), 'while True:\n x = 1'); + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'TEXTAREA'); + + // Tab en milieu de ligne : complète jusqu'à la colonne multiple de 4. + await page.keyboard.press('End'); + await page.keyboard.press('Tab'); + assert.equal(await value(), 'while True:\n x = 1 '); + + // Maj+Tab désindente la ligne. + await page.keyboard.press('Shift+Tab'); + assert.equal(await value(), 'while True:\nx = 1 '); + + // Sélection de plusieurs lignes : toutes sont indentées, puis désindentées. + await page.keyboard.press('Control+a'); + await page.keyboard.press('Tab'); + assert.equal(await value(), ' while True:\n x = 1 '); + await page.keyboard.press('Shift+Tab'); + assert.equal(await value(), 'while True:\nx = 1 '); + + // Ctrl+Z annule l'indentation (historique conservé). + await page.keyboard.press('Control+End'); + await page.keyboard.press('Tab'); + await page.keyboard.press('Control+z'); + assert.equal(await value(), 'while True:\nx = 1 '); + + // Échap puis Tab : le focus quitte l'éditeur (pas de piège clavier). + await page.keyboard.press('Escape'); + await page.keyboard.press('Tab'); + assert.notEqual(await page.evaluate(() => document.activeElement.tagName), 'TEXTAREA'); + // Revenu dans l'éditeur, Tab indente de nouveau. + await page.keyboard.press('Shift+Tab'); + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'TEXTAREA'); + await page.keyboard.press('Control+Home'); + await page.keyboard.press('Tab'); + assert.equal((await value()).startsWith(' while'), true); +}); + test('personnage-guide : messages variés selon la situation, réglage pour le masquer', { skip, timeout: 120000 }, async () => { const guideFr = JSON.parse(readFileSync(`${root}app/js/i18n/guide.fr.json`, 'utf8')); const page = await (await browser.newContext()).newPage();