Add glow background and URL-driven steps to donate page #4

Merged
barnabas merged 1 commit from feature/donate-glow-flow into main 2026-10-24 09:57:23 +00:00
3 changed files with 436 additions and 137 deletions

View file

@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Suspense, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { loadStripe, type Appearance } from "@stripe/stripe-js";
import {
CheckoutElementsProvider,
@ -15,11 +16,12 @@ 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 WaveBackground from "@/components/wave-pattern";
import { DonateGlow, type GlowTheme } from "@/components/donate-glow";
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? "");
const DRAFT_KEY = "frg-donate-draft-v1";
const PAYMENT_STEP = "payment";
type Answers = {
intent: string;
@ -351,20 +353,56 @@ function StepShell({ title, description, error, children }: {
);
}
const TIER_GLOW: Record<string, GlowTheme> = { iron: "iron", gold: "gold", diamond: "diamond", patron: "purple" };
// Green until a choice is made, then a colour per intent, then per rank.
function glowFor(ans: Answers, step: string): GlowTheme {
const rankColour = step !== "intent" ? TIER_GLOW[ans.intent === "upgrade" ? ans.upgradeTo : ans.rank] : undefined;
switch (ans.intent) {
case "rank": return rankColour ?? "lime";
case "upgrade": return rankColour ?? "teal";
case "patron": return "purple";
case "custom": return "blue";
default: return "green";
}
}
export default function DonatePage() {
return (
<Suspense fallback={<main className="min-h-dvh bg-background" />}>
<DonateFlow />
</Suspense>
);
}
// The URL is the source of truth for where the visitor is: /donate is the
// landing screen and /donate?step=<name> is a step, so browser back/forward
// walk the flow.
function DonateFlow() {
const stepParam = useSearchParams().get("step");
const [ans, setAns] = useState<Answers>(EMPTY_ANSWERS);
const [restored, setRestored] = useState(false);
const [pending, setPending] = useState<Pending | null>(null);
const [started, setStarted] = useState(false);
const [stepIdx, setStepIdx] = useState(0);
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const set = (patch: Partial<Answers>) => {
setError(null);
// A checkout session no longer matches once an answer changes.
setPending(null);
setAns((a) => ({ ...a, ...patch }));
};
// Each navigation is its own history entry. The depth is kept in
// history.state so the Back button can pop an entry we pushed, instead of
// piling new ones on top, and falls back to replacing on a deep link.
function go(name: string | null, mode: "push" | "replace" = "push") {
const url = name ? `/donate?step=${name}` : "/donate";
const depth: number = window.history.state?.donateDepth ?? 0;
if (mode === "push") window.history.pushState({ donateDepth: depth + 1 }, "", url);
else window.history.replaceState({ donateDepth: depth }, "", url);
}
useEffect(() => {
try {
const raw = localStorage.getItem(DRAFT_KEY);
@ -409,8 +447,9 @@ export default function DonatePage() {
return s;
}, [ans.intent, ans.gift]);
const current = Math.min(stepIdx, steps.length - 1);
const step = steps[current];
const started = stepParam !== null;
const step = stepParam !== null && steps.includes(stepParam) ? stepParam : steps[0];
const current = steps.indexOf(step);
const last = step === "confirm";
function validateStep(name: string): string | null {
@ -429,30 +468,47 @@ export default function DonatePage() {
}
}
// Where the URL should really be: a step is only reachable once every step
// before it is answered, and payment needs a live checkout session. This
// covers reloads, deep links and stale forward entries.
function resolveStep(param: string): string {
if (param === PAYMENT_STEP && pending) return PAYMENT_STEP;
const target = steps.includes(param) ? param : "confirm";
for (const s of steps) {
if (s === target || validateStep(s)) return s;
}
return steps[0];
}
const resolved = restored && stepParam !== null ? resolveStep(stepParam) : null;
// True while the draft is loading or a redirect is about to happen.
const waiting = stepParam !== null && resolved !== stepParam;
useEffect(() => {
if (resolved && resolved !== stepParam) go(resolved, "replace");
}, [resolved, stepParam]);
useEffect(() => {
setError(null);
}, [stepParam]);
function goNext() {
const err = validateStep(step);
if (err) { setError(err); return; }
setError(null);
setStepIdx((i) => Math.min(i + 1, steps.length - 1));
go(steps[Math.min(current + 1, steps.length - 1)]);
}
function goBack() {
setError(null);
setStepIdx((i) => Math.max(i - 1, 0));
if ((window.history.state?.donateDepth ?? 0) > 0) window.history.back();
else go(current > 0 ? steps[current - 1] : null, "replace");
}
// Gift step: pick yes -> "who to?" step, pick no -> move straight on
function chooseGift(choice: "yes" | "no") {
set({ gift: choice });
const s: string[] = ["intent"];
if (ans.intent === "rank") s.push("rank");
s.push("username");
if (ans.intent === "upgrade") s.push("upgrade");
s.push("gift");
if (choice === "yes") s.push("giftTo");
if (ans.intent === "custom") s.push("amount");
s.push("confirm");
setStepIdx(s.indexOf("gift") + 1);
go(choice === "yes" ? "giftTo" : ans.intent === "custom" ? "amount" : "confirm");
}
async function handleSubmit() {
@ -517,6 +573,7 @@ export default function DonatePage() {
forUser: ans.gift === "yes" ? giftToVal : playerVal,
gift: ans.gift === "yes",
});
go(PAYMENT_STEP);
} else toast.error(j.error || "Checkout failed");
} catch {
toast.error("Checkout failed");
@ -531,24 +588,30 @@ export default function DonatePage() {
else goNext();
}
if (pending) {
const glow: GlowTheme = started ? glowFor(ans, step) : "green";
if (stepParam === PAYMENT_STEP && pending && !waiting) {
return (
<main className="min-h-dvh bg-background text-foreground">
<PaymentStage pending={pending} onBack={() => setPending(null)} />
<PaymentStage pending={pending} onBack={() => window.history.back()} />
</main>
);
}
if (waiting) {
return <main className="min-h-dvh bg-background" />;
}
if (!started) {
return (
<main className="relative z-0 min-h-dvh bg-background text-foreground font-mona flex flex-col">
<WaveBackground />
<DonateGlow theme={glow} />
<TopBar />
<div className="flex-1 flex items-center justify-center px-4 py-12">
<div className="max-w-md w-full text-center space-y-6">
<h1 className="text-3xl font-semibold tracking-tight">Support FRG</h1>
<p className="text-sm text-muted-foreground">Ranks are cosmetic only. Your donation keeps the server running and funds new features.</p>
<Button size="lg" onClick={()=>setStarted(true)} className="w-full">Donate</Button>
<Button size="lg" onClick={()=>go("intent")} className="w-full">Donate</Button>
<p className="text-xs text-muted-foreground">Secure via Stripe · 1.5% to <a href="https://stripe.com/gb/climate" target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">Stripe Climate</a></p>
</div>
</div>
@ -557,7 +620,8 @@ export default function DonatePage() {
}
return (
<main className="min-h-dvh bg-background text-foreground font-mona flex flex-col">
<main className="relative z-0 min-h-dvh bg-background text-foreground font-mona flex flex-col">
<DonateGlow theme={glow} />
<TopBar />
<div className="flex-1 flex items-center justify-center px-4 py-8">
<div className="w-full max-w-md">
@ -660,9 +724,7 @@ export default function DonatePage() {
)}
<div className="flex items-center justify-between gap-2">
{current > 1 ? (
<Button type="button" variant="outline" onClick={goBack}>Back</Button>
) : <span />}
{last ? (
<Button type="submit" className="min-w-40" disabled={submitting}>
{submitting ? <Loader2 className="size-4 animate-spin" /> : "Continue to Stripe"}

View file

@ -0,0 +1,349 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Mesh, Program, Renderer, Triangle } from "ogl";
import { cn } from "@/lib/utils";
// Soft gradient glow behind the donate page. It rises from the bottom edge,
// drifts slowly, leans towards the cursor, and fades to a new colour whenever
// `theme` changes. Grain matches the home page's GradientShimmer.
type Color = [number, number, number];
const hex = (value: string): Color => [
parseInt(value.slice(1, 3), 16) / 255,
parseInt(value.slice(3, 5), 16) / 255,
parseInt(value.slice(5, 7), 16) / 255,
];
// Each theme is a two-colour gradient: `a` is the deeper tone, `b` the lighter.
export const GLOW_THEMES = {
green: { a: hex("#2f8a1a"), b: hex("#78c23a") },
lime: { a: hex("#3fd10a"), b: hex("#a6ff3c") },
teal: { a: hex("#0d9488"), b: hex("#5eead4") },
purple: { a: hex("#6d3df0"), b: hex("#4f8bff") },
blue: { a: hex("#2563eb"), b: hex("#38bdf8") },
iron: { a: hex("#64748b"), b: hex("#cbd5e1") },
gold: { a: hex("#f59e0b"), b: hex("#ffe14d") },
diamond: { a: hex("#06b6d4"), b: hex("#67e8f9") },
} as const;
export type GlowTheme = keyof typeof GLOW_THEMES;
const VERTEX_SHADER = `#version 300 es
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
const FRAGMENT_SHADER = `#version 300 es
precision highp float;
uniform vec2 u_size;
uniform float u_time;
uniform vec3 u_a;
uniform vec3 u_b;
uniform vec2 u_mouse; // 0..1, y up
uniform float u_hover;
uniform float u_boost;
out vec4 fragment_color;
float hash(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
vec3 overlayBlend(vec3 base, vec3 blend) {
vec3 low = 2.0 * base * blend;
vec3 high = 1.0 - 2.0 * (1.0 - base) * (1.0 - blend);
return mix(low, high, step(vec3(0.5), base));
}
float blob(vec2 q, vec2 centre, vec2 radius) {
vec2 d = (q - centre) / radius;
return exp(-dot(d, d));
}
void main() {
vec2 uv = gl_FragCoord.xy / u_size;
float aspect = u_size.x / u_size.y;
vec2 q = vec2(uv.x * aspect, uv.y);
float t = u_time;
// Blobs rise from the bottom edge and the upper corners so the middle,
// where the content sits, stays calm.
float w_a = 0.0;
float w_b = 0.0;
w_a += 0.75 * blob(q, vec2(0.24 * aspect + 0.08 * sin(t * 0.23), -0.04 + 0.07 * sin(t * 0.31 + 1.0)), vec2(0.55 * aspect * 0.6, 0.52));
w_b += 0.75 * blob(q, vec2(0.76 * aspect + 0.09 * sin(t * 0.19 + 2.0), -0.06 + 0.06 * sin(t * 0.27)), vec2(0.55 * aspect * 0.6, 0.5));
w_a += 0.5 * blob(q, vec2(0.5 * aspect + 0.16 * sin(t * 0.15), 0.0 + 0.05 * sin(t * 0.21 + 0.5)), vec2(0.5 * aspect * 0.6, 0.34));
w_b += 0.32 * blob(q, vec2(0.96 * aspect + 0.05 * sin(t * 0.17 + 4.0), 1.0 + 0.05 * sin(t * 0.25)), vec2(0.4 * aspect * 0.6, 0.42));
w_a += 0.26 * blob(q, vec2(0.02 * aspect + 0.04 * sin(t * 0.2 + 3.0), 1.02), vec2(0.35 * aspect * 0.6, 0.38));
// A light that follows the cursor.
vec2 mouse = vec2(u_mouse.x * aspect, u_mouse.y);
w_b += blob(q, mouse, vec2(0.3, 0.3)) * u_hover * 0.3;
float total = (w_a + w_b) * (1.0 + 0.35 * u_boost);
vec3 color = (u_a * w_a + u_b * w_b) / max(w_a + w_b, 0.0001);
float alpha = 1.0 - exp(-total * 0.95);
alpha = min(alpha, 0.9) * 0.9;
// Film grain on CSS pixels, same recipe as the home page.
vec2 cell = floor(gl_FragCoord.xy);
vec3 shift = vec3(hash(cell + 17.0), hash(cell + 29.0), hash(cell + 41.0)) - 0.5;
float luminance = 0.565 + (hash(cell) - 0.5) * 0.376;
vec3 grain = clamp(vec3(luminance) + shift * 0.125, 0.0, 1.0);
color = mix(color, overlayBlend(color, grain), 0.35);
fragment_color = vec4(color * alpha, alpha);
}
`;
const lerp = (from: number, to: number, amount: number) => from + (to - from) * amount;
export function DonateGlow({ theme, className }: { theme: GlowTheme; className?: string }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const themeRef = useRef<GlowTheme>(theme);
const themeChangedRef = useRef<() => void>(() => {});
const [failed, setFailed] = useState(false);
const [visible, setVisible] = useState(false);
useEffect(() => {
themeRef.current = theme;
themeChangedRef.current();
}, [theme]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) {
return;
}
let renderer: Renderer;
try {
renderer = new Renderer({
canvas,
alpha: true,
antialias: false,
depth: false,
premultipliedAlpha: true,
dpr: 1,
webgl: 2,
});
} catch {
// eslint-disable-next-line react-hooks/set-state-in-effect
setFailed(true);
return;
}
const { gl } = renderer;
if (!gl || !renderer.isWebgl2) {
setFailed(true);
return;
}
gl.clearColor(0, 0, 0, 0);
const start = GLOW_THEMES[themeRef.current];
const colorA: Color = [...start.a];
const colorB: Color = [...start.b];
const uniforms = {
u_size: { value: [1, 1] },
u_time: { value: 0 },
u_a: { value: colorA },
u_b: { value: colorB },
u_mouse: { value: [0.5, 0.5] },
u_hover: { value: 0 },
u_boost: { value: 0 },
};
const geometry = new Triangle(gl);
const program = new Program(gl, {
vertex: VERTEX_SHADER,
fragment: FRAGMENT_SHADER,
uniforms,
cullFace: false,
depthTest: false,
depthWrite: false,
});
const mesh = new Mesh(gl, { geometry, program, frustumCulled: false });
const reducedMotionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
let time = Math.random() * 30;
let lastFrame: number | null = null;
let animationFrame: number | null = null;
// A small swell when the theme changes: the target eases in and decays,
// and the value follows it, so there is never a sudden jump.
let boost = 0;
let boostTarget = 0;
let hoverTarget = 0;
const target = { x: 0.5, y: 0.5 };
const current = { x: 0.5, y: 0.5 };
let seenPointer = false;
const render = () => {
uniforms.u_time.value = time;
uniforms.u_boost.value = boost;
renderer.render({ scene: mesh, clear: true, update: false, sort: false, frustumCull: false });
};
const resize = () => {
const rect = canvas.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
renderer.setSize(width, height);
canvas.style.width = "";
canvas.style.height = "";
uniforms.u_size.value = [width, height];
};
const frame = (now: number) => {
animationFrame = null;
const dt = lastFrame === null ? 0 : Math.min((now - lastFrame) / 1000, 0.064);
lastFrame = now;
time += dt;
const goal = GLOW_THEMES[themeRef.current];
const fade = 1 - Math.exp(-dt * 3);
for (let i = 0; i < 3; i++) {
colorA[i] = lerp(colorA[i]!, goal.a[i]!, fade);
colorB[i] = lerp(colorB[i]!, goal.b[i]!, fade);
}
const follow = 1 - Math.exp(-dt * 4);
current.x = lerp(current.x, target.x, follow);
current.y = lerp(current.y, target.y, follow);
uniforms.u_mouse.value = [current.x, current.y];
uniforms.u_hover.value = lerp(uniforms.u_hover.value, hoverTarget, 1 - Math.exp(-dt * 3));
boost = lerp(boost, boostTarget, 1 - Math.exp(-dt * 5));
boostTarget *= Math.exp(-dt * 1.4);
render();
schedule();
};
const schedule = () => {
if (animationFrame !== null || reducedMotionQuery.matches) {
return;
}
animationFrame = requestAnimationFrame(frame);
};
// Reduced motion: no loop, so snap to the colour and draw one still frame.
const drawStill = () => {
const goal = GLOW_THEMES[themeRef.current];
for (let i = 0; i < 3; i++) {
colorA[i] = goal.a[i]!;
colorB[i] = goal.b[i]!;
}
boost = 0;
boostTarget = 0;
uniforms.u_hover.value = 0;
render();
};
themeChangedRef.current = () => {
if (reducedMotionQuery.matches) {
drawStill();
return;
}
boostTarget = 1;
};
const onPointerMove = (event: PointerEvent) => {
if (reducedMotionQuery.matches || event.pointerType === "touch") {
return;
}
target.x = event.clientX / window.innerWidth;
target.y = 1 - event.clientY / window.innerHeight;
if (!seenPointer) {
seenPointer = true;
current.x = target.x;
current.y = target.y;
}
hoverTarget = 1;
};
const onPointerLeave = () => {
hoverTarget = 0;
};
const onMotionChange = () => {
lastFrame = null;
if (reducedMotionQuery.matches) {
if (animationFrame !== null) {
cancelAnimationFrame(animationFrame);
animationFrame = null;
}
drawStill();
return;
}
schedule();
};
resize();
render();
requestAnimationFrame(() => setVisible(true));
schedule();
const resizeObserver = new ResizeObserver(() => {
resize();
render();
});
resizeObserver.observe(canvas);
window.addEventListener("pointermove", onPointerMove, { passive: true });
document.documentElement.addEventListener("pointerleave", onPointerLeave);
reducedMotionQuery.addEventListener("change", onMotionChange);
return () => {
themeChangedRef.current = () => {};
setVisible(false);
if (animationFrame !== null) {
cancelAnimationFrame(animationFrame);
}
resizeObserver.disconnect();
window.removeEventListener("pointermove", onPointerMove);
document.documentElement.removeEventListener("pointerleave", onPointerLeave);
reducedMotionQuery.removeEventListener("change", onMotionChange);
geometry.remove();
program.remove();
};
}, []);
const [a, b] = [GLOW_THEMES[theme].a, GLOW_THEMES[theme].b].map(
(c) => `rgb(${c.map((v) => Math.round(v * 255)).join(" ")})`,
);
// Sits behind the page content: the parent needs its own stacking context
// (relative z-0) so -z-10 paints above its background but below its children.
return (
<div
aria-hidden="true"
className={cn("pointer-events-none fixed inset-0 -z-10 overflow-hidden", className)}
style={failed ? { background: `radial-gradient(ellipse 80% 50% at 50% 110%, ${a}, transparent), radial-gradient(ellipse 50% 40% at 100% 0%, color-mix(in srgb, ${b} 20%, transparent), transparent)` } : undefined}
>
<canvas
ref={canvasRef}
className={cn("block size-full transition-opacity duration-700", visible ? "opacity-100" : "opacity-0", failed && "hidden")}
/>
</div>
);
}

View file

@ -1,112 +0,0 @@
"use client"
import { useEffect, useRef } from "react"
import { cn } from "@/lib/utils"
export default function GridBackground({ className }: { className?: string }) {
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext("2d")
if (!ctx) return
let animationId: number
let width = 0
let height = 0
const PIXEL_SIZE = 6
const WAVE_SPEED = 0.012
const WAVE_AMP = 0.10
const WAVE_FREQ = 2.8
const FALLOFF = 0.35 // how far upward the glow reaches
const resize = () => {
const dpr = window.devicePixelRatio || 1
width = window.innerWidth
height = window.innerHeight
canvas.width = width * dpr
canvas.height = height * dpr
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
}
resize()
let t = 0
const bayer4x4 = [
[0.0, 0.5, 0.125, 0.625],
[0.75, 0.25, 0.875, 0.375],
[0.1875, 0.6875, 0.0625, 0.5625],
[0.9375, 0.4375, 0.8125, 0.3125]
]
const draw = () => {
ctx.clearRect(0, 0, width, height)
// Prioritize the 'dark' class set by next-themes to avoid system overrides
const isDark = document.documentElement.classList.contains("dark")
// Use the theme's primary colour (falls back to foreground)
const cs = getComputedStyle(document.documentElement)
const primary = cs.getPropertyValue("--primary").trim() || cs.getPropertyValue("--foreground").trim()
const alpha = isDark ? 0.18 : 0.14
const cols = Math.ceil(width / PIXEL_SIZE) + 1
const rows = Math.ceil(height / PIXEL_SIZE) + 1
// Falloff reaches upward from the wave
const falloffPx = FALLOFF * height
const amp = WAVE_AMP * height
// color-mix applies the alpha since --primary may be any CSS colour format
ctx.fillStyle = `color-mix(in oklab, ${primary} ${alpha * 100}%, transparent)`
for (let row = 0; row <= rows; row++) {
for (let col = 0; col <= cols; col++) {
const x = col * PIXEL_SIZE
const y = row * PIXEL_SIZE
const wx = (x / width) * Math.PI * 2 * WAVE_FREQ
// Move the wave lower (75% down the screen)
const waveY = (height * 0.90) - amp * Math.sin(wx + t)
// dist: 0 = at or below the wave, positive = above wave
const dist = Math.max(0, waveY - y)
// intensity: 1 = at wave line, 0 = far above it
let intensity = Math.max(0, 1 - dist / falloffPx)
intensity = intensity * intensity
// Dither check: below waveY is always intensity 1, so it draws solid
if (intensity <= bayer4x4[row % 4][col % 4]) continue
ctx.fillRect(x, y, PIXEL_SIZE, PIXEL_SIZE)
}
}
t += WAVE_SPEED
animationId = requestAnimationFrame(draw)
}
draw()
const onResize = () => {
ctx.resetTransform()
resize()
}
window.addEventListener("resize", onResize)
return () => {
cancelAnimationFrame(animationId)
window.removeEventListener("resize", onResize)
}
}, [])
return (
<canvas
ref={canvasRef}
aria-hidden="true"
style={{ width: "100%", height: "100%" }}
className={cn("pointer-events-none fixed inset-0 -z-10", className)}
/>
)
}