201 lines
16 KiB
JavaScript
201 lines
16 KiB
JavaScript
/**
|
|
* @file Affiche la collection du joueur : l'album (progressions par collection, filtres, recyclage des doublons, détail des
|
|
* éditions) ou l'affichage « Stats » des cartes possédées des Expéditions, pour comparer leurs profils et classer un build.
|
|
*
|
|
* Utilisé par : CardsPage.jsx (section « collection »), en version complète et en mode mobile.
|
|
* Attention : les filtres Recherche, Collection et Rareté valent pour les deux affichages ; Possession n'existe que dans l'album
|
|
* (l'affichage Stats ne montre que des cartes possédées), Profil que dans l'affichage Stats.
|
|
* @see website/src/features/cards/cardStats.js
|
|
*/
|
|
|
|
import { useMemo, useState } from "react";
|
|
import { Icon } from "../../components/Icon.jsx";
|
|
import { SelectDropdown } from "../../components/SelectDropdown.jsx";
|
|
import { Tooltip } from "../../components/Tooltip.jsx";
|
|
import { ActiveFilterBadges } from "../games/ActiveFilterBadges.jsx";
|
|
import { ConfirmModal } from "../../components/ToolboxModals.jsx";
|
|
import { CardDetailModal } from "./CardDetailModal.jsx";
|
|
import { CardsFilterMenu } from "./CardsFilterMenu.jsx";
|
|
import { PROFILE_SHAPES, rankRows, statRows } from "./cardStats.js";
|
|
import { CollectionStats } from "./CollectionStats.jsx";
|
|
import { DashboardAside } from "./CardsDashboard.jsx";
|
|
import { MaskIcon } from "./expeditions/ExpeditionLabels.jsx";
|
|
import { recycleDuplicates } from "./cardsApi.js";
|
|
import { readCollection, visibleCollections } from "./collectionState.js";
|
|
import { NebulaCard } from "./rendering/NebulaCard.jsx";
|
|
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 VIEWS = ["album", "stats"];
|
|
const VIEW_ICONS = { album: "cards", stats: "table" };
|
|
|
|
/**
|
|
* Bascule entre l'album et l'outil de stats : deux tuiles (icône, nom, phrase d'usage) sous le titre, pour qu'on voie qu'il existe
|
|
* deux façons de parcourir la collection. Le nom seul nomme l'onglet ; la phrase le décrit.
|
|
*/
|
|
function CollectionViews({ view, onChange, content }) {
|
|
return <div className="nebula-collection-views" role="tablist" aria-label={content.label}>{VIEWS.map((id) => {
|
|
const selected = id === view;
|
|
return <button key={id} type="button" role="tab" className="nebula-collection-view" aria-selected={selected} aria-labelledby={`nebula-view-${id}`}
|
|
aria-describedby={`nebula-view-${id}-help`} onClick={() => onChange(id)}>
|
|
<MaskIcon name={VIEW_ICONS[id]} />
|
|
<span className="nebula-collection-view-text"><strong id={`nebula-view-${id}`}>{content[id]}</strong><small id={`nebula-view-${id}-help`}>{content[`${id}Help`]}</small></span>
|
|
</button>;
|
|
})}</div>;
|
|
}
|
|
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([]);
|
|
const [ownership, setOwnership] = useState([]);
|
|
const [view, setView] = useState("album");
|
|
const [statMode, setStatMode] = useState("profile");
|
|
const [targets, setTargets] = useState([]);
|
|
const [shapes, setShapes] = useState([]);
|
|
// Fiche ouverte : la carte et son onglet (« Amélioration » depuis l'affichage Stats).
|
|
const [selected, setSelected] = useState(null);
|
|
const [confirmingRecycle, setConfirmingRecycle] = useState(false);
|
|
const [recycleNotice, setRecycleNotice] = useState("");
|
|
// Rareté maximale du recyclage en masse : les communes seules par défaut, pour ne pas jeter les doublons utiles à un Éveil.
|
|
const [maxRarity, setMaxRarity] = useState("common");
|
|
const owned = useMemo(() => readCollection(state), [state]);
|
|
const { quantities } = owned;
|
|
const cards = useMemo(() => new Map(catalog.cards.map((card) => [card.id, card])), [catalog.cards]);
|
|
const favorites = new Set(state.favorites);
|
|
const normalizedSearch = search.trim().toLocaleLowerCase("fr");
|
|
const collections = visibleCollections(catalog, owned.ownedCardIds);
|
|
const visibleCollectionIds = new Set(collections.map((collection) => collection.id));
|
|
// Recherche, collection et rareté : communes aux deux affichages. Une carte inconnue ne se cherche que par son nom : sa
|
|
// description, cachée, est un indice de la Carte du jour.
|
|
const matchesCommon = (card, edition, quantity) => visibleCollectionIds.has(card.collectionId)
|
|
&& (!normalizedSearch || `${card.name} ${quantity > 0 ? card.description : ""}`.toLocaleLowerCase("fr").includes(normalizedSearch))
|
|
&& (!collectionIds.length || collectionIds.includes(card.collectionId))
|
|
&& (!rarities.length || rarities.includes(edition.rarity));
|
|
const editions = catalog.editions.filter((edition) => {
|
|
const quantity = quantities.get(edition.id) || 0;
|
|
return matchesCommon(cards.get(edition.cardId), edition, quantity)
|
|
&& (!ownership.length || ownership.includes("owned") && quantity > 0 || ownership.includes("missing") && quantity === 0 || ownership.includes("duplicates") && quantity > 1);
|
|
});
|
|
const allStatRows = useMemo(() => statRows(catalog, state), [catalog, state]);
|
|
const shownStatRows = rankRows(allStatRows.filter((row) => matchesCommon(row.card, row.edition, 1) && (!shapes.length || shapes.includes(row.shape))), targets, statMode);
|
|
const hasCurrent = allStatRows.some((row) => row.current);
|
|
const currentMax = Math.max(0, ...allStatRows.flatMap((row) => (row.current ? Object.values(row.current) : [])));
|
|
const statsContent = headingContent.stats;
|
|
|
|
/** Éditions hors promotion d'une collection, décomptées dans les titres de l'album. */
|
|
function collectionEditionsOf(collection) {
|
|
return catalog.editions.filter((edition) => !edition.promotional && cards.get(edition.cardId)?.collectionId === collection.id);
|
|
}
|
|
|
|
function resetFilters() {
|
|
setSearch("");
|
|
setCollectionIds([]);
|
|
setRarities([]);
|
|
setOwnership([]);
|
|
setShapes([]);
|
|
}
|
|
|
|
async function recycleAll() {
|
|
setRecycleNotice("");
|
|
const result = await runMutation(() => recycleDuplicates(null, maxRarity));
|
|
if (!result?.recycled) return;
|
|
setRecycleNotice(fillTemplate(content.done, { count: countDuplicates(result.recycled.count), recycled: result.recycled.count > 1 ? "recyclés" : "recyclé", stardust: formatStardust(result.recycled.stardust) }));
|
|
// Il ne reste plus de doublon à montrer : on revient à toute la collection.
|
|
if (ownership.includes("duplicates")) setOwnership(ownership.filter((value) => value !== "duplicates"));
|
|
}
|
|
|
|
const { recycling, wallet, shop } = state;
|
|
// Raretés recyclables en masse (sans les mythiques), dans l'ordre du catalogue, avec l'aperçu de chacune envoyé par le serveur.
|
|
const massRarities = catalog.rarities.filter((rarity) => Object.hasOwn(recycling.byRarity ?? {}, rarity.id));
|
|
const chosenRarities = massRarities.slice(0, massRarities.findIndex((rarity) => rarity.id === maxRarity) + 1);
|
|
const chosen = chosenRarities.map((rarity) => recycling.byRarity[rarity.id]);
|
|
const awakeningRarities = chosenRarities.filter((rarity) => rarity.id !== "common");
|
|
const preview = { count: chosen.reduce((total, item) => total + item.count, 0), stardust: chosen.reduce((total, item) => total + item.stardust, 0) };
|
|
const showingDuplicates = ownership.includes("duplicates");
|
|
const collectionOptions = collections.map((item) => ({ value: item.id, label: item.name }));
|
|
const rarityOptions = catalog.rarities.map((item) => ({ value: item.id, label: item.label }));
|
|
const shapeOptions = PROFILE_SHAPES.map((id) => ({ value: id, label: statsContent.shapes[id] }));
|
|
const activeFilters = [
|
|
...(search.trim() ? [{ id: "search", label: `Recherche : ${search.trim()}`, onRemove: () => setSearch("") }] : []),
|
|
...collectionOptions.filter((option) => collectionIds.includes(option.value)).map((option) => ({ id: `collection-${option.value}`, label: `Collection : ${option.label}`, onRemove: () => setCollectionIds(collectionIds.filter((value) => value !== option.value)) })),
|
|
...rarityOptions.filter((option) => rarities.includes(option.value)).map((option) => ({ id: `rarity-${option.value}`, label: `Rareté : ${option.label}`, onRemove: () => setRarities(rarities.filter((value) => value !== option.value)) })),
|
|
...(view === "album" ? OWNERSHIP_OPTIONS : []).filter((option) => ownership.includes(option.value)).map((option) => ({ id: `ownership-${option.value}`, label: `Possession : ${option.label}`, onRemove: () => setOwnership(ownership.filter((value) => value !== option.value)) })),
|
|
...(view === "stats" ? shapeOptions : []).filter((option) => shapes.includes(option.value)).map((option) => ({ id: `shape-${option.value}`, label: `${statsContent.shapeFilter} : ${option.label}`, onRemove: () => setShapes(shapes.filter((value) => value !== option.value)) }))
|
|
];
|
|
|
|
return <>
|
|
<div className="nds-section-heading nebula-section-heading">
|
|
<div><p className="eyebrow">{headingContent.eyebrow}</p><h2>{headingContent.title}</h2></div>
|
|
</div>
|
|
<CollectionViews view={view} onChange={setView} content={headingContent.views} />
|
|
{recycling.count > 0 && <DashboardAside>
|
|
<section className="nds-panel nebula-recycle-box" aria-label={content.barLabel}>
|
|
<StardustBalance value={wallet.stardust} />
|
|
<SelectDropdown className="nebula-recycle-box-rarity" label={content.maxRarityLabel} size="sm" value={maxRarity} options={massRarities.map((rarity) => ({ value: rarity.id, label: rarity.label }))} onChange={setMaxRarity} />
|
|
{preview.count ? <p><strong>{countDuplicates(preview.count)}</strong> à recycler pour <strong>+{formatStardust(preview.stardust)}</strong></p> : <p>{content.none}</p>}
|
|
<div className="nebula-recycle-box-actions">
|
|
<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={() => { setView("album"); setOwnership(showingDuplicates ? [] : ["duplicates"]); }}>{showingDuplicates ? content.viewAll : content.viewDuplicates}</button>
|
|
</div>
|
|
{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>}
|
|
<section className="filter-panel nds-filter-panel nebula-album-filters" data-variant="horizontal-menu" aria-label="Filtres de la collection">
|
|
<label className="nds-filter-search"><span className="sr-only">Recherche</span><input className="nds-input" data-size="sm" type="search" value={search} placeholder="Rechercher..." onChange={(event) => setSearch(event.target.value)} /></label>
|
|
<CardsFilterMenu label="Collection" options={collectionOptions} selected={collectionIds} onChange={setCollectionIds} />
|
|
<CardsFilterMenu label="Rareté" options={rarityOptions} selected={rarities} onChange={setRarities} />
|
|
{view === "album" ? <CardsFilterMenu label="Possession" options={OWNERSHIP_OPTIONS} selected={ownership} onChange={setOwnership} />
|
|
: <CardsFilterMenu label={statsContent.shapeFilter} options={shapeOptions} selected={shapes} onChange={setShapes} />}
|
|
<Tooltip as="button" className="filter-reset-button nds-icon-button nds-filter-reset" content={headingContent.resetFilters} data-size="xs" type="button" aria-label={headingContent.resetFilters} onClick={resetFilters}><Icon name="rubber" /></Tooltip>
|
|
<ActiveFilterBadges items={activeFilters} />
|
|
</section>
|
|
{view === "stats" ? <CollectionStats catalog={catalog} rows={shownStatRows} total={allStatRows.length} mode={hasCurrent ? statMode : "profile"} onModeChange={setStatMode}
|
|
targets={targets} onTargetsChange={setTargets} hasCurrent={hasCurrent} currentMax={currentMax} content={statsContent} statNames={cardSheetContent.stats}
|
|
onSelect={(row) => setSelected({ entry: { edition: row.edition, card: row.card }, tab: "improve" })} />
|
|
: <section aria-label="Cartes de la collection">
|
|
{editions.length ? <div className="nebula-album-groups">{collections.map((collection) => {
|
|
const shownEditions = editions.filter((edition) => cards.get(edition.cardId).collectionId === collection.id);
|
|
if (!shownEditions.length) return null;
|
|
// Le compteur décrit toute la collection : il ne change pas avec les filtres.
|
|
const allEditions = collectionEditionsOf(collection);
|
|
const ownedEditions = allEditions.filter((edition) => quantities.has(edition.id)).length;
|
|
const allCards = catalog.cards.filter((card) => card.collectionId === collection.id && allEditions.some((edition) => edition.cardId === card.id));
|
|
const ownedCards = allCards.filter((card) => owned.ownedCardIds.has(card.id)).length;
|
|
return <section key={collection.id} className="nebula-album-group" aria-labelledby={`nebula-album-group-${collection.id}`}>
|
|
<h3 id={`nebula-album-group-${collection.id}`}>{collection.name} <Tooltip className="nds-badge" content={`Éditions différentes possédées · ${ownedCards} cartes découvertes sur ${allCards.length}`} data-variant="neutral" aria-label={`${ownedEditions} éditions différentes possédées sur ${allEditions.length}`}>{ownedEditions} / {allEditions.length}</Tooltip></h3>
|
|
<div className="nds-progress" data-size="sm"><span style={{ width: `${allEditions.length ? ownedEditions / allEditions.length * 100 : 0}%` }} /></div>
|
|
<div className="nebula-album-grid">{shownEditions.map((edition) => {
|
|
const entry = { edition, card: cards.get(edition.cardId) };
|
|
const quantity = quantities.get(edition.id) || 0;
|
|
const discovered = quantity > 0;
|
|
return <div key={edition.id} className="nebula-album-entry" data-missing={!quantity || undefined} data-undiscovered={!discovered || undefined}>
|
|
<NebulaCard catalog={catalog} entry={entry} quantity={quantity} size="md" concealed={!discovered} backCollection={collection} onSelect={discovered ? () => setSelected({ entry, tab: "card" }) : undefined} />
|
|
{discovered && favorites.has(edition.id) && <span className="nebula-favorite-mark" aria-label="Favorite">★</span>}
|
|
</div>;
|
|
})}</div>
|
|
</section>;
|
|
})}</div> : <div className="nds-empty-state"><p>Aucune édition ne correspond à ces filtres.</p></div>}
|
|
</section>}
|
|
{confirmingRecycle && <ConfirmModal
|
|
title={fillTemplate(content.confirmTitle, { count: countDuplicates(preview.count) })}
|
|
message={fillTemplate(content.confirmText, { rarities: frenchList(chosenRarities.map((rarity) => rarityAdjective(catalog, rarity.id, 2))), stardust: formatStardust(preview.stardust) })}
|
|
confirmLabel={content.allButton}
|
|
onClose={(confirmed) => { setConfirmingRecycle(false); if (confirmed) void recycleAll(); }}
|
|
>
|
|
{/* Au-delà des communes, les doublons recyclés auraient pu éveiller des cartes. */}
|
|
{awakeningRarities.length > 0 && <p className="nds-inline-notice" data-variant="warning">{fillTemplate(content.keepForAwakening, { rarities: frenchList(awakeningRarities.map((rarity) => rarityAdjective(catalog, rarity.id, 2))) })}</p>}
|
|
<p className="nebula-form-help">{content.confirmKept}</p>
|
|
{/* Seules les raretés recyclées cette fois, avec ce que rapporte chacun de leurs doublons. */}
|
|
<ul className="nebula-shop-rates" aria-label={content.ratesLabel}>{chosenRarities.map((rarity) => <li key={rarity.id} data-rarity={rarity.id}><span>{rarity.label}</span><StardustBalance value={shop.stardustValues[rarity.id] ?? 0} /></li>)}</ul>
|
|
</ConfirmModal>}
|
|
{selected && <CardDetailModal catalog={catalog} state={state} entry={selected.entry} initialTab={selected.tab} content={cardSheetContent} runMutation={runMutation} busy={busy} onClose={() => setSelected(null)} onStartTransfer={onStartTransfer} />}
|
|
</>;
|
|
}
|