Add UI components, i18n, settings store and base styles

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:11:52 +02:00
parent 07f3b22e58
commit 81f8402260
14 changed files with 1029 additions and 1 deletions
+213
View File
@@ -0,0 +1,213 @@
/* Styles de l'application : jetons de thème, clair/sombre, taille réglable, focus visible. */
:root {
--bg: #ffffff;
--surface: #f4f6fa;
--text: #1b1f27;
--muted: #4a5365;
--border: #b8c0cf;
--accent: #1d4ed8;
--accent-text: #ffffff;
--ok: #146c2e;
--ko: #a31515;
--focus: #b45309;
/* Réglable par SettingsPanel : html { font-size: calc(var(--font-scale) * 100%) } */
--font-scale: 1;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #12151c;
--surface: #1c212c;
--text: #eceff5;
--muted: #b3bccd;
--border: #4a5365;
--accent: #8ab4ff;
--accent-text: #0b1020;
--ok: #6ee08a;
--ko: #ff8a8a;
--focus: #ffcc66;
}
}
:root[data-theme="dark"] {
--bg: #12151c;
--surface: #1c212c;
--text: #eceff5;
--muted: #b3bccd;
--border: #4a5365;
--accent: #8ab4ff;
--accent-text: #0b1020;
--ok: #6ee08a;
--ko: #ff8a8a;
--focus: #ffcc66;
}
html {
font-size: calc(var(--font-scale) * 100%);
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
line-height: 1.55;
}
:focus-visible {
outline: 3px solid var(--focus);
outline-offset: 2px;
}
.notebook {
max-width: 48rem;
margin: 0 auto;
padding: 1rem;
}
.notebook-status {
color: var(--muted);
min-height: 1.5em;
}
.explain,
.cell {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 0.5rem;
padding: 1rem;
margin: 1rem 0;
}
.btn {
min-height: 2.75rem; /* cible tactile confortable (WCAG 2.5.8) */
padding: 0.4rem 1rem;
border: 1px solid var(--border);
border-radius: 0.375rem;
background: var(--bg);
color: var(--text);
font: inherit;
cursor: pointer;
}
.btn-primary {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-text);
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.cell-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin: 0.5rem 0;
}
.code-editor {
width: 100%;
box-sizing: border-box;
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
font-size: 1rem;
padding: 0.75rem;
background: var(--bg);
color: var(--text);
border: 1px solid var(--border);
border-radius: 0.375rem;
tab-size: 4;
}
.cell-shortcut {
margin: 0.25rem 0;
color: var(--muted);
font-size: 0.875rem;
}
.cell-output {
min-height: 1.5rem;
margin: 0.5rem 0;
padding: 0.5rem 0.75rem;
background: var(--bg);
border-left: 4px solid var(--border);
white-space: pre-wrap;
}
.feedback-ok {
color: var(--ok);
font-weight: 600;
}
.feedback-ko,
.error-title {
color: var(--ko);
font-weight: 600;
}
.hint-list {
flex-basis: 100%;
margin: 0;
}
.toast-region {
position: fixed;
right: 1rem;
bottom: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
max-width: calc(100vw - 2rem);
}
.toast {
display: flex;
gap: 0.75rem;
align-items: center;
padding: 0.75rem 1rem;
background: var(--surface);
color: var(--text);
border: 2px solid var(--accent);
border-radius: 0.5rem;
}
.level-list {
list-style: none;
padding: 0;
}
.level-button {
display: flex;
justify-content: space-between;
width: 100%;
margin: 0.25rem 0;
padding: 0.5rem 0.75rem;
background: var(--surface);
color: var(--text);
border: 1px solid var(--border);
border-radius: 0.375rem;
font: inherit;
cursor: pointer;
}
.level-button.is-current {
border-width: 3px;
border-color: var(--accent);
}
.setting {
display: flex;
gap: 0.75rem;
align-items: center;
margin: 0.5rem 0;
}
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}
+45
View File
@@ -0,0 +1,45 @@
// Réglages utilisateur persistés (langue, taille du texte, thème, son, voix).
const STORAGE_KEY = 'settings';
export const DEFAULT_SETTINGS = Object.freeze({
lang: 'fr',
fontSize: 100, // en pourcentage de la taille de base
theme: 'auto', // 'auto' | 'light' | 'dark'
soundEnabled: true,
volume: 0.8,
voiceEnabled: false,
voiceRate: 1,
});
export class SettingsStore extends EventTarget {
#store;
#settings = { ...DEFAULT_SETTINGS };
/** @param {{get: Function, set: Function}} store Magasin clé/valeur (voir KeyValueStores.js). */
constructor(store) {
super();
this.#store = store;
}
get settings() {
return { ...this.#settings };
}
async load() {
const saved = await this.#store.get(STORAGE_KEY);
// Seules les clés connues sont reprises : un ancien format ne casse rien.
const known = Object.fromEntries(Object.entries(saved ?? {}).filter(([key]) => key in DEFAULT_SETTINGS));
this.#settings = { ...DEFAULT_SETTINGS, ...known };
return this.settings;
}
async update(key, value) {
if (!(key in DEFAULT_SETTINGS)) {
throw new Error(`Unknown setting: ${key}`);
}
this.#settings[key] = value;
await this.#store.set(STORAGE_KEY, this.#settings);
this.dispatchEvent(new CustomEvent('change', { detail: { key, value, settings: this.settings } }));
}
}
+61
View File
@@ -0,0 +1,61 @@
{
"app.title": "PyQuest",
"engine.loading": "Loading Python… (the first time can take a few seconds)",
"engine.failed": "Could not load Python. Reload the page or check your connection.",
"step.progress": "Step {current} of {total}",
"step.continue": "Continue",
"voice.listen": "Listen",
"voice.stop": "Stop reading",
"cell.editor": "Python code editor",
"cell.run": "Run",
"cell.running": "Running…",
"cell.stop": "Stop",
"cell.reset": "Reset",
"cell.hint": "Hint",
"cell.hint_count": "Hint {current} of {total}",
"cell.solution": "Show the solution",
"cell.output": "Output",
"cell.output_empty": "(nothing printed)",
"cell.shortcut": "Ctrl/Cmd + Enter to run",
"cell.passed": "Well done, that's correct!",
"cell.failed": "Not yet. Here is what is wrong:",
"cell.line": "Line {line}",
"cell.details": "Technical details",
"reason.syntax_error": "The code contains a syntax error.",
"reason.stdout_mismatch": "What is printed is not exactly what is expected.",
"reason.stdout_missing": "Something is missing from what is printed.",
"reason.variable_missing": "An expected variable does not exist.",
"reason.value_mismatch": "A variable does not have the right value.",
"reason.type_mismatch": "A variable does not have the right type.",
"reason.invalid_regex": "This test is badly defined (tell the level authors).",
"reason.unsupported_kind": "This test is not handled by the app yet.",
"reason.runtime_error": "The code stopped on an error.",
"mission.label": "Mission",
"mission.understand": "I understand",
"mission.done": "Level complete! +{xp} XP",
"mission.already": "Level already completed: no new XP, but well done for practising!",
"progress.title": "Your progress",
"progress.done": "Completed",
"progress.current": "In progress",
"progress.todo": "To do",
"progress.xp": "{xp} XP",
"progress.streak": "Streak: {days} day(s)",
"badge.earned": "Badge earned: {name}",
"badge.first_level": "First step",
"badge.three_levels": "Three levels",
"badge.xp_100": "100 XP",
"badge.streak_3": "3 days in a row",
"badge.streak_7": "7 days in a row",
"toast.close": "Close",
"settings.title": "Settings",
"settings.language": "Language",
"settings.fontSize": "Text size",
"settings.theme": "Theme",
"settings.theme.auto": "Automatic",
"settings.theme.light": "Light",
"settings.theme.dark": "Dark",
"settings.sound": "Sound effects",
"settings.volume": "Volume",
"settings.voice": "Voice",
"settings.voiceRate": "Voice speed"
}
+61
View File
@@ -0,0 +1,61 @@
{
"app.title": "PyQuest",
"engine.loading": "Chargement de Python… (la première fois peut prendre quelques secondes)",
"engine.failed": "Impossible de charger Python. Recharge la page ou vérifie ta connexion.",
"step.progress": "Étape {current} sur {total}",
"step.continue": "Continuer",
"voice.listen": "Écouter",
"voice.stop": "Arrêter la lecture",
"cell.editor": "Éditeur de code Python",
"cell.run": "Exécuter",
"cell.running": "Exécution en cours…",
"cell.stop": "Arrêter",
"cell.reset": "Réinitialiser",
"cell.hint": "Indice",
"cell.hint_count": "Indice {current} sur {total}",
"cell.solution": "Voir la solution",
"cell.output": "Résultat",
"cell.output_empty": "(aucun affichage)",
"cell.shortcut": "Ctrl/Cmd + Entrée pour exécuter",
"cell.passed": "Bravo, c'est correct !",
"cell.failed": "Pas encore. Voici ce qui ne va pas :",
"cell.line": "Ligne {line}",
"cell.details": "Détail technique",
"reason.syntax_error": "Le code contient une erreur de syntaxe.",
"reason.stdout_mismatch": "Ce qui s'affiche n'est pas exactement ce qui est attendu.",
"reason.stdout_missing": "Il manque quelque chose dans ce qui s'affiche.",
"reason.variable_missing": "Une variable attendue n'existe pas.",
"reason.value_mismatch": "Une variable n'a pas la bonne valeur.",
"reason.type_mismatch": "Une variable n'a pas le bon type.",
"reason.invalid_regex": "Ce test est mal défini (signale-le aux auteurs du niveau).",
"reason.unsupported_kind": "Ce test n'est pas encore géré par l'application.",
"reason.runtime_error": "Le code s'est arrêté sur une erreur.",
"mission.label": "Mission",
"mission.understand": "Je comprends",
"mission.done": "Niveau terminé ! +{xp} XP",
"mission.already": "Niveau déjà terminé : pas de nouveaux XP, mais bien joué de t'être entraîné·e !",
"progress.title": "Ta progression",
"progress.done": "Terminé",
"progress.current": "En cours",
"progress.todo": "À faire",
"progress.xp": "{xp} XP",
"progress.streak": "Série : {days} jour(s)",
"badge.earned": "Badge obtenu : {name}",
"badge.first_level": "Premier pas",
"badge.three_levels": "Trois niveaux",
"badge.xp_100": "100 XP",
"badge.streak_3": "3 jours de suite",
"badge.streak_7": "7 jours de suite",
"toast.close": "Fermer",
"settings.title": "Réglages",
"settings.language": "Langue",
"settings.fontSize": "Taille du texte",
"settings.theme": "Thème",
"settings.theme.auto": "Automatique",
"settings.theme.light": "Clair",
"settings.theme.dark": "Sombre",
"settings.sound": "Effets sonores",
"settings.volume": "Volume",
"settings.voice": "Voix",
"settings.voiceRate": "Vitesse de la voix"
}
+36
View File
@@ -0,0 +1,36 @@
// Traduction de l'interface : catalogues plats par langue, repli sur le français.
const FALLBACK_LANG = 'fr';
export class I18n extends EventTarget {
#catalogs;
#lang;
/** @param {Record<string, Record<string, string>>} catalogs Contenu de fr.json, en.json. */
constructor(catalogs, lang = FALLBACK_LANG) {
super();
this.#catalogs = catalogs;
this.#lang = catalogs[lang] ? lang : FALLBACK_LANG;
}
get lang() {
return this.#lang;
}
get languages() {
return Object.keys(this.#catalogs);
}
setLang(lang) {
if (this.#catalogs[lang] && lang !== this.#lang) {
this.#lang = lang;
this.dispatchEvent(new CustomEvent('change', { detail: { lang } }));
}
}
/** Traduit une clé ; les `{param}` sont remplacés. Une clé inconnue est renvoyée telle quelle. */
t(key, params = {}) {
const template = this.#catalogs[this.#lang]?.[key] ?? this.#catalogs[FALLBACK_LANG]?.[key] ?? key;
return template.replace(/\{(\w+)\}/g, (whole, name) => String(params[name] ?? whole));
}
}
+35
View File
@@ -0,0 +1,35 @@
// Notifications éphémères (badges, XP). Région role="status" : annoncée sans voler le focus.
import { el } from './dom.js';
const DISPLAY_MS = 7000;
export class BadgeToast {
#i18n;
#root;
constructor(i18n) {
this.#i18n = i18n;
this.#root = el('div', { class: 'toast-region', role: 'status', 'aria-live': 'polite' });
}
get element() {
return this.#root;
}
/** Affiche un message ; se ferme seul après quelques secondes ou au clic sur « Fermer ». */
show(message) {
const toast = el(
'div',
{ class: 'toast' },
el('span', { text: message }),
el('button', { type: 'button', class: 'btn', text: this.#i18n.t('toast.close'), onclick: () => toast.remove() }),
);
this.#root.append(toast);
setTimeout(() => toast.remove(), DISPLAY_MS);
}
showBadge(badgeId) {
this.show(this.#i18n.t('badge.earned', { name: this.#i18n.t(`badge.${badgeId}`) }));
}
}
+151
View File
@@ -0,0 +1,151 @@
// Orchestre un niveau : affiche les étapes, exécute les cellules, valide, attribue la progression.
// Émet 'levelcomplete' (detail: résultat de ProgressStore.completeLevel).
import { ValidationEngine } from '../core/ValidationEngine.js';
import { CellView } from './CellView.js';
export class CellManager extends EventTarget {
#deps;
#session = null;
/**
* @param {object} deps
* @param {import('../i18n/i18n.js').I18n} deps.i18n
* @param {import('./NotebookView.js').NotebookView} deps.notebook
* @param {import('../core/PyodideWorkerClient.js').PyodideWorkerClient} deps.client
* @param {import('../core/ValidationEngine.js').ValidationEngine} deps.validator
* @param {import('../core/ErrorTranslator.js').ErrorTranslator} deps.translator
* @param {import('../core/AudioEngine.js').AudioEngine} deps.audio
* @param {import('../core/ProgressStore.js').ProgressStore} deps.progress
* @param {import('./BadgeToast.js').BadgeToast} deps.toast
*/
constructor(deps) {
super();
this.#deps = deps;
}
/** Démarre (ou redémarre) un niveau à partir d'une LevelSession. */
async start(session) {
const { notebook, client, i18n } = this.#deps;
this.#session = session;
notebook.clear();
notebook.setStatus(i18n.t('engine.loading'));
try {
await client.start();
await client.reset();
} catch {
notebook.setStatus(i18n.t('engine.failed'));
return;
}
notebook.setStatus('');
this.#showCurrent();
}
#showCurrent() {
const session = this.#session;
if (session.onMission) {
this.#showMission();
} else if (session.step.type === 'explain') {
this.#showExplain(session.step);
} else {
this.#showCode(session.step);
}
}
#announceProgress() {
const { notebook, i18n } = this.#deps;
const { index, stepCount } = this.#session;
notebook.setStatus(i18n.t('step.progress', { current: Math.min(index + 1, stepCount), total: stepCount }));
}
#advance() {
this.#session.next();
this.#showCurrent();
}
#showExplain(step) {
const { notebook, i18n } = this.#deps;
this.#announceProgress();
notebook.addExplain(step);
notebook.addAction(i18n.t('step.continue'), () => this.#advance());
}
#showCode(step) {
const { notebook, i18n } = this.#deps;
this.#announceProgress();
const cell = new CellView(i18n, step);
notebook.add(cell.element);
cell.focus();
cell.addEventListener('stop', () => this.#deps.client.interrupt());
let continueShown = false;
cell.addEventListener('run', async (event) => {
const passed = await this.#execute(cell, event.detail.code, step.tests);
if (passed && !continueShown) {
continueShown = true;
notebook.addAction(i18n.t('step.continue'), () => this.#advance());
}
});
}
#showMission() {
const { notebook, i18n } = this.#deps;
const mission = this.#session.mission;
notebook.setStatus(`${i18n.t('mission.label')} : ${mission.title}`);
if (mission.tests.length === 0) {
// Mission sans code (ex. niveau 00) : un simple bouton de validation.
notebook.addExplain({ text: mission.goal, voice: false, image: null });
notebook.addAction(i18n.t('mission.understand'), () => this.#completeLevel(mission));
return;
}
const cell = new CellView(i18n, { starter: mission.starter, instruction: mission.goal });
notebook.add(cell.element);
cell.focus();
cell.addEventListener('stop', () => this.#deps.client.interrupt());
cell.addEventListener('run', async (event) => {
if (await this.#execute(cell, event.detail.code, mission.tests)) {
await this.#completeLevel(mission);
}
});
}
/** Exécute le code d'une cellule et valide. Renvoie vrai si tous les tests passent. */
async #execute(cell, code, tests) {
const { client, validator, translator, audio, i18n } = this.#deps;
await audio.unlock(); // le clic sur « Exécuter » est le geste utilisateur requis
cell.clearOutput();
cell.setBusy(true);
let stdout = '';
const onOutput = (text) => {
stdout += text;
cell.appendOutput(text);
};
const result = await client.run(code, {
collect: ValidationEngine.variablesToCollect(tests),
onStdout: onOutput,
onStderr: onOutput,
});
cell.setBusy(false);
if (result.error) {
cell.showError(translator.translate(result.error, i18n.lang));
audio.play('error');
return false;
}
const validation = validator.validate(tests, { stdout, result });
cell.showValidation(validation);
audio.play(validation.passed ? 'success_small' : 'error');
return validation.passed;
}
async #completeLevel(mission) {
const { progress, toast, audio, i18n, notebook } = this.#deps;
const outcome = await progress.completeLevel(this.#session.id, this.#session.xp);
audio.play(mission.rewardSound ?? 'success_small');
toast.show(i18n.t(outcome.alreadyCompleted ? 'mission.already' : 'mission.done', { xp: outcome.xpGained }));
for (const badge of outcome.newBadges) {
toast.showBadge(badge);
}
notebook.setStatus(i18n.t('mission.done', { xp: outcome.xpGained }));
this.dispatchEvent(new CustomEvent('levelcomplete', { detail: outcome }));
}
}
+156
View File
@@ -0,0 +1,156 @@
// Une cellule de code : éditeur, boutons, sortie, retour de validation.
// Émet les événements 'run' (detail: { code }), 'stop' et 'reset'. Aucune logique d'exécution ici.
import { el, renderInline, uniqueId } from './dom.js';
import { HintPanel } from './HintPanel.js';
export class CellView extends EventTarget {
#i18n;
#starter;
#root;
#editor;
#output;
#feedback;
#runButton;
#stopButton;
#busy = false;
/**
* @param {import('../i18n/i18n.js').I18n} i18n
* @param {object} options
* @param {string} options.starter
* @param {string} options.instruction Consigne localisée.
* @param {string[]} [options.hints]
* @param {string|null} [options.solution]
*/
constructor(i18n, { starter, instruction, hints = [], solution = null }) {
super();
this.#i18n = i18n;
this.#starter = starter;
const editorId = uniqueId('editor');
const outputId = uniqueId('output');
this.#editor = el('textarea', {
id: editorId,
class: 'code-editor',
spellcheck: 'false',
autocapitalize: 'off',
autocomplete: 'off',
autocorrect: 'off',
rows: Math.max(3, starter.split('\n').length + 1),
'aria-label': i18n.t('cell.editor'),
'aria-describedby': `${editorId}-hint`,
onkeydown: (event) => this.#onKeyDown(event),
});
this.#editor.value = starter;
this.#runButton = el('button', { type: 'button', class: 'btn btn-primary', text: i18n.t('cell.run'), onclick: () => this.#emitRun() });
this.#stopButton = el('button', {
type: 'button',
class: 'btn',
hidden: true,
text: i18n.t('cell.stop'),
onclick: () => this.dispatchEvent(new CustomEvent('stop')),
});
const resetButton = el('button', { type: 'button', class: 'btn', text: i18n.t('cell.reset'), onclick: () => this.reset() });
this.#output = el('pre', { id: outputId, class: 'cell-output', 'aria-live': 'polite', 'aria-label': i18n.t('cell.output') });
this.#feedback = el('div', { class: 'cell-feedback', role: 'status' });
const solutionBlock = solution
? el('details', { class: 'solution' }, el('summary', { text: i18n.t('cell.solution') }), el('pre', {}, el('code', { text: solution })))
: null;
this.#root = el(
'section',
{ class: 'cell', tabindex: '-1' },
el('p', { class: 'cell-instruction' }, renderInline(instruction)),
this.#editor,
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, new HintPanel(i18n, hints).element),
this.#output,
this.#feedback,
solutionBlock,
);
}
get element() {
return this.#root;
}
get code() {
return this.#editor.value;
}
focus() {
this.#editor.focus();
}
setBusy(busy) {
this.#busy = busy;
this.#runButton.disabled = busy;
this.#runButton.textContent = this.#i18n.t(busy ? 'cell.running' : 'cell.run');
this.#stopButton.hidden = !busy;
this.#root.setAttribute('aria-busy', String(busy));
}
clearOutput() {
this.#output.textContent = '';
this.#feedback.replaceChildren();
}
appendOutput(text) {
this.#output.append(document.createTextNode(text));
}
/** Remet le code de départ et vide la sortie. */
reset() {
this.#editor.value = this.#starter;
this.clearOutput();
this.dispatchEvent(new CustomEvent('reset'));
}
/** Affiche le résultat de ValidationEngine.validate(). */
showValidation({ passed, results }) {
if (passed) {
// Le texte porte le sens : la couleur et l'icône ne font qu'appuyer.
this.#feedback.replaceChildren(el('p', { class: 'feedback-ok' }, el('span', { 'aria-hidden': 'true', text: '✔ ' }), this.#i18n.t('cell.passed')));
return;
}
const failures = results
.filter((entry) => !entry.passed)
.map((entry) => el('li', {}, entry.message ?? this.#i18n.t(`reason.${entry.reason}`)));
this.#feedback.replaceChildren(
el('p', { class: 'feedback-ko' }, el('span', { 'aria-hidden': 'true', text: '✘ ' }), this.#i18n.t('cell.failed')),
el('ul', {}, ...failures),
);
}
/** Affiche une erreur déjà traduite par ErrorTranslator. */
showError({ title, explanation, tip, line, traceback }) {
this.#feedback.replaceChildren(
el(
'div',
{ class: 'feedback-error' },
el('p', { class: 'error-title' }, el('span', { 'aria-hidden': 'true', text: '🔍 ' }), title, line ? ` (${this.#i18n.t('cell.line', { line })})` : ''),
el('p', { text: explanation }),
el('p', {}, el('span', { 'aria-hidden': 'true', text: '💡 ' }), tip),
traceback ? el('details', {}, el('summary', { text: this.#i18n.t('cell.details') }), el('pre', { text: traceback })) : null,
),
);
}
#emitRun() {
if (!this.#busy) {
this.dispatchEvent(new CustomEvent('run', { detail: { code: this.code } }));
}
}
#onKeyDown(event) {
// Tab n'est pas capturé : il garde son rôle de navigation clavier (WCAG 2.1.2).
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
this.#emitRun();
}
}
}
+45
View File
@@ -0,0 +1,45 @@
// Indices graduels : un seul nouvel indice par clic, jamais tous à la fois.
import { el, renderInline } from './dom.js';
export class HintPanel {
#i18n;
#hints;
#revealed = 0;
#button;
#list;
#root;
/** @param {string[]} hints Indices déjà localisés, du plus vague au plus précis. */
constructor(i18n, hints) {
this.#i18n = i18n;
this.#hints = hints;
this.#button = el('button', { type: 'button', class: 'btn', onclick: () => this.reveal() });
this.#list = el('ol', { class: 'hint-list', 'aria-live': 'polite' });
this.#root = el('div', { class: 'hint-panel', hidden: hints.length === 0 }, this.#button, this.#list);
this.#refresh();
}
get element() {
return this.#root;
}
/** Affiche l'indice suivant. Renvoie false s'il n'en reste plus. */
reveal() {
if (this.#revealed >= this.#hints.length) {
return false;
}
this.#list.append(el('li', {}, renderInline(this.#hints[this.#revealed])));
this.#revealed += 1;
this.#refresh();
return true;
}
#refresh() {
const remaining = this.#revealed < this.#hints.length;
this.#button.disabled = !remaining;
this.#button.textContent = remaining
? this.#i18n.t('cell.hint_count', { current: this.#revealed + 1, total: this.#hints.length })
: this.#i18n.t('cell.hint');
}
}
+72
View File
@@ -0,0 +1,72 @@
// Zone verticale façon notebook : étapes d'explication, cellules et messages s'empilent.
import { el, renderInline } from './dom.js';
export class NotebookView {
#i18n;
#root;
#status;
#onSpeak;
/**
* @param {import('../i18n/i18n.js').I18n} i18n
* @param {object} [options]
* @param {(text: string) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton.
*/
constructor(i18n, { onSpeak = null } = {}) {
this.#i18n = i18n;
this.#onSpeak = onSpeak;
this.#status = el('p', { class: 'notebook-status', role: 'status' });
this.#root = el('main', { class: 'notebook', id: 'main' }, this.#status);
}
get element() {
return this.#root;
}
clear() {
this.#root.replaceChildren(this.#status);
this.#status.textContent = '';
}
/** Message d'état global (chargement, échec). */
setStatus(text) {
this.#status.textContent = text;
}
/** Ajoute un élément et déplace le focus dessus pour les lecteurs d'écran. */
add(element, { focus = true } = {}) {
this.#root.append(element);
if (focus) {
element.scrollIntoView?.({ block: 'nearest' });
(element.matches('[tabindex]') ? element : element.querySelector('[tabindex]'))?.focus?.();
}
return element;
}
/** Étape d'explication : texte, et bouton de lecture si la voix est demandée par le niveau. */
addExplain({ text, voice, image }) {
const children = [el('p', {}, renderInline(text))];
if (image) {
children.push(el('img', { src: image, alt: '' }));
}
if (voice && this.#onSpeak) {
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text) }));
}
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
}
/** Bouton « Continuer » ou équivalent ; retiré du DOM une fois cliqué. */
addAction(label, onClick) {
const button = el('button', {
type: 'button',
class: 'btn btn-primary',
text: label,
onclick: () => {
button.remove();
onClick();
},
});
return this.add(el('div', { class: 'notebook-action' }, button), { focus: false });
}
}
+50
View File
@@ -0,0 +1,50 @@
// Carte de progression : liste des niveaux avec leur état, en texte (pas seulement en couleur).
// Émet 'select' (detail: { id }). Aucun verrou : tous les niveaux restent accessibles.
import { el } from './dom.js';
export class ProgressMap extends EventTarget {
#i18n;
#root;
constructor(i18n) {
super();
this.#i18n = i18n;
this.#root = el('nav', { class: 'progress-map', 'aria-label': i18n.t('progress.title') });
}
get element() {
return this.#root;
}
/**
* @param {object} data
* @param {{id: string, title: string}[]} data.levels Titres déjà localisés, dans l'ordre.
* @param {{completedLevels: object, xp: number, streak: {current: number}}} data.progress Snapshot du ProgressStore.
* @param {string|null} data.currentId
*/
render({ levels, progress, currentId }) {
const items = levels.map(({ id, title }) => {
const done = id in progress.completedLevels;
const current = id === currentId;
const stateKey = done ? 'progress.done' : current ? 'progress.current' : 'progress.todo';
const button = el(
'button',
{
type: 'button',
class: `level-button${done ? ' is-done' : ''}${current ? ' is-current' : ''}`,
'aria-current': current ? 'step' : null,
onclick: () => this.dispatchEvent(new CustomEvent('select', { detail: { id } })),
},
el('span', { class: 'level-title', text: title }),
el('span', { class: 'level-state', text: this.#i18n.t(stateKey) }),
);
return el('li', {}, button);
});
this.#root.replaceChildren(
el('h2', { text: this.#i18n.t('progress.title') }),
el('p', { class: 'progress-summary', text: `${this.#i18n.t('progress.xp', { xp: progress.xp })} · ${this.#i18n.t('progress.streak', { days: progress.streak.current })}` }),
el('ol', { class: 'level-list' }, ...items),
);
}
}
+61
View File
@@ -0,0 +1,61 @@
// Panneau de réglages : accessible au clavier, chaque champ a un label visible.
// Émet 'change' (detail: { key, value }) ; l'application persiste et applique.
import { el, uniqueId } from './dom.js';
export class SettingsPanel extends EventTarget {
#i18n;
#root;
/** @param {import('../i18n/i18n.js').I18n} i18n */
constructor(i18n) {
super();
this.#i18n = i18n;
this.#root = el('section', { class: 'settings', 'aria-label': i18n.t('settings.title') });
}
get element() {
return this.#root;
}
/** @param {import('../core/SettingsStore.js').DEFAULT_SETTINGS} settings */
render(settings) {
const t = (key) => this.#i18n.t(key);
this.#root.replaceChildren(
el('h2', { text: t('settings.title') }),
this.#field('settings.language', 'select', {
value: settings.lang,
options: this.#i18n.languages.map((lang) => [lang, lang.toUpperCase()]),
key: 'lang',
}),
this.#field('settings.fontSize', 'range', { value: settings.fontSize, min: 80, max: 200, step: 10, key: 'fontSize', number: true }),
this.#field('settings.theme', 'select', {
value: settings.theme,
options: ['auto', 'light', 'dark'].map((theme) => [theme, t(`settings.theme.${theme}`)]),
key: 'theme',
}),
this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }),
this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }),
this.#field('settings.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }),
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
);
}
#field(labelKey, kind, { value, options = [], key, number = false, ...range }) {
const id = uniqueId('setting');
const emit = (newValue) => this.dispatchEvent(new CustomEvent('change', { detail: { key, value: newValue } }));
let control;
if (kind === 'select') {
control = el(
'select',
{ id, onchange: (event) => emit(event.target.value) },
...options.map(([optionValue, text]) => el('option', { value: optionValue, text, selected: optionValue === value })),
);
} else if (kind === 'checkbox') {
control = el('input', { id, type: 'checkbox', checked: value, onchange: (event) => emit(event.target.checked) });
} else {
control = el('input', { id, type: 'range', value, ...range, onchange: (event) => emit(number ? Number(event.target.value) : event.target.value) });
}
return el('div', { class: 'setting' }, el('label', { for: id, text: this.#i18n.t(labelKey) }), control);
}
}
+42
View File
@@ -0,0 +1,42 @@
// Helpers DOM : construction d'éléments sans jamais passer par innerHTML (contenus de niveaux non fiables).
/** Crée un élément. `attrs` : propriétés DOM ou attributs ; les enfants sont des nœuds ou des chaînes. */
export function el(tag, attrs = {}, ...children) {
const element = document.createElement(tag);
for (const [name, value] of Object.entries(attrs)) {
if (value === null || value === undefined || value === false) {
continue;
}
if (name === 'class') {
element.className = value;
} else if (name.startsWith('on') && typeof value === 'function') {
element.addEventListener(name.slice(2), value);
} else if (name === 'text') {
element.textContent = value;
} else {
element.setAttribute(name, value === true ? '' : String(value));
}
}
element.append(...children.flat().filter((child) => child !== null && child !== undefined));
return element;
}
/** Transforme un texte avec `code` inline (backticks) en fragment de nœuds, sans HTML interprété. */
export function renderInline(text) {
const fragment = document.createDocumentFragment();
text.split('`').forEach((part, index) => {
if (part === '') {
return;
}
fragment.append(index % 2 === 1 ? el('code', { text: part }) : document.createTextNode(part));
});
return fragment;
}
let counter = 0;
/** Identifiant unique pour relier labels et champs. */
export function uniqueId(prefix) {
counter += 1;
return `${prefix}-${counter}`;
}