246 lines
19 KiB
JavaScript
246 lines
19 KiB
JavaScript
/**
|
|
* @file Présente une expédition en préparation sur le tableau de la Guilde : membres (prêts ou en
|
|
* préparation), places libres, résultat attendu si elle partait maintenant (seule ou en groupe), et la
|
|
* carte du joueur qui rejoint : choisie et équipée comme dans la préparation, jusqu'à « Prêt ». À qui
|
|
* peut rejoindre, les exigences sont celles du groupe avec lui en plus ; dès qu'il choisit une carte,
|
|
* le résultat prévu et les exigences la comptent, avec son équipement, avant même l'inscription.
|
|
*/
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { previewJoinExpedition } from "../cardsApi.js";
|
|
import { fillTemplate, formatCountdown } from "../textFormat.js";
|
|
import { conditionText, dangerText, editionEntry, formatDecimal, formatEclats, powerNote, synergyBadges, tagLabel } from "./expeditionFormat.js";
|
|
import { DestinationArt, MainStatMark, MaskIcon } from "./ExpeditionLabels.jsx";
|
|
import { ExpeditionLoadout } from "./ExpeditionLoadout.jsx";
|
|
import { BonusBadges, PowersTile, TierTile } from "./ExpeditionOutcome.jsx";
|
|
import { NebulaCard } from "../rendering/NebulaCard.jsx";
|
|
|
|
const PREVIEW_DELAY_MS = 250;
|
|
|
|
/** Exigences face à l'apport de l'équipe : une ligne par stat ; sans prévision (Coup de folie), l'exigence seule (`team` nul). */
|
|
function requirementRows(requirements, projected) {
|
|
const team = new Map((projected.hiddenRequirements ? [] : projected.requirements || []).map((item) => [item.stat, item.team]));
|
|
return requirements.map(({ stat, main, value }) => ({ stat, main, value, team: team.get(stat) ?? null }));
|
|
}
|
|
|
|
/**
|
|
* Aperçu de l'inscription avec la carte choisie, demandé au serveur après une courte pause ; il se recalcule quand la carte, son
|
|
* équipement ou le groupe changent. Pendant ce temps, le précédent reste affiché.
|
|
*/
|
|
function useJoinPreview(group, card) {
|
|
const [preview, setPreview] = useState({ key: "", editionId: null, value: null, error: "" });
|
|
const editionId = card?.editionId ?? null;
|
|
const key = editionId ? JSON.stringify([group.id, editionId, card.stats, card.powers, group.members, group.projected]) : "";
|
|
const groupId = group.id;
|
|
useEffect(() => {
|
|
if (!key) return undefined;
|
|
let active = true;
|
|
const timer = setTimeout(() => {
|
|
previewJoinExpedition(groupId, { editionId })
|
|
.then((result) => { if (active) setPreview({ key, editionId, value: result.preview, error: "" }); })
|
|
.catch((error) => { if (active) setPreview({ key, editionId, value: null, error: error.message }); });
|
|
}, PREVIEW_DELAY_MS);
|
|
return () => { active = false; clearTimeout(timer); };
|
|
}, [key, groupId, editionId]);
|
|
// L'aperçu d'une autre carte ne vaut pas pour celle-ci.
|
|
if (!key || preview.editionId !== editionId) return { value: null, error: "", stale: Boolean(key) };
|
|
return { value: preview.value, error: preview.key === key ? preview.error : "", stale: preview.key !== key };
|
|
}
|
|
|
|
/**
|
|
* Carte du joueur pour ce groupe, dans le même cadre que la préparation : emplacement de la carte (la liste des cartes jouables
|
|
* s'ouvre d'un clic), stats et équipements, « Améliorer la carte ». La carte seule n'est pas comparée aux exigences de toute l'équipe :
|
|
* `needs` les rappelle à côté face à l'apport du groupe, `pickerNeeds` dans le choix de la carte.
|
|
* `children` : les boutons, en bas à droite du cadre ; `notice` : un avis sous le cadre.
|
|
*/
|
|
function MemberLoadout({ catalog, state, view, group, card, help, needs, pickerNeeds = needs, content, busy, runMutation, onChooseCard, notice = null, children }) {
|
|
const destination = { ...group.destination, requirements: [], condition: group.condition, dangers: group.dangers };
|
|
return <section className="nebula-expedition-join" aria-labelledby={`nebula-group-loadout-${group.id}`}>
|
|
<h5 id={`nebula-group-loadout-${group.id}`}>{content.ownLoadoutTitle}</h5>
|
|
<p className="nebula-form-help">{help}</p>
|
|
<ExpeditionLoadout catalog={catalog} state={state} view={view} destination={destination} card={card} onChooseCard={onChooseCard} content={content} busy={busy} runMutation={runMutation} needs={needs} pickerNeeds={pickerNeeds} actions={children} />
|
|
{notice}
|
|
</section>;
|
|
}
|
|
|
|
/**
|
|
* Inscription : la carte se choisit et s'équipe avant de rejoindre ; tout reste modifiable ensuite, jusqu'à « Prêt ».
|
|
* `outlook` : exigences et résultat du groupe avec le joueur (sa carte comprise dès l'aperçu reçu).
|
|
*/
|
|
function JoinForm({ catalog, state, view, group, card, outlook, content, busy, runMutation, onChooseCard, onJoin, onCancel }) {
|
|
const players = group.members.length + 1;
|
|
const without = { title: fillTemplate(content.needsWithout, { players }), rows: requirementRows(group.joinRequirements || group.requirements, group.projected), missing: true };
|
|
const needs = outlook.preview ? { title: fillTemplate(content.needsWith, { players }), rows: outlook.rows, stale: outlook.stale } : without;
|
|
return <MemberLoadout catalog={catalog} state={state} view={view} group={group} card={card} help={content.joinHelp} needs={needs} pickerNeeds={without} content={content} busy={busy} runMutation={runMutation} onChooseCard={onChooseCard}
|
|
notice={outlook.error && <p className="nds-inline-notice" data-variant="warning" role="status">{outlook.error}</p>}>
|
|
<button className="nds-button" data-variant="secondary" type="button" onClick={onCancel}>{content.cancel}</button>
|
|
<button className="nds-button" data-variant="primary" type="button" disabled={busy || !card} onClick={() => onJoin(group.id, { editionId: card.editionId, ready: true })}>{content.joinConfirm}</button>
|
|
</MemberLoadout>;
|
|
}
|
|
|
|
/**
|
|
* Joueur inscrit (pas le créateur) : tant qu'il n'est pas prêt, il change de carte ou d'équipement, et le groupe compte aussitôt sa
|
|
* carte telle qu'elle est ; « Prêt » la fige et le signale au créateur, « Modifier ma préparation » la rouvre.
|
|
*/
|
|
function OwnSlot({ catalog, state, view, group, content, busy, runMutation, onMember }) {
|
|
const { editionId, ready } = group.ownSlot;
|
|
const card = view.cards.find((item) => item.editionId === editionId) || null;
|
|
// Prêt : la liste des membres le montre déjà ; « Modifier ma préparation » est dans les actions du groupe.
|
|
if (ready) return null;
|
|
return <MemberLoadout catalog={catalog} state={state} view={view} group={group} card={card} help={content.ownLoadoutHelp}
|
|
needs={{ title: fillTemplate(content.needsWith, { players: group.members.length }), rows: requirementRows(group.requirements, group.projected) }} content={content} busy={busy} runMutation={runMutation}
|
|
onChooseCard={(id) => onMember(group.id, { editionId: id }, null)}>
|
|
<button className="nds-button" data-variant="primary" type="button" disabled={busy || !card} onClick={() => onMember(group.id, { ready: true }, content.readyNotice)}>{content.ready}</button>
|
|
</MemberLoadout>;
|
|
}
|
|
|
|
function Thumb({ ok, label }) {
|
|
return <span className="nebula-destination-hazard-state" data-ok={ok ? "true" : "false"} title={label} aria-hidden="true"><MaskIcon name="thumb" /></span>;
|
|
}
|
|
|
|
/**
|
|
* Rappel de ce que demande la destination face à ce qu'apporte l'équipe si elle partait maintenant : une ligne par stat exigée
|
|
* (valeur de l'équipe / exigence, en vert ou en rouge), puis la condition et les dangers, chacun avec un pouce vert (remplie, paré)
|
|
* ou rouge.
|
|
* Avec le Coup de folie, les exigences seules (pas de prévision).
|
|
*/
|
|
function GroupRecap({ catalog, group, title, rows, projected, content }) {
|
|
const hidden = projected.hiddenRequirements;
|
|
const countered = new Map((projected.dangers || []).map((danger) => [danger.id, danger.countered]));
|
|
const tagNames = (tags) => tags.map((tag) => tagLabel(catalog, tag)).join(content.or);
|
|
return <section className="nebula-group-recap" aria-label={title}>
|
|
<h5>{title}</h5>
|
|
<ul className="nebula-group-recap-list">
|
|
{rows.map(({ stat, value, main, team }) => {
|
|
const ok = team == null ? null : team >= value;
|
|
const label = [fillTemplate(content.requirementValue, { stat: content.stats[stat], value }),
|
|
ok == null ? "" : fillTemplate(ok ? content.requirementMet : content.requirementUnmet, { team: formatDecimal(team) })].filter(Boolean).join(" ");
|
|
return <li key={stat} className="nebula-group-recap-row" aria-label={label}>
|
|
<span className="nebula-group-recap-name" aria-hidden="true"><MaskIcon name={stat} />{content.stats[stat]}{main && <MainStatMark content={content} />}</span>
|
|
<strong aria-hidden="true" data-met={ok == null ? undefined : String(ok)}>{ok == null ? value : fillTemplate(content.teamVersus, { team: formatDecimal(team), value })}</strong>
|
|
</li>;
|
|
})}
|
|
</ul>
|
|
{(group.condition || group.dangers.length > 0) && <ul className="nebula-group-recap-list" data-kind="hazards">
|
|
{group.condition && (() => {
|
|
const name = group.condition.type === "collection" ? catalog.collections.find((item) => item.id === group.condition.collectionId)?.name || group.condition.collectionId : tagLabel(catalog, group.condition.tag);
|
|
const ok = projected.conditionMet;
|
|
return <li className="nebula-group-recap-row" title={conditionText(group.condition, catalog, content)}
|
|
aria-label={`${conditionText(group.condition, catalog, content)}${hidden ? "" : ` ${ok ? content.conditionOk : content.conditionKo}`}`}>
|
|
<span className="nebula-group-recap-name" aria-hidden="true">{fillTemplate(content.conditionShort, { name })}</span>
|
|
{!hidden && <Thumb ok={ok} label={ok ? content.conditionOk : content.conditionKo} />}
|
|
</li>;
|
|
})()}
|
|
{group.dangers.map((danger) => {
|
|
const ok = countered.get(danger.id);
|
|
return <li key={danger.id} className="nebula-group-recap-row" title={dangerText(danger, catalog, content)}
|
|
aria-label={`${dangerText(danger, catalog, content)}${hidden ? "" : ` ${ok ? content.dangerOk : content.dangerKo}`}`}>
|
|
<span className="nebula-group-recap-name" aria-hidden="true">{fillTemplate(content.dangerShort, { label: danger.label })}<small>{fillTemplate(content.dangerDetail, { stat: content.stats[danger.stat], tags: tagNames(danger.unlessTags) })}</small></span>
|
|
{!hidden && <Thumb ok={ok} label={ok ? content.dangerOk : content.dangerKo} />}
|
|
</li>;
|
|
})}
|
|
</ul>}
|
|
</section>;
|
|
}
|
|
|
|
/** Lien d'invitation : il ouvre la page des Expéditions sur cette expédition, son inscription déjà dépliée. */
|
|
const inviteUrl = (groupId) => `${window.location.origin}/#/cards/expeditions/${encodeURIComponent(groupId)}`;
|
|
|
|
function InviteLink({ groupId, content }) {
|
|
const [copied, setCopied] = useState(false);
|
|
const url = inviteUrl(groupId);
|
|
const copy = async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(url);
|
|
setCopied(true);
|
|
} catch {
|
|
setCopied(false);
|
|
}
|
|
};
|
|
return <div className="nebula-expedition-invite">
|
|
<label className="nebula-form-help" htmlFor={`nebula-invite-${groupId}`}>{content.inviteLabel}</label>
|
|
<div className="nds-toolbar">
|
|
<input id={`nebula-invite-${groupId}`} className="nds-input" type="text" readOnly value={url} onFocus={(event) => event.target.select()} />
|
|
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={copy}>{copied ? content.inviteCopied : content.inviteCopy}</button>
|
|
</div>
|
|
</div>;
|
|
}
|
|
|
|
/**
|
|
* `invited` : le joueur arrive par le lien d'invitation de cette expédition : elle est mise en vue, son inscription dépliée.
|
|
* `onJoiningChange(groupId, open)` : prévient le panneau quand l'inscription se déplie ou se replie.
|
|
*/
|
|
export function ExpeditionGroupCard({ catalog, state, view, group, content, now, busy, limitReached, runMutation, onJoin, onMember, onLeave, onDepart, onTestPlayer = null, onJoiningChange = null, invited = false }) {
|
|
const [joining, setJoining] = useState(invited && group.canJoin && !limitReached);
|
|
const articleRef = useRef(null);
|
|
useEffect(() => { if (invited) articleRef.current?.scrollIntoView({ block: "center" }); }, [invited]);
|
|
// Inscription : la carte choisie compte déjà dans le résultat prévu et les exigences.
|
|
const [editionId, setEditionId] = useState(null);
|
|
const open = joining && !group.isMember;
|
|
useEffect(() => {
|
|
if (!open || !onJoiningChange) return undefined;
|
|
onJoiningChange(group.id, true);
|
|
return () => onJoiningChange(group.id, false);
|
|
}, [open, group.id, onJoiningChange]);
|
|
const card = (open && view.cards.find((item) => item.editionId === editionId && !item.busy)) || null;
|
|
const { value: preview, error: previewError, stale } = useJoinPreview(group, card);
|
|
const projected = preview?.projected || group.projected;
|
|
const players = group.members.length + 1;
|
|
const rows = requirementRows(preview?.requirements || group.joinRequirements || group.requirements, projected);
|
|
const outlook = { preview, rows, stale, error: previewError };
|
|
const left = Math.max(0, group.recruitUntil - now);
|
|
const span = Math.max(1, group.recruitUntil - (group.openedAt ?? group.recruitUntil - 3_600_000));
|
|
const departTime = new Date(group.recruitUntil).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
|
|
const bonuses = synergyBadges(projected, catalog, content);
|
|
return <article ref={articleRef} className="nds-card nebula-expedition-group" data-invited={invited || undefined} aria-labelledby={`nebula-group-${group.id}`}>
|
|
<div className="nebula-group-side">
|
|
<DestinationArt catalog={catalog} destination={group.destination} />
|
|
<section className="nebula-group-team" aria-label={content.groupMembers}>
|
|
<h5>{content.groupMembers}</h5>
|
|
<ul className="nebula-expedition-group-members">
|
|
{group.members.map((member) => {
|
|
const entry = editionEntry(catalog, member.editionId);
|
|
return <li key={member.position}>{entry && <NebulaCard catalog={catalog} entry={entry} size="sm" />}<strong>{member.own ? content.you : member.playerName}</strong>
|
|
<span className="nds-badge" data-variant={member.ready ? "success" : "warning"}>{member.ready ? content.memberReady : content.memberPreparing}</span></li>;
|
|
})}
|
|
{Array.from({ length: group.freeSlots }, (_, index) => <li key={`free-${index}`}><span className="nebula-expedition-group-free">{content.groupFreeRole}</span></li>)}
|
|
</ul>
|
|
{group.isCreator && group.members.length > 1 && <p className="nebula-form-help">{fillTemplate(content.readyCount, { ready: group.members.filter((member) => member.ready).length, count: group.members.length })}</p>}
|
|
{group.freeSlots > 0 && <p className="nebula-form-help nebula-group-scaling">{content.groupScaling}</p>}
|
|
</section>
|
|
<div className="nds-toolbar nebula-expedition-group-actions">
|
|
{group.canJoin && !joining && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy || limitReached} onClick={() => setJoining(true)}>{content.join}</button>}
|
|
{group.canDepart && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={() => onDepart(group.id)}>{content.depart}</button>}
|
|
{group.ownSlot?.ready && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => onMember(group.id, { ready: false }, content.unreadyNotice)}>{content.unready}</button>}
|
|
{group.isMember && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => onLeave(group.id)}>{group.isCreator ? content.dissolve : content.leave}</button>}
|
|
{onTestPlayer && group.isMember && group.freeSlots > 0 && <button className="nds-button" data-size="sm" data-variant="ghost" type="button" disabled={busy} onClick={() => onTestPlayer(group.id)}>{content.testPlayer}</button>}
|
|
</div>
|
|
</div>
|
|
<div className="nebula-group-main">
|
|
<div className="nebula-group-heading">
|
|
<p className="eyebrow">{fillTemplate(content.groupMeta, { stars: "★".repeat(group.stars), hours: group.hours, creator: group.isCreator ? content.you : group.creatorName })}</p>
|
|
<h4 id={`nebula-group-${group.id}`}>{group.destination.name}</h4>
|
|
</div>
|
|
<div className="nebula-group-deadline">
|
|
<span>{fillTemplate(content.groupDeadline, { time: formatCountdown(left), at: departTime })}</span>
|
|
<div className="nds-progress" data-size="sm" role="progressbar" aria-label={content.groupDeadlineBar} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round((1 - left / span) * 100)}><span style={{ width: `${Math.min(100, (1 - left / span) * 100)}%` }} /></div>
|
|
</div>
|
|
{group.canJoin && <p className="nebula-form-help nebula-group-outcome-note">{preview ? fillTemplate(content.joinOutcomeWith, { players }) : content.joinOutcomeWithout}</p>}
|
|
<dl className="nebula-group-outcome" aria-label={preview ? fillTemplate(content.joinOutcomeWith, { players }) : content.groupProjected} aria-busy={stale} data-stale={stale || undefined}>
|
|
{projected.hiddenRequirements ? <div><dt>{content.groupOutcomeTier}</dt><dd><span className="nds-badge" data-variant="warning">{content.hiddenResult}</span></dd></div>
|
|
: <TierTile tier={projected.tier} scorePct={projected.scorePct} lootPct={projected.tierLootPct ?? group.tierLootPct?.[projected.tier]} content={content} />}
|
|
{projected.players > 1 && <div><dt>{content.groupOutcomeGroupLoot}</dt><dd>{fillTemplate(content.lootBonus, { value: formatEclats(projected.lootPct / 100) })}</dd></div>}
|
|
<PowersTile powers={projected.powers} attunement={projected.attunement} values={view.powers} content={content}
|
|
noteOf={(power) => powerNote(power, { stars: group.stars, players: projected.players, dangers: projected.dangers ? projected.dangers.filter((danger) => !danger.countered).length : group.dangers?.length ?? 0, values: view.powers }, content)} />
|
|
{bonuses.length > 0 && <div><dt>{content.groupOutcomeBonuses}</dt><dd><BonusBadges badges={bonuses} /></dd></div>}
|
|
</dl>
|
|
<GroupRecap catalog={catalog} group={group} projected={projected} rows={rows} content={content}
|
|
title={group.canJoin ? fillTemplate(content.joinRecapTitle, { players }) : content.groupRecapTitle} />
|
|
{group.isMember && <InviteLink groupId={group.id} content={content} />}
|
|
</div>
|
|
{group.canJoin && limitReached && <p className="nebula-form-help">{content.groupLimit}</p>}
|
|
{open && <JoinForm catalog={catalog} state={state} view={view} group={group} card={card} outlook={outlook} content={content} busy={busy} runMutation={runMutation} onChooseCard={setEditionId}
|
|
onJoin={async (...args) => { if (await onJoin(...args)) setJoining(false); }} onCancel={() => { setJoining(false); setEditionId(null); }} />}
|
|
{group.ownSlot && <OwnSlot catalog={catalog} state={state} view={view} group={group} content={content} busy={busy} runMutation={runMutation} onMember={onMember} />}
|
|
</article>;
|
|
}
|