"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 { 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 ; } // 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(null); const silhouette = useRef(null); const [scope, animate] = useAnimate(); const [resolved, setResolved] = useState(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 (
{hideUntilFound && (
{/* Ground shadow. */} ); } // 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 (

{status === "checking" ? "Looking for that player…" : status === "found" ? `Found ${name}` : status === "missing" ? `No ${edition} player called "${name}". Check the spelling, or switch edition.` : ""}

); } 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 (
{/* The nametag. Monospace so the field can size itself in `ch`. */} 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")} />
); }