mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
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:
@@ -211,3 +211,48 @@ body {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 |
@@ -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
@@ -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}`;
|
||||
});
|
||||
@@ -7,15 +7,18 @@ export class NotebookView {
|
||||
#root;
|
||||
#status;
|
||||
#onSpeak;
|
||||
#canSpeak;
|
||||
|
||||
/**
|
||||
* @param {import('../i18n/i18n.js').I18n} i18n
|
||||
* @param {object} [options]
|
||||
* @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.#onSpeak = onSpeak;
|
||||
this.#canSpeak = canSpeak;
|
||||
this.#status = el('p', { class: 'notebook-status', role: 'status' });
|
||||
this.#root = el('main', { class: 'notebook', id: 'main' }, this.#status);
|
||||
}
|
||||
@@ -50,7 +53,7 @@ export class NotebookView {
|
||||
if (image) {
|
||||
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) }));
|
||||
}
|
||||
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
|
||||
|
||||
@@ -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" }
|
||||
]
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user