mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add UI components, i18n, settings store and base styles
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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}`) }));
|
||||
}
|
||||
}
|
||||
@@ -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 }));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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}`;
|
||||
}
|
||||
Reference in New Issue
Block a user