Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Toast.tsx

334 lines11.4 KB

1import { useGT } from "gt-react-native";
2import { cn } from "../../lib/cn";
3import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens";
4import { type ReactNode, useCallback, useEffect, useLayoutEffect, useState } from "react";
5import {
6 AccessibilityInfo,
7 Platform,
8 Pressable,
9 StyleSheet,
10 View,
11 useWindowDimensions,
12} from "react-native";
13import { GestureDetector, usePanGesture } from "react-native-gesture-handler";
14import Animated, {
15 cancelAnimation,
16 Easing,
17 FadeOut,
18 ReduceMotion,
19 runOnJS,
20 useAnimatedStyle,
21 useDerivedValue,
22 useSharedValue,
23 withTiming,
24 type EntryAnimationsValues,
25} from "react-native-reanimated";
26​
27import { AppText } from "./AppText";
28import { Button } from "./Button";
29import { GlassSurface } from "./GlassSurface";
30import { useControlTheme } from "./useControlTheme";
31import { IconButton } from "./IconButton";
32import { AppActivityIndicator } from "./AppActivityIndicator";
33import { SymbolView } from "./AppSymbol";
34​
35export type ToastProps = {
36 readonly message: string;
37 readonly description?: string;
38 readonly singleLine?: boolean;
39 readonly tone?: "default" | "success" | "warning" | "danger";
40 readonly busy?: boolean;
41 readonly action?: { readonly label: string; readonly onPress: () => void };
42 /** Details a chevron beside the message reveals below it while `expanded`. */
43 readonly children?: ReactNode;
44 readonly expanded?: boolean;
45 readonly onExpandedChange?: (expanded: boolean) => void;
46} & (
47 | { readonly dismissMode: "swipe"; readonly onDismiss: () => void }
48 | { readonly dismissMode?: "button"; readonly onDismiss?: () => void }
49);
50​
51export function Toast(props: ToastProps) {
52 return props.dismissMode === "swipe" ? (
53 <SwipeableToast {...props} />
54 ) : (
55 <ToastContent {...props} />
56 );
58​
59function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) {
60 const gt = useGT();
61 const { fontScale } = useWindowDimensions();
62 const { colorScheme } = useControlTheme();
63 const borderRadius = Platform.OS === "ios" ? 28 : MOBILE_SHAPE.toast;
64 // Explicit single-line notices reserve the action's width and truncate the text.
65 const inlineAction = props.singleLine || (!props.description && fontScale < 1.5);
66 const message =
67 props.singleLine && props.description
68 ? `${props.message}: ${props.description}`
69 : props.message;
70 const action = props.action ? (
71 <Button
72 label={props.action.label}
73 onPress={props.action.onPress}
74 size={Platform.OS === "ios" ? "compact" : "default"}
75 />
76 ) : null;
77 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- announces the toast message to VoiceOver through AccessibilityInfo
78 useEffect(() => {
79 if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(props.message);
80 }, [props.message]);
81 const surface = (
82 <GlassSurface
83 key={props.glassReady === false ? "entering" : "settled"}
84 chrome={Platform.OS === "ios" && colorScheme === "dark" ? "none" : undefined}
85 tintColor={Platform.OS === "ios" ? null : undefined}
86 className={Platform.OS === "ios" ? "bg-transparent p-2" : "p-3"}
87 style={{ borderRadius }}
88 >
89 <View
90 className={cn(
91 "flex-row items-center gap-3",
92 // Match the leading inset to the action label's, which sits inside the button's padding.
93 Platform.OS === "ios" && inlineAction && action && "pl-5",
94 Platform.OS === "ios" && props.onExpandedChange && "pl-3",
95 )}
96 >
97 {props.busy ? (
98 <AppActivityIndicator />
99 ) : (
100 <SymbolView
101 name={
102 props.tone === "danger" || props.tone === "warning"
103 ? "exclamationmark.triangle"
104 : "checkmark.circle"
105 }
106 size={20}
107 tintColorClassName={
108 props.tone === "danger"
109 ? "accent-danger-foreground"
110 : props.tone === "warning"
111 ? "accent-warning-foreground"
112 : "accent-icon"
113 }
114 />
115 )}
116 <View className="min-w-0 flex-1" accessibilityLiveRegion="polite">
117 <AppText
118 textRole="footnote"
119 className="font-t3-semibold"
120 numberOfLines={props.singleLine ? 1 : undefined}
121 accessibilityLabel={props.singleLine ? message : undefined}
122 >
123 {message}
124 </AppText>
125 {props.description && !props.singleLine ? (
126 <AppText textRole="label" className="text-foreground-muted">
127 {props.description}
128 </AppText>
129 ) : null}
130 </View>
131 {inlineAction && action ? <View className="self-center">{action}</View> : null}
132 {props.onExpandedChange ? (
133 <Disclosure
134 expanded={props.expanded === true}
135 onExpandedChange={props.onExpandedChange}
136 />
137 ) : null}
138 {props.onDismiss && props.dismissMode !== "swipe" ? (
139 <IconButton
140 accessibilityLabel={gt`Dismiss message`}
141 icon="xmark"
142 onPress={props.onDismiss}
143 />
144 ) : null}
145 </View>
146 {action && !inlineAction ? <View className="mt-2 self-end">{action}</View> : null}
147 {props.children ? (
148 <ToastExpansion expanded={props.expanded === true}>{props.children}</ToastExpansion>
149 ) : null}
150 </GlassSurface>
151 );
152 return Platform.OS === "ios" ? (
153 <View
154 style={{
155 borderRadius,
156 boxShadow: [
157 {
158 offsetX: 0,
159 offsetY: 0,
160 blurRadius: 8,
161 color: colorScheme === "dark" ? "rgba(0, 0, 0, 0.22)" : "rgba(0, 0, 0, 0.08)",
162 },
163 ],
164 }}
165 >
166 {surface}
167 </View>
168 ) : (
169 surface
170 );
172​
173function Disclosure(props: {
174 readonly expanded: boolean;
175 readonly onExpandedChange: (expanded: boolean) => void;
176}) {
177 const gt = useGT();
178 const { expanded } = props;
179 const turn = useDerivedValue(() =>
180 withTiming(expanded ? 1 : 0, expanded ? ENTER_TIMING : COLLAPSE_TIMING),
181 );
182 const chevronStyle = useAnimatedStyle(() => ({
183 transform: [{ rotate: `${turn.value * 180}deg` }],
184 }));
185 return (
186 <Pressable
187 accessibilityRole="button"
188 accessibilityLabel={gt`Details`}
189 accessibilityState={{ expanded }}
190 hitSlop={4}
191 onPress={() => props.onExpandedChange(!expanded)}
192 className={cn(
193 "items-center justify-center rounded-full bg-secondary active:opacity-70",
194 Platform.OS === "ios" ? "size-10" : "size-12",
195 )}
196 >
197 <Animated.View style={chevronStyle}>
198 <SymbolView name="chevron.up" size={16} tintColorClassName="accent-secondary-foreground" />
199 </Animated.View>
200 </Pressable>
201 );
203​
204const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };
205const ENTER_TIMING = {
206 duration: MOBILE_MOTION.enter,
207 easing: Easing.out(Easing.cubic),
208 reduceMotion: ReduceMotion.System,
209};
210const TOAST_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);
211const COLLAPSE_TIMING = {
212 duration: MOBILE_MOTION.exit,
213 easing: Easing.out(Easing.cubic),
214 reduceMotion: ReduceMotion.System,
215};
216​
217/**
218 * Animates the clip's height every frame so the glass grows with it; a layout transition on the
219 * content alone left the glass jumping to its final size. Content stays mounted until collapsed.
220 */
221function ToastExpansion(props: { readonly expanded: boolean; readonly children: ReactNode }) {
222 const { expanded } = props;
223 const [mounted, setMounted] = useState(expanded);
224 if (expanded && !mounted) setMounted(true);
225 const contentHeight = useSharedValue(0);
226 const progress = useDerivedValue(() =>
227 withTiming(expanded ? 1 : 0, expanded ? ENTER_TIMING : COLLAPSE_TIMING, (finished) => {
228 if (finished && !expanded) runOnJS(setMounted)(false);
229 }),
230 );
231 const clipStyle = useAnimatedStyle(() => ({
232 height: contentHeight.value * progress.value,
233 opacity: progress.value,
234 }));
235 if (!mounted) return null;
236 return (
237 <Animated.View style={[{ overflow: "hidden" }, clipStyle]}>
238 {/* Absolute, so it lays out at its natural height inside the shorter clip. */}
239 <View
240 className={cn(
241 "absolute inset-x-0 top-0",
242 Platform.OS === "ios" ? "px-3 pt-1 pb-2" : "pt-3",
243 )}
244 onLayout={(event) => contentHeight.set(event.nativeEvent.layout.height)}
245 >
246 {props.children}
247 </View>
248 </Animated.View>
249 );
251function SwipeableToast(props: ToastProps & { readonly onDismiss: () => void }) {
252 const gt = useGT();
253 const [glassReady, setGlassReady] = useState(Platform.OS !== "ios");
254 const finishEntering = useCallback(() => setGlassReady(true), []);
255 // UIKit can skip glass on a moving host; remount the surface after entry so its blur installs.
256 const toastEntering = (values: EntryAnimationsValues) => {
257 "worklet";
258 return {
259 initialValues: { originY: values.targetOriginY + values.targetHeight + 12 },
260 animations: { originY: withTiming(values.targetOriginY, ENTER_TIMING) },
261 callback: (finished: boolean) => {
262 if (finished) runOnJS(finishEntering)();
263 },
264 };
265 };
266 const { onDismiss } = props;
267 const translation = useSharedValue(0);
268 const width = useSharedValue(0);
269 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the Reanimated swipe translation animation on unmount
270 useLayoutEffect(
271 () => () => {
272 cancelAnimation(translation);
273 },
274 [translation],
275 );
276 const gesture = usePanGesture({
277 activeOffsetX: [-10, 10],
278 failOffsetY: [-12, 12],
279 onUpdate: (event) => {
280 translation.set(event.translationX);
281 },
282 onDeactivate: (event) => {
283 if (
284 !event.canceled &&
285 (Math.abs(event.translationX) > width.value * 0.25 ||
286 (Math.abs(event.velocityX) > 800 && event.translationX * event.velocityX > 0))
287 ) {
288 const direction = Math.sign(event.translationX || event.velocityX);
289 translation.set(
290 withTiming(direction * (width.value + 24), SWIPE_TIMING, (finished) => {
291 if (finished) runOnJS(onDismiss)();
292 }),
293 );
294 } else {
295 translation.set(withTiming(0, SWIPE_TIMING));
296 }
297 },
298 });
299 const animatedStyle = useAnimatedStyle(() => ({
300 transform: [{ translateX: translation.value }],
301 }));
302 return (
303 <Animated.View
304 className={Platform.OS === "android" ? "overflow-hidden" : undefined}
305 pointerEvents="box-none"
306 exiting={TOAST_EXITING}
307 onAccessibilityEscape={onDismiss}
308 onLayout={(event) => {
309 width.set(event.nativeEvent.layout.width);
310 }}
311 >
312 <GestureDetector gesture={gesture}>
313 <Animated.View collapsable={false} entering={toastEntering} style={animatedStyle}>
314 {Platform.OS === "android" ? (
315 // Keep the dismiss target separate so TalkBack can also focus the action button.
316 <View
317 accessible
318 accessibilityRole="alert"
319 accessibilityLiveRegion="assertive"
320 accessibilityLabel={props.message}
321 accessibilityActions={[{ name: "dismiss", label: gt`Dismiss message` }]}
322 onAccessibilityAction={({ nativeEvent }) => {
323 if (nativeEvent.actionName === "dismiss") onDismiss();
324 }}
325 pointerEvents="none"
326 style={StyleSheet.absoluteFill}
327 />
328 ) : null}
329 <ToastContent {...props} glassReady={glassReady} />
330 </Animated.View>
331 </GestureDetector>
332 </Animated.View>
333 );