183 lines
6.8 KiB
JavaScript
183 lines
6.8 KiB
JavaScript
// 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` + (ex.sides ? " / côté" : "") + (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";
|
||
}
|