Add author-mode level editor: forms, live checks, Python execution of solutions, learner preview, YAML export

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 16:51:33 +02:00
parent 3003eda8a2
commit 57bda6eecf
27 changed files with 1712 additions and 10 deletions
+80
View File
@@ -416,3 +416,83 @@ test('carte de progression et badges : états en texte, badge obtenu à la fin d
assert.equal(await page.locator('.badge-item.is-locked .badge-status').first().textContent(), 'À débloquer');
assert.deepEqual(errors, []);
});
test('éditeur de niveaux (mode auteur) : écrire un niveau, le vérifier, l\'essayer, l\'exporter', { skip, timeout: 240000 }, async () => {
const { spawnSync } = await import('node:child_process');
const { mkdtempSync, writeFileSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
const page = await (await browser.newContext({ acceptDownloads: true })).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const field = (path) => page.locator(`[data-path="${path}"]`);
const fill = async (path, value) => field(path).fill(value);
await page.goto(`${base}author.html`);
await page.waitForSelector('.level-form', { timeout: 60000 });
// Niveau vide : des erreurs sont déjà signalées, avec un bouton pour aller au champ.
assert.match(await page.textContent('.problems-summary'), /[1-9]\d* erreur/);
// Informations + une explication + un exercice de code + la mission.
await fill('id', '99-essai');
await fill('title.fr', 'Essai');
await fill('title.en', 'Test');
await page.getByRole('button', { name: 'Ajouter une explication' }).click();
await fill('steps.0.text.fr', 'Voici `print()`.');
await fill('steps.0.text.en', 'Here is `print()`.');
await page.getByRole('button', { name: 'Ajouter un exercice de code' }).click();
await fill('steps.1.instruction.fr', 'Affiche b.');
await fill('steps.1.instruction.en', 'Print b.');
await fill('steps.1.starter', 'print("a")');
await fill('steps.1.tests.0.value', 'b\n');
await fill('steps.1.hints.fr', 'Change la lettre.');
await fill('steps.1.hints.en', 'Change the letter.');
await fill('steps.1.solution', 'print("b")');
await fill('mission.title.fr', 'Fin');
await fill('mission.title.en', 'End');
await fill('mission.goal.fr', 'Bravo.');
await fill('mission.goal.en', 'Well done.');
await page.waitForFunction(() => document.querySelector('.problems-summary')?.textContent.startsWith('0 erreur'), null, { timeout: 5000 });
// Exécution avec le vrai Python : la solution passe, le départ échoue → tout est correct.
await page.locator('#author-check').click();
await page.waitForFunction(() => /exercice\(s\) sont corrects/.test(document.querySelector('#author-check + p')?.textContent ?? ''), null, { timeout: 60000 });
// Une solution fausse est détectée, avec le bon message.
await fill('steps.1.solution', 'print("z")');
await page.locator('#author-check').click();
await page.waitForSelector('.problem-error');
assert.match(await page.textContent('.problem-error'), /La solution ne passe pas ses tests/);
await page.locator('.problem-error button', { hasText: 'Aller au champ' }).click();
assert.equal(await page.evaluate(() => document.activeElement.dataset.path), 'steps.1.solution');
await fill('steps.1.solution', 'print("b")');
// Essai comme apprenant dans l'interface réelle.
await page.locator('#author-preview').click();
await page.waitForSelector('.preview-frame .explain', { timeout: 60000 });
assert.match(await page.textContent('.preview-frame .explain'), /Voici print\(\)/);
// Export : le fichier téléchargé est accepté par le validateur Python de la CI.
const [download] = await Promise.all([page.waitForEvent('download'), page.locator('#author-download').click()]);
const dir = mkdtempSync(join(tmpdir(), 'pyquest-author-'));
const file = join(dir, 'level.yaml');
await download.saveAs(file);
assert.equal(download.suggestedFilename(), 'level.yaml');
const python = existsSync(`${root}.venv/bin/python`) ? `${root}.venv/bin/python` : null;
if (python) {
const result = spawnSync(python, [`${root}scripts/validate_levels.py`, '--file', file], { encoding: 'utf8' });
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.match(result.stdout, /^OK/);
}
writeFileSync(join(dir, 'unused'), '');
// Brouillon restauré après rechargement ; la langue de l'éditeur se change sans perdre le contenu.
await page.reload();
await page.waitForSelector('.level-form');
assert.equal(await field('id').inputValue(), '99-essai');
assert.match(await page.textContent('.author-status'), /restauré/);
await page.locator('#author-lang').selectOption('en');
await page.getByRole('button', { name: 'Add a code exercise' }).waitFor();
assert.equal(await field('steps.1.solution').inputValue(), 'print("b")');
assert.deepEqual(errors, []);
});
+39
View File
@@ -0,0 +1,39 @@
// Les textes de l'éditeur de niveaux : toutes les clés utilisées dans le code existent en français et en
// anglais, chaque code de vérification (linter, vérification d'exécution) a son message, et les deux
// catalogues sont strictement parallèles (mêmes clés, mêmes paramètres).
import { readFileSync, readdirSync } from 'node:fs';
import assert from 'node:assert';
import { PYTHON_TYPES, TEST_KINDS } from '../../app/js/author/LevelDraft.js';
const root = new URL('../../', import.meta.url).pathname;
const read = (path) => readFileSync(`${root}${path}`, 'utf8');
const catalogs = {
fr: { ...JSON.parse(read('app/js/i18n/fr.json')), ...JSON.parse(read('app/js/i18n/author.fr.json')) },
en: { ...JSON.parse(read('app/js/i18n/en.json')), ...JSON.parse(read('app/js/i18n/author.en.json')) },
};
const author = { fr: JSON.parse(read('app/js/i18n/author.fr.json')), en: JSON.parse(read('app/js/i18n/author.en.json')) };
// Parallélisme strict.
assert.deepEqual(Object.keys(author.fr).sort(), Object.keys(author.en).sort());
const params = (text) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join(',');
for (const key of Object.keys(author.fr)) assert.equal(params(author.fr[key]), params(author.en[key]), `paramètres de ${key}`);
// Clés littérales utilisées dans le code de l'éditeur.
const sources = readdirSync(`${root}app/js/author`).filter((name) => name.endsWith('.js')).map((name) => read(`app/js/author/${name}`));
const used = new Set(sources.flatMap((source) => [...source.matchAll(/\bt\('([\w.]+)'/g)].map((m) => m[1])));
// Clés construites dynamiquement.
for (const kind of Object.keys(TEST_KINDS)) ['', '.help'].forEach((suffix) => used.add(`author.kind.${kind}${suffix}`));
for (const type of ['explain', 'code']) used.add(`author.step.type.${type}`);
for (const severity of ['error', 'warning', 'info']) used.add(`author.severity.${severity}`);
for (let n = 1; n <= 5; n++) used.add(`author.export.step${n}`);
for (const lang of ['fr', 'en']) for (const key of used) assert.ok(catalogs[lang][key]?.trim(), `${lang} : clé ${key} manquante`);
// Un message par code de problème émis par le linter ou le vérificateur.
const emitted = new Set(['core/LevelLinter.js', 'core/LevelChecker.js'].flatMap((file) => [...read(`app/js/${file}`).matchAll(/add\('(?:error|warning|info)', '([a-z_]+)'/g)].map((m) => m[1])));
assert.ok(emitted.size >= 20, `codes détectés : ${emitted.size}`);
for (const lang of ['fr', 'en']) for (const code of emitted) assert.ok(catalogs[lang][`lint.${code}`], `${lang} : message lint.${code} manquant`);
// Pas de message orphelin : chaque lint.* correspond à un code réellement émis.
for (const key of Object.keys(author.fr).filter((k) => k.startsWith('lint.'))) assert.ok(emitted.has(key.slice(5)), `message orphelin ${key}`);
assert.ok(PYTHON_TYPES.length > 0);
console.log('author i18n ok');
@@ -31,7 +31,7 @@ test('les solutions de référence passent, les codes de départ échouent', { s
// --- Niveaux fautifs fabriqués : chaque défaut est détecté, au bon endroit.
const base = () => structuredClone(load('04-math'));
let level = base(); level.steps[1].solution = 'print(1 + 1)';
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@steps.1']);
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@steps.1.solution']);
level = base(); level.steps[1].starter = level.steps[1].solution;
assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution : étape « exécuter pour voir »');
@@ -40,18 +40,18 @@ test('les solutions de référence passent, les codes de départ échouent', { s
assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution + commentaires de ligne : idem');
level = base(); level.steps[1].starter = 'print(36)';
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_passes@steps.1'], 'départ qui passe déjà sans être la solution');
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_passes@steps.1.starter'], 'départ qui passe déjà sans être la solution');
level = base(); level.steps[1].solution = 'print(';
const syntax = (await checker.check(level)).problems;
assert.deepEqual(summary(syntax), ['solution_error@steps.1']);
assert.deepEqual(summary(syntax), ['solution_error@steps.1.solution']);
assert.equal(syntax[0].params.type, 'SyntaxError');
level = base(); level.mission.solution = 'print("rien")';
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@mission']);
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@mission.solution']);
level = base(); level.steps[1].starter = 'print(';
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_error@steps.1']);
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_error@steps.1.starter']);
console.log(`${checked} exercices vérifiés`);
} finally {