Group Sokko TCG's interface files by Guild quest and card rendering

The 48 files of the Daily Card, Expeditions, Daily Team and race, Broken
Mirror and card rendering move to daily/, expeditions/, team/, mirror/ and
rendering/ under website/src/features/cards, with every relative import
rewritten. The root keeps the page, server calls, cache and the player
sections outside the Guild. The cards README, the quest recipe and the
current docs follow the new paths; dated audits and plans keep theirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-12-01 11:35:18 +01:00
parent 863050437f
commit 88c7bf8317
74 changed files with 165 additions and 161 deletions

View file

@ -0,0 +1,154 @@
/**
* @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>;
}

View file

@ -0,0 +1,117 @@
/**
* @file Page de la Course des courants : choix du coureur, course en direct, course interrompue et résultat.
*/
import { useEffect, useRef, useState } from "react";
import { finishRace, loadTeam, recordRaceBoosts, resetRace, startRace } from "../cardsApi.js";
import { RaceLive } from "./RaceLive.jsx";
import { RaceResult } from "./RaceResult.jsx";
import { RaceCircuit } from "./RaceTrack.jsx";
import { TeamCompanion } from "./TeamCompanion.jsx";
export function RacePanel({ catalog, runMutation, busy, content, teamContent, statLabels }) {
const [team, setTeam] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [notice, setNotice] = useState("");
// Course lancée sur cette page : elle s'anime, puis laisse la place au résultat.
const [live, setLive] = useState(null);
const [finished, setFinished] = useState(null);
const titleRef = useRef(null);
useEffect(() => {
let active = true;
loadTeam()
.then((result) => { if (active) { setTeam(result.team); setLoadError(""); } })
.catch((error) => { if (active) setLoadError(error.message); });
return () => { active = false; };
}, [reloadKey]);
const showResult = !live && team?.race?.status === "finished";
const wasLive = useRef(false);
useEffect(() => {
if (live) wasLive.current = true;
else if (wasLive.current && showResult) titleRef.current?.focus();
}, [live, showResult]);
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p><button className="nds-button" data-variant="secondary" type="button" onClick={() => setReloadKey((key) => key + 1)}>{teamContent.retry}</button></section>;
if (!team) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
// Les refus propres à la course restent dans ce panneau ; runMutation garde le reste (erreurs réseau, solde).
async function play(action) {
setNotice("");
const result = await runMutation(async () => {
try {
return await action();
} catch (error) {
if (/^(RACE|TEAM)_/.test(String(error.code || ""))) return { raceError: error };
throw error;
}
});
if (result?.raceError) {
setNotice(result.raceError.message);
setLive(null);
setReloadKey((key) => key + 1);
}
return result?.team || null;
}
async function start(cardId) {
const next = await play(() => startRace(team.day, cardId));
if (!next?.race) return;
setTeam(next);
setFinished(null);
setLive(next.race);
}
// L'arrivée du joueur est envoyée aussitôt ; le résultat s'affiche quand tous les coureurs sont arrivés à l'écran.
async function finish(boosts) {
const next = await play(() => finishRace(boosts));
if (next) setFinished(next);
return next;
}
async function over() {
const next = finished || await finish(null);
if (next) setTeam(next);
setLive(null);
}
// Développement : la course du jour s'efface, l'équipe reste.
async function rerun() {
const next = await play(() => resetRace());
if (!next) return;
setLive(null);
setFinished(null);
setTeam(next);
}
async function finishInterrupted() {
const next = await finish(null);
if (next) setTeam(next);
}
const { race } = team;
const interrupted = !live && race?.status === "running";
const choosing = !live && !race && team.status === "ready" && team.raceEnabled;
return <section className="nebula-race" aria-labelledby="nebula-race-title">
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-race-title">{content.title}</h2></div>
<div className="nebula-team-heading-actions">{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={rerun}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a></div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
{live && <RaceLive key={live.day} catalog={catalog} race={live} companions={team.companions} content={content} teamContent={teamContent} statLabels={statLabels}
onBoost={(boosts) => { recordRaceBoosts(boosts).catch(() => {}); }} onFinish={finish} onOver={over} />}
{interrupted && <div className="nds-panel nebula-race-interrupted"><h3>{content.interruptedTitle}</h3><p>{content.interruptedText}</p><button className="nds-button" data-variant="primary" type="button" disabled={busy} onClick={finishInterrupted}>{content.interruptedAction}</button></div>}
{showResult && <RaceResult catalog={catalog} race={race} nextAt={team.nextAt} content={content} teamContent={teamContent} statLabels={statLabels} titleRef={titleRef} />}
{!live && !race && !choosing && <div className="nds-empty-state"><p>{!team.enabled ? teamContent.closed : !team.raceEnabled ? content.closed : content.needTeam}</p>{team.raceEnabled && <a className="nds-button" data-variant="primary" href="#/cards/team">{content.recruitFirst}</a>}</div>}
{choosing && <>
<RaceCircuit zones={team.zones} content={content} statLabels={statLabels} />
<section className="nebula-race-choice" aria-labelledby="nebula-race-choice-title">
<h3 id="nebula-race-choice-title">{content.chooseTitle}</h3>
<p className="nebula-race-intro">{content.intro}</p>
<ul className="nebula-team-list">{team.companions.map((companion) => <li key={companion.cardId}><TeamCompanion catalog={catalog} companion={companion} content={{ ...teamContent, recruitLabel: content.chooseLabel }} statLabels={statLabels} disabled={busy} actionLabel={content.chooseAction} onSelect={() => start(companion.cardId)} /></li>)}</ul>
</section>
</>}
</section>;
}

View file

@ -0,0 +1,129 @@
/**
* @file Résultat d'une Course des courants finie : la place et la récompense, l'arrivée en couloirs, puis le
* bilan (temps, élans posés sur le circuit, équipiers), pour apprendre après coup sans être guidé
* pendant la course.
*/
import { useMemo, useState } from "react";
import { CurrencyIcon } from "../Currency.jsx";
import { fillTemplate, formatCountdown } from "../dailyShare.js";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { imageOf, nameOf, racerName, raceRanking, raceReview } from "./raceRun.js";
import { formatStardust } from "../stardustFormat.js";
const formatTime = (milliseconds) => `${(milliseconds / 1_000).toLocaleString("fr-FR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} s`;
const placeText = (place, content) => fillTemplate(place === 1 ? content.placeFirst : content.placeOther, { place });
const ordinal = (place) => `${place}${place === 1 ? "re" : "e"}`;
// En dessous, l'écart avec les meilleurs élans ne vaut pas d'être signalé.
const NEAR_BEST_MS = 150;
// Arrivée en couloirs, du premier au dernier : chaque coureur est placé selon son temps, le plus rapide contre la ligne d'arrivée.
// Dans le couloir du joueur, une silhouette dorée montre où l'auraient mené les meilleurs élans.
function RaceFinish({ catalog, race, review, showBest, content, teamContent }) {
const ranking = raceRanking(race);
const times = [...ranking.map((entry) => entry.finishedAt), ...(showBest ? [review.best] : [])];
const [fastest, slowest] = [Math.min(...times), Math.max(...times)];
const at = (time) => (slowest === fastest ? 1 : (slowest - time) / (slowest - fastest));
return <ol className="nebula-race-finish">{ranking.map((entry, index) => {
const image = imageOf(catalog, entry.runner.cardId);
return <li key={entry.index} data-player={entry.player || undefined}>
<span className="nebula-race-finish-place">{index + 1}</span>
<span className="nebula-race-finish-who"><img src={image} alt="" />
<span><strong>{entry.player ? content.you : racerName(entry, content)}</strong><small>{nameOf(catalog, entry.runner.cardId, teamContent)}{entry.ghost && ` · ${content.ghost}`}</small></span></span>
<span className="nebula-race-finish-track" aria-hidden="true">
{entry.player && showBest && <>
<span className="nebula-race-finish-gap" style={{ "--from": at(entry.finishedAt), "--to": at(review.best) }} />
<img className="nebula-race-finish-ghost" src={image} alt="" style={{ "--at": at(review.best) }} />
</>}
<img className="nebula-race-finish-runner" src={image} alt="" style={{ "--at": at(entry.finishedAt) }} />
</span>
<span className="nebula-race-finish-time">{formatTime(entry.finishedAt)}{entry.player && showBest && <small aria-hidden="true">{fillTemplate(content.reviewBestTime, { time: formatTime(review.best) })}</small>}</span>
</li>;
})}</ol>;
}
// Remplit un texte dont les valeurs peuvent être des éléments (nom de zone en couleur, nombre en gras).
function fillParts(template, values) {
return template.split(/(\{\w+\})/).map((part, index) => {
const key = part.match(/^\{(\w+)\}$/)?.[1];
return key && key in values ? <span key={index}>{values[key]}</span> : part;
});
}
// Nom d'une zone, à sa couleur et avec son icône.
function ZoneName({ stat, statLabels }) {
return <span className="nebula-race-zone-name" style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} />{statLabels[stat]}</span>;
}
function RaceReview({ catalog, race, review, content, teamContent, statLabels }) {
const gain = review.mine - review.best;
const perfect = gain <= NEAR_BEST_MS;
// Pas de phrase à part : ce que les temps ne disent pas d'eux-mêmes (écart, place possible, élans presque parfaits) tient sous
// le temps des meilleurs élans.
const bestNote = perfect
? (race.place === 1 ? content.reviewBestPerfect : content.reviewBestPerfectBeaten)
: fillTemplate(review.bestPlace < race.place ? content.reviewBestGainPlace : content.reviewBestGain, { gain: formatTime(gain), place: ordinal(review.bestPlace) });
const tiles = [
{ key: "plain", label: content.reviewPlain, time: review.plain },
{ key: "mine", label: content.reviewMine, time: review.mine, note: fillTemplate(content.reviewBoostsGain, { gain: formatTime(review.plain - review.mine) }) },
{ key: "best", label: content.reviewBest, time: review.best, note: bestNote, perfect }
];
const name = (cardId) => nameOf(catalog, cardId, teamContent);
const missed = review.boosts.filter((boost) => !boost.stat || boost.value < boost.bestValue);
return <section className="nds-panel nebula-race-review" aria-labelledby="nebula-race-review-title">
<h3 id="nebula-race-review-title">{content.reviewTitle}</h3>
<ol className="nebula-race-review-times">{tiles.map((tile) => <li key={tile.key} data-kind={tile.key} data-perfect={tile.perfect || undefined}>
<span>{tile.label}</span><strong>{formatTime(tile.time)}</strong>{tile.note && <small>{tile.note}</small>}
</li>)}</ol>
{/* Le choix du coureur vient avant les élans : la remarque passe avant le circuit. */}
{review.fasterRunner && <p className="nebula-race-review-runner"><img src={imageOf(catalog, review.fasterRunner)} alt="" />
<span>{fillParts(content.reviewRunner, { card: <strong>{name(review.fasterRunner)}</strong>, runner: <strong>{name(race.runner.cardId)}</strong> })}</span></p>}
<h4>{content.reviewBoostsTitle}</h4>
<ol className="nebula-race-review-road" aria-label={content.reviewRoadLabel}>{race.zones.map((stat, zone) => {
const here = review.boosts.filter((boost) => boost.zone === zone);
return <li key={zone} style={{ "--specialty": `var(--color-stat-${stat})` }}>
<span className="nebula-race-review-zone"><MaskIcon name={stat} /><span>{statLabels[stat]}</span></span>
<span className="nebula-race-review-given">{here.map((boost) => {
const missed = boost.value < boost.bestValue;
// Élan qui valait plus ailleurs : bordure en pointillés à la couleur de la meilleure stat de l'équipier, pas de la zone.
return <span key={boost.cardId} data-missed={missed || undefined} style={missed ? { "--better": `var(--color-stat-${boost.bestStat})` } : undefined}>
<img src={imageOf(catalog, boost.cardId)} alt={name(boost.cardId)} title={missed ? fillTemplate(content.reviewBetterBadge, { value: `+${boost.bestValue}`, stat: statLabels[boost.bestStat] }) : name(boost.cardId)} />
<b>+{boost.value}</b>
</span>;
})}</span>
</li>;
})}</ol>
{/* Le circuit montre déjà chaque élan : on ne détaille que ceux qui valaient plus ailleurs, ou qui n'ont pas été donnés. */}
{missed.length > 0 && <>
<h4>{content.reviewNotesTitle}</h4>
<ul className="nebula-race-review-notes">{missed.map((boost) => <li key={boost.cardId}>
<img src={imageOf(catalog, boost.cardId)} alt="" style={{ "--better": `var(--color-stat-${boost.bestStat})` }} />
<p>{boost.stat
? fillParts(content.reviewNoteGiven, { card: <strong>{name(boost.cardId)}</strong>, zone: <ZoneName stat={boost.stat} statLabels={statLabels} />, value: <b>+{boost.value}</b> })
: fillParts(content.reviewNoteMissing, { card: <strong>{name(boost.cardId)}</strong> })}
{" "}{fillParts(content.reviewNoteBetter, { zone: <ZoneName stat={boost.bestStat} statLabels={statLabels} />, value: <b>+{boost.bestValue}</b> })}</p>
</li>)}</ul>
</>}
</section>;
}
export function RaceResult({ catalog, race, nextAt, content, teamContent, statLabels, titleRef }) {
const [now] = useState(() => Date.now());
const review = useMemo(() => raceReview(race), [race]);
const showBest = review.mine - review.best > NEAR_BEST_MS;
return <div className="nebula-race-outcome">
<section className="nds-panel nebula-race-result" aria-labelledby="nebula-race-result-title" data-place={race.place}>
<div className="nebula-race-result-head">
<span className="nebula-race-medal" aria-hidden="true">{race.place}<small>{race.place === 1 ? "re" : "e"}</small></span>
<div>
<h3 id="nebula-race-result-title" ref={titleRef} tabIndex={-1}>{placeText(race.place, content)}</h3>
<p className="nebula-race-reward">{race.reward > 0 ? <><CurrencyIcon kind="stardust" />{fillTemplate(content.earned, { reward: formatStardust(race.reward) })}</> : content.noReward}</p>
</div>
</div>
<RaceFinish catalog={catalog} race={race} review={review} showBest={showBest} content={content} teamContent={teamContent} />
<p className="nebula-race-next">{fillTemplate(content.next, { time: formatCountdown(nextAt - now) })}</p>
</section>
<RaceReview catalog={catalog} race={race} review={review} content={content} teamContent={teamContent} statLabels={statLabels} />
</div>;
}

