diff --git a/CONTEXT.md b/CONTEXT.md
index 80df1f3..4ca7348 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -29,6 +29,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
| Validation | `app/js/core/ValidationEngine.js` (kinds déclaratifs, dont `code_contains`), `StepValidator.js` (rejeux à `inputs`) ; `tests/js/level-solutions.integration.test.mjs` vérifie toutes les solutions de référence avec le vrai Pyodide |
| 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` |
+| 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` |
| Shell PWA | `app/index.html`, `app/js/main.js`, `app/service-worker.js`, `app/manifest.webmanifest` |
@@ -83,9 +84,9 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
fr/en) ; **recommandation : palette B, typo 2, mascotte 1 (Chouette)** — **choix validé par l'utilisateur** (voir
`docs/design/07-visual-identity.md`). **Étape 2 faite** : CSS découpé (`themes`/`base`/`cells`),
palette B + typo 2 auto-hébergée, éditeur coloré (`CodeEditor`, `highlightPython`), icône
- chouette + PNG (`make icons`), test de contraste des thèmes. **Étape 3 restante** : carte de
- progression graphique + personnage-guide (chouette) aux messages variés fr/en, badges
- illustrés, feedback coloré doublé de texte. Anciennes notes : **Reste** : identité visuelle
+ chouette + PNG (`make icons`), test de contraste des thèmes. **Étape 3a faite** : personnage-guide (chouette, 4 humeurs, messages variés fr/en,
+ `GuideEngine`, réglage pour le masquer). **Étape 3b restante** : carte de progression
+ graphique, badges illustrés, feedback coloré (vert/rouge) doublé de texte. Anciennes notes : **Reste** : identité visuelle
(palette, typo, logo), découpage CSS (`base`/`themes`/`cells`), coloration syntaxique de
l'éditeur, carte de progression graphique, personnage-guide aux messages variés fr/en,
badges illustrés, feedback coloré (vert/rouge, toujours doublé d'un texte). Procéder en 3
diff --git a/app/css/guide.css b/app/css/guide.css
new file mode 100644
index 0000000..ee5b1f0
--- /dev/null
+++ b/app/css/guide.css
@@ -0,0 +1,112 @@
+/* Personnage-guide : chouette (aux couleurs du thème) et sa bulle. Masqué par le réglage « guide ». */
+
+.guide-bubble {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.75rem;
+ margin: 0.75rem 0;
+ animation: guide-pop 0.3s ease-out;
+}
+
+.guide-avatar {
+ flex: 0 0 3.5rem;
+ width: 3.5rem;
+ height: 3.5rem;
+}
+
+.guide-avatar svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+}
+
+.guide-text {
+ position: relative;
+ margin: 0.25rem 0 0;
+ padding: 0.6rem 0.9rem;
+ background: var(--bg);
+ color: var(--text);
+ border: 2px solid var(--accent);
+ border-radius: 0.75rem;
+}
+
+/* Pointe de la bulle, vers l'avatar. */
+.guide-text::before {
+ content: "";
+ position: absolute;
+ left: -0.55rem;
+ top: 0.9rem;
+ width: 0.8rem;
+ height: 0.8rem;
+ background: var(--bg);
+ border-left: 2px solid var(--accent);
+ border-bottom: 2px solid var(--accent);
+ transform: rotate(45deg);
+}
+
+:root[data-guide="off"] .guide-bubble {
+ display: none;
+}
+
+@keyframes guide-pop {
+ from {
+ opacity: 0;
+ transform: translateY(0.4rem) scale(0.97);
+ }
+}
+
+/* Dessin : couleurs via les jetons du thème. */
+.owl-body {
+ fill: var(--accent);
+}
+
+.owl-belly {
+ fill: var(--surface);
+ opacity: 0.85;
+}
+
+.owl-eye {
+ fill: var(--bg);
+}
+
+.owl-pupil {
+ fill: var(--text);
+}
+
+.owl-glint {
+ fill: var(--bg);
+}
+
+.owl-beak,
+.owl-spark {
+ fill: var(--hl);
+}
+
+.owl-line {
+ fill: none;
+ stroke: var(--text);
+ stroke-width: 4;
+ stroke-linecap: round;
+}
+
+/* Humeurs : par défaut (neutral) yeux ronds ; les autres groupes sont masqués. */
+.owl-wings,
+.owl-sparkles,
+.eyes-happy,
+.eyes-thinking {
+ display: none;
+}
+
+[data-mood="happy"] .eyes-round,
+[data-mood="celebrate"] .eyes-round,
+[data-mood="thinking"] .eyes-round {
+ display: none;
+}
+
+[data-mood="happy"] .eyes-happy,
+[data-mood="celebrate"] .eyes-happy,
+[data-mood="thinking"] .eyes-thinking,
+[data-mood="celebrate"] .owl-wings,
+[data-mood="celebrate"] .owl-sparkles {
+ display: inline;
+}
diff --git a/app/index.html b/app/index.html
index 839a570..66d9058 100644
--- a/app/index.html
+++ b/app/index.html
@@ -11,6 +11,7 @@
+
Aller au contenu / Skip to content
diff --git a/app/js/core/GuideEngine.js b/app/js/core/GuideEngine.js
new file mode 100644
index 0000000..3f01101
--- /dev/null
+++ b/app/js/core/GuideEngine.js
@@ -0,0 +1,88 @@
+// Personnage-guide : choisit un message adapté à la situation, jamais le même deux fois de suite.
+// Les messages viennent de app/js/i18n/guide..json ; ici seulement la logique de variété.
+
+// Humeur du dessin (voir ui/guideArt.js) pour chaque situation.
+const MOODS = {
+ level_start: 'happy',
+ welcome_back: 'happy',
+ success_step: 'happy',
+ success_first_try: 'celebrate',
+ success_after_retry: 'celebrate',
+ error_runtime: 'thinking',
+ fail_tests: 'thinking',
+ suggest_hint: 'thinking',
+ hint_revealed: 'thinking',
+ interrupted: 'neutral',
+ input_waiting: 'neutral',
+ level_complete: 'celebrate',
+ level_complete_replay: 'happy',
+ streak: 'celebrate',
+};
+
+export class GuideEngine {
+ #catalogs;
+ #defaultLang;
+ #random;
+ #bags = new Map(); // `${lang}/${situation}` -> indices restants (tirage sans remise)
+ #last = new Map(); // `${lang}/${situation}` -> dernier indice dit
+
+ /**
+ * @param {Record>} catalogs Contenu de guide.fr.json, guide.en.json.
+ * @param {object} [options]
+ * @param {string} [options.defaultLang]
+ * @param {() => number} [options.random] Remplaçable pour des tests déterministes.
+ */
+ constructor(catalogs, { defaultLang = 'fr', random = Math.random } = {}) {
+ this.#catalogs = catalogs;
+ this.#defaultLang = defaultLang;
+ this.#random = random;
+ }
+
+ static get situations() {
+ return Object.keys(MOODS);
+ }
+
+ /**
+ * @param {string} situation Clé de MOODS (ex. 'success_step').
+ * @param {string} lang
+ * @param {Record} [params] Valeurs des {paramètres} du message.
+ * @returns {{situation: string, mood: string, text: string}}
+ */
+ say(situation, lang, params = {}) {
+ const catalog = this.#catalogs[lang]?.[situation] ? this.#catalogs[lang] : this.#catalogs[this.#defaultLang];
+ const variants = catalog[situation];
+ if (!variants || !(situation in MOODS)) {
+ throw new Error(`Unknown guide situation: ${situation}`);
+ }
+ const text = variants[this.#nextIndex(`${lang}/${situation}`, variants.length)].replace(/\{(\w+)\}/g, (whole, name) => String(params[name] ?? whole));
+ return { situation, mood: MOODS[situation], text };
+ }
+
+ /** Tirage sans remise : toutes les variantes passent avant qu'une se répète, jamais deux fois de suite. */
+ #nextIndex(key, size) {
+ if (size === 1) {
+ return 0;
+ }
+ let bag = this.#bags.get(key) ?? [];
+ if (bag.length === 0) {
+ bag = this.#shuffled(size);
+ // Le premier tirage du nouveau sac ne doit pas répéter le dernier message dit.
+ if (bag[0] === this.#last.get(key)) {
+ bag.push(bag.shift());
+ }
+ }
+ const index = bag.shift();
+ this.#bags.set(key, bag);
+ this.#last.set(key, index);
+ return index;
+ }
+
+ #shuffled(size) {
+ const indices = Array.from({ length: size }, (_, i) => i);
+ for (let i = indices.length - 1; i > 0; i--) {
+ const j = Math.floor(this.#random() * (i + 1));
+ [indices[i], indices[j]] = [indices[j], indices[i]];
+ }
+ return indices;
+ }
+}
diff --git a/app/js/core/SettingsStore.js b/app/js/core/SettingsStore.js
index f98b6aa..c7114cb 100644
--- a/app/js/core/SettingsStore.js
+++ b/app/js/core/SettingsStore.js
@@ -10,6 +10,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
volume: 0.8,
voiceEnabled: true, // le bouton « Écouter » ne lit jamais automatiquement : un clic à chaque fois
voiceRate: 1,
+ guideEnabled: true, // personnage-guide (bulles d'encouragement)
});
export class SettingsStore extends EventTarget {
diff --git a/app/js/i18n/en.json b/app/js/i18n/en.json
index b3501a3..a0f6468 100644
--- a/app/js/i18n/en.json
+++ b/app/js/i18n/en.json
@@ -57,6 +57,7 @@
"settings.theme.auto": "Automatic",
"settings.theme.light": "Light",
"settings.theme.dark": "Dark",
+ "settings.guide": "Guide character",
"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 866b0a4..d4f71e5 100644
--- a/app/js/i18n/fr.json
+++ b/app/js/i18n/fr.json
@@ -57,6 +57,7 @@
"settings.theme.auto": "Automatique",
"settings.theme.light": "Clair",
"settings.theme.dark": "Sombre",
+ "settings.guide": "Personnage-guide",
"settings.sound": "Effets sonores",
"settings.volume": "Volume",
"settings.voice": "Voix",
diff --git a/app/js/i18n/guide.en.json b/app/js/i18n/guide.en.json
new file mode 100644
index 0000000..46989f9
--- /dev/null
+++ b/app/js/i18n/guide.en.json
@@ -0,0 +1,70 @@
+{
+ "level_start": [
+ "Let's go! One small step at a time.",
+ "Ready? We'll take it easy.",
+ "Welcome to this level. Take your time.",
+ "Great idea to keep going. Let's do it!"
+ ],
+ "welcome_back": [
+ "Good to see you again! We pick up where you left off.",
+ "You're back! No pressure, we'll go gently.",
+ "Welcome back. Even a short session counts."
+ ],
+ "success_step": [
+ "Well done, that's correct!",
+ "Exactly right. You're getting the hang of it.",
+ "Clean! Shall we move on?",
+ "It works. You're making progress."
+ ],
+ "success_first_try": [
+ "First try, well done!",
+ "Right and straight to the point. Impressive!",
+ "All correct on the first attempt!"
+ ],
+ "success_after_retry": [
+ "You kept at it, and it paid off!",
+ "There, you found it. Every attempt got you closer.",
+ "Well done for carrying on: that's how we learn."
+ ],
+ "error_runtime": [
+ "An error is a clue: look at the line shown.",
+ "Don't panic, it happens to everyone. Let's read the message together.",
+ "Python tells you where to look: that's helpful, not a failure.",
+ "Almost! Fix the line shown and run again."
+ ],
+ "fail_tests": [
+ "It runs, but it's not the expected result yet. Reread the instruction.",
+ "You're on the right track. Compare what is printed with what is asked.",
+ "Not quite. A small detail to adjust?"
+ ],
+ "suggest_hint": [
+ "A hint can help: the Hint button is there for that.",
+ "Stuck? Ask for a hint, there is no penalty."
+ ],
+ "hint_revealed": [
+ "Here's a nudge. Over to you!",
+ "One more hint: try it with that.",
+ "Does that help? Go back to your code and test."
+ ],
+ "interrupted": [
+ "Execution stopped. Good call cutting the loop!",
+ "Stop! Check that your loop's condition can become false."
+ ],
+ "input_waiting": [
+ "I'm listening: type your answer.",
+ "The program is waiting for your input."
+ ],
+ "level_complete": [
+ "Level complete: +{xp} XP! Nice step.",
+ "Well done! +{xp} XP, and you learned something solid.",
+ "Mission accomplished, +{xp} XP. You can be proud."
+ ],
+ "level_complete_replay": [
+ "Nicely revised! No new XP, but practice counts.",
+ "Reviewing is always a good idea."
+ ],
+ "streak": [
+ "{days} days in a row! Come back tomorrow, no pressure.",
+ "A {days}-day streak: you're building a nice habit."
+ ]
+}
diff --git a/app/js/i18n/guide.fr.json b/app/js/i18n/guide.fr.json
new file mode 100644
index 0000000..2749afb
--- /dev/null
+++ b/app/js/i18n/guide.fr.json
@@ -0,0 +1,70 @@
+{
+ "level_start": [
+ "C'est parti ! Une petite étape à la fois.",
+ "Prêt·e ? On avance tranquillement.",
+ "Bienvenue dans ce niveau. Prends ton temps.",
+ "Bonne idée de continuer. Allons-y !"
+ ],
+ "welcome_back": [
+ "Content de te revoir ! On reprend là où tu t'étais arrêté·e.",
+ "Te revoilà ! Aucune pression, on y va doucement.",
+ "Bon retour. Même une petite session compte."
+ ],
+ "success_step": [
+ "Bien joué, c'est correct !",
+ "Exactement ça. Tu prends le coup de main.",
+ "Propre ! Passons à la suite ?",
+ "Ça marche. Tu progresses."
+ ],
+ "success_first_try": [
+ "Du premier coup, bravo !",
+ "Juste et sans détour. Impressionnant !",
+ "Tout bon dès le premier essai !"
+ ],
+ "success_after_retry": [
+ "Tu as persévéré, et ça a payé !",
+ "Voilà, tu l'as trouvé. Chaque essai t'a rapproché·e.",
+ "Bravo d'avoir continué : c'est comme ça qu'on apprend."
+ ],
+ "error_runtime": [
+ "Une erreur, c'est un indice : regarde la ligne indiquée.",
+ "Pas de panique, ça arrive à tout le monde. Lis le message avec moi.",
+ "Python te dit où chercher : c'est utile, pas un échec.",
+ "Presque ! Corrige la ligne signalée et relance."
+ ],
+ "fail_tests": [
+ "Ça tourne, mais ce n'est pas encore le résultat attendu. Relis la consigne.",
+ "Tu es sur la bonne voie. Compare ce qui s'affiche avec ce qui est demandé.",
+ "Pas tout à fait. Un petit détail à ajuster ?"
+ ],
+ "suggest_hint": [
+ "Un indice peut aider : le bouton Indice est là pour ça.",
+ "Bloqué·e ? Demande un indice, il n'y a aucune pénalité."
+ ],
+ "hint_revealed": [
+ "Voilà un coup de pouce. À toi de jouer !",
+ "Un indice de plus : essaie avec ça.",
+ "Ça t'aide ? Reprends ton code et teste."
+ ],
+ "interrupted": [
+ "Exécution arrêtée. Bien vu d'avoir coupé la boucle !",
+ "Stop ! Vérifie que la condition de ta boucle peut devenir fausse."
+ ],
+ "input_waiting": [
+ "Je t'écoute : tape ta réponse.",
+ "Le programme attend ta saisie."
+ ],
+ "level_complete": [
+ "Niveau terminé : +{xp} XP ! Belle étape.",
+ "Bravo ! +{xp} XP, et tu as appris du solide.",
+ "Mission accomplie, +{xp} XP. Tu peux être fier·ère."
+ ],
+ "level_complete_replay": [
+ "Bien revu ! Pas de nouveaux XP, mais la pratique, ça compte.",
+ "Réviser, c'est toujours une bonne idée."
+ ],
+ "streak": [
+ "{days} jours de suite ! Reviens demain, sans pression.",
+ "Série de {days} jours : tu prends une belle habitude."
+ ]
+}
diff --git a/app/js/main.js b/app/js/main.js
index acdb2f9..394b83a 100644
--- a/app/js/main.js
+++ b/app/js/main.js
@@ -2,6 +2,7 @@
import { AudioEngine } from './core/AudioEngine.js';
import { ErrorTranslator } from './core/ErrorTranslator.js';
+import { GuideEngine } from './core/GuideEngine.js';
import { LessonEngine } from './core/LessonEngine.js';
import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStores.js';
import { ProgressStore } from './core/ProgressStore.js';
@@ -49,6 +50,7 @@ function applySettings(settings) {
root.setAttribute('data-theme', settings.theme);
}
root.lang = settings.lang;
+ root.dataset.guide = settings.guideEnabled ? 'on' : 'off';
}
class App {
@@ -73,11 +75,13 @@ class App {
this.#settings = new SettingsStore(store);
const settings = await this.#settings.load();
- const [translations, errorCatalogs] = await Promise.all([
+ const [translations, errorCatalogs, guideCatalogs] = await Promise.all([
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/${lang}.json`))),
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/errors.${lang}.json`))),
+ Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/guide.${lang}.json`))),
]);
this.#i18n = new I18n(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, translations[i]])), settings.lang);
+ const guide = new GuideEngine(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, guideCatalogs[i]])));
const translator = new ErrorTranslator(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, errorCatalogs[i]])));
this.#progress = new ProgressStore(store);
@@ -103,6 +107,7 @@ class App {
audio: this.#audio,
progress: this.#progress,
toast,
+ guide,
});
this.#manager.addEventListener('levelcomplete', () => this.#renderMap());
@@ -129,10 +134,23 @@ class App {
const next = requested ?? this.#levelIds.find((id) => !this.#progress.isCompleted(id)) ?? this.#levelIds.at(-1);
history.replaceState(null, '', `#/levels/${next}`);
window.addEventListener('popstate', () => this.#openLevel(this.#levelFromHash() ?? this.#levelIds[0]));
- await this.#openLevel(next);
+ // Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche.
+ await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
this.#registerServiceWorker();
}
+ /** Vrai si l'apprenant a déjà de l'activité mais pas depuis au moins deux jours. */
+ #isReturning() {
+ const { lastDay } = this.#progress.snapshot().streak;
+ if (!lastDay) {
+ return false;
+ }
+ const [year, month, day] = lastDay.split('-').map(Number);
+ const now = new Date();
+ const days = (Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()) - Date.UTC(year, month - 1, day)) / 86400000;
+ return days >= 2;
+ }
+
/** Id de niveau demandé par l'URL (#/levels/), s'il existe. */
#levelFromHash() {
const match = /^#\/levels\/([a-z0-9-]+)$/.exec(location.hash);
@@ -150,12 +168,12 @@ class App {
await this.#openLevel(id);
}
- async #openLevel(id) {
+ async #openLevel(id, { greeting = 'level_start' } = {}) {
this.#currentId = id;
await this.#renderMap();
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
this.#updateLevelNav(session.title);
- await this.#manager.start(session);
+ await this.#manager.start(session, { greeting });
}
async #renderMap() {
diff --git a/app/js/ui/CellManager.js b/app/js/ui/CellManager.js
index 99bd968..b5accd1 100644
--- a/app/js/ui/CellManager.js
+++ b/app/js/ui/CellManager.js
@@ -9,6 +9,7 @@ export class CellManager extends EventTarget {
#deps;
#stepValidator;
#session = null;
+ #passes = 0; // réussites du premier coup : alterne deux familles de messages pour varier
/**
* @param {object} deps
@@ -20,6 +21,7 @@ export class CellManager extends EventTarget {
* @param {import('../core/AudioEngine.js').AudioEngine} deps.audio
* @param {import('../core/ProgressStore.js').ProgressStore} deps.progress
* @param {import('./BadgeToast.js').BadgeToast} deps.toast
+ * @param {import('../core/GuideEngine.js').GuideEngine} deps.guide
*/
constructor(deps) {
super();
@@ -27,8 +29,12 @@ export class CellManager extends EventTarget {
this.#stepValidator = new StepValidator({ client: deps.client, validator: deps.validator });
}
- /** Démarre (ou redémarre) un niveau à partir d'une LevelSession. */
- async start(session) {
+ /**
+ * Démarre (ou redémarre) un niveau à partir d'une LevelSession.
+ * @param {object} [options]
+ * @param {string} [options.greeting] Situation du guide pour l'accueil ('level_start' ou 'welcome_back').
+ */
+ async start(session, { greeting = 'level_start' } = {}) {
const { notebook, client, i18n } = this.#deps;
this.#session = session;
notebook.clear();
@@ -41,9 +47,14 @@ export class CellManager extends EventTarget {
return;
}
notebook.setStatus('');
+ notebook.addGuide(this.#say(greeting));
this.#showCurrent();
}
+ #say(situation, params = {}) {
+ return this.#deps.guide.say(situation, this.#deps.i18n.lang, params);
+ }
+
#showCurrent() {
const session = this.#session;
if (session.onMission) {
@@ -80,9 +91,11 @@ export class CellManager extends EventTarget {
notebook.add(cell.element);
cell.focus();
cell.addEventListener('stop', () => this.#stop(cell));
+ cell.addEventListener('hint', () => cell.showGuide(this.#say('hint_revealed')));
+ const state = { failures: 0 };
let continueShown = false;
cell.addEventListener('run', async (event) => {
- const passed = await this.#execute(cell, event.detail.code, step.tests);
+ const passed = await this.#execute(cell, event.detail.code, step.tests, state);
if (passed && !continueShown) {
continueShown = true;
notebook.addAction(i18n.t('step.continue'), () => this.#advance());
@@ -104,13 +117,20 @@ export class CellManager extends EventTarget {
notebook.add(cell.element);
cell.focus();
cell.addEventListener('stop', () => this.#stop(cell));
+ cell.addEventListener('hint', () => cell.showGuide(this.#say('hint_revealed')));
+ const state = { failures: 0 };
cell.addEventListener('run', async (event) => {
- if (await this.#execute(cell, event.detail.code, mission.tests)) {
+ if (await this.#execute(cell, event.detail.code, mission.tests, state)) {
await this.#completeLevel(mission);
}
});
}
+ /** Deux échecs d'affilée et des indices encore cachés : le guide suggère un indice. */
+ #struggling(cell, state) {
+ return state.failures >= 2 && cell.hasHintsLeft;
+ }
+
#stop(cell) {
// Ordre important : l'interruption doit être posée avant d'annuler la saisie en attente,
// pour que Python reçoive KeyboardInterrupt plutôt qu'une fin de fichier.
@@ -122,7 +142,7 @@ export class CellManager extends EventTarget {
* Exécute le code d'une cellule et valide. Renvoie vrai si tous les tests passent.
* Les tests qui déclarent `inputs` rejouent le code, en isolation, avec ces saisies scriptées.
*/
- async #execute(cell, code, tests) {
+ async #execute(cell, code, tests, state) {
const { client, translator, audio, i18n } = this.#deps;
await audio.unlock(); // le clic sur « Exécuter » est le geste utilisateur requis
cell.clearOutput();
@@ -136,19 +156,37 @@ export class CellManager extends EventTarget {
collect: ValidationEngine.variablesToCollect(tests),
onStdout: onOutput,
onStderr: onOutput,
- onInput: (prompt) => cell.requestInput(prompt),
+ onInput: (prompt) => {
+ cell.showGuide(this.#say('input_waiting'));
+ return cell.requestInput(prompt);
+ },
});
if (result.error) {
cell.setBusy(false);
cell.showError(translator.translate(result.error, i18n.lang));
audio.play('error');
+ if (result.error.type === 'KeyboardInterrupt') {
+ cell.showGuide(this.#say('interrupted'));
+ } else {
+ state.failures += 1;
+ cell.showGuide(this.#say(this.#struggling(cell, state) ? 'suggest_hint' : 'error_runtime'));
+ }
return false;
}
const validation = await this.#stepValidator.validate(code, tests, { stdout, result });
cell.setBusy(false);
cell.showValidation(validation);
audio.play(validation.passed ? 'success_small' : 'error');
+ if (validation.passed) {
+ const first = state.failures === 0;
+ this.#passes += first ? 1 : 0;
+ cell.showGuide(this.#say(first ? (this.#passes % 2 === 1 ? 'success_first_try' : 'success_step') : 'success_after_retry'));
+ state.failures = 0;
+ } else {
+ state.failures += 1;
+ cell.showGuide(this.#say(this.#struggling(cell, state) ? 'suggest_hint' : 'fail_tests'));
+ }
return validation.passed;
}
@@ -161,6 +199,10 @@ export class CellManager extends EventTarget {
toast.showBadge(badge);
}
notebook.setStatus(i18n.t('mission.done', { xp: outcome.xpGained }));
+ notebook.addGuide(this.#say(outcome.alreadyCompleted ? 'level_complete_replay' : 'level_complete', { xp: outcome.xpGained }));
+ if (!outcome.alreadyCompleted && outcome.streak.current >= 2) {
+ notebook.addGuide(this.#say('streak', { days: outcome.streak.current }));
+ }
this.dispatchEvent(new CustomEvent('levelcomplete', { detail: outcome }));
}
}
diff --git a/app/js/ui/CellView.js b/app/js/ui/CellView.js
index fff1c8f..a768182 100644
--- a/app/js/ui/CellView.js
+++ b/app/js/ui/CellView.js
@@ -3,6 +3,7 @@
import { el, renderInline, uniqueId } from './dom.js';
import { CodeEditor } from './CodeEditor.js';
+import { GuideBubble } from './GuideBubble.js';
import { HintPanel } from './HintPanel.js';
export class CellView extends EventTarget {
@@ -12,6 +13,8 @@ export class CellView extends EventTarget {
#editor;
#output;
#feedback;
+ #guideSlot;
+ #hintPanel;
#runButton;
#stopButton;
#busy = false;
@@ -57,6 +60,8 @@ export class CellView extends EventTarget {
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' });
+ this.#guideSlot = el('div', { class: 'cell-guide' });
+ this.#hintPanel = new HintPanel(i18n, hints, { onReveal: () => this.dispatchEvent(new CustomEvent('hint')) });
// Saisie demandée par input() : formulaire affiché seulement pendant l'attente.
const inputId = uniqueId('input');
@@ -79,10 +84,11 @@ export class CellView extends EventTarget {
el('p', { class: 'cell-instruction' }, renderInline(instruction)),
this.#editor.element,
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),
+ el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, this.#hintPanel.element),
this.#output,
this.#inputForm,
this.#feedback,
+ this.#guideSlot,
solutionBlock,
);
}
@@ -110,6 +116,17 @@ export class CellView extends EventTarget {
clearOutput() {
this.#output.textContent = '';
this.#feedback.replaceChildren();
+ this.#guideSlot.replaceChildren();
+ }
+
+ /** Reste-t-il des indices à révéler ? */
+ get hasHintsLeft() {
+ return this.#hintPanel.hasMore;
+ }
+
+ /** Affiche un message du personnage-guide sous le retour de validation. */
+ showGuide(message) {
+ this.#guideSlot.replaceChildren(new GuideBubble(message).element);
}
appendOutput(text) {
diff --git a/app/js/ui/GuideBubble.js b/app/js/ui/GuideBubble.js
new file mode 100644
index 0000000..3caf1ef
--- /dev/null
+++ b/app/js/ui/GuideBubble.js
@@ -0,0 +1,23 @@
+// Bulle du personnage-guide : avatar (chouette) + message. Décoratif pour les lecteurs d'écran
+// (l'avatar est masqué) ; le texte reste lisible dans l'ordre de lecture.
+
+import { el } from './dom.js';
+import { createOwl } from './guideArt.js';
+
+export class GuideBubble {
+ #root;
+
+ /** @param {{text: string, mood: string}} message Issu de GuideEngine.say(). */
+ constructor({ text, mood }) {
+ this.#root = el(
+ 'div',
+ { class: 'guide-bubble', 'data-mood': mood },
+ el('div', { class: 'guide-avatar', 'aria-hidden': 'true' }, createOwl()),
+ el('p', { class: 'guide-text', text }),
+ );
+ }
+
+ get element() {
+ return this.#root;
+ }
+}
diff --git a/app/js/ui/HintPanel.js b/app/js/ui/HintPanel.js
index 455981b..03dcb46 100644
--- a/app/js/ui/HintPanel.js
+++ b/app/js/ui/HintPanel.js
@@ -5,14 +5,17 @@ import { el, renderInline } from './dom.js';
export class HintPanel {
#i18n;
#hints;
+ #onReveal;
#revealed = 0;
#button;
#list;
#root;
- /** @param {string[]} hints Indices déjà localisés, du plus vague au plus précis. */
- constructor(i18n, hints) {
+ /** @param {string[]} hints Indices déjà localisés, du plus vague au plus précis.
+ * @param {{onReveal?: () => void}} [options] Rappel à chaque indice révélé. */
+ constructor(i18n, hints, { onReveal = () => {} } = {}) {
this.#i18n = i18n;
+ this.#onReveal = onReveal;
this.#hints = hints;
this.#button = el('button', { type: 'button', class: 'btn', onclick: () => this.reveal() });
this.#list = el('ol', { class: 'hint-list', 'aria-live': 'polite' });
@@ -24,6 +27,11 @@ export class HintPanel {
return this.#root;
}
+ /** Reste-t-il au moins un indice à révéler ? */
+ get hasMore() {
+ return this.#revealed < this.#hints.length;
+ }
+
/** Affiche l'indice suivant. Renvoie false s'il n'en reste plus. */
reveal() {
if (this.#revealed >= this.#hints.length) {
@@ -32,6 +40,7 @@ export class HintPanel {
this.#list.append(el('li', {}, renderInline(this.#hints[this.#revealed])));
this.#revealed += 1;
this.#refresh();
+ this.#onReveal();
return true;
}
diff --git a/app/js/ui/NotebookView.js b/app/js/ui/NotebookView.js
index b3c4354..0598e3c 100644
--- a/app/js/ui/NotebookView.js
+++ b/app/js/ui/NotebookView.js
@@ -1,5 +1,6 @@
// Zone verticale façon notebook : étapes d'explication, cellules et messages s'empilent.
+import { GuideBubble } from './GuideBubble.js';
import { el, renderInline } from './dom.js';
export class NotebookView {
@@ -69,6 +70,11 @@ export class NotebookView {
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
}
+ /** Message du personnage-guide dans le fil du notebook (sans déplacer le focus). */
+ addGuide(message) {
+ return this.add(new GuideBubble(message).element, { focus: false });
+ }
+
/** Réaffiche ou masque les boutons « Écouter » existants (réglage de la voix modifié). */
refreshVoiceButtons() {
const visible = this.#canSpeak();
diff --git a/app/js/ui/SettingsPanel.js b/app/js/ui/SettingsPanel.js
index d3a1adf..c817706 100644
--- a/app/js/ui/SettingsPanel.js
+++ b/app/js/ui/SettingsPanel.js
@@ -34,6 +34,7 @@ export class SettingsPanel extends EventTarget {
options: ['auto', 'light', 'dark'].map((theme) => [theme, t(`settings.theme.${theme}`)]),
key: 'theme',
}),
+ this.#field('settings.guide', 'checkbox', { value: settings.guideEnabled, key: 'guideEnabled' }),
this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }),
this.#testButton('settings.testSound', 'sound'),
this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }),
diff --git a/app/js/ui/guideArt.js b/app/js/ui/guideArt.js
new file mode 100644
index 0000000..4330993
--- /dev/null
+++ b/app/js/ui/guideArt.js
@@ -0,0 +1,43 @@
+// Dessin de la chouette-guide (SVG constant, aux couleurs du thème via les classes CSS de guide.css).
+// L'humeur (neutral, happy, thinking, celebrate) est portée par l'attribut data-mood du conteneur.
+
+const OWL_SVG = ``;
+
+/** Crée un nouvel élément SVG de chouette. */
+export function createOwl() {
+ // Marque constante (jamais construite à partir de données externes) : l'analyse DOM est sûre.
+ const document_ = new DOMParser().parseFromString(OWL_SVG, 'image/svg+xml');
+ return document.importNode(document_.documentElement, true);
+}
diff --git a/app/service-worker.js b/app/service-worker.js
index e1ab4e3..2af7994 100644
--- a/app/service-worker.js
+++ b/app/service-worker.js
@@ -3,9 +3,9 @@
// - Pyodide vendorisé, niveaux, scripts : mis en cache à la première utilisation (hors ligne ensuite).
// Les en-têtes COOP/COEP du document viennent du serveur ; ce worker ne les fabrique pas.
-const CACHE_VERSION = 'pyquest-v3';
+const CACHE_VERSION = 'pyquest-v4';
-const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'icons/icon.svg', 'js/main.js'];
+const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'css/guide.css', 'icons/icon.svg', 'js/main.js'];
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE_VERSION).then((cache) => cache.addAll(SHELL)));
diff --git a/docs/design/07-visual-identity.md b/docs/design/07-visual-identity.md
index e669f9e..95962ad 100644
--- a/docs/design/07-visual-identity.md
+++ b/docs/design/07-visual-identity.md
@@ -21,3 +21,20 @@ Choix de l'utilisateur parmi les propositions de [`identity/index.html`](identit
(texte ≥ 4,5 : 1, composants et focus ≥ 3 : 1, couleurs de coloration incluses), thèmes clair et sombre.
- La coloration syntaxique (`app/js/ui/highlightPython.js`, `CodeEditor.js`) est décorative :
le contrôle reste un `