accesscodes/src/components/donate-player.tsx
anonymousratwastaken ebfa25d1e8 Rework donate flow into guided steps with gift options
- Split the donate page into step components and reorder the flow: intent, rank or amount, recipient, gift, upgrade target, then confirm
- Let a gift go to a player on the other edition, and allow anonymous gifts (donor is left blank in metadata)
- Look up the recipient's current rank for upgrades and disable ranks they already hold
- Validate custom amounts on the server as integers between CUSTOM_MIN and CUSTOM_MAX
- Show friendly messages for checkout errors and send users back to the step that needs fixing
- Build the Stripe appearance from the page's glow accent colour, and tint the glow to match a custom amount's unlocked tier
2026-10-24 16:40:08 +01:00

272 lines
11 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import { motion, useAnimate, useReducedMotion } from "motion/react";
import { Segmented } from "@/components/segmented";
import { useFinePointer } from "@/lib/use-fine-pointer";
import type { LookupStatus } from "@/lib/player-lookup";
import { cn } from "@/lib/utils";
// The "Minecraft username" step as a stage: the visitor's own skin stands on
// the floor and the name field is its nametag, floating above the head.
export type Platform = "java" | "bedrock";
// Mojang's own Steve account, shown until there is a name to look up.
const DEFAULT_SKIN = "https://mc-heads.net/skin/MHF_Steve";
// The shared look of a nametag: a dark plate, white shadowed monospace text.
export const NAMETAG =
"rounded-[3px] bg-black/50 px-2 py-1.5 text-center font-mono text-sm text-white [text-shadow:1px_1px_0_rgb(0_0_0/0.55)]";
// Resolves a skin texture URL for a name, or null when there is none.
async function lookupSkin(platform: Platform, name: string): Promise<string | null> {
if (platform === "java") return `https://mc-heads.net/skin/${encodeURIComponent(name)}`;
const r = await fetch("/api/resolve-player", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "bedrock", username: name }),
});
const xuid = (await r.json())?.data?.xuid as string | undefined;
if (!xuid) return null;
const s = await (await fetch(`/api/geyser-skin?xuid=${encodeURIComponent(xuid)}`)).json();
return s.textureUrl ?? s.fallbackUrls?.[0] ?? null;
}
// Draws the front of a skin onto a 16x32 canvas, one canvas pixel per skin
// pixel: classic or slim arms, second layer on top, legacy 64x32 skins mirrored.
function drawPlayer(canvas: HTMLCanvasElement, img: HTMLImageElement) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const k = img.width / 64;
const legacy = img.height * 2 === img.width;
const probe = document.createElement("canvas");
probe.width = img.width;
probe.height = img.height;
const pctx = probe.getContext("2d", { willReadFrequently: true });
pctx?.drawImage(img, 0, 0);
// Slim arms leave the fourth column of the arm empty.
const slim = !legacy && !!pctx && pctx.getImageData(Math.round(54 * k), Math.round(20 * k), 1, Math.round(12 * k)).data.every((v, i) => i % 4 !== 3 || v === 0);
const aw = slim ? 3 : 4;
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, 16, 32);
const part = (sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, flip = false) => {
if (flip) {
ctx.save();
ctx.translate(dx + sw, 0);
ctx.scale(-1, 1);
ctx.drawImage(img, sx * k, sy * k, sw * k, sh * k, 0, dy, sw, sh);
ctx.restore();
} else {
ctx.drawImage(img, sx * k, sy * k, sw * k, sh * k, dx, dy, sw, sh);
}
};
const rightArmX = slim ? 1 : 0;
part(4, 20, 4, 12, 4, 20); // right leg
part(legacy ? 4 : 20, legacy ? 20 : 52, 4, 12, 8, 20, legacy); // left leg
part(20, 20, 8, 12, 4, 8); // body
part(44, 20, aw, 12, rightArmX, 8); // right arm
part(legacy ? 44 : 36, legacy ? 20 : 52, aw, 12, 12, 8, legacy); // left arm
part(8, 8, 8, 8, 4, 0); // head
if (!legacy) {
part(4, 36, 4, 12, 4, 20);
part(4, 52, 4, 12, 8, 20);
part(20, 36, 8, 12, 4, 8);
part(44, 36, aw, 12, rightArmX, 8);
part(52, 52, aw, 12, 12, 8);
}
part(40, 8, 8, 8, 4, 0); // hat
}
const PLATFORMS = [
{ id: "java", label: "Java" },
{ id: "bedrock", label: "Bedrock" },
] as const;
export function PlatformToggle({ value, onChange, label = "Minecraft edition", compact, className }: {
// "" leaves both halves unchosen.
value: Platform | "";
onChange: (p: Platform) => void;
label?: string;
compact?: boolean;
className?: string;
}) {
return <Segmented options={PLATFORMS} value={value} onChange={onChange} label={label} compact={compact} className={className} />;
}
// Paints a flat grey stand-in the shape of a player, for a skin not found yet.
function drawSilhouette(canvas: HTMLCanvasElement) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, 16, 32);
ctx.fillStyle = "rgb(255 255 255 / 0.1)";
ctx.fillRect(4, 8, 8, 12); // body
ctx.fillRect(0, 8, 4, 12); // arms
ctx.fillRect(12, 8, 4, 12);
ctx.fillRect(4, 20, 4, 12); // legs
ctx.fillRect(8, 20, 4, 12);
ctx.fillStyle = "rgb(255 255 255 / 0.16)";
ctx.fillRect(4, 0, 8, 8); // head
}
const SHOWN = "inset(0% 0% 0% 0%)";
const HIDDEN = "inset(100% 0% 0% 0%)";
// A standing player built from a name's skin. With `hideUntilFound` it starts
// as a blank silhouette and the skin fills in from the feet up once found, so
// give it a `key` that changes when the name becomes usable.
export function PlayerFigure({ platform, name: raw, hideUntilFound = false, bobDelay = 0, className }: {
platform: Platform;
name: string;
hideUntilFound?: boolean;
bobDelay?: number;
className?: string;
}) {
const reduced = useReducedMotion() ?? false;
const canvas = useRef<HTMLCanvasElement>(null);
const silhouette = useRef<HTMLCanvasElement>(null);
const [scope, animate] = useAnimate();
const [resolved, setResolved] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [painted, setPainted] = useState(false);
const hadSkin = useRef(false);
const firstLookup = useRef(true);
const name = raw.trim();
// Until a lookup lands, the figure keeps whatever skin it last had.
const skin = hideUntilFound
? resolved
: name.length < 3 ? DEFAULT_SKIN : resolved ?? DEFAULT_SKIN;
// Look the skin up once typing pauses (straight away the first time).
useEffect(() => {
if (name.length < 3) return;
let stale = false;
const delay = firstLookup.current ? 0 : 450;
firstLookup.current = false;
const t = setTimeout(async () => {
setLoading(true);
let url: string | null = null;
try { url = await lookupSkin(platform, name); } catch {}
if (stale) return;
setResolved(url);
setLoading(false);
}, delay);
return () => { stale = true; clearTimeout(t); };
}, [platform, name]);
useEffect(() => {
if (hideUntilFound && silhouette.current) drawSilhouette(silhouette.current);
}, [hideUntilFound]);
// Paint it, with a small pop when a different skin replaces one already shown.
useEffect(() => {
if (!skin) return;
let stale = false;
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
if (stale || !canvas.current) return;
drawPlayer(canvas.current, img);
if (!reduced && hadSkin.current && scope.current) animate(scope.current, { scale: [0.94, 1] }, { type: "spring", stiffness: 420, damping: 22 });
hadSkin.current = true;
setPainted(true);
};
img.src = skin;
return () => { stale = true; };
}, [skin, reduced, animate, scope]);
const show = !hideUntilFound || painted;
return (
<div className="flex flex-col items-center">
<motion.div
animate={reduced ? undefined : { y: [0, -4, 0] }}
transition={{ duration: 3.2, ease: "easeInOut", repeat: Infinity, delay: bobDelay }}
>
<div className={cn("relative h-56 w-28 md:h-80 md:w-40", className)}>
{hideUntilFound && (
<canvas ref={silhouette} width={16} height={32} aria-hidden="true" className="absolute inset-0 size-full [image-rendering:pixelated]" />
)}
<motion.div
className="size-full"
initial={hideUntilFound ? { clipPath: HIDDEN } : false}
animate={{ clipPath: show ? SHOWN : HIDDEN }}
transition={reduced ? { duration: 0 } : { duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
>
<div ref={scope} className="size-full" style={{ transformOrigin: "50% 100%" }}>
<canvas
ref={canvas}
width={16}
height={32}
aria-hidden="true"
className={cn("size-full [image-rendering:pixelated] transition-opacity duration-200", loading && !hideUntilFound && "opacity-60")}
/>
</div>
</motion.div>
</div>
</motion.div>
{/* Ground shadow. */}
<div aria-hidden="true" className="-mt-1 h-4 w-[115%] bg-[radial-gradient(closest-side,rgb(0_0_0/0.5),transparent)]" />
</div>
);
}
// One line under a nametag saying whether the name was found. Reserved at a
// fixed height so the figure below does not jump as the lookup lands.
export function LookupNote({ status, name, platform, className }: {
status: LookupStatus;
name: string;
platform: Platform;
className?: string;
}) {
const edition = platform === "java" ? "Java" : "Bedrock";
return (
<p aria-live="polite" className={cn("min-h-5 text-center text-xs/5", status === "missing" ? "text-destructive" : "text-muted-foreground", className)}>
{status === "checking" ? "Looking for that player…"
: status === "found" ? `Found ${name}`
: status === "missing" ? `No ${edition} player called "${name}". Check the spelling, or switch edition.`
: ""}
</p>
);
}
export function PlayerStage({ platform, value, status, resolvedName, onChange, onPlatformChange }: {
platform: Platform;
value: string;
status: LookupStatus;
resolvedName: string;
onChange: (name: string) => void;
onPlatformChange: (platform: Platform) => void;
}) {
const finePointer = useFinePointer();
return (
<div className="flex flex-col items-center gap-6">
<PlatformToggle value={platform} onChange={onPlatformChange} />
<div className="flex flex-col items-center gap-4">
{/* The nametag. Monospace so the field can size itself in `ch`. */}
<input
autoFocus={finePointer}
value={value}
onChange={(e) => onChange(e.target.value)}
maxLength={platform === "java" ? 16 : 20}
aria-label="Minecraft name"
placeholder="Your Minecraft name"
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
style={{ width: `${Math.max(value.length, 19) + 3}ch` }}
aria-invalid={status === "missing" || undefined}
className={cn(NAMETAG, "max-w-[calc(100vw-3rem)] py-2.5 text-base caret-primary outline-none transition-[box-shadow] duration-200 placeholder:text-white/45 focus-visible:ring-2 focus-visible:ring-primary", status === "missing" && "ring-2 ring-destructive")}
/>
<LookupNote status={status} name={resolvedName} platform={platform} className="-mt-2 max-w-xs" />
<PlayerFigure platform={platform} name={value} className="md:w-40" />
</div>
</div>
);
}