View file

@ -0,0 +1,49 @@
/**
* @file Dessine le parcours d'une course et les coureurs sur leurs couloirs.
*/
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { fillTemplate } from "../dailyShare.js";
import { imageOf } from "./raceRun.js";
import { countText } from "./teamFormat.js";
export function RaceZones({ zones, current = -1, statLabels }) {
return <ol className="nebula-race-zones">{zones.map((stat, index) => <li key={index} style={{ "--specialty": `var(--color-stat-${stat})` }} data-current={index === current || undefined} aria-current={index === current ? "step" : undefined}>
<MaskIcon name={stat} /><span>{statLabels[stat]}</span>
</li>)}</ol>;
}
// Circuit du jour, avant le départ : les zones numérotées du départ à l'arrivée, ce que veut dire leur couleur, et combien
// de zones compte chaque stat, pour choisir son coureur.
export function RaceCircuit({ zones, content, statLabels }) {
const counts = [...new Set(zones)].map((stat) => ({ stat, count: zones.filter((zone) => zone === stat).length })).sort((left, right) => right.count - left.count);
return <section className="nds-panel nebula-race-circuit" aria-labelledby="nebula-race-circuit-title">
<div className="nebula-race-circuit-head">
<h3 id="nebula-race-circuit-title">{content.circuitTitle}</h3>
<ul className="nebula-race-circuit-counts">{counts.map(({ stat, count }) => <li key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} />{countText(content.circuitCount, count, { stat: statLabels[stat] })}</li>)}</ul>
</div>
<p>{content.circuitText}</p>
<div className="nebula-race-circuit-road">
<span className="nebula-race-circuit-end">{content.circuitStart}</span>
<ol className="nebula-race-zones">{zones.map((stat, index) => <li key={index} style={{ "--specialty": `var(--color-stat-${stat})` }}>
<small>{fillTemplate(content.circuitZone, { number: index + 1 })}</small><MaskIcon name={stat} /><span>{statLabels[stat]}</span>
</li>)}</ol>
<span className="nebula-race-circuit-end" data-end="finish">{content.circuitFinish}</span>
</div>
</section>;
}
// `lanes` : [{ name, player, cardId, helperId }] ; `laneRef(index)` reçoit l'élément du coureur, dont la page règle l'avancée.
export function RaceTrack({ catalog, zones, current, lanes, laneRef, statLabels }) {
return <div className="nebula-race-track">
<RaceZones zones={zones} current={current} statLabels={statLabels} />
{lanes.map((lane, index) => <div key={index} className="nebula-race-lane" data-player={lane.player || undefined}>
<div className="nebula-race-ground" aria-hidden="true">{zones.map((stat, zone) => <i key={zone} style={{ "--specialty": `var(--color-stat-${stat})` }} />)}</div>
<div className="nebula-race-runner" ref={laneRef(index)} data-boosted={lane.helperId ? true : undefined}>
<img src={imageOf(catalog, lane.cardId)} alt="" />
{lane.helperId && <img className="nebula-race-helper" src={imageOf(catalog, lane.helperId)} alt="" />}
</div>
<span className="nebula-race-name">{lane.name}</span>
</div>)}
</div>;
}

