sokko-g/website/src/features/cards/ExpeditionsPanel.jsx
Shinuwa 84b0d69b1f Keep the expedition view in sync with other players and only send alerts players still want
- The expeditions page rereads its view on its own: every 10 seconds while a
  group is shown, every 20 seconds otherwise, on tab return and at the next
  recruitment deadline; late responses no longer overwrite a newer action. A
  failed load offers "Réessayer" and a failed refresh keeps the last view.
- The periodic alert pass first departs groups whose recruitment ended, so
  their return is announced even if nobody visits the site.
- Queued alerts are checked again at sending time: a player who opted out or
  alerts switched off by the administration drop the message for good.
- The engraving confirmation sticks to the bottom of its window, the workshop
  lists commons by spare count, the guild expeditions card shows the Great
  Void, and stale help texts and comments are fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:24:39 +01:00

263 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : présente les Expéditions, quête de la Guilde, en deux onglets. « Préparer » suit le parcours du joueur : la carte de
// destination offerte à sa première visite, puis son expédition (à récupérer, en route, ou ouverte au groupe) ou, s'il n'en a pas,
// les expéditions à rejoindre et la préparation. Une expédition revenue montre son butin sur place ; un clic le récupère, puis la
// carte disparaît et un avis confirme. « Journal » garde les expéditions terminées et leur butin. La vue se relit d'elle-même pour
// suivre les autres joueurs (relecture régulière, retour sur l'onglet, échéances d'inscription et de retour).
import { useCallback, useEffect, useRef, useState } from "react";
import { Tabs } from "../../components/Tabs.jsx";
import { addBonusDestination, addTestPlayer, claimExpedition, craftPowerCommon, recallExpedition, departExpedition, joinExpedition, leaveExpedition, loadExpeditions, markStarterSeen, rerollDestinations, startExpedition } from "./cardsApi.js";
import { CurrencyAmount } from "./Currency.jsx";
import { fillTemplate, formatCountdown } from "./dailyShare.js";
import { ExpeditionAtelier } from "./ExpeditionAtelier.jsx";
import { ExpeditionGroupCard } from "./ExpeditionGroupCard.jsx";
import { EngraveModal, ImproveCardPicker } from "./ExpeditionImprove.jsx";
import { ExpeditionJourney } from "./ExpeditionJourney.jsx";
import { MaskIcon } from "./ExpeditionLabels.jsx";
import { ExpeditionPlanner } from "./ExpeditionPlanner.jsx";
import { ExpeditionReport } from "./ExpeditionReport.jsx";
import { ExpeditionReturn } from "./ExpeditionReturn.jsx";
import { ExpeditionStarter } from "./ExpeditionStarter.jsx";
import { formatEclats, ITEM_ART } from "./expeditionFormat.js";
const COUNTDOWN_TICK_MS = 30_000;
// La vue est relue à ce rythme pour suivre les autres joueurs : vite tant qu'un groupe est affiché (inscriptions, départs,
// annulations), plus lentement sinon (nouveaux groupes à rejoindre).
const GROUP_POLL_MS = 10_000;
const IDLE_POLL_MS = 20_000;
// Les refus propres aux Expéditions restent dans ce panneau ; runMutation garde le reste (réseau, session).
const expeditionCall = (call) => async () => {
try {
return await call();
} catch (error) {
if (String(error.code || "").startsWith("EXPEDITION")) return { expeditionError: error };
throw error;
}
};
// Sac du Veilleur : objets rapportés ; les destinations bonus s'ouvrent ici, l'ancre et le burin depuis l'expédition et la fiche de carte.
// Sac du Veilleur en grille de cartes : l'illustration de chaque objet (sans illustration, l'icône générique des objets) et sa
// quantité, son nom, son aide, puis son action. La Rose des vents s'utilise depuis les destinations du jour ; le plan ouvre
// l'atelier en fenêtre.
const BAG_ORDER = ["guideStar", "skyChart", "fragment", "windRose", "anchor", "engraving", "plan", "oblivion"];
function ItemArt({ id, count }) {
return <span className="nebula-bag-art">
{ITEM_ART[id] ? <img src={ITEM_ART[id]} alt="" loading="lazy" decoding="async" /> : <MaskIcon name="items" />}
<span className="nebula-bag-count">×{count}</span>
</span>;
}
function ItemBag({ catalog, state, view, content, busy, onBonus, onCraft, onAtelierClosed, runMutation }) {
const [crafting, setCrafting] = useState(false);
// Burin ou Parchemin : la fenêtre des cartes ouverte pour cet objet, puis la fiche de la carte choisie.
const [improving, setImproving] = useState(null);
const { items } = view;
const used = new Set(view.destinations.map((destination) => destination.bonusSlot).filter(Boolean));
// Objets de destination : la place de la destination ajoutée et le nombre d'exemplaires qu'il faut.
const actions = { guideStar: ["5", 1], skyChart: ["6", 1], fragment: ["hidden", view.fragmentsForMap] };
// Les objets de destination d'abord, du plus simple au plus riche ; puis les autres.
const owned = Object.entries(items).filter(([, count]) => count > 0)
.sort(([a], [b]) => BAG_ORDER.indexOf(a) - BAG_ORDER.indexOf(b));
// Sans objet, pas de Sac du Veilleur.
if (!owned.length) return null;
return <section className="nds-panel nebula-expedition-bag" aria-labelledby="nebula-expedition-bag-title">
<h3 id="nebula-expedition-bag-title">{content.bagTitle}</h3>
<ul>{owned.map(([id, count]) => {
const action = actions[id];
return <li key={id} className="nds-card nebula-bag-item">
<ItemArt id={id} count={count} />
<span className="nebula-bag-text"><strong>{content.items[id]}</strong><span className="nebula-form-help">{fillTemplate(content.itemHelp[id], { count: view.fragmentsForMap })}</span></span>
{/* Les fragments n'ont de bouton qu'une fois assez nombreux pour une carte au trésor. */}
{action && view.enabled && count >= action[1] && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy || used.has(action[0])} aria-label={fillTemplate(content.useItemLabel, { item: content.items[id] })} onClick={() => onBonus(id)}>{content.useItem}</button>}
{(id === "engraving" || id === "oblivion") && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy}
aria-label={fillTemplate(content.useItemLabel, { item: content.items[id] })} onClick={() => setImproving(id)}>{content.useItem}</button>}
{id === "plan" && view.atelierAvailable && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => setCrafting(true)}>{content.atelierOpen}</button>}
</li>;
})}</ul>
{improving === "engraving" && <EngraveModal catalog={catalog} state={state} view={view} content={content} busy={busy} runMutation={runMutation} onClose={() => setImproving(null)} />}
{improving === "oblivion" && <ImproveCardPicker catalog={catalog} state={state} view={view} item={improving} content={content} busy={busy} runMutation={runMutation} onClose={() => setImproving(null)} />}
{crafting && <ExpeditionAtelier catalog={catalog} state={state} content={content} busy={busy} powerValues={view.powers} onCraft={onCraft} onClose={() => { setCrafting(false); onAtelierClosed(); }} />}
</section>;
}
// `joinId` : expédition ouverte par un lien d'invitation (#/cards/expeditions/<id>).
export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, joinId = "" }) {
const [view, setView] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [notice, setNotice] = useState(null);
const [tab, setTab] = useState("prepare");
const [starterClosed, setStarterClosed] = useState(false);
const [now, setNow] = useState(() => Date.now());
// Numéro du dernier chargement ou de la dernière mutation : une réponse plus ancienne, arrivée en retard, est ignorée.
const latest = useRef(0);
// Demande une relecture de la vue. En cas d'échec, la vue déjà affichée reste en place avec un avis et « Réessayer ».
const load = useCallback(() => setReloadKey((key) => key + 1), []);
useEffect(() => {
const ticket = ++latest.current;
loadExpeditions()
.then((result) => {
if (ticket !== latest.current) return;
setView(result);
setLoadError("");
setNow(Date.now());
})
.catch((error) => { if (ticket === latest.current) setLoadError(error.message); });
// Relecture suivante ou démontage : cette réponse devient périmée.
return () => { latest.current += 1; };
}, [reloadKey]);
// Retour sur l'onglet : la vue a pu changer pendant l'absence (groupe rejoint, parti, revenu).
useEffect(() => {
const refresh = () => { if (globalThis.document.visibilityState === "visible") load(); };
window.addEventListener("focus", refresh);
globalThis.document.addEventListener("visibilitychange", refresh);
return () => {
window.removeEventListener("focus", refresh);
globalThis.document.removeEventListener("visibilitychange", refresh);
};
}, [load]);
// Relecture régulière, onglet visible seulement, plus rapide quand un groupe est affiché ; et à l'échéance d'inscription la plus
// proche, quand le groupe part de lui-même.
const groups = view?.groups || [];
const pollMs = !view ? null : groups.length > 0 ? GROUP_POLL_MS : IDLE_POLL_MS;
const nextRecruitEnd = groups.length ? Math.min(...groups.map((group) => group.recruitUntil)) : null;
useEffect(() => {
if (pollMs == null) return undefined;
const timer = setInterval(() => { if (globalThis.document.visibilityState === "visible") load(); }, pollMs);
return () => clearInterval(timer);
}, [pollMs, load]);
useEffect(() => {
if (nextRecruitEnd == null) return undefined;
const timer = setTimeout(load, Math.max(0, nextRecruitEnd - Date.now()) + 500);
return () => clearTimeout(timer);
}, [nextRecruitEnd, load]);
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), COUNTDOWN_TICK_MS);
return () => clearInterval(timer);
}, []);
// Une expédition revient pendant que la page est ouverte : la vue est relue à son heure de retour pour obtenir son résultat et
// son butin.
useEffect(() => {
const returns = (view?.expeditions || []).filter((expedition) => expedition.status === "running" && !expedition.result).map((expedition) => expedition.returnsAt);
if (!returns.length) return undefined;
const timer = setTimeout(load, Math.max(0, Math.min(...returns) - Date.now()) + 500);
return () => clearTimeout(timer);
}, [view, load]);
// Premier chargement en échec : le message et « Réessayer ».
if (loadError && !view) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p>
<button className="nds-button" data-variant="primary" type="button" onClick={load}>{content.retry}</button></section>;
if (!view) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
const reload = () => { setNotice(null); setReloadKey((key) => key + 1); };
const handle = (result, success) => {
if (result?.expeditions) {
// La réponse d'une action prime sur un chargement encore en cours.
latest.current += 1;
setView(result.expeditions);
setLoadError("");
setNow(Date.now());
setNotice(success ? { variant: "success", text: success } : null);
return true;
}
if (result?.expeditionError?.code === "EXPEDITION_DAY_EXPIRED") setNow(view.nextDayAt);
else if (result?.expeditionError) setNotice({ variant: "warning", text: result.expeditionError.message });
return false;
};
const start = async (body) => handle(await runMutation(expeditionCall(() => startExpedition(body))), body.departNow ? content.departedSolo : content.groupOpened);
const claim = async (id) => handle(await runMutation(expeditionCall(() => claimExpedition(id))), content.claimedNotice);
const join = async (id, choice) => handle(await runMutation(expeditionCall(() => joinExpedition(id, choice))), content.joined);
const leave = async (id) => handle(await runMutation(expeditionCall(() => leaveExpedition(id))), content.left);
// Serveur Vite local : un joueur de test rejoint une expédition ouverte au groupe.
const testPlayer = view.testPlayers ? async (id) => handle(await runMutation(expeditionCall(() => addTestPlayer(id))), content.testPlayerAdded) : null;
const bonus = async (item) => handle(await runMutation(expeditionCall(() => addBonusDestination(item))), content.bonusAdded);
const reroll = async () => handle(await runMutation(expeditionCall(() => rerollDestinations())), content.rerolled);
// Atelier : l'erreur s'affiche dans sa fenêtre ; à sa fermeture, la vue est relue pour le compte des plans.
const craft = async (editionIds) => {
const result = await runMutation(async () => {
try {
return await craftPowerCommon(editionIds);
} catch (error) {
return { error: error.message };
}
});
return result?.crafted ? { crafted: result.crafted } : { error: result?.error || "" };
};
const recall = async (id) => handle(await runMutation(expeditionCall(() => recallExpedition(id))), content.recalled);
const depart = async (id) => handle(await runMutation(expeditionCall(() => departExpedition(id))), content.departed);
// L'équipement change les stats des cartes : la vue des Expéditions est relue après chaque pose ou retrait.
const equipAndRefresh = async (call) => {
const result = await runMutation(call);
if (result) load();
return result;
};
const closeStarter = () => {
setStarterClosed(true);
markStarterSeen().catch(() => {});
};
const expired = view.enabled && now >= view.nextDayAt;
const limitReached = view.group.active >= view.group.limit;
const mine = view.groups.filter((group) => group.isMember);
const others = view.groups.filter((group) => !group.isMember);
const invited = joinId && view.groups.find((group) => group.id === joinId);
const journalCount = view.journal.length;
const prepare = <>
{joinId && !invited && view.enabled && <p className="nds-inline-notice" data-variant="info">{content.joinMissing}</p>}
{view.expeditions.map((expedition) => (expedition.status === "running" && expedition.returnsAt > now
? <ExpeditionJourney key={expedition.id} catalog={catalog} expedition={expedition} content={content} now={now} busy={busy} anchors={view.items.anchor} onRecall={recall} />
: <ExpeditionReturn key={expedition.id} catalog={catalog} expedition={expedition} content={content} busy={busy} onClaim={claim} />))}
{mine.length > 0 && <section className="nebula-expedition-active" aria-labelledby="nebula-expedition-mine-title">
<h3 id="nebula-expedition-mine-title">{content.mineTitle}</h3>
<div className="nebula-expedition-reports">{mine.map((group) => <ExpeditionGroupCard key={group.id} catalog={catalog} group={group} cards={view.cards} content={content} now={now} busy={busy} limitReached={limitReached} onJoin={join} onLeave={leave} onDepart={depart} onTestPlayer={testPlayer} />)}</div>
</section>}
{!view.enabled ? <div className="nds-empty-state"><h3>{content.closedTitle}</h3><p>{content.closedText}</p></div>
: !expired && !limitReached && <>
{others.length > 0 && <section className="nebula-expedition-active" aria-labelledby="nebula-expedition-groups-title">
<h3 id="nebula-expedition-groups-title">{content.groupsTitle}</h3>
<div className="nebula-expedition-reports">{others.map((group) => <ExpeditionGroupCard key={group.id} catalog={catalog} group={group} cards={view.cards} content={content} now={now} busy={busy} limitReached={limitReached} onJoin={join} onLeave={leave} onDepart={depart} invited={group.id === joinId} />)}</div>
</section>}
<div className="nebula-expedition-plan-heading">
<h3>{content.planTitle}</h3>
<span className="nebula-form-help">{fillTemplate(content.nextDay, { time: formatCountdown(view.nextDayAt - now) })}</span>
</div>
<ItemBag catalog={catalog} state={state} view={view} content={content} busy={busy} onBonus={bonus} onCraft={craft} onAtelierClosed={reload} runMutation={equipAndRefresh} />
<ExpeditionPlanner key={view.day} catalog={catalog} state={state} view={view} content={content} busy={busy} onStart={start} onReroll={reroll} runMutation={equipAndRefresh} />
</>}
{view.enabled && limitReached && invited && !invited.isMember && <p className="nds-inline-notice" data-variant="info">{content.groupLimit}</p>}
</>;
const journal = <>
<section className="nebula-expedition-active" aria-labelledby="nebula-expedition-journal-title">
<h3 id="nebula-expedition-journal-title">{content.journalTitle}</h3>
{journalCount ? <div className="nebula-expedition-reports">{view.journal.map((expedition) => <ExpeditionReport key={expedition.id} catalog={catalog} expedition={expedition} content={content} now={now} busy={busy} onClaim={claim} />)}</div>
: <p className="nebula-form-help">{content.journalEmpty}</p>}
</section>
</>;
return <section className="nebula-expeditions" aria-labelledby="nebula-expeditions-title">
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-expeditions-title">{content.title}</h2><p className="nebula-guild-intro">{content.intro}</p></div>
<div className="nebula-daily-heading-actions">
<span className="nds-badge" data-variant="gold" title={content.eclatsHelp}><CurrencyAmount kind="eclats">{fillTemplate(content.eclatsBalance, { value: formatEclats(state.wallet.eclats ?? 0) })}</CurrencyAmount></span>
<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a>
</div>
</div>
<Tabs className="nebula-expedition-tabs" tabs={[{ id: "prepare", label: content.tabPrepare }, { id: "journal", label: journalCount ? fillTemplate(content.tabJournalCount, { count: journalCount }) : content.tabJournal }]} activeTab={tab} onChange={setTab} />
{notice && <p className="nds-inline-notice" data-variant={notice.variant} role="status">{notice.text}</p>}
{/* Relecture en échec : la vue précédente reste affichée. */}
{loadError && <div className="nds-inline-notice nebula-daily-expired" data-variant="warning" role="alert"><span>{fillTemplate(content.syncError, { error: loadError })}</span>
<button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={load}>{content.retry}</button></div>}
{expired && <div className="nds-inline-notice nebula-daily-expired" data-variant="warning" role="status"><span>{content.expired}</span><button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={reload}>{content.reload}</button></div>}
{tab === "prepare" ? prepare : journal}
{view.starterCard && !starterClosed && <ExpeditionStarter catalog={catalog} editionId={view.starterCard} content={content} onClose={closeStarter} />}
</section>;
}