Add PWA shell, entry point, service worker and dev server

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:13:55 +02:00
parent 81f8402260
commit e538d4d122
9 changed files with 405 additions and 3 deletions
+1 -1
View File
@@ -53,7 +53,7 @@ Le brief original est [`prompt-pyquest.md`](prompt-pyquest.md) (résumé fidèle
`speechSynthesis`, déblocage uniquement sur geste utilisateur (contrainte iOS autoplay). `speechSynthesis`, déblocage uniquement sur geste utilisateur (contrainte iOS autoplay).
9. ✅ FAIT (testé sur DOM simulé linkedom, pas dans un vrai navigateur) — `app/js/ui/*` + `app/css/app.css`, `i18n.js`, `SettingsStore.js` — `NotebookView`, `CellManager`, `CellView`, `HintPanel`, `ProgressMap`, 9. ✅ FAIT (testé sur DOM simulé linkedom, pas dans un vrai navigateur) — `app/js/ui/*` + `app/css/app.css`, `i18n.js`, `SettingsStore.js` — `NotebookView`, `CellManager`, `CellView`, `HintPanel`, `ProgressMap`,
`BadgeToast`, `SettingsPanel`. `BadgeToast`, `SettingsPanel`.
10. `app/index.html`, `app/manifest.webmanifest`, `app/service-worker.js` — app shell PWA, 10. ✅ FAIT (non testé dans un navigateur) — `app/index.html`, `app/manifest.webmanifest`, `app/service-worker.js` — app shell PWA,
cache des assets Pyodide vendorisés + des fichiers de niveaux pour le hors-ligne. cache des assets Pyodide vendorisés + des fichiers de niveaux pour le hors-ligne.
Puis point 8 : `Makefile`, `pyrightconfig.json`, `README.md`/`README-EN.md`, Puis point 8 : `Makefile`, `pyrightconfig.json`, `README.md`/`README-EN.md`,
+45
View File
@@ -211,3 +211,48 @@ body {
transition: none !important; transition: none !important;
} }
} }
.skip-link {
position: absolute;
left: -9999px;
}
.skip-link:focus {
left: 1rem;
top: 1rem;
padding: 0.5rem 1rem;
background: var(--bg);
color: var(--text);
z-index: 10;
}
.app-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
border-bottom: 1px solid var(--border);
}
.app-header h1 {
margin: 0;
font-size: 1.5rem;
}
.app-layout {
display: grid;
grid-template-columns: minmax(12rem, 18rem) 1fr;
gap: 1rem;
padding: 0 1rem;
}
#settings-region {
padding: 0 1rem;
max-width: 48rem;
}
@media (max-width: 40rem) {
.app-layout {
grid-template-columns: 1fr;
}
}
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="PyQuest">
<rect width="512" height="512" rx="96" fill="#1d4ed8"/>
<path d="M150 200l-70 56 70 56M362 200l70 56-70 56" fill="none" stroke="#ffffff" stroke-width="36" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M286 150l-60 212" fill="none" stroke="#ffcc66" stroke-width="36" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 417 B