View file

@ -0,0 +1,38 @@
/**
* @file Présente un compagnon de l'Équipe du jour : illustration, spécialité en couleur, Puissance et stats
* fortes.
*/
import { STAT_IDS } from "../expeditions/expeditionFormat.js";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { fillTemplate } from "../dailyShare.js";
import { bandOf, BALANCED, mainStats, specialtyStyle } from "./teamFormat.js";
export function SpecialtyBand({ companion, content, statLabels }) {
return <span className="nebula-team-band">{bandOf(companion).map((id) => <span key={id} style={{ "--specialty": `var(--color-stat-${id})` }}>
<MaskIcon name={id} />{id === BALANCED ? content.balanced : statLabels[id]}
</span>)}</span>;
}
// `onSelect` : toute la carte devient un bouton, avec `actionLabel` en pied. `badge` : mention sur l'illustration.
export function TeamCompanion({ catalog, companion, content, statLabels, badge = "", footer = null, onSelect = null, actionLabel = "", disabled = false, showPower = true, size = "md" }) {
const card = catalog.cards.find((item) => item.id === companion.cardId);
const strong = mainStats(companion);
const name = card?.name || content.unknownCard;
const Tag = onSelect ? "button" : "div";
const action = onSelect ? { type: "button", disabled, onClick: onSelect, "aria-label": fillTemplate(content.recruitLabel, { card: name }) } : {};
return <Tag className="nebula-team-companion" data-size={size} style={specialtyStyle(companion)} {...action}>
<span className="nebula-team-art">
{card?.image && <img src={card.image} alt="" loading="lazy" draggable="false" />}
{badge && <span className="nebula-team-tag">{badge}</span>}
{companion.lent && <span className="nebula-team-tag" data-side="end">{content.lent}</span>}
</span>
<SpecialtyBand companion={companion} content={content} statLabels={statLabels} />
<span className="nebula-team-name">{name}</span>
{showPower && <span className="nebula-team-power">{fillTemplate(content.power, { power: companion.power })}</span>}
<span className="nebula-team-strong">{strong.map((stat) => <span key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} /><span className="sr-only">{statLabels[stat]} </span>{companion.stats[stat]}</span>)}</span>
{size !== "sm" && <span className="nebula-team-stats">{STAT_IDS.filter((stat) => !strong.includes(stat)).map((stat) => <span key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} /><span className="sr-only">{statLabels[stat]} </span>{companion.stats[stat]}</span>)}</span>}
{footer}
{onSelect && <span className="nebula-team-action" aria-hidden="true">{actionLabel}</span>}
</Tag>;
}

