屏幕
配色方案
明暗
圆角
颜色
所有状态
- 何时出现
- 行为规则
把这 2 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// A one-time code entered in a single native text field, with segmented or single-box styling.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState, type ComponentRef, type Ref } from 'react';
import { AccessibilityInfo, Animated, Platform, StyleSheet, Text, TextInput, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type OtpInputVariant = 'segmented' | 'single';
export type OtpInputProps = {
/** Digits typed so far. Keep it in state and pass it back, like a TextInput. */
value: string;
/** Called with the new digits on every edit. Non-digits are already removed. */
onChangeText: (value: string) => void;
/** Called once each time the full code is entered. */
onFilled?: (code: string) => void;
/** Number of digits. */
length?: number;
/** Show each digit in its own cell or all digits inside one outline. */
variant?: OtpInputVariant;
/** Red outline and a shake. Clear it when the user edits the code. */
error?: boolean;
/** Disable editing, for example while the code is checked. */
disabled?: boolean;
/** Focus the field and bring up the number pad when the screen opens. */
autoFocus?: boolean;
/** What screen readers announce for the field. */
accessibilityLabel?: string;
/** The hidden field, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function OtpInput({
value, onChangeText, onFilled, length = 6, variant = 'segmented', error = false, disabled = false, autoFocus = false, accessibilityLabel, ref,
}: OtpInputProps) {
const [focused, setFocused] = useState(false);
const filled = useRef<string | null>(null);
useEffect(() => {
// A controlled form can clear the input after a submission and then receive the same code again.
if (value.length < length) filled.current = null;
}, [value, length]);
function handleChange(text: string) {
let digits = text.replace(/\D/g, '');
if (digits.length > length) {
// One more key on a full code is ignored; a paste replaces the whole code.
digits = digits.length === value.length + 1 ? value : digits.slice(-length);
}
if (digits === value) return;
onChangeText(digits);
if (digits.length === length && filled.current !== digits) {
filled.current = digits;
onFilled?.(digits);
}
if (digits.length < length) filled.current = null;
}
return (
<View style={styles.root}>
<View aria-hidden={true} importantForAccessibility="no-hide-descendants">
<OtpCells value={value} length={length} variant={variant} focused={focused && !disabled} error={error} disabled={disabled} />
</View>
<TextInput
ref={ref}
value={value}
onChangeText={handleChange}
keyboardType="number-pad"
inputMode="numeric"
textContentType="oneTimeCode"
autoComplete={Platform.OS === 'android' ? 'sms-otp' : 'one-time-code'}
autoFocus={autoFocus}
editable={!disabled}
caretHidden
contextMenuHidden={false}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
accessibilityLabel={accessibilityLabel ?? `One-time code, ${length} digits`}
style={styles.input}
/>
</View>
);
}
export type OtpCellsProps = {
value: string;
length?: number;
variant?: OtpInputVariant;
focused?: boolean;
error?: boolean;
disabled?: boolean;
};
/** The read-only face used by OtpInput and frozen previews. */
export function OtpCells({ value, length = 6, variant = 'segmented', focused = false, error = false, disabled = false }: OtpCellsProps) {
const shake = useRef(new Animated.Value(0)).current;
const still = useReduceMotion();
useEffect(() => {
if (!error || still) return;
shake.setValue(0);
const animation = Animated.sequence(
[-9, 8, -6, 4, -2, 0].map((toValue) => Animated.timing(shake, { toValue, duration: 70, useNativeDriver: NATIVE_DRIVER })),
);
animation.start();
return () => {
animation.stop();
shake.setValue(0);
};
}, [error, shake, still]);
const active = focused && !disabled && value.length < length ? value.length : -1;
const motion = { transform: [{ translateX: shake }] };
if (variant === 'single') {
return (
<Animated.View
pointerEvents="none"
style={[
styles.box, styles.single,
disabled && styles.cellDisabled,
focused && !disabled && styles.cellActive,
error && styles.cellError,
motion,
]}
>
<Text style={[styles.digit, styles.singleDigits, disabled && styles.digitDisabled]}>{value.slice(0, length)}</Text>
{active >= 0 && <Caret />}
</Animated.View>
);
}
return (
<Animated.View style={[styles.row, motion]} pointerEvents="none">
{Array.from({ length }, (_, i) => {
const digit = value[i] ?? '';
return (
<View
key={i}
style={[
styles.box, styles.cell,
disabled && styles.cellDisabled,
i === active && styles.cellActive,
error && styles.cellError,
]}
>
{i === active ? <Caret /> : <Text style={[styles.digit, disabled && styles.digitDisabled]}>{digit}</Text>}
</View>
);
})}
</Animated.View>
);
}
/** True when the user asked the system for less motion: no shake, and the caret stays solid. */
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
function Caret() {
const opacity = useRef(new Animated.Value(1)).current;
const still = useReduceMotion();
useEffect(() => {
if (still) return;
const blink = Animated.loop(
Animated.sequence([
Animated.delay(530),
Animated.timing(opacity, { toValue: 0, duration: 0, useNativeDriver: NATIVE_DRIVER }),
Animated.delay(530),
Animated.timing(opacity, { toValue: 1, duration: 0, useNativeDriver: NATIVE_DRIVER }),
]),
);
blink.start();
return () => {
blink.stop();
opacity.setValue(1);
};
}, [opacity, still]);
return <Animated.View style={[styles.caret, { opacity }]} />;
}
const styles = StyleSheet.create({
root: { position: 'relative' },
row: { flexDirection: 'row', gap: 8 },
box: {
height: 56,
alignItems: 'center',
justifyContent: 'center',
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
cell: { flex: 1 },
single: { flexDirection: 'row', justifyContent: 'flex-start', paddingHorizontal: 16 },
singleDigits: { letterSpacing: 4 },
cellActive: { borderWidth: 2, borderColor: colors.primary },
cellError: { borderWidth: 2, borderColor: colors.error },
cellDisabled: { borderWidth: 0, backgroundColor: colors.surfaceVariant },
digit: { fontSize: 24, fontWeight: '600', color: colors.onSurface, fontVariant: ['tabular-nums'] },
digitDisabled: { color: colors.onSurfaceVariant },
caret: { width: 2, height: 28, borderRadius: 1, backgroundColor: colors.primary },
// Covers the cells so a tap anywhere on them focuses the field; invisible but still reachable by screen readers.
input: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, opacity: 0, color: 'transparent' },
});
// A one-time code entered in a single native text field, with segmented or single-box styling.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState, type ComponentRef, type Ref } from 'react';
import { AccessibilityInfo, Animated, Platform, StyleSheet, Text, TextInput, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type OtpInputVariant = 'segmented' | 'single';
export type OtpInputProps = {
/** Digits typed so far. Keep it in state and pass it back, like a TextInput. */
value: string;
/** Called with the new digits on every edit. Non-digits are already removed. */
onChangeText: (value: string) => void;
/** Called once each time the full code is entered. */
onFilled?: (code: string) => void;
/** Number of digits. */
length?: number;
/** Show each digit in its own cell or all digits inside one outline. */
variant?: OtpInputVariant;
/** Red outline and a shake. Clear it when the user edits the code. */
error?: boolean;
/** Disable editing, for example while the code is checked. */
disabled?: boolean;
/** Focus the field and bring up the number pad when the screen opens. */
autoFocus?: boolean;
/** What screen readers announce for the field. */
accessibilityLabel?: string;
/** The hidden field, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function OtpInput({
value, onChangeText, onFilled, length = 6, variant = 'segmented', error = false, disabled = false, autoFocus = false, accessibilityLabel, ref,
}: OtpInputProps) {
const [focused, setFocused] = useState(false);
const filled = useRef<string | null>(null);
useEffect(() => {
// A controlled form can clear the input after a submission and then receive the same code again.
if (value.length < length) filled.current = null;
}, [value, length]);
function handleChange(text: string) {
let digits = text.replace(/\D/g, '');
if (digits.length > length) {
// One more key on a full code is ignored; a paste replaces the whole code.
digits = digits.length === value.length + 1 ? value : digits.slice(-length);
}
if (digits === value) return;
onChangeText(digits);
if (digits.length === length && filled.current !== digits) {
filled.current = digits;
onFilled?.(digits);
}
if (digits.length < length) filled.current = null;
}
return (
<View style={styles.root}>
<View aria-hidden={true} importantForAccessibility="no-hide-descendants">
<OtpCells value={value} length={length} variant={variant} focused={focused && !disabled} error={error} disabled={disabled} />
</View>
<TextInput
ref={ref}
value={value}
onChangeText={handleChange}
keyboardType="number-pad"
inputMode="numeric"
textContentType="oneTimeCode"
autoComplete={Platform.OS === 'android' ? 'sms-otp' : 'one-time-code'}
autoFocus={autoFocus}
editable={!disabled}
caretHidden
contextMenuHidden={false}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
accessibilityLabel={accessibilityLabel ?? `One-time code, ${length} digits`}
style={styles.input}
/>
</View>
);
}
export type OtpCellsProps = {
value: string;
length?: number;
variant?: OtpInputVariant;
focused?: boolean;
error?: boolean;
disabled?: boolean;
};
/** The read-only face used by OtpInput and frozen previews. */
export function OtpCells({ value, length = 6, variant = 'segmented', focused = false, error = false, disabled = false }: OtpCellsProps) {
const shake = useRef(new Animated.Value(0)).current;
const still = useReduceMotion();
useEffect(() => {
if (!error || still) return;
shake.setValue(0);
const animation = Animated.sequence(
[-9, 8, -6, 4, -2, 0].map((toValue) => Animated.timing(shake, { toValue, duration: 70, useNativeDriver: NATIVE_DRIVER })),
);
animation.start();
return () => {
animation.stop();
shake.setValue(0);
};
}, [error, shake, still]);
const active = focused && !disabled && value.length < length ? value.length : -1;
const motion = { transform: [{ translateX: shake }] };
if (variant === 'single') {
return (
<Animated.View
pointerEvents="none"
style={[
styles.box, styles.single,
disabled && styles.cellDisabled,
focused && !disabled && styles.cellActive,
error && styles.cellError,
motion,
]}
>
<Text style={[styles.digit, styles.singleDigits, disabled && styles.digitDisabled]}>{value.slice(0, length)}</Text>
{active >= 0 && <Caret />}
</Animated.View>
);
}
return (
<Animated.View style={[styles.row, motion]} pointerEvents="none">
{Array.from({ length }, (_, i) => {
const digit = value[i] ?? '';
return (
<View
key={i}
style={[
styles.box, styles.cell,
disabled && styles.cellDisabled,
i === active && styles.cellActive,
error && styles.cellError,
]}
>
{i === active ? <Caret /> : <Text style={[styles.digit, disabled && styles.digitDisabled]}>{digit}</Text>}
</View>
);
})}
</Animated.View>
);
}
/** True when the user asked the system for less motion: no shake, and the caret stays solid. */
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
function Caret() {
const opacity = useRef(new Animated.Value(1)).current;
const still = useReduceMotion();
useEffect(() => {
if (still) return;
const blink = Animated.loop(
Animated.sequence([
Animated.delay(530),
Animated.timing(opacity, { toValue: 0, duration: 0, useNativeDriver: NATIVE_DRIVER }),
Animated.delay(530),
Animated.timing(opacity, { toValue: 1, duration: 0, useNativeDriver: NATIVE_DRIVER }),
]),
);
blink.start();
return () => {
blink.stop();
opacity.setValue(1);
};
}, [opacity, still]);
return <Animated.View style={[styles.caret, { opacity }]} />;
}
const styles = StyleSheet.create({
root: { position: 'relative' },
row: { flexDirection: 'row', gap: 8 },
box: {
height: 56,
alignItems: 'center',
justifyContent: 'center',
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
cell: { flex: 1 },
single: { flexDirection: 'row', justifyContent: 'flex-start', paddingHorizontal: 16 },
singleDigits: { letterSpacing: 4 },
cellActive: { borderWidth: 2, borderColor: colors.primary },
cellError: { borderWidth: 2, borderColor: colors.error },
cellDisabled: { borderWidth: 0, backgroundColor: colors.surfaceVariant },
digit: { fontSize: 24, fontWeight: '600', color: colors.onSurface, fontVariant: ['tabular-nums'] },
digitDisabled: { color: colors.onSurfaceVariant },
caret: { width: 2, height: 28, borderRadius: 1, backgroundColor: colors.primary },
// Covers the cells so a tap anywhere on them focuses the field; invisible but still reachable by screen readers.
input: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, opacity: 0, color: 'transparent' },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
用法
import { useState } from 'react';
import { OtpInput } from '@/components/mobilens/OtpInput';
export function VerifyCode({ verify }: { verify: (code: string) => Promise<boolean> }) {
const [code, setCode] = useState('');
const [wrong, setWrong] = useState(false);
const [checking, setChecking] = useState(false);
return (
<OtpInput
variant="segmented"
value={code}
autoFocus
error={wrong}
disabled={checking}
onChangeText={(next) => {
setCode(next);
setWrong(false);
}}
onFilled={async (full) => {
setChecking(true);
setWrong(!(await verify(full)));
setChecking(false);
}}
/>
);
}
import { useState } from 'react';
import { OtpInput } from '@/components/mobilens/OtpInput';
export function VerifyCode({ verify }: { verify: (code: string) => Promise<boolean> }) {
const [code, setCode] = useState('');
const [wrong, setWrong] = useState(false);
const [checking, setChecking] = useState(false);
return (
<OtpInput
variant="segmented"
value={code}
autoFocus
error={wrong}
disabled={checking}
onChangeText={(next) => {
setCode(next);
setWrong(false);
}}
onFilled={async (full) => {
setChecking(true);
setWrong(!(await verify(full)));
setChecking(false);
}}
/>
);
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| value | string | – | Digits typed so far. Keep it in state and pass it back, like a TextInput. |
| onChangeText | (value: string) => void | – | Called with the new digits on every edit. Non-digits are already removed. |
| onFilled? | (code: string) => void | – | Called once each time the full code is entered. |
| length? | number | 6 | Number of digits. |
| variant? | OtpInputVariant | 'segmented' | Show each digit in its own cell or all digits inside one outline. |
| error? | boolean | false | Red outline and a shake. Clear it when the user edits the code. |
| disabled? | boolean | false | Disable editing, for example while the code is checked. |
| autoFocus? | boolean | false | Focus the field and bring up the number pad when the screen opens. |
| accessibilityLabel? | string | – | What screen readers announce for the field. |
| ref? | Ref<ComponentRef<typeof TextInput>> | – | The hidden field, to focus() or blur() it. |
用在这些流程里
Add the "OTP input" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them. FILES Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths. --- components/mobilens/theme.ts --- // Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app. export const colors = { background: '#fafafa', surface: '#ffffff', surfaceVariant: '#f4f4f5', onBackground: '#18181b', onSurface: '#18181b', onSurfaceVariant: '#6b6b74', outline: '#8a8a93', outlineVariant: '#e4e4e7', error: '#ba1a1a', success: '#296b2a', warning: '#b45309', shadow: '#000000', scrim: 'rgba(0,0,0,0.32)', primary: '#006c50', onPrimary: '#ffffff', primaryContainer: '#82f8cb', onPrimaryContainer: '#002116', secondary: '#3e6374', onSecondary: '#ffffff', secondaryContainer: '#d8dfe2', onSecondaryContainer: '#1c2d34', tertiary: '#1f6862', onTertiary: '#ffffff', tertiaryContainer: '#d3e0df', onTertiaryContainer: '#0e2f2c', onError: '#ffffff', onSuccess: '#ffffff', onWarning: '#ffffff', } as const; export const radius = { sm: 6, md: 12, lg: 20, } as const; --- end of theme.ts --- --- components/mobilens/OtpInput.tsx --- // A one-time code entered in a single native text field, with segmented or single-box styling. // Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme. import { useEffect, useRef, useState, type ComponentRef, type Ref } from 'react'; import { AccessibilityInfo, Animated, Platform, StyleSheet, Text, TextInput, View } from 'react-native'; import { colors, radius } from './theme'; const NATIVE_DRIVER = Platform.OS !== 'web'; export type OtpInputVariant = 'segmented' | 'single'; export type OtpInputProps = { /** Digits typed so far. Keep it in state and pass it back, like a TextInput. */ value: string; /** Called with the new digits on every edit. Non-digits are already removed. */ onChangeText: (value: string) => void; /** Called once each time the full code is entered. */ onFilled?: (code: string) => void; /** Number of digits. */ length?: number; /** Show each digit in its own cell or all digits inside one outline. */ variant?: OtpInputVariant; /** Red outline and a shake. Clear it when the user edits the code. */ error?: boolean; /** Disable editing, for example while the code is checked. */ disabled?: boolean; /** Focus the field and bring up the number pad when the screen opens. */ autoFocus?: boolean; /** What screen readers announce for the field. */ accessibilityLabel?: string; /** The hidden field, to focus() or blur() it. */ ref?: Ref<ComponentRef<typeof TextInput>>; }; export function OtpInput({ value, onChangeText, onFilled, length = 6, variant = 'segmented', error = false, disabled = false, autoFocus = false, accessibilityLabel, ref, }: OtpInputProps) { const [focused, setFocused] = useState(false); const filled = useRef<string | null>(null); useEffect(() => { // A controlled form can clear the input after a submission and then receive the same code again. if (value.length < length) filled.current = null; }, [value, length]); function handleChange(text: string) { let digits = text.replace(/\D/g, ''); if (digits.length > length) { // One more key on a full code is ignored; a paste replaces the whole code. digits = digits.length === value.length + 1 ? value : digits.slice(-length); } if (digits === value) return; onChangeText(digits); if (digits.length === length && filled.current !== digits) { filled.current = digits; onFilled?.(digits); } if (digits.length < length) filled.current = null; } return ( <View style={styles.root}> <View aria-hidden={true} importantForAccessibility="no-hide-descendants"> <OtpCells value={value} length={length} variant={variant} focused={focused && !disabled} error={error} disabled={disabled} /> </View> <TextInput ref={ref} value={value} onChangeText={handleChange} keyboardType="number-pad" inputMode="numeric" textContentType="oneTimeCode" autoComplete={Platform.OS === 'android' ? 'sms-otp' : 'one-time-code'} autoFocus={autoFocus} editable={!disabled} caretHidden contextMenuHidden={false} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} accessibilityLabel={accessibilityLabel ?? `One-time code, ${length} digits`} style={styles.input} /> </View> ); } export type OtpCellsProps = { value: string; length?: number; variant?: OtpInputVariant; focused?: boolean; error?: boolean; disabled?: boolean; }; /** The read-only face used by OtpInput and frozen previews. */ export function OtpCells({ value, length = 6, variant = 'segmented', focused = false, error = false, disabled = false }: OtpCellsProps) { const shake = useRef(new Animated.Value(0)).current; const still = useReduceMotion(); useEffect(() => { if (!error || still) return; shake.setValue(0); const animation = Animated.sequence( [-9, 8, -6, 4, -2, 0].map((toValue) => Animated.timing(shake, { toValue, duration: 70, useNativeDriver: NATIVE_DRIVER })), ); animation.start(); return () => { animation.stop(); shake.setValue(0); }; }, [error, shake, still]); const active = focused && !disabled && value.length < length ? value.length : -1; const motion = { transform: [{ translateX: shake }] }; if (variant === 'single') { return ( <Animated.View pointerEvents="none" style={[ styles.box, styles.single, disabled && styles.cellDisabled, focused && !disabled && styles.cellActive, error && styles.cellError, motion, ]} > <Text style={[styles.digit, styles.singleDigits, disabled && styles.digitDisabled]}>{value.slice(0, length)}</Text> {active >= 0 && <Caret />} </Animated.View> ); } return ( <Animated.View style={[styles.row, motion]} pointerEvents="none"> {Array.from({ length }, (_, i) => { const digit = value[i] ?? ''; return ( <View key={i} style={[ styles.box, styles.cell, disabled && styles.cellDisabled, i === active && styles.cellActive, error && styles.cellError, ]} > {i === active ? <Caret /> : <Text style={[styles.digit, disabled && styles.digitDisabled]}>{digit}</Text>} </View> ); })} </Animated.View> ); } /** True when the user asked the system for less motion: no shake, and the caret stays solid. */ function useReduceMotion() { const [reduce, setReduce] = useState(false); useEffect(() => { let live = true; AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on)); const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce); return () => { live = false; sub.remove(); }; }, []); return reduce; } function Caret() { const opacity = useRef(new Animated.Value(1)).current; const still = useReduceMotion(); useEffect(() => { if (still) return; const blink = Animated.loop( Animated.sequence([ Animated.delay(530), Animated.timing(opacity, { toValue: 0, duration: 0, useNativeDriver: NATIVE_DRIVER }), Animated.delay(530), Animated.timing(opacity, { toValue: 1, duration: 0, useNativeDriver: NATIVE_DRIVER }), ]), ); blink.start(); return () => { blink.stop(); opacity.setValue(1); }; }, [opacity, still]); return <Animated.View style={[styles.caret, { opacity }]} />; } const styles = StyleSheet.create({ root: { position: 'relative' }, row: { flexDirection: 'row', gap: 8 }, box: { height: 56, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, borderWidth: 1, borderColor: colors.outline, backgroundColor: colors.surface, }, cell: { flex: 1 }, single: { flexDirection: 'row', justifyContent: 'flex-start', paddingHorizontal: 16 }, singleDigits: { letterSpacing: 4 }, cellActive: { borderWidth: 2, borderColor: colors.primary }, cellError: { borderWidth: 2, borderColor: colors.error }, cellDisabled: { borderWidth: 0, backgroundColor: colors.surfaceVariant }, digit: { fontSize: 24, fontWeight: '600', color: colors.onSurface, fontVariant: ['tabular-nums'] }, digitDisabled: { color: colors.onSurfaceVariant }, caret: { width: 2, height: 28, borderRadius: 1, backgroundColor: colors.primary }, // Covers the cells so a tap anywhere on them focuses the field; invisible but still reachable by screen readers. input: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, opacity: 0, color: 'transparent' }, }); --- end of OtpInput.tsx --- HOW TO USE IT import { useState } from 'react'; import { OtpInput } from '@/components/mobilens/OtpInput'; export function VerifyCode({ verify }: { verify: (code: string) => Promise<boolean> }) { const [code, setCode] = useState(''); const [wrong, setWrong] = useState(false); const [checking, setChecking] = useState(false); return ( <OtpInput variant="segmented" value={code} autoFocus error={wrong} disabled={checking} onChangeText={(next) => { setCode(next); setWrong(false); }} onFilled={async (full) => { setChecking(true); setWrong(!(await verify(full))); setChecking(false); }} /> ); } STATES: all 6 must work in the screen where you use it - Empty: when nothing typed and the field is not focused. The empty field has a neutral outline. - Focused: when the field has focus and nothing is typed. The caret appears at the first digit. The number pad comes up. - Typing: when some digits are typed. The caret follows the last digit entered. Delete removes the last digit. Pasting a complete code replaces the partial entry. Only digits are kept: letters and spaces are dropped. - Full: when all digits are entered. onFilled is called once with the code. Another digit is ignored. - Error: when the screen sets error, for a wrong code. The outline turns red and the field shakes once. The screen clears error when the user edits a digit. - Disabled: when the screen sets disabled, for example while it checks the code. The field turns grey and stops accepting edits. ACCESSIBILITY - Screen readers announce a single field, labelled "One-time code, 6 digits" by default. - The field is marked as a one-time code, so iOS offers the code from Messages and Android offers it from SMS. - With Reduce Motion on, the row does not shake and the caret does not blink. WHEN YOU FINISH List every state and rule above and say how you verified each one.