sokko-g/website/src/features/cards/CardsPage.jsx
Shinuwa c3e494b8a6
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 24m57s
Validate and deploy Sokko G / deploy (push) Successful in 17s
Let players use Sokko TCG from a phone through a mobile fallback mode
#/mobile/cards shows the game without the site shell: a title, a footer
with the account and a discreet "Version complète" link, and a tab bar
fixed at the bottom. Phones opening #/cards are sent to the same section
in mobile mode unless the player chose the full version. Account,
History and Administration point to the computer.

The panels are the computer ones, adapted under .nebula-mobile (and
body.nebula-mobile-body for dialogs) for a 393×852 reference phone:
small cards with names under them when opening packs, a revealed card
shown large on tap, tap-to-pick team recruitment with a single Recruit
button and large stars, row lists for explorers and commons in the
expedition pickers, a race track and circuit that read at phone size,
and full-width actions throughout. Firefox no longer shows a mirrored
back on a flipped card.

Phone Playwright journeys check that every section fits the screen with
no button wrapping, then open a pack, run an expedition and recruit a
team by touch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 23:55:35 +01:00

378 lines
21 KiB
JavaScript

/**
* @file Page de Sokko TCG (`#/cards/...`) : connexion, chargement de l'état du joueur, cache hors connexion,
* choix de la section affichée et envoi des actions au serveur ; ouvre aussi l'administration.
*
* Contexte : point d'entrée de l'interface du TCG, chargé à la demande par router/RouteContent.jsx. Il tient
* l'état complet renvoyé par `GET /api/cards/state` et le passe aux panneaux (`GuildPanel`, `PackPanel`…).
* Points d'entrée : `CardsPage` ; aux panneaux, `runMutation(action)`, qui envoie une action et applique l'état
* renvoyé par le serveur.
* Utilisé par : router/RouteContent.jsx (routes `/cards`, `/cards/<section>/<sous-section>`, `/cards/admin/...`) et,
* avec `mobile`, mobile/MobileCardsApp.jsx (routes `/mobile/cards/...`).
* Dépend de : cardsApi.js, cardCache.js, cardsReserve.js, cardsRoutes.js, useCardsHref.js, CardsDashboard.jsx,
* mobile/MobileCardsLayout.jsx, les panneaux de section, admin/AdminPanel.jsx (chargé à la demande).
* Attention :
* - Réponses périmées : `stateGeneration` et `latestMutation` font ignorer une lecture partie avant une
* mutation, et le résultat d'une mutation dépassée par une plus récente.
* - Sections : `PLAYER_NAVIGATION` pour le menu ; les quêtes de la Guilde sont des sous-sections
* (`SUBSECTION_PARENTS`). Une nouvelle section s'ajoute aux deux endroits utiles et au rendu en fin de fichier.
* - Hors connexion, l'état vient du cache et `runMutation` ne fait rien.
* - Mode mobile (`mobile`) : mêmes panneaux dans le cadre mobile, limités à `MOBILE_SECTIONS` ; les liens des
* panneaux suivent la racine fournie par `CardsBaseContext` (useCardsHref.js), jamais `#/cards/...` en dur.
* - Importe cards-route.scss : les styles du TCG ne se chargent qu'avec cette page.
* @see website/src/features/cards/README.md
*/
import "../../styles/cards-route.scss";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { navigate } from "../../router/hashRouter.js";
import { CARDS_BASE, MOBILE_CARDS_BASE, MOBILE_SECTIONS, cardsRoute, resolveCardsSection } from "./cardsRoutes.js";
import { CardsBaseContext } from "./useCardsHref.js";
import { MobileCardsLayout, MobileUnavailable } from "./mobile/MobileCardsLayout.jsx";
import { isPhoneScreen, rememberFullVersion } from "./mobile/mobileDevice.js";
import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js";
import { AccountPanel } from "./AccountPanel.jsx";
import { deleteCardsAccount, devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js";
import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx";
import { CardsHomePanel } from "./CardsHomePanel.jsx";
import { CollectionPanel } from "./CollectionPanel.jsx";
import { DailyPanel } from "./daily/DailyPanel.jsx";
import { ExpeditionsPanel } from "./expeditions/ExpeditionsPanel.jsx";
import { HistoryPanel } from "./HistoryPanel.jsx";
import { PackPanel } from "./PackPanel.jsx";
import { publishCardsReserve } from "./cardsReserve.js";
import { PrivacyNotice } from "./PrivacyNotice.jsx";
import { GuildPanel } from "./GuildPanel.jsx";
import { pendingQuestCount } from "./guildQuests.js";
import { MirrorPanel } from "./mirror/MirrorPanel.jsx";
import { RacePanel } from "./team/RacePanel.jsx";
import { ShopPanel } from "./ShopPanel.jsx";
import { TeamPanel } from "./team/TeamPanel.jsx";
import { TransfersPanel } from "./TransfersPanel.jsx";
// Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration.
const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
// Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente.
const SUBSECTION_PARENTS = { daily: "guild", team: "guild", race: "guild", mirror: "guild", expeditions: "guild" };
const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]);
const DISCORD_AUTH_PARAM = "cardsAuth";
// Réservée aux administrateurs : les joueurs ne téléchargent pas son code.
const AdminPanel = lazy(() => import("./admin/AdminPanel.jsx").then((module) => ({ default: module.AdminPanel })));
/** React peut abandonner un rendu ou remonter la page : l'initialiseur ne fait que lire, le nettoyage attend un écran affiché. */
function readDiscordAuthFailure() {
return new URLSearchParams(window.location.search).get(DISCORD_AUTH_PARAM) || "";
}
/** Le cache est un confort hors connexion : un refus du stockage ne doit ni bloquer le jeu ni laisser une promesse rejetée. */
function saveCardsCache(state, catalog) {
void writeCardsCache(state, catalog).catch(() => {});
}
function clearDiscordAuthFailure() {
const params = new URLSearchParams(window.location.search);
if (!params.has(DISCORD_AUTH_PARAM)) return;
params.delete(DISCORD_AUTH_PARAM);
const query = params.toString();
window.history.replaceState(window.history.state, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`);
}
export function CardsPage({ siteContent, cardsConfig, playerSection = "", playerSubsection = "", adminMode = false, adminSection = "", adminSubsection = "", mobile = false }) {
const content = siteContent.cards;
const [status, setStatus] = useState("loading");
const [state, setState] = useState(null);
const [cachedCatalog, setCachedCatalog] = useState(null);
const [offline, setOffline] = useState(false);
const [error, setError] = useState("");
const [authFailure] = useState(readDiscordAuthFailure);
const [busy, setBusy] = useState(false);
const [accountDeleted, setAccountDeleted] = useState(false);
const [privacyOpen, setPrivacyOpen] = useState(false);
const privacyPanelRef = useRef(null);
const resolvedSection = resolveCardsSection(playerSection);
const section = PLAYER_SECTIONS.has(resolvedSection) ? resolvedSection : "home";
// Racine des liens : version complète ou mode mobile. En mobile, Compte, Historique et Administration renvoient
// vers la version complète.
const base = mobile ? MOBILE_CARDS_BASE : CARDS_BASE;
const mobileUnavailable = mobile && (resolvedSection === "admin" || (PLAYER_SECTIONS.has(resolvedSection) && !MOBILE_SECTIONS.has(resolvedSection)));
const [transferDraft, setTransferDraft] = useState(null);
const clearTransferDraft = useCallback(() => setTransferDraft(null), []);
const catalog = cardsConfig.catalog || cachedCatalog;
const { loading: configLoading, enabled: configEnabled, error: configError } = cardsConfig;
// Le catalogue peut être remplacé par l'administration : le chargement initial ne doit pas se relancer pour autant.
const configCatalogRef = useRef(cardsConfig.catalog);
useEffect(() => { configCatalogRef.current = cardsConfig.catalog; }, [cardsConfig.catalog]);
// Une relecture de l'état ne s'applique que si rien de plus récent ne l'a dépassée : chaque mutation, déconnexion ou
// nouvelle lecture change la génération, et une réponse partie avant ce changement est ignorée.
const stateGeneration = useRef(0);
const latestMutation = useRef(0);
const refreshInFlight = useRef(null);
const reloadState = useCallback(async () => {
const generation = ++stateGeneration.current;
const next = await loadCardsState();
if (generation !== stateGeneration.current) return null;
setState(next);
return next;
}, []);
useEffect(() => {
let active = true;
async function load() {
if (configLoading) return;
let playerId = null;
try {
if (!configEnabled) throw new Error(configError || content.disabled);
const session = await loadCardsSession();
if (!active) return;
if (!session.authenticated) {
void clearCardsCache().catch(() => {});
setStatus("anonymous");
return;
}
playerId = session.player.id;
const next = await loadCardsState();
if (!active) return;
setState(next);
setStatus("ready");
setOffline(false);
saveCardsCache(next, configCatalogRef.current);
} catch (loadError) {
// Session reconnue : seule la copie de ce joueur peut s'afficher. Serveur injoignable : la dernière copie enregistrée.
const cached = await readLatestCardsCache(playerId).catch(() => null);
if (!active) return;
if (cached?.state && cached?.catalog) {
setState(cached.state);
setCachedCatalog(cached.catalog);
setOffline(true);
setStatus("ready");
setError(loadError.message);
} else {
setStatus(configEnabled ? "error" : "disabled");
setError(loadError.message);
}
}
}
void load();
return () => { active = false; };
}, [configLoading, configEnabled, configError, content.disabled]);
useEffect(() => {
if (status !== "loading") clearDiscordAuthFailure();
}, [status]);
// La pastille du menu suit chaque état reçu, sans attendre sa propre relecture.
useEffect(() => {
if (status === "anonymous") publishCardsReserve(null);
else if (status === "ready" && !offline && state?.recharge) publishCardsReserve(state.recharge);
}, [offline, state?.recharge, status]);
// Le panneau s'ouvre sous le login, parfois hors de l'écran.
useEffect(() => {
if (privacyOpen) privacyPanelRef.current?.scrollIntoView({ block: "nearest" });
}, [privacyOpen]);
useEffect(() => {
const nextOpeningAt = state?.recharge?.nextOpeningAt;
if (status !== "ready" || offline || !nextOpeningAt) return undefined;
const timeout = window.setTimeout(async () => {
try {
const next = await reloadState();
if (next) saveCardsCache(next, catalog);
} catch {
// Le prochain chargement ou une mutation resynchronisera l'état serveur.
}
}, Math.max(0, nextOpeningAt - Date.now()) + 250);
return () => window.clearTimeout(timeout);
}, [catalog, offline, reloadState, state?.recharge?.nextOpeningAt, status]);
// Les propositions arrivent sans notification : l'état se resynchronise au retour sur la page.
useEffect(() => {
if (status !== "ready" || offline) return undefined;
/** Le focus et visibilitychange arrivent ensemble au retour sur l'onglet : une seule lecture part. */
function refresh() {
if (globalThis.document.visibilityState !== "visible" || refreshInFlight.current) return;
refreshInFlight.current = reloadState()
.catch(() => {
// Le prochain retour ou la prochaine action resynchronisera l'état serveur.
})
.finally(() => { refreshInFlight.current = null; });
}
window.addEventListener("focus", refresh);
globalThis.document.addEventListener("visibilitychange", refresh);
return () => {
window.removeEventListener("focus", refresh);
globalThis.document.removeEventListener("visibilitychange", refresh);
};
}, [offline, reloadState, status]);
async function runMutation(action) {
if (offline) return null;
setBusy(true);
setError("");
// Une lecture partie avant ou pendant la mutation décrit un état que la mutation a peut-être déjà remplacé :
// la génération change au début et à la fin, et seule la dernière mutation lancée applique son résultat.
const mutation = ++latestMutation.current;
stateGeneration.current += 1;
try {
const result = await action();
const next = result?.state || result;
if (next?.player && mutation === latestMutation.current) {
setState(next);
saveCardsCache(next, catalog);
}
return result;
} catch (mutationError) {
setError(mutationError.message);
return null;
} finally {
stateGeneration.current += 1;
setBusy(false);
}
}
async function loginAsDev() {
setBusy(true);
setError("");
try {
await devLogin();
const next = await reloadState();
if (!next) return;
setStatus("ready");
saveCardsCache(next, catalog);
} catch (loginError) {
setError(loginError.message);
} finally {
setBusy(false);
}
}
if (cardsConfig.loading || status === "loading") return <section className="empty nds-empty-state" aria-busy="true"><h1>{content.loadingTitle}</h1><p>{content.loadingText}</p></section>;
if (status === "disabled") return <section className="empty nds-empty-state"><h1>{content.disabledTitle}</h1><p>{error || content.disabled}</p></section>;
if (status === "error") return <section className="empty nds-empty-state" role="alert"><h1>{content.errorTitle}</h1><p>{error}</p></section>;
if (status === "anonymous") return <>
<section className="nebula-login nds-panel">
<div className="nebula-login-art"><img src="/static/img/cards/login.webp" alt="" width="800" height="800" /></div>
<div className="nebula-login-content">
<p className="eyebrow">{content.eyebrow}</p>
<h1>{content.title}</h1>
<p>{content.loginDescription}</p>
<div className="nebula-login-actions">
{cardsConfig.discordConfigured && <a className="nds-button nebula-discord-login" href={`/api/cards/auth/discord?returnTo=${encodeURIComponent(adminMode ? `/cards/admin${adminSection ? `/${adminSection}` : ""}${adminSubsection ? `/${adminSubsection}` : ""}` : cardsRoute(base, mobileUnavailable ? "" : section))}`}><img src="/static/icons/discord.svg" alt="" aria-hidden="true" /><span>{content.discordLogin}</span></a>}
{cardsConfig.devAuth && <button className="nds-button nebula-dev-login" data-variant="secondary" type="button" disabled={busy} onClick={loginAsDev}>{content.devLogin}</button>}
</div>
{!cardsConfig.discordConfigured && <p className="nds-inline-notice" data-variant="warning" role="status">{content.discordUnavailable}</p>}
{authFailure && <p className="nds-inline-notice" data-variant="danger" role="alert">{content.discordErrors[authFailure] || content.discordErrors.failed}</p>}
{error && <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>}
{accountDeleted && <p className="nds-inline-notice" data-variant="success" role="status">{content.account.deleted}</p>}
</div>
</section>
<button className="nebula-privacy-toggle" type="button" aria-expanded={privacyOpen} aria-controls="nebula-login-privacy" onClick={() => setPrivacyOpen((open) => !open)}><span aria-hidden="true">▸</span>{content.privacy.title}</button>
{privacyOpen && <section ref={privacyPanelRef} id="nebula-login-privacy" className="nebula-login-privacy nds-panel" aria-labelledby="nebula-login-privacy-title">
<h2 id="nebula-login-privacy-title">{content.privacy.title}</h2>
<PrivacyNotice content={content.privacy} contact={cardsConfig.privacyContact} controller={cardsConfig.privacyController} />
</section>}
</>;
async function deleteAccount() {
const result = await runMutation(() => deleteCardsAccount());
if (!result?.ok) return;
await clearCardsCache().catch(() => {});
setState(null);
setAccountDeleted(true);
setStatus("anonymous");
navigate(base);
}
async function logout() {
stateGeneration.current += 1;
await logoutCards();
await clearCardsCache().catch(() => {});
setState(null);
setStatus("anonymous");
}
const notices = <>
{offline && <p className="nds-inline-notice" data-variant="warning" role="status">Mode hors connexion : la dernière collection enregistrée est consultable, les actions sont suspendues.</p>}
{error && <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>}
</>;
// L'administration a son propre en-tête compact (titre, actualisation, joueur).
if (adminMode && state.player.isAdmin) return <div className="nebula-cards-page">
{notices}
<Suspense fallback={<section className="empty nds-empty-state" aria-busy="true"><h1>{content.loadingTitle}</h1><p>{content.loadingText}</p></section>}>
<AdminPanel catalog={catalog} state={state} runMutation={runMutation} busy={busy || offline} section={adminSection} subsection={adminSubsection} onCatalogChange={cardsConfig.replaceCatalog} backLabel={content.admin.backToGame} onLogout={offline ? null : logout} />
</Suspense>
</div>;
const openPacks = () => navigate(cardsRoute(base, "packs"));
const navigationCounts = {
guild: pendingQuestCount(state),
// Seulement la réserve rechargée automatiquement, pas les ouvertures achetées.
packs: state.recharge.openingsBalance,
transfers: state.transfers.filter((transfer) => transfer.status === "open" && transfer.direction === "received").length
};
const startTransfer = (type, editionId) => {
setTransferDraft({ type, editionId });
navigate(cardsRoute(base, "transfers"));
};
// `cardSheetContent` : textes de la fiche d'une carte, ouverte depuis plusieurs panneaux ; ceux des Expéditions y nomment les stats
// et les pouvoirs d'une commune.
const panelProps = { catalog, state, runMutation, busy: busy || offline, cardSheetContent: { ...content.cardSheet, expeditions: content.expeditions } };
// Sur un téléphone seulement, la version complète propose de revenir au mode mobile, sur la même section quand il
// la propose. Ailleurs, le hero reste inchangé.
const mobileSwitch = isPhoneScreen() && <a className="nds-button nebula-mobile-switch" data-size="sm" data-variant="secondary" href={`#${cardsRoute(MOBILE_CARDS_BASE, MOBILE_SECTIONS.has(section) ? section : "")}`} onClick={() => rememberFullVersion(false)}>{content.mobile.mobileVersion}</a>;
const hero = <header className="page-hero nds-page-hero nebula-player-hero">
<div><p className="eyebrow">{content.eyebrow}</p><h1>{content.title}</h1><p>{content.description}</p></div>
<CardsAccount player={state.player} onLogout={offline ? null : logout} />
{mobileSwitch}
</header>;
const panel = <>
{section === "home" && <CardsHomePanel {...panelProps} content={content.home} guildContent={content.guild} tipsContent={content.tips} onOpenPacks={openPacks} />}
{section === "guild" && <GuildPanel catalog={catalog} state={state} content={content.guild} teamContent={content.team} statLabels={content.expeditions.stats} />}
{section === "daily" && <DailyPanel {...panelProps} content={content.daily} />}
{section === "team" && <TeamPanel {...panelProps} content={content.team} statLabels={content.expeditions.stats} />}
{section === "race" && <RacePanel {...panelProps} content={content.race} teamContent={content.team} statLabels={content.expeditions.stats} />}
{section === "mirror" && <MirrorPanel {...panelProps} content={content.mirror} teamContent={content.team} />}
{section === "expeditions" && <ExpeditionsPanel {...panelProps} content={{ ...content.expeditions, cardSheet: content.cardSheet }} joinId={decodeURIComponent(playerSubsection)} />}
{section === "packs" && <PackPanel {...panelProps} content={content.packs} reserveContent={content.home} />}
{section === "collection" && <CollectionPanel {...panelProps} headingContent={content.collection} recyclingContent={content.recycling} onStartTransfer={startTransfer} />}
{section === "shop" && <ShopPanel {...panelProps} content={content.shop} openingContent={content.packs} />}
{section === "transfers" && <TransfersPanel {...panelProps} content={content.transfers} draft={transferDraft} onDraftUsed={clearTransferDraft} />}
{section === "history" && <HistoryPanel catalog={catalog} state={state} content={content.history} />}
{section === "account" && <AccountPanel state={state} busy={busy || offline} content={content.account} privacy={content.privacy} privacyContact={cardsConfig.privacyContact} privacyController={cardsConfig.privacyController} onDelete={deleteAccount} runMutation={runMutation} />}
</>;
if (mobile) {
const desktopSection = mobileUnavailable ? resolvedSection : section;
const fullVersionHref = `#${cardsRoute(CARDS_BASE, desktopSection, mobileUnavailable ? "" : playerSubsection)}`;
return <CardsBaseContext.Provider value={base}>
<div className="nebula-cards-page">
<MobileCardsLayout content={content} player={state.player} counts={navigationCounts} active={mobileUnavailable ? "" : SUBSECTION_PARENTS[section] || section} busy={busy} onLogout={offline ? null : logout} fullVersionHref={fullVersionHref} notices={notices}>
{mobileUnavailable ? <MobileUnavailable content={content} fullVersionHref={fullVersionHref} /> : panel}
</MobileCardsLayout>
</div>
</CardsBaseContext.Provider>;
}
return <CardsBaseContext.Provider value={base}>
<div className="nebula-cards-page">
{adminMode ? <div className="nebula-dashboard">
{hero}
{notices}
<section className="nds-empty-state"><h2>{content.admin.restrictedTitle}</h2><p>{content.admin.restrictedText}</p><a className="nds-button" data-variant="secondary" href={`#${base}`}>{content.admin.backToGame}</a></section>
</div> : <div className="nebula-dashboard">
{hero}
{notices}
<CardsDashboardLayout
label={`Sections de ${content.title}`}
groups={PLAYER_NAVIGATION.map((ids) => ids.map((id) => [id, content.navigation[id], navigationCounts[id] || 0]))}
active={SUBSECTION_PARENTS[section] || section}
hrefFor={(id) => `#${cardsRoute(base, id)}`}
switchLink={state.player.isAdmin ? { href: "#/cards/admin", label: "Administration" } : null}
>
{panel}
</CardsDashboardLayout>
</div>}
</div>
</CardsBaseContext.Provider>;
}