View file

@ -0,0 +1,122 @@
/**
* @file Page de l'Équipe du jour : réserve d'étoiles dorées, recrutement, équipe prête et choix de la garder
* ou d'en recruter une autre.
*/
import { useEffect, useRef, useState } from "react";
import { chooseTeamCharacter, healTeamCompanion, keepTeamCompanion, loadTeam, recruitTeam, rerollTeamOffer, resetTeam, revealTeamStar } from "../cardsApi.js";
import { fillTemplate } from "../dailyShare.js";
import { ITEM_ART } from "../expeditions/expeditionFormat.js";
import { TeamRecruitment } from "./TeamRecruitment.jsx";
import { TeamSky } from "./TeamSky.jsx";
import { TeamTable } from "./TeamTable.jsx";
import { TeamWelcome } from "./TeamWelcome.jsx";
import { averagePower, countText } from "./teamFormat.js";
function GoldReserve({ team, content }) {
return <span className="nebula-team-reserve" role="img" aria-label={fillTemplate(content.reserveLabel, { count: team.goldStars, max: team.maxGoldStars })}>
<span>{content.reserve}</span>
{Array.from({ length: team.maxGoldStars }, (_, index) => <i key={index} data-full={index < team.goldStars || undefined}>★</i>)}
</span>;
}
// Baumes disponibles, à côté des étoiles dorées : ils soignent un compagnon affaibli pendant le recrutement.
function BalmCount({ team, content }) {
return <span className="nebula-team-balms" role="img" aria-label={fillTemplate(content.balmsLabel, { count: team.balms ?? 0 })} title={content.balmsHelp}>
<img src={ITEM_ART.balm} alt="" /><span>{content.balms}</span><strong>{team.balms ?? 0}</strong>
</span>;
}
// Recruter remplace l'équipe : une équipe encore utilisable demande une confirmation.
function RecruitAction({ team, content, busy, onRecruit }) {
const [confirming, setConfirming] = useState(false);
const losing = team.status === "ready";
const reserve = team.goldStars ? countText(content.reserveWillBeUsed, team.goldStars) : content.reserveEmpty;
if (confirming) return <div className="nds-inline-notice nebula-team-confirm" data-variant="warning" role="group" aria-label={content.confirmTitle}>
<p>{content.confirmText} {reserve}</p>
<div className="nds-toolbar">
<button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={onRecruit}>{content.confirmAction}</button>
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" autoFocus onClick={() => setConfirming(false)}>{content.keepTeam}</button>
</div>
</div>;
return <div className="nebula-team-recruit">
<button className="nds-button" data-variant={losing ? "secondary" : "primary"} type="button" disabled={busy} onClick={() => (losing ? setConfirming(true) : onRecruit())}>{losing ? content.recruitAnother : content.recruitStart}</button>
<p>{reserve}</p>
</div>;
}
export function TeamPanel({ catalog, state, runMutation, busy, content, statLabels }) {
const [team, setTeam] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [notice, setNotice] = useState("");
// Paliers du recrutement qui vient de se terminer : le bilan dévoile ses étoiles une fois, avant de jouer.
const [finishedPowers, setFinishedPowers] = useState(null);
const readyTitleRef = useRef(null);
useEffect(() => { if (finishedPowers) readyTitleRef.current?.focus(); }, [finishedPowers]);
useEffect(() => {
let active = true;
loadTeam()
.then((result) => { if (active) { setTeam(result.team); setLoadError(""); } })
.catch((error) => { if (active) setLoadError(error.message); });
return () => { active = false; };
}, [reloadKey]);
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p><button className="nds-button" data-variant="secondary" type="button" onClick={() => setReloadKey((key) => key + 1)}>{content.retry}</button></section>;
if (!team) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
// Les refus propres à l'équipe restent dans ce panneau ; runMutation garde le reste (erreurs réseau, solde).
async function play(action) {
setNotice("");
const result = await runMutation(async () => {
try {
return await action();
} catch (error) {
if (String(error.code || "").startsWith("TEAM_")) return { teamError: error };
throw error;
}
});
if (result?.team) {
if (team.status === "recruiting" && result.team.status === "ready") setFinishedPowers(team.recruitment.powers);
setTeam(result.team);
} else if (result?.teamError) {
setNotice(result.teamError.message);
setReloadKey((key) => key + 1);
}
}
const recruiting = team.status === "recruiting";
const dailyToPlay = state.daily && (state.daily.status === "playing" || state.daily.rewardPending);
const recruit = () => play(() => recruitTeam(team.day));
const recruitBlock = team.canRecruit && <>
{dailyToPlay && team.goldStars < team.maxGoldStars && <p className="nds-inline-notice" role="status">{content.dailyFirst} <a href="#/cards/daily">{content.dailyLink}</a></p>}
<RecruitAction key={team.status} team={team} content={content} busy={busy} onRecruit={recruit} />
</>;
return <section className="nebula-team" aria-labelledby="nebula-team-title" aria-busy={busy || undefined}>
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-team-title">{content.title}</h2></div>
<div className="nebula-team-heading-actions"><GoldReserve team={team} content={content} /><BalmCount team={team} content={content} />{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => { setFinishedPowers(null); play(() => resetTeam()); }}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a></div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
{!team.enabled && !recruiting && <p className="nds-inline-notice" role="status">{content.closed}</p>}
{recruiting && <TeamRecruitment catalog={catalog} team={team} content={content} statLabels={statLabels} busy={busy}
onChoose={(cardId) => play(() => chooseTeamCharacter(cardId))} onReroll={(offer) => play(() => rerollTeamOffer(offer))} onReveal={(index) => play(() => revealTeamStar(index))} onHeal={() => play(() => healTeamCompanion(team.recruitment.current.cardId))} onKeep={() => play(() => keepTeamCompanion(team.recruitment.current.cardId))} />}
{!recruiting && finishedPowers && team.status === "ready" && <section className="nebula-team-ready" aria-label={content.readyTitle}>
<TeamTable catalog={catalog} companions={team.companions} content={content} statLabels={statLabels} powers={finishedPowers} size="md"
title={content.readyTitle} titleId="nebula-team-ready-title" titleRef={readyTitleRef}
status={<>{fillTemplate(content.readyText, { power: averagePower(team.companions) })}{team.lastDust > 0 && ` ${fillTemplate(content.readyDust, { count: team.lastDust })}`}</>}
action={<a className="nds-button" data-size="sm" data-variant="primary" href="#/cards/guild">{content.back}</a>} />
<div className="nds-panel nebula-team-stars-panel"><p>{content.skyRevealed}</p><TeamSky sky={team.lastSky} content={content} /></div>
</section>}
{!recruiting && !(finishedPowers && team.status === "ready") && <>
{team.status === "ready" ? <section className="nebula-team-ready" aria-label={content.yourTeam}>
<TeamTable catalog={catalog} companions={team.companions} content={content} statLabels={statLabels} size="md"
title={fillTemplate(content.teamDay, { day: team.teamDay, max: team.maxDays })} titleId="nebula-team-current-title"
status={<>{team.teamDay === team.maxDays ? content.lastDay : team.canRecruit ? content.keepOrRecruit : content.teamText}<span className="nebula-team-days" aria-hidden="true">{Array.from({ length: team.maxDays }, (_, index) => <i key={index} data-on={index < team.teamDay || undefined} />)}</span></>} />
</section> : <TeamWelcome catalog={catalog} team={team} content={content} action={recruitBlock} />}
{team.status === "ready" && recruitBlock}
</>}
</section>;
}

