A gold count now sits on the Sokko TCG menu icon while the opening reserve is full, so players notice it from any page. A light reserve route keeps it up to date outside the game, and the game page updates it with every state it gets. The opening stage also lists the remaining openings, apart for the automatic recharge and for openings bought one at a time, since the sidebar reserve is hidden there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
276 lines
14 KiB
JavaScript
276 lines
14 KiB
JavaScript
// Rôle : assemble l'authentification, les sections adressables et le cache local de Sokko TCG.
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import { navigate } from "../../router/hashRouter.js";
|
|
import { AdminPanel } from "./admin/AdminPanel.jsx";
|
|
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 { HistoryPanel } from "./HistoryPanel.jsx";
|
|
import { PackPanel } from "./PackPanel.jsx";
|
|
import { publishCardsReserve } from "./cardsReserve.js";
|
|
import { PrivacyNotice } from "./PrivacyNotice.jsx";
|
|
import { ShopPanel } from "./ShopPanel.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", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
|
|
const PLAYER_SECTIONS = new Set(PLAYER_NAVIGATION.flat());
|
|
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
|
|
const PLAYER_SECTION_ALIASES = { recycling: "collection" };
|
|
|
|
const DISCORD_AUTH_PARAM = "cardsAuth";
|
|
|
|
// 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) || "";
|
|
}
|
|
|
|
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 = "", adminMode = false, adminSection = "", adminSubsection = "" }) {
|
|
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 = PLAYER_SECTION_ALIASES[playerSection] || playerSection;
|
|
const section = PLAYER_SECTIONS.has(resolvedSection) ? resolvedSection : "home";
|
|
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]);
|
|
|
|
useEffect(() => {
|
|
let active = true;
|
|
async function load() {
|
|
if (configLoading) return;
|
|
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;
|
|
}
|
|
const next = await loadCardsState();
|
|
if (!active) return;
|
|
setState(next);
|
|
setStatus("ready");
|
|
setOffline(false);
|
|
void writeCardsCache(next, configCatalogRef.current);
|
|
} catch (loadError) {
|
|
const cached = await readLatestCardsCache().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 loadCardsState();
|
|
setState(next);
|
|
void writeCardsCache(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, 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;
|
|
async function refresh() {
|
|
if (globalThis.document.visibilityState !== "visible") return;
|
|
try {
|
|
setState(await loadCardsState());
|
|
} catch {
|
|
// Le prochain retour ou la prochaine action resynchronisera l'état serveur.
|
|
}
|
|
}
|
|
window.addEventListener("focus", refresh);
|
|
globalThis.document.addEventListener("visibilitychange", refresh);
|
|
return () => {
|
|
window.removeEventListener("focus", refresh);
|
|
globalThis.document.removeEventListener("visibilitychange", refresh);
|
|
};
|
|
}, [offline, status]);
|
|
|
|
async function runMutation(action) {
|
|
if (offline) return null;
|
|
setBusy(true);
|
|
setError("");
|
|
try {
|
|
const result = await action();
|
|
const next = result?.state || result;
|
|
if (next?.player) {
|
|
setState(next);
|
|
void writeCardsCache(next, catalog);
|
|
}
|
|
return result;
|
|
} catch (mutationError) {
|
|
setError(mutationError.message);
|
|
return null;
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
async function loginAsDev() {
|
|
setBusy(true);
|
|
setError("");
|
|
try {
|
|
await devLogin();
|
|
const next = await loadCardsState();
|
|
setState(next);
|
|
setStatus("ready");
|
|
void writeCardsCache(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}` : ""}` : `/cards${section === "home" ? "" : `/${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("/cards");
|
|
}
|
|
|
|
async function logout() {
|
|
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}
|
|
<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} />
|
|
</div>;
|
|
|
|
const openPacks = () => navigate("/cards/packs");
|
|
const pendingTransfers = state.transfers.filter((transfer) => transfer.status === "open" && transfer.direction === "received").length;
|
|
const startTransfer = (type, editionId) => {
|
|
setTransferDraft({ type, editionId });
|
|
navigate("/cards/transfers");
|
|
};
|
|
const panelProps = { catalog, state, runMutation, busy: busy || offline };
|
|
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} />
|
|
</header>;
|
|
|
|
return <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="#/cards">{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], id === "transfers" ? pendingTransfers : 0]))}
|
|
active={section}
|
|
hrefFor={(id) => id === "home" ? "#/cards" : `#/cards/${id}`}
|
|
switchLink={state.player.isAdmin ? { href: "#/cards/admin", label: "Administration" } : null}
|
|
>
|
|
{section === "home" && <CardsHomePanel {...panelProps} content={content.home} onOpenPacks={openPacks} />}
|
|
{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} onOpenPacks={openPacks} />}
|
|
{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} />}
|
|
</CardsDashboardLayout>
|
|
</div>}
|
|
</div>;
|
|
}
|