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

Toast.tsx

216 lines7.5 KB

1import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens";
2import { useCallback, useEffect, useLayoutEffect, useMemo, 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 );
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 useEffect(() => {
59 if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(props.message);
60 }, [props.message]);
61 const surface = (
62 <GlassSurface
63 key={props.glassReady === false ? "entering" : "settled"}
64 chrome={Platform.OS === "ios" && colorScheme === "dark" ? "none" : undefined}
65 tintColor={Platform.OS === "ios" ? null : undefined}
66 className={Platform.OS === "ios" ? "bg-transparent p-3" : "p-3"}
67 style={{ borderRadius }}
68 >
69 <View className="flex-row items-center gap-3">
70 {props.busy ? (
71 <AppActivityIndicator />
72 ) : (
73 <SymbolView
74 name={props.tone === "danger" ? "exclamationmark.triangle" : "checkmark.circle"}
75 size={20}
76 tintColorClassName={
77 props.tone === "danger" ? "accent-danger-foreground" : "accent-icon"
78 }
79 />
80 )}
81 <View className="min-w-0 flex-1" accessibilityLiveRegion="polite">
82 <AppText
83 textRole="footnote"
84 className="font-t3-semibold"
85 numberOfLines={props.singleLine ? 1 : undefined}
86 accessibilityLabel={props.singleLine ? message : undefined}
87 >
88 {message}
89 </AppText>
90 {props.description && !props.singleLine ? (
91 <AppText textRole="label" className="text-foreground-muted">
92 {props.description}
93 </AppText>
94 ) : null}
95 </View>
96 {inlineAction && action ? <View className="self-center">{action}</View> : null}
97 {props.onDismiss && props.dismissMode !== "swipe" ? (
98 <IconButton accessibilityLabel="Dismiss message" icon="xmark" onPress={props.onDismiss} />
99 ) : null}
100 </View>
101 {action && !inlineAction ? <View className="mt-2 self-end">{action}</View> : null}
102 </GlassSurface>
103 );
104 return Platform.OS === "ios" ? (
105 <View
106 style={{
107 borderRadius,
108 boxShadow: [
109 {
110 offsetX: 0,
111 offsetY: 0,
112 blurRadius: 8,
113 color: colorScheme === "dark" ? "rgba(0, 0, 0, 0.22)" : "rgba(0, 0, 0, 0.08)",
114 },
115 ],
116 }}
117 >
118 {surface}
119 </View>
120 ) : (
121 surface
122 );
124​
125const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };
126const ENTER_TIMING = {
127 duration: MOBILE_MOTION.enter,
128 easing: Easing.out(Easing.cubic),
129 reduceMotion: ReduceMotion.System,
130};
131const TOAST_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);
132function SwipeableToast(props: ToastProps & { readonly onDismiss: () => void }) {
133 const [glassReady, setGlassReady] = useState(Platform.OS !== "ios");
134 const finishEntering = useCallback(() => setGlassReady(true), []);
135 // UIKit can skip glass on a moving host; remount the surface after entry so its blur installs.
136 const toastEntering = useMemo(
137 () => (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 [finishEntering],
148 );
149 const { onDismiss } = props;
150 const translation = useSharedValue(0);
151 const width = useSharedValue(0);
152 useLayoutEffect(
153 () => () => {
154 cancelAnimation(translation);
155 },
156 [translation],
157 );
158 const gesture = usePanGesture({
159 activeOffsetX: [-10, 10],
160 failOffsetY: [-12, 12],
161 onUpdate: (event) => {
162 translation.set(event.translationX);
163 },
164 onDeactivate: (event) => {
165 if (
166 !event.canceled &&
167 (Math.abs(event.translationX) > width.value * 0.25 ||
168 (Math.abs(event.velocityX) > 800 && event.translationX * event.velocityX > 0))
169 ) {
170 const direction = Math.sign(event.translationX || event.velocityX);
171 translation.set(
172 withTiming(direction * (width.value + 24), SWIPE_TIMING, (finished) => {
173 if (finished) runOnJS(onDismiss)();
174 }),
175 );
176 } else {
177 translation.set(withTiming(0, SWIPE_TIMING));
178 }
179 },
180 });
181 const animatedStyle = useAnimatedStyle(() => ({
182 transform: [{ translateX: translation.value }],
183 }));
184 return (
185 <Animated.View
186 className={Platform.OS === "android" ? "overflow-hidden" : undefined}
187 pointerEvents="box-none"
188 exiting={TOAST_EXITING}
189 onAccessibilityEscape={onDismiss}
190 onLayout={(event) => {
191 width.set(event.nativeEvent.layout.width);
192 }}
193 >
194 <GestureDetector gesture={gesture}>
195 <Animated.View collapsable={false} entering={toastEntering} style={animatedStyle}>
196 {Platform.OS === "android" ? (
197 // Keep the dismiss target separate so TalkBack can also focus the action button.
198 <View
199 accessible
200 accessibilityRole="alert"
201 accessibilityLiveRegion="assertive"
202 accessibilityLabel={props.message}
203 accessibilityActions={[{ name: "dismiss", label: "Dismiss message" }]}
204 onAccessibilityAction={({ nativeEvent }) => {
205 if (nativeEvent.actionName === "dismiss") onDismiss();
206 }}
207 pointerEvents="none"
208 style={StyleSheet.absoluteFill}
209 />
210 ) : null}
211 <ToastContent {...props} glassReady={glassReady} />
212 </Animated.View>
213 </GestureDetector>
214 </Animated.View>
215 );