sokko-g/website/src/features/cards/cardsReserve.js
Shinuwa 498e171bc3 Show a full reserve count on the Sokko TCG menu icon and remaining openings while opening a pack
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>
2026-11-07 23:16:47 +01:00

54 lines
2.2 KiB
JavaScript

// Rôle : partage la réserve d'ouvertures Sokko TCG entre la page de jeu et la pastille du menu.
// La page publie chaque état serveur reçu ; hors de la page, la route légère `/reserve` le relit.
import { useEffect, useSyncExternalStore } from "react";
import { loadCardsReserve } from "./cardsApi.js";
let reserve = null;
const listeners = new Set();
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const snapshot = () => reserve;
// `recharge` vient de l'état serveur ; `null` quand personne n'est connecté.
export function publishCardsReserve(recharge) {
const next = recharge ? { openingsBalance: recharge.openingsBalance, nextOpeningAt: recharge.nextOpeningAt } : null;
if (next?.openingsBalance === reserve?.openingsBalance && next?.nextOpeningAt === reserve?.nextOpeningAt) return;
reserve = next;
for (const listener of listeners) listener();
}
async function refreshReserve() {
if (globalThis.document.visibilityState === "hidden") return;
try {
publishCardsReserve((await loadCardsReserve()).recharge);
} catch {
// Hors connexion, la pastille garde la dernière réserve connue.
}
}
// Renvoie le solde quand la réserve est pleine, sinon `null` : une réserve pleine n'a plus d'échéance de recharge.
export function useFullCardsReserve(enabled) {
const current = useSyncExternalStore(subscribe, snapshot);
const nextOpeningAt = current?.nextOpeningAt;
useEffect(() => {
if (!enabled) return undefined;
void refreshReserve();
window.addEventListener("focus", refreshReserve);
globalThis.document.addEventListener("visibilitychange", refreshReserve);
return () => {
window.removeEventListener("focus", refreshReserve);
globalThis.document.removeEventListener("visibilitychange", refreshReserve);
};
}, [enabled]);
useEffect(() => {
if (!enabled || !nextOpeningAt) return undefined;
const timeout = window.setTimeout(refreshReserve, Math.max(0, nextOpeningAt - Date.now()) + 250);
return () => window.clearTimeout(timeout);
}, [enabled, nextOpeningAt]);
return enabled && current && current.nextOpeningAt == null && current.openingsBalance > 0 ? current.openingsBalance : null;
}