Files
ia-fit/app/ui/screens/library.js
T
Pierre MARTINandClaude Opus 5.5 be3e820b88 Bibliothèque consultable (lot 3a), arbitrages du lot 4
Écran #/bibliotheque : recherche, filtres zone, muscle, famille et matériel
dans l'adresse (nav.set), fiche avec place dans le programme, exercices
proches et « Demander à mon IA » ; exercices génériques. #import-json=
devient un fragment réservé. Plan du lot 4 (WOD).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:20:47 +01:00

185 lines
10 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 { 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";
/** @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 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(href.library(formatCriteria(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);
replace(filters,
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);
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 ? []
: 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);
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 }) => row(href.libraryItem(ref), exercise.name,
`${EQUIPMENT_LABELS[exercise.equipment]} · ${exercise.primary.map((m) => MUSCLES[m].name).join(", ")}`)))]),
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 node = h("div", { class: "screen" },
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." }),
h("div", { class: "field" }, h("label", { class: "field__label", for: "lib-q" }, "Rechercher"), search),
filters,
results);
return { node, title: "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))),
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, `${EQUIPMENT_LABELS[x.equipment]} · ${x.primary.map((m) => MUSCLES[m].name).join(", ")}`);
}))]);
return { node, title: name };
}
/** @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" })));
}