{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-field",
  "type": "registry:item",
  "title": "Code Field",
  "description": "A one-time-code field: digits pop into cells, a caret glides along, a wrong code shakes and a right one ripples.",
  "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/code-field.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/code-field.tsx",
      "content": "import { useEffect, useRef, useState } from 'react';\nimport {\n  AccessibilityInfo,\n  StyleSheet,\n  Text,\n  TextInput,\n  View,\n  type StyleProp,\n  type TextStyle,\n  type ViewStyle,\n} from 'react-native';\nimport Animated, {\n  interpolateColor,\n  useAnimatedStyle,\n  useSharedValue,\n  withDelay,\n  withRepeat,\n  withSequence,\n  withSpring,\n  withTiming,\n  type SharedValue,\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';\nimport type { Palette } from '../../lib/kinetik/tokens/tokens';\n\nexport type CodeFieldStatus = 'idle' | 'error' | 'success';\n\nexport type CodeFieldProps = {\n  value: string;\n  /** Called with digits only, never longer than `length`. */\n  onChangeText: (value: string) => void;\n  /** Called once when the last digit is entered. */\n  onComplete?: (code: string) => void;\n  /** Number of digits. Defaults to 6. */\n  length?: number;\n  /** `error` shakes the row and tints it red; `success` sends a wave along it. Defaults to `idle`. */\n  status?: CodeFieldStatus;\n  /** Names the field for screen readers. Defaults to 'Verification code'. */\n  accessibilityLabel?: string;\n  /** Show dots instead of digits. Defaults to false. */\n  secure?: boolean;\n  autoFocus?: boolean;\n  /** Haptics on error and success. Defaults to true. */\n  haptics?: boolean;\n  disabled?: boolean;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\nconst CELL_H = 56;\nconst GAP = 8;\n\n/**\n * A one-time-code field drawn as a row of cells. Digits pop into place, a\n * caret glides to the next cell, a wrong code shakes the row and a right one\n * sends a ripple along it. One real text input sits on top, so paste, SMS\n * autofill and the system keyboard all work as usual.\n */\nexport function CodeField({\n  value,\n  onChangeText,\n  onComplete,\n  length = 6,\n  status = 'idle',\n  accessibilityLabel = 'Verification code',\n  secure = false,\n  autoFocus = false,\n  haptics = true,\n  disabled = false,\n  testID,\n  style,\n}: CodeFieldProps) {\n  const { colors, font, radius } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const haptic = useHaptic(haptics);\n  const input = useRef<TextInput>(null);\n  const [focused, setFocused] = useState(false);\n  const [width, setWidth] = useState(0);\n  const digits = value.replace(/\\D/g, '').slice(0, length);\n  const active = Math.min(digits.length, length - 1);\n  const cellW = width > 0 ? (width - GAP * (length - 1)) / length : 0;\n\n  const shake = useSharedValue(0);\n  const wave = useSharedValue(0);\n  const caretX = useSharedValue(0);\n  const blink = useSharedValue(1);\n\n  useEffect(() => {\n    if (status === 'error') {\n      haptic('error');\n      AccessibilityInfo.announceForAccessibility('Code not accepted');\n      if (!reduced) {\n        shake.set(\n          withSequence(\n            withTiming(-10, { duration: 50 }),\n            withTiming(9, { duration: 70 }),\n            withTiming(-6, { duration: 70 }),\n            withTiming(4, { duration: 70 }),\n            withSpring(0, spring('snappy')),\n          ),\n        );\n      }\n    }\n    if (status === 'success') {\n      haptic('success');\n      AccessibilityInfo.announceForAccessibility('Code accepted');\n      wave.set(0);\n      if (!reduced) wave.set(withTiming(1, { duration: 700, easing: easings.standard }));\n    }\n  }, [status, reduced, haptic, shake, wave]);\n\n  useEffect(() => {\n    const x = active * (cellW + GAP);\n    caretX.set(reduced ? x : withSpring(x, spring('snappy')));\n  }, [active, cellW, reduced, caretX]);\n\n  // The caret blinks only while the field has focus and is still waiting for digits.\n  const waiting = focused && digits.length < length && status !== 'success';\n  useEffect(() => {\n    if (!waiting || reduced) {\n      blink.set(1);\n      return;\n    }\n    blink.set(\n      withRepeat(\n        withSequence(\n          withDelay(450, withTiming(0, { duration: 120 })),\n          withDelay(300, withTiming(1, { duration: 120 })),\n        ),\n        -1,\n      ),\n    );\n  }, [waiting, reduced, blink]);\n\n  const change = (text: string) => {\n    const next = text.replace(/\\D/g, '').slice(0, length);\n    if (next === digits) return;\n    onChangeText(next);\n    if (next.length === length) onComplete?.(next);\n  };\n\n  const row = useAnimatedStyle(() => ({ transform: [{ translateX: shake.get() }] }));\n  const caret = useAnimatedStyle(() => ({\n    opacity: waiting ? blink.get() : 0,\n    transform: [{ translateX: caretX.get() + cellW / 2 - 1 }],\n  }));\n\n  const tone =\n    status === 'error' ? colors.danger : status === 'success' ? colors.success : colors.azure;\n\n  return (\n    <View\n      testID={testID}\n      style={[{ opacity: disabled ? 0.45 : 1 }, style]}\n      onLayout={(e) => setWidth(e.nativeEvent.layout.width)}\n    >\n      <Animated.View style={[styles.row, { gap: GAP }, row]} pointerEvents=\"none\">\n        {Array.from({ length }, (_, i) => (\n          <Cell\n            key={i}\n            char={digits[i]}\n            secure={secure}\n            index={i}\n            count={length}\n            current={focused && i === active && status === 'idle'}\n            tone={tone}\n            status={status}\n            wave={wave}\n            reduced={reduced}\n            colors={colors}\n            radius={radius.md}\n            fontSize={font.size['2xl']}\n            fontWeight={font.weight.semibold}\n          />\n        ))}\n        {cellW > 0 ? (\n          <Animated.View style={[styles.caret, { backgroundColor: colors.azure }, caret]} />\n        ) : null}\n      </Animated.View>\n      <TextInput\n        ref={input}\n        value={digits}\n        onChangeText={change}\n        editable={!disabled}\n        autoFocus={autoFocus}\n        onFocus={() => setFocused(true)}\n        onBlur={() => setFocused(false)}\n        keyboardType=\"number-pad\"\n        inputMode=\"numeric\"\n        textContentType=\"oneTimeCode\"\n        autoComplete=\"one-time-code\"\n        maxLength={length}\n        caretHidden\n        contextMenuHidden={false}\n        selectionColor=\"transparent\"\n        accessibilityLabel={accessibilityLabel}\n        accessibilityHint={`${length} digits`}\n        accessibilityState={{ disabled }}\n        style={[StyleSheet.absoluteFill, styles.input]}\n      />\n    </View>\n  );\n}\n\ntype CellProps = {\n  char: string | undefined;\n  secure: boolean;\n  index: number;\n  count: number;\n  current: boolean;\n  tone: string;\n  status: CodeFieldStatus;\n  wave: SharedValue<number>;\n  reduced: boolean;\n  colors: Palette;\n  radius: number;\n  fontSize: number;\n  fontWeight: TextStyle['fontWeight'];\n};\n\nfunction Cell({\n  char,\n  secure,\n  index,\n  count,\n  current,\n  tone,\n  status,\n  wave,\n  reduced,\n  colors,\n  radius,\n  fontSize,\n  fontWeight,\n}: CellProps) {\n  const pop = useSharedValue(char ? 1 : 0);\n  const ring = useSharedValue(current ? 1 : 0);\n  const filled = char !== undefined;\n\n  useEffect(() => {\n    if (!filled) {\n      pop.set(withTiming(0, { duration: durations.quick }));\n      return;\n    }\n    pop.set(0);\n    pop.set(reduced ? 1 : withSpring(1, spring('bouncy')));\n  }, [char, filled, reduced, pop]);\n\n  useEffect(() => {\n    ring.set(withSpring(current || status !== 'idle' ? 1 : 0, spring('snappy', reduced)));\n  }, [current, status, reduced, ring]);\n\n  const cell = useAnimatedStyle(() => {\n    // Each cell lifts as the success wave passes over it.\n    const at = wave.get() * (count + 2) - index - 1;\n    const lift = at > 0 && at < 2 ? Math.sin((at / 2) * Math.PI) : 0;\n    return {\n      borderColor: interpolateColor(ring.get(), [0, 1], [colors.border, tone]),\n      backgroundColor: filled ? colors.surfaceRaised : colors.surface,\n      transform: [{ translateY: -lift * 6 }],\n    };\n  });\n  const glyph = useAnimatedStyle(() => ({\n    opacity: Math.min(1, pop.get() * 1.4),\n    transform: [{ translateY: (1 - pop.get()) * 10 }, { scale: 0.6 + pop.get() * 0.4 }],\n  }));\n\n  return (\n    <Animated.View style={[styles.cell, { borderRadius: radius }, cell]}>\n      <Animated.View style={glyph}>\n        {secure && filled ? (\n          <View style={[styles.dot, { backgroundColor: colors.text }]} />\n        ) : (\n          <Text\n            style={{\n              color: status === 'error' ? colors.danger : colors.text,\n              fontSize,\n              fontWeight,\n              fontVariant: ['tabular-nums'],\n            }}\n          >\n            {char ?? ''}\n          </Text>\n        )}\n      </Animated.View>\n    </Animated.View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  row: { flexDirection: 'row' },\n  cell: {\n    flex: 1,\n    height: CELL_H,\n    borderWidth: 1.5,\n    alignItems: 'center',\n    justifyContent: 'center',\n  },\n  caret: {\n    position: 'absolute',\n    left: 0,\n    top: CELL_H / 2 - 12,\n    width: 2,\n    height: 24,\n    borderRadius: 1,\n  },\n  dot: { width: 12, height: 12, borderRadius: 6 },\n  // The real input covers the row so taps, long-press paste and autofill land on it.\n  input: { opacity: 0.02, color: 'transparent', fontSize: 1 },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "input",
    "web": "live",
    "perf": {
      "budget": "One text input and a row of plain views. While focused and empty the caret blinks (one opacity value); otherwise nothing runs.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 26,
          "baselineMs": 20,
          "jankyPercent": 4.89,
          "atRest": "idle",
          "memoryMb": 148,
          "notes": "The long p99 frame is the system keyboard opening when the field takes focus."
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Digits appear in place, the caret stays lit, and results change colour without the shake or the ripple.",
      "screenReader": "One text field named by accessibilityLabel, with the number of digits as its hint. Accepted and rejected codes are announced.",
      "touchTarget": "The cells are 56 pt tall and the input covers the whole row."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { CodeField } from '@/components/kinetik/code-field';\n\nconst [code, setCode] = useState('');\nconst [status, setStatus] = useState<'idle' | 'error' | 'success'>('idle');\n\n<CodeField\n  value={code}\n  onChangeText={setCode}\n  onComplete={async (c) => setStatus((await verify(c)) ? 'success' : 'error')}\n  status={status}\n  autoFocus\n/>;\n```\n\nSet `status` to `error` to shake the row, or `success` to send a ripple along it. Set it back to `idle` when the person starts typing again.\n\n## When to use\n\n- Verification codes sent by SMS, email or an authenticator app.\n- Short numeric PINs, with `secure`.\n\n## When not to use\n\n- Codes with letters, or longer than about eight characters. Use a plain text field.\n- Passwords. Use a password field, such as Password Meter.\n\n## Notes\n\n- One real `TextInput` covers the cells, so SMS autofill (`oneTimeCode` on iOS, `one-time-code` on Android), paste and the system keyboard work as usual. Everything but digits is dropped.\n- `onComplete` fires once, when the last digit lands. A pasted code that is too long is trimmed to `length`.\n- The caret blinks only while the field is focused and waiting for digits.\n- With reduced motion the digits appear in place and results change colour without moving.\n"
  },
  "docs": "Prefer `npx kinetik-ui add code-field`: it installs dependencies with expo install, so versions match your Expo SDK."
}