View file

@ -0,0 +1,130 @@
/**
* @file Recrutement de l'Équipe du jour : choix d'un personnage, puis amélioration en révélant des étoiles.
*/
import { useEffect, useRef } from "react";
import { CurrencyIcon } from "../Currency.jsx";
import { fillTemplate } from "../dailyShare.js";
import { ITEM_ART } from "../expeditions/expeditionFormat.js";
import { TeamCompanion } from "./TeamCompanion.jsx";
import { TeamSky } from "./TeamSky.jsx";
import { TeamBest, TeamTable } from "./TeamTable.jsx";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { BALANCED, bandOf, countText, isMissing, mainStats, riskLevel, riskPct, specialtyStyle } from "./teamFormat.js";
// Étoiles encore cachées : un nombre par sorte, avec son effet en quelques mots.
function StarsLeft({ recruitment, content }) {
const { hidden, dustValue, fallPower } = recruitment;
const rows = [
["gold", "★", content.starGold],
["black", "✖", fillTemplate(content.starBlack, { power: fallPower })],
["dust", <CurrencyIcon key="dust" kind="stardust" />, fillTemplate(content.starDust, { value: dustValue })]
];
return <section className="nebula-team-stars-left" aria-labelledby="nebula-team-stars-left-title">
<h3 id="nebula-team-stars-left-title">{content.starsLeft}</h3>
<ul>{rows.map(([kind, icon, effect]) => <li key={kind} data-kind={kind} data-empty={!hidden[kind] || undefined}>
<i aria-hidden="true">{icon}</i><strong>{hidden[kind]}</strong><span><span className="sr-only">{content.stars[kind]} : </span>{effect}</span>
</li>)}</ul>
</section>;
}
// Les deux étapes d'un compagnon, avec les numéros dorés de l'accueil.
// L'équipe en bref : une mini-carte par place, sans illustration, à la couleur de la spécialité (bicolore s'il y en a deux), avec
// l'icône et la Puissance ; la place en cours en doré, les places libres en pointillés.
function MiniTeam({ companions, size, content, statLabels }) {
return <ol className="nebula-team-mini" aria-label={content.yourTeam}>{Array.from({ length: size }, (_, index) => {
const companion = companions[index];
if (!companion) return <li key={index} data-current={index === companions.length || undefined}><span aria-hidden="true">{index === companions.length ? "?" : index + 1}</span><span className="sr-only">{index === companions.length ? content.seatCurrent : content.seat}</span></li>;
const band = bandOf(companion);
const names = band.map((id) => (id === BALANCED ? content.balanced : statLabels[id]));
return <li key={index} data-filled="true" style={specialtyStyle(companion)} title={names.join(" · ")}>
<span className="nebula-team-mini-icons" aria-hidden="true">{band.map((id) => <MaskIcon key={id} name={id} />)}</span>
<strong>{companion.power}</strong>
<span className="sr-only">{names.join(", ")}</span>
</li>;
})}</ol>;
}
function Steps({ step, content }) {
return <ol className="nebula-team-steps">{[content.stepRecruit, content.stepImprove].map((label, index) => <li key={label} data-current={step === index + 1 || undefined} aria-current={step === index + 1 ? "step" : undefined}>
<span aria-hidden="true">{index + 1}</span>{label}
</li>)}</ol>;
}
function Improve({ catalog, recruitment, last, content, statLabels, busy, titleRef, onReveal, onHeal, onKeep }) {
const { current, powers, hidden, sky } = recruitment;
const top = current.step === powers.length - 1;
const total = hidden.gold + hidden.black + hidden.dust;
const over = current.fallen || top || !total;
const risk = riskPct(hidden);
const strong = mainStats(current);
const keepRef = useRef(null);
// Fin des essais : le bouton qui continue reçoit le focus, l'étoile cliquée ne réagit plus.
useEffect(() => { if (over) keepRef.current?.focus({ preventScroll: true }); }, [over]);
return <div className="nebula-team-improve">
<h3 ref={titleRef} tabIndex={-1}>{content.improveTitle}</h3>
<TeamCompanion catalog={catalog} companion={current} content={content} statLabels={statLabels} />
<div className="nebula-team-stars-panel">
<ol className="nebula-team-ladder" data-fallen={(current.fallen && !current.healed) || undefined}>{powers.map((power, index) => <li key={power} data-state={index <= (current.healed ? 0 : current.step) ? "reached" : index === current.step + 1 && !over ? "next" : undefined}>
<small>{index ? countText(content.ladderStep, index) : content.ladderStart}</small>
<strong>{power}</strong>
<small>{strong.map((stat) => `${statLabels[stat]} ${recruitment.ladder[index][stat]}`).join(" · ")}</small>
</li>)}</ol>
<TeamSky sky={sky} content={content} canReveal={!over && !busy} onReveal={onReveal} />
<p className="nebula-team-risk" role="status">
{current.healed ? <strong data-risk="low">{fillTemplate(content.healed, { power: current.power })}</strong> : current.fallen ? fillTemplate(content.fallen, { power: recruitment.fallPower }) : top ? content.top : !total ? content.noStars
: hidden.black > 0 ? <>{content.risk} <strong data-risk={riskLevel(risk)}>{fillTemplate(content.riskValue, { risk })}</strong></> : <strong data-risk="low">{content.noRisk}</strong>}
</p>
<div className="nds-toolbar nebula-team-actions">
<button ref={keepRef} className="nds-button" data-variant={over ? "primary" : "secondary"} type="button" disabled={busy} onClick={onKeep}>{over ? (last ? content.seeTeam : content.nextCompanion) : fillTemplate(content.keepAt, { power: current.power })}</button>
{!over && <span>{content.orClickStar}</span>}
{current.fallen && !current.healed && recruitment.balms > 0 && <button className="nds-button nebula-team-heal" data-variant="secondary" type="button" disabled={busy} onClick={onHeal}><img src={ITEM_ART.balm} alt="" />{fillTemplate(content.heal, { power: powers[0], count: recruitment.balms })}</button>}
</div>
<p className="nebula-team-note">{content.starsShared}</p>
</div>
</div>;
}
export function TeamRecruitment({ catalog, team, content, statLabels, busy, onChoose, onReroll, onReveal, onHeal, onKeep }) {
const { recruitment, companions } = team;
const count = companions.length + 1;
const titleRef = useRef(null);
const step = `${count}-${recruitment.current ? "improve" : "offer"}`;
const shownStep = useRef(step);
// Chaque étape remplace la précédente : son titre reçoit le focus, pour le clavier, le lecteur d'écran et le défilement.
useEffect(() => {
if (shownStep.current === step) return;
shownStep.current = step;
titleRef.current?.focus();
}, [step]);
return <div className="nebula-team-recruiting">
<section className="nds-panel nebula-team-stage" aria-label={fillTemplate(content.stepCount, { count, max: recruitment.size })}>
<Steps step={recruitment.current ? 2 : 1} content={content} />
<div className="nebula-team-stage-main">{recruitment.current
? <Improve key={recruitment.current.cardId} catalog={catalog} recruitment={recruitment} last={count === recruitment.size} content={content} statLabels={statLabels} busy={busy} titleRef={titleRef} onReveal={onReveal} onHeal={onHeal} onKeep={onKeep} />
: <section aria-labelledby="nebula-team-offer-title" className="nebula-team-offer">
<h3 id="nebula-team-offer-title" ref={titleRef} tabIndex={-1}>{content.offerTitle}</h3>
<p>{fillTemplate(content.offerText, { power: recruitment.powers[0] })}{companions.length === 0 && recruitment.extraGold > 0 && <> <strong>{countText(content.reserveUsed, recruitment.extraGold)}</strong></>}</p>
{/* Le bouton qui renouvelle la proposition, au-dessus des cartes, aligné sur leur bord droit. */}
<div className="nebula-team-offer-pick">
<div className="nebula-team-reroll"><button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy || !recruitment.rerolls} title={recruitment.rerolls ? countText(content.rerollsLeft, recruitment.rerolls) : content.rerollsNone} onClick={() => onReroll(recruitment.offer.map((companion) => companion.cardId))}>
{content.reroll}<span className="nebula-team-reroll-count" aria-hidden="true">×{recruitment.rerolls}</span><span className="sr-only">{recruitment.rerolls ? countText(content.rerollsLeft, recruitment.rerolls) : content.rerollsNone}</span>
</button></div>
<div className="nebula-team-offer-cards">{recruitment.offer.map((companion) => <TeamCompanion key={companion.cardId} catalog={catalog} companion={companion} content={content} statLabels={statLabels} showPower={false} disabled={busy}
badge={isMissing(companion, companions) ? content.missing : ""} actionLabel={content.recruitAction} onSelect={() => onChoose(companion.cardId)} />)}</div>
</div>
</section>}</div>
<div className="nebula-team-stage-side">
<StarsLeft recruitment={recruitment} content={content} />
{/* Rappel des points forts de l'équipe, pour comparer les cartes proposées sans descendre jusqu'à elle. */}
<section className="nebula-team-stage-best" aria-labelledby="nebula-team-stage-best-title">
<h3 id="nebula-team-stage-best-title">{content.stageBestTitle}</h3>
<MiniTeam companions={companions} size={recruitment.size} content={content} statLabels={statLabels} />
{companions.length ? <TeamBest companions={companions} content={content} statLabels={statLabels} /> : <p>{content.stageBestEmpty}</p>}
</section>
</div>
</section>
<TeamTable catalog={catalog} companions={companions} slots={recruitment.size} content={content} statLabels={statLabels} powers={recruitment.powers}
title={content.yourTeam} titleId="nebula-team-summary-title" status={fillTemplate(content.stepCount, { count, max: recruitment.size })} seatLabel={content.seat} currentLabel={content.seatCurrent} />
</div>;
}

