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