屏幕
配色方案
明暗
圆角
颜色
这个流程的所有画面
查看
确认
完成
- 何时出现
- 怎么离开
- 下一步
- 行为规则
把这 6 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// Delete account: what will go, a typed confirmation in a sheet, then the request with its failures.
// Uses ./Button, ./BottomSheet, ./TextField and ./Snackbar.
// 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 { StyleSheet, Text, View } from 'react-native';
import { BottomSheet } from './BottomSheet';
import { Button } from './Button';
import { Snackbar, useSnackbar } from './Snackbar';
import { TextField } from './TextField';
import { colors, radius } from './theme';
/** rejected: the backend will not delete yet, with a reason the user can act on, such as an active subscription. */
export type DeleteResult = { status: 'deleted' } | { status: 'rejected'; reason: string; fixLabel?: string } | { status: 'failed' };
export type DeleteStep = 'review' | 'confirm' | 'invalid' | 'deleting' | 'rejected' | 'failed' | 'deleted';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type DeleteAccountLabels = {
deletedTitle: string;
deletedSub: string;
reviewSub: string;
rejectedTitle: string;
rejectedReason: string;
manageSubscription: string;
done: string;
sheetTitle: string;
sheetText: string;
confirmLabel: string;
confirmHint: string;
deleteForGood: string;
keepAccount: string;
failedText: string;
retry: string;
};
const defaultLabels: DeleteAccountLabels = {
deletedTitle: 'Your account is deleted',
deletedSub: 'Your data is gone from our servers. Thanks for being here.',
reviewSub: "This can't be undone. Deleting removes:",
rejectedTitle: "Your account can't be deleted yet",
rejectedReason: 'You have an active subscription. Cancel it first, so you are not charged again.',
manageSubscription: 'Manage subscription',
done: 'Done',
sheetTitle: 'Delete your account?',
sheetText: 'Type {confirmWord} to confirm. Everything listed is removed for good.',
confirmLabel: 'Confirm',
confirmHint: 'Type {confirmWord} in capitals.',
deleteForGood: 'Delete for good',
keepAccount: 'Keep my account',
failedText: "Couldn't delete your account. Nothing was removed.",
retry: 'Retry',
};
/** 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 DeleteAccountProps = {
/** Heading shown on the account review step. */
title?: string;
/** Label of the review button that opens the confirmation sheet. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<DeleteAccountLabels>;
/** Deletes the account. A call that throws counts as failed. */
deleteAccount: () => Promise<DeleteResult>;
/** Called after the goodbye screen's button: sign out and go to the start. */
onDeleted: () => void;
/** Called when the user taps the fix for a rejection, such as Manage subscription. */
onFix?: () => void;
/** What is deleted, one line each. */
losing: string[];
/** The word to type to confirm. */
confirmWord?: string;
/** Focus the field and bring up the keyboard when the sheet opens. */
autoFocus?: boolean;
/** Where to start. Defaults to the review; pass a step in tests. */
initialStep?: DeleteStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: DeleteStep) => void;
};
export function DeleteAccount({
title = 'Delete account', primaryLabel = 'Delete account', labels, deleteAccount, onDeleted, onFix,
losing, confirmWord = 'DELETE', autoFocus = true, initialStep = 'review', onStepChange,
}: DeleteAccountProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<DeleteStep>(initialStep);
const [typed, setTyped] = useState(initialStep === 'invalid' ? 'delte' : ['deleting', 'failed'].includes(initialStep) ? confirmWord : '');
const [reason, setReason] = useState<{ reason: string; fixLabel?: string }>({ reason: t.rejectedReason, fixLabel: t.manageSubscription });
const snack = useSnackbar();
const busy = useRef(false);
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => changed.current?.(step), [step]);
const failedShown = useRef(false);
useEffect(() => {
// A failure keeps the sheet open and says so at the bottom, with Retry.
if (step === 'failed' && !failedShown.current) {
failedShown.current = true;
snack.show({ text: t.failedText, tone: 'error', action: { label: t.retry, onPress: () => run() } });
}
if (step !== 'failed') failedShown.current = false;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step]);
const matches = typed.trim() === confirmWord;
const sheetOpen = ['confirm', 'invalid', 'deleting', 'failed'].includes(step);
async function run() {
if (busy.current) return;
busy.current = true;
setStep('deleting');
const r = await deleteAccount().catch((): DeleteResult => ({ status: 'failed' }));
busy.current = false;
if (r.status === 'deleted') setStep('deleted');
else if (r.status === 'rejected') {
setReason(r);
setStep('rejected');
} else setStep('failed');
}
if (step === 'deleted') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title} accessibilityRole="header">{t.deletedTitle}</Text>
<Text style={[styles.sub, styles.centerText]}>{t.deletedSub}</Text>
<Button title={t.done} onPress={onDeleted} style={styles.done} />
</View>
);
}
return (
<View style={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<Text style={styles.sub}>{t.reviewSub}</Text>
<View style={styles.list}>
{losing.map((line) => (
<View key={line} style={styles.item}>
<View style={styles.dot} />
<Text style={styles.itemText}>{line}</Text>
</View>
))}
</View>
{step === 'rejected' ? (
<View style={styles.rejected} accessibilityLiveRegion="polite">
<Text style={styles.rejectedTitle}>{t.rejectedTitle}</Text>
<Text style={styles.rejectedText}>{reason.reason}</Text>
</View>
) : null}
<View style={styles.actions}>
{step === 'rejected' && reason.fixLabel && onFix ? <Button title={reason.fixLabel} onPress={onFix} /> : null}
<Button title={primaryLabel} variant={step === 'rejected' ? 'secondary' : 'destructive'} onPress={() => setStep('confirm')} />
</View>
<BottomSheet visible={sheetOpen} onClose={() => setStep('review')} title={t.sheetTitle} dismissible={step !== 'deleting'}>
<Text style={styles.sheetText}>{fill(t.sheetText, { confirmWord })}</Text>
<TextField
label={t.confirmLabel}
value={typed}
onChangeText={(t) => {
setTyped(t);
if (step === 'invalid' || step === 'failed') setStep('confirm');
}}
placeholder={confirmWord}
disabled={step === 'deleting'}
autoFocus={autoFocus && step === 'confirm'}
error={step === 'invalid' ? fill(t.confirmHint, { confirmWord }) : undefined}
inputProps={{
autoCapitalize: 'characters', autoCorrect: false, autoComplete: 'off', returnKeyType: 'done',
onSubmitEditing: () => (matches ? run() : setStep('invalid')),
onBlur: () => typed && !matches && step === 'confirm' && setStep('invalid'),
}}
/>
<Button title={t.deleteForGood} variant="destructive" loading={step === 'deleting'} disabled={!matches} onPress={run} />
<Button title={t.keepAccount} variant="ghost" onPress={() => setStep('review')} disabled={step === 'deleting'} />
</BottomSheet>
<Snackbar {...snack.props} />
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 32, paddingBottom: 16 },
center: { alignItems: 'center', justifyContent: 'center' },
centerText: { textAlign: 'center' },
title: { fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 8, fontSize: 16, lineHeight: 22, color: colors.onSurfaceVariant },
list: { marginTop: 20, padding: 16, gap: 12, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant },
item: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },
dot: { width: 6, height: 6, marginTop: 8, borderRadius: 3, backgroundColor: colors.error },
itemText: { flex: 1, fontSize: 16, lineHeight: 22, color: colors.onSurface },
rejected: { marginTop: 16, padding: 14, gap: 4, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
rejectedTitle: { fontSize: 15, fontWeight: '600', color: colors.onSurface },
rejectedText: { fontSize: 14, lineHeight: 20, color: colors.onSurfaceVariant },
actions: { marginTop: 'auto', gap: 10 },
sheetText: { fontSize: 15, lineHeight: 21, color: colors.onSurfaceVariant },
done: { alignSelf: 'stretch', marginTop: 32 },
});
// Delete account: what will go, a typed confirmation in a sheet, then the request with its failures.
// Uses ./Button, ./BottomSheet, ./TextField and ./Snackbar.
// 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 { StyleSheet, Text, View } from 'react-native';
import { BottomSheet } from './BottomSheet';
import { Button } from './Button';
import { Snackbar, useSnackbar } from './Snackbar';
import { TextField } from './TextField';
import { colors, radius } from './theme';
/** rejected: the backend will not delete yet, with a reason the user can act on, such as an active subscription. */
export type DeleteResult = { status: 'deleted' } | { status: 'rejected'; reason: string; fixLabel?: string } | { status: 'failed' };
export type DeleteStep = 'review' | 'confirm' | 'invalid' | 'deleting' | 'rejected' | 'failed' | 'deleted';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type DeleteAccountLabels = {
deletedTitle: string;
deletedSub: string;
reviewSub: string;
rejectedTitle: string;
rejectedReason: string;
manageSubscription: string;
done: string;
sheetTitle: string;
sheetText: string;
confirmLabel: string;
confirmHint: string;
deleteForGood: string;
keepAccount: string;
failedText: string;
retry: string;
};
const defaultLabels: DeleteAccountLabels = {
deletedTitle: 'Your account is deleted',
deletedSub: 'Your data is gone from our servers. Thanks for being here.',
reviewSub: "This can't be undone. Deleting removes:",
rejectedTitle: "Your account can't be deleted yet",
rejectedReason: 'You have an active subscription. Cancel it first, so you are not charged again.',
manageSubscription: 'Manage subscription',
done: 'Done',
sheetTitle: 'Delete your account?',
sheetText: 'Type {confirmWord} to confirm. Everything listed is removed for good.',
confirmLabel: 'Confirm',
confirmHint: 'Type {confirmWord} in capitals.',
deleteForGood: 'Delete for good',
keepAccount: 'Keep my account',
failedText: "Couldn't delete your account. Nothing was removed.",
retry: 'Retry',
};
/** 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 DeleteAccountProps = {
/** Heading shown on the account review step. */
title?: string;
/** Label of the review button that opens the confirmation sheet. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<DeleteAccountLabels>;
/** Deletes the account. A call that throws counts as failed. */
deleteAccount: () => Promise<DeleteResult>;
/** Called after the goodbye screen's button: sign out and go to the start. */
onDeleted: () => void;
/** Called when the user taps the fix for a rejection, such as Manage subscription. */
onFix?: () => void;
/** What is deleted, one line each. */
losing: string[];
/** The word to type to confirm. */
confirmWord?: string;
/** Focus the field and bring up the keyboard when the sheet opens. */
autoFocus?: boolean;
/** Where to start. Defaults to the review; pass a step in tests. */
initialStep?: DeleteStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: DeleteStep) => void;
};
export function DeleteAccount({
title = 'Delete account', primaryLabel = 'Delete account', labels, deleteAccount, onDeleted, onFix,
losing, confirmWord = 'DELETE', autoFocus = true, initialStep = 'review', onStepChange,
}: DeleteAccountProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<DeleteStep>(initialStep);
const [typed, setTyped] = useState(initialStep === 'invalid' ? 'delte' : ['deleting', 'failed'].includes(initialStep) ? confirmWord : '');
const [reason, setReason] = useState<{ reason: string; fixLabel?: string }>({ reason: t.rejectedReason, fixLabel: t.manageSubscription });
const snack = useSnackbar();
const busy = useRef(false);
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => changed.current?.(step), [step]);
const failedShown = useRef(false);
useEffect(() => {
// A failure keeps the sheet open and says so at the bottom, with Retry.
if (step === 'failed' && !failedShown.current) {
failedShown.current = true;
snack.show({ text: t.failedText, tone: 'error', action: { label: t.retry, onPress: () => run() } });
}
if (step !== 'failed') failedShown.current = false;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step]);
const matches = typed.trim() === confirmWord;
const sheetOpen = ['confirm', 'invalid', 'deleting', 'failed'].includes(step);
async function run() {
if (busy.current) return;
busy.current = true;
setStep('deleting');
const r = await deleteAccount().catch((): DeleteResult => ({ status: 'failed' }));
busy.current = false;
if (r.status === 'deleted') setStep('deleted');
else if (r.status === 'rejected') {
setReason(r);
setStep('rejected');
} else setStep('failed');
}
if (step === 'deleted') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title} accessibilityRole="header">{t.deletedTitle}</Text>
<Text style={[styles.sub, styles.centerText]}>{t.deletedSub}</Text>
<Button title={t.done} onPress={onDeleted} style={styles.done} />
</View>
);
}
return (
<View style={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<Text style={styles.sub}>{t.reviewSub}</Text>
<View style={styles.list}>
{losing.map((line) => (
<View key={line} style={styles.item}>
<View style={styles.dot} />
<Text style={styles.itemText}>{line}</Text>
</View>
))}
</View>
{step === 'rejected' ? (
<View style={styles.rejected} accessibilityLiveRegion="polite">
<Text style={styles.rejectedTitle}>{t.rejectedTitle}</Text>
<Text style={styles.rejectedText}>{reason.reason}</Text>
</View>
) : null}
<View style={styles.actions}>
{step === 'rejected' && reason.fixLabel && onFix ? <Button title={reason.fixLabel} onPress={onFix} /> : null}
<Button title={primaryLabel} variant={step === 'rejected' ? 'secondary' : 'destructive'} onPress={() => setStep('confirm')} />
</View>
<BottomSheet visible={sheetOpen} onClose={() => setStep('review')} title={t.sheetTitle} dismissible={step !== 'deleting'}>
<Text style={styles.sheetText}>{fill(t.sheetText, { confirmWord })}</Text>
<TextField
label={t.confirmLabel}
value={typed}
onChangeText={(t) => {
setTyped(t);
if (step === 'invalid' || step === 'failed') setStep('confirm');
}}
placeholder={confirmWord}
disabled={step === 'deleting'}
autoFocus={autoFocus && step === 'confirm'}
error={step === 'invalid' ? fill(t.confirmHint, { confirmWord }) : undefined}
inputProps={{
autoCapitalize: 'characters', autoCorrect: false, autoComplete: 'off', returnKeyType: 'done',
onSubmitEditing: () => (matches ? run() : setStep('invalid')),
onBlur: () => typed && !matches && step === 'confirm' && setStep('invalid'),
}}
/>
<Button title={t.deleteForGood} variant="destructive" loading={step === 'deleting'} disabled={!matches} onPress={run} />
<Button title={t.keepAccount} variant="ghost" onPress={() => setStep('review')} disabled={step === 'deleting'} />
</BottomSheet>
<Snackbar {...snack.props} />
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 32, paddingBottom: 16 },
center: { alignItems: 'center', justifyContent: 'center' },
centerText: { textAlign: 'center' },
title: { fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 8, fontSize: 16, lineHeight: 22, color: colors.onSurfaceVariant },
list: { marginTop: 20, padding: 16, gap: 12, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant },
item: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },
dot: { width: 6, height: 6, marginTop: 8, borderRadius: 3, backgroundColor: colors.error },
itemText: { flex: 1, fontSize: 16, lineHeight: 22, color: colors.onSurface },
rejected: { marginTop: 16, padding: 14, gap: 4, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
rejectedTitle: { fontSize: 15, fontWeight: '600', color: colors.onSurface },
rejectedText: { fontSize: 14, lineHeight: 20, color: colors.onSurfaceVariant },
actions: { marginTop: 'auto', gap: 10 },
sheetText: { fontSize: 15, lineHeight: 21, color: colors.onSurfaceVariant },
done: { alignSelf: 'stretch', marginTop: 32 },
});
// 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' },
});
// Bottom sheet: a panel that slides up over the screen for a short task or a choice.
// It closes on a tap outside, on a drag down from the handle, and on Android's back button, unless the task
// must not be interrupted (dismissible={false}). It rises with the keyboard.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState, type ReactNode } from 'react';
import {
AccessibilityInfo, Animated, KeyboardAvoidingView, Modal, PanResponder, Platform, Pressable, StyleSheet, Text, View,
} from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type BottomSheetProps = {
/** Open or closed. Closing animates out before the sheet is removed. */
visible: boolean;
/** Called when the user asks to close it: backdrop, drag down or back button. Set visible to false. */
onClose: () => void;
/** Shown at the top and announced when the sheet opens. */
title?: string;
/** The sheet's content. */
children: ReactNode;
/** false keeps it open on backdrop taps, drags and back, for example while it saves. */
dismissible?: boolean;
};
export function BottomSheet({ visible, onClose, title, children, dismissible = true }: BottomSheetProps) {
const [mounted, setMounted] = useState(visible);
const open = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const still = useReduceMotion();
const close = useRef(onClose);
close.current = onClose;
const canClose = useRef(dismissible);
canClose.current = dismissible;
useEffect(() => {
if (visible) {
setMounted(true);
drag.setValue(0);
Animated.timing(open, { toValue: 1, duration: still ? 150 : 260, useNativeDriver: NATIVE_DRIVER }).start();
} else {
Animated.timing(open, { toValue: 0, duration: still ? 120 : 200, useNativeDriver: NATIVE_DRIVER }).start(({ finished }) => finished && setMounted(false));
}
}, [visible, open, drag, still]);
const pan = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => canClose.current,
onMoveShouldSetPanResponder: (_, g) => canClose.current && g.dy > 4,
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 80 || g.vy > 1) close.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER, bounciness: 0 }).start();
},
}),
).current;
if (!mounted) return null;
const rise = open.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 400, 0] });
const sheet = (
<View style={styles.layer}>
<Animated.View style={[styles.layer, { opacity: open }]}>
<Pressable style={styles.backdrop} onPress={dismissible ? onClose : undefined} accessibilityRole="button" accessibilityLabel="Close" />
</Animated.View>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.bottom} pointerEvents="box-none">
<Animated.View style={{ opacity: still ? open : 1, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SheetView title={title} handle={<View {...pan.panHandlers} style={styles.handleArea}><View style={styles.handle} /></View>}>
{children}
</SheetView>
</Animated.View>
</KeyboardAvoidingView>
</View>
);
// On a device the sheet covers everything, header and tab bar too. On the web a Modal covers the whole window,
// so there the sheet stays inside the screen that renders it: render it as the screen's last child.
if (Platform.OS === 'web') return sheet;
return (
<Modal transparent visible animationType="none" statusBarTranslucent onRequestClose={() => {
if (dismissible) onClose();
}}>
{sheet}
</Modal>
);
}
/** The panel itself, with no animation or gestures. BottomSheet draws this; use it alone to show a state. */
export function SheetView({ title, handle, children }: { title?: string; handle?: ReactNode; children: ReactNode }) {
return (
<View style={styles.sheet} accessibilityViewIsModal>
{handle ?? <View style={styles.handleArea}><View style={styles.handle} /></View>}
{title ? <Text style={styles.title} accessibilityRole="header">{title}</Text> : null}
<View style={styles.body}>{children}</View>
</View>
);
}
/** The dimmed screen behind a sheet. */
export function SheetBackdrop() {
return <View style={[styles.layer, styles.backdrop]} />;
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
layer: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
backdrop: { flex: 1, backgroundColor: colors.scrim },
bottom: { position: 'absolute', left: 0, right: 0, bottom: 0 },
sheet: {
paddingHorizontal: 20,
paddingBottom: 24,
borderTopLeftRadius: radius.lg,
borderTopRightRadius: radius.lg,
backgroundColor: colors.surface,
},
handleArea: { height: 28, alignItems: 'center', justifyContent: 'center' },
handle: { width: 36, height: 5, borderRadius: 3, backgroundColor: colors.outlineVariant },
title: { fontSize: 20, fontWeight: '600', color: colors.onSurface },
body: { marginTop: 12, gap: 12 },
});
// Bottom sheet: a panel that slides up over the screen for a short task or a choice.
// It closes on a tap outside, on a drag down from the handle, and on Android's back button, unless the task
// must not be interrupted (dismissible={false}). It rises with the keyboard.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState, type ReactNode } from 'react';
import {
AccessibilityInfo, Animated, KeyboardAvoidingView, Modal, PanResponder, Platform, Pressable, StyleSheet, Text, View,
} from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type BottomSheetProps = {
/** Open or closed. Closing animates out before the sheet is removed. */
visible: boolean;
/** Called when the user asks to close it: backdrop, drag down or back button. Set visible to false. */
onClose: () => void;
/** Shown at the top and announced when the sheet opens. */
title?: string;
/** The sheet's content. */
children: ReactNode;
/** false keeps it open on backdrop taps, drags and back, for example while it saves. */
dismissible?: boolean;
};
export function BottomSheet({ visible, onClose, title, children, dismissible = true }: BottomSheetProps) {
const [mounted, setMounted] = useState(visible);
const open = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const still = useReduceMotion();
const close = useRef(onClose);
close.current = onClose;
const canClose = useRef(dismissible);
canClose.current = dismissible;
useEffect(() => {
if (visible) {
setMounted(true);
drag.setValue(0);
Animated.timing(open, { toValue: 1, duration: still ? 150 : 260, useNativeDriver: NATIVE_DRIVER }).start();
} else {
Animated.timing(open, { toValue: 0, duration: still ? 120 : 200, useNativeDriver: NATIVE_DRIVER }).start(({ finished }) => finished && setMounted(false));
}
}, [visible, open, drag, still]);
const pan = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => canClose.current,
onMoveShouldSetPanResponder: (_, g) => canClose.current && g.dy > 4,
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 80 || g.vy > 1) close.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER, bounciness: 0 }).start();
},
}),
).current;
if (!mounted) return null;
const rise = open.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 400, 0] });
const sheet = (
<View style={styles.layer}>
<Animated.View style={[styles.layer, { opacity: open }]}>
<Pressable style={styles.backdrop} onPress={dismissible ? onClose : undefined} accessibilityRole="button" accessibilityLabel="Close" />
</Animated.View>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.bottom} pointerEvents="box-none">
<Animated.View style={{ opacity: still ? open : 1, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SheetView title={title} handle={<View {...pan.panHandlers} style={styles.handleArea}><View style={styles.handle} /></View>}>
{children}
</SheetView>
</Animated.View>
</KeyboardAvoidingView>
</View>
);
// On a device the sheet covers everything, header and tab bar too. On the web a Modal covers the whole window,
// so there the sheet stays inside the screen that renders it: render it as the screen's last child.
if (Platform.OS === 'web') return sheet;
return (
<Modal transparent visible animationType="none" statusBarTranslucent onRequestClose={() => {
if (dismissible) onClose();
}}>
{sheet}
</Modal>
);
}
/** The panel itself, with no animation or gestures. BottomSheet draws this; use it alone to show a state. */
export function SheetView({ title, handle, children }: { title?: string; handle?: ReactNode; children: ReactNode }) {
return (
<View style={styles.sheet} accessibilityViewIsModal>
{handle ?? <View style={styles.handleArea}><View style={styles.handle} /></View>}
{title ? <Text style={styles.title} accessibilityRole="header">{title}</Text> : null}
<View style={styles.body}>{children}</View>
</View>
);
}
/** The dimmed screen behind a sheet. */
export function SheetBackdrop() {
return <View style={[styles.layer, styles.backdrop]} />;
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
layer: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
backdrop: { flex: 1, backgroundColor: colors.scrim },
bottom: { position: 'absolute', left: 0, right: 0, bottom: 0 },
sheet: {
paddingHorizontal: 20,
paddingBottom: 24,
borderTopLeftRadius: radius.lg,
borderTopRightRadius: radius.lg,
backgroundColor: colors.surface,
},
handleArea: { height: 28, alignItems: 'center', justifyContent: 'center' },
handle: { width: 36, height: 5, borderRadius: 3, backgroundColor: colors.outlineVariant },
title: { fontSize: 20, fontWeight: '600', color: colors.onSurface },
body: { marginTop: 12, gap: 12 },
});
// 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' },
});
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
// 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 { DeleteAccount, type DeleteResult } from '@/components/mobilens/DeleteAccount';
async function deleteAccount(): Promise<DeleteResult> {
const res = await fetch('https://api.example.com/me', { method: 'DELETE' });
if (res.ok) return { status: 'deleted' };
if (res.status === 409) return { status: 'rejected', reason: 'You have an active subscription. Cancel it first.', fixLabel: 'Manage subscription' };
return { status: 'failed' };
}
export function DeleteAccountScreen({ signOut, openSubscriptions }: { signOut: () => void; openSubscriptions: () => void }) {
return (
<DeleteAccount
deleteAccount={deleteAccount}
onDeleted={signOut}
onFix={openSubscriptions}
losing={['Your profile and username', 'Your photos and albums', 'Your messages']}
/>
);
}
import { DeleteAccount, type DeleteResult } from '@/components/mobilens/DeleteAccount';
async function deleteAccount(): Promise<DeleteResult> {
const res = await fetch('https://api.example.com/me', { method: 'DELETE' });
if (res.ok) return { status: 'deleted' };
if (res.status === 409) return { status: 'rejected', reason: 'You have an active subscription. Cancel it first.', fixLabel: 'Manage subscription' };
return { status: 'failed' };
}
export function DeleteAccountScreen({ signOut, openSubscriptions }: { signOut: () => void; openSubscriptions: () => void }) {
return (
<DeleteAccount
deleteAccount={deleteAccount}
onDeleted={signOut}
onFix={openSubscriptions}
losing={['Your profile and username', 'Your photos and albums', 'Your messages']}
/>
);
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| title? | string | 'Delete account' | Heading shown on the account review step. |
| primaryLabel? | string | 'Delete account' | Label of the review button that opens the confirmation sheet. |
| labels? | Partial<DeleteAccountLabels> | – | The words the screen shows. Pass a partial set to change only some of them. |
| deleteAccount | () => Promise<DeleteResult> | – | Deletes the account. A call that throws counts as failed. |
| onDeleted | () => void | – | Called after the goodbye screen's button: sign out and go to the start. |
| onFix? | () => void | – | Called when the user taps the fix for a rejection, such as Manage subscription. |
| losing | string[] | – | What is deleted, one line each. |
| confirmWord? | string | 'DELETE' | The word to type to confirm. |
| autoFocus? | boolean | true | Focus the field and bring up the keyboard when the sheet opens. |
| initialStep? | DeleteStep | 'review' | Where to start. Defaults to the review; pass a step in tests. |
| onStepChange? | (step: DeleteStep) => void | – | Called with every step the screen enters, for analytics or logging. |
这个流程用到的控件
Add the "Delete account" flow 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/DeleteAccount.tsx ---
// Delete account: what will go, a typed confirmation in a sheet, then the request with its failures.
// Uses ./Button, ./BottomSheet, ./TextField and ./Snackbar.
// 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 { StyleSheet, Text, View } from 'react-native';
import { BottomSheet } from './BottomSheet';
import { Button } from './Button';
import { Snackbar, useSnackbar } from './Snackbar';
import { TextField } from './TextField';
import { colors, radius } from './theme';
/** rejected: the backend will not delete yet, with a reason the user can act on, such as an active subscription. */
export type DeleteResult = { status: 'deleted' } | { status: 'rejected'; reason: string; fixLabel?: string } | { status: 'failed' };
export type DeleteStep = 'review' | 'confirm' | 'invalid' | 'deleting' | 'rejected' | 'failed' | 'deleted';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type DeleteAccountLabels = {
deletedTitle: string;
deletedSub: string;
reviewSub: string;
rejectedTitle: string;
rejectedReason: string;
manageSubscription: string;
done: string;
sheetTitle: string;
sheetText: string;
confirmLabel: string;
confirmHint: string;
deleteForGood: string;
keepAccount: string;
failedText: string;
retry: string;
};
const defaultLabels: DeleteAccountLabels = {
deletedTitle: 'Your account is deleted',
deletedSub: 'Your data is gone from our servers. Thanks for being here.',
reviewSub: "This can't be undone. Deleting removes:",
rejectedTitle: "Your account can't be deleted yet",
rejectedReason: 'You have an active subscription. Cancel it first, so you are not charged again.',
manageSubscription: 'Manage subscription',
done: 'Done',
sheetTitle: 'Delete your account?',
sheetText: 'Type {confirmWord} to confirm. Everything listed is removed for good.',
confirmLabel: 'Confirm',
confirmHint: 'Type {confirmWord} in capitals.',
deleteForGood: 'Delete for good',
keepAccount: 'Keep my account',
failedText: "Couldn't delete your account. Nothing was removed.",
retry: 'Retry',
};
/** 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 DeleteAccountProps = {
/** Heading shown on the account review step. */
title?: string;
/** Label of the review button that opens the confirmation sheet. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<DeleteAccountLabels>;
/** Deletes the account. A call that throws counts as failed. */
deleteAccount: () => Promise<DeleteResult>;
/** Called after the goodbye screen's button: sign out and go to the start. */
onDeleted: () => void;
/** Called when the user taps the fix for a rejection, such as Manage subscription. */
onFix?: () => void;
/** What is deleted, one line each. */
losing: string[];
/** The word to type to confirm. */
confirmWord?: string;
/** Focus the field and bring up the keyboard when the sheet opens. */
autoFocus?: boolean;
/** Where to start. Defaults to the review; pass a step in tests. */
initialStep?: DeleteStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: DeleteStep) => void;
};
export function DeleteAccount({
title = 'Delete account', primaryLabel = 'Delete account', labels, deleteAccount, onDeleted, onFix,
losing, confirmWord = 'DELETE', autoFocus = true, initialStep = 'review', onStepChange,
}: DeleteAccountProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<DeleteStep>(initialStep);
const [typed, setTyped] = useState(initialStep === 'invalid' ? 'delte' : ['deleting', 'failed'].includes(initialStep) ? confirmWord : '');
const [reason, setReason] = useState<{ reason: string; fixLabel?: string }>({ reason: t.rejectedReason, fixLabel: t.manageSubscription });
const snack = useSnackbar();
const busy = useRef(false);
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => changed.current?.(step), [step]);
const failedShown = useRef(false);
useEffect(() => {
// A failure keeps the sheet open and says so at the bottom, with Retry.
if (step === 'failed' && !failedShown.current) {
failedShown.current = true;
snack.show({ text: t.failedText, tone: 'error', action: { label: t.retry, onPress: () => run() } });
}
if (step !== 'failed') failedShown.current = false;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step]);
const matches = typed.trim() === confirmWord;
const sheetOpen = ['confirm', 'invalid', 'deleting', 'failed'].includes(step);
async function run() {
if (busy.current) return;
busy.current = true;
setStep('deleting');
const r = await deleteAccount().catch((): DeleteResult => ({ status: 'failed' }));
busy.current = false;
if (r.status === 'deleted') setStep('deleted');
else if (r.status === 'rejected') {
setReason(r);
setStep('rejected');
} else setStep('failed');
}
if (step === 'deleted') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title} accessibilityRole="header">{t.deletedTitle}</Text>
<Text style={[styles.sub, styles.centerText]}>{t.deletedSub}</Text>
<Button title={t.done} onPress={onDeleted} style={styles.done} />
</View>
);
}
return (
<View style={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<Text style={styles.sub}>{t.reviewSub}</Text>
<View style={styles.list}>
{losing.map((line) => (
<View key={line} style={styles.item}>
<View style={styles.dot} />
<Text style={styles.itemText}>{line}</Text>
</View>
))}
</View>
{step === 'rejected' ? (
<View style={styles.rejected} accessibilityLiveRegion="polite">
<Text style={styles.rejectedTitle}>{t.rejectedTitle}</Text>
<Text style={styles.rejectedText}>{reason.reason}</Text>
</View>
) : null}
<View style={styles.actions}>
{step === 'rejected' && reason.fixLabel && onFix ? <Button title={reason.fixLabel} onPress={onFix} /> : null}
<Button title={primaryLabel} variant={step === 'rejected' ? 'secondary' : 'destructive'} onPress={() => setStep('confirm')} />
</View>
<BottomSheet visible={sheetOpen} onClose={() => setStep('review')} title={t.sheetTitle} dismissible={step !== 'deleting'}>
<Text style={styles.sheetText}>{fill(t.sheetText, { confirmWord })}</Text>
<TextField
label={t.confirmLabel}
value={typed}
onChangeText={(t) => {
setTyped(t);
if (step === 'invalid' || step === 'failed') setStep('confirm');
}}
placeholder={confirmWord}
disabled={step === 'deleting'}
autoFocus={autoFocus && step === 'confirm'}
error={step === 'invalid' ? fill(t.confirmHint, { confirmWord }) : undefined}
inputProps={{
autoCapitalize: 'characters', autoCorrect: false, autoComplete: 'off', returnKeyType: 'done',
onSubmitEditing: () => (matches ? run() : setStep('invalid')),
onBlur: () => typed && !matches && step === 'confirm' && setStep('invalid'),
}}
/>
<Button title={t.deleteForGood} variant="destructive" loading={step === 'deleting'} disabled={!matches} onPress={run} />
<Button title={t.keepAccount} variant="ghost" onPress={() => setStep('review')} disabled={step === 'deleting'} />
</BottomSheet>
<Snackbar {...snack.props} />
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 32, paddingBottom: 16 },
center: { alignItems: 'center', justifyContent: 'center' },
centerText: { textAlign: 'center' },
title: { fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 8, fontSize: 16, lineHeight: 22, color: colors.onSurfaceVariant },
list: { marginTop: 20, padding: 16, gap: 12, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant },
item: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },
dot: { width: 6, height: 6, marginTop: 8, borderRadius: 3, backgroundColor: colors.error },
itemText: { flex: 1, fontSize: 16, lineHeight: 22, color: colors.onSurface },
rejected: { marginTop: 16, padding: 14, gap: 4, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
rejectedTitle: { fontSize: 15, fontWeight: '600', color: colors.onSurface },
rejectedText: { fontSize: 14, lineHeight: 20, color: colors.onSurfaceVariant },
actions: { marginTop: 'auto', gap: 10 },
sheetText: { fontSize: 15, lineHeight: 21, color: colors.onSurfaceVariant },
done: { alignSelf: 'stretch', marginTop: 32 },
});
--- end of DeleteAccount.tsx ---
--- components/mobilens/Button.tsx ---
// 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' },
});
--- end of Button.tsx ---
--- components/mobilens/BottomSheet.tsx ---
// Bottom sheet: a panel that slides up over the screen for a short task or a choice.
// It closes on a tap outside, on a drag down from the handle, and on Android's back button, unless the task
// must not be interrupted (dismissible={false}). It rises with the keyboard.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState, type ReactNode } from 'react';
import {
AccessibilityInfo, Animated, KeyboardAvoidingView, Modal, PanResponder, Platform, Pressable, StyleSheet, Text, View,
} from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type BottomSheetProps = {
/** Open or closed. Closing animates out before the sheet is removed. */
visible: boolean;
/** Called when the user asks to close it: backdrop, drag down or back button. Set visible to false. */
onClose: () => void;
/** Shown at the top and announced when the sheet opens. */
title?: string;
/** The sheet's content. */
children: ReactNode;
/** false keeps it open on backdrop taps, drags and back, for example while it saves. */
dismissible?: boolean;
};
export function BottomSheet({ visible, onClose, title, children, dismissible = true }: BottomSheetProps) {
const [mounted, setMounted] = useState(visible);
const open = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const still = useReduceMotion();
const close = useRef(onClose);
close.current = onClose;
const canClose = useRef(dismissible);
canClose.current = dismissible;
useEffect(() => {
if (visible) {
setMounted(true);
drag.setValue(0);
Animated.timing(open, { toValue: 1, duration: still ? 150 : 260, useNativeDriver: NATIVE_DRIVER }).start();
} else {
Animated.timing(open, { toValue: 0, duration: still ? 120 : 200, useNativeDriver: NATIVE_DRIVER }).start(({ finished }) => finished && setMounted(false));
}
}, [visible, open, drag, still]);
const pan = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => canClose.current,
onMoveShouldSetPanResponder: (_, g) => canClose.current && g.dy > 4,
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 80 || g.vy > 1) close.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER, bounciness: 0 }).start();
},
}),
).current;
if (!mounted) return null;
const rise = open.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 400, 0] });
const sheet = (
<View style={styles.layer}>
<Animated.View style={[styles.layer, { opacity: open }]}>
<Pressable style={styles.backdrop} onPress={dismissible ? onClose : undefined} accessibilityRole="button" accessibilityLabel="Close" />
</Animated.View>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.bottom} pointerEvents="box-none">
<Animated.View style={{ opacity: still ? open : 1, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SheetView title={title} handle={<View {...pan.panHandlers} style={styles.handleArea}><View style={styles.handle} /></View>}>
{children}
</SheetView>
</Animated.View>
</KeyboardAvoidingView>
</View>
);
// On a device the sheet covers everything, header and tab bar too. On the web a Modal covers the whole window,
// so there the sheet stays inside the screen that renders it: render it as the screen's last child.
if (Platform.OS === 'web') return sheet;
return (
<Modal transparent visible animationType="none" statusBarTranslucent onRequestClose={() => {
if (dismissible) onClose();
}}>
{sheet}
</Modal>
);
}
/** The panel itself, with no animation or gestures. BottomSheet draws this; use it alone to show a state. */
export function SheetView({ title, handle, children }: { title?: string; handle?: ReactNode; children: ReactNode }) {
return (
<View style={styles.sheet} accessibilityViewIsModal>
{handle ?? <View style={styles.handleArea}><View style={styles.handle} /></View>}
{title ? <Text style={styles.title} accessibilityRole="header">{title}</Text> : null}
<View style={styles.body}>{children}</View>
</View>
);
}
/** The dimmed screen behind a sheet. */
export function SheetBackdrop() {
return <View style={[styles.layer, styles.backdrop]} />;
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
layer: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
backdrop: { flex: 1, backgroundColor: colors.scrim },
bottom: { position: 'absolute', left: 0, right: 0, bottom: 0 },
sheet: {
paddingHorizontal: 20,
paddingBottom: 24,
borderTopLeftRadius: radius.lg,
borderTopRightRadius: radius.lg,
backgroundColor: colors.surface,
},
handleArea: { height: 28, alignItems: 'center', justifyContent: 'center' },
handle: { width: 36, height: 5, borderRadius: 3, backgroundColor: colors.outlineVariant },
title: { fontSize: 20, fontWeight: '600', color: colors.onSurface },
body: { marginTop: 12, gap: 12 },
});
--- end of BottomSheet.tsx ---
--- components/mobilens/TextField.tsx ---
// 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' },
});
--- end of TextField.tsx ---
--- components/mobilens/Snackbar.tsx ---
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
--- end of Snackbar.tsx ---
HOW TO USE IT
Connect it to the project's real backend as below. Keep the result shapes: the flow's states depend on them.
import { DeleteAccount, type DeleteResult } from '@/components/mobilens/DeleteAccount';
async function deleteAccount(): Promise<DeleteResult> {
const res = await fetch('https://api.example.com/me', { method: 'DELETE' });
if (res.ok) return { status: 'deleted' };
if (res.status === 409) return { status: 'rejected', reason: 'You have an active subscription. Cancel it first.', fixLabel: 'Manage subscription' };
return { status: 'failed' };
}
export function DeleteAccountScreen({ signOut, openSubscriptions }: { signOut: () => void; openSubscriptions: () => void }) {
return (
<DeleteAccount
deleteAccount={deleteAccount}
onDeleted={signOut}
onFix={openSubscriptions}
losing={['Your profile and username', 'Your photos and albums', 'Your messages']}
/>
);
}
STATES: all 7 must work in the screen where you use it
- What goes: when the screen opens. List what is deleted in the user's own numbers, not a generic warning. Next: Confirm.
- Confirm: when delete account tapped. The sheet opens with the field focused and capitals on. Delete for good stays disabled until the word matches. Tapping outside or Keep my account closes the sheet. Next: Wrong word, Deleting, What goes.
- Wrong word: when the user left the field or pressed return with another word. Editing clears the error. Next: Confirm.
- Deleting: when delete for good tapped. The sheet cannot be closed and the button ignores taps until the answer comes. Next: Deleted, Failed, Not yet.
- Failed: when the request failed or could not reach the backend. The sheet stays open; a snackbar says nothing was removed and offers Retry. Next: Deleting.
- Not yet: when the backend refuses, for example for an active subscription. The sheet closes and the screen says why, with a button that fixes it. Next: Confirm.
- Deleted: when the backend deleted the account. Done signs out and goes to the start; there is no way back into the account.
ACCESSIBILITY
- The confirmation sheet is a modal with its title announced; the error and the failure are announced as they appear.
- The destructive button is labelled with what it does, not just Delete.
- Typing the word is the confirmation, so it works the same with a screen reader.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.