From 5a34a2471f5881922f475c4f442f46e89fe75211 Mon Sep 17 00:00:00 2001 From: anonymousratwastaken Date: Sat, 24 Oct 2026 13:32:13 +0100 Subject: [PATCH 1/2] Tint donate UI accent to match the glow colour Co-Authored-By: Claude Sonnet 5.5 --- src/app/donate/page.tsx | 6 +++--- src/components/donate-glow.tsx | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/app/donate/page.tsx b/src/app/donate/page.tsx index de15eed..8c60e01 100644 --- a/src/app/donate/page.tsx +++ b/src/app/donate/page.tsx @@ -16,7 +16,7 @@ import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { TIERS, tierForAmount, upgradePrice } from "@/lib/donations"; import { TopBar } from "@/components/top-bar"; -import { DonateGlow, type GlowTheme } from "@/components/donate-glow"; +import { DonateGlow, glowAccentStyle, type GlowTheme } from "@/components/donate-glow"; const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ""); @@ -604,7 +604,7 @@ function DonateFlow() { if (!started) { return ( -
+
@@ -620,7 +620,7 @@ function DonateFlow() { } return ( -
+
diff --git a/src/components/donate-glow.tsx b/src/components/donate-glow.tsx index c713b35..4b461dc 100644 --- a/src/components/donate-glow.tsx +++ b/src/components/donate-glow.tsx @@ -30,6 +30,30 @@ export const 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 = { + 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 in vec2 position; void main() { -- 2.45.3 From ebfa25d1e87991100ce8583a79896a765fa03332 Mon Sep 17 00:00:00 2001 From: anonymousratwastaken Date: Sat, 24 Oct 2026 16:40:08 +0100 Subject: [PATCH 2/2] 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 --- src/app/api/donations/checkout/route.ts | 16 +- src/app/donate/page.tsx | 787 +++++++++++++----------- src/components/donate-amount.tsx | 104 ++++ src/components/donate-confirm.tsx | 54 ++ src/components/donate-gift.tsx | 158 +++++ src/components/donate-hand.tsx | 203 ++++++ src/components/donate-player.tsx | 272 ++++++++ src/components/donate-podium.tsx | 164 +++++ src/components/segmented.tsx | 68 ++ src/lib/donate-errors.ts | 36 ++ src/lib/donations.ts | 4 + src/lib/player-lookup.ts | 44 ++ src/lib/stripe-appearance.ts | 74 +++ src/lib/use-fine-pointer.ts | 16 + 14 files changed, 1642 insertions(+), 358 deletions(-) create mode 100644 src/components/donate-amount.tsx create mode 100644 src/components/donate-confirm.tsx create mode 100644 src/components/donate-gift.tsx create mode 100644 src/components/donate-hand.tsx create mode 100644 src/components/donate-player.tsx create mode 100644 src/components/donate-podium.tsx create mode 100644 src/components/segmented.tsx create mode 100644 src/lib/donate-errors.ts create mode 100644 src/lib/player-lookup.ts create mode 100644 src/lib/stripe-appearance.ts create mode 100644 src/lib/use-fine-pointer.ts diff --git a/src/app/api/donations/checkout/route.ts b/src/app/api/donations/checkout/route.ts index f7ba1e9..ecb0de2 100644 --- a/src/app/api/donations/checkout/route.ts +++ b/src/app/api/donations/checkout/route.ts @@ -1,22 +1,23 @@ import { NextRequest, NextResponse } from "next/server"; import { getStripe } from "@/lib/stripe"; 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 { minecraft } from "@/lib/servertap"; export async function POST(req: NextRequest) { try { const body = await req.json(); - const { platform, username, tier, customAmount, customRecurring, giftTo, upgrade } = body as { - platform: "java" | "bedrock"; username: string; tier: string; customAmount?: number; customRecurring?: boolean; giftTo?: string; upgrade?: boolean; + const { platform, giftPlatform, username, tier, customAmount, customRecurring, giftTo, upgrade, anonymous } = body as { + 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 }); // resolve recipient first — validates the account exists and gives us // uuid/xuid so the webhook can grant by UUID instead of name 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) => { 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; if (tier === "custom") { - if (!customAmount || customAmount < 100) return NextResponse.json({ error: "Custom amount min £1" }, { status: 400 }); - price = customAmount; isSub = !!customRecurring; + 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; // >=£5/mo recurring custom grants Patron const unlocked = isSub && price >= TIERS.patron.price ? "patron" : tierForAmount(price); label = unlocked ? `Custom — unlocks ${unlocked}` : "Custom donation"; @@ -54,7 +55,8 @@ export async function POST(req: NextRequest) { const metadata: Record = { tier: tierId, platform: recipientPlatform, username: recipient.username, 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", upgradeFrom: verifiedFrom || "", upgrade: verifiedFrom ? "1" : "0", }; diff --git a/src/app/donate/page.tsx b/src/app/donate/page.tsx index 8c60e01..2ae250c 100644 --- a/src/app/donate/page.tsx +++ b/src/app/donate/page.tsx @@ -1,6 +1,5 @@ "use client"; -import { Suspense, useEffect, useMemo, useState } from "react"; -import Link from "next/link"; +import { Suspense, useEffect, useMemo, useRef, useState } from "react"; import { useSearchParams } from "next/navigation"; import { loadStripe, type Appearance } from "@stripe/stripe-js"; import { @@ -11,12 +10,21 @@ import { } from "@stripe/react-stripe-js/checkout"; import { toast } from "sonner"; import { ArrowLeft, Loader2, Leaf } from "lucide-react"; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import { TIERS, tierForAmount, upgradePrice } from "@/lib/donations"; +import { CUSTOM_MAX, CUSTOM_MIN, TIERS, tierForCustom, upgradePrice, type TierId } from "@/lib/donations"; +import { explainCheckoutError } from "@/lib/donate-errors"; +import { usePlayerLookup } from "@/lib/player-lookup"; +import { useFinePointer } from "@/lib/use-fine-pointer"; +import { buildStripeAppearance } from "@/lib/stripe-appearance"; import { TopBar } from "@/components/top-bar"; import { DonateGlow, glowAccentStyle, type GlowTheme } from "@/components/donate-glow"; +import { DonateHand, type Intent } from "@/components/donate-hand"; +import { DonatePodium, type Rank } from "@/components/donate-podium"; +import { GiftStage } from "@/components/donate-gift"; +import { AmountStage } from "@/components/donate-amount"; +import { ConfirmStage } from "@/components/donate-confirm"; +import { PlayerStage } from "@/components/donate-player"; const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ""); @@ -31,6 +39,8 @@ type Answers = { platform: "java" | "bedrock"; player: string; giftTo: string; + giftPlatform: "" | "java" | "bedrock"; + anonymous: boolean; customPounds: string; customRecurring: boolean; }; @@ -39,158 +49,164 @@ const EMPTY_ANSWERS: Answers = { intent: "", rank: "", upgradeTo: "", - gift: "", + // Most donations are for the donor, so that is the starting answer. + gift: "no", platform: "java", player: "", giftTo: "", + giftPlatform: "", + anonymous: false, customPounds: "", customRecurring: false, }; -function Choice({ title, description, checked, disabled, onClick }: { - title: React.ReactNode; - description?: React.ReactNode; - checked: boolean; - disabled?: boolean; - onClick: () => void; +const money = (pence: number) => `£${(pence / 100).toFixed(2)}`; + +// The rank the recipient already holds, which decides what an upgrade costs. +type RankLookup = { status: "idle" | "checking" | "found" | "none" | "error"; current: TierId | null; label?: string }; +const IDLE_RANK: RankLookup = { status: "idle", current: null }; + +function useCurrentRank(raw: string, platform: "java" | "bedrock", enabled: boolean): RankLookup { + const name = raw.trim(); + const key = `${platform}:${name.toLowerCase()}`; + const [result, setResult] = useState<{ key: string; value: RankLookup } | null>(null); + const active = enabled && name.length >= 3; + + useEffect(() => { + if (!active) return; + let stale = false; + const t = setTimeout(async () => { + let value: RankLookup = { status: "error", current: null }; + try { + const r = await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}&platform=${platform}`); + const j = await r.json(); + if (r.ok && !j.error) value = j.current ? { status: "found", current: j.current, label: j.label } : { status: "none", current: null }; + } catch {} + if (!stale) setResult({ key, value }); + }, 400); + return () => { stale = true; clearTimeout(t); }; + }, [active, key, platform, name]); + + if (!active) return IDLE_RANK; + if (result?.key !== key) return { status: "checking", current: null }; + return result.value; +} + +// The upgrade step's podium. The recipient's current rank is looked up from +// their name: ranks at or below it stay on the podium but cannot be picked, +// and the rest show the price of the difference. +function UpgradeStage({ value, onChange, onPreview, rank, name }: { + value: string; + onChange: (v: Rank) => void; + onPreview: (id: Rank | null) => void; + rank: RankLookup; + name: string; }) { - return ( - - ); -} + const current = rank.current; + const known = rank.status === "found"; + // Iron is the floor: it is never an upgrade target. Until the current rank + // is known nothing is priced, and if it cannot be found nothing can be picked. + const canPick = (id: Rank) => + id !== "iron" && rank.status !== "none" && rank.status !== "error" && !(current && !upgradePrice(current, id)); + const disabled = (["iron", "gold", "diamond"] as const).filter((id) => !canPick(id)); -function Field({ className, ...props }: React.InputHTMLAttributes) { return ( - - ); -} - -function UpgradeTargetPicker({ value, onChange, player }: { value: string; onChange: (v: string)=>void; player: string }) { - const [verified, setVerified] = useState<{current:string|null;label?:string}|null>(null); - useEffect(()=>{ - const name=(player||"").trim(); - if(name.length<3){setVerified(null);return;} - let cancelled=false; - const t=setTimeout(async()=>{ - try{ - const r=await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}`); - const j=await r.json(); - if(!cancelled) setVerified(j.error?null:j); - }catch{ if(!cancelled) setVerified(null); } - },500); - return()=>{cancelled=true;clearTimeout(t);}; - },[player]); - return (<> - {verified?.current ?

Verified current: {verified.label} — price will be difference

: player.trim().length>=3 ?

No rank found for "{player.trim()}" — upgrade requires an existing rank.

:

Enter your Minecraft name in the next step to verify.

} -
- {(["gold","diamond"] as const).map(id=>{ - const t=(TIERS as any)[id]; - const disabled = !!verified?.current && !upgradePrice(verified.current as any, id as any); - const price = verified?.current ? upgradePrice(verified.current as any, id as any) : null; - return onChange(id)} title={`${t.label}${price ? ` — £${(price/100).toFixed(2)} upgrade` : ` — £${(t.price/100).toFixed(2)}`}`} description={disabled ? `Already have ${verified?.label} or higher` : t.perks.join(" · ")} />; - })} +
+

+ {rank.status === "checking" ? "Checking their current rank…" + : known ? <>{name} is {rank.label} now + : rank.status === "none" ? <>No rank found for "{name}". Upgrades need an existing rank, so go back to check the name or buy a rank instead. + : rank.status === "error" ? "We couldn't check their rank just now. Go back and try again in a moment." + : null} +

+ { + if (!canPick(id)) return null; + const diff = current ? upgradePrice(current, id) : null; + return diff != null ? money(diff) : null; + }} + note={(id) => (canPick(id) ? (known ? "upgrade price" : undefined) : id === "iron" ? "Starting rank" : current === id ? "Their rank" : undefined)} + />
- ); + ); } -type Pending = { +// What the confirm and payment steps list, worked out from the answers. +type Summary = { rows: { label: string; value: React.ReactNode }[]; total: string; perks?: string[] }; + +function confirmSummary(ans: Answers, rank: RankLookup): Summary { + const edition = ans.gift === "yes" ? ans.giftPlatform || ans.platform : ans.platform; + const rows: Summary["rows"] = [ + { label: "Edition", value: {edition} }, + ]; + let total = "—"; + let perks: string[] | undefined; + if (ans.intent === "rank" && ans.rank) { + const t = TIERS[ans.rank as "iron" | "gold" | "diamond"]; + rows.push({ label: "Getting", value: {t.label} }); + total = money(t.price); + perks = [...t.perks]; + } else if (ans.intent === "patron") { + rows.push({ label: "Getting", value: {TIERS.patron.label} }); + total = `${money(TIERS.patron.price)} / month`; + perks = [...TIERS.patron.perks]; + } else if (ans.intent === "upgrade" && ans.upgradeTo) { + const t = TIERS[ans.upgradeTo as "gold" | "diamond"]; + const diff = rank.current ? upgradePrice(rank.current, ans.upgradeTo as TierId) : null; + if (rank.label) rows.push({ label: "Current rank", value: rank.label }); + rows.push({ label: "Getting", value: {t.label} }); + total = diff != null ? money(diff) : "Worked out at checkout"; + perks = [...t.perks]; + } else if (ans.intent === "custom") { + const pounds = parseFloat(ans.customPounds); + const pence = Math.round((isNaN(pounds) ? 0 : pounds) * 100); + const unlocked = tierForCustom(pence, ans.customRecurring); + rows.push({ label: "Getting", value: unlocked ? {TIERS[unlocked as keyof typeof TIERS].label} : "Donation" }); + rows.push({ label: "Frequency", value: ans.customRecurring ? "Monthly" : "One-time" }); + total = `${money(pence)}${ans.customRecurring ? " / month" : ""}`; + if (unlocked) perks = [...TIERS[unlocked as keyof typeof TIERS].perks]; + } + return { rows, total, perks }; +} + +type Pending = Summary & { clientSecret: string; - label: string; - perks: string[]; isSub: boolean; - forUser: string; - gift: boolean; + recipient: string; + platform: "java" | "bedrock"; + // Who a gift is from; absent when it is not a gift. + from?: string; }; -function useStripeAppearance() { - return useMemo(() => { - const cs = getComputedStyle(document.documentElement); - const v = (n: string) => cs.getPropertyValue(n).trim(); - const primary = v("--primary"); - const fg = v("--foreground"); - const bg = v("--background"); - const border = v("--border"); - const input = v("--input"); - const mutedFg = v("--muted-foreground"); - const destructive = v("--destructive"); - const accent = v("--accent"); - const radius = v("--radius") || "0.75rem"; - const appearance: Appearance = { - theme: "night", - labels: "above", - variables: { - fontFamily: - "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, sans-serif", - colorPrimary: primary, - colorPrimaryText: v("--primary-foreground"), - 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" }, - ".Divider": { backgroundColor: border }, - ".Error": { color: destructive }, - ".TermsText": { color: mutedFg }, - }, - }; - return { appearance }; +function PaymentStage({ pending, glow, onBack }: { pending: Pending; glow: GlowTheme; onBack: () => void }) { + const root = useRef(null); + const [appearance, setAppearance] = useState(null); + // The accent lives on this element, so Stripe's colours are read from here. + useEffect(() => { + if (root.current) setAppearance(buildStripeAppearance(root.current)); }, []); -} -function PaymentStage({ pending, onBack }: { pending: Pending; onBack: () => void }) { - const { appearance } = useStripeAppearance(); return ( - - - +
+ + {appearance ? ( + + + + ) : ( +
+ +
+ )} +
); } @@ -211,7 +227,7 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo

Couldn't load checkout

{state.error.message}

- +
); @@ -223,6 +239,7 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo const total = checkout.total.total.minorUnitsAmount / divisor; const fmt = (n: number) => new Intl.NumberFormat("en-GB", { style: "currency", currency }).format(n); + const totalText = `${fmt(total)}${pending.isSub ? " / month" : ""}`; async function pay(e: React.FormEvent) { e.preventDefault(); @@ -240,72 +257,75 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo } } + const summary = { + recipient: pending.recipient, + platform: pending.platform, + from: pending.from, + rows: pending.rows, + total: totalText, + perks: pending.perks, + }; + return (
-
); } + const errorLine = error && step !== "amount" + ?

