É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:
co-authored by
Claude Opus 5.5
parent
077f2dc58d
commit
41d5e44daa
@@ -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)) };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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."),
|
||||
|
||||
@@ -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" };
|
||||
@@ -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) };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user