Interface : magasin, routeur, brouillon de séance et modules purs testés
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
74db3014f0
commit
ba08daaa89
@@ -0,0 +1,33 @@
|
||||
// Couleurs venues du programme (choisies par l'IA ou l'utilisateur) : on calcule
|
||||
// la couleur du texte posé dessus pour garder un contraste lisible.
|
||||
|
||||
/** Luminance relative WCAG d'une couleur #RRGGBB. @param {string} hex */
|
||||
export function luminance(hex) {
|
||||
const [r, g, b] = [1, 3, 5]
|
||||
.map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
|
||||
.map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
/** Ratio de contraste WCAG entre deux couleurs #RRGGBB. @param {string} a @param {string} b */
|
||||
export function contrastRatio(a, b) {
|
||||
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||
return (hi + 0.05) / (lo + 0.05);
|
||||
}
|
||||
|
||||
export const INK_DARK = "#0E1113";
|
||||
export const INK_LIGHT = "#FFFFFF";
|
||||
|
||||
/**
|
||||
* Texte à poser sur un fond de couleur : le plus contrasté du presque-noir et
|
||||
* du blanc.
|
||||
* @param {string} background #RRGGBB
|
||||
*/
|
||||
export function inkOn(background) {
|
||||
return contrastRatio(INK_DARK, background) >= contrastRatio(INK_LIGHT, background) ? INK_DARK : INK_LIGHT;
|
||||
}
|
||||
|
||||
/** Couleur d'une séance, ou un gris neutre si le programme n'en donne pas. @param {string|undefined} color */
|
||||
export function sessionColor(color) {
|
||||
return color && /^#[0-9A-Fa-f]{6}$/.test(color) ? color : "#8A9199";
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Petits outils DOM. Aucun innerHTML : les textes passent par des nœuds texte,
|
||||
// ce qui protège des données venues de l'utilisateur ou de l'IA. Aucun style en
|
||||
// ligne non plus (CSP stricte, lot 1f) : seules des variables CSS de couleur
|
||||
// venues du programme passent par style.setProperty (voir setAccent).
|
||||
|
||||
/** @typedef {Node|string|number|null|undefined|false|Children} Child */
|
||||
/** @typedef {Array<Child>} Children */
|
||||
|
||||
/**
|
||||
* Crée un élément.
|
||||
* - `class` : classes CSS ;
|
||||
* - `on` : { click: fn, … } branchés par addEventListener ;
|
||||
* - `data` : { cle: valeur } vers dataset ;
|
||||
* - une valeur `true` pose l'attribut vide, `false`, null ou undefined l'omet ;
|
||||
* - le reste devient un attribut.
|
||||
* @template {keyof HTMLElementTagNameMap} K
|
||||
* @param {K} tag
|
||||
* @param {Record<string, any>|null} [attrs]
|
||||
* @param {...Child} children
|
||||
* @returns {HTMLElementTagNameMap[K]}
|
||||
*/
|
||||
export function h(tag, attrs, ...children) {
|
||||
const el = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attrs ?? {})) {
|
||||
if (value === null || value === undefined || value === false) continue;
|
||||
if (key === "class") el.className = String(value);
|
||||
else if (key === "on") for (const [type, fn] of Object.entries(value)) el.addEventListener(type, fn);
|
||||
else if (key === "data") for (const [k, v] of Object.entries(value)) el.dataset[k] = String(v);
|
||||
else if (key === "style") throw new Error("Pas de style en ligne : utiliser une classe CSS.");
|
||||
else if (key === "value" && "value" in el) /** @type {any} */ (el).value = String(value);
|
||||
else el.setAttribute(key, value === true ? "" : String(value));
|
||||
}
|
||||
append(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Element} parent
|
||||
* @param {Child[]} children
|
||||
*/
|
||||
export function append(parent, children) {
|
||||
for (const child of /** @type {any[]} */ (children).flat(Infinity)) {
|
||||
if (child === null || child === undefined || child === false) continue;
|
||||
parent.append(typeof child === "object" ? child : String(child));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remplace le contenu d'un élément.
|
||||
* @param {Element} el
|
||||
* @param {...Child} children
|
||||
*/
|
||||
export function replace(el, ...children) {
|
||||
el.replaceChildren();
|
||||
append(el, children);
|
||||
}
|
||||
|
||||
/**
|
||||
* Couleur d'accent d'une séance (donnée du programme) : variable CSS posée par
|
||||
* le CSSOM, permise par une CSP sans 'unsafe-inline', contrairement à un
|
||||
* attribut style.
|
||||
* @param {HTMLElement} el
|
||||
* @param {string|undefined} color #RRGGBB
|
||||
* @param {string} ink couleur du texte posé sur l'accent
|
||||
*/
|
||||
export function setAccent(el, color, ink) {
|
||||
if (!color) return;
|
||||
el.style.setProperty("--accent", color);
|
||||
el.style.setProperty("--accent-ink", ink);
|
||||
}
|
||||
|
||||
/** Vibration courte, si l'appareil sait le faire. @param {number[]} pattern */
|
||||
export function vibrate(pattern) {
|
||||
try {
|
||||
if ("vibrate" in navigator) navigator.vibrate(pattern);
|
||||
} catch {
|
||||
// vibration indisponible : sans conséquence
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// 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.
|
||||
|
||||
/**
|
||||
* 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")}`;
|
||||
}
|
||||
|
||||
/** @param {string} day AAAA-MM-JJ */
|
||||
const noon = (day) => new Date(day + "T12:00:00");
|
||||
|
||||
/** « jeudi 18 novembre » @param {string} day */
|
||||
export function longDay(day) {
|
||||
return noon(day).toLocaleDateString("fr-FR", { weekday: "long", day: "numeric", month: "long" });
|
||||
}
|
||||
|
||||
/** « 18/11 » @param {string} day */
|
||||
export function shortDay(day) {
|
||||
return noon(day).toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit" });
|
||||
}
|
||||
|
||||
/** « 18 nov. 2026 » @param {string} day */
|
||||
export function mediumDay(day) {
|
||||
return noon(day).toLocaleDateString("fr-FR", { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
|
||||
/** Chrono : 90 → « 1:30 », 5 → « 0:05 ». @param {number} seconds */
|
||||
export function clock(seconds) {
|
||||
const s = Math.max(0, Math.round(seconds));
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/** Repos lisible : 90 → « 1 min 30 », 45 → « 45 s », 120 → « 2 min ». @param {number} seconds */
|
||||
export function restLabel(seconds) {
|
||||
if (seconds < 60) return `${seconds} s`;
|
||||
const m = Math.floor(seconds / 60), s = seconds % 60;
|
||||
return s ? `${m} min ${String(s).padStart(2, "0")}` : `${m} min`;
|
||||
}
|
||||
|
||||
/** Charge : 62.5 → « 62,5 ». @param {number} kg */
|
||||
export function kg(kg) {
|
||||
return String(kg).replace(".", ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit un nombre saisi (virgule ou point), positif ou nul. Champ vide : null.
|
||||
* Texte illisible : undefined (la saisie est refusée).
|
||||
* @param {string} text
|
||||
* @returns {number|null|undefined}
|
||||
*/
|
||||
export function parseAmount(text) {
|
||||
const t = text.trim().replace(",", ".");
|
||||
if (t === "") return null;
|
||||
const n = Number(t);
|
||||
return Number.isFinite(n) && n >= 0 ? n : undefined;
|
||||
}
|
||||
|
||||
/** Accord simple : plural(3, "série") → « 3 séries ». @param {number} n @param {string} word */
|
||||
export function plural(n, word) {
|
||||
return `${n} ${word}${n > 1 ? "s" : ""}`;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 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.
|
||||
|
||||
import { groupBlocks, resolveExercise, targetSeconds } from "../domain/program.js";
|
||||
|
||||
/**
|
||||
* Dernière date (AAAA-MM-JJ) où chaque séance de force a été faite.
|
||||
* @param {import("../domain/state.js").State} state
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
export function lastDoneByKey(state) {
|
||||
/** @type {Record<string, string>} */
|
||||
const last = {};
|
||||
for (const s of state.sessions)
|
||||
if (s.kind === "strength" && (!last[s.ref] || s.date > last[s.ref])) last[s.ref] = s.date;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @returns {import("../domain/program.js").ProgramSession|null}
|
||||
*/
|
||||
export function nextByRotation(state) {
|
||||
const sessions = state.program?.sessions ?? [];
|
||||
if (!sessions.length) return null;
|
||||
const last = lastDoneByKey(state);
|
||||
const never = sessions.find((s) => !last[s.key]);
|
||||
if (never) return never;
|
||||
return [...sessions].sort((a, b) => (last[a.key] < last[b.key] ? -1 : last[a.key] > last[b.key] ? 1 : 0))[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
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;
|
||||
}
|
||||
return Math.round(total / 60 / 5) * 5;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Libellés français des valeurs fermées du domaine (app/domain/vocabulary.js).
|
||||
|
||||
/** @type {Record<import("../domain/vocabulary.js").TrackingMode, string>} */
|
||||
export const TRACKING_LABELS = {
|
||||
load: "Charge",
|
||||
time: "Durée",
|
||||
"time+load": "Durée et charge",
|
||||
none: "Rien à saisir",
|
||||
};
|
||||
|
||||
/**
|
||||
* Ressenti d'une série. Glossaire : docs/glossaire/ressenti.md
|
||||
* @type {Record<import("../domain/vocabulary.js").Effort, {label: string, hint: 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" },
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
// Un écran par adresse, dans le fragment (#/…) : l'app reste un site statique
|
||||
// et le bouton retour du navigateur fonctionne.
|
||||
//
|
||||
// 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=).
|
||||
|
||||
/**
|
||||
* @typedef {{name: "home"}
|
||||
* | {name: "session", key: string}
|
||||
* | {name: "history"}
|
||||
* | {name: "history-edit", id: string}
|
||||
* | {name: "reserved"}
|
||||
* | {name: "not-found"}} Route
|
||||
*/
|
||||
|
||||
/** Fragments réservés à d'autres modules. */
|
||||
export const RESERVED = ["#import=", "#pair="];
|
||||
|
||||
/**
|
||||
* Lit une adresse. Fonction pure, testée.
|
||||
* @param {string} hash location.hash, avec son #
|
||||
* @returns {Route}
|
||||
*/
|
||||
export function parseRoute(hash) {
|
||||
if (RESERVED.some((p) => hash.startsWith(p))) return { name: "reserved" };
|
||||
const path = hash.replace(/^#\/?/, "").replace(/\/+$/, "");
|
||||
if (path === "") return { name: "home" };
|
||||
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] };
|
||||
return { name: "not-found" };
|
||||
}
|
||||
|
||||
/** Adresses, pour écrire les liens sans les recopier. */
|
||||
export const href = {
|
||||
home: () => "#/",
|
||||
session: (/** @type {string} */ key) => "#/seance/" + encodeURIComponent(key),
|
||||
history: () => "#/historique",
|
||||
historyEdit: (/** @type {string} */ id) => "#/historique/" + encodeURIComponent(id),
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {object} Screen
|
||||
* @property {HTMLElement} node
|
||||
* @property {string} title titre de l'onglet
|
||||
* @property {() => void} [destroy] appelé quand on quitte l'écran
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} Navigation
|
||||
* @property {(hash: string, options?: {replace?: boolean}) => void} go
|
||||
* @property {(fallback?: string) => void} back retour dans l'app, ou vers fallback
|
||||
*/
|
||||
|
||||
/**
|
||||
* Branche le routeur sur la fenêtre.
|
||||
* @param {HTMLElement} root
|
||||
* @param {(route: Route, nav: Navigation) => Screen} render
|
||||
*/
|
||||
export function startRouter(root, render) {
|
||||
/** Adresses vues pendant la visite, pour savoir si « retour » reste dans l'app. */
|
||||
const visited = [location.hash];
|
||||
/** @type {Screen|null} */
|
||||
let current = null;
|
||||
|
||||
/** @type {Navigation} */
|
||||
const nav = {
|
||||
go(hash, { replace = false } = {}) {
|
||||
if (replace) {
|
||||
history.replaceState(null, "", hash);
|
||||
visited[visited.length - 1] = hash;
|
||||
show();
|
||||
} else location.hash = hash;
|
||||
},
|
||||
back(fallback = href.home()) {
|
||||
if (visited.length > 1) history.back();
|
||||
else nav.go(fallback, { replace: true });
|
||||
},
|
||||
};
|
||||
|
||||
const show = () => {
|
||||
let route = parseRoute(location.hash);
|
||||
// Un fragment réservé ne change pas l'écran ; au démarrage, on montre l'accueil.
|
||||
if (route.name === "reserved") {
|
||||
if (current) return;
|
||||
route = { name: "home" };
|
||||
}
|
||||
current?.destroy?.();
|
||||
current = render(route, nav);
|
||||
root.replaceChildren(current.node);
|
||||
document.title = current.title ? `${current.title} · IA-Fit` : "IA-Fit";
|
||||
window.scrollTo(0, 0);
|
||||
// Le focus suit l'écran (lecteurs d'écran, clavier).
|
||||
const heading = current.node.querySelector("h1");
|
||||
if (heading) {
|
||||
heading.setAttribute("tabindex", "-1");
|
||||
heading.focus({ preventScroll: true });
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("hashchange", () => {
|
||||
if (visited.length > 1 && visited[visited.length - 2] === location.hash) visited.pop();
|
||||
else visited.push(location.hash);
|
||||
show();
|
||||
});
|
||||
show();
|
||||
return nav;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// La séance en cours : un brouillon local, jamais un événement par série
|
||||
// (ADR 0006, point 3). « Terminer » le transforme en un seul SessionLogged.
|
||||
// Module pur (sans DOM), testé dans tests/ui/session-draft.test.js.
|
||||
|
||||
import { resolveExercise, exerciseKey, trackingFor, targetSeconds } from "../domain/program.js";
|
||||
|
||||
/** @typedef {import("../domain/vocabulary.js").TrackingMode} TrackingMode */
|
||||
/** @typedef {import("../domain/events.js").LoggedSet} LoggedSet */
|
||||
/** @typedef {import("../domain/events.js").SessionData} SessionData */
|
||||
|
||||
/**
|
||||
* @typedef {object} DraftExercise
|
||||
* @property {string} key clé de charge et de mode de suivi : « A-squat »
|
||||
* @property {string} id clé stable de l'exercice (ref, sinon nom)
|
||||
* @property {string} name
|
||||
* @property {number} sets séries prévues
|
||||
* @property {string} reps objectif de répétitions du programme (« 6–8 »)
|
||||
* @property {number} rest repos en secondes
|
||||
* @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
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} Draft
|
||||
* @property {string} sessionKey
|
||||
* @property {string} name
|
||||
* @property {string} date jour local AAAA-MM-JJ de la séance
|
||||
* @property {boolean[]} warmup étapes d'échauffement cochées
|
||||
* @property {DraftExercise[]} exercises
|
||||
*/
|
||||
|
||||
/** Durée par défaut d'une série au temps quand le programme n'en donne pas. */
|
||||
export const DEFAULT_SECONDS = 45;
|
||||
|
||||
/** @param {TrackingMode} mode */
|
||||
export const usesLoad = (mode) => mode === "load" || mode === "time+load";
|
||||
/** @param {TrackingMode} mode */
|
||||
export const usesTime = (mode) => mode === "time" || mode === "time+load";
|
||||
|
||||
/**
|
||||
* Exercice du brouillon, lu dans le programme et l'état (charge de travail, mode
|
||||
* de suivi choisi).
|
||||
* @param {string} sessionKey
|
||||
* @param {import("../domain/program.js").ProgramExercise} item
|
||||
* @param {import("../domain/state.js").State} state
|
||||
* @returns {DraftExercise}
|
||||
*/
|
||||
export function draftExercise(sessionKey, item, state) {
|
||||
const ex = resolveExercise(item);
|
||||
const key = exerciseKey(sessionKey, item);
|
||||
const tracking = trackingFor(item, state.trackingOverrides[key]);
|
||||
const saved = state.workingLoads[key];
|
||||
return {
|
||||
key,
|
||||
id: ex.id,
|
||||
name: ex.name,
|
||||
sets: ex.sets,
|
||||
reps: ex.reps,
|
||||
rest: ex.rest,
|
||||
tracking,
|
||||
loadKg: usesLoad(tracking) ? saved?.loadKg ?? null : null,
|
||||
seconds: usesTime(tracking) ? saved?.seconds ?? targetSeconds(ex.reps) ?? DEFAULT_SECONDS : null,
|
||||
done: Array(ex.sets).fill(null),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../domain/program.js").ProgramSession} session
|
||||
* @param {import("../domain/state.js").State} state
|
||||
* @param {string} date
|
||||
* @param {number} warmupSteps
|
||||
* @returns {Draft}
|
||||
*/
|
||||
export function createDraft(session, state, date, warmupSteps) {
|
||||
return {
|
||||
sessionKey: session.key,
|
||||
name: session.name,
|
||||
date,
|
||||
warmup: Array(warmupSteps).fill(false),
|
||||
exercises: session.exercises.map((item) => draftExercise(session.key, item, state)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Un brouillon gardé (rechargement de la page, téléphone verrouillé) est repris
|
||||
* s'il porte sur la même séance du programme, avec les mêmes exercices.
|
||||
* @param {unknown} draft
|
||||
* @param {import("../domain/program.js").ProgramSession} session
|
||||
* @param {number} warmupSteps
|
||||
* @returns {draft is Draft}
|
||||
*/
|
||||
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) => {
|
||||
const ex = resolveExercise(item);
|
||||
const x = d.exercises[i];
|
||||
return x && x.id === ex.id && Array.isArray(x.done) && x.done.length === ex.sets;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Objectif lisible : « 4 × 8 », « 3 × 40 s ».
|
||||
* @param {DraftExercise} ex
|
||||
*/
|
||||
export function targetLabel(ex) {
|
||||
return usesTime(ex.tracking) ? `${ex.sets} × ${ex.seconds ?? DEFAULT_SECONDS} s` : `${ex.sets} × ${ex.reps}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fourchette de répétitions d'un objectif : « 6–8 » → {low: 6, high: 8}. Null si
|
||||
* l'objectif est un temps ou n'a pas de nombre.
|
||||
* @param {string} reps
|
||||
* @returns {{low: number, high: number}|null}
|
||||
*/
|
||||
export function targetReps(reps) {
|
||||
if (targetSeconds(reps) !== null) return null;
|
||||
const m = /(\d+)\s*(?:[–-]\s*(\d+))?/.exec(reps || "");
|
||||
if (!m) return null;
|
||||
const low = Number(m[1]);
|
||||
return { low, high: m[2] ? Number(m[2]) : low };
|
||||
}
|
||||
|
||||
/**
|
||||
* Répétitions proposées pour une série : celles de la série précédente faite,
|
||||
* sinon le haut de la fourchette.
|
||||
* @param {DraftExercise} ex
|
||||
* @param {number} index
|
||||
*/
|
||||
export function proposedReps(ex, index) {
|
||||
for (let i = index - 1; i >= 0; i--) {
|
||||
const reps = ex.done[i]?.reps;
|
||||
if (typeof reps === "number") return reps;
|
||||
}
|
||||
return targetReps(ex.reps)?.high ?? 0;
|
||||
}
|
||||
|
||||
/** @param {DraftExercise} ex */
|
||||
export const doneCount = (ex) => ex.done.filter((s) => s !== null).length;
|
||||
|
||||
/**
|
||||
* Où en est la séance : exercices pas commencés et incomplets.
|
||||
* @param {Draft} draft
|
||||
*/
|
||||
export function completion(draft) {
|
||||
const doneSets = draft.exercises.reduce((n, ex) => n + doneCount(ex), 0);
|
||||
const missing = draft.exercises.filter((ex) => doneCount(ex) === 0).map((ex) => ex.name);
|
||||
const partial = draft.exercises.filter((ex) => doneCount(ex) > 0 && doneCount(ex) < ex.sets).map((ex) => ex.name);
|
||||
return { doneSets, missing, partial, complete: missing.length === 0 && partial.length === 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Le contenu du SessionLogged (docs/evenements.md). Tous les exercices
|
||||
* prévus y figurent, avec leurs seules séries faites : un exercice sauté garde
|
||||
* `sets: []`, ce qui reste visible dans l'historique et les analyses.
|
||||
* @param {Draft} draft
|
||||
* @returns {SessionData}
|
||||
*/
|
||||
export function buildSessionData(draft) {
|
||||
return {
|
||||
date: draft.date,
|
||||
kind: "strength",
|
||||
ref: draft.sessionKey,
|
||||
name: draft.name,
|
||||
warmup: draft.warmup.length ? { done: draft.warmup.filter(Boolean).length, total: draft.warmup.length } : null,
|
||||
exercises: draft.exercises.map((ex) => ({
|
||||
id: ex.id,
|
||||
name: ex.name,
|
||||
target: targetLabel(ex),
|
||||
tracking: ex.tracking,
|
||||
loadKg: usesLoad(ex.tracking) ? ex.loadKg : null,
|
||||
seconds: usesTime(ex.tracking) ? ex.seconds : null,
|
||||
plannedSets: ex.sets,
|
||||
sets: /** @type {LoggedSet[]} */ (ex.done.filter((s) => s !== null)).map((s) => ({ reps: s.reps, effort: s.effort })),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Le contenu d'une séance enregistrée, sans ce que le repli ajoute (id,
|
||||
* loggedAt) : la base d'un SessionCorrected.
|
||||
* @param {import("../domain/state.js").LoggedSession} logged
|
||||
* @returns {SessionData}
|
||||
*/
|
||||
export function sessionDataOf(logged) {
|
||||
const { id: _id, loggedAt: _at, ...data } = structuredClone(logged);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Résumé d'une séance enregistrée : « 5 exercices · 17 séries ».
|
||||
* @param {SessionData} s
|
||||
*/
|
||||
export function sessionSummary(s) {
|
||||
const sets = s.exercises.reduce((n, x) => n + x.sets.length, 0);
|
||||
const done = s.exercises.filter((x) => x.sets.length > 0).length;
|
||||
if (s.kind !== "strength") return "";
|
||||
return `${done} exercice${done > 1 ? "s" : ""} · ${sets} série${sets > 1 ? "s" : ""}`;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Le magasin de l'interface : il tient le journal (les événements), l'appareil
|
||||
// et l'état replié. Chaque intention passe par dispatch, qui crée UN événement
|
||||
// métier validé, l'ajoute au journal, recalcule l'état et prévient les abonnés.
|
||||
// Sans DOM : testé sous Node (tests/ui/store.test.js).
|
||||
//
|
||||
// À brancher : event-store.js (app/infra/, stockage IndexedDB, autre sous-agent).
|
||||
// Le journal vit pour l'instant en mémoire : il est perdu au rechargement.
|
||||
|
||||
import { createEvent } from "../domain/events.js";
|
||||
import { foldEvents } from "../domain/state.js";
|
||||
import { randomId } from "../domain/ids.js";
|
||||
|
||||
/** @typedef {import("../domain/events.js").DomainEvent} DomainEvent */
|
||||
/** @typedef {import("../domain/events.js").EventType} EventType */
|
||||
/** @typedef {import("../domain/state.js").State} State */
|
||||
|
||||
/**
|
||||
* @typedef {object} Store
|
||||
* @property {string} device
|
||||
* @property {() => State} getState
|
||||
* @property {() => readonly DomainEvent[]} getEvents
|
||||
* @property {<T extends EventType>(type: T, data: Extract<DomainEvent, {type: T}>["data"]) => Extract<DomainEvent, {type: T}>} dispatch
|
||||
* @property {(events: DomainEvent[]) => void} load remplace le journal (au démarrage)
|
||||
* @property {(fn: (state: State) => void) => () => void} subscribe renvoie de quoi se désabonner
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {{events?: DomainEvent[], device?: string, onAppend?: (event: DomainEvent) => void}} [options]
|
||||
* onAppend : appelé pour chaque événement créé (persistance, à brancher)
|
||||
* @returns {Store}
|
||||
*/
|
||||
export function createStore(options = {}) {
|
||||
// Provisoire : l'identifiant d'appareil sera gardé par event-store.js.
|
||||
const device = options.device ?? "browser-" + randomId();
|
||||
/** @type {DomainEvent[]} */
|
||||
let events = [...(options.events ?? [])];
|
||||
let state = foldEvents(events);
|
||||
/** @type {Set<(state: State) => void>} */
|
||||
const listeners = new Set();
|
||||
const notify = () => { for (const fn of [...listeners]) fn(state); };
|
||||
|
||||
return {
|
||||
device,
|
||||
getState: () => state,
|
||||
getEvents: () => events,
|
||||
dispatch(type, data) {
|
||||
const event = createEvent(type, /** @type {any} */ (data), { device });
|
||||
events = [...events, event];
|
||||
state = foldEvents(events);
|
||||
options.onAppend?.(event);
|
||||
notify();
|
||||
return event;
|
||||
},
|
||||
load(list) {
|
||||
events = [...list];
|
||||
state = foldEvents(events);
|
||||
notify();
|
||||
},
|
||||
subscribe(fn) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user