{error}

+ : null; + return (
-
+
-

Step {current + 1} of {steps.length}

+

+ Step {current + 1}{ans.intent ? ` of ${steps.length}` : ""} +

+
{step === "intent" && ( - -
- set({intent:"rank"})} title="Purchase a rank" description="Iron £3 · Gold £5 · Diamond £7 — one-time" /> - set({intent:"upgrade"})} title="Upgrade rank" description="Already have a rank? Pay the difference" /> - set({intent:"patron"})} title="Become a patron" description="£5/mo — all cosmetics + Patron badge" /> - set({intent:"custom"})} title="Custom donation" description="Any amount — £5+ unlocks Patron" /> -
-
+
+ + + {errorLine} +
)} {step === "rank" && ( - -
- {(["iron","gold","diamond"] as const).map(id=>{ - const t=(TIERS as any)[id]; - return set({rank:id})} title={`${t.label} — £${(t.price/100).toFixed(2)}`} description={t.perks.join(" · ")} />; - })} -
-
- )} - - {step === "username" && ( - - set({platform: v as any})} className="w-full"> - JavaBedrock - - set({player:e.target.value})} aria-label="Minecraft name" placeholder="Your Minecraft name" /> - - )} - - {step === "upgrade" && ( - - set({upgradeTo:v})} player={ans.player} /> - - )} - - {step === "gift" && ( - -
- chooseGift("no")} title="For me" description="The donation goes to your account" /> - chooseGift("yes")} title="Gift to a friend" description="We'll mail it to them in-game" /> -
-
- )} - - {step === "giftTo" && ( - - set({giftTo:e.target.value})} aria-label="Gift recipient" placeholder="Recipient Minecraft name" /> - +
+ + { set({ rank: id }); setPreview(null); }} onPreview={setPreview} /> + {errorLine} +
)} {step === "amount" && ( - - set({customPounds:e.target.value})} aria-label="Custom amount in pounds" placeholder="Amount in £ e.g. 10" /> -
- set({customRecurring:false})} title="One-time" /> - set({customRecurring:true})} title="Monthly" description="£5+/mo grants Patron" /> -
-
+
+ + set({ customPounds })} + onRecurring={(customRecurring) => set({ customRecurring })} + /> +
+ )} + + {step === "username" && ( +
+ + set({ player })} + onPlatformChange={(platform) => set({ platform })} + /> + {errorLine} +
+ )} + + {step === "gift" && ( +
+ + set({ gift })} + onGiftTo={(giftTo) => set({ giftTo })} + onGiftPlatform={(giftPlatform) => set({ giftPlatform })} + onAnonymous={(anonymous) => set({ anonymous })} + /> + {errorLine} +
+ )} + + {step === "upgrade" && ( +
+ + { set({ upgradeTo }); setPreview(null); }} onPreview={setPreview} rank={rank} name={recipientName} /> + {errorLine} +
)} {step === "confirm" && ( - -
-

- Recipient - {ans.gift==="yes" && ans.giftTo.trim() ? ans.giftTo.trim() : ans.player.trim() || "—"} -

-

- Platform - {ans.platform} -

- {(ans.intent === "rank" || ans.intent === "patron" || ans.intent === "upgrade") && ( -

- Getting - - {ans.intent === "rank" && ans.rank ? (TIERS as any)[ans.rank]?.label : null} - {ans.intent === "patron" ? TIERS.patron.label : null} - {ans.intent === "upgrade" && ans.upgradeTo ? `Upgrade → ${(TIERS as any)[ans.upgradeTo]?.label}` : null} - -

- )} - {ans.intent === "custom" && ( -

- Amount - £{ans.customPounds || "—"}{ans.customRecurring ? " /mo" : " one-time"} -

- )} -
-
+
+ + +
)} -
- +
+ +
+ {last ? ( - ) : ( - + )}
-

