屏幕
配色方案
明暗
圆角
颜色
这个流程的所有画面
询问之前
回答
- 何时出现
- 怎么离开
- 下一步
- 行为规则
把这 3 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// Notification permission: explain first, then ask the system once, and handle every answer, including the one
// where the system will no longer ask and the only way is Settings. Uses ./Button.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AppState, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { colors, radius } from './theme';
/** undetermined: never asked. denied: said no, can be asked again (Android). blocked: only Settings can turn it on. */
export type PermissionStatus = 'undetermined' | 'granted' | 'denied' | 'blocked';
export type PermissionApi = {
/** The current status, without asking. */
get: () => Promise<PermissionStatus>;
/** Shows the system prompt and returns the answer. */
request: () => Promise<PermissionStatus>;
/** Opens this app's page in the system Settings. */
openSettings: () => void;
};
export type PermissionStep = 'ask' | 'asking' | 'granted' | 'denied' | 'blocked';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type NotificationPermissionLabels = {
askTitle: string;
askBody: string;
grantedTitle: string;
grantedBody: string;
deniedTitle: string;
deniedBody: string;
blockedTitle: string;
blockedBody: string;
notNow: string;
openSettings: string;
continueWithout: string;
continue: string;
sampleFrom: string;
sampleMessage: string;
now: string;
};
const defaultLabels: NotificationPermissionLabels = {
askTitle: 'Know when they reply',
askBody: 'Get a notification when someone replies or mentions you. Nothing else, and you can change it any time.',
grantedTitle: "You're all set",
grantedBody: "We'll let you know when someone replies or mentions you.",
deniedTitle: 'No notifications for now',
deniedBody: "That's fine. You can turn them on later from your profile.",
blockedTitle: 'Notifications are off',
blockedBody: 'To get replies, turn on notifications for {app} in Settings. We\'ll notice when you come back.',
notNow: 'Not now',
openSettings: 'Open Settings',
continueWithout: 'Continue without',
continue: 'Continue',
sampleFrom: 'Maya replied to your comment',
sampleMessage: '“Love this, can you share the file?”',
now: 'now',
};
/** 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 NotificationPermissionProps = {
/** get, request and openSettings, connected to the platform (see Usage). */
permissions: PermissionApi;
/** Called when the user moves on, with whether notifications are on. */
onDone: (enabled: boolean) => void;
/** The app's name, used in the copy. */
appName: string;
/** Heading on the explanation screen before requesting permission. */
title?: string;
/** Label for the button that opens the system permission prompt. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationPermissionLabels>;
/** Where to start. Defaults to checking the current status; pass a step in tests. */
initialStep?: PermissionStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: PermissionStep) => void;
};
export function NotificationPermission({ permissions, onDone, appName, title, primaryLabel = 'Turn on notifications', labels, initialStep, onStepChange }: NotificationPermissionProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<PermissionStep | null>(initialStep ?? null);
const generation = useRef(0);
const requesting = useRef(false);
const done = useRef(onDone);
done.current = onDone;
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => {
if (step) changed.current?.(step);
}, [step]);
// Already decided: skip the explanation. Granted means there is nothing to ask.
useEffect(() => {
const id = ++generation.current;
requesting.current = false;
setStep(initialStep ?? null);
if (!initialStep) {
Promise.resolve().then(() => permissions.get()).then(status => {
if (id !== generation.current) return;
if (status === 'granted') done.current(true);
else setStep(status === 'undetermined' ? 'ask' : status);
}, () => { if (id === generation.current) setStep('ask'); });
}
return () => { generation.current++; };
}, [permissions, initialStep]);
// Back from Settings: check again, so turning it on there moves the screen on by itself.
useEffect(() => {
if (step !== 'blocked') return;
let live = true;
const sub = AppState.addEventListener('change', (state) => {
if (state === 'active') void Promise.resolve().then(() => permissions.get()).then(status => {
if (live && status === 'granted') setStep('granted');
}, () => {});
});
return () => { live = false; sub.remove(); };
}, [step, permissions]);
async function ask() {
if (requesting.current) return;
const id = generation.current;
requesting.current = true;
setStep('asking');
try {
const answer = await permissions.request();
if (id === generation.current) setStep(answer === 'undetermined' ? 'ask' : answer);
} catch {
if (id === generation.current) setStep('ask');
} finally {
if (id === generation.current) requesting.current = false;
}
}
if (!step) return <View style={styles.screen} />;
const copy = copyFor(step, t, appName);
const beforeAnswer = step === 'ask' || step === 'asking';
return (
<View style={styles.screen}>
<View style={styles.top}>
<Preview appName={appName} muted={step === 'denied' || step === 'blocked'} labels={t} />
<Text style={styles.title} accessibilityRole="header">{beforeAnswer ? title ?? copy.title : copy.title}</Text>
<Text style={styles.sub}>{copy.body}</Text>
</View>
<View style={styles.actions}>
{beforeAnswer ? (
<>
<Button title={primaryLabel} onPress={ask} loading={step === 'asking'} />
<Button title={t.notNow} variant="ghost" onPress={() => onDone(false)} disabled={step === 'asking'} />
</>
) : step === 'blocked' ? (
<>
<Button title={t.openSettings} onPress={permissions.openSettings} />
<Button title={t.continueWithout} variant="ghost" onPress={() => onDone(false)} />
</>
) : (
<Button title={t.continue} onPress={() => onDone(step === 'granted')} />
)}
</View>
</View>
);
}
/** What the screen says in each step. */
function copyFor(step: PermissionStep, t: NotificationPermissionLabels, app: string) {
if (step === 'ask' || step === 'asking') return { title: t.askTitle, body: t.askBody };
if (step === 'granted') return { title: t.grantedTitle, body: t.grantedBody };
if (step === 'denied') return { title: t.deniedTitle, body: t.deniedBody };
return { title: t.blockedTitle, body: fill(t.blockedBody, { app }) };
}
/** A sample notification, so the user sees what they would get. */
function Preview({ appName, muted, labels }: { appName: string; muted: boolean; labels: NotificationPermissionLabels }) {
return (
<View style={[styles.card, muted && styles.cardMuted]} accessible={false} importantForAccessibility="no-hide-descendants">
<View style={styles.icon}><Text style={styles.iconText}>{appName.slice(0, 1)}</Text></View>
<View style={styles.cardText}>
<View style={styles.cardHead}>
<Text style={styles.app}>{appName.toUpperCase()}</Text>
<Text style={styles.time}>{labels.now}</Text>
</View>
<Text style={styles.from}>{labels.sampleFrom}</Text>
<Text style={styles.msg} numberOfLines={1}>{labels.sampleMessage}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 40, paddingBottom: 16 },
top: { flex: 1, justifyContent: 'center' },
title: { marginTop: 32, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 10, fontSize: 16, lineHeight: 23, color: colors.onSurfaceVariant },
actions: { gap: 8 },
card: {
flexDirection: 'row',
gap: 12,
padding: 14,
borderRadius: radius.lg,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.outlineVariant,
shadowColor: colors.shadow,
shadowOpacity: 0.08,
shadowRadius: 16,
shadowOffset: { width: 0, height: 6 },
elevation: 3,
},
cardMuted: { opacity: 0.45 },
icon: { width: 38, height: 38, borderRadius: 9, backgroundColor: colors.secondary, alignItems: 'center', justifyContent: 'center' },
iconText: { fontSize: 18, fontWeight: '700', color: colors.onSecondary },
cardText: { flex: 1 },
cardHead: { flexDirection: 'row', justifyContent: 'space-between' },
app: { fontSize: 12, fontWeight: '600', letterSpacing: 0.4, color: colors.onSurfaceVariant },
time: { fontSize: 12, color: colors.onSurfaceVariant },
from: { marginTop: 2, fontSize: 15, fontWeight: '600', color: colors.onSurface },
msg: { fontSize: 15, color: colors.onSurface },
});
// Notification permission: explain first, then ask the system once, and handle every answer, including the one
// where the system will no longer ask and the only way is Settings. Uses ./Button.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AppState, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { colors, radius } from './theme';
/** undetermined: never asked. denied: said no, can be asked again (Android). blocked: only Settings can turn it on. */
export type PermissionStatus = 'undetermined' | 'granted' | 'denied' | 'blocked';
export type PermissionApi = {
/** The current status, without asking. */
get: () => Promise<PermissionStatus>;
/** Shows the system prompt and returns the answer. */
request: () => Promise<PermissionStatus>;
/** Opens this app's page in the system Settings. */
openSettings: () => void;
};
export type PermissionStep = 'ask' | 'asking' | 'granted' | 'denied' | 'blocked';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type NotificationPermissionLabels = {
askTitle: string;
askBody: string;
grantedTitle: string;
grantedBody: string;
deniedTitle: string;
deniedBody: string;
blockedTitle: string;
blockedBody: string;
notNow: string;
openSettings: string;
continueWithout: string;
continue: string;
sampleFrom: string;
sampleMessage: string;
now: string;
};
const defaultLabels: NotificationPermissionLabels = {
askTitle: 'Know when they reply',
askBody: 'Get a notification when someone replies or mentions you. Nothing else, and you can change it any time.',
grantedTitle: "You're all set",
grantedBody: "We'll let you know when someone replies or mentions you.",
deniedTitle: 'No notifications for now',
deniedBody: "That's fine. You can turn them on later from your profile.",
blockedTitle: 'Notifications are off',
blockedBody: 'To get replies, turn on notifications for {app} in Settings. We\'ll notice when you come back.',
notNow: 'Not now',
openSettings: 'Open Settings',
continueWithout: 'Continue without',
continue: 'Continue',
sampleFrom: 'Maya replied to your comment',
sampleMessage: '“Love this, can you share the file?”',
now: 'now',
};
/** 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 NotificationPermissionProps = {
/** get, request and openSettings, connected to the platform (see Usage). */
permissions: PermissionApi;
/** Called when the user moves on, with whether notifications are on. */
onDone: (enabled: boolean) => void;
/** The app's name, used in the copy. */
appName: string;
/** Heading on the explanation screen before requesting permission. */
title?: string;
/** Label for the button that opens the system permission prompt. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationPermissionLabels>;
/** Where to start. Defaults to checking the current status; pass a step in tests. */
initialStep?: PermissionStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: PermissionStep) => void;
};
export function NotificationPermission({ permissions, onDone, appName, title, primaryLabel = 'Turn on notifications', labels, initialStep, onStepChange }: NotificationPermissionProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<PermissionStep | null>(initialStep ?? null);
const generation = useRef(0);
const requesting = useRef(false);
const done = useRef(onDone);
done.current = onDone;
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => {
if (step) changed.current?.(step);
}, [step]);
// Already decided: skip the explanation. Granted means there is nothing to ask.
useEffect(() => {
const id = ++generation.current;
requesting.current = false;
setStep(initialStep ?? null);
if (!initialStep) {
Promise.resolve().then(() => permissions.get()).then(status => {
if (id !== generation.current) return;
if (status === 'granted') done.current(true);
else setStep(status === 'undetermined' ? 'ask' : status);
}, () => { if (id === generation.current) setStep('ask'); });
}
return () => { generation.current++; };
}, [permissions, initialStep]);
// Back from Settings: check again, so turning it on there moves the screen on by itself.
useEffect(() => {
if (step !== 'blocked') return;
let live = true;
const sub = AppState.addEventListener('change', (state) => {
if (state === 'active') void Promise.resolve().then(() => permissions.get()).then(status => {
if (live && status === 'granted') setStep('granted');
}, () => {});
});
return () => { live = false; sub.remove(); };
}, [step, permissions]);
async function ask() {
if (requesting.current) return;
const id = generation.current;
requesting.current = true;
setStep('asking');
try {
const answer = await permissions.request();
if (id === generation.current) setStep(answer === 'undetermined' ? 'ask' : answer);
} catch {
if (id === generation.current) setStep('ask');
} finally {
if (id === generation.current) requesting.current = false;
}
}
if (!step) return <View style={styles.screen} />;
const copy = copyFor(step, t, appName);
const beforeAnswer = step === 'ask' || step === 'asking';
return (
<View style={styles.screen}>
<View style={styles.top}>
<Preview appName={appName} muted={step === 'denied' || step === 'blocked'} labels={t} />
<Text style={styles.title} accessibilityRole="header">{beforeAnswer ? title ?? copy.title : copy.title}</Text>
<Text style={styles.sub}>{copy.body}</Text>
</View>
<View style={styles.actions}>
{beforeAnswer ? (
<>
<Button title={primaryLabel} onPress={ask} loading={step === 'asking'} />
<Button title={t.notNow} variant="ghost" onPress={() => onDone(false)} disabled={step === 'asking'} />
</>
) : step === 'blocked' ? (
<>
<Button title={t.openSettings} onPress={permissions.openSettings} />
<Button title={t.continueWithout} variant="ghost" onPress={() => onDone(false)} />
</>
) : (
<Button title={t.continue} onPress={() => onDone(step === 'granted')} />
)}
</View>
</View>
);
}
/** What the screen says in each step. */
function copyFor(step: PermissionStep, t: NotificationPermissionLabels, app: string) {
if (step === 'ask' || step === 'asking') return { title: t.askTitle, body: t.askBody };
if (step === 'granted') return { title: t.grantedTitle, body: t.grantedBody };
if (step === 'denied') return { title: t.deniedTitle, body: t.deniedBody };
return { title: t.blockedTitle, body: fill(t.blockedBody, { app }) };
}
/** A sample notification, so the user sees what they would get. */
function Preview({ appName, muted, labels }: { appName: string; muted: boolean; labels: NotificationPermissionLabels }) {
return (
<View style={[styles.card, muted && styles.cardMuted]} accessible={false} importantForAccessibility="no-hide-descendants">
<View style={styles.icon}><Text style={styles.iconText}>{appName.slice(0, 1)}</Text></View>
<View style={styles.cardText}>
<View style={styles.cardHead}>
<Text style={styles.app}>{appName.toUpperCase()}</Text>
<Text style={styles.time}>{labels.now}</Text>
</View>
<Text style={styles.from}>{labels.sampleFrom}</Text>
<Text style={styles.msg} numberOfLines={1}>{labels.sampleMessage}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 40, paddingBottom: 16 },
top: { flex: 1, justifyContent: 'center' },
title: { marginTop: 32, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 10, fontSize: 16, lineHeight: 23, color: colors.onSurfaceVariant },
actions: { gap: 8 },
card: {
flexDirection: 'row',
gap: 12,
padding: 14,
borderRadius: radius.lg,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.outlineVariant,
shadowColor: colors.shadow,
shadowOpacity: 0.08,
shadowRadius: 16,
shadowOffset: { width: 0, height: 6 },
elevation: 3,
},
cardMuted: { opacity: 0.45 },
icon: { width: 38, height: 38, borderRadius: 9, backgroundColor: colors.secondary, alignItems: 'center', justifyContent: 'center' },
iconText: { fontSize: 18, fontWeight: '700', color: colors.onSecondary },
cardText: { flex: 1 },
cardHead: { flexDirection: 'row', justifyContent: 'space-between' },
app: { fontSize: 12, fontWeight: '600', letterSpacing: 0.4, color: colors.onSurfaceVariant },
time: { fontSize: 12, color: colors.onSurfaceVariant },
from: { marginTop: 2, fontSize: 15, fontWeight: '600', color: colors.onSurface },
msg: { fontSize: 15, color: colors.onSurface },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// Button: four variants, pressed feedback, a loading state that keeps its width, and a real disabled state.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
import { colors, radius } from './theme';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
export type ButtonProps = {
/** The label. Keep it a verb: "Send code", not "OK". */
title: string;
/** Called on tap. Not called while loading or disabled. */
onPress?: () => void;
/** primary for the one main action on a screen, destructive for what cannot be undone. */
variant?: ButtonVariant;
/** Shows a spinner in place of the label, keeps the width, and ignores taps. */
loading?: boolean;
/** Greyed out and ignores taps. Screen readers say "dimmed". */
disabled?: boolean;
/** Shown before the label. */
icon?: ReactNode;
/** Override the label and spinner colour while enabled. */
color?: string;
/** Override the enabled button surface colour. */
backgroundColor?: string;
/** Minimum height of the visible button surface, in points. */
minHeight?: number;
/** Layout only, such as margins or alignSelf. Width fills the parent by default. */
style?: StyleProp<ViewStyle>;
};
type CopyInkProps = { copyTestIDs?: { label?: string } };
export function Button({ title, onPress, variant = 'primary', loading = false, disabled = false, icon, color, backgroundColor, minHeight, style, copyTestIDs }: ButtonProps & CopyInkProps) {
const inactive = disabled || loading;
return (
<Pressable
onPress={inactive ? undefined : onPress}
disabled={inactive}
accessibilityRole="button"
accessibilityLabel={title}
aria-disabled={inactive}
aria-busy={loading}
style={style}
>
{({ pressed }) => (
<ButtonFace title={title} variant={variant} loading={loading} disabled={disabled} pressed={pressed && !inactive} icon={icon}
color={color} backgroundColor={backgroundColor} minHeight={minHeight} copyTestIDs={copyTestIDs} />
)}
</Pressable>
);
}
export type ButtonFaceProps = Pick<ButtonProps, 'title' | 'variant' | 'loading' | 'disabled' | 'icon' | 'color' | 'backgroundColor' | 'minHeight'> & { pressed?: boolean };
/** What the button looks like, with no press handling. Button draws this; use it alone to show a state. */
export function ButtonFace({ title, variant = 'primary', loading = false, disabled = false, pressed = false, icon, color, backgroundColor, minHeight, copyTestIDs }: ButtonFaceProps & CopyInkProps) {
const look = LOOKS[variant];
const text = disabled ? colors.onSurfaceVariant : color ?? look.text;
const fill = disabled ? colors.surfaceVariant : backgroundColor ?? look.fill;
const variantBorder = look.fill === look.border ? fill : look.border;
const border = disabled ? colors.surfaceVariant : variantBorder;
return (
<View
style={[
styles.face,
{ backgroundColor: fill, borderColor: border },
minHeight !== undefined && { minHeight },
pressed && styles.pressed,
]}
>
{pressed ? <View style={[styles.fill, styles.shade, { backgroundColor: look.shade }]} /> : null}
{/* The label stays in the layout while loading, so the button does not change width. */}
<View style={[styles.content, loading && styles.hidden]}>
{icon}
<Text testID={loading ? undefined : copyTestIDs?.label} style={[styles.label, { color: text }]} numberOfLines={1}>{title}</Text>
</View>
{loading ? <ActivityIndicator style={styles.fill} color={text} /> : null}
</View>
);
}
// Pressed darkens a filled button and tints an outlined one, so it works with any theme colours.
const LOOKS: Record<ButtonVariant, { fill: string; border: string; text: string; shade: string }> = {
primary: { fill: colors.primary, border: colors.primary, text: colors.onPrimary, shade: colors.shadow },
secondary: { fill: colors.surface, border: colors.outlineVariant, text: colors.onSurface, shade: colors.onSurface },
ghost: { fill: 'transparent', border: 'transparent', text: colors.primary, shade: colors.primary },
destructive: { fill: colors.error, border: colors.error, text: colors.onError, shade: colors.shadow },
};
const styles = StyleSheet.create({
face: {
minHeight: 50,
paddingHorizontal: 20,
borderRadius: radius.md,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
},
pressed: { transform: [{ scale: 0.98 }] },
fill: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
shade: { opacity: 0.12 },
content: { flexDirection: 'row', alignItems: 'center', gap: 8 },
hidden: { opacity: 0 },
label: { fontSize: 17, fontWeight: '600' },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
用法
import * as Notifications from 'expo-notifications';
import { Linking } from 'react-native';
import { NotificationPermission, type PermissionApi } from '@/components/mobilens/NotificationPermission';
// expo-notifications: "denied" with canAskAgain false means only Settings can turn it on.
const toStatus = (p: Notifications.NotificationPermissionsStatus) =>
p.granted ? 'granted' : p.status === 'undetermined' ? 'undetermined' : p.canAskAgain ? 'denied' : 'blocked';
const permissions: PermissionApi = {
get: async () => toStatus(await Notifications.getPermissionsAsync()),
request: async () => toStatus(await Notifications.requestPermissionsAsync()),
openSettings: () => Linking.openSettings(),
};
export function NotificationsStep({ next }: { next: (enabled: boolean) => void }) {
return <NotificationPermission permissions={permissions} appName="Northwind" onDone={next} />;
}
import * as Notifications from 'expo-notifications';
import { Linking } from 'react-native';
import { NotificationPermission, type PermissionApi } from '@/components/mobilens/NotificationPermission';
// expo-notifications: "denied" with canAskAgain false means only Settings can turn it on.
const toStatus = (p: Notifications.NotificationPermissionsStatus) =>
p.granted ? 'granted' : p.status === 'undetermined' ? 'undetermined' : p.canAskAgain ? 'denied' : 'blocked';
const permissions: PermissionApi = {
get: async () => toStatus(await Notifications.getPermissionsAsync()),
request: async () => toStatus(await Notifications.requestPermissionsAsync()),
openSettings: () => Linking.openSettings(),
};
export function NotificationsStep({ next }: { next: (enabled: boolean) => void }) {
return <NotificationPermission permissions={permissions} appName="Northwind" onDone={next} />;
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| permissions | PermissionApi | – | get, request and openSettings, connected to the platform (see Usage). |
| onDone | (enabled: boolean) => void | – | Called when the user moves on, with whether notifications are on. |
| appName | string | – | The app's name, used in the copy. |
| title? | string | – | Heading on the explanation screen before requesting permission. |
| primaryLabel? | string | 'Turn on notifications' | Label for the button that opens the system permission prompt. |
| labels? | Partial<NotificationPermissionLabels> | – | The words the screen shows. Pass a partial set to change only some of them. |
| initialStep? | PermissionStep | – | Where to start. Defaults to checking the current status; pass a step in tests. |
| onStepChange? | (step: PermissionStep) => void | – | Called with every step the screen enters, for analytics or logging. |
这个流程用到的控件
Add the "Notification permission" 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/NotificationPermission.tsx ---
// Notification permission: explain first, then ask the system once, and handle every answer, including the one
// where the system will no longer ask and the only way is Settings. Uses ./Button.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AppState, StyleSheet, Text, View } from 'react-native';
import { Button } from './Button';
import { colors, radius } from './theme';
/** undetermined: never asked. denied: said no, can be asked again (Android). blocked: only Settings can turn it on. */
export type PermissionStatus = 'undetermined' | 'granted' | 'denied' | 'blocked';
export type PermissionApi = {
/** The current status, without asking. */
get: () => Promise<PermissionStatus>;
/** Shows the system prompt and returns the answer. */
request: () => Promise<PermissionStatus>;
/** Opens this app's page in the system Settings. */
openSettings: () => void;
};
export type PermissionStep = 'ask' | 'asking' | 'granted' | 'denied' | 'blocked';
/** Every word the screen shows. Override them for another language; {name} is replaced with a value. */
export type NotificationPermissionLabels = {
askTitle: string;
askBody: string;
grantedTitle: string;
grantedBody: string;
deniedTitle: string;
deniedBody: string;
blockedTitle: string;
blockedBody: string;
notNow: string;
openSettings: string;
continueWithout: string;
continue: string;
sampleFrom: string;
sampleMessage: string;
now: string;
};
const defaultLabels: NotificationPermissionLabels = {
askTitle: 'Know when they reply',
askBody: 'Get a notification when someone replies or mentions you. Nothing else, and you can change it any time.',
grantedTitle: "You're all set",
grantedBody: "We'll let you know when someone replies or mentions you.",
deniedTitle: 'No notifications for now',
deniedBody: "That's fine. You can turn them on later from your profile.",
blockedTitle: 'Notifications are off',
blockedBody: 'To get replies, turn on notifications for {app} in Settings. We\'ll notice when you come back.',
notNow: 'Not now',
openSettings: 'Open Settings',
continueWithout: 'Continue without',
continue: 'Continue',
sampleFrom: 'Maya replied to your comment',
sampleMessage: '“Love this, can you share the file?”',
now: 'now',
};
/** 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 NotificationPermissionProps = {
/** get, request and openSettings, connected to the platform (see Usage). */
permissions: PermissionApi;
/** Called when the user moves on, with whether notifications are on. */
onDone: (enabled: boolean) => void;
/** The app's name, used in the copy. */
appName: string;
/** Heading on the explanation screen before requesting permission. */
title?: string;
/** Label for the button that opens the system permission prompt. */
primaryLabel?: string;
/** The words the screen shows. Pass a partial set to change only some of them. */
labels?: Partial<NotificationPermissionLabels>;
/** Where to start. Defaults to checking the current status; pass a step in tests. */
initialStep?: PermissionStep;
/** Called with every step the screen enters, for analytics or logging. */
onStepChange?: (step: PermissionStep) => void;
};
export function NotificationPermission({ permissions, onDone, appName, title, primaryLabel = 'Turn on notifications', labels, initialStep, onStepChange }: NotificationPermissionProps) {
const t = { ...defaultLabels, ...labels };
const [step, setStep] = useState<PermissionStep | null>(initialStep ?? null);
const generation = useRef(0);
const requesting = useRef(false);
const done = useRef(onDone);
done.current = onDone;
const changed = useRef(onStepChange);
changed.current = onStepChange;
useEffect(() => {
if (step) changed.current?.(step);
}, [step]);
// Already decided: skip the explanation. Granted means there is nothing to ask.
useEffect(() => {
const id = ++generation.current;
requesting.current = false;
setStep(initialStep ?? null);
if (!initialStep) {
Promise.resolve().then(() => permissions.get()).then(status => {
if (id !== generation.current) return;
if (status === 'granted') done.current(true);
else setStep(status === 'undetermined' ? 'ask' : status);
}, () => { if (id === generation.current) setStep('ask'); });
}
return () => { generation.current++; };
}, [permissions, initialStep]);
// Back from Settings: check again, so turning it on there moves the screen on by itself.
useEffect(() => {
if (step !== 'blocked') return;
let live = true;
const sub = AppState.addEventListener('change', (state) => {
if (state === 'active') void Promise.resolve().then(() => permissions.get()).then(status => {
if (live && status === 'granted') setStep('granted');
}, () => {});
});
return () => { live = false; sub.remove(); };
}, [step, permissions]);
async function ask() {
if (requesting.current) return;
const id = generation.current;
requesting.current = true;
setStep('asking');
try {
const answer = await permissions.request();
if (id === generation.current) setStep(answer === 'undetermined' ? 'ask' : answer);
} catch {
if (id === generation.current) setStep('ask');
} finally {
if (id === generation.current) requesting.current = false;
}
}
if (!step) return <View style={styles.screen} />;
const copy = copyFor(step, t, appName);
const beforeAnswer = step === 'ask' || step === 'asking';
return (
<View style={styles.screen}>
<View style={styles.top}>
<Preview appName={appName} muted={step === 'denied' || step === 'blocked'} labels={t} />
<Text style={styles.title} accessibilityRole="header">{beforeAnswer ? title ?? copy.title : copy.title}</Text>
<Text style={styles.sub}>{copy.body}</Text>
</View>
<View style={styles.actions}>
{beforeAnswer ? (
<>
<Button title={primaryLabel} onPress={ask} loading={step === 'asking'} />
<Button title={t.notNow} variant="ghost" onPress={() => onDone(false)} disabled={step === 'asking'} />
</>
) : step === 'blocked' ? (
<>
<Button title={t.openSettings} onPress={permissions.openSettings} />
<Button title={t.continueWithout} variant="ghost" onPress={() => onDone(false)} />
</>
) : (
<Button title={t.continue} onPress={() => onDone(step === 'granted')} />
)}
</View>
</View>
);
}
/** What the screen says in each step. */
function copyFor(step: PermissionStep, t: NotificationPermissionLabels, app: string) {
if (step === 'ask' || step === 'asking') return { title: t.askTitle, body: t.askBody };
if (step === 'granted') return { title: t.grantedTitle, body: t.grantedBody };
if (step === 'denied') return { title: t.deniedTitle, body: t.deniedBody };
return { title: t.blockedTitle, body: fill(t.blockedBody, { app }) };
}
/** A sample notification, so the user sees what they would get. */
function Preview({ appName, muted, labels }: { appName: string; muted: boolean; labels: NotificationPermissionLabels }) {
return (
<View style={[styles.card, muted && styles.cardMuted]} accessible={false} importantForAccessibility="no-hide-descendants">
<View style={styles.icon}><Text style={styles.iconText}>{appName.slice(0, 1)}</Text></View>
<View style={styles.cardText}>
<View style={styles.cardHead}>
<Text style={styles.app}>{appName.toUpperCase()}</Text>
<Text style={styles.time}>{labels.now}</Text>
</View>
<Text style={styles.from}>{labels.sampleFrom}</Text>
<Text style={styles.msg} numberOfLines={1}>{labels.sampleMessage}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, paddingHorizontal: 24, paddingTop: 40, paddingBottom: 16 },
top: { flex: 1, justifyContent: 'center' },
title: { marginTop: 32, fontSize: 30, fontWeight: '600', letterSpacing: -0.5, color: colors.onBackground },
sub: { marginTop: 10, fontSize: 16, lineHeight: 23, color: colors.onSurfaceVariant },
actions: { gap: 8 },
card: {
flexDirection: 'row',
gap: 12,
padding: 14,
borderRadius: radius.lg,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.outlineVariant,
shadowColor: colors.shadow,
shadowOpacity: 0.08,
shadowRadius: 16,
shadowOffset: { width: 0, height: 6 },
elevation: 3,
},
cardMuted: { opacity: 0.45 },
icon: { width: 38, height: 38, borderRadius: 9, backgroundColor: colors.secondary, alignItems: 'center', justifyContent: 'center' },
iconText: { fontSize: 18, fontWeight: '700', color: colors.onSecondary },
cardText: { flex: 1 },
cardHead: { flexDirection: 'row', justifyContent: 'space-between' },
app: { fontSize: 12, fontWeight: '600', letterSpacing: 0.4, color: colors.onSurfaceVariant },
time: { fontSize: 12, color: colors.onSurfaceVariant },
from: { marginTop: 2, fontSize: 15, fontWeight: '600', color: colors.onSurface },
msg: { fontSize: 15, color: colors.onSurface },
});
--- end of NotificationPermission.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 * as Notifications from 'expo-notifications';
import { Linking } from 'react-native';
import { NotificationPermission, type PermissionApi } from '@/components/mobilens/NotificationPermission';
// expo-notifications: "denied" with canAskAgain false means only Settings can turn it on.
const toStatus = (p: Notifications.NotificationPermissionsStatus) =>
p.granted ? 'granted' : p.status === 'undetermined' ? 'undetermined' : p.canAskAgain ? 'denied' : 'blocked';
const permissions: PermissionApi = {
get: async () => toStatus(await Notifications.getPermissionsAsync()),
request: async () => toStatus(await Notifications.requestPermissionsAsync()),
openSettings: () => Linking.openSettings(),
};
export function NotificationsStep({ next }: { next: (enabled: boolean) => void }) {
return <NotificationPermission permissions={permissions} appName="Northwind" onDone={next} />;
}
STATES: all 5 must work in the screen where you use it
- Explain: when notifications were never asked for. Show what a notification looks like before the system asks. Not now moves on without asking: the system prompt can be shown only once, so don't spend it on a user who isn't ready. If notifications are already on, the screen is skipped. Next: System prompt.
- System prompt: when turn on was tapped. The app's buttons are locked while the system prompt is up. Next: Allowed, Not allowed, Off in Settings.
- Allowed: when the user allowed notifications. Confirm in one line and move on.
- Not allowed: when the user said no, and the system can ask again later. No guilt and no second ask on the spot; say where to turn it on later.
- Off in Settings: when the system will no longer ask. Open Settings goes to this app's page in system Settings. Coming back with notifications on moves to Allowed by itself. Next: Allowed.
ACCESSIBILITY
- The sample notification is hidden from screen readers; the title and text say the same.
- Each step's title is a heading, so screen readers announce the change.
- Buttons stay at the bottom, within thumb reach, on every screen size.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.