{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "auth",
  "type": "registry:block",
  "title": "Auth",
  "description": "Passwordless sign-in: an email, a one-time code with a resend timer, and a check once you are in.",
  "categories": [
    "screen"
  ],
  "dependencies": [
    "react-native-reanimated",
    "react-native-safe-area-context",
    "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/code-field.json",
    "https://kinetik-ui.dev/r/press-jelly.json",
    "https://kinetik-ui.dev/r/word-cascade.json"
  ],
  "files": [
    {
      "path": "src/components/kinetik/screens/auth.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/screens/auth.tsx",
      "content": "import { useEffect, useState, type ReactNode } from 'react';\nimport {\n  Keyboard,\n  KeyboardAvoidingView,\n  Platform,\n  Pressable,\n  ScrollView,\n  StyleSheet,\n  Text,\n  TextInput,\n  View,\n} from 'react-native';\nimport Animated, {\n  FadeIn,\n  FadeOut,\n  SlideInRight,\n  SlideOutLeft,\n  useAnimatedStyle,\n  useSharedValue,\n  withDelay,\n  withSpring,\n  withTiming,\n} from 'react-native-reanimated';\nimport { useSafeAreaInsets } from 'react-native-safe-area-context';\n\nimport { CodeField, type CodeFieldStatus } from '../code-field';\nimport { PressJelly } from '../press-jelly';\nimport { WordCascade } from '../word-cascade';\nimport { durations, easings, spring, timing } from '../../../lib/kinetik/motion/motion';\nimport { useReduceMotion } from '../../../lib/kinetik/hooks/use-reduce-motion';\nimport { useKinetikTheme } from '../../../lib/kinetik/tokens/theme';\nimport { minTouchTarget } from '../../../lib/kinetik/tokens/tokens';\n\nexport type AuthProps = {\n  /** Send a one-time code to the address. Reject with an Error to show its message. */\n  onSendCode: (email: string) => Promise<void> | void;\n  /** Check the code. Reject when it is wrong; the field shakes and clears. */\n  onVerify: (email: string, code: string) => Promise<void> | void;\n  /** Called by the button on the final step. */\n  onDone: () => void;\n  /** Digits in the code. Defaults to 6. */\n  codeLength?: number;\n  /** Seconds before the code can be sent again. Defaults to 30. */\n  resendAfter?: number;\n  /** Prefills the address. */\n  initialEmail?: string;\n};\n\ntype Step = 'email' | 'code' | 'done';\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/**\n * Passwordless sign-in in three steps that slide into each other: an email,\n * a one-time code with a resend countdown, and a check that pops in once\n * you are through.\n */\nexport function Auth({\n  onSendCode,\n  onVerify,\n  onDone,\n  codeLength = 6,\n  resendAfter = 30,\n  initialEmail = '',\n}: AuthProps) {\n  const { colors, space } = useKinetikTheme();\n  const insets = useSafeAreaInsets();\n  const reduced = useReduceMotion();\n  const [step, setStep] = useState<Step>('email');\n  const [back, setBack] = useState(false);\n  const [email, setEmail] = useState(initialEmail);\n\n  const enter = reduced\n    ? FadeIn.duration(durations.quick)\n    : back\n      ? FadeIn.duration(durations.base).easing(easings.standard)\n      : SlideInRight.duration(durations.slow).easing(easings.standard);\n  const exit = reduced\n    ? FadeOut.duration(durations.quick)\n    : back\n      ? FadeOut.duration(durations.quick)\n      : SlideOutLeft.duration(durations.base).easing(easings.exit);\n\n  return (\n    <KeyboardAvoidingView\n      style={[styles.fill, { backgroundColor: colors.background }]}\n      behavior={Platform.OS === 'ios' ? 'padding' : undefined}\n    >\n      <ScrollView\n        style={styles.fill}\n        keyboardShouldPersistTaps=\"handled\"\n        contentContainerStyle={{\n          flexGrow: 1,\n          paddingTop: insets.top + space[6],\n          paddingBottom: insets.bottom + space[4],\n          paddingHorizontal: space[6],\n        }}\n      >\n        <Animated.View key={step} entering={enter} exiting={exit} style={styles.fill}>\n          {step === 'email' ? (\n            <EmailStep\n              email={email}\n              onChange={setEmail}\n              onSend={async (address) => {\n                await onSendCode(address);\n                setEmail(address);\n                setBack(false);\n                setStep('code');\n              }}\n            />\n          ) : step === 'code' ? (\n            <CodeStep\n              email={email}\n              length={codeLength}\n              resendAfter={resendAfter}\n              onResend={() => onSendCode(email)}\n              onVerify={(code) => onVerify(email, code)}\n              onVerified={() => {\n                Keyboard.dismiss();\n                setBack(false);\n                setStep('done');\n              }}\n              onChangeEmail={() => {\n                setBack(true);\n                setStep('email');\n              }}\n            />\n          ) : (\n            <DoneStep onDone={onDone} />\n          )}\n        </Animated.View>\n      </ScrollView>\n    </KeyboardAvoidingView>\n  );\n}\n\nfunction Heading({ title, body }: { title: string; body: ReactNode }) {\n  const { colors, space, font } = useKinetikTheme();\n  return (\n    <View style={{ gap: space[2] }}>\n      <WordCascade\n        text={title}\n        delay={120}\n        style={{\n          color: colors.text,\n          fontSize: font.size['2xl'],\n          fontWeight: font.weight.bold,\n          letterSpacing: font.tracking.tight,\n        }}\n      />\n      <Text style={{ color: colors.textMuted, fontSize: font.size.md, lineHeight: 22 }}>\n        {body}\n      </Text>\n    </View>\n  );\n}\n\n/** A round badge with an envelope drawn from two views. */\nfunction Envelope() {\n  const { colors, radius } = useKinetikTheme();\n  return (\n    <View\n      aria-hidden\n      style={[styles.badge, { backgroundColor: colors.surface, borderColor: colors.border }]}\n    >\n      <View style={[styles.letter, { borderColor: colors.text, borderRadius: radius.xs }]}>\n        <View style={[styles.flap, { borderColor: colors.text }]} />\n      </View>\n    </View>\n  );\n}\n\nfunction EmailStep({\n  email,\n  onChange,\n  onSend,\n}: {\n  email: string;\n  onChange: (email: string) => void;\n  onSend: (email: string) => Promise<void>;\n}) {\n  const { colors, space, font, radius } = useKinetikTheme();\n  const [busy, setBusy] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n\n  const send = async () => {\n    const address = email.trim();\n    if (!EMAIL.test(address)) {\n      setError('Enter a valid email address');\n      return;\n    }\n    setError(null);\n    setBusy(true);\n    try {\n      await onSend(address);\n    } catch (e) {\n      setError(e instanceof Error && e.message ? e.message : 'We could not send a code.');\n      setBusy(false);\n    }\n  };\n\n  return (\n    <View style={[styles.fill, { gap: space[6] }]}>\n      <Envelope />\n      <Heading\n        title=\"Sign in with a code\"\n        body=\"We’ll email you a one-time code. No password to remember.\"\n      />\n      <View style={{ gap: space[2] }}>\n        <Text\n          style={{ color: colors.text, fontSize: font.size.sm, fontWeight: font.weight.medium }}\n        >\n          Email\n        </Text>\n        <TextInput\n          value={email}\n          onChangeText={(text) => {\n            onChange(text);\n            if (error) setError(null);\n          }}\n          accessibilityLabel=\"Email\"\n          placeholder=\"you@example.com\"\n          placeholderTextColor={colors.textSubtle}\n          keyboardType=\"email-address\"\n          autoCapitalize=\"none\"\n          autoCorrect={false}\n          autoComplete=\"email\"\n          textContentType=\"emailAddress\"\n          returnKeyType=\"send\"\n          onSubmitEditing={send}\n          onFocus={() => setFocused(true)}\n          onBlur={() => setFocused(false)}\n          editable={!busy}\n          selectionColor={colors.azure}\n          cursorColor={colors.azure}\n          style={[\n            styles.input,\n            {\n              color: colors.text,\n              fontSize: font.size.md,\n              backgroundColor: colors.surface,\n              borderColor: error ? colors.danger : focused ? colors.azure : colors.borderStrong,\n              borderRadius: radius.md,\n              paddingHorizontal: space[4],\n            },\n          ]}\n        />\n        {error ? (\n          <Text\n            accessibilityLiveRegion=\"polite\"\n            style={{ color: colors.danger, fontSize: font.size.xs }}\n          >\n            {error}\n          </Text>\n        ) : null}\n      </View>\n      <PressJelly block size=\"lg\" loading={busy} onPress={busy ? undefined : send}>\n        Send code\n      </PressJelly>\n    </View>\n  );\n}\n\nfunction CodeStep({\n  email,\n  length,\n  resendAfter,\n  onResend,\n  onVerify,\n  onVerified,\n  onChangeEmail,\n}: {\n  email: string;\n  length: number;\n  resendAfter: number;\n  onResend: () => Promise<void> | void;\n  onVerify: (code: string) => Promise<void> | void;\n  onVerified: () => void;\n  onChangeEmail: () => void;\n}) {\n  const { colors, space, font } = useKinetikTheme();\n  const [code, setCode] = useState('');\n  const [status, setStatus] = useState<CodeFieldStatus>('idle');\n  const [checking, setChecking] = useState(false);\n  const [message, setMessage] = useState<string | null>(null);\n  const [left, setLeft] = useState(resendAfter);\n\n  // One tick per second while the resend link is locked.\n  useEffect(() => {\n    if (left <= 0) return;\n    const id = setTimeout(() => setLeft((s) => s - 1), 1000);\n    return () => clearTimeout(id);\n  }, [left]);\n\n  const verify = async (value: string) => {\n    setChecking(true);\n    setMessage(null);\n    try {\n      await onVerify(value);\n      setStatus('success');\n      // Let the success wave run along the digits before moving on.\n      setTimeout(onVerified, 650);\n    } catch {\n      setStatus('error');\n      setMessage('That code didn’t match. Try again.');\n      setTimeout(() => setCode(''), 450);\n    } finally {\n      setChecking(false);\n    }\n  };\n\n  const resend = async () => {\n    setMessage(null);\n    setLeft(resendAfter);\n    try {\n      await onResend();\n      setMessage('A new code is on its way.');\n    } catch {\n      setLeft(0);\n      setMessage('We could not send a new code.');\n    }\n  };\n\n  const clock = `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}`;\n\n  return (\n    <View style={[styles.fill, { gap: space[6] }]}>\n      <Pressable\n        accessibilityRole=\"button\"\n        accessibilityLabel=\"Change email\"\n        onPress={onChangeEmail}\n        style={styles.backLink}\n      >\n        <Text\n          style={{\n            color: colors.textMuted,\n            fontSize: font.size.sm,\n            fontWeight: font.weight.medium,\n          }}\n        >\n          ‹ Change email\n        </Text>\n      </Pressable>\n      <Heading\n        title=\"Check your inbox\"\n        body={\n          <>\n            Enter the code we sent to{' '}\n            <Text style={{ color: colors.text, fontWeight: font.weight.semibold }}>{email}</Text>\n          </>\n        }\n      />\n      <View style={{ gap: space[3] }}>\n        <CodeField\n          value={code}\n          onChangeText={(value) => {\n            setCode(value);\n            if (status === 'error') setStatus('idle');\n          }}\n          onComplete={verify}\n          length={length}\n          status={status}\n          disabled={checking || status === 'success'}\n          autoFocus\n        />\n        <Text\n          accessibilityLiveRegion=\"polite\"\n          style={{\n            minHeight: 18,\n            color: status === 'error' ? colors.danger : colors.textMuted,\n            fontSize: font.size.xs,\n          }}\n        >\n          {checking ? 'Checking…' : (message ?? '')}\n        </Text>\n      </View>\n      {left > 0 ? (\n        <Text\n          accessibilityLabel={`You can resend the code in ${left} seconds`}\n          style={[styles.resend, { color: colors.textSubtle, fontSize: font.size.sm }]}\n        >\n          Resend code in {clock}\n        </Text>\n      ) : (\n        <Pressable accessibilityRole=\"button\" onPress={resend} style={styles.resend}>\n          <Text\n            style={{\n              color: colors.text,\n              fontSize: font.size.sm,\n              fontWeight: font.weight.semibold,\n              textDecorationLine: 'underline',\n            }}\n          >\n            Resend code\n          </Text>\n        </Pressable>\n      )}\n    </View>\n  );\n}\n\n/** A check that pops into a filled circle while a ring breathes out once behind it. */\nfunction DoneStep({ onDone }: { onDone: () => void }) {\n  const { colors, space, font } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const pop = useSharedValue(reduced ? 1 : 0);\n  const ring = useSharedValue(reduced ? 1 : 0);\n\n  useEffect(() => {\n    if (reduced) return;\n    pop.set(withDelay(160, withSpring(1, spring('bouncy'))));\n    ring.set(withDelay(260, withTiming(1, { ...timing('slow'), duration: 900 })));\n  }, [reduced, pop, ring]);\n\n  const badge = useAnimatedStyle(() => ({ transform: [{ scale: pop.get() }] }));\n  const tick = useAnimatedStyle(() => ({\n    opacity: Math.min(1, Math.max(0, pop.get() * 2 - 0.8)),\n    transform: [{ rotate: '-45deg' }, { scale: 0.6 + pop.get() * 0.4 }],\n  }));\n  const halo = useAnimatedStyle(() => ({\n    opacity: reduced ? 0 : (1 - ring.get()) * 0.6,\n    transform: [{ scale: 1 + ring.get() * 0.9 }],\n  }));\n\n  return (\n    <View style={[styles.fill, styles.done, { gap: space[6] }]}>\n      <View style={styles.doneArt}>\n        <Animated.View style={[styles.halo, { borderColor: colors.success }, halo]} />\n        <Animated.View style={[styles.doneBadge, { backgroundColor: colors.success }, badge]}>\n          <Animated.View style={[styles.tick, { borderColor: colors.background }, tick]} />\n        </Animated.View>\n      </View>\n      <View style={{ gap: space[2], alignItems: 'center' }}>\n        <Text\n          accessibilityRole=\"header\"\n          style={{\n            color: colors.text,\n            fontSize: font.size['2xl'],\n            fontWeight: font.weight.bold,\n            letterSpacing: font.tracking.tight,\n          }}\n        >\n          You’re in\n        </Text>\n        <Text\n          style={{\n            color: colors.textMuted,\n            fontSize: font.size.md,\n            lineHeight: 22,\n            textAlign: 'center',\n          }}\n        >\n          Your email is verified. Next time it takes a single code.\n        </Text>\n      </View>\n      <PressJelly block size=\"lg\" onPress={onDone} style={styles.doneButton}>\n        Continue\n      </PressJelly>\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  fill: { flex: 1 },\n  input: { minHeight: 52, borderWidth: 1 },\n  badge: {\n    width: 56,\n    height: 56,\n    borderRadius: 28,\n    borderWidth: StyleSheet.hairlineWidth,\n    alignItems: 'center',\n    justifyContent: 'center',\n  },\n  letter: { width: 24, height: 18, borderWidth: 1.75, overflow: 'hidden', alignItems: 'center' },\n  flap: {\n    width: 16,\n    height: 16,\n    marginTop: -10,\n    borderWidth: 1.75,\n    transform: [{ rotate: '45deg' }],\n  },\n  backLink: { minHeight: minTouchTarget, justifyContent: 'center', alignSelf: 'flex-start' },\n  resend: {\n    minHeight: minTouchTarget,\n    alignSelf: 'center',\n    justifyContent: 'center',\n    textAlignVertical: 'center',\n  },\n  done: { alignItems: 'center', justifyContent: 'center' },\n  doneArt: { width: 120, height: 120, alignItems: 'center', justifyContent: 'center' },\n  halo: { position: 'absolute', width: 96, height: 96, borderRadius: 48, borderWidth: 2 },\n  doneBadge: {\n    width: 96,\n    height: 96,\n    borderRadius: 48,\n    alignItems: 'center',\n    justifyContent: 'center',\n  },\n  tick: {\n    width: 34,\n    height: 18,\n    marginTop: -8,\n    borderLeftWidth: 5,\n    borderBottomWidth: 5,\n    borderRadius: 2,\n  },\n  doneButton: { alignSelf: 'stretch' },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "template",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "screen",
    "web": "live",
    "perf": {
      "budget": "Steps slide in with one layout animation each; the code row and the final check are UI-thread springs. The resend countdown re-renders once a second while it runs.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-14",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 23,
          "baselineMs": 17,
          "jankyPercent": 6.88,
          "atRest": "idle",
          "memoryMb": 154,
          "notes": "Most janky frames are the software keyboard and the step slide on the emulator; the code row itself stays at the baseline."
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Steps cross-fade instead of sliding, the check appears without popping or a ring, and the code row does not shake or wave (Code Field).",
      "screenReader": "Each step leads with its title. The code field is named Verification code; checking, a wrong code and a resent code are announced. The countdown reads \"You can resend the code in 24 seconds\".",
      "touchTarget": "The email field is 52 pt; buttons and links are at least 44 pt."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { Auth } from '@/components/kinetik/screens/auth';\n\n<Auth\n  onSendCode={(email) => auth.sendOtp({ email })}\n  onVerify={async (email, code) => {\n    const { error } = await auth.verifyOtp({ email, token: code });\n    if (error) throw error;\n  }}\n  onDone={() => router.replace('/home')}\n/>;\n```\n\nThe demo accepts the code **123456**.\n\n## When to use\n\n- Passwordless sign-in or sign-up with a one-time code sent by email (Supabase, Clerk, Firebase email links, your own API).\n- Confirming an address after sign-up.\n\n## When not to use\n\n- Codes sent by SMS: the copy, keyboard and field label assume email. Change them before you reuse the flow.\n- Accounts with passwords: use the Login screen.\n\n## Notes\n\n- `onVerify` runs as soon as the last digit is entered. Reject to shake and clear the code; resolve to play the success wave and move to the final step.\n- Resend unlocks after `resendAfter` seconds (default 30) and restarts the timer each time it is used.\n- Codes paste and autofill from the keyboard suggestion (Code Field handles one-time-code autofill).\n"
  },
  "docs": "Prefer `npx kinetik-ui add auth`: it installs dependencies with expo install, so versions match your Expo SDK."
}
