Files

261 lines
14 KiB
JavaScript

// La bibliothèque consultable (lot 3a) : la liste par famille, avec recherche et
// filtres dans l'adresse (ADR 0009), et la fiche d'un exercice. Calculs du
// domaine : domain/library.js.
import { KIT, canDo, missingKit, requiredKit } from "../../domain/kit.js";
import { h, replace } from "../dom.js";
import { EXERCISES, FAMILIES, MUSCLES } from "../../domain/exercises.js";
import { resolveExercise } from "../../domain/program.js";
import {
EQUIPMENT_GROUPS, ZONE_LABELS, exerciseRequest, filterLibrary, fold, formatCriteria, genericExercises,
parseCriteria, similarExercises, usage,
} from "../../domain/library.js";
import { ZONES } from "../../domain/vocabulary.js";
import { kg, plural, shortDay } from "../format.js";
import { screenHeader } from "../layout.js";
import { href } from "../router.js";
import { copyText } from "../files.js";
import { toast } from "../feedback.js";
import { doneCount, draftMatches, parseReplace, replaceExercise, replaceQuery } from "../session-draft.js";
import { loadDraft, markReopen, saveDraft } from "../draft-storage.js";
/** @typedef {import("../../domain/library.js").LibraryCriteria} LibraryCriteria */
/** Matériel affiché sur une fiche. */
const EQUIPMENT_LABELS = {
barbell: "Barre", dumbbell: "Un haltère", dumbbells: "Deux haltères", kettlebell: "Kettlebell",
machine: "Machine guidée", cable: "Poulie", band: "Élastique", bodyweight: "Poids du corps",
"cardio-machine": "Machine de cardio", other: "Petit matériel",
};
/**
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, query: string}} ctx
* @returns {import("../router.js").Screen}
*/
export function libraryScreen({ store, nav, query }) {
/** @type {LibraryCriteria} */
let criteria = parseCriteria(query);
const total = Object.keys(EXERCISES).length;
const pick = pickContext(store.getState(), query);
// Le mode choix reste dans l'adresse quand les filtres changent (ADR 0009).
const listHref = (/** @type {LibraryCriteria} */ c) =>
href.library([pick ? replaceQuery(pick.sessionKey, pick.index) : "", formatCriteria(c)].filter(Boolean).join("&"));
/** @param {string} ref */
const choose = (ref) => {
if (!pick) return;
replaceExercise(pick.draft, pick.index, ref, pick.item, store.getState());
saveDraft(pick.draft);
markReopen(pick.index);
nav.back(href.session(pick.sessionKey));
};
/** @param {string} ref @param {string} title @param {string} meta */
const entry = (ref, title, meta) => pick
? h("li", null, h("button", { type: "button", class: "row", on: { click: () => choose(ref) } },
h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), h("span", { class: "row__meta" }, meta)),
h("span", { class: "mark" }, "Choisir")))
: row(href.libraryItem(ref), title, meta);
const search = h("input", {
class: "field__input", type: "search", id: "lib-q", placeholder: "squat, développé, pont…",
autocomplete: "off", enterkeyhint: "search", value: criteria.q ?? "",
});
const filters = h("div", { class: "lib-filters" });
const results = h("div", { class: "lib-results", "aria-live": "polite" });
/** @param {LibraryCriteria} next */
const update = (next) => {
criteria = parseCriteria(formatCriteria(next)); // mêmes règles qu'à la lecture
nav.set(listHref(criteria));
paint();
};
/**
* Groupe de boutons exclusifs ; toucher l'option active la retire.
* @param {string} label @param {[string, string][]} options @param {string|undefined} current
* @param {(v: string|undefined) => void} pick
*/
const segmented = (label, options, current, pick) =>
h("div", { class: "segmented segmented--wrap", role: "group", "aria-label": label },
options.map(([value, text]) => h("button", {
type: "button", class: "segmented__opt", "aria-pressed": String(current === value),
on: { click: () => pick(current === value ? undefined : value) },
}, text)));
const paint = () => {
const c = criteria;
const muscles = c.zone ? Object.entries(MUSCLES).filter(([, m]) => m.zone === c.zone) : [];
const more = !!(c.family || c.equipment);
const kit = store.getState().profile.kit;
replace(filters,
// Le matériel coché du profil (lot 5a) : un seul geste pour ne voir que le faisable.
kit && h("button", {
type: "button", class: "choice lib-possible", "aria-pressed": String(!!c.possible),
on: { click: () => update({ ...c, possible: !c.possible || undefined }) },
}, "Seulement ce que mon matériel permet"),
h("p", { class: "mini-label" }, "Zone"),
segmented("Zone", ZONES.map((z) => [z, ZONE_LABELS[z]]), c.zone, (zone) => update({ ...c, zone: /** @type {any} */ (zone), muscle: undefined })),
muscles.length > 1 && [
h("p", { class: "mini-label" }, "Muscle"),
segmented("Muscle", muscles.map(([k, m]) => [k, m.name]), c.muscle, (muscle) => update({ ...c, muscle }))],
h("details", { class: "lib-more", open: more },
h("summary", null, "Famille et matériel"),
h("p", { class: "mini-label" }, "Famille"),
segmented("Famille", Object.entries(FAMILIES).map(([k, v]) => [k, v.split(/[ :,]/)[0]]), c.family, (family) => update({ ...c, family: /** @type {any} */ (family) })),
h("p", { class: "mini-label" }, "Matériel"),
segmented("Matériel", Object.entries(EQUIPMENT_GROUPS).map(([k, v]) => [k, v.label]), c.equipment, (equipment) => update({ ...c, equipment: /** @type {any} */ (equipment) }))));
const groups = filterLibrary(c, kit);
const count = groups.reduce((n, g) => n + g.items.length, 0);
// Les exercices génériques n'ont pas de muscles : ils ne suivent que la recherche.
const words = c.q ? fold(c.q).split(/\s+/).filter(Boolean) : [];
const generic = c.zone || c.muscle || c.family || c.equipment || c.possible ? []
: genericExercises(store.getState()).filter((x) => words.every((w) => fold(x.name).includes(w)));
const filtered = !!(c.q || c.zone || c.muscle || c.family || c.equipment || c.possible);
replace(results,
h("p", { class: "lib-count" }, filtered ? `${plural(count, "exercice")} sur ${total}` : `${total} exercices`,
filtered && h("button", { type: "button", class: "btn btn--ghost btn--sm", on: { click: () => { search.value = ""; update({}); } } }, "Tout effacer")),
count === 0 && generic.length === 0 && h("p", { class: "coach-note coach-note--plain" }, "Aucun exercice ne répond à ces critères. Retire un filtre, ou décris l'exercice à ton IA : elle peut l'ajouter comme exercice générique."),
groups.map((g) => [
h("h2", { class: "tape" }, g.label, h("span", { class: "tape__hint" }, String(g.items.length))),
h("ul", { class: "rows" }, g.items.map(({ ref, exercise }) => entry(ref, exercise.name, metaOf(exercise))))]),
!pick && generic.length > 0 && [
h("h2", { class: "tape" }, "Mes exercices", h("span", { class: "tape__hint" }, "hors bibliothèque")),
h("ul", { class: "rows" }, generic.map((x) => row(href.libraryItem(x.id), x.name, "Exercice générique de ton programme")))]);
};
let typing = 0;
search.addEventListener("input", () => {
clearTimeout(typing);
typing = window.setTimeout(() => update({ ...criteria, q: search.value }), 150);
});
paint();
const near = pick ? [
...(pick.planned.id !== pick.currentId && EXERCISES[pick.planned.id] ? [pick.planned.id] : []),
// Ni un exercice déjà dans la séance (un doublon), ni un que le matériel coché ne permet pas.
...similarExercises(pick.planned.id, 16)
.filter((r) => !pick.draft.exercises.some((x) => x.id === r) && canDo(r, store.getState().profile.kit)).slice(0, 8),
] : [];
const node = h("div", { class: "screen" },
pick
? screenHeader({ back: { label: `Séance ${pick.sessionKey}`, onClick: () => nav.back(href.session(pick.sessionKey)) },
kicker: `Séance ${pick.sessionKey} · exercice ${pick.index + 1}`, title: "Remplacer",
sub: `« ${pick.planned.name} » : choisis un exercice pour cette séance seulement. Séries, répétitions et repos restent ceux du programme.` })
: screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Exercices", title: "Bibliothèque",
sub: "Le geste, les erreurs à éviter et un tutoriel pour chaque exercice." }),
near.length > 0 && [
h("h2", { class: "tape" }, "Proches", h("span", { class: "tape__hint" }, "mêmes muscles")),
h("ul", { class: "rows" }, near.map((ref) => entry(ref, EXERCISES[ref].name + (ref === pick?.planned.id ? " (prévu)" : ""), metaOf(EXERCISES[ref]))))],
pick && h("h2", { class: "tape" }, "Toute la bibliothèque"),
h("div", { class: "field" }, h("label", { class: "field__label", for: "lib-q" }, "Rechercher"), search),
filters,
results);
return { node, title: pick ? "Remplacer un exercice" : "Bibliothèque", destroy: () => clearTimeout(typing) };
}
/**
* La fiche d'un exercice : de la bibliothèque (par sa ref) ou générique (par son nom).
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string, id: string}} ctx
* @returns {import("../router.js").Screen}
*/
export function libraryItemScreen({ store, nav, today, id }) {
const state = store.getState();
const library = EXERCISES[id] ?? null;
const generic = library ? null : genericExercises(state).find((x) => x.id === id) ?? null;
const back = { label: "Bibliothèque", onClick: () => nav.back(href.library()) };
if (!library && !generic) {
return {
title: "Exercice introuvable",
node: h("div", { class: "screen" }, screenHeader({ back, title: "Introuvable", sub: "Cet exercice n'est ni dans la bibliothèque, ni dans ton programme." })),
};
}
const r = library ? resolveExercise({ ref: id, sets: 1, reps: "", rest: 0 }) : null;
const name = library?.name ?? /** @type {NonNullable<typeof generic>} */ (generic).name;
const cues = r?.cues ?? generic?.cues ?? [];
const mistakes = r?.mistakes ?? generic?.mistakes ?? [];
const tutorial = r?.tutorial ?? generic?.tutorial ?? "";
const use = usage(state, id);
const near = library ? similarExercises(id) : [];
const fallback = h("div", { class: "manual-copy", hidden: true });
const ask = async () => {
const text = exerciseRequest(state, id, { today: today(), baseUrl: location.origin });
if (await copyText(text, fallback, "Texte pour ton IA")) toast("Texte copié : colle-le dans ton IA.");
};
const node = h("div", { class: "screen" },
screenHeader({ back, kicker: library ? FAMILIES[library.family].split(/[:,]/)[0] : "Exercice générique", title: name,
sub: library ? EQUIPMENT_LABELS[library.equipment] : "Hors bibliothèque, venu de ton programme." }),
library && h("ul", { class: "chips", "aria-label": "Muscles" },
library.primary.map((m) => h("li", { class: "chip" }, MUSCLES[m].name)),
library.secondary.map((m) => h("li", { class: "chip chip--secondary" }, MUSCLES[m].name))),
library && kitLine(id, state.profile.kit),
h("h2", { class: "tape" }, "Dans ton programme"),
use.sessions.length
? h("ul", { class: "rows" }, use.sessions.map((s) => row(href.session(s.key), `Séance ${s.key} · ${s.name}`, s.target)))
: h("p", { class: "muted" }, "Il n'est dans aucune séance de ton programme."),
use.times > 0 && h("p", { class: "lib-usage" },
`Fait ${plural(use.times, "fois")}, la dernière le ${shortDay(/** @type {string} */ (use.lastDate))}`,
use.lastLoadKg ? ` à ${kg(use.lastLoadKg)} kg` : "",
use.bestLoadKg ? ` · record ${kg(use.bestLoadKg)} kg` : "", ". ",
h("a", { href: href.analysis(id) }, "Voir la progression")),
h("button", { type: "button", class: "btn btn--block", on: { click: () => void ask() } },
use.sessions.length ? "Demander à mon IA de l'ajuster" : "Demander à mon IA de l'intégrer"),
fallback,
cues.length > 0 && [h("h2", { class: "tape" }, "Le geste"), h("ul", { class: "cues" }, cues.map((c) => h("li", null, c)))],
mistakes.length > 0 && [h("h2", { class: "tape" }, "À éviter"), h("ul", { class: "mistakes" }, mistakes.map((c) => h("li", null, c)))],
tutorial && h("p", null, h("a", { class: "btn btn--ghost btn--sm tutorial", href: tutorial, target: "_blank", rel: "noopener noreferrer" }, "Voir un tutoriel ↗")),
near.length > 0 && [
h("h2", { class: "tape" }, "Exercices proches"),
h("ul", { class: "rows" }, near.map((ref) => {
const x = EXERCISES[ref];
return row(href.libraryItem(ref), x.name, metaOf(x));
}))]);
return { node, title: name };
}
/**
* Le mode choix (« remplacer=A.3 ») : valable seulement si le brouillon gardé
* porte sur cette séance et que l'exercice n'a encore aucune série faite.
* @param {import("../../domain/state.js").State} state
* @param {string} query
*/
function pickContext(state, query) {
const target = parseReplace(query);
if (!target) return null;
const session = state.program?.sessions.find((s) => s.key === target.sessionKey);
const draft = /** @type {any} */ (loadDraft());
if (!session || !Array.isArray(draft?.warmup) || !draftMatches(draft, session, draft.warmup.length)) return null;
const ex = draft.exercises[target.index];
if (!ex || doneCount(ex) > 0) return null;
return {
...target, draft, item: session.exercises[target.index], currentId: ex.id,
planned: ex.replaces ?? { id: ex.id, name: ex.name },
};
}
/** Ligne d'une liste : matériel et muscles principaux. @param {import("../../domain/exercises.js").LibraryExercise} x */
/**
* Le matériel que demande l'exercice, et ce qui manque au profil (lot 5a).
* @param {string} ref @param {readonly string[]|undefined} kit
*/
function kitLine(ref, kit) {
const needs = requiredKit(ref);
if (!needs.length) return null;
const missing = missingKit(ref, kit);
return h("p", { class: "lib-kit" }, `Matériel : ${needs.map((k) => KIT[k]).join(", ")}.`,
missing.length > 0 && h("strong", null, ` Il te manque : ${missing.map((k) => KIT[k].toLowerCase()).join(", ")}.`));
}
const metaOf = (x) => `${EQUIPMENT_LABELS[x.equipment]} · ${x.primary.map((m) => MUSCLES[m].name).join(", ")}`;
/** @param {string} link @param {string} title @param {string} meta */
function row(link, title, meta) {
return h("li", null, h("a", { class: "row", href: link },
h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), h("span", { class: "row__meta" }, meta)),
h("span", { class: "chevron", "aria-hidden": "true" })));
}