View file

@ -0,0 +1,23 @@
/**
* @file Affiche les étoiles d'un recrutement, cachées ou révélées, et laisse choisir celle à révéler.
*/
import { CurrencyIcon } from "../Currency.jsx";
import { fillTemplate } from "../dailyShare.js";
// Le ciel tient sur deux rangées.
function Star({ star, index, content, canReveal, onReveal }) {
const label = star.kind ? content.stars[star.kind] : fillTemplate(content.hiddenStar, { number: index + 1 });
const locked = Boolean(star.kind) || !canReveal;
return <button className="nebula-team-star" type="button" data-kind={star.kind || "hidden"} data-missed={(star.kind && !star.revealed) || undefined} aria-label={label} aria-disabled={locked || undefined} onClick={() => { if (!locked) onReveal(index); }}>
<span aria-hidden="true">{star.kind === "dust" ? <CurrencyIcon kind="stardust" /> : { gold: "★", black: "✖" }[star.kind] || "?"}</span>
</button>;
}
export function TeamSky({ sky, content, canReveal = false, onReveal = () => {} }) {
const half = Math.ceil(sky.length / 2);
const rows = [[sky.slice(0, half), 0], [sky.slice(half), half]];
return <div className="nebula-team-sky" role="group" aria-label={content.skyLabel} style={{ "--star-count": half }}>{rows.map(([stars, start]) => <div key={start}>
{stars.map((star, position) => <Star key={start + position} star={star} index={start + position} content={content} canReveal={canReveal} onReveal={onReveal} />)}
</div>)}</div>;
}

View file

