import { useGT } from "gt-react-native";
import { cn } from "../../lib/cn";
import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens";
import { type ReactNode, useCallback, useEffect, useLayoutEffect, useState } from "react";
import {
AccessibilityInfo,
Platform,
Pressable,
StyleSheet,
View,
useWindowDimensions,
} from "react-native";
import { GestureDetector, usePanGesture } from "react-native-gesture-handler";
import Animated, {
cancelAnimation,
Easing,
FadeOut,
ReduceMotion,
runOnJS,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withTiming,
type EntryAnimationsValues,
} from "react-native-reanimated";
import { AppText } from "./AppText";
import { Button } from "./Button";
import { GlassSurface } from "./GlassSurface";
import { useControlTheme } from "./useControlTheme";
import { IconButton } from "./IconButton";
import { AppActivityIndicator } from "./AppActivityIndicator";
import { SymbolView } from "./AppSymbol";
export type ToastProps = {
readonly message: string;
readonly description?: string;
readonly singleLine?: boolean;
readonly tone?: "default" | "success" | "warning" | "danger";
readonly busy?: boolean;
readonly action?: { readonly label: string; readonly onPress: () => void };
/** Details a chevron beside the message reveals below it while `expanded`. */
readonly children?: ReactNode;
readonly expanded?: boolean;
readonly onExpandedChange?: (expanded: boolean) => void;
} & (
| { readonly dismissMode: "swipe"; readonly onDismiss: () => void }
| { readonly dismissMode?: "button"; readonly onDismiss?: () => void }
);
export function Toast(props: ToastProps) {
return props.dismissMode === "swipe" ? (
) : (
);
}
function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) {
const gt = useGT();
const { fontScale } = useWindowDimensions();
const { colorScheme } = useControlTheme();
const borderRadius = Platform.OS === "ios" ? 28 : MOBILE_SHAPE.toast;
// Explicit single-line notices reserve the action's width and truncate the text.
const inlineAction = props.singleLine || (!props.description && fontScale < 1.5);
const message =
props.singleLine && props.description
? `${props.message}: ${props.description}`
: props.message;
const action = props.action ? (
) : null;
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- announces the toast message to VoiceOver through AccessibilityInfo
useEffect(() => {
if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(props.message);
}, [props.message]);
const surface = (
{props.busy ? (
) : (
)}
{message}
{props.description && !props.singleLine ? (
{props.description}
) : null}
{inlineAction && action ? {action} : null}
{props.onExpandedChange ? (
) : null}
{props.onDismiss && props.dismissMode !== "swipe" ? (
) : null}
{action && !inlineAction ? {action} : null}
{props.children ? (
{props.children}
) : null}
);
return Platform.OS === "ios" ? (
{surface}
) : (
surface
);
}
function Disclosure(props: {
readonly expanded: boolean;
readonly onExpandedChange: (expanded: boolean) => void;
}) {
const gt = useGT();
const { expanded } = props;
const turn = useDerivedValue(() =>
withTiming(expanded ? 1 : 0, expanded ? ENTER_TIMING : COLLAPSE_TIMING),
);
const chevronStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${turn.value * 180}deg` }],
}));
return (
props.onExpandedChange(!expanded)}
className={cn(
"items-center justify-center rounded-full bg-secondary active:opacity-70",
Platform.OS === "ios" ? "size-10" : "size-12",
)}
>
);
}
const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };
const ENTER_TIMING = {
duration: MOBILE_MOTION.enter,
easing: Easing.out(Easing.cubic),
reduceMotion: ReduceMotion.System,
};
const TOAST_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);
const COLLAPSE_TIMING = {
duration: MOBILE_MOTION.exit,
easing: Easing.out(Easing.cubic),
reduceMotion: ReduceMotion.System,
};
/**
* Animates the clip's height every frame so the glass grows with it; a layout transition on the
* content alone left the glass jumping to its final size. Content stays mounted until collapsed.
*/
function ToastExpansion(props: { readonly expanded: boolean; readonly children: ReactNode }) {
const { expanded } = props;
const [mounted, setMounted] = useState(expanded);
if (expanded && !mounted) setMounted(true);
const contentHeight = useSharedValue(0);
const progress = useDerivedValue(() =>
withTiming(expanded ? 1 : 0, expanded ? ENTER_TIMING : COLLAPSE_TIMING, (finished) => {
if (finished && !expanded) runOnJS(setMounted)(false);
}),
);
const clipStyle = useAnimatedStyle(() => ({
height: contentHeight.value * progress.value,
opacity: progress.value,
}));
if (!mounted) return null;
return (
{/* Absolute, so it lays out at its natural height inside the shorter clip. */}
contentHeight.set(event.nativeEvent.layout.height)}
>
{props.children}
);
}
function SwipeableToast(props: ToastProps & { readonly onDismiss: () => void }) {
const gt = useGT();
const [glassReady, setGlassReady] = useState(Platform.OS !== "ios");
const finishEntering = useCallback(() => setGlassReady(true), []);
// UIKit can skip glass on a moving host; remount the surface after entry so its blur installs.
const toastEntering = (values: EntryAnimationsValues) => {
"worklet";
return {
initialValues: { originY: values.targetOriginY + values.targetHeight + 12 },
animations: { originY: withTiming(values.targetOriginY, ENTER_TIMING) },
callback: (finished: boolean) => {
if (finished) runOnJS(finishEntering)();
},
};
};
const { onDismiss } = props;
const translation = useSharedValue(0);
const width = useSharedValue(0);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the Reanimated swipe translation animation on unmount
useLayoutEffect(
() => () => {
cancelAnimation(translation);
},
[translation],
);
const gesture = usePanGesture({
activeOffsetX: [-10, 10],
failOffsetY: [-12, 12],
onUpdate: (event) => {
translation.set(event.translationX);
},
onDeactivate: (event) => {
if (
!event.canceled &&
(Math.abs(event.translationX) > width.value * 0.25 ||
(Math.abs(event.velocityX) > 800 && event.translationX * event.velocityX > 0))
) {
const direction = Math.sign(event.translationX || event.velocityX);
translation.set(
withTiming(direction * (width.value + 24), SWIPE_TIMING, (finished) => {
if (finished) runOnJS(onDismiss)();
}),
);
} else {
translation.set(withTiming(0, SWIPE_TIMING));
}
},
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: translation.value }],
}));
return (
{
width.set(event.nativeEvent.layout.width);
}}
>
{Platform.OS === "android" ? (
// Keep the dismiss target separate so TalkBack can also focus the action button.
{
if (nativeEvent.actionName === "dismiss") onDismiss();
}}
pointerEvents="none"
style={StyleSheet.absoluteFill}
/>
) : null}
);
}