Group Sokko TCG's interface files by Guild quest and card rendering

The 48 files of the Daily Card, Expeditions, Daily Team and race, Broken
Mirror and card rendering move to daily/, expeditions/, team/, mirror/ and
rendering/ under website/src/features/cards, with every relative import
rewritten. The root keeps the page, server calls, cache and the player
sections outside the Guild. The cards README, the quest recipe and the
current docs follow the new paths; dated audits and plans keep theirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-12-01 11:35:18 +01:00
parent 863050437f
commit 88c7bf8317
74 changed files with 165 additions and 161 deletions

View file

@ -0,0 +1,24 @@
/**
* @file Rend le dos visuel partagé d'une collection pour les paquets et cartes inconnues.
*/
const SYMBOLS = {
star: <path d="M24 5 28 20 43 24 28 28 24 43 20 28 5 24 20 20Z" />,
rift: <><path d="M10 35C18 18 28 12 39 9" /><path d="M9 40C22 36 31 27 39 12" /></>,
orbit: <><ellipse cx="24" cy="24" rx="19" ry="9" /><path d="M24 12 27 21 36 24 27 27 24 36 21 27 12 24 21 21Z" /></>
};
export function CollectionCardBack({ collection }) {
const back = collection?.back || { primary: "#7c3aed", secondary: "#312e81", symbol: "star" };
return <span
className="nebula-collection-back"
data-back-symbol={back.symbol}
data-has-image={back.image ? "true" : undefined}
style={{ "--pack-primary": back.primary, "--pack-secondary": back.secondary }}
>
{back.image
? <img className="nebula-collection-back-image" src={back.image} alt="" aria-hidden="true" />
: <><span className="nebula-collection-back-rings" aria-hidden="true" /><svg viewBox="0 0 48 48" aria-hidden="true">{SYMBOLS[back.symbol] || SYMBOLS.star}</svg></>}
{collection?.name && <span className="nebula-collection-back-copy"><strong>{collection.name}</strong></span>}
</span>;
}

View file

