屏幕
配色方案
明暗
圆角
颜色
所有状态
- 何时出现
- 行为规则
把这 2 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
用法
import type { ReactNode } from 'react';
import { View } from 'react-native';
import { Snackbar, useSnackbar } from '@/components/mobilens/Snackbar';
export function Inbox({ archive, unarchive, children }: { archive: (id: string) => Promise<void>; unarchive: (id: string) => void; children: (onArchive: (id: string) => void) => ReactNode }) {
const snack = useSnackbar();
const onArchive = async (id: string) => {
try {
await archive(id);
snack.show({ text: 'Conversation archived', action: { label: 'Undo', onPress: () => unarchive(id) } });
} catch {
snack.show({ text: "Couldn't archive. Try again.", tone: 'error' });
}
};
return (
<View style={{ flex: 1 }}>
{children(onArchive)}
<Snackbar {...snack.props} />
</View>
);
}
import type { ReactNode } from 'react';
import { View } from 'react-native';
import { Snackbar, useSnackbar } from '@/components/mobilens/Snackbar';
export function Inbox({ archive, unarchive, children }: { archive: (id: string) => Promise<void>; unarchive: (id: string) => void; children: (onArchive: (id: string) => void) => ReactNode }) {
const snack = useSnackbar();
const onArchive = async (id: string) => {
try {
await archive(id);
snack.show({ text: 'Conversation archived', action: { label: 'Undo', onPress: () => unarchive(id) } });
} catch {
snack.show({ text: "Couldn't archive. Try again.", tone: 'error' });
}
};
return (
<View style={{ flex: 1 }}>
{children(onArchive)}
<Snackbar {...snack.props} />
</View>
);
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| message | SnackbarMessage | null | – | The message on screen, or null for none. useSnackbar() manages this for you. |
| onDismiss | () => void | – | Called when it should go away: time ran out, the action was tapped, or it was swiped down. |
| duration? | number | 4000 | How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. |
用在这些流程里
Add the "Snackbar" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them.
FILES
Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths.
--- components/mobilens/theme.ts ---
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
--- end of theme.ts ---
--- components/mobilens/Snackbar.tsx ---
// Snackbar: a short message at the bottom of the screen, with an optional action such as Undo.
// It goes away by itself, when its action is tapped, or when it is swiped down. Messages shown while one is up wait
// their turn. Render the host once, as the last child of the screen.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, PanResponder, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
const NATIVE_DRIVER = Platform.OS !== 'web';
export type SnackbarMessage = {
/** One short sentence: "Photo deleted". */
text: string;
/** One action, such as Undo. Tapping it also closes the snackbar. */
action?: { label: string; onPress: () => void };
/** error shows a red stripe; use it when something failed. */
tone?: 'default' | 'error';
};
export type SnackbarProps = {
/** The message on screen, or null for none. useSnackbar() manages this for you. */
message: SnackbarMessage | null;
/** Called when it should go away: time ran out, the action was tapped, or it was swiped down. */
onDismiss: () => void;
/** How long it stays, in ms. With a screen reader on, a message with an action stays until it is used. */
duration?: number;
};
export function Snackbar({ message, onDismiss, duration = 4000 }: SnackbarProps) {
const show = useRef(new Animated.Value(0)).current;
const drag = useRef(new Animated.Value(0)).current;
const [shown, setShown] = useState<SnackbarMessage | null>(message);
const still = useReduceMotion();
const reader = useScreenReader();
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// In: slide up (or fade with Reduce Motion). Out: the reverse, then the next message can come in.
useEffect(() => {
if (message) {
setShown(message);
drag.setValue(0);
Animated.timing(show, { toValue: 1, duration: still ? 120 : 220, useNativeDriver: NATIVE_DRIVER }).start();
AccessibilityInfo.announceForAccessibility(message.action ? `${message.text}. ${message.action.label} available` : message.text);
} else {
Animated.timing(show, { toValue: 0, duration: still ? 120 : 180, useNativeDriver: NATIVE_DRIVER }).start(() => setShown(null));
}
}, [message, show, drag, still]);
useEffect(() => {
if (!message || (reader && message.action)) return;
const timer = setTimeout(() => dismiss.current(), duration);
return () => clearTimeout(timer);
}, [message, duration, reader]);
const pan = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
onPanResponderRelease: (_, g) => {
if (g.dy > 40 || g.vy > 0.8) dismiss.current();
else Animated.spring(drag, { toValue: 0, useNativeDriver: NATIVE_DRIVER }).start();
},
}),
).current;
if (!shown) return null;
const rise = show.interpolate({ inputRange: [0, 1], outputRange: [still ? 0 : 24, 0] });
return (
<View style={styles.host} pointerEvents="box-none">
<Animated.View {...pan.panHandlers} style={{ opacity: show, transform: [{ translateY: Animated.add(rise, drag) }] }}>
<SnackbarView
message={shown}
onAction={() => {
shown.action?.onPress();
dismiss.current();
}}
/>
</Animated.View>
</View>
);
}
/** The bar itself, with no timing or gestures. Snackbar draws this; use it alone to show a state. */
export function SnackbarView({ message, onAction }: { message: SnackbarMessage; onAction?: () => void }) {
return (
<View style={[styles.bar, message.tone === 'error' && styles.barError]} accessibilityLiveRegion="polite">
<Text style={styles.text}>{message.text}</Text>
{message.action ? (
<Pressable onPress={onAction} hitSlop={8} accessibilityRole="button" style={({ pressed }) => pressed && styles.pressed}>
<Text style={styles.action}>{message.action.label}</Text>
</Pressable>
) : null}
</View>
);
}
/**
* Keeps a queue of messages and shows them one at a time.
* const snack = useSnackbar();
* snack.show({ text: 'Photo deleted', action: { label: 'Undo', onPress: restore } });
* return <View style={{ flex: 1 }}>{...}<Snackbar {...snack.props} /></View>;
*/
export function useSnackbar() {
const [queue, setQueue] = useState<SnackbarMessage[]>([]);
const [leaving, setLeaving] = useState(false);
const busy = useRef(false);
const show = useCallback((m: SnackbarMessage) => setQueue((q) => [...q, m]), []);
// The current message slides out first; only then does the next one come in.
const onDismiss = useCallback(() => {
if (busy.current) return;
busy.current = true;
setLeaving(true);
setTimeout(() => {
setQueue((q) => q.slice(1));
setLeaving(false);
busy.current = false;
}, 240);
}, []);
return { show, props: { message: leaving ? null : (queue[0] ?? null), onDismiss } };
}
function useReduceMotion() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
function useScreenReader() {
const [on, setOn] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isScreenReaderEnabled().then((v) => live && setOn(v));
const sub = AccessibilityInfo.addEventListener('screenReaderChanged', setOn);
return () => {
live = false;
sub.remove();
};
}, []);
return on;
}
const styles = StyleSheet.create({
host: { position: 'absolute', left: 16, right: 16, bottom: 16 },
bar: {
minHeight: 48,
paddingVertical: 12,
paddingHorizontal: 16,
flexDirection: 'row',
alignItems: 'center',
gap: 16,
borderRadius: radius.md,
backgroundColor: colors.onBackground,
shadowColor: colors.shadow,
shadowOpacity: 0.18,
shadowRadius: 12,
shadowOffset: { width: 0, height: 4 },
elevation: 6,
},
barError: { borderLeftWidth: 4, borderLeftColor: colors.error, paddingLeft: 12 },
text: { flex: 1, fontSize: 15, color: colors.background },
action: { fontSize: 15, fontWeight: '600', color: colors.secondaryContainer },
pressed: { opacity: 0.6 },
});
--- end of Snackbar.tsx ---
HOW TO USE IT
import type { ReactNode } from 'react';
import { View } from 'react-native';
import { Snackbar, useSnackbar } from '@/components/mobilens/Snackbar';
export function Inbox({ archive, unarchive, children }: { archive: (id: string) => Promise<void>; unarchive: (id: string) => void; children: (onArchive: (id: string) => void) => ReactNode }) {
const snack = useSnackbar();
const onArchive = async (id: string) => {
try {
await archive(id);
snack.show({ text: 'Conversation archived', action: { label: 'Undo', onPress: () => unarchive(id) } });
} catch {
snack.show({ text: "Couldn't archive. Try again.", tone: 'error' });
}
};
return (
<View style={{ flex: 1 }}>
{children(onArchive)}
<Snackbar {...snack.props} />
</View>
);
}
STATES: all 5 must work in the screen where you use it
- Shown: when something just happened that can be undone. It slides up from the bottom; with Reduce Motion on it fades in. Tapping the action runs it and closes the snackbar.
- Error: when something failed and can be retried. A red stripe marks it; the action is Retry.
- Swiping away: when the user drags it down. It follows the finger and fades. Let go past 40 points, or flick, and it closes; otherwise it springs back.
- Next in line: when A second message arrives while one is up. The second waits until the first is gone, then slides in. Messages never stack.
- Gone: when four seconds passed without a touch. It slides down and out. With a screen reader on, a message that has an action stays until it is used or swiped.
ACCESSIBILITY
- Each message is announced when it appears, with its action.
- With a screen reader on, messages with an action do not time out.
- With Reduce Motion on, it fades instead of sliding.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.