Compare commits

..

3 commits

Author SHA1 Message Date
6d8e813d19 Merge pull request 'Rework donate flow into guided steps with gift options' (#7) from feature/donate-enhancement into main 2026-10-24 15:40:46 +00:00
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
5a34a2471f Tint donate UI accent to match the glow colour
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 13:32:13 +01:00
15 changed files with 1669 additions and 361 deletions

View file

@ -1,22 +1,23 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { getStripe } from "@/lib/stripe"; import { getStripe } from "@/lib/stripe";
import { cfg } from "@/lib/cfg"; import { cfg } from "@/lib/cfg";
import { TIERS, tierForAmount } from "@/lib/donations"; import { TIERS, tierForAmount, CUSTOM_MIN, CUSTOM_MAX } from "@/lib/donations";
import { minecraftApi } from "@/lib/minecraft-api"; import { minecraftApi } from "@/lib/minecraft-api";
import { minecraft } from "@/lib/servertap"; import { minecraft } from "@/lib/servertap";
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
try { try {
const body = await req.json(); const body = await req.json();
const { platform, username, tier, customAmount, customRecurring, giftTo, upgrade } = body as { const { platform, giftPlatform, username, tier, customAmount, customRecurring, giftTo, upgrade, anonymous } = body as {
platform: "java" | "bedrock"; username: string; tier: string; customAmount?: number; customRecurring?: boolean; giftTo?: string; upgrade?: boolean; platform: "java" | "bedrock"; giftPlatform?: "java" | "bedrock"; username: string; tier: string; customAmount?: number; customRecurring?: boolean; giftTo?: string; upgrade?: boolean; anonymous?: boolean;
}; };
if (!username || !platform || !tier) return NextResponse.json({ error: "Missing fields" }, { status: 400 }); if (!username || !platform || !tier) return NextResponse.json({ error: "Missing fields" }, { status: 400 });
// resolve recipient first — validates the account exists and gives us // resolve recipient first — validates the account exists and gives us
// uuid/xuid so the webhook can grant by UUID instead of name // uuid/xuid so the webhook can grant by UUID instead of name
const recipientName = (giftTo?.trim() || username).trim(); const recipientName = (giftTo?.trim() || username).trim();
const recipientPlatform = platform; // A gift can go to a player on the other edition from the donor.
const recipientPlatform = giftTo?.trim() && (giftPlatform === "java" || giftPlatform === "bedrock") ? giftPlatform : platform;
const resolved = await minecraftApi.resolvePlayerIdentifier({ type: recipientPlatform, username: recipientName }).catch((e: any) => { const resolved = await minecraftApi.resolvePlayerIdentifier({ type: recipientPlatform, username: recipientName }).catch((e: any) => {
return { error: e?.message || "Could not resolve that player" } as const; return { error: e?.message || "Could not resolve that player" } as const;
}); });
@ -25,8 +26,8 @@ export async function POST(req: NextRequest) {
let price = 0; let tierId = tier; let isSub = false; let label = ""; let verifiedFrom: string | null = null; let price = 0; let tierId = tier; let isSub = false; let label = ""; let verifiedFrom: string | null = null;
if (tier === "custom") { if (tier === "custom") {
if (!customAmount || customAmount < 100) return NextResponse.json({ error: "Custom amount min £1" }, { status: 400 }); if (!Number.isInteger(customAmount) || customAmount! < CUSTOM_MIN || customAmount! > CUSTOM_MAX) return NextResponse.json({ error: "Custom amount must be between £1 and £1,000" }, { status: 400 });
price = customAmount; isSub = !!customRecurring; price = customAmount!; isSub = !!customRecurring;
// >=£5/mo recurring custom grants Patron // >=£5/mo recurring custom grants Patron
const unlocked = isSub && price >= TIERS.patron.price ? "patron" : tierForAmount(price); const unlocked = isSub && price >= TIERS.patron.price ? "patron" : tierForAmount(price);
label = unlocked ? `Custom — unlocks ${unlocked}` : "Custom donation"; label = unlocked ? `Custom — unlocks ${unlocked}` : "Custom donation";
@ -54,7 +55,8 @@ export async function POST(req: NextRequest) {
const metadata: Record<string, string> = { const metadata: Record<string, string> = {
tier: tierId, platform: recipientPlatform, username: recipient.username, tier: tierId, platform: recipientPlatform, username: recipient.username,
uuid: recipient.uuid ?? "", xuid: recipient.xuid ?? "", uuid: recipient.uuid ?? "", xuid: recipient.xuid ?? "",
donor: username, gift: giftTo ? "1" : "0", // An anonymous gift leaves the donor blank; the webhook then says "someone".
donor: giftTo && anonymous ? "" : username, gift: giftTo ? "1" : "0",
custom: tier === "custom" ? "1" : "0", customAmount: String(price), isSub: isSub ? "1" : "0", custom: tier === "custom" ? "1" : "0", customAmount: String(price), isSub: isSub ? "1" : "0",
upgradeFrom: verifiedFrom || "", upgrade: verifiedFrom ? "1" : "0", upgradeFrom: verifiedFrom || "", upgrade: verifiedFrom ? "1" : "0",
}; };

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,104 @@
"use client";
import { Segmented } from "@/components/segmented";
import { CUSTOM_MAX, CUSTOM_MIN, TIERS, tierForCustom } from "@/lib/donations";
import { useFinePointer } from "@/lib/use-fine-pointer";
import { cn } from "@/lib/utils";
// The "how much?" step: the amount is typed large, straight onto the page, and
// the line beneath says which rank it unlocks. The page glow and accent follow
// that rank, so the colour climbs as the number does.
const PRESETS = [3, 5, 7, 10, 25];
const CADENCE = [
{ id: "once", label: "One-time" },
{ id: "monthly", label: "Monthly" },
] as const;
// Digits and at most one point, two decimal places.
const clean = (raw: string) => {
const [whole, ...rest] = raw.replace(/[^\d.]/g, "").split(".");
return rest.length ? `${whole}.${rest.join("").slice(0, 2)}` : whole;
};
export function AmountStage({ pounds, recurring, error, onPounds, onRecurring }: {
pounds: string;
recurring: boolean;
// Why the amount cannot be used, shown in place of the hint.
error?: string | null;
onPounds: (value: string) => void;
onRecurring: (recurring: boolean) => void;
}) {
const finePointer = useFinePointer();
const amount = parseFloat(pounds);
const valid = !isNaN(amount) && amount * 100 >= CUSTOM_MIN && amount * 100 <= CUSTOM_MAX;
const unlocked = valid ? tierForCustom(Math.round(amount * 100), recurring) : null;
const tier = unlocked ? TIERS[unlocked as keyof typeof TIERS] : null;
return (
<div className="flex flex-col items-center gap-6">
<label className="flex items-baseline justify-center gap-1 border-b-2 border-white/20 pb-1 transition-colors duration-200 focus-within:border-primary">
<span aria-hidden="true" className="text-4xl font-semibold text-white/55">£</span>
<input
autoFocus={finePointer}
inputMode="decimal"
value={pounds}
onChange={(e) => {
const next = clean(e.target.value);
// Past the ceiling the keystroke is ignored, so the number never outgrows its field.
if (parseFloat(next) * 100 > CUSTOM_MAX) return;
onPounds(next);
}}
aria-label="Amount in pounds"
placeholder="10"
autoComplete="off"
style={{ width: `${pounds.length || 2}ch` }}
className="max-w-[9ch] bg-transparent text-center text-6xl font-semibold tracking-tight tabular-nums caret-primary outline-none placeholder:text-white/25"
/>
</label>
<div className="flex flex-wrap justify-center gap-2" role="group" aria-label="Suggested amounts">
{PRESETS.map((n) => {
const on = pounds === String(n);
return (
<button
key={n}
type="button"
onClick={() => onPounds(String(n))}
aria-pressed={on}
className={cn(
"h-11 min-w-14 rounded-full border px-4 text-sm font-semibold tabular-nums outline-none transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-primary",
on ? "border-primary bg-primary/15 text-primary" : "border-white/15 bg-black/25 text-white/80 hover:border-white/30 hover:text-white"
)}
>
£{n}
</button>
);
})}
</div>
<Segmented
options={CADENCE}
value={recurring ? "monthly" : "once"}
onChange={(id) => onRecurring(id === "monthly")}
label="How often"
/>
<div aria-live="polite" className="flex min-h-12 flex-col items-center gap-1 text-center">
{error ? (
<p role="alert" className="text-sm text-destructive">{error}</p>
) : !valid ? (
<p className="text-sm text-muted-foreground">Enter an amount from £{CUSTOM_MIN / 100} to £{(CUSTOM_MAX / 100).toLocaleString("en-GB")}.</p>
) : tier ? (
<>
<p className="text-sm">Unlocks <span className="font-semibold text-primary">{tier.label}</span></p>
<p className="max-w-xs text-xs/relaxed text-pretty text-muted-foreground">{tier.perks.join(" · ")}</p>
</>
) : (
<p className="text-sm text-muted-foreground">Under £{TIERS.iron.price / 100} doesn&apos;t unlock a rank.</p>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,54 @@
"use client";
import { NAMETAG, PlayerFigure, type Platform } from "@/components/donate-player";
import { cn } from "@/lib/utils";
// The "confirm details" step: the person who will receive the rank stands there
// with their nametag, and a receipt underneath says exactly what is being paid.
type Row = { label: string; value: React.ReactNode };
export function ConfirmStage({ recipient, platform, from, rows, total, perks, compact = false }: {
recipient: string;
platform: Platform;
// Set for a gift: who it is from.
from?: string;
rows: Row[];
total: string;
perks?: string[];
// Drops the standing figure, for places short on height.
compact?: boolean;
}) {
return (
<div className="flex flex-col items-center gap-5">
<div className="flex flex-col items-center gap-3">
<div className={cn(NAMETAG, "max-w-[calc(100vw-3rem)] truncate")}>{recipient || "—"}</div>
{!compact && <PlayerFigure platform={platform} name={recipient} className="h-44 w-22 md:h-56 md:w-28" />}
</div>
<div className="w-full rounded-2xl border border-white/12 bg-black/25 px-4 py-3">
<dl className="divide-y divide-white/10 text-sm">
{from && (
<div className="flex justify-between gap-4 py-2.5">
<dt className="text-muted-foreground">Gift from</dt>
<dd className="font-medium">{from}</dd>
</div>
)}
{rows.map((r) => (
<div key={r.label} className="flex justify-between gap-4 py-2.5">
<dt className="text-muted-foreground">{r.label}</dt>
<dd className="text-right font-medium">{r.value}</dd>
</div>
))}
<div className="flex items-baseline justify-between gap-4 pt-3 pb-1">
<dt className="text-muted-foreground">Total</dt>
<dd className="text-2xl font-semibold tracking-tight tabular-nums text-primary">{total}</dd>
</div>
</dl>
{perks && perks.length > 0 && (
<p className="mt-2 border-t border-white/10 pt-2.5 text-xs/relaxed text-pretty text-muted-foreground">{perks.join(" · ")}</p>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,158 @@
"use client";
import { useRef } from "react";
import { motion, useReducedMotion } from "motion/react";
import { Check } from "lucide-react";
import { LookupNote, NAMETAG, PlatformToggle, PlayerFigure, type Platform } from "@/components/donate-player";
import { useFinePointer } from "@/lib/use-fine-pointer";
import type { LookupStatus } from "@/lib/player-lookup";
import { cn } from "@/lib/utils";
// The "is this a gift?" step as two figures side by side. "For me" is the
// visitor's own skin; "Gift to a friend" is a blank silhouette whose nametag
// is the recipient field, and the skin fills in as their name is typed.
export function GiftStage({ platform, player, gift, giftTo, giftPlatform, anonymous, lookup, onGift, onGiftTo, onGiftPlatform, onAnonymous }: {
platform: Platform;
player: string;
gift: string;
giftTo: string;
// "" until the visitor says which edition their friend plays.
giftPlatform: Platform | "";
anonymous: boolean;
// The recipient name lookup, for a gift.
lookup: { status: LookupStatus; name: string };
onGift: (choice: "yes" | "no") => void;
onGiftTo: (name: string) => void;
onGiftPlatform: (platform: Platform) => void;
onAnonymous: (anonymous: boolean) => void;
}) {
const reduced = useReducedMotion() ?? false;
const finePointer = useFinePointer();
const input = useRef<HTMLInputElement>(null);
const tiles = [
{ id: "no" as const, title: "For me", note: "The donation goes to your account" },
{ id: "yes" as const, title: "Gift to a friend", note: "We'll mail it to them in-game" },
];
return (
<div className="flex flex-col gap-4">
<div role="radiogroup" aria-label="Is this a gift?" className="grid grid-cols-2 gap-3">
{tiles.map((tile) => {
const checked = gift === tile.id;
const mine = tile.id === "no";
return (
<motion.div
key={tile.id}
animate={{ opacity: gift && !checked ? 0.8 : 1 }}
transition={reduced ? { duration: 0 } : { duration: 0.2 }}
className={cn(
"relative flex min-w-0 flex-col items-center rounded-2xl border px-3 pt-4 pb-4 transition-colors duration-200",
checked ? "border-primary bg-primary/10" : "border-white/12 bg-black/25"
)}
>
{/* Covers the whole tile; the recipient field sits above it. */}
<button
type="button"
role="radio"
aria-checked={checked}
aria-label={tile.title}
onClick={() => {
onGift(tile.id);
if (!mine && finePointer) requestAnimationFrame(() => input.current?.focus());
}}
className="absolute inset-0 cursor-pointer rounded-2xl focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-primary"
/>
<span
aria-hidden="true"
className={cn(
"absolute top-2.5 left-2.5 flex size-5 items-center justify-center rounded-full border transition-colors duration-200",
checked ? "border-primary bg-primary text-primary-foreground" : "border-white/25"
)}
>
{checked && <Check className="size-3" strokeWidth={3.5} />}
</span>
{mine ? (
<div className="relative mt-6 flex h-9 items-center justify-center text-xs font-semibold text-white/70 capitalize">{platform}</div>
) : (
<PlatformToggle
compact
label="Which edition does your friend play?"
value={giftPlatform}
onChange={(p) => { onGiftPlatform(p); if (gift !== "yes") onGift("yes"); }}
className="relative z-10 mt-6"
/>
)}
{mine ? (
<div className={cn(NAMETAG, "mt-2 w-full truncate text-xs")}>{player.trim() || "You"}</div>
) : (
<input
ref={input}
value={giftTo}
onChange={(e) => onGiftTo(e.target.value)}
onFocus={() => { if (gift !== "yes") onGift("yes"); }}
maxLength={giftPlatform === "bedrock" ? 20 : 16}
aria-label="Recipient's Minecraft name"
aria-invalid={lookup.status === "missing" || undefined}
placeholder="Friend's name"
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
// 16px so iOS does not zoom the page when the field is focused.
className={cn(NAMETAG, "relative z-10 mt-2 w-full min-w-0 px-1 text-base caret-primary outline-none placeholder:text-white/45 focus-visible:ring-2 focus-visible:ring-primary", lookup.status === "missing" && "ring-2 ring-destructive")}
/>
)}
{/* The figure paints over the tile's button, so it must not take the tap. */}
<div className="pointer-events-none">
<PlayerFigure
// Remounts when the name becomes usable, so the fill-in replays
// from a blank silhouette.
key={mine ? "me" : giftTo.trim().length < 3 || !giftPlatform ? "blank" : `named-${giftPlatform}`}
platform={mine ? platform : giftPlatform || "java"}
// No lookup until the edition is known.
name={mine ? player : giftPlatform ? giftTo : ""}
hideUntilFound={!mine}
bobDelay={mine ? 0 : 1.2}
className="mt-3 h-40 w-20 md:h-56 md:w-28"
/>
</div>
<span className="mt-3 text-sm font-semibold text-balance">{tile.title}</span>
<span className="mt-0.5 text-center text-xs/snug text-pretty text-muted-foreground">{tile.note}</span>
</motion.div>
);
})}
</div>
{gift === "yes" && (
<div className="flex flex-col items-center gap-3">
{giftPlatform ? (
<LookupNote status={lookup.status} name={lookup.name} platform={giftPlatform} className="max-w-xs" />
) : (
<p className="min-h-5 text-center text-xs/5 text-muted-foreground">Pick their edition to look them up.</p>
)}
<label className="flex min-h-11 cursor-pointer items-center gap-3 rounded-xl border border-white/12 bg-black/25 px-4 text-sm has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-primary">
<input
type="checkbox"
checked={anonymous}
onChange={(e) => onAnonymous(e.target.checked)}
className="peer sr-only"
/>
<span
aria-hidden="true"
className="flex size-5 shrink-0 items-center justify-center rounded-md border border-white/30 text-primary-foreground transition-colors duration-200 peer-checked:border-primary peer-checked:bg-primary"
>
{anonymous && <Check className="size-3.5" strokeWidth={3.5} />}
</span>
Don&apos;t put my name on the gift
</label>
</div>
)}
</div>
);
}

View file

@ -30,6 +30,30 @@ export const GLOW_THEMES = {
export type GlowTheme = keyof typeof GLOW_THEMES; export type GlowTheme = keyof typeof GLOW_THEMES;
// UI accent that goes with each glow. `green` is the site default, so it sets
// nothing and the stylesheet's own --primary applies.
const GLOW_ACCENTS: Record<GlowTheme, { primary: string; foreground: string } | null> = {
green: null,
lime: { primary: "#a6ff3c", foreground: "#14210a" },
teal: { primary: "#2dd4bf", foreground: "#042f2b" },
purple: { primary: "#8b6cf6", foreground: "#ffffff" },
blue: { primary: "#4a90f7", foreground: "#ffffff" },
iron: { primary: "#cbd5e1", foreground: "#1e293b" },
gold: { primary: "#fbbf24", foreground: "#2b1d02" },
diamond: { primary: "#22d3ee", foreground: "#052e38" },
};
// Inline style that retints the accent variables for the glow's theme.
export function glowAccentStyle(theme: GlowTheme): React.CSSProperties | undefined {
const accent = GLOW_ACCENTS[theme];
if (!accent) return undefined;
return {
"--primary": accent.primary,
"--primary-foreground": accent.foreground,
"--ring": accent.primary,
} as React.CSSProperties;
}
const VERTEX_SHADER = `#version 300 es const VERTEX_SHADER = `#version 300 es
in vec2 position; in vec2 position;
void main() { void main() {

View file

@ -0,0 +1,203 @@
"use client";
import { useRef, useState, useSyncExternalStore } from "react";
import { motion, useReducedMotion } from "motion/react";
import { Check } from "lucide-react";
import { TIERS } from "@/lib/donations";
import { cn } from "@/lib/utils";
// The "how do you want to donate?" step as a hand of four cards. On wide
// screens they overlap in a shallow fan; hovering one lifts it a little and
// brings it to the front. On narrow screens the hand is laid on the table as a
// loose 2x2. Each card is tinted with the glow it switches the page to, and
// previews that glow while hovered or focused.
export type Intent = "rank" | "upgrade" | "patron" | "custom";
type CardDef = {
id: Intent;
title: string;
description: string;
foot: string;
// Light and deep tone, matching the page glow this card selects.
light: string;
deep: string;
};
const pounds = (pence: number) => `£${pence / 100}`;
const CARDS: CardDef[] = [
{
id: "rank",
title: "Purchase a rank",
description: "Iron, Gold or Diamond. One-time.",
foot: `${pounds(TIERS.iron.price)} – ${pounds(TIERS.diamond.price)}`,
light: "#a6ff3c",
deep: "#3fd10a",
},
{
id: "upgrade",
title: "Upgrade rank",
description: "Already have a rank? Pay the difference.",
foot: "Difference only",
light: "#5eead4",
deep: "#0d9488",
},
{
id: "patron",
title: "Become a patron",
description: "All cosmetics + Patron badge.",
foot: `${pounds(TIERS.patron.price)} / month`,
light: "#8b6cf6",
deep: "#6d3df0",
},
{
id: "custom",
title: "Custom donation",
description: "Any amount. Monthly £5+ makes you a Patron.",
foot: "From £1",
light: "#38bdf8",
deep: "#2563eb",
},
];
// Resting pose of each card in the fan, and a looser one for the 2x2 grid.
const FAN = [
{ rotate: -5, y: 8 },
{ rotate: -1.7, y: 1 },
{ rotate: 1.7, y: 1 },
{ rotate: 5, y: 8 },
];
const GRID = [{ rotate: -1.2 }, { rotate: 1 }, { rotate: 1.2 }, { rotate: -1 }];
const SPRING = { type: "spring", stiffness: 380, damping: 30, mass: 0.7 } as const;
const subscribeWide = (cb: () => void) => {
const mq = window.matchMedia("(min-width: 768px)");
mq.addEventListener("change", cb);
return () => mq.removeEventListener("change", cb);
};
const isWide = () => window.matchMedia("(min-width: 768px)").matches;
// True from the md breakpoint up; assumed true on the server.
export const useIsWide = () => useSyncExternalStore(subscribeWide, isWide, () => true);
export function DonateHand({ value, onSelect, onPreview }: {
value: string;
onSelect: (id: Intent) => void;
onPreview: (id: Intent | null) => void;
}) {
const wide = useIsWide();
const reduced = useReducedMotion() ?? false;
const [hovered, setHovered] = useState<number | null>(null);
const hoveredRef = useRef<number | null>(null);
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
const selected = CARDS.findIndex((c) => c.id === value);
const tabStop = selected >= 0 ? selected : 0;
// One owner for the lifted card and the glow preview, so they never
// disagree. Pressing a card moves focus onto it, which blurs whichever card
// had focus before; that blur must not clear a preview someone else holds.
function hover(i: number | null) {
hoveredRef.current = i;
setHovered(i);
onPreview(i === null ? null : CARDS[i].id);
}
function focusCard(i: number) {
buttons.current[(i + CARDS.length) % CARDS.length]?.focus();
}
function onKeyDown(e: React.KeyboardEvent, i: number) {
if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); focusCard(i + 1); }
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); focusCard(i - 1); }
}
return (
<div
role="radiogroup"
aria-label="How do you want to donate?"
className="mx-auto grid w-full max-w-sm grid-cols-2 gap-3 px-1 py-2 md:flex md:max-w-none md:items-end md:justify-center md:gap-0 md:px-0 md:pt-8 md:pb-8"
onPointerLeave={() => hover(null)}
>
{CARDS.map((card, i) => {
const checked = i === selected;
const lifted = hovered === i;
const faded = selected >= 0 && !checked && !lifted;
// Neighbours of the hovered card ease aside, less the further they are.
const spread = wide && hovered !== null && hovered !== i
? Math.sign(i - hovered) * (10 / Math.abs(i - hovered))
: 0;
const rest = wide ? FAN[i] : { ...GRID[i], y: 0 };
const raise = wide ? -10 : -2;
const pose = checked || lifted
? { rotate: rest.rotate * 0.4, y: raise, x: 0 }
: { rotate: rest.rotate, y: rest.y, x: spread };
return (
<div
key={card.id}
className={cn("relative", wide && "-ml-6 first:ml-0")}
style={{ zIndex: checked || lifted ? 20 : i }}
onPointerEnter={(e) => {
if (e.pointerType === "touch") return;
hover(i);
}}
>
<motion.button
ref={(el) => { buttons.current[i] = el; }}
type="button"
role="radio"
aria-checked={checked}
tabIndex={i === tabStop ? 0 : -1}
onClick={() => onSelect(card.id)}
onKeyDown={(e) => onKeyDown(e, i)}
onFocus={(e) => {
if (e.currentTarget.matches(":focus-visible")) hover(i);
}}
onBlur={() => { if (hoveredRef.current === i) hover(null); }}
initial={reduced ? false : { opacity: 0, y: 90, rotate: 0 }}
animate={{ ...pose, opacity: faded ? 0.85 : 1 }}
whileTap={reduced ? undefined : { scale: 0.98 }}
transition={reduced ? { duration: 0 } : SPRING}
style={{
"--c": card.light,
"--c2": card.deep,
transformOrigin: wide ? "50% 160%" : "50% 50%",
} as React.CSSProperties}
className={cn(
"relative flex aspect-[5/7] w-full cursor-pointer flex-col rounded-2xl border p-4 text-start select-none md:aspect-auto md:h-72 md:w-48",
"bg-[color-mix(in_oklab,var(--c2)_20%,oklch(0.19_0.006_286))]",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-(--c)",
checked
? "border-(--c)"
: "border-[color-mix(in_oklab,var(--c)_20%,transparent)]",
"shadow-[-6px_0_14px_-8px_rgb(0_0_0/0.55),0_16px_24px_-14px_rgb(0_0_0/0.7)]",
"transition-[border-color] duration-200"
)}
>
<span className="pe-5 text-lg/tight font-semibold tracking-tight text-balance text-white md:pe-6">{card.title}</span>
<span className="mt-1.5 pe-5 text-xs/snug text-pretty text-white/65 md:pe-6">{card.description}</span>
<span className="mt-auto flex items-center gap-2 text-xs font-semibold tabular-nums text-[color-mix(in_oklab,var(--c)_70%,white)]">
<span
aria-hidden="true"
className={cn(
"flex size-4 shrink-0 items-center justify-center rounded-full border transition-colors duration-200",
checked ? "border-(--c) bg-(--c) text-black/80" : "border-white/25"
)}
>
{checked && <Check className="size-2.5" strokeWidth={3.5} />}
</span>
{card.foot}
</span>
</motion.button>
</div>
);
})}
</div>
);
}

View file

@ -0,0 +1,272 @@
"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>
);
}

View file

@ -0,0 +1,164 @@
"use client";
import { useRef, useState } from "react";
import { motion, useReducedMotion } from "motion/react";
import { Check } from "lucide-react";
import { TIERS } from "@/lib/donations";
import { useIsWide } from "@/components/donate-hand";
import { cn } from "@/lib/utils";
// The "which rank?" step as a podium: the top rank stands tallest in the
// middle, the others step down on either side. Blocks grow up from the floor
// when the step opens, rise a little under the pointer, and the perks of the
// rank being looked at are written underneath.
export type Rank = "iron" | "gold" | "diamond";
type Step = {
id: Rank;
// Block height in rem on narrow and wide screens.
narrow: number;
wide: number;
// Light and deep tone, matching the page glow this rank selects.
light: string;
deep: string;
};
// Left to right, so keyboard order matches what is on screen.
const PODIUM: Step[] = [
{ id: "gold", narrow: 11, wide: 12.5, light: "#fbbf24", deep: "#f59e0b" },
{ id: "diamond", narrow: 13, wide: 15, light: "#22d3ee", deep: "#06b6d4" },
{ id: "iron", narrow: 9, wide: 10.5, light: "#cbd5e1", deep: "#64748b" },
];
// Centre first, then outwards.
const ENTRANCE = [1, 0, 2];
const SPRING = { type: "spring", stiffness: 320, damping: 30, mass: 0.8 } as const;
export function DonatePodium({ value, onSelect, onPreview, ariaLabel = "Which rank?", disabled = [], price, note }: {
value: string;
onSelect: (id: Rank) => void;
onPreview: (id: Rank | null) => void;
ariaLabel?: string;
// Ranks that stand on the podium but cannot be picked.
disabled?: Rank[];
// Overrides for the line under a rank's name (null hides it) and a small
// caption below that. The default is the rank's full price.
price?: (id: Rank) => string | null;
note?: (id: Rank) => string | undefined;
}) {
const reduced = useReducedMotion() ?? false;
const wide = useIsWide();
const [hovered, setHovered] = useState<number | null>(null);
const hoveredRef = useRef<number | null>(null);
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
const selected = PODIUM.findIndex((p) => p.id === value);
const off = (i: number) => disabled.includes(PODIUM[i].id);
const firstOn = PODIUM.findIndex((_, i) => !off(i));
const tabStop = selected >= 0 && !off(selected) ? selected : firstOn;
const shown = hovered ?? (selected >= 0 ? selected : null);
// One owner for the lifted block and the glow preview. A block's blur only
// clears it when that block holds it, so pressing another block (which moves
// focus) cannot flash the old colour.
function hover(i: number | null) {
hoveredRef.current = i;
setHovered(i);
onPreview(i === null ? null : PODIUM[i].id);
}
// Move focus to the next pickable block in a direction, wrapping round.
function focusStep(from: number, dir: 1 | -1) {
for (let n = 1; n <= PODIUM.length; n++) {
const i = (from + dir * n + PODIUM.length * n) % PODIUM.length;
if (!off(i)) { buttons.current[i]?.focus(); return; }
}
}
function onKeyDown(e: React.KeyboardEvent, i: number) {
if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); focusStep(i, 1); }
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); focusStep(i, -1); }
}
return (
<div className="flex flex-col gap-5">
<div
role="radiogroup"
aria-label={ariaLabel}
className="mx-auto flex w-full max-w-md items-end justify-center gap-1.5 pt-6 md:gap-2"
onPointerLeave={() => hover(null)}
>
{PODIUM.map((step, i) => {
const tier = TIERS[step.id];
const unavailable = off(i);
const checked = i === selected && !unavailable;
const lifted = hovered === i;
const faded = selected >= 0 && !checked && !lifted && !unavailable;
const priceText = price ? price(step.id) : `£${(tier.price / 100).toFixed(2)}`;
const noteText = note?.(step.id);
const bump = checked ? 0.75 : lifted ? 0.5 : 0;
return (
<motion.button
key={step.id}
ref={(el) => { buttons.current[i] = el; }}
type="button"
role="radio"
aria-checked={checked}
aria-disabled={unavailable || undefined}
tabIndex={i === tabStop ? 0 : -1}
onClick={() => { if (!unavailable) onSelect(step.id); }}
onKeyDown={(e) => onKeyDown(e, i)}
onPointerEnter={(e) => { if (e.pointerType !== "touch" && !unavailable) hover(i); }}
onFocus={(e) => { if (e.currentTarget.matches(":focus-visible")) hover(i); }}
onBlur={() => { if (hoveredRef.current === i) hover(null); }}
initial={reduced ? false : { height: 0 }}
animate={{
height: ((wide ? step.wide : step.narrow) + bump) * 16,
opacity: unavailable ? 0.45 : faded ? 0.8 : 1,
}}
transition={reduced ? { duration: 0 } : { ...SPRING, delay: ENTRANCE[i] * 0.07 }}
style={{
"--c": step.light,
"--c2": step.deep,
} as React.CSSProperties}
className={cn(
"relative flex min-w-0 flex-1 flex-col overflow-hidden rounded-t-2xl border border-b-0 p-3 text-start select-none md:p-4",
"bg-[color-mix(in_oklab,var(--c2)_20%,oklch(0.19_0.006_286))]",
"shadow-[inset_0_1px_0_color-mix(in_oklab,var(--c)_45%,transparent),0_-14px_24px_-16px_rgb(0_0_0/0.6)]",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-(--c)",
checked ? "border-(--c)" : "border-[color-mix(in_oklab,var(--c)_20%,transparent)]",
unavailable ? "cursor-not-allowed" : "cursor-pointer",
"transition-[border-color] duration-200"
)}
>
<span
aria-hidden="true"
className={cn(
"flex size-4 shrink-0 items-center justify-center rounded-full border transition-colors duration-200",
checked ? "border-(--c) bg-(--c) text-black/80" : "border-white/25"
)}
>
{checked && <Check className="size-2.5" strokeWidth={3.5} />}
</span>
<span className="mt-3 text-base/tight font-semibold tracking-tight text-white md:text-xl/tight">{tier.label}</span>
{priceText !== null && <span className="mt-1 text-sm font-semibold tabular-nums text-[color-mix(in_oklab,var(--c)_70%,white)]">{priceText}</span>}
{noteText && <span className="mt-0.5 text-xs/tight text-white/70">{noteText}</span>}
</motion.button>
);
})}
</div>
{/* The floor the podium stands on. */}
<div aria-hidden="true" className="mx-auto -mt-5 h-px w-full max-w-md bg-white/15" />
<p aria-live="polite" className="mx-auto min-h-10 max-w-sm text-center text-xs/relaxed text-pretty text-muted-foreground">
{shown === null
? "Pick a rank to see what's included."
: TIERS[PODIUM[shown].id].perks.join(" · ")}
</p>
</div>
);
}

View file

@ -0,0 +1,68 @@
"use client";
import { useId } from "react";
import { motion, useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";
// A two-or-more way switch: big halves with a pill in the accent colour that
// slides to the chosen one. `value` may be "" to leave every option unchosen.
export function Segmented<T extends string>({ options, value, onChange, label, compact = false, className }: {
options: readonly { id: T; label: string }[];
value: T | "";
onChange: (id: T) => void;
label: string;
compact?: boolean;
className?: string;
}) {
const reduced = useReducedMotion() ?? false;
const pillId = useId();
return (
<div
role="radiogroup"
aria-label={label}
style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}
className={cn(
"grid w-full rounded-full border border-white/15 bg-black/35 p-1",
compact ? "h-9 max-w-44" : "h-14 max-w-xs",
className
)}
>
{options.map((o, i) => {
const active = o.id === value;
return (
<button
key={o.id}
type="button"
role="radio"
aria-checked={active}
tabIndex={active || (!value && i === 0) ? 0 : -1}
onClick={() => onChange(o.id)}
onKeyDown={(e) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
const step = e.key === "ArrowRight" ? 1 : -1;
const next = options[(i + step + options.length) % options.length];
onChange(next.id);
(e.currentTarget.parentElement?.children[options.indexOf(next)] as HTMLElement | undefined)?.focus();
}}
className={cn(
"relative rounded-full font-semibold outline-none transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-black",
compact ? "text-xs" : "text-sm",
active ? "text-primary-foreground" : "text-white/70 hover:text-white"
)}
>
{active && (
<motion.span
layoutId={pillId}
aria-hidden="true"
className="absolute inset-0 rounded-full bg-primary"
transition={reduced ? { duration: 0 } : { type: "spring", stiffness: 420, damping: 34 }}
/>
)}
<span className="relative">{o.label}</span>
</button>
);
})}
</div>
);
}

36
src/lib/donate-errors.ts Normal file
View file

@ -0,0 +1,36 @@
// Turns a checkout failure into something a donor can act on, and says which
// step holds the thing to fix.
export type CheckoutFailure = {
message: string;
// The step to send the donor back to; absent when nothing they typed is wrong.
step?: "username" | "gift" | "upgrade" | "amount";
};
export function explainCheckoutError(raw: string, gifting: boolean): CheckoutFailure {
const text = raw || "";
const who = gifting ? "gift" : "username";
const edition = /bedrock|gamertag|geyser|xbox/i.test(text) ? "Bedrock gamertag" : "Java name";
if (/rate limit/i.test(text)) {
return { message: "Minecraft's player lookup is busy right now. Wait a moment and try again. Nothing has been charged." };
}
if (/not found|failed to resolve|could not resolve|error: 400/i.test(text)) {
return {
step: who,
message: gifting
? `We couldn't find that ${edition}. Check the spelling and the edition you picked.`
: `We couldn't find that ${edition}. Check the spelling, or switch edition above the name.`,
};
}
if (/no existing rank/i.test(text)) {
return { step: "upgrade", message: "That player doesn't have a rank to upgrade from. Go back and check the name, or buy a rank instead." };
}
if (/already has/i.test(text)) {
return { step: "upgrade", message: "That player already has this rank or a higher one. Choose a higher rank." };
}
if (/custom amount|between/i.test(text)) {
return { step: "amount", message: "Enter an amount between £1 and £1,000." };
}
return { message: "We couldn't start checkout. Nothing has been charged. Please try again in a moment." };
}

View file

@ -31,3 +31,7 @@ export function tierForCustom(pence: number, recurring?: boolean): TierId | null
if (recurring && pence >= TIERS.patron.price) return "patron"; if (recurring && pence >= TIERS.patron.price) return "patron";
return tierForAmount(pence); return tierForAmount(pence);
} }
// Custom donation limits, in pence. The checkout route enforces the same bounds.
export const CUSTOM_MIN = 100;
export const CUSTOM_MAX = 100_000;

44
src/lib/player-lookup.ts Normal file
View file

@ -0,0 +1,44 @@
"use client";
import { useEffect, useState } from "react";
export type LookupStatus = "idle" | "checking" | "found" | "missing" | "error";
// Looks a Minecraft name up once typing pauses. "missing" only means the
// upstream said the player does not exist; a rate limit or an outage is
// "error", which must never stop someone from donating.
export function usePlayerLookup(platform: "java" | "bedrock", raw: string, enabled = true): { status: LookupStatus; name: string } {
const name = raw.trim();
const [result, setResult] = useState<{ key: string; status: LookupStatus; name: string } | null>(null);
const key = `${platform}:${name.toLowerCase()}`;
const active = enabled && name.length >= 3;
useEffect(() => {
if (!active) return;
let stale = false;
const t = setTimeout(async () => {
let status: LookupStatus = "error";
let resolved = name;
try {
const r = await fetch("/api/resolve-player", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: platform, username: name }),
});
const j = await r.json().catch(() => null);
if (r.ok && j?.data) {
status = "found";
resolved = j.data.username ?? name;
} else if (/not found|error: 400/i.test(String(j?.error ?? ""))) {
status = "missing";
}
} catch {}
if (!stale) setResult({ key, status, name: resolved });
}, 500);
return () => { stale = true; clearTimeout(t); };
}, [active, key, platform, name]);
if (!active) return { status: "idle", name };
if (result?.key !== key) return { status: "checking", name };
return { status: result.status, name: result.name };
}

View file

@ -0,0 +1,74 @@
import type { Appearance } from "@stripe/stripe-js";
// Stripe's Appearance API only understands hex, rgb(a) and hsl(a). The site's
// tokens are oklch or lab, so each one is resolved to a computed colour inside
// `root` (where the page's accent is applied) and painted onto a pixel to read
// it back as sRGB.
function toCssRgb(root: HTMLElement, cssColor: string, fallback: string): string {
const probe = document.createElement("span");
probe.style.color = cssColor;
probe.style.display = "none";
root.appendChild(probe);
const computed = getComputedStyle(probe).color;
probe.remove();
const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
if (!ctx) return fallback;
ctx.canvas.width = ctx.canvas.height = 1;
const sentinel = "#010203";
ctx.fillStyle = sentinel;
ctx.fillStyle = computed;
if (ctx.fillStyle === sentinel) return fallback;
ctx.clearRect(0, 0, 1, 1);
ctx.fillRect(0, 0, 1, 1);
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
if (a === 0) return fallback;
if (a === 255) return `#${[r, g, b].map((n) => n.toString(16).padStart(2, "0")).join("")}`;
return `rgba(${r}, ${g}, ${b}, ${+(a / 255).toFixed(3)})`;
}
export function buildStripeAppearance(root: HTMLElement): Appearance {
const c = (token: string, fallback: string) => toCssRgb(root, `var(${token})`, fallback);
const primary = c("--primary", "#a6ff3c");
const primaryText = c("--primary-foreground", "#14210a");
const fg = c("--foreground", "#fafafa");
const bg = c("--background", "#09090b");
const border = c("--border", "rgba(255, 255, 255, 0.1)");
const input = c("--input", "rgba(255, 255, 255, 0.15)");
const mutedFg = c("--muted-foreground", "#a1a1aa");
const destructive = c("--destructive", "#f87171");
const accent = c("--accent", "#27272a");
const radius = getComputedStyle(root).getPropertyValue("--radius").trim() || "0.75rem";
return {
theme: "night",
labels: "above",
variables: {
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, sans-serif",
colorPrimary: primary,
colorPrimaryText: primaryText,
colorBackground: bg,
colorText: fg,
colorTextSecondary: mutedFg,
colorTextPlaceholder: mutedFg,
colorIcon: mutedFg,
colorDanger: destructive,
colorSuccess: primary,
borderRadius: radius,
},
rules: {
".Input": { border: `1px solid ${input}`, backgroundColor: "transparent", boxShadow: "none" },
".Input:focus": { border: `1px solid ${primary}`, boxShadow: "none" },
".Input--invalid": { border: `1px solid ${destructive}`, boxShadow: "none" },
".Label": { color: mutedFg, fontWeight: "500", marginBottom: "6px" },
".Tab": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" },
".Tab:hover": { backgroundColor: accent, boxShadow: "none" },
".Tab--selected": { borderColor: primary, boxShadow: "none" },
".AccordionItem": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" },
".AccordionItem--selected": { borderColor: primary, boxShadow: "none" },
".Block": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" },
".Error": { color: destructive },
".TermsText": { color: mutedFg },
},
};
}

View file

@ -0,0 +1,16 @@
"use client";
import { useSyncExternalStore } from "react";
const QUERY = "(hover: hover) and (pointer: fine)";
const subscribe = (cb: () => void) => {
const mq = window.matchMedia(QUERY);
mq.addEventListener("change", cb);
return () => mq.removeEventListener("change", cb);
};
// True on devices with a mouse or trackpad. Used to decide whether a field may
// grab focus on arrival: on a phone that would raise the keyboard over the
// buttons before the visitor has read the question.
export const useFinePointer = () =>
useSyncExternalStore(subscribe, () => window.matchMedia(QUERY).matches, () => false);