Domaine : tendance et repères du poids, import de pesées, export .ics
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
08b149ff0a
commit
8ca88e27d7
@@ -0,0 +1,182 @@
|
||||
// Export de la semaine au format iCalendar (.ics, RFC 5545), repris d'exportICS
|
||||
// d'Atelier. Corrige son identifiant d'événement : la même clé servait au cardio et
|
||||
// aux activités, et deux événements du même jour se confondaient dans l'agenda.
|
||||
|
||||
import { addDays } from "./dates.js";
|
||||
import { exerciseKey, resolveExercise, targetSeconds, trackingFor } from "./program.js";
|
||||
import { estimatedMinutes } from "./progression.js";
|
||||
import { slotRef, weekStatus } from "./planning.js";
|
||||
|
||||
/** @typedef {import("./state.js").State} State */
|
||||
/** @typedef {import("./planning.js").Slot} Slot */
|
||||
/** @typedef {import("./planning.js").WeekPlan} WeekPlan */
|
||||
|
||||
/** Libellés des zones, pour la description d'une activité. */
|
||||
const ZONE_LABELS = { cardio: "Cardio", lower: "Bas du corps", upper: "Haut du corps", core: "Tronc" };
|
||||
|
||||
/** Durées par défaut, en minutes. */
|
||||
const CARDIO_MINUTES = 50;
|
||||
const ACTIVITY_MINUTES = 90;
|
||||
|
||||
/** Échappe un texte (RFC 5545, 3.3.11). @param {string} text */
|
||||
export function icsEscape(text) {
|
||||
return String(text ?? "")
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/;/g, "\\;")
|
||||
.replace(/,/g, "\\,")
|
||||
.replace(/\r?\n/g, "\\n");
|
||||
}
|
||||
|
||||
/** @param {string} char */
|
||||
const byteLength = (char) => {
|
||||
const c = /** @type {number} */ (char.codePointAt(0));
|
||||
return c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
|
||||
};
|
||||
|
||||
/**
|
||||
* Plie une ligne de contenu : 75 octets au plus par ligne, et non 75 caractères
|
||||
* (un « é » en UTF-8 en fait deux). Les lignes de suite commencent par une espace,
|
||||
* comptée dans les 75 octets. Un caractère n'est jamais coupé.
|
||||
* @param {string} line
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function foldLine(line) {
|
||||
const out = [];
|
||||
let current = "";
|
||||
let size = 0;
|
||||
for (const char of line) {
|
||||
const n = byteLength(char);
|
||||
if (size + n > 75) {
|
||||
out.push(current);
|
||||
current = " ";
|
||||
size = 1;
|
||||
}
|
||||
current += char;
|
||||
size += n;
|
||||
}
|
||||
out.push(current);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** @param {number} n */
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
/** Horodatage UTC : 20261118T170500Z. @param {Date} d */
|
||||
function utcStamp(d) {
|
||||
return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Heure locale « flottante » (sans fuseau) : l'agenda la place à l'heure locale.
|
||||
* @param {string} date AAAA-MM-JJ
|
||||
* @param {number} minutes depuis minuit, éventuellement au-delà de 24 h
|
||||
*/
|
||||
function localStamp(date, minutes) {
|
||||
const day = addDays(date, Math.floor(minutes / 1440));
|
||||
const m = minutes % 1440;
|
||||
return `${day.replace(/-/g, "")}T${pad(Math.floor(m / 60))}${pad(m % 60)}00`;
|
||||
}
|
||||
|
||||
/** « 1 min 30 », « 45 s ». @param {number} s */
|
||||
function formatRest(s) {
|
||||
return s >= 60 ? `${Math.floor(s / 60)} min${s % 60 ? " " + (s % 60) : ""}` : `${s} s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifiant stable et unique d'un créneau : jour, nature et objet.
|
||||
* @param {Slot} slot
|
||||
*/
|
||||
export function slotUid(slot) {
|
||||
const what = slot.kind === "strength" ? slot.sessionKey : slot.kind === "cardio" ? slot.cardioIndex : slot.activityId;
|
||||
return `${slot.date}-${slot.kind}-${what}@ia-fit`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Titre, description et durée de l'événement d'un créneau.
|
||||
* @param {State} state
|
||||
* @param {Slot} slot
|
||||
* @returns {{title: string, description: string, minutes: number}|null}
|
||||
*/
|
||||
function describe(state, slot) {
|
||||
const program = /** @type {import("./program.js").Program|null} */ (state.program);
|
||||
if (!program) return null;
|
||||
if (slot.kind === "strength") {
|
||||
const session = program.sessions.find((s) => s.key === slot.sessionKey);
|
||||
if (!session) return null;
|
||||
const lines = session.exercises.map((item, j) => {
|
||||
const ex = resolveExercise(item);
|
||||
const key = exerciseKey(session.key, item);
|
||||
const mode = trackingFor(item, state.trackingOverrides[key]);
|
||||
const saved = state.workingLoads[key];
|
||||
let target;
|
||||
if (mode === "time" || mode === "time+load") {
|
||||
const seconds = saved?.seconds ?? targetSeconds(ex.reps) ?? 45;
|
||||
target = `${ex.sets} × ${seconds} s` + (mode === "time+load" && saved?.loadKg ? ` à ${saved.loadKg} kg` : "");
|
||||
} else {
|
||||
target = `${ex.sets} × ${ex.reps}` + (mode === "load" ? (saved?.loadKg ? ` à ${saved.loadKg} kg` : " — charge à définir") : "");
|
||||
}
|
||||
return `${j + 1}. ${ex.name} — ${target} (repos ${formatRest(ex.rest)})`;
|
||||
});
|
||||
return {
|
||||
title: `Séance ${session.key} — ${session.name}`,
|
||||
description: [session.subtitle ?? "", "", ...lines].join("\n").trim(),
|
||||
minutes: estimatedMinutes(session),
|
||||
};
|
||||
}
|
||||
if (slot.kind === "activity") {
|
||||
const activity = (program.activities ?? []).find((a) => a.id === slot.activityId);
|
||||
return {
|
||||
title: activity?.name ?? "Activité",
|
||||
description: activity ? "Sollicite : " + activity.zones.map((z) => ZONE_LABELS[z]).join(", ") + "." : "",
|
||||
minutes: activity?.minutes ?? ACTIVITY_MINUTES,
|
||||
};
|
||||
}
|
||||
const cardio = program.cardio?.[slot.cardioIndex ?? -1];
|
||||
return { title: "Cardio — " + slotRef(slot, program).ref, description: cardio?.text ?? "", minutes: CARDIO_MINUTES };
|
||||
}
|
||||
|
||||
/**
|
||||
* Créneaux d'une semaine à exporter : ni faits, ni marqués non faits.
|
||||
* @param {State} state
|
||||
* @param {WeekPlan} plan
|
||||
*/
|
||||
export function slotsToExport(state, plan) {
|
||||
const { bySlot } = weekStatus(state, plan);
|
||||
const skipped = new Set(state.skippedDays);
|
||||
return plan.slots.filter((s) => !bySlot.get(s)?.done && !skipped.has(s.date));
|
||||
}
|
||||
|
||||
/**
|
||||
* Le fichier .ics d'une semaine : un événement par créneau à faire, à l'heure
|
||||
* choisie, avec un rappel 30 minutes avant. Lignes séparées par CRLF et pliées à
|
||||
* 75 octets. Sans programme, un calendrier sans événement.
|
||||
* @param {State} state
|
||||
* @param {WeekPlan} plan
|
||||
* @param {{hour: number, minute: number, now: Date}} options `now` sert à l'horodatage DTSTAMP
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildIcs(state, plan, { hour, minute, now }) {
|
||||
const lines = [
|
||||
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//IA-Fit//Planning//FR",
|
||||
"CALSCALE:GREGORIAN", "METHOD:PUBLISH", ...foldLine("X-WR-CALNAME:" + icsEscape(/** @type {import("./program.js").Program|null} */ (state.program)?.name || "IA-Fit")),
|
||||
];
|
||||
const start = hour * 60 + minute;
|
||||
for (const slot of slotsToExport(state, plan)) {
|
||||
const event = describe(state, slot);
|
||||
if (!event) continue;
|
||||
lines.push(
|
||||
"BEGIN:VEVENT",
|
||||
"UID:" + slotUid(slot),
|
||||
"DTSTAMP:" + utcStamp(now),
|
||||
"DTSTART:" + localStamp(slot.date, start),
|
||||
"DTEND:" + localStamp(slot.date, start + event.minutes),
|
||||
...foldLine("SUMMARY:" + icsEscape(event.title)),
|
||||
...foldLine("DESCRIPTION:" + icsEscape(event.description)),
|
||||
"BEGIN:VALARM", "TRIGGER:-PT30M", "ACTION:DISPLAY",
|
||||
...foldLine("DESCRIPTION:" + icsEscape(event.title)),
|
||||
"END:VALARM", "END:VEVENT",
|
||||
);
|
||||
}
|
||||
lines.push("END:VCALENDAR");
|
||||
return lines.join("\r\n") + "\r\n";
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Poids corporel : tendance, repères et import en texte libre. Repris
|
||||
// d'analysePoids, jalonsPoids et importerPesees d'Atelier.
|
||||
|
||||
import { addDays, daysBetween } from "./dates.js";
|
||||
|
||||
/** @typedef {{date: string, kg: number}} Weighing */
|
||||
|
||||
/** @param {readonly Weighing[]} weights */
|
||||
const sorted = (weights) => [...weights].sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
|
||||
|
||||
/**
|
||||
* @typedef {object} WeightTrend
|
||||
* @property {number} kgPerWeek pente de la droite de régression, en kg par semaine
|
||||
* @property {string} from première pesée de la fenêtre
|
||||
* @property {string} to dernière pesée
|
||||
* @property {number} count pesées dans la fenêtre
|
||||
* @property {number|null} staleDays jours écoulés entre la dernière pesée et `today` (null sans `today`)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Tendance du poids par régression linéaire sur une fenêtre de `windowDays`
|
||||
* jours. La fenêtre part de la dernière pesée, pas d'aujourd'hui : après une
|
||||
* pause de pesées, la tendance reste celle des dernières semaines mesurées
|
||||
* (`staleDays` dit depuis quand). Il faut au moins deux pesées à des jours
|
||||
* différents dans la fenêtre.
|
||||
* @param {readonly Weighing[]} weights
|
||||
* @param {{windowDays?: number, today?: string}} [options]
|
||||
* @returns {WeightTrend|null}
|
||||
*/
|
||||
export function weightTrend(weights, { windowDays = 56, today } = {}) {
|
||||
const all = sorted(weights);
|
||||
if (all.length < 2) return null;
|
||||
const last = all[all.length - 1];
|
||||
const points = all.filter((w) => w.date >= addDays(last.date, -windowDays));
|
||||
const first = points[0];
|
||||
if (points.length < 2 || first.date === last.date) return null;
|
||||
const xs = points.map((w) => daysBetween(first.date, w.date));
|
||||
const ys = points.map((w) => w.kg);
|
||||
const mx = xs.reduce((a, b) => a + b, 0) / xs.length;
|
||||
const my = ys.reduce((a, b) => a + b, 0) / ys.length;
|
||||
let num = 0, den = 0;
|
||||
for (let i = 0; i < xs.length; i++) {
|
||||
num += (xs[i] - mx) * (ys[i] - my);
|
||||
den += (xs[i] - mx) ** 2;
|
||||
}
|
||||
return {
|
||||
kgPerWeek: den ? (num / den) * 7 : 0,
|
||||
from: first.date,
|
||||
to: last.date,
|
||||
count: points.length,
|
||||
staleDays: today ? Math.max(0, daysBetween(last.date, today)) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} WeightMilestones
|
||||
* @property {Weighing} current dernière pesée
|
||||
* @property {Weighing|null} lastBelow la dernière fois sous le poids actuel
|
||||
* @property {number|null} daysSinceLastBelow
|
||||
* @property {Weighing[]} below pesées antérieures sous le poids actuel, de la plus récente à la plus ancienne
|
||||
* @property {Weighing} minimum la plus basse (la plus ancienne à égalité)
|
||||
* @property {number} daysSinceMinimum
|
||||
*/
|
||||
|
||||
/**
|
||||
* Repères : depuis quand n'as-tu pas été aussi léger, et ton minimum. Les durées
|
||||
* se comptent depuis la dernière pesée. Il faut au moins deux pesées.
|
||||
* @param {readonly Weighing[]} weights
|
||||
* @returns {WeightMilestones|null}
|
||||
*/
|
||||
export function weightMilestones(weights) {
|
||||
const all = sorted(weights);
|
||||
if (all.length < 2) return null;
|
||||
const current = all[all.length - 1];
|
||||
const below = all.slice(0, -1).filter((w) => w.kg < current.kg).reverse();
|
||||
const minimum = all.reduce((a, b) => (b.kg < a.kg ? b : a));
|
||||
const lastBelow = below[0] ?? null;
|
||||
return {
|
||||
current,
|
||||
lastBelow,
|
||||
daysSinceLastBelow: lastBelow ? daysBetween(lastBelow.date, current.date) : null,
|
||||
below,
|
||||
minimum,
|
||||
daysSinceMinimum: daysBetween(minimum.date, current.date),
|
||||
};
|
||||
}
|
||||
|
||||
const LINE = /^(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})\s*[,;\t ]\s*(\d+(?:[.,]\d+)?)/;
|
||||
|
||||
/**
|
||||
* Import souple : une pesée par ligne, une date (AAAA-MM-JJ ou JJ/MM/AAAA, avec
|
||||
* « / » ou « . », année sur deux chiffres admise) puis un poids (virgule ou
|
||||
* point décimal), séparés par une espace, une tabulation, « ; » ou « , ».
|
||||
* Les lignes vides sont ignorées ; les autres lignes illisibles, aux dates
|
||||
* impossibles ou au poids hors de 20 à 400 kg sont rendues dans `rejected`.
|
||||
* @param {string} text
|
||||
* @returns {{entries: Weighing[], rejected: string[]}}
|
||||
*/
|
||||
export function parseWeightLines(text) {
|
||||
/** @type {Weighing[]} */
|
||||
const entries = [];
|
||||
/** @type {string[]} */
|
||||
const rejected = [];
|
||||
for (const line of String(text ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) {
|
||||
const m = LINE.exec(line);
|
||||
const date = m ? normalizeDate(m[1]) : null;
|
||||
const kg = m ? Number(m[2].replace(",", ".")) : NaN;
|
||||
if (!date || !(kg >= 20 && kg <= 400)) rejected.push(line);
|
||||
else entries.push({ date, kg });
|
||||
}
|
||||
return { entries, rejected };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} raw AAAA-MM-JJ ou JJ/MM/AAAA
|
||||
* @returns {string|null} AAAA-MM-JJ, ou null si la date n'existe pas
|
||||
*/
|
||||
function normalizeDate(raw) {
|
||||
let iso = raw;
|
||||
if (!raw.includes("-")) {
|
||||
const [d, m, y] = raw.split(/[/.]/);
|
||||
if (y.length === 3) return null;
|
||||
iso = `${y.length === 2 ? "20" + y : y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
|
||||
}
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
const check = new Date(Date.UTC(y, m - 1, d));
|
||||
return check.getUTCFullYear() === y && check.getUTCMonth() === m - 1 && check.getUTCDate() === d ? iso : null;
|
||||
}
|
||||
Reference in New Issue
Block a user