sokko-g/website/src/features/cards/team/RaceLive.jsx
Shinuwa 166790245f Turn the comments that describe functions into JSDoc so the editor shows them on hover
The 669 // comments sitting right above a function, method or hook become
/** */ blocks, unchanged in wording; eslint directives stay right above the
line they target. website/AGENTS.md now asks for JSDoc on function comments
and // inside function bodies. ExpeditionPlanner.jsx grew past 300 lines and
gets its full header, as the header test requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:51:47 +01:00

156 lines
8.3 KiB
JavaScript

/**
* @file Course en direct : décompte, animation des quatre coureurs, équipiers à cliquer pour donner leurs
* élans.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { BOOST_FACTOR, BOOST_MS, RACE_LENGTH } from "../../../../../services/cards/race-rules.js";
import { fillTemplate } from "../dailyShare.js";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { activeHelper, advanceRace, advanceToNextChoice, allRuns, canGiveBoost, createRace, giveBoost, imageOf, nameOf, playerZone, raceOver, racerName } from "./raceRun.js";
import { RaceTrack } from "./RaceTrack.jsx";
import { SpecialtyBand } from "./TeamCompanion.jsx";
import { countText, specialtyStyle } from "./teamFormat.js";
const COUNTDOWN_MS = 3_000;
// Une image très en retard (onglet caché) n'avance pas la course d'un bond.
const MAX_FRAME_MS = 250;
const reducedMotion = () => Boolean(globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
/**
* Ce que l'écran montre d'une course, hors avancée des coureurs : il ne change que quelques fois par course. `boostValue` : la stat
* figée de l'élan en cours, prise dans la zone du clic.
*/
function snapshot(race) {
const { run } = race.player;
const helpers = allRuns(race).map(activeHelper);
return { zone: playerZone(race), used: run.used, helpers, boostValue: helpers[0] >= 0 ? Math.round(run.boostSpeed / BOOST_FACTOR) : null, finished: run.finishedAt !== null, over: raceOver(race) };
}
const sameSnapshot = (left, right) => left.zone === right.zone && left.boostValue === right.boostValue && left.finished === right.finished && left.over === right.over && left.used.length === right.used.length && left.helpers.every((helper, index) => helper === right.helpers[index]);
export function RaceLive({ catalog, race, companions, content, teamContent, statLabels, onBoost, onFinish, onOver }) {
const [stepped] = useState(reducedMotion);
// La course avance sur place, hors du rendu : React ne redessine que quand `view` change.
const raceRef = useRef(null);
const [view, setView] = useState(() => snapshot(createRace(race)));
const [countdown, setCountdown] = useState(() => (stepped ? 0 : Math.ceil(COUNTDOWN_MS / 1_000)));
const lanes = useRef([]);
const liveRef = useRef(null);
const finishSent = useRef(false);
const callbacks = useRef({});
useEffect(() => { callbacks.current = { onBoost, onFinish, onOver }; });
// Place les coureurs et met à jour l'écran si quelque chose a changé.
const show = useCallback(() => {
const current = raceRef.current;
allRuns(current).forEach((run, index) => lanes.current[index]?.style.setProperty("--progress", String(run.position / RACE_LENGTH)));
const next = snapshot(current);
setView((previous) => (sameSnapshot(previous, next) ? previous : next));
if (next.finished && !finishSent.current) {
finishSent.current = true;
callbacks.current.onFinish(current.player.run.boosts);
}
}, []);
useEffect(() => {
raceRef.current ??= createRace(race);
show();
if (stepped) return undefined;
let frame = 0;
let previous = null;
let wait = COUNTDOWN_MS;
let rest = 0;
function tick(now) {
const elapsed = previous === null ? 0 : Math.min(MAX_FRAME_MS, now - previous);
previous = now;
if (wait > 0) {
wait -= elapsed;
setCountdown(Math.max(0, Math.ceil(wait / 1_000)));
} else {
rest = advanceRace(raceRef.current, rest + elapsed);
show();
}
if (!raceOver(raceRef.current)) frame = requestAnimationFrame(tick);
}
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [race, show, stepped]);
// L'arrivée du dernier coureur passe au résultat.
useEffect(() => {
if (!view.over) return undefined;
const timer = setTimeout(() => callbacks.current.onOver(), stepped ? 0 : 700);
return () => clearTimeout(timer);
}, [view.over, stepped]);
const boost = useCallback((helper) => {
const current = raceRef.current;
if (!current || !canGiveBoost(current, helper)) return;
callbacks.current.onBoost(giveBoost(current, helper));
show();
}, [show]);
useEffect(() => { liveRef.current?.scrollIntoView({ block: "start" }); }, []);
const started = countdown === 0;
// Touches 1 à 4 : l'équipier de ce rang.
useEffect(() => {
if (!started) return undefined;
const onKey = (event) => {
if (event.altKey || event.ctrlKey || event.metaKey || event.repeat || event.target.closest?.("input, textarea, select, [contenteditable]")) return;
const helper = ["1", "2", "3", "4"].indexOf(event.key);
if (helper >= 0) boost(helper);
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [boost, started]);
function goOn() {
advanceToNextChoice(raceRef.current);
show();
}
const stat = race.zones[view.zone];
const nextStat = race.zones[view.zone + 1];
const left = race.helpers.length - view.used.length;
const helperId = (entry, index) => (view.helpers[index] >= 0 ? entry.helpers[view.helpers[index]].cardId : null);
const entries = [{ name: content.you, player: true, entry: race }, ...race.opponents.map((opponent) => ({ name: racerName(opponent, content), player: false, entry: opponent }))];
const companionOf = (cardId) => companions.find((companion) => companion.cardId === cardId);
return <div ref={liveRef} className="nebula-race-live">
<div className="nebula-race-stage">
<RaceTrack catalog={catalog} zones={race.zones} current={view.zone} statLabels={statLabels}
lanes={entries.map(({ name, player, entry }, index) => ({ name, player, cardId: entry.runner.cardId, helperId: helperId(entry, index) }))}
laneRef={(index) => (element) => { lanes.current[index] = element; }} />
{!started && <div className="nebula-race-countdown" role="status"><span>{countdown}</span></div>}
</div>
{view.finished ? <p className="nebula-race-arrived" role="status">{content.arrived}</p> : <>
<p className="nebula-race-zone" style={{ "--specialty": `var(--color-stat-${stat})` }}>
<span><MaskIcon name={stat} />{fillTemplate(content.zone, { stat: statLabels[stat], value: race.runner.stats[stat] })}</span>
<span>{nextStat ? fillTemplate(content.nextZone, { stat: statLabels[nextStat] }) : content.lastZone}</span>
</p>
<ul className="nebula-race-helpers" data-boosting={view.helpers[0] >= 0 || undefined}>{race.helpers.map((helper, index) => {
const used = view.used.includes(index);
const active = view.helpers[0] === index;
const blocked = used || !started || view.helpers[0] >= 0;
const name = nameOf(catalog, helper.cardId, teamContent);
// L'équipier qui donne son élan est tout de suite marqué : sa valeur est figée, une barre montre le temps qui reste.
const value = active ? view.boostValue : helper.stats[stat];
const label = active ? content.helperActive : used ? content.helperUsed : content.helperLabel;
return <li key={helper.cardId}><button className="nebula-race-mate" type="button" data-active={active || undefined} data-used={(used && !active) || undefined} aria-disabled={blocked || undefined}
aria-label={fillTemplate(label, { card: name, stat: statLabels[stat], value })} style={{ ...specialtyStyle(companionOf(helper.cardId) || { specialties: [] }), "--specialty": `var(--color-stat-${stat})` }} onClick={() => boost(index)}>
<span className="nebula-race-mate-art"><img src={imageOf(catalog, helper.cardId)} alt="" /><kbd aria-hidden="true">{index + 1}</kbd>
{active && <span className="nebula-race-mate-boost" aria-hidden="true" style={{ "--boost-ms": `${BOOST_MS}ms` }}>{content.boosting}<i /></span>}</span>
<SpecialtyBand companion={companionOf(helper.cardId) || { specialties: [] }} content={teamContent} statLabels={statLabels} />
<span className="nebula-race-mate-name">{name}</span>
<strong>+{value}</strong>
</button></li>;
})}</ul>
<div className="nds-toolbar nebula-race-help">
{stepped && <button className="nds-button" data-variant="primary" type="button" onClick={goOn}>{content.goOn}</button>}
<span>{left ? countText(stepped ? content.boostsLeftStepped : content.boostsLeft, left) : content.boostsDone}</span>
</div>
</>}
</div>;
}