{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "animated-number",
  "title": "Animated number",
  "description": "A number that moves to its new value when it changes, written for its locale: each digit that changed rolls to its new one, spins through the digits between, or the whole number counts. A screen reader hears the value once, never the numbers in between.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/roll.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/run-progress.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/animated-number.tsx",
      "content": "'use client'\n\nimport { formatOptionsOf, numberFormatter } from '@/registry/lib/number-format'\nimport { followSize } from '@/registry/lib/resize'\nimport { Roll } from '@/registry/lib/roll'\nimport { registerProgress, runProgress, stopProgress } from '@/registry/lib/run-progress'\nimport { Swap } from '@/registry/lib/swap'\nimport { mergeProps, type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A number that moves to its new value when it changes, written for its\n * locale. `roll` rolls each digit that differs to its new one, `spin` spins\n * each through the digits between, and `count` counts the whole number\n * through the values between. The number drawn is for the eye only; screen\n * readers get the value once, never the numbers in between.\n */\n\ntype NumberProps = Omit<PartProps<'span'>, 'className' | 'children'> & {\n  className?: string\n  value: number\n  /** The locale the value is written in. Give one, so the page's server and browser agree. */\n  locale?: Intl.LocalesArgument\n  /** How the value is written: a currency, a percentage, a unit, how many decimals. */\n  format?: Intl.NumberFormatOptions\n}\n\nconst RTL_LANGUAGES = new Set([\n  'ar',\n  'ckb',\n  'dv',\n  'fa',\n  'he',\n  'ks',\n  'ps',\n  'sd',\n  'ug',\n  'ur',\n  'yi',\n])\n\n/** Which way the value's locale writes, so a currency or sign sits on the side its readers expect. */\nfunction localeDirection(formatter: Intl.NumberFormat): 'ltr' | 'rtl' {\n  const { language } = new Intl.Locale(formatter.resolvedOptions().locale)\n  return RTL_LANGUAGES.has(language) ? 'rtl' : 'ltr'\n}\n\nconst SIGN_PARTS = new Set(['minusSign', 'plusSign', 'approximatelySign'])\n\nconst NUMBER_PARTS = new Set([\n  'integer',\n  'group',\n  'decimal',\n  'fraction',\n  'nan',\n  'infinity',\n])\n\n/**\n * The value as it shows, split where it moves: its sign when it leads, what\n * else comes before the number (a currency), the number, and what comes\n * after (a percent sign, a unit, K). `tail` is how many of the number's characters come after its\n * whole part, so its digits line up on the decimal point.\n */\nfunction numberParts(formatter: Intl.NumberFormat, value: number) {\n  const parts = formatter.formatToParts(value)\n  const first = parts.findIndex((part) => NUMBER_PARTS.has(part.type))\n  const last = parts.findLastIndex((part) => NUMBER_PARTS.has(part.type))\n  const join = (from: number, to: number) =>\n    parts\n      .slice(from, to)\n      .map((part) => part.value)\n      .join('')\n  const number = parts.slice(first, last + 1)\n  const signed = parts.findIndex((part) => !SIGN_PARTS.has(part.type))\n  const sign = Math.min(signed === -1 ? parts.length : signed, first)\n  return {\n    text: join(0, parts.length),\n    sign: join(0, sign),\n    prefix: join(sign, first),\n    number: number.map((part) => part.value).join(''),\n    suffix: join(last + 1, parts.length),\n    tail: number\n      .filter((part) => part.type === 'decimal' || part.type === 'fraction')\n      .reduce((length, part) => length + part.value.length, 0),\n  }\n}\n\n// Count is timed by CSS: a transition runs this from 0 to 1 in the feel's timing,\n// and each frame writes the number at that point.\nconst PROGRESS = '--animated-number-progress'\n\nconst decimals = (formatter: Intl.NumberFormat, value: number) =>\n  formatter\n    .formatToParts(value)\n    .filter((part) => part.type === 'fraction')\n    .reduce((length, part) => length + part.value.length, 0)\n\n/**\n * The options the numbers in between are written with: no more decimals\n * than the two ends show, so a count from 0 to 1,000 never shows 512.347.\n * A compact or significant-digit format already rounds for itself.\n */\nfunction countFormat(\n  formatter: Intl.NumberFormat,\n  format: Intl.NumberFormatOptions | undefined,\n  from: number,\n  to: number,\n): Intl.NumberFormatOptions | undefined {\n  const options = formatter.resolvedOptions()\n  if (options.notation === 'compact' || options.maximumSignificantDigits !== undefined) {\n    return format\n  }\n  const most = Math.max(decimals(formatter, from), decimals(formatter, to))\n  return {\n    ...format,\n    minimumFractionDigits: Math.min(options.minimumFractionDigits ?? 0, most),\n    maximumFractionDigits: most,\n  }\n}\n\n/** The number a count shows at `progress`, from 0 to 1. */\nfunction countAt(from: number, to: number, progress: number) {\n  return progress >= 1 ? to : from + (to - from) * progress\n}\n\n/**\n * The parts around the number with their spaces kept: a flex item drops a\n * space at its start or end, which would join a unit to the number (`7 GB`).\n */\nfunction keepSpaces(text: string) {\n  return text.replace(/^ | $/g, '\\u00a0')\n}\n\nfunction RollingNumber({\n  value,\n  locale,\n  format,\n  spin,\n  className,\n  render,\n  ...props\n}: NumberProps & { spin: boolean }) {\n  const [seen, setSeen] = useState({ value, trend: 1 })\n  if (seen.value !== value) setSeen({ value, trend: value < seen.value ? -1 : 1 })\n  const formatter = numberFormatter(locale, format)\n  const { text, sign, prefix, number, suffix, tail } = numberParts(formatter, value)\n  const direction = localeDirection(formatter)\n  return renderElement(\n    'span',\n    mergeProps(\n      {\n        'data-slot': 'animated-number',\n        className: cn('whitespace-nowrap tabular-nums', className),\n        children: (\n          <>\n            {/* The digits read left to right in every language; the parts around them follow the locale. An agent reads the row's text, where every digit of each reel would show. */}\n            <span aria-hidden data-agent-hidden dir={direction} className='select-none'>\n              {/* Only the number rolls, so the words around it keep their letters joined. */}\n              <Swap roll align='end'>\n                {sign}\n              </Swap>\n              <Swap roll align='end'>\n                {keepSpaces(prefix)}\n              </Swap>\n              <Roll value={number} tail={tail} trend={seen.trend} spin={spin} />\n              <Swap roll align='start'>\n                {keepSpaces(suffix)}\n              </Swap>\n            </span>\n            <span className='sr-only'>{text}</span>\n          </>\n        ),\n      },\n      props,\n    ),\n    render,\n  )\n}\n\nfunction CountingNumber({\n  value,\n  locale,\n  format,\n  className,\n  render,\n  ...props\n}: NumberProps) {\n  const formatter = numberFormatter(locale, format)\n  const text = formatter.format(value)\n  const [surface, setSurface] = useState<HTMLSpanElement | null>(null)\n  const live = useRef<HTMLSpanElement>(null)\n  const shown = useRef(value)\n  const target = useRef(value)\n\n  useEffect(() => registerProgress(PROGRESS), [])\n  // The box glides to each width the count reaches, so what follows it never jumps.\n  useEffect(() => {\n    const box = surface\n    if (!box || !live.current) return\n    // It clips only while it catches up, so a box narrower than the number at rest still shows all of it.\n    return followSize(box, live.current, 'width', {\n      moving: () => {\n        box.dataset.following = ''\n        return undefined\n      },\n      settled: () => delete box.dataset.following,\n    })\n  }, [surface])\n\n  // Before the first paint of the new value, so it never shows before the count.\n  useLayoutEffect(() => {\n    const element = live.current\n    if (!element) return\n    if (target.current === value) {\n      // Only how it's written changed, such as its currency: a count still\n      // running would end on the old text, so it stops at the new one.\n      if (element.textContent !== text) {\n        stopProgress(element)\n        shown.current = value\n        element.textContent = text\n      }\n      return\n    }\n    const from = shown.current\n    // The decimals come from the value it was going to, never from one part\n    // way there, so a count cut short still shows whole members.\n    const between = numberFormatter(\n      formatter.resolvedOptions().locale,\n      countFormat(formatter, formatOptionsOf(formatter), target.current, value),\n    )\n    target.current = value\n    runProgress(element, PROGRESS, (progress) => {\n      shown.current = countAt(from, value, progress)\n      element.textContent = progress >= 1 ? text : between.format(shown.current)\n    })\n    // The formatter, not `format`: an object passed anew on each render must not end a count.\n  }, [value, text, formatter])\n\n  return renderElement(\n    'span',\n    mergeProps(\n      {\n        'data-slot': 'animated-number',\n        ref: setSurface,\n        className: cn(\n          // While the box catches up with a wider number, it clips it, so nothing after it is drawn over.\n          'inline-flex whitespace-nowrap data-following:overflow-x-clip tabular-nums transition-[width] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n          className,\n        ),\n        children: (\n          <>\n            <span\n              ref={live}\n              aria-hidden\n              data-agent-hidden\n              dir={localeDirection(formatter)}\n              className='shrink-0 select-none transition-[--animated-number-progress] duration-(--motion-draw-duration) ease-(--motion-draw-easing) motion-reduce:transition-none'\n            >\n              {text}\n            </span>\n            <span className='sr-only'>{text}</span>\n          </>\n        ),\n      },\n      props,\n    ),\n    render,\n  )\n}\n\nfunction AnimatedNumber({\n  variant = 'roll',\n  ...props\n}: NumberProps & {\n  /** How it moves to a new value: rolling the digits that changed, spinning them, or counting. */\n  variant?: 'roll' | 'spin' | 'count'\n}) {\n  return variant === 'count' ? (\n    <CountingNumber {...props} />\n  ) : (\n    <RollingNumber {...props} spin={variant === 'spin'} />\n  )\n}\n\nexport { AnimatedNumber, countAt, countFormat, keepSpaces, localeDirection, numberParts }\n",
      "type": "registry:component",
      "target": "@components/kino/animated-number.tsx"
    }
  ],
  "type": "registry:component"
}