Open History to see the last commit
1import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens";
2import { useCallback, useEffect, useLayoutEffect, useState } from "react";
3import { AccessibilityInfo, Platform, StyleSheet, View, useWindowDimensions } from "react-native";
4import { GestureDetector, usePanGesture } from "react-native-gesture-handler";
5import Animated, {
6 cancelAnimation,
7 Easing,
8 FadeOut,
9 ReduceMotion,
10 runOnJS,
11 useAnimatedStyle,
12 useSharedValue,
13 withTiming,
14 type EntryAnimationsValues,
15} from "react-native-reanimated";
16
17import { AppText } from "./AppText";
18import { Button } from "./Button";
19import { GlassSurface } from "./GlassSurface";
20import { useControlTheme } from "./useControlTheme";
21import { IconButton } from "./IconButton";
22import { AppActivityIndicator } from "./AppActivityIndicator";
23import { SymbolView } from "./AppSymbol";
24
25export type ToastProps = {
26 readonly message: string;
27 readonly description?: string;
28 readonly singleLine?: boolean;
29 readonly tone?: "default" | "success" | "danger";
30 readonly busy?: boolean;
31 readonly action?: { readonly label: string; readonly onPress: () => void };
32} & (
33 | { readonly dismissMode: "swipe"; readonly onDismiss: () => void }
34 | { readonly dismissMode?: "button"; readonly onDismiss?: () => void }
35);
36
37export function Toast(props: ToastProps) {
38 return props.dismissMode === "swipe" ? (
39 <SwipeableToast {...props} />
40 ) : (
41 <ToastContent {...props} />
42 );
43}
44
45function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) {
46 const { fontScale } = useWindowDimensions();
47 const { colorScheme } = useControlTheme();
48 const borderRadius = Platform.OS === "ios" ? 31 : MOBILE_SHAPE.toast;
49 // Explicit single-line notices reserve the action's width and truncate the text.
50 const inlineAction = props.singleLine || (!props.description && fontScale < 1.5);
51 const message =
52 props.singleLine && props.description
53 ? `${props.message}: ${props.description}`
54 : props.message;
55 const action = props.action ? (
56 <Button label={props.action.label} onPress={props.action.onPress} />
57 ) : null;
58 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- announces the toast message to VoiceOver through AccessibilityInfo
59 useEffect(() => {
60 if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(props.message);
61 }, [props.message]);
62 const surface = (
63 <GlassSurface
64 key={props.glassReady === false ? "entering" : "settled"}
65 chrome={Platform.OS === "ios" && colorScheme === "dark" ? "none" : undefined}
66 tintColor={Platform.OS === "ios" ? null : undefined}
67 className={Platform.OS === "ios" ? "bg-transparent p-3" : "p-3"}
68 style={{ borderRadius }}
69 >
70 <View className="flex-row items-center gap-3">
71 {props.busy ? (
72 <AppActivityIndicator />
73 ) : (
74 <SymbolView
75 name={props.tone === "danger" ? "exclamationmark.triangle" : "checkmark.circle"}
76 size={20}
77 tintColorClassName={
78 props.tone === "danger" ? "accent-danger-foreground" : "accent-icon"
79 }
80 />
81 )}
82 <View className="min-w-0 flex-1" accessibilityLiveRegion="polite">
83 <AppText
84 textRole="footnote"
85 className="font-t3-semibold"
86 numberOfLines={props.singleLine ? 1 : undefined}
87 accessibilityLabel={props.singleLine ? message : undefined}
88 >
89 {message}
90 </AppText>
91 {props.description && !props.singleLine ? (
92 <AppText textRole="label" className="text-foreground-muted">
93 {props.description}
94 </AppText>
95 ) : null}
96 </View>
97 {inlineAction && action ? <View className="self-center">{action}</View> : null}
98 {props.onDismiss && props.dismissMode !== "swipe" ? (
99 <IconButton accessibilityLabel="Dismiss message" icon="xmark" onPress={props.onDismiss} />
100 ) : null}
101 </View>
102 {action && !inlineAction ? <View className="mt-2 self-end">{action}</View> : null}
103 </GlassSurface>
104 );
105 return Platform.OS === "ios" ? (
106 <View
107 style={{
108 borderRadius,
109 boxShadow: [
110 {
111 offsetX: 0,
112 offsetY: 0,
113 blurRadius: 8,
114 color: colorScheme === "dark" ? "rgba(0, 0, 0, 0.22)" : "rgba(0, 0, 0, 0.08)",
115 },
116 ],
117 }}
118 >
119 {surface}
120 </View>
121 ) : (
122 surface
123 );
124}
125
126const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };
127const ENTER_TIMING = {
128 duration: MOBILE_MOTION.enter,
129 easing: Easing.out(Easing.cubic),
130 reduceMotion: ReduceMotion.System,
131};
132const TOAST_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);
133function SwipeableToast(props: ToastProps & { readonly onDismiss: () => void }) {
134 const [glassReady, setGlassReady] = useState(Platform.OS !== "ios");
135 const finishEntering = useCallback(() => setGlassReady(true), []);
136 // UIKit can skip glass on a moving host; remount the surface after entry so its blur installs.
137 const toastEntering = (values: EntryAnimationsValues) => {
138 "worklet";
139 return {
140 initialValues: { originY: values.targetOriginY + values.targetHeight + 12 },
141 animations: { originY: withTiming(values.targetOriginY, ENTER_TIMING) },
142 callback: (finished: boolean) => {
143 if (finished) runOnJS(finishEntering)();
144 },
145 };
146 };
147 const { onDismiss } = props;
148 const translation = useSharedValue(0);
149 const width = useSharedValue(0);
150 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the Reanimated swipe translation animation on unmount
151 useLayoutEffect(
152 () => () => {
153 cancelAnimation(translation);
154 },
155 [translation],
156 );
157 const gesture = usePanGesture({
158 activeOffsetX: [-10, 10],
159 failOffsetY: [-12, 12],
160 onUpdate: (event) => {
161 translation.set(event.translationX);
162 },
163 onDeactivate: (event) => {
164 if (
165 !event.canceled &&
166 (Math.abs(event.translationX) > width.value * 0.25 ||
167 (Math.abs(event.velocityX) > 800 && event.translationX * event.velocityX > 0))
168 ) {
169 const direction = Math.sign(event.translationX || event.velocityX);
170 translation.set(
171 withTiming(direction * (width.value + 24), SWIPE_TIMING, (finished) => {
172 if (finished) runOnJS(onDismiss)();
173 }),
174 );
175 } else {
176 translation.set(withTiming(0, SWIPE_TIMING));
177 }
178 },
179 });
180 const animatedStyle = useAnimatedStyle(() => ({
181 transform: [{ translateX: translation.value }],
182 }));
183 return (
184 <Animated.View
185 className={Platform.OS === "android" ? "overflow-hidden" : undefined}
186 pointerEvents="box-none"
187 exiting={TOAST_EXITING}
188 onAccessibilityEscape={onDismiss}
189 onLayout={(event) => {
190 width.set(event.nativeEvent.layout.width);
191 }}
192 >
193 <GestureDetector gesture={gesture}>
194 <Animated.View collapsable={false} entering={toastEntering} style={animatedStyle}>
195 {Platform.OS === "android" ? (
196 // Keep the dismiss target separate so TalkBack can also focus the action button.
197 <View
198 accessible
199 accessibilityRole="alert"
200 accessibilityLiveRegion="assertive"
201 accessibilityLabel={props.message}
202 accessibilityActions={[{ name: "dismiss", label: "Dismiss message" }]}
203 onAccessibilityAction={({ nativeEvent }) => {
204 if (nativeEvent.actionName === "dismiss") onDismiss();
205 }}
206 pointerEvents="none"
207 style={StyleSheet.absoluteFill}
208 />
209 ) : null}
210 <ToastContent {...props} glassReady={glassReady} />
211 </Animated.View>
212 </GestureDetector>
213 </Animated.View>
214 );
215}