{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "roll",
  "title": "Roll",
  "description": "The digit roll: tabular digits that travel vertically like a ball between stops, only the changed ones, in the direction of change, with reserved width so the layout never shifts.",
  "dependencies": [
    "motion"
  ],
  "devDependencies": [],
  "registryDependencies": [
    "utils",
    "https://reactmotionkit.com/r/motion-presets.json",
    "https://reactmotionkit.com/r/motion-kit.json"
  ],
  "files": [
    {
      "path": "lib/roll.tsx",
      "content": "\"use client\"\n\nimport { animate, motion, type MotionValue, useMotionValue, useTransform } from \"motion/react\"\nimport { type ComponentProps, useEffect, useMemo, useRef, useState } from \"react\"\n\nimport { useMotionKit } from \"@/lib/motion-kit\"\nimport type { MotionTokens, Temperament } from \"@/lib/motion\"\nimport { cn } from \"@/lib/utils\"\n\n/**\n * Roll: digits travel vertically like a ball between stops (docs/plan/SHAPE-LANGUAGE.md).\n * Each digit is a soft-edged cell holding a ring of 0-9; when the value changes, only the\n * changed digits roll, upward when the value grows and downward when it shrinks, on the\n * temperament's spring (or the calm spring in tables). The changed digits roll in lockstep, one\n * line at the same pace, so every frame shows them at one height (a digit with a shorter way\n * waits on its stop for the others) and all nod together at the end. Figures are tabular and the width\n * is reserved for `reserveFor`, so the layout never shifts. Glyphs are only translated,\n * never scaled. The formatted value is exposed once to assistive tech; the rolling cells\n * are `aria-hidden`. With reduced motion the changed digits swap with a short crossfade.\n */\n\nconst DIGITS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as const\n\n/*\n * A digit of the ring is drawn at its distance from the current position, wrapped into\n * [-5, 5) lines: the column behaves as an endless odometer strip, so 9 -> 0 going up\n * continues upward instead of rewinding through 8..1.\n */\nfunction wrapped(distance: number) {\n  return ((((distance + 5) % 10) + 10) % 10) - 5\n}\n\n/**\n * Where a digit's strip should travel to show `digit`, starting from the strip's current\n * (possibly fractional, mid-roll) position: forward (`direction` 1) or backward (-1), never\n * more than one turn. Exported for tests and for components that drive their own strips.\n */\nexport function rollTarget(current: number, digit: number, direction: 1 | -1) {\n  const ahead = (((digit - current) % 10) + 10) % 10\n  return direction > 0 ? current + ahead : current - ((10 - ahead) % 10)\n}\n\n/*\n * The window of a cell. Digits are drawn on a strip one STEP apart and seen through a window\n * centred on the line, WINDOW above and below the centre, whose outer FADE dissolves into\n * transparent. Digit ink (baseline to cap height) sits about 0.37em around the centre of the\n * line box, so a digit at rest is wholly inside the solid part, and its neighbours on the strip\n * (one STEP away) are wholly outside the window: no peeking at rest, whatever the line height.\n * STEP is twice the window, so at every instant of a roll the leaving and the arriving digit\n * share the window, each sliced by its edge like an odometer: at mid-roll the bottom half of\n * one and the top half of the other. The cell is never empty, and a glyph off its baseline is\n * always cut by the window, never shown whole. The window stays within the line box for normal\n * line heights, so no glyph ever reaches the text above or below the number.\n */\nconst WINDOW = 0.55\nconst FADE = 0.1\nconst STEP = WINDOW * 2\nconst MASK = `linear-gradient(to bottom, transparent calc(50% - ${WINDOW}em), #000 calc(50% - ${WINDOW - FADE}em), #000 calc(50% + ${WINDOW - FADE}em), transparent calc(50% + ${WINDOW}em))`\n\n/*\n * The `clean` window (opt-in): no mask slices a glyph, so no sliver of a digit ever hangs at\n * the cell's edge. The strip is shorter (CLEAN_STEP per line instead of STEP) and each digit\n * fades by its distance from the centre, `1 - (d / CLEAN_FADE)^2`: wholly gone by\n * CLEAN_FADE lines (0.6em off centre). At half opacity its ink (0.37em around its centre)\n * reaches about 0.8em, so only a near-transparent glyph ever passes the line box of normal\n * line heights. At mid-roll both digits show\n * at about 56%, 0.8em apart, so their ink never overlaps: the cell is never empty, never\n * doubled, and nothing is cut.\n */\nconst CLEAN_STEP = 0.8\nconst CLEAN_FADE = 0.75\n\nfunction cleanOpacity(distance: number) {\n  const share = Math.min(1, Math.abs(distance) / CLEAN_FADE)\n  return 1 - share * share\n}\n\n/*\n * Once the strip has reached its stop, the spring's overshoot and settle are worth an eighth\n * of a step: the digit nods past its stop, its neighbour stays out of the window.\n */\nconst OVERSHOOT_LINES = 0.12\n\ninterface DigitProps {\n  digit: number\n  /** +1 when the whole value grew, -1 when it shrank. */\n  direction: 1 | -1\n  /** Mounted after the first paint: fade in on its own digit (never a leading 0). */\n  rollIn: boolean\n  /**\n   * Lines travelled by the longest-rolling digit of this change. Each digit covers lines at\n   * that shared pace and waits on its stop, so the moving digits always share one height.\n   * Default: its own travel (each digit spans the whole spring).\n   */\n  span?: number\n  motion: MotionTokens\n  calm: boolean\n  /** The unmasked, distance-faded window (see CLEAN_STEP). */\n  clean: boolean\n}\n\nfunction RollDigit({ digit, direction, rollIn, span, motion: tokens, calm, clean }: DigitProps) {\n  const position = useMotionValue(digit)\n  const opacity = useMotionValue(rollIn ? 0 : 1)\n  const shown = useRef(digit)\n\n  // A cell added by a longer value (999 -> 1,000) fades in on its digit while the others roll.\n  useEffect(() => {\n    if (opacity.get() === 1) return\n    const fade = animate(opacity, 1, tokens.reduced ? tokens.fade : tokens.tween)\n    return () => {\n      fade.stop()\n    }\n  }, [opacity, tokens])\n\n  useEffect(() => {\n    if (shown.current === digit) return\n    shown.current = digit\n    if (tokens.reduced) {\n      position.jump(digit)\n      opacity.jump(0)\n      const fade = animate(opacity, 1, tokens.fade)\n      return () => {\n        fade.stop()\n      }\n    }\n    // Retarget from wherever the strip is now (interruptible), travelling in the value's direction.\n    const start = position.get()\n    const target = rollTarget(start, digit, direction)\n    const travel = target - start\n    const sign = Math.sign(travel)\n    const own = Math.abs(travel)\n    const lines = Math.max(span ?? own, own)\n    let arrived = false\n    /*\n     * The spring drives progress 0 -> 1. On the way there it spans the whole travel; once\n     * it has reached the stop, its overshoot and settle are scaled to OVERSHOOT_LINES, so a\n     * digit that rolled through eight others peeks as much as one that moved by one.\n     */\n    const control = animate(0, 1, {\n      ...(calm ? tokens.springCalm : tokens.spring),\n      onUpdate: (progress) => {\n        if (progress >= 1) arrived = true\n        position.set(\n          arrived\n            ? target + (progress - 1) * sign * OVERSHOOT_LINES\n            : start + sign * Math.min(own, lines * progress),\n        )\n      },\n    })\n    return () => {\n      control.stop()\n    }\n    // `span` is read when the digit changes; a new span alone starts nothing.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [digit, direction, tokens, calm, position, opacity])\n\n  return (\n    <motion.span\n      data-slot=\"roll-digit\"\n      className=\"inline-block\"\n      style={\n        clean\n          ? { opacity }\n          : {\n              opacity,\n              // Only this cell's own digits, inside its window, ever show in it.\n              maskImage: MASK,\n              WebkitMaskImage: MASK,\n            }\n      }\n    >\n      <span className=\"relative block\">\n        <span className=\"invisible\">{digit}</span>\n        {DIGITS.map((d) =>\n          clean ? (\n            <CleanRingDigit key={d} digit={d} position={position} />\n          ) : (\n            <RingDigit key={d} digit={d} position={position} />\n          ),\n        )}\n      </span>\n    </motion.span>\n  )\n}\n\nfunction RingDigit({ digit, position }: { digit: number; position: MotionValue<number> }) {\n  const y = useTransform(position, (p) => `${wrapped(digit - p) * STEP}em`)\n  // Digits more than one step away can never reach the window: skip painting them.\n  const visibility = useTransform(position, (p) =>\n    Math.abs(wrapped(digit - p)) < 1 ? \"visible\" : \"hidden\",\n  )\n  return (\n    <motion.span className=\"absolute inset-x-0 top-0 text-center\" style={{ y, visibility }}>\n      {digit}\n    </motion.span>\n  )\n}\n\nfunction CleanRingDigit({ digit, position }: { digit: number; position: MotionValue<number> }) {\n  const y = useTransform(position, (p) => `${wrapped(digit - p) * CLEAN_STEP}em`)\n  const opacity = useTransform(position, (p) => cleanOpacity(wrapped(digit - p)))\n  const visibility = useTransform(position, (p) =>\n    Math.abs(wrapped(digit - p)) < CLEAN_FADE ? \"visible\" : \"hidden\",\n  )\n  return (\n    <motion.span\n      className=\"absolute inset-x-0 top-0 text-center\"\n      style={{ y, opacity, visibility }}\n    >\n      {digit}\n    </motion.span>\n  )\n}\n\nexport interface RollProps extends Omit<ComponentProps<\"span\">, \"children\"> {\n  /** The number to show. Changing it rolls the changed digits from the ones on screen. */\n  value: number\n  /** `Intl.NumberFormat` options: currency, percent, compact notation, fraction digits. */\n  format?: Intl.NumberFormatOptions\n  /** Locale of the formatter. Fixed by default so server and client render the same text. */\n  locale?: string\n  /** Widest value expected; its formatted width is reserved so updates never shift the layout. Default: `value`. */\n  reserveFor?: number\n  /** Where the digits sit inside the reserved width. Default `end` (numbers align right). */\n  align?: \"start\" | \"end\"\n  /** Dense or serious contexts (tables, totals, payments): roll on the calm spring, no bounce. */\n  calm?: boolean\n  /**\n   * Opt-in. No mask: a leaving digit fades out before it reaches the cell's edge instead of\n   * being sliced by it, so no sliver of a digit shows mid-roll (totals, counts in small\n   * type). Default `false`: the odometer window.\n   */\n  clean?: boolean\n  /** Motion intensity only. Wins over `MotionKitProvider`. */\n  temperament?: Temperament\n}\n\n/** Splits a formatted number into cells keyed from the right, so units stay units as digits are added. */\nfunction cells(text: string) {\n  const chars = Array.from(text)\n  return chars.map((char, index) => {\n    const fromRight = chars.length - 1 - index\n    const digit = char >= \"0\" && char <= \"9\" ? Number(char) : null\n    return { key: digit === null ? `c${fromRight}${char}` : `d${fromRight}`, char, digit }\n  })\n}\n\n/**\n * A number whose digits roll. Use it wherever a number changes in front of the person:\n * KPI values, page numbers, counts, character counters.\n *\n * @example <Roll value={48210} format={{ style: \"currency\", currency: \"EUR\" }} reserveFor={99999} />\n */\nexport function Roll({\n  value,\n  format,\n  locale = \"en-US\",\n  reserveFor,\n  align = \"end\",\n  calm = false,\n  clean = false,\n  temperament,\n  className,\n  ref,\n  ...props\n}: RollProps) {\n  const tokens = useMotionKit(temperament)\n  const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, format])\n  const text = formatter.format(value)\n  const reserved = reserveFor === undefined ? text : formatter.format(reserveFor)\n\n  // Derived from the previous value during render: which way the value went, and whether\n  // it has changed since mount (digits added after the first paint fade in on their own digit).\n  const [seen, setSeen] = useState({ value, from: value, direction: 1 as 1 | -1, changed: false })\n  if (seen.value !== value) {\n    setSeen({ value, from: seen.value, direction: value >= seen.value ? 1 : -1, changed: true })\n  }\n\n  // The longest roll of this change, in lines: the pace every changed digit shares.\n  const span = useMemo(() => {\n    const before = new Map(cells(formatter.format(seen.from)).map((c) => [c.key, c.digit]))\n    let longest = 0\n    for (const cell of cells(text)) {\n      const was = before.get(cell.key)\n      if (cell.digit === null || was === null || was === undefined) continue\n      const ahead = (cell.digit - was + 10) % 10\n      longest = Math.max(longest, seen.direction > 0 ? ahead : (10 - ahead) % 10)\n    }\n    return longest\n  }, [formatter, seen.from, seen.direction, text])\n\n  return (\n    <span\n      ref={ref}\n      className={cn(\"inline-grid items-baseline whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      <span data-slot=\"roll-value\" className=\"sr-only\">\n        {text}\n      </span>\n      <span\n        aria-hidden\n        className={cn(\n          \"col-start-1 row-start-1 flex items-baseline\",\n          align === \"end\" ? \"justify-self-end\" : \"justify-self-start\",\n        )}\n      >\n        {cells(text).map((cell) =>\n          cell.digit === null ? (\n            <motion.span\n              key={cell.key}\n              className=\"inline-block\"\n              initial={seen.changed ? { opacity: 0 } : false}\n              animate={{ opacity: 1 }}\n              transition={tokens.reduced ? tokens.fade : tokens.tween}\n            >\n              {cell.char}\n            </motion.span>\n          ) : (\n            <RollDigit\n              key={cell.key}\n              digit={cell.digit}\n              direction={seen.direction}\n              rollIn={seen.changed}\n              span={span}\n              motion={tokens}\n              calm={calm}\n              clean={clean}\n            />\n          ),\n        )}\n      </span>\n      {/* After the digits, so the grid takes its baseline from them; only its width counts. */}\n      <span aria-hidden className=\"invisible col-start-1 row-start-1\">\n        {reserved}\n      </span>\n    </span>\n  )\n}\n",
      "type": "registry:lib"
    }
  ],
  "meta": {
    "tier": "free",
    "collection": "interface",
    "needsImage": false,
    "addedAt": "2026-10-18",
    "tags": [
      "shape",
      "roll",
      "number",
      "digits"
    ],
    "tech": [],
    "presets": [],
    "keyboard": [],
    "heavy": false
  },
  "categories": [
    "internal"
  ],
  "type": "registry:lib"
}