From 57bda6eecfbe8acbc253b29c82c0150a1401e1dc Mon Sep 17 00:00:00 2001 From: denis Date: Fri, 16 Oct 2026 16:51:33 +0200 Subject: [PATCH] Add author-mode level editor: forms, live checks, Python execution of solutions, learner preview, YAML export Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 3 + CONTEXT.md | 10 + CONTRIBUTING.md | 10 +- README-EN.md | 1 + README.md | 1 + app/author.html | 21 ++ app/css/author.css | 289 ++++++++++++++++ app/css/base.css | 7 + app/js/author/AuthorApp.js | 310 ++++++++++++++++++ app/js/author/LevelForm.js | 167 ++++++++++ app/js/author/ProblemsPanel.js | 83 +++++ app/js/author/StepEditor.js | 87 +++++ app/js/author/TestEditor.js | 83 +++++ app/js/author/fields.js | 71 ++++ app/js/author/main.js | 77 +++++ app/js/core/LevelChecker.js | 3 +- app/js/core/LevelLinter.js | 8 +- app/js/core/SettingsStore.js | 1 + app/js/i18n/author.en.json | 147 +++++++++ app/js/i18n/author.fr.json | 147 +++++++++ app/js/i18n/en.json | 2 + app/js/i18n/fr.json | 2 + app/js/ui/SettingsPanel.js | 2 + docs/design/08-author-editor.md | 61 ++++ tests/e2e/e2e.test.mjs | 80 +++++ tests/js/author-i18n.test.mjs | 39 +++ tests/js/level-solutions.integration.test.mjs | 10 +- 27 files changed, 1712 insertions(+), 10 deletions(-) create mode 100644 app/author.html create mode 100644 app/css/author.css create mode 100644 app/js/author/AuthorApp.js create mode 100644 app/js/author/LevelForm.js create mode 100644 app/js/author/ProblemsPanel.js create mode 100644 app/js/author/StepEditor.js create mode 100644 app/js/author/TestEditor.js create mode 100644 app/js/author/fields.js create mode 100644 app/js/author/main.js create mode 100644 app/js/i18n/author.en.json create mode 100644 app/js/i18n/author.fr.json create mode 100644 docs/design/08-author-editor.md create mode 100644 tests/js/author-i18n.test.mjs 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 @@ + + + + + + + PyQuest — éditeur de niveaux + + + + + + + + + +
+ + + + diff --git a/app/css/author.css b/app/css/author.css new file mode 100644 index 0000000..bfe3dc5 --- /dev/null +++ b/app/css/author.css @@ -0,0 +1,289 @@ +/* Éditeur de niveaux (mode auteur) : formulaires, vérifications, panneau latéral. */ + +.author-header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem 1.5rem; + padding: 0.75rem 1rem; + background: var(--surface); + border-bottom: 1px solid var(--border); +} + +.author-header h1 { + margin: 0; + font-size: 1.25rem; +} + +.author-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +.author-toolbar select, +.author-header select { + min-height: 2.75rem; + font: inherit; +} + +.author-toolbar a.btn, +.author-toolbar label.btn { + display: inline-flex; + align-items: center; + text-decoration: none; +} + +.author-status { + flex-basis: 100%; + margin: 0; + color: var(--muted); + min-height: 1.5em; +} + +.author-layout { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(18rem, 26rem); + gap: 1.5rem; + max-width: 90rem; + margin: 0 auto; + padding: 1rem; +} + +.author-side { + align-self: start; + position: sticky; + top: 0.5rem; + max-height: calc(100vh - 1rem); + overflow-y: auto; +} + +.form-section, +.side-section { + margin: 0 0 1.5rem; +} + +.form-section > h2, +.side-section > h2 { + margin: 0 0 0.75rem; + font-size: 1.2rem; + border-bottom: 2px solid var(--border); + padding-bottom: 0.25rem; +} + +.field { + display: flex; + flex-direction: column; + gap: 0.25rem; + margin: 0.75rem 0; +} + +.field label { + font-weight: 700; +} + +.field input[type="text"], +.field input[type="number"], +.field select, +.field textarea { + width: 100%; + box-sizing: border-box; + min-height: 2.5rem; + padding: 0.4rem 0.6rem; + font: inherit; + background: var(--bg); + color: var(--text); + border: 1px solid var(--border); + border-radius: 0.375rem; +} + +.field textarea.mono, +.field input.mono, +pre.mono, +textarea.mono { + font-family: var(--font-code); + font-variant-ligatures: none; + font-size: 0.95rem; + tab-size: 4; +} + +textarea.mono { + width: 100%; + box-sizing: border-box; + background: var(--code); + color: var(--text); + border: 1px solid var(--border); + border-radius: 0.375rem; + padding: 0.5rem; +} + +pre.mono { + margin: 0.25rem 0 1rem; + padding: 0.5rem; + background: var(--code); + border-radius: 0.375rem; + overflow-x: auto; +} + +.field-check { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +.field-check input { + width: 1.4rem; + height: 1.4rem; + accent-color: var(--accent); +} + +.field-check .field-help { + flex-basis: 100%; + margin: 0; +} + +.field-help { + margin: 0; + color: var(--muted); + font-size: 0.9rem; +} + +.field-row { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); + gap: 1rem; +} + +.i18n-pair { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); + gap: 1rem; +} + +.step-editor, +.test-editor, +.requires { + margin: 1rem 0; + padding: 1rem; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 0.5rem; +} + +.test-editor { + background: var(--bg); +} + +.step-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.step-header h3 { + margin: 0; + font-size: 1.1rem; +} + +.step-actions, +.step-add { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.test-editor legend, +.requires legend { + padding: 0 0.4rem; + font-weight: 700; +} + +.test-message { + margin: 0.75rem 0; +} + +/* Vérifications */ +.problems-summary { + margin: 0 0 0.5rem; + font-weight: 700; +} + +.problem-list { + margin: 0; + padding: 0; + list-style: none; +} + +.problem { + display: flex; + align-items: flex-start; + gap: 0.6rem; + margin: 0.4rem 0; + padding: 0.5rem 0.6rem; + background: var(--surface); + border: 1px solid var(--border); + border-left-width: 5px; + border-radius: 0.375rem; +} + +.problem-error { + border-left-color: var(--ko); +} + +.problem-warning { + border-left-color: var(--hl); +} + +.problem-info { + border-left-color: var(--accent); +} + +.problem-icon { + flex: 0 0 1.2rem; + font-weight: 700; +} + +.problem-error .problem-severity { + color: var(--ko); +} + +.problem-body { + flex: 1; + min-width: 0; +} + +.problem-path { + color: var(--muted); + font-size: 0.85rem; +} + +.problem .btn { + min-height: 2.25rem; + padding: 0.1rem 0.6rem; + font-size: 0.9rem; +} + +.export-steps { + padding-left: 1.25rem; +} + +.preview-frame { + margin-top: 1rem; + border: 2px dashed var(--border); + border-radius: 0.5rem; +} + +@media (max-width: 64rem) { + .author-layout { + grid-template-columns: minmax(0, 1fr); + } + + .author-side { + position: static; + max-height: none; + } +} diff --git a/app/css/base.css b/app/css/base.css index df69b17..5e401dc 100644 --- a/app/css/base.css +++ b/app/css/base.css @@ -287,6 +287,13 @@ pre { accent-color: var(--accent); } +.author-link { + display: inline-flex; + align-items: center; + margin-top: 0.5rem; + text-decoration: none; +} + .setting > .btn:only-child { grid-column: 1 / -1; } diff --git a/app/js/author/AuthorApp.js b/app/js/author/AuthorApp.js new file mode 100644 index 0000000..8988182 --- /dev/null +++ b/app/js/author/AuthorApp.js @@ -0,0 +1,310 @@ +// Éditeur de niveaux (mode auteur) : formulaires, vérifications en direct, exécution des solutions avec le +// vrai Python, essai comme apprenant, export YAML. Aucun serveur : tout se passe dans le navigateur. + +import { AudioEngine } from '../core/AudioEngine.js'; +import { ErrorTranslator } from '../core/ErrorTranslator.js'; +import { GuideEngine } from '../core/GuideEngine.js'; +import { LevelChecker } from '../core/LevelChecker.js'; +import { LevelSession } from '../core/LevelSession.js'; +import { MemoryKeyValueStore } from '../core/KeyValueStores.js'; +import { ProgressStore } from '../core/ProgressStore.js'; +import { PyodideWorkerClient } from '../core/PyodideWorkerClient.js'; +import { ValidationEngine } from '../core/ValidationEngine.js'; +import { BadgeToast } from '../ui/BadgeToast.js'; +import { CellManager } from '../ui/CellManager.js'; +import { NotebookView } from '../ui/NotebookView.js'; +import { el } from '../ui/dom.js'; +import { LevelForm } from './LevelForm.js'; +import { emptyLevelModel, fromLevel, levelFromYaml, levelToYaml, toLevel } from './LevelDraft.js'; +import { ProblemsPanel } from './ProblemsPanel.js'; + +const DEBOUNCE_MS = 250; +const DRAFT_KEY = 'draft'; + +export class AuthorApp { + #i18n; + #linter; + #lessons; + #store; + #catalogs; + #root; + #knownIds = []; + #model = emptyLevelModel(); + #loadedId = null; + #form = null; + #problemsPanel = null; + #staticProblems = []; + #checkProblems = null; + #timer = null; + #status = null; + #yamlView = null; + #manifestView = null; + #checkButton = null; + #checkStatus = null; + #runtime = null; + #previewHost = null; + #keepNotice = false; // garde « brouillon restauré » affiché malgré le premier enregistrement + + /** + * @param {object} deps + * @param {import('../i18n/i18n.js').I18n} deps.i18n Catalogue fusionné (application + auteur). + * @param {import('../core/LevelLinter.js').LevelLinter} deps.linter + * @param {import('../core/LessonEngine.js').LessonEngine} deps.lessons + * @param {{get: Function, set: Function}} deps.store Magasin des brouillons. + * @param {{errors: object, guide: object}} deps.catalogs Catalogues d'erreurs et du guide, par langue (pour l'essai). + * @param {HTMLElement} deps.root + */ + constructor({ i18n, linter, lessons, store, catalogs, root }) { + this.#i18n = i18n; + this.#linter = linter; + this.#lessons = lessons; + this.#store = store; + this.#catalogs = catalogs; + this.#root = root; + } + + async run() { + this.#knownIds = (await this.#lessons.listLevels()).map((level) => level.id); + const draft = await this.#store.get(DRAFT_KEY).catch(() => undefined); + if (draft) { + this.#model = draft; + this.#loadedId = draft.id && this.#knownIds.includes(draft.id) ? draft.id : null; + } + this.#i18n.addEventListener('change', () => this.#build()); + this.#keepNotice = Boolean(draft); + this.#build(); + if (draft) { + this.#setStatus(this.#i18n.t('author.status.draft_restored')); + } + } + + // ---- Construction de l'interface ----------------------------------------------------------------------- + + #t = (key, params) => this.#i18n.t(key, params); + + #build() { + const t = this.#t; + this.#form = new LevelForm({ t, model: this.#model, knownIds: this.#knownIds, onChange: () => this.#changed() }); + this.#problemsPanel = new ProblemsPanel({ t, onGoto: (path) => this.#form.focusPath(path) }); + this.#status = el('p', { class: 'author-status', role: 'status' }); + this.#root.replaceChildren( + el('a', { class: 'skip-link', href: '#author-main', text: t('author.skip') }), + this.#header(), + el('main', { id: 'author-main', class: 'author-layout' }, el('div', { class: 'author-form' }, this.#form.element), el('aside', { class: 'author-side' }, this.#sidePanels())), + ); + this.#refresh(); + } + + #header() { + const t = this.#t; + const languages = el( + 'select', + { id: 'author-lang', 'aria-label': t('author.language'), onchange: (event) => this.#i18n.setLang(event.target.value) }, + ...this.#i18n.languages.map((lang) => el('option', { value: lang, text: lang.toUpperCase(), selected: lang === this.#i18n.lang })), + ); + const loader = el('select', { id: 'author-load-select', 'aria-label': t('author.toolbar.load_select') }, ...this.#knownIds.map((id) => el('option', { value: id, text: id, selected: id === this.#loadedId }))); + const fileInput = el('input', { id: 'author-file', type: 'file', accept: '.yaml,.yml,text/yaml', class: 'sr-only', onchange: (event) => this.#importFile(event.target.files[0]) }); + return el( + 'header', + { class: 'author-header' }, + el('div', { class: 'brand' }, el('img', { src: 'icons/icon.svg', alt: '', width: 32, height: 32 }), el('h1', { text: t('author.title') })), + el( + 'div', + { class: 'author-toolbar', role: 'toolbar', 'aria-label': t('author.toolbar.label') }, + el('button', { type: 'button', class: 'btn', id: 'author-new', text: t('author.toolbar.new'), onclick: () => this.#newLevel() }), + loader, + el('button', { type: 'button', class: 'btn', id: 'author-load', text: t('author.toolbar.load'), onclick: () => this.#loadFromSite(loader.value) }), + el('label', { class: 'btn', for: 'author-file', text: t('author.toolbar.import') }), + fileInput, + el('button', { type: 'button', class: 'btn btn-primary', id: 'author-download', text: t('author.toolbar.download'), onclick: () => this.#download() }), + languages, + el('a', { class: 'btn', href: './', text: t('author.toolbar.back') }), + ), + this.#status, + ); + } + + #sidePanels() { + const t = this.#t; + this.#checkButton = el('button', { type: 'button', class: 'btn', id: 'author-check', text: t('author.check.run'), onclick: () => this.#runChecks() }); + this.#checkStatus = el('p', { class: 'field-help', role: 'status' }); + this.#yamlView = el('textarea', { id: 'author-yaml', class: 'mono', readonly: true, rows: 14, wrap: 'off', 'aria-label': t('author.export.yaml') }); + this.#manifestView = el('pre', { class: 'mono', id: 'author-manifest' }); + this.#previewHost = el('div', { class: 'preview-host' }); + return [ + el('section', { class: 'side-section', 'aria-labelledby': 'side-problems' }, el('h2', { id: 'side-problems', text: t('author.section.problems') }), this.#problemsPanel.element), + el('section', { class: 'side-section', 'aria-labelledby': 'side-check' }, el('h2', { id: 'side-check', text: t('author.section.check') }), el('p', { class: 'field-help', text: t('author.check.help') }), this.#checkButton, this.#checkStatus), + el( + 'section', + { class: 'side-section', 'aria-labelledby': 'side-preview' }, + el('h2', { id: 'side-preview', text: t('author.section.preview') }), + el('p', { class: 'field-help', text: t('author.preview.help') }), + el('button', { type: 'button', class: 'btn', id: 'author-preview', text: t('author.preview.start'), onclick: () => this.#startPreview() }), + this.#previewHost, + ), + el( + 'section', + { class: 'side-section', 'aria-labelledby': 'side-export' }, + el('h2', { id: 'side-export', text: t('author.section.export') }), + el('ol', { class: 'export-steps' }, ...[1, 2, 3, 4, 5].map((n) => el('li', { text: t(`author.export.step${n}`) }))), + el('p', { class: 'field-help', text: t('author.export.manifest') }), + this.#manifestView, + el('details', {}, el('summary', { text: t('author.export.yaml') }), this.#yamlView), + ), + ]; + } + + // ---- Modèle et vérifications --------------------------------------------------------------------------- + + #changed() { + this.#checkProblems = null; // résultats d'exécution périmés + this.#checkStatus && (this.#checkStatus.textContent = ''); + clearTimeout(this.#timer); + this.#timer = setTimeout(() => this.#refresh(), DEBOUNCE_MS); + } + + /** Recalcule vérifications statiques, export et brouillon. */ + #refresh() { + const level = toLevel(this.#model); + // En modification d'un niveau existant, son propre id n'est pas un doublon. + const known = this.#model.id === this.#loadedId ? this.#knownIds.filter((id) => id !== this.#loadedId) : this.#knownIds; + this.#staticProblems = this.#linter.lint(level, { knownLevelIds: known }); + this.#problemsPanel.render([...this.#staticProblems, ...(this.#checkProblems ?? [])]); + this.#yamlView.value = levelToYaml(level); + const requires = JSON.stringify(level.requires); + this.#manifestView.textContent = `{ "id": ${JSON.stringify(level.id)}, "requires": ${requires} }`; + this.#store + .set(DRAFT_KEY, this.#model) + .then(() => { + if (this.#keepNotice) { + this.#keepNotice = false; + return; + } + this.#setStatus(this.#t('author.status.saved', { time: new Date().toLocaleTimeString(this.#i18n.lang) })); + }) + .catch(() => {}); + } + + #setStatus(text) { + this.#status.textContent = text; + } + + #setModel(model, loadedId = null) { + this.#model = model; + this.#loadedId = loadedId; + this.#checkProblems = null; + this.#build(); + } + + // ---- Actions de la barre d'outils ---------------------------------------------------------------------- + + #newLevel() { + if (window.confirm(this.#t('author.confirm.new'))) { + this.#setModel(emptyLevelModel()); + } + } + + async #loadFromSite(id) { + if (!window.confirm(this.#t('author.confirm.load', { id }))) { + return; + } + this.#setModel(fromLevel(await this.#lessons.loadLevel(id)), id); + this.#setStatus(this.#t('author.status.loaded', { id })); + } + + async #importFile(file) { + if (!file) { + return; + } + try { + const level = levelFromYaml(await file.text()); + if (level === null || typeof level !== 'object' || Array.isArray(level)) { + throw new Error('not a mapping'); + } + this.#setModel(fromLevel(level), null); + this.#setStatus(this.#t('author.status.imported', { name: file.name })); + } catch (error) { + this.#setStatus(this.#t('author.status.import_error', { detail: error.message })); + } + } + + #download() { + const level = toLevel(this.#model); + const blob = new Blob([levelToYaml(level)], { type: 'text/yaml' }); + const url = URL.createObjectURL(blob); + const link = el('a', { href: url, download: 'level.yaml' }); + document.body.append(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); + const errors = this.#staticProblems.filter((problem) => problem.severity === 'error').length; + this.#setStatus(errors > 0 ? this.#t('author.status.downloaded_with_errors', { count: errors }) : this.#t('author.status.downloaded', { id: level.id })); + } + + // ---- Exécution (Python) -------------------------------------------------------------------------------- + + /** Client Python et, pour l'essai, le même assemblage que l'application (progression en mémoire). */ + async #getRuntime() { + if (this.#runtime) { + return this.#runtime; + } + const i18n = this.#i18n; + const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href }); + const validator = new ValidationEngine(); + const progress = new ProgressStore(new MemoryKeyValueStore()); + await progress.load(); + const notebook = new NotebookView(i18n); + const toast = new BadgeToast(i18n); + const manager = new CellManager({ + i18n, + notebook, + client, + validator, + translator: new ErrorTranslator(this.#catalogs.errors), + audio: new AudioEngine({ enabled: false }), + progress, + toast, + guide: new GuideEngine(this.#catalogs.guide), + }); + this.#runtime = { client, checker: new LevelChecker({ client, validator }), manager, notebook, toast }; + return this.#runtime; + } + + async #runChecks() { + const t = this.#t; + const level = toLevel(this.#model); + const structural = this.#staticProblems.some((problem) => problem.severity === 'error' && problem.code.startsWith('schema_')); + if (structural) { + this.#checkStatus.textContent = t('author.check.fix_structure'); + return; + } + this.#checkButton.disabled = true; + this.#checkStatus.textContent = t('author.check.starting'); + try { + const { checker } = await this.#getRuntime(); + const { exercises, problems } = await checker.check(level, { + onProgress: (done, total) => (this.#checkStatus.textContent = t('author.check.progress', { done, total })), + }); + this.#checkProblems = problems; + this.#problemsPanel.render([...this.#staticProblems, ...problems]); + this.#checkStatus.textContent = problems.some((problem) => problem.severity === 'error') ? t('author.check.failed', { count: exercises.length }) : t('author.check.passed', { count: exercises.length }); + } catch { + this.#checkStatus.textContent = t('engine.failed'); + } finally { + this.#checkButton.disabled = false; + } + } + + async #startPreview() { + const t = this.#t; + const structural = this.#staticProblems.some((problem) => problem.severity === 'error' && problem.code.startsWith('schema_')); + if (structural) { + this.#previewHost.replaceChildren(el('p', { class: 'field-help', text: t('author.check.fix_structure') })); + return; + } + const runtime = await this.#getRuntime(); + this.#previewHost.replaceChildren(el('div', { class: 'preview-frame' }, runtime.notebook.element), runtime.toast.element); + const session = new LevelSession(toLevel(this.#model), this.#i18n.lang, new URL('./', location.href).href); + await runtime.manager.start(session); + } +} diff --git a/app/js/author/LevelForm.js b/app/js/author/LevelForm.js new file mode 100644 index 0000000..fc31869 --- /dev/null +++ b/app/js/author/LevelForm.js @@ -0,0 +1,167 @@ +// Formulaire complet d'un niveau : informations, étapes, mission. Modifie le modèle en place et signale +// les changements ; se reconstruit entièrement quand la structure change (ajout, suppression, déplacement). + +import { el } from '../ui/dom.js'; +import { REWARD_SOUNDS, newStepModel } from './LevelDraft.js'; +import { checkboxField, i18nPair, numberField, selectField, textField } from './fields.js'; +import { stepEditor, testsEditor } from './StepEditor.js'; + +export class LevelForm { + #t; + #model; + #root; + #knownIds; + #onChange; + + /** + * @param {object} options + * @param {(key: string, params?: object) => string} options.t + * @param {object} options.model Modèle de formulaire (voir LevelDraft). + * @param {string[]} options.knownIds Ids des niveaux existants (pour `requires`). + * @param {() => void} options.onChange + */ + constructor({ t, model, knownIds, onChange }) { + this.#t = t; + this.#model = model; + this.#knownIds = knownIds; + this.#onChange = onChange; + this.#root = el('div', { class: 'level-form' }); + this.render(); + } + + get element() { + return this.#root; + } + + /** Remplace le modèle (chargement d'un niveau, nouveau niveau) et reconstruit le formulaire. */ + setModel(model) { + this.#model = model; + this.render(); + } + + /** Donne le focus au champ d'un chemin (ex. 'steps.2.solution'), avec repli sur les variantes .fr/.en. */ + focusPath(path) { + const dotted = path.join ? path.join('.') : path; + for (const candidate of [dotted, `${dotted}.fr`, `${dotted}.en`, `${dotted}.kind`]) { + const target = this.#root.querySelector(`[data-path="${candidate}"]`); + if (target) { + target.scrollIntoView?.({ block: 'center' }); + target.focus(); + return true; + } + } + return false; + } + + render(focusPath = null) { + const t = this.#t; + const model = this.#model; + const changed = () => this.#onChange(); + const restructure = (focus) => { + this.render(focus ?? null); + changed(); + }; + + const info = el( + 'section', + { class: 'form-section', 'aria-labelledby': 'section-info' }, + el('h2', { id: 'section-info', text: t('author.section.info') }), + textField({ label: t('author.level.id'), path: 'id', value: model.id, code: true, help: t('author.level.id.help'), onInput: (value) => ((model.id = value), changed()) }), + i18nPair({ label: t('author.level.title'), path: 'title', value: model.title, onChange: changed }), + el( + 'div', + { class: 'field-row' }, + numberField({ label: t('author.level.difficulty'), path: 'difficulty', value: model.difficulty, min: 0, max: 10, help: t('author.level.difficulty.help'), onInput: (value) => ((model.difficulty = value), changed()) }), + numberField({ label: t('author.level.xp'), path: 'xp', value: model.xp, min: 0, help: t('author.level.xp.help'), onInput: (value) => ((model.xp = value), changed()) }), + ), + this.#requires(), + ); + + const steps = el( + 'section', + { class: 'form-section', 'aria-labelledby': 'section-steps' }, + el('h2', { id: 'section-steps', text: t('author.section.steps') }), + el('p', { class: 'field-help', text: t('author.section.steps.help') }), + ...model.steps.map((step, index) => + stepEditor({ + t, + step, + index, + count: model.steps.length, + onChange: changed, + onStructure: restructure, + actions: { + move: (delta) => { + const target = index + delta; + [model.steps[index], model.steps[target]] = [model.steps[target], model.steps[index]]; + restructure(`steps.${target}.${delta < 0 ? 'up' : 'down'}`); + }, + remove: () => { + model.steps.splice(index, 1); + restructure('steps.add'); + }, + }, + }), + ), + el( + 'div', + { class: 'step-add' }, + el('button', { type: 'button', class: 'btn', 'data-path': 'steps.add', text: t('author.step.add.explain'), onclick: () => (model.steps.push(newStepModel('explain')), restructure(`steps.${model.steps.length - 1}.text`)) }), + el('button', { type: 'button', class: 'btn', text: t('author.step.add.code'), onclick: () => (model.steps.push(newStepModel('code')), restructure(`steps.${model.steps.length - 1}.instruction`)) }), + ), + ); + + const { mission } = model; + const missionSection = el( + 'section', + { class: 'form-section', 'aria-labelledby': 'section-mission' }, + el('h2', { id: 'section-mission', text: t('author.section.mission') }), + i18nPair({ label: t('author.mission.title'), path: 'mission.title', value: mission.title, onChange: changed }), + i18nPair({ label: t('author.mission.goal'), path: 'mission.goal', value: mission.goal, multiline: true, rows: 3, onChange: changed }), + textField({ label: t('author.step.starter'), path: 'mission.starter', value: mission.starter, multiline: true, rows: 5, code: true, onInput: (value) => ((mission.starter = value), changed()) }), + el('h4', { text: t('author.tests') }), + el('p', { class: 'field-help', text: t('author.mission.tests.help') }), + testsEditor({ t, tests: mission.tests, path: 'mission.tests', onChange: changed, onStructure: restructure, addLabel: t('author.test.add') }), + textField({ label: t('author.step.solution'), path: 'mission.solution', value: mission.solution, multiline: true, rows: 6, code: true, help: t('author.step.solution.help'), onInput: (value) => ((mission.solution = value), changed()) }), + selectField({ + label: t('author.mission.reward'), + path: 'mission.rewardSound', + value: mission.rewardSound, + options: [['', '—'], ...REWARD_SOUNDS.map((sound) => [sound, sound])], + onChange: (value) => ((mission.rewardSound = value), changed()), + }), + ); + + this.#root.replaceChildren(info, steps, missionSection); + if (focusPath) { + this.focusPath(focusPath); + } + } + + #requires() { + const t = this.#t; + const model = this.#model; + // Un prérequis est un niveau antérieur : si l'id est valide, on ne propose que les ids plus petits. + const ordered = /^\d\d-/.test(model.id); + const others = this.#knownIds.filter((id) => id !== model.id && (!ordered || id < model.id)); + return el( + 'fieldset', + { class: 'requires' }, + el('legend', { text: t('author.level.requires') }), + el('p', { class: 'field-help', text: t('author.level.requires.help') }), + ...(others.length === 0 + ? [el('p', { text: t('author.level.requires.none') })] + : others.map((id) => + checkboxField({ + label: id, + path: `requires.${id}`, + checked: model.requires.includes(id), + onChange: (checked) => { + model.requires = checked ? [...model.requires, id] : model.requires.filter((other) => other !== id); + this.#onChange(); + }, + }), + )), + ); + } +} diff --git a/app/js/author/ProblemsPanel.js b/app/js/author/ProblemsPanel.js new file mode 100644 index 0000000..8de161c --- /dev/null +++ b/app/js/author/ProblemsPanel.js @@ -0,0 +1,83 @@ +// Panneau des vérifications : problèmes triés par gravité, chacun avec un bouton « aller au champ ». +// Les textes viennent des catalogues (clés `lint.`) ; 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 {