Let players use Sokko TCG from a phone through a mobile fallback mode
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 24m57s
Validate and deploy Sokko G / deploy (push) Successful in 17s

#/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>
This commit is contained in:
Shinuwa 2026-12-03 23:55:35 +01:00
parent 0262f596c9
commit c3e494b8a6
53 changed files with 1830 additions and 123 deletions

View file

@ -2,10 +2,10 @@
* @file Cadre commun des tableaux de bord joueur et administration de Sokko TCG : menu de sections (menu
* déroulant quand la place manque), encart sous le menu, compte et chiffres clés.
*
* Points d'entrée : `CardsDashboardLayout`, `DashboardAside` (encart sous le menu, déclaré par un panneau),
* `CardsAccount`, `DashboardStat`.
* Utilisé par : CardsPage.jsx et admin/AdminPanel.jsx ; `DashboardAside` par l'accueil, les paquets, l'album et
* la boutique.
* Points d'entrée : `CardsDashboardLayout`, `CardsStackedSection` (section sans colonne de menu, en mode
* mobile), `DashboardAside` (encart sous le menu, déclaré par un panneau), `CardsAccount`, `DashboardStat`.
* Utilisé par : CardsPage.jsx, admin/AdminPanel.jsx et mobile/MobileCardsLayout.jsx ; `DashboardAside` par
* l'accueil, les paquets, l'album et la boutique.
*/
import { createContext, Fragment, useContext, useEffect, useId, useRef, useState } from "react";
@ -75,6 +75,20 @@ export function CardsDashboardLayout({ label, groups, active, hrefFor, switchLin
</div>;
}
/**
* Section seule, sans colonne de menu : l'encart déclaré par le panneau (`DashboardAside`) passe au-dessus d'elle.
* Utilisé par le mode mobile, dont le menu est une barre d'onglets.
*/
export function CardsStackedSection({ active, busy = false, children }) {
const [asideSlot, setAsideSlot] = useState(null);
return <>
<div ref={setAsideSlot} className="nebula-dashboard-aside-slot" />
<div className="nebula-dashboard-section" data-section={active} aria-busy={busy || undefined}>
<AsideSlotContext.Provider value={asideSlot}>{children}</AsideSlotContext.Provider>
</div>
</>;
}
/** Place un encart propre à la section sous le menu, tout en gardant son état dans le panneau qui le déclare. */
export function DashboardAside({ children }) {
const slot = useContext(AsideSlotContext);

View file

@ -12,12 +12,14 @@ import { OpeningReserve } from "./OpeningReserve.jsx";
import { fillTemplate } from "./textFormat.js";
import { pendingQuestCount } from "./guildQuests.js";
import { StardustBalance } from "./Currency.jsx";
import { useCardsHref } from "./useCardsHref.js";
// Le dragon des Veilleurs, parchemin de quête en main : l'emblème de la Guilde, propre à elle et non à l'une de ses quêtes.
const GUILD_ILLUSTRATION = "/static/img/cards/guild-veilleurs.webp";
/** Encart de la Guilde des Veilleurs, à côté du meilleur tirage : une entrée vers la Guilde, qui annonce combien de quêtes attendent sans les détailler. */
function GuildBanner({ state, content, guildContent }) {
const cardsHref = useCardsHref();
const pending = pendingQuestCount(state);
const status = pending ? fillTemplate(content.guildPending, { count: pending, s: pending > 1 ? "s" : "", ent: pending > 1 ? "ent" : "" }) : content.guildIdle;
return <section className="nds-panel nebula-guild-banner" data-pending={pending > 0 || undefined} aria-labelledby="nebula-guild-banner-title">
@ -26,7 +28,7 @@ function GuildBanner({ state, content, guildContent }) {
<h3 id="nebula-guild-banner-title">{guildContent.title}</h3>
<p>{content.guildTagline}</p>
<p className="nebula-guild-banner-status">{status}</p>
<a className="nds-button" data-size="sm" data-variant={pending ? "primary" : "secondary"} href="#/cards/guild">{content.guildAction}</a>
<a className="nds-button" data-size="sm" data-variant={pending ? "primary" : "secondary"} href={cardsHref("guild")}>{content.guildAction}</a>
</div>
</section>;
}

View file

@ -6,15 +6,18 @@
* 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/...`).
* Dépend de : cardsApi.js, cardCache.js, cardsReserve.js, CardsDashboard.jsx, les panneaux de section,
* admin/AdminPanel.jsx (chargé à la demande).
* 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
*/
@ -22,6 +25,10 @@
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";
@ -47,8 +54,6 @@ const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "t
// 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)]);
// 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";
// Réservée aux administrateurs : les joueurs ne téléchargent pas son code.
@ -72,7 +77,7 @@ function clearDiscordAuthFailure() {
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 = "" }) {
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);
@ -84,8 +89,12 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
const [accountDeleted, setAccountDeleted] = useState(false);
const [privacyOpen, setPrivacyOpen] = useState(false);
const privacyPanelRef = useRef(null);
const resolvedSection = PLAYER_SECTION_ALIASES[playerSection] || playerSection;
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;
@ -248,7 +257,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
<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.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>}
@ -271,7 +280,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
setState(null);
setAccountDeleted(true);
setStatus("anonymous");
navigate("/cards");
navigate(base);
}
async function logout() {
@ -295,7 +304,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
</Suspense>
</div>;
const openPacks = () => navigate("/cards/packs");
const openPacks = () => navigate(cardsRoute(base, "packs"));
const navigationCounts = {
guild: pendingQuestCount(state),
// Seulement la réserve rechargée automatiquement, pas les ouvertures achetées.
@ -304,45 +313,66 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
};
const startTransfer = (type, editionId) => {
setTransferDraft({ type, editionId });
navigate("/cards/transfers");
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} />}
</>;
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], navigationCounts[id] || 0]))}
active={SUBSECTION_PARENTS[section] || 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} 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} />}
</CardsDashboardLayout>
</div>}
</div>;
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>;
}

View file

@ -18,11 +18,13 @@ import { StardustBalance } from "./Currency.jsx";
import { formatStardust } from "./stardustFormat.js";
import { fillTemplate } from "./textFormat.js";
import { frenchList, rarityAdjective } from "./rarityWords.js";
import { useCardsHref } from "./useCardsHref.js";
const OWNERSHIP_OPTIONS = [{ value: "owned", label: "Possédées" }, { value: "missing", label: "Manquantes" }, { value: "duplicates", label: "Doublons" }];
const countDuplicates = (count) => `${count} doublon${count > 1 ? "s" : ""}`;
export function CollectionPanel({ catalog, state, runMutation, busy, headingContent, recyclingContent: content, cardSheetContent, onStartTransfer }) {
const cardsHref = useCardsHref();
const [search, setSearch] = useState("");
const [collectionIds, setCollectionIds] = useState([]);
const [rarities, setRarities] = useState([]);
@ -98,7 +100,7 @@ export function CollectionPanel({ catalog, state, runMutation, busy, headingCont
<button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy || Boolean(state.pendingOpening) || !preview.count} onClick={() => setConfirmingRecycle(true)}>{content.allButton}</button>
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => setOwnership(showingDuplicates ? [] : ["duplicates"])}>{showingDuplicates ? content.viewAll : content.viewDuplicates}</button>
</div>
{state.pendingOpening && <p className="nebula-form-help">{content.pending} <a href="#/cards/packs">{content.pendingAction}</a></p>}
{state.pendingOpening && <p className="nebula-form-help">{content.pending} <a href={cardsHref("packs")}>{content.pendingAction}</a></p>}
</section>
</DashboardAside>}
{recycleNotice && <p className="nds-inline-notice" data-variant="success" role="status">{recycleNotice}</p>}

View file

@ -13,6 +13,7 @@ import { fillTemplate, formatStreak } from "./textFormat.js";
import { expeditionQuestStatus } from "./expeditions/expeditionFormat.js";
import { guildGreeting, guildQuests, mirrorDone, questDone } from "./guildQuests.js";
import { TeamTable } from "./team/TeamTable.jsx";
import { useCardsHref } from "./useCardsHref.js";
const ART = {
hall: "/static/img/cards/guild/hall.webp",
@ -50,32 +51,36 @@ function QuestTile({ id, art, kind, title, description, status = null, action, h
}
function DailyQuest({ summary: daily, pending, content }) {
const cardsHref = useCardsHref();
const finished = daily.status !== "playing" && !daily.rewardPending;
return <QuestTile id="daily" art={ART.daily} kind={content.dailyKind} title={content.dailyTitle} description={content.dailyDescription} doneSign={content.doneSign}
action={finished ? content.dailyResult : daily.rewardPending ? content.dailyChoose : content.dailyAction} href="#/cards/daily" primary={pending} done={finished}
action={finished ? content.dailyResult : daily.rewardPending ? content.dailyChoose : content.dailyAction} href={cardsHref("daily")} primary={pending} done={finished}
badge={daily.streak > 0 && <span className="nds-badge" data-variant="gold">{fillTemplate(content.dailyStreak, { streak: formatStreak(daily.streak) })}</span>} />;
}
/** La Course attend une équipe : sans elle, sa tuile renvoie au recrutement. */
function RaceQuest({ summary: team, pending, content }) {
const cardsHref = useCardsHref();
const locked = team.status !== "ready" && team.race === "none";
return <QuestTile id="race" art={ART.race} kind={content.raceKind} title={content.raceTitle} description={content.raceDescription} doneSign={content.doneSign}
action={locked ? content.raceToTeam : team.race === "finished" ? content.raceResult : content.raceAction} href={locked ? "#/cards/team" : "#/cards/race"}
action={locked ? content.raceToTeam : team.race === "finished" ? content.raceResult : content.raceAction} href={cardsHref(locked ? "team" : "race")}
primary={pending && !locked} locked={locked} done={team.race === "finished"} sign={locked ? content.groupSign : ""} />;
}
/** Miroir brisé : le Normal, puis le Difficile du jour, le même pour tous. */
function MirrorQuest({ summary: mirror, pending, content }) {
const cardsHref = useCardsHref();
const done = mirrorDone(mirror);
const playing = ["easy", "normal", "hard"].some((mode) => mirror[mode] === "playing");
return <QuestTile id="mirror" art={ART.mirror} kind={content.mirrorKind} title={content.mirrorTitle} description={content.mirrorDescription} doneSign={content.doneSign}
action={done ? content.mirrorResult : playing ? content.mirrorResume : content.mirrorAction} href="#/cards/mirror" primary={pending} done={done} />;
action={done ? content.mirrorResult : playing ? content.mirrorResume : content.mirrorAction} href={cardsHref("mirror")} primary={pending} done={done} />;
}
function ExpeditionsQuest({ summary, pending, content, now }) {
const cardsHref = useCardsHref();
const returned = summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now);
return <QuestTile id="expeditions" art={ART.expeditions} kind={content.expeditionsKind} title={content.expeditionsTitle} description={content.expeditionsDescription}
status={expeditionQuestStatus(summary, content, now)} href="#/cards/expeditions" primary={pending}
status={expeditionQuestStatus(summary, content, now)} href={cardsHref("expeditions")} primary={pending}
action={returned ? content.expeditionsClaim : summary.running ? content.expeditionsInProgress : summary.enabled ? content.expeditionsAction : content.expeditionsOpen} />;
}
@ -106,13 +111,14 @@ function GuildCounter({ state, quests, content, now }) {
/** Votre équipe : le même bloc que sur la page Équipe du jour, avec le bouton qui y mène. */
function GuildTeam({ catalog, team, content, teamContent, statLabels }) {
const cardsHref = useCardsHref();
const ready = team.status === "ready";
const recruiting = team.status === "recruiting";
const text = ready ? fillTemplate(content.teamReady, { day: team.teamDay, max: team.maxDays }) : recruiting ? content.teamRecruiting : content.teamEmpty;
return <TeamTable catalog={catalog} companions={team.companions} content={teamContent} statLabels={statLabels} showBest={ready} seatLabel={teamContent.seat}
title={content.teamTitle} titleId="nebula-guild-team-title"
status={<>{text}{ready && <span className="nebula-team-days" aria-hidden="true">{Array.from({ length: team.maxDays }, (_, index) => <i key={index} data-on={index < team.teamDay || undefined} />)}</span>}</>}
action={<a className="nds-button" data-size="sm" data-variant={ready ? "secondary" : "primary"} href="#/cards/team">{ready ? content.teamOpen : recruiting ? content.teamResume : content.teamRecruit}</a>} />;
action={<a className="nds-button" data-size="sm" data-variant={ready ? "secondary" : "primary"} href={cardsHref("team")}>{ready ? content.teamOpen : recruiting ? content.teamResume : content.teamRecruit}</a>} />;
}
export function GuildPanel({ catalog, state, content, teamContent, statLabels }) {

View file

@ -10,6 +10,9 @@ import { formatPercent, rarityPercentages } from "./dropRates.js";
import { NebulaCard } from "./rendering/NebulaCard.jsx";
import { OpeningReserve } from "./OpeningReserve.jsx";
import { packDetails, summarizeReward } from "./rewardText.js";
import { useCardsMobile } from "./useCardsHref.js";
import { OpeningCardZoom } from "./mobile/OpeningCardZoom.jsx";
import { fillTemplate } from "./textFormat.js";
export function PackPanel({ catalog, state, runMutation, busy, content, reserveContent }) {
const activeCollections = catalog.collections.filter((collection) => collection.active);
@ -133,18 +136,28 @@ export function OpeningStage({ catalog, opening, onComplete, onDismiss, onOpenAn
const [revealed, setRevealed] = useState(new Set());
const [finishedReveals, setFinishedReveals] = useState(new Set());
const [completed, setCompleted] = useState(false);
// Les boutons de fin n'apparaissent qu'une fois l'enregistrement automatique répondu : affichés pendant la requête,
// ils naissaient désactivés puis s'activaient aussitôt, ce qui clignotait.
const [completionSettled, setCompletionSettled] = useState(false);
const completionRequestedRef = useRef(false);
const revealAllRef = useRef(null);
const allStarted = revealed.size === opening.cards.length;
const allRevealed = finishedReveals.size === opening.cards.length;
const collection = catalog.collections.find((item) => item.id === opening.collectionId);
// Sur téléphone, les trois cartes tiennent côte à côte en petit format, qui n'affiche pas le nom : il passe dessous.
// Le bouton « Ouvrir un autre paquet » y prend un libellé court pour tenir sur une ligne, et la révélation y est
// sobre (pas d'effets qui déborderaient sur les cartes voisines).
const mobile = useCardsMobile();
const finished = allRevealed && completionSettled;
// Sur téléphone, une carte révélée se touche pour la voir en grand.
const [zoomed, setZoomed] = useState(null);
useEffect(() => {
if (!allRevealed || completionRequestedRef.current) return;
completionRequestedRef.current = true;
void onComplete().then((result) => {
if (result) setCompleted(true);
});
}).finally(() => setCompletionSettled(true));
}, [allRevealed, onComplete]);
useEffect(() => {
@ -173,15 +186,24 @@ export function OpeningStage({ catalog, opening, onComplete, onDismiss, onOpenAn
</dl>
</div>
</div>
{!allStarted && <button ref={revealAllRef} className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => setRevealed(new Set(opening.cards.map((card) => card.id)))}>Tout révéler</button>}
{allRevealed && <div className="nds-toolbar">
{/* Sur téléphone, les actions sont sous le titre : « Tout révéler » reste en place, invisible, jusqu'aux boutons
de fin, pour que la page ne saute pas entre les deux. */}
{(!allStarted || (mobile && !finished)) && <button ref={revealAllRef} className="nds-button" data-size="sm" data-variant="secondary" type="button" data-placeholder={allStarted || undefined} disabled={allStarted} onClick={() => setRevealed(new Set(opening.cards.map((card) => card.id)))}>Tout révéler</button>}
{finished && <div className="nds-toolbar">
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={finish}>{content.back}</button>
{onOpenAnother && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={openAnother}>{content.openAnother}</button>}
{onOpenAnother && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={openAnother}>{mobile ? content.openAnotherShort : content.openAnother}</button>}
</div>}
</div>
<div className="nebula-opening-cards">
{opening.cards.map((card) => <NebulaCard key={card.id} catalog={catalog} entry={card} size="lg" faceUp={false} backCollection={collection} newBadge={card.isNewEdition ? content.newBadge : null} revealed={revealed.has(card.id)} onReveal={() => setRevealed((current) => new Set([...current, card.id]))} onRevealComplete={() => setFinishedReveals((current) => new Set([...current, card.id]))} />)}
{opening.cards.map((card) => <NebulaCard key={card.id} catalog={catalog} entry={card} size={mobile ? "sm" : "lg"} quietReveal={mobile} onOpen={mobile ? () => setZoomed(card) : null} openLabel={fillTemplate(content.zoomCard, { card: card.card.name })} faceUp={false} backCollection={collection} newBadge={card.isNewEdition ? content.newBadge : null} revealed={revealed.has(card.id)} onReveal={() => setRevealed((current) => new Set([...current, card.id]))} onRevealComplete={() => setFinishedReveals((current) => new Set([...current, card.id]))} />)}
{mobile && <ol className="nebula-opening-names" aria-hidden="true">
{opening.cards.map((card) => <li key={card.id}>{finishedReveals.has(card.id) && <>
<span className="nds-badge nebula-opening-rarity" data-rarity={card.edition.rarity}>{catalog.rarities.find((item) => item.id === card.edition.rarity)?.label}</span>
<strong>{card.card.name}</strong>
</>}</li>)}
</ol>}
</div>
<OpeningOdds catalog={catalog} opening={opening} collection={collection} content={content} shopShare={shopShare} />
{zoomed && <OpeningCardZoom catalog={catalog} entry={zoomed} closeLabel={content.zoomClose} onClose={() => setZoomed(null)} />}
</section>;
}

View file

@ -30,6 +30,7 @@ quête de la Guilde et le rendu des cartes ont leur sous-dossier.
| Chemin | Contenu |
| --- | --- |
| racine : `CardsPage`, `cardsApi.js`, `cardCache.js`, `cardsReserve.js`, `useCardsConfig.js`, `CardsDashboard` | Page, appels au serveur, cache, configuration, cadre des tableaux de bord |
| racine : `cardsRoutes.js`, `useCardsHref.js` | Adresses des sections en version complète et en mode mobile, sections proposées sur téléphone (`MOBILE_SECTIONS`), règle de redirection ; liens internes des panneaux (`useCardsHref`) |
| racine : `CardsHomePanel`, `DailyTip`, `PackPanel`, `OpeningReserve`, `CollectionPanel`, `CardDetailModal`, `ShopPanel`, `TransfersPanel`, `TransferComposer`, `HistoryPanel`, `AccountPanel`, `PrivacyNotice` | Sections du joueur hors Guilde (`DailyTip` est l'« Astuce du jour » de l'accueil, pas la Carte du jour) |
| racine : `GuildPanel`, `guildQuests.js` | Hall de la Guilde et liste des quêtes |
| racine : `textFormat.js`, `stardustFormat.js`, `rarityWords.js`, `rewardText.js`, `collectionState.js`, `dropRates.js`, `Currency.jsx` | Règles d'affichage partagées. `textFormat.js` contient `fillTemplate` (remplissage des textes de `site.json`) et `formatCountdown` |
@ -37,6 +38,7 @@ quête de la Guilde et le rendu des cartes ont leur sous-dossier.
| `expeditions/` | Expéditions, amélioration des cartes (`CardPlan`, `AwakeningPicker`), `expeditionFormat.js` |
| `team/` | Équipe du jour et Course des courants (`Race*`, `raceRun.js`) |
| `mirror/` | Miroir brisé |
| `mobile/` | Mode mobile de dépannage : application sans le shell (`MobileCardsApp`), cadre avec barre d'onglets (`MobileCardsLayout`), reconnaissance d'un téléphone et choix « Version complète » (`mobileDevice.js`), carte révélée vue en grand (`OpeningCardZoom`) |
| `rendering/` | `NebulaCard`, dos des collections, particules holographiques (`holo*.js`, Canvas 2D), effets d'ouverture |
| `admin/` | Administration : `AdminPanel.jsx` (navigation), un fichier par section, `useAdminDashboard.js` (données) |
@ -62,6 +64,20 @@ règles pures du serveur (`services/cards/race-rules.js`) au lieu de les recopie
(`latest`), `MirrorPanel` avec un drapeau `active` remis à faux quand la
lecture est remplacée. Reprendre ce principe pour toute nouvelle page qui se
relit seule.
- **Mode mobile de dépannage** : `#/mobile/cards` réutilise ces panneaux sans
le shell du site, pour les sections de `MOBILE_SECTIONS` (`cardsRoutes.js`).
`main.jsx` y redirige un téléphone qui ouvre `#/cards/...`, sauf choix
« Version complète ». Ses adaptations restent sous `.nebula-mobile`
(`cards-mobile-route.scss`), et sous `body.nebula-mobile-body` pour les
fenêtres, rendues hors de la page. Quand une mise en page diffère vraiment
(lignes du choix d'un explorateur ou des communes, fiche du recrutement),
le composant la choisit avec `useCardsMobile()` ; principes dans
[DESIGN_SYSTEM.md](../../../../DESIGN_SYSTEM.md#mode-mobile-de-dépannage).
- **Liens entre sections** : un panneau du joueur passe par `useCardsHref()`,
jamais par `#/cards/...` écrit en dur, sinon un joueur sur téléphone repart
vers la version complète (`tests/nebula-cards-mobile.test.mjs` le vérifie).
Les liens à partager (invitation d'expédition, Carte du jour) gardent
l'adresse complète : la redirection s'occupe des téléphones.
- **Ajouter une quête** : voir la recette de [CONTRIBUTING.md](../../../../CONTRIBUTING.md#ajouter-une-quête-à-la-guilde).
## Vérifier
@ -69,4 +85,6 @@ règles pures du serveur (`services/cards/race-rules.js`) au lieu de les recopie
```bash
npm run check:cards
npx playwright test e2e/nebula-cards.spec.js --config playwright.cards.config.js
# mode mobile seul, sans repasser les parcours ordinateur
npx playwright test --config playwright.cards.config.js --project phone-cards --no-deps
```

View file

@ -0,0 +1,75 @@
/**
* @file Adresses des sections du joueur de Sokko TCG, en version complète (`#/cards/...`) et en mode mobile de
* dépannage (`#/mobile/cards/...`), et règle de redirection des téléphones vers ce mode.
*
* Utilisé par : useCardsHref.js (liens des panneaux), CardsPage.jsx, mobile/ (application, préférence, redirection),
* main.jsx (choix de l'application) et tests/nebula-cards-mobile.test.mjs.
* Attention :
* - Fichier sans React ni navigateur : les tests Node l'importent directement.
* - `MOBILE_SECTIONS` est la liste des sections proposées sur téléphone ; une section ajoutée ici doit passer le
* parcours e2e en émulation de téléphone (e2e/nebula-cards-mobile.spec.js).
* @see DESIGN_SYSTEM.md (section 24, « Mode mobile de dépannage »)
*/
/** Racine des routes du jeu en version complète. */
export const CARDS_BASE = "/cards";
/** Racine des routes du mode mobile de dépannage. */
export const MOBILE_CARDS_BASE = "/mobile/cards";
/**
* Sections du joueur proposées en mode mobile, quêtes de la Guilde comprises. Compte, Historique et Administration
* restent sur ordinateur.
*/
export const MOBILE_SECTIONS = new Set(["home", "guild", "daily", "team", "race", "mirror", "expeditions", "packs", "collection", "shop", "transfers"]);
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
const SECTION_ALIASES = { recycling: "collection" };
/** Section réelle d'une adresse : les anciennes adresses mènent à la section qui les a remplacées. */
export function resolveCardsSection(section) {
return SECTION_ALIASES[section] || section;
}
/**
* Route d'une section sous une racine (`/cards` ou `/mobile/cards`), sans le `#`. L'accueil est la racine elle-même.
* @param {string} base Racine, `CARDS_BASE` ou `MOBILE_CARDS_BASE`.
* @param {string} [section] Identifiant de section (`guild`, `packs`…) ; vide ou `home` pour l'accueil.
* @param {string} [subsection] Complément d'adresse, comme l'identifiant d'une expédition rejointe par lien.
* @returns {string}
*/
export function cardsRoute(base, section = "", subsection = "") {
if (!section || section === "home") return base;
return `${base}/${section}${subsection ? `/${subsection}` : ""}`;
}
/** Vrai pour une route du mode mobile (`/mobile/cards` et ses sections). */
export function isMobileCardsRoute(route) {
return route === MOBILE_CARDS_BASE || route.startsWith(`${MOBILE_CARDS_BASE}/`);
}
/**
* Découpe une route du mode mobile en section et complément.
* @param {string} route Route sans le `#`, comme `/mobile/cards/expeditions/<id>`.
* @returns {{ section: string, subsection: string }}
*/
export function parseMobileCardsRoute(route) {
const [section = "", subsection = ""] = route.slice(MOBILE_CARDS_BASE.length).split("/").filter(Boolean);
return { section, subsection };
}
/**
* Route mobile vers laquelle envoyer un téléphone qui ouvre une route du jeu, ou `""` pour rester.
* Seules les sections proposées en mobile sont redirigées : Compte, Historique, Administration, les toolboxes et
* les guides restent où ils sont. Le choix « Version complète » du joueur l'emporte.
* @param {string} route Route courante sans le `#`.
* @param {{ phone: boolean, fullVersion: boolean }} device `phone` : écran tactile de téléphone ;
* `fullVersion` : le joueur a choisi la version complète sur cet appareil.
* @returns {string}
*/
export function mobileRedirectTarget(route, { phone, fullVersion }) {
if (!phone || fullVersion) return "";
if (route !== CARDS_BASE && !route.startsWith(`${CARDS_BASE}/`)) return "";
const [section = "", subsection = ""] = route.slice(CARDS_BASE.length).split("/").filter(Boolean);
if (section && !MOBILE_SECTIONS.has(resolveCardsSection(section))) return "";
return cardsRoute(MOBILE_CARDS_BASE, section, subsection);
}

View file

@ -16,6 +16,7 @@ import { fillTemplate } from "../textFormat.js";
import { DailyTrack } from "./DailyTrack.jsx";
import { NebulaCard } from "../rendering/NebulaCard.jsx";
import { formatStardust } from "../stardustFormat.js";
import { useCardsHref } from "../useCardsHref.js";
const COUNTDOWN_TICK_MS = 30_000;
// Un mot répandu (« étoile ») désigne plus de cartes que les huit suggestions habituelles : la liste défile.
@ -30,6 +31,7 @@ function referenceEntry(catalog, cardId) {
}
export function DailyPanel({ catalog, state, runMutation, busy, content }) {
const cardsHref = useCardsHref();
const [daily, setDaily] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
@ -149,7 +151,7 @@ export function DailyPanel({ catalog, state, runMutation, busy, content }) {
<div><p className="eyebrow">{fillTemplate(content.number, { number: daily.number })}</p><h2 id="nebula-daily-title">{content.title}</h2></div>
<div className="nebula-daily-heading-actions">
<span className="nds-badge" data-variant="gold">{fillTemplate(content.reward, { reward: formatStardust(daily.reward) })}</span>
<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a>
<a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("guild")}>{content.back}</a>
</div>
</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={() => { setNow(Date.now()); setReloadKey((key) => key + 1); }}>{content.reload}</button></div>}

View file

@ -3,21 +3,57 @@
* carte, sa Puissance en haut à droite, ses stats en icônes (nom au survol) et ses étiquettes : celles
* utiles à la destination en pastilles (condition, dangers parés, Affinité), toutes au survol de
* l'icône d'étiquette.
*
* Attention : en mode mobile, la tuile devient une ligne entièrement touchable (`MobileCardRow`) : sans survol, le
* nom, la Puissance, les stats et les étiquettes y sont écrits en clair.
*/
import { useId } from "react";
import { Tooltip } from "../../../components/Tooltip.jsx";
import { fillTemplate } from "../textFormat.js";
import { useCardsMobile } from "../useCardsHref.js";
import { cardHelps, editionEntry, formatDecimal, STAT_BY_PLAN, STAT_IDS, tagLabel } from "./expeditionFormat.js";
import { MaskIcon } from "./ExpeditionLabels.jsx";
import { NebulaCard } from "../rendering/NebulaCard.jsx";
/**
* Ligne d'une carte jouable sur téléphone : un seul bouton (petite carte, nom, Puissance, stats, étiquettes), nommé
* « Choisir … » comme la tuile de l'ordinateur ; le détail est sa description accessible.
*/
function MobileCardRow({ catalog, entry, card, content, selected, sortKey, powerLabel, vocation, helps, tags, onSelect }) {
const detailsId = useId();
return <li className="nebula-expedition-card-row" data-busy={card.busy || undefined} data-selected={selected || undefined}>
<button type="button" className="nebula-expedition-card-pick" disabled={card.busy} aria-label={fillTemplate(content.chooseCard, { card: entry.card.name })} aria-describedby={detailsId} onClick={onSelect}>
<span className="nebula-expedition-card-frame" aria-hidden="true">
<NebulaCard catalog={catalog} entry={entry} size="sm" />
{card.busy && <span className="nebula-expedition-card-busy">{content.busy}</span>}
</span>
<span className="nebula-expedition-card-main" id={detailsId}>
<strong className="nebula-expedition-card-name">{entry.card.name}</strong>
<span className="nebula-expedition-card-power-line">{vocation && <MaskIcon name={vocation} />}{powerLabel}</span>
<span className="nebula-expedition-stats">{STAT_IDS.map((stat) => <span key={stat} className="nebula-expedition-stat" data-sorted={stat === sortKey || undefined}>
<MaskIcon name={stat} /><span className="sr-only">{content.stats[stat]} </span>{formatDecimal(card.stats[stat])}
</span>)}</span>
{(helps.condition || helps.dangers.length > 0 || helps.affinity) && <span className="nebula-expedition-card-tags">
{helps.condition && <span className="nds-badge" data-variant="success">{content.tagCondition}</span>}
{helps.dangers.map((danger) => <span key={danger.id} className="nds-badge" data-variant="success">{fillTemplate(content.tagParry, { label: danger.label })}</span>)}
{helps.affinity && <span className="nds-badge" data-variant="gold">{content.tagAffinity}</span>}
</span>}
<span className="nebula-expedition-card-taglist"><MaskIcon name="tag" />{tags.length ? tags.join(" · ") : content.tagsNone}</span>
</span>
</button>
</li>;
}
export function ExpeditionCardTile({ catalog, card, destination, content, selected, sortKey = null, onSelect }) {
const mobile = useCardsMobile();
const entry = editionEntry(catalog, card.editionId);
if (!entry) return null;
const vocation = STAT_BY_PLAN[card.plan];
const helps = cardHelps(card, destination);
const tags = (card.tags || []).map((tag) => tagLabel(catalog, tag));
const powerLabel = vocation ? fillTemplate(content.powerVocation, { power: card.power, stat: content.stats[vocation] }) : fillTemplate(content.power, { power: card.power });
if (mobile) return <MobileCardRow catalog={catalog} entry={entry} card={card} content={content} selected={selected} sortKey={sortKey} powerLabel={powerLabel} vocation={vocation} helps={helps} tags={tags} onSelect={onSelect} />;
return <li data-busy={card.busy || undefined} data-selected={selected || undefined}>
<div className="nebula-expedition-card-frame">
<NebulaCard catalog={catalog} entry={entry} size="sm" selected={selected} disabled={card.busy} onSelect={card.busy ? undefined : onSelect}

View file

@ -5,13 +5,17 @@
* pose ou retire une commune, celles déjà posées sur la carte sont en surbrillance.
*
* L'équipement reste sur la carte d'une expédition à l'autre.
* Attention : en mode mobile, une commune posée s'affiche en petit format avec son nom en dessous, et la fenêtre de
* choix liste les communes en lignes entièrement touchables (carte, nom, effet, synergie), qui posent ou
* retirent la commune : sans survol, le nom n'y serait lisible qu'en infobulle.
*/
import { useState } from "react";
import { useId, useState } from "react";
import { Modal } from "../../../components/Modal.jsx";
import { Tooltip } from "../../../components/Tooltip.jsx";
import { equipCard } from "../cardsApi.js";
import { fillTemplate } from "../textFormat.js";
import { useCardsMobile } from "../useCardsHref.js";
import { editionEntry, STAT_IDS, tagColor, tagLabel } from "./expeditionFormat.js";
import { MaskIcon, StatValue } from "./ExpeditionLabels.jsx";
import { PowerEffects, PowerName } from "./ExpeditionOutcome.jsx";
@ -58,6 +62,7 @@ export function EquipmentStats({ item, content, color, powerValues }) {
* gravure sur elle et sur la carte.
*/
export function EquipmentSlots({ catalog, progress, content, busy, runMutation, onOpen, powerValues, onEngrave = null }) {
const mobile = useCardsMobile();
const remove = (slot) => runMutation(() => equipCard(progress.editionId, slot, null));
if (!progress) return <ul className="nebula-equipment-slots" aria-label={content.equipmentTitle}>{PLACEHOLDER_SLOTS.map((slot) => <li key={slot}>
<span className="nebula-equipment-slot" data-locked><span aria-hidden="true">+</span></span>
@ -71,11 +76,12 @@ export function EquipmentSlots({ catalog, progress, content, busy, runMutation,
</li>;
return <li key={slot}>
<span className="nebula-equipment-card">
<NebulaCard catalog={catalog} entry={entry} size="md" onSelect={() => onOpen(slot)} selectLabel={fillTemplate(content.equipmentReplace, { card: entry.card.name })} />
<NebulaCard catalog={catalog} entry={entry} size={mobile ? "sm" : "md"} onSelect={() => onOpen(slot)} selectLabel={fillTemplate(content.equipmentReplace, { card: entry.card.name })} />
<button className="nds-icon-button nebula-equipment-remove" type="button" disabled={busy} aria-label={fillTemplate(content.equipmentRemove, { card: entry.card.name })} title={fillTemplate(content.equipmentRemove, { card: entry.card.name })} onClick={() => remove(slot)}>
<MaskIcon name="trash" />
</button>
</span>
{mobile && <strong className="nebula-equipment-name" aria-hidden="true">{entry.card.name}</strong>}
<EquipmentStats item={item} content={content} powerValues={powerValues} color={tagColor(progress.tags, item.synergyTag)} />
{item.synergyTag && <SynergyBadge catalog={catalog} tag={item.synergyTag} tags={progress.tags} content={content} />}
{onEngrave && !item.synergyTag && !item.engraved && <button className="nds-button nebula-equipment-engrave" data-size="sm" data-variant="secondary" type="button" disabled={busy}
@ -86,6 +92,26 @@ export function EquipmentSlots({ catalog, progress, content, busy, runMutation,
})}</ul>;
}
/**
* Ligne d'une commune dans la fenêtre de choix, sur téléphone : un seul bouton, comme la ligne d'un explorateur (petite carte,
* nom, effet, synergie, où elle est posée) ; il pose la commune ou la retire, et dit par `aria-pressed` si elle est posée.
*/
function MobileEquipmentRow({ catalog, entry, item, content, progress, tag, here, elsewhereName, label, busy, powerValues, onToggle }) {
const detailsId = useId();
return <li className="nebula-equipment-row" data-equipped={here || undefined}>
<button type="button" className="nebula-equipment-row-pick" disabled={busy} aria-pressed={here} aria-label={label} aria-describedby={detailsId} onClick={onToggle}>
<span className="nebula-equipment-row-card" aria-hidden="true"><NebulaCard catalog={catalog} entry={entry} size="sm" /></span>
<span className="nebula-equipment-row-main" id={detailsId}>
<strong>{entry.card.name}</strong>
<EquipmentStats item={item} content={content} powerValues={powerValues} color={tagColor(progress.tags, tag)} />
{tag && <SynergyBadge catalog={catalog} tag={tag} tags={progress.tags} content={content} />}
{here && <small className="nebula-equipment-here">{content.equipmentHere}</small>}
{elsewhereName && <small className="nebula-form-help">{fillTemplate(content.equipmentElsewhere, { card: elsewhereName })}</small>}
</span>
</button>
</li>;
}
/**
* Fenêtre de choix des communes, ouverte depuis l'emplacement `slot`. Un clic sur une commune déjà posée sur la carte la retire ; sur
* une autre, il la pose sur l'emplacement ouvert s'il est libre, sinon sur le premier emplacement libre, sinon à la place de
@ -93,6 +119,7 @@ export function EquipmentSlots({ catalog, progress, content, busy, runMutation,
* dit. Un refus du serveur s'affiche aussi dans la fenêtre (le message de la page serait caché derrière).
*/
export function EquipmentPicker({ catalog, state, progress, cardName, slot, content, busy, runMutation, onClose, powerValues }) {
const mobile = useCardsMobile();
const [sort, setSort] = useState("synergy");
const [error, setError] = useState("");
const nameOf = (cardId) => catalog.cards.find((card) => card.id === cardId)?.name || cardId;
@ -144,15 +171,19 @@ export function EquipmentPicker({ catalog, state, progress, cardName, slot, cont
const tag = sharedTag(item);
const here = placed.has(item.editionId);
const elsewhere = item.equippedOn && item.equippedOn !== progress.editionId;
const toggleLabel = fillTemplate(here ? content.equipmentRemove : content.equipmentPut, { card: choice.card.name });
const elsewhereName = elsewhere && nameOf(catalog.editions.find((edition) => edition.id === item.equippedOn)?.cardId);
if (mobile) return <MobileEquipmentRow key={item.editionId} catalog={catalog} entry={choice} item={item} content={content} progress={progress} tag={tag} here={here}
elsewhereName={elsewhereName} label={toggleLabel} busy={busy} powerValues={powerValues} onToggle={() => toggle(item)} />;
return <li key={item.editionId} data-equipped={here || undefined}>
<Tooltip className="nebula-equipment-choice" content={choice.card.name} tabIndex={-1}>
<NebulaCard catalog={catalog} entry={choice} size="sm" selected={here} onSelect={busy ? undefined : () => toggle(item)}
selectLabel={fillTemplate(here ? content.equipmentRemove : content.equipmentPut, { card: choice.card.name })} />
selectLabel={toggleLabel} />
</Tooltip>
<EquipmentStats item={item} content={content} powerValues={powerValues} color={tagColor(progress.tags, tag)} />
{tag && <SynergyBadge catalog={catalog} tag={tag} tags={progress.tags} content={content} />}
{here && <small className="nebula-equipment-here">{content.equipmentHere}</small>}
{elsewhere && <small className="nebula-form-help">{fillTemplate(content.equipmentElsewhere, { card: nameOf(catalog.editions.find((edition) => edition.id === item.equippedOn)?.cardId) })}</small>}
{elsewhere && <small className="nebula-form-help">{fillTemplate(content.equipmentElsewhere, { card: elsewhereName })}</small>}
</li>;
})}</ul> : <p className="nebula-form-help">{content.equipmentNone}</p>}
<div className="nds-toolbar nebula-expedition-picker-actions">

View file

@ -206,7 +206,7 @@ export function ExpeditionGroupCard({ catalog, state, view, group, content, now,
{Array.from({ length: group.freeSlots }, (_, index) => <li key={`free-${index}`}><span className="nebula-expedition-group-free">{content.groupFreeRole}</span></li>)}
</ul>
{group.isCreator && group.members.length > 1 && <p className="nebula-form-help">{fillTemplate(content.readyCount, { ready: group.members.filter((member) => member.ready).length, count: group.members.length })}</p>}
{group.freeSlots > 0 && <p className="nebula-form-help">{content.groupScaling}</p>}
{group.freeSlots > 0 && <p className="nebula-form-help nebula-group-scaling">{content.groupScaling}</p>}
</section>
<div className="nds-toolbar nebula-expedition-group-actions">
{group.canJoin && !joining && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy || limitReached} onClick={() => setJoining(true)}>{content.join}</button>}

View file

@ -11,6 +11,7 @@ import { useMemo, useState } from "react";
import { Modal } from "../../../components/Modal.jsx";
import { Tooltip } from "../../../components/Tooltip.jsx";
import { fillTemplate } from "../textFormat.js";
import { useCardsMobile } from "../useCardsHref.js";
import { ExpeditionCardTile } from "./ExpeditionCardTile.jsx";
import { EquipmentPicker, EquipmentSlots } from "./ExpeditionEquipmentSlots.jsx";
import { CardSheet, EngraveModal } from "./ExpeditionImprove.jsx";
@ -96,13 +97,16 @@ function CardPicker({ catalog, view, destination, selectedId, needs, content, on
export function ExpeditionLoadout({ catalog, state, view, destination, card, onChooseCard, content, busy, runMutation, needs = null, pickerNeeds = null, actions = null }) {
// Fenêtre ouverte : « card » (choix de la carte) ou le numéro de l'emplacement d'équipement.
const [picker, setPicker] = useState(null);
// Sur téléphone, la carte choisie est en petit format (illustration seule) : son nom est juste dessous, et les textes
// d'une grande carte réduite à cette largeur seraient illisibles.
const mobile = useCardsMobile();
// Exigences de la destination choisie pour une carte seule : elles ne donnent que la couleur des totaux.
const requirements = destination?.requirements || [];
const entry = card && editionEntry(catalog, card.editionId);
const progress = card && state.cardProgress?.find((item) => item.editionId === card.editionId);
return <div className="nebula-expedition-loadout">
<div className="nebula-loadout-card">
{entry ? <NebulaCard catalog={catalog} entry={entry} size="lg" onSelect={() => setPicker("card")} selectLabel={fillTemplate(content.changeCard, { card: entry.card.name })} />
{entry ? <NebulaCard catalog={catalog} entry={entry} size={mobile ? "sm" : "lg"} onSelect={() => setPicker("card")} selectLabel={fillTemplate(content.changeCard, { card: entry.card.name })} />
: <button className="nebula-loadout-empty" type="button" onClick={() => setPicker("card")}><span aria-hidden="true">+</span><strong>{content.chooseCardSlot}</strong></button>}
{card?.tags?.length > 0 && <ul className="nebula-loadout-tags" aria-label={content.tagsTitle}>{card.tags.map((tag) => <li key={tag} className="nebula-tag-chip" data-tag-color={tagColor(card.tags, tag)}>{tagLabel(catalog, tag)}</li>)}</ul>}
{/* La fiche de la carte, sans quitter les Expéditions : niveau, plan de progression, équipement et gravure. */}

View file

@ -13,6 +13,7 @@ import { useEffect, useMemo, useState } from "react";
import { Tooltip } from "../../../components/Tooltip.jsx";
import { previewExpedition } from "../cardsApi.js";
import { fillTemplate } from "../textFormat.js";
import { useCardsMobile } from "../useCardsHref.js";
import { conditionText, coverEntry, dangerText, editionEntry, formatDecimal, formatEclats, ITEM_ART, powerNote, synergyBadges, tagLabel } from "./expeditionFormat.js";
import { MainStatMark, MaskIcon } from "./ExpeditionLabels.jsx";
import { ExpeditionLoadout } from "./ExpeditionLoadout.jsx";
@ -233,6 +234,9 @@ function DestinationOption({ catalog, item, selected, card, view, content, onSel
export function ExpeditionPlanner({ catalog, state, view, content, busy, onStart, onReroll, onBonus, runMutation }) {
// Destinations de la plus facile à la plus difficile.
const destinations = useMemo(() => [...view.destinations].sort((a, b) => (a.level ?? 0) - (b.level ?? 0)), [view.destinations]);
// Sur téléphone, la Rose des vents prend un libellé court et son nombre en pastille, pour tenir sur une ligne ; le
// libellé complet reste son nom accessible.
const mobile = useCardsMobile();
const [destinationId, setDestinationId] = useState(destinations[0]?.id || "");
const [hours, setHours] = useState(view.durations[0]);
const [editionId, setEditionId] = useState(null);
@ -269,8 +273,10 @@ export function ExpeditionPlanner({ catalog, state, view, content, busy, onStart
{/* La Rose des vents se joue ici, à côté des destinations qu'elle remplace, tant que le joueur en a. */}
<div className="nebula-expedition-step-heading">
<h3 id="nebula-expedition-destinations-title">{content.destinationsTitle}</h3>
{view.enabled && view.items?.windRose > 0 && <button className="nds-button nebula-wind-rose-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={onReroll}>
<img src={ITEM_ART.windRose} alt="" />{fillTemplate(content.useWindRose, { count: view.items.windRose })}
{view.enabled && view.items?.windRose > 0 && <button className="nds-button nebula-wind-rose-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} aria-label={mobile ? fillTemplate(content.useWindRose, { count: view.items.windRose }) : undefined} onClick={onReroll}>
<img src={ITEM_ART.windRose} alt="" />{mobile
? <>{content.useWindRoseShort}<span className="nebula-item-count-pill" aria-hidden="true">×{view.items.windRose}</span></>
: fillTemplate(content.useWindRose, { count: view.items.windRose })}
</button>}
</div>
{view.unlocked && view.unlocked.count < view.unlocked.total && <p className="nebula-form-help">{fillTemplate(content.unlockedDestinations, { ...view.unlocked, s: view.unlocked.count > 1 ? "s" : "" })}</p>}

View file

@ -32,6 +32,7 @@ import { ExpeditionReport } from "./ExpeditionReport.jsx";
import { ExpeditionReturn } from "./ExpeditionReturn.jsx";
import { ExpeditionStarter } from "./ExpeditionStarter.jsx";
import { formatEclats, ITEM_ART } from "./expeditionFormat.js";
import { useCardsHref, useCardsMobile } from "../useCardsHref.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,
@ -64,11 +65,13 @@ function ItemArt({ id, count }) {
// Sac replié ou déplié : une préférence de ce navigateur seulement, gardée d'une visite à l'autre.
const BAG_OPEN_KEY = "sokko-tcg-bag-open";
const readBagOpen = () => {
// Sans choix enregistré, le Sac est ouvert en version complète et replié en mode mobile, où la page est déjà longue.
const readBagOpen = (fallback) => {
try {
return globalThis.localStorage?.getItem(BAG_OPEN_KEY) !== "false";
const stored = globalThis.localStorage?.getItem(BAG_OPEN_KEY);
return stored == null ? fallback : stored !== "false";
} catch {
return true;
return fallback;
}
};
@ -77,7 +80,8 @@ function ItemBag({ catalog, state, view, content, busy, onCraft, onAtelierClosed
// Burin : l'atelier de gravure, ouvert depuis le Sac.
const [engraving, setEngraving] = useState(false);
// Replié, le Sac n'est qu'une rangée d'objets et leur quantité : la préparation de l'expédition remonte.
const [open, setOpen] = useState(readBagOpen);
const mobile = useCardsMobile();
const [open, setOpen] = useState(() => readBagOpen(!mobile));
const toggle = () => {
setOpen(!open);
try {
@ -124,6 +128,7 @@ function ItemBag({ catalog, state, view, content, busy, onCraft, onAtelierClosed
/** `joinId` : expédition ouverte par un lien d'invitation (#/cards/expeditions/<id>). */
export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, joinId = "" }) {
const cardsHref = useCardsHref();
const [view, setView] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
@ -305,7 +310,7 @@ export function ExpeditionsPanel({ catalog, state, runMutation, busy, content, j
<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>
<a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("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} />

View file

@ -20,6 +20,7 @@ import { MirrorBoard } from "./MirrorBoard.jsx";
import { mirrorShareText } from "./mirrorFormat.js";
import { formatStardustFull } from "../stardustFormat.js";
import { MaskIcon } from "../expeditions/ExpeditionLabels.jsx";
import { useCardsHref } from "../useCardsHref.js";
// Les trois miroirs du jour, dans l'ordre : chacun s'ouvre une fois le précédent terminé.
const MODES = ["easy", "normal", "hard"];
@ -68,7 +69,8 @@ function MirrorReminders({ content }) {
* veut ; deux par partie, chez les compagnons de son choix. Une double spécialité a deux boutons, au choix.
*/
function MirrorHelpers({ catalog, mirror, game, content, teamContent, busy, aiming, onHelp }) {
if (!mirror.team.length) return <section className="nds-panel nebula-mirror-helpers"><h3>{content.helpersTitle}</h3><p className="nebula-mirror-note">{content.helpersNone}</p><a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/team">{content.toTeam}</a></section>;
const cardsHref = useCardsHref();
if (!mirror.team.length) return <section className="nds-panel nebula-mirror-helpers"><h3>{content.helpersTitle}</h3><p className="nebula-mirror-note">{content.helpersNone}</p><a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("team")}>{content.toTeam}</a></section>;
const playing = game.status === "playing";
const left = game.helpsLeft;
return <section className="nds-panel nebula-mirror-helpers" aria-labelledby="nebula-mirror-helpers-title">
@ -122,6 +124,7 @@ function MirrorResult({ catalog, mirror, game, content, nextAt }) {
}
export function MirrorPanel({ catalog, runMutation, busy, content, teamContent }) {
const cardsHref = useCardsHref();
const [mirror, setMirror] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
@ -279,7 +282,7 @@ export function MirrorPanel({ catalog, runMutation, busy, content, teamContent }
<div className="nebula-team-heading-actions">
{game && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => { setMode(null); setPeeking(false); setAiming(null); setSelected(null); }}>{content.chooseOther}</button>}
{mirror.devReset && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={async () => { commitBoards({}); setMode(null); await act(() => resetMirror()); }}>{content.devReset}</button>}
<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a>
<a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("guild")}>{content.back}</a>
</div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}

View file

@ -0,0 +1,54 @@
/**
* @file Application du mode mobile de Sokko TCG (`#/mobile/cards/...`) : charge les textes du site et la
* configuration du jeu, puis affiche CardsPage en mode mobile, sans le shell du site.
*
* Utilisé par : main.jsx, chargé à la demande quand la route commence par `/mobile/cards`.
* Attention :
* - Pas de shell : ni barre latérale, ni toolboxes, ni tiroir, ni sauvegarde. Ce mode ne sert qu'à jouer depuis
* un téléphone ; une page qui aurait besoin du reste du site n'y a pas sa place.
* - Les fenêtres (Modal) sont rendues dans `body`, hors de `.nebula-mobile` : tant que ce mode est affiché, `body`
* porte la classe `nebula-mobile-body`, qui leur donne leurs styles de téléphone.
* - Importe CardsPage avant sa feuille de style : cards-mobile-route.scss passe après celle du jeu et l'emporte à
* spécificité égale.
* @see DESIGN_SYSTEM.md (section 24, « Mode mobile de dépannage »)
*/
import { useEffect } from "react";
import { CardsPage } from "../CardsPage.jsx";
import "../../../styles/cards-mobile-route.scss";
import { AppErrorBoundary } from "../../../components/AppErrorBoundary.jsx";
import { Icon } from "../../../components/Icon.jsx";
import { useAppData } from "../../../hooks/useAppData.js";
import { parseMobileCardsRoute } from "../cardsRoutes.js";
import { useCardsConfig } from "../useCardsConfig.js";
/** Page complète du mode mobile pour `route` (`/mobile/cards/<section>/<complément>`). */
export function MobileCardsApp({ route }) {
const cardsConfig = useCardsConfig();
const { siteContent, siteContentError, siteContentLoading, retrySiteContent } = useAppData(route);
const { section, subsection } = parseMobileCardsRoute(route);
useEffect(() => {
document.body.classList.add("nebula-mobile-body");
return () => document.body.classList.remove("nebula-mobile-body");
}, []);
if (!siteContent) {
return <main className="startup-error">
<section className="empty nds-empty-state" aria-busy={siteContentLoading}>
<h1>Contenu indisponible</h1>
<p>{siteContentError || "Chargement du contenu..."}</p>
{siteContentError && <button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={retrySiteContent}>
<Icon name="refresh" />Réessayer
</button>}
</section>
</main>;
}
return <div className="nebula-mobile">
<main>
<AppErrorBoundary route={route}>
<CardsPage siteContent={siteContent} cardsConfig={cardsConfig} playerSection={section} playerSubsection={subsection} mobile />
</AppErrorBoundary>
</main>
</div>;
}

View file

@ -0,0 +1,68 @@
/**
* @file Cadre du mode mobile de Sokko TCG : titre, section affichée, pied de page (compte, lien discret vers la
* version complète), barre d'onglets en bas d'écran.
*
* Utilisé par : CardsPage.jsx quand la page est ouverte en mode mobile (`#/mobile/cards/...`).
* Attention : les onglets ne listent que les sections principales ; les quêtes de la Guilde s'ouvrent depuis la
* Guilde et allument son onglet. « Version complète » retient le choix pour que la redirection des téléphones ne
* ramène pas aussitôt le joueur ici.
* @see DESIGN_SYSTEM.md (section 24, « Mode mobile de dépannage »)
*/
import { CardsAccount, CardsStackedSection } from "../CardsDashboard.jsx";
import { useCardsHref } from "../useCardsHref.js";
import { rememberFullVersion } from "./mobileDevice.js";
// Ordre des onglets : le jeu, puis l'économie et les échanges, comme les groupes du menu complet.
const MOBILE_TABS = ["home", "guild", "packs", "collection", "shop", "transfers"];
/**
* @param {object} props
* @param {object} props.content Textes `cards` de site.json (titre, `mobile`).
* @param {object} props.player Joueur connecté (nom, avatar).
* @param {Record<string, number>} props.counts Pastilles des onglets (quêtes en attente, ouvertures, propositions reçues).
* @param {string} props.active Onglet à allumer : la section, ou la Guilde pour une de ses quêtes.
* @param {string} props.fullVersionHref Lien de la même section en version complète.
* @param {Function|null} props.onLogout Déconnexion, absente hors connexion.
*/
export function MobileCardsLayout({ content, player, counts, active, busy, onLogout, fullVersionHref, notices, children }) {
const cardsHref = useCardsHref();
const text = content.mobile;
return <div className="nebula-dashboard nebula-mobile-dashboard">
<header className="nebula-mobile-header">
<a className="nebula-mobile-title" href={cardsHref()}><span className="eyebrow">{content.eyebrow}</span><strong>{content.title}</strong></a>
</header>
{notices}
<CardsStackedSection active={active} busy={busy}>{children}</CardsStackedSection>
<footer className="nebula-mobile-footer">
<CardsAccount player={player} onLogout={onLogout} />
<p>{text.note}</p>
{/* Seule sortie de la redirection des téléphones : discrète, mais toujours là en fin de page. */}
<a className="nebula-mobile-full" href={fullVersionHref} onClick={() => rememberFullVersion(true)}>{text.fullVersion}</a>
</footer>
<nav className="nebula-mobile-tabs" aria-label={`Sections de ${content.title}`}>
{MOBILE_TABS.map((id) => <a key={id} className="nebula-mobile-tab" href={cardsHref(id)} aria-current={active === id ? "page" : undefined}>
<span>{text.tabs[id]}</span>
{counts[id] > 0 && <span className="nds-badge" data-variant="gold">{counts[id]}</span>}
</a>)}
</nav>
</div>;
}
/**
* Section que le mode mobile ne propose pas (Compte, Historique, Administration) : renvoie vers la version complète.
* Ces sections ne sont jamais redirigées vers le mode mobile : le lien n'a pas besoin de retenir un choix, et ne
* doit pas le faire (le joueur garderait la version complète pour tout le reste).
*/
export function MobileUnavailable({ content, fullVersionHref }) {
const cardsHref = useCardsHref();
const text = content.mobile;
return <section className="nds-empty-state nebula-mobile-unavailable">
<h2>{text.unavailableTitle}</h2>
<p>{text.unavailableText}</p>
<div className="nebula-mobile-unavailable-actions">
<a className="nds-button" data-variant="primary" href={fullVersionHref}>{text.unavailableAction}</a>
<a className="nds-button" data-variant="secondary" href={cardsHref()}>{text.backHome}</a>
</div>
</section>;
}

View file

@ -0,0 +1,27 @@
/**
* @file Affiche en grand, par-dessus l'ouverture d'un paquet, une carte révélée touchée sur téléphone : format `lg`
* (nom, description, effets holographiques), fermée par le fond ou par « Fermer ».
*
* Utilisé par : PackPanel.jsx (`OpeningStage`) en mode mobile, où les cartes de l'ouverture sont en petit format.
* Attention : la fenêtre est rendue dans `body`, hors de `.nebula-mobile` ; ses styles portent la classe propre
* `nebula-card-zoom` (cards-mobile-route.scss), qui n'existe qu'en mode mobile. Elle ne lit pas la collection du
* joueur, qui n'est à jour qu'après l'enregistrement de l'ouverture : c'est un coup d'œil, pas la fiche de carte.
* @see DESIGN_SYSTEM.md (section 24, « Mode mobile de dépannage »)
*/
import { Modal } from "../../../components/Modal.jsx";
import { NebulaCard } from "../rendering/NebulaCard.jsx";
/**
* @param {object} props
* @param {object} props.catalog Catalogue des cartes.
* @param {object} props.entry Carte révélée (`{ card, edition }`).
* @param {string} props.closeLabel Libellé du bouton de fermeture.
* @param {Function} props.onClose Ferme la fenêtre ; le focus revient sur la carte touchée.
*/
export function OpeningCardZoom({ catalog, entry, closeLabel, onClose }) {
return <Modal rootClassName="confirm-modal-root nebula-card-zoom-root" dialogClassName="nebula-card-zoom" ariaLabel={entry.card.name} onRequestClose={onClose}>
<NebulaCard catalog={catalog} entry={entry} size="lg" />
<button className="nds-button" data-variant="secondary" type="button" data-modal-initial-focus onClick={onClose}>{closeLabel}</button>
</Modal>;
}

View file

@ -0,0 +1,51 @@
/**
* @file Reconnaît un téléphone et retient, pour ce navigateur, le choix entre le mode mobile de Sokko TCG et la
* version complète.
*
* Utilisé par : main.jsx (redirection avant le premier affichage), mobile/MobileCardsLayout.jsx (« Version
* complète ») et CardsPage.jsx (« Version mobile »).
* Attention :
* - Un téléphone, c'est un pointeur tactile ET un petit écran : on mesure le petit côté de l'écran, pas la
* fenêtre, pour qu'un téléphone en paysage reste un téléphone et qu'une fenêtre d'ordinateur étroite, avec sa
* souris, garde la version complète. Une tablette garde aussi la version complète.
* - Le choix est gardé dans localStorage ; un stockage refusé (navigation privée stricte) revient au comportement
* par défaut, sans erreur.
* @see DESIGN_SYSTEM.md (section 24, « Mode mobile de dépannage »)
*/
import { mobileRedirectTarget } from "../cardsRoutes.js";
const FULL_VERSION_STORAGE_KEY = "sokkog:cards-full-version";
// Petit côté de l'écran, en pixels CSS, sous lequel un appareil tactile est traité comme un téléphone (les tablettes
// commencent vers 744 px).
const PHONE_MAX_SHORT_SIDE = 600;
/** Vrai sur un écran tactile de téléphone, en portrait comme en paysage. */
export function isPhoneScreen() {
if (typeof window === "undefined" || !window.matchMedia) return false;
return window.matchMedia("(pointer: coarse)").matches && Math.min(window.screen.width, window.screen.height) < PHONE_MAX_SHORT_SIDE;
}
/** Vrai si le joueur a choisi la version complète sur ce navigateur. */
export function prefersFullVersion() {
try {
return window.localStorage.getItem(FULL_VERSION_STORAGE_KEY) === "1";
} catch {
return false;
}
}
/** Retient le choix du joueur : `true` pour la version complète, `false` pour revenir au mode mobile. */
export function rememberFullVersion(full) {
try {
if (full) window.localStorage.setItem(FULL_VERSION_STORAGE_KEY, "1");
else window.localStorage.removeItem(FULL_VERSION_STORAGE_KEY);
} catch {
// Sans stockage, le choix vaut seulement pour ce lien.
}
}
/** Route mobile vers laquelle rediriger cet appareil depuis `route`, ou `""` pour rester. */
export function mobileRedirectForDevice(route) {
return mobileRedirectTarget(route, { phone: isPhoneScreen(), fullVersion: prefersFullVersion() });
}

View file

@ -362,7 +362,21 @@ function CardFace({ entry, quantity, visual, size, flare = null }) {
</div>;
}
export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp = true, onReveal, onRevealComplete, onConceal, onSelect, selectLabel, selected, revealed = false, replayable = false, revealLabel = "la carte", disabled = false, concealed = false, backCollection = null, newBadge = null }) {
/**
* Carte collectionnable : face visible (`article`, ou bouton avec `onSelect`), face cachée à révéler (`faceUp` faux)
* ou dos seul (`concealed`).
* @param {object} props
* @param {object} props.catalog Catalogue (finitions, effets d'ouverture, palettes).
* @param {object} props.entry Carte et édition (`{ card, edition }`).
* @param {"sm"|"md"|"lg"} [props.size] Format : `sm` sans nom, `md` avec le nom, `lg` avec la description.
* @param {boolean} [props.faceUp] Faux pour une carte à révéler : `revealed`, `onReveal` et `onRevealComplete` la pilotent.
* @param {Function} [props.onRevealComplete] Appelé quand la révélation est terminée, effets compris.
* @param {Function} [props.onOpen] Rend une carte révélée touchable (sauf si `replayable`) : l'ouvre en grand.
* @param {string} [props.openLabel] Nom accessible de la carte révélée quand `onOpen` est donné.
* @param {boolean} [props.quietReveal] Révélation sobre : retournement et lueur seulement, sans halo, couronne ni
* particules ; la révélation se termine avec le retournement au lieu d'attendre la fin des particules.
*/
export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp = true, onReveal, onRevealComplete, onConceal, onSelect, selectLabel, selected, revealed = false, replayable = false, revealLabel = "la carte", disabled = false, concealed = false, backCollection = null, newBadge = null, quietReveal = false, onOpen = null, openLabel = "" }) {
const cardSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
const rarity = entry.edition?.rarity || "common";
const finish = entry.edition?.finishIds?.join(" ") || "standard";
@ -442,7 +456,8 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
}
const auraDuration = openingVisual.auraDurationMs;
const revealDuration = Math.max(600, openingVisual.particleDurationMs);
// 600 ms : la durée du retournement (`.nebula-card-inner`). Sans particules, rien ne reste à attendre après lui.
const revealDuration = quietReveal ? 600 : Math.max(600, openingVisual.particleDurationMs);
queueMicrotask(() => setRevealPhase(auraDuration ? "aura" : "revealing"));
if (auraDuration) timers.push(window.setTimeout(() => setRevealPhase("revealing"), auraDuration));
timers.push(window.setTimeout(() => {
@ -450,7 +465,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
onRevealCompleteRef.current?.();
}, auraDuration + revealDuration));
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [revealed, openingVisual.auraDurationMs, openingVisual.particleDurationMs]);
}, [revealed, quietReveal, openingVisual.auraDurationMs, openingVisual.particleDurationMs]);
if (concealed) {
return <article ref={cardRef} className="nebula-card nebula-card-concealed" data-card-size={cardSize} aria-label={`Carte inconnue — ${backCollection?.name || "collection inconnue"}`}>
@ -459,11 +474,13 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
}
if (!faceUp) {
const hasAuraPalette = openingVisual.auraColors.length > 1;
const outerAura = hasAuraPalette && !quietReveal;
const locked = ["aura", "revealing", "concealing"].includes(revealPhase);
const faceVisible = ["revealing", "revealed"].includes(revealPhase);
const particlesVisible = faceVisible && rarity !== "common" && openingVisual.particlePreset;
const particlesVisible = faceVisible && !quietReveal && rarity !== "common" && openingVisual.particlePreset;
const openable = revealPhase === "revealed" && !replayable && Boolean(onOpen);
const ariaLabel = revealPhase === "revealed"
? (replayable ? `Remettre ${revealLabel} face cachée` : `${entry.card.name} révélée${newBadge ? ", nouvelle carte" : ""}`)
? (replayable ? `Remettre ${revealLabel} face cachée` : openable ? openLabel : `${entry.card.name} révélée${newBadge ? ", nouvelle carte" : ""}`)
: `Révéler ${revealLabel}`;
return <button
ref={cardRef}
@ -476,13 +493,13 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
data-aura-palette={hasAuraPalette || undefined}
{...visualAttributes}
type="button"
disabled={disabled || (revealPhase === "revealed" && !replayable)}
aria-disabled={disabled || locked || (revealPhase === "revealed" && !replayable) || undefined}
disabled={disabled || (revealPhase === "revealed" && !replayable && !openable)}
aria-disabled={disabled || locked || (revealPhase === "revealed" && !replayable && !openable) || undefined}
data-reveal-locked={locked || undefined}
aria-label={ariaLabel}
onClick={() => {
if (locked || disabled) return;
if (revealPhase === "revealed") onConceal?.();
if (revealPhase === "revealed") (openable ? onOpen : onConceal)?.();
else onReveal?.();
}}
>
@ -498,7 +515,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
</span>
{newBadge && revealPhase === "revealed" && <span className="nds-badge nebula-card-new-badge" aria-hidden="true">{newBadge}</span>}
</span>
{hasAuraPalette && <><span className="nebula-card-opening-aura-palette" aria-hidden="true" /><span className="nebula-card-opening-crown-palette" aria-hidden="true" /><span className="nebula-card-opening-glow-palette" aria-hidden="true"><span /></span></>}
{outerAura && <><span className="nebula-card-opening-aura-palette" aria-hidden="true" /><span className="nebula-card-opening-crown-palette" aria-hidden="true" /><span className="nebula-card-opening-glow-palette" aria-hidden="true"><span /></span></>}
{particlesVisible && <span className="nebula-card-particles" aria-hidden="true">{rarity === "mythic" && <><span className="nebula-card-particle-ring-glow" data-glow="outer"><span><span /></span></span><span className="nebula-card-particle-ring-glow" data-glow="inner"><span><span /></span></span></>}{Array.from({ length: openingVisual.particlePreset.count }, (_, index) => <i key={index} style={particlePosition(index, openingVisual.particlePreset.count, rarity === "legendary" || rarity === "mythic", openingVisual.particlePalette?.colors[index % openingVisual.particlePalette.colors.length])} />)}</span>}
</button>;
}

View file

@ -8,8 +8,10 @@ import { RaceLive } from "./RaceLive.jsx";
import { RaceResult } from "./RaceResult.jsx";
import { RaceCircuit } from "./RaceTrack.jsx";
import { TeamCompanion } from "./TeamCompanion.jsx";
import { useCardsHref } from "../useCardsHref.js";
export function RacePanel({ catalog, runMutation, busy, content, teamContent, statLabels }) {
const cardsHref = useCardsHref();
const [team, setTeam] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
@ -97,14 +99,14 @@ export function RacePanel({ catalog, runMutation, busy, content, teamContent, st
return <section className="nebula-race" aria-labelledby="nebula-race-title">
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-race-title">{content.title}</h2></div>
<div className="nebula-team-heading-actions">{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={rerun}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a></div>
<div className="nebula-team-heading-actions">{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={rerun}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("guild")}>{content.back}</a></div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
{live && <RaceLive key={live.day} catalog={catalog} race={live} companions={team.companions} content={content} teamContent={teamContent} statLabels={statLabels}
onBoost={(boosts) => { recordRaceBoosts(boosts).catch(() => {}); }} onFinish={finish} onOver={over} />}
{interrupted && <div className="nds-panel nebula-race-interrupted"><h3>{content.interruptedTitle}</h3><p>{content.interruptedText}</p><button className="nds-button" data-variant="primary" type="button" disabled={busy} onClick={finishInterrupted}>{content.interruptedAction}</button></div>}
{showResult && <RaceResult catalog={catalog} race={race} nextAt={team.nextAt} content={content} teamContent={teamContent} statLabels={statLabels} titleRef={titleRef} />}
{!live && !race && !choosing && <div className="nds-empty-state"><p>{!team.enabled ? teamContent.closed : !team.raceEnabled ? content.closed : content.needTeam}</p>{team.raceEnabled && <a className="nds-button" data-variant="primary" href="#/cards/team">{content.recruitFirst}</a>}</div>}
{!live && !race && !choosing && <div className="nds-empty-state"><p>{!team.enabled ? teamContent.closed : !team.raceEnabled ? content.closed : content.needTeam}</p>{team.raceEnabled && <a className="nds-button" data-variant="primary" href={cardsHref("team")}>{content.recruitFirst}</a>}</div>}
{choosing && <>
<RaceCircuit zones={team.zones} content={content} statLabels={statLabels} />
<section className="nebula-race-choice" aria-labelledby="nebula-race-choice-title">

View file

@ -10,21 +10,32 @@ import { bandOf, BALANCED, mainStats, specialtyStyle } from "./teamFormat.js";
export function SpecialtyBand({ companion, content, statLabels }) {
return <span className="nebula-team-band">{bandOf(companion).map((id) => <span key={id} style={{ "--specialty": `var(--color-stat-${id})` }}>
<MaskIcon name={id} />{id === BALANCED ? content.balanced : statLabels[id]}
<MaskIcon name={id} /><span className="nebula-team-band-label">{id === BALANCED ? content.balanced : statLabels[id]}</span>
</span>)}</span>;
}
/** `onSelect` : toute la carte devient un bouton, avec `actionLabel` en pied. `badge` : mention sur l'illustration. */
export function TeamCompanion({ catalog, companion, content, statLabels, badge = "", footer = null, onSelect = null, actionLabel = "", disabled = false, showPower = true, size = "md" }) {
/**
* Fiche d'un compagnon.
* @param {object} props
* @param {Function|null} [props.onSelect] Toute la carte devient un bouton, avec `actionLabel` en pied (s'il est donné).
* @param {string} [props.badge] Mention sur l'illustration.
* @param {boolean|null} [props.selected] Carte à choisir avant d'agir (mode mobile) : bouton bascule (`aria-pressed`)
* nommé par le personnage, au lieu d'un bouton « Recruter … » qui agit tout de suite.
* @param {string} [props.warning] Avertissement court en pastille « ! » sur l'illustration (mode mobile, à la place du
* badge) ; son texte complet s'ajoute au nom accessible de la carte.
*/
export function TeamCompanion({ catalog, companion, content, statLabels, badge = "", footer = null, onSelect = null, actionLabel = "", disabled = false, showPower = true, size = "md", selected = null, warning = "" }) {
const card = catalog.cards.find((item) => item.id === companion.cardId);
const strong = mainStats(companion);
const name = card?.name || content.unknownCard;
const Tag = onSelect ? "button" : "div";
const action = onSelect ? { type: "button", disabled, onClick: onSelect, "aria-label": fillTemplate(content.recruitLabel, { card: name }) } : {};
const choosing = selected !== null;
const action = onSelect ? { type: "button", disabled, onClick: onSelect, ...(choosing ? { "aria-label": warning ? `${name}, ${warning}` : name, "aria-pressed": selected } : { "aria-label": fillTemplate(content.recruitLabel, { card: name }) }) } : {};
return <Tag className="nebula-team-companion" data-size={size} style={specialtyStyle(companion)} {...action}>
<span className="nebula-team-art">
{card?.image && <img src={card.image} alt="" loading="lazy" draggable="false" />}
{badge && <span className="nebula-team-tag">{badge}</span>}
{warning && <span className="nebula-team-warning" title={warning} aria-hidden="true">!</span>}
{companion.lent && <span className="nebula-team-tag" data-side="end">{content.lent}</span>}
</span>
<SpecialtyBand companion={companion} content={content} statLabels={statLabels} />
@ -33,6 +44,6 @@ export function TeamCompanion({ catalog, companion, content, statLabels, badge =
<span className="nebula-team-strong">{strong.map((stat) => <span key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} /><span className="sr-only">{statLabels[stat]} </span>{companion.stats[stat]}</span>)}</span>
{size !== "sm" && <span className="nebula-team-stats">{STAT_IDS.filter((stat) => !strong.includes(stat)).map((stat) => <span key={stat} style={{ "--specialty": `var(--color-stat-${stat})` }}><MaskIcon name={stat} /><span className="sr-only">{statLabels[stat]} </span>{companion.stats[stat]}</span>)}</span>}
{footer}
{onSelect && <span className="nebula-team-action" aria-hidden="true">{actionLabel}</span>}
{onSelect && actionLabel && <span className="nebula-team-action" aria-hidden="true">{actionLabel}</span>}
</Tag>;
}

View file

@ -12,6 +12,7 @@ import { TeamSky } from "./TeamSky.jsx";
import { TeamTable } from "./TeamTable.jsx";
import { TeamWelcome } from "./TeamWelcome.jsx";
import { averagePower, countText } from "./teamFormat.js";
import { useCardsHref } from "../useCardsHref.js";
function GoldReserve({ team, content }) {
return <span className="nebula-team-reserve" role="img" aria-label={fillTemplate(content.reserveLabel, { count: team.goldStars, max: team.maxGoldStars })}>
@ -46,6 +47,7 @@ function RecruitAction({ team, content, busy, onRecruit }) {
}
export function TeamPanel({ catalog, state, runMutation, busy, content, statLabels }) {
const cardsHref = useCardsHref();
const [team, setTeam] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
@ -91,13 +93,13 @@ export function TeamPanel({ catalog, state, runMutation, busy, content, statLabe
const dailyToPlay = state.daily && (state.daily.status === "playing" || state.daily.rewardPending);
const recruit = () => play(() => recruitTeam(team.day));
const recruitBlock = team.canRecruit && <>
{dailyToPlay && team.goldStars < team.maxGoldStars && <p className="nds-inline-notice" role="status">{content.dailyFirst} <a href="#/cards/daily">{content.dailyLink}</a></p>}
{dailyToPlay && team.goldStars < team.maxGoldStars && <p className="nds-inline-notice" role="status">{content.dailyFirst} <a href={cardsHref("daily")}>{content.dailyLink}</a></p>}
<RecruitAction key={team.status} team={team} content={content} busy={busy} onRecruit={recruit} />
</>;
return <section className="nebula-team" aria-labelledby="nebula-team-title" aria-busy={busy || undefined}>
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-team-title">{content.title}</h2></div>
<div className="nebula-team-heading-actions"><GoldReserve team={team} content={content} /><BalmCount team={team} content={content} />{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => { setFinishedPowers(null); play(() => resetTeam()); }}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a></div>
<div className="nebula-team-heading-actions"><GoldReserve team={team} content={content} /><BalmCount team={team} content={content} />{team.devReset && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => { setFinishedPowers(null); play(() => resetTeam()); }}>{content.devReset}</button>}<a className="nds-button" data-size="sm" data-variant="secondary" href={cardsHref("guild")}>{content.back}</a></div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
{!team.enabled && !recruiting && <p className="nds-inline-notice" role="status">{content.closed}</p>}
@ -107,7 +109,7 @@ export function TeamPanel({ catalog, state, runMutation, busy, content, statLabe
<TeamTable catalog={catalog} companions={team.companions} content={content} statLabels={statLabels} powers={finishedPowers} size="md"
title={content.readyTitle} titleId="nebula-team-ready-title" titleRef={readyTitleRef}
status={<>{fillTemplate(content.readyText, { power: averagePower(team.companions) })}{team.lastDust > 0 && ` ${fillTemplate(content.readyDust, { count: team.lastDust })}`}</>}
action={<a className="nds-button" data-size="sm" data-variant="primary" href="#/cards/guild">{content.back}</a>} />
action={<a className="nds-button" data-size="sm" data-variant="primary" href={cardsHref("guild")}>{content.back}</a>} />
<div className="nds-panel nebula-team-stars-panel"><p>{content.skyRevealed}</p><TeamSky sky={team.lastSky} content={content} /></div>
</section>}
{!recruiting && !(finishedPowers && team.status === "ready") && <>

View file

@ -1,11 +1,15 @@
/**
* @file Recrutement de l'Équipe du jour : choix d'un personnage, puis amélioration en révélant des étoiles.
*
* Attention : en mode mobile, la proposition change de forme (`MobileOffer`) : trois cartes réduites à choisir, puis
* la fiche de la carte choisie et un seul bouton « Recruter ». Sur ordinateur, chaque carte recrute directement.
*/
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { CurrencyIcon } from "../Currency.jsx";
import { fillTemplate } from "../textFormat.js";
import { ITEM_ART } from "../expeditions/expeditionFormat.js";
import { ITEM_ART, STAT_IDS } from "../expeditions/expeditionFormat.js";
import { useCardsMobile } from "../useCardsHref.js";
import { TeamCompanion } from "./TeamCompanion.jsx";
import { TeamSky } from "./TeamSky.jsx";
import { TeamBest, TeamTable } from "./TeamTable.jsx";
@ -61,6 +65,10 @@ function Improve({ catalog, recruitment, last, content, statLabels, busy, titleR
const risk = riskPct(hidden);
const strong = mainStats(current);
const keepRef = useRef(null);
// Sur téléphone, « Soigner » prend un libellé court et son nombre de Baumes en pastille, pour tenir sur une ligne ;
// le libellé complet reste son nom accessible.
const mobile = useCardsMobile();
const healText = fillTemplate(content.heal, { power: powers[0], count: recruitment.balms });
// Fin des essais : le bouton qui continue reçoit le focus, l'étoile cliquée ne réagit plus.
useEffect(() => { if (over) keepRef.current?.focus({ preventScroll: true }); }, [over]);
return <div className="nebula-team-improve">
@ -80,15 +88,45 @@ function Improve({ catalog, recruitment, last, content, statLabels, busy, titleR
<div className="nds-toolbar nebula-team-actions">
<button ref={keepRef} className="nds-button" data-variant={over ? "primary" : "secondary"} type="button" disabled={busy} onClick={onKeep}>{over ? (last ? content.seeTeam : content.nextCompanion) : fillTemplate(content.keepAt, { power: current.power })}</button>
{!over && <span>{content.orClickStar}</span>}
{current.fallen && !current.healed && recruitment.balms > 0 && <button className="nds-button nebula-team-heal" data-variant="secondary" type="button" disabled={busy} onClick={onHeal}><img src={ITEM_ART.balm} alt="" />{fillTemplate(content.heal, { power: powers[0], count: recruitment.balms })}</button>}
{current.fallen && !current.healed && recruitment.balms > 0 && <button className="nds-button nebula-team-heal" data-variant="secondary" type="button" disabled={busy} aria-label={mobile ? healText : undefined} onClick={onHeal}><img src={ITEM_ART.balm} alt="" />{mobile
? <>{fillTemplate(content.healShort, { power: powers[0] })}<span className="nebula-item-count-pill" aria-hidden="true">×{recruitment.balms}</span></>
: healText}</button>}
</div>
<p className="nebula-team-note">{content.starsShared}</p>
</div>
</div>;
}
/**
* Proposition sur téléphone : trois cartes réduites (illustration à la bordure de la spécialité, pastille « ! » si la
* spécialité manque à l'équipe, stat forte) qui se choisissent d'un toucher, puis dessous la fiche de la carte choisie (nom entier, quatre stats nommées, la forte
* grossie à sa couleur) et le bouton qui la recrute.
* Le choix se perd quand la proposition change (nouveau tirage) : aucune carte de l'ancienne n'y figure.
*/
function MobileOffer({ catalog, offer, companions, content, statLabels, busy, onChoose }) {
const [pickedId, setPickedId] = useState(null);
const picked = offer.find((companion) => companion.cardId === pickedId) || null;
const name = picked && (catalog.cards.find((item) => item.id === picked.cardId)?.name || content.unknownCard);
const strong = picked ? mainStats(picked) : [];
return <>
<div className="nebula-team-offer-cards">{offer.map((companion) => <TeamCompanion key={companion.cardId} catalog={catalog} companion={companion} content={content} statLabels={statLabels} showPower={false} size="sm" disabled={busy}
warning={isMissing(companion, companions) ? content.missing : ""} selected={companion.cardId === pickedId} onSelect={() => setPickedId(companion.cardId)} />)}</div>
<div className="nebula-team-offer-detail">
{picked ? <>
<h4>{name}</h4>
{isMissing(picked, companions) && <p className="nebula-team-offer-missing">{content.missing}</p>}
<ul className="nebula-team-offer-stats">{STAT_IDS.map((stat) => <li key={stat} data-strong={strong.includes(stat) || undefined} style={{ "--specialty": `var(--color-stat-${stat})` }}>
<MaskIcon name={stat} /><span>{statLabels[stat]}</span><strong>{picked.stats[stat]}</strong>
</li>)}</ul>
</> : <p className="nebula-team-offer-hint">{content.pickHint}</p>}
<button className="nds-button" data-variant="primary" type="button" disabled={busy || !picked} aria-label={picked ? fillTemplate(content.recruitLabel, { card: name }) : undefined} onClick={() => onChoose(picked.cardId)}>{content.recruitAction}</button>
</div>
</>;
}
export function TeamRecruitment({ catalog, team, content, statLabels, busy, onChoose, onReroll, onReveal, onHeal, onKeep }) {
const { recruitment, companions } = team;
const mobile = useCardsMobile();
const count = companions.length + 1;
const titleRef = useRef(null);
const step = `${count}-${recruitment.current ? "improve" : "offer"}`;
@ -112,8 +150,9 @@ export function TeamRecruitment({ catalog, team, content, statLabels, busy, onCh
<div className="nebula-team-reroll"><button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy || !recruitment.rerolls} title={recruitment.rerolls ? countText(content.rerollsLeft, recruitment.rerolls) : content.rerollsNone} onClick={() => onReroll(recruitment.offer.map((companion) => companion.cardId))}>
{content.reroll}<span className="nebula-team-reroll-count" aria-hidden="true">×{recruitment.rerolls}</span><span className="sr-only">{recruitment.rerolls ? countText(content.rerollsLeft, recruitment.rerolls) : content.rerollsNone}</span>
</button></div>
<div className="nebula-team-offer-cards">{recruitment.offer.map((companion) => <TeamCompanion key={companion.cardId} catalog={catalog} companion={companion} content={content} statLabels={statLabels} showPower={false} disabled={busy}
badge={isMissing(companion, companions) ? content.missing : ""} actionLabel={content.recruitAction} onSelect={() => onChoose(companion.cardId)} />)}</div>
{mobile ? <MobileOffer key={recruitment.offer.map((companion) => companion.cardId).join()} catalog={catalog} offer={recruitment.offer} companions={companions} content={content} statLabels={statLabels} busy={busy} onChoose={onChoose} />
: <div className="nebula-team-offer-cards">{recruitment.offer.map((companion) => <TeamCompanion key={companion.cardId} catalog={catalog} companion={companion} content={content} statLabels={statLabels} showPower={false} disabled={busy}
badge={isMissing(companion, companions) ? content.missing : ""} actionLabel={content.recruitAction} onSelect={() => onChoose(companion.cardId)} />)}</div>}
</div>
</section>}</div>
<div className="nebula-team-stage-side">

View file

@ -0,0 +1,32 @@
/**
* @file Liens internes des panneaux du joueur de Sokko TCG : la même section mène à `#/cards/...` en version
* complète et à `#/mobile/cards/...` en mode mobile.
*
* Utilisé par : CardsPage.jsx (fournit la racine), les panneaux qui renvoient vers une autre section et ceux qui
* s'adaptent au mode mobile (`useCardsMobile`).
* Attention : un panneau du joueur n'écrit jamais `#/cards/...` en dur, sinon un joueur sur téléphone repart vers
* la version complète ; tests/nebula-cards-mobile.test.mjs le vérifie. Les liens à partager (invitation
* d'expédition, résultat de la Carte du jour) gardent l'adresse complète : la redirection s'occupe des téléphones.
*/
import { createContext, useCallback, useContext } from "react";
import { CARDS_BASE, MOBILE_CARDS_BASE, cardsRoute } from "./cardsRoutes.js";
/** Racine des routes de la page affichée : `CARDS_BASE` ou `MOBILE_CARDS_BASE`. */
export const CardsBaseContext = createContext(CARDS_BASE);
/** Racine des routes de la page affichée, pour `navigate` ou un retour après connexion. */
export function useCardsBase() {
return useContext(CardsBaseContext);
}
/** Vrai quand le panneau est affiché dans le mode mobile de dépannage, pour un réglage qui n'a pas de solution en CSS. */
export function useCardsMobile() {
return useContext(CardsBaseContext) === MOBILE_CARDS_BASE;
}
/** Renvoie une fonction `(section, subsection?) => "#/…"` qui construit le lien d'une section dans la page affichée. */
export function useCardsHref() {
const base = useContext(CardsBaseContext);
return useCallback((section = "", subsection = "") => `#${cardsRoute(base, section, subsection)}`, [base]);
}