Files
ia-fit/app/ui/screens/weight.js
T

148 lines
9.0 KiB
JavaScript

// 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) };
}