diff --git a/CLAUDE.md b/CLAUDE.md index b3bcc62..28e4202 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,6 +67,9 @@ lire en premier en reprenant une session sur ce projet. Livrables 1 à 8 du brief écrits ; l'app tourne dans Chromium (8 niveaux : 00 à 07). Détail, architecture du code, priorités et pièges : [CONTEXT.md](CONTEXT.md). +Éditeur de niveaux (mode auteur, `app/author.html`) : voir `docs/design/08-author-editor.md`. Un nouveau +kind de test touche ValidationEngine, schéma, `LevelDraft.TEST_KINDS`, catalogues et linter. + Commandes : `make test` (JS `node:test`, Python `unittest`, backend Django, validation des niveaux), `make test-e2e` (Chromium), `make typecheck` (pyright), `make dev`, `make build`. Pyodide épinglé 314.0.7 (Python 3.14.2) via `make vendor-pyodide`. diff --git a/CONTEXT.md b/CONTEXT.md index 9a1dc95..5e634ec 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -30,6 +30,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables. | Erreurs | `app/js/core/ErrorTranslator.js` + `app/js/i18n/errors.{fr,en}.json` | | Progression | `app/js/core/ProgressStore.js`, `KeyValueStores.js` (IndexedDB/mémoire), `SettingsStore.js` | | Carte / badges | `app/js/ui/{ProgressMap,BadgeShelf,badgeArt}.js`, `app/css/progress.css` | +| Éditeur de niveaux | `app/author.html`, `app/js/author/*`, `app/css/author.css`, `app/js/i18n/author.*.json`, `app/js/core/{LevelLinter,LevelChecker}.js`, `app/js/lib/json-schema/` | | Guide | `app/js/core/GuideEngine.js`, `app/js/i18n/guide.{fr,en}.json`, `app/js/ui/{GuideBubble,guideArt}.js`, `app/css/guide.css` | | Audio / voix | `app/js/core/AudioEngine.js` (sons synthétisés), `VoiceEngine.js` (mp3 Piper + repli speechSynthesis), `speechKey.js` ; `scripts/generate_voice.py`, `voice_key.py` | | UI | `app/js/ui/` (CellView, CellManager, NotebookView, HintPanel, ProgressMap, BadgeToast, SettingsPanel, dom.js), `app/js/i18n/{i18n.js,fr.json,en.json}`, `app/css/{themes,base,cells}.css`, `ui/CodeEditor.js`, `ui/highlightPython.js` | @@ -38,6 +39,15 @@ vrai navigateur (Chromium) avec 4 niveaux jouables. | Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) | | Backend | `backend/` Django : `GET/PUT /api/sync/` avec jeton Bearer (haché côté serveur) | +## Éditeur de niveaux (mode auteur) — fait le 2026-10-16 + +Décision de l'utilisateur : ouvrir à des contributeurs + éditeur en mode auteur (Django inchangé : sync +seulement). Voir `docs/design/08-author-editor.md`. Page `app/author.html`, code `app/js/author/`, +vérifications `core/LevelLinter.js` + `core/LevelChecker.js` (partagées avec `make test`), schéma validé +dans le navigateur par `lib/json-schema`. `scripts/validate_levels.py --file` valide un fichier seul. +**Reste** : documenter le flux de pull request / CI (pas de remote git), audit accessibilité réel de +l'éditeur (lecteur d'écran), éventuelle génération de narration côté CI. + ## Décisions actées (ne pas redemander) - Moteur Python : **Pyodide 314.0.7** (Python 3.14.2), épinglé + SHA-256 dans `vendor_pyodide.sh`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 999a0a9..414b5d8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,6 +15,14 @@ Français d'abord, English below. ## Ajouter un niveau +**Le plus simple : l'éditeur de niveaux (mode auteur).** Lance `make dev`, active « Mode auteur » dans +les réglages de l'application, puis ouvre l'éditeur (`/author.html`). Il te guide champ par champ, +vérifie le niveau en direct, exécute tes solutions avec le vrai Python, te laisse l'essayer comme un +apprenant et exporte `level.yaml`. Il ne remplace pas la relecture : les commandes `make` ci-dessous +restent la référence. Voir `docs/design/08-author-editor.md`. + +À la main, ou pour finir ce que l'éditeur a produit : + 1. **Créer le dossier** `levels/NN-slug/` (ex. `levels/03-input/`) avec un fichier `level.yaml`. L'`id` doit être identique au nom du dossier (`^[0-9]{2}-[a-z0-9-]+$`). 2. **Écrire le contenu** en suivant le schéma [`levels/schema/level.schema.json`](levels/schema/level.schema.json). @@ -26,7 +34,7 @@ Français d'abord, English below. - une `mission` finale motivante, avec `reward_sound`. 3. **Fournir le français et l'anglais** pour chaque texte (`fr` et `en`). 4. **Référencer le niveau** dans `levels/manifest.json` (ordre et `requires`). -5. **Valider** : `make validate-levels` vérifie le schéma, le manifeste, la présence des +5. **Valider** : `python scripts/validate_levels.py --file mon-niveau.yaml` contrôle un fichier seul ; `make validate-levels` vérifie le schéma, le manifeste, la présence des traductions `en` et que le code de départ compile. ### Tests déclaratifs disponibles diff --git a/README-EN.md b/README-EN.md index a2c384c..7992b88 100644 --- a/README-EN.md +++ b/README-EN.md @@ -7,6 +7,7 @@ beginners and advanced learners alike. a Web Worker: genuine error messages, translated into plain language. - Notebook-style cells, progressive hints, automatic exercise validation. - Declarative levels (YAML): adding a level requires no code change. +- Built-in level editor (author mode) to contribute without hand-writing YAML. - XP, badges, daily streaks, optional sound effects and narration (pre-generated Piper voices), French/English interface. - Accessibility target: WCAG 2.2 AA (full keyboard use, light/dark themes, adjustable text size). diff --git a/README.md b/README.md index af3a7e8..d432ab1 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ fonctionne hors ligne (PWA), pour les débutants comme pour les plus avancés. Web Worker : les vrais messages d'erreur, traduits en langage simple. - Console à cellules façon notebook, indices progressifs, validation automatique des exercices. - Niveaux déclaratifs (YAML) : ajouter un niveau ne demande aucune modification du code. +- Éditeur de niveaux intégré (mode auteur) pour contribuer sans écrire de YAML à la main. - XP, badges, séries de jours, effets sonores et narration vocale (voix Piper pré-générées) optionnels, interface fr/en. - Accessibilité visée : WCAG 2.2 AA (clavier complet, thèmes clair/sombre, taille de texte réglable). diff --git a/app/author.html b/app/author.html new file mode 100644 index 0000000..b9a6988 --- /dev/null +++ b/app/author.html @@ -0,0 +1,21 @@ + + +
+ + + +`) ; les paramètres sont complétés ici.
+
+import { el } from '../ui/dom.js';
+
+const ORDER = { error: 0, warning: 1, info: 2 };
+const ICONS = { error: '✘', warning: '⚠', info: 'ℹ' };
+
+/** « Étape 3 › Test 1 › value » à partir du chemin d'un problème. */
+export function describePath(path, t) {
+ const parts = [];
+ for (let i = 0; i < path.length; i++) {
+ const segment = path[i];
+ if (segment === 'steps' && typeof path[i + 1] === 'number') {
+ parts.push(t('author.path.step', { n: path[++i] + 1 }));
+ } else if (segment === 'tests' && typeof path[i + 1] === 'number') {
+ parts.push(t('author.path.test', { n: path[++i] + 1 }));
+ } else if (segment === 'mission') {
+ parts.push(t('author.path.mission'));
+ } else if (typeof segment === 'number') {
+ parts.push(`#${segment + 1}`);
+ } else {
+ parts.push(segment);
+ }
+ }
+ return parts.join(' › ');
+}
+
+/** Texte complet d'un problème, paramètres de présentation inclus. */
+export function describeProblem(problem, t) {
+ const params = { ...problem.params };
+ if (Array.isArray(params.failures)) {
+ params.failures = params.failures.map((failure) => `${t(`author.kind.${failure.kind}`)} (${t(`reason.${failure.reason}`)})`).join(' ; ');
+ }
+ if (params.line) {
+ params.line = ` (${t('cell.line', { line: params.line })})`;
+ } else if ('line' in params) {
+ params.line = '';
+ }
+ return t(`lint.${problem.code}`, params);
+}
+
+export class ProblemsPanel {
+ #t;
+ #root;
+ #onGoto;
+
+ /** @param {{t: Function, onGoto: (path: (string|number)[]) => void}} options */
+ constructor({ t, onGoto }) {
+ this.#t = t;
+ this.#onGoto = onGoto;
+ this.#root = el('div', { class: 'problems', role: 'region', 'aria-live': 'polite' });
+ }
+
+ get element() {
+ return this.#root;
+ }
+
+ /** @param {{severity: string, code: string, path: (string|number)[], params: object}[]} problems */
+ render(problems) {
+ const t = this.#t;
+ const sorted = [...problems].sort((a, b) => ORDER[a.severity] - ORDER[b.severity]);
+ const count = (severity) => problems.filter((problem) => problem.severity === severity).length;
+ const summary = el('p', { class: 'problems-summary', text: problems.length === 0 ? t('author.problems.none') : t('author.problems.summary', { errors: count('error'), warnings: count('warning'), infos: count('info') }) });
+ const items = sorted.map((problem) =>
+ el(
+ 'li',
+ { class: `problem problem-${problem.severity}` },
+ el('span', { class: 'problem-icon', 'aria-hidden': 'true', text: ICONS[problem.severity] }),
+ el(
+ 'div',
+ { class: 'problem-body' },
+ el('strong', { class: 'problem-severity', text: t(`author.severity.${problem.severity}`) }),
+ ' ',
+ el('span', { class: 'problem-text', text: describeProblem(problem, t) }),
+ problem.path.length > 0 ? el('div', { class: 'problem-path', text: describePath(problem.path, t) }) : null,
+ ),
+ problem.path.length > 0 ? el('button', { type: 'button', class: 'btn', text: t('author.problems.goto'), onclick: () => this.#onGoto(problem.path) }) : null,
+ ),
+ );
+ this.#root.replaceChildren(summary, el('ul', { class: 'problem-list' }, ...items));
+ }
+}
diff --git a/app/js/author/StepEditor.js b/app/js/author/StepEditor.js
new file mode 100644
index 0000000..8be4fe1
--- /dev/null
+++ b/app/js/author/StepEditor.js
@@ -0,0 +1,87 @@
+// Éditeur d'une étape (explication ou exercice de code) et de sa liste de tests.
+
+import { el } from '../ui/dom.js';
+import { newTestModel } from './LevelDraft.js';
+import { checkboxField, i18nPair, textField } from './fields.js';
+import { testEditor } from './TestEditor.js';
+
+/** Liste de tests éditables, avec bouton d'ajout. Partagée par les exercices et la mission. */
+export function testsEditor({ t, tests, path, onChange, onStructure, addLabel }) {
+ return el(
+ 'div',
+ { class: 'tests-editor' },
+ ...tests.map((test, index) =>
+ testEditor({
+ t,
+ test,
+ path: `${path}.${index}`,
+ number: index + 1,
+ onChange,
+ onStructure,
+ onRemove: () => {
+ tests.splice(index, 1);
+ onChange();
+ onStructure(`${path}.add`);
+ },
+ }),
+ ),
+ el('button', {
+ type: 'button',
+ class: 'btn',
+ 'data-path': `${path}.add`,
+ text: addLabel,
+ onclick: () => {
+ tests.push(newTestModel());
+ onChange();
+ onStructure(`${path}.${tests.length - 1}.kind`);
+ },
+ }),
+ );
+}
+
+/**
+ * @param {object} options
+ * @param {(key: string, params?: object) => string} options.t
+ * @param {object} options.step Modèle de l'étape (modifié en place).
+ * @param {number} options.index Position (à partir de 0).
+ * @param {number} options.count Nombre d'étapes.
+ * @param {() => void} options.onChange
+ * @param {(focusPath?: string) => void} options.onStructure
+ * @param {{move: (delta: number) => void, remove: () => void}} options.actions
+ */
+export function stepEditor({ t, step, index, count, onChange, onStructure, actions }) {
+ const path = `steps.${index}`;
+ const number = index + 1;
+ const body =
+ step.type === 'explain'
+ ? [
+ i18nPair({ label: t('author.step.text'), path: `${path}.text`, value: step.text, multiline: true, rows: 4, help: t('author.step.text.help'), onChange }),
+ checkboxField({ label: t('author.step.voice'), path: `${path}.voice`, checked: step.voice, help: t('author.step.voice.help'), onChange: (checked) => ((step.voice = checked), onChange()) }),
+ textField({ label: t('author.step.image'), path: `${path}.image`, value: step.image, help: t('author.step.image.help'), onInput: (value) => ((step.image = value), onChange()) }),
+ ]
+ : [
+ i18nPair({ label: t('author.step.instruction'), path: `${path}.instruction`, value: step.instruction, multiline: true, rows: 2, onChange }),
+ textField({ label: t('author.step.starter'), path: `${path}.starter`, value: step.starter, multiline: true, rows: 6, code: true, help: t('author.step.starter.help'), onInput: (value) => ((step.starter = value), onChange()) }),
+ el('h4', { text: t('author.tests') }),
+ testsEditor({ t, tests: step.tests, path: `${path}.tests`, onChange, onStructure, addLabel: t('author.test.add') }),
+ i18nPair({ label: t('author.step.hints'), path: `${path}.hints`, value: step.hints, multiline: true, rows: 3, help: t('author.step.hints.help'), onChange }),
+ textField({ label: t('author.step.solution'), path: `${path}.solution`, value: step.solution, multiline: true, rows: 6, code: true, help: t('author.step.solution.help'), onInput: (value) => ((step.solution = value), onChange()) }),
+ ];
+ return el(
+ 'section',
+ { class: 'step-editor', 'aria-labelledby': `${path}-title` },
+ el(
+ 'div',
+ { class: 'step-header' },
+ el('h3', { id: `${path}-title`, text: t('author.step.title', { n: number, type: t(`author.step.type.${step.type}`) }) }),
+ el(
+ 'div',
+ { class: 'step-actions' },
+ el('button', { type: 'button', class: 'btn', 'data-path': `${path}.up`, disabled: index === 0, 'aria-label': t('author.step.up', { n: number }), text: '↑', onclick: () => actions.move(-1) }),
+ el('button', { type: 'button', class: 'btn', 'data-path': `${path}.down`, disabled: index === count - 1, 'aria-label': t('author.step.down', { n: number }), text: '↓', onclick: () => actions.move(1) }),
+ el('button', { type: 'button', class: 'btn', 'aria-label': t('author.step.remove', { n: number }), text: t('author.remove'), onclick: actions.remove }),
+ ),
+ ),
+ ...body,
+ );
+}
diff --git a/app/js/author/TestEditor.js b/app/js/author/TestEditor.js
new file mode 100644
index 0000000..0ef883f
--- /dev/null
+++ b/app/js/author/TestEditor.js
@@ -0,0 +1,83 @@
+// Éditeur d'un test déclaratif (un `tests[]` du niveau) : kind, champs adaptés au kind, saisies scriptées, message.
+
+import { el } from '../ui/dom.js';
+import { PYTHON_TYPES, TEST_KINDS } from './LevelDraft.js';
+import { i18nPair, selectField, textField } from './fields.js';
+
+/**
+ * @param {object} options
+ * @param {(key: string, params?: object) => string} options.t
+ * @param {object} options.test Modèle du test (modifié en place).
+ * @param {string} options.path Chemin du test, ex. 'steps.1.tests.0'.
+ * @param {number} options.number Numéro affiché (à partir de 1).
+ * @param {() => void} options.onChange Un champ a changé.
+ * @param {() => void} options.onStructure La forme du formulaire change (re-rendu nécessaire).
+ * @param {() => void} options.onRemove
+ */
+export function testEditor({ t, test, path, number, onChange, onStructure, onRemove }) {
+ const spec = TEST_KINDS[test.kind];
+ const fields = [
+ selectField({
+ label: t('author.test.kind'),
+ path: `${path}.kind`,
+ value: test.kind,
+ options: Object.keys(TEST_KINDS).map((kind) => [kind, t(`author.kind.${kind}`)]),
+ help: t(`author.kind.${test.kind}.help`),
+ onChange: (kind) => {
+ test.kind = kind;
+ onChange();
+ onStructure();
+ },
+ }),
+ ];
+ if (spec.name) {
+ fields.push(textField({ label: t('author.test.name'), path: `${path}.name`, value: test.name, code: true, onInput: (value) => ((test.name = value), onChange()) }));
+ }
+ if (spec.value === 'text') {
+ fields.push(
+ textField({
+ label: t('author.test.value'),
+ path: `${path}.value`,
+ value: test.value,
+ multiline: true,
+ rows: 2,
+ code: true,
+ help: test.kind === 'stdout_equals' ? t('author.test.value.newline') : test.kind === 'stdout_matches_regex' ? t('author.test.value.regex') : null,
+ onInput: (value) => ((test.value = value), onChange()),
+ }),
+ );
+ } else if (spec.value === 'typed') {
+ fields.push(
+ textField({ label: t('author.test.value'), path: `${path}.value`, value: test.value, code: true, onInput: (value) => ((test.value = value), onChange()) }),
+ selectField({
+ label: t('author.test.valueType'),
+ path: `${path}.valueType`,
+ value: test.valueType,
+ options: [['text', t('author.valueType.text')], ['number', t('author.valueType.number')], ['boolean', t('author.valueType.boolean')]],
+ help: t('author.test.valueType.help'),
+ onChange: (valueType) => ((test.valueType = valueType), onChange()),
+ }),
+ );
+ } else if (spec.value === 'type') {
+ fields.push(
+ selectField({
+ label: t('author.test.type'),
+ path: `${path}.value`,
+ value: PYTHON_TYPES.includes(test.value) ? test.value : '',
+ options: [['', '—'], ...PYTHON_TYPES.map((type) => [type, type])],
+ onChange: (value) => ((test.value = value), onChange()),
+ }),
+ );
+ }
+ fields.push(
+ textField({ label: t('author.test.inputs'), path: `${path}.inputs`, value: test.inputs, multiline: true, rows: 2, code: true, help: t('author.test.inputs.help'), onInput: (value) => ((test.inputs = value), onChange()) }),
+ el('details', { class: 'test-message' }, el('summary', { text: t('author.test.message') }), i18nPair({ label: t('author.test.message.label'), path: `${path}.message`, value: test.message, onChange })),
+ );
+ return el(
+ 'fieldset',
+ { class: 'test-editor' },
+ el('legend', { text: t('author.test.title', { n: number }) }),
+ ...fields,
+ el('button', { type: 'button', class: 'btn', 'aria-label': t('author.test.remove', { n: number }), text: t('author.remove'), onclick: onRemove }),
+ );
+}
diff --git a/app/js/author/fields.js b/app/js/author/fields.js
new file mode 100644
index 0000000..fb82293
--- /dev/null
+++ b/app/js/author/fields.js
@@ -0,0 +1,71 @@
+// Champs de formulaire accessibles de l'éditeur de niveaux : chaque champ a un label, un repère
+// `data-path` (même chemin que les problèmes du linter, pour « aller au champ ») et notifie le modèle.
+
+import { el, uniqueId } from '../ui/dom.js';
+
+function wrap(label, control, help) {
+ const helpId = help ? `${control.id}-help` : null;
+ if (helpId) {
+ control.setAttribute('aria-describedby', helpId);
+ }
+ return el('div', { class: 'field' }, el('label', { for: control.id, text: label }), control, help ? el('p', { class: 'field-help', id: helpId, text: help }) : null);
+}
+
+/** Champ texte sur une ligne ou zone de texte (code : police à chasse fixe, sans retour à la ligne automatique). */
+export function textField({ label, path, value, onInput, multiline = false, rows = 3, code = false, help = null, type = 'text' }) {
+ const control = multiline
+ ? el('textarea', { id: uniqueId('f'), rows, class: code ? 'mono' : null, wrap: code ? 'off' : null, spellcheck: code ? 'false' : null })
+ : el('input', { id: uniqueId('f'), type, class: code ? 'mono' : null });
+ control.dataset.path = path;
+ control.value = value;
+ control.addEventListener('input', () => onInput(control.value));
+ return wrap(label, control, help);
+}
+
+export function selectField({ label, path, value, options, onChange, help = null }) {
+ const control = el('select', { id: uniqueId('f') }, ...options.map(([optionValue, text]) => el('option', { value: optionValue, text, selected: optionValue === value })));
+ control.dataset.path = path;
+ control.addEventListener('change', () => onChange(control.value));
+ return wrap(label, control, help);
+}
+
+export function numberField({ label, path, value, min, max, onInput, help = null }) {
+ const control = el('input', { id: uniqueId('f'), type: 'number', min, max, step: 1 });
+ control.dataset.path = path;
+ control.value = String(value);
+ control.addEventListener('input', () => onInput(control.value === '' ? 0 : Number(control.value)));
+ return wrap(label, control, help);
+}
+
+export function checkboxField({ label, path, checked, onChange, help = null }) {
+ const control = el('input', { id: uniqueId('f'), type: 'checkbox', checked });
+ control.dataset.path = path;
+ control.addEventListener('change', () => onChange(control.checked));
+ const helpId = help ? `${control.id}-help` : null;
+ if (helpId) {
+ control.setAttribute('aria-describedby', helpId);
+ }
+ return el('div', { class: 'field field-check' }, control, el('label', { for: control.id, text: label }), help ? el('p', { class: 'field-help', id: helpId, text: help }) : null);
+}
+
+/**
+ * Paire de champs français / anglais pour un texte traduit. `value` est { fr, en } et est modifié en place.
+ * `path` est le chemin de l'objet i18n (ex. 'title') ; les champs sont repérés par `${path}.fr` et `${path}.en`.
+ */
+export function i18nPair({ label, path, value, onChange, multiline = false, rows = 3, code = false, help = null }) {
+ const make = (lang, langLabel) =>
+ textField({
+ label: `${label} — ${langLabel}`,
+ path: `${path}.${lang}`,
+ value: value[lang],
+ multiline,
+ rows,
+ code,
+ help: lang === 'fr' ? help : null,
+ onInput: (text) => {
+ value[lang] = text;
+ onChange();
+ },
+ });
+ return el('div', { class: 'i18n-pair' }, make('fr', 'Français'), make('en', 'English'));
+}
diff --git a/app/js/author/main.js b/app/js/author/main.js
new file mode 100644
index 0000000..bf99526
--- /dev/null
+++ b/app/js/author/main.js
@@ -0,0 +1,77 @@
+// Point d'entrée de l'éditeur de niveaux (mode auteur) : assemble les modules et lance l'application.
+
+import { IndexedDbKeyValueStore, MemoryKeyValueStore } from '../core/KeyValueStores.js';
+import { LessonEngine } from '../core/LessonEngine.js';
+import { LevelLinter } from '../core/LevelLinter.js';
+import { I18n } from '../i18n/i18n.js';
+import { AuthorApp } from './AuthorApp.js';
+
+const LANGUAGES = ['fr', 'en'];
+
+async function loadJson(url) {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Cannot load ${url}`);
+ }
+ return response.json();
+}
+
+const json = (path) => loadJson(new URL(path, import.meta.url));
+
+/** Magasin IndexedDB si utilisable, sinon mémoire (les brouillons ne survivraient pas au rechargement). */
+async function openStore(name) {
+ try {
+ const store = new IndexedDbKeyValueStore(name);
+ await store.get('probe');
+ return store;
+ } catch {
+ return new MemoryKeyValueStore();
+ }
+}
+
+/** Reprend langue, thème et taille de texte choisis dans l'application (lecture seule). */
+async function readLearnerSettings() {
+ try {
+ return (await new IndexedDbKeyValueStore('pyquest').get('settings')) ?? {};
+ } catch {
+ return {};
+ }
+}
+
+async function main() {
+ const [app, author, errors, guide, schema, settings] = await Promise.all([
+ Promise.all(LANGUAGES.map((lang) => json(`../i18n/${lang}.json`))),
+ Promise.all(LANGUAGES.map((lang) => json(`../i18n/author.${lang}.json`))),
+ Promise.all(LANGUAGES.map((lang) => json(`../i18n/errors.${lang}.json`))),
+ Promise.all(LANGUAGES.map((lang) => json(`../i18n/guide.${lang}.json`))),
+ loadJson(new URL('/levels/schema/level.schema.json', location.href)),
+ readLearnerSettings(),
+ ]);
+ const byLang = (list) => Object.fromEntries(LANGUAGES.map((lang, index) => [lang, list[index]]));
+ // Un seul catalogue par langue : textes de l'application (pour l'essai) + textes de l'éditeur.
+ const catalogs = Object.fromEntries(LANGUAGES.map((lang, index) => [lang, { ...app[index], ...author[index] }]));
+
+ const root = document.documentElement;
+ root.style.setProperty('--font-scale', String((settings.fontSize ?? 100) / 100));
+ if (settings.theme && settings.theme !== 'auto') {
+ root.setAttribute('data-theme', settings.theme);
+ }
+ root.dataset.guide = settings.guideEnabled === false ? 'off' : 'on';
+
+ const i18n = new I18n(catalogs, settings.lang ?? 'fr');
+ root.lang = i18n.lang;
+ i18n.addEventListener('change', () => (root.lang = i18n.lang));
+
+ await new AuthorApp({
+ i18n,
+ linter: new LevelLinter(schema),
+ lessons: new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href }),
+ store: await openStore('pyquest-author'),
+ catalogs: { errors: byLang(errors), guide: byLang(guide) },
+ root: document.getElementById('author-root'),
+ }).run();
+}
+
+main().catch((error) => {
+ document.getElementById('author-root').textContent = `PyQuest: ${error.message}`;
+});
diff --git a/app/js/core/LevelChecker.js b/app/js/core/LevelChecker.js
index 47cccdd..a2d290a 100644
--- a/app/js/core/LevelChecker.js
+++ b/app/js/core/LevelChecker.js
@@ -45,7 +45,8 @@ export class LevelChecker {
const summary = [];
let done = 0;
for (const { path, exercise } of exercises) {
- const add = (severity, code, params = {}) => problems.push({ severity, code, path, params });
+ // Chemin du champ en cause : la solution pour ses échecs, le code de départ pour les siens.
+ const add = (severity, code, params = {}) => problems.push({ severity, code, path: [...path, code.startsWith('starter') ? 'starter' : 'solution'], params });
const entry = { path, runOnly: false, solutionPassed: null };
summary.push(entry);
onProgress(done, exercises.length);
diff --git a/app/js/core/LevelLinter.js b/app/js/core/LevelLinter.js
index 6846768..cdfbaa8 100644
--- a/app/js/core/LevelLinter.js
+++ b/app/js/core/LevelLinter.js
@@ -180,12 +180,14 @@ export class LevelLinter {
// ---- Règles de contribution et cohérence des tests ----------------------------------------------------
#contribution(level, add) {
+ // Un seul rappel pour toutes les étapes narrées (sinon une ligne par étape noie le reste).
+ const narrated = level.steps.map((step, index) => (step.type === 'explain' && step.voice ? index : null)).filter((index) => index !== null);
+ if (narrated.length > 0) {
+ add('info', 'voice_to_generate', ['steps', narrated[0]], { steps: narrated.map((index) => index + 1).join(', ') });
+ }
level.steps.forEach((step, index) => {
const path = ['steps', index];
if (step.type === 'explain') {
- if (step.voice) {
- add('info', 'voice_to_generate', path);
- }
return;
}
this.#tests(step.tests, [...path, 'tests'], add);
diff --git a/app/js/core/SettingsStore.js b/app/js/core/SettingsStore.js
index c7114cb..714b349 100644
--- a/app/js/core/SettingsStore.js
+++ b/app/js/core/SettingsStore.js
@@ -11,6 +11,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
voiceEnabled: true, // le bouton « Écouter » ne lit jamais automatiquement : un clic à chaque fois
voiceRate: 1,
guideEnabled: true, // personnage-guide (bulles d'encouragement)
+ authorMode: false, // affiche le lien vers l'éditeur de niveaux (mode auteur)
});
export class SettingsStore extends EventTarget {
diff --git a/app/js/i18n/author.en.json b/app/js/i18n/author.en.json
new file mode 100644
index 0000000..7ef590c
--- /dev/null
+++ b/app/js/i18n/author.en.json
@@ -0,0 +1,147 @@
+{
+ "author.title": "Level editor — author mode",
+ "author.skip": "Go to the form",
+ "author.language": "Editor language",
+ "author.toolbar.label": "Level actions",
+ "author.toolbar.new": "New level",
+ "author.toolbar.load_select": "Site level to load",
+ "author.toolbar.load": "Load this level",
+ "author.toolbar.import": "Import a YAML file",
+ "author.toolbar.download": "Download level.yaml",
+ "author.toolbar.back": "Back to the app",
+ "author.confirm.new": "Start a new level? The current draft will be replaced.",
+ "author.confirm.load": "Load level {id}? The current draft will be replaced.",
+ "author.status.saved": "Draft saved in this browser at {time}.",
+ "author.status.draft_restored": "Previous draft restored.",
+ "author.status.loaded": "Level {id} loaded: edit it, then download the file.",
+ "author.status.imported": "File {name} imported.",
+ "author.status.import_error": "Import failed: {detail}",
+ "author.status.downloaded": "level.yaml downloaded for level {id}.",
+ "author.status.downloaded_with_errors": "level.yaml downloaded, but {count} error(s) remain to fix before proposing it.",
+ "author.section.info": "Level information",
+ "author.section.steps": "Steps",
+ "author.section.steps.help": "One new notion per step. Alternate explanations and code exercises.",
+ "author.section.mission": "Final mission",
+ "author.section.problems": "Checks",
+ "author.section.check": "Run the exercises",
+ "author.section.preview": "Try it as a learner",
+ "author.section.export": "Publish the level",
+ "author.level.id": "Identifier",
+ "author.level.id.help": "Two digits, a dash, a short lowercase name (e.g. 08-functions). It must equal the folder name levels//.",
+ "author.level.title": "Level title",
+ "author.level.difficulty": "Difficulty (0 to 10)",
+ "author.level.difficulty.help": "0 = no prerequisite.",
+ "author.level.xp": "Mission XP",
+ "author.level.xp.help": "Awarded once, at the end of the level.",
+ "author.level.requires": "Prerequisite levels",
+ "author.level.requires.help": "Informative only: never prevents opening the level.",
+ "author.level.requires.none": "No other level exists yet.",
+ "author.step.title": "Step {n} — {type}",
+ "author.step.type.explain": "Explanation",
+ "author.step.type.code": "Code exercise",
+ "author.step.add.explain": "Add an explanation",
+ "author.step.add.code": "Add a code exercise",
+ "author.step.up": "Move step {n} up",
+ "author.step.down": "Move step {n} down",
+ "author.step.remove": "Remove step {n}",
+ "author.step.text": "Text",
+ "author.step.text.help": "Short sentences. Inline code goes between backticks: `print()`.",
+ "author.step.voice": "Offer voice narration",
+ "author.step.voice.help": "Adds a \"Listen\" button. The audio file is then generated with make voice.",
+ "author.step.image": "Image (optional)",
+ "author.step.image.help": "Path relative to the level folder.",
+ "author.step.instruction": "Instruction",
+ "author.step.starter": "Starter code",
+ "author.step.starter.help": "It must run as is, without errors, and must not already pass the tests (except for a \"run to see\" step).",
+ "author.step.hints": "Hints",
+ "author.step.hints.help": "One hint per line, from vaguest to most precise. Same count in French and English.",
+ "author.step.solution": "Reference solution",
+ "author.step.solution.help": "Required: it is executed to check that the tests are right.",
+ "author.tests": "Validation tests",
+ "author.test.title": "Test {n}",
+ "author.test.add": "Add a test",
+ "author.test.remove": "Remove test {n}",
+ "author.test.kind": "Test type",
+ "author.test.name": "Variable name",
+ "author.test.value": "Expected value",
+ "author.test.value.newline": "Exact output: press Enter at the end of the text to expect a final line break (print adds one).",
+ "author.test.value.regex": "Regular expression applied to the whole output. If the program asks for input, the prompt is part of the output.",
+ "author.test.valueType": "Value type",
+ "author.test.valueType.help": "An integer and a decimal that are equal (10 and 10.0) count as the same value; add a \"variable type\" test to tell them apart.",
+ "author.test.type": "Expected type",
+ "author.test.inputs": "Scripted inputs (optional)",
+ "author.test.inputs.help": "One per line, answered in order to input(). The test is then evaluated on a replay of the code with these inputs.",
+ "author.test.message": "Message if the test fails (optional)",
+ "author.test.message.label": "Failure message",
+ "author.valueType.text": "Text",
+ "author.valueType.number": "Number",
+ "author.valueType.boolean": "True / false",
+ "author.kind.no_syntax_error": "No syntax error",
+ "author.kind.no_syntax_error.help": "The code runs without a syntax error.",
+ "author.kind.stdout_equals": "Output exactly equal",
+ "author.kind.stdout_equals.help": "Everything printed, final line break included.",
+ "author.kind.stdout_contains": "Output contains",
+ "author.kind.stdout_contains.help": "A piece of text present in the output.",
+ "author.kind.stdout_matches_regex": "Output matches a regular expression",
+ "author.kind.stdout_matches_regex.help": "Useful for randomness or varying output.",
+ "author.kind.code_contains": "Code contains",
+ "author.kind.code_contains.help": "Checks the use of a notion (e.g. random.choice, while).",
+ "author.kind.var_equals": "Variable equals",
+ "author.kind.var_equals.help": "Value of a variable after execution.",
+ "author.kind.var_type_is": "Variable type",
+ "author.kind.var_type_is.help": "Type of a variable after execution (str, int, float…).",
+ "author.mission.title": "Mission title",
+ "author.mission.goal": "Goal",
+ "author.mission.tests.help": "Without tests, the mission is validated with a simple \"I understand\" button (like level 00).",
+ "author.mission.reward": "Reward sound",
+ "author.remove": "Remove",
+ "author.path.step": "Step {n}",
+ "author.path.test": "Test {n}",
+ "author.path.mission": "Mission",
+ "author.severity.error": "Error",
+ "author.severity.warning": "Warning",
+ "author.severity.info": "Good to know",
+ "author.problems.none": "No problem detected.",
+ "author.problems.summary": "{errors} error(s), {warnings} warning(s), {infos} note(s).",
+ "author.problems.goto": "Go to field",
+ "author.check.help": "Runs, with real Python, each exercise's solution (it must pass its tests) and its starter code (it must not pass them).",
+ "author.check.run": "Run the exercises",
+ "author.check.starting": "Starting Python…",
+ "author.check.progress": "Exercise {done} of {total}…",
+ "author.check.passed": "All {count} exercise(s) are correct.",
+ "author.check.failed": "Some exercises have problems (see the checks).",
+ "author.check.fix_structure": "First fix the structure errors reported in the checks.",
+ "author.preview.help": "Plays this level in the real learner interface. Progress is not saved.",
+ "author.preview.start": "Try this level",
+ "author.export.step1": "Download level.yaml (toolbar) and place it in levels//level.yaml.",
+ "author.export.step2": "Add the level to levels/manifest.json (line below).",
+ "author.export.step3": "Run make validate-levels.",
+ "author.export.step4": "If steps have narration enabled, run make voice and add the audio files.",
+ "author.export.step5": "Run make test, then propose your contribution (see CONTRIBUTING.md).",
+ "author.export.manifest": "Line to add to levels/manifest.json:",
+ "author.export.yaml": "Contents of level.yaml",
+ "lint.schema_required": "Required field missing: {field}.",
+ "lint.schema_unknown_field": "Unknown field: {field}.",
+ "lint.schema_pattern": "Invalid format (two digits, dash, lowercase name).",
+ "lint.schema_enum": "Value not allowed here.",
+ "lint.schema_type": "Wrong value type.",
+ "lint.schema_range": "Value out of range, or list too short.",
+ "lint.schema_invalid": "Invalid structure: {detail}",
+ "lint.missing_english": "English translation missing.",
+ "lint.hint_count_differs": "Hint counts differ: {fr} in French, {en} in English.",
+ "lint.id_already_exists": "A level {id} already exists: the file would replace it.",
+ "lint.requires_self": "A level cannot be its own prerequisite.",
+ "lint.requires_unknown": "Unknown prerequisite: {id}.",
+ "lint.solution_missing": "Reference solution missing.",
+ "lint.hints_missing": "No hint: providing at least one helps stuck learners.",
+ "lint.kind_unsupported": "The \"{kind}\" test is not handled by the engine yet.",
+ "lint.test_name_missing": "Variable name missing.",
+ "lint.test_value_missing": "Expected value missing.",
+ "lint.type_unusual": "Unusual type. Usual types: {allowed}.",
+ "lint.regex_invalid": "Invalid regular expression: {detail}",
+ "lint.voice_to_generate": "Narration enabled on steps {steps}: run make voice to generate the audio before proposing the level.",
+ "lint.solution_error": "The solution crashes: {type} — {message}{line}",
+ "lint.solution_fails": "The solution does not pass its tests: {failures}.",
+ "lint.starter_passes": "The starter code already passes the tests: the exercise would already be solved.",
+ "lint.starter_error": "The starter code does not run: {type} — {message}{line}"
+}
diff --git a/app/js/i18n/author.fr.json b/app/js/i18n/author.fr.json
new file mode 100644
index 0000000..187cd0d
--- /dev/null
+++ b/app/js/i18n/author.fr.json
@@ -0,0 +1,147 @@
+{
+ "author.title": "Éditeur de niveaux — mode auteur",
+ "author.skip": "Aller au formulaire",
+ "author.language": "Langue de l'éditeur",
+ "author.toolbar.label": "Actions sur le niveau",
+ "author.toolbar.new": "Nouveau niveau",
+ "author.toolbar.load_select": "Niveau du site à charger",
+ "author.toolbar.load": "Charger ce niveau",
+ "author.toolbar.import": "Importer un fichier YAML",
+ "author.toolbar.download": "Télécharger level.yaml",
+ "author.toolbar.back": "Retour à l'application",
+ "author.confirm.new": "Commencer un nouveau niveau ? Le brouillon actuel sera remplacé.",
+ "author.confirm.load": "Charger le niveau {id} ? Le brouillon actuel sera remplacé.",
+ "author.status.saved": "Brouillon enregistré dans ce navigateur à {time}.",
+ "author.status.draft_restored": "Brouillon précédent restauré.",
+ "author.status.loaded": "Niveau {id} chargé : modifie-le puis télécharge le fichier.",
+ "author.status.imported": "Fichier {name} importé.",
+ "author.status.import_error": "Import impossible : {detail}",
+ "author.status.downloaded": "level.yaml téléchargé pour le niveau {id}.",
+ "author.status.downloaded_with_errors": "level.yaml téléchargé, mais {count} erreur(s) restent à corriger avant de le proposer.",
+ "author.section.info": "Informations du niveau",
+ "author.section.steps": "Étapes",
+ "author.section.steps.help": "Une seule notion nouvelle par étape. Alterne explications et exercices de code.",
+ "author.section.mission": "Mission finale",
+ "author.section.problems": "Vérifications",
+ "author.section.check": "Exécuter les exercices",
+ "author.section.preview": "Essayer comme apprenant",
+ "author.section.export": "Publier le niveau",
+ "author.level.id": "Identifiant",
+ "author.level.id.help": "Deux chiffres, un tiret, un nom court en minuscules (ex. 08-functions). Il doit être identique au nom du dossier levels//.",
+ "author.level.title": "Titre du niveau",
+ "author.level.difficulty": "Difficulté (0 à 10)",
+ "author.level.difficulty.help": "0 = aucun prérequis.",
+ "author.level.xp": "XP de la mission",
+ "author.level.xp.help": "Accordés une seule fois, à la fin du niveau.",
+ "author.level.requires": "Niveaux prérequis",
+ "author.level.requires.help": "Indicatif : n'empêche jamais d'ouvrir le niveau.",
+ "author.level.requires.none": "Aucun autre niveau n'existe pour l'instant.",
+ "author.step.title": "Étape {n} — {type}",
+ "author.step.type.explain": "Explication",
+ "author.step.type.code": "Exercice de code",
+ "author.step.add.explain": "Ajouter une explication",
+ "author.step.add.code": "Ajouter un exercice de code",
+ "author.step.up": "Monter l'étape {n}",
+ "author.step.down": "Descendre l'étape {n}",
+ "author.step.remove": "Supprimer l'étape {n}",
+ "author.step.text": "Texte",
+ "author.step.text.help": "Phrases courtes. Le code en ligne s'écrit entre apostrophes inversées : `print()`.",
+ "author.step.voice": "Proposer la narration vocale",
+ "author.step.voice.help": "Ajoute un bouton « Écouter ». Le fichier audio se génère ensuite avec make voice.",
+ "author.step.image": "Image (facultatif)",
+ "author.step.image.help": "Chemin relatif au dossier du niveau.",
+ "author.step.instruction": "Consigne",
+ "author.step.starter": "Code de départ",
+ "author.step.starter.help": "Doit s'exécuter tel quel, sans erreur, et ne pas passer déjà les tests (sauf étape « exécute pour voir »).",
+ "author.step.hints": "Indices",
+ "author.step.hints.help": "Un indice par ligne, du plus vague au plus précis. Même nombre en français et en anglais.",
+ "author.step.solution": "Solution de référence",
+ "author.step.solution.help": "Obligatoire : elle est exécutée pour vérifier que les tests sont justes.",
+ "author.tests": "Tests de validation",
+ "author.test.title": "Test {n}",
+ "author.test.add": "Ajouter un test",
+ "author.test.remove": "Supprimer le test {n}",
+ "author.test.kind": "Type de test",
+ "author.test.name": "Nom de la variable",
+ "author.test.value": "Valeur attendue",
+ "author.test.value.newline": "Sortie exacte : appuie sur Entrée en fin de texte pour attendre un retour à la ligne final (print en ajoute un).",
+ "author.test.value.regex": "Expression régulière appliquée à toute la sortie. Si le programme demande une saisie, l'invite est dans la sortie.",
+ "author.test.valueType": "Type de la valeur",
+ "author.test.valueType.help": "Un entier et un décimal égaux (10 et 10.0) comptent pour la même valeur ; ajoute un test « type de variable » pour les distinguer.",
+ "author.test.type": "Type attendu",
+ "author.test.inputs": "Saisies scriptées (facultatif)",
+ "author.test.inputs.help": "Une par ligne, répondues dans l'ordre aux input(). Le test est alors évalué sur un rejeu du code avec ces saisies.",
+ "author.test.message": "Message si le test échoue (facultatif)",
+ "author.test.message.label": "Message d'échec",
+ "author.valueType.text": "Texte",
+ "author.valueType.number": "Nombre",
+ "author.valueType.boolean": "Vrai / faux",
+ "author.kind.no_syntax_error": "Pas d'erreur de syntaxe",
+ "author.kind.no_syntax_error.help": "Le code s'exécute sans erreur de syntaxe.",
+ "author.kind.stdout_equals": "Sortie exactement égale",
+ "author.kind.stdout_equals.help": "Tout ce qui est affiché, retour à la ligne final compris.",
+ "author.kind.stdout_contains": "Sortie contient",
+ "author.kind.stdout_contains.help": "Un morceau de texte présent dans la sortie.",
+ "author.kind.stdout_matches_regex": "Sortie conforme à une expression régulière",
+ "author.kind.stdout_matches_regex.help": "Utile pour du hasard ou des sorties qui varient.",
+ "author.kind.code_contains": "Le code contient",
+ "author.kind.code_contains.help": "Vérifie l'usage d'une notion (ex. random.choice, while).",
+ "author.kind.var_equals": "Variable égale à",
+ "author.kind.var_equals.help": "Valeur d'une variable après exécution.",
+ "author.kind.var_type_is": "Type de variable",
+ "author.kind.var_type_is.help": "Type d'une variable après exécution (str, int, float…).",
+ "author.mission.title": "Titre de la mission",
+ "author.mission.goal": "Objectif",
+ "author.mission.tests.help": "Sans test, la mission se valide par un simple bouton « Je comprends » (comme au niveau 00).",
+ "author.mission.reward": "Son de récompense",
+ "author.remove": "Supprimer",
+ "author.path.step": "Étape {n}",
+ "author.path.test": "Test {n}",
+ "author.path.mission": "Mission",
+ "author.severity.error": "Erreur",
+ "author.severity.warning": "Avertissement",
+ "author.severity.info": "À savoir",
+ "author.problems.none": "Aucun problème détecté.",
+ "author.problems.summary": "{errors} erreur(s), {warnings} avertissement(s), {infos} information(s).",
+ "author.problems.goto": "Aller au champ",
+ "author.check.help": "Exécute avec le vrai Python la solution de chaque exercice (elle doit passer ses tests) et son code de départ (il ne doit pas les passer).",
+ "author.check.run": "Exécuter les exercices",
+ "author.check.starting": "Démarrage de Python…",
+ "author.check.progress": "Exercice {done} sur {total}…",
+ "author.check.passed": "Les {count} exercice(s) sont corrects.",
+ "author.check.failed": "Des exercices posent problème (voir les vérifications).",
+ "author.check.fix_structure": "Corrige d'abord les erreurs de structure signalées dans les vérifications.",
+ "author.preview.help": "Joue ce niveau dans l'interface réelle de l'apprenant. La progression n'est pas enregistrée.",
+ "author.preview.start": "Essayer ce niveau",
+ "author.export.step1": "Télécharge level.yaml (barre d'outils) et place-le dans levels//level.yaml.",
+ "author.export.step2": "Ajoute le niveau à levels/manifest.json (ligne ci-dessous).",
+ "author.export.step3": "Lance make validate-levels.",
+ "author.export.step4": "Si des étapes ont la narration activée, lance make voice et ajoute les fichiers audio.",
+ "author.export.step5": "Lance make test, puis propose ta contribution (voir CONTRIBUTING.md).",
+ "author.export.manifest": "Ligne à ajouter à levels/manifest.json :",
+ "author.export.yaml": "Contenu du fichier level.yaml",
+ "lint.schema_required": "Champ obligatoire manquant : {field}.",
+ "lint.schema_unknown_field": "Champ inconnu : {field}.",
+ "lint.schema_pattern": "Format invalide (deux chiffres, tiret, nom en minuscules).",
+ "lint.schema_enum": "Valeur non autorisée ici.",
+ "lint.schema_type": "Type de valeur incorrect.",
+ "lint.schema_range": "Valeur hors limites, ou liste trop courte.",
+ "lint.schema_invalid": "Structure invalide : {detail}",
+ "lint.missing_english": "Traduction anglaise manquante.",
+ "lint.hint_count_differs": "Le nombre d'indices diffère : {fr} en français, {en} en anglais.",
+ "lint.id_already_exists": "Un niveau {id} existe déjà : le fichier le remplacerait.",
+ "lint.requires_self": "Un niveau ne peut pas être son propre prérequis.",
+ "lint.requires_unknown": "Prérequis inconnu : {id}.",
+ "lint.solution_missing": "Solution de référence manquante.",
+ "lint.hints_missing": "Aucun indice : prévoir au moins un indice aide les apprenants bloqués.",
+ "lint.kind_unsupported": "Le test « {kind} » n'est pas encore géré par le moteur.",
+ "lint.test_name_missing": "Nom de variable manquant.",
+ "lint.test_value_missing": "Valeur attendue manquante.",
+ "lint.type_unusual": "Type inhabituel. Types usuels : {allowed}.",
+ "lint.regex_invalid": "Expression régulière invalide : {detail}",
+ "lint.voice_to_generate": "Narration activée aux étapes {steps} : lance make voice pour générer l'audio avant de proposer le niveau.",
+ "lint.solution_error": "La solution plante : {type} — {message}{line}",
+ "lint.solution_fails": "La solution ne passe pas ses tests : {failures}.",
+ "lint.starter_passes": "Le code de départ passe déjà les tests : l'exercice serait déjà résolu.",
+ "lint.starter_error": "Le code de départ ne s'exécute pas : {type} — {message}{line}"
+}
diff --git a/app/js/i18n/en.json b/app/js/i18n/en.json
index e98187f..5fa2425 100644
--- a/app/js/i18n/en.json
+++ b/app/js/i18n/en.json
@@ -58,6 +58,8 @@
"settings.theme.light": "Light",
"settings.theme.dark": "Dark",
"settings.guide": "Guide character",
+ "settings.author": "Author mode",
+ "settings.authorOpen": "Open the level editor",
"settings.sound": "Sound effects",
"settings.volume": "Volume",
"settings.voice": "Voice",
diff --git a/app/js/i18n/fr.json b/app/js/i18n/fr.json
index 5575af5..6aae56f 100644
--- a/app/js/i18n/fr.json
+++ b/app/js/i18n/fr.json
@@ -58,6 +58,8 @@
"settings.theme.light": "Clair",
"settings.theme.dark": "Sombre",
"settings.guide": "Personnage-guide",
+ "settings.author": "Mode auteur",
+ "settings.authorOpen": "Ouvrir l'éditeur de niveaux",
"settings.sound": "Effets sonores",
"settings.volume": "Volume",
"settings.voice": "Voix",
diff --git a/app/js/ui/SettingsPanel.js b/app/js/ui/SettingsPanel.js
index c817706..5db5d3b 100644
--- a/app/js/ui/SettingsPanel.js
+++ b/app/js/ui/SettingsPanel.js
@@ -41,6 +41,8 @@ export class SettingsPanel extends EventTarget {
this.#field('settings.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }),
this.#testButton('settings.testVoice', 'voice'),
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
+ this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
+ settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
);
}
diff --git a/docs/design/08-author-editor.md b/docs/design/08-author-editor.md
new file mode 100644
index 0000000..5ae244b
--- /dev/null
+++ b/docs/design/08-author-editor.md
@@ -0,0 +1,61 @@
+# Éditeur de niveaux (mode auteur)
+
+Décidé le 2026-10-16 : ouvrir le projet à des contributeurs avec un outil convivial pour composer les
+niveaux, **sans serveur** (le backend Django reste réservé à la synchronisation de la progression).
+
+## Accès
+
+Page statique `app/author.html` (`/author.html`). Le réglage « Mode auteur » de l'application affiche
+un lien vers elle ; elle n'est jamais proposée aux apprenants autrement.
+
+## Ce qu'il fait
+
+- **Formulaires** pour les informations du niveau, les étapes (explication / exercice de code), les
+ tests déclaratifs (kind, valeur, saisies scriptées, message), les indices, les solutions et la
+ mission. Chaque texte est saisi en français **et** en anglais, côte à côte.
+- **Vérifications en direct** (`core/LevelLinter.js`) : conformité au schéma (messages ciblés, pas de
+ cascade), traductions `en`, `requires`, solutions présentes, cohérence des tests, expressions
+ régulières, rappels (narration à générer). Même esprit que `scripts/validate_levels.py`.
+- **Exécution avec le vrai Python** (`core/LevelChecker.js`, bouton « Exécuter les exercices ») : la
+ solution de chaque exercice passe ses tests, le code de départ ne les passe pas. Même module que
+ `make test`.
+- **Essai comme apprenant** : le niveau joué dans la vraie interface (`CellManager`), progression en
+ mémoire (jamais enregistrée).
+- **Export** : `level.yaml` au style du projet (4 espaces, `- clé:` compacté), ligne à ajouter au
+ manifeste, étapes à suivre (`make validate-levels`, `make voice`, `make test`). Import d'un fichier ou
+ chargement d'un niveau existant pour le modifier. Brouillon enregistré dans le navigateur (IndexedDB).
+
+## Organisation du code
+
+| Module | Rôle |
+|---|---|
+| `author/LevelDraft.js` | modèle de formulaire ⇄ niveau du schéma (`toLevel` / `fromLevel`), YAML |
+| `author/{fields,TestEditor,StepEditor,LevelForm}.js` | formulaires accessibles (labels, `data-path`, fieldsets) |
+| `author/ProblemsPanel.js` | affichage des vérifications, bouton « aller au champ » |
+| `author/AuthorApp.js` | orchestration (brouillon, vérifications, essai, export) |
+| `core/LevelLinter.js`, `core/LevelChecker.js` | vérifications statiques et d'exécution (partagées avec les tests) |
+| `lib/json-schema/` | `@cfworker/json-schema` 4.1.1 (MIT) vendorisé, sans `eval` |
+| `i18n/author.{fr,en}.json` | textes de l'éditeur + messages `lint.` |
+
+## Garde-fous (tests)
+
+- `level-draft.test.mjs` : `toLevel(fromLevel(niveau))` redonne **exactement** chaque niveau existant,
+ le YAML exporté se recharge à l'identique et est accepté par `scripts/validate_levels.py`.
+- `level-linter.test.mjs` : aucun problème bloquant sur les vrais niveaux ; chaque défaut fabriqué est
+ détecté, au bon chemin.
+- `level-solutions.integration.test.mjs` : `LevelChecker` sur les vrais niveaux et sur des niveaux fautifs.
+- `author-i18n.test.mjs` : toutes les clés utilisées existent en fr et en, un message par code de problème.
+- e2e : écrire un niveau de A à Z dans le navigateur, le vérifier, l'essayer, télécharger un fichier valide.
+
+## Ajouter un kind de test (évolution du moteur)
+
+1. `ValidationEngine` : interpréter le kind (+ `supportedKinds`) ; 2. `levels/schema/level.schema.json` :
+l'ajouter à l'enum ; 3. `author/LevelDraft.js` : l'ajouter à `TEST_KINDS` ; 4. catalogues : `author.kind.`
+et `.help` ; 5. `core/LevelLinter.js` si des règles de cohérence s'imposent ; 6. tests unitaires.
+
+## Limites connues
+
+- La narration (Piper) ne se génère pas dans le navigateur : l'auteur la fait générer avec `make voice`
+ avant la fusion (le linter le rappelle).
+- Les saisies scriptées sont une par ligne : une saisie vide au milieu est possible, pas en dernière position.
+- Un niveau n'est pas publié par l'éditeur : il produit un fichier à proposer par pull request.
diff --git a/tests/e2e/e2e.test.mjs b/tests/e2e/e2e.test.mjs
index 44a6c46..c690ffe 100644
--- a/tests/e2e/e2e.test.mjs
+++ b/tests/e2e/e2e.test.mjs
@@ -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, []);
+});
diff --git a/tests/js/author-i18n.test.mjs b/tests/js/author-i18n.test.mjs
new file mode 100644
index 0000000..2ddcc19
--- /dev/null
+++ b/tests/js/author-i18n.test.mjs
@@ -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');
diff --git a/tests/js/level-solutions.integration.test.mjs b/tests/js/level-solutions.integration.test.mjs
index 085bd3b..00ff042 100644
--- a/tests/js/level-solutions.integration.test.mjs
+++ b/tests/js/level-solutions.integration.test.mjs
@@ -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 {