@ -0,0 +1,507 @@
/**
* @file Rendu d'une carte de Sokko TCG, partout dans le jeu : face et dos, rareté, inclinaison au survol,
* finitions holographiques, parallaxe, particules mythiques et animations de révélation.
*
* Contexte : composant le plus partagé du TCG. Il résout le visuel d'une édition depuis le catalogue publié
* (finition, effet d'ouverture, particules) et délègue les particules aux moteurs Canvas 2D (holo*.js).
* Points d'entrée : `NebulaCard` (props principales : `catalog`, `entry` = `{ card, edition }`, `size` = `sm` |
* `md` | `lg`, `faceUp`, `onReveal`, `onSelect`) ; `RarityGlyph`, `RaritySymbol`.
* Utilisé par : la plupart des panneaux joueur et de l'administration (paquets, album, expéditions, équipe…).
* Dépend de : holoFlares.js, holoFireflies.js, holoLightning.js, holoTwinkle.js, openingEffects.js,
* CollectionCardBack.jsx ; styles dans website/src/styles/_nebula-cards.scss.
* Attention :
* - Coût d'affichage : les particules ne tournent qu'en `lg` ou au survol, quand la carte est visible et que
* l'onglet est actif ; `prefers-reduced-motion` coupe le mouvement.
* - Une carte de destination s'affiche en pleine illustration, avec un autre habillage.
* @see DESIGN_SYSTEM.md
*/
import { useEffect, useId, useRef, useState } from "react";
import { CollectionCardBack } from "./CollectionCardBack.jsx";
import { resolveFlare } from "./holoFlares.js";
import { createFireflies } from "./holoFireflies.js";
import { createLightning } from "./holoLightning.js";
import { createTwinkle } from "./holoTwinkle.js";
import { MATCH_HOLO_PALETTE_ID, MATCH_HOLO_PALETTE_LABEL, resolveMythicOpeningStyle, resolveOpeningEffect } from "./openingEffects.js";
const STANDARD_CARD_LAYOUT = "standard";
// Effets holographiques qui découpent l'illustration en calques de parallaxe (décor, puis héros détouré).
const PARALLAX_EFFECTS = new Set(["prismatic-backdrop"]);
// Effets holographiques à facettes : chaque groupe d'éclats de la mosaïque capte la lumière sous un angle qui lui est propre.
const SHARD_EFFECTS = new Set(["shattered-ice"]);
const SHARD_FACETS = [0, 1, 2, 3];
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)}%`);
// Tilt normalisé (-1 à 1) : +1 quand le pointeur est au bord droit ou au bord bas. Les calques de parallaxe s'en servent.
card.style.setProperty("--card-tilt-nx", (current.y / 5).toFixed(3));
card.style.setProperty("--card-tilt-ny", (-current.x / 4).toFixed(3));
// É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;
}
// Calques de parallaxe, deux au plus : le décor sans le héros puis le héros détouré. `depth` vaut 1 au fond, 0 au plan de la
// carte et devient négatif devant. Sans plaque de décor, le composite la remplace (mode de compatibilité) ; sans héros détouré,
// l'illustration reste un seul plan immobile, qui garde le prisme de la palette.
function resolveParallaxLayers(card, fullArt, compositeImage) {
const cutout = fullArt ? card.fullCutoutImage : card.cutoutImage;
const backdrop = fullArt ? card.fullBackdropImage : card.backdropImage;
if (!cutout) return compositeImage ? { setup: "flat", layers: [{ id: "backdrop", role: "backdrop", depth: 0, src: compositeImage }] } : null;
return {
setup: backdrop ? "clean" : "compat",
layers: [
{ id: "backdrop", role: "backdrop", depth: 1, src: backdrop || compositeImage },
{ id: "subject", role: "subject", depth: -0.2, src: cutout }
]
};
}
// Symbole céleste d'une rareté, seul : l'appelant fixe sa taille et son nom accessible. Celui d'une mythique porte le prisme.
function RarityGlyph({ rarity }) {
const gradientId = useId();
const prism = rarity === "mythic" ? `url("#${gradientId}") currentColor` : undefined;
return <svg className="nebula-rarity-glyph" data-rarity={rarity} viewBox="0 0 32 32" aria-hidden="true" style={prism && { fill: prism, stroke: prism }}>
{prism && <defs><linearGradient id={gradientId} gradientUnits="userSpaceOnUse" x1="4" y1="4" x2="28" y2="28">
{["gold", "pink", "violet", "mint"].map((tint, index) => <stop key={tint} offset={index / 3} style={{ stopColor: `var(--color-prism-${tint})` }} />)}
</linearGradient></defs>}
{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>;
}
function RaritySymbol({ rarity, label }) {
return <span className="nebula-card-rarity-symbol" data-rarity={rarity} title={label}>
<RarityGlyph rarity={rarity} />
<span className="sr-only">{label}</span>
</span>;
}
// Carte de destination : toujours en pleine illustration (son paysage remplit la carte), quelle que soit sa finition.
function destinationVisual(card, visual) {
return card?.kind === "destination" ? { ...visual, layout: "full-art" } : visual;
}
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
};
}
// Moteur de chaque animation de particules persistantes ; tous partagent la même interface.
const FLARE_ENGINES = { lightning: createLightning, twinkle: createTwinkle, fireflies: createFireflies };
// Particules d'une variation mythique : un canvas dans l'illustration ou sur toute la face, animé seulement quand la carte
// est affichée en grand ou survolée, visible et dans un onglet actif. Sous mouvement réduit, une image fixe. Sur toute la
// face, les éclairs visent toujours l'illustration, dont la boîte est mesurée dans le canvas.
function HoloFlareCanvas({ flare, behindSubject, size }) {
const canvasRef = useRef(null);
const colorsKey = flare.colors.join(",");
useEffect(() => {
const canvas = canvasRef.current;
const card = canvas?.closest(".nebula-card");
if (!canvas || !card) return undefined;
const engine = FLARE_ENGINES[flare.effect.id](canvas, { colors: colorsKey.split(","), core: flare.core, intensity: flare.intensity, level: flare.level, count: flare.count, motifId: flare.motifId, behindSubject });
const resize = () => {
const art = flare.scope === "card" ? canvas.parentElement?.querySelector(".nebula-card-art") : null;
const focus = art ? { x: art.offsetLeft, y: art.offsetTop, width: art.offsetWidth, height: art.offsetHeight } : null;
engine.resize(canvas.offsetWidth, canvas.offsetHeight, Math.min(2, window.devicePixelRatio || 1), focus);
};
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(canvas);
resize();
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
engine.renderStatic();
return () => { resizeObserver.disconnect(); engine.destroy(); };
}
let hovered = false;
let visible = true;
const update = () => engine.setActive(visible && !document.hidden && (size === "lg" || hovered));
const enter = () => { hovered = true; update(); };
const leave = () => { hovered = false; engine.setPointer(null); update(); };
const move = (event) => {
const bounds = canvas.getBoundingClientRect();
engine.setPointer({ x: (event.clientX - bounds.left) / bounds.width, y: (event.clientY - bounds.top) / bounds.height });
};
const intersection = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; update(); });
intersection.observe(canvas);
card.addEventListener("pointerenter", enter);
card.addEventListener("pointerleave", leave);
card.addEventListener("pointermove", move);
card.addEventListener("focus", enter);
card.addEventListener("blur", leave);
document.addEventListener("visibilitychange", update);
update();
return () => {
resizeObserver.disconnect();
intersection.disconnect();
card.removeEventListener("pointerenter", enter);
card.removeEventListener("pointerleave", leave);
card.removeEventListener("pointermove", move);
card.removeEventListener("focus", enter);
card.removeEventListener("blur", leave);
document.removeEventListener("visibilitychange", update);
engine.destroy();
};
}, [colorsKey, flare.effect.id, flare.core, flare.intensity, flare.level, flare.count, flare.motifId, flare.scope, behindSubject, size]);
return <canvas ref={canvasRef} className="nebula-card-flare" data-flare={flare.effect.id} data-flare-scope={flare.scope} data-behind-subject={behindSubject || undefined} aria-hidden="true" />;
}
function CardFace({ entry, quantity, visual, size, flare = null }) {
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;
const parallax = PARALLAX_EFFECTS.has(visual.effectPreset?.id) ? resolveParallaxLayers(card, fullArt, image) : null;
const loading = size === "lg" ? "eager" : "lazy";
// Dans l'illustration, derrière un héros détouré, les éclairs passent entre le décor et lui ; scintillements et lucioles,
// eux, restent devant pour être vus. Sur toute la carte, les particules couvrent la face sous le texte, devant le héros.
const cardScope = flare?.scope === "card";
const behindSubject = Boolean(flare?.effect.id === "lightning" && !cardScope && parallax && parallax.layers.length > 1);
const flareCanvas = flare && <HoloFlareCanvas flare={flare} behindSubject={behindSubject} size={size} />;
const artFlare = cardScope ? null : flareCanvas;
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" : ""}`} data-parallax-setup={parallax?.setup} aria-hidden="true">
{/* Chaque calque porte sa profondeur ; son image sert aussi de masque au reflet prismatique qui ne touche que lui. */}
{parallax ? parallax.layers.flatMap((layer, index) => [layer.role === "subject" && behindSubject && artFlare ? <span key="flare" className="nebula-card-flare-plane">{artFlare}</span> : null, <span
key={layer.id}
className="nebula-card-depth-layer"
data-depth-layer={layer.id}
data-depth-role={layer.role}
style={{ "--layer-depth": layer.depth, "--layer-depth-abs": Math.abs(layer.depth), "--layer-index": index, "--layer-image": `url("${layer.src}")`, zIndex: index * 2 }}
>
<img src={layer.src} alt="" loading={loading} decoding="async" />
{layer.role === "backdrop" && <span className="nebula-card-depth-tint" />}
<span className="nebula-card-depth-foil" />
</span>]) : image ? <img src={image} alt="" loading={loading} decoding="async" /> : <span className="nebula-card-placeholder-mark" />}
{!behindSubject && artFlare}
</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" || size === "sm") && 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" />
{SHARD_EFFECTS.has(visual.effectPreset.id) && <span className="nebula-card-holo-layer nebula-card-holo-shards" aria-hidden="true">
{SHARD_FACETS.map((facet) => <i key={facet} data-facet={facet} />)}
</span>}
</>}
{cardScope && flareCanvas}
<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, newBadge = 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 = destinationVisual(entry.card, resolveFinishVisual(entry.edition, catalog));
const flare = resolveFlare(entry.edition, catalog, visual);
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,
// Paliers de la variation (intensité de la palette, palier propre à l'effet) : le palier central n'a pas d'attribut.
"data-holo-intensity": visual.effectPreset ? entry.edition?.holoIntensity : undefined,
"data-holo-level": visual.effectPreset?.level ? entry.edition?.holoLevel : undefined,
"data-flare": flare?.effect.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${newBadge ? ", nouvelle carte" : ""}`)
: `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} flare={revealPhase === "revealed" ? flare : null} />
</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></>}
{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} flare={flare} /></div>;
return onSelect
? <button ref={cardRef} className="nebula-card nebula-card-select" data-card-size={cardSize} data-card-layout={visual.layout} data-card-kind={entry.card.kind} 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-card-kind={entry.card.kind} data-rarity={rarity} data-finish={finish} {...visualAttributes}>{content}</article>;
}
export { RarityGlyph, RaritySymbol };

