Flow · Account
Notification settings
Screen
Colour scheme
Mode
Corners
Colours
Every screen in this flow
Load
Change
- When
- Way out
- Next
- Behaviour
Save these 6 files in components/mobilens/. They need only react-native (checked with Expo SDK 58).
// Notification settings: a list of switches and one choice that save as soon as they change.
// A change shows at once; if saving fails it goes back and a snackbar says why, with Retry.
// Uses ./ToggleRow, ./SegmentedControl 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 { ScrollView, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { SegmentedControl } from './SegmentedControl';
import { Snackbar, useSnackbar } from './Snackbar';
import { ToggleRow } from './ToggleRow';
import { colors, radius } from './theme';
export type Values = Record<string, boolean | string>;
export type SaveResult = 'saved' | 'failed' | 'offline';
export type SettingsApi = {
/** Loads the current values. Throw if it fails. */
load: () => Promise<Values>;
/** Saves one changed value. A call that throws counts as offline. */
save: (key: string, value: boolean | string) => Promise<SaveResult>;
};
/** A switch. `under` names the master switch it depends on: while that is off, this row is disabled. */
export type ToggleSetting = { key: string; label: string; description?: string; under?: string };
export type ChoiceSetting = { key: string; label: string; options: { value: string; label: string }[] };
export type SettingsState = {
status: 'loading' | 'load-failed' | 'ready';
values: Values;
/** Keys being saved. */
pending: string[];
/** The last change that could not be saved, and was undone. */
failed?: { key: string; value: boolean | string; offline: boolean };
};
export type SettingsStep = 'loading' | 'load-failed' | 'ready' | 'saving' | 'reverted' | 'offline';
/** Every word the screen shows. Override them for another language. */
export type NotificationSettingsLabels = {
loadFailedTitle: string;
loadFailedSub: string;
tryAgain: string;
offlineUndo: string;
saveFailedUndo: string;
retry: string;
loading: string;
};
const defaultLabels: NotificationSettingsLabels = {
loadFailedTitle: "Couldn't load your settings",
loadFailedSub: 'Check your connection and try again.',
tryAgain: 'Try again',
offlineUndo: "You're offline. The change was undone.",
saveFailedUndo: "Couldn't save. The change was undone.",
retry: 'Retry',
loading: 'Loading',
};
export type NotificationSettingsProps = {
/** load and save, connected to your backend. */
api: SettingsApi;
/** The switches, in order. */
toggles: ToggleSetting[];
/** Heading above the notification settings. */
title?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationSettingsLabels>;
/** One choice under the switches, such as how often to email a summary. */
choice?: ChoiceSetting;
/** Where to start. Defaults to loading; pass a state in tests. */
initialState?: SettingsState;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: SettingsStep) => void;
/** Called after one changed setting has been successfully saved. */
onSaved?: (key: string, value: boolean | string) => void;
};
export function NotificationSettings({ api, toggles, title = 'Notifications', labels, choice, initialState, onStepChange, onSaved }: NotificationSettingsProps) {
const words = { ...defaultLabels, ...labels };
const [s, setS] = useState<SettingsState>(initialState ?? { status: 'loading', values: {}, pending: [] });
const snack = useSnackbar();
const changed = useRef(onStepChange);
changed.current = onStepChange;
const saved = useRef(onSaved);
saved.current = onSaved;
const generation = useRef(0);
const saving = useRef(new Set<string>(initialState?.pending));
const step: SettingsStep = s.status !== 'ready' ? s.status : s.pending.length ? 'saving' : s.failed ? (s.failed.offline ? 'offline' : 'reverted') : 'ready';
useEffect(() => changed.current?.(step), [step]);
// An undone change is explained at the bottom, with Retry.
const { failed } = s;
useEffect(() => {
if (!failed) return;
snack.show({
text: failed.offline ? words.offlineUndo : words.saveFailedUndo,
tone: 'error',
action: { label: words.retry, onPress: () => change(failed.key, failed.value) },
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [failed]);
async function load() {
const id = ++generation.current;
saving.current.clear();
setS({ status: 'loading', values: {}, pending: [] });
try {
const values = await api.load();
if (generation.current === id) setS({ status: 'ready', values, pending: [] });
} catch {
if (generation.current === id) setS({ status: 'load-failed', values: {}, pending: [] });
}
}
useEffect(() => {
if (!initialState) void load();
return () => { generation.current++; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function change(key: string, value: boolean | string) {
if (saving.current.has(key)) return;
saving.current.add(key);
const id = generation.current;
const before = s.values[key];
setS((p) => ({ ...p, failed: undefined, values: { ...p.values, [key]: value }, pending: [...p.pending, key] }));
let result: SaveResult;
try { result = await api.save(key, value); }
catch { result = 'offline'; }
if (generation.current !== id) return;
saving.current.delete(key);
setS((p) => {
const pending = p.pending.filter(k => k !== key);
if (result === 'saved') return { ...p, pending };
const values = { ...p.values };
if (before === undefined) delete values[key];
else values[key] = before;
return { ...p, values, pending, failed: { key, value, offline: result === 'offline' } };
});
if (result === 'saved') saved.current?.(key, value);
}
if (s.status === 'load-failed') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title}>{words.loadFailedTitle}</Text>
<Text style={styles.sub}>{words.loadFailedSub}</Text>
<Button title={words.tryAgain} variant="secondary" onPress={load} style={styles.retry} />
</View>
);
}
const on = (key: string) => s.values[key] === true;
return (
<View style={styles.fill}>
<ScrollView contentContainerStyle={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<View style={styles.group}>
{toggles.map((t, i) => (
<View key={t.key}>
{i ? <View style={styles.line} /> : null}
{s.status === 'loading' ? (
<Skeleton label={words.loading} />
) : (
<ToggleRow
label={t.label}
description={t.description}
value={on(t.key)}
pending={s.pending.includes(t.key)}
disabled={!!t.under && !on(t.under)}
onValueChange={(v) => change(t.key, v)}
/>
)}
</View>
))}
</View>
{choice ? (
<View style={styles.choice}>
<Text style={styles.choiceLabel}>{choice.label}</Text>
<SegmentedControl
options={choice.options}
value={String(s.values[choice.key] ?? choice.options[0].value)}
onChange={(v) => change(choice.key, v)}
disabled={s.status === 'loading' || s.pending.includes(choice.key)}
accessibilityLabel={choice.label}
/>
</View>
) : null}
</ScrollView>
<Snackbar
{...snack.props}
onDismiss={() => {
setS((p) => ({ ...p, failed: undefined }));
snack.props.onDismiss();
}}
/>
</View>
);
}
function Skeleton({ label }: { label: string }) {
return (
<View style={styles.skeleton} accessibilityLabel={label}>
<View style={styles.skeletonText}>
<View style={[styles.bone, { width: '55%' }]} />
<View style={[styles.bone, styles.boneSmall, { width: '35%' }]} />
</View>
<View style={[styles.bone, styles.boneSwitch]} />
</View>
);
}
const styles = StyleSheet.create({
fill: { flex: 1 },
screen: { paddingHorizontal: 16, paddingTop: 32, paddingBottom: 96 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 },
title: { marginHorizontal: 8, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground, textAlign: 'left' },
sub: { marginTop: 8, fontSize: 16, color: colors.onSurfaceVariant },
retry: { marginTop: 24, alignSelf: 'stretch' },
group: { marginTop: 20, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant, overflow: 'hidden' },
line: { height: 1, marginLeft: 16, backgroundColor: colors.outlineVariant },
choice: { marginTop: 28, marginHorizontal: 8, gap: 10 },
choiceLabel: { fontSize: 14, fontWeight: '500', color: colors.onSurfaceVariant },
skeleton: { minHeight: 56, paddingHorizontal: 16, paddingVertical: 14, flexDirection: 'row', alignItems: 'center', gap: 12 },
skeletonText: { flex: 1, gap: 8 },
bone: { height: 12, borderRadius: 6, backgroundColor: colors.surfaceVariant },
boneSmall: { height: 10 },
boneSwitch: { width: 50, height: 30, borderRadius: 15 },
});
// Notification settings: a list of switches and one choice that save as soon as they change.
// A change shows at once; if saving fails it goes back and a snackbar says why, with Retry.
// Uses ./ToggleRow, ./SegmentedControl 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 { ScrollView, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { SegmentedControl } from './SegmentedControl';
import { Snackbar, useSnackbar } from './Snackbar';
import { ToggleRow } from './ToggleRow';
import { colors, radius } from './theme';
export type Values = Record<string, boolean | string>;
export type SaveResult = 'saved' | 'failed' | 'offline';
export type SettingsApi = {
/** Loads the current values. Throw if it fails. */
load: () => Promise<Values>;
/** Saves one changed value. A call that throws counts as offline. */
save: (key: string, value: boolean | string) => Promise<SaveResult>;
};
/** A switch. `under` names the master switch it depends on: while that is off, this row is disabled. */
export type ToggleSetting = { key: string; label: string; description?: string; under?: string };
export type ChoiceSetting = { key: string; label: string; options: { value: string; label: string }[] };
export type SettingsState = {
status: 'loading' | 'load-failed' | 'ready';
values: Values;
/** Keys being saved. */
pending: string[];
/** The last change that could not be saved, and was undone. */
failed?: { key: string; value: boolean | string; offline: boolean };
};
export type SettingsStep = 'loading' | 'load-failed' | 'ready' | 'saving' | 'reverted' | 'offline';
/** Every word the screen shows. Override them for another language. */
export type NotificationSettingsLabels = {
loadFailedTitle: string;
loadFailedSub: string;
tryAgain: string;
offlineUndo: string;
saveFailedUndo: string;
retry: string;
loading: string;
};
const defaultLabels: NotificationSettingsLabels = {
loadFailedTitle: "Couldn't load your settings",
loadFailedSub: 'Check your connection and try again.',
tryAgain: 'Try again',
offlineUndo: "You're offline. The change was undone.",
saveFailedUndo: "Couldn't save. The change was undone.",
retry: 'Retry',
loading: 'Loading',
};
export type NotificationSettingsProps = {
/** load and save, connected to your backend. */
api: SettingsApi;
/** The switches, in order. */
toggles: ToggleSetting[];
/** Heading above the notification settings. */
title?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationSettingsLabels>;
/** One choice under the switches, such as how often to email a summary. */
choice?: ChoiceSetting;
/** Where to start. Defaults to loading; pass a state in tests. */
initialState?: SettingsState;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: SettingsStep) => void;
/** Called after one changed setting has been successfully saved. */
onSaved?: (key: string, value: boolean | string) => void;
};
export function NotificationSettings({ api, toggles, title = 'Notifications', labels, choice, initialState, onStepChange, onSaved }: NotificationSettingsProps) {
const words = { ...defaultLabels, ...labels };
const [s, setS] = useState<SettingsState>(initialState ?? { status: 'loading', values: {}, pending: [] });
const snack = useSnackbar();
const changed = useRef(onStepChange);
changed.current = onStepChange;
const saved = useRef(onSaved);
saved.current = onSaved;
const generation = useRef(0);
const saving = useRef(new Set<string>(initialState?.pending));
const step: SettingsStep = s.status !== 'ready' ? s.status : s.pending.length ? 'saving' : s.failed ? (s.failed.offline ? 'offline' : 'reverted') : 'ready';
useEffect(() => changed.current?.(step), [step]);
// An undone change is explained at the bottom, with Retry.
const { failed } = s;
useEffect(() => {
if (!failed) return;
snack.show({
text: failed.offline ? words.offlineUndo : words.saveFailedUndo,
tone: 'error',
action: { label: words.retry, onPress: () => change(failed.key, failed.value) },
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [failed]);
async function load() {
const id = ++generation.current;
saving.current.clear();
setS({ status: 'loading', values: {}, pending: [] });
try {
const values = await api.load();
if (generation.current === id) setS({ status: 'ready', values, pending: [] });
} catch {
if (generation.current === id) setS({ status: 'load-failed', values: {}, pending: [] });
}
}
useEffect(() => {
if (!initialState) void load();
return () => { generation.current++; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function change(key: string, value: boolean | string) {
if (saving.current.has(key)) return;
saving.current.add(key);
const id = generation.current;
const before = s.values[key];
setS((p) => ({ ...p, failed: undefined, values: { ...p.values, [key]: value }, pending: [...p.pending, key] }));
let result: SaveResult;
try { result = await api.save(key, value); }
catch { result = 'offline'; }
if (generation.current !== id) return;
saving.current.delete(key);
setS((p) => {
const pending = p.pending.filter(k => k !== key);
if (result === 'saved') return { ...p, pending };
const values = { ...p.values };
if (before === undefined) delete values[key];
else values[key] = before;
return { ...p, values, pending, failed: { key, value, offline: result === 'offline' } };
});
if (result === 'saved') saved.current?.(key, value);
}
if (s.status === 'load-failed') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title}>{words.loadFailedTitle}</Text>
<Text style={styles.sub}>{words.loadFailedSub}</Text>
<Button title={words.tryAgain} variant="secondary" onPress={load} style={styles.retry} />
</View>
);
}
const on = (key: string) => s.values[key] === true;
return (
<View style={styles.fill}>
<ScrollView contentContainerStyle={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<View style={styles.group}>
{toggles.map((t, i) => (
<View key={t.key}>
{i ? <View style={styles.line} /> : null}
{s.status === 'loading' ? (
<Skeleton label={words.loading} />
) : (
<ToggleRow
label={t.label}
description={t.description}
value={on(t.key)}
pending={s.pending.includes(t.key)}
disabled={!!t.under && !on(t.under)}
onValueChange={(v) => change(t.key, v)}
/>
)}
</View>
))}
</View>
{choice ? (
<View style={styles.choice}>
<Text style={styles.choiceLabel}>{choice.label}</Text>
<SegmentedControl
options={choice.options}
value={String(s.values[choice.key] ?? choice.options[0].value)}
onChange={(v) => change(choice.key, v)}
disabled={s.status === 'loading' || s.pending.includes(choice.key)}
accessibilityLabel={choice.label}
/>
</View>
) : null}
</ScrollView>
<Snackbar
{...snack.props}
onDismiss={() => {
setS((p) => ({ ...p, failed: undefined }));
snack.props.onDismiss();
}}
/>
</View>
);
}
function Skeleton({ label }: { label: string }) {
return (
<View style={styles.skeleton} accessibilityLabel={label}>
<View style={styles.skeletonText}>
<View style={[styles.bone, { width: '55%' }]} />
<View style={[styles.bone, styles.boneSmall, { width: '35%' }]} />
</View>
<View style={[styles.bone, styles.boneSwitch]} />
</View>
);
}
const styles = StyleSheet.create({
fill: { flex: 1 },
screen: { paddingHorizontal: 16, paddingTop: 32, paddingBottom: 96 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 },
title: { marginHorizontal: 8, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground, textAlign: 'left' },
sub: { marginTop: 8, fontSize: 16, color: colors.onSurfaceVariant },
retry: { marginTop: 24, alignSelf: 'stretch' },
group: { marginTop: 20, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant, overflow: 'hidden' },
line: { height: 1, marginLeft: 16, backgroundColor: colors.outlineVariant },
choice: { marginTop: 28, marginHorizontal: 8, gap: 10 },
choiceLabel: { fontSize: 14, fontWeight: '500', color: colors.onSurfaceVariant },
skeleton: { minHeight: 56, paddingHorizontal: 16, paddingVertical: 14, flexDirection: 'row', alignItems: 'center', gap: 12 },
skeletonText: { flex: 1, gap: 8 },
bone: { height: 12, borderRadius: 6, backgroundColor: colors.surfaceVariant },
boneSmall: { height: 10 },
boneSwitch: { width: 50, height: 30, borderRadius: 15 },
});
// Toggle row: a setting with a label, an optional description and a switch. The whole row is the tap target.
// While a change is being saved the switch shows the new value and a spinner, and ignores more taps.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { ActivityIndicator, Pressable, StyleSheet, Switch, Text, View } from 'react-native';
import { colors } from './theme';
export type ToggleRowProps = {
/** What the setting turns on, such as "Push notifications". */
label: string;
/** One line under the label about what changes. */
description?: string;
/** On or off. */
value: boolean;
/** Called with the new value when the row or the switch is tapped. */
onValueChange: (value: boolean) => void;
/** Grey and cannot be changed. Say why in the description. */
disabled?: boolean;
/** The change is being saved: shows a spinner and ignores taps until it is cleared. */
pending?: boolean;
};
type CopyInkProps = { copyTestIDs?: { label?: string; description?: string } };
export function ToggleRow({ label, description, value, onValueChange, disabled = false, pending = false, copyTestIDs }: ToggleRowProps & CopyInkProps) {
const locked = disabled || pending;
return (
<Pressable
onPress={locked ? undefined : () => onValueChange(!value)}
disabled={locked}
accessibilityRole="switch"
accessibilityLabel={label}
accessibilityHint={description}
aria-checked={value}
aria-disabled={locked}
aria-busy={pending}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
<View style={styles.text}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
{description ? <Text testID={copyTestIDs?.description} style={styles.description}>{description}</Text> : null}
</View>
{pending ? <ActivityIndicator size="small" color={colors.onSurfaceVariant} /> : null}
<Switch
value={value}
onValueChange={locked ? undefined : onValueChange}
disabled={locked}
trackColor={{ false: colors.outlineVariant, true: colors.primary }}
thumbColor={colors.surface}
ios_backgroundColor={colors.outlineVariant}
// The row carries the label and state for screen readers.
importantForAccessibility="no-hide-descendants"
accessibilityElementsHidden
/>
</Pressable>
);
}
const styles = StyleSheet.create({
row: { minHeight: 56, paddingVertical: 12, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', gap: 12 },
pressed: { backgroundColor: colors.surfaceVariant },
text: { flex: 1, gap: 2 },
label: { fontSize: 17, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
description: { fontSize: 13, color: colors.onSurfaceVariant },
});
// Toggle row: a setting with a label, an optional description and a switch. The whole row is the tap target.
// While a change is being saved the switch shows the new value and a spinner, and ignores more taps.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { ActivityIndicator, Pressable, StyleSheet, Switch, Text, View } from 'react-native';
import { colors } from './theme';
export type ToggleRowProps = {
/** What the setting turns on, such as "Push notifications". */
label: string;
/** One line under the label about what changes. */
description?: string;
/** On or off. */
value: boolean;
/** Called with the new value when the row or the switch is tapped. */
onValueChange: (value: boolean) => void;
/** Grey and cannot be changed. Say why in the description. */
disabled?: boolean;
/** The change is being saved: shows a spinner and ignores taps until it is cleared. */
pending?: boolean;
};
type CopyInkProps = { copyTestIDs?: { label?: string; description?: string } };
export function ToggleRow({ label, description, value, onValueChange, disabled = false, pending = false, copyTestIDs }: ToggleRowProps & CopyInkProps) {
const locked = disabled || pending;
return (
<Pressable
onPress={locked ? undefined : () => onValueChange(!value)}
disabled={locked}
accessibilityRole="switch"
accessibilityLabel={label}
accessibilityHint={description}
aria-checked={value}
aria-disabled={locked}
aria-busy={pending}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
<View style={styles.text}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
{description ? <Text testID={copyTestIDs?.description} style={styles.description}>{description}</Text> : null}
</View>
{pending ? <ActivityIndicator size="small" color={colors.onSurfaceVariant} /> : null}
<Switch
value={value}
onValueChange={locked ? undefined : onValueChange}
disabled={locked}
trackColor={{ false: colors.outlineVariant, true: colors.primary }}
thumbColor={colors.surface}
ios_backgroundColor={colors.outlineVariant}
// The row carries the label and state for screen readers.
importantForAccessibility="no-hide-descendants"
accessibilityElementsHidden
/>
</Pressable>
);
}
const styles = StyleSheet.create({
row: { minHeight: 56, paddingVertical: 12, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', gap: 12 },
pressed: { backgroundColor: colors.surfaceVariant },
text: { flex: 1, gap: 2 },
label: { fontSize: 17, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
description: { fontSize: 13, color: colors.onSurfaceVariant },
});
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// 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 { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// 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 { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
// 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 },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
Usage
import { NotificationSettings, type SettingsApi } from '@/components/mobilens/NotificationSettings';
const api: SettingsApi = {
async load() {
const res = await fetch('https://api.example.com/me/notifications');
if (!res.ok) throw new Error(String(res.status));
return res.json();
},
async save(key, value) {
const res = await fetch('https://api.example.com/me/notifications', { method: 'PATCH', body: JSON.stringify({ [key]: value }) });
return res.ok ? 'saved' : 'failed';
},
};
export function NotificationSettingsScreen() {
return (
<NotificationSettings
api={api}
toggles={[
{ key: 'push', label: 'Push notifications', description: 'On this phone' },
{ key: 'replies', label: 'Replies', under: 'push' },
{ key: 'mentions', label: 'Mentions', under: 'push' },
]}
choice={{ key: 'digest', label: 'Email summary', options: [{ value: 'off', label: 'Off' }, { value: 'weekly', label: 'Weekly' }] }}
/>
);
}
import { NotificationSettings, type SettingsApi } from '@/components/mobilens/NotificationSettings';
const api: SettingsApi = {
async load() {
const res = await fetch('https://api.example.com/me/notifications');
if (!res.ok) throw new Error(String(res.status));
return res.json();
},
async save(key, value) {
const res = await fetch('https://api.example.com/me/notifications', { method: 'PATCH', body: JSON.stringify({ [key]: value }) });
return res.ok ? 'saved' : 'failed';
},
};
export function NotificationSettingsScreen() {
return (
<NotificationSettings
api={api}
toggles={[
{ key: 'push', label: 'Push notifications', description: 'On this phone' },
{ key: 'replies', label: 'Replies', under: 'push' },
{ key: 'mentions', label: 'Mentions', under: 'push' },
]}
choice={{ key: 'digest', label: 'Email summary', options: [{ value: 'off', label: 'Off' }, { value: 'weekly', label: 'Weekly' }] }}
/>
);
}
API
| Prop | Type | Default | Description |
|---|---|---|---|
| api | SettingsApi | – | load and save, connected to your backend. |
| toggles | ToggleSetting[] | – | The switches, in order. |
| title? | string | 'Notifications' | Heading above the notification settings. |
| labels? | Partial<NotificationSettingsLabels> | – | The words the screen shows. Pass a partial set to change only some of them. |
| choice? | ChoiceSetting | – | One choice under the switches, such as how often to email a summary. |
| initialState? | SettingsState | – | Where to start. Defaults to loading; pass a state in tests. |
| onStepChange? | (step: SettingsStep) => void | – | Called with every step the screen enters, for analytics or logging. |
| onSaved? | (key: string, value: boolean | string) => void | – | Called after one changed setting has been successfully saved. |
Controls in this flow
Add the "Notification settings" 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/NotificationSettings.tsx ---
// Notification settings: a list of switches and one choice that save as soon as they change.
// A change shows at once; if saving fails it goes back and a snackbar says why, with Retry.
// Uses ./ToggleRow, ./SegmentedControl 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 { ScrollView, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { SegmentedControl } from './SegmentedControl';
import { Snackbar, useSnackbar } from './Snackbar';
import { ToggleRow } from './ToggleRow';
import { colors, radius } from './theme';
export type Values = Record<string, boolean | string>;
export type SaveResult = 'saved' | 'failed' | 'offline';
export type SettingsApi = {
/** Loads the current values. Throw if it fails. */
load: () => Promise<Values>;
/** Saves one changed value. A call that throws counts as offline. */
save: (key: string, value: boolean | string) => Promise<SaveResult>;
};
/** A switch. `under` names the master switch it depends on: while that is off, this row is disabled. */
export type ToggleSetting = { key: string; label: string; description?: string; under?: string };
export type ChoiceSetting = { key: string; label: string; options: { value: string; label: string }[] };
export type SettingsState = {
status: 'loading' | 'load-failed' | 'ready';
values: Values;
/** Keys being saved. */
pending: string[];
/** The last change that could not be saved, and was undone. */
failed?: { key: string; value: boolean | string; offline: boolean };
};
export type SettingsStep = 'loading' | 'load-failed' | 'ready' | 'saving' | 'reverted' | 'offline';
/** Every word the screen shows. Override them for another language. */
export type NotificationSettingsLabels = {
loadFailedTitle: string;
loadFailedSub: string;
tryAgain: string;
offlineUndo: string;
saveFailedUndo: string;
retry: string;
loading: string;
};
const defaultLabels: NotificationSettingsLabels = {
loadFailedTitle: "Couldn't load your settings",
loadFailedSub: 'Check your connection and try again.',
tryAgain: 'Try again',
offlineUndo: "You're offline. The change was undone.",
saveFailedUndo: "Couldn't save. The change was undone.",
retry: 'Retry',
loading: 'Loading',
};
export type NotificationSettingsProps = {
/** load and save, connected to your backend. */
api: SettingsApi;
/** The switches, in order. */
toggles: ToggleSetting[];
/** Heading above the notification settings. */
title?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationSettingsLabels>;
/** One choice under the switches, such as how often to email a summary. */
choice?: ChoiceSetting;
/** Where to start. Defaults to loading; pass a state in tests. */
initialState?: SettingsState;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: SettingsStep) => void;
/** Called after one changed setting has been successfully saved. */
onSaved?: (key: string, value: boolean | string) => void;
};
export function NotificationSettings({ api, toggles, title = 'Notifications', labels, choice, initialState, onStepChange, onSaved }: NotificationSettingsProps) {
const words = { ...defaultLabels, ...labels };
const [s, setS] = useState<SettingsState>(initialState ?? { status: 'loading', values: {}, pending: [] });
const snack = useSnackbar();
const changed = useRef(onStepChange);
changed.current = onStepChange;
const saved = useRef(onSaved);
saved.current = onSaved;
const generation = useRef(0);
const saving = useRef(new Set<string>(initialState?.pending));
const step: SettingsStep = s.status !== 'ready' ? s.status : s.pending.length ? 'saving' : s.failed ? (s.failed.offline ? 'offline' : 'reverted') : 'ready';
useEffect(() => changed.current?.(step), [step]);
// An undone change is explained at the bottom, with Retry.
const { failed } = s;
useEffect(() => {
if (!failed) return;
snack.show({
text: failed.offline ? words.offlineUndo : words.saveFailedUndo,
tone: 'error',
action: { label: words.retry, onPress: () => change(failed.key, failed.value) },
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [failed]);
async function load() {
const id = ++generation.current;
saving.current.clear();
setS({ status: 'loading', values: {}, pending: [] });
try {
const values = await api.load();
if (generation.current === id) setS({ status: 'ready', values, pending: [] });
} catch {
if (generation.current === id) setS({ status: 'load-failed', values: {}, pending: [] });
}
}
useEffect(() => {
if (!initialState) void load();
return () => { generation.current++; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function change(key: string, value: boolean | string) {
if (saving.current.has(key)) return;
saving.current.add(key);
const id = generation.current;
const before = s.values[key];
setS((p) => ({ ...p, failed: undefined, values: { ...p.values, [key]: value }, pending: [...p.pending, key] }));
let result: SaveResult;
try { result = await api.save(key, value); }
catch { result = 'offline'; }
if (generation.current !== id) return;
saving.current.delete(key);
setS((p) => {
const pending = p.pending.filter(k => k !== key);
if (result === 'saved') return { ...p, pending };
const values = { ...p.values };
if (before === undefined) delete values[key];
else values[key] = before;
return { ...p, values, pending, failed: { key, value, offline: result === 'offline' } };
});
if (result === 'saved') saved.current?.(key, value);
}
if (s.status === 'load-failed') {
return (
<View style={[styles.screen, styles.center]}>
<Text style={styles.title}>{words.loadFailedTitle}</Text>
<Text style={styles.sub}>{words.loadFailedSub}</Text>
<Button title={words.tryAgain} variant="secondary" onPress={load} style={styles.retry} />
</View>
);
}
const on = (key: string) => s.values[key] === true;
return (
<View style={styles.fill}>
<ScrollView contentContainerStyle={styles.screen}>
<Text style={styles.title} accessibilityRole="header">{title}</Text>
<View style={styles.group}>
{toggles.map((t, i) => (
<View key={t.key}>
{i ? <View style={styles.line} /> : null}
{s.status === 'loading' ? (
<Skeleton label={words.loading} />
) : (
<ToggleRow
label={t.label}
description={t.description}
value={on(t.key)}
pending={s.pending.includes(t.key)}
disabled={!!t.under && !on(t.under)}
onValueChange={(v) => change(t.key, v)}
/>
)}
</View>
))}
</View>
{choice ? (
<View style={styles.choice}>
<Text style={styles.choiceLabel}>{choice.label}</Text>
<SegmentedControl
options={choice.options}
value={String(s.values[choice.key] ?? choice.options[0].value)}
onChange={(v) => change(choice.key, v)}
disabled={s.status === 'loading' || s.pending.includes(choice.key)}
accessibilityLabel={choice.label}
/>
</View>
) : null}
</ScrollView>
<Snackbar
{...snack.props}
onDismiss={() => {
setS((p) => ({ ...p, failed: undefined }));
snack.props.onDismiss();
}}
/>
</View>
);
}
function Skeleton({ label }: { label: string }) {
return (
<View style={styles.skeleton} accessibilityLabel={label}>
<View style={styles.skeletonText}>
<View style={[styles.bone, { width: '55%' }]} />
<View style={[styles.bone, styles.boneSmall, { width: '35%' }]} />
</View>
<View style={[styles.bone, styles.boneSwitch]} />
</View>
);
}
const styles = StyleSheet.create({
fill: { flex: 1 },
screen: { paddingHorizontal: 16, paddingTop: 32, paddingBottom: 96 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 },
title: { marginHorizontal: 8, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground, textAlign: 'left' },
sub: { marginTop: 8, fontSize: 16, color: colors.onSurfaceVariant },
retry: { marginTop: 24, alignSelf: 'stretch' },
group: { marginTop: 20, borderRadius: radius.md, backgroundColor: colors.surface, borderWidth: 1, borderColor: colors.outlineVariant, overflow: 'hidden' },
line: { height: 1, marginLeft: 16, backgroundColor: colors.outlineVariant },
choice: { marginTop: 28, marginHorizontal: 8, gap: 10 },
choiceLabel: { fontSize: 14, fontWeight: '500', color: colors.onSurfaceVariant },
skeleton: { minHeight: 56, paddingHorizontal: 16, paddingVertical: 14, flexDirection: 'row', alignItems: 'center', gap: 12 },
skeletonText: { flex: 1, gap: 8 },
bone: { height: 12, borderRadius: 6, backgroundColor: colors.surfaceVariant },
boneSmall: { height: 10 },
boneSwitch: { width: 50, height: 30, borderRadius: 15 },
});
--- end of NotificationSettings.tsx ---
--- components/mobilens/ToggleRow.tsx ---
// Toggle row: a setting with a label, an optional description and a switch. The whole row is the tap target.
// While a change is being saved the switch shows the new value and a spinner, and ignores more taps.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { ActivityIndicator, Pressable, StyleSheet, Switch, Text, View } from 'react-native';
import { colors } from './theme';
export type ToggleRowProps = {
/** What the setting turns on, such as "Push notifications". */
label: string;
/** One line under the label about what changes. */
description?: string;
/** On or off. */
value: boolean;
/** Called with the new value when the row or the switch is tapped. */
onValueChange: (value: boolean) => void;
/** Grey and cannot be changed. Say why in the description. */
disabled?: boolean;
/** The change is being saved: shows a spinner and ignores taps until it is cleared. */
pending?: boolean;
};
type CopyInkProps = { copyTestIDs?: { label?: string; description?: string } };
export function ToggleRow({ label, description, value, onValueChange, disabled = false, pending = false, copyTestIDs }: ToggleRowProps & CopyInkProps) {
const locked = disabled || pending;
return (
<Pressable
onPress={locked ? undefined : () => onValueChange(!value)}
disabled={locked}
accessibilityRole="switch"
accessibilityLabel={label}
accessibilityHint={description}
aria-checked={value}
aria-disabled={locked}
aria-busy={pending}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
<View style={styles.text}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
{description ? <Text testID={copyTestIDs?.description} style={styles.description}>{description}</Text> : null}
</View>
{pending ? <ActivityIndicator size="small" color={colors.onSurfaceVariant} /> : null}
<Switch
value={value}
onValueChange={locked ? undefined : onValueChange}
disabled={locked}
trackColor={{ false: colors.outlineVariant, true: colors.primary }}
thumbColor={colors.surface}
ios_backgroundColor={colors.outlineVariant}
// The row carries the label and state for screen readers.
importantForAccessibility="no-hide-descendants"
accessibilityElementsHidden
/>
</Pressable>
);
}
const styles = StyleSheet.create({
row: { minHeight: 56, paddingVertical: 12, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', gap: 12 },
pressed: { backgroundColor: colors.surfaceVariant },
text: { flex: 1, gap: 2 },
label: { fontSize: 17, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
description: { fontSize: 13, color: colors.onSurfaceVariant },
});
--- end of ToggleRow.tsx ---
--- components/mobilens/SegmentedControl.tsx ---
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// 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 { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
--- end of SegmentedControl.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 ---
--- 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 ---
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 { NotificationSettings, type SettingsApi } from '@/components/mobilens/NotificationSettings';
const api: SettingsApi = {
async load() {
const res = await fetch('https://api.example.com/me/notifications');
if (!res.ok) throw new Error(String(res.status));
return res.json();
},
async save(key, value) {
const res = await fetch('https://api.example.com/me/notifications', { method: 'PATCH', body: JSON.stringify({ [key]: value }) });
return res.ok ? 'saved' : 'failed';
},
};
export function NotificationSettingsScreen() {
return (
<NotificationSettings
api={api}
toggles={[
{ key: 'push', label: 'Push notifications', description: 'On this phone' },
{ key: 'replies', label: 'Replies', under: 'push' },
{ key: 'mentions', label: 'Mentions', under: 'push' },
]}
choice={{ key: 'digest', label: 'Email summary', options: [{ value: 'off', label: 'Off' }, { value: 'weekly', label: 'Weekly' }] }}
/>
);
}
STATES: all 6 must work in the screen where you use it
- Loading: when the screen opens. Grey placeholder rows in the shape of the real ones, so nothing jumps when they arrive. Next: Ready, Couldn't load.
- Couldn't load: when loading failed. No switches are shown: a switch with an unknown value would lie. Next: Loading.
- Ready: when the values are loaded. There is no Save button: each change saves itself. While a master switch is off, the rows that depend on it are disabled. Next: Saving.
- Saving: when A value was changed. The new value shows at once, with a spinner on that row only. Other rows can still be changed. Next: Ready, Undone, Offline.
- Undone: when the backend refused the change. The row goes back to what it was; a snackbar says so and offers Retry. Next: Saving.
- Offline: when the save could not reach the backend. Same as Undone, and the message says it was the connection. Next: Saving.
ACCESSIBILITY
- Each row is one switch for screen readers, announced busy while it saves.
- The undo message is announced, with Retry.
- The loading rows are announced as loading, not as empty switches.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.