Écrans branchés : planning du jour, semaine, activités, poids, données, profil, analyses, propositions avec aperçu, gamification

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-18 05:26:02 +01:00
co-authored by Claude Opus 5.5
parent 077f2dc58d
commit 41d5e44daa
35 changed files with 2931 additions and 367 deletions
+100
View File
@@ -0,0 +1,100 @@
// Petites courbes en SVG, sans bibliothèque : poids, charge, répétitions,
// assiduité. Une seule série par courbe (jamais deux échelles), un trait plein
// à angles vifs, des repères carrés. Les valeurs sont aussi dans une liste ou
// un tableau à côté : la courbe n'est jamais la seule source.
// La géométrie (pure, testée) est séparée du dessin (DOM).
const NS = "http://www.w3.org/2000/svg";
/**
* @typedef {object} Geometry
* @property {string} path « M x,y L x,y … »
* @property {{x: number, y: number}[]} dots
* @property {{y: number, value: number}[]} ticks trois repères horizontaux
* @property {(x: number, value: number) => {x: number, y: number}} at
*/
/**
* Place des points (x quelconque, croissant ; y en unité) dans un cadre.
* @param {{x: number, y: number}[]} points
* @param {{width: number, height: number, left?: number, right?: number, top?: number, bottom?: number, minSpan?: number}} box
* @returns {Geometry}
*/
export function lineGeometry(points, { width, height, left = 36, right = 8, top = 10, bottom = 20, minSpan = 1 }) {
const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
const x0 = Math.min(...xs), x1 = Math.max(...xs);
let y0 = Math.min(...ys), y1 = Math.max(...ys);
const margin = Math.max(minSpan / 2, (y1 - y0) * 0.15);
y0 -= margin;
y1 += margin;
const px = (/** @type {number} */ x) => left + (width - left - right) * (x1 === x0 ? 0.5 : (x - x0) / (x1 - x0));
const py = (/** @type {number} */ y) => top + (height - top - bottom) * (1 - (y - y0) / (y1 - y0));
const round = (/** @type {number} */ n) => Math.round(n * 10) / 10;
const dots = points.map((p) => ({ x: round(px(p.x)), y: round(py(p.y)) }));
return {
path: dots.map((d, i) => `${i ? "L" : "M"}${d.x},${d.y}`).join(" "),
dots,
ticks: [0, 0.5, 1].map((f) => ({ value: y0 + (y1 - y0) * f, y: round(py(y0 + (y1 - y0) * f)) })),
at: (x, value) => ({ x: round(px(x)), y: round(py(value)) }),
};
}
/**
* @param {string} tag
* @param {Record<string, string|number>} attrs
* @param {string} [text]
*/
function el(tag, attrs, text) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v));
if (text !== undefined) e.textContent = text;
return e;
}
/**
* Courbe d'une série dans le temps.
* @param {{points: {x: number, y: number}[], label: string, format: (v: number) => string, xLabels: [string, string], trend?: {from: number, to: number}|null, minSpan?: number}} o
* x : jours depuis une origine ; trend : valeurs de la tendance au premier et au dernier x
* @returns {SVGSVGElement}
*/
export function lineChart({ points, label, format, xLabels, trend = null, minSpan = 1 }) {
const W = 340, H = 160;
const g = lineGeometry(points, { width: W, height: H, minSpan });
const svg = /** @type {SVGSVGElement} */ (el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": label }));
for (const t of g.ticks) {
svg.append(el("line", { class: "chart__axis", x1: 36, x2: W - 8, y1: t.y, y2: t.y }));
svg.append(el("text", { class: "chart__text", x: 30, y: t.y + 4, "text-anchor": "end" }, format(t.value)));
}
if (trend && points.length > 2) {
const a = g.at(points[0].x, trend.from), b = g.at(points[points.length - 1].x, trend.to);
svg.append(el("line", { class: "chart__trend", x1: a.x, y1: a.y, x2: b.x, y2: b.y }));
}
svg.append(el("path", { class: "chart__line", d: g.path }));
for (const d of g.dots) svg.append(el("rect", { class: "chart__dot", x: d.x - 3, y: d.y - 3, width: 6, height: 6 }));
svg.append(el("text", { class: "chart__text", x: 36, y: H - 4 }, xLabels[0]));
svg.append(el("text", { class: "chart__text", x: W - 8, y: H - 4, "text-anchor": "end" }, xLabels[1]));
return svg;
}
/**
* Barres verticales (une par semaine) : des blocs, comme des disques empilés.
* @param {{values: number[], label: string, labels: [string, string], highlightLast?: boolean}} o
* @returns {SVGSVGElement}
*/
export function barChart({ values, label, labels, highlightLast = true }) {
const W = 340, H = 130, top = 8, bottom = 20, left = 4, right = 4;
const max = Math.max(1, ...values);
const step = (W - left - right) / values.length;
const svg = /** @type {SVGSVGElement} */ (el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": label }));
svg.append(el("line", { class: "chart__axis", x1: left, x2: W - right, y1: H - bottom, y2: H - bottom }));
values.forEach((v, i) => {
const h = ((H - top - bottom) * v) / max;
if (v > 0) svg.append(el("rect", {
class: `chart__bar${highlightLast && i === values.length - 1 ? " chart__bar--now" : ""}`,
x: Math.round(left + i * step + 2), y: Math.round(H - bottom - h), width: Math.max(2, Math.round(step - 4)), height: Math.round(h),
}));
});
svg.append(el("text", { class: "chart__text", x: left, y: H - 4 }, labels[0]));
svg.append(el("text", { class: "chart__text", x: W - right, y: H - 4, "text-anchor": "end" }, labels[1]));
return svg;
}
+32
View File
@@ -69,6 +69,38 @@ export function setAccent(el, color, ink) {
el.style.setProperty("--accent-ink", ink);
}
/**
* Repeint une zone à chaque changement de l'état, sauf pendant une saisie :
* piège d'Atelier, on ne reconstruit jamais une zone qui contient le champ en
* cours de saisie. Le repeint attend alors que le champ perde le focus.
* @param {HTMLElement} zone
* @param {() => void} paint
* @returns {() => void} à appeler à chaque changement
*/
export function paintWhenIdle(zone, paint) {
let pending = false;
zone.addEventListener("focusout", () => {
if (!pending) return;
// Le focus peut passer à un autre champ de la même zone.
setTimeout(() => {
if (pending && !isTyping(zone)) {
pending = false;
paint();
}
}, 0);
});
return () => {
if (isTyping(zone)) pending = true;
else paint();
};
}
/** @param {HTMLElement} zone */
function isTyping(zone) {
const el = document.activeElement;
return !!el && zone.contains(el) && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement);
}
/** Vibration courte, si l'appareil sait le faire. @param {number[]} pattern */
export function vibrate(pattern) {
try {
+36 -6
View File
@@ -11,10 +11,12 @@ import { TRACKING_MODES, EFFORTS } from "../domain/vocabulary.js";
import { resolveExercise, trackingFor } from "../domain/program.js";
import { EFFORT_LABELS, TRACKING_LABELS } from "./labels.js";
import { kg, parseAmount, restLabel } from "./format.js";
import { doneCount, draftExercise, proposedReps, targetLabel, targetReps, usesLoad, usesTime } from "./session-draft.js";
import { doneCount, draftExercise, markSet, proposedReps, targetLabel, targetReps, usesLoad, usesTime } from "./session-draft.js";
import { progressionAdvice } from "../domain/progression.js";
/**
* @typedef {object} ExerciseCardOptions
* @property {import("./session-draft.js").Draft} draft
* @property {import("./session-draft.js").DraftExercise} ex exercice du brouillon (modifié sur place)
* @property {import("../domain/program.js").ProgramExercise} item
* @property {string} sessionKey
@@ -59,13 +61,17 @@ export function exerciseCard(o) {
let openPanel = null;
/** @type {HTMLButtonElement|null} */
let chronoBtn = null;
/** @type {HTMLInputElement|null} */
let loadInput = null;
const paintSets = () => {
setButtons.forEach((b, i) => {
const s = ex.done[i];
b.classList.toggle("set-btn--done", s !== null);
b.dataset.effort = s?.effort ?? "";
b.textContent = s === null ? String(i + 1) : typeof s.reps === "number" ? String(s.reps) : "✓";
replace(b,
h("span", { class: "set-btn__n" }, s === null ? String(i + 1) : typeof s.reps === "number" ? String(s.reps) : "✓"),
s?.effort ? h("span", { class: "set-btn__effort" }, EFFORT_LABELS[s.effort].short) : null);
const what = s === null ? "à faire"
: [typeof s.reps === "number" ? `${s.reps} répétitions` : "faite", s.effort ? EFFORT_LABELS[s.effort].label.toLowerCase() : null]
.filter(Boolean).join(", ");
@@ -105,7 +111,7 @@ export function exerciseCard(o) {
type: "button", class: "effort", data: { effort },
"aria-pressed": String(existing?.effort === effort),
on: { click: () => {
ex.done[i] = { reps: timed ? null : reps, effort };
markSet(o.draft, ex, i, { reps: timed ? null : reps, effort });
closePanel();
changed();
// Le repos démarre au ressenti.
@@ -130,7 +136,7 @@ export function exerciseCard(o) {
timer.startWork(seconds, `${ex.name} · série ${i + 1}`, () => {
// Fin du chrono : la série est cochée (bug d'Atelier : « cocher » n'existait
// pas), puis on demande le ressenti, qui lancera le repos.
if (ex.done[i] === null) ex.done[i] = { reps: null, effort: null };
if (ex.done[i] === null) markSet(o.draft, ex, i, { reps: null, effort: null });
changed();
openPanel = null;
showPanel(i);
@@ -163,6 +169,7 @@ export function exerciseCard(o) {
refreshChrono();
o.onChange();
});
if (isLoad) loadInput = input;
input.addEventListener("change", () => {
const v = parseAmount(input.value);
if (v === undefined || (field === "seconds" && !v)) return;
@@ -178,6 +185,7 @@ export function exerciseCard(o) {
const drawWork = () => {
openPanel = null;
chronoBtn = null;
loadInput = null;
setButtons = Array.from({ length: ex.sets }, (_, i) =>
h("button", { type: "button", class: "set-btn", on: { click: () => showPanel(i) } }, String(i + 1)));
const fields = h("div", { class: "work__fields" },
@@ -210,12 +218,34 @@ export function exerciseCard(o) {
ex.loadKg = fresh.loadKg;
ex.seconds = fresh.seconds;
drawWork();
paintAdvice();
changed();
/** @type {HTMLElement|null} */ (tracking.querySelector("[aria-pressed=true]"))?.focus();
} },
}, TRACKING_LABELS[mode])));
};
// ---- conseil de progression (double progression) ------------------------------
const advice = h("div", { class: "advice", hidden: true });
const paintAdvice = () => {
const a = usesLoad(ex.tracking) ? progressionAdvice(store.getState(), o.sessionKey, item) : null;
if (!a || ex.loadKg === a.newLoadKg) {
advice.hidden = true;
return;
}
advice.hidden = false;
replace(advice,
h("p", { class: "advice__head" }, h("span", { class: "mark" }, "Prêt à monter"), h("span", { class: "num advice__kg" }, `${kg(a.newLoadKg)} kg`)),
h("p", { class: "muted" }, `Dernière fois : ${a.reason}.`),
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => {
store.dispatch("WorkingLoadSet", { key: ex.key, loadKg: a.newLoadKg });
ex.loadKg = a.newLoadKg;
if (loadInput) { loadInput.value = kg(a.newLoadKg); loadInput.setAttribute("aria-invalid", "false"); }
advice.hidden = true;
changed();
} } }, `Adopter ${kg(a.newLoadKg)} kg`));
};
// ---- consignes ---------------------------------------------------------------
const muscles = library
? h("ul", { class: "chips", "aria-label": "Muscles sollicités" },
@@ -241,12 +271,12 @@ export function exerciseCard(o) {
h("a", { class: "btn btn--ghost btn--sm tutorial", href: resolved.tutorial, target: "_blank", rel: "noopener noreferrer" },
"Voir un tutoriel", h("span", { class: "visually-hidden" }, " (nouvel onglet)"), h("span", { "aria-hidden": "true" }, " ↗")),
h("p", { class: "objective" }, objective, h("span", { class: "objective__rest" }, `Repos ${restLabel(ex.rest)}`)),
// À brancher : progression (domaine, sous-lot 1b) pour le conseil « prêt à
// monter à X kg » au-dessus des séries.
advice,
work,
h("div", { class: "tracking" }, h("span", { class: "mini-label" }, "Je suis"), tracking)));
drawWork();
refreshLabels();
paintAdvice();
return card;
}
+49
View File
@@ -0,0 +1,49 @@
// Fichiers et presse-papiers : téléchargement (instantané, .ics), lecture d'un
// fichier choisi, copie d'un texte.
import { h } from "./dom.js";
/**
* Télécharge un texte. La libération de l'adresse est différée de 30 s : la
* révoquer aussitôt interrompt le téléchargement sur certains mobiles
* (piège d'Atelier, docs/lot-1.md).
* @param {string} name
* @param {string} content
* @param {string} type
*/
export function download(name, content, type) {
const url = URL.createObjectURL(new Blob([content], { type }));
const a = h("a", { href: url, download: name, rel: "noopener", class: "visually-hidden" });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
/** @param {File} file @returns {Promise<string>} */
export function readFile(file) {
return file.text();
}
/**
* Copie un texte. Si le presse-papiers est refusé (http, navigateur ancien), le
* texte s'affiche dans `fallback`, sélectionné, pour une copie à la main.
* @param {string} text
* @param {HTMLElement} fallback
* @param {string} label nom du champ pour les lecteurs d'écran
* @returns {Promise<boolean>} vrai si le texte est dans le presse-papiers
*/
export async function copyText(text, fallback, label) {
try {
await navigator.clipboard.writeText(text);
fallback.hidden = true;
return true;
} catch {
const area = h("textarea", { class: "field__input field__input--area field__input--mono", readonly: true, "aria-label": label });
area.value = text;
fallback.replaceChildren(h("p", { class: "muted" }, "Copie ce texte à la main :"), area);
fallback.hidden = false;
area.select();
return false;
}
}
+24 -3
View File
@@ -1,13 +1,34 @@
// Mise en forme pour l'affichage, en français. Fonctions pures, testées.
// À brancher : dates.js (domaine, sous-lot 1b) fournira les calculs de jours ;
// ici, seulement ce que l'interface affiche.
// Les calculs de jours sont ceux du domaine (dates.js).
import { localISO } from "../domain/dates.js";
/**
* Jour local AAAA-MM-JJ (pas UTC : une séance faite à 23 h reste le bon jour).
* @param {Date} [d]
*/
export function localDay(d = new Date()) {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
return localISO(d);
}
/** « lun. 16/11 » @param {string} day */
export function weekdayShort(day) {
return noon(day).toLocaleDateString("fr-FR", { weekday: "short", day: "2-digit", month: "2-digit" });
}
/** Une décimale au plus, à la française : 82.456 → « 82,5 ». @param {number} n */
export function dec1(n) {
return kg(Math.round(n * 10) / 10);
}
/** Durée lisible : 20 → « 20 jours », 400 → « 1 an et 1 mois ». @param {number} days */
export function durationLabel(days) {
if (days < 45) return plural(days, "jour");
let months = Math.round(days / 30.44);
const years = Math.floor(months / 12);
months -= years * 12;
if (!years) return `${months} mois`;
return plural(years, "an") + (months ? ` et ${months} mois` : "");
}
/** @param {string} day AAAA-MM-JJ */
+233
View File
@@ -0,0 +1,233 @@
// 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" });
}
+223 -23
View File
@@ -1,14 +1,26 @@
// Ce que l'accueil affiche, calculé à partir de l'état. Module pur, testé.
//
// À brancher : planning.weekPlan(state, monday) (domaine, sous-lot 1b). Tant
// qu'il n'existe pas, la carte du jour propose la séance faite le moins
// récemment (rotation simple) et le dit à l'utilisateur.
// Ce que l'accueil et l'écran Semaine affichent, calculé à partir de l'état et
// du planning (domaine). Module pur, testé (tests/ui/home-model.test.js).
import { groupBlocks, resolveExercise, targetSeconds } from "../domain/program.js";
import { addDays, dayIndex, mondayOf } from "../domain/dates.js";
import { lateSlots, settingsForWeek, slotRef, weekPlan, weekStatus } from "../domain/planning.js";
/** @typedef {import("../domain/state.js").State} State */
/** @typedef {import("../domain/planning.js").Slot} Slot */
/** @typedef {import("../domain/program.js").Program} Program */
/** Jours de la semaine, du lundi au dimanche. */
export const DAY_SHORT = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
export const DAY_LETTERS = ["L", "M", "M", "J", "V", "S", "D"];
export const DAY_NAMES = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
/** @type {Record<string, string>} */
export const ZONE_LABELS = { cardio: "Cardio", lower: "Bas du corps", upper: "Haut du corps", core: "Tronc" };
/** @type {Record<string, string>} */
export const INTENSITY_LABELS = { light: "Légère", moderate: "Modérée", hard: "Intense" };
/**
* Dernière date (AAAA-MM-JJ) où chaque séance de force a été faite.
* @param {import("../domain/state.js").State} state
* @param {State} state
* @returns {Record<string, string>}
*/
export function lastDoneByKey(state) {
@@ -20,9 +32,9 @@ export function lastDoneByKey(state) {
}
/**
* Prochaine séance par rotation : une séance jamais faite d'abord (dans l'ordre
* du programme), sinon celle faite le moins récemment.
* @param {import("../domain/state.js").State} state
* Prochaine séance par rotation, quand aucun planning n'est réglé : une séance
* jamais faite d'abord (dans l'ordre du programme), sinon la moins récente.
* @param {State} state
* @returns {import("../domain/program.js").ProgramSession|null}
*/
export function nextByRotation(state) {
@@ -35,19 +47,207 @@ export function nextByRotation(state) {
}
/**
* Durée estimée d'une séance, en minutes, arrondie à 5 : dix minutes
* d'échauffement, puis pour chaque bloc le travail des séries et les repos
* (40 s par série quand l'objectif est en répétitions). Reprise d'Atelier.
* @param {import("../domain/program.js").ProgramSession} session
* Nom et détail d'un créneau, pour l'affichage.
* @param {Slot} slot
* @param {Program|null} program
* @returns {{title: string, detail: string, color: string|undefined, key: string|null}}
*/
export function estimateMinutes(session) {
let total = 10 * 60;
for (const block of groupBlocks(session.exercises)) {
const items = block.items.map(resolveExercise);
const rounds = Math.max(...items.map((x) => x.sets));
const work = items.reduce((n, x) => n + (targetSeconds(x.reps) ?? 40), 0);
const rest = items.reduce((n, x) => n + x.rest, 0);
total += rounds * work + (rounds - 1) * rest + 45 * items.length;
export function slotLabel(slot, program) {
if (slot.kind === "strength") {
const s = program?.sessions.find((x) => x.key === slot.sessionKey);
return { title: `Séance ${slot.sessionKey}`, detail: s?.name ?? "", color: s?.color, key: slot.sessionKey ?? null };
}
return Math.round(total / 60 / 5) * 5;
if (slot.kind === "activity") {
const a = program?.activities?.find((x) => x.id === slot.activityId);
return {
title: a?.name ?? "Activité",
detail: a ? `${a.zones.map((z) => ZONE_LABELS[z]).join(", ")} · ${a.minutes} min` : "",
color: a?.color, key: null,
};
}
const c = program?.cardio?.[slot.cardioIndex ?? -1];
return { title: "Cardio", detail: c?.name ?? "", color: undefined, key: null };
}
/**
* Le contenu d'un SessionLogged pour un cardio ou une activité marqué fait.
* @param {Slot} slot
* @param {Program|null} program
* @param {string} date
* @returns {import("../domain/events.js").SessionData}
*/
export function loggedForSlot(slot, program, date) {
const { kind, ref } = slotRef(slot, program);
const name = slot.kind === "activity" ? slotLabel(slot, program).title : ref;
return { date, kind, ref, name, warmup: null, exercises: [] };
}
/**
* @typedef {object} TodayModel
* @property {boolean} planned un planning est réglé pour cette semaine
* @property {Slot|null} slot le créneau du jour
* @property {"none"|"rest"|"todo"|"done"|"skipped"} status
* @property {Slot|null} next le prochain créneau de la semaine, après aujourd'hui
* @property {Slot[]} late créneaux passés, ni faits ni marqués non faits
* @property {{state: "done"|"skip"|"todo"}[]} cells un par créneau de la semaine
* @property {number} done
* @property {number} skipped
* @property {number} extra séances faites hors planning cette semaine
* @property {import("../domain/state.js").LoggedSession[]} doneToday
*/
/**
* La carte du jour.
* @param {State} state
* @param {string} today
* @returns {TodayModel}
*/
export function todayModel(state, today) {
const monday = mondayOf(today);
const plan = weekPlan(state, monday);
const planned = settingsForWeek(state, monday) !== null && plan.slots.length > 0;
const { bySlot, extra } = weekStatus(state, plan);
const skipped = new Set(state.skippedDays);
const slot = planned ? plan.slots.find((s) => s.date === today) ?? null : null;
const doneToday = state.sessions.filter((s) => s.date === today);
/** @type {TodayModel["status"]} */
let status = "none";
if (planned) {
if (!slot) status = "rest";
else if (bySlot.get(slot)?.done) status = "done";
else if (skipped.has(today)) status = "skipped";
else status = "todo";
}
const cells = plan.slots.map((s) => ({
state: /** @type {"done"|"skip"|"todo"} */ (bySlot.get(s)?.done ? "done" : skipped.has(s.date) ? "skip" : "todo"),
}));
return {
planned,
slot,
status,
next: plan.slots.find((s) => s.date > today) ?? null,
late: planned ? lateSlots(state, today) : [],
cells,
done: cells.filter((c) => c.state === "done").length,
skipped: cells.filter((c) => c.state === "skip").length,
extra: extra.length,
doneToday,
};
}
/**
* @typedef {object} WeekRow
* @property {number} day
* @property {string} date
* @property {Slot|null} slot
* @property {boolean} available jour disponible ou imposé
* @property {string|null} lock
* @property {{done: boolean, date: string|null, shifted: boolean}|null} status
* @property {boolean} skipped
* @property {boolean} isToday
* @property {("done"|"skip"|"unskip"|"remove")[]} actions
*/
/**
* Les sept lignes de l'écran Semaine. Les actions « Faite », « Non fait »,
* « Annuler » et « Retirer » ne valent que pour les jours passés ou le jour
* même de la semaine en cours.
* @param {State} state
* @param {string} monday
* @param {string} today
* @returns {{plan: import("../domain/planning.js").WeekPlan, rows: WeekRow[], extra: import("../domain/state.js").LoggedSession[]}}
*/
export function weekRows(state, monday, today) {
const current = mondayOf(today);
const plan = weekPlan(state, monday, { today });
const { bySlot, extra } = weekStatus(state, plan);
const skippedDays = new Set(state.skippedDays);
const rows = Array.from({ length: 7 }, (_, day) => {
const date = addDays(monday, day);
const slot = plan.slots.find((s) => s.day === day) ?? null;
const status = slot ? bySlot.get(slot) ?? null : null;
const done = !!status?.done;
const skipped = !done && skippedDays.has(date);
/** @type {WeekRow["actions"]} */
const actions = [];
if (slot && monday === current && date <= today) {
if (done) actions.push("remove");
else if (skipped) actions.push("unskip");
else actions.push("done", "skip");
}
return {
day, date, slot, status, skipped, actions,
available: plan.days.includes(day) || plan.locks[day] !== undefined,
lock: plan.locks[day] ?? null,
isToday: date === today,
};
});
return { plan, rows, extra };
}
/**
* Séance enregistrée qui a rempli un créneau (pour « Retirer »).
* @param {State} state
* @param {Slot} slot
* @param {{date: string|null}} status
*/
export function sessionForSlot(state, slot, status) {
const { kind, ref } = slotRef(slot, state.program);
return state.sessions.find((s) => s.kind === kind && s.ref === ref && s.date === status.date) ?? null;
}
/**
* Ce qu'on peut imposer à un jour.
* @param {Program|null} program
* @returns {{value: string, label: string}[]}
*/
export function lockOptions(program) {
return [
{ value: "", label: "Automatique" },
{ value: "strength", label: "Une séance de force" },
...(program?.sessions ?? []).map((s) => ({ value: `strength:${s.key}`, label: `Séance ${s.key} · ${s.name}` })),
...(program?.cardio ?? []).map((c, i) => ({ value: `cardio:${i}`, label: `Cardio · ${c.name}` })),
...(program?.activities ?? []).map((a) => ({ value: `activity:${a.id}`, label: a.name })),
{ value: "rest", label: "Repos" },
];
}
/**
* Nouveaux jours disponibles : les jours imposés des jours retirés tombent.
* @param {{days: number[], locks: Record<string, string>}|null} settings
* @param {number[]} days
*/
export function withDays(settings, days) {
/** @type {Record<string, string>} */
const locks = {};
for (const [d, lock] of Object.entries(settings?.locks ?? {})) if (days.includes(Number(d))) locks[d] = lock;
return { days: [...new Set(days)].sort((a, b) => a - b), locks };
}
/**
* Impose (ou libère, valeur vide) un jour ; un jour imposé devient disponible.
* @param {{days: number[], locks: Record<string, string>}|null} settings
* @param {number} day
* @param {string} value
*/
export function withLock(settings, day, value) {
const locks = { ...(settings?.locks ?? {}) };
if (value) locks[day] = value;
else delete locks[day];
const days = [...new Set([...(settings?.days ?? []), ...(value ? [day] : [])])].sort((a, b) => a - b);
return { days, locks };
}
/**
* Retire d'un réglage les jours imposés qui désignent une activité supprimée.
* @param {{days: number[], locks: Record<string, string>}} settings
* @param {string} activityId
* @returns {{days: number[], locks: Record<string, string>}|null} null si rien ne change
*/
export function withoutActivity(settings, activityId) {
const locks = Object.fromEntries(Object.entries(settings.locks).filter(([, l]) => l !== `activity:${activityId}`));
return Object.keys(locks).length === Object.keys(settings.locks).length ? null : { days: [...settings.days], locks };
}
/** Jour de la semaine d'une date. @param {string} date */
export const dayName = (date) => DAY_NAMES[dayIndex(date)];
+7 -5
View File
@@ -10,11 +10,13 @@ export const TRACKING_LABELS = {
/**
* Ressenti d'une série. Glossaire : docs/glossaire/ressenti.md
* @type {Record<import("../domain/vocabulary.js").Effort, {label: string, hint: string}>}
* `short` s'affiche sous les répétitions d'une série faite : le ressenti se lit
* en toutes lettres, jamais par la seule couleur.
* @type {Record<import("../domain/vocabulary.js").Effort, {label: string, hint: string, short: string}>}
*/
export const EFFORT_LABELS = {
easy: { label: "Facile", hint: "3 répétitions ou plus en réserve" },
ok: { label: "Correct", hint: "1 ou 2 répétitions en réserve" },
hard: { label: "Dur", hint: "Rien en réserve" },
failure: { label: "Échec", hint: "Série non terminée" },
easy: { label: "Facile", hint: "3 répétitions ou plus en réserve", short: "facile" },
ok: { label: "Correct", hint: "1 ou 2 répétitions en réserve", short: "ok" },
hard: { label: "Dur", hint: "Rien en réserve", short: "dur" },
failure: { label: "Échec", hint: "Série non terminée", short: "échec" },
};
+2 -2
View File
@@ -16,12 +16,12 @@ export function screenHeader({ kicker, title, sub, back }) {
}
/**
* Titre de section.
* Titre de section : un ruban adhésif.
* @param {string} text
* @param {string} [hint]
*/
export function sectionLabel(text, hint) {
return h("h2", { class: "section-label" }, text, hint && h("span", { class: "section-label__hint" }, hint));
return h("h2", { class: "tape" }, text, hint && h("span", { class: "tape__hint" }, hint));
}
/**
+32 -57
View File
@@ -1,11 +1,14 @@
// Premier lancement : pas de programme, pas de proposition en attente.
// But : un programme dans l'app en moins de deux minutes, construit avec l'IA
// de l'utilisateur (ADR 0005, point 7 : le circuit par lien).
// de l'utilisateur (ADR 0008 ; ADR 0005, point 7 : le circuit par lien).
import { h } from "./dom.js";
import { actionBar } from "./layout.js";
import { toast } from "./feedback.js";
import { exampleProgram, onboardingBrief } from "./pending.js";
import { copyText } from "./files.js";
import { href } from "./router.js";
import { buildOnboardingBrief } from "../domain/ai-brief.js";
import { EXAMPLE_PROGRAM } from "../domain/example-program.js";
/** Consigne courte pour une IA qui sait lire une page web. */
export const AI_GUIDE_URL = "https://ia-fit.sans.pub/ia.md";
@@ -14,47 +17,21 @@ export const AI_GUIDE_URL = "https://ia-fit.sans.pub/ia.md";
* @param {{store: import("./store.js").Store}} o
*/
export function onboarding({ store }) {
const status = h("p", { class: "status status--info", role: "status", "aria-live": "polite" });
const status = h("p", { class: "status status--ok", role: "status", "aria-live": "polite" });
const manual = h("div", { class: "manual-copy", hidden: true });
const copyBrief = async () => {
const text = await onboardingBrief(location.origin);
if (!text) {
// À brancher : ai-brief.buildOnboardingBrief({baseUrl}) (autre sous-agent).
status.textContent = "Le texte à donner à ton IA arrive bientôt. En attendant, dis-lui de lire " + AI_GUIDE_URL + ".";
return;
}
try {
await navigator.clipboard.writeText(text);
status.textContent = "Copié. Colle-le maintenant dans ton IA.";
toast("Texte copié.");
} catch {
// Presse-papiers refusé (http, navigateur ancien) : copie à la main.
const area = h("textarea", { class: "field__input field__input--area", readonly: true, "aria-label": "Texte à copier dans ton IA" });
area.value = text;
manual.replaceChildren(h("p", { class: "muted" }, "Copie ce texte à la main :"), area);
manual.hidden = false;
area.select();
status.textContent = "";
}
const ok = await copyText(buildOnboardingBrief({ baseUrl: location.origin }), manual, "Texte à copier dans ton IA");
status.textContent = ok ? "Copié. Colle-le dans ton IA." : "";
if (ok) toast("Texte copié.");
};
const startFromExample = async () => {
const program = await exampleProgram();
if (!program) {
// À brancher : example-program.EXAMPLE_PROGRAM (autre sous-agent).
toast("Le programme d'exemple arrive bientôt.");
return;
}
try {
store.dispatch("ProgramProposed", {
program,
source: /** @type {any} */ ("example"),
reason: "Programme d'exemple : trois séances à domicile avec barre, haltères, banc et élastiques. Ton IA pourra l'adapter ensuite.",
});
} catch (e) {
toast("Le programme d'exemple n'a pas pu être proposé : " + (e instanceof Error ? e.message : String(e)));
}
const startFromExample = () => {
store.dispatch("ProgramProposed", {
program: structuredClone(EXAMPLE_PROGRAM),
source: "example",
reason: "Programme d'exemple : trois séances à domicile avec barre, haltères, banc et élastiques. Ton IA pourra l'adapter ensuite.",
});
};
const copyGuide = async () => {
@@ -67,32 +44,30 @@ export function onboarding({ store }) {
};
return h("div", { class: "onboarding" },
h("header", { class: "screen-head hero" },
h("p", { class: "kicker" }, "IA-Fit"),
h("h1", { class: "title title--hero" }, "Ton programme, construit avec ton IA"),
h("p", { class: "lede" }, "Puis suivi séance par séance : séries, charges, repos. Tes données restent sur ton appareil, sans compte.")),
h("header", { class: "screen-head" },
h("p", { class: "kicker" }, "IA-Fit · sans compte"),
h("h1", { class: "title title--hero" }, "Ton programme. Ton IA."),
h("p", { class: "lede" }, "Elle le construit, tu le suis ici, série par série. Tes données restent sur ton appareil.")),
h("section", { class: "card card--onboarding", "aria-labelledby": "onb-how" },
h("h2", { class: "card__title", id: "onb-how" }, "En trois gestes"),
h("section", { class: "block", "aria-labelledby": "onb-how" },
h("h2", { class: "h2", id: "onb-how" }, "Trois gestes"),
h("ol", { class: "how" },
h("li", { class: "how__step" }, h("strong", null, "Copie le texte"), h("span", null, " et colle-le dans ton IA : Claude, ChatGPT, Le Chat…")),
h("li", { class: "how__step" }, h("strong", null, "Réponds à ses questions"), h("span", null, ", ou montre-lui ton programme actuel : export d'une autre app, texte, captures d'écran.")),
h("li", { class: "how__step" }, h("strong", null, "Touche le lien qu'elle te renvoie"), h("span", null, " : ton programme s'affiche ici, et tu le valides."))),
h("li", { class: "how__step" }, h("span", null, h("strong", null, "Copie le texte"), " et colle-le dans ton IA : Claude, ChatGPT, Le Chat…")),
h("li", { class: "how__step" }, h("span", null, h("strong", null, "Réponds à ses questions"), ", ou montre-lui ton programme actuel.")),
h("li", { class: "how__step" }, h("span", null, h("strong", null, "Touche le lien qu'elle renvoie."), " Ton programme s'affiche ici. Tu valides."))),
status,
manual,
h("p", { class: "card__hint" }, "Ou, si ton IA sait lire une page web, dis-lui simplement :"),
h("p", { class: "muted" }, "Ton IA lit les pages web ? Dis-lui :"),
h("div", { class: "copy-line" },
h("code", { class: "copy-line__text" }, `lis ${AI_GUIDE_URL}`),
h("button", { type: "button", class: "btn btn--sm btn--ghost", on: { click: copyGuide } }, "Copier")),
h("p", { class: "card__hint" }, "Connecteur MCP pour ton IA : bientôt.")),
h("button", { type: "button", class: "btn btn--sm", on: { click: copyGuide } }, "Copier"))),
h("section", { class: "alt", "aria-label": "Autres façons de commencer" },
h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Partir d'un programme d'exemple"),
// À brancher : import d'un instantané (snapshot.js, autre sous-agent).
h("button", { type: "button", class: "btn btn--block btn--ghost", disabled: true, "aria-describedby": "onb-restore" }, "Restaurer une sauvegarde"),
h("p", { class: "muted", id: "onb-restore" }, "Restaurer une sauvegarde : bientôt.")),
h("h2", { class: "tape" }, "Ou bien"),
h("div", { class: "btn-stack" },
h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Programme d'exemple"),
h("a", { class: "btn btn--block btn--ghost", href: href.data() }, "Restaurer une sauvegarde")),
h("footer", { class: "foot" }, "Rien ne part sur un serveur : ce que tu colles dans ton IA, c'est toi qui le choisis."),
h("p", { class: "foot" }, "Rien ne part sur un serveur. Ce que tu colles dans ton IA, c'est toi qui le choisis."),
actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme avec mon IA")));
actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme")));
}
-13
View File
@@ -1,13 +0,0 @@
// Modules du domaine utilisés par l'accueil.
import { buildOnboardingBrief } from "../domain/ai-brief.js";
import { EXAMPLE_PROGRAM } from "../domain/example-program.js";
/** Le prompt d'onboarding à coller dans son IA. @param {string} baseUrl */
export async function onboardingBrief(baseUrl) {
return buildOnboardingBrief({ baseUrl });
}
/** Le programme d'exemple (celui d'Atelier). */
export async function exampleProgram() {
return structuredClone(EXAMPLE_PROGRAM);
}
+204
View File
@@ -0,0 +1,204 @@
// Aperçu d'une proposition : ce qui change par rapport au programme courant
// (ADR 0005, point 6). Module pur, testé (tests/ui/program-diff.test.js).
//
// Les séances se rapprochent par leur clé (« A »), les exercices d'une séance
// par leur identifiant stable (la ref, sinon le nom ; un exercice présent deux
// fois se rapproche dans l'ordre), les activités par leur id, le cardio et les
// repères par leur nom.
import { resolveExercise } from "../domain/program.js";
/** @typedef {import("../domain/program.js").Program} Program */
/** @typedef {import("../domain/program.js").ProgramSession} ProgramSession */
/** @typedef {import("../domain/program.js").ProgramExercise} ProgramExercise */
/** @typedef {import("../domain/profile.js").Profile} Profile */
/** @typedef {"added"|"removed"|"changed"|"same"} Change */
/**
* Une valeur qui change.
* @typedef {object} FieldChange
* @property {string} field
* @property {string} label
* @property {unknown} from
* @property {unknown} to
*/
/**
* @typedef {object} ExerciseDiff
* @property {Change} change
* @property {string} id
* @property {string} name
* @property {ProgramExercise} item l'exercice proposé (ou retiré)
* @property {FieldChange[]} fields
*/
/**
* @typedef {object} SessionDiff
* @property {Change} change
* @property {string} key
* @property {string} name
* @property {string|undefined} color
* @property {FieldChange[]} fields
* @property {ExerciseDiff[]} exercises
*/
/**
* @typedef {object} ItemDiff
* @property {Change} change
* @property {string} name
* @property {FieldChange[]} fields
*/
/**
* @typedef {object} ProgramDiff
* @property {boolean} isNew pas de programme courant
* @property {FieldChange|null} name
* @property {SessionDiff[]} sessions dans l'ordre proposé, puis les séances retirées
* @property {ItemDiff[]} activities
* @property {ItemDiff[]} cardio
* @property {ItemDiff[]} rules
* @property {{added: number, removed: number, changed: number}} counts séances et exercices
* @property {boolean} identical
*/
/** Champs comparés d'un exercice. */
const EXERCISE_FIELDS = /** @type {const} */ ([
["sets", "séries"], ["reps", "répétitions"], ["rest", "repos"], ["group", "superset"],
["tracking", "suivi"], ["note", "note du coach"], ["name", "nom"],
]);
/** @param {unknown} a @param {unknown} b */
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
/**
* @param {Record<string, any>} from
* @param {Record<string, any>} to
* @param {readonly (readonly [string, string])[]} fields
* @returns {FieldChange[]}
*/
function compareFields(from, to, fields) {
return fields
.filter(([f]) => !same(from[f], to[f]))
.map(([field, label]) => ({ field, label, from: from[field] ?? null, to: to[field] ?? null }));
}
/**
* Rapproche deux listes par une clé ; à clé égale, dans l'ordre.
* @template T
* @param {T[]} before
* @param {T[]} after
* @param {(x: T) => string} keyOf
* @returns {{before: T|null, after: T|null}[]} dans l'ordre de `after`, puis les retirés
*/
function pair(before, after, keyOf) {
/** @type {Map<string, T[]>} */
const pool = new Map();
for (const x of before) pool.set(keyOf(x), [...(pool.get(keyOf(x)) ?? []), x]);
/** @type {{before: T|null, after: T|null}[]} */
const out = after.map((x) => {
const list = pool.get(keyOf(x));
return { before: list?.shift() ?? null, after: x };
});
for (const list of pool.values()) for (const x of list) out.push({ before: x, after: null });
return out;
}
/** @param {{before: unknown, after: unknown}} p @param {boolean} changed @returns {Change} */
const changeOf = (p, changed) => (!p.before ? "added" : !p.after ? "removed" : changed ? "changed" : "same");
/**
* @param {ProgramSession|null} before
* @param {ProgramSession|null} after
* @returns {SessionDiff}
*/
function diffSession(before, after) {
const s = /** @type {ProgramSession} */ (after ?? before);
const exercises = pair(before?.exercises ?? [], after?.exercises ?? [], (x) => resolveExercise(x).id).map((p) => {
const item = /** @type {ProgramExercise} */ (p.after ?? p.before);
const fields = p.before && p.after ? compareFields(p.before, p.after, EXERCISE_FIELDS) : [];
return { change: changeOf(p, fields.length > 0), id: resolveExercise(item).id, name: resolveExercise(item).name, item, fields };
});
const fields = before && after ? compareFields(before, after, [["name", "nom"], ["subtitle", "sous-titre"]]) : [];
const moved = before && after && !same(before.exercises.map((x) => resolveExercise(x).id), after.exercises.map((x) => resolveExercise(x).id));
if (moved && exercises.every((x) => x.change !== "added" && x.change !== "removed"))
fields.push({ field: "order", label: "ordre des exercices", from: null, to: null });
const changed = fields.length > 0 || exercises.some((x) => x.change !== "same");
return { change: changeOf({ before, after }, changed), key: s.key, name: s.name, color: s.color, fields, exercises };
}
/**
* @template T
* @param {T[]} before
* @param {T[]} after
* @param {(x: T) => string} keyOf
* @param {(x: T) => string} nameOf
* @param {readonly (readonly [string, string])[]} fields
* @returns {ItemDiff[]}
*/
function diffItems(before, after, keyOf, nameOf, fields) {
return pair(before, after, keyOf).map((p) => {
const f = p.before && p.after ? compareFields(/** @type {any} */ (p.before), /** @type {any} */ (p.after), fields) : [];
return { change: changeOf(p, f.length > 0), name: nameOf(/** @type {T} */ (p.after ?? p.before)), fields: f };
});
}
/**
* Différence entre le programme courant (ou rien) et un programme proposé.
* @param {Program|null} current
* @param {Program} proposed
* @returns {ProgramDiff}
*/
export function diffProgram(current, proposed) {
const sessions = pair(current?.sessions ?? [], proposed.sessions, (s) => s.key).map((p) => diffSession(p.before, p.after));
const activities = diffItems(current?.activities ?? [], proposed.activities ?? [], (a) => a.id, (a) => a.name,
[["name", "nom"], ["zones", "zones"], ["intensity", "intensité"], ["minutes", "durée"]]);
const cardio = diffItems(current?.cardio ?? [], proposed.cardio ?? [], (c) => c.name, (c) => c.name,
[["inPlan", "au planning"], ["text", "consigne"]]);
const rules = diffItems(current?.rules ?? [], proposed.rules ?? [], (r) => r.name, (r) => r.name, [["text", "texte"]]);
const counts = { added: 0, removed: 0, changed: 0 };
for (const s of sessions) {
if (s.change === "added" || s.change === "removed") counts[s.change]++;
else for (const x of s.exercises) if (x.change !== "same") counts[x.change]++;
if (s.change === "changed" && s.fields.length) counts.changed++;
}
const name = current && current.name !== proposed.name ? { field: "name", label: "nom", from: current.name, to: proposed.name } : null;
const identical = !!current && !name && [...sessions, ...activities, ...cardio, ...rules].every((x) => x.change === "same")
&& same(current.subtitle, proposed.subtitle);
return { isNew: !current, name, sessions, activities, cardio, rules, counts, identical };
}
/** Champs du profil, dans l'ordre d'affichage. */
export const PROFILE_FIELDS = /** @type {const} */ ([
["goal", "Objectif"], ["context", "Contexte"], ["equipment", "Matériel"], ["constraints", "Contraintes"],
["heightCm", "Taille (cm)"], ["sessionMinutes", "Durée d'une séance (min)"],
]);
/**
* @typedef {object} ProfileChange
* @property {string} field
* @property {string} label
* @property {unknown} from
* @property {unknown} to
* @property {string[]} [added] pour une liste
* @property {string[]} [removed]
*/
/**
* Ce qui change dans le profil.
* @param {Profile} current
* @param {Profile} proposed
* @returns {ProfileChange[]}
*/
export function diffProfile(current, proposed) {
/** @type {ProfileChange[]} */
const out = [];
for (const [field, label] of PROFILE_FIELDS) {
const from = current[field], to = proposed[field];
if (same(from, to)) continue;
if (Array.isArray(from) && Array.isArray(to))
out.push({ field, label, from, to, added: to.filter((x) => !from.includes(x)), removed: from.filter((x) => !to.includes(x)) });
else out.push({ field, label, from, to });
}
return out;
}
+178 -30
View File
@@ -1,55 +1,203 @@
// Une proposition de programme en attente : un aperçu simple, « Adopter » ou
// « Refuser ». Glossaire : docs/glossaire/proposition.md
//
// À brancher (sous-lot 1e) : l'écran de proposition avec l'aperçu détaillé des
// changements (exercices ajoutés, retirés, modifiés). Ce rendu provisoire montre
// le programme proposé tel quel.
// Une proposition de programme : raison, source, aperçu de ce qui change par
// rapport au programme courant, puis « Adopter » ou « Refuser ».
// Glossaire : docs/glossaire/proposition.md
import { h } from "./dom.js";
import { plural } from "./format.js";
import { resolveExercise } from "../domain/program.js";
import { append, h, setAccent } from "./dom.js";
import { inkOn, sessionColor } from "./color.js";
import { mediumDay, plural, restLabel } from "./format.js";
import { TRACKING_LABELS } from "./labels.js";
import { diffProfile, diffProgram } from "./program-diff.js";
import { toast } from "./feedback.js";
import { href } from "./router.js";
import { INTENSITY_LABELS, ZONE_LABELS } from "./home-model.js";
/** @type {Record<string, string>} */
const SOURCE_LABELS = {
export const SOURCE_LABELS = {
ai: "Proposé par ton IA",
link: "Reçu par un lien",
import: "Venu d'une sauvegarde",
import: "Venu d'un fichier importé",
atelier: "Repris d'Atelier",
example: "Programme d'exemple",
default: "Programme de départ",
app: "Modifié dans l'app",
};
/**
* @param {{proposal: import("../domain/state.js").Proposal, store: import("./store.js").Store}} o
* Ce qu'est devenue une proposition, d'après le journal : son id est stable
* (tiré de son contenu), rouvrir le même lien retrouve donc la même.
* @param {readonly import("../domain/events.js").DomainEvent[]} events
* @param {string} id
* @returns {{event: Extract<import("../domain/events.js").DomainEvent, {type: "ProgramProposed"}>|null, outcome: "pending"|"adopted"|"rejected", at: string|null}}
*/
export function proposalCard({ proposal, store }) {
const p = proposal.program;
// Le profil proposé est facultatif (onboarding par l'IA) : adopté avec le programme.
const profile = /** @type {any} */ (proposal).profile;
export function proposalOutcome(events, id) {
const event = /** @type {any} */ (events.find((e) => e.id === id && e.type === "ProgramProposed") ?? null);
for (const e of events) {
if (e.type === "ProgramAdopted" && e.data.proposalId === id) return { event, outcome: "adopted", at: e.at };
if (e.type === "ProposalRejected" && e.data.proposalId === id) return { event, outcome: "rejected", at: e.at };
}
return { event, outcome: "pending", at: null };
}
/**
* Une valeur lisible dans l'aperçu.
* @param {string} field
* @param {unknown} v
*/
function show(field, v) {
if (v === null || v === undefined || v === "") return "—";
if (field === "rest" && typeof v === "number") return restLabel(v);
if (field === "tracking") return TRACKING_LABELS[/** @type {keyof TRACKING_LABELS} */ (v)] ?? String(v);
if (field === "zones" && Array.isArray(v)) return v.map((z) => ZONE_LABELS[z] ?? z).join(", ");
if (field === "intensity") return INTENSITY_LABELS[String(v)] ?? String(v);
if (field === "minutes") return `${v} min`;
if (field === "inPlan") return v ? "oui" : "non";
if (Array.isArray(v)) return v.join(", ");
return String(v);
}
/** @param {import("./program-diff.js").FieldChange} f */
const fieldLine = (f) => f.field === "order"
? h("li", { data: { change: "changed" } }, "Ordre des exercices revu")
: h("li", { data: { change: "changed" } }, `${f.label} : `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to)));
/** @param {import("../domain/program.js").ProgramExercise} x */
const target = (x) => `${x.sets} × ${x.reps}, repos ${restLabel(x.rest)}`;
/** @type {Record<string, string>} */
const CHANGE_WORD = { added: "Nouvelle", removed: "Retirée", changed: "Modifiée", same: "Inchangée" };
/**
* L'aperçu des changements.
* @param {import("../domain/program.js").Program|null} current
* @param {import("../domain/program.js").Program} proposed
* @param {import("../domain/profile.js").Profile} currentProfile
* @param {import("../domain/profile.js").Profile|null} proposedProfile
*/
export function diffView(current, proposed, currentProfile, proposedProfile) {
const d = diffProgram(current, proposed);
const profile = proposedProfile ? diffProfile(currentProfile, proposedProfile) : [];
const summary = d.isNew
? `${plural(proposed.sessions.length, "séance")}, ${plural(proposed.sessions.reduce((n, s) => n + s.exercises.length, 0), "exercice")}.`
: d.identical ? "Identique à ton programme actuel."
: [d.counts.added && `${d.counts.added} ajout${d.counts.added > 1 ? "s" : ""}`,
d.counts.removed && `${d.counts.removed} retrait${d.counts.removed > 1 ? "s" : ""}`,
d.counts.changed && `${d.counts.changed} modification${d.counts.changed > 1 ? "s" : ""}`].filter(Boolean).join(" · ") || "Petits changements.";
const sessions = d.sessions.map((s) => {
const plaque = h("span", { class: "plaque plaque--sm", "aria-hidden": "true" }, s.key);
const color = sessionColor(s.color);
setAccent(plaque, color, inkOn(color));
const lines = s.change === "same" ? [] : [
...s.fields.map(fieldLine),
...s.exercises.filter((x) => d.isNew || s.change !== "changed" || x.change !== "same").map((x) => {
if (d.isNew || s.change === "added") return h("li", { data: { change: "added" } }, `${x.name} · ${target(x.item)}`);
if (x.change === "added") return h("li", { data: { change: "added" } }, `${x.name} · ${target(x.item)}`);
if (x.change === "removed") return h("li", { data: { change: "removed" } }, x.name);
return h("li", { data: { change: "changed" } }, x.name, " · ",
x.fields.map((f, i) => [i ? ", " : "", `${f.label} `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to))]));
}),
];
return h("li", { class: "diff__item" },
h("div", { class: "diff__head" }, plaque,
h("span", { class: "diff__what" }, `Séance ${s.key} · ${s.name}`),
!d.isNew && h("span", { class: "mark" }, CHANGE_WORD[s.change])),
lines.length > 0 && h("ul", { class: "diff__lines" }, lines));
});
/** @param {string} title @param {import("./program-diff.js").ItemDiff[]} items */
const others = (title, items) => {
const changed = items.filter((x) => d.isNew || x.change !== "same");
if (!changed.length) return null;
return h("li", { class: "diff__item" },
h("div", { class: "diff__head" }, h("span", { class: "diff__what" }, title)),
h("ul", { class: "diff__lines" }, changed.map((x) => x.change === "changed"
? h("li", { data: { change: "changed" } }, x.name, " · ", x.fields.map((f, i) => [i ? ", " : "", `${f.label} `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to))]))
: h("li", { data: { change: d.isNew ? "added" : x.change } }, x.name))));
};
return h("div", { class: "proposal-diff" },
h("p", { class: "mark" }, d.isNew ? "Nouveau programme · " : "Par rapport à ton programme · ", summary),
h("ul", { class: "diff" },
d.name && h("li", { class: "diff__item" }, h("ul", { class: "diff__lines" }, fieldLine(d.name))),
sessions,
others("Activités", d.activities),
others("Cardio", d.cardio),
others("Repères", d.rules),
profile.length > 0 && h("li", { class: "diff__item" },
h("div", { class: "diff__head" }, h("span", { class: "diff__what" }, "Ton profil")),
h("ul", { class: "diff__lines" }, profile.map((p) => p.added
? [...p.added.map((x) => h("li", { data: { change: "added" } }, `${p.label} : ${x}`)),
...(p.removed ?? []).map((x) => h("li", { data: { change: "removed" } }, `${p.label} : ${x}`))]
: h("li", { data: { change: "changed" } }, `${p.label} : `, h("del", null, show(p.field, p.from)), " → ", h("ins", null, show(p.field, p.to))))))));
}
/**
* Une proposition en attente, avec ses deux actions.
* @param {{proposal: import("../domain/state.js").Proposal, store: import("./store.js").Store, nav?: import("./router.js").Navigation, headingLevel?: "h1"|"h2"}} o
*/
export function proposalCard({ proposal, store, nav, headingLevel = "h2" }) {
const state = store.getState();
const p = proposal.program;
const adopt = () => {
store.dispatch("ProgramAdopted", { program: p, source: proposal.source, proposalId: proposal.id, ...(proposal.reason ? { reason: proposal.reason } : {}) });
if (profile) store.dispatch("ProfileUpdated", { profile });
if (proposal.profile) store.dispatch("ProfileUpdated", { profile: proposal.profile });
toast(`Programme « ${p.name} » adopté.`);
nav?.go(href.home(), { replace: true });
};
const reject = () => {
store.dispatch("ProposalRejected", { proposalId: proposal.id });
toast("Proposition refusée.");
nav?.go(href.home(), { replace: true });
};
return h("section", { class: "card card--proposal", "aria-labelledby": `prop-${proposal.id}` },
h("p", { class: "kicker" }, "À valider · ", SOURCE_LABELS[proposal.source] ?? proposal.source),
h("h2", { class: "card__title", id: `prop-${proposal.id}` }, p.name),
p.subtitle && h("p", { class: "card__text" }, p.subtitle),
const id = `prop-${proposal.id}`;
return h("section", { class: "block block--today proposal", "aria-labelledby": id },
h("p", { class: "kicker" }, "À valider · ", SOURCE_LABELS[proposal.source] ?? proposal.source, " · ", mediumDay(proposal.at.slice(0, 10))),
h(headingLevel, { class: headingLevel === "h1" ? "title" : "block__title", id }, p.name),
p.subtitle && h("p", null, p.subtitle),
proposal.reason && h("p", { class: "coach-note" }, proposal.reason),
h("ul", { class: "preview" }, p.sessions.map((s) =>
h("li", { class: "preview__session" },
h("strong", null, `Séance ${s.key} · ${s.name}`),
h("span", { class: "muted" }, `${plural(s.exercises.length, "exercice")} : ${s.exercises.map((x) => resolveExercise(x).name).join(", ")}`)))),
profile && h("p", { class: "muted" }, "Ton profil (objectif, matériel, contraintes) sera aussi mis à jour."),
h("div", { class: "card__actions" },
h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: adopt } }, "Adopter ce programme"),
diffView(state.program, p, state.profile, proposal.profile),
h("div", { class: "btn-stack" },
h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: adopt } }, "Adopter"),
h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: reject } }, "Refuser")));
}
/**
* L'écran d'une proposition, retrouvée par son id (lien rouvert, accueil).
* @param {{store: import("./store.js").Store, nav: import("./router.js").Navigation, id: string}} ctx
* @returns {import("./router.js").Screen}
*/
export function proposalScreen({ store, nav, id }) {
const node = h("div", { class: "screen" });
const back = h("button", { type: "button", class: "back", on: { click: () => nav.back(href.home()) } }, "← Accueil");
const pending = store.getState().proposals.find((x) => x.id === id);
if (pending) {
node.append(h("header", { class: "screen-head" }, back, h("p", { class: "kicker" }, "Proposition"), h("h1", { class: "title" }, "À valider")),
proposalCard({ proposal: pending, store, nav }));
return { node, title: "Proposition" };
}
const { event, outcome, at } = proposalOutcome(store.getEvents(), id);
if (!event) {
node.append(h("header", { class: "screen-head" }, back, h("h1", { class: "title" }, "Proposition introuvable")),
h("p", { class: "empty" }, "Elle n'est pas dans ton journal."));
return { node, title: "Proposition introuvable" };
}
const state = store.getState();
const reopen = () => {
const fresh = store.dispatch("ProgramProposed", { ...event.data });
nav.go(href.proposal(fresh.id), { replace: true });
};
append(node, [
h("header", { class: "screen-head" }, back,
h("p", { class: "kicker" }, SOURCE_LABELS[event.data.source] ?? event.data.source),
h("h1", { class: "title" }, outcome === "adopted" ? "Déjà adoptée" : "Déjà refusée")),
h("p", { class: "coach-note coach-note--plain" },
outcome === "adopted"
? `Tu as adopté cette proposition le ${mediumDay(/** @type {string} */ (at).slice(0, 10))}. Ce lien ne change plus rien.`
: `Tu as refusé cette proposition le ${mediumDay(/** @type {string} */ (at).slice(0, 10))}. Le lien est le même : c'est la même proposition.`),
h("section", { class: "block" },
h("h2", { class: "block__title" }, event.data.program.name),
event.data.reason && h("p", { class: "coach-note" }, event.data.reason),
diffView(state.program, event.data.program, state.profile, event.data.profile ?? null)),
outcome === "rejected" && h("div", { class: "action-bar" }, h("div", { class: "action-bar__in" },
h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: reopen } }, "La réexaminer")))]);
return { node, title: "Proposition" };
}
+38 -7
View File
@@ -3,13 +3,22 @@
//
// Les fragments #import= (lien d'une IA, ADR 0005 point 7) et #pair=
// (appariement, lot 2) sont réservés : le routeur ne les interprète pas et ne
// les réécrit pas. À brancher : link.js (#import=), appariement (#pair=).
// les réécrit pas : main.js lit #import= (link.js) ; #pair= attend le lot 2.
/**
* @typedef {{name: "home"}
* | {name: "session", key: string}
* | {name: "session", key: string, date: string|null}
* | {name: "finish"}
* | {name: "progress"}
* | {name: "history"}
* | {name: "history-edit", id: string}
* | {name: "week"}
* | {name: "activities"}
* | {name: "weight"}
* | {name: "data"}
* | {name: "profile"}
* | {name: "analysis", exercise: string|null}
* | {name: "proposal", id: string}
* | {name: "reserved"}
* | {name: "not-found"}} Route
*/
@@ -29,18 +38,40 @@ export function parseRoute(hash) {
const parts = path.split("/").map((p) => {
try { return decodeURIComponent(p); } catch { return p; }
});
if (parts[0] === "seance" && parts.length === 2 && parts[1]) return { name: "session", key: parts[1] };
if (parts[0] === "historique" && parts.length === 1) return { name: "history" };
if (parts[0] === "historique" && parts.length === 2 && parts[1]) return { name: "history-edit", id: parts[1] };
const [head, arg, extra] = parts;
if (head === "seance" && arg && parts.length === 2) return { name: "session", key: arg, date: null };
if (head === "seance" && arg && parts.length === 3 && /^\d{4}-\d{2}-\d{2}$/.test(extra)) return { name: "session", key: arg, date: extra };
if (head === "historique" && parts.length === 2 && arg) return { name: "history-edit", id: arg };
if (head === "analyses" && parts.length === 1) return { name: "analysis", exercise: null };
if (head === "analyses" && parts.length === 2 && arg) return { name: "analysis", exercise: arg };
if (head === "proposition" && parts.length === 2 && arg) return { name: "proposal", id: arg };
if (parts.length === 1 && SIMPLE[head]) return /** @type {Route} */ ({ name: SIMPLE[head] });
return { name: "not-found" };
}
/** Écrans sans paramètre : adresse → nom. @type {Record<string, string>} */
const SIMPLE = {
bravo: "finish", progression: "progress", historique: "history", semaine: "week", activites: "activities",
poids: "weight", donnees: "data", profil: "profile",
};
const enc = encodeURIComponent;
/** Adresses, pour écrire les liens sans les recopier. */
export const href = {
home: () => "#/",
session: (/** @type {string} */ key) => "#/seance/" + encodeURIComponent(key),
session: (/** @type {string} */ key, /** @type {string|null} */ date = null) => "#/seance/" + enc(key) + (date ? "/" + date : ""),
finish: () => "#/bravo",
progress: () => "#/progression",
history: () => "#/historique",
historyEdit: (/** @type {string} */ id) => "#/historique/" + encodeURIComponent(id),
historyEdit: (/** @type {string} */ id) => "#/historique/" + enc(id),
week: () => "#/semaine",
activities: () => "#/activites",
weight: () => "#/poids",
data: () => "#/donnees",
profile: () => "#/profil",
analysis: (/** @type {string|null} */ exercise = null) => "#/analyses" + (exercise ? "/" + enc(exercise) : ""),
proposal: (/** @type {string} */ id) => "#/proposition/" + enc(id),
};
/**
+188
View File
@@ -0,0 +1,188 @@
// Activités : sports en dehors du programme (foot, escalade…), avec leurs zones
// sollicitées, leur intensité et leur durée. Elles font partie du programme :
// les modifier adopte une nouvelle version du programme (ProgramAdopted, source
// « app »), qui garde tout le reste à l'identique.
import { h, paintWhenIdle, replace } from "../dom.js";
import { ZONES, INTENSITIES } from "../../domain/vocabulary.js";
import { mondayOf } from "../../domain/dates.js";
import { INTENSITY_LABELS, ZONE_LABELS, withoutActivity } from "../home-model.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { confirmDialog, toast } from "../feedback.js";
/** @typedef {import("../../domain/program.js").Activity} Activity */
/** @typedef {import("../../domain/program.js").Program} Program */
/**
* Identifiant d'une activité tiré de son nom : minuscules, chiffres et tirets.
* @param {string} name
* @param {string[]} taken
*/
export function activityId(name, taken) {
const base = name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 28) || "activite";
let id = base, n = 2;
while (taken.includes(id)) id = `${base}-${n++}`;
return id;
}
/**
* Le programme avec une activité ajoutée, remplacée ou retirée. Les autres
* champs du programme sont gardés tels quels.
* @param {Program} program
* @param {{id: string, activity: Activity|null}} change activity null : retrait
* @returns {Program}
*/
export function withActivity(program, { id, activity }) {
const list = program.activities ?? [];
const next = activity
? (list.some((a) => a.id === id) ? list.map((a) => (a.id === id ? activity : a)) : [...list, activity])
: list.filter((a) => a.id !== id);
return { ...structuredClone(program), activities: structuredClone(next) };
}
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
export function activitiesScreen({ store, nav, today }) {
const list = h("div");
const back = { label: "Accueil", onClick: () => nav.back(href.home()) };
if (!store.getState().program) {
return {
title: "Activités",
node: h("div", { class: "screen" }, screenHeader({ back, title: "Activités" }),
h("p", { class: "empty" }, "Adopte d'abord un programme : les activités en font partie.")),
};
}
// ---- formulaire (jamais reconstruit pendant la saisie) ----------------------
/** @type {string|null} */
let editing = null;
const zones = new Set(["cardio"]);
let intensity = "moderate";
const formTitle = h("h2", { class: "tape" }, "Ajouter");
const name = h("input", { id: "act-name", class: "field__input", type: "text", autocomplete: "off", maxlength: "40" });
const minutes = h("input", { id: "act-min", class: "field__input", type: "text", inputmode: "numeric", value: "90" });
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const zoneBtns = ZONES.map((z) => h("button", { type: "button", class: "segmented__opt", "aria-pressed": "false", data: { zone: z } }, ZONE_LABELS[z]));
const intBtns = INTENSITIES.map((i) => h("button", { type: "button", class: "segmented__opt", "aria-pressed": "false", data: { intensity: i } }, INTENSITY_LABELS[i]));
const paintChoices = () => {
zoneBtns.forEach((b) => b.setAttribute("aria-pressed", String(zones.has(/** @type {string} */ (b.dataset.zone)))));
intBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.intensity === intensity)));
};
zoneBtns.forEach((b) => b.addEventListener("click", () => {
const z = /** @type {string} */ (b.dataset.zone);
if (zones.has(z)) zones.delete(z); else zones.add(z);
paintChoices();
}));
intBtns.forEach((b) => b.addEventListener("click", () => { intensity = /** @type {string} */ (b.dataset.intensity); paintChoices(); }));
const cancel = h("button", { type: "button", class: "btn btn--ghost btn--block", hidden: true }, "Annuler la modification");
const reset = () => {
editing = null;
zones.clear();
zones.add("cardio");
intensity = "moderate";
name.value = "";
minutes.value = "90";
formTitle.textContent = "Ajouter";
cancel.hidden = true;
paintChoices();
};
cancel.addEventListener("click", reset);
/** @param {Activity} a */
const load = (a) => {
editing = a.id;
zones.clear();
a.zones.forEach((z) => zones.add(z));
intensity = a.intensity;
name.value = a.name;
minutes.value = String(a.minutes);
formTitle.textContent = `Modifier · ${a.name}`;
cancel.hidden = false;
paintChoices();
name.focus();
};
const submit = () => {
const program = /** @type {Program} */ (store.getState().program);
const label = name.value.trim();
const min = Math.round(Number(minutes.value.replace(",", ".")));
status.className = "status status--err";
if (!label) { status.textContent = "Donne un nom à l'activité."; return; }
if (!zones.size) { status.textContent = "Choisis au moins une zone."; return; }
if (!(min >= 5 && min <= 600)) { status.textContent = "Durée : de 5 à 600 minutes."; return; }
const ids = (program.activities ?? []).map((a) => a.id);
const old = editing ? program.activities?.find((a) => a.id === editing) : null;
const id = editing ?? activityId(label, ids);
/** @type {Activity} */
const activity = { ...(old ?? {}), id, name: label, zones: /** @type {any} */ ([...zones]), intensity: /** @type {any} */ (intensity), minutes: min };
try {
store.dispatch("ProgramAdopted", { program: withActivity(program, { id, activity }), source: "app", reason: `${editing ? "Activité modifiée" : "Activité ajoutée"} : ${label}` });
} catch (e) {
status.textContent = e instanceof Error ? e.message : String(e);
return;
}
status.className = "status status--ok";
status.textContent = editing ? `« ${label} » mise à jour.` : `« ${label} » ajoutée. Place-la dans ta semaine.`;
reset();
};
/** @param {Activity} a */
const remove = async (a) => {
const ok = await confirmDialog({
title: `Supprimer « ${a.name} » ?`, lines: ["Les jours qui lui étaient réservés redeviennent automatiques. L'historique reste."],
confirm: "Supprimer", cancel: "Garder", danger: true,
});
if (!ok) return;
const state = store.getState();
store.dispatch("ProgramAdopted", { program: withActivity(/** @type {Program} */ (state.program), { id: a.id, activity: null }), source: "app", reason: `Activité retirée : ${a.name}` });
// Les jours imposés qui la désignaient tombent : réglage par défaut et semaines à venir.
const monday = mondayOf(today());
if (state.planSettings) {
const next = withoutActivity(state.planSettings, a.id);
if (next) store.dispatch("PlanSettingsChanged", { week: null, ...next });
}
for (const [week, settings] of Object.entries(state.weekPlanSettings)) {
if (week < monday) continue;
const next = withoutActivity(settings, a.id);
if (next) store.dispatch("PlanSettingsChanged", { week, ...next });
}
if (editing === a.id) reset();
toast(`« ${a.name} » supprimée.`);
};
const paint = () => {
const activities = store.getState().program?.activities ?? [];
replace(list, activities.length
? h("ul", { class: "rows" }, activities.map((a) => h("li", { class: "row" },
h("span", { class: "row__main" },
h("span", { class: "row__title" }, a.name),
h("span", { class: "row__meta" }, `${a.zones.map((z) => ZONE_LABELS[z]).join(", ")} · ${INTENSITY_LABELS[a.intensity].toLowerCase()} · ${a.minutes} min`)),
h("span", { class: "row__actions" },
h("button", { type: "button", class: "btn btn--sm", "aria-label": `Modifier ${a.name}`, on: { click: () => load(a) } }, "Modifier"),
h("button", { type: "button", class: "btn btn--sm btn--ghost", "aria-label": `Supprimer ${a.name}`, on: { click: () => void remove(a) } }, "✕")))))
: h("p", { class: "empty" }, "Aucune activité. Ajoute-la ci-dessous, puis place-la dans ta semaine."));
};
paint();
paintChoices();
const node = h("div", { class: "screen" },
screenHeader({ back, kicker: "Hors programme", title: "Activités", sub: "Foot, escalade, vélo… Le planning en tient compte : une activité cardio remplace une sortie, une activité intense éloigne la séance qui travaille les mêmes zones." }),
list,
formTitle,
h("div", { class: "field" }, h("label", { class: "field__label", for: "act-name" }, "Nom"), name),
h("p", { class: "field__label", id: "act-zones" }, "Zones sollicitées"),
h("div", { class: "segmented", role: "group", "aria-labelledby": "act-zones" }, zoneBtns),
h("p", { class: "field__label act-gap", id: "act-int" }, "Intensité"),
h("div", { class: "segmented", role: "group", "aria-labelledby": "act-int" }, intBtns),
h("div", { class: "field act-gap" }, h("label", { class: "field__label", for: "act-min" }, "Durée (minutes)"), minutes),
status,
h("div", { class: "btn-stack" },
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: submit } }, "Enregistrer l'activité"),
cancel));
return { node, title: "Activités", destroy: store.subscribe(paintWhenIdle(list, paint)) };
}
+114
View File
@@ -0,0 +1,114 @@
// Analyses simples (ADR 0006, point 6) : assiduité des douze dernières
// semaines, et pour chaque exercice la courbe de la charge et des répétitions.
// Calculs du domaine : analysis.js.
import { h } from "../dom.js";
import { addDays, daysBetween, mondayOf } from "../../domain/dates.js";
import { attendance, exerciseHistory } from "../../domain/analysis.js";
import { dec1, kg, mediumDay, plural, shortDay } from "../format.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { barChart, lineChart } from "../chart.js";
import { EFFORT_LABELS } from "../labels.js";
/** Semaines affichées dans l'assiduité. */
export const ATTENDANCE_WEEKS = 12;
/**
* Les exercices faits au moins une fois, du plus récent au plus ancien.
* @param {import("../../domain/state.js").State} state
* @returns {{id: string, name: string, count: number, last: string}[]}
*/
export function exercisesDone(state) {
/** @type {Map<string, {id: string, name: string, count: number, last: string}>} */
const map = new Map();
for (const s of state.sessions) {
if (s.kind !== "strength") continue;
for (const x of s.exercises) {
if (!x.sets.length) continue;
const cur = map.get(x.id) ?? { id: x.id, name: x.name, count: 0, last: s.date };
cur.count++;
if (s.date >= cur.last) { cur.last = s.date; cur.name = x.name; }
map.set(x.id, cur);
}
}
return [...map.values()].sort((a, b) => (a.last < b.last ? 1 : a.last > b.last ? -1 : a.name.localeCompare(b.name)));
}
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string, exercise: string|null}} ctx
* @returns {import("../router.js").Screen}
*/
export function analysisScreen({ store, nav, today, exercise }) {
return exercise ? exerciseScreen({ store, nav, exercise }) : overview({ store, nav, today });
}
/** @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx */
function overview({ store, nav, today }) {
const state = store.getState();
const to = today();
const from = addDays(mondayOf(to), -7 * (ATTENDANCE_WEEKS - 1));
const { weeks, totals } = attendance(state, from, to);
const list = exercisesDone(state);
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Ton parcours", title: "Analyses" }),
h("h2", { class: "tape" }, "Assiduité", h("span", { class: "tape__hint" }, `${ATTENDANCE_WEEKS} semaines`)),
h("div", { class: "stats" },
h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.strength)), h("span", { class: "stat__label" }, "force")),
h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.cardio)), h("span", { class: "stat__label" }, "cardio")),
h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.activity)), h("span", { class: "stat__label" }, "activités")),
h("div", { class: "stat" }, h("span", { class: "stat__value" }, dec1(totals.total / ATTENDANCE_WEEKS)), h("span", { class: "stat__label" }, "par semaine"))),
h("figure", { class: "chart analysis-gap" },
barChart({
values: weeks.map((w) => w.total),
label: `Séances par semaine : ${weeks.map((w) => `semaine du ${shortDay(w.monday)}, ${w.total}`).join(" ; ")}`,
labels: [shortDay(weeks[0].monday), "cette semaine"],
}),
h("figcaption", { class: "chart__caption" }, "Séances par semaine, toutes natures. En couleur : la semaine en cours.")),
h("h2", { class: "tape" }, "Par exercice"),
list.length
? h("ul", { class: "rows" }, list.map((x) => h("li", null, h("a", { class: "row", href: href.analysis(x.id) },
h("span", { class: "row__main" }, h("span", { class: "row__title" }, x.name), h("span", { class: "row__meta" }, `${x.count} fois · dernière le ${shortDay(x.last)}`)),
h("span", { class: "chevron", "aria-hidden": "true" })))))
: h("p", { class: "empty" }, "Aucun exercice fait pour l'instant."));
return { node, title: "Analyses" };
}
/** @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, exercise: string}} ctx */
function exerciseScreen({ store, nav, exercise }) {
const state = store.getState();
const points = exerciseHistory(state, exercise);
const name = exercisesDone(state).find((x) => x.id === exercise)?.name ?? exercise;
const back = { label: "Analyses", onClick: () => nav.back(href.analysis()) };
const withLoad = points.filter((p) => p.loadKg !== null && p.loadKg > 0);
const withReps = points.filter((p) => p.bestReps !== null);
const origin = points[0]?.date;
/** @param {typeof points} pts @param {(p: typeof points[number]) => number} y @param {string} what @param {(v: number) => string} format */
const chart = (pts, y, what, format) => pts.length > 1
? h("figure", { class: "chart" }, lineChart({
points: pts.map((p) => ({ x: daysBetween(/** @type {string} */ (origin), p.date), y: y(p) })),
label: `${what}, du ${mediumDay(pts[0].date)} au ${mediumDay(pts[pts.length - 1].date)}`,
format, xLabels: [shortDay(pts[0].date), shortDay(pts[pts.length - 1].date)], minSpan: 2,
}))
: h("p", { class: "muted" }, "Deux séances suffisent pour une courbe.");
const best = withLoad.length ? Math.max(...withLoad.map((p) => /** @type {number} */ (p.loadKg))) : null;
const node = h("div", { class: "screen" },
screenHeader({ back, kicker: plural(points.length, "séance"), title: name }),
h("div", { class: "stats" },
h("div", { class: "stat" }, h("span", { class: "stat__value" }, best !== null ? kg(best) : "—", best !== null && h("small", null, "kg")), h("span", { class: "stat__label" }, "meilleure charge")),
h("div", { class: "stat" }, h("span", { class: "stat__value" }, withReps.length ? String(Math.max(...withReps.map((p) => /** @type {number} */ (p.bestReps)))) : "—"), h("span", { class: "stat__label" }, "meilleure série"))),
withLoad.length > 0 && [h("h2", { class: "tape" }, "Charge"), chart(withLoad, (p) => /** @type {number} */ (p.loadKg), "Charge en kg", (v) => dec1(v))],
h("h2", { class: "tape" }, "Répétitions", h("span", { class: "tape__hint" }, "meilleure série")),
chart(withReps, (p) => /** @type {number} */ (p.bestReps), "Répétitions de la meilleure série", (v) => String(Math.round(v))),
h("h2", { class: "tape" }, "Séance par séance"),
h("ul", { class: "rows" }, [...points].reverse().map((p) => h("li", { class: "row" },
h("span", { class: "row__main" },
h("span", { class: "row__title" }, mediumDay(p.date)),
h("span", { class: "row__meta" }, [
`séance ${p.sessionRef}`, plural(p.sets, "série"),
p.bestReps !== null ? `meilleure ${p.bestReps}` : null,
p.effort ? EFFORT_LABELS[p.effort].label.toLowerCase() : null,
].filter(Boolean).join(" · "))),
h("span", { class: "row__side num analysis__kg" }, p.loadKg ? `${kg(p.loadKg)} kg` : p.seconds ? `${p.seconds} s` : "")))));
return { node, title: name };
}
+141
View File
@@ -0,0 +1,141 @@
// Données : sauvegarde (instantané), import (instantané, fichier d'Atelier,
// programme seul), texte pour l'IA, réinitialisation.
// Règle d'Atelier : rien n'est écrit avant le choix explicite de l'utilisateur.
import { h, replace } from "../dom.js";
import { createSnapshot, readImport } from "../../domain/snapshot.js";
import { buildEvolutionBrief } from "../../domain/ai-brief.js";
import { plural } from "../format.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { confirmDialog, toast } from "../feedback.js";
import { copyText, download, readFile } from "../files.js";
import { clearDraft } from "../draft-storage.js";
/** @typedef {import("../../domain/events.js").DomainEvent} DomainEvent */
/**
* Écritures du journal en bloc (IndexedDB puis magasin), fournies par main.js.
* @typedef {object} Journal
* @property {(events: DomainEvent[]) => Promise<number>} merge union : renvoie le nombre d'événements nouveaux
* @property {(events: DomainEvent[]) => Promise<void>} replace remplace tout le journal
*/
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, journal: Journal, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
export function dataScreen({ store, nav, journal, today }) {
// ---- sauvegarde -----------------------------------------------------------------
const exportSnapshot = () => {
const snapshot = createSnapshot(store.getEvents(), { now: new Date() });
download(`ia-fit-${today()}.json`, JSON.stringify(snapshot, null, 1), "application/json");
toast("Sauvegarde téléchargée.");
};
// ---- texte pour l'IA --------------------------------------------------------------
const briefFallback = h("div", { class: "manual-copy", hidden: true });
const copyBrief = async () => {
const text = buildEvolutionBrief(store.getState(), { today: today(), baseUrl: location.origin });
if (await copyText(text, briefFallback, "Texte pour ton IA")) toast("Texte copié : colle-le dans ton IA.");
};
// ---- import -----------------------------------------------------------------------
const file = h("input", { id: "imp-file", class: "visually-hidden", type: "file", accept: ".json,application/json,text/plain" });
const pasted = h("textarea", { id: "imp-text", class: "field__input field__input--area field__input--mono", placeholder: "{ \"format\": \"ia-fit-snapshot\", … }" });
const report = h("div", { class: "import-report", role: "status", "aria-live": "polite" });
/** @param {string} text */
const read = (text) => {
let result;
try {
result = readImport(text, { device: store.device, now: new Date() });
} catch (e) {
replace(report, h("p", { class: "status status--err" }, e instanceof Error ? e.message : String(e)));
return;
}
const known = new Set(store.getEvents().map((e) => e.id));
const fresh = result.events.filter((e) => !known.has(e.id)).length;
const kind = { snapshot: "Sauvegarde IA-Fit", atelier: "Données d'Atelier, converties", program: "Programme seul" }[result.kind];
const merge = async () => {
const added = await journal.merge(result.events);
replace(report, h("p", { class: "status status--ok" }, added ? `${plural(added, "événement")} ajouté${added > 1 ? "s" : ""}.` : "Rien de nouveau : tout était déjà là."));
pasted.value = "";
if (result.kind === "program") nav.go(href.home());
};
const replaceAll = async () => {
const ok = await confirmDialog({
title: "Remplacer tout ?",
lines: [`Ton journal actuel (${plural(store.getEvents().length, "événement")}) sera effacé et remplacé par celui du fichier.`, "Exporte d'abord une sauvegarde si tu as un doute."],
confirm: "Remplacer", cancel: "Annuler", danger: true,
});
if (!ok) return;
await journal.replace(result.events);
clearDraft();
replace(report, h("p", { class: "status status--ok" }, "Journal remplacé."));
pasted.value = "";
};
replace(report,
h("div", { class: "block" },
h("p", { class: "mark" }, kind),
h("ul", { class: "diff__lines" }, result.report.map((line) => h("li", null, line))),
h("p", { class: "muted" }, fresh === result.events.length
? `${plural(fresh, "événement")} à ajouter.`
: `${plural(fresh, "événement")} nouveau${fresh > 1 ? "x" : ""} sur ${result.events.length} : le reste est déjà dans ton journal.`),
h("div", { class: "btn-stack" },
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => void merge() } },
result.kind === "program" ? "Ajouter la proposition" : "Fusionner avec mes données"),
result.kind !== "program" && h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => void replaceAll() } }, "Remplacer mes données"),
h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => replace(report) } }, "Ne rien importer"))));
};
file.addEventListener("change", async () => {
const f = file.files?.[0];
if (f) read(await readFile(f));
file.value = "";
});
// ---- réinitialisation ---------------------------------------------------------------
const reset = async () => {
const n = store.getEvents().length;
const first = await confirmDialog({
title: "Tout effacer ?",
lines: [`Les ${plural(n, "événement")} de cet appareil seront effacés : programme, séances, pesées, réglages.`, "Exporte d'abord une sauvegarde."],
confirm: "Continuer", cancel: "Annuler", danger: true,
});
if (!first) return;
const second = await confirmDialog({
title: "Vraiment ?", lines: ["Impossible de revenir en arrière sans sauvegarde."],
confirm: "Tout effacer", cancel: "Non, garder", danger: true,
});
if (!second) return;
await journal.replace([]);
clearDraft();
toast("Données effacées.");
nav.go(href.home(), { replace: true });
};
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Sans compte", title: "Données", sub: "Tout vit sur cet appareil. Une sauvegarde te protège d'une perte." }),
h("p", { class: "mark" }, `${plural(store.getEvents().length, "événement")} au journal`),
h("h2", { class: "tape" }, "Ton IA"),
h("p", { class: "muted" }, "Ton historique, ton profil et ton programme, à coller dans ton IA. Elle répond par un lien : ta proposition s'ouvre ici."),
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => void copyBrief() } }, "Copier le texte pour mon IA"),
briefFallback,
h("h2", { class: "tape" }, "Sauvegarde"),
h("button", { type: "button", class: "btn btn--block", on: { click: exportSnapshot } }, "Exporter une sauvegarde"),
h("p", { class: "muted" }, "Un fichier .json : le journal complet et un résumé lisible."),
h("h2", { class: "tape", id: "import" }, "Restaurer · importer"),
h("p", { class: "muted" }, "Une sauvegarde IA-Fit, un fichier d'Atelier (converti) ou un programme seul (proposé à validation)."),
h("label", { class: "btn btn--block", for: "imp-file" }, "Choisir un fichier"),
file,
h("div", { class: "field data-gap" }, h("label", { class: "field__label", for: "imp-text" }, "Ou colle le texte"), pasted),
h("button", { type: "button", class: "btn btn--block", on: { click: () => read(pasted.value) } }, "Lire le texte"),
report,
h("h2", { class: "tape" }, "Zone dangereuse"),
h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void reset() } }, "Tout effacer"));
return { node, title: "Données" };
}
+6 -5
View File
@@ -20,11 +20,12 @@ export function historyScreen({ store, nav }) {
replace(list, h("p", { class: "empty" }, "Aucune séance enregistrée pour l'instant. Termine ta première séance : elle apparaîtra ici."));
return;
}
replace(list, h("ul", { class: "history__list" }, sessions.map((s) =>
h("li", null, h("a", { class: "history__item", href: href.historyEdit(s.id) },
h("span", { class: "history__date" }, mediumDay(s.date)),
h("span", { class: "history__name" }, s.name),
h("span", { class: "history__meta" }, sessionSummary(s) || kindLabel(s.kind)),
replace(list, h("ul", { class: "rows history__list" }, sessions.map((s) =>
h("li", null, h("a", { class: "row history__item", href: href.historyEdit(s.id) },
h("span", { class: "row__main" },
h("span", { class: "history__date" }, mediumDay(s.date)),
h("span", { class: "row__title history__name" }, s.name),
h("span", { class: "row__meta history__meta" }, sessionSummary(s) || kindLabel(s.kind))),
h("span", { class: "chevron", "aria-hidden": "true" }))))));
};
paint();
+197 -67
View File
@@ -1,112 +1,242 @@
// Accueil. Par priorité : une proposition en attente, sinon l'onboarding s'il
// n'y a pas encore de programme, sinon la carte du jour, les séances, le
// cardio et les repères.
// n'y a pas encore de programme, sinon le HUD (niveau, série), la carte du
// jour tirée du planning, les séances, le cardio, les repères et la grille des
// autres écrans.
import { h, setAccent } from "../dom.js";
import { h, paintWhenIdle, setAccent } from "../dom.js";
import { inkOn, sessionColor } from "../color.js";
import { longDay, localDay, shortDay, plural } from "../format.js";
import { estimateMinutes, lastDoneByKey, nextByRotation } from "../home-model.js";
import { actionBar, note, screenHeader, sectionLabel } from "../layout.js";
import { longDay, plural, shortDay } from "../format.js";
import { dayName, lastDoneByKey, loggedForSlot, nextByRotation, slotLabel, todayModel } from "../home-model.js";
import { actionBar, note } from "../layout.js";
import { href } from "../router.js";
import { onboarding } from "../onboarding.js";
import { proposalCard } from "../proposal-card.js";
import { estimatedMinutes } from "../../domain/progression.js";
import { hud } from "../game.js";
import { toast } from "../feedback.js";
/** @typedef {import("../../domain/state.js").State} State */
/** @typedef {import("../../domain/planning.js").Slot} Slot */
/** @typedef {import("../store.js").Store} Store */
/**
* Un programme a-t-il été adopté ? Il n'y a pas de programme par défaut
* (décision du porteur du projet, 2026-11-18) : tant qu'aucun ProgramAdopted
* n'est au journal, l'accueil montre l'onboarding.
* @param {import("../../domain/state.js").State} state
* (ADR 0008) : tant qu'aucun ProgramAdopted n'est au journal, l'accueil montre
* l'onboarding.
* @param {State} state
*/
export const hasProgram = (state) => !!state.program && state.programVersions.length > 0;
/**
* @param {{store: import("../store.js").Store}} ctx
* @param {{store: Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
export function homeScreen({ store }) {
export function homeScreen({ store, nav, today }) {
const node = h("div", { class: "screen screen--home" });
// L'accueil n'a aucun champ de saisie : le reconstruire à chaque changement est sans risque.
const paint = () => node.replaceChildren(homeContent(store));
const paint = () => node.replaceChildren(homeContent(store, nav, today()));
paint();
return { node, title: "", destroy: store.subscribe(paint) };
return { node, title: "", destroy: store.subscribe(paintWhenIdle(node, paint)) };
}
/**
* @param {import("../store.js").Store} store
* Plaque d'une séance : sa lettre sur sa couleur.
* @param {string} key
* @param {string|undefined} color
* @param {string} [cls]
*/
export function plaque(key, color, cls = "plaque") {
const el = h("span", { class: cls, "aria-hidden": "true" }, key);
const c = sessionColor(color);
setAccent(el, c, inkOn(c));
return el;
}
/**
* @param {Store} store
* @param {import("../router.js").Navigation} nav
* @param {string} today
* @returns {Node}
*/
function homeContent(store) {
function homeContent(store, nav, today) {
const state = store.getState();
// Une proposition en attente passe avant tout le reste.
if (state.proposals.length) {
const [first, ...others] = state.proposals;
return h("div", null,
h("header", { class: "screen-head" }, h("p", { class: "kicker" }, "IA-Fit"), h("h1", { class: "title" }, "Un programme t'attend")),
state.proposals.map((proposal) => proposalCard({ proposal, store })));
proposalCard({ proposal: first, store }),
others.length > 0 && h("p", { class: "muted" }, `Et ${plural(others.length, "autre proposition")} ensuite.`));
}
if (!hasProgram(state)) return onboarding({ store });
const program = /** @type {import("../../domain/program.js").Program} */ (state.program);
const model = todayModel(state, today);
const last = lastDoneByKey(state);
const today = localDay();
/** @type {Node|null} */
let primary = null;
// À brancher : planning.weekPlan(state, monday) donnera le créneau du jour
// (séance, cardio, activité, repos), les créneaux en retard et l'avancement de
// la semaine. En attendant : rotation simple, annoncée comme telle.
const next = nextByRotation(state);
/** @param {Slot} slot @param {string} date */
const markDone = (slot, date) => {
const data = loggedForSlot(slot, program, date);
if (state.skippedDays.includes(date)) store.dispatch("DayUnskipped", { date });
store.dispatch("SessionLogged", data);
toast(`${data.name} : fait.`);
};
const todayCard = next
? sessionLink(next, "card card--today", [
h("p", { class: "kicker" }, "Aujourd'hui · ", longDay(today)),
h("p", { class: "card__eyebrow" }, h("span", { class: "swatch", "aria-hidden": "true" }), `Séance ${next.key}`),
h("h2", { class: "card__title" }, next.name),
h("p", { class: "card__meta" },
`${plural(next.exercises.length, "exercice")} · environ ${estimateMinutes(next)} min`,
last[next.key] ? ` · faite le ${shortDay(last[next.key])}` : " · jamais faite"),
next.subtitle && h("p", { class: "card__text" }, next.subtitle),
h("p", { class: "card__hint" },
"Proposée par rotation : la séance faite le moins récemment. Le planning de la semaine arrive bientôt."),
])
: h("div", { class: "card card--today" }, h("p", { class: "card__text" }, "Le programme ne contient aucune séance."));
// ---- carte du jour -----------------------------------------------------------
const kicker = h("p", { class: "kicker" }, "Aujourd'hui · ", longDay(today));
/** @type {import("../dom.js").Child[]} */
let body = [];
if (!model.planned) {
const next = nextByRotation(state);
if (next) {
body = [
h("div", { class: "block__head" }, plaque(next.key, next.color),
h("div", null, h("h2", { class: "block__title" }, next.name),
h("p", { class: "block__meta" }, `${plural(next.exercises.length, "exercice")} · ${estimatedMinutes(next)} min · ${last[next.key] ? "faite le " + shortDay(last[next.key]) : "jamais faite"}`))),
h("p", { class: "muted" }, "Pas de planning : la séance faite le moins récemment. "),
h("a", { class: "btn btn--block", href: href.week() }, "Planifier ma semaine"),
];
primary = h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(next.key) }, `Commencer · séance ${next.key}`);
}
} else if (model.status === "rest") {
body = [h("h2", { class: "block__title" }, "Repos"), h("p", { class: "block__meta" }, nextText(model.next, program))];
} else if (model.status === "done") {
body = [h("h2", { class: "block__title" }, "C'est fait."), h("p", { class: "block__meta" }, nextText(model.next, program))];
} else if (model.status === "skipped") {
body = [
h("h2", { class: "block__title" }, "Passée"),
h("p", { class: "block__meta" }, `Marquée non faite. ${nextText(model.next, program)}`),
h("button", { type: "button", class: "btn btn--block", on: { click: () => store.dispatch("DayUnskipped", { date: today }) } }, "Annuler, je la fais"),
];
} else if (model.slot) {
const slot = model.slot;
const label = slotLabel(slot, program);
const session = slot.kind === "strength" ? program.sessions.find((s) => s.key === slot.sessionKey) : null;
body = [
h("div", { class: "block__head" },
session ? plaque(session.key, session.color) : h("span", { class: "plaque plaque--empty", "aria-hidden": "true" }, slot.kind === "cardio" ? "C" : "A"),
h("div", null,
h("h2", { class: "block__title" }, session ? session.name : label.title),
h("p", { class: "block__meta" }, session
? `Séance ${session.key} · ${plural(session.exercises.length, "exercice")} · ${estimatedMinutes(session)} min`
: label.detail))),
session?.subtitle && h("p", null, session.subtitle),
slot.kind === "cardio" && program.cardio?.[slot.cardioIndex ?? -1]?.text && h("p", { class: "muted" }, program.cardio[slot.cardioIndex ?? -1].text),
h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => store.dispatch("DaySkipped", { date: today }) } }, "Pas aujourd'hui"),
];
primary = session
? h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(session.key) }, "Commencer")
: h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: () => markDone(slot, today) } }, "Marquer comme fait");
}
const late = model.late.length > 0 && h("div", { class: "block__sep" },
h("p", { class: "mark" }, "En retard cette semaine"),
h("ul", { class: "rows" }, model.late.map((slot) => {
const label = slotLabel(slot, program);
return h("li", { class: "row" },
h("span", { class: "row__main" },
h("span", { class: "row__title" }, label.title + (label.detail ? ` · ${label.detail}` : "")),
h("span", { class: "row__meta" }, `Prévue ${dayName(slot.date)}`)),
slot.kind === "strength"
? h("a", { class: "btn btn--sm", href: href.session(/** @type {string} */ (slot.sessionKey)) }, "Faire")
: h("button", { type: "button", class: "btn btn--sm", on: { click: () => markDone(slot, slot.date) } }, "Marquer faite"));
})));
const progress = model.planned && h("div", { class: "block__sep" },
h("p", { class: "mark" }, `Semaine · ${model.done}/${model.cells.length} fait`,
model.skipped ? ` · ${model.skipped} manqué${model.skipped > 1 ? "s" : ""}` : "",
model.extra ? ` · ${model.extra} en plus` : ""),
h("span", { class: "cells", "aria-hidden": "true" }, model.cells.map((c) => h("i", { data: { state: c.state } }))));
const doneToday = model.doneToday.length > 0 && h("p", { class: "muted" },
"Déjà fait aujourd'hui : ", model.doneToday.map((s) => s.name).join(", "), ".");
const todayBlock = h("section", { class: "block block--today", "aria-label": "Aujourd'hui" },
kicker, ...body, otherActivity(store, today), doneToday, late, progress);
return h("div", null,
screenHeader({ kicker: "IA-Fit", title: program.name, sub: program.subtitle }),
todayCard,
hud(state, today),
h("header", { class: "visually-hidden" }, h("h1", null, program.name)),
todayBlock,
sectionLabel("Séances"),
h("ul", { class: "plates" }, program.sessions.map((s) =>
h("li", null, sessionLink(s, "plate", [
h("span", { class: "plate__bar", "aria-hidden": "true" }),
h("span", { class: "plate__body" },
h("span", { class: "plate__id" }, `Séance ${s.key}${s.tag ? " · " + s.tag : ""}`),
h("span", { class: "plate__name" }, s.name),
h("span", { class: "plate__meta" }, `${plural(s.exercises.length, "exercice")} · environ ${estimateMinutes(s)} min`)),
h("span", { class: "plate__last" }, last[s.key] ? `Faite le ${shortDay(last[s.key])}` : "Jamais faite"),
])))),
h("h2", { class: "tape" }, "Séances"),
h("ul", { class: "rows" }, program.sessions.map((s) =>
h("li", null, h("a", { class: "row", href: href.session(s.key) },
plaque(s.key, s.color),
h("span", { class: "row__main" },
h("span", { class: "row__title" }, s.name),
h("span", { class: "row__meta" }, `${plural(s.exercises.length, "exercice")} · ${estimatedMinutes(s)} min · ${last[s.key] ? "faite le " + shortDay(last[s.key]) : "jamais faite"}`)),
h("span", { class: "chevron", "aria-hidden": "true" }))))),
program.cardio?.length ? [sectionLabel("Cardio"), program.cardio.map((c) => note(c.name, c.text))] : null,
program.rules?.length ? [sectionLabel("Repères"), program.rules.map((r) => note(r.name, r.text))] : null,
program.cardio?.length ? [h("h2", { class: "tape" }, "Cardio"), program.cardio.map((c) => note(c.name, c.text))] : null,
program.rules?.length ? [h("h2", { class: "tape" }, "Repères"), program.rules.map((r) => note(r.name, r.text))] : null,
sectionLabel("Aller plus loin"),
h("nav", { class: "links", "aria-label": "Autres écrans" },
h("a", { class: "btn btn--block btn--ghost", href: href.history() }, "Historique des séances"),
// À brancher (sous-lot 1d) : semaine, activités, poids, données, profil.
h("p", { class: "muted" }, "Semaine, activités, poids et sauvegarde : bientôt.")),
h("h2", { class: "tape" }, "Tout le reste"),
h("nav", { class: "grid-nav", "aria-label": "Autres écrans" },
tile(href.week(), "Semaine", "jours, planning, agenda"),
tile(href.history(), "Historique", plural(state.sessions.length, "séance")),
tile(href.weight(), "Poids", state.weights.length ? `${String(state.weights[state.weights.length - 1].kg).replace(".", ",")} kg` : "première pesée"),
tile(href.analysis(), "Analyses", "charges, assiduité"),
tile(href.progress(), "Succès", "niveau, records"),
tile(href.activities(), "Activités", plural(program.activities?.length ?? 0, "activité")),
tile(href.profile(), "Profil", "objectif, mode"),
tile(href.data(), "Données", "sauvegarde, IA")),
h("footer", { class: "foot" }, "Tes données restent sur cet appareil."),
h("p", { class: "foot" }, `${program.name} · tes données restent sur cet appareil.`),
primary && actionBar(primary));
}
next && actionBar(h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(next.key) },
`Commencer la séance ${next.key}`)));
/** @param {string} link @param {string} name @param {string} meta */
function tile(link, name, meta) {
return h("a", { class: "tile", href: link }, h("span", { class: "tile__name" }, name), h("span", { class: "tile__meta" }, meta));
}
/**
* Lien vers une séance, coloré par sa couleur.
* @param {import("../../domain/program.js").ProgramSession} s
* @param {string} cls
* @param {import("../dom.js").Child[]} children
* @param {Slot|null} next
* @param {import("../../domain/program.js").Program} program
*/
function sessionLink(s, cls, children) {
const a = h("a", { class: cls, href: href.session(s.key) }, ...children);
const color = sessionColor(s.color);
setAccent(a, color, inkOn(color));
return a;
function nextText(next, program) {
if (!next) return "Plus rien de prévu cette semaine.";
const l = slotLabel(next, program);
return `Ensuite : ${dayName(next.date)}, ${l.title.toLowerCase()}${l.detail ? " · " + l.detail : ""}.`;
}
/**
* « Autre activité » : enregistrer n'importe quelle séance, cardio ou activité,
* à une date choisie avant.
* @param {Store} store
* @param {string} today
*/
function otherActivity(store, today) {
const program = /** @type {import("../../domain/program.js").Program} */ (store.getState().program);
const panel = h("div", { class: "other", hidden: true });
const toggle = h("button", { type: "button", class: "btn btn--ghost btn--block", "aria-expanded": "false" }, "Autre activité");
toggle.addEventListener("click", () => {
panel.hidden = !panel.hidden;
toggle.setAttribute("aria-expanded", String(!panel.hidden));
});
const date = h("input", { id: "other-date", class: "field__input", type: "date", max: today, value: today });
const day = () => (/^\d{4}-\d{2}-\d{2}$/.test(date.value) && date.value <= today ? date.value : today);
/** @param {"cardio"|"activity"} kind @param {string} ref @param {string} name */
const log = (kind, ref, name) => {
const d = day();
if (store.getState().sessions.some((s) => s.kind === kind && s.ref === ref && s.date === d)) {
toast(`${name} est déjà enregistré à cette date.`);
return;
}
if (store.getState().skippedDays.includes(d)) store.dispatch("DayUnskipped", { date: d });
store.dispatch("SessionLogged", { date: d, kind, ref, name, warmup: null, exercises: [] });
toast(`${name} : enregistré le ${shortDay(d)}.`);
};
const session = (/** @type {string} */ key) => {
location.hash = href.session(key, day() === today ? null : day());
};
panel.append(
h("div", { class: "field field--inline" }, h("label", { class: "field__label", for: "other-date" }, "Le"), date),
h("div", { class: "choice-list" },
program.sessions.map((s) => h("button", { type: "button", class: "choice", on: { click: () => session(s.key) } }, `Séance ${s.key} · ${s.name}`)),
(program.cardio ?? []).map((c) => h("button", { type: "button", class: "choice", on: { click: () => log("cardio", c.name, c.name) } }, `Cardio · ${c.name}`)),
(program.activities ?? []).map((a) => h("button", { type: "button", class: "choice", on: { click: () => log("activity", a.id, a.name) } }, a.name))));
return h("div", null, toggle, panel);
}
+121
View File
@@ -0,0 +1,121 @@
// Profil (ProfileUpdated) et mode (ModeChanged) : ce que l'IA doit savoir pour
// construire et faire évoluer le programme. Plus le thème, simple préférence
// d'affichage de l'appareil (pas un événement, ADR 0006 point 3).
import { h } from "../dom.js";
import { MODES } from "../../domain/vocabulary.js";
import { validateProfile } from "../../domain/profile.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { toast } from "../feedback.js";
import { getTheme, setTheme } from "../theme-pref.js";
/** @type {Record<string, {label: string, text: string}>} */
export const MODE_LABELS = {
progression: { label: "Progression", text: "Les charges montent dès que toutes les séries atteignent le haut de la fourchette, sans « dur » ni « échec »." },
maintenance: { label: "Maintien", text: "Garder le niveau : les charges restent stables." },
recovery: { label: "Récupération", text: "Reprise ou fatigue : rien ne monte, l'IA allège." },
};
/**
* Lit le formulaire. Les listes s'écrivent une ligne par élément.
* @param {{goal: string, context: string, equipment: string, constraints: string, heightCm: string, sessionMinutes: string}} form
* @returns {{profile: import("../../domain/profile.js").Profile, errors: string[]}}
*/
export function profileFromForm(form) {
const lines = (/** @type {string} */ t) => t.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
// Un nombre illisible devient NaN, que validateProfile refuse.
const height = form.heightCm.trim() === "" ? null : Math.round(Number(form.heightCm.replace(",", ".")));
const profile = {
goal: form.goal.trim(),
context: form.context.trim(),
equipment: lines(form.equipment),
constraints: lines(form.constraints),
heightCm: height,
sessionMinutes: Math.round(Number(form.sessionMinutes.replace(",", "."))),
};
/** @type {Record<string, string>} */
const plain = {
heightCm: "Taille : un nombre de centimètres entre 50 et 260, ou vide.",
sessionMinutes: "Durée d'une séance : de 10 à 240 minutes.",
};
const errors = validateProfile(profile).map((e) => Object.entries(plain).find(([k]) => e.includes(`'${k}'`))?.[1] ?? e);
return { profile, errors };
}
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx
* @returns {import("../router.js").Screen}
*/
export function profileScreen({ store, nav }) {
const p = store.getState().profile;
/** @param {string} id @param {string} label @param {HTMLElement} input @param {string} [hint] */
const field = (id, label, input, hint) => h("div", { class: "field" },
h("label", { class: "field__label", for: id }, label), input, hint && h("p", { class: "field__hint" }, hint));
const area = (/** @type {string} */ id, /** @type {string} */ value) => h("textarea", { id, class: "field__input field__input--area", value });
const goal = area("p-goal", p.goal);
const context = area("p-context", p.context);
const equipment = area("p-equipment", p.equipment.join("\n"));
const constraints = area("p-constraints", p.constraints.join("\n"));
const height = h("input", { id: "p-height", class: "field__input", type: "text", inputmode: "numeric", value: p.heightCm ?? "" });
const minutes = h("input", { id: "p-minutes", class: "field__input", type: "text", inputmode: "numeric", value: String(p.sessionMinutes) });
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const save = () => {
const { profile, errors } = profileFromForm({
goal: goal.value, context: context.value, equipment: equipment.value, constraints: constraints.value,
heightCm: height.value, sessionMinutes: minutes.value,
});
if (errors.length) {
status.className = "status status--err";
status.textContent = errors.join(" ");
return;
}
store.dispatch("ProfileUpdated", { profile });
status.className = "status status--ok";
status.textContent = "Profil enregistré.";
};
// Le mode change d'un geste : seul l'état des boutons est mis à jour.
const modeText = h("p", { class: "muted" });
const modeBtns = MODES.map((m) => h("button", { type: "button", class: "segmented__opt", data: { mode: m } }, MODE_LABELS[m].label));
const paintMode = () => {
const mode = store.getState().mode;
modeBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.mode === mode)));
modeText.textContent = MODE_LABELS[mode].text;
};
modeBtns.forEach((b) => b.addEventListener("click", () => {
const mode = /** @type {import("../../domain/vocabulary.js").Mode} */ (b.dataset.mode);
if (mode === store.getState().mode) return;
store.dispatch("ModeChanged", { mode });
paintMode();
toast(`Mode : ${MODE_LABELS[mode].label.toLowerCase()}.`);
}));
paintMode();
const themes = /** @type {const} */ ([["auto", "Système"], ["dark", "Sombre"], ["light", "Clair"]]);
const themeBtns = themes.map(([value, label]) => h("button", { type: "button", class: "segmented__opt", data: { theme: value } }, label));
const paintTheme = () => themeBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.theme === getTheme())));
themeBtns.forEach((b) => b.addEventListener("click", () => { setTheme(/** @type {any} */ (b.dataset.theme)); paintTheme(); }));
paintTheme();
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Pour ton IA", title: "Profil", sub: "Ton IA lit ce profil pour construire et ajuster ton programme." }),
h("h2", { class: "tape" }, "Mode"),
h("div", { class: "segmented", role: "group", "aria-label": "Mode du programme" }, modeBtns),
modeText,
h("h2", { class: "tape" }, "Toi"),
field("p-goal", "Objectif", goal, "En une phrase."),
field("p-context", "Contexte", context, "Pratique passée, lieu d'entraînement."),
field("p-equipment", "Matériel", equipment, "Un élément par ligne."),
field("p-constraints", "Contraintes", constraints, "Sécurité, blessures, organisation. Une par ligne."),
h("div", { class: "field-pair" },
field("p-height", "Taille (cm)", height),
field("p-minutes", "Séance (min)", minutes)),
status,
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: save } }, "Enregistrer le profil"),
h("h2", { class: "tape" }, "Affichage"),
h("div", { class: "segmented", role: "group", "aria-label": "Thème" }, themeBtns),
h("p", { class: "muted" }, "Sombre par défaut : un écran OLED noir consomme moins."));
return { node, title: "Profil" };
}
+20 -13
View File
@@ -5,20 +5,22 @@ import { h, setAccent } from "../dom.js";
import { groupBlocks, resolveExercise } from "../../domain/program.js";
import { inkOn, sessionColor } from "../color.js";
import { localDay, longDay, plural } from "../format.js";
import { estimateMinutes } from "../home-model.js";
import { estimatedMinutes } from "../../domain/progression.js";
import { actionBar, screenHeader } from "../layout.js";
import { href } from "../router.js";
import { buildSessionData, completion, createDraft, doneCount, draftMatches } from "../session-draft.js";
import { buildSessionData, completion, createDraft, doneCount, draftMatches, draftTotals, setsInOrder } from "../session-draft.js";
import { clearDraft, loadDraft, saveDraft } from "../draft-storage.js";
import { exerciseCard } from "../exercise-card.js";
import { WARMUP_STEPS, warmupCard } from "../warmup-card.js";
import { warmupCard, warmupSteps } from "../warmup-card.js";
import { confirmDialog, toast } from "../feedback.js";
import { comboLabel, recordFinish } from "../game.js";
/**
* @param {{store: import("../store.js").Store, key: string, nav: import("../router.js").Navigation, timer: import("../timer.js").Timer}} ctx
* @param {{store: import("../store.js").Store, key: string, date: string|null, nav: import("../router.js").Navigation, timer: import("../timer.js").Timer}} ctx
* date : séance saisie pour un autre jour (« Autre activité », un créneau passé)
* @returns {import("../router.js").Screen}
*/
export function sessionScreen({ store, key, nav, timer }) {
export function sessionScreen({ store, key, date, nav, timer }) {
const state = store.getState();
const session = state.program?.sessions.find((s) => s.key === key);
const back = { label: "Accueil", onClick: () => nav.back(href.home()) };
@@ -31,18 +33,21 @@ export function sessionScreen({ store, key, nav, timer }) {
}
const today = localDay();
const warmup = warmupSteps(state, session);
const stored = loadDraft();
const draft = draftMatches(stored, session, WARMUP_STEPS.length)
const draft = draftMatches(stored, session, warmup.steps.length)
? stored
: createDraft(session, state, today, WARMUP_STEPS.length);
: createDraft(session, state, date && date <= today ? date : today, warmup.steps.length);
const resumed = draft === stored;
if (resumed && date && date <= today) draft.date = date;
const progress = h("span", { class: "action-bar__meta", "aria-live": "polite" });
const status = h("p", { class: "status", role: "alert" });
const totalSets = draft.exercises.reduce((n, ex) => n + ex.sets, 0);
const paintProgress = () => {
const done = draft.exercises.reduce((n, ex) => n + doneCount(ex), 0);
progress.textContent = `${done}/${totalSets} séries`;
const combo = comboLabel(setsInOrder(draft));
progress.replaceChildren(h("span", null, `${done}/${totalSets} séries`), combo ? h("span", { class: "combo" }, combo) : "");
};
// Le brouillon n'est gardé qu'au premier changement : ouvrir une séance pour
// la regarder n'écrase pas celle qu'on a commencée.
@@ -76,7 +81,7 @@ export function sessionScreen({ store, key, nav, timer }) {
const cards = block.items.map((item, k) => {
const i = index++;
return exerciseCard({
ex: draft.exercises[i], item, sessionKey: session.key, number: String(i + 1),
draft, ex: draft.exercises[i], item, sessionKey: session.key, number: String(i + 1),
letter: block.items.length > 1 ? String.fromCharCode(65 + k) : null,
open: resumed && i === firstOpen, store, timer, onChange,
});
@@ -106,6 +111,7 @@ export function sessionScreen({ store, key, nav, timer }) {
const ok = await confirmDialog({ title: "La séance n'est pas finie", lines, confirm: "Enregistrer quand même", cancel: "Continuer la séance" });
if (!ok) return;
}
const before = store.getState();
try {
store.dispatch("SessionLogged", buildSessionData(draft));
} catch (e) {
@@ -114,14 +120,15 @@ export function sessionScreen({ store, key, nav, timer }) {
}
clearDraft();
timer.stop();
toast(draft.date === today ? "Séance enregistrée." : `Séance enregistrée au ${longDay(draft.date)}.`);
nav.go(href.home(), { replace: true });
if (draft.date !== today) toast(`Séance enregistrée au ${longDay(draft.date)}.`);
recordFinish(before, store.getState(), today, { name: draft.name, date: draft.date, ...draftTotals(draft) });
nav.go(href.finish(), { replace: true });
};
const node = h("div", { class: "screen screen--session" },
screenHeader({
back,
kicker: `Séance ${session.key}${session.tag ? " · " + session.tag : ""} · environ ${estimateMinutes(session)} min`,
kicker: `Séance ${session.key}${session.tag ? " · " + session.tag : ""} · environ ${estimatedMinutes(session)} min`,
title: session.name,
sub: session.subtitle,
}),
@@ -131,7 +138,7 @@ export function sessionScreen({ store, key, nav, timer }) {
dateInput),
dateNotice,
h("div", { class: "exercises" },
warmupCard({ done: draft.warmup, timer, onChange, open: !resumed }),
warmupCard({ plan: warmup, done: draft.warmup, timer, onChange, open: !resumed }),
blocks),
status,
h("p", { class: "foot" }, "Touche une série pour noter tes répétitions et ton ressenti : le repos démarre tout seul."),
+172
View File
@@ -0,0 +1,172 @@
// Semaine : jours disponibles, jours imposés, créneaux de la semaine en cours
// ou suivante, « Faite », « Non fait », « Retirer », export .ics.
// Le planning est calculé (planning.js), jamais stocké : seuls les réglages
// (PlanSettingsChanged) et les faits (SessionLogged, DaySkipped…) sont au journal.
import { h, paintWhenIdle, replace } from "../dom.js";
import { addDays, mondayOf } from "../../domain/dates.js";
import { settingsForWeek } from "../../domain/planning.js";
import { buildIcs } from "../../domain/ics.js";
import { DAY_LETTERS, DAY_NAMES, DAY_SHORT, dayName, lockOptions, loggedForSlot, sessionForSlot, slotLabel, weekRows, withDays, withLock } from "../home-model.js";
import { mediumDay, shortDay } from "../format.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { confirmDialog, toast } from "../feedback.js";
import { download } from "../files.js";
import { plaque } from "./home.js";
/** @typedef {import("../home-model.js").WeekRow} WeekRow */
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
export function weekScreen({ store, nav, today }) {
let tab = 0;
/** @type {number|null} */
let lockOpen = null;
const zone = h("div", { class: "week" });
const status = h("p", { class: "status status--ok", role: "status", "aria-live": "polite" });
const monday = () => addDays(mondayOf(today()), tab * 7);
/** Où écrire : la semaine suivante a toujours son propre réglage ; la semaine en cours écrit le réglage par défaut, sauf si elle a le sien. */
const target = () => {
const m = monday();
if (tab === 1) return m;
return store.getState().weekPlanSettings[m] ? m : null;
};
/** @param {{days: number[], locks: Record<string, string>}} settings */
const save = (settings) => store.dispatch("PlanSettingsChanged", { week: target(), days: settings.days, locks: settings.locks });
const paint = () => {
const state = store.getState();
const program = state.program;
const m = monday();
const settings = settingsForWeek(state, m);
const { plan, rows, extra } = weekRows(state, m, today());
const selected = new Set(settings?.days ?? []);
const tabs = h("div", { class: "segmented", role: "group", "aria-label": "Semaine affichée" },
["Cette semaine", "Semaine suivante"].map((label, i) => h("button", {
type: "button", class: "segmented__opt", "aria-pressed": String(tab === i),
on: { click: () => { tab = i; lockOpen = null; status.textContent = ""; paint(); } },
}, label)));
const days = h("div", { class: "segmented segmented--days", role: "group", "aria-label": "Jours où je peux m'entraîner" },
DAY_LETTERS.map((letter, d) => h("button", {
type: "button", class: "segmented__opt", "aria-pressed": String(selected.has(d)), "aria-label": DAY_NAMES[d],
on: { click: () => {
const next = selected.has(d) ? [...selected].filter((x) => x !== d) : [...selected, d];
save(withDays(settings, next));
const strength = weekRows(store.getState(), m, today()).plan.slots.filter((s) => s.kind === "strength").length;
const need = program?.sessions.length ?? 0;
status.textContent = next.length === 0 ? "Aucun jour retenu."
: strength < need ? `${strength} séance${strength > 1 ? "s" : ""} de force sur ${need} : la rotation rattrapera la semaine suivante.`
: `${strength} séances de force, espacées au maximum.`;
} },
}, letter)));
/** @param {WeekRow} r */
const row = (r) => {
const label = r.slot ? slotLabel(r.slot, program) : null;
const title = label ? label.title : r.lock === "rest" ? "Repos imposé" : r.available ? "Libre" : "Off";
let detail = label ? label.detail : r.available ? "disponible, rien à placer" : "";
if (r.lock && r.slot) detail += " · imposé";
if (r.status?.done && r.status.shifted && r.status.date) detail += ` · faite ${dayName(r.status.date)}`;
const state = r.status?.done ? "✓ Fait" : r.skipped ? "✕ Non fait" : "";
const mark = r.slot?.kind === "strength" && label?.key
? plaque(label.key, label.color, "plaque plaque--sm")
: h("span", { class: "plaque plaque--sm plaque--empty", "aria-hidden": "true" }, r.slot ? (r.slot.kind === "cardio" ? "C" : "A") : "·");
const actions = r.actions.map((a) => h("button", {
type: "button", class: "btn btn--sm",
on: { click: (/** @type {Event} */ e) => { e.stopPropagation(); void act(a, r); } },
}, ACTION_LABELS[a]));
const head = h("button", {
type: "button", class: "week__day", "aria-expanded": String(lockOpen === r.day),
"aria-label": `${DAY_NAMES[r.day]} ${shortDay(r.date)} : ${title}${detail ? ", " + detail : ""}${state ? ", " + state : ""}. Choisir ce que porte ce jour.`,
on: { click: () => { lockOpen = lockOpen === r.day ? null : r.day; paint(); } },
},
h("span", { class: "row__day" }, h("span", { class: "mark" }, DAY_SHORT[r.day]), h("span", { class: "num" }, r.date.slice(8))),
mark,
h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), detail && h("span", { class: "row__meta" }, detail)),
state && h("span", { class: "row__side mark" }, state));
return h("li", { class: `week__row${r.isToday ? " row--today" : ""}` },
h("div", { class: "row" }, head, actions.length > 0 && h("span", { class: "row__actions" }, actions)),
lockOpen === r.day && h("div", { class: "choice-list", role: "group", "aria-label": `Ce que porte ${DAY_NAMES[r.day]}` },
lockOptions(program).map((o) => h("button", {
type: "button", class: "choice", "aria-pressed": String((r.lock ?? "") === o.value),
on: { click: () => {
save(withLock(settings, r.day, o.value));
status.textContent = `${DAY_NAMES[r.day]} : ${o.label.toLowerCase()}.`;
lockOpen = null;
paint();
} },
}, o.label))));
};
replace(zone,
tabs,
h("p", { class: "mark week__range" }, `${mediumDay(m)} → ${mediumDay(addDays(m, 6))}`, plan.isOverride ? " · réglage propre à cette semaine" : ""),
h("h2", { class: "tape" }, "Jours dispo"),
days,
status,
!program && h("p", { class: "coach-note coach-note--plain" }, "Pas encore de programme : les jours sont gardés, les séances viendront avec le programme."),
h("h2", { class: "tape" }, "Planning", h("span", { class: "tape__hint" }, "touche un jour pour l'imposer")),
settings
? h("ul", { class: "rows week__rows" }, rows.map(row))
: h("p", { class: "empty" }, tab === 1 ? "Choisis les jours de la semaine suivante ci-dessus." : "Choisis tes jours ci-dessus : les séances se placent toutes seules."),
extra.length > 0 && h("p", { class: "muted" }, `En plus du planning : ${extra.map((s) => s.name).join(", ")}.`),
h("p", { class: "muted" }, tab === 1
? "Ces réglages ne valent que pour la semaine suivante. La rotation poursuit celle de cette semaine."
: "« Non fait » marque un créneau manqué sans toucher à ton historique."));
};
/** @param {"done"|"skip"|"unskip"|"remove"} action @param {WeekRow} r */
const act = async (action, r) => {
const state = store.getState();
const slot = /** @type {import("../../domain/planning.js").Slot} */ (r.slot);
if (action === "skip") store.dispatch("DaySkipped", { date: r.date });
else if (action === "unskip") store.dispatch("DayUnskipped", { date: r.date });
else if (action === "done") {
if (slot.kind === "strength") {
nav.go(href.session(/** @type {string} */ (slot.sessionKey), r.date === today() ? null : r.date));
return;
}
const data = loggedForSlot(slot, state.program, r.date);
store.dispatch("SessionLogged", data);
toast(`${data.name} : fait le ${shortDay(r.date)}.`);
} else if (action === "remove") {
const session = r.status ? sessionForSlot(state, slot, r.status) : null;
if (!session) return;
const ok = await confirmDialog({
title: "Retirer cette séance ?",
lines: [`${session.name}, ${mediumDay(session.date)}.`, "Elle disparaît de l'historique et des calculs."],
confirm: "Retirer", cancel: "Garder", danger: true,
});
if (ok) store.dispatch("SessionDeleted", { sessionId: session.id });
}
};
// ---- export .ics --------------------------------------------------------------
const time = h("input", { id: "ics-time", class: "field__input", type: "time", value: "18:00", step: "900" });
const exportIcs = () => {
const [hour, minute] = (time.value || "18:00").split(":").map(Number);
const state = store.getState();
const { plan } = weekRows(state, monday(), today());
download(`ia-fit-semaine-${plan.monday}.ics`, buildIcs(state, plan, { hour, minute, now: new Date() }), "text/calendar;charset=utf-8");
toast("Agenda téléchargé.");
};
paint();
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Planning", title: "Semaine" }),
zone,
h("h2", { class: "tape" }, "Agenda"),
h("div", { class: "field field--inline" }, h("label", { class: "field__label", for: "ics-time" }, "Départ à"), time),
h("button", { type: "button", class: "btn btn--block", on: { click: exportIcs } }, "Télécharger le .ics"),
h("p", { class: "muted" }, "Un événement par créneau à faire, avec un rappel 30 minutes avant."));
return { node, title: "Semaine", destroy: store.subscribe(paintWhenIdle(zone, paint)) };
}
/** @type {Record<string, string>} */
const ACTION_LABELS = { done: "Faite", skip: "Non fait", unskip: "Annuler", remove: "Retirer" };
+147
View File
@@ -0,0 +1,147 @@
// Poids : pesée, courbe (3 mois, 1 an, tout), tendance, repères, import en
// texte libre et liste. Calculs du domaine : weight.js.
import { h, replace } from "../dom.js";
import { addDays, daysBetween } from "../../domain/dates.js";
import { parseWeightLines, weightMilestones, weightTrend } from "../../domain/weight.js";
import { dec1, durationLabel, kg, mediumDay, parseAmount, plural, shortDay } from "../format.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { lineChart } from "../chart.js";
import { toast } from "../feedback.js";
/** Périodes de la courbe, en jours (Infinity : tout). */
const PERIODS = [{ days: 90, label: "3 mois" }, { days: 365, label: "1 an" }, { days: Infinity, label: "Tout" }];
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
export function weightScreen({ store, nav, today }) {
let period = 90;
const summary = h("div");
const chartZone = h("div");
const milestones = h("div");
const list = h("div");
// ---- pesée ----------------------------------------------------------------------
const date = h("input", { id: "w-date", class: "field__input", type: "date", max: today(), value: today() });
const amount = h("input", { id: "w-kg", class: "field__input field__input--big", type: "text", inputmode: "decimal", autocomplete: "off", placeholder: "—" });
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const add = () => {
const v = parseAmount(amount.value);
status.className = "status status--err";
if (!/^\d{4}-\d{2}-\d{2}$/.test(date.value) || date.value > today()) { status.textContent = "Date invalide."; return; }
if (typeof v !== "number" || v < 20 || v > 400) { status.textContent = "Poids invalide (20 à 400 kg)."; return; }
store.dispatch("WeightRecorded", { date: date.value, kg: v });
status.className = "status status--ok";
status.textContent = `${kg(v)} kg le ${shortDay(date.value)}.`;
amount.value = "";
};
amount.addEventListener("keydown", (e) => { if (e.key === "Enter") add(); });
// ---- import en texte libre ------------------------------------------------------
const text = h("textarea", { id: "w-import", class: "field__input field__input--area field__input--mono", placeholder: "2026-11-02 82,4\n09/11/2026 ; 82,1" });
const report = h("div", { class: "import-report" });
const read = () => {
const { entries, rejected } = parseWeightLines(text.value);
if (!entries.length && !rejected.length) { replace(report, h("p", { class: "status status--err" }, "Colle d'abord tes pesées.")); return; }
replace(report,
h("p", { class: entries.length ? "status status--ok" : "status status--err" },
entries.length ? `${plural(entries.length, "pesée")} lisible${entries.length > 1 ? "s" : ""}.` : "Aucune ligne lisible : une date puis un poids par ligne."),
rejected.length > 0 && [h("p", { class: "muted" }, `${plural(rejected.length, "ligne")} ignorée${rejected.length > 1 ? "s" : ""} :`),
h("ul", { class: "mono-list" }, rejected.slice(0, 5).map((l) => h("li", null, l)))],
entries.length > 0 && h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => {
for (const e of entries) store.dispatch("WeightRecorded", e);
toast(`${plural(entries.length, "pesée")} importée${entries.length > 1 ? "s" : ""}.`);
text.value = "";
replace(report);
} } }, `Importer ${plural(entries.length, "pesée")}`));
};
const paint = () => {
const weights = store.getState().weights;
const last = weights[weights.length - 1];
const trend = weightTrend(weights, { today: today() });
const sens = !trend ? "" : trend.kgPerWeek < -0.05 ? "en baisse" : trend.kgPerWeek > 0.05 ? "en hausse" : "stable";
replace(summary, last
? h("div", { class: "stats" },
h("div", { class: "stat" }, h("span", { class: "stat__value" }, kg(last.kg), h("small", null, "kg")), h("span", { class: "stat__label" }, `le ${shortDay(last.date)}`)),
h("div", { class: "stat" },
h("span", { class: "stat__value" }, trend ? `${trend.kgPerWeek > 0 ? "+" : ""}${dec1(trend.kgPerWeek)}` : "—", trend && h("small", null, "kg/sem")),
h("span", { class: "stat__label" }, trend ? `${sens} · 8 semaines` : "tendance : 2 pesées")))
: h("p", { class: "empty" }, "Aucune pesée pour l'instant. Saisis la première."));
if (trend?.staleDays && trend.staleDays > 14) summary.append(h("p", { class: "muted" }, `Dernière pesée il y a ${durationLabel(trend.staleDays)}.`));
// Courbe
const from = period === Infinity ? "" : addDays(today(), -period);
const inPeriod = weights.filter((w) => w.date >= from);
const pts = inPeriod.length > 1 ? inPeriod : weights;
replace(chartZone,
h("div", { class: "segmented", role: "group", "aria-label": "Période de la courbe" }, PERIODS.map((p) =>
h("button", { type: "button", class: "segmented__opt", "aria-pressed": String(p.days === period), on: { click: () => { period = p.days; paint(); } } }, p.label))),
pts.length > 1
? h("figure", { class: "chart" },
lineChart({
points: pts.map((w) => ({ x: daysBetween(pts[0].date, w.date), y: w.kg })),
label: `Courbe du poids, du ${mediumDay(pts[0].date)} au ${mediumDay(pts[pts.length - 1].date)}`,
format: (v) => dec1(v), xLabels: [shortDay(pts[0].date), shortDay(pts[pts.length - 1].date)], minSpan: 1.2,
}),
inPeriod.length < 2 && h("figcaption", { class: "chart__caption" }, "Pas assez de pesées sur la période : tout l'historique."))
: h("p", { class: "empty" }, "Deux pesées suffisent pour tracer la courbe."));
// Repères
const m = weightMilestones(weights);
replace(milestones, m
? h("ul", { class: "rows" },
h("li", { class: "row" }, h("span", { class: "row__main" },
m.lastBelow
? [h("span", { class: "row__title" }, `La dernière fois sous ${kg(m.current.kg)} kg`),
h("span", { class: "row__meta" }, `Le ${mediumDay(m.lastBelow.date)}, à ${kg(m.lastBelow.kg)} kg : il y a ${durationLabel(/** @type {number} */ (m.daysSinceLastBelow))}.`)]
: [h("span", { class: "row__title" }, "Ton point le plus bas"),
h("span", { class: "row__meta" }, `${kg(m.current.kg)} kg : aucune pesée enregistrée n'est plus basse.`)])),
m.minimum.date !== m.current.date && h("li", { class: "row" }, h("span", { class: "row__main" },
h("span", { class: "row__title" }, `Minimum : ${kg(m.minimum.kg)} kg`),
h("span", { class: "row__meta" }, `Le ${mediumDay(m.minimum.date)}, il y a ${durationLabel(m.daysSinceMinimum)}. ${dec1(m.current.kg - m.minimum.kg)} kg au-dessus aujourd'hui.`))))
: h("p", { class: "muted" }, "Les repères viennent avec deux pesées."));
// Liste
const recent = [...weights].reverse().slice(0, 40);
replace(list, recent.length
? h("ul", { class: "rows" }, recent.map((w, i) => {
const prev = recent[i + 1];
const delta = prev ? w.kg - prev.kg : null;
return h("li", { class: "row" },
h("span", { class: "row__main" }, h("span", { class: "row__title" }, mediumDay(w.date)),
delta !== null && h("span", { class: "row__meta" }, `${delta > 0 ? "+" : ""}${dec1(delta)} kg`)),
h("span", { class: "row__side num weight__kg" }, kg(w.kg)),
h("button", { type: "button", class: "btn btn--sm btn--ghost", "aria-label": `Supprimer la pesée du ${mediumDay(w.date)}`, on: { click: () => store.dispatch("WeightDeleted", { date: w.date }) } }, "✕"));
}))
: null);
};
paint();
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Suivi", title: "Poids" }),
summary,
h("h2", { class: "tape" }, "Pesée"),
h("div", { class: "field-pair" },
h("div", { class: "field" }, h("label", { class: "field__label", for: "w-kg" }, "Poids (kg)"), amount),
h("div", { class: "field" }, h("label", { class: "field__label", for: "w-date" }, "Date"), date)),
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: add } }, "Enregistrer"),
status,
h("h2", { class: "tape" }, "Courbe"),
chartZone,
h("h2", { class: "tape" }, "Repères"),
milestones,
h("h2", { class: "tape" }, "Pesées"),
list,
h("details", { class: "import" },
h("summary", { class: "btn btn--ghost btn--block" }, "Importer des pesées"),
h("div", { class: "field" }, h("label", { class: "field__label", for: "w-import" }, "Une pesée par ligne : date puis poids"), text),
h("button", { type: "button", class: "btn btn--block", on: { click: read } }, "Lire"),
report));
// Les champs (pesée, import) ne sont jamais dans une zone repeinte : on repeint tout de suite.
return { node, title: "Poids", destroy: store.subscribe(paint) };
}
+53 -3
View File
@@ -19,7 +19,13 @@ import { resolveExercise, exerciseKey, trackingFor, targetSeconds } from "../dom
* @property {TrackingMode} tracking
* @property {number|null} loadKg charge du jour (modes avec charge)
* @property {number|null} seconds durée d'une série (modes au temps)
* @property {(LoggedSet|null)[]} done une case par série prévue, null tant qu'elle n'est pas faite
* @property {(DraftSet|null)[]} done une case par série prévue, null tant qu'elle n'est pas faite
*/
/**
* Série faite dans le brouillon : `n` est son rang de validation dans la séance
* (pour le combo), absent des brouillons plus anciens.
* @typedef {LoggedSet & {n?: number}} DraftSet
*/
/**
@@ -94,12 +100,16 @@ export function createDraft(session, state, date, warmupSteps) {
export function draftMatches(draft, session, warmupSteps) {
const d = /** @type {any} */ (draft);
if (!d || d.sessionKey !== session.key || !Array.isArray(d.exercises) || !Array.isArray(d.warmup)) return false;
if (d.warmup.length !== warmupSteps || d.exercises.length !== session.exercises.length) return false;
return session.exercises.every((item, i) => {
if (d.exercises.length !== session.exercises.length) return false;
const ok = session.exercises.every((item, i) => {
const ex = resolveExercise(item);
const x = d.exercises[i];
return x && x.id === ex.id && Array.isArray(x.done) && x.done.length === ex.sets;
});
// Le nombre d'étapes d'échauffement suit la charge saisie (séries d'approche) :
// un écart ne fait pas perdre la séance, les cases sont ajustées.
if (ok && d.warmup.length !== warmupSteps) d.warmup = Array.from({ length: warmupSteps }, (_, i) => d.warmup[i] === true);
return ok;
}
/**
@@ -138,6 +148,46 @@ export function proposedReps(ex, index) {
return targetReps(ex.reps)?.high ?? 0;
}
/**
* Valide une série : elle prend le rang suivant dans la séance.
* @param {Draft} draft
* @param {DraftExercise} ex
* @param {number} index
* @param {LoggedSet} set
*/
export function markSet(draft, ex, index, set) {
const n = 1 + Math.max(0, ...draft.exercises.flatMap((x) => x.done.map((s) => s?.n ?? 0)));
ex.done[index] = { reps: set.reps, effort: set.effort, n };
}
/**
* Les séries faites, dans l'ordre où elles ont été validées (à défaut, dans
* l'ordre de la séance).
* @param {Draft} draft
* @returns {LoggedSet[]}
*/
export function setsInOrder(draft) {
const all = draft.exercises.flatMap((x) => x.done.filter((s) => s !== null));
return /** @type {DraftSet[]} */ (all).map((s, i) => ({ s, k: s.n ?? i / 1000 })).sort((a, b) => a.k - b.k).map(({ s }) => s);
}
/**
* Résumé chiffré du brouillon, pour l'écran de fin : séries, répétitions et
* volume (répétitions × charge).
* @param {Draft} draft
*/
export function draftTotals(draft) {
let sets = 0, reps = 0, volumeKg = 0;
for (const ex of draft.exercises)
for (const s of ex.done) {
if (!s) continue;
sets++;
reps += s.reps ?? 0;
if (usesLoad(ex.tracking) && ex.loadKg) volumeKg += (s.reps ?? 0) * ex.loadKg;
}
return { sets, reps, volumeKg };
}
/** @param {DraftExercise} ex */
export const doneCount = (ex) => ex.done.filter((s) => s !== null).length;
+35
View File
@@ -0,0 +1,35 @@
// Thème choisi sur cet appareil : « auto » (celui du système), « dark » ou
// « light ». Préférence d'affichage, gardée dans le stockage local, jamais un
// événement. theme.js (script classique, chargé avant le premier affichage)
// lit la même clé pour éviter un flash de l'autre thème.
const KEY = "ia-fit.theme";
/** @returns {"auto"|"dark"|"light"} */
export function getTheme() {
try {
const v = localStorage.getItem(KEY);
return v === "dark" || v === "light" ? v : "auto";
} catch {
return "auto";
}
}
/** @param {"auto"|"dark"|"light"} theme */
export function setTheme(theme) {
try {
if (theme === "auto") localStorage.removeItem(KEY);
else localStorage.setItem(KEY, theme);
} catch {
// stockage interdit : le choix vaut pour cette visite
}
applyTheme(theme);
}
/** @param {"auto"|"dark"|"light"} theme */
export function applyTheme(theme) {
if (theme === "auto") document.documentElement.removeAttribute("data-theme");
else document.documentElement.setAttribute("data-theme", theme);
const dark = theme === "dark" || (theme === "auto" && !matchMedia("(prefers-color-scheme: light)").matches);
for (const meta of document.querySelectorAll('meta[name="theme-color"]')) meta.setAttribute("content", dark ? "#000000" : "#F2F2EC");
}
+12
View File
@@ -0,0 +1,12 @@
// Script classique (pas un module), chargé dans <head> avant le premier
// affichage : il pose le thème choisi sur cet appareil (voir theme-pref.js)
// sans attendre les modules, donc sans flash de l'autre thème. Aucun script en
// ligne : la CSP stricte l'interdit.
(function () {
try {
var theme = localStorage.getItem("ia-fit.theme");
if (theme === "dark" || theme === "light") document.documentElement.setAttribute("data-theme", theme);
} catch (e) {
// stockage interdit : thème du système
}
})();
+44 -29
View File
@@ -1,25 +1,38 @@
// L'échauffement guidé, en tête de séance. Glossaire : docs/glossaire/echauffement.md
//
// À brancher : warmup.warmupPlan (domaine, sous-lot 1b) calculera les étapes et
// les séries d'approche à partir de la charge de travail du premier exercice.
// En attendant, les étapes de mobilité sont codées ici (reprises d'Atelier) et
// les séries d'approche ne sont pas chiffrées.
// L'échauffement guidé, en tête de séance : un peu de cardio, la mobilité
// (warmup.MOBILITY), puis les séries d'approche du premier exercice, chiffrées à
// partir de sa charge de travail (warmup.warmupPlan).
// Glossaire : docs/glossaire/echauffement.md, docs/glossaire/approche.md
import { h } from "./dom.js";
import { restLabel } from "./format.js";
import { MOBILITY, warmupPlan } from "../domain/warmup.js";
/** @typedef {{title: string, detail: string, seconds: number}} WarmupStep */
/** @typedef {{title: string, detail: string, seconds: number|null, approach: boolean}} WarmupStep */
/** @type {WarmupStep[]} */
export const WARMUP_STEPS = [
{ title: "Vélo, marche ou corde légère", detail: "Allure tranquille, juste de quoi avoir chaud et le souffle un peu plus court.", seconds: 360 },
{ title: "Cercles de bras et rotations d'épaules", detail: "Bras tendus, 10 cercles en avant puis 10 en arrière. Puis les épaules qui montent et descendent.", seconds: 45 },
{ title: "Balancements de jambe", detail: "Appuie-toi au mur. 10 balancements avant-arrière par jambe, puis 10 latéraux.", seconds: 60 },
{ title: "Squats au poids du corps", detail: "10 répétitions, descente lente, en cherchant un peu plus de profondeur à chaque fois.", seconds: 60 },
];
/** Mise en route, avant la mobilité (reprise d'Atelier). */
const GENERAL = { title: "Vélo, marche ou corde légère", detail: "Allure tranquille, juste de quoi avoir chaud et le souffle un peu plus court.", seconds: 360 };
/**
* @param {{done: boolean[], timer: import("./timer.js").Timer, onChange: () => void, open: boolean}} o
* Les étapes de l'échauffement d'une séance.
* @param {import("../domain/state.js").State} state
* @param {import("../domain/program.js").ProgramSession} session
* @returns {{steps: WarmupStep[], exerciseName: string|null, note: string|null}}
*/
export function warmupSteps(state, session) {
const plan = warmupPlan(state, session);
return {
steps: [
{ ...GENERAL, approach: false },
...MOBILITY.map((m) => ({ ...m, approach: false })),
...(plan?.lines ?? []).map((l) => ({ title: l.title, detail: l.detail, seconds: null, approach: true })),
],
exerciseName: plan?.exerciseName ?? null,
note: plan?.note ?? null,
};
}
/**
* @param {{plan: ReturnType<typeof warmupSteps>, done: boolean[], timer: import("./timer.js").Timer, onChange: () => void, open: boolean}} o
* done : étapes cochées, modifié sur place
*/
export function warmupCard(o) {
@@ -30,11 +43,9 @@ export function warmupCard(o) {
count.classList.toggle("exercise__count--done", n === o.done.length);
};
const steps = WARMUP_STEPS.map((step, i) => {
const tick = h("button", {
type: "button", class: "tick", "aria-pressed": String(o.done[i]),
"aria-label": `Fait : ${step.title}`,
});
/** @param {WarmupStep} step @param {number} i */
const row = (step, i) => {
const tick = h("button", { type: "button", class: "tick", "aria-pressed": String(!!o.done[i]), "aria-label": `Fait : ${step.title}` });
tick.addEventListener("click", () => {
o.done[i] = !o.done[i];
tick.setAttribute("aria-pressed", String(o.done[i]));
@@ -44,25 +55,29 @@ export function warmupCard(o) {
return h("li", { class: "step" },
tick,
h("div", { class: "step__text" }, h("strong", null, step.title), h("span", null, step.detail)),
h("button", {
step.seconds && h("button", {
type: "button", class: "btn btn--sm step__go", "aria-label": `Lancer ${restLabel(step.seconds)} : ${step.title}`,
on: { click: () => o.timer.startRest(step.seconds, step.title, "Étape terminée") },
on: { click: () => o.timer.startRest(/** @type {number} */ (step.seconds), step.title, "Étape terminée") },
}, restLabel(step.seconds)));
});
};
const steps = o.plan.steps;
const general = steps.filter((s) => !s.approach);
const approach = steps.filter((s) => s.approach);
const card = h("details", { class: "exercise exercise--warmup", open: o.open },
h("summary", { class: "exercise__head" },
h("span", { class: "badge badge--warmup", "aria-hidden": "true" }, "0"),
h("span", { class: "badge", "aria-hidden": "true" }, "0"),
h("span", { class: "exercise__name" },
h("strong", null, "Échauffement"),
h("span", { class: "exercise__sub" }, "À faire en premier · environ 10 min")),
h("span", { class: "exercise__sub" }, "En premier · environ 10 min")),
count,
h("span", { class: "chevron", "aria-hidden": "true" })),
h("div", { class: "exercise__body" },
h("ol", { class: "steps" }, steps),
h("h3", { class: "mini-label" }, "Séries d'approche"),
h("p", { class: "muted" },
"Monte progressivement jusqu'à ta charge du jour sur le premier exercice. Le calcul chiffré des séries d'approche arrive bientôt.")));
h("ol", { class: "steps" }, general.map((s, i) => row(s, i))),
approach.length > 0 && [
h("h3", { class: "mini-label" }, `Séries d'approche · ${o.plan.exerciseName ?? ""}`),
h("ol", { class: "steps" }, approach.map((s, i) => row(s, general.length + i)))],
o.plan.note && h("p", { class: "coach-note" }, o.plan.note)));
refresh();
return card;
}