From af92c021e2bba8e8565b7106a402a5e7d6eb94f6 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 01:04:40 +0100 Subject: [PATCH] =?UTF-8?q?=C3=89crans=20:=20onboarding,=20accueil,=20s?= =?UTF-8?q?=C3=A9ance=20guid=C3=A9e,=20minuteur,=20historique?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/main.js | 35 ++++++ app/ui/draft-storage.js | 33 +++++ app/ui/exercise-card.js | 252 ++++++++++++++++++++++++++++++++++++++ app/ui/feedback.js | 51 ++++++++ app/ui/layout.js | 42 +++++++ app/ui/onboarding.js | 99 +++++++++++++++ app/ui/pending.js | 41 +++++++ app/ui/proposal-card.js | 55 +++++++++ app/ui/screens/history.js | 149 ++++++++++++++++++++++ app/ui/screens/home.js | 112 +++++++++++++++++ app/ui/screens/session.js | 143 +++++++++++++++++++++ app/ui/timer.js | 120 ++++++++++++++++++ app/ui/warmup-card.js | 68 ++++++++++ 13 files changed, 1200 insertions(+) create mode 100644 app/main.js create mode 100644 app/ui/draft-storage.js create mode 100644 app/ui/exercise-card.js create mode 100644 app/ui/feedback.js create mode 100644 app/ui/layout.js create mode 100644 app/ui/onboarding.js create mode 100644 app/ui/pending.js create mode 100644 app/ui/proposal-card.js create mode 100644 app/ui/screens/history.js create mode 100644 app/ui/screens/home.js create mode 100644 app/ui/screens/session.js create mode 100644 app/ui/timer.js create mode 100644 app/ui/warmup-card.js diff --git a/app/main.js b/app/main.js new file mode 100644 index 0000000..7adc0df --- /dev/null +++ b/app/main.js @@ -0,0 +1,35 @@ +// Démarrage de l'app : le magasin, le minuteur, le routeur et ses écrans. + +import { createStore } from "./ui/store.js"; +import { startRouter } from "./ui/router.js"; +import { createTimer } from "./ui/timer.js"; +import { h } from "./ui/dom.js"; +import { screenHeader } from "./ui/layout.js"; +import { homeScreen } from "./ui/screens/home.js"; +import { sessionScreen } from "./ui/screens/session.js"; +import { historyEditScreen, historyScreen } from "./ui/screens/history.js"; + +// À brancher : event-store.js (app/infra/) : ouvrir la base IndexedDB, charger +// le journal (store.load) et l'identifiant d'appareil, puis enregistrer chaque +// événement créé (option onAppend de createStore). +export const store = createStore(); + +const timer = createTimer(); +document.body.append(timer.node); + +const root = /** @type {HTMLElement} */ (document.getElementById("app")); + +startRouter(root, (route, nav) => { + switch (route.name) { + case "session": return sessionScreen({ store, key: route.key, nav, timer }); + case "history": return historyScreen({ store, nav }); + case "history-edit": return historyEditScreen({ store, nav, id: route.id }); + case "not-found": + return { + title: "Page introuvable", + node: h("div", { class: "screen" }, + screenHeader({ back: { label: "Accueil", onClick: () => nav.go("#/") }, title: "Page introuvable", sub: "Cette adresse ne correspond à aucun écran." })), + }; + default: return homeScreen({ store }); + } +}); diff --git a/app/ui/draft-storage.js b/app/ui/draft-storage.js new file mode 100644 index 0000000..f3638c5 --- /dev/null +++ b/app/ui/draft-storage.js @@ -0,0 +1,33 @@ +// Le brouillon de la séance en cours est gardé dans le stockage local du +// navigateur : un rechargement de la page ou un téléphone mis en veille ne le +// perd pas. Ce n'est pas un événement (ADR 0006, point 3) : il ne se synchronise +// pas et disparaît quand la séance est terminée. + +const KEY = "ia-fit.draft"; + +/** @returns {unknown} */ +export function loadDraft() { + try { + const raw = localStorage.getItem(KEY); + return raw ? JSON.parse(raw) : null; + } catch { + return null; + } +} + +/** @param {import("./session-draft.js").Draft} draft */ +export function saveDraft(draft) { + try { + localStorage.setItem(KEY, JSON.stringify(draft)); + } catch { + // stockage plein ou interdit (navigation privée) : le brouillon reste en mémoire + } +} + +export function clearDraft() { + try { + localStorage.removeItem(KEY); + } catch { + // rien à effacer + } +} diff --git a/app/ui/exercise-card.js b/app/ui/exercise-card.js new file mode 100644 index 0000000..f2e76ce --- /dev/null +++ b/app/ui/exercise-card.js @@ -0,0 +1,252 @@ +// Carte d'un exercice dans la séance : consignes, tutoriel, charge, séries. +// +// Piège d'Atelier (docs/lot-1.md) : ne jamais reconstruire une zone qui contient +// un champ en cours de saisie. Ici, une frappe ne met à jour que des libellés +// (refreshLabels) ; la zone de saisie n'est reconstruite (drawWork) que lorsque le +// mode de suivi change, par un bouton, donc sans champ actif. + +import { h, replace } from "./dom.js"; +import { MUSCLES, EXERCISES } from "../domain/exercises.js"; +import { TRACKING_MODES, EFFORTS } from "../domain/vocabulary.js"; +import { resolveExercise, trackingFor } from "../domain/program.js"; +import { EFFORT_LABELS, TRACKING_LABELS } from "./labels.js"; +import { kg, parseAmount, restLabel } from "./format.js"; +import { doneCount, draftExercise, proposedReps, targetLabel, targetReps, usesLoad, usesTime } from "./session-draft.js"; + +/** + * @typedef {object} ExerciseCardOptions + * @property {import("./session-draft.js").DraftExercise} ex exercice du brouillon (modifié sur place) + * @property {import("../domain/program.js").ProgramExercise} item + * @property {string} sessionKey + * @property {string} number « 3 » + * @property {string|null} letter « A » dans un superset + * @property {boolean} open + * @property {import("./store.js").Store} store + * @property {import("./timer.js").Timer} timer + * @property {() => void} onChange le brouillon a changé (à garder, compteur de séries) + */ + +/** @param {ExerciseCardOptions} o */ +export function exerciseCard(o) { + const { ex, item, store, timer } = o; + const resolved = resolveExercise(item); + const library = item.ref ? EXERCISES[item.ref] ?? null : null; + + const sub = h("span", { class: "exercise__sub" }); + const count = h("span", { class: "exercise__count" }); + const objective = h("span", { class: "objective__value" }); + const work = h("div", { class: "work" }); + const tracking = h("div", { class: "segmented", role: "group", "aria-label": "Ce que je suis" }); + + const refreshLabels = () => { + const load = usesLoad(ex.tracking) && ex.loadKg !== null ? ` · ${kg(ex.loadKg)} kg` : ""; + sub.textContent = `${targetLabel(ex)}${load} · repos ${restLabel(ex.rest)}`; + count.textContent = `${doneCount(ex)}/${ex.sets}`; + count.classList.toggle("exercise__count--done", doneCount(ex) === ex.sets); + objective.textContent = targetLabel(ex); + }; + + const changed = () => { + refreshLabels(); + o.onChange(); + }; + + // ---- séries ---------------------------------------------------------------- + /** @type {HTMLButtonElement[]} */ + let setButtons = []; + const panelSlot = h("div", { class: "work__panel" }); + /** @type {number|null} */ + let openPanel = null; + /** @type {HTMLButtonElement|null} */ + let chronoBtn = null; + + const paintSets = () => { + setButtons.forEach((b, i) => { + const s = ex.done[i]; + b.classList.toggle("set-btn--done", s !== null); + b.dataset.effort = s?.effort ?? ""; + b.textContent = s === null ? String(i + 1) : typeof s.reps === "number" ? String(s.reps) : "✓"; + const what = s === null ? "à faire" + : [typeof s.reps === "number" ? `${s.reps} répétitions` : "faite", s.effort ? EFFORT_LABELS[s.effort].label.toLowerCase() : null] + .filter(Boolean).join(", "); + b.setAttribute("aria-label", `Série ${i + 1} : ${what}`); + b.setAttribute("aria-expanded", String(openPanel === i)); + }); + }; + + const closePanel = () => { + openPanel = null; + panelSlot.replaceChildren(); + paintSets(); + }; + + /** @param {number} i */ + const showPanel = (i) => { + if (openPanel === i) return closePanel(); + openPanel = i; + const existing = ex.done[i]; + const timed = usesTime(ex.tracking); + let reps = typeof existing?.reps === "number" ? existing.reps : proposedReps(ex, i); + const range = targetReps(ex.reps); + const value = h("output", { class: "stepper__value", "aria-live": "polite" }, String(reps)); + const step = (/** @type {number} */ d) => { reps = Math.max(0, reps + d); value.textContent = String(reps); }; + + const panel = h("div", { class: "set-panel", role: "group", "aria-label": `Série ${i + 1}` }, + h("p", { class: "set-panel__title" }, `Série ${i + 1}`, + timed ? ` · ${ex.seconds} s` : range ? ` · objectif ${range.low === range.high ? range.low : range.low + "–" + range.high} répétitions` : ""), + !timed && h("div", { class: "stepper" }, + h("button", { type: "button", class: "stepper__btn", "aria-label": "Une répétition de moins", on: { click: () => step(-1) } }, "−"), + value, + h("button", { type: "button", class: "stepper__btn", "aria-label": "Une répétition de plus", on: { click: () => step(1) } }, "+"), + h("span", { class: "stepper__unit" }, "répétitions")), + h("p", { class: "set-panel__ask" }, "Ressenti ?"), + h("div", { class: "effort-picker" }, EFFORTS.map((effort) => + h("button", { + type: "button", class: "effort", data: { effort }, + "aria-pressed": String(existing?.effort === effort), + on: { click: () => { + ex.done[i] = { reps: timed ? null : reps, effort }; + closePanel(); + changed(); + // Le repos démarre au ressenti. + if (ex.rest > 0) timer.startRest(ex.rest, `Repos · ${ex.name}`); + } }, + }, h("span", { class: "effort__label" }, EFFORT_LABELS[effort].label), h("span", { class: "effort__hint" }, EFFORT_LABELS[effort].hint)))), + existing && h("button", { + type: "button", class: "btn btn--ghost btn--block btn--sm", + on: { click: () => { ex.done[i] = null; closePanel(); changed(); } }, + }, "Annuler cette série")); + panelSlot.replaceChildren(panel); + paintSets(); + }; + + const startChrono = () => { + const i = ex.done.findIndex((s) => s === null); + if (i < 0) { + if (chronoBtn) chronoBtn.textContent = "Toutes les séries sont faites"; + return; + } + const seconds = ex.seconds ?? 45; + timer.startWork(seconds, `${ex.name} · série ${i + 1}`, () => { + // Fin du chrono : la série est cochée (bug d'Atelier : « cocher » n'existait + // pas), puis on demande le ressenti, qui lancera le repos. + if (ex.done[i] === null) ex.done[i] = { reps: null, effort: null }; + changed(); + openPanel = null; + showPanel(i); + }); + }; + + const refreshChrono = () => { + if (chronoBtn) chronoBtn.textContent = `Lancer la série · ${ex.seconds ?? 45} s`; + }; + + /** + * Champ de charge ou de durée. La frappe ne change que le brouillon et les + * libellés ; la charge de travail (WorkingLoadSet) est enregistrée à la + * validation du champ (événement change : sortie du champ ou touche Entrée). + * @param {"loadKg"|"seconds"} field + */ + const amountField = (field) => { + const isLoad = field === "loadKg"; + const id = `f-${o.sessionKey}-${o.number}-${field}`; + const input = h("input", { + id, class: "field__input", type: "text", inputmode: "decimal", autocomplete: "off", + placeholder: "—", value: ex[field] === null ? "" : kg(/** @type {number} */ (ex[field])), + }); + input.addEventListener("input", () => { + const v = parseAmount(input.value); + input.setAttribute("aria-invalid", String(v === undefined || (field === "seconds" && v === 0))); + if (v === undefined) return; + ex[field] = field === "seconds" && !v ? null : v; + refreshLabels(); + refreshChrono(); + o.onChange(); + }); + input.addEventListener("change", () => { + const v = parseAmount(input.value); + if (v === undefined || (field === "seconds" && !v)) return; + const saved = store.getState().workingLoads[ex.key]?.[field] ?? null; + if (saved !== v) store.dispatch("WorkingLoadSet", isLoad ? { key: ex.key, loadKg: v } : { key: ex.key, seconds: v }); + }); + return h("div", { class: "field field--amount" }, + h("label", { class: "field__label", for: id }, isLoad ? "Charge" : "Durée"), + input, + h("span", { class: "field__unit" }, isLoad ? "kg" : "s")); + }; + + const drawWork = () => { + openPanel = null; + chronoBtn = null; + setButtons = Array.from({ length: ex.sets }, (_, i) => + h("button", { type: "button", class: "set-btn", on: { click: () => showPanel(i) } }, String(i + 1))); + const fields = h("div", { class: "work__fields" }, + usesTime(ex.tracking) && amountField("seconds"), + usesLoad(ex.tracking) && amountField("loadKg"), + ex.tracking === "none" && h("p", { class: "muted" }, "Poids du corps : rien à saisir.")); + if (usesTime(ex.tracking)) + chronoBtn = h("button", { type: "button", class: "btn btn--block btn--work", on: { click: startChrono } }); + replace(work, + fields, + h("div", { class: "set-row", role: "group", "aria-label": "Séries" }, setButtons), + panelSlot, + chronoBtn); + panelSlot.replaceChildren(); + paintSets(); + refreshChrono(); + drawTracking(); + }; + + const drawTracking = () => { + replace(tracking, TRACKING_MODES.map((mode) => + h("button", { + type: "button", class: "segmented__opt", "aria-pressed": String(mode === ex.tracking), + on: { click: () => { + if (mode === ex.tracking) return; + const programMode = trackingFor(item, undefined); + store.dispatch("TrackingModeSet", { key: ex.key, mode: mode === programMode ? null : mode }); + const fresh = draftExercise(o.sessionKey, item, store.getState()); + ex.tracking = fresh.tracking; + ex.loadKg = fresh.loadKg; + ex.seconds = fresh.seconds; + drawWork(); + changed(); + /** @type {HTMLElement|null} */ (tracking.querySelector("[aria-pressed=true]"))?.focus(); + } }, + }, TRACKING_LABELS[mode]))); + }; + + // ---- consignes --------------------------------------------------------------- + const muscles = library + ? h("ul", { class: "chips", "aria-label": "Muscles sollicités" }, + library.primary.map((m) => h("li", { class: "chip" }, MUSCLES[m]?.name ?? m)), + library.secondary.map((m) => h("li", { class: "chip chip--secondary" }, MUSCLES[m]?.name ?? m))) + : null; + + const card = h("details", { class: "exercise", open: o.open }, + h("summary", { class: "exercise__head" }, + h("span", { class: "badge", "aria-hidden": "true" }, o.number), + h("span", { class: "exercise__name" }, + h("strong", null, o.letter && h("span", { class: "tag" }, o.letter), resolved.name), + sub), + count, + h("span", { class: "chevron", "aria-hidden": "true" })), + h("div", { class: "exercise__body" }, + resolved.note && h("p", { class: "coach-note" }, resolved.note), + muscles, + resolved.cues.length > 0 && [h("h3", { class: "mini-label" }, "Le geste"), + h("ul", { class: "cues" }, resolved.cues.map((c) => h("li", null, c)))], + resolved.mistakes.length > 0 && [h("h3", { class: "mini-label" }, "À éviter"), + h("ul", { class: "mistakes" }, resolved.mistakes.map((c) => h("li", null, c)))], + h("a", { class: "btn btn--ghost btn--sm tutorial", href: resolved.tutorial, target: "_blank", rel: "noopener noreferrer" }, + "Voir un tutoriel", h("span", { class: "visually-hidden" }, " (nouvel onglet)"), h("span", { "aria-hidden": "true" }, " ↗")), + h("p", { class: "objective" }, objective, h("span", { class: "objective__rest" }, `Repos ${restLabel(ex.rest)}`)), + // À brancher : progression (domaine, sous-lot 1b) pour le conseil « prêt à + // monter à X kg » au-dessus des séries. + work, + h("div", { class: "tracking" }, h("span", { class: "mini-label" }, "Je suis"), tracking))); + + drawWork(); + refreshLabels(); + return card; +} diff --git a/app/ui/feedback.js b/app/ui/feedback.js new file mode 100644 index 0000000..f51bec9 --- /dev/null +++ b/app/ui/feedback.js @@ -0,0 +1,51 @@ +// Retours à l'utilisateur : message bref (toast) et demande de confirmation. + +import { h } from "./dom.js"; + +/** @type {HTMLElement|null} */ +let toastNode = null; +/** @type {ReturnType|null} */ +let toastTimer = null; + +/** + * Message bref en bas de l'écran, lu par les lecteurs d'écran. + * @param {string} message + */ +export function toast(message) { + if (!toastNode) { + toastNode = h("div", { class: "toast", role: "status", "aria-live": "polite" }); + document.body.append(toastNode); + } + toastNode.textContent = message; + toastNode.classList.add("toast--on"); + if (toastTimer) clearTimeout(toastTimer); + toastTimer = setTimeout(() => toastNode?.classList.remove("toast--on"), 3500); +} + +/** + * Demande de confirmation dans une boîte de dialogue native (). + * @param {{title: string, lines?: string[], confirm: string, cancel?: string, danger?: boolean}} options + * @returns {Promise} + */ +export function confirmDialog({ title, lines = [], confirm, cancel = "Annuler", danger = false }) { + return new Promise((resolve) => { + const yes = h("button", { type: "button", class: `btn btn--block ${danger ? "btn--danger" : "btn--primary"}` }, confirm); + const no = h("button", { type: "button", class: "btn btn--block btn--ghost" }, cancel); + const dialog = h("dialog", { class: "dialog", "aria-labelledby": "dialog-title" }, + h("h2", { class: "dialog__title", id: "dialog-title" }, title), + lines.map((l) => h("p", { class: "dialog__text" }, l)), + h("div", { class: "dialog__actions" }, yes, no)); + /** @param {boolean} answer */ + const done = (answer) => { + dialog.close(); + dialog.remove(); + resolve(answer); + }; + yes.addEventListener("click", () => done(true)); + no.addEventListener("click", () => done(false)); + dialog.addEventListener("cancel", (e) => { e.preventDefault(); done(false); }); + document.body.append(dialog); + dialog.showModal(); + no.focus(); + }); +} diff --git a/app/ui/layout.js b/app/ui/layout.js new file mode 100644 index 0000000..5c13edf --- /dev/null +++ b/app/ui/layout.js @@ -0,0 +1,42 @@ +// Morceaux de mise en page communs aux écrans. + +import { h } from "./dom.js"; + +/** + * En-tête d'écran : surtitre, titre en capitales condensées, sous-titre. + * @param {{kicker?: string, title: string, sub?: string|null, back?: {label: string, onClick: () => void}}} o + */ +export function screenHeader({ kicker, title, sub, back }) { + return h("header", { class: "screen-head" }, + back && h("button", { type: "button", class: "back", on: { click: back.onClick } }, + h("span", { "aria-hidden": "true" }, "← "), back.label), + kicker && h("p", { class: "kicker" }, kicker), + h("h1", { class: "title" }, title), + sub && h("p", { class: "lede" }, sub)); +} + +/** + * Titre de section. + * @param {string} text + * @param {string} [hint] + */ +export function sectionLabel(text, hint) { + return h("h2", { class: "section-label" }, text, hint && h("span", { class: "section-label__hint" }, hint)); +} + +/** + * Barre d'action collée en bas de l'écran, à portée de pouce. + * @param {...(Node|null|false)} children + */ +export function actionBar(...children) { + return h("div", { class: "action-bar" }, h("div", { class: "action-bar__in" }, ...children)); +} + +/** + * Petite carte de texte (cardio, repères). + * @param {string} title + * @param {string} text + */ +export function note(title, text) { + return h("article", { class: "note" }, h("h3", { class: "note__title" }, title), h("p", { class: "note__text" }, text)); +} diff --git a/app/ui/onboarding.js b/app/ui/onboarding.js new file mode 100644 index 0000000..511036a --- /dev/null +++ b/app/ui/onboarding.js @@ -0,0 +1,99 @@ +// Premier lancement : pas de programme, pas de proposition en attente. +// But : un programme dans l'app en moins de deux minutes, construit avec l'IA +// de l'utilisateur (ADR 0005, point 7 : le circuit par lien). + +import { h } from "./dom.js"; +import { actionBar } from "./layout.js"; +import { toast } from "./feedback.js"; +import { exampleProgram, onboardingBrief } from "./pending.js"; + +/** Consigne courte pour une IA qui sait lire une page web. */ +export const AI_GUIDE_URL = "https://ia-fit.sans.pub/ia.md"; + +/** + * @param {{store: import("./store.js").Store}} o + */ +export function onboarding({ store }) { + const status = h("p", { class: "status status--ok", role: "status", "aria-live": "polite" }); + const manual = h("div", { class: "manual-copy", hidden: true }); + + const copyBrief = async () => { + const text = await onboardingBrief(location.origin); + if (!text) { + // À brancher : ai-brief.buildOnboardingBrief({baseUrl}) (autre sous-agent). + status.textContent = "Le texte à donner à ton IA arrive bientôt. En attendant, dis-lui de lire " + AI_GUIDE_URL + "."; + return; + } + try { + await navigator.clipboard.writeText(text); + status.textContent = "Copié. Colle-le maintenant dans ton IA."; + toast("Texte copié."); + } catch { + // Presse-papiers refusé (http, navigateur ancien) : copie à la main. + const area = h("textarea", { class: "field__input field__input--area", readonly: true, "aria-label": "Texte à copier dans ton IA" }); + area.value = text; + manual.replaceChildren(h("p", { class: "muted" }, "Copie ce texte à la main :"), area); + manual.hidden = false; + area.select(); + status.textContent = ""; + } + }; + + const startFromExample = async () => { + const program = await exampleProgram(); + if (!program) { + // À brancher : example-program.EXAMPLE_PROGRAM (autre sous-agent). + toast("Le programme d'exemple arrive bientôt."); + return; + } + try { + store.dispatch("ProgramProposed", { + program, + source: /** @type {any} */ ("example"), + reason: "Programme d'exemple : trois séances à domicile avec barre, haltères, banc et élastiques. Ton IA pourra l'adapter ensuite.", + }); + } catch (e) { + toast("Le programme d'exemple n'a pas pu être proposé : " + (e instanceof Error ? e.message : String(e))); + } + }; + + const copyGuide = async () => { + try { + await navigator.clipboard.writeText(`Lis ${AI_GUIDE_URL}`); + toast("Phrase copiée."); + } catch { + toast("Copie impossible : recopie l'adresse à la main."); + } + }; + + return h("div", { class: "onboarding" }, + h("header", { class: "screen-head hero" }, + h("p", { class: "kicker" }, "IA-Fit"), + h("h1", { class: "title title--hero" }, "Ton programme, construit avec ton IA"), + h("p", { class: "lede" }, "Puis suivi séance par séance : séries, charges, repos. Tes données restent sur ton appareil, sans compte.")), + + h("section", { class: "card card--today", "aria-labelledby": "onb-how" }, + h("h2", { class: "card__title", id: "onb-how" }, "En trois gestes"), + h("ol", { class: "how" }, + h("li", { class: "how__step" }, h("strong", null, "Copie le texte"), h("span", null, " et colle-le dans ton IA : Claude, ChatGPT, Le Chat…")), + h("li", { class: "how__step" }, h("strong", null, "Réponds à ses questions"), h("span", null, ", ou montre-lui ton programme actuel : export d'une autre app, texte, captures d'écran.")), + h("li", { class: "how__step" }, h("strong", null, "Touche le lien qu'elle te renvoie"), h("span", null, " : ton programme s'affiche ici, et tu le valides."))), + status, + manual, + h("p", { class: "card__hint" }, + "Ou dis simplement à ton IA : ", + h("code", { class: "inline-code" }, `lis ${AI_GUIDE_URL}`), + " ", + h("button", { type: "button", class: "link-btn", on: { click: copyGuide } }, "Copier")), + h("p", { class: "card__hint" }, "Connecteur MCP pour ton IA : bientôt.")), + + h("section", { class: "alt", "aria-label": "Autres façons de commencer" }, + h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Partir d'un programme d'exemple"), + // À brancher : import d'un instantané (snapshot.js, autre sous-agent). + h("button", { type: "button", class: "btn btn--block btn--ghost", disabled: true, "aria-describedby": "onb-restore" }, "Restaurer une sauvegarde"), + h("p", { class: "muted", id: "onb-restore" }, "Restaurer une sauvegarde : bientôt.")), + + h("footer", { class: "foot" }, "Rien ne part sur un serveur : ce que tu colles dans ton IA, c'est toi qui le choisis."), + + actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme avec mon IA"))); +} diff --git a/app/ui/pending.js b/app/ui/pending.js new file mode 100644 index 0000000..f0e7550 --- /dev/null +++ b/app/ui/pending.js @@ -0,0 +1,41 @@ +// Modules du domaine écrits en parallèle par d'autres sous-agents (lot 1) : on +// les charge à la demande, et l'écran dit honnêtement « bientôt » s'ils ne sont +// pas encore là. Le chemin passe par une variable : ni tsc ni le navigateur ne +// les exigent au chargement de l'app. +// +// À retirer quand ai-brief.js et example-program.js seront fusionnés : les +// remplacer par des import statiques. + +/** + * @param {string} path relatif à app/ui/ + * @returns {Promise|null>} + */ +async function optionalImport(path) { + try { + const url = new URL(path, import.meta.url).href; + return await import(url); + } catch { + return null; + } +} + +/** + * Le prompt d'onboarding à coller dans son IA. + * À brancher : ai-brief.buildOnboardingBrief({baseUrl}). + * @param {string} baseUrl + * @returns {Promise} + */ +export async function onboardingBrief(baseUrl) { + const mod = await optionalImport("../domain/ai-brief.js"); + return typeof mod?.buildOnboardingBrief === "function" ? String(mod.buildOnboardingBrief({ baseUrl })) : null; +} + +/** + * Le programme d'exemple (celui d'Atelier). + * À brancher : example-program.EXAMPLE_PROGRAM. + * @returns {Promise} + */ +export async function exampleProgram() { + const mod = await optionalImport("../domain/example-program.js"); + return mod?.EXAMPLE_PROGRAM ?? null; +} diff --git a/app/ui/proposal-card.js b/app/ui/proposal-card.js new file mode 100644 index 0000000..c22df95 --- /dev/null +++ b/app/ui/proposal-card.js @@ -0,0 +1,55 @@ +// Une proposition de programme en attente : un aperçu simple, « Adopter » ou +// « Refuser ». Glossaire : docs/glossaire/proposition.md +// +// À brancher (sous-lot 1e) : l'écran de proposition avec l'aperçu détaillé des +// changements (exercices ajoutés, retirés, modifiés). Ce rendu provisoire montre +// le programme proposé tel quel. + +import { h } from "./dom.js"; +import { plural } from "./format.js"; +import { resolveExercise } from "../domain/program.js"; +import { toast } from "./feedback.js"; + +/** @type {Record} */ +const SOURCE_LABELS = { + ai: "Proposé par ton IA", + link: "Reçu par un lien", + import: "Venu d'une sauvegarde", + atelier: "Repris d'Atelier", + example: "Programme d'exemple", + default: "Programme de départ", + app: "Modifié dans l'app", +}; + +/** + * @param {{proposal: import("../domain/state.js").Proposal, store: import("./store.js").Store}} o + */ +export function proposalCard({ proposal, store }) { + const p = proposal.program; + // Le profil proposé est facultatif (onboarding par l'IA) : adopté avec le programme. + const profile = /** @type {any} */ (proposal).profile; + + const adopt = () => { + store.dispatch("ProgramAdopted", { program: p, source: proposal.source, proposalId: proposal.id, ...(proposal.reason ? { reason: proposal.reason } : {}) }); + if (profile) store.dispatch("ProfileUpdated", { profile }); + toast(`Programme « ${p.name} » adopté.`); + }; + const reject = () => { + store.dispatch("ProposalRejected", { proposalId: proposal.id }); + toast("Proposition refusée."); + }; + + return h("section", { class: "card card--proposal", "aria-labelledby": `prop-${proposal.id}` }, + h("p", { class: "kicker" }, "À valider · ", SOURCE_LABELS[proposal.source] ?? proposal.source), + h("h2", { class: "card__title", id: `prop-${proposal.id}` }, p.name), + p.subtitle && h("p", { class: "card__text" }, p.subtitle), + proposal.reason && h("p", { class: "coach-note" }, proposal.reason), + h("ul", { class: "preview" }, p.sessions.map((s) => + h("li", { class: "preview__session" }, + h("strong", null, `Séance ${s.key} · ${s.name}`), + h("span", { class: "muted" }, `${plural(s.exercises.length, "exercice")} : ${s.exercises.map((x) => resolveExercise(x).name).join(", ")}`)))), + profile && h("p", { class: "muted" }, "Ton profil (objectif, matériel, contraintes) sera aussi mis à jour."), + h("div", { class: "card__actions" }, + h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: adopt } }, "Adopter ce programme"), + h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: reject } }, "Refuser"))); +} diff --git a/app/ui/screens/history.js b/app/ui/screens/history.js new file mode 100644 index 0000000..9501269 --- /dev/null +++ b/app/ui/screens/history.js @@ -0,0 +1,149 @@ +// Historique : la liste des séances faites, et la correction ou la suppression +// d'une séance passée (SessionCorrected, SessionDeleted). + +import { h, replace } from "../dom.js"; +import { kg, localDay, longDay, mediumDay, parseAmount } from "../format.js"; +import { actionBar, screenHeader, sectionLabel } from "../layout.js"; +import { href } from "../router.js"; +import { sessionDataOf, sessionSummary, usesLoad, usesTime } from "../session-draft.js"; +import { confirmDialog, toast } from "../feedback.js"; + +/** + * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx + * @returns {import("../router.js").Screen} + */ +export function historyScreen({ store, nav }) { + const list = h("div", { class: "history" }); + const paint = () => { + const sessions = [...store.getState().sessions].reverse(); + if (!sessions.length) { + 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)), + h("span", { class: "chevron", "aria-hidden": "true" })))))); + }; + paint(); + const unsubscribe = store.subscribe(paint); + const node = h("div", { class: "screen" }, + screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Ton parcours", title: "Historique", sub: "Touche une séance pour la corriger ou la retirer." }), + list); + return { node, title: "Historique", destroy: unsubscribe }; +} + +/** @param {string} kind */ +const kindLabel = (kind) => (kind === "cardio" ? "Cardio" : kind === "activity" ? "Activité" : "Séance"); + +/** + * Correction d'une séance passée. Le formulaire travaille sur une copie ; rien + * n'est enregistré avant « Enregistrer les modifications ». + * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, id: string}} ctx + * @returns {import("../router.js").Screen} + */ +export function historyEditScreen({ store, nav, id }) { + const back = { label: "Historique", onClick: () => nav.back(href.history()) }; + const logged = store.getState().sessions.find((s) => s.id === id); + if (!logged) { + return { + title: "Séance introuvable", + node: h("div", { class: "screen" }, screenHeader({ back, title: "Séance introuvable", sub: "Elle a peut-être été retirée de l'historique." })), + }; + } + const data = sessionDataOf(logged); + const today = localDay(); + const status = h("p", { class: "status", role: "alert" }); + + const dateInput = h("input", { id: "edit-date", class: "field__input field__input--date", type: "date", max: today, value: data.date }); + dateInput.addEventListener("change", () => { + if (/^\d{4}-\d{2}-\d{2}$/.test(dateInput.value) && dateInput.value <= today) data.date = dateInput.value; + else dateInput.value = data.date; + }); + + /** @type {Set} */ + const invalid = new Set(); + /** + * Champ numérique qui écrit dans la copie à chaque frappe (aucune + * reconstruction : le focus reste). + * @param {string} label + * @param {number|null} value + * @param {(v: number|null) => void} write + * @param {string} unit + */ + const numberField = (label, value, write, unit) => { + const input = h("input", { class: "field__input", type: "text", inputmode: "decimal", autocomplete: "off", placeholder: "—", "aria-label": label, value: value === null ? "" : kg(value) }); + input.addEventListener("input", () => { + const v = parseAmount(input.value); + input.setAttribute("aria-invalid", String(v === undefined)); + if (v === undefined) invalid.add(input); + else { invalid.delete(input); write(v); } + }); + return h("span", { class: "field field--amount field--compact" }, input, h("span", { class: "field__unit" }, unit)); + }; + + const exercises = data.exercises.map((x) => { + const sets = h("div", { class: "edit-sets" }); + const drawSets = () => { + replace(sets, + x.sets.map((s, i) => h("div", { class: "edit-set" }, + h("span", { class: "edit-set__n" }, `Série ${i + 1}`), + numberField(`Répétitions de la série ${i + 1}, ${x.name}`, s.reps, (v) => { s.reps = v === null ? null : Math.round(v); }, "rép."))), + h("div", { class: "edit-sets__btns" }, + h("button", { type: "button", class: "btn btn--sm", on: { click: () => { + const prev = x.sets[x.sets.length - 1]; + x.sets.push({ reps: prev?.reps ?? null, effort: null }); + drawSets(); + } } }, "+ Série"), + x.sets.length > 0 && h("button", { type: "button", class: "btn btn--sm btn--ghost", on: { click: () => { x.sets.pop(); drawSets(); } } }, "− Série"))); + }; + drawSets(); + return h("li", { class: "edit-ex" }, + h("div", { class: "edit-ex__head" }, + h("strong", null, x.name), + h("span", { class: "muted" }, x.target)), + h("div", { class: "work__fields" }, + usesLoad(x.tracking) && numberField(`Charge, ${x.name}`, x.loadKg, (v) => { x.loadKg = v; }, "kg"), + usesTime(x.tracking) && numberField(`Durée, ${x.name}`, x.seconds, (v) => { x.seconds = v; }, "s")), + sets); + }); + + const save = () => { + if (invalid.size) { + status.textContent = "Un nombre est illisible : corrige le champ signalé."; + return; + } + try { + store.dispatch("SessionCorrected", { sessionId: id, session: data }); + } catch (e) { + status.textContent = "La correction n'a pas pu être enregistrée : " + (e instanceof Error ? e.message : String(e)); + return; + } + toast("Séance corrigée."); + nav.back(href.history()); + }; + + const remove = async () => { + const ok = await confirmDialog({ + title: "Retirer cette séance ?", + lines: [`${data.name}, ${longDay(data.date)}.`, "Elle disparaît de l'historique et des calculs de progression."], + confirm: "Retirer la séance", cancel: "Garder", danger: true, + }); + if (!ok) return; + store.dispatch("SessionDeleted", { sessionId: id }); + toast("Séance retirée de l'historique."); + nav.back(href.history()); + }; + + const node = h("div", { class: "screen" }, + screenHeader({ back, kicker: mediumDay(logged.date), title: "Corriger", sub: logged.name }), + h("div", { class: "field field--inline" }, h("label", { class: "field__label", for: "edit-date" }, "Date"), dateInput), + data.exercises.length > 0 && [sectionLabel("Exercices", "séries faites et charge"), h("ul", { class: "edit-list" }, exercises)], + sectionLabel("Retirer"), + h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: remove } }, "Retirer cette séance de l'historique"), + status, + actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: save } }, "Enregistrer les modifications"))); + return { node, title: "Corriger une séance" }; +} diff --git a/app/ui/screens/home.js b/app/ui/screens/home.js new file mode 100644 index 0000000..0160745 --- /dev/null +++ b/app/ui/screens/home.js @@ -0,0 +1,112 @@ +// 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. + +import { h, 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 { href } from "../router.js"; +import { onboarding } from "../onboarding.js"; +import { proposalCard } from "../proposal-card.js"; + +/** + * 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 + */ +export const hasProgram = (state) => !!state.program && state.programVersions.length > 0; + +/** + * @param {{store: import("../store.js").Store}} ctx + * @returns {import("../router.js").Screen} + */ +export function homeScreen({ store }) { + 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)); + paint(); + return { node, title: "", destroy: store.subscribe(paint) }; +} + +/** + * @param {import("../store.js").Store} store + * @returns {Node} + */ +function homeContent(store) { + const state = store.getState(); + // Une proposition en attente passe avant tout le reste. + if (state.proposals.length) { + 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 }))); + } + if (!hasProgram(state)) return onboarding({ store }); + + const program = /** @type {import("../../domain/program.js").Program} */ (state.program); + const last = lastDoneByKey(state); + const today = localDay(); + + // À 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); + + 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.")); + + return h("div", null, + screenHeader({ kicker: "IA-Fit", title: program.name, sub: program.subtitle }), + todayCard, + + 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"), + ])))), + + 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, + + 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("footer", { class: "foot" }, "Tes données restent sur cet appareil."), + + next && actionBar(h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(next.key) }, + `Commencer la séance ${next.key}`))); +} + +/** + * 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 + */ +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; +} diff --git a/app/ui/screens/session.js b/app/ui/screens/session.js new file mode 100644 index 0000000..4b819b6 --- /dev/null +++ b/app/ui/screens/session.js @@ -0,0 +1,143 @@ +// La séance guidée : échauffement, blocs et supersets, séries, minuteur. +// Le brouillon est local ; « Terminer » crée un seul SessionLogged. + +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 { actionBar, screenHeader } from "../layout.js"; +import { href } from "../router.js"; +import { buildSessionData, completion, createDraft, doneCount, draftMatches } 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 { confirmDialog, toast } from "../feedback.js"; + +/** + * @param {{store: import("../store.js").Store, key: string, nav: import("../router.js").Navigation, timer: import("../timer.js").Timer}} ctx + * @returns {import("../router.js").Screen} + */ +export function sessionScreen({ store, key, 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()) }; + if (!session) { + return { + title: "Séance introuvable", + node: h("div", { class: "screen" }, + screenHeader({ back, title: "Séance introuvable", sub: `Le programme n'a pas de séance « ${key} ».` })), + }; + } + + const today = localDay(); + const stored = loadDraft(); + const draft = draftMatches(stored, session, WARMUP_STEPS.length) + ? stored + : createDraft(session, state, today, WARMUP_STEPS.length); + const resumed = draft === stored; + + 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`; + }; + // 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. + const onChange = () => { + saveDraft(draft); + paintProgress(); + status.textContent = ""; + }; + + // ---- date de la séance (saisie a posteriori possible) ------------------------ + const dateNotice = h("p", { class: "coach-note", hidden: draft.date === today }); + const paintDate = () => { + dateNotice.hidden = draft.date === today; + dateNotice.textContent = `Cette séance sera enregistrée au ${longDay(draft.date)}.`; + }; + const dateInput = h("input", { id: "session-date", class: "field__input field__input--date", type: "date", max: today, value: draft.date }); + dateInput.addEventListener("change", () => { + const value = dateInput.value; + draft.date = /^\d{4}-\d{2}-\d{2}$/.test(value) && value <= today ? value : today; + if (draft.date !== value) dateInput.value = draft.date; + paintDate(); + onChange(); + }); + paintDate(); + + // ---- blocs --------------------------------------------------------------------- + const color = sessionColor(session.color); + const firstOpen = draft.exercises.findIndex((ex) => doneCount(ex) < ex.sets); + let index = 0; + const blocks = groupBlocks(session.exercises).map((block) => { + const cards = block.items.map((item, k) => { + const i = index++; + return exerciseCard({ + 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, + }); + }); + if (block.items.length === 1) return cards[0]; + const names = block.items.map((item) => resolveExercise(item).name).join(" + "); + const rounds = Math.max(...block.items.map((item) => item.sets)); + return h("section", { class: "superset", "aria-label": `Superset : ${names}` }, + h("div", { class: "superset__head" }, + h("span", { class: "tag tag--superset" }, "Superset"), + h("p", { class: "superset__text" }, `${rounds} tours : enchaîne les exercices, le vrai repos vient après le dernier.`)), + cards); + }); + + const finish = async () => { + const c = completion(draft); + if (c.doneSets === 0) { + status.textContent = "Aucune série validée : rien à enregistrer."; + return; + } + if (!c.complete) { + const lines = []; + if (c.missing.length) + lines.push(`${plural(c.missing.length, "exercice")} pas commencé${c.missing.length > 1 ? "s" : ""} : ${c.missing.slice(0, 3).join(", ")}${c.missing.length > 3 ? "…" : ""}.`); + if (c.partial.length) lines.push(`${plural(c.partial.length, "exercice")} incomplet${c.partial.length > 1 ? "s" : ""}.`); + lines.push("Tu pourras la corriger ensuite depuis l'historique."); + 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; + } + try { + store.dispatch("SessionLogged", buildSessionData(draft)); + } catch (e) { + status.textContent = "La séance n'a pas pu être enregistrée : " + (e instanceof Error ? e.message : String(e)); + return; + } + 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 }); + }; + + const node = h("div", { class: "screen screen--session" }, + screenHeader({ + back, + kicker: `Séance ${session.key}${session.tag ? " · " + session.tag : ""} · environ ${estimateMinutes(session)} min`, + title: session.name, + sub: session.subtitle, + }), + resumed && h("p", { class: "coach-note" }, "Séance reprise là où tu l'avais laissée."), + h("div", { class: "field field--inline" }, + h("label", { class: "field__label", for: "session-date" }, "Date de la séance"), + dateInput), + dateNotice, + h("div", { class: "exercises" }, + warmupCard({ 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."), + actionBar(progress, h("button", { type: "button", class: "btn btn--primary btn--lg", on: { click: finish } }, "Terminer la séance"))); + setAccent(node, color, inkOn(color)); + paintProgress(); + + return { node, title: session.name, destroy: () => timer.stop() }; +} diff --git a/app/ui/timer.js b/app/ui/timer.js new file mode 100644 index 0000000..761b146 --- /dev/null +++ b/app/ui/timer.js @@ -0,0 +1,120 @@ +// Le minuteur, fixé en bas de l'écran : repos entre les séries, ou chrono d'une +// série au temps. Il se cale sur l'horloge (Date.now) et non sur le nombre de +// tics : il reste juste si le téléphone met l'onglet en veille. +// Ce n'est pas un événement (ADR 0006, point 3). + +import { h, vibrate } from "./dom.js"; +import { clock } from "./format.js"; + +/** + * @typedef {object} Timer + * @property {(seconds: number, label: string, endText?: string) => void} startRest + * repos, ou toute durée simple (échauffement) ; endText s'affiche à la fin + * @property {(seconds: number, label: string, onDone: () => void) => void} startWork + * chrono de série : onDone est appelé à la fin, ou si l'on touche « Terminer » + * @property {(seconds: number) => void} add + * @property {() => void} stop + * @property {HTMLElement} node + */ + +/** @returns {Timer} */ +export function createTimer() { + const bar = h("div", { class: "timer__bar", "aria-hidden": "true" }); + const label = h("div", { class: "timer__label" }, "Repos"); + const time = h("div", { class: "timer__time" }, "0:00"); + const live = h("div", { class: "visually-hidden", role: "status", "aria-live": "polite" }); + const close = h("button", { type: "button", class: "btn btn--primary timer__btn" }, "Terminer"); + const more = h("button", { type: "button", class: "btn timer__btn", "aria-label": "Ajouter 30 secondes" }, "+30 s"); + const node = h("section", { class: "timer", "aria-label": "Minuteur", hidden: true }, + bar, + h("div", { class: "timer__in" }, + h("div", { class: "timer__read" }, label, time), + h("div", { class: "timer__btns" }, more, close)), + live); + + let end = 0, total = 0, labelText = ""; + /** @type {ReturnType|null} */ + let tick = null; + /** @type {(() => void)|null} */ + let onDone = null; + let work = false; + let endText = "Repos terminé"; + + const paint = () => { + const left = Math.max(0, Math.round((end - Date.now()) / 1000)); + time.textContent = clock(left); + node.classList.toggle("timer--low", left > 0 && left <= 10); + node.classList.toggle("timer--zero", left === 0); + bar.style.setProperty("--progress", String(total ? left / total : 0)); + if (left === 0 && tick) finish(); + }; + + const finish = () => { + if (tick) clearInterval(tick); + tick = null; + vibrate(work ? [300, 120, 300, 120, 300] : [180, 90, 180]); + label.textContent = work ? `${labelText} · série terminée` : endText; + live.textContent = work ? "Série terminée" : endText; + close.textContent = "Fermer"; + const done = onDone; + onDone = null; + done?.(); + }; + + /** @param {number} seconds @param {string} text @param {boolean} isWork */ + const start = (seconds, text, isWork) => { + // Un chrono de série interrompu par un nouveau minuteur ne coche rien. + onDone = null; + work = isWork; + labelText = text; + total = seconds; + end = Date.now() + seconds * 1000; + label.textContent = text; + live.textContent = ""; + close.textContent = "Terminer"; + node.classList.toggle("timer--work", isWork); + node.hidden = false; + document.body.classList.add("has-timer"); + if (!tick) tick = setInterval(paint, 250); + paint(); + }; + + const stop = () => { + if (tick) clearInterval(tick); + tick = null; + end = 0; + onDone = null; + node.hidden = true; + document.body.classList.remove("has-timer"); + }; + + more.addEventListener("click", () => { + if (!end) return; + const left = Math.max(0, end - Date.now()); + end = Date.now() + left + 30_000; + total = Math.max(total, Math.round((end - Date.now()) / 1000)); + label.textContent = labelText; + close.textContent = "Terminer"; + if (!tick) tick = setInterval(paint, 250); + paint(); + }); + close.addEventListener("click", () => { + // « Terminer » pendant un chrono de série : la série est faite. + if (tick && onDone) { + const done = onDone; + onDone = null; + stop(); + done(); + return; + } + stop(); + }); + + return { + node, + startRest: (seconds, text, end = "Repos terminé") => { start(seconds, text, false); endText = end; }, + startWork: (seconds, text, done) => { start(seconds, text, true); onDone = done; }, + add: (seconds) => { end += seconds * 1000; total += seconds; paint(); }, + stop, + }; +} diff --git a/app/ui/warmup-card.js b/app/ui/warmup-card.js new file mode 100644 index 0000000..59ada2c --- /dev/null +++ b/app/ui/warmup-card.js @@ -0,0 +1,68 @@ +// L'échauffement guidé, en tête de séance. Glossaire : docs/glossaire/echauffement.md +// +// À brancher : warmup.warmupPlan (domaine, sous-lot 1b) calculera les étapes et +// les séries d'approche à partir de la charge de travail du premier exercice. +// En attendant, les étapes de mobilité sont codées ici (reprises d'Atelier) et +// les séries d'approche ne sont pas chiffrées. + +import { h } from "./dom.js"; +import { restLabel } from "./format.js"; + +/** @typedef {{title: string, detail: string, seconds: number}} WarmupStep */ + +/** @type {WarmupStep[]} */ +export const WARMUP_STEPS = [ + { title: "Vélo, marche ou corde légère", detail: "Allure tranquille, juste de quoi avoir chaud et le souffle un peu plus court.", seconds: 360 }, + { title: "Cercles de bras et rotations d'épaules", detail: "Bras tendus, 10 cercles en avant puis 10 en arrière. Puis les épaules qui montent et descendent.", seconds: 45 }, + { title: "Balancements de jambe", detail: "Appuie-toi au mur. 10 balancements avant-arrière par jambe, puis 10 latéraux.", seconds: 60 }, + { title: "Squats au poids du corps", detail: "10 répétitions, descente lente, en cherchant un peu plus de profondeur à chaque fois.", seconds: 60 }, +]; + +/** + * @param {{done: boolean[], timer: import("./timer.js").Timer, onChange: () => void, open: boolean}} o + * done : étapes cochées, modifié sur place + */ +export function warmupCard(o) { + const count = h("span", { class: "exercise__count" }); + const refresh = () => { + const n = o.done.filter(Boolean).length; + count.textContent = `${n}/${o.done.length}`; + count.classList.toggle("exercise__count--done", n === o.done.length); + }; + + const steps = WARMUP_STEPS.map((step, i) => { + const tick = h("button", { + type: "button", class: "tick", "aria-pressed": String(o.done[i]), + "aria-label": `Fait : ${step.title}`, + }); + tick.addEventListener("click", () => { + o.done[i] = !o.done[i]; + tick.setAttribute("aria-pressed", String(o.done[i])); + refresh(); + o.onChange(); + }); + return h("li", { class: "step" }, + tick, + h("div", { class: "step__text" }, h("strong", null, step.title), h("span", null, step.detail)), + h("button", { + type: "button", class: "btn btn--sm step__go", "aria-label": `Lancer ${restLabel(step.seconds)} : ${step.title}`, + on: { click: () => o.timer.startRest(step.seconds, step.title, "Étape terminée") }, + }, restLabel(step.seconds))); + }); + + const card = h("details", { class: "exercise exercise--warmup", open: o.open }, + h("summary", { class: "exercise__head" }, + h("span", { class: "badge badge--warmup", "aria-hidden": "true" }, "0"), + h("span", { class: "exercise__name" }, + h("strong", null, "Échauffement"), + h("span", { class: "exercise__sub" }, "À faire en premier · environ 10 min")), + count, + h("span", { class: "chevron", "aria-hidden": "true" })), + h("div", { class: "exercise__body" }, + h("ol", { class: "steps" }, steps), + h("h3", { class: "mini-label" }, "Séries d'approche"), + h("p", { class: "muted" }, + "Monte progressivement jusqu'à ta charge du jour sur le premier exercice. Le calcul chiffré des séries d'approche arrive bientôt."))); + refresh(); + return card; +}