+27
View File
@@ -0,0 +1,27 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#1d4ed8">
<title>PyQuest</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="icons/icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<a class="skip-link" href="#main">Aller au contenu / Skip to content</a>
<header class="app-header">
<h1 id="app-title">PyQuest</h1>
<button type="button" class="btn" id="settings-toggle" aria-expanded="false" aria-controls="settings-region"></button>
</header>
<div class="app-layout">
<aside id="progress-region"></aside>
<div id="notebook-region"></div>
</div>
<div id="settings-region" hidden></div>
<div id="toast-region"></div>
<noscript>PyQuest a besoin de JavaScript. / PyQuest needs JavaScript.</noscript>
<script type="module" src="js/main.js"></script>
</body>
</html>
+181
View File
@@ -0,0 +1,181 @@
// Point d'entrée : assemble les modules et branche l'interface.
import { AudioEngine } from './core/AudioEngine.js';
import { ErrorTranslator } from './core/ErrorTranslator.js';
import { LessonEngine } from './core/LessonEngine.js';
import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStores.js';
import { ProgressStore } from './core/ProgressStore.js';
import { PyodideWorkerClient } from './core/PyodideWorkerClient.js';
import { SettingsStore } from './core/SettingsStore.js';
import { ValidationEngine } from './core/ValidationEngine.js';
import { VoiceEngine } from './core/VoiceEngine.js';
import { I18n } from './i18n/i18n.js';
import { BadgeToast } from './ui/BadgeToast.js';
import { CellManager } from './ui/CellManager.js';
import { NotebookView } from './ui/NotebookView.js';
import { ProgressMap } from './ui/ProgressMap.js';
import { SettingsPanel } from './ui/SettingsPanel.js';
const LANGUAGES = ['fr', 'en'];
async function loadJson(path) {
const response = await fetch(new URL(path, import.meta.url));
if (!response.ok) {
throw new Error(`Cannot load ${path}`);
}
return response.json();
}
/** IndexedDB si utilisable (refusé en navigation privée sur certains navigateurs), sinon mémoire. */
async function openStore() {
try {
const store = new IndexedDbKeyValueStore();
await store.get('probe');
return store;
} catch {
return new MemoryKeyValueStore();
}
}
function applySettings(settings) {
const root = document.documentElement;
root.style.setProperty('--font-scale', String(settings.fontSize / 100));
if (settings.theme === 'auto') {
root.removeAttribute('data-theme');
} else {
root.setAttribute('data-theme', settings.theme);
}
root.lang = settings.lang;
}
class App {
#i18n;
#settings;
#progress;
#lessons;
#audio;
#voice;
#manager;
#map;
#panel;
#levelIds = [];
#currentId = null;
async run() {
const store = await openStore();
this.#settings = new SettingsStore(store);
const settings = await this.#settings.load();
const [translations, errorCatalogs] = await Promise.all([
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/${lang}.json`))),
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/errors.${lang}.json`))),
]);
this.#i18n = new I18n(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, translations[i]])), settings.lang);
const translator = new ErrorTranslator(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, errorCatalogs[i]])));
this.#progress = new ProgressStore(store);
await this.#progress.load();
this.#lessons = new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href });
this.#audio = new AudioEngine({ enabled: settings.soundEnabled, volume: settings.volume });
this.#voice = new VoiceEngine({ enabled: settings.voiceEnabled, rate: settings.voiceRate });
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
const notebook = new NotebookView(this.#i18n, {
onSpeak: (text) => this.#voice.speak(text, this.#i18n.lang),
canSpeak: () => this.#voice.supported && this.#voice.enabled,
});
const toast = new BadgeToast(this.#i18n);
this.#manager = new CellManager({
i18n: this.#i18n,
notebook,
client,
validator: new ValidationEngine(),
translator,
audio: this.#audio,
progress: this.#progress,
toast,
});
this.#manager.addEventListener('levelcomplete', () => this.#renderMap());
this.#map = new ProgressMap(this.#i18n);
this.#map.addEventListener('select', (event) => this.#openLevel(event.detail.id));
this.#panel = new SettingsPanel(this.#i18n);
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
document.getElementById('progress-region').append(this.#map.element);
document.getElementById('notebook-region').append(notebook.element);
document.getElementById('settings-region').append(this.#panel.element);
document.getElementById('toast-region').append(toast.element);
this.#bindSettingsToggle();
applySettings(settings);
this.#renderChrome();
this.#levelIds = (await this.#lessons.listLevels()).map((level) => level.id);
// Premier niveau non terminé, ou le dernier si tout est fait.
const next = this.#levelIds.find((id) => !this.#progress.isCompleted(id)) ?? this.#levelIds.at(-1);
await this.#openLevel(next);
this.#registerServiceWorker();
}
async #openLevel(id) {
this.#currentId = id;
await this.#renderMap();
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
await this.#manager.start(session);
}
async #renderMap() {
const levels = await Promise.all(
this.#levelIds.map(async (id) => {
const level = await this.#lessons.loadLevel(id);
return { id, title: level.title[this.#i18n.lang] ?? level.title.fr };
}),
);
this.#map.render({ levels, progress: this.#progress.snapshot(), currentId: this.#currentId });
}
#renderChrome() {
const toggle = document.getElementById('settings-toggle');
toggle.textContent = this.#i18n.t('settings.title');
document.getElementById('app-title').textContent = this.#i18n.t('app.title');
this.#panel.render(this.#settings.settings);
}
#bindSettingsToggle() {
const toggle = document.getElementById('settings-toggle');
const region = document.getElementById('settings-region');
toggle.addEventListener('click', () => {
const open = region.hidden;
region.hidden = !open;
toggle.setAttribute('aria-expanded', String(open));
});
}
async #onSettingChange({ key, value }) {
await this.#settings.update(key, value);
const settings = this.#settings.settings;
applySettings(settings);
this.#audio.setEnabled(settings.soundEnabled);
this.#audio.setVolume(settings.volume);
this.#voice.setEnabled(settings.voiceEnabled);
this.#voice.setRate(settings.voiceRate);
if (key === 'lang') {
this.#i18n.setLang(value);
this.#renderChrome();
// Le niveau courant redémarre dans la nouvelle langue (les saisies en cours sont perdues).
await this.#openLevel(this.#currentId);
}
}
#registerServiceWorker() {
// Repli : sans service worker (http hors localhost, navigateur ancien), l'app fonctionne en ligne.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js').catch(() => {});
}
}
}
new App().run().catch((error) => {
document.getElementById('notebook-region').textContent = `PyQuest: ${error.message}`;
});
+5 -2
View File
@@ -7,15 +7,18 @@ export class NotebookView {
#root; #root;
#status; #status;
#onSpeak; #onSpeak;
#canSpeak;
/** /**
* @param {import('../i18n/i18n.js').I18n} i18n * @param {import('../i18n/i18n.js').I18n} i18n
* @param {object} [options] * @param {object} [options]
* @param {(text: string) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton. * @param {(text: string) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton.
* @param {() => boolean} [options.canSpeak] Évalué à chaque étape : la voix est-elle activée ?
*/ */
constructor(i18n, { onSpeak = null } = {}) { constructor(i18n, { onSpeak = null, canSpeak = () => true } = {}) {
this.#i18n = i18n; this.#i18n = i18n;
this.#onSpeak = onSpeak; this.#onSpeak = onSpeak;
this.#canSpeak = canSpeak;
this.#status = el('p', { class: 'notebook-status', role: 'status' }); this.#status = el('p', { class: 'notebook-status', role: 'status' });
this.#root = el('main', { class: 'notebook', id: 'main' }, this.#status); this.#root = el('main', { class: 'notebook', id: 'main' }, this.#status);
} }
@@ -50,7 +53,7 @@ export class NotebookView {
if (image) { if (image) {
children.push(el('img', { src: image, alt: '' })); children.push(el('img', { src: image, alt: '' }));
} }
if (voice && this.#onSpeak) { if (voice && this.#onSpeak && this.#canSpeak()) {
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text) })); 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)); return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
+15
View File
@@ -0,0 +1,15 @@
{
"name": "PyQuest",
"short_name": "PyQuest",
"description": "Apprendre Python par la pratique, directement dans le navigateur.",
"lang": "fr",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#12151c",
"theme_color": "#1d4ed8",
"icons": [
{ "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
{ "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "maskable" }
]
}
+64
View File
@@ -0,0 +1,64 @@
// Service worker : app shell hors ligne.
// - Coquille de l'app : pré-cachée à l'installation.
// - 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-v1';
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/app.css', 'icons/icon.svg', 'js/main.js'];
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE_VERSION).then((cache) => cache.addAll(SHELL)));
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key))))
.then(() => self.clients.claim()),
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.method !== 'GET' || url.origin !== self.location.origin) {
return;
}
// Niveaux : réseau d'abord (contenu qui évolue), cache en repli hors ligne.
// Le reste (code, Pyodide) : cache d'abord, rempli à la première requête.
const networkFirst = url.pathname.startsWith('/levels/') || request.mode === 'navigate';
event.respondWith(networkFirst ? fromNetwork(request) : fromCache(request));
});
async function fromCache(request) {
const cache = await caches.open(CACHE_VERSION);
const cached = await cache.match(request);
if (cached) {
return cached;
}
const response = await fetch(request);
if (response.ok) {
cache.put(request, response.clone());
}
return response;
}
async function fromNetwork(request) {
const cache = await caches.open(CACHE_VERSION);
try {
const response = await fetch(request);
if (response.ok) {
cache.put(request, response.clone());
}
return response;
} catch (error) {
const cached = await cache.match(request);
if (cached) {
return cached;
}
throw error;
}
}
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Serveur de développement : sert app/ à la racine, plus /levels/ et /vendor/ du dépôt.
Ajoute les en-têtes COOP/COEP/CORP exigés par le SharedArrayBuffer (interruption de Pyodide).
"""
from __future__ import annotations
import argparse
import mimetypes
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
APP_DIR = ROOT / "app"
MOUNTS = {"/levels/": ROOT / "levels", "/vendor/": ROOT / "vendor"}
mimetypes.add_type("text/javascript", ".mjs")
mimetypes.add_type("application/manifest+json", ".webmanifest")
mimetypes.add_type("application/wasm", ".wasm")
class DevHandler(SimpleHTTPRequestHandler):
def translate_path(self, path: str) -> str:
clean = path.split("?", 1)[0].split("#", 1)[0]
base, relative = APP_DIR, clean.lstrip("/")
for prefix, directory in MOUNTS.items():
if clean.startswith(prefix):
base, relative = directory, clean[len(prefix):]
break
target = (base / relative).resolve()
# Refuse toute sortie du dossier servi (../).
if base.resolve() not in (target, *target.parents):
return str(base / "__forbidden__")
return str(target)
def end_headers(self) -> None:
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
self.send_header("Cache-Control", "no-cache")
super().end_headers()
def log_message(self, format: str, *args: Any) -> None:
if os.environ.get("PYQUEST_QUIET") != "1":
super().log_message(format, *args)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--host", default="127.0.0.1")
args = parser.parse_args()
server = ThreadingHTTPServer((args.host, args.port), DevHandler)
print(f"PyQuest dev server: http://{args.host}:{args.port}/")
server.serve_forever()
if __name__ == "__main__":
main()