"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";/* ───────────────────────────────────────────────────────── * LEADERBOARD: where you stand, and what it takes to move up * * to pass under the board a line of hairlines measures you * against the person just above you: it fills as you * score, with "184 pts to pass Mira" rolling down as * it goes. You can always see how close the next place is * overtake when you (or anyone) pass someone, the climber swings * out a lane, passes, and settles in its new place while * the one passed drops back; the ranks roll and a small * ▲2 shows beside the climber for a moment * pinned outside the top few, your own row stays pinned under * them, so you never scroll to find yourself * lead in first place the line becomes your lead over second * * Scores are yours: pass entries and who you are; the board sorts, * ranks and animates whatever changes. * ───────────────────────────────────────────────────────── */export interface LeaderEntry { id: string; name: string; score: number; /** An image URL; initials are drawn without one. */ avatar?: string;}export interface LeaderboardProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title"> { entries: LeaderEntry[]; /** The id of the person looking. */ you?: string; title?: string; /** e.g. "This week". */ period?: string; /** After scores, e.g. "pts" or "XP". */ unit?: string; /** How many rows show before your pinned row. */ top?: number; locale?: string;}const EASE = "cubic-bezier(0.16,1,0.3,1)";const ROW = 46;const TICKS = "repeating-linear-gradient(to right, #000 0 2px, transparent 2px 4px)";const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(reducedQuery); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const subscribeNothing = () => () => {};const useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);const mix = (color: string, amount: number, into = "transparent") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;const hue = (seed: string) => { let h = 0; for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0; return `var(--chart-${(h % 5) + 1}, var(--primary))`;};const initials = (name: string) => name .split(/\s+/) .filter(Boolean) .slice(0, 2) .map((w) => w[0]?.toUpperCase()) .join("");export function Leaderboard({ entries, you, title = "Leaderboard", period, unit = "pts", top = 5, locale, className = "", ...props }: LeaderboardProps) { const reduced = useReducedMotion(); const hydrated = useHydrated(); const loc = locale ?? (hydrated ? undefined : "en-US"); const ranked = React.useMemo(() => [...entries].sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)), [entries]); const rank = new Map(ranked.map((e, i) => [e.id, i + 1])); const meIndex = you ? ranked.findIndex((e) => e.id === you) : -1; const me = meIndex >= 0 ? ranked[meIndex] : null; const pinned = me && meIndex >= top; const shown = ranked.slice(0, top); // Rank moves since the last order, kept a moment for the ▲ chips. const orderKey = ranked.map((e) => e.id).join("|"); const [last, setLast] = React.useState({ key: orderKey, ranks: rank }); const [moves, setMoves] = React.useState<Record<string, { delta: number; live: boolean; at: number }>>({}); if (last.key !== orderKey) { const next = { ...moves }; let stamp = Object.values(moves).reduce((m, v) => Math.max(m, v.at), 0); ranked.forEach((e) => { const before = last.ranks.get(e.id); const now = rank.get(e.id)!; if (before !== undefined && before > now) next[e.id] = { delta: before - now, live: true, at: ++stamp }; }); setMoves(next); setLast({ key: orderKey, ranks: rank }); } React.useEffect(() => { const liveOnes = Object.entries(moves).filter(([, m]) => m.live); if (!liveOnes.length) return; const timer = window.setTimeout(() => setMoves((m) => Object.fromEntries(Object.entries(m).map(([id, v]) => [id, { ...v, live: false }]))), 2200); return () => window.clearTimeout(timer); }, [moves]); // The person to pass, and how far you've closed on them since they became your target. const target = me && meIndex > 0 ? ranked[meIndex - 1] : null; const gap = target && me ? target.score - me.score + 1 : 0; const lead = me && meIndex === 0 && ranked[1] ? me.score - ranked[1].score : 0; const [start, setStart] = React.useState<{ id: string | null; gap: number }>({ id: target?.id ?? null, gap }); if ((target?.id ?? null) !== start.id) setStart({ id: target?.id ?? null, gap }); const fill = target ? Math.max(0.02, Math.min(1, 1 - gap / Math.max(1, start.id === target.id ? start.gap : gap))) : 1; // Overtakes: rows glide from where they were; climbers swing out a lane to pass. const rowRefs = React.useRef(new Map<string, HTMLElement>()); const tops = React.useRef(new Map<string, number>()); React.useLayoutEffect(() => { const prev = tops.current; const now = new Map<string, number>(); rowRefs.current.forEach((el, id) => now.set(id, el.offsetTop)); tops.current = now; if (reduced) return; now.forEach((y, id) => { const from = prev.get(id); const el = rowRefs.current.get(id); if (from === undefined || !el || from === y) return; const dy = from - y; el.getAnimations().forEach((a) => a.cancel()); if (dy > 0) { // Climbing: out a lane, past, and back in. el.style.zIndex = "1"; const a = el.animate( [ { transform: `translate(0, ${dy}px)` }, { transform: `translate(12px, ${dy * 0.5}px) scale(1.015)`, offset: 0.45 }, { transform: "none" }, ], { duration: 760, easing: "cubic-bezier(0.45,0,0.2,1)" }, ); a.onfinish = a.oncancel = () => (el.style.zIndex = ""); } else { el.animate([{ transform: `translate(0, ${dy}px)`, opacity: 1 }, { opacity: 0.7, offset: 0.5 }, { transform: "none", opacity: 1 }], { duration: 760, easing: "cubic-bezier(0.45,0,0.2,1)" }); } }); }, [orderKey, reduced]); const fmt = (v: number) => new Intl.NumberFormat(loc).format(v); const row = (e: LeaderEntry, i: number, isPinned = false) => { const mine = e.id === you; const color = hue(e.name); const move = moves[e.id]; const r = i + 1; return ( <li key={isPinned ? `${e.id}-pinned` : e.id} ref={(el) => { if (isPinned) return; if (el) rowRefs.current.set(e.id, el); else rowRefs.current.delete(e.id); }} className="relative flex items-center gap-2.5 rounded-[12px] px-2 @[20rem]:gap-3 @[20rem]:px-2.5" /* Your row is a solid step of grey, no border. */ style={{ height: ROW, background: mine ? "var(--muted)" : undefined }} aria-current={mine ? "true" : undefined} > <span className={`w-6 shrink-0 text-right text-[13px] tabular-nums ${r <= 3 ? "font-semibold text-foreground" : "text-muted-foreground"}`}> <NumberRoll value={r} duration={700} /> </span> {e.avatar ? ( // eslint-disable-next-line @next/next/no-img-element <img src={e.avatar} alt="" className="size-7 shrink-0 rounded-full object-cover" /> ) : ( <span aria-hidden="true" className="flex size-7 shrink-0 items-center justify-center rounded-full text-[10.5px] font-semibold" style={{ background: mix(color, 20, "var(--background)"), color: mix(color, 80, "var(--foreground)") }}> {initials(e.name)} </span> )} <span className="flex min-w-0 flex-1 items-center gap-2"> <span className={`truncate text-[13.5px] ${mine ? "font-medium text-foreground" : "text-foreground"}`}>{mine ? `${e.name} (you)` : e.name}</span> <span aria-hidden="true" className="shrink-0 rounded-full px-1.5 text-[10.5px] font-medium tabular-nums text-emerald-600 transition-[opacity,translate] duration-500 dark:text-emerald-400" style={{ opacity: move?.live ? 1 : 0, translate: move?.live ? "0 0" : "0 3px", background: mix("var(--color-emerald-500, #10b981)", 12), transitionTimingFunction: EASE }} > ▲{move?.delta ?? 1} </span> </span> <span className="shrink-0 text-[13.5px] font-medium tabular-nums text-foreground"> <NumberRoll value={e.score} locales={loc} duration={700} /> <span className="ml-1 hidden text-[11.5px] font-normal text-muted-foreground @[20rem]:inline">{unit}</span> </span> </li> ); }; return ( <div className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}> <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 400px)" }} /> <div className="@container w-full"> <div className="flex items-baseline justify-between gap-3 px-4 pb-2 pt-4 sm:px-5"> <p className="truncate text-[15px] font-medium tracking-[-0.01em] text-foreground">{title}</p> {period && <p className="shrink-0 text-[12px] text-muted-foreground">{period}</p>} </div> <ol aria-label={title} className="relative px-2 sm:px-3"> {shown.map((e, i) => row(e, i))} </ol> {pinned && me && ( <> <div aria-hidden="true" className="mx-5 my-1 flex justify-center gap-1"> {[0, 1, 2].map((d) => ( <span key={d} className="size-1 rounded-full bg-muted-foreground/40" /> ))} </div> <ol aria-label="Your place" className="px-2 sm:px-3"> {row(me, meIndex, true)} </ol> </> )} {me && ( <div className="mx-4 mb-4 mt-3 rounded-[14px] px-3.5 py-3 sm:mx-5" style={{ background: mix("var(--foreground)", 4) }}> <p className="flex items-baseline justify-between gap-2 text-[12.5px]"> <span className="min-w-0 truncate text-muted-foreground"> {target ? ( <> <span className="font-medium tabular-nums text-foreground"> <NumberRoll value={gap} locales={loc} duration={600} direction="down" /> </span>{" "} {unit} to pass <TextMorph>{target.name}</TextMorph> </> ) : ( <> You lead by{" "} <span className="font-medium tabular-nums text-foreground"> <NumberRoll value={lead} locales={loc} duration={600} /> </span>{" "} {unit} </> )} </span> <span className="shrink-0 tabular-nums text-muted-foreground"> <TextMorph>{target ? `#${meIndex + 1} → #${meIndex}` : "#1"}</TextMorph> </span> </p> <div aria-hidden="true" className="relative mt-2.5 h-3"> <div className="absolute inset-0" style={{ background: mix("var(--foreground)", 14), maskImage: TICKS, WebkitMaskImage: TICKS }} /> <div className="absolute inset-y-0 left-0 w-full origin-left" style={{ background: target ? "linear-gradient(90deg, var(--primary), color-mix(in oklab, var(--primary) 65%, var(--chart-3, var(--primary))))" : "var(--color-emerald-500, #10b981)", maskImage: TICKS, WebkitMaskImage: TICKS, transform: `scaleX(${fill})`, transition: reduced ? "none" : `transform 700ms ${EASE}`, }} /> </div> </div> )} </div> <p className="sr-only" aria-live="polite"> {/* Only your place is announced, never the scores ticking. */} {me ? `You are in place ${fmt(meIndex + 1)}${target ? `, next to pass is ${target.name}` : ", in the lead"}.` : ""} </p> </div> );}