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

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

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

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

375 lines
16 KiB
JavaScript

/**
* @file Point d'entrée React : monte l'application dans `#app` et assemble les données du site, le stockage des
* toolboxes, la configuration de Sokko TCG, le shell (menu, notifications), le routeur et le tiroir de
* toolbox.
*
* Contexte : le composant `App` appelle une seule fois les hooks globaux (useAppData, useIndexedToolboxes,
* useToolboxActions, useCardsConfig, useAutoBackup, useToolboxAlerts) et transmet leurs résultats aux pages par
* RouteContent. Au-dessus, `Root` choisit l'application : le mode mobile de Sokko TCG (`#/mobile/cards/...`,
* features/cards/mobile/MobileCardsApp.jsx, sans le shell) ou le site complet ; un téléphone qui ouvre une
* section du jeu proposée en mobile y est d'abord redirigé, sauf s'il a choisi la version complète.
* Utilisé par : index.html (script d'entrée de Vite).
* Attention :
* - L'application est enveloppée dans `StrictMode` : en développement, React rejoue des rendus et des effets.
* - Un composant hors de cet arbre peut afficher une notification par l'événement `sokkog:notify`.
* - Ne pas réintroduire de contenu de secours en dur : les textes viennent de site.json.
* @see ARCHITECTURE.md
*/
/* eslint-disable react-refresh/only-export-components -- point d'entrée Vite sans export de composant. */
import { lazy, StrictMode, Suspense, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import "./styles/main.scss";
import { AppOverlays } from "./components/AppOverlays.jsx";
import { AppErrorBoundary } from "./components/AppErrorBoundary.jsx";
import { Shell } from "./components/Shell.jsx";
import { Icon } from "./components/Icon.jsx";
import { useIndexedToolboxes } from "./features/toolboxes/storage/useIndexedToolboxes.js";
import { useToolboxActions } from "./features/toolboxes/useToolboxActions.js";
import { useAppData } from "./hooks/useAppData.js";
import { GuideChecklistContext } from "./features/games/useGuideChecklist.js";
import { useGuideChecklistStorage } from "./hooks/useGuideChecklistStorage.js";
import { useGameFilters } from "./hooks/useGameFilters.js";
import { useToolboxAlerts } from "./hooks/useToolboxAlerts.js";
import { RouteContent } from "./router/RouteContent.jsx";
import { useHashRoute } from "./router/hashRouter.js";
import { normalizeCalendarData, normalizeTimerData } from "./features/toolboxes/storage/toolboxStorage.js";
import { useAutoBackup } from "./features/toolboxes/storage/useAutoBackup.js";
import { GlobalMemosTicker } from "./features/toolboxes/GlobalMemosTicker.jsx";
import { CARDS_TOOLBOX_TARGET_ID, getDrawerToolboxId, getRouteToolboxTargetId } from "./features/toolboxes/toolboxTargets.js";
import { useCardsToolboxChoice } from "./features/toolboxes/useCardsToolboxChoice.js";
import { useMediaQuery } from "./hooks/useMediaQuery.js";
import { useCardsConfig } from "./features/cards/useCardsConfig.js";
import { useSharesConfig } from "./features/toolboxes/sharing/useSharesConfig.js";
import { isMobileCardsRoute } from "./features/cards/cardsRoutes.js";
import { mobileRedirectForDevice } from "./features/cards/mobile/mobileDevice.js";
const assetRecoveryUrl = new URL(window.location.href);
if (assetRecoveryUrl.searchParams.has("_asset-recovery")) {
assetRecoveryUrl.searchParams.delete("_asset-recovery");
window.history.replaceState(
window.history.state,
"",
`${assetRecoveryUrl.pathname}${assetRecoveryUrl.search}${assetRecoveryUrl.hash}`
);
}
const MobileCardsApp = lazy(() => import("./features/cards/mobile/MobileCardsApp.jsx").then((module) => ({ default: module.MobileCardsApp })));
const ToolboxDrawer = lazy(() => import("./features/toolboxes/ToolboxPages.jsx").then((module) => ({ default: module.ToolboxDrawer })));
const DEFAULT_NOTIFICATION_DURATION_MS = 6000;
function getNotificationDuration(_message, options = {}) {
if (options.persistent) return 0;
if (Number.isFinite(options.durationMs)) return Math.max(1000, Number(options.durationMs));
return DEFAULT_NOTIFICATION_DURATION_MS;
}
function App() {
const route = useHashRoute();
const compactGameLayout = useMediaQuery("(max-width: 1439px)");
const reducedSidebar = useMediaQuery("(max-width: 1024px)");
const cardsConfig = useCardsConfig();
const sharesConfig = useSharesConfig();
const {
siteContent,
siteContentError,
siteContentLoading,
retrySiteContent,
games,
gamesError,
gamesLoading,
retryGames,
mhwilds,
diablo4,
aniimo
} = useAppData(route);
const [filters, setFilters] = useGameFilters();
const [confirmModal, setConfirmModal] = useState(null);
const [createModal, setCreateModal] = useState(null);
const [autoBackupModalOpen, setAutoBackupModalOpen] = useState(false);
const [linkModalGameId, setLinkModalGameId] = useState("");
const [shareToolboxId, setShareToolboxId] = useState("");
const [drawerGameId, setDrawerGameId] = useState("");
const [drawerVisible, setDrawerVisible] = useState(false);
const [drawerContext, setDrawerContext] = useState({ route, compactGameLayout });
const [cardsToolboxId, setCardsToolboxId] = useCardsToolboxChoice();
const [image, setImage] = useState(null);
const [pendingTutorialToolboxId, setPendingTutorialToolboxId] = useState("");
const [notifications, setNotifications] = useState([]);
const [storageError, setStorageError] = useState("");
const backupReminderIdRef = useRef("");
const handleStorageError = useCallback((message) => setStorageError(message), []);
const store = useIndexedToolboxes(handleStorageError);
const autoBackup = useAutoBackup(store);
const { backupNeeded, requestPermission: requestBackupPermission } = autoBackup;
const guideChecklistStorage = useGuideChecklistStorage(store);
const guideScrollRef = useRef(0);
const setGameToolbox = useCallback((gameId) => {
if (gameId) {
if (compactGameLayout && !drawerVisible) guideScrollRef.current = window.scrollY;
setDrawerGameId(gameId);
setDrawerVisible(true);
if (compactGameLayout) window.requestAnimationFrame(() => window.scrollTo({ top: 0, behavior: "auto" }));
return;
}
setDrawerVisible(false);
if (compactGameLayout) {
window.requestAnimationFrame(() => window.scrollTo({ top: guideScrollRef.current, behavior: "auto" }));
} else {
setDrawerGameId("");
}
}, [compactGameLayout, drawerVisible]);
if (drawerContext.route !== route || drawerContext.compactGameLayout !== compactGameLayout) {
setDrawerContext({ route, compactGameLayout });
const activeGameId = getRouteToolboxTargetId(route);
if (activeGameId !== drawerGameId) {
setDrawerGameId("");
setDrawerVisible(false);
} else if (!compactGameLayout && !drawerVisible && drawerGameId) {
setDrawerGameId("");
}
}
const notify = useCallback((message, options = {}) => {
const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
setNotifications((current) => [
{
id,
message,
durationMs: getNotificationDuration(message, options),
actionLabel: options.actionLabel,
onAction: options.onAction
},
...current
].slice(0, 5));
return id;
}, []);
const dismissNotification = useCallback((notificationId) => {
setNotifications((current) => current.filter((notification) => notification.id !== notificationId));
}, []);
useEffect(() => {
function handleNotification(event) {
if (event.detail?.message) notify(event.detail.message, event.detail);
}
window.addEventListener("sokkog:notify", handleNotification);
return () => window.removeEventListener("sokkog:notify", handleNotification);
}, [notify]);
useEffect(() => {
if (!backupNeeded) {
if (backupReminderIdRef.current) dismissNotification(backupReminderIdRef.current);
backupReminderIdRef.current = "";
return;
}
if (backupReminderIdRef.current || !siteContent?.toolboxes?.autoBackup) return;
const content = siteContent.toolboxes.autoBackup;
backupReminderIdRef.current = notify(content.reminderMessage, {
persistent: true,
actionLabel: content.reminderAction,
onAction: () => void requestBackupPermission()
});
}, [backupNeeded, dismissNotification, notify, requestBackupPermission, siteContent]);
const t = (key, { capitalize = false } = {}) => {
const value = mhwilds.translations[key] || String(key || "").replace(/_/g, " ");
return capitalize ? value.charAt(0).toUpperCase() + value.slice(1) : value;
};
const getGame = (gameId) => games.find((item) => item.id === gameId);
// La page courante propose le tiroir : un jeu connu (sa toolbox liée), ou Sokko TCG quand le jeu est ouvert (une toolbox au choix).
const routeToolboxTargetId = getRouteToolboxTargetId(route);
const shellToolboxTargetId = routeToolboxTargetId === CARDS_TOOLBOX_TARGET_ID ? (cardsConfig.enabled ? routeToolboxTargetId : "") : getGame(routeToolboxTargetId) ? routeToolboxTargetId : "";
const drawerToolboxId = getDrawerToolboxId(drawerGameId, store.links, cardsToolboxId, store.toolboxes);
const cardsDrawer = drawerGameId === CARDS_TOOLBOX_TARGET_ID;
const getToolboxGameId = (toolbox) => Object.entries(store.links).find(([, toolboxId]) => toolboxId === toolbox?.id)?.[0] || "";
const getToolboxGame = (toolbox) => getGame(getToolboxGameId(toolbox));
const actions = useToolboxActions({
store,
notify,
creationTemplate: siteContent?.toolboxes?.creationTemplate,
importContent: siteContent?.toolboxes?.imports,
setCreateModal,
setConfirmModal,
setLinkModalGameId,
setDrawerGameId: setGameToolbox,
setImage,
sharesConfig,
setShareToolboxId
});
useToolboxAlerts({
toolboxes: store.toolboxes,
moduleData: store.moduleData,
route,
drawerToolboxId: drawerVisible ? drawerToolboxId : "",
normalizeTimerData,
normalizeCalendarData,
textContent: siteContent?.toolboxes?.modules,
notify
});
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>
);
}
if (!store.ready) {
const content = siteContent.toolboxes.storageStatus;
return (
<main className="startup-error">
<section className="empty nds-empty-state" aria-busy={!store.loadError}>
<h1>{store.loadError ? content.errorTitle : content.loadingTitle}</h1>
<p>{store.loadError ? content.errorMessage : content.loadingMessage}</p>
{store.loadError && <>
<p role="alert">{store.loadError}</p>
<button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={store.retryLoad}>
<Icon name="refresh" />{content.retryLabel}
</button>
</>}
</section>
</main>
);
}
return (
<GuideChecklistContext.Provider value={{ route, aniimo, mhwilds, diablo4, siteContent, toolboxes: store.toolboxes, links: store.links, moduleData: store.moduleData, guideChecklistStorage, actions, filters, t }}>
<Shell
route={route}
content={siteContent}
toolboxTargetId={shellToolboxTargetId}
drawerGameId={drawerGameId}
drawerVisible={drawerVisible}
compactGameLayout={compactGameLayout}
reducedSidebar={reducedSidebar}
cardsEnabled={cardsConfig.enabled}
actions={actions}
onOpenAutoBackup={() => setAutoBackupModalOpen(true)}
>
<div className="route-content-view" aria-hidden={compactGameLayout && drawerVisible || undefined} inert={compactGameLayout && drawerVisible || undefined}>
<AppErrorBoundary route={route}>
<RouteContent
route={route}
siteContent={siteContent}
cardsConfig={cardsConfig}
games={games}
gamesError={gamesError}
gamesLoading={gamesLoading}
retryGames={retryGames}
mhwilds={mhwilds}
diablo4={diablo4}
aniimo={aniimo}
filters={filters}
setFilters={setFilters}
t={t}
toolboxes={store.toolboxes}
links={store.links}
getGame={getGame}
getToolboxGame={getToolboxGame}
actions={actions}
storageUsage={store.storageUsage}
storageReady={store.ready}
toastPosition={store.toastPosition}
setToastPosition={store.setToastPosition}
getModuleData={store.getModuleData}
updateToolbox={actions.updateToolbox}
updateModuleData={store.updateModuleData}
addImageFiles={actions.addImageFiles}
pendingTutorialToolboxId={pendingTutorialToolboxId}
setPendingTutorialToolboxId={setPendingTutorialToolboxId}
/>
</AppErrorBoundary>
</div>
{drawerGameId && (
<Suspense fallback={null}>
<ToolboxDrawer
gameId={drawerGameId}
game={cardsDrawer ? undefined : getGame(drawerGameId)}
toolboxId={drawerToolboxId}
chooser={cardsDrawer ? { onChoose: setCardsToolboxId, getToolboxGame } : null}
siteContent={siteContent}
toolboxes={store.toolboxes}
links={store.links}
actions={actions}
storageUsage={store.storageUsage}
storageReady={store.ready}
getModuleData={store.getModuleData}
updateToolbox={actions.updateToolbox}
updateModuleData={store.updateModuleData}
addImageFiles={actions.addImageFiles}
visible={drawerVisible}
compact={compactGameLayout}
/>
</Suspense>
)}
<GlobalMemosTicker
route={route}
toolboxes={store.toolboxes}
links={store.links}
cardsToolboxId={cardsToolboxId}
moduleData={store.moduleData}
textContent={siteContent.toolboxes.modules.memos}
/>
<AppOverlays
storageErrorTitle={siteContent.toolboxes.storageStatus.writeErrorTitle}
actions={actions}
confirmModal={confirmModal}
setConfirmModal={setConfirmModal}
createModal={createModal}
setCreateModal={setCreateModal}
linkModalGameId={linkModalGameId}
setLinkModalGameId={setLinkModalGameId}
shareToolboxId={shareToolboxId}
setShareToolboxId={setShareToolboxId}
shareContent={siteContent.toolboxShare}
setDrawerGameId={setGameToolbox}
storageError={storageError}
setStorageError={setStorageError}
image={image}
setImage={setImage}
notifications={notifications}
dismissNotification={dismissNotification}
toastPosition={store.toastPosition}
getGame={getGame}
toolboxes={store.toolboxes}
links={store.links}
setPendingTutorialToolboxId={setPendingTutorialToolboxId}
autoBackupModalOpen={autoBackupModalOpen}
setAutoBackupModalOpen={setAutoBackupModalOpen}
autoBackup={autoBackup}
autoBackupContent={siteContent.toolboxes.autoBackup}
/>
</Shell>
</GuideChecklistContext.Provider>
);
}
/**
* Choisit l'application selon la route : mode mobile de Sokko TCG ou site complet. Un téléphone qui ouvre une section
* du jeu proposée en mobile est d'abord envoyé vers elle ; l'adresse est remplacée, pour que Retour ne boucle pas.
*/
function Root() {
const route = useHashRoute();
const redirect = mobileRedirectForDevice(route);
useLayoutEffect(() => {
if (redirect) window.location.replace(`#${redirect}`);
}, [redirect]);
if (redirect) return null;
if (isMobileCardsRoute(route)) return <Suspense fallback={null}><MobileCardsApp route={route} /></Suspense>;
return <App />;
}
createRoot(document.querySelector("#app")).render(<StrictMode><Root /></StrictMode>);