View file

@ -0,0 +1,204 @@
/**
* @file Ressources communes des particules persistantes : sprites des motifs (scintillements, lucioles),
* silhouettes procédurales de rayon 1 rendues une fois par couleur avec halo et cœur clair puis
* recopiées à chaque image, gardées dans un cache partagé entre toutes les cartes ; et surface de
* dessin d'un canvas réservée seulement pendant l'animation.
*/
const TAU = Math.PI * 2;
export const SPRITE_SIZE = 96;
// Angle d'affichage d'un motif. La bulle ne tourne jamais : son reflet reste en haut à droite, comme la lumière qui
// l'éclaire. Le cœur reste à l'endroit, à peine incliné. Les autres motifs prennent l'angle libre qu'on leur donne.
export function motifAngle(motifId, angle) {
if (motifId === "bubble") return 0;
if (motifId === "heart") return Math.sin(angle) * 0.25;
return angle;
}
// Silhouette d'un motif centrée sur l'origine, de rayon 1 ; `stroke` pour les motifs en traits.
function motifPath(context, motifId) {
context.beginPath();
if (motifId === "four-point-star" || motifId === "glint") {
const k = motifId === "glint" ? 0.06 : 0.16;
context.moveTo(0, -1);
context.quadraticCurveTo(k, -k, 1, 0);
context.quadraticCurveTo(k, k, 0, 1);
context.quadraticCurveTo(-k, k, -1, 0);
context.quadraticCurveTo(-k, -k, 0, -1);
} else if (motifId === "star") {
for (let index = 0; index < 10; index++) {
const radius = index % 2 ? 0.45 : 1;
const angle = -Math.PI / 2 + (index * Math.PI) / 5;
context.lineTo(Math.cos(angle) * radius, Math.sin(angle) * radius);
}
context.closePath();
} else if (motifId === "diamond") {
context.moveTo(0, -1);
context.lineTo(0.62, 0);
context.lineTo(0, 1);
context.lineTo(-0.62, 0);
context.closePath();
} else if (motifId === "heart") {
context.moveTo(0, 0.9);
context.bezierCurveTo(-1.1, 0.1, -0.85, -0.85, 0, -0.35);
context.bezierCurveTo(0.85, -0.85, 1.1, 0.1, 0, 0.9);
} else if (motifId === "snowflake") {
for (let arm = 0; arm < 6; arm++) {
const angle = (arm * Math.PI) / 3;
const point = (radius, offset = 0) => [Math.cos(angle + offset) * radius, Math.sin(angle + offset) * radius];
context.moveTo(0, 0);
context.lineTo(...point(1));
context.moveTo(...point(0.55));
context.lineTo(...point(0.8, 0.32));
context.moveTo(...point(0.55));
context.lineTo(...point(0.8, -0.32));
}
} else if (motifId === "firefly") {
context.arc(0, 0, 0.55, 0, TAU);
} else {
context.arc(0, 0, 1, 0, TAU);
}
}
// Bulle : une sphère translucide (voile coloré et contour lumineux) avec son reflet clair décalé en haut à droite, aux
// bords à peine adoucis par un dégradé (un filtre de flou n'est pas pris en charge partout sur un canvas).
function bubble(context, radius, color, core) {
context.save();
context.scale(radius, radius);
context.beginPath();
context.arc(0, 0, 1, 0, TAU);
context.globalAlpha = 0.28;
context.fillStyle = color;
context.fill();
context.globalAlpha = 1;
context.lineWidth = 0.09;
context.strokeStyle = color;
context.shadowColor = color;
context.shadowBlur = 6;
context.stroke();
context.shadowBlur = 0;
const highlight = context.createRadialGradient(0.36, -0.36, 0, 0.36, -0.36, 0.3);
highlight.addColorStop(0, core);
highlight.addColorStop(0.75, core);
highlight.addColorStop(1, "transparent");
context.globalAlpha = 0.9;
context.fillStyle = highlight;
context.beginPath();
context.arc(0.36, -0.36, 0.3, 0, TAU);
context.fill();
context.restore();
}
// Sprite d'un motif dans une couleur : halo, silhouette colorée lumineuse, puis cœur clair. Rendu une seule fois (le flou y
// est permis), puis seulement recopié à chaque image.
function drawMotifSprite(motifId, color, core) {
const canvas = document.createElement("canvas");
canvas.width = SPRITE_SIZE;
canvas.height = SPRITE_SIZE;
const context = canvas.getContext("2d");
const half = SPRITE_SIZE / 2;
const halo = context.createRadialGradient(half, half, 0, half, half, half);
halo.addColorStop(0, color);
halo.addColorStop(0.2, color);
// La luciole rayonne plus loin que les motifs dessinés.
halo.addColorStop(motifId === "firefly" ? 1 : 0.75, "transparent");
// La luciole est surtout un halo : petit cœur, large lueur.
context.globalAlpha = motifId === "bubble" ? 0.3 : motifId === "firefly" ? 0.8 : 0.55;
context.fillStyle = halo;
context.fillRect(0, 0, SPRITE_SIZE, SPRITE_SIZE);
context.globalAlpha = 1;
context.translate(half, half);
if (motifId === "bubble") {
bubble(context, half * 0.34, color, core);
return canvas;
}
const stroked = motifId === "snowflake";
for (const [scale, style, blur, width] of [[0.34, color, 10, 0.16], [0.2, core, 4, 0.1]]) {
context.save();
context.scale(half * scale, half * scale);
context.shadowColor = color;
context.shadowBlur = blur;
motifPath(context, motifId);
if (stroked) {
context.lineCap = "round";
context.lineWidth = width;
context.strokeStyle = style;
context.stroke();
} else {
context.fillStyle = style;
context.fill();
}
context.restore();
}
return canvas;
}
// Éclat en croix de l'apogée : deux traits fins dégradés, clairs au centre.
function drawStreakSprite(color, core) {
const canvas = document.createElement("canvas");
canvas.width = SPRITE_SIZE * 2;
canvas.height = SPRITE_SIZE * 2;
const context = canvas.getContext("2d");
const size = SPRITE_SIZE * 2;
for (const vertical of [false, true]) {
const gradient = vertical ? context.createLinearGradient(0, 0, 0, size) : context.createLinearGradient(0, 0, size, 0);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(0.4, color);
gradient.addColorStop(0.5, core);
gradient.addColorStop(0.6, color);
gradient.addColorStop(1, "transparent");
context.fillStyle = gradient;
const thickness = vertical ? 4 : 5;
if (vertical) context.fillRect(size / 2 - thickness / 2, size * 0.18, thickness, size * 0.64);
else context.fillRect(0, size / 2 - thickness / 2, size, thickness);
}
return canvas;
}
// Cache partagé : une grille de cartes mythiques réutilise les mêmes sprites au lieu d'en refaire par carte. Borné, les plus
// anciens partent d'abord.
const SPRITE_CACHE_LIMIT = 160;
const spriteCache = new Map();
function cached(key, build) {
if (!spriteCache.has(key)) {
if (spriteCache.size >= SPRITE_CACHE_LIMIT) spriteCache.delete(spriteCache.keys().next().value);
spriteCache.set(key, build());
}
return spriteCache.get(key);
}
export const motifSprite = (motifId, color, core) => cached(`motif|${motifId}|${color}|${core}`, () => drawMotifSprite(motifId, color, core));
export const streakSprite = (color, core) => cached(`streak|${color}|${core}`, () => drawStreakSprite(color, core));
// Surface de dessin d'un canvas : réservée (largeur x hauteur x densité de pixels) seulement quand le moteur anime ou fige une
// image, libérée (0 x 0) au repos. Une grille de cartes au repos ne garde ainsi aucun pixel en mémoire.
export function canvasBacking(canvas) {
let size = { width: 0, height: 0, ratio: 1 };
let attached = false;
const attach = () => {
const width = Math.max(1, Math.round(size.width * size.ratio));
const height = Math.max(1, Math.round(size.height * size.ratio));
if (attached && canvas.width === width && canvas.height === height) return;
canvas.width = width;
canvas.height = height;
attached = true;
};
const release = () => {
canvas.width = 0;
canvas.height = 0;
attached = false;
};
release();
return {
resize(width, height, ratio) {
size = { width, height, ratio };
if (attached) {
attached = false;
attach();
}
},
attach,
release
};
}

