{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "roll",
  "title": "Roll",
  "description": "Text that rolls when it changes, like an odometer: each character that differs leaves one way and its replacement arrives from the other, or a digit spins to its new one. Animated number, Number field and Date input roll their digits with it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/resize.json"
  ],
  "files": [
    {
      "path": "registry/lib/roll.tsx",
      "content": "'use client'\n\nimport {\n  animateSize,\n  runningTransitions,\n  sizeNow,\n  startRun,\n  transitionsQuiet,\n  withoutTransition,\n} from '@/registry/lib/resize'\nimport {\n  type ComponentProps,\n  type CSSProperties,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Text that rolls when it changes, like an odometer: each character that\n * differs leaves one way and its replacement arrives from the other, up when\n * the value grew, at full strength so it reads while it moves. Under reduced\n * motion the old character goes at once and the new one fades in, so two\n * never show over each other. It is drawn for the eye only: give screen\n * readers the value beside it.\n */\n\nconst SLOTS = 3\n\n/**\n * One character's place. Its three slots take turns: one character arriving\n * and up to two leaving. A character still arriving when the value changes\n * again leaves from where it got to, because it stays the same element.\n */\nexport interface RollColumn {\n  id: number\n  chars: string[]\n  keys: number[]\n  /** Which way each slot leaves, fixed when it starts to: 1 up, -1 down. */\n  exits: (1 | -1)[]\n  arriving: number\n}\n\nfunction emptyColumn(key: number): { column: RollColumn; nextKey: number } {\n  return {\n    column: {\n      id: key,\n      chars: ['', '', ''],\n      keys: [key + 1, key + 2, key + 3],\n      exits: [1, 1, 1],\n      arriving: 0,\n    },\n    nextKey: key + 4,\n  }\n}\n\n/** Columns at rest, for a value that hasn't changed yet. Columns run from the value's end. */\nexport function restingColumns(value: string): {\n  columns: RollColumn[]\n  nextKey: number\n} {\n  let nextKey = 0\n  const columns = value\n    .split('')\n    .reverse()\n    .map((char) => {\n      const made = emptyColumn(nextKey)\n      nextKey = made.nextKey\n      return { ...made.column, chars: [char, '', ''] }\n    })\n  return { columns, nextKey }\n}\n\nexport interface RollOptions {\n  /** Above 0 when the value grew, below 0 when it shrank. */\n  trend?: number\n  /**\n   * The value is typed: when it carries the last one on (a digit typed or\n   * deleted at the end), it lines up from the start, so only that digit moves.\n   */\n  typed?: boolean\n  /** How many characters come after the place the value lines up on, such as a number's decimals. */\n  tail?: number\n  /** The same for the value before. */\n  wasTail?: number\n  /** A digit that becomes another stays in its slot and spins to it. */\n  spin?: boolean\n}\n\n/**\n * The columns once the value has changed: each column whose character differs\n * turns to its next slot. Places line up from the end, or `tail` characters\n * before it, so units stay over units and the decimal point stays where it\n * is. A typed value that carries the last one on lines up from the start.\n */\nexport function rollColumns(\n  columns: RollColumn[],\n  value: string,\n  key: number,\n  { trend = 1, typed = false, tail = 0, wasTail = 0, spin = false }: RollOptions = {},\n): { columns: RollColumn[]; nextKey: number } {\n  let nextKey = key\n  const fresh = () => {\n    const made = emptyColumn(nextKey)\n    nextKey = made.nextKey\n    return made.column\n  }\n  const chars = value.split('').reverse()\n  const shown = columns.flatMap((column, index) =>\n    column.chars[column.arriving] ? [index] : [],\n  )\n  const was = shown\n    .map((index) => columns[index].chars[columns[index].arriving])\n    .reverse()\n    .join('')\n  let placed = [...columns]\n  const carriesOn =\n    typed &&\n    was !== '' &&\n    value !== '' &&\n    (value.startsWith(was) || was.startsWith(value))\n  // The column the old value lined up on, past its last one if it was shorter.\n  const last = shown.length > 0 ? shown[shown.length - 1] : -1\n  const anchor = shown[wasTail] ?? last + 1 + (wasTail - shown.length)\n  // Where the value's last character goes; columns before it empty out.\n  let end = carriesOn ? last - (chars.length - 1) : anchor - tail\n  if (end < 0) {\n    placed = [...Array.from({ length: -end }, fresh), ...placed]\n    end = 0\n  }\n  const width = Math.max(placed.length, end + chars.length)\n  const next = Array.from({ length: width }, (_, index) => {\n    const char = index < end ? '' : (chars[index - end] ?? '')\n    const column = placed[index] ?? fresh()\n    const current = column.chars[column.arriving]\n    if (current === char) return column\n    if (spin && digitOf(current) && digitOf(char)) {\n      return {\n        ...column,\n        chars: column.chars.map((old, slot) => (slot === column.arriving ? char : old)),\n      }\n    }\n    const arriving = (column.arriving + 1) % SLOTS\n    return {\n      ...column,\n      chars: column.chars.map((old, slot) => (slot === arriving ? char : old)),\n      keys: column.keys.map((old, slot) => (slot === arriving ? nextKey++ : old)),\n      exits: column.exits.map((old, slot) =>\n        slot === column.arriving ? (trend >= 0 ? 1 : -1) : old,\n      ),\n      arriving,\n    }\n  })\n  return { columns: next, nextKey }\n}\n\nconst DIGIT = /^\\p{Nd}$/u\n\n/**\n * A digit's value and the code of its numbering system's zero, such as 7 and\n * the code of `0`, or of `٠` in Arabic-Indic. Null for anything else.\n */\nexport function digitOf(char: string): { value: number; zero: number } | null {\n  if (!DIGIT.test(char)) return null\n  const code = char.codePointAt(0) ?? 0\n  let zero = code\n  // A numbering system's digits are ten code points in a row, from its zero.\n  while (code - zero < 9 && DIGIT.test(String.fromCodePoint(zero - 1))) zero -= 1\n  return { value: code - zero, zero }\n}\n\n/** How many copies of the ten digits a spinning strip holds, so a spin either way stays on it. */\nconst SPIN_COPIES = 3\n\nconst wrap = (digits: number) => ((digits % 10) + 10) % 10\n\n/**\n * Where a spinning strip goes, in digits from its top, to show `digit` from\n * `from`: forward through the digits after it when the value grew, back\n * through those before it when it shrank, round past 9 or 0 as a counter does.\n */\nexport function spinTarget(from: number, digit: number, trend: number): number {\n  const at = wrap(from)\n  const steps = trend >= 0 ? wrap(digit - at) : -wrap(at - digit)\n  return Math.abs(steps) < 1e-6 ? from : from + steps\n}\n\n/** Where a strip is now, in digits from its top, part way through a spin or at rest. */\nfunction spinNow(strip: HTMLElement): number {\n  const step = (strip.firstElementChild as HTMLElement | null)?.offsetHeight ?? 0\n  const y = Number.parseFloat(getComputedStyle(strip).translate.split(' ')[1] ?? '0')\n  return step > 0 && Number.isFinite(y) ? -y / step : 10\n}\n\n/**\n * Spins a strip to `digit`. It first moves, with no transition, to the same\n * place in its middle copy, which looks the same, so a spin cut short goes\n * on from where it is and never runs off the strip. Kept outside the\n * component: the React Compiler drops a forced reflow written inside one.\n */\nfunction spinTo(strip: HTMLElement, digit: number, trend: number) {\n  const now = spinNow(strip)\n  const from = 10 + wrap(now)\n  if (Math.abs(from - now) > 1e-3) {\n    withoutTransition(strip, () => strip.style.setProperty('--roll-spin', String(from)))\n  }\n  strip.style.setProperty('--roll-spin', String(spinTarget(from, digit, trend)))\n}\n\nconst columnWidths = new WeakMap<Element, number>()\n\n/** What a column's width moves on: its grid track as it fills or empties, its width as its character changes width. */\nconst COLUMN_SIZES = ['grid-template-columns', 'width']\n\n/**\n * Glides each column whose character became one of another width, such as K\n * to M or one currency sign to another, from its old width to its new one,\n * so what follows slides over rather than jumps. A column that fills or\n * empties glides on its own grid track instead. Each column is marked\n * `data-moving` while its width moves, the only time its character can be\n * wider than it. Kept outside the component: the React Compiler drops a\n * forced reflow written inside one.\n */\nfunction glideColumns(root: HTMLElement) {\n  for (const column of root.querySelectorAll<HTMLElement>(':scope > [data-change]')) {\n    const sizer = column.querySelector<HTMLElement>('[data-roll-sizer]')\n    if (!sizer) continue\n    const to = sizer.offsetWidth\n    const last = columnWidths.get(column)\n    columnWidths.set(column, to)\n    if (\n      column.dataset.change === 'none' &&\n      last !== undefined &&\n      Math.abs(to - last) >= 0.5\n    ) {\n      void animateSize(column, 'width', sizeNow(column, 'width', last), to).then(\n        (latest) => {\n          if (latest) column.style.width = ''\n        },\n      )\n    }\n    if (runningTransitions(column, { property: COLUMN_SIZES }).length === 0) continue\n    // The run is kept on the sizer: one on the column would end the width glide's.\n    const latest = startRun(sizer)\n    column.dataset.moving = ''\n    void transitionsQuiet(column, { property: COLUMN_SIZES }).then(() => {\n      if (latest()) delete column.dataset.moving\n    })\n  }\n}\n\n/** A digit drawn as a strip of its numbering system's digits, which spins to the next one. */\nfunction RollDigit({ char, trend }: { char: string; trend: number }) {\n  const { value, zero } = digitOf(char) ?? { value: 0, zero: 48 }\n  const ref = useRef<HTMLSpanElement>(null)\n  const [start] = useState(() => 10 + value)\n  const shown = useRef(value)\n  useLayoutEffect(() => {\n    if (!ref.current || shown.current === value) return\n    shown.current = value\n    spinTo(ref.current, value, trend)\n  }, [value, trend])\n  return (\n    // Clipped to its own line, so a digit arriving or leaving shows none of its neighbours.\n    <span className='relative inline-block [clip-path:inset(0_-1em)]'>\n      <span className='invisible'>{char}</span>\n      <span\n        ref={ref}\n        style={{ '--roll-spin': start } as CSSProperties}\n        className='absolute inset-x-0 top-0 flex translate-y-[calc(var(--roll-spin)*-1lh)] flex-col transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n      >\n        {Array.from({ length: 10 * SPIN_COPIES }, (_, index) => (\n          // oxlint-disable-next-line react/no-array-index-key -- the strip's digits never move\n          <span key={index}>{String.fromCodePoint(zero + (index % 10))}</span>\n        ))}\n      </span>\n    </span>\n  )\n}\n\n/**\n * How a column's width moves as a character arrives: it grows from nothing\n * when the column was empty, shrinks to nothing when the column empties, and\n * otherwise stays as wide as what arrives.\n */\nexport function columnWidthChange(\n  left: string,\n  arriving: string,\n): 'grow' | 'shrink' | 'none' {\n  if (left === '' && arriving !== '') return 'grow'\n  if (left !== '' && arriving === '') return 'shrink'\n  return 'none'\n}\n\nfunction Roll({\n  value,\n  trend = 1,\n  typed = false,\n  tail = 0,\n  spin = false,\n  className,\n  style,\n  ...props\n}: Omit<ComponentProps<'span'>, 'children'> &\n  Omit<RollOptions, 'wasTail'> & {\n    value: string\n  }) {\n  const [state, setState] = useState(() => ({\n    value,\n    tail,\n    rolled: false,\n    settled: false,\n    ...restingColumns(value),\n  }))\n  if (state.value !== value || state.tail !== tail) {\n    setState({\n      value,\n      tail,\n      rolled: true,\n      settled: false,\n      ...rollColumns(state.columns, value, state.nextKey, {\n        trend,\n        typed,\n        tail,\n        wasTail: state.tail,\n        spin,\n      }),\n    })\n  }\n  const draw = (char: string) =>\n    spin && digitOf(char) ? <RollDigit char={char} trend={trend} /> : char\n  const root = useRef<HTMLSpanElement>(null)\n  useLayoutEffect(() => {\n    const element = root.current\n    if (!element) return\n    glideColumns(element)\n    if (!state.rolled || state.settled) return\n    // Once every move has landed, the starting styles go, so a roll shown\n    // again after it was hidden (a tab panel) doesn't play its arrival again.\n    let current = true\n    void transitionsQuiet(element, { subtree: true }).then(() => {\n      if (current) setState((now) => (now === state ? { ...now, settled: true } : now))\n    })\n    return () => {\n      current = false\n    }\n  }, [state])\n  // Whether what last arrived is still on its way in.\n  const arriving = state.rolled && !state.settled\n\n  return (\n    // Digits read left to right in every language, so the row doesn't flip in RTL.\n    <span\n      ref={root}\n      data-slot='roll'\n      aria-hidden\n      dir='ltr'\n      style={\n        {\n          '--roll-from': trend >= 0 ? '1lh' : '-1lh',\n          ...style,\n        } as CSSProperties\n      }\n      className={cn(\n        // The clip keeps a character on its way in out of the line's measured height.\n        'inline-flex overflow-y-clip whitespace-pre select-none [clip-path:inset(0_-1em)]',\n        className,\n      )}\n      {...props}\n    >\n      {state.columns\n        .map((column) => {\n          const shown = column.chars[column.arriving]\n          // What holds the column open: its character, or the one leaving while it closes.\n          const sizer = shown || column.chars[(column.arriving + SLOTS - 1) % SLOTS]\n          const change = arriving\n            ? columnWidthChange(\n                column.chars[(column.arriving + SLOTS - 1) % SLOTS],\n                shown,\n              )\n            : 'none'\n          return (\n            <span\n              key={column.id}\n              data-change={change}\n              className={cn(\n                // A column that fills or empties glides open or shut, so the rest slide over rather than jump.\n                // It clips at its sides only while it moves, so a character in one still opening never shows\n                // over its neighbour. At rest it doesn't: tight tracking puts a digit's ink at its box's edge,\n                // and a clip there cut the last pixel off where text renders a little wider, as on Windows.\n                // Its character fades as well, the way the room for it opens or closes.\n                'group/roll-column inline-grid transition-[grid-template-columns,width] duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-moving:[clip-path:inset(0_-0.04em)] motion-reduce:transition-none',\n                shown ? 'grid-cols-[1fr]' : 'grid-cols-[0fr]',\n                change === 'grow' && 'starting:grid-cols-[0fr]',\n              )}\n            >\n              <span className='relative min-w-0'>\n                <span data-roll-sizer className='invisible'>\n                  {sizer}\n                </span>\n                {column.chars.map((char, slot) =>\n                  slot !== column.arriving ? (\n                    <span\n                      key={column.keys[slot]}\n                      style={\n                        {\n                          '--roll-to': column.exits[slot] > 0 ? '-1lh' : '1lh',\n                        } as CSSProperties\n                      }\n                      className='absolute inset-y-0 start-0 transition-[translate,opacity] duration-(--motion-exit-duration) ease-(--motion-exit-easing) motion-safe:translate-y-(--roll-to) group-data-[change=shrink]/roll-column:opacity-0 motion-reduce:opacity-0 motion-reduce:transition-none'\n                    >\n                      {draw(char)}\n                    </span>\n                  ) : arriving ? (\n                    <span\n                      key={column.keys[slot]}\n                      className='absolute inset-y-0 start-0 transition-[translate,opacity] duration-(--motion-enter-duration) ease-(--motion-enter-easing) motion-safe:starting:translate-y-(--roll-from) group-data-[change=grow]/roll-column:starting:opacity-0 motion-reduce:starting:opacity-0'\n                    >\n                      {draw(char)}\n                    </span>\n                  ) : (\n                    // At rest, on first paint and once it has landed: nothing moves until the value changes.\n                    <span key={column.keys[slot]} className='absolute inset-y-0 start-0'>\n                      {draw(char)}\n                    </span>\n                  ),\n                )}\n              </span>\n            </span>\n          )\n        })\n        .reverse()}\n    </span>\n  )\n}\n\nexport { Roll }\n",
      "type": "registry:lib",
      "target": "@lib/roll.tsx"
    }
  ],
  "type": "registry:lib"
}