234 lines
11 KiB
JavaScript
234 lines
11 KiB
JavaScript
// La gamification dans l'interface : tout l'usage de app/domain/gamification.js
|
||
// passe par ce module (HUD de l'accueil, combo de la séance, écran de fin de
|
||
// séance). Codes du jeu vidéo, avec mesure : on récompense la régularité et la
|
||
// progression, jamais l'échec ni l'excès (les règles sont dans le domaine).
|
||
// Animations courtes, une seule fois, coupées par prefers-reduced-motion.
|
||
|
||
import { gameStats, sessionCombo, sessionRewards } from "../domain/gamification.js";
|
||
import { h } from "./dom.js";
|
||
import { href } from "./router.js";
|
||
|
||
/** @typedef {import("../domain/state.js").State} State */
|
||
/** @typedef {import("../domain/gamification.js").SessionRewards} SessionRewards */
|
||
|
||
/** Nombre de cases de la jauge d'XP. */
|
||
export const XP_CELLS = 20;
|
||
|
||
/**
|
||
* Jauge en cases : `filled` cases pleines sur `total`.
|
||
* @param {number} filled
|
||
* @param {number} total
|
||
* @param {string} [cls]
|
||
*/
|
||
export function cells(filled, total, cls = "cells") {
|
||
return h("span", { class: cls, "aria-hidden": "true" },
|
||
Array.from({ length: total }, (_, i) => h("i", { data: { state: i < filled ? "done" : "todo" } })));
|
||
}
|
||
|
||
/**
|
||
* Bandeau de l'accueil : niveau, XP, série de semaines. Il mène au détail
|
||
* (succès, records).
|
||
* @param {State} state
|
||
* @param {string} today
|
||
*/
|
||
export function hud(state, today) {
|
||
const stats = gameStats(state, { today });
|
||
const { level, streak } = stats;
|
||
const filled = Math.floor(level.progress * XP_CELLS);
|
||
return h("a", {
|
||
class: "hud", href: href.progress(),
|
||
"aria-label": `${level.label}. ${level.xpForNext} XP avant le niveau suivant. ${streak.label}. Voir tes succès.`,
|
||
},
|
||
h("span", { class: "hud__lvl" }, h("span", { class: "mark" }, "Niv."), h("span", { class: "hud__big num" }, String(level.level))),
|
||
h("span", { class: "hud__body" },
|
||
h("span", { class: "hud__title" }, level.title),
|
||
cells(filled, XP_CELLS, "cells cells--xp"),
|
||
h("span", { class: "mark muted" }, `${level.xpInLevel} / ${level.xpInLevel + level.xpForNext} XP`)),
|
||
h("span", { class: "hud__streak" },
|
||
h("span", { class: "hud__big num" }, String(streak.current)),
|
||
h("span", { class: "mark" }, streak.current > 1 ? "semaines" : "semaine"),
|
||
streak.atStake && h("span", { class: "mark muted" }, "en jeu")));
|
||
}
|
||
|
||
/**
|
||
* Combo de la séance en cours, à partir des séries du brouillon (dans l'ordre
|
||
* où elles ont été validées, voir session-draft.setsInOrder).
|
||
* @param {(import("../domain/events.js").LoggedSet|null)[]} sets
|
||
* @returns {string} « Combo ×4 », ou vide
|
||
*/
|
||
export function comboLabel(sets) {
|
||
return sessionCombo(sets).label;
|
||
}
|
||
|
||
/** @type {{rewards: SessionRewards, summary: SessionSummary}|null} */
|
||
let lastFinish = null;
|
||
|
||
/**
|
||
* @typedef {object} SessionSummary
|
||
* @property {string} name
|
||
* @property {string} date
|
||
* @property {number} sets
|
||
* @property {number} reps
|
||
* @property {number} volumeKg somme des répétitions × charge
|
||
*/
|
||
|
||
/**
|
||
* À la fin d'une séance : calcule et garde ce qu'elle rapporte, pour l'écran de
|
||
* fin. Rien n'est stocké : un rechargement de la page ramène à l'accueil.
|
||
* @param {State} before
|
||
* @param {State} after
|
||
* @param {string} today
|
||
* @param {SessionSummary} summary
|
||
*/
|
||
export function recordFinish(before, after, today, summary) {
|
||
lastFinish = { rewards: sessionRewards(before, after, { today }), summary };
|
||
}
|
||
|
||
export function takeFinish() {
|
||
return lastFinish;
|
||
}
|
||
|
||
/** L'utilisateur a demandé moins de mouvement. */
|
||
const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||
|
||
/**
|
||
* Compteur qui monte jusqu'à sa valeur en moins d'une seconde, une fois.
|
||
* @param {HTMLElement} el
|
||
* @param {number} to
|
||
* @param {(n: number) => string} format
|
||
*/
|
||
function countUp(el, to, format) {
|
||
if (reducedMotion() || to <= 0) {
|
||
el.textContent = format(to);
|
||
return;
|
||
}
|
||
const start = performance.now();
|
||
const duration = 700;
|
||
el.textContent = format(0);
|
||
const step = (/** @type {number} */ now) => {
|
||
const t = Math.min(1, (now - start) / duration);
|
||
el.textContent = format(Math.round(to * (1 - (1 - t) ** 3)));
|
||
if (t < 1) requestAnimationFrame(step);
|
||
};
|
||
requestAnimationFrame(step);
|
||
}
|
||
|
||
/** « 1 840 » @param {number} n */
|
||
const thousands = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, " ");
|
||
|
||
/**
|
||
* Écran de fin de séance : le moment endorphine. Un grand chiffre, l'XP qui
|
||
* monte, le niveau, les records et les succès.
|
||
* @param {{nav: import("./router.js").Navigation}} ctx
|
||
* @returns {import("./router.js").Screen}
|
||
*/
|
||
export function finishScreen({ nav }) {
|
||
const done = lastFinish;
|
||
if (!done) {
|
||
queueMicrotask(() => nav.go(href.home(), { replace: true }));
|
||
return { node: h("div", { class: "screen" }), title: "" };
|
||
}
|
||
const { rewards, summary } = done;
|
||
const big = h("span", { class: "big-number" });
|
||
const xp = h("span", { class: "num" });
|
||
const lvl = rewards.levelAfter;
|
||
const filled = Math.floor(lvl.progress * XP_CELLS);
|
||
const volume = summary.volumeKg > 0;
|
||
|
||
const node = h("div", { class: "screen screen--finish" },
|
||
h("header", { class: "screen-head" },
|
||
h("p", { class: "kicker" }, "Séance terminée · ", summary.name),
|
||
h("h1", { class: "title title--hero" }, "Bien joué.")),
|
||
h("section", { class: "reward", "aria-label": "Ce que tu as fait" },
|
||
h("p", { class: "reward__big" }, big, h("small", null, volume ? "kg" : "séries")),
|
||
h("p", { class: "mark" }, volume
|
||
? `soulevés · ${summary.sets} séries · ${summary.reps} répétitions`
|
||
: `${summary.reps} répétitions`)),
|
||
h("section", { class: "reward__xp", "aria-label": "Expérience" },
|
||
h("p", { class: "reward__gain" }, "+", xp, " XP"),
|
||
h("ul", { class: "reward__parts" }, rewards.parts.map((p) =>
|
||
h("li", null, h("span", null, p.label), h("span", { class: "num" }, `+${p.xp}`)))),
|
||
h("div", { class: "reward__level" },
|
||
h("span", { class: "mark" }, lvl.label),
|
||
cells(filled, XP_CELLS, "cells cells--xp reward__cells"),
|
||
h("span", { class: "mark muted" }, `${lvl.xpForNext} XP avant le niveau ${lvl.level + 1}`))),
|
||
rewards.levelUp && h("p", { class: "stamp", role: "status" }, "Niveau supérieur ! ", h("br"), rewards.levelUp.text),
|
||
rewards.records.length > 0 && h("section", { class: "reward__records" },
|
||
h("p", { class: "stamp stamp--record" }, rewards.records.length > 1 ? `${rewards.records.length} records !` : "Record !"),
|
||
h("ul", { class: "rows" }, rewards.records.map((r) =>
|
||
h("li", { class: "row" }, h("span", { class: "row__main" }, h("span", { class: "row__title" }, r.text)))))),
|
||
rewards.achievements.length > 0 && h("section", null,
|
||
h("h2", { class: "tape" }, "Succès débloqué"),
|
||
h("ul", { class: "rows" }, rewards.achievements.map((a) =>
|
||
h("li", { class: "row" },
|
||
h("span", { class: "badge badge--signal", "aria-hidden": "true" }, "★"),
|
||
h("span", { class: "row__main" }, h("span", { class: "row__title" }, a.title), h("span", { class: "row__meta" }, a.description)))))),
|
||
rewards.streak.after > 0 && h("p", { class: "muted reward__streak" },
|
||
`Série : ${rewards.streak.after} semaine${rewards.streak.after > 1 ? "s" : ""}.`,
|
||
rewards.streak.after > rewards.streak.before ? " Elle monte." : ""),
|
||
h("div", { class: "action-bar" }, h("div", { class: "action-bar__in" },
|
||
h("a", { class: "btn btn--primary btn--block btn--lg", href: href.home() }, "Continuer"))));
|
||
|
||
countUp(big, volume ? summary.volumeKg : summary.sets, thousands);
|
||
countUp(xp, rewards.xp, String);
|
||
return { node, title: "Bien joué", destroy: () => { lastFinish = null; } };
|
||
}
|
||
|
||
/**
|
||
* Écran « Progression » : niveau, série, records et succès.
|
||
* @param {{store: import("./store.js").Store, nav: import("./router.js").Navigation, today: string}} ctx
|
||
* @returns {import("./router.js").Screen}
|
||
*/
|
||
export function progressScreen({ store, nav, today }) {
|
||
const stats = gameStats(store.getState(), { today });
|
||
const { level, streak } = stats;
|
||
const unlocked = stats.achievements.filter((a) => a.unlocked);
|
||
const locked = stats.achievements.filter((a) => !a.unlocked);
|
||
const recent = stats.streak.weeks.slice(-8);
|
||
const node = h("div", { class: "screen" },
|
||
h("header", { class: "screen-head" },
|
||
h("button", { type: "button", class: "back", on: { click: () => nav.back(href.home()) } }, "← Accueil"),
|
||
h("p", { class: "kicker" }, level.label),
|
||
h("h1", { class: "title" }, "Progression")),
|
||
h("div", { class: "stats" },
|
||
stat(String(level.level), "niveau"),
|
||
stat(thousands(stats.xp), "XP au total"),
|
||
stat(String(streak.current), `semaine${streak.current > 1 ? "s" : ""} de série`),
|
||
stat(String(stats.records.beaten), "records battus")),
|
||
h("div", { class: "block" },
|
||
h("p", { class: "mark" }, `${level.xpInLevel} / ${level.xpInLevel + level.xpForNext} XP · niveau ${level.level + 1} ensuite`),
|
||
cells(Math.floor(level.progress * XP_CELLS), XP_CELLS, "cells cells--xp"),
|
||
h("p", { class: "muted" }, "Une séance de force rapporte 100 XP, un cardio ou une activité 50. Bonus : séance complète, faite le jour prévu, record battu. Une série en échec ne rapporte rien de plus : écoute ton corps.")),
|
||
h("h2", { class: "tape" }, "Semaines", h("span", { class: "tape__hint" }, streak.thisWeek.label)),
|
||
recent.length
|
||
? h("ul", { class: "rows" }, [...recent].reverse().map((w) =>
|
||
h("li", { class: "row" },
|
||
h("span", { class: "row__main" }, h("span", { class: "row__title" }, `Semaine du ${dayMonth(w.monday)}`), h("span", { class: "row__meta" }, w.label)),
|
||
h("span", { class: "row__side mark" }, WEEK_STATUS[w.status] ?? w.status))))
|
||
: h("p", { class: "empty" }, "Ta première séance lance la série."),
|
||
h("h2", { class: "tape" }, "Succès", h("span", { class: "tape__hint" }, `${unlocked.length} / ${stats.achievements.length}`)),
|
||
h("ul", { class: "rows" },
|
||
unlocked.map((a) => h("li", { class: "row" },
|
||
h("span", { class: "badge badge--signal", "aria-hidden": "true" }, "★"),
|
||
h("span", { class: "row__main" }, h("span", { class: "row__title" }, a.title), h("span", { class: "row__meta" }, a.description)),
|
||
h("span", { class: "row__side mark" }, a.date ? dayMonth(a.date) : ""))),
|
||
locked.map((a) => h("li", { class: "row" },
|
||
h("span", { class: "badge", "aria-hidden": "true" }, "·"),
|
||
h("span", { class: "row__main" }, h("span", { class: "row__title muted" }, a.title), h("span", { class: "row__meta" }, a.description)),
|
||
h("span", { class: "row__side mark muted" }, "à débloquer")))));
|
||
return { node, title: "Progression" };
|
||
}
|
||
|
||
/** @type {Record<string, string>} */
|
||
const WEEK_STATUS = { met: "✓ atteinte", missed: "manquée", rest: "repos", start: "départ", inPlay: "en jeu" };
|
||
|
||
/** @param {string} value @param {string} label */
|
||
function stat(value, label) {
|
||
return h("div", { class: "stat" }, h("span", { class: "stat__value" }, value), h("span", { class: "stat__label" }, label));
|
||
}
|
||
|
||
/** @param {string} day */
|
||
function dayMonth(day) {
|
||
return new Date(day + "T12:00:00").toLocaleDateString("fr-FR", { day: "numeric", month: "short" });
|
||
}
|