Add progress export/import (JSON file) with strict import validation and change events

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 17:19:54 +02:00
parent b19d3c038d
commit aa2fd84352
8 changed files with 191 additions and 10 deletions
+20
View File
@@ -287,6 +287,26 @@ pre {
accent-color: var(--accent);
}
.setting-group {
margin: 1rem 0;
padding: 0.75rem;
border: 1px solid var(--border);
border-radius: 0.5rem;
}
.setting-group legend {
padding: 0 0.25rem;
font-weight: 700;
}
.setting-group .hint {
margin: 0 0 0.5rem;
}
.setting-group .btn {
margin: 0.25rem 0.5rem 0.25rem 0;
}
.author-link {
display: inline-flex;
align-items: center;
+40 -8
View File
@@ -4,6 +4,13 @@
const STORAGE_KEY = 'progress';
const SCHEMA_VERSION = 1;
const ID_PATTERN = /^(?!__proto__$)[A-Za-z0-9_-]{1,64}$/;
const MAX_ENTRIES = 500;
const MAX_LEVEL_XP = 100000;
function isPlainObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
// Badges de progression : règle déclarative évaluée sur l'état complet.
const BADGES = [
@@ -14,12 +21,13 @@ const BADGES = [
{ id: 'streak_7', test: (state) => state.streak.best >= 7 },
];
export class ProgressStore {
export class ProgressStore extends EventTarget {
#store;
#state = null;
/** @param {{get: (key: string) => Promise<any>, set: (key: string, value: any) => Promise<void>}} store */
constructor(store) {
super();
this.#store = store;
}
@@ -103,20 +111,24 @@ export class ProgressStore {
/**
* Importe une progression exportée. Fusion par défaut (union, jamais de perte) : pratique
* pour réunir deux appareils. `replace` écrase tout.
* pour réunir deux appareils. `replace` écrase tout. Lève une erreur si le contenu est invalide.
*/
async import(json, { mode = 'merge' } = {}) {
const incoming = this.#parseImport(json);
const state = this.#requireState();
const before = Object.keys(state.completedLevels).length;
if (mode === 'replace') {
this.#state = incoming;
} else {
this.#merge(state, incoming);
}
await this.#save();
return this.snapshot();
// `addedLevels` : niveaux nouveaux pour cet appareil (pour informer l'apprenant).
const after = Object.keys(this.#requireState().completedLevels).length;
return { ...this.snapshot(), addedLevels: Math.max(0, after - before) };
}
/** Valide strictement un fichier venant de l'extérieur (jamais fiable : fichier édité, jeton volé…). */
#parseImport(json) {
let data;
try {
@@ -124,15 +136,34 @@ export class ProgressStore {
} catch {
throw new Error('Invalid progress file: not JSON');
}
if (!isPlainObject(data) || data.version !== SCHEMA_VERSION) {
throw new Error('Invalid progress file: unsupported format');
}
const { completedLevels, badges, streak } = data;
const valid =
data?.version === SCHEMA_VERSION &&
typeof data.completedLevels === 'object' &&
typeof data.badges === 'object' &&
typeof data.streak === 'object';
isPlainObject(completedLevels) &&
Object.entries(completedLevels).length <= MAX_ENTRIES &&
Object.entries(completedLevels).every(
([id, level]) =>
ID_PATTERN.test(id) &&
isPlainObject(level) &&
Number.isFinite(level.xp) &&
level.xp >= 0 &&
level.xp <= MAX_LEVEL_XP &&
typeof level.completedAt === 'string',
) &&
isPlainObject(badges) &&
Object.entries(badges).length <= MAX_ENTRIES &&
Object.entries(badges).every(([id, at]) => ID_PATTERN.test(id) && typeof at === 'string') &&
isPlainObject(streak) &&
Number.isInteger(streak.current) &&
Number.isInteger(streak.best) &&
(streak.lastDay === null || typeof streak.lastDay === 'string');
if (!valid) {
throw new Error('Invalid progress file: unsupported format');
}
return data;
// On ne reprend que les champs connus.
return { version: SCHEMA_VERSION, completedLevels, badges, streak: { current: streak.current, best: streak.best, lastDay: streak.lastDay } };
}
#merge(state, incoming) {
@@ -182,6 +213,7 @@ export class ProgressStore {
async #save() {
await this.#store.set(STORAGE_KEY, this.#state);
this.dispatchEvent(new Event('change'));
}
#requireState() {
+8 -1
View File
@@ -86,5 +86,12 @@
"settings.testSound": "Test the sound",
"settings.testVoice": "Test the voice",
"settings.voiceOffNotice": "Turn the voice on in the settings first.",
"settings.voiceRate": "Voice speed"
"settings.voiceRate": "Voice speed",
"backup.title": "Progress backup",
"backup.help": "A file to keep or copy to another device. Nothing is sent over the Internet.",
"backup.export": "Export my progress",
"backup.import": "Import progress",
"backup.imported": "Progress imported: {n} new level(s).",
"backup.importFailed": "This file is not a valid PyQuest progress file.",
"backup.exported": "Progress exported."
}
+8 -1
View File
@@ -86,5 +86,12 @@
"settings.testSound": "Tester le son",
"settings.testVoice": "Tester la voix",
"settings.voiceOffNotice": "Active d'abord la voix dans les réglages.",
"settings.voiceRate": "Vitesse de la voix"
"settings.voiceRate": "Vitesse de la voix",
"backup.title": "Sauvegarde de la progression",
"backup.help": "Un fichier à garder ou à copier sur un autre appareil. Rien n'est envoyé sur Internet.",
"backup.export": "Exporter ma progression",
"backup.import": "Importer une progression",
"backup.imported": "Progression importée : {n} nouveau(x) niveau(x).",
"backup.importFailed": "Ce fichier n'est pas une progression PyQuest valide.",
"backup.exported": "Progression exportée."
}
+25
View File
@@ -122,6 +122,8 @@ class App {
this.#panel = new SettingsPanel(this.#i18n);
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
this.#panel.addEventListener('export', () => this.#exportProgress());
this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file));
document.getElementById('notebook-region').append(notebook.element);
document.getElementById('toast-region').append(toast.element);
@@ -267,6 +269,29 @@ class App {
}
}
/** Télécharge la progression en JSON (Blob + lien temporaire : API standard, sans serveur). */
#exportProgress() {
const blob = new Blob([this.#progress.export()], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = el('a', { href: url, download: `pyquest-progress-${ProgressStore.dayKey(new Date())}.json` });
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
this.#toast.show(this.#i18n.t('backup.exported'));
}
/** Fusionne un fichier de progression (union : on ne perd jamais rien). */
async #importProgress(file) {
try {
const result = await this.#progress.import(await file.text());
await this.#renderMap();
this.#toast.show(this.#i18n.t('backup.imported', { n: result.addedLevels }));
} catch {
this.#toast.show(this.#i18n.t('backup.importFailed'));
}
}
/** Échantillons des réglages : le clic est le geste utilisateur qui débloque le son. */
async #onTest(kind) {
if (kind === 'sound') {
+29
View File
@@ -42,6 +42,7 @@ export class SettingsPanel extends EventTarget {
this.#testButton('settings.testVoice', 'voice'),
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
this.#backupSection(),
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
);
}
@@ -51,6 +52,34 @@ export class SettingsPanel extends EventTarget {
this.#root.querySelector(`[data-setting="${key}"]`)?.focus();
}
/** Sauvegarde manuelle de la progression : fichier JSON, sans serveur. */
#backupSection() {
const t = (key) => this.#i18n.t(key);
const fileId = uniqueId('import');
const input = el('input', {
id: fileId,
type: 'file',
accept: 'application/json,.json',
hidden: true,
onchange: (event) => {
const [file] = event.target.files;
event.target.value = '';
if (file) {
this.dispatchEvent(new CustomEvent('import', { detail: { file } }));
}
},
});
return el(
'fieldset',
{ class: 'setting-group' },
el('legend', { text: t('backup.title') }),
el('p', { class: 'hint', text: t('backup.help') }),
el('button', { type: 'button', class: 'btn', text: t('backup.export'), onclick: () => this.dispatchEvent(new Event('export')) }),
el('button', { type: 'button', class: 'btn', text: t('backup.import'), onclick: () => input.click() }),
input,
);
}
#testButton(labelKey, kind) {
const button = el('button', {
type: 'button',