@ -0,0 +1,43 @@
/**
* @file Bloc « Votre équipe », le même sur la Guilde et sur la page Équipe du jour : la table de l'équipe en
* fond, ses compagnons (ou leurs places à pourvoir, numérotées en pointillés), puis ses points forts.
* L'équipe n'y est liée à aucun jeu.
*/
import { STAT_IDS } from "../expeditions/expeditionFormat.js";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { TeamCompanion } from "./TeamCompanion.jsx";
import { fateOf, teamBest } from "./teamFormat.js";
const TABLE_ART = "/static/img/cards/guild/tavern.webp";
// Meilleure valeur de l'équipe dans chaque stat.
export function TeamBest({ companions, content, statLabels }) {
const best = teamBest(companions);
return <dl className="nebula-team-best" aria-label={content.bestTitle}>{STAT_IDS.map((stat) => <div key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}>
<dt><MaskIcon name={stat} />{statLabels[stat]}</dt><dd>{best[stat]}</dd>
</div>)}</dl>;
}
// `status` : phrase à côté du titre ; `action` : bouton de l'en-tête ; `powers` : paliers d'un recrutement, pour dire ce que chaque
// compagnon y est devenu ; `size` : « sm » (Guilde, recrutement) ou « md » (équipe prête) ; `currentLabel` : la première place libre
// est celle du compagnon en cours de recrutement.
export function TeamTable({ catalog, companions, slots = 5, content, statLabels, title, titleId, titleRef = null, status = null, action = null, powers = null, size = "sm", showBest = true, seatLabel, currentLabel = "" }) {
return <section className="nds-panel nebula-team-table" data-size={size} aria-labelledby={titleId}>
<img className="nebula-team-table-bg" src={TABLE_ART} alt="" />
<div className="nebula-team-table-head">
<h3 id={titleId} ref={titleRef} tabIndex={titleRef ? -1 : undefined}>{title}</h3>
{status && <p>{status}</p>}
{action}
</div>
<ol className="nebula-team-table-list">{Array.from({ length: Math.max(slots, companions.length) }, (_, index) => {
const companion = companions[index];
const current = currentLabel && index === companions.length;
if (!companion) return <li key={`slot-${index}`}><span className="nebula-team-table-slot" data-current={current || undefined}><strong>{index + 1}</strong>{current ? currentLabel : seatLabel}</span></li>;
const fate = powers && fateOf(companion, powers, content);
return <li key={companion.cardId}><TeamCompanion catalog={catalog} companion={companion} content={content} statLabels={statLabels} size={size}
footer={fate && <span className="nebula-team-fate" data-fate={fate.kind}>{fate.text}</span>} /></li>;
})}</ol>
{showBest && companions.length > 0 && <div className="nebula-team-table-best"><span>{content.bestLabel}</span><TeamBest companions={companions} content={content} statLabels={statLabels} /></div>}
</section>;
}

View file

@ -0,0 +1,51 @@
/**
* @file Accueil de l'Équipe du jour quand le joueur n'a pas d'équipe (ou qu'elle s'est reposée) : un appel à
* recruter, cinq places à pourvoir, puis les trois étapes (recruter, améliorer, partir en quête),
* chacune avec un visuel. L'équipe n'est liée à aucun jeu.
*/
import { CurrencyIcon } from "../Currency.jsx";
import { fillTemplate } from "../dailyShare.js";
const TABLE_ART = "/static/img/cards/guild/tavern.webp";
// Trois personnages du catalogue, pris loin les uns des autres, pour montrer une proposition de recrutement.
function sampleCards(catalog) {
const cards = catalog.cards.filter((card) => card.image && card.expedition?.profile);
const pool = cards.length >= 3 ? cards : catalog.cards.filter((card) => card.image);
return pool.length ? [0, Math.floor(pool.length / 2), pool.length - 1].map((index) => pool[index]) : [];
}
const STEP_VISUALS = {
recruit: ({ catalog }) => <span className="nebula-team-welcome-fan">{sampleCards(catalog).map((card) => <img key={card.id} src={card.image} alt="" loading="lazy" />)}</span>,
improve: () => <span className="nebula-team-welcome-stars">
<i data-kind="gold">★</i><i data-kind="gold">★</i><i data-kind="hidden">?</i><i data-kind="black">✖</i><i data-kind="dust"><CurrencyIcon kind="stardust" /></i>
</span>,
quest: ({ maxDays }) => <span className="nebula-team-welcome-days">{Array.from({ length: maxDays }, (_, index) => <i key={index}>{index + 1}</i>)}</span>
};
export function TeamWelcome({ catalog, team, content, action }) {
const expired = team.status === "expired";
return <>
<section className="nds-panel nebula-team-welcome" aria-labelledby="nebula-team-none-title">
<img className="nebula-team-welcome-bg" src={TABLE_ART} alt="" />
<div className="nebula-team-welcome-copy">
<h3 id="nebula-team-none-title">{expired ? content.expiredTitle : content.noneTitle}</h3>
<p>{fillTemplate(expired ? content.expiredText : content.noneText, { max: team.maxDays })}</p>
<ol className="nebula-team-welcome-slots" aria-hidden="true">{Array.from({ length: 5 }, (_, index) => <li key={index}>{index + 1}</li>)}</ol>
{action}
</div>
</section>
<ol className="nebula-team-welcome-steps" aria-label={content.welcomeStepsLabel}>{content.welcomeSteps.map((step, index) => {
const Visual = STEP_VISUALS[step.id];
return <li key={step.id} className="nds-card">
<div className="nebula-team-welcome-visual" aria-hidden="true"><span className="nebula-team-welcome-number">{index + 1}</span>{Visual && <Visual catalog={catalog} maxDays={team.maxDays} />}</div>
<div className="nds-card-body">
<h4>{step.title}</h4>
<p>{fillTemplate(step.text, { max: team.maxDays })}</p>
{step.tip && <p className="nebula-team-welcome-tip">{step.tip}</p>}
</div>
</li>;
})}</ol>
</>;
}

View file

