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>
This commit is contained in:
Shinuwa 2026-11-18 15:24:39 +01:00
parent 30413de036
commit 84b0d69b1f
13 changed files with 174 additions and 24 deletions

View file

@ -1,8 +1,9 @@
// 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 résultat et son butin sur place ; récupéré, il reste
// affiché jusqu'à « Préparer la suivante ». « Journal » garde les expéditions terminées et leur butin.
import { useEffect, useState } from "react";
// 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";
@ -19,6 +20,10 @@ 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 () => {
@ -85,15 +90,53 @@ export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, j
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(() => {
let active = true;
const ticket = ++latest.current;
loadExpeditions()
.then((result) => { if (active) { setView(result); setLoadError(""); setNow(Date.now()); } })
.catch((error) => { if (active) setLoadError(error.message); });
return () => { active = false; };
.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);
@ -104,17 +147,22 @@ export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, j
useEffect(() => {
const returns = (view?.expeditions || []).filter((expedition) => expedition.status === "running" && !expedition.result).map((expedition) => expedition.returnsAt);
if (!returns.length) return undefined;
const timer = setTimeout(() => setReloadKey((key) => key + 1), Math.max(0, Math.min(...returns) - Date.now()) + 500);
const timer = setTimeout(load, Math.max(0, Math.min(...returns) - Date.now()) + 500);
return () => clearTimeout(timer);
}, [view]);
}, [view, load]);
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p></section>;
// 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;
@ -147,7 +195,7 @@ export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, j
// 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) loadExpeditions().then(setView).catch(() => {});
if (result) load();
return result;
};
const closeStarter = () => {
@ -205,6 +253,9 @@ export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, j
</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} />}