Secure via Stripe · Refunds 7 days · Cosmetic only · 1.5% of each donation supports Stripe Climate carbon removal

+

+ Secure via Stripe · Refunds 7 days · Cosmetic only · 1.5% of each donation supports Stripe Climate carbon removal +

diff --git a/src/components/donate-amount.tsx b/src/components/donate-amount.tsx new file mode 100644 index 0000000..a5379f2 --- /dev/null +++ b/src/components/donate-amount.tsx @@ -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 ( +
+ + +
+ {PRESETS.map((n) => { + const on = pounds === String(n); + return ( + + ); + })} +
+ + onRecurring(id === "monthly")} + label="How often" + /> + +
+ {error ? ( +

{error}

+ ) : !valid ? ( +

Enter an amount from £{CUSTOM_MIN / 100} to £{(CUSTOM_MAX / 100).toLocaleString("en-GB")}.

+ ) : tier ? ( + <> +

Unlocks {tier.label}

+

{tier.perks.join(" · ")}

+ + ) : ( +

Under £{TIERS.iron.price / 100} doesn't unlock a rank.

+ )} +
+
+ ); +} diff --git a/src/components/donate-confirm.tsx b/src/components/donate-confirm.tsx new file mode 100644 index 0000000..10aade6 --- /dev/null +++ b/src/components/donate-confirm.tsx @@ -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 ( +
+
+
{recipient || "—"}
+ {!compact && } +
+ +
+
+ {from && ( +
+
Gift from
+
{from}
+
+ )} + {rows.map((r) => ( +
+
{r.label}
+
{r.value}
+
+ ))} +
+
Total
+
{total}
+
+
+ {perks && perks.length > 0 && ( +

{perks.join(" · ")}

+ )} +
+
+ ); +} diff --git a/src/components/donate-gift.tsx b/src/components/donate-gift.tsx new file mode 100644 index 0000000..08f4a43 --- /dev/null +++ b/src/components/donate-gift.tsx @@ -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(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 ( +
+
+ {tiles.map((tile) => { + const checked = gift === tile.id; + const mine = tile.id === "no"; + return ( + + {/* Covers the whole tile; the recipient field sits above it. */} +
+ + {gift === "yes" && ( +
+ {giftPlatform ? ( + + ) : ( +

Pick their edition to look them up.

+ )} + +
+ )} +
+ ); +} diff --git a/src/components/donate-hand.tsx b/src/components/donate-hand.tsx new file mode 100644 index 0000000..6b2bf38 --- /dev/null +++ b/src/components/donate-hand.tsx @@ -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(null); + const hoveredRef = useRef(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 ( +
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 ( +
{ + if (e.pointerType === "touch") return; + hover(i); + }} + > + { 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" + )} + > + {card.title} + {card.description} + + + + {card.foot} + + +
+ ); + })} +
+ ); +} diff --git a/src/components/donate-player.tsx b/src/components/donate-player.tsx new file mode 100644 index 0000000..a0bc84c --- /dev/null +++ b/src/components/donate-player.tsx @@ -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 { + 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")} + /> + + +
+
+ ); +} diff --git a/src/components/donate-podium.tsx b/src/components/donate-podium.tsx new file mode 100644 index 0000000..480244c --- /dev/null +++ b/src/components/donate-podium.tsx @@ -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(null); + const hoveredRef = useRef(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 ( +
+
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 ( + { 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" + )} + > + + {tier.label} + {priceText !== null && {priceText}} + {noteText && {noteText}} + + ); + })} +
+ + {/* The floor the podium stands on. */} + + ); +} diff --git a/src/components/segmented.tsx b/src/components/segmented.tsx new file mode 100644 index 0000000..07d4e91 --- /dev/null +++ b/src/components/segmented.tsx @@ -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({ 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 ( +
+ {options.map((o, i) => { + const active = o.id === value; + return ( + + ); + })} +
+ ); +} diff --git a/src/lib/donate-errors.ts b/src/lib/donate-errors.ts new file mode 100644 index 0000000..4455360 --- /dev/null +++ b/src/lib/donate-errors.ts @@ -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." }; +} diff --git a/src/lib/donations.ts b/src/lib/donations.ts index 569a30d..eb04ece 100644 --- a/src/lib/donations.ts +++ b/src/lib/donations.ts @@ -31,3 +31,7 @@ export function tierForCustom(pence: number, recurring?: boolean): TierId | null if (recurring && pence >= TIERS.patron.price) return "patron"; 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; diff --git a/src/lib/player-lookup.ts b/src/lib/player-lookup.ts new file mode 100644 index 0000000..3edae50 --- /dev/null +++ b/src/lib/player-lookup.ts @@ -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 }; +} diff --git a/src/lib/stripe-appearance.ts b/src/lib/stripe-appearance.ts new file mode 100644 index 0000000..27b5015 --- /dev/null +++ b/src/lib/stripe-appearance.ts @@ -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 }, + }, + }; +} diff --git a/src/lib/use-fine-pointer.ts b/src/lib/use-fine-pointer.ts new file mode 100644 index 0000000..22882c3 --- /dev/null +++ b/src/lib/use-fine-pointer.ts @@ -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); -- 2.45.3