@ -0,0 +1,113 @@
/**
* @file Fait avancer une course à l'écran avec les règles du serveur (coureur du joueur, adversaires et leurs
* élans), et en fait le bilan une fois finie.
*/
import { applyBoost, autoRun, bestBoosts, canBoost, placeOf, RACE_STATS, replayRun, startRun, STEP_MS, stepRun, zoneAt } from "../../../../../services/cards/race-rules.js";
const entrant = ({ runner, helpers }) => ({ runner: runner.stats, helpers: helpers.map((helper) => helper.stats) });
// État d'une course, modifié sur place : une course avance de plusieurs pas par image, sans rendu React à chaque pas.
export function createRace(race) {
return {
zones: race.zones,
player: { ...entrant(race), run: startRun() },
opponents: race.opponents.map((opponent) => ({ ...entrant(opponent), queue: [...opponent.boosts], run: startRun() }))
};
}
export function stepRace(race) {
race.player.run = stepRun(race.player.run, race.player.runner, race.zones);
for (const opponent of race.opponents) {
while (opponent.queue.length && opponent.queue[0].at <= opponent.run.time) opponent.run = applyBoost(opponent.run, opponent.helpers, race.zones, opponent.queue.shift().helper);
opponent.run = stepRun(opponent.run, opponent.runner, race.zones);
}
}
export const allRuns = (race) => [race.player.run, ...race.opponents.map((opponent) => opponent.run)];
export const raceOver = (race) => allRuns(race).every((run) => run.finishedAt !== null);
export const playerZone = (race) => zoneAt(race.player.run.position);
export const canGiveBoost = (race, helper) => canBoost(race.player.run, race.player.helpers, helper);
export function giveBoost(race, helper) {
race.player.run = applyBoost(race.player.run, race.player.helpers, race.zones, helper);
return race.player.run.boosts;
}
// Avance d'une durée ; le reste inférieur à un pas est renvoyé pour l'image suivante.
export function advanceRace(race, duration) {
let left = duration;
while (left >= STEP_MS && !raceOver(race)) {
stepRace(race);
left -= STEP_MS;
}
return left;
}
// Mouvement réduit : avance d'un coup jusqu'à la zone suivante, la fin d'un élan ou l'arrivée du joueur, puis laisse choisir.
export function advanceToNextChoice(race) {
const zone = playerZone(race);
const boosting = () => race.player.run.time < race.player.run.boostEnd;
const wasBoosting = boosting();
do stepRace(race);
while (race.player.run.finishedAt === null && playerZone(race) === zone && !(wasBoosting && !boosting()));
if (race.player.run.finishedAt !== null) while (!raceOver(race)) stepRace(race);
}
// Équipier dont l'élan est en cours, ou -1.
export const activeHelper = (run) => (run.finishedAt === null && run.time < run.boostEnd ? run.boosts.at(-1).helper : -1);
// Classement d'une course finie : à égalité, le joueur passe devant, comme sur le serveur.
export function raceRanking(race) {
return [{ player: true, finishedAt: race.finishedAt, runner: race.runner }, ...race.opponents.map((opponent) => ({ player: false, ...opponent }))]
.map((entry, index) => ({ ...entry, index })).sort((left, right) => left.finishedAt - right.finishedAt || left.index - right.index);
}
// Bilan d'une course finie, pour apprendre sans être guidé pendant la course : temps sans élan, avec ceux du joueur et avec les
// meilleurs trouvés (et la place qu'ils auraient donnée) ; pour chaque équipier, la zone de son élan et sa meilleure stat ; un
// coureur nettement plus rapide dans l'équipe, s'il n'a pas couru.
const CLEARLY_FASTER_MS = 300;
export function raceReview(race) {
const runner = race.runner.stats;
const helpers = race.helpers.map((helper) => helper.stats);
const others = race.opponents.map((opponent) => opponent.finishedAt);
const replay = (boosts) => replayRun({ runner, helpers, boosts }, race.zones).finishedAt;
const mine = replay(race.boosts);
const best = Math.min(mine, replay(bestBoosts({ runner, helpers }, race.zones)));
// Zone de chaque élan donné, en rejouant la course.
const given = new Map();
const queue = [...race.boosts].sort((left, right) => left.at - right.at);
let run = startRun();
while (run.finishedAt === null) {
while (queue.length && queue[0].at <= run.time) {
const { helper } = queue.shift();
const next = applyBoost(run, helpers, race.zones, helper);
if (next !== run) given.set(helper, zoneAt(run.position));
run = next;
}
run = stepRun(run, runner, race.zones);
}
// Chaque compagnon comme coureur, avec des élans bien joués ; un autre n'est signalé que s'il gagne nettement.
const team = [runner, ...helpers];
const times = team.map((stats, index) => autoRun({ runner: stats, helpers: team.filter((_, other) => other !== index) }, race.zones, "skilled", () => 0).finishedAt);
const fastest = times.reduce((best, time, index) => (time < times[best] ? index : best), 0);
return {
plain: replay([]), mine, best, bestPlace: placeOf(best, others),
boosts: race.helpers.map((helper, index) => {
const bestStat = RACE_STATS.reduce((top, stat) => (helper.stats[stat] > helper.stats[top] ? stat : top), RACE_STATS[0]);
const zone = given.get(index) ?? null;
const stat = zone === null ? null : race.zones[zone];
return { cardId: helper.cardId, zone, stat, value: stat ? helper.stats[stat] : 0, bestStat, bestValue: helper.stats[bestStat] };
}),
fasterRunner: times[0] - times[fastest] > CLEARLY_FASTER_MS ? race.helpers[fastest - 1].cardId : null
};
}
// Nom d'un adversaire : son pseudo, une Équipe des Veilleurs ou un compte supprimé depuis.
export function racerName(entry, content) {
return entry.name || (entry.watchers ? content.watchers : content.deletedPlayer);
}
export const imageOf = (catalog, cardId) => catalog.cards.find((card) => card.id === cardId)?.image || "";
export const nameOf = (catalog, cardId, content) => catalog.cards.find((card) => card.id === cardId)?.name || content.unknownCard;

View file

@ -0,0 +1,53 @@
/**
* @file Règles d'affichage de l'Équipe du jour (stats fortes d'un compagnon, meilleures stats d'une équipe,
* textes au pluriel).
*/
import { fillTemplate } from "../dailyShare.js";
import { STAT_IDS } from "../expeditions/expeditionFormat.js";
// Spécialités affichées sur le bandeau : celles données par le serveur, ou l'équilibre.
export const BALANCED = "balanced";
export const bandOf = (companion) => (companion.specialties.length ? companion.specialties : [BALANCED]);
// Stats montrées en grand : les spécialités, sinon la plus haute.
export function mainStats({ specialties, stats }) {
if (specialties.length) return specialties;
return [STAT_IDS.reduce((best, stat) => (stats[stat] > stats[best] ? stat : best), STAT_IDS[0])];
}
export const teamBest = (companions) => Object.fromEntries(STAT_IDS.map((stat) => [stat, Math.max(0, ...companions.map((companion) => companion.stats[stat]))]));
export const averagePower = (companions) => Math.round(companions.reduce((sum, companion) => sum + companion.power, 0) / companions.length);
// Un candidat « manque à l'équipe » s'il a une spécialité que personne n'a encore.
export function isMissing(companion, team) {
const covered = new Set(team.flatMap((member) => member.specialties));
return team.length > 0 && companion.specialties.some((stat) => !covered.has(stat));
}
// Texte au singulier ou au pluriel : `{ one, many }`, avec `{count}`.
export const countText = (texts, count, values = {}) => fillTemplate(count > 1 ? texts.many : texts.one, { count, ...values });
export const riskPct = ({ gold, black, dust }) => {
const total = gold + black + dust;
return total ? Math.round((black / total) * 100) : 0;
};
// Couleur du risque : vers 30 % (26 à 33 selon le palier et les poussières restantes, réglages par défaut), une étoile de plus fait perdre de la
// Puissance en moyenne.
export const riskLevel = (pct) => (pct > 30 ? "high" : pct > 20 ? "medium" : "low");
// Couleurs d'une spécialité, ou des deux : lues par la bordure et le bandeau.
export function specialtyStyle(companion) {
const band = bandOf(companion);
return { "--specialty-start": `var(--color-stat-${band[0]})`, "--specialty-end": `var(--color-stat-${band.at(-1)})` };
}
// Ce que les étoiles ont fait d'un compagnon.
export function fateOf({ fallen, healed, step }, powers, content) {
if (healed) return { kind: "healed", text: content.fateHealed };
if (fallen) return { kind: "fallen", text: content.fateFallen };
if (step === powers.length - 1) return { kind: "top", text: content.fateTop };
return step ? { kind: "improved", text: countText(content.fateImproved, step) } : { kind: "none", text: content.fateNone };
}