{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stats-parts",
  "title": "Stats parts",
  "description": "What the Stats blocks share: a stat and where it comes from, the number that moves into place the first time its section is seen, and the section it stands in.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/animated-number.json",
    "https://kinoui.com/r/hero-parts.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scene.json",
    "https://kinoui.com/r/section-heading.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/stats-parts.tsx",
      "content": "'use client'\n\nimport {\n  AnimatedNumber,\n  localeDirection,\n} from '@/registry/components/kino/animated-number'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { sectionColumnClassName } from '@/registry/lib/hero-parts'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { FOLLOWS_TRANSITION } from '@/registry/lib/resize'\nimport { feelStretch, onScreen, useSeen } from '@/registry/lib/scene'\nimport type { SectionHeadingLevel } from '@/registry/lib/section-heading'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * What the Stats blocks share: a stat and where it comes from, the number\n * that moves into place once the section is seen, and the section it stands\n * in.\n *\n * The page's HTML always holds the real numbers, so a search engine and a\n * page read before its script loads never see a zero. A section already on\n * screen when the page loads stays as it was painted (motion rule 6); one\n * further down drops to zero before it is painted and moves into place, a\n * number at a time, the first time it is seen. Under reduced motion every\n * number is in place from the start. Screen readers hear each value once,\n * never the numbers in between.\n */\n\n/**\n * A stat's figure: a number, which moves into place and is written for the\n * locale, or words that stand still, such as 24/7.\n */\ntype StatFigure =\n  | {\n      value: number\n      /** How the number is written: compact (2.1M), a percentage, a currency, how many decimals. */\n      format?: Intl.NumberFormatOptions\n      /** Written after the number and never moving, such as the + of 135+. */\n      suffix?: string\n    }\n  | { text: string }\n\n/** A figure worth a headline, and what it counts. */\ntype Stat = StatFigure & {\n  /** What it counts, such as teams plan their week in Kino. */\n  label: ReactNode\n  /** A line on why it matters. */\n  description?: ReactNode\n  /** Where the number comes from, so a reader can check it: a status page, a survey. */\n  source?: StatSource\n}\n\ninterface StatSource {\n  label: ReactNode\n  href: string\n}\n\n/** What every Stats block takes, whatever its words. */\ninterface StatsWordsProps {\n  /** A few words above the title that name the topic, such as Kino in numbers. */\n  eyebrow?: ReactNode\n  /** The title's level: `h2` under the page's `h1`. */\n  heading?: SectionHeadingLevel\n  /** The locale the numbers are written in. Give one, so the page's server and browser agree. */\n  locale?: Intl.LocalesArgument\n}\n\n/** The section every arrangement stands in, laid out by its own width. */\nconst statsSectionClassName =\n  '@container/stats relative isolate flex w-full min-w-0 flex-col overflow-x-clip bg-background'\n\n/** The column it sits in, with a section's room above and below, as every landing page section has. */\nconst statsColumnClassName = sectionColumnClassName\n\n/** How long after the one before it each number seen at the same time starts to move, in ms in the default feel. */\nconst STAT_STAGGER_MS = 120\n\ninterface StatsArrivalState {\n  locale: Intl.LocalesArgument\n  /**\n   * How long a number seen now waits before it moves, in ms in the default\n   * feel: none for the first seen in a frame, a stagger more for each after\n   * it, so a row seen at once moves one number after another, in the page's order.\n   */\n  wait: () => number\n}\n\nconst StatsArrivalContext = createContext<StatsArrivalState | null>(null)\n\n/** Where a batch of numbers seen together is: how many have asked to wait, and whether its frame is still open. */\ninterface ArrivalBatch {\n  asked: number\n  open: boolean\n}\n\n/** The wait of the next number in a batch, in ms in the default feel, and the batch after it asks. */\nfunction nextWait(batch: ArrivalBatch): { wait: number; batch: ArrivalBatch } {\n  const asked = batch.open ? batch.asked : 0\n  return { wait: asked * STAT_STAGGER_MS, batch: { asked: asked + 1, open: true } }\n}\n\n/** The locale its numbers are written in, and the stagger between numbers seen at the same time. */\nfunction StatsArrival({\n  locale = 'en-US',\n  children,\n}: {\n  /** The locale the numbers are written in. Give one, so the page's server and browser agree. */\n  locale?: Intl.LocalesArgument\n  children: ReactNode\n}) {\n  const batch = useRef<ArrivalBatch>({ asked: 0, open: false })\n  const value = useMemo(\n    () => ({\n      locale,\n      wait: () => {\n        const next = nextWait(batch.current)\n        if (!batch.current.open) {\n          // The numbers seen in one frame are one batch.\n          requestAnimationFrame(() => {\n            batch.current = { ...batch.current, open: false }\n          })\n        }\n        batch.current = next.batch\n        return next.wait\n      },\n    }),\n    [locale],\n  )\n  return <StatsArrivalContext value={value}>{children}</StatsArrivalContext>\n}\n\n/** A stat's figure alone, for its `StatsNumber`. */\nfunction figureOf(stat: StatFigure): StatFigure {\n  return 'text' in stat\n    ? { text: stat.text }\n    : { value: stat.value, format: stat.format, suffix: stat.suffix }\n}\n\n/**\n * Where a number is: standing at its value with nothing moving (`still`: it\n * was painted so, or motion is reduced), at zero waiting to be seen,\n * `moving` into place, or `settled` there once it has.\n */\ntype StatsNumberPhase = 'still' | 'waiting' | 'moving' | 'settled'\n\n/**\n * A stat's figure: its number moves into place the first time it is seen,\n * `roll`ing each digit up from zero, `spin`ning each through the digits\n * between, or `count`ing through the values between. It holds the room of\n * its final value from the start, and grows into it from its last digit, as\n * an odometer does, so nothing around it moves. At rest it is plain text,\n * so it reads, copies and is found on the page as the words around it are.\n */\nfunction StatsNumber({\n  variant = 'roll',\n  className,\n  ...figure\n}: StatFigure & {\n  /** How it moves into place: rolling each digit up from zero, or counting through the values between. */\n  variant?: 'roll' | 'count'\n  className?: string\n}) {\n  const arrival = use(StatsArrivalContext)\n  const { ref, seen } = useSeen<HTMLSpanElement>()\n  const layer = useRef<HTMLSpanElement>(null)\n  // At its value until it is known to be off screen, so the page's HTML holds the real numbers.\n  const [phase, setPhase] = useState<StatsNumberPhase>('still')\n  const waited = useRef<number | null>(null)\n\n  // Before the first paint: on screen as the page shows it, it stays as it is (motion rule 6);\n  // further down, it drops to zero, which nobody sees, and moves in once it is seen.\n  useLayoutEffect(() => {\n    const element = ref.current\n    if (element && !reducesMotion(element) && !onScreen(element)) setPhase('waiting')\n  }, [ref])\n\n  useEffect(() => {\n    const element = ref.current\n    if (seen !== 'seen' || phase !== 'waiting' || !element) return\n    waited.current ??= arrival?.wait() ?? 0\n    // Stretched by the feel's `enter`, so a slower feel or a tool that slows the roles stretches the wait too.\n    const clock = element.animate([], {\n      duration: waited.current * feelStretch(element),\n      id: FOLLOWS_TRANSITION,\n    })\n    clock.finished.then(\n      () => setPhase('moving'),\n      () => {},\n    )\n    return () => clock.cancel()\n  }, [seen, phase, ref, arrival])\n\n  // Once every move inside it has ended, the moving copy gives way to the plain text under it.\n  useEffect(() => {\n    const moving = layer.current\n    if (phase !== 'moving' || !moving) return\n    let ended = false\n    let frame = 0\n    const settle = () => {\n      const running = moving\n        .getAnimations({ subtree: true })\n        .filter((animation) => animation.playState === 'running')\n      if (running.length === 0) {\n        setPhase('settled')\n        return\n      }\n      void Promise.allSettled(running.map((animation) => animation.finished)).then(() => {\n        if (!ended) frame = requestAnimationFrame(settle)\n      })\n    }\n    // A frame on, so the moves the new value starts are running.\n    frame = requestAnimationFrame(settle)\n    return () => {\n      ended = true\n      cancelAnimationFrame(frame)\n    }\n  }, [phase])\n\n  if ('text' in figure) {\n    return (\n      <span className={cn('tabular-nums', className)}>\n        <bdi>{figure.text}</bdi>\n      </span>\n    )\n  }\n  const { value, format, suffix } = figure\n\n  const locale = arrival?.locale ?? 'en-US'\n  const formatter = numberFormatter(locale, format)\n  const text = formatter.format(value) + (suffix ?? '')\n  const drawn = (phase === 'waiting' || phase === 'moving') && seen !== 'reduced'\n  return (\n    <span\n      ref={ref}\n      data-slot='stats-number'\n      // The number's own direction, so its room fills from its last digit on the side that digit sits.\n      dir={localeDirection(formatter)}\n      // Only as wide as its value, so the moving copy lines up with it wherever it stands.\n      className={cn(\n        'relative inline-block w-fit whitespace-nowrap tabular-nums',\n        className,\n      )}\n    >\n      {/*\n       * The final value as text: it holds the room while the copy over it moves\n       * into it, and it is what screen readers read, search engines find and a\n       * copy takes. Forced colours paint it, so the moving copy goes there.\n       */}\n      <span className={cn(drawn && 'text-transparent')}>{text}</span>\n      {drawn ? (\n        <span\n          ref={layer}\n          aria-hidden\n          className='absolute end-0 top-0 select-none forced-colors:hidden [&_.sr-only]:hidden'\n        >\n          <AnimatedNumber\n            value={phase === 'moving' ? value : 0}\n            locale={locale}\n            format={format}\n            variant={variant}\n          />\n          {suffix}\n        </span>\n      ) : null}\n    </span>\n  )\n}\n\n/**\n * A link to where a number comes from, quiet under it, with an arrow that\n * nudges out on hover. It runs as text, so a long one wraps with the arrow\n * after its last word.\n */\nfunction StatsSource({\n  source,\n  className,\n  ...props\n}: Omit<ComponentProps<'a'>, 'href' | 'children'> & { source: StatSource }) {\n  return (\n    <a\n      data-slot='stats-source'\n      href={source.href}\n      className={cn(\n        'group/source text-muted-foreground hover:text-foreground inline-block py-0.5 text-sm text-pretty underline-offset-4 transition-[color] duration-(--motion-press-duration) ease-(--motion-press-fade-easing) hover:underline focus-visible:rounded-(--control-radius-xs) focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden',\n        className,\n      )}\n      {...props}\n    >\n      <bdi>{source.label}</bdi>\n      <IconPlaceholder\n        lucide='ArrowUpRightIcon'\n        tabler='IconArrowUpRight'\n        hugeicons='ArrowUpRight01Icon'\n        phosphor='ArrowUpRightIcon'\n        remixicon='RiArrowRightUpLine'\n        aria-hidden\n        className='ms-1 inline-block size-4 align-[-0.1875rem] transition-transform duration-(--motion-press-duration) ease-(--motion-press-easing) group-hover/source:translate-x-0.5 group-hover/source:-translate-y-0.5 motion-reduce:transition-none rtl:-scale-x-100 rtl:group-hover/source:-translate-x-0.5'\n      />\n    </a>\n  )\n}\n\nexport {\n  type ArrivalBatch,\n  figureOf,\n  nextWait,\n  STAT_STAGGER_MS,\n  type Stat,\n  type StatFigure,\n  type StatSource,\n  StatsArrival,\n  statsColumnClassName,\n  StatsNumber,\n  statsSectionClassName,\n  StatsSource,\n  type StatsWordsProps,\n}\n",
      "type": "registry:lib",
      "target": "@lib/stats-parts.tsx"
    }
  ],
  "type": "registry:lib"
}