屏幕
配色方案
明暗
圆角
颜色
演示验证码 123456
这个流程的所有画面
邮箱这一步
验证码这一步
完成
- 何时出现
- 怎么离开
- 下一步
- 行为规则
把这 5 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// Email OTP sign-in: email, a six-digit code, resend, expiry and every failure on the way, as one screen.
// Connect it to your backend through `api`; the screen handles the states. Uses ./TextField, ./OtpInput, ./Button.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { OtpInput, type OtpInputVariant } from './OtpInput';
import { TextField } from './TextField';
import { colors, radius } from './theme';
export type SendCodeResult =
| { status: 'sent'; expiresInSeconds?: number; resendInSeconds?: number }
| { status: 'rate-limited'; retryInSeconds: number }
| { status: 'failed' }
| { status: 'offline' };
export type VerifyCodeResult =
| { status: 'ok' }
| { status: 'wrong'; attemptsLeft: number }
| { status: 'expired' }
| { status: 'locked'; retryInSeconds: number }
| { status: 'failed' }
| { status: 'offline' };
/** Your backend. A call that throws counts as offline; one that takes longer than timeoutMs counts as timed out. */
export type EmailOtpApi = {
sendCode: (email: string) => Promise<SendCodeResult>;
verifyCode: (email: string, code: string) => Promise<VerifyCodeResult>;
};
export type SignInStatus =
| 'idle' | 'sending' | 'limited' | 'failed' | 'offline' | 'timeout'
| 'sent' | 'verifying' | 'wrong' | 'check-failed' | 'expired' | 'locked' | 'done';
export type SignInState = {
status: SignInStatus;
email: string;
code: string;
/** Times are Date.now() values, so countdowns stay right after the app was in the background. */
resendAt?: number;
expiresAt?: number;
retryAt?: number;
attemptsLeft?: number;
};
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type EmailOtpSignInLabels = {
signedIn: string;
subtitle: string;
emailLabel: string;
emailPlaceholder: string;
tooManyCodes: string;
offline: string;
timeout: string;
failed: string;
tryAgain: string;
changeEmail: string;
useDifferentEmail: string;
checkEmail: string;
tooManyTries: string;
paused: string;
enterCode: string;
checking: string;
wrongCode: string;
checkFailed: string;
expired: string;
noCode: string;
deliveryHelp: string;
sendNewCode: string;
resendIn: string;
resend: string;
};
const defaultLabels: EmailOtpSignInLabels = {
signedIn: "You're signed in",
subtitle: "We'll email you a six-digit code.",
emailLabel: 'Email',
emailPlaceholder: 'name@example.com',
tooManyCodes: 'Too many codes requested. Try again in {seconds} s.',
offline: "You're offline. Check your connection and try again.",
timeout: 'This is taking longer than it should. Try again.',
failed: 'Something went wrong on our side. Try again in a moment.',
tryAgain: 'Try again',
changeEmail: '‹ Change email',
useDifferentEmail: 'Use a different email',
checkEmail: 'Check your email',
tooManyTries: 'Too many tries',
paused: 'For your security, sign-in for {email} is paused. Try again in {minutes} min.',
enterCode: 'Enter the code we sent to {email}.',
checking: 'Checking…',
wrongCode: "That code isn't right. {tries} left.",
checkFailed: "Couldn't check the code. Try again.",
expired: 'This code has expired.',
noCode: 'Didn’t get a code?',
deliveryHelp: 'Make sure {email} is correct. Check your spam or junk folder. If you resend the code, use the one in the newest email.',
sendNewCode: 'Send a new code',
resendIn: 'Resend code in {minutes}:{seconds}',
resend: 'Resend code',
};
/** Puts the values into the label. A {name} with no value is left as it is. */
function fill(template: string, values: Record<string, string | number>) {
return template.replace(/\{(\w+)\}/g, (match, key) => (key in values ? String(values[key]) : match));
}
export type EmailOtpSignInProps = {
/** Heading shown on the email entry step. */
title?: string;
/** Label of the button that requests the first code. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<EmailOtpSignInLabels>;
/** Display the verification code in separate cells or one outlined field. */
otpVariant?: OtpInputVariant;
/** sendCode and verifyCode, connected to your backend. */
api: EmailOtpApi;
/** Called once the code is accepted. Navigate into the app from here. */
onSignedIn: (email: string) => void;
/** How long to wait for the backend before showing the timeout state, in ms. */
timeoutMs?: number;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Where to start. Defaults to an empty email step; pass a saved state to resume, or any state in tests. */
initialState?: SignInState;
/** Called with every state the screen enters, for analytics or logging. */
onStateChange?: (state: SignInState) => void;
};
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const TIMEOUT = Symbol('timeout');
export function EmailOtpSignIn({
title = 'Sign in', primaryLabel = 'Send code', labels,
api, onSignedIn, otpVariant = 'segmented', timeoutMs = 15000, autoFocus = true, initialState = { status: 'idle', email: '', code: '' }, onStateChange,
}: EmailOtpSignInProps) {
const t = { ...defaultLabels, ...labels };
const [s, setS] = useState<SignInState>(initialState);
const now = useNow(!!(s.resendAt || s.expiresAt || s.retryAt));
const request = useRef(0);
const busy = useRef(false);
const changed = useRef(onStateChange);
changed.current = onStateChange;
useEffect(() => changed.current?.(s), [s]);
useEffect(() => () => { request.current++; }, []);
useEffect(() => {
if (s.status === 'locked' && s.retryAt !== undefined && now >= s.retryAt) {
setS({ status: 'idle', email: s.email, code: '' });
} else if (s.expiresAt !== undefined && now >= s.expiresAt && ['sent', 'wrong', 'check-failed'].includes(s.status)) {
setS((p) => ({ ...p, status: 'expired', code: '' }));
}
}, [now, s.email, s.expiresAt, s.retryAt, s.status]);
async function call<T>(work: () => Promise<T>): Promise<T | typeof TIMEOUT | 'threw'> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
work(),
new Promise<typeof TIMEOUT>((resolve) => { timer = setTimeout(() => resolve(TIMEOUT), timeoutMs); }),
]);
} catch {
return 'threw';
} finally {
clearTimeout(timer);
}
}
async function send() {
// A second tap while a request is in flight does nothing, even before the button shows it is busy.
if (busy.current || !EMAIL.test(s.email.trim())) return;
if (s.status === 'limited' && (s.retryAt ?? 0) > Date.now()) return;
if ((s.status === 'sent' || s.status === 'wrong') && (s.resendAt ?? 0) > Date.now()) return;
const email = s.email.trim();
const id = ++request.current;
busy.current = true;
setS({ status: 'sending', email, code: '' });
const r = await call(() => api.sendCode(email));
if (id !== request.current) return; // the user moved on
busy.current = false;
const at = (seconds: number) => Date.now() + seconds * 1000;
if (r === TIMEOUT) setS({ status: 'timeout', email, code: '' });
else if (r === 'threw' || r.status === 'offline') setS({ status: 'offline', email, code: '' });
else if (r.status === 'failed') setS({ status: 'failed', email, code: '' });
else if (r.status === 'rate-limited') setS({ status: 'limited', email, code: '', retryAt: at(r.retryInSeconds) });
else setS({ status: 'sent', email, code: '', resendAt: at(r.resendInSeconds ?? 30), expiresAt: at(r.expiresInSeconds ?? 600) });
}
async function verify(code: string) {
if (busy.current || !/^\d{6}$/.test(code)) return;
if (s.expiresAt !== undefined && Date.now() >= s.expiresAt) {
setS((p) => ({ ...p, status: 'expired', code: '' }));
return;
}
const id = ++request.current;
busy.current = true;
setS((p) => ({ ...p, status: 'verifying', code }));
const r = await call(() => api.verifyCode(s.email, code));
if (id !== request.current) return;
busy.current = false;
if (r === TIMEOUT || r === 'threw' || r.status === 'offline' || r.status === 'failed') setS((p) => ({ ...p, status: 'check-failed' }));
else if (r.status === 'ok') {
setS({ status: 'done', email: s.email, code: '' });
onSignedIn(s.email);
} else if (r.status === 'expired') setS((p) => ({ ...p, status: 'expired', code: '' }));
else if (r.status === 'locked' || r.attemptsLeft <= 0) {
setS((p) => ({ ...p, status: 'locked', code: '', retryAt: Date.now() + (r.status === 'locked' ? r.retryInSeconds : 900) * 1000 }));
} else setS((p) => ({ ...p, status: 'wrong', attemptsLeft: r.attemptsLeft }));
}
function changeEmail() {
request.current++;
busy.current = false;
setS({ status: 'idle', email: s.email, code: '' });
}
const left = (at?: number) => Math.max(0, Math.ceil(((at ?? 0) - now) / 1000));
const emailStep = ['idle', 'sending', 'limited', 'failed', 'offline', 'timeout'].includes(s.status);
return (
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.screen}>
{s.status === 'done' ? (
<View style={styles.done}>
<View style={styles.check}><Text style={styles.checkMark}>✓</Text></View>
<Text style={styles.title}>{t.signedIn}</Text>
<Text style={styles.sub}>{s.email}</Text>
</View>
) : emailStep ? (
<>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<Text style={styles.sub}>{t.subtitle}</Text>
<View style={styles.body}>
<TextField
label={t.emailLabel}
value={s.email}
onChangeText={(email) => setS((p) => ({ ...p, email, status: p.status === 'limited' ? 'limited' : 'idle' }))}
placeholder={t.emailPlaceholder}
disabled={s.status === 'sending'}
autoFocus={autoFocus}
error={s.status === 'limited' && left(s.retryAt) ? fill(t.tooManyCodes, { seconds: left(s.retryAt) }) : undefined}
inputProps={{
keyboardType: 'email-address', autoCapitalize: 'none', autoCorrect: false, autoComplete: 'email', textContentType: 'emailAddress',
returnKeyType: 'send', onSubmitEditing: send,
}}
/>
{s.status === 'offline' ? <Banner text={t.offline} /> : null}
{s.status === 'timeout' ? <Banner text={t.timeout} /> : null}
{s.status === 'failed' ? <Banner text={t.failed} /> : null}
</View>
<Button
title={['offline', 'timeout', 'failed'].includes(s.status) ? t.tryAgain : primaryLabel}
onPress={send}
loading={s.status === 'sending'}
disabled={!EMAIL.test(s.email.trim()) || (s.status === 'limited' && left(s.retryAt) > 0)}
style={styles.primary}
/>
</>
) : (
<ScrollView contentContainerStyle={styles.codeStep} keyboardShouldPersistTaps="handled">
<Pressable onPress={changeEmail} hitSlop={8} accessibilityRole="button" style={styles.back}>
<Text style={styles.link}>{t.changeEmail}</Text>
</Pressable>
<Text style={styles.title} accessibilityRole="header">{s.status === 'locked' ? t.tooManyTries : t.checkEmail}</Text>
<Text style={styles.sub}>
{s.status === 'locked'
? fill(t.paused, { email: s.email, minutes: Math.ceil(left(s.retryAt) / 60) })
: fill(t.enterCode, { email: s.email })}
</Text>
{s.status === 'locked' ? null : (
<View style={styles.body}>
<OtpInput
variant={otpVariant}
value={s.code}
onChangeText={(code) => setS((p) => ({ ...p, code, status: p.status === 'wrong' || p.status === 'check-failed' ? 'sent' : p.status }))}
onFilled={verify}
error={s.status === 'wrong'}
disabled={s.status === 'verifying' || s.status === 'expired'}
autoFocus={autoFocus && s.status !== 'expired'}
/>
<Text style={[styles.note, (s.status === 'wrong' || s.status === 'check-failed' || s.status === 'expired') && styles.noteError]} accessibilityLiveRegion="polite">
{s.status === 'verifying' ? t.checking
: s.status === 'wrong' ? fill(t.wrongCode, { tries: s.attemptsLeft ?? 0 })
: s.status === 'check-failed' ? t.checkFailed
: s.status === 'expired' ? t.expired
: ' '}
</Text>
<CodeDeliveryHelp email={s.email} labels={t} />
</View>
)}
{s.status === 'expired' ? <Button title={t.sendNewCode} onPress={send} style={styles.primary} />
: s.status === 'check-failed' ? <Button title={t.tryAgain} onPress={() => verify(s.code)} style={styles.primary} />
: s.status === 'locked' ? <Button title={t.useDifferentEmail} variant="secondary" onPress={() => setS({ status: 'idle', email: '', code: '' })} style={styles.primary} />
: left(s.resendAt) > 0 ? <Text style={[styles.resend, styles.primary]}>{fill(t.resendIn, { minutes: Math.floor(left(s.resendAt) / 60), seconds: String(left(s.resendAt) % 60).padStart(2, '0') })}</Text>
: <Button title={t.resend} variant="ghost" onPress={send} disabled={s.status === 'verifying'} style={styles.primary} />}
</ScrollView>
)}
</KeyboardAvoidingView>
);
}
function CodeDeliveryHelp({ email, labels }: { email: string; labels: EmailOtpSignInLabels }) {
const [expanded, setExpanded] = useState(false);
return (
<View>
<Pressable accessibilityRole="button" accessibilityState={{ expanded }} hitSlop={6}
onPress={() => setExpanded((open) => !open)} style={styles.helpButton}>
<Text style={styles.link}>{labels.noCode}</Text>
</Pressable>
{expanded && (
<Text style={styles.helpText}>{fill(labels.deliveryHelp, { email })}</Text>
)}
</View>
);
}
function Banner({ text }: { text: string }) {
return (
<View style={styles.banner} accessibilityLiveRegion="polite">
<Text style={styles.bannerText}>{text}</Text>
</View>
);
}
/** Date.now(), updated every second while something on screen counts down. */
function useNow(ticking: boolean) {
const [now, setNow] = useState(Date.now);
useEffect(() => {
if (!ticking) return;
setNow(Date.now());
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [ticking]);
return now;
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 32, paddingBottom: 16 },
codeStep: { flexGrow: 1 },
helpButton: { alignSelf: 'flex-start', paddingVertical: 4 },
helpText: { marginTop: 4, fontSize: 14, lineHeight: 20, color: colors.onSurfaceVariant },
back: { alignSelf: 'flex-start', marginBottom: 16 },
link: { fontSize: 16, fontWeight: '500', color: colors.primary },
title: { fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 8, fontSize: 16, lineHeight: 22, color: colors.onSurfaceVariant },
body: { marginTop: 24, gap: 12 },
note: { fontSize: 14, color: colors.onSurfaceVariant },
noteError: { color: colors.error },
banner: { padding: 12, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
bannerText: { fontSize: 14, lineHeight: 20, color: colors.onSurface },
primary: { marginTop: 'auto' },
resend: { textAlign: 'center', paddingVertical: 14, fontSize: 15, color: colors.onSurfaceVariant, fontVariant: ['tabular-nums'] },
done: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 4 },
check: { width: 64, height: 64, marginBottom: 16, borderRadius: 32, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.secondaryContainer },
checkMark: { fontSize: 30, fontWeight: '700', color: colors.onSecondaryContainer },
});
// Email OTP sign-in: email, a six-digit code, resend, expiry and every failure on the way, as one screen.
// Connect it to your backend through `api`; the screen handles the states. Uses ./TextField, ./OtpInput, ./Button.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { OtpInput, type OtpInputVariant } from './OtpInput';
import { TextField } from './TextField';
import { colors, radius } from './theme';
export type SendCodeResult =
| { status: 'sent'; expiresInSeconds?: number; resendInSeconds?: number }
| { status: 'rate-limited'; retryInSeconds: number }
| { status: 'failed' }
| { status: 'offline' };
export type VerifyCodeResult =
| { status: 'ok' }
| { status: 'wrong'; attemptsLeft: number }
| { status: 'expired' }
| { status: 'locked'; retryInSeconds: number }
| { status: 'failed' }
| { status: 'offline' };
/** Your backend. A call that throws counts as offline; one that takes longer than timeoutMs counts as timed out. */
export type EmailOtpApi = {
sendCode: (email: string) => Promise<SendCodeResult>;
verifyCode: (email: string, code: string) => Promise<VerifyCodeResult>;
};
export type SignInStatus =
| 'idle' | 'sending' | 'limited' | 'failed' | 'offline' | 'timeout'
| 'sent' | 'verifying' | 'wrong' | 'check-failed' | 'expired' | 'locked' | 'done';
export type SignInState = {
status: SignInStatus;
email: string;
code: string;
/** Times are Date.now() values, so countdowns stay right after the app was in the background. */
resendAt?: number;
expiresAt?: number;
retryAt?: number;
attemptsLeft?: number;
};
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type EmailOtpSignInLabels = {
signedIn: string;
subtitle: string;
emailLabel: string;
emailPlaceholder: string;
tooManyCodes: string;
offline: string;
timeout: string;
failed: string;
tryAgain: string;
changeEmail: string;
useDifferentEmail: string;
checkEmail: string;
tooManyTries: string;
paused: string;
enterCode: string;
checking: string;
wrongCode: string;
checkFailed: string;
expired: string;
noCode: string;
deliveryHelp: string;
sendNewCode: string;
resendIn: string;
resend: string;
};
const defaultLabels: EmailOtpSignInLabels = {
signedIn: "You're signed in",
subtitle: "We'll email you a six-digit code.",
emailLabel: 'Email',
emailPlaceholder: 'name@example.com',
tooManyCodes: 'Too many codes requested. Try again in {seconds} s.',
offline: "You're offline. Check your connection and try again.",
timeout: 'This is taking longer than it should. Try again.',
failed: 'Something went wrong on our side. Try again in a moment.',
tryAgain: 'Try again',
changeEmail: '‹ Change email',
useDifferentEmail: 'Use a different email',
checkEmail: 'Check your email',
tooManyTries: 'Too many tries',
paused: 'For your security, sign-in for {email} is paused. Try again in {minutes} min.',
enterCode: 'Enter the code we sent to {email}.',
checking: 'Checking…',
wrongCode: "That code isn't right. {tries} left.",
checkFailed: "Couldn't check the code. Try again.",
expired: 'This code has expired.',
noCode: 'Didn’t get a code?',
deliveryHelp: 'Make sure {email} is correct. Check your spam or junk folder. If you resend the code, use the one in the newest email.',
sendNewCode: 'Send a new code',
resendIn: 'Resend code in {minutes}:{seconds}',
resend: 'Resend code',
};
/** Puts the values into the label. A {name} with no value is left as it is. */
function fill(template: string, values: Record<string, string | number>) {
return template.replace(/\{(\w+)\}/g, (match, key) => (key in values ? String(values[key]) : match));
}
export type EmailOtpSignInProps = {
/** Heading shown on the email entry step. */
title?: string;
/** Label of the button that requests the first code. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<EmailOtpSignInLabels>;
/** Display the verification code in separate cells or one outlined field. */
otpVariant?: OtpInputVariant;
/** sendCode and verifyCode, connected to your backend. */
api: EmailOtpApi;
/** Called once the code is accepted. Navigate into the app from here. */
onSignedIn: (email: string) => void;
/** How long to wait for the backend before showing the timeout state, in ms. */
timeoutMs?: number;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Where to start. Defaults to an empty email step; pass a saved state to resume, or any state in tests. */
initialState?: SignInState;
/** Called with every state the screen enters, for analytics or logging. */
onStateChange?: (state: SignInState) => void;
};
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const TIMEOUT = Symbol('timeout');
export function EmailOtpSignIn({
title = 'Sign in', primaryLabel = 'Send code', labels,
api, onSignedIn, otpVariant = 'segmented', timeoutMs = 15000, autoFocus = true, initialState = { status: 'idle', email: '', code: '' }, onStateChange,
}: EmailOtpSignInProps) {
const t = { ...defaultLabels, ...labels };
const [s, setS] = useState<SignInState>(initialState);
const now = useNow(!!(s.resendAt || s.expiresAt || s.retryAt));
const request = useRef(0);
const busy = useRef(false);
const changed = useRef(onStateChange);
changed.current = onStateChange;
useEffect(() => changed.current?.(s), [s]);
useEffect(() => () => { request.current++; }, []);
useEffect(() => {
if (s.status === 'locked' && s.retryAt !== undefined && now >= s.retryAt) {
setS({ status: 'idle', email: s.email, code: '' });
} else if (s.expiresAt !== undefined && now >= s.expiresAt && ['sent', 'wrong', 'check-failed'].includes(s.status)) {
setS((p) => ({ ...p, status: 'expired', code: '' }));
}
}, [now, s.email, s.expiresAt, s.retryAt, s.status]);
async function call<T>(work: () => Promise<T>): Promise<T | typeof TIMEOUT | 'threw'> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
work(),
new Promise<typeof TIMEOUT>((resolve) => { timer = setTimeout(() => resolve(TIMEOUT), timeoutMs); }),
]);
} catch {
return 'threw';
} finally {
clearTimeout(timer);
}
}
async function send() {
// A second tap while a request is in flight does nothing, even before the button shows it is busy.
if (busy.current || !EMAIL.test(s.email.trim())) return;
if (s.status === 'limited' && (s.retryAt ?? 0) > Date.now()) return;
if ((s.status === 'sent' || s.status === 'wrong') && (s.resendAt ?? 0) > Date.now()) return;
const email = s.email.trim();
const id = ++request.current;
busy.current = true;
setS({ status: 'sending', email, code: '' });
const r = await call(() => api.sendCode(email));
if (id !== request.current) return; // the user moved on
busy.current = false;
const at = (seconds: number) => Date.now() + seconds * 1000;
if (r === TIMEOUT) setS({ status: 'timeout', email, code: '' });
else if (r === 'threw' || r.status === 'offline') setS({ status: 'offline', email, code: '' });
else if (r.status === 'failed') setS({ status: 'failed', email, code: '' });
else if (r.status === 'rate-limited') setS({ status: 'limited', email, code: '', retryAt: at(r.retryInSeconds) });
else setS({ status: 'sent', email, code: '', resendAt: at(r.resendInSeconds ?? 30), expiresAt: at(r.expiresInSeconds ?? 600) });
}
async function verify(code: string) {
if (busy.current || !/^\d{6}$/.test(code)) return;
if (s.expiresAt !== undefined && Date.now() >= s.expiresAt) {
setS((p) => ({ ...p, status: 'expired', code: '' }));
return;
}
const id = ++request.current;
busy.current = true;
setS((p) => ({ ...p, status: 'verifying', code }));
const r = await call(() => api.verifyCode(s.email, code));
if (id !== request.current) return;
busy.current = false;
if (r === TIMEOUT || r === 'threw' || r.status === 'offline' || r.status === 'failed') setS((p) => ({ ...p, status: 'check-failed' }));
else if (r.status === 'ok') {
setS({ status: 'done', email: s.email, code: '' });
onSignedIn(s.email);
} else if (r.status === 'expired') setS((p) => ({ ...p, status: 'expired', code: '' }));
else if (r.status === 'locked' || r.attemptsLeft <= 0) {
setS((p) => ({ ...p, status: 'locked', code: '', retryAt: Date.now() + (r.status === 'locked' ? r.retryInSeconds : 900) * 1000 }));
} else setS((p) => ({ ...p, status: 'wrong', attemptsLeft: r.attemptsLeft }));
}
function changeEmail() {
request.current++;
busy.current = false;
setS({ status: 'idle', email: s.email, code: '' });
}
const left = (at?: number) => Math.max(0, Math.ceil(((at ?? 0) - now) / 1000));
const emailStep = ['idle', 'sending', 'limited', 'failed', 'offline', 'timeout'].includes(s.status);
return (
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.screen}>
{s.status === 'done' ? (
<View style={styles.done}>
<View style={styles.check}><Text style={styles.checkMark}>✓</Text></View>
<Text style={styles.title}>{t.signedIn}</Text>
<Text style={styles.sub}>{s.email}</Text>
</View>
) : emailStep ? (
<>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<Text style={styles.sub}>{t.subtitle}</Text>
<View style={styles.body}>
<TextField
label={t.emailLabel}
value={s.email}
onChangeText={(email) => setS((p) => ({ ...p, email, status: p.status === 'limited' ? 'limited' : 'idle' }))}
placeholder={t.emailPlaceholder}
disabled={s.status === 'sending'}
autoFocus={autoFocus}
error={s.status === 'limited' && left(s.retryAt) ? fill(t.tooManyCodes, { seconds: left(s.retryAt) }) : undefined}
inputProps={{
keyboardType: 'email-address', autoCapitalize: 'none', autoCorrect: false, autoComplete: 'email', textContentType: 'emailAddress',
returnKeyType: 'send', onSubmitEditing: send,
}}
/>
{s.status === 'offline' ? <Banner text={t.offline} /> : null}
{s.status === 'timeout' ? <Banner text={t.timeout} /> : null}
{s.status === 'failed' ? <Banner text={t.failed} /> : null}
</View>
<Button
title={['offline', 'timeout', 'failed'].includes(s.status) ? t.tryAgain : primaryLabel}
onPress={send}
loading={s.status === 'sending'}
disabled={!EMAIL.test(s.email.trim()) || (s.status === 'limited' && left(s.retryAt) > 0)}
style={styles.primary}
/>
</>
) : (
<ScrollView contentContainerStyle={styles.codeStep} keyboardShouldPersistTaps="handled">
<Pressable onPress={changeEmail} hitSlop={8} accessibilityRole="button" style={styles.back}>
<Text style={styles.link}>{t.changeEmail}</Text>
</Pressable>
<Text style={styles.title} accessibilityRole="header">{s.status === 'locked' ? t.tooManyTries : t.checkEmail}</Text>
<Text style={styles.sub}>
{s.status === 'locked'
? fill(t.paused, { email: s.email, minutes: Math.ceil(left(s.retryAt) / 60) })
: fill(t.enterCode, { email: s.email })}
</Text>
{s.status === 'locked' ? null : (
<View style={styles.body}>
<OtpInput
variant={otpVariant}
value={s.code}
onChangeText={(code) => setS((p) => ({ ...p, code, status: p.status === 'wrong' || p.status === 'check-failed' ? 'sent' : p.status }))}
onFilled={verify}
error={s.status === 'wrong'}
disabled={s.status === 'verifying' || s.status === 'expired'}
autoFocus={autoFocus && s.status !== 'expired'}
/>
<Text style={[styles.note, (s.status === 'wrong' || s.status === 'check-failed' || s.status === 'expired') && styles.noteError]} accessibilityLiveRegion="polite">
{s.status === 'verifying' ? t.checking
: s.status === 'wrong' ? fill(t.wrongCode, { tries: s.attemptsLeft ?? 0 })
: s.status === 'check-failed' ? t.checkFailed
: s.status === 'expired' ? t.expired
: ' '}
</Text>
<CodeDeliveryHelp email={s.email} labels={t} />
</View>
)}
{s.status === 'expired' ? <Button title={t.sendNewCode} onPress={send} style={styles.primary} />
: s.status === 'check-failed' ? <Button title={t.tryAgain} onPress={() => verify(s.code)} style={styles.primary} />
: s.status === 'locked' ? <Button title={t.useDifferentEmail} variant="secondary" onPress={() => setS({ status: 'idle', email: '', code: '' })} style={styles.primary} />
: left(s.resendAt) > 0 ? <Text style={[styles.resend, styles.primary]}>{fill(t.resendIn, { minutes: Math.floor(left(s.resendAt) / 60), seconds: String(left(s.resendAt) % 60).padStart(2, '0') })}</Text>
: <Button title={t.resend} variant="ghost" onPress={send} disabled={s.status === 'verifying'} style={styles.primary} />}
</ScrollView>
)}
</KeyboardAvoidingView>
);
}
function CodeDeliveryHelp({ email, labels }: { email: string; labels: EmailOtpSignInLabels }) {
const [expanded, setExpanded] = useState(false);
return (
<View>
<Pressable accessibilityRole="button" accessibilityState={{ expanded }} hitSlop={6}
onPress={() => setExpanded((open) => !open)} style={styles.helpButton}>
<Text style={styles.link}>{labels.noCode}</Text>
</Pressable>
{expanded && (
<Text style={styles.helpText}>{fill(labels.deliveryHelp, { email })}</Text>
)}
</View>
);
}
function Banner({ text }: { text: string }) {
return (
<View style={styles.banner} accessibilityLiveRegion="polite">
<Text style={styles.bannerText}>{text}</Text>
</View>
);
}
/** Date.now(), updated every second while something on screen counts down. */
function useNow(ticking: boolean) {
const [now, setNow] = useState(Date.now);
useEffect(() => {
if (!ticking) return;
setNow(Date.now());
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [ticking]);
return now;
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 32, paddingBottom: 16 },
codeStep: { flexGrow: 1 },
helpButton: { alignSelf: 'flex-start', paddingVertical: 4 },
helpText: { marginTop: 4, fontSize: 14, lineHeight: 20, color: colors.onSurfaceVariant },
back: { alignSelf: 'flex-start', marginBottom: 16 },
link: { fontSize: 16, fontWeight: '500', color: colors.primary },
title: { fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 8, fontSize: 16, lineHeight: 22, color: colors.onSurfaceVariant },
body: { marginTop: 24, gap: 12 },
note: { fontSize: 14, color: colors.onSurfaceVariant },
noteError: { color: colors.error },
banner: { padding: 12, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
bannerText: { fontSize: 14, lineHeight: 20, color: colors.onSurface },
primary: { marginTop: 'auto' },
resend: { textAlign: 'center', paddingVertical: 14, fontSize: 15, color: colors.onSurfaceVariant, fontVariant: ['tabular-nums'] },
done: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 4 },
check: { width: 64, height: 64, marginBottom: 16, borderRadius: 32, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.secondaryContainer },
checkMark: { fontSize: 30, fontWeight: '700', color: colors.onSecondaryContainer },
});
// Text field: a label above, help or an error below, a character count, a clear button, and Show / Hide for passwords.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useImperativeHandle, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type TextFieldVariant = 'outlined' | 'underlined' | 'filled';
export type TextFieldProps = {
/** Shown above the field and announced by screen readers. */
label: string;
/** The text. Keep it in state and pass it back. */
value: string;
/** Called with the new text on every edit. */
onChangeText: (value: string) => void;
/** Draw an outline, a bottom line, or a tinted box around the input. */
variant?: TextFieldVariant;
/** Minimum height of the whole labelled field. Additional space is given to the input. */
minHeight?: number;
/** Grey hint inside the empty field. Not a replacement for the label. */
placeholder?: string;
/** One line of help under the field. Hidden while there is an error. */
helper?: string;
/** The error message. The field turns red while it is set; clear it when the user edits. */
error?: string;
/** Grey and read-only. */
disabled?: boolean;
/** The most characters allowed. Shows a count under the field. */
maxLength?: number;
/** Hides the text and adds a Show / Hide button. */
secureTextEntry?: boolean;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'>;
/** The TextInput, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function TextField({
label, value, onChangeText, variant = 'outlined', minHeight, placeholder, helper, error, disabled = false, maxLength, secureTextEntry = false, autoFocus = false, inputProps, ref, copyTestIDs,
}: TextFieldProps & Pick<FieldFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
const [shown, setShown] = useState(false);
const input = useRef<ComponentRef<typeof TextInput>>(null);
useImperativeHandle(ref, () => input.current!, []);
const trailing = secureTextEntry ? (
<Pressable onPress={() => setShown((s) => !s)} hitSlop={8} accessibilityRole="button" accessibilityLabel={shown ? 'Hide password' : 'Show password'} disabled={disabled}>
<Text style={styles.action}>{shown ? 'Hide' : 'Show'}</Text>
</Pressable>
) : value && !disabled ? (
<Pressable onPress={() => { onChangeText(''); input.current?.focus(); }} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Clear ${label}`}>
<View style={styles.clear}><Text style={styles.clearMark}>×</Text></View>
</Pressable>
) : null;
return (
<FieldFrame label={label} copyTestIDs={copyTestIDs} variant={variant} minHeight={minHeight} helper={helper} error={error} disabled={disabled} focused={focused} count={maxLength ? [value.length, maxLength] : undefined} trailing={trailing}>
<TextInput
underlineColorAndroid="transparent"
{...inputProps}
ref={input}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.outline}
editable={!disabled}
maxLength={maxLength}
secureTextEntry={secureTextEntry && !shown}
autoFocus={autoFocus}
onFocus={(e) => {
setFocused(true);
inputProps?.onFocus?.(e);
}}
onBlur={(e) => {
setFocused(false);
inputProps?.onBlur?.(e);
}}
accessibilityLabel={label}
accessibilityHint={error ?? helper}
style={[styles.input, NO_WEB_RING, disabled && styles.inputDisabled]}
/>
</FieldFrame>
);
}
export type FieldFrameProps = {
label: string;
copyTestIDs?: { label?: string; helper?: string };
variant?: TextFieldVariant;
minHeight?: number;
helper?: string;
error?: string;
disabled?: boolean;
focused?: boolean;
count?: [number, number];
trailing?: ReactNode;
children: ReactNode;
};
/** The label, box, help line and count around any input. TextField draws this; use it alone to show a state. */
export function FieldFrame({ label, copyTestIDs, variant = 'outlined', minHeight, helper, error, disabled = false, focused = false, count, trailing, children }: FieldFrameProps) {
const full = !!count && count[0] >= count[1];
const underlined = variant === 'underlined';
const active = !disabled && (focused || !!error);
return (
<View style={[styles.root, minHeight !== undefined && { minHeight }]}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
<View style={[
styles.box, styles[variant], minHeight !== undefined && styles.grow,
active && (underlined ? styles.lineActive : styles.boxActive),
active && { borderColor: error ? colors.error : colors.primary },
disabled && (underlined ? styles.lineDisabled : styles.boxDisabled),
]}>
<View style={styles.inputWrap}>{children}</View>
{trailing}
</View>
{error || helper || count ? (
<View style={styles.below}>
<Text testID={error == null && helper ? copyTestIDs?.helper : undefined} style={[styles.help, !!error && styles.error]} accessibilityLiveRegion={error ? 'polite' : 'none'}>{error ?? helper ?? ''}</Text>
{count ? <Text style={[styles.help, styles.count, full && styles.countFull]}>{count[0]}/{count[1]}</Text> : null}
</View>
) : null}
</View>
);
}
// The box shows focus, so the browser's own focus ring is turned off on the web. React Native's types have no
// 'none' for outlineStyle, but react-native-web passes it through to CSS.
const NO_WEB_RING = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : null;
const styles = StyleSheet.create({
root: { gap: 6 },
grow: { flexGrow: 1 },
label: { fontSize: 14, fontWeight: '500', color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
box: {
minHeight: 50,
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
outlined: {
paddingHorizontal: 14,
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
underlined: { borderBottomWidth: 1, borderColor: colors.outline, paddingTop: 1 },
filled: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: 'transparent', backgroundColor: colors.surfaceVariant },
boxActive: { borderWidth: 2, paddingHorizontal: 13 },
lineActive: { borderBottomWidth: 2, paddingTop: 2 },
lineDisabled: { borderColor: colors.outlineVariant },
boxDisabled: { borderWidth: 0, paddingHorizontal: 15, backgroundColor: colors.surfaceVariant },
inputWrap: { flex: 1, justifyContent: 'center' },
input: { fontSize: 17, color: colors.onSurface, paddingVertical: 12 },
inputDisabled: { color: colors.onSurfaceVariant },
action: { fontSize: 15, fontWeight: '600', color: colors.primary },
clear: { width: 20, height: 20, borderRadius: 10, backgroundColor: colors.outline, alignItems: 'center', justifyContent: 'center' },
clearMark: { marginTop: -2, fontSize: 16, lineHeight: 18, fontWeight: '700', color: colors.surface },
below: { flexDirection: 'row', gap: 12 },
help: { flex: 1, fontSize: 13, color: colors.onSurfaceVariant },
error: { color: colors.error },
count: { flex: 0, fontVariant: ['tabular-nums'] },
countFull: { color: colors.onSurface, fontWeight: '600' },
});
// Text field: a label above, help or an error below, a character count, a clear button, and Show / Hide for passwords.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useImperativeHandle, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type TextFieldVariant = 'outlined' | 'underlined' | 'filled';
export type TextFieldProps = {
/** Shown above the field and announced by screen readers. */
label: string;
/** The text. Keep it in state and pass it back. */
value: string;
/** Called with the new text on every edit. */
onChangeText: (value: string) => void;
/** Draw an outline, a bottom line, or a tinted box around the input. */
variant?: TextFieldVariant;
/** Minimum height of the whole labelled field. Additional space is given to the input. */
minHeight?: number;
/** Grey hint inside the empty field. Not a replacement for the label. */
placeholder?: string;
/** One line of help under the field. Hidden while there is an error. */
helper?: string;
/** The error message. The field turns red while it is set; clear it when the user edits. */
error?: string;
/** Grey and read-only. */
disabled?: boolean;
/** The most characters allowed. Shows a count under the field. */
maxLength?: number;
/** Hides the text and adds a Show / Hide button. */
secureTextEntry?: boolean;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'>;
/** The TextInput, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function TextField({
label, value, onChangeText, variant = 'outlined', minHeight, placeholder, helper, error, disabled = false, maxLength, secureTextEntry = false, autoFocus = false, inputProps, ref, copyTestIDs,
}: TextFieldProps & Pick<FieldFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
const [shown, setShown] = useState(false);
const input = useRef<ComponentRef<typeof TextInput>>(null);
useImperativeHandle(ref, () => input.current!, []);
const trailing = secureTextEntry ? (
<Pressable onPress={() => setShown((s) => !s)} hitSlop={8} accessibilityRole="button" accessibilityLabel={shown ? 'Hide password' : 'Show password'} disabled={disabled}>
<Text style={styles.action}>{shown ? 'Hide' : 'Show'}</Text>
</Pressable>
) : value && !disabled ? (
<Pressable onPress={() => { onChangeText(''); input.current?.focus(); }} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Clear ${label}`}>
<View style={styles.clear}><Text style={styles.clearMark}>×</Text></View>
</Pressable>
) : null;
return (
<FieldFrame label={label} copyTestIDs={copyTestIDs} variant={variant} minHeight={minHeight} helper={helper} error={error} disabled={disabled} focused={focused} count={maxLength ? [value.length, maxLength] : undefined} trailing={trailing}>
<TextInput
underlineColorAndroid="transparent"
{...inputProps}
ref={input}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.outline}
editable={!disabled}
maxLength={maxLength}
secureTextEntry={secureTextEntry && !shown}
autoFocus={autoFocus}
onFocus={(e) => {
setFocused(true);
inputProps?.onFocus?.(e);
}}
onBlur={(e) => {
setFocused(false);
inputProps?.onBlur?.(e);
}}
accessibilityLabel={label}
accessibilityHint={error ?? helper}
style={[styles.input, NO_WEB_RING, disabled && styles.inputDisabled]}
/>
</FieldFrame>
);
}
export type FieldFrameProps = {
label: string;
copyTestIDs?: { label?: string; helper?: string };
variant?: TextFieldVariant;
minHeight?: number;
helper?: string;
error?: string;
disabled?: boolean;
focused?: boolean;
count?: [number, number];
trailing?: ReactNode;
children: ReactNode;
};
/** The label, box, help line and count around any input. TextField draws this; use it alone to show a state. */
export function FieldFrame({ label, copyTestIDs, variant = 'outlined', minHeight, helper, error, disabled = false, focused = false, count, trailing, children }: FieldFrameProps) {
const full = !!count && count[0] >= count[1];
const underlined = variant === 'underlined';
const active = !disabled && (focused || !!error);
return (
<View style={[styles.root, minHeight !== undefined && { minHeight }]}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
<View style={[
styles.box, styles[variant], minHeight !== undefined && styles.grow,
active && (underlined ? styles.lineActive : styles.boxActive),
active && { borderColor: error ? colors.error : colors.primary },
disabled && (underlined ? styles.lineDisabled : styles.boxDisabled),
]}>
<View style={styles.inputWrap}>{children}</View>
{trailing}
</View>
{error || helper || count ? (
<View style={styles.below}>
<Text testID={error == null && helper ? copyTestIDs?.helper : undefined} style={[styles.help, !!error && styles.error]} accessibilityLiveRegion={error ? 'polite' : 'none'}>{error ?? helper ?? ''}</Text>
{count ? <Text style={[styles.help, styles.count, full && styles.countFull]}>{count[0]}/{count[1]}</Text> : null}
</View>
) : null}
</View>
);
}
// The box shows focus, so the browser's own focus ring is turned off on the web. React Native's types have no
// 'none' for outlineStyle, but react-native-web passes it through to CSS.
const NO_WEB_RING = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : null;
const styles = StyleSheet.create({
root: { gap: 6 },
grow: { flexGrow: 1 },
label: { fontSize: 14, fontWeight: '500', color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
box: {
minHeight: 50,
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
outlined: {
paddingHorizontal: 14,
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
underlined: { borderBottomWidth: 1, borderColor: colors.outline, paddingTop: 1 },
filled: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: 'transparent', backgroundColor: colors.surfaceVariant },
boxActive: { borderWidth: 2, paddingHorizontal: 13 },
lineActive: { borderBottomWidth: 2, paddingTop: 2 },
lineDisabled: { borderColor: colors.outlineVariant },
boxDisabled: { borderWidth: 0, paddingHorizontal: 15, backgroundColor: colors.surfaceVariant },
inputWrap: { flex: 1, justifyContent: 'center' },
input: { fontSize: 17, color: colors.onSurface, paddingVertical: 12 },
inputDisabled: { color: colors.onSurfaceVariant },
action: { fontSize: 15, fontWeight: '600', color: colors.primary },
clear: { width: 20, height: 20, borderRadius: 10, backgroundColor: colors.outline, alignItems: 'center', justifyContent: 'center' },
clearMark: { marginTop: -2, fontSize: 16, lineHeight: 18, fontWeight: '700', color: colors.surface },
below: { flexDirection: 'row', gap: 12 },
help: { flex: 1, fontSize: 13, color: colors.onSurfaceVariant },
error: { color: colors.error },
count: { flex: 0, fontVariant: ['tabular-nums'] },
countFull: { color: colors.onSurface, fontWeight: '600' },
});
// 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' },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// 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 { EmailOtpSignIn, type EmailOtpApi } from '@/components/mobilens/EmailOtpSignIn';
// Map your backend's answers onto the result shapes. Network errors can simply throw: they show as offline.
const api: EmailOtpApi = {
async sendCode(email) {
const res = await fetch('https://api.example.com/auth/code', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }),
});
if (res.status === 429) {
const retry = res.headers.get('Retry-After');
const seconds = retry && /^\d+$/.test(retry) ? Number(retry) : (Date.parse(retry ?? '') - Date.now()) / 1000;
return { status: 'rate-limited', retryInSeconds: Number.isFinite(seconds) ? Math.max(0, Math.ceil(seconds)) : 60 };
}
if (!res.ok) return { status: 'failed' };
return { status: 'sent', expiresInSeconds: 600, resendInSeconds: 30 };
},
async verifyCode(email, code) {
const res = await fetch('https://api.example.com/auth/verify', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code }),
});
if (res.ok) return { status: 'ok' };
const body = await res.json().catch(() => null);
if (body?.reason === 'expired') return { status: 'expired' };
if (body?.reason === 'locked') return { status: 'locked', retryInSeconds: body.retryInSeconds ?? 900 };
if (body?.reason === 'wrong' && Number.isInteger(body.attemptsLeft)) return { status: 'wrong', attemptsLeft: body.attemptsLeft };
return { status: 'failed' };
},
};
// With Expo Router: goHome = () => router.replace('/')
export function SignInScreen({ goHome }: { goHome: () => void }) {
return <EmailOtpSignIn api={api} otpVariant="segmented" onSignedIn={goHome} />;
}
import { EmailOtpSignIn, type EmailOtpApi } from '@/components/mobilens/EmailOtpSignIn';
// Map your backend's answers onto the result shapes. Network errors can simply throw: they show as offline.
const api: EmailOtpApi = {
async sendCode(email) {
const res = await fetch('https://api.example.com/auth/code', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }),
});
if (res.status === 429) {
const retry = res.headers.get('Retry-After');
const seconds = retry && /^\d+$/.test(retry) ? Number(retry) : (Date.parse(retry ?? '') - Date.now()) / 1000;
return { status: 'rate-limited', retryInSeconds: Number.isFinite(seconds) ? Math.max(0, Math.ceil(seconds)) : 60 };
}
if (!res.ok) return { status: 'failed' };
return { status: 'sent', expiresInSeconds: 600, resendInSeconds: 30 };
},
async verifyCode(email, code) {
const res = await fetch('https://api.example.com/auth/verify', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code }),
});
if (res.ok) return { status: 'ok' };
const body = await res.json().catch(() => null);
if (body?.reason === 'expired') return { status: 'expired' };
if (body?.reason === 'locked') return { status: 'locked', retryInSeconds: body.retryInSeconds ?? 900 };
if (body?.reason === 'wrong' && Number.isInteger(body.attemptsLeft)) return { status: 'wrong', attemptsLeft: body.attemptsLeft };
return { status: 'failed' };
},
};
// With Expo Router: goHome = () => router.replace('/')
export function SignInScreen({ goHome }: { goHome: () => void }) {
return <EmailOtpSignIn api={api} otpVariant="segmented" onSignedIn={goHome} />;
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| title? | string | 'Sign in' | Heading shown on the email entry step. |
| primaryLabel? | string | 'Send code' | Label of the button that requests the first code. |
| labels? | Partial<EmailOtpSignInLabels> | – | The words the screen shows. Pass a partial set to change only some of them. |
| otpVariant? | OtpInputVariant | 'segmented' | Display the verification code in separate cells or one outlined field. |
| api | EmailOtpApi | – | sendCode and verifyCode, connected to your backend. |
| onSignedIn | (email: string) => void | – | Called once the code is accepted. Navigate into the app from here. |
| timeoutMs? | number | 15000 | How long to wait for the backend before showing the timeout state, in ms. |
| autoFocus? | boolean | true | Focus the field and bring up the keyboard when the screen opens. |
| initialState? | SignInState | { status: 'idle' | Where to start. Defaults to an empty email step; pass a saved state to resume, or any state in tests. |
| onStateChange? | (state: SignInState) => void | – | Called with every state the screen enters, for analytics or logging. |