{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "money-field",
  "type": "registry:item",
  "title": "Money Field",
  "description": "A currency field typed like a till: every place rolls to its new digit and separators slide in as it grows.",
  "categories": [
    "input"
  ],
  "dependencies": [
    "react-native-reanimated",
    "react-native-worklets"
  ],
  "registryDependencies": [
    "https://kinetik-ui.dev/r/kinetik-tokens.json",
    "https://kinetik-ui.dev/r/kinetik-motion.json",
    "https://kinetik-ui.dev/r/kinetik-haptics.json"
  ],
  "files": [
    {
      "path": "src/components/kinetik/money-field.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/money-field.tsx",
      "content": "import { useEffect, useState } from 'react';\nimport {\n  StyleSheet,\n  Text,\n  TextInput,\n  View,\n  type StyleProp,\n  type TextStyle,\n  type ViewStyle,\n} from 'react-native';\nimport Animated, {\n  cancelAnimation,\n  useAnimatedStyle,\n  useSharedValue,\n  withRepeat,\n  withSequence,\n  withSpring,\n  withTiming,\n} from 'react-native-reanimated';\n\nimport { useHaptic } from '../../lib/kinetik/hooks/use-haptic';\nimport { useReduceMotion } from '../../lib/kinetik/hooks/use-reduce-motion';\nimport { durations, easings, spring } from '../../lib/kinetik/motion/motion';\nimport { useKinetikTheme } from '../../lib/kinetik/tokens/theme';\n\nexport type MoneyFieldProps = {\n  /** The amount in minor units: cents for dollars, pence for pounds. */\n  value: number;\n  onChangeValue: (minor: number) => void;\n  /** Names the field for screen readers, e.g. \"Amount to send\". */\n  label: string;\n  /** Written before the amount. Defaults to \"$\". */\n  currency?: string;\n  /** Digits after the decimal separator. Defaults to 2. */\n  fractionDigits?: number;\n  /** Defaults to \",\". */\n  groupSeparator?: string;\n  /** Defaults to \".\". */\n  decimalSeparator?: string;\n  /** Largest amount in minor units. Defaults to 99,999,999 (999,999.99). */\n  max?: number;\n  /** A tick per typed digit. Defaults to true. */\n  haptics?: boolean;\n  /** Style for the amount; the cell widths are measured from it. */\n  textStyle?: StyleProp<TextStyle>;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\ntype Kind = 'digit' | 'group' | 'decimal';\ntype Glyph = { ch: string; kind: Kind; fraction: boolean };\n\n/** Formats minor units into glyphs, without the currency sign. */\nexport function formatMinor(\n  minor: number,\n  fractionDigits = 2,\n  groupSeparator = ',',\n  decimalSeparator = '.',\n): Glyph[] {\n  const digits = String(Math.max(0, Math.floor(minor))).padStart(fractionDigits + 1, '0');\n  const whole = digits.slice(0, digits.length - fractionDigits);\n  const fraction = fractionDigits > 0 ? digits.slice(-fractionDigits) : '';\n  const out: Glyph[] = [];\n  for (let i = 0; i < whole.length; i++) {\n    if (i > 0 && (whole.length - i) % 3 === 0) {\n      out.push({ ch: groupSeparator, kind: 'group', fraction: false });\n    }\n    out.push({ ch: whole[i]!, kind: 'digit', fraction: false });\n  }\n  if (fraction) {\n    out.push({ ch: decimalSeparator, kind: 'decimal', fraction: true });\n    for (const ch of fraction) out.push({ ch, kind: 'digit', fraction: true });\n  }\n  return out;\n}\n\ntype Widths = Record<Kind | 'sign', number>;\n\n/**\n * A currency field typed like a till: digits come in from the right, every\n * place rolls to its new digit, separators slide in as the amount grows, and\n * a caret blinks at the end. The value is kept in minor units, so there is\n * no floating-point rounding.\n */\nexport function MoneyField({\n  value,\n  onChangeValue,\n  label,\n  currency = '$',\n  fractionDigits = 2,\n  groupSeparator = ',',\n  decimalSeparator = '.',\n  max = 99_999_999,\n  haptics = true,\n  textStyle,\n  testID,\n  style,\n}: MoneyFieldProps) {\n  const { colors, font, space } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const haptic = useHaptic(haptics);\n  const [focused, setFocused] = useState(false);\n\n  const amount = StyleSheet.flatten([\n    {\n      color: colors.text,\n      fontSize: font.size['4xl'],\n      fontWeight: font.weight.semibold,\n      letterSpacing: font.tracking.tight,\n    },\n    textStyle,\n  ]);\n  const size = amount.fontSize ?? font.size['4xl'];\n  const lineHeight = Math.round(size * 1.2);\n  const styleKey = JSON.stringify(amount);\n\n  const [widths, setWidths] = useState<{ key: string; w: Partial<Widths> }>({\n    key: styleKey,\n    w: {},\n  });\n  if (widths.key !== styleKey) setWidths({ key: styleKey, w: {} });\n  const measured =\n    widths.w.digit !== undefined &&\n    widths.w.group !== undefined &&\n    widths.w.decimal !== undefined &&\n    widths.w.sign !== undefined;\n\n  const glyphs = formatMinor(value, fractionDigits, groupSeparator, decimalSeparator);\n  const text = currency + glyphs.map((g) => g.ch).join('');\n\n  // Places are keyed from the right, so typing a digit rolls every place instead of\n  // inserting one. Places that drop off the left leave with a short exit.\n  const [state, setState] = useState({\n    value,\n    glyphs,\n    leaving: [] as Glyph[],\n    dir: 1,\n    batch: 0,\n  });\n  if (state.value !== value) {\n    const lost = state.glyphs.length - glyphs.length;\n    setState({\n      value,\n      glyphs,\n      leaving: lost > 0 && !reduced ? state.glyphs.slice(0, lost) : [],\n      dir: value >= state.value ? 1 : -1,\n      batch: state.batch + 1,\n    });\n  }\n  const { batch } = state;\n  const leavingCount = state.leaving.length;\n  useEffect(() => {\n    if (leavingCount === 0) return;\n    const id = setTimeout(\n      () => setState((s) => (s.batch === batch ? { ...s, leaving: [] } : s)),\n      durations.base,\n    );\n    return () => clearTimeout(id);\n  }, [batch, leavingCount]);\n\n  const change = (typed: string) => {\n    const digits = typed.replace(/\\D/g, '').replace(/^0+/, '');\n    const next = digits.length === 0 ? 0 : Number(digits);\n    if (!Number.isFinite(next) || next > max) {\n      haptic('warning');\n      return;\n    }\n    if (next !== value) {\n      haptic('tick');\n      onChangeValue(next);\n    }\n  };\n\n  const caret = useSharedValue(0);\n  useEffect(() => {\n    if (!focused) {\n      cancelAnimation(caret);\n      caret.set(0);\n      return;\n    }\n    caret.set(1);\n    if (reduced) return;\n    caret.set(\n      withRepeat(\n        withSequence(\n          withTiming(1, { duration: 500 }),\n          withTiming(0, { duration: 180, easing: easings.inOut }),\n          withTiming(0, { duration: 320 }),\n          withTiming(1, { duration: 180, easing: easings.inOut }),\n        ),\n        -1,\n      ),\n    );\n    return () => cancelAnimation(caret);\n  }, [focused, reduced, caret]);\n  const caretStyle = useAnimatedStyle(() => ({ opacity: caret.get() }));\n\n  const measure =\n    (kind: keyof Widths) =>\n    (w: number): void =>\n      setWidths((m) =>\n        m.key !== styleKey || m.w[kind] !== undefined ? m : { ...m, w: { ...m.w, [kind]: w } },\n      );\n\n  const widthOf = (g: Glyph) => (measured ? widths.w[g.kind] : undefined);\n  const colorOf = (g: Glyph) => (g.fraction ? colors.textMuted : amount.color);\n\n  return (\n    <View testID={testID} style={[{ gap: space[1] }, style]}>\n      {!measured ? (\n        <View\n          style={styles.measure}\n          pointerEvents=\"none\"\n          importantForAccessibility=\"no-hide-descendants\"\n        >\n          {(\n            [\n              ['digit', '0'],\n              ['group', groupSeparator],\n              ['decimal', decimalSeparator],\n              ['sign', currency],\n            ] as const\n          ).map(([kind, ch]) => (\n            <Text\n              key={kind}\n              style={[amount, styles.tabular]}\n              onLayout={(e) => measure(kind)(e.nativeEvent.layout.width)}\n            >\n              {ch}\n            </Text>\n          ))}\n        </View>\n      ) : null}\n      <View style={styles.frame}>\n        <View\n          style={[styles.amount, { height: lineHeight + space[2] }]}\n          accessibilityElementsHidden\n          importantForAccessibility=\"no-hide-descendants\"\n        >\n          <Text style={[amount, styles.tabular, { color: colors.textMuted, lineHeight }]}>\n            {currency}\n          </Text>\n          {state.leaving.map((g, i) => (\n            <Cell\n              key={`out-${state.batch}-${i}`}\n              glyph={g}\n              width={widthOf(g)}\n              height={lineHeight}\n              style={amount}\n              color={colorOf(g)}\n              dir={state.dir}\n              phase=\"leave\"\n              reduced={reduced}\n            />\n          ))}\n          {glyphs.map((g, i) => (\n            <Cell\n              key={`p${glyphs.length - 1 - i}`}\n              glyph={g}\n              width={widthOf(g)}\n              height={lineHeight}\n              style={amount}\n              color={colorOf(g)}\n              dir={state.dir}\n              phase=\"stay\"\n              reduced={reduced}\n            />\n          ))}\n          <Animated.View\n            style={[\n              styles.caret,\n              { height: Math.round(size * 0.9), backgroundColor: colors.azure },\n              caretStyle,\n            ]}\n          />\n        </View>\n        <TextInput\n          value={value === 0 ? '' : String(value)}\n          onChangeText={change}\n          keyboardType=\"number-pad\"\n          caretHidden\n          contextMenuHidden\n          onFocus={() => setFocused(true)}\n          onBlur={() => setFocused(false)}\n          accessibilityLabel={label}\n          accessibilityValue={{ text }}\n          style={styles.input}\n        />\n      </View>\n    </View>\n  );\n}\n\ntype CellProps = {\n  glyph: Glyph;\n  width: number | undefined;\n  height: number;\n  style: TextStyle;\n  color: TextStyle['color'];\n  dir: number;\n  phase: 'stay' | 'leave';\n  reduced: boolean;\n};\n\n/** One place of the amount. A new digit rolls in over the old one; new places open from nothing. */\nfunction Cell({ glyph, width, height, style, color, dir, phase, reduced }: CellProps) {\n  const [roll, setRoll] = useState({ ch: glyph.ch, prev: null as string | null, n: 0 });\n  if (roll.ch !== glyph.ch) setRoll({ ch: glyph.ch, prev: roll.ch, n: roll.n + 1 });\n\n  const p = useSharedValue(1);\n  const open = useSharedValue(reduced ? 1 : 0);\n  useEffect(() => {\n    if (roll.n === 0 || reduced) return;\n    p.set(0);\n    p.set(withSpring(1, spring('snappy')));\n  }, [roll.n, reduced, p]);\n  useEffect(() => {\n    if (phase === 'leave') {\n      open.set(withTiming(0, { duration: durations.base, easing: easings.exit }));\n    } else {\n      open.set(withSpring(1, spring('smooth', reduced)));\n    }\n  }, [phase, reduced, open]);\n\n  const box = useAnimatedStyle(() =>\n    width === undefined ? {} : { width: width * open.get(), opacity: open.get() },\n  );\n  const incoming = useAnimatedStyle(() => ({\n    transform: [\n      { translateY: (1 - p.get()) * height * 0.6 * dir + (1 - open.get()) * height * 0.4 },\n    ],\n    opacity: Math.min(p.get(), open.get() * 1.5),\n  }));\n  const outgoing = useAnimatedStyle(() => ({\n    transform: [{ translateY: -p.get() * height * 0.6 * dir }],\n    opacity: 1 - p.get(),\n  }));\n\n  return (\n    <Animated.View style={[styles.cell, { height }, box]}>\n      {roll.prev !== null && roll.prev !== roll.ch ? (\n        <Animated.Text\n          style={[style, styles.tabular, styles.ghost, { color, lineHeight: height }, outgoing]}\n        >\n          {roll.prev}\n        </Animated.Text>\n      ) : null}\n      <Animated.Text style={[style, styles.tabular, { color, lineHeight: height }, incoming]}>\n        {glyph.ch}\n      </Animated.Text>\n    </Animated.View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  measure: { position: 'absolute', opacity: 0, flexDirection: 'row', top: 0, left: 0 },\n  frame: { alignSelf: 'center', minWidth: 160 },\n  amount: { flexDirection: 'row', alignItems: 'center', alignSelf: 'center' },\n  tabular: { fontVariant: ['tabular-nums'], includeFontPadding: false },\n  cell: { overflow: 'hidden', alignItems: 'center', justifyContent: 'center' },\n  ghost: { position: 'absolute' },\n  caret: { width: 2, borderRadius: 1, marginLeft: 3 },\n  input: {\n    position: 'absolute',\n    top: 0,\n    left: 0,\n    right: 0,\n    bottom: 0,\n    opacity: 0,\n    color: 'transparent',\n  },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "input",
    "web": "live",
    "perf": {
      "budget": "Plain text cells, two shared values each; widths are measured once per text style. Only the caret loops, and only while focused.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 18,
          "baselineMs": 18,
          "jankyPercent": 2.28,
          "atRest": "idle",
          "memoryMb": 149
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Digits change in place, new places appear at once and the caret stays lit.",
      "screenReader": "A number field named by its label whose value is the formatted amount.",
      "touchTarget": "The whole amount is the target, at least 160 by 66 pt."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { MoneyField } from '@/components/kinetik/money-field';\n\n// `cents` is an integer: 4250 is $42.50.\n<MoneyField label=\"Amount to send\" value={cents} onChangeValue={setCents} />;\n```\n\n## When to use\n\n- Entering an amount of money: sending, tipping, splitting a bill, setting a budget.\n- Any amount where floating-point rounding must never creep in; the value is an integer of minor units.\n\n## When not to use\n\n- Numbers that are not money, or that step in fixed amounts. Use Roll Stepper.\n- Picking from a few preset amounts only. Use chips or Choice Cards.\n\n## Notes\n\n- Digits arrive from the right like a till: typing 1, 2, 5, 0 gives 0.01, 0.12, 1.25, 12.50, and every place rolls to its new digit.\n- `currency`, `groupSeparator`, `decimalSeparator` and `fractionDigits` cover most locales (for example `€`, `.` and `,`).\n- A transparent native field sits over the amount, so tapping it opens the number pad and screen readers read the formatted amount.\n- With reduced motion digits change in place and new places appear without opening.\n"
  },
  "docs": "Prefer `npx kinetik-ui add money-field`: it installs dependencies with expo install, so versions match your Expo SDK."
}
