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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 16:51:33 +02:00
parent 3003eda8a2
commit 57bda6eecf
27 changed files with 1712 additions and 10 deletions
+310
View File
@@ -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);
}
}
+167
View File
@@ -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();
},
}),
)),
);
}
}
+83
View File
@@ -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.<code>`) ; 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));
}
}
+87
View File
@@ -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,
);
}
+83
View File
@@ -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 }),
);
}
+71
View File
@@ -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'));
}
+77
View File
@@ -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}`;
});