OTP verification

Six-digit code entry where one hidden input (so paste and SMS autofill work) and an on-screen number pad drive the same boxes: digits pop in, the active box carries an accent ring and a pulsing caret, and the sixth digit verifies on its own with a shimmer. A match sends a green wave across the row and draws a check, a miss shakes, flashes red and clears, and a draining ring counts down to Resend code.

authotp2faverificationcode inputnumber padresend countdownanimationreanimated
Paste into Claude Code Cursor Codex Lovable RapidNative
Live preview · follows the site themeOpen full screen

Details

File
components/patterns/otp-verification.tsx
Lines
795
Stack
React Native, StyleSheet
Packages
expo-linear-gradient, lucide-react-native, react-native-reanimated, react-native-safe-area-context, react-native-svg, react-native-worklets
Platforms
iOS, Android, Web

Using gluestack-ui?

Optional. The screen is plain React Native; these components can stand in for its primitives.

components/patterns/otp-verification.tsx
1import { useEffect, useRef, useState, type ComponentRef, type ReactNode } from 'react';
2import { Platform, Pressable, StyleSheet, Text, TextInput, View, useColorScheme, useWindowDimensions, type LayoutChangeEvent } from 'react-native';
3import Animated, {
4 cancelAnimation,
5 Easing,
6 FadeIn,
7 FadeInDown,
8 interpolate,
9 interpolateColor,
10 useAnimatedProps,
11 useAnimatedStyle,
12 useSharedValue,
13 withDelay,
14 withRepeat,
15 withSequence,
16 withSpring,
17 withTiming,
18 type SharedValue,
19} from 'react-native-reanimated';
20import { LinearGradient } from 'expo-linear-gradient';
21import { useSafeAreaInsets } from 'react-native-safe-area-context';
22import Svg, { Circle, Path } from 'react-native-svg';
23import { ChevronLeft, CircleAlert, CircleCheck, Delete, PhoneCall, RotateCw } from 'lucide-react-native';
24
25// ─── Brand ──────────────────────────────────────────────────────────────────
26// The screen's accent. Every accent colour below derives from these, so changing them rebrands the screen.
27
28const ACCENT = '#1064FF';
29const ACCENT_DARK = '#5B97FF'; // the accent on dark backgrounds
30const ON_ACCENT = '#FFFFFF'; // text and icons on an accent fill
31
32/** `hex` at `alpha` opacity, as rgba(). */
33function tint(hex: string, alpha: number) {
34 const n = parseInt(hex.slice(1), 16);
35 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
36}
37
38/** `hex` mixed toward black (amount > 0) or white (amount < 0); amount from -1 to 1. */
39function shade(hex: string, amount: number) {
40 const n = parseInt(hex.slice(1), 16);
41 const target = amount < 0 ? 255 : 0;
42 const p = Math.abs(amount);
43 const c = (v: number) => Math.round(v + (target - v) * p).toString(16).padStart(2, '0');
44 return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`.toUpperCase();
45}
46
47// ─── Sample data ────────────────────────────────────────────────────────────
48
49const PHONE_MASKED = '+1 ••• ••• 4821';
50const CODE_LENGTH = 6;
51
52// The code this demo accepts, and what the Paste key reads from its pretend clipboard.
53const CORRECT_CODE = '482913';
54const CLIPBOARD_CODE = '482913';
55
56// The preview opens part way through: three digits typed, the code sent a few seconds ago.
57const PREFILL = '482';
58const RESEND_AFTER = 30; // seconds before another code can be requested
59const OPENING_SECONDS = 26;
60
61const CHECK_MS = 900; // stands in for the round trip to your verification endpoint
62const ERROR_HOLD_MS = 620; // how long the wrong digits stay red before the boxes clear
63const REPLAY_MS = 2300; // success stays up this long, then the preview resets
64const NOTICE_MS = 2600;
65
66const PAD: string[][] = [
67 ['1', '2', '3'],
68 ['4', '5', '6'],
69 ['7', '8', '9'],
70 ['paste', '0', 'del'],
71];
72
73// ─── Palette ────────────────────────────────────────────────────────────────
74
75const SUCCESS = '#16A34A';
76const PRESS = { damping: 16, stiffness: 320, mass: 0.6 };
77const TABULAR = { fontVariant: ['tabular-nums' as const] };
78const NO_OUTLINE = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as object) : null;
79
80function usePalette() {
81 const dark = useColorScheme() === 'dark';
82 return {
83 dark,
84 bg: dark ? '#000000' : '#FAFAFA',
85 fg: dark ? '#FAFAFA' : '#0A0A0A',
86 muted: dark ? '#8E8E93' : '#71717A',
87 faint: dark ? '#48484D' : '#C4C4CC',
88 field: dark ? '#141416' : '#FFFFFF',
89 border: dark ? '#2A2A2E' : '#E4E4E7',
90 press: dark ? '#1F1F23' : '#E9E9ED',
91 link: dark ? ACCENT_DARK : ACCENT,
92 filled: dark ? shade(ACCENT_DARK, 0.8) : shade(ACCENT, -0.93),
93 filledBorder: dark ? shade(ACCENT_DARK, 0.54) : shade(ACCENT, -0.75),
94 glow: dark ? tint(ACCENT_DARK, 0.26) : tint(ACCENT, 0.16),
95 shimmer: dark ? tint(shade(ACCENT_DARK, -0.18), 0.3) : tint(ACCENT, 0.16),
96 ok: dark ? '#34D399' : SUCCESS,
97 okFill: dark ? '#0B2A1E' : '#E7F8EE',
98 error: dark ? '#FF6B6B' : '#E5484D',
99 errorFill: dark ? '#331518' : '#FDECEC',
100 bubble: dark ? '#1C1C20' : '#FFFFFF',
101 bubbleBorder: dark ? '#34343A' : shade(ACCENT, -0.85),
102 bubbleShadow: dark ? '0px 6px 16px rgba(0, 0, 0, 0.5)' : `0px 6px 16px ${tint(shade(ACCENT, 0.38), 0.16)}`,
103 rings: dark ? ACCENT_DARK : ACCENT,
104 band: dark ? ([shade(ACCENT, 0.65), shade(ACCENT, 0.835), '#000000'] as const) : ([shade(ACCENT, -0.83), shade(ACCENT, -0.91), '#FAFAFA'] as const),
105 veil: dark ? (['rgba(0,0,0,0)', '#000000'] as const) : (['rgba(250,250,250,0)', '#FAFAFA'] as const),
106 };
107}
108type Palette = ReturnType<typeof usePalette>;
109
110// ─── Background: a soft band of the accent, with rings spreading from the phone ───
111
112const ART_SCALE = 1.2; // the illustration is drawn on a 96 x 90 canvas
113const ART_W = 96 * ART_SCALE;
114const ART_H = 90 * ART_SCALE;
115
116function Backdrop({ width, top, cy }: { width: number; top: number; cy: number }) {
117 const c = usePalette();
118 const height = top + 330;
119 return (
120 <View style={[styles.backdrop, { height }]}>
121 <LinearGradient colors={c.band} locations={[0, 0.5, 1]} style={StyleSheet.absoluteFill} />
122 <View style={styles.rings}>
123 <Svg width={width} height={height}>
124 {[62, 104, 152, 206, 266].map((r, i) => (
125 <Circle key={r} cx={width / 2} cy={cy} r={r} fill="none" stroke={c.rings} strokeWidth={1} strokeOpacity={(c.dark ? 0.24 : 0.17) - i * 0.035} />
126 ))}
127 </Svg>
128 </View>
129 {/* The rings dissolve into the page before the band ends */}
130 <LinearGradient colors={c.veil} style={styles.veil} />
131 </View>
132 );
133}
134
135// ─── Illustration: a phone, and a message bubble that types until the code checks out ───
136
137const AnimatedCircle = Animated.createAnimatedComponent(Circle);
138const AnimatedPath = Animated.createAnimatedComponent(Path);
139
140const SUCCESS_BEAT = 360; // the check and the headline wait for the green wave to cross the boxes
141const TICK_LENGTH = 20;
142
143function TypingDot({ index, wave, done, color }: { index: number; wave: SharedValue<number>; done: SharedValue<number>; color: string }) {
144 const style = useAnimatedStyle(() => {
145 const phase = (wave.value - index * 0.16 + 1) % 1;
146 const lift = phase < 0.45 ? Math.sin((phase / 0.45) * Math.PI) : 0;
147 return {
148 opacity: (0.35 + 0.65 * lift) * interpolate(done.value, [0, 0.25], [1, 0], 'clamp'),
149 transform: [{ translateY: -3 * lift }],
150 };
151 });
152 return <Animated.View style={[styles.typingDot, { backgroundColor: color }, style]} />;
153}
154
155function Illustration({ verified }: { verified: boolean }) {
156 const c = usePalette();
157 const wave = useSharedValue(0);
158 const arrive = useSharedValue(0);
159 const done = useSharedValue(0);
160
161 useEffect(() => {
162 wave.value = withRepeat(withTiming(1, { duration: 1300, easing: Easing.linear }), -1);
163 arrive.value = withDelay(300, withTiming(1, { duration: 420, easing: Easing.out(Easing.back(2.2)) }));
164 return () => cancelAnimation(wave);
165 }, [wave, arrive]);
166 useEffect(() => {
167 done.value = verified ? withDelay(SUCCESS_BEAT, withTiming(1, { duration: 560, easing: Easing.out(Easing.cubic) })) : withTiming(0, { duration: 240 });
168 }, [verified, done]);
169
170 const bubble = useAnimatedStyle(() => ({
171 opacity: Math.max(0, Math.min(1, arrive.value * 1.6)),
172 backgroundColor: interpolateColor(done.value, [0, 0.35], [c.bubble, SUCCESS]),
173 borderColor: interpolateColor(done.value, [0, 0.35], [c.bubbleBorder, SUCCESS]),
174 transform: [{ scale: (0.5 + 0.5 * arrive.value) * interpolate(done.value, [0, 0.4, 1], [1, 1.14, 1]) }],
175 }));
176 const tickLayer = useAnimatedStyle(() => ({ opacity: interpolate(done.value, [0.25, 0.4], [0, 1], 'clamp') }));
177 const tick = useAnimatedProps(() => ({ strokeDashoffset: TICK_LENGTH * (1 - interpolate(done.value, [0.3, 1], [0, 1], 'clamp')) }));
178
179 return (
180 <View role="img" aria-label={verified ? 'Code verified' : 'A text message arriving on a phone'} style={styles.art}>
181 <View style={styles.artCanvas}>
182 <View style={styles.phone}>
183 <LinearGradient colors={[shade(ACCENT, -0.31), ACCENT]} style={styles.phoneFace}>
184 <View style={styles.phoneSpeaker} />
185 <View style={[styles.phoneLine, styles.phoneLineFirst]} />
186 <View style={styles.phoneLine} />
187 <View style={[styles.phoneLine, styles.phoneLineShort]} />
188 </LinearGradient>
189 </View>
190 <Animated.View style={[styles.bubble, { boxShadow: c.bubbleShadow }, bubble]}>
191 <View style={styles.typing}>
192 {[0, 1, 2].map((i) => (
193 <TypingDot key={i} index={i} wave={wave} done={done} color={c.link} />
194 ))}
195 </View>
196 <Animated.View style={[StyleSheet.absoluteFill, styles.center, tickLayer]}>
197 <Svg width={24} height={24} viewBox="0 0 24 24">
198 <AnimatedPath d="M5.5 12.6 10 17 18.5 7.5" stroke="#FFFFFF" strokeWidth={2.8} strokeLinecap="round" strokeLinejoin="round" fill="none" strokeDasharray={TICK_LENGTH} animatedProps={tick} />
199 </Svg>
200 </Animated.View>
201 </Animated.View>
202 </View>
203 </View>
204 );
205}
206
207// ─── Small pieces ───────────────────────────────────────────────────────────
208
209function BackButton({ pal }: { pal: Palette }) {
210 const scale = useSharedValue(1);
211 const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
212 return (
213 <Pressable
214 role="button"
215 aria-label="Back"
216 hitSlop={6}
217 onPressIn={() => (scale.value = withSpring(0.9, PRESS))}
218 onPressOut={() => (scale.value = withSpring(1, PRESS))}
219 style={styles.backPress}
220 >
221 <Animated.View style={[styles.back, { backgroundColor: pal.field, borderColor: pal.border }, style]}>
222 <ChevronLeft size={22} color={pal.fg} strokeWidth={2.2} style={styles.backIcon} />
223 </Animated.View>
224 </Pressable>
225 );
226}
227
228/** One of two stacked lines; only the current one is opaque, so a change is a true cross-fade. */
229function Layer({ on, delay = 0, children }: { on: boolean; delay?: number; children: ReactNode }) {
230 const t = useSharedValue(on ? 1 : 0);
231 useEffect(() => {
232 // The incoming line waits a beat, so the two are never legible on top of each other.
233 t.value = withDelay(delay + (on ? 130 : 0), withTiming(on ? 1 : 0, { duration: on ? 280 : 150, easing: Easing.out(Easing.cubic) }));
234 }, [on, delay, t]);
235 const style = useAnimatedStyle(() => ({ opacity: t.value, transform: [{ translateY: interpolate(t.value, [0, 1], [8, 0]) }] }));
236 return (
237 <Animated.View aria-hidden={!on} style={[StyleSheet.absoluteFill, styles.center, { pointerEvents: on ? 'auto' : 'none' }, style]}>
238 {children}
239 </Animated.View>
240 );
241}
242
243function Spinner({ color, track }: { color: string; track: string }) {
244 const r = useSharedValue(0);
245 useEffect(() => {
246 r.value = withRepeat(withTiming(360, { duration: 700, easing: Easing.linear }), -1);
247 return () => cancelAnimation(r);
248 }, [r]);
249 const style = useAnimatedStyle(() => ({ transform: [{ rotate: `${r.value}deg` }] }));
250 return <Animated.View style={[styles.spinner, { borderColor: track, borderTopColor: color }, style]} />;
251}
252
253/** A tiny ring that drains clockwise from the top as the resend wait runs down. */
254function CountdownRing({ left, color, track }: { left: SharedValue<number>; color: string; track: string }) {
255 const radius = 6.6;
256 const length = 2 * Math.PI * radius;
257 const arc = useAnimatedProps(() => ({ strokeDashoffset: length * (1 - left.value) }));
258 return (
259 <View style={styles.countdownRing}>
260 <Svg width={18} height={18} viewBox="0 0 18 18">
261 <Circle cx={9} cy={9} r={radius} stroke={track} strokeWidth={2.4} fill="none" />
262 <AnimatedCircle cx={9} cy={9} r={radius} stroke={color} strokeWidth={2.4} strokeLinecap="round" fill="none" strokeDasharray={length} animatedProps={arc} />
263 </Svg>
264 </View>
265 );
266}
267
268// ─── Code boxes: six views painted from one hidden input ────────────────────
269
270type Status = 'idle' | 'checking' | 'success' | 'error';
271
272const BOX_H = 60;
273const BOX_RADIUS = 15;
274const BOX_GAP = 8;
275const DASH_W = 26;
276const SHIMMER_W = 90;
277
278function Caret() {
279 const on = useSharedValue(1);
280 useEffect(() => {
281 // A soft pulse rather than a hard blink, so it never disappears completely.
282 on.value = withRepeat(withSequence(withDelay(700, withTiming(0.2, { duration: 160 })), withDelay(180, withTiming(1, { duration: 160 }))), -1);
283 return () => cancelAnimation(on);
284 }, [on]);
285 const style = useAnimatedStyle(() => ({ opacity: on.value }));
286 return <Animated.View entering={FadeIn.duration(140)} style={[styles.caret, style]} />;
287}
288
289type BoxProps = {
290 index: number;
291 digit?: string;
292 active: boolean;
293 status: Status;
294 /** How long the digit waits before popping in: staggers a paste, and the opening digits. */
295 delay: number;
296 width: number;
297 /** Left edge within the row, so the shimmer reads as one band crossing all six boxes. */
298 x: number;
299 rowWidth: number;
300 sweep: SharedValue<number>;
301 pal: Palette;
302};
303
304function CodeBox({ index, digit, active, status, delay, width, x, rowWidth, sweep, pal }: BoxProps) {
305 const [glyph, setGlyph] = useState(digit ?? '');
306 const pop = useSharedValue(0);
307 const ring = useSharedValue(0);
308 const tone = useSharedValue(0); // -1 wrong, 0 neutral, 1 verified
309 const hop = useSharedValue(0);
310 const busy = useSharedValue(0);
311
312 useEffect(() => {
313 if (digit) {
314 setGlyph(digit);
315 pop.value = withDelay(delay, withTiming(1, { duration: 260, easing: Easing.out(Easing.back(2.6)) }));
316 } else {
317 pop.value = withTiming(0, { duration: 150, easing: Easing.in(Easing.quad) });
318 }
319 // eslint-disable-next-line react-hooks/exhaustive-deps
320 }, [digit]);
321
322 useEffect(() => {
323 ring.value = withTiming(active ? 1 : 0, { duration: 170 });
324 }, [active, ring]);
325
326 useEffect(() => {
327 busy.value = withTiming(status === 'checking' ? 1 : 0, { duration: 160 });
328 if (status === 'success') {
329 // Green crosses the row left to right, each box with a small hop.
330 tone.value = withDelay(index * 70, withTiming(1, { duration: 220 }));
331 hop.value = withDelay(index * 70, withSequence(withTiming(-7, { duration: 130, easing: Easing.out(Easing.quad) }), withTiming(0, { duration: 300, easing: Easing.out(Easing.back(2.4)) })));
332 } else if (status === 'error') {
333 tone.value = withTiming(-1, { duration: 110 });
334 } else {
335 tone.value = withTiming(0, { duration: 280 });
336 }
337 }, [status, index, busy, tone, hop]);
338
339 const body = useAnimatedStyle(() => ({ transform: [{ translateY: hop.value }] }));
340 const filled = useAnimatedStyle(() => ({ opacity: Math.max(0, Math.min(1, pop.value)) }));
341 const focus = useAnimatedStyle(() => ({ opacity: ring.value, transform: [{ scale: interpolate(ring.value, [0, 1], [1.08, 1]) }] }));
342 const good = useAnimatedStyle(() => ({ opacity: Math.max(0, tone.value) }));
343 const bad = useAnimatedStyle(() => ({ opacity: Math.max(0, -tone.value) }));
344 const band = useAnimatedStyle(() => ({
345 opacity: busy.value,
346 transform: [{ translateX: interpolate(sweep.value, [0, 1], [-SHIMMER_W, rowWidth]) - x }],
347 }));
348 const text = useAnimatedStyle(() => ({
349 opacity: Math.max(0, Math.min(1, pop.value * 1.6)),
350 color: interpolateColor(tone.value, [-1, 0, 1], [pal.error, pal.fg, pal.ok]),
351 transform: [{ translateY: (1 - pop.value) * 8 }, { scale: 0.4 + 0.6 * pop.value }],
352 }));
353
354 const layer = [StyleSheet.absoluteFill, styles.boxLayer];
355 return (
356 <Animated.View style={[styles.box, { width }, body]}>
357 <View style={[layer, { backgroundColor: pal.field, borderColor: pal.border }]} />
358 <Animated.View style={[layer, { backgroundColor: pal.filled, borderColor: pal.filledBorder }, filled]} />
359 <Animated.View style={[layer, { backgroundColor: pal.okFill, borderColor: pal.ok }, good]} />
360 <Animated.View style={[layer, { backgroundColor: pal.errorFill, borderColor: pal.error }, bad]} />
361 <View style={[StyleSheet.absoluteFill, styles.boxClip]}>
362 <Animated.View style={[styles.shimmer, band]}>
363 <LinearGradient colors={['rgba(0,0,0,0)', pal.shimmer, 'rgba(0,0,0,0)']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.fill} />
364 </Animated.View>
365 </View>
366 <Animated.View style={[layer, styles.boxFocus, { boxShadow: `0px 0px 0px 4px ${pal.glow}` }, focus]} />
367 <Animated.Text style={[styles.digit, TABULAR, text]}>{glyph}</Animated.Text>
368 {active && <Caret />}
369 </Animated.View>
370 );
371}
372
373// ─── Number pad: a circle flashes under the key and fades ───────────────────
374
375function PadKey({ value, height, onPress, onLongPress, pal }: { value: string; height: number; onPress: () => void; onLongPress?: () => void; pal: Palette }) {
376 const glow = useSharedValue(0);
377 const style = useAnimatedStyle(() => ({ opacity: glow.value, transform: [{ scale: 0.8 + glow.value * 0.2 }] }));
378 const size = Math.min(72, height + 6);
379 const label = value === 'del' ? 'Delete' : value === 'paste' ? 'Paste code' : value;
380 return (
381 <Pressable
382 role="button"
383 aria-label={label}
384 onPress={onPress}
385 onLongPress={onLongPress}
386 onPressIn={() => (glow.value = 1)}
387 onPressOut={() => (glow.value = withTiming(0, { duration: 380, easing: Easing.out(Easing.quad) }))}
388 style={[styles.padKey, { height }, NO_OUTLINE]}
389 >
390 <Animated.View style={[styles.padGlow, { width: size, height: size, borderRadius: size / 2, backgroundColor: pal.press }, style]} />
391 {value === 'del' ? (
392 <View>
393 <Delete size={26} color={pal.fg} strokeWidth={1.9} />
394 </View>
395 ) : value === 'paste' ? (
396 <Text style={[styles.padPaste, { color: pal.link }]}>Paste</Text>
397 ) : (
398 <Text style={[styles.padDigit, { color: pal.fg }, TABULAR]}>{value}</Text>
399 )}
400 </Pressable>
401 );
402}
403
404// ─── Screen ─────────────────────────────────────────────────────────────────
405
406type Notice = 'sent' | 'calling' | null;
407
408export default function OtpVerificationScreen() {
409 const c = usePalette();
410 const insets = useSafeAreaInsets();
411 const { width, height } = useWindowDimensions();
412 const [code, setCode] = useState(PREFILL);
413 const [status, setStatus] = useState<Status>('idle');
414 const [failed, setFailed] = useState(false);
415 const [notice, setNotice] = useState<Notice>(null);
416 const [deadline, setDeadline] = useState(() => Date.now() + OPENING_SECONDS * 1000);
417 const [secondsLeft, setSecondsLeft] = useState(OPENING_SECONDS);
418 const inputRef = useRef<ComponentRef<typeof TextInput>>(null);
419 const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
420 const noticeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
421
422 const verified = status === 'success';
423 const busy = status !== 'idle';
424
425 useEffect(
426 () => () => {
427 timers.current.forEach(clearTimeout);
428 if (noticeTimer.current) clearTimeout(noticeTimer.current);
429 },
430 []
431 );
432 const later = (ms: number, run: () => void) => timers.current.push(setTimeout(run, ms));
433
434 // ── Verifying ──
435
436 const shake = useSharedValue(0);
437 const sweep = useSharedValue(0);
438 const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: shake.value }] }));
439
440 useEffect(() => {
441 if (status !== 'checking') return;
442 sweep.value = 0;
443 sweep.value = withRepeat(withTiming(1, { duration: CHECK_MS - 80, easing: Easing.inOut(Easing.quad) }), -1);
444 return () => cancelAnimation(sweep);
445 }, [status, sweep]);
446
447 const verify = (value: string) => {
448 setStatus('checking');
449 // Replace this timer with your verification call.
450 later(CHECK_MS, () => {
451 if (value === CORRECT_CODE) {
452 setStatus('success');
453 // Navigate onward here. The reset only exists so the preview can replay.
454 later(REPLAY_MS, () => {
455 setStatus('idle');
456 setCode(PREFILL);
457 });
458 return;
459 }
460 setStatus('error');
461 setFailed(true);
462 shake.value = withSequence(
463 withTiming(-10, { duration: 50 }),
464 withTiming(10, { duration: 60 }),
465 withTiming(-7, { duration: 60 }),
466 withTiming(7, { duration: 60 }),
467 withTiming(-3, { duration: 50 }),
468 withTiming(0, { duration: 50 })
469 );
470 later(ERROR_HOLD_MS, () => {
471 setCode('');
472 setStatus('idle');
473 });
474 });
475 };
476
477 // Every source of digits (keyboard, paste, SMS autofill, the pad) ends up here.
478 const enter = (raw: string) => {
479 if (busy) return;
480 const next = raw.replace(/\D/g, '').slice(0, CODE_LENGTH);
481 if (next === code) return;
482 setCode(next);
483 if (next) setFailed(false);
484 if (next.length === CODE_LENGTH) verify(next);
485 };
486 const press = (key: string) => enter(key === 'paste' ? CLIPBOARD_CODE : key === 'del' ? code.slice(0, -1) : code + key);
487
488 // Web only: a hardware keyboard reaches the code even when the hidden input is not focused.
489 const pressRef = useRef(press);
490 useEffect(() => {
491 pressRef.current = press;
492 });
493 useEffect(() => {
494 if (Platform.OS !== 'web' || typeof document === 'undefined') return;
495 const onKey = (e: KeyboardEvent) => {
496 const tag = (e.target as HTMLElement | null)?.tagName;
497 if (e.metaKey || e.ctrlKey || e.altKey || tag === 'INPUT' || tag === 'TEXTAREA') return;
498 if (/^\d$/.test(e.key)) pressRef.current(e.key);
499 else if (e.key === 'Backspace') pressRef.current('del');
500 };
501 document.addEventListener('keydown', onKey);
502 return () => document.removeEventListener('keydown', onKey);
503 }, []);
504
505 // ── Resend countdown ──
506
507 const drain = useSharedValue(OPENING_SECONDS / RESEND_AFTER);
508 useEffect(() => {
509 const left = Math.max(0, deadline - Date.now());
510 drain.value = left / (RESEND_AFTER * 1000);
511 drain.value = withTiming(0, { duration: left, easing: Easing.linear });
512 const id = setInterval(() => {
513 const s = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
514 setSecondsLeft(s);
515 if (s === 0) clearInterval(id);
516 }, 250);
517 return () => clearInterval(id);
518 }, [deadline, drain]);
519
520 const flash = (next: Notice) => {
521 setNotice(next);
522 if (noticeTimer.current) clearTimeout(noticeTimer.current);
523 noticeTimer.current = setTimeout(() => setNotice(null), NOTICE_MS);
524 };
525 const resend = () => {
526 if (busy) return;
527 // Call your resend endpoint here.
528 setDeadline(Date.now() + RESEND_AFTER * 1000);
529 setSecondsLeft(RESEND_AFTER);
530 setCode('');
531 setFailed(false);
532 flash('sent');
533 };
534
535 // ── Layout ──
536
537 const rowWidth = Math.min(width, 440) - 48;
538 const boxWidth = (rowWidth - BOX_GAP * 4 - DASH_W) / CODE_LENGTH;
539 const boxX = (i: number) => i * (boxWidth + BOX_GAP) + (i >= 3 ? DASH_W - BOX_GAP : 0);
540 // Everything above the pad has a fixed height, so shorter phones get shorter keys and nothing scrolls.
541 const keyHeight = Math.max(44, Math.min(64, Math.floor((height - insets.top - insets.bottom - 450) / 4)));
542 // Where the illustration sits inside the centred block; measured, so the rings behind it stay centred on it.
543 const [artTop, setArtTop] = useState(() => Math.max(0, (height - insets.top - insets.bottom - 60 - keyHeight * 4 - 368) / 2));
544
545 // Digits that arrive together (a paste, or the opening three) pop in one after another.
546 const booted = useRef(false);
547 const lastLength = useRef(0);
548 const delayFor = (i: number) => (booted.current ? 0 : 380) + Math.max(0, i - lastLength.current) * (booted.current ? 45 : 70);
549 useEffect(() => {
550 booted.current = true;
551 lastLength.current = code.length;
552 }, [code]);
553
554 const padStyle = useAnimatedStyle(() => ({ opacity: withTiming(busy ? 0.32 : 1, { duration: 220 }) }), [busy]);
555 // Once the code is accepted there is nothing left to resend.
556 const resendStyle = useAnimatedStyle(() => ({ opacity: withDelay(verified ? SUCCESS_BEAT : 0, withTiming(verified ? 0 : 1, { duration: 220 })) }), [verified]);
557 const enterAt = (i: number) => FadeInDown.delay(40 + i * 55).duration(420);
558 const timer = `0:${String(secondsLeft).padStart(2, '0')}`;
559
560 const box = (i: number) => (
561 <CodeBox key={i} index={i} digit={code[i]} active={status === 'idle' && i === code.length} status={status} delay={delayFor(i)} width={boxWidth} x={boxX(i)} rowWidth={rowWidth} sweep={sweep} pal={c} />
562 );
563
564 return (
565 <View style={[styles.screen, { backgroundColor: c.bg }]}>
566 <Backdrop width={width} top={insets.top} cy={insets.top + 52 + artTop + ART_H / 2} />
567
568 <View style={[styles.body, { paddingTop: insets.top + 8 }]}>
569 {/* Top bar */}
570 <Animated.View entering={enterAt(0)} style={styles.topBar}>
571 <BackButton pal={c} />
572 </Animated.View>
573
574 <View style={styles.main}>
575 <Animated.View entering={enterAt(1)} onLayout={(e: LayoutChangeEvent) => setArtTop(e.nativeEvent.layout.y)}>
576 <Illustration verified={verified} />
577 </Animated.View>
578
579 {/* Headline and the number the code went to; both swap once the code is accepted */}
580 <Animated.View entering={enterAt(2)} style={styles.heading}>
581 <View style={styles.titleSlot}>
582 <Layer on={!verified} delay={verified ? SUCCESS_BEAT : 0}>
583 <Text role="heading" style={[styles.title, { color: c.fg }]}>
584 Enter the code
585 </Text>
586 </Layer>
587 <Layer on={verified} delay={verified ? SUCCESS_BEAT : 0}>
588 <Text role="heading" style={[styles.title, { color: c.fg }]}>
589 Verified
590 </Text>
591 </Layer>
592 </View>
593 <View style={styles.subtitleSlot}>
594 <Layer on={!verified} delay={verified ? SUCCESS_BEAT + 60 : 0}>
595 <Text numberOfLines={1} style={[styles.subtitle, { color: c.muted }]}>
596 Sent to <Text style={[styles.strong, { color: c.fg }, TABULAR]}>{PHONE_MASKED}</Text>
597 {' '}
598 <Text role="link" aria-label="Change phone number" onPress={() => {}} style={[styles.strong, { color: c.link }]}>
599 Change
600 </Text>
601 </Text>
602 </Layer>
603 <Layer on={verified} delay={verified ? SUCCESS_BEAT + 60 : 0}>
604 <Text numberOfLines={1} style={[styles.subtitle, { color: c.muted }]}>
605 Your number is confirmed.
606 </Text>
607 </Layer>
608 </View>
609 </Animated.View>
610
611 {/* Code: the input sits invisibly over the boxes, so a tap focuses it and a paste or SMS autofill lands in it */}
612 <Animated.View entering={enterAt(3)} style={styles.codeSlot}>
613 <Animated.View style={[styles.code, { width: rowWidth }, rowStyle]}>
614 <View aria-hidden style={styles.row}>
615 <View style={styles.boxGroup}>{[0, 1, 2].map(box)}</View>
616 <View style={styles.dashSlot}>
617 <View style={[styles.dash, { backgroundColor: c.faint }]} />
618 </View>
619 <View style={styles.boxGroup}>{[3, 4, 5].map(box)}</View>
620 </View>
621 <TextInput
622 ref={inputRef}
623 value={code}
624 onChangeText={enter}
625 editable={!busy}
626 keyboardType="number-pad"
627 inputMode="numeric"
628 autoComplete="one-time-code"
629 textContentType="oneTimeCode"
630 maxLength={CODE_LENGTH}
631 selection={{ start: code.length, end: code.length }}
632 caretHidden
633 aria-label="Verification code"
634 aria-invalid={failed}
635 style={[StyleSheet.absoluteFill, styles.hiddenInput, NO_OUTLINE]}
636 />
637 </Animated.View>
638 </Animated.View>
639
640 {/* One line that reports on the code: checking, wrong, or a fresh one on its way */}
641 <View aria-live="polite" style={styles.status}>
642 {status === 'checking' ? (
643 <Animated.View key="checking" entering={FadeIn.duration(160)} style={styles.statusRowWide}>
644 <Spinner color={c.link} track={c.border} />
645 <Text style={[styles.quiet, { color: c.muted }]}>Checking code</Text>
646 </Animated.View>
647 ) : failed ? (
648 <Animated.View key="error" entering={FadeInDown.duration(200)} role="alert" style={styles.statusRow}>
649 <CircleAlert size={15} color={c.error} strokeWidth={2.4} />
650 <Text style={[styles.statusText, { color: c.error }]}>That code didn't match. Try again.</Text>
651 </Animated.View>
652 ) : notice && !verified ? (
653 <Animated.View key={notice} entering={FadeInDown.duration(200)} style={styles.statusRow}>
654 {notice === 'sent' ? <CircleCheck size={15} color={c.ok} strokeWidth={2.4} /> : <PhoneCall size={14} color={c.link} strokeWidth={2.4} />}
655 <Text style={[styles.statusText, { color: notice === 'sent' ? c.ok : c.link }]}>{notice === 'sent' ? 'New code sent' : 'Calling you with the code'}</Text>
656 </Animated.View>
657 ) : null}
658 </View>
659
660 {/* Resend */}
661 <Animated.View entering={enterAt(4)} style={styles.resendSlot}>
662 <Animated.View aria-hidden={verified} style={[styles.resend, { pointerEvents: verified ? 'none' : 'auto' }, resendStyle]}>
663 <View style={styles.resendLine}>
664 {secondsLeft > 0 ? (
665 <Animated.View key="wait" entering={FadeIn.duration(200)} style={styles.statusRowWide}>
666 <CountdownRing left={drain} color={c.link} track={c.border} />
667 <Text style={[styles.resendWait, { color: c.muted }]}>
668 Resend code in <Text style={[styles.strong, { color: c.fg }, TABULAR]}>{timer}</Text>
669 </Text>
670 </Animated.View>
671 ) : (
672 <Animated.View key="ready" entering={FadeInDown.duration(220)}>
673 <Pressable role="button" aria-label="Resend code" onPress={resend} hitSlop={10} style={({ pressed }) => [styles.resendButton, { opacity: pressed ? 0.6 : 1 }]}>
674 <RotateCw size={15} color={c.link} strokeWidth={2.6} />
675 <Text style={[styles.resendLabel, { color: c.link }]}>Resend code</Text>
676 </Pressable>
677 </Animated.View>
678 )}
679 </View>
680 <Pressable role="button" aria-label="Call me instead" onPress={() => !busy && flash('calling')} hitSlop={6} style={({ pressed }) => [styles.resendLine, { opacity: pressed ? 0.6 : 1 }]}>
681 <Text style={[styles.quiet, { color: c.muted }]}>Call me instead</Text>
682 </Pressable>
683 </Animated.View>
684 </Animated.View>
685 </View>
686 </View>
687
688 {/* Number pad: drives the same code as the hidden input, and clears the home indicator */}
689 <Animated.View entering={FadeIn.delay(300).duration(420)} style={[styles.padSlot, { paddingBottom: insets.bottom + 8 }]}>
690 <Animated.View style={[styles.pad, { pointerEvents: busy ? 'none' : 'auto' }, padStyle]}>
691 {PAD.map((row) => (
692 <View key={row[0]} style={styles.padRow}>
693 {row.map((k) => (
694 <PadKey key={k} value={k} height={keyHeight} onPress={() => press(k)} onLongPress={k === 'del' ? () => enter('') : undefined} pal={c} />
695 ))}
696 </View>
697 ))}
698 </Animated.View>
699 </Animated.View>
700 </View>
701 );
702}
703
704// ─── Styles ─────────────────────────────────────────────────────────────────
705
706const styles = StyleSheet.create({
707 screen: { flex: 1, overflow: 'hidden' },
708 fill: { flex: 1 },
709 center: { alignItems: 'center', justifyContent: 'center' },
710 row: { flexDirection: 'row', alignItems: 'center' },
711 body: { flex: 1, paddingHorizontal: 24 },
712 topBar: { height: 44, justifyContent: 'center' },
713 main: { flex: 1, alignItems: 'center', justifyContent: 'center' },
714 backPress: { alignSelf: 'flex-start' },
715 back: { width: 40, height: 40, borderRadius: 20, borderWidth: 1, alignItems: 'center', justifyContent: 'center' },
716 backIcon: { marginLeft: -2 },
717
718 // Background
719 backdrop: { position: 'absolute', top: 0, left: 0, right: 0, overflow: 'hidden', pointerEvents: 'none' },
720 rings: { position: 'absolute', top: 0, left: 0 },
721 veil: { position: 'absolute', left: 0, right: 0, bottom: 0, height: 170 },
722
723 // Illustration
724 art: { width: ART_W, height: ART_H },
725 artCanvas: { width: 96, height: 90, transformOrigin: 'left top', transform: [{ scale: ART_SCALE }] },
726 phone: { position: 'absolute', left: 6, top: 14, width: 46, height: 74, borderRadius: 13, transform: [{ rotate: '-8deg' }], boxShadow: `0px 12px 24px ${tint(ACCENT, 0.34)}` },
727 phoneFace: { flex: 1, borderRadius: 13, borderTopWidth: 1, borderTopColor: tint(ON_ACCENT, 0.45), alignItems: 'center' },
728 phoneSpeaker: { marginTop: 6, width: 14, height: 3.5, borderRadius: 2, backgroundColor: tint(ON_ACCENT, 0.6) },
729 phoneLine: { marginTop: 6, width: 26, height: 4, borderRadius: 2, backgroundColor: tint(ON_ACCENT, 0.24) },
730 phoneLineFirst: { marginTop: 17, backgroundColor: tint(ON_ACCENT, 0.42) },
731 phoneLineShort: { width: 16, alignSelf: 'flex-start', marginLeft: 10 },
732 bubble: {
733 position: 'absolute',
734 left: 40,
735 top: 0,
736 width: 56,
737 height: 38,
738 borderRadius: 19,
739 borderBottomLeftRadius: 6,
740 borderWidth: 1,
741 alignItems: 'center',
742 justifyContent: 'center',
743 transformOrigin: 'left bottom',
744 },
745 typing: { flexDirection: 'row', gap: 5 },
746 typingDot: { width: 6, height: 6, borderRadius: 3 },
747
748 // Heading
749 heading: { marginTop: 14, alignSelf: 'stretch' },
750 titleSlot: { height: 38 },
751 title: { fontSize: 30, lineHeight: 36, fontWeight: '700', letterSpacing: -0.8 },
752 subtitleSlot: { height: 24, marginTop: 4 },
753 subtitle: { fontSize: 15.5, lineHeight: 22 },
754 strong: { fontWeight: '600' },
755
756 // Code boxes
757 codeSlot: { marginTop: 24 },
758 code: { height: BOX_H },
759 boxGroup: { flexDirection: 'row', gap: BOX_GAP },
760 dashSlot: { width: DASH_W, alignItems: 'center' },
761 dash: { width: 10, height: 3, borderRadius: 2 },
762 hiddenInput: { opacity: 0, fontSize: 16, color: 'transparent' },
763 box: { height: BOX_H, alignItems: 'center', justifyContent: 'center' },
764 boxLayer: { borderRadius: BOX_RADIUS, borderWidth: 1.5 },
765 boxClip: { borderRadius: BOX_RADIUS, overflow: 'hidden' },
766 shimmer: { width: SHIMMER_W, height: '100%' },
767 boxFocus: { borderWidth: 2, borderColor: ACCENT },
768 digit: { fontSize: 27, lineHeight: 34, fontWeight: '600' },
769 caret: { position: 'absolute', width: 2.5, height: 26, borderRadius: 2, backgroundColor: ACCENT },
770
771 // Status and resend
772 status: { height: 20, marginTop: 10, justifyContent: 'center' },
773 statusRow: { flexDirection: 'row', alignItems: 'center', gap: 6 },
774 statusRowWide: { flexDirection: 'row', alignItems: 'center', gap: 8 },
775 statusText: { fontSize: 14, fontWeight: '600' },
776 quiet: { fontSize: 14, fontWeight: '500' },
777 spinner: { width: 15, height: 15, borderRadius: 8, borderWidth: 2 },
778 resendSlot: { marginTop: 6 },
779 resend: { alignItems: 'center' },
780 resendLine: { height: 30, justifyContent: 'center' },
781 resendWait: { fontSize: 15 },
782 resendButton: { flexDirection: 'row', alignItems: 'center', gap: 7 },
783 resendLabel: { fontSize: 15, fontWeight: '600' },
784 countdownRing: { width: 18, height: 18, transform: [{ scaleX: -1 }, { rotate: '-90deg' }] },
785
786 // Number pad
787 padSlot: { paddingHorizontal: 24 },
788 pad: { alignSelf: 'center', width: '100%', maxWidth: 392 },
789 padRow: { flexDirection: 'row' },
790 padKey: { flex: 1, alignItems: 'center', justifyContent: 'center' },
791 padGlow: { position: 'absolute', pointerEvents: 'none' },
792 padPaste: { fontSize: 16, fontWeight: '600' },
793 padDigit: { fontSize: 28, fontWeight: '500' },
794});

More screens like this.

All Authentication