// 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}} 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} */ const ACTION_LABELS = { done: "Faite", skip: "Non fait", unskip: "Annuler", remove: "Retirer" };