Files
ia-fit/app/ui/exercise-card.js

253 lines
12 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Carte d'un exercice dans la séance : consignes, tutoriel, charge, séries.
//
// Piège d'Atelier (docs/lot-1.md) : ne jamais reconstruire une zone qui contient
// un champ en cours de saisie. Ici, une frappe ne met à jour que des libellés
// (refreshLabels) ; la zone de saisie n'est reconstruite (drawWork) que lorsque le
// mode de suivi change, par un bouton, donc sans champ actif.
import { h, replace } from "./dom.js";
import { MUSCLES, EXERCISES } from "../domain/exercises.js";
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";
/**
* @typedef {object} ExerciseCardOptions
* @property {import("./session-draft.js").DraftExercise} ex exercice du brouillon (modifié sur place)
* @property {import("../domain/program.js").ProgramExercise} item
* @property {string} sessionKey
* @property {string} number « 3 »
* @property {string|null} letter « A » dans un superset
* @property {boolean} open
* @property {import("./store.js").Store} store
* @property {import("./timer.js").Timer} timer
* @property {() => void} onChange le brouillon a changé (à garder, compteur de séries)
*/
/** @param {ExerciseCardOptions} o */
export function exerciseCard(o) {
const { ex, item, store, timer } = o;
const resolved = resolveExercise(item);
const library = item.ref ? EXERCISES[item.ref] ?? null : null;
const sub = h("span", { class: "exercise__sub" });
const count = h("span", { class: "exercise__count" });
const objective = h("span", { class: "objective__value" });
const work = h("div", { class: "work" });
const tracking = h("div", { class: "segmented", role: "group", "aria-label": "Ce que je suis" });
const refreshLabels = () => {
const load = usesLoad(ex.tracking) && ex.loadKg !== null ? ` · ${kg(ex.loadKg)} kg` : "";
sub.textContent = `${targetLabel(ex)}${load} · repos ${restLabel(ex.rest)}`;
count.textContent = `${doneCount(ex)}/${ex.sets}`;
count.classList.toggle("exercise__count--done", doneCount(ex) === ex.sets);
objective.textContent = targetLabel(ex);
};
const changed = () => {
refreshLabels();
o.onChange();
};
// ---- séries ----------------------------------------------------------------
/** @type {HTMLButtonElement[]} */
let setButtons = [];
const panelSlot = h("div", { class: "work__panel" });
/** @type {number|null} */
let openPanel = null;
/** @type {HTMLButtonElement|null} */
let chronoBtn = 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) : "✓";
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(", ");
b.setAttribute("aria-label", `Série ${i + 1} : ${what}`);
b.setAttribute("aria-expanded", String(openPanel === i));
});
};
const closePanel = () => {
openPanel = null;
panelSlot.replaceChildren();
paintSets();
};
/** @param {number} i */
const showPanel = (i) => {
if (openPanel === i) return closePanel();
openPanel = i;
const existing = ex.done[i];
const timed = usesTime(ex.tracking);
let reps = typeof existing?.reps === "number" ? existing.reps : proposedReps(ex, i);
const range = targetReps(ex.reps);
const value = h("output", { class: "stepper__value", "aria-live": "polite" }, String(reps));
const step = (/** @type {number} */ d) => { reps = Math.max(0, reps + d); value.textContent = String(reps); };
const panel = h("div", { class: "set-panel", role: "group", "aria-label": `Série ${i + 1}` },
h("p", { class: "set-panel__title" }, `Série ${i + 1}`,
timed ? ` · ${ex.seconds} s` : range ? ` · objectif ${range.low === range.high ? range.low : range.low + "–" + range.high} répétitions` : ""),
!timed && h("div", { class: "stepper" },
h("button", { type: "button", class: "stepper__btn", "aria-label": "Une répétition de moins", on: { click: () => step(-1) } }, "−"),
value,
h("button", { type: "button", class: "stepper__btn", "aria-label": "Une répétition de plus", on: { click: () => step(1) } }, "+"),
h("span", { class: "stepper__unit" }, "répétitions")),
h("p", { class: "set-panel__ask" }, "Ressenti ?"),
h("div", { class: "effort-picker" }, EFFORTS.map((effort) =>
h("button", {
type: "button", class: "effort", data: { effort },
"aria-pressed": String(existing?.effort === effort),
on: { click: () => {
ex.done[i] = { reps: timed ? null : reps, effort };
closePanel();
changed();
// Le repos démarre au ressenti.
if (ex.rest > 0) timer.startRest(ex.rest, `Repos · ${ex.name}`);
} },
}, h("span", { class: "effort__label" }, EFFORT_LABELS[effort].label), h("span", { class: "effort__hint" }, EFFORT_LABELS[effort].hint)))),
existing && h("button", {
type: "button", class: "btn btn--ghost btn--block btn--sm",
on: { click: () => { ex.done[i] = null; closePanel(); changed(); } },
}, "Annuler cette série"));
panelSlot.replaceChildren(panel);
paintSets();
};
const startChrono = () => {
const i = ex.done.findIndex((s) => s === null);
if (i < 0) {
if (chronoBtn) chronoBtn.textContent = "Toutes les séries sont faites";
return;
}
const seconds = ex.seconds ?? 45;
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 };
changed();
openPanel = null;
showPanel(i);
});
};
const refreshChrono = () => {
if (chronoBtn) chronoBtn.textContent = `Lancer la série · ${ex.seconds ?? 45} s`;
};
/**
* Champ de charge ou de durée. La frappe ne change que le brouillon et les
* libellés ; la charge de travail (WorkingLoadSet) est enregistrée à la
* validation du champ (événement change : sortie du champ ou touche Entrée).
* @param {"loadKg"|"seconds"} field
*/
const amountField = (field) => {
const isLoad = field === "loadKg";
const id = `f-${o.sessionKey}-${o.number}-${field}`;
const input = h("input", {
id, class: "field__input", type: "text", inputmode: "decimal", autocomplete: "off",
placeholder: "—", value: ex[field] === null ? "" : kg(/** @type {number} */ (ex[field])),
});
input.addEventListener("input", () => {
const v = parseAmount(input.value);
input.setAttribute("aria-invalid", String(v === undefined || (field === "seconds" && v === 0)));
if (v === undefined) return;
ex[field] = field === "seconds" && !v ? null : v;
refreshLabels();
refreshChrono();
o.onChange();
});
input.addEventListener("change", () => {
const v = parseAmount(input.value);
if (v === undefined || (field === "seconds" && !v)) return;
const saved = store.getState().workingLoads[ex.key]?.[field] ?? null;
if (saved !== v) store.dispatch("WorkingLoadSet", isLoad ? { key: ex.key, loadKg: v } : { key: ex.key, seconds: v });
});
return h("div", { class: "field field--amount" },
h("label", { class: "field__label", for: id }, isLoad ? "Charge" : "Durée"),
input,
h("span", { class: "field__unit" }, isLoad ? "kg" : "s"));
};
const drawWork = () => {
openPanel = null;
chronoBtn = 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" },
usesTime(ex.tracking) && amountField("seconds"),
usesLoad(ex.tracking) && amountField("loadKg"),
ex.tracking === "none" && h("p", { class: "muted" }, "Poids du corps : rien à saisir."));
if (usesTime(ex.tracking))
chronoBtn = h("button", { type: "button", class: "btn btn--block btn--work", on: { click: startChrono } });
replace(work,
fields,
h("div", { class: "set-row", role: "group", "aria-label": "Séries" }, setButtons),
panelSlot,
chronoBtn);
panelSlot.replaceChildren();
paintSets();
refreshChrono();
drawTracking();
};
const drawTracking = () => {
replace(tracking, TRACKING_MODES.map((mode) =>
h("button", {
type: "button", class: "segmented__opt", "aria-pressed": String(mode === ex.tracking),
on: { click: () => {
if (mode === ex.tracking) return;
const programMode = trackingFor(item, undefined);
store.dispatch("TrackingModeSet", { key: ex.key, mode: mode === programMode ? null : mode });
const fresh = draftExercise(o.sessionKey, item, store.getState());
ex.tracking = fresh.tracking;
ex.loadKg = fresh.loadKg;
ex.seconds = fresh.seconds;
drawWork();
changed();
/** @type {HTMLElement|null} */ (tracking.querySelector("[aria-pressed=true]"))?.focus();
} },
}, TRACKING_LABELS[mode])));
};
// ---- consignes ---------------------------------------------------------------
const muscles = library
? h("ul", { class: "chips", "aria-label": "Muscles sollicités" },
library.primary.map((m) => h("li", { class: "chip" }, MUSCLES[m]?.name ?? m)),
library.secondary.map((m) => h("li", { class: "chip chip--secondary" }, MUSCLES[m]?.name ?? m)))
: null;
const card = h("details", { class: "exercise", open: o.open },
h("summary", { class: "exercise__head" },
h("span", { class: "badge", "aria-hidden": "true" }, o.number),
h("span", { class: "exercise__name" },
h("strong", null, o.letter && h("span", { class: "tag" }, o.letter), resolved.name),
sub),
count,
h("span", { class: "chevron", "aria-hidden": "true" })),
h("div", { class: "exercise__body" },
resolved.note && h("p", { class: "coach-note" }, resolved.note),
muscles,
resolved.cues.length > 0 && [h("h3", { class: "mini-label" }, "Le geste"),
h("ul", { class: "cues" }, resolved.cues.map((c) => h("li", null, c)))],
resolved.mistakes.length > 0 && [h("h3", { class: "mini-label" }, "À éviter"),
h("ul", { class: "mistakes" }, resolved.mistakes.map((c) => h("li", null, c)))],
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.
work,
h("div", { class: "tracking" }, h("span", { class: "mini-label" }, "Je suis"), tracking)));
drawWork();
refreshLabels();
return card;
}