View file

@ -0,0 +1,212 @@
/**
* @file Moteur des lucioles holographiques d'une carte mythique (Canvas 2D) : de petites lueurs qui flottent
* sur des trajectoires sinueuses, pulsent doucement, apparaissent et s'éteignent en chemin, et
* s'écartent du pointeur. Nombre moyen, vitesse et intensité réglables ; motifs partagés avec les
* scintillements ; temps réel ; aucune boucle au repos. Même interface que les autres moteurs de
* particules.
*/
import { canvasBacking, motifAngle, motifSprite, SPRITE_SIZE } from "./flareSprites.js";
const TAU = Math.PI * 2;
// Les motifs proposés (identifiants et libellés) sont déclarés par le catalogue (`flareEffects`).
// Paliers 1 à 5 : nombre moyen de lucioles (illustration d'une carte `lg`), vitesse de vol en fraction de la largeur par
// seconde (et durée de vie qui raccourcit avec elle), intensité (taille et éclat).
export const FIREFLY_COUNTS = [4, 6, 8, 12, 16];
const SPEED = [0.03, 0.045, 0.065, 0.09, 0.125];
const LIFETIME_MS = [8000, 6800, 5600, 4600, 3800];
const INTENSITY_SCALE = [0.6, 0.75, 0.9, 1.1, 1.35];
const REFERENCE_AREA = 280 * 240;
// Quand la carte n'est plus survolée, les motifs encore en vie s'effacent ensemble en une demi-seconde au lieu de finir leur
// vie : l'animation s'arrête vite au lieu de tourner plusieurs secondes pour rien.
const OUTRO_MS = 500;
// Opacité selon l'âge relatif : apparition sur 20 % de la vie, extinction sur les 25 derniers.
export function fireflyFade(t) {
if (t <= 0 || t >= 1) return 0;
if (t < 0.2) return t / 0.2;
if (t > 0.75) return (1 - t) / 0.25;
return 1;
}
// Cap d'une luciole : une direction de base que deux sinusoïdes de fréquences et phases propres font onduler.
export function fireflyHeading(firefly, seconds) {
return firefly.heading + Math.sin(seconds * firefly.wobble[0] + firefly.phase[0]) * 1.1 + Math.sin(seconds * firefly.wobble[1] + firefly.phase[1]) * 0.6;
}
export function createFireflies(canvas, options) {
const context = canvas.getContext("2d");
const backing = canvasBacking(canvas);
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let sprites = [];
let flies = [];
let pointer = null;
let active = false;
let frame = 0;
let last = 0;
let nextSpawn = 0;
let leftAt = 0;
let fade = 1;
let destroyed = false;
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const lifetime = () => LIFETIME_MS[(settings.level || 3) - 1];
const speed = () => SPEED[(settings.level || 3) - 1] * size.width;
const areaFactor = () => Math.min(1.6, Math.max(0.3, (size.width * size.height) / REFERENCE_AREA));
const average = () => FIREFLY_COUNTS[(settings.count || 3) - 1] * areaFactor();
const sizeFactor = () => Math.min(1.2, Math.max(0.5, Math.min(size.width, size.height) / 240));
function buildSprites() {
sprites = settings.colors.map((color) => motifSprite(settings.motifId || "firefly", color, settings.core || "#ffffff"));
}
// `age` (0 à 1) permet de semer une première volée déjà en vol, pour qu'elles n'apparaissent pas toutes ensemble.
function spawn(now, age = 0) {
const life = lifetime() * (0.75 + random() * 0.5);
flies.push({
x: (0.08 + random() * 0.84) * size.width,
y: (0.1 + random() * 0.82) * size.height,
born: now - age * life,
life,
// Légère tendance à monter, comme une lueur portée par l'air chaud.
heading: -Math.PI / 2 + (random() - 0.5) * 2.6,
wobble: [0.35 + random() * 0.5, 0.9 + random() * 0.9],
phase: [random() * TAU, random() * TAU],
pulse: [1.4 + random() * 1.6, random() * TAU],
speed: 0.7 + random() * 0.6,
radius: (6 + random() ** 2 * 6) * intensity() * sizeFactor(),
color: Math.floor(random() * settings.colors.length),
rotation: random() * TAU
});
nextSpawn = now + (lifetime() / average()) * (0.5 + random());
}
function move(fly, now, elapsed) {
const seconds = now / 1000;
const heading = fireflyHeading(fly, seconds);
let vx = Math.cos(heading) * speed() * fly.speed;
let vy = Math.sin(heading) * speed() * fly.speed;
// Près des bords, elles reviennent doucement vers l'intérieur.
const margin = 0.08;
if (fly.x < size.width * margin) vx += speed();
if (fly.x > size.width * (1 - margin)) vx -= speed();
if (fly.y < size.height * margin) vy += speed();
if (fly.y > size.height * (1 - margin)) vy -= speed();
// Elles s'écartent du pointeur qui s'approche.
if (pointer) {
const dx = fly.x - pointer.x * size.width;
const dy = fly.y - pointer.y * size.height;
const distance = Math.hypot(dx, dy) || 1;
const reach = size.width * 0.22;
if (distance < reach) {
const push = (1 - distance / reach) * speed() * 3;
vx += (dx / distance) * push;
vy += (dy / distance) * push;
}
}
fly.x += (vx * elapsed) / 1000;
fly.y += (vy * elapsed) / 1000;
}
function drawFly(fly, alpha, glow) {
const spriteSize = (fly.radius * 2 * SPRITE_SIZE) / (SPRITE_SIZE * 0.34) * (0.85 + 0.15 * glow);
context.save();
context.translate(fly.x, fly.y);
context.rotate(motifAngle(settings.motifId, fly.rotation));
context.globalAlpha = fade * alpha * (0.65 + 0.35 * glow);
context.drawImage(sprites[fly.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
context.restore();
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
const seconds = now / 1000;
for (const fly of flies) {
// Pulsation propre à chaque luciole : elle s'avive et se voile à son rythme.
const glow = 0.5 + 0.5 * Math.sin(seconds * fly.pulse[0] + fly.pulse[1]);
drawFly(fly, fireflyFade((now - fly.born) / fly.life), glow);
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
const elapsed = last ? Math.min(50, now - last) : 16;
last = now;
if (active && !flies.length) {
const count = Math.round(average());
for (let index = 0; index < count; index++) spawn(now, random() * 0.6);
}
while (active && now >= nextSpawn && flies.length < average() * 1.6) spawn(now);
flies = flies.filter((fly) => now - fly.born < fly.life);
fade = leftAt ? Math.max(0, 1 - (now - leftAt) / OUTRO_MS) : 1;
if (!fade) flies = [];
for (const fly of flies) move(fly, now, elapsed);
draw(now);
if (active || flies.length) frame = requestAnimationFrame(tick);
else {
last = 0;
backing.release();
}
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
// Sprites construits à la première animation (et pris dans le cache partagé) : une carte jamais survolée n'en crée pas.
return {
resize(width, height, ratio = 1) {
size = { width, height, ratio };
backing.resize(width, height, ratio);
flies = [];
if (active) schedule();
},
setActive(next) {
if (!next && active) leftAt = performance.now();
if (next) leftAt = 0;
if (next) {
if (!sprites.length) buildSprites();
backing.attach();
}
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
sprites = [];
},
// Mouvement réduit : quelques lueurs immobiles.
renderStatic() {
if (!size.width) return;
if (!sprites.length) buildSprites();
backing.attach();
flies = [];
const count = Math.max(2, Math.round(average() / 2));
for (let index = 0; index < count; index++) spawn(0);
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const fly of flies) drawFly(fly, 0.7, 0.6);
context.globalCompositeOperation = "source-over";
flies = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}

View file

@ -0,0 +1,70 @@
/**
* @file Particules persistantes d'une variation mythique (distinctes des particules d'ouverture) côté
* navigateur : réglages d'une édition (animation, motif, palette, zone, paliers) d'après les animations
* déclarées par le catalogue (`flareEffects`, `flareScopes`), champs d'édition pour un aperçu et
* comparaison de deux réglages. Les moteurs de rendu sont à part.
*/
export const DEFAULT_FLARE_TUNING = 3;
export const DEFAULT_FLARE_SCOPE = "art";
export const MATCH_HOLO_FLARE_PALETTE = "match-holo";
export const MATCH_HOLO_FLARE_LABEL = "Comme le holo";
export const NO_FLARE = { id: "", motifId: "", paletteId: MATCH_HOLO_FLARE_PALETTE, intensity: DEFAULT_FLARE_TUNING, level: DEFAULT_FLARE_TUNING, count: DEFAULT_FLARE_TUNING, scope: DEFAULT_FLARE_SCOPE };
const TUNING_FIELDS = { intensity: "flareIntensity", level: "flareLevel", count: "flareCount" };
const effectOf = (catalog, id) => catalog?.flareEffects?.find((item) => item.id === id);
// Motif retenu : celui choisi s'il appartient à l'animation, sinon le premier de sa liste ; aucun si elle n'a pas de motifs.
export const flareMotifOf = (effect, motifId) => (effect?.motifs ? (effect.motifs.some((item) => item.id === motifId) ? motifId : effect.motifs[0].id) : null);
// Champs portés par l'édition, comme le serveur les publie : les paliers centraux, le motif par défaut, la palette héritée et
// la zone par défaut ne sont pas transmis, ni les réglages que l'animation n'a pas.
export function flareEditionFields(flare, catalog) {
const effect = effectOf(catalog, flare?.id);
if (!effect) return {};
const motifId = flareMotifOf(effect, flare.motifId);
return {
flareId: effect.id,
...(motifId && motifId !== effect.motifs[0].id ? { flareMotifId: motifId } : {}),
...(flare.paletteId && flare.paletteId !== MATCH_HOLO_FLARE_PALETTE ? { flarePaletteId: flare.paletteId } : {}),
...(flare.scope && flare.scope !== DEFAULT_FLARE_SCOPE ? { flareScope: flare.scope } : {}),
...Object.fromEntries(effect.tunings.filter(({ key }) => flare[key] && flare[key] !== DEFAULT_FLARE_TUNING).map(({ key }) => [TUNING_FIELDS[key], flare[key]]))
};
}
// Réglages éditables d'une édition publiée (ou NO_FLARE), pour l'éditeur des variations.
export function flareOfEdition(edition, catalog) {
const effect = effectOf(catalog, edition?.flareId);
if (!effect) return NO_FLARE;
return {
id: effect.id,
motifId: flareMotifOf(effect, edition.flareMotifId) || "",
paletteId: edition.flarePaletteId || MATCH_HOLO_FLARE_PALETTE,
scope: edition.flareScope || DEFAULT_FLARE_SCOPE,
intensity: edition.flareIntensity || DEFAULT_FLARE_TUNING,
level: edition.flareLevel || DEFAULT_FLARE_TUNING,
count: edition.flareCount || DEFAULT_FLARE_TUNING
};
}
// Deux réglages se valent s'ils publient les mêmes champs.
export const sameFlare = (left, right, catalog) => JSON.stringify(flareEditionFields(left, catalog)) === JSON.stringify(flareEditionFields(right, catalog));
// Réglages affichés pour une édition, ou null : sans palette explicite, les particules prennent celle du holo.
export function resolveFlare(edition, catalog, finishVisual) {
const effect = effectOf(catalog, edition?.flareId);
if (!effect || !finishVisual?.effectPreset) return null;
const palette = edition.flarePaletteId ? catalog?.effectPalettes?.find((item) => item.id === edition.flarePaletteId) : finishVisual.palette;
if (!palette) return null;
const scope = catalog.flareScopes?.some((item) => item.id === edition.flareScope) ? edition.flareScope : DEFAULT_FLARE_SCOPE;
return {
effect,
motifId: flareMotifOf(effect, edition.flareMotifId),
colors: palette.colors,
core: palette.highlight,
intensity: edition.flareIntensity || DEFAULT_FLARE_TUNING,
level: edition.flareLevel || DEFAULT_FLARE_TUNING,
count: edition.flareCount || DEFAULT_FLARE_TUNING,
scope
};
}

View file

@ -0,0 +1,245 @@
/**
* @file Moteur des éclairs holographiques d'une carte mythique, dessinés sur un Canvas 2D posé dans
* l'illustration. Des éclairs fractals partent des bords, progressent vers un point libre autour du
* héros avec une pointe lumineuse, se ramifient, puis frappent dans un éclat bref avant de s'éteindre.
* Couleurs de la palette, temps réel (indépendant de la fréquence d'affichage), aucune boucle quand la
* carte est au repos.
*/
import { canvasBacking } from "./flareSprites.js";
const TAU = Math.PI * 2;
// Paliers 1 à 5 : intensité (épaisseur, halo, éclat d'impact) et fréquence (intervalle moyen entre deux éclairs, éclairs simultanés).
const INTENSITY_SCALE = [0.6, 0.8, 1, 1.25, 1.5];
const SPAWN_INTERVAL_MS = [1800, 1250, 850, 560, 360];
const MAX_BOLTS = [2, 2, 3, 3, 4];
const GROW_MS = [170, 260];
const HOLD_MS = 140;
const FADE_MS = [420, 620];
const IMPACT_MS = 320;
const between = (random, [min, max]) => min + random() * (max - min);
const pick = (random, items) => items[Math.floor(random() * items.length) % items.length];
// Tracé fractal par déplacement du point milieu : chaque subdivision décale le milieu perpendiculairement au segment, de
// moins en moins à chaque niveau. 2^depth segments (32 par défaut), extrémités conservées.
export function boltPath(start, end, random, { depth = 5, roughness = 0.24 } = {}) {
let points = [start, end];
let offset = Math.hypot(end.x - start.x, end.y - start.y) * roughness;
for (let level = 0; level < depth; level++) {
const next = [points[0]];
for (let index = 1; index < points.length; index++) {
const from = points[index - 1];
const to = points[index];
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy) || 1;
const shift = (random() - 0.5) * offset;
next.push({ x: (from.x + to.x) / 2 - (dy / length) * shift, y: (from.y + to.y) / 2 + (dx / length) * shift }, to);
}
points = next;
offset *= 0.55;
}
return points;
}
// Point d'arrivée tiré dans une zone ovale autour du centre de l'illustration, à une distance comprise entre `min` et `max`
// (fractions de la largeur et de la hauteur) : un éclair peut s'arrêter plus haut, plus à droite, ou dépasser le milieu.
function targetIn(center, width, height, random, [min, max]) {
const angle = random() * TAU;
const distance = min + Math.sqrt(random()) * (max - min);
return { x: center.x + Math.cos(angle) * width * distance, y: center.y + Math.sin(angle) * height * distance * 0.9 };
}
// Géométrie d'un éclair dans une zone width x height : départ sur une ellipse qui déborde des bords (le canvas coupe),
// arrivée en un point libre de la zone centrale de `focus` (la boîte de l'illustration dans le canvas, tout le canvas par
// défaut : sur toute la carte, les éclairs partent des bords de la carte et visent toujours le héros). Derrière un héros détouré, la zone va jusqu'au cœur : le héros le
// recouvre. Sans héros détouré, elle garde un petit vide au centre pour épargner son visage.
export const TARGET_ZONE = { behind: [0, 0.32], flat: [0.14, 0.38] };
export function boltGeometry(width, height, angle, random, { behindSubject = false, focus = null } = {}) {
const box = focus || { x: 0, y: 0, width, height };
const center = { x: box.x + box.width / 2, y: box.y + box.height * 0.48 };
const zone = behindSubject ? TARGET_ZONE.behind : TARGET_ZONE.flat;
const startAngle = angle + (random() - 0.5) * 0.9;
const start = { x: width / 2 + Math.cos(startAngle) * width * 0.66, y: height / 2 + Math.sin(startAngle) * height * 0.62 };
const end = targetIn(center, box.width, box.height, random, zone);
const main = boltPath(start, end, random);
// Une ou deux ramifications partent du premier tiers du tronc vers un autre point de la zone, sans l'atteindre : elles
// s'écartent du tronc puis s'éteignent en chemin.
const branches = [];
const branchCount = random() < 0.7 ? (random() < 0.35 ? 2 : 1) : 0;
for (let index = 0; index < branchCount; index++) {
const from = main[Math.floor(main.length * (0.25 + random() * 0.3))];
const aim = targetIn(center, box.width, box.height, random, zone);
const reach = 0.45 + random() * 0.25;
branches.push(boltPath(from, { x: from.x + (aim.x - from.x) * reach, y: from.y + (aim.y - from.y) * reach }, random, { depth: 4, roughness: 0.2 }));
}
return { center, main, branches };
}
function partialPath(context, points, fraction) {
const span = (points.length - 1) * Math.min(1, fraction);
const whole = Math.floor(span);
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for (let index = 1; index <= whole; index++) context.lineTo(points[index].x, points[index].y);
let tip = points[whole];
if (whole < points.length - 1) {
const next = points[whole + 1];
const rest = span - whole;
tip = { x: tip.x + (next.x - tip.x) * rest, y: tip.y + (next.y - tip.y) * rest };
context.lineTo(tip.x, tip.y);
}
return tip;
}
// Trois passes additives au lieu d'un `shadowBlur`, coûteux : halo large et pâle, gaine colorée, cœur clair.
function strokeBolt(context, points, fraction, { color, core, width, alpha }) {
const passes = [[width * 6, color, 0.2], [width * 2.6, color, 0.75], [width, core, 1]];
let tip = points[0];
for (const [lineWidth, strokeStyle, opacity] of passes) {
context.globalAlpha = alpha * opacity;
context.lineWidth = lineWidth;
context.strokeStyle = strokeStyle;
tip = partialPath(context, points, fraction);
context.stroke();
}
return tip;
}
function glow(context, x, y, radius, color, alpha) {
const gradient = context.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, color);
gradient.addColorStop(1, "transparent");
context.globalAlpha = alpha;
context.fillStyle = gradient;
context.beginPath();
context.arc(x, y, radius, 0, TAU);
context.fill();
}
export function createLightning(canvas, options) {
const context = canvas.getContext("2d");
const backing = canvasBacking(canvas);
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let bolts = [];
let impacts = [];
let pointer = null;
let active = false;
let frame = 0;
let nextSpawn = 0;
let destroyed = false;
const scale = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const level = () => (settings.level || 3) - 1;
function spawn(now) {
// Une fois sur deux, l'éclair vient du côté où se trouve le pointeur : la carte « répond » à la main qui la tient.
const angle = pointer && random() < 0.5
? Math.atan2(pointer.y - 0.48, pointer.x - 0.5) + (random() - 0.5) * 0.8
: random() * TAU;
const color = pick(random, settings.colors);
bolts.push({ ...boltGeometry(size.width, size.height, angle, random, settings), color, born: now, grow: between(random, GROW_MS), fade: between(random, FADE_MS), struck: false, width: (2 + random() * 1.2) * scale() });
nextSpawn = now + SPAWN_INTERVAL_MS[level()] * (0.6 + random() * 0.8);
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
const core = settings.core || "#ffffff";
for (const bolt of bolts) {
const age = now - bolt.born;
const fraction = age / bolt.grow;
const fading = age - bolt.grow - HOLD_MS;
// Pendant le maintien, l'éclair vacille ; ensuite il s'éteint.
const alpha = fading > 0 ? Math.max(0, 1 - fading / bolt.fade) : fraction >= 1 ? 0.7 + 0.3 * random() : 1;
const style = { color: bolt.color, core, width: bolt.width, alpha };
const tip = strokeBolt(context, bolt.main, fraction, style);
// Les ramifications naissent quand le tronc les atteint.
for (const branch of bolt.branches) strokeBolt(context, branch, Math.max(0, fraction * 1.3 - 0.35), { ...style, width: bolt.width * 0.55, alpha: alpha * 0.85 });
if (fraction < 1) glow(context, tip.x, tip.y, bolt.width * 7, core, 1);
if (fraction >= 1 && !bolt.struck) {
bolt.struck = true;
impacts.push({ x: tip.x, y: tip.y, color: bolt.color, born: now });
}
}
for (const impact of impacts) {
const progress = (now - impact.born) / IMPACT_MS;
glow(context, impact.x, impact.y, (10 + progress * 26) * scale(), impact.color, Math.max(0, 1 - progress));
glow(context, impact.x, impact.y, (4 + progress * 8) * scale(), core, Math.max(0, 1 - progress * 1.3));
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
if (active && now >= nextSpawn && bolts.length < MAX_BOLTS[level()]) spawn(now);
bolts = bolts.filter((bolt) => now - bolt.born < bolt.grow + HOLD_MS + bolt.fade);
impacts = impacts.filter((impact) => now - impact.born < IMPACT_MS);
draw(now);
// Au repos, on laisse les derniers éclairs s'éteindre puis la boucle s'arrête.
if (active || bolts.length || impacts.length) frame = requestAnimationFrame(tick);
else backing.release();
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
return {
resize(width, height, ratio = 1, focus = null) {
size = { width, height, ratio };
settings = { ...settings, focus };
backing.resize(width, height, ratio);
bolts = [];
impacts = [];
if (active) schedule();
},
setActive(next) {
// Un premier éclair part dès que la carte s'anime.
if (next && !active) nextSpawn = 0;
if (next) backing.attach();
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
},
// Mouvement réduit : une image fixe de deux éclairs posés, sans boucle.
renderStatic() {
if (!size.width) return;
backing.attach();
const now = 0;
bolts = [0.8, 3.6].map((angle) => ({ ...boltGeometry(size.width, size.height, angle, random, settings), color: settings.colors[0], born: now - 10_000, grow: 1, fade: 1, struck: true, width: 1.3 * scale() }));
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
for (const bolt of bolts) {
strokeBolt(context, bolt.main, 1, { color: bolt.color, core: settings.core || "#ffffff", width: bolt.width, alpha: 0.55 });
}
context.globalCompositeOperation = "source-over";
bolts = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}

View file

@ -0,0 +1,196 @@
/**
* @file Moteur des scintillements holographiques d'une carte mythique (Canvas 2D) : des motifs lumineux
* (étoile, reflet, losange, cœur, flocon, bulle…) apparaissent en grossissant, vivent un instant avec
* un éclat en croix à leur apogée, puis disparaissent en rétrécissant. Nombre moyen à l'écran, vitesse
* et intensité réglables ; couleurs de la palette ; temps réel ; aucune boucle au repos. Même interface
* que le moteur des éclairs.
*/
import { canvasBacking, motifAngle, motifSprite, SPRITE_SIZE, streakSprite } from "./flareSprites.js";
const TAU = Math.PI * 2;
// Les motifs proposés (identifiants et libellés) sont déclarés par le catalogue (`flareEffects`).
// Paliers 1 à 5 : nombre moyen de motifs visibles (pour une illustration de carte `lg`), durée de vie d'un motif, intensité
// (taille et éclat).
export const TWINKLE_COUNTS = [2, 3, 4, 6, 9];
const LIFETIME_MS = [3400, 2600, 1900, 1350, 950];
const INTENSITY_SCALE = [0.55, 0.65, 0.8, 1, 1.25];
// Surface de référence : l'illustration d'une carte `lg`. Une carte plus petite montre moins de motifs, une zone « toute la
// carte » un peu plus.
const REFERENCE_AREA = 280 * 240;
// Quand la carte n'est plus survolée, les motifs encore en vie s'effacent ensemble en une demi-seconde au lieu de finir leur
// vie : l'animation s'arrête vite au lieu de tourner plusieurs secondes pour rien.
const OUTRO_MS = 500;
const easeOutBack = (t) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;
// Phase d'un motif selon son âge relatif (0 à 1) : apparition (35 %) avec un léger dépassement, apogée (20 %), disparition.
export function twinkleState(t) {
if (t < 0.35) {
const p = t / 0.35;
return { scale: Math.max(0, easeOutBack(p)), alpha: Math.min(1, p * 1.6), peak: 0 };
}
if (t < 0.55) {
const p = (t - 0.35) / 0.2;
return { scale: 1, alpha: 1, peak: Math.sin(p * Math.PI) };
}
const p = Math.min(1, (t - 0.55) / 0.45);
return { scale: 1 - p * 0.75, alpha: 1 - p, peak: 0 };
}
export function createTwinkle(canvas, options) {
const context = canvas.getContext("2d");
const backing = canvasBacking(canvas);
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let sprites = [];
let streaks = [];
let items = [];
let pointer = null;
let active = false;
let frame = 0;
let nextSpawn = 0;
let leftAt = 0;
let fade = 1;
let destroyed = false;
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const lifetime = () => LIFETIME_MS[(settings.level || 3) - 1];
const areaFactor = () => Math.min(1.6, Math.max(0.3, (size.width * size.height) / REFERENCE_AREA));
const average = () => TWINKLE_COUNTS[(settings.count || 3) - 1] * areaFactor();
const sizeFactor = () => Math.min(1.2, Math.max(0.5, Math.min(size.width, size.height) / 240));
function buildSprites() {
const core = settings.core || "#ffffff";
sprites = settings.colors.map((color) => motifSprite(settings.motifId || "four-point-star", color, core));
streaks = settings.colors.map((color) => streakSprite(color, core));
}
// Position libre : marges de 6 %, à distance des motifs vivants ; un tiers des motifs naissent près du pointeur, là où
// la lumière frappe.
function position(radius) {
let best = null;
for (let attempt = 0; attempt < 4; attempt++) {
const near = pointer && random() < 0.35;
const x = near ? (pointer.x + (random() - 0.5) * 0.36) * size.width : (0.06 + random() * 0.88) * size.width;
const y = near ? (pointer.y + (random() - 0.5) * 0.36) * size.height : (0.06 + random() * 0.88) * size.height;
const candidate = { x: Math.min(size.width * 0.96, Math.max(size.width * 0.04, x)), y: Math.min(size.height * 0.96, Math.max(size.height * 0.04, y)) };
const crowded = items.some((item) => Math.hypot(item.x - candidate.x, item.y - candidate.y) < (item.radius + radius) * 1.6);
best = candidate;
if (!crowded) break;
}
return best;
}
function spawn(now) {
// Tailles contrastées : surtout des motifs moyens, et de temps en temps un grand éclat qui attire l'œil.
const radius = (9 + random() ** 2.5 * 18) * intensity() * sizeFactor();
const color = Math.floor(random() * settings.colors.length);
const life = lifetime() * (0.75 + random() * 0.5);
items.push({ ...position(radius), radius, color, born: now, life, rotation: random() * TAU, spin: (random() - 0.5) * 1.2 });
// Intervalle moyen = durée de vie / nombre moyen voulu : le nombre visible se stabilise autour de la moyenne.
nextSpawn = now + (lifetime() / average()) * (0.4 + random() * 1.2);
}
function drawItem(item, state) {
const spriteSize = item.radius * 2 * (SPRITE_SIZE / (SPRITE_SIZE * 0.34)) * state.scale;
context.save();
context.translate(item.x, item.y);
context.rotate(motifAngle(settings.motifId, item.rotation + item.spin * state.age));
context.globalAlpha = fade * state.alpha * Math.min(1, 0.75 + 0.25 * intensity());
context.drawImage(sprites[item.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
// Le reflet garde sa croix de lumière toute sa vie ; les autres motifs la font jaillir à leur apogée.
const peak = settings.motifId === "glint" ? Math.max(state.peak, state.alpha * 0.7) : state.peak;
if (peak > 0 && settings.motifId !== "bubble") {
const streak = item.radius * 10 * (0.55 + 0.45 * peak) * Math.min(1.3, intensity());
context.globalAlpha = fade * peak;
context.drawImage(streaks[item.color], -streak / 2, -streak / 2, streak, streak);
}
context.restore();
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const item of items) {
const age = (now - item.born) / item.life;
drawItem(item, { ...twinkleState(age), age });
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
// Plusieurs naissances par image si la fréquence l'exige (beaucoup de motifs très rapides).
while (active && now >= nextSpawn && items.length < average() * 2.5) spawn(now);
items = items.filter((item) => now - item.born < item.life);
fade = leftAt ? Math.max(0, 1 - (now - leftAt) / OUTRO_MS) : 1;
if (!fade) items = [];
draw(now);
if (active || items.length) frame = requestAnimationFrame(tick);
else backing.release();
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
// Sprites construits à la première animation (et pris dans le cache partagé) : une carte jamais survolée n'en crée pas.
return {
resize(width, height, ratio = 1) {
size = { width, height, ratio };
backing.resize(width, height, ratio);
items = [];
if (active) schedule();
},
setActive(next) {
if (next && !active) nextSpawn = 0;
if (!next && active) leftAt = performance.now();
if (next) leftAt = 0;
if (next) {
if (!sprites.length) buildSprites();
backing.attach();
}
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
sprites = [];
streaks = [];
},
// Mouvement réduit : quelques motifs fixes, à mi-éclat.
renderStatic() {
if (!size.width) return;
if (!sprites.length) buildSprites();
backing.attach();
items = [];
const count = Math.max(2, Math.round(average() / 2));
for (let index = 0; index < count; index++) {
const radius = 10 * intensity() * sizeFactor();
items.push({ ...position(radius), radius, color: index % settings.colors.length, born: 0, life: 1, rotation: random() * TAU, spin: 0 });
}
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const item of items) drawItem(item, { scale: 0.85, alpha: 0.6, peak: 0, age: 0 });
context.globalCompositeOperation = "source-over";
items = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}

View file

@ -0,0 +1,42 @@
/**
* @file Résout l'effet d'ouverture d'une carte et le style des particules mythiques (défaut, collection,
* carte).
*/
// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation.
export const MATCH_HOLO_PALETTE_ID = "match-holo";
export const MATCH_HOLO_PALETTE_LABEL = "Comme la palette holo";
function setting(catalog, scope, targetId) {
return catalog?.mythicOpeningSettings?.find((item) => item.scope === scope && item.targetId === targetId) || null;
}
// Effet d'aura et de durées de la rareté (un seul par rareté).
export function resolveOpeningEffect(catalog, rarity) {
return catalog?.openingEffects?.find((effect) => effect.rarity === rarity) || null;
}
// Forme et palette des particules mythiques, chacune héritée indépendamment : carte, puis collection, puis défaut.
export function resolveMythicOpeningStyle(catalog, cardId, collectionId) {
const effect = resolveOpeningEffect(catalog, "mythic");
const basePreset = catalog?.particlePresets?.find((preset) => preset.id === effect?.particlePresetId) || null;
const cardSetting = setting(catalog, "card", cardId);
const collectionSetting = setting(catalog, "collection", collectionId);
const pick = (key, presetKey) => {
if (cardSetting?.[key]) return { id: cardSetting[key], source: "card" };
if (collectionSetting?.[key]) return { id: collectionSetting[key], source: "collection" };
return { id: basePreset?.[presetKey] || null, source: "default" };
};
return { effect, basePreset, shape: pick("particleShapeId", "shapeId"), palette: pick("particlePaletteId", "paletteId") };
}
// Catalogue d'aperçu où la carte reçoit un réglage d'ouverture précis, sans toucher aux autres réglages.
export function withCardOpeningSetting(catalog, cardId, { particleShapeId = null, particlePaletteId = null }) {
return {
...catalog,
mythicOpeningSettings: [
...(catalog.mythicOpeningSettings || []).filter((item) => item.scope !== "card" || item.targetId !== cardId),
...(particleShapeId || particlePaletteId ? [{ scope: "card", targetId: cardId, particleShapeId, particlePaletteId }] : [])
]
};
}