sokko-g/website/src/features/cards/expeditions/CardPlan.jsx
Shinuwa aa8bb1ebaa Split dailyShare.js and document the shared exported functions with JSDoc
dailyShare.js held fillTemplate and formatCountdown, used across the whole TCG,
under a Daily Card name. They now live in textFormat.js at the root, and the
Daily Card helpers in daily/dailyFormat.js.

173 exported functions that other files call now explain what they return and
how they treat missing values: the server game rules, the toolbox storage chain,
the shared hooks and utilities, and the TCG display helpers. website/AGENTS.md
asks the same of new shared functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:32:20 +01:00

119 lines
7.8 KiB
JavaScript

/**
* @file Répartition des statistiques d'une carte depuis sa fiche : ses points de niveau suivent sa collection
* (« Par défaut »), un profil (une stat privilégiée ; une étoile marque celui qui lui donne la stat la
* plus haute) ou la répartition du joueur (« Personnalisé »). Le choix en cours s'affiche dans le
* récapitulatif de la fiche (`onPreview`) avant de valider. Le premier choix est gratuit ; ensuite, la
* répartition se verrouille : la réinitialiser coûte un Parchemin d'oubli et remet la carte en
* « Personnalisé », sans point placé, d'où un nouveau choix gratuit (un profil répartit tout seul).
* Ajouter des points en « Personnalisé » reste gratuit.
*/
import { useState } from "react";
import { setCardPlan } from "../cardsApi.js";
import { fillTemplate } from "../textFormat.js";
import { MaskIcon } from "./ExpeditionLabels.jsx";
const STATS = ["bravoure", "endurance", "fortune", "orientation"];
// Profils et la stat que chacun privilégie (libellés et aides : cards.cardSheet.plan.profiles).
const PROFILES = [{ id: "leader", stat: "bravoure" }, { id: "guardian", stat: "endurance" }, { id: "seeker", stat: "fortune" }, { id: "navigator", stat: "orientation" }];
const ZERO = Object.fromEntries(STATS.map((stat) => [stat, 0]));
const total = (stats) => Object.values(stats).reduce((sum, value) => sum + value, 0);
const toDraft = (allocation) => Object.fromEntries(STATS.map((stat) => [stat, String(allocation?.[stat] ?? 0)]));
const toAllocation = (draft) => Object.fromEntries(STATS.map((stat) => [stat, Math.max(0, Number.parseInt(draft[stat], 10) || 0)]));
const plural = (count) => (count > 1 ? "s" : "");
/**
* `locked` : la carte est en expédition, sa répartition ne change pas avant son retour. `content` : textes cards.cardSheet.plan,
* `statNames` : noms des stats.
*/
export function CardPlan({ progress, oblivions, content, statNames, locked = false, busy, runMutation, onPreview = () => {} }) {
const plan = progress.plan;
// Choix encore ouvert : premier choix, ou après une réinitialisation.
const open = !plan.paid;
const placed = plan.allocation || ZERO;
const [choice, setChoice] = useState(plan.id);
const [draft, setDraft] = useState(() => toDraft(plan.allocation));
const free = choice === "free";
const profile = PROFILES.find((item) => item.id === choice) || null;
const allocation = toAllocation(draft);
const left = plan.points - total(allocation);
const statsFor = (id, points) => (id === "free" ? Object.fromEntries(STATS.map((stat) => [stat, plan.levelBase[stat] + points[stat]])) : plan.previews[id]);
const unchangedFor = (id, points) => id === plan.id && (id !== "free" || STATS.every((stat) => points[stat] === placed[stat]));
const unchanged = unchangedFor(choice, allocation);
// Le profil qui donne à la carte sa stat la plus haute.
const best = PROFILES.reduce((top, item) => (plan.previews[item.id][item.stat] > plan.previews[top.id][top.stat] ? item : top), PROFILES[0]).id;
const report = (id, points) => onPreview(unchangedFor(id, points) ? null : statsFor(id, points));
const choose = (id) => {
setChoice(id);
report(id, allocation);
};
/** Un point de plus ne dépasse ni le plafond d'une stat, ni les points restants ; sans réinitialisation, on ne retire pas un point placé. */
const setPoints = (stat, raw) => {
const limit = Math.min(plan.maxStatPoints, allocation[stat] + left);
const next = { ...draft, [stat]: raw !== "" && Number(raw) > limit ? String(limit) : raw };
setDraft(next);
report("free", toAllocation(next));
};
const cancel = () => {
setChoice(plan.id);
setDraft(toDraft(plan.allocation));
onPreview(null);
};
const save = async () => {
if (await runMutation(() => setCardPlan(progress.editionId, choice, free ? allocation : null))) onPreview(null);
};
const reset = async () => {
if (await runMutation(() => setCardPlan(progress.editionId, "free", ZERO))) onPreview(null);
};
const removesPoints = free && plan.id === "free" && STATS.some((stat) => allocation[stat] < placed[stat]);
const editable = !locked && (open || plan.id === "free");
const option = (id, label, stat = null) => <button key={id} type="button" className="nds-button" data-size="sm" data-variant={id === choice ? "primary" : "secondary"} aria-pressed={id === choice}
disabled={busy || locked || (!open && id !== choice)} onClick={() => choose(id)}>
{stat && <MaskIcon name={stat} />}{label}{id === best && <span className="nebula-card-plan-best" aria-label={content.best} title={content.bestTitle}>★</span>}
</button>;
// « Valider » et « Annuler » dans le cadre du choix en cours, sous ce qui a changé.
const actions = !unchanged && <div className="nebula-card-plan-actions">
{plan.id === "collection" && !free && <p className="nebula-form-help">{content.firstFree}</p>}
{removesPoints && <p className="nebula-form-help">{content.removeNeedsReset}</p>}
<div className="nds-toolbar">
<button className="nds-button" data-variant="primary" type="button" disabled={busy || locked || removesPoints} onClick={save}>{content.save}</button>
<button className="nds-button" data-variant="secondary" type="button" disabled={busy} onClick={cancel}>{content.cancel}</button>
</div>
</div>;
return <section className="nebula-card-plan" aria-labelledby="nebula-card-plan-title">
<h3 id="nebula-card-plan-title">{content.title}</h3>
<p className="nebula-form-help">{plan.points
? fillTemplate(content.pointsGained, { count: plan.points, s: plural(plan.points) })
: content.pointsLater}</p>
{/* Deux cadres : « Par défaut » ou « Personnalisé » (et ses points juste dessous), puis les profils ; le cadre du choix en cours
est souligné d'or. */}
<div role="group" aria-label={content.defaultOrCustom} className="nebula-card-plan-frame" data-active={!profile || undefined}>
<div className="nds-toolbar">{option("collection", content.default)}{option("free", content.custom)}</div>
{!profile && <p className="nebula-form-help">{content.help[choice]}</p>}
{free && <div className="nebula-card-plan-points">
<p className="nebula-card-plan-left" role="status">{!plan.points ? content.noPoints : <>
{left > 0 ? fillTemplate(content.left, { count: left, s: plural(left) }) : content.allPlaced}
<small>{fillTemplate(content.cap, { count: plan.maxStatPoints })}</small>
</>}</p>
{STATS.map((stat) => <label key={stat}><span><MaskIcon name={stat} />{statNames[stat]}</span>
<input className="nds-input" type="number" inputMode="numeric" min={open ? 0 : placed[stat]} max={plan.maxStatPoints} step="1" value={draft[stat]} disabled={busy || !editable || !plan.points}
onChange={(event) => setPoints(stat, event.target.value)} onBlur={() => { if (draft[stat] === "") setDraft((current) => ({ ...current, [stat]: "0" })); }} />
</label>)}
</div>}
{!profile && actions}
</div>
<div role="group" aria-labelledby="nebula-card-plan-profiles" className="nebula-card-plan-frame" data-active={profile ? true : undefined}>
<h4 id="nebula-card-plan-profiles">{content.profilesTitle}</h4>
<div className="nds-toolbar">{PROFILES.map((item) => option(item.id, content.profiles[item.id].label, item.stat))}</div>
{profile && <p className="nebula-form-help">{content.profiles[profile.id].help}</p>}
{profile && actions}
</div>
{locked && <p className="nebula-form-help">{content.locked}</p>}
{!open && !locked && <div className="nebula-card-plan-reset">
<button className="nds-button" data-variant="secondary" type="button" disabled={busy || oblivions < 1} onClick={reset}>{content.reset}</button>
<p className="nebula-form-help">{`${fillTemplate(content.resetCount, { count: oblivions })} ${oblivions < 1 ? content.resetBuy : content.resetHelp}`}</p>
</div>}
</section>;
}