// Le panneau d'une séance WOD (lot 4b, ADR 0010) : le format, les mouvements, // le chrono (compte à rebours, intervalles, temps limite) et la saisie du score. // L'horloge se cale sur l'heure (draft.wod.startedAt) : elle reste juste si le // téléphone se met en veille, et reprend après un rechargement. // Calculs : domain/wod.js ; état : session-draft.js (DraftWod). import { h, replace, vibrate } from "./dom.js"; import { resolveExercise } from "../domain/program.js"; import { clockText, currentMovement, formatHint, formatLabel, formatSeconds, parseClock, scoreFields, wodClock } from "../domain/wod.js"; import { usesLoad, wodElapsed } from "./session-draft.js"; import { kg, parseAmount } from "./format.js"; import { confirmDialog } from "./feedback.js"; /** Compte à rebours avant le départ, en secondes. */ const COUNTDOWN = 5; /** * @param {{draft: import("./session-draft.js").Draft, session: import("../domain/program.js").ProgramSession, * store: import("./store.js").Store, onChange: () => void}} o * @returns {{node: HTMLElement, destroy: () => void}} */ export function wodPanel({ draft, session, store, onChange }) { const w = /** @type {import("./session-draft.js").DraftWod} */ (draft.wod); const format = w.format; const fields = scoreFields(format); const total = formatSeconds(format); // ---- son et écran allumé ---------------------------------------------------------- /** @type {AudioContext|null} */ let audio = null; /** @param {number} freq @param {number} ms */ const beep = (freq, ms) => { try { audio ??= new AudioContext(); const osc = audio.createOscillator(); const gain = audio.createGain(); osc.frequency.value = freq; gain.gain.value = 0.2; osc.connect(gain).connect(audio.destination); osc.start(); osc.stop(audio.currentTime + ms / 1000); } catch { // pas de son possible : la vibration et l'affichage suffisent } }; /** @type {any} */ let wakeLock = null; const keepAwake = async (on) => { try { if (on && !wakeLock && "wakeLock" in navigator) wakeLock = await /** @type {any} */ (navigator).wakeLock.request("screen"); if (!on && wakeLock) { await wakeLock.release(); wakeLock = null; } } catch { wakeLock = null; } }; // ---- mouvements ------------------------------------------------------------------- const moves = session.exercises.map((item, i) => { const ex = draft.exercises[i]; const r = resolveExercise(item); const load = usesLoad(ex.tracking) ? h("input", { class: "field__input", inputmode: "decimal", "aria-label": `Charge, ${r.name} (kg)`, value: ex.loadKg === null ? "" : kg(ex.loadKg) }) : null; load?.addEventListener("change", () => { const v = parseAmount(load.value); ex.loadKg = typeof v === "number" && v > 0 ? v : null; if (ex.loadKg !== null && store.getState().workingLoads[ex.key]?.loadKg !== ex.loadKg) store.dispatch("WorkingLoadSet", { key: ex.key, loadKg: ex.loadKg }); onChange(); }); return h("li", { class: "wod-move" }, h("div", { class: "wod-move__main" }, h("span", { class: "wod-move__reps num" }, item.reps), h("span", { class: "wod-move__name" }, r.name), load && h("span", { class: "wod-move__load" }, load, h("span", { "aria-hidden": "true" }, " kg"))), r.note && h("p", { class: "wod-move__note" }, r.note), (r.cues.length > 0 || r.tutorial) && h("details", { class: "wod-move__guide" }, h("summary", null, "Le geste"), h("ul", { class: "cues" }, r.cues.map((c) => h("li", null, c))), h("a", { class: "btn btn--ghost btn--sm tutorial", href: r.tutorial, target: "_blank", rel: "noopener noreferrer" }, "Voir un tutoriel ↗"))); }); // ---- chrono ----------------------------------------------------------------------- const time = h("div", { class: "wod-clock__time num", "aria-hidden": "true" }, "0:00"); const phase = h("div", { class: "wod-clock__phase" }); const live = h("div", { class: "visually-hidden", role: "status", "aria-live": "polite" }); const buttons = h("div", { class: "btn-row wod-clock__btns" }); const clockBox = h("section", { class: "wod-clock", "aria-label": "Chrono du WOD" }, phase, time, live, buttons); let last = { phase: "", round: /** @type {number|null} */ (null), remaining: /** @type {number|null} */ (null) }; /** @type {ReturnType|null} */ let tick = null; const running = () => w.startedAt !== null; const stopTicking = () => { if (tick) clearInterval(tick); tick = null; }; const start = () => { beep(660, 60); // débloque le son sur iOS, au geste de l'utilisateur w.startedAt = Date.now() + (w.banked === 0 ? COUNTDOWN * 1000 : 0); onChange(); void keepAwake(true); run(); }; const pause = () => { w.banked = Math.max(0, wodElapsed(w, Date.now())); w.startedAt = null; onChange(); void keepAwake(false); stopTicking(); paint(); }; /** Arrêt du chrono : For Time et tours prennent le temps comme score. */ const finishWod = () => { const elapsed = Math.round(Math.max(0, wodElapsed(w, Date.now()))); pause(); if (fields.seconds) { w.seconds = total !== null ? Math.min(elapsed, total) : elapsed; if (secondsInput) secondsInput.value = clockText(w.seconds); } onChange(); paintScore(); }; const reset = async () => { if (w.banked > 0 || running()) { const ok = await confirmDialog({ title: "Remettre le chrono à zéro ?", lines: ["Le temps couru sera perdu."], confirm: "Remettre à zéro" }); if (!ok) return; } w.startedAt = null; w.banked = 0; w.capped = false; onChange(); void keepAwake(false); stopTicking(); paint(); }; const run = () => { stopTicking(); tick = setInterval(paint, 200); paint(); }; const paint = () => { const now = Date.now(); const pre = w.startedAt !== null && w.startedAt > now ? Math.ceil((w.startedAt - now) / 1000) : 0; const c = wodClock(format, pre ? 0 : wodElapsed(w, now)); const movement = currentMovement(c, moves.length); moves.forEach((m, i) => m.classList.toggle("wod-move--now", running() && !pre && i === movement)); if (pre) { time.textContent = String(pre); phase.textContent = "Prêt ?"; if (last.remaining !== pre) beep(440, 80); last = { phase: "pre", round: null, remaining: pre }; } else { // For Time et tours : on mesure un temps, le chrono monte. Sinon il descend. const up = format.type === "fortime" || format.type === "rounds"; time.textContent = clockText(up || c.remaining === null ? c.elapsed : c.remaining); phase.textContent = phaseText(format, c); if (running()) { if (last.phase === "pre" || (last.phase && (c.phase !== last.phase || c.round !== last.round))) { beep(c.phase === "rest" ? 520 : 880, c.phase === "done" ? 900 : 250); vibrate(c.phase === "done" ? [400, 150, 400] : [200]); live.textContent = phase.textContent; } else if (c.remaining !== null && c.remaining <= 3 && c.remaining > 0 && c.remaining !== last.remaining) beep(660, 70); } last = { phase: c.phase, round: c.round, remaining: c.remaining }; } clockBox.classList.toggle("wod-clock--rest", c.phase === "rest"); clockBox.classList.toggle("wod-clock--done", c.phase === "done"); if (c.phase === "done" && running()) { // fin du format : For Time au cap, AMRAP, EMOM, Tabata terminés w.banked = /** @type {number} */ (total); w.startedAt = null; if (format.type === "fortime") { w.capped = true; w.seconds = null; } onChange(); void keepAwake(false); stopTicking(); paintScore(); } paintButtons(c.phase === "done"); }; const paintButtons = (/** @type {boolean} */ done) => { const btn = (/** @type {string} */ label, /** @type {() => void} */ fn, cls = "btn") => h("button", { type: "button", class: cls, on: { click: fn } }, label); replace(buttons, !done && !running() && btn(w.banked > 0 ? "Reprendre" : "Démarrer", start, "btn btn--primary btn--lg"), running() && btn("Pause", pause), running() && (format.type === "fortime" || format.type === "rounds") && btn("Fini !", finishWod, "btn btn--primary btn--lg"), (w.banked > 0 || running()) && btn("Zéro", () => void reset(), "btn btn--ghost")); }; // ---- score ------------------------------------------------------------------------ /** @param {string} id @param {string} label @param {number|null} value @param {(v: number|null) => void} set */ const numberField = (id, label, value, set) => { const input = h("input", { id, class: "field__input", inputmode: "numeric", value: value === null ? "" : String(value) }); input.addEventListener("input", () => { const v = Number.parseInt(input.value, 10); set(Number.isInteger(v) && v >= 0 ? v : null); onChange(); }); return h("div", { class: "field" }, h("label", { class: "field__label", for: id }, label), input); }; /** @type {HTMLInputElement|null} */ let secondsInput = null; const score = h("div", { class: "wod-score" }); const paintScore = () => { secondsInput = fields.seconds ? h("input", { id: "wod-time", class: "field__input", inputmode: "numeric", placeholder: "7:42", value: w.seconds === null ? "" : clockText(w.seconds) }) : null; secondsInput?.addEventListener("change", () => { const v = parseClock(/** @type {HTMLInputElement} */ (secondsInput).value); w.seconds = v; if (v !== null) w.capped = false; onChange(); }); const capped = format.type === "fortime" && format.capMinutes ? h("input", { id: "wod-cap", type: "checkbox", checked: w.capped }) : null; capped?.addEventListener("change", () => { w.capped = /** @type {HTMLInputElement} */ (capped).checked; if (w.capped) w.seconds = null; onChange(); paintScore(); }); const rx = (/** @type {boolean} */ value, /** @type {string} */ label) => h("button", { type: "button", class: "segmented__opt", "aria-pressed": String(w.rx === value), on: { click: () => { w.rx = value; onChange(); paintScore(); } }, }, label); replace(score, h("h2", { class: "tape" }, "Score"), fields.seconds && !w.capped && h("div", { class: "field" }, h("label", { class: "field__label", for: "wod-time" }, "Temps (min:s)"), secondsInput), capped && h("label", { class: "check" }, capped, ` Temps limite atteint (${format.capMinutes} min)`), fields.rounds && numberField("wod-rounds", "Tours complets", w.rounds, (v) => { w.rounds = v; }), fields.reps && (format.type !== "fortime" || w.capped) && numberField("wod-reps", format.type === "amrap" ? "Répétitions en plus" : format.type === "fortime" ? "Répétitions faites au temps limite" : "Répétitions au total (facultatif)", w.reps, (v) => { w.reps = v; }), h("div", { class: "field" }, h("label", { class: "field__label", for: "wod-kg" }, "Charge principale (kg, facultatif)"), kgInput()), h("div", { class: "segmented", role: "group", "aria-label": "RX ou scaled" }, rx(true, "RX"), rx(false, "Scaled"))); }; const kgInput = () => { const input = h("input", { id: "wod-kg", class: "field__input", inputmode: "decimal", value: w.kg === null ? "" : kg(w.kg) }); input.addEventListener("change", () => { const v = parseAmount(input.value); w.kg = typeof v === "number" && v > 0 ? v : null; onChange(); }); return input; }; paintScore(); paint(); if (running()) { void keepAwake(true); run(); } const node = h("div", { class: "wod" }, h("section", { class: "wod-format" }, h("p", { class: "kicker" }, "WOD"), h("p", { class: "wod-format__label" }, formatLabel(format)), h("p", { class: "muted" }, formatHint(format))), h("ol", { class: "wod-moves" }, moves), clockBox, score); return { node, destroy: () => { stopTicking(); void keepAwake(false); void audio?.close().catch(() => {}); }, }; } /** * Ce que montre l'horloge, en mots : « Temps restant », « Intervalle 3/10 », * « Repos · tour 2/8 », « Chrono · cap 15 min ». * @param {import("../domain/wod.js").WodFormat} format * @param {import("../domain/wod.js").WodClock} c */ export function phaseText(format, c) { if (c.phase === "done") return "Terminé"; switch (format.type) { case "amrap": return "Temps restant"; case "emom": return `Intervalle ${c.round}/${c.rounds}`; case "tabata": return `${c.phase === "rest" ? "Repos" : "Effort"} · tour ${c.round}/${c.rounds}`; case "fortime": return format.capMinutes ? `Chrono · cap ${format.capMinutes} min` : "Chrono"; default: return "Chrono"; } }