sokko-g/website/src/features/cards/NebulaCard.jsx
Shinuwa 5ce35cd7ba Add the Sokko TCG collectible card mini-game
Add the server-backed card game: Discord login, recharging pack openings,
album, trades, gifts, stardust shop, campaign codes and its administration,
stored in SQLite and disabled in production until configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 17:47:35 +01:00

356 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : affiche les cartes Sokko TCG et pilote leur tilt, leurs finitions et leurs animations de révélation.
import { useEffect, useRef, useState } from "react";
import { CollectionCardBack } from "./CollectionCardBack.jsx";
import { MATCH_HOLO_PALETTE_ID, MATCH_HOLO_PALETTE_LABEL, resolveMythicOpeningStyle, resolveOpeningEffect } from "./openingEffects.js";
const STANDARD_CARD_LAYOUT = "standard";
function useCardTilt() {
const cardRef = useRef(null);
useEffect(() => {
const card = cardRef.current;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
const finePointer = window.matchMedia("(hover: hover) and (pointer: fine)");
if (!card || reducedMotion.matches || !finePointer.matches) return undefined;
let frame = 0;
let interacting = false;
const current = { x: 0, y: 0, lift: 0, pointerX: 50, pointerY: 35 };
const target = { ...current };
const schedule = () => {
if (!frame) frame = window.requestAnimationFrame(render);
};
const render = () => {
current.x += (target.x - current.x) * 0.16;
current.y += (target.y - current.y) * 0.16;
current.lift += (target.lift - current.lift) * 0.16;
current.pointerX += (target.pointerX - current.pointerX) * 0.16;
current.pointerY += (target.pointerY - current.pointerY) * 0.16;
card.style.setProperty("--card-tilt-x", `${current.x.toFixed(2)}deg`);
card.style.setProperty("--card-tilt-y", `${current.y.toFixed(2)}deg`);
card.style.setProperty("--card-lift", `${current.lift.toFixed(2)}px`);
card.style.setProperty("--card-pointer-x", `${current.pointerX.toFixed(1)}%`);
card.style.setProperty("--card-pointer-y", `${current.pointerY.toFixed(1)}%`);
// Énergie du tilt (0 à 1) : nulle au repos, modérée sur une carte à plat, maximale sur les bords.
const engaged = Math.min(1, current.lift / -4);
const inclination = Math.min(1, Math.hypot(current.x / 4, current.y / 5));
card.style.setProperty("--card-tilt-energy", (engaged * (0.35 + 0.65 * inclination)).toFixed(3));
const moving = Math.abs(target.x - current.x) > 0.03
|| Math.abs(target.y - current.y) > 0.03
|| Math.abs(target.lift - current.lift) > 0.03
|| Math.abs(target.pointerX - current.pointerX) > 0.1
|| Math.abs(target.pointerY - current.pointerY) > 0.1;
frame = moving ? window.requestAnimationFrame(render) : 0;
if (!moving && !interacting) delete card.dataset.tiltActive;
};
const reset = () => {
interacting = false;
target.x = 0;
target.y = 0;
target.lift = 0;
target.pointerX = 50;
target.pointerY = 35;
schedule();
};
const handlePointerMove = (event) => {
if (event.pointerType === "touch") return;
const bounds = card.getBoundingClientRect();
const pointerX = Math.min(1, Math.max(0, (event.clientX - bounds.left) / bounds.width));
const pointerY = Math.min(1, Math.max(0, (event.clientY - bounds.top) / bounds.height));
interacting = true;
card.dataset.tiltActive = "true";
target.x = (0.5 - pointerY) * 8;
target.y = (pointerX - 0.5) * 10;
target.lift = -4;
target.pointerX = pointerX * 100;
target.pointerY = pointerY * 100;
schedule();
};
const handleFocus = () => {
interacting = true;
card.dataset.tiltActive = "true";
target.x = -1.2;
target.y = 1.8;
target.lift = -4;
target.pointerX = 62;
target.pointerY = 28;
schedule();
};
card.addEventListener("pointermove", handlePointerMove);
card.addEventListener("pointerleave", reset);
card.addEventListener("focus", handleFocus);
card.addEventListener("blur", reset);
return () => {
window.cancelAnimationFrame(frame);
card.removeEventListener("pointermove", handlePointerMove);
card.removeEventListener("pointerleave", reset);
card.removeEventListener("focus", handleFocus);
card.removeEventListener("blur", reset);
};
}, []);
return cardRef;
}
function RaritySymbol({ rarity, label }) {
return <span className="nebula-card-rarity-symbol" data-rarity={rarity} title={label}>
<svg viewBox="0 0 32 32" aria-hidden="true">
{rarity === "common" && <circle cx="16" cy="16" r="7" />}
{rarity === "rare" && <path d="M16 3 19 13 29 16 19 19 16 29 13 19 3 16 13 13Z" />}
{rarity === "epic" && <path d="m16 3 3.8 8.2 9.2.8-7 6 2 9-8-4.7L8 27l2-9-7-6 9.2-.8Z" />}
{rarity === "legendary" && <><circle cx="16" cy="16" r="12" /><path d="M16 5 19 13 27 16 19 19 16 27 13 19 5 16 13 13Z" /></>}
{rarity === "mythic" && <><ellipse cx="16" cy="16" rx="14" ry="7" /><ellipse cx="16" cy="16" rx="7" ry="14" /><path d="M16 6 19 13 26 16 19 19 16 26 13 19 6 16 13 13Z" /></>}
</svg>
<span className="sr-only">{label}</span>
</span>;
}
function resolveFinishVisual(edition, catalog) {
const finishes = (edition.finishIds || [])
.map((finishId) => catalog?.finishes.find((finish) => finish.id === finishId))
.filter(Boolean);
const effectFinish = finishes.find((finish) => finish.effectPresetId);
const effectPreset = catalog?.effectPresets.find((candidate) => candidate.id === effectFinish?.effectPresetId);
const palette = catalog?.effectPalettes.find((candidate) => candidate.id === effectFinish?.paletteId);
const colors = palette?.colors || [];
const repeatedColors = palette ? [...colors, ...colors, ...colors] : [];
return {
finishLabel: finishes.map((finish) => finish.label).join(" · ") || edition.finishIds?.join(" · "),
effectPreset,
layout: effectFinish?.formatId || STANDARD_CARD_LAYOUT,
palette,
style: palette ? {
"--holo-1": colors[0],
"--holo-2": colors[1],
"--holo-3": colors[2],
"--holo-4": colors[3],
"--holo-5": colors[4],
"--holo-6": colors[5],
"--holo-7": colors[6],
"--holo-highlight": palette.highlight,
"--holo-gradient": `linear-gradient(125deg, ${repeatedColors.join(", ")})`
} : undefined
};
}
function resolveOpeningVisual(rarity, cardId, collectionId, catalog, finishVisual) {
let effect = resolveOpeningEffect(catalog, rarity);
let particlePreset = catalog?.particlePresets.find((candidate) => candidate.id === effect?.particlePresetId) || null;
let particlePalette = catalog?.particlePalettes?.find((candidate) => candidate.id === particlePreset?.paletteId);
// Ouverture mythique : forme et palette réglées par carte, collection ou défaut, sur le preset mythique de base.
if (rarity === "mythic") {
const style = resolveMythicOpeningStyle(catalog, cardId, collectionId);
effect = style.effect;
if (style.basePreset) {
particlePreset = { ...style.basePreset, shapeId: style.shape.id, paletteId: style.palette.id };
particlePalette = style.palette.id === MATCH_HOLO_PALETTE_ID
? (finishVisual.palette ? { id: MATCH_HOLO_PALETTE_ID, label: MATCH_HOLO_PALETTE_LABEL, colors: finishVisual.palette.colors } : catalog?.particlePalettes?.find((candidate) => candidate.id === style.basePreset.paletteId))
: catalog?.particlePalettes?.find((candidate) => candidate.id === style.palette.id);
}
}
const particleShape = catalog?.particleShapes?.find((candidate) => candidate.id === particlePreset?.shapeId);
// Une aura irisée (plusieurs couleurs) suit la palette des particules : la couronne, son halo et la lueur de la carte
// prennent les mêmes teintes que l'explosion. Les auras unies des autres raretés gardent leur couleur du catalogue.
const auraColors = effect?.auraColors?.length > 1 && particlePalette?.colors?.length > 1
? particlePalette.colors
: effect?.auraColors || [];
return {
effect,
particlePreset,
particleShape,
particlePalette,
auraColors,
auraDurationMs: effect?.auraDurationMs || 0,
particleDurationMs: effect?.particleDurationMs || (particlePreset ? 800 : 0)
};
}
function particlePosition(index, count, intense, color) {
const angle = (Math.PI * 2 * index / count) - Math.PI / 2;
const ringOffset = (index % 4) * (intense ? 18 : 12);
const distance = (intense ? 190 : 142) + ringOffset;
return {
"--x": `${Math.cos(angle) * distance}px`,
"--y": `${Math.sin(angle) * distance}px`,
"--particle-angle": `${angle}rad`,
"--particle-delay": `${(index % 6) * 18}ms`,
"--particle-color": color
};
}
function CardFace({ entry, quantity, visual, size }) {
const { card, edition } = entry;
const finishIds = edition.finishIds || [];
const showName = size !== "sm";
// Pleine illustration : l'image remplit la carte et seul le nom reste, gravé par-dessus.
const fullArt = visual.layout !== STANDARD_CARD_LAYOUT;
const showDetails = size === "lg" && !fullArt;
const image = (fullArt && card.fullImage) || card.image;
return <div
className="nebula-card-face"
data-card-layout={visual.layout}
data-rarity={edition.rarity}
data-finish={finishIds.join(" ")}
data-holo-effect={visual.effectPreset?.id}
data-holo-palette={visual.palette?.id}
>
<div className={`nebula-card-art ${image ? "has-image" : ""}`} aria-hidden="true">{image ? <img src={image} alt="" loading={size === "lg" ? "eager" : "lazy"} decoding="async" /> : <span className="nebula-card-placeholder-mark" />}</div>
{showName && <h3><span>{card.name}</span></h3>}
{showDetails && <div className="nebula-card-copy">
<p>{card.description}</p>
{edition.rarity === "mythic" && <span className="nebula-card-finish">{visual.finishLabel}</span>}
</div>}
{size === "md" && quantity > 0 && <span className="nebula-card-quantity" aria-label={`${quantity} exemplaires`}>×{quantity}</span>}
<RaritySymbol rarity={edition.rarity} label={edition.rarity} />
{visual.effectPreset && <>
<span className="nebula-card-holo-layer nebula-card-holo-primary" aria-hidden="true" />
<span className="nebula-card-holo-layer nebula-card-holo-secondary" aria-hidden="true" />
</>}
<span className="nebula-card-glare" aria-hidden="true" />
</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 }) {
const cardSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
const rarity = entry.edition?.rarity || "common";
const finish = entry.edition?.finishIds?.join(" ") || "standard";
const visual = resolveFinishVisual(entry.edition, catalog);
const openingVisual = resolveOpeningVisual(rarity, entry.card.id, entry.card.collectionId, catalog, visual);
// Les particules n'existent que pendant l'ouverture : une carte face visible n'en déclare aucune.
const displayedParticlePreset = faceUp ? null : openingVisual.particlePreset;
const displayedParticleShape = faceUp ? null : openingVisual.particleShape;
const displayedParticlePalette = faceUp ? null : openingVisual.particlePalette;
const particleColors = openingVisual.particlePalette?.colors || [];
const particleGradient = particleColors.length > 1
? `conic-gradient(from 0deg, ${[...particleColors, particleColors[0]].join(", ")})`
: particleColors[0];
const [revealPhase, setRevealPhase] = useState(revealed ? "revealed" : "concealed");
const previousRevealedRef = useRef(revealed);
const mountedRef = useRef(false);
const onRevealCompleteRef = useRef(onRevealComplete);
const visualAttributes = {
"data-holo-effect": visual.effectPreset?.id,
"data-holo-palette": visual.palette?.id,
"data-particle-preset": displayedParticlePreset?.id,
"data-particle-shape": displayedParticleShape?.id,
"data-particle-palette": displayedParticlePalette?.id,
"data-opening-effect": faceUp ? undefined : openingVisual.effect?.id,
style: {
...visual.style,
"--opening-aura": openingVisual.auraColors[0],
"--opening-aura-secondary": openingVisual.auraColors[1] || "transparent",
"--opening-aura-tertiary": openingVisual.auraColors[2] || "transparent",
"--opening-aura-quaternary": openingVisual.auraColors[3] || "transparent",
"--opening-aura-gradient": openingVisual.auraColors.length > 1
? `conic-gradient(from 15deg, ${[...openingVisual.auraColors, openingVisual.auraColors[0]].join(", ")})`
: undefined,
"--opening-aura-duration": `${openingVisual.auraDurationMs}ms`,
"--opening-particle-duration": `${openingVisual.particleDurationMs}ms`,
"--particle-primary": particleColors[0],
"--particle-gradient": particleGradient
}
};
const cardRef = useCardTilt();
useEffect(() => {
onRevealCompleteRef.current = onRevealComplete;
}, [onRevealComplete]);
useEffect(() => {
if (!mountedRef.current) {
mountedRef.current = true;
return undefined;
}
if (previousRevealedRef.current === revealed) return undefined;
previousRevealedRef.current = revealed;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const timers = [];
if (!revealed) {
if (reducedMotion) {
queueMicrotask(() => setRevealPhase("concealed"));
} else {
queueMicrotask(() => setRevealPhase("concealing"));
timers.push(window.setTimeout(() => setRevealPhase("concealed"), 600));
}
return () => timers.forEach((timer) => window.clearTimeout(timer));
}
if (reducedMotion) {
queueMicrotask(() => {
setRevealPhase("revealed");
onRevealCompleteRef.current?.();
});
return undefined;
}
const auraDuration = openingVisual.auraDurationMs;
const revealDuration = Math.max(600, openingVisual.particleDurationMs);
queueMicrotask(() => setRevealPhase(auraDuration ? "aura" : "revealing"));
if (auraDuration) timers.push(window.setTimeout(() => setRevealPhase("revealing"), auraDuration));
timers.push(window.setTimeout(() => {
setRevealPhase("revealed");
onRevealCompleteRef.current?.();
}, auraDuration + revealDuration));
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [revealed, 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"}`}>
<span className="nebula-card-tilt-surface"><CollectionCardBack collection={backCollection} /></span>
</article>;
}
if (!faceUp) {
const hasAuraPalette = openingVisual.auraColors.length > 1;
const locked = ["aura", "revealing", "concealing"].includes(revealPhase);
const faceVisible = ["revealing", "revealed"].includes(revealPhase);
const particlesVisible = faceVisible && rarity !== "common" && openingVisual.particlePreset;
const ariaLabel = revealPhase === "revealed"
? (replayable ? `Remettre ${revealLabel} face cachée` : `${entry.card.name} révélée`)
: `Révéler ${revealLabel}`;
return <button
ref={cardRef}
className={`nebula-card nebula-card-reveal ${faceVisible ? "is-revealed" : ""}`}
data-card-size={cardSize}
data-card-layout={visual.layout}
data-rarity={rarity}
data-finish={finish}
data-reveal-phase={revealPhase}
data-aura-palette={hasAuraPalette || undefined}
{...visualAttributes}
type="button"
disabled={disabled || (revealPhase === "revealed" && !replayable)}
aria-disabled={disabled || locked || (revealPhase === "revealed" && !replayable) || undefined}
data-reveal-locked={locked || undefined}
aria-label={ariaLabel}
onClick={() => {
if (locked || disabled) return;
if (revealPhase === "revealed") onConceal?.();
else onReveal?.();
}}
>
<span className="nebula-card-tilt-surface">
<span className="nebula-card-inner">
{hasAuraPalette && <><span className="nebula-card-glow-palette" data-side="back" aria-hidden="true" /><span className="nebula-card-glow-palette" data-side="face" aria-hidden="true" /></>}
<span
className="nebula-card-back"
data-has-image={backCollection?.back?.image ? "true" : undefined}
style={backCollection?.back?.image ? { "--card-back-image": `url("${backCollection.back.image}")` } : undefined}
><CollectionCardBack collection={backCollection} /></span>
<CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} />
</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></>}
{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>;
}
const content = <div className="nebula-card-tilt-surface"><CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} /></div>;
return onSelect
? <button ref={cardRef} className="nebula-card nebula-card-select" data-card-size={cardSize} data-card-layout={visual.layout} data-rarity={rarity} data-finish={finish} {...visualAttributes} type="button" onClick={onSelect} aria-label={selectLabel || `Voir ${entry.card.name}`} aria-pressed={selected}>{content}</button>
: <article ref={cardRef} className="nebula-card" data-card-size={cardSize} data-card-layout={visual.layout} data-rarity={rarity} data-finish={finish} {...visualAttributes}>{content}</article>;
}
export { RaritySymbol };