{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"leaderboard","type":"registry:component","title":"Leaderboard","description":"Players glide past each other to their new ranks.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/leaderboard.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport Image from \"next/image\";\nimport { AnimatePresence, motion, useSpring, useTransform } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Player = { id: string; name: string; score: number; avatar?: string };\n\nconst ROW_H = 52;\nconst AVATAR = 32;\n// Rows glide to their new rank. Critically damped, so a row never\n// overshoots into the slot of the player it just passed.\nconst REORDER = { type: \"spring\", visualDuration: 0.45, bounce: 0 } as const;\nconst ROLL = { type: \"spring\", visualDuration: 0.35, bounce: 0 } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst SCORE = { visualDuration: 0.45, bounce: 0 };\n\nconst number = new Intl.NumberFormat(\"en-US\");\n\nexport function Leaderboard({\n  players,\n  moves = {},\n  label = \"Leaderboard\",\n  className,\n}: {\n  players: Player[];\n  /** Places each player just gained (positive) or lost (negative). */\n  moves?: Record<string, number>;\n  label?: string;\n  className?: string;\n}) {\n  const ranked = [...players].sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));\n\n  return (\n    // Rows are placed by transform, not flow, so the list keeps one fixed\n    // height however the ranks shuffle.\n    <ol\n      aria-label={label}\n      className={cn(\"relative w-full\", className)}\n      style={{ height: ranked.length * ROW_H }}\n    >\n      {ranked.map((p, i) => (\n        <Row key={p.id} player={p} rank={i + 1} move={moves[p.id] ?? 0} />\n      ))}\n    </ol>\n  );\n}\n\nfunction Row({ player, rank, move }: { player: Player; rank: number; move: number }) {\n  const reduceMotion = useReducedMotion();\n  const score = useSpring(player.score, SCORE);\n  const scoreText = useTransform(score, (v) => number.format(Math.round(v)));\n\n  useEffect(() => {\n    if (reduceMotion) score.jump(player.score);\n    else score.set(player.score);\n  }, [player.score, reduceMotion, score]);\n\n  return (\n    <motion.li\n      initial={false}\n      animate={{ y: (rank - 1) * ROW_H }}\n      transition={reduceMotion ? { duration: 0 } : REORDER}\n      className={cn(\n        \"absolute inset-x-0 top-0 flex items-center gap-3 rounded-xl bg-muted px-3\",\n        // Climbers pass over fallers, so crossing rows never interleave.\n        move > 0 ? \"z-[2]\" : move < 0 ? \"z-[1]\" : \"z-0\",\n      )}\n      style={{ height: ROW_H }}\n    >\n      <Rank rank={rank} reduceMotion={!!reduceMotion} />\n      <Avatar player={player} />\n      <span className=\"min-w-0 flex-1 truncate text-[15px] text-foreground\">\n        <span className=\"sr-only\">{ordinal(rank)}, </span>\n        {player.name}\n        <span className=\"sr-only\">, {number.format(player.score)} points</span>\n      </span>\n      <Movement move={move} reduceMotion={!!reduceMotion} />\n      <motion.span\n        aria-hidden\n        className=\"w-16 text-right text-[15px] font-medium text-foreground tabular-nums\"\n      >\n        {scoreText}\n      </motion.span>\n    </motion.li>\n  );\n}\n\nfunction Rank({ rank, reduceMotion }: { rank: number; reduceMotion: boolean }) {\n  // Remembers which way the rank last changed, so the old number rolls\n  // out the way the row is heading and the new one follows it in.\n  const [seen, setSeen] = useState({ rank, direction: 0 });\n  if (seen.rank !== rank) setSeen({ rank, direction: rank < seen.rank ? 1 : -1 });\n  const direction = seen.direction;\n\n  const podium = rank <= 3;\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        \"relative grid size-7 shrink-0 place-items-center overflow-hidden rounded-full text-sm tabular-nums\",\n        \"transition-[background-color,color] duration-200 ease-out\",\n        // A restrained podium: the leader inverts, second and third get a\n        // quiet tint, everyone else is plain muted text.\n        rank === 1 && \"bg-foreground font-semibold text-background\",\n        podium && rank !== 1 && \"bg-foreground/10 font-semibold text-foreground\",\n        !podium && \"text-muted-foreground\",\n      )}\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\" custom={direction}>\n        <motion.span\n          key={rank}\n          custom={direction}\n          variants={{\n            enter: (d: number) => ({ y: reduceMotion ? 0 : `${d * 100}%`, opacity: 0 }),\n            idle: { y: \"0%\", opacity: 1 },\n            exit: (d: number) => ({ y: reduceMotion ? 0 : `${-d * 100}%`, opacity: 0 }),\n          }}\n          initial=\"enter\"\n          animate=\"idle\"\n          exit=\"exit\"\n          transition={ROLL}\n          className=\"col-start-1 row-start-1\"\n        >\n          {rank}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction Avatar({ player }: { player: Player }) {\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        \"grid shrink-0 place-items-center overflow-hidden rounded-full text-xs font-medium\",\n        // Line-drawn faces are black ink, so they sit on a light circle in\n        // both themes; initials take the theme's own tint.\n        player.avatar ? \"bg-[oklch(0.97_0_0)]\" : \"bg-foreground/[0.07] text-foreground\",\n        \"outline-1 -outline-offset-1 outline-foreground/10\",\n      )}\n      style={{ width: AVATAR, height: AVATAR }}\n    >\n      {player.avatar ? (\n        <Image\n          src={player.avatar}\n          alt=\"\"\n          width={AVATAR}\n          height={AVATAR}\n          unoptimized\n          draggable={false}\n          className=\"size-full\"\n        />\n      ) : (\n        initials(player.name)\n      )}\n    </span>\n  );\n}\n\nfunction Movement({ move, reduceMotion }: { move: number; reduceMotion: boolean }) {\n  // Keeps the last change on screen while it fades out, so the arrow never\n  // empties mid-exit.\n  const [last, setLast] = useState(move);\n  if (move !== 0 && move !== last) setLast(move);\n  const visible = move !== 0;\n  const up = last > 0;\n  const hidden = reduceMotion ? { opacity: 0 } : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n\n  return (\n    <motion.span\n      aria-hidden\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={ICON_SWAP}\n      className={cn(\n        \"flex w-9 shrink-0 items-center justify-end gap-0.5 text-xs font-medium tabular-nums\",\n        up ? \"text-foreground\" : \"text-muted-foreground\",\n      )}\n    >\n      <svg\n        viewBox=\"0 0 12 12\"\n        className={cn(\"size-3\", !up && \"rotate-180\")}\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        <path d=\"M6 9.5v-7M3 5.5l3-3 3 3\" />\n      </svg>\n      {Math.abs(last)}\n    </motion.span>\n  );\n}\n\nfunction initials(name: string) {\n  return name\n    .split(\" \")\n    .map((part) => part[0])\n    .join(\"\")\n    .slice(0, 2);\n}\n\nfunction ordinal(n: number) {\n  const suffix = { one: \"st\", two: \"nd\", few: \"rd\", other: \"th\" } as const;\n  const rule = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" }).select(n);\n  return `${n}${suffix[rule as keyof typeof suffix] ?? \"th\"}`;\n}\n\nfunction mulberry32(seed: number) {\n  return () => {\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n// Faces are \"Notionists\" by Zoish, CC0 1.0, stored in public/avatars.\nconst PLAYERS: Player[] = [\n  { id: \"ava\", name: \"Amara Okafor\", score: 2480, avatar: \"/avatars/ava.svg\" },\n  { id: \"ben\", name: \"Jonas Weber\", score: 2310, avatar: \"/avatars/ben.svg\" },\n  { id: \"cara\", name: \"Mei Tanaka\", score: 2265, avatar: \"/avatars/cara.svg\" },\n  { id: \"dev\", name: \"Rafael Costa\", score: 2140, avatar: \"/avatars/dev.svg\" },\n  { id: \"fay\", name: \"Sara Lindqvist\", score: 2055, avatar: \"/avatars/fay.svg\" },\n  { id: \"gus\", name: \"Gus Holm\", score: 1990 },\n  { id: \"ivy\", name: \"Ivy Nakamura\", score: 1920 },\n  { id: \"jon\", name: \"Jon Reyes\", score: 1875 },\n];\n// Long enough to spot who moved, short enough to be gone before the next\n// round is likely to be played.\nconst MOVE_CUE_MS = 1600;\n\nfunction rankOf(players: Player[]) {\n  const order = [...players].sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));\n  return Object.fromEntries(order.map((p, i) => [p.id, i]));\n}\n\nexport default function LeaderboardDemo() {\n  const [players, setPlayers] = useState(PLAYERS);\n  const [moves, setMoves] = useState<Record<string, number>>({});\n  const [round, setRound] = useState(1);\n  const random = useRef(mulberry32(42));\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  const simulate = () => {\n    const before = rankOf(players);\n    // Gains overlap the gaps between players, so most rounds reshuffle a\n    // few places without turning the whole table upside down.\n    const next = players.map((p) => ({\n      ...p,\n      score: p.score + Math.round(random.current() ** 1.5 * 260),\n    }));\n    const after = rankOf(next);\n    setPlayers(next);\n    setMoves(Object.fromEntries(next.map((p) => [p.id, before[p.id] - after[p.id]])));\n    setRound((r) => r + 1);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setMoves({}), MOVE_CUE_MS);\n  };\n\n  const leader = players.reduce((a, b) => (b.score > a.score ? b : a));\n\n  return (\n    <div className=\"flex w-[440px] max-w-full flex-col gap-4\">\n      <div className=\"flex items-center justify-between gap-4\">\n        <div>\n          <p className=\"text-[15px] font-medium text-foreground\">Weekly league</p>\n          <p className=\"text-sm text-muted-foreground tabular-nums\">Round {round}</p>\n        </div>\n        <button\n          type=\"button\"\n          onClick={simulate}\n          className=\"h-9 touch-manipulation rounded-full bg-background px-4 text-sm font-medium text-foreground shadow-raised transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n        >\n          Simulate round\n        </button>\n      </div>\n      {/* 6px of padding around 12px row radii keeps the corners concentric:\n          18 = 12 + 6. */}\n      <div className=\"rounded-[18px] bg-muted p-1.5\">\n        <Leaderboard players={players} moves={moves} label=\"Weekly league standings\" />\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {round > 1 ? `Round ${round}. ${leader.name} leads with ${number.format(leader.score)} points.` : \"\"}\n      </p>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/leaderboard"}