TypeScript
fix(mobile): share toast motion and bring bottom undo to iOS (#23968)
Alex8096799b85bd
diff --git a/apps/mobile/src/components/ui/GlassSurface.tsx b/apps/mobile/src/components/ui/GlassSurface.tsxindex 05bf0532e46..8af080fc19c 100644--- a/apps/mobile/src/components/ui/GlassSurface.tsx+++ b/apps/mobile/src/components/ui/GlassSurface.tsx@@ -25,7 +25,8 @@ interface GlassSurfaceProps extends ViewProps {readonly ref?: Ref<ViewInstance>;readonly children: ReactNode;readonly glassEffectStyle?: "clear" | "regular" | "none";- readonly tintColor?: ColorValue;+ // null leaves UIKit's material untinted instead of applying the theme tint.+ readonly tintColor?: ColorValue | null;readonly tintColorClassName?: string;readonly chrome?: "default" | "none";readonly fallbackColor?: ColorValue;@@ -71,7 +72,7 @@ export function GlassSurface({className,)}glassEffectStyle={glassEffectStyle}- tintColor={tintColor === undefined ? undefined : String(tintColor)}+ tintColor={tintColor == null ? undefined : String(tintColor)}tintColorClassName={tintColorClassName ?? (tintColor === undefined ? "accent-glass-tint" : undefined)}diff --git a/apps/mobile/src/components/ui/Toast.tsx b/apps/mobile/src/components/ui/Toast.tsxindex 2daa0873b65..96039971d1f 100644--- a/apps/mobile/src/components/ui/Toast.tsx+++ b/apps/mobile/src/components/ui/Toast.tsx@@ -1,36 +1,71 @@-import { MOBILE_SHAPE } from "../../lib/designTokens";-import { useEffect } from "react";-import { AccessibilityInfo, Platform, View, useWindowDimensions } from "react-native";+import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens";+import { useCallback, useEffect, useLayoutEffect, useMemo, useState } from "react";+import { AccessibilityInfo, Platform, StyleSheet, View, useWindowDimensions } from "react-native";+import { GestureDetector, usePanGesture } from "react-native-gesture-handler";+import Animated, {+ cancelAnimation,+ Easing,+ FadeOut,+ ReduceMotion,+ runOnJS,+ useAnimatedStyle,+ 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 interface ToastProps {+export type ToastProps = {readonly message: string;readonly description?: string;+ readonly singleLine?: boolean;readonly tone?: "default" | "success" | "danger";readonly busy?: boolean;readonly action?: { readonly label: string; readonly onPress: () => void };- readonly onDismiss?: () => void;-}+} & (+ | { readonly dismissMode: "swipe"; readonly onDismiss: () => void }+ | { readonly dismissMode?: "button"; readonly onDismiss?: () => void }+);export function Toast(props: ToastProps) {+ return props.dismissMode === "swipe" ? (+ <SwipeableToast {...props} />+ ) : (+ <ToastContent {...props} />+ );+}++function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) {const { fontScale } = useWindowDimensions();- // A one-line message keeps its action on the same row. Descriptions and- // accessibility text sizes need the full width, so the action moves below.- const inlineAction = !props.description && fontScale < 1.5;+ const { colorScheme } = useControlTheme();+ const borderRadius = Platform.OS === "ios" ? 31 : 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 ? (<Button label={props.action.label} onPress={props.action.onPress} />) : null;useEffect(() => {if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(props.message);}, [props.message]);- return (- <GlassSurface className="p-3" style={{ borderRadius: MOBILE_SHAPE.toast }}>+ const surface = (+ <GlassSurface+ key={props.glassReady === false ? "entering" : "settled"}+ chrome={Platform.OS === "ios" && colorScheme === "dark" ? "none" : undefined}+ tintColor={Platform.OS === "ios" ? null : undefined}+ className={Platform.OS === "ios" ? "bg-transparent p-3" : "p-3"}+ style={{ borderRadius }}+ ><View className="flex-row items-center gap-3">{props.busy ? (<AppActivityIndicator />@@ -44,21 +79,138 @@ export function Toast(props: ToastProps) {/>)}<View className="min-w-0 flex-1" accessibilityLiveRegion="polite">- <AppText textRole="footnote" className="font-t3-semibold">- {props.message}+ <AppText+ textRole="footnote"+ className="font-t3-semibold"+ numberOfLines={props.singleLine ? 1 : undefined}+ accessibilityLabel={props.singleLine ? message : undefined}+ >+ {message}</AppText>- {props.description ? (+ {props.description && !props.singleLine ? (<AppText textRole="label" className="text-foreground-muted">{props.description}</AppText>) : null}</View>{inlineAction ? action : null}- {props.onDismiss ? (+ {props.onDismiss && props.dismissMode !== "swipe" ? (<IconButton accessibilityLabel="Dismiss message" icon="xmark" onPress={props.onDismiss} />) : null}</View>{action && !inlineAction ? <View className="mt-2 self-end">{action}</View> : null}</GlassSurface>);+ return Platform.OS === "ios" ? (+ <View+ style={{+ borderRadius,+ boxShadow: [+ {+ offsetX: 0,+ offsetY: 0,+ blurRadius: 8,+ color: colorScheme === "dark" ? "rgba(0, 0, 0, 0.22)" : "rgba(0, 0, 0, 0.08)",+ },+ ],+ }}+ >+ {surface}+ </View>+ ) : (+ surface+ );+}++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);+function SwipeableToast(props: ToastProps & { readonly onDismiss: () => void }) {+ 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 = useMemo(+ () => (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)();+ },+ };+ },+ [finishEntering],+ );+ const { onDismiss } = props;+ const translation = useSharedValue(0);+ const width = useSharedValue(0);+ 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 (+ <Animated.View+ className={Platform.OS === "android" ? "overflow-hidden" : undefined}+ pointerEvents="box-none"+ exiting={TOAST_EXITING}+ onAccessibilityEscape={onDismiss}+ onLayout={(event) => {+ width.set(event.nativeEvent.layout.width);+ }}+ >+ <GestureDetector gesture={gesture}>+ <Animated.View collapsable={false} entering={toastEntering} style={animatedStyle}>+ {Platform.OS === "android" ? (+ // Keep the dismiss target separate so TalkBack can also focus the action button.+ <View+ accessible+ accessibilityRole="alert"+ accessibilityLiveRegion="assertive"+ accessibilityLabel={props.message}+ accessibilityActions={[{ name: "dismiss", label: "Dismiss message" }]}+ onAccessibilityAction={({ nativeEvent }) => {+ if (nativeEvent.actionName === "dismiss") onDismiss();+ }}+ pointerEvents="none"+ style={StyleSheet.absoluteFill}+ />+ ) : null}+ <ToastContent {...props} glassReady={glassReady} />+ </Animated.View>+ </GestureDetector>+ </Animated.View>+ );}diff --git a/apps/mobile/src/features/development/ComponentCatalogScreen.tsx b/apps/mobile/src/features/development/ComponentCatalogScreen.tsxindex d759ee6d078..9a3d894d384 100644--- a/apps/mobile/src/features/development/ComponentCatalogScreen.tsx+++ b/apps/mobile/src/features/development/ComponentCatalogScreen.tsx@@ -4,6 +4,7 @@ import { Progress } from "../../components/ui/Progress";import { useNavigation } from "@react-navigation/native";import { useRef, useState } from "react";import { View, type TextInputInstance } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";import { AppText, AppTextInput } from "../../components/ui/AppText";import { Sheet } from "../../components/ui/Sheet";@@ -34,6 +35,7 @@ const CHOICES = [];export function ComponentCatalogScreen() {+ const insets = useSafeAreaInsets();const navigation = useNavigation();const appearance = useAppearancePreferences();const [page, setPage] = useState("controls");@@ -204,22 +206,7 @@ export function ComponentCatalogScreen() {<View className="gap-3"><AppText className="text-lg font-t3-semibold">Feedback and presentation</AppText><Notice message="This action could not finish. Try again." tone="danger" />- {notice ? (- <Toast- message="Changes are ready to review."- tone="success"- action={{- label: "Undo",- onPress: () => {- setNotice(false);- setText("Restored example");- },- }}- onDismiss={() => setNotice(false)}- />- ) : (- <Button label="Show notice" onPress={announceAction} />- )}+ <Button label="Show notice" onPress={announceAction} /><View className="flex-row flex-wrap gap-2"><Button label="Sheet" onPress={() => setSheet(true)} /><Button label="Dialog" onPress={confirm} />@@ -275,6 +262,28 @@ export function ComponentCatalogScreen() {</View>) : null}</ScreenScrollView>+ {page === "feedback" && notice ? (+ <View+ collapsable={false}+ className="absolute inset-x-3 z-[100]"+ style={{ bottom: insets.bottom + 12 }}+ pointerEvents="box-none"+ >+ <Toast+ message="Changes are ready to review."+ tone="success"+ dismissMode="swipe"+ action={{+ label: "Undo",+ onPress: () => {+ setNotice(false);+ setText("Restored example");+ },+ }}+ onDismiss={() => setNotice(false)}+ />+ </View>+ ) : null}{sheet ? (<Sheet title="Example sheet" onClose={() => setSheet(false)}><ScreenScrollViewdiff --git a/apps/mobile/src/features/home/ThreadUndoNotice.android.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.android.tsxdeleted file mode 100644index d1caf4e664b..00000000000--- a/apps/mobile/src/features/home/ThreadUndoNotice.android.tsx+++ /dev/null@@ -1,128 +0,0 @@-import { useLayoutEffect, useState } from "react";-import { StyleSheet, View } from "react-native";-import { GestureDetector, usePanGesture } from "react-native-gesture-handler";-import Animated, {- cancelAnimation,- Easing,- FadeOut,- ReduceMotion,- runOnJS,- useAnimatedStyle,- useSharedValue,- withTiming,- type EntryAnimationsValues,-} from "react-native-reanimated";-import { useSafeAreaInsets } from "react-native-safe-area-context";-import { Toast } from "../../components/ui/Toast";-import { MOBILE_MOTION } from "../../lib/designTokens";-import {- dismissThreadUndoNotice,- readThreadUndoNotice,- useThreadUndoNotice,-} from "./thread-undo-notice";--const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };-const ENTER_TIMING = {- duration: MOBILE_MOTION.enter,- easing: Easing.out(Easing.cubic),- reduceMotion: ReduceMotion.System,-};-const NOTICE_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);-const noticeEntering = (values: EntryAnimationsValues) => {- "worklet";- return {- initialValues: { originY: values.targetOriginY + values.targetHeight + 12 },- animations: { originY: withTiming(values.targetOriginY, ENTER_TIMING) },- };-};--export function ThreadUndoNotice(props: { readonly visible: boolean }) {- const notice = useThreadUndoNotice();- // Replacing a notice must also cancel the native gesture tracking the old one.- const [instance, setInstance] = useState({ notice, key: 0 });- if (instance.notice !== notice) setInstance({ notice, key: instance.key + 1 });- if (!props.visible || notice === null) return null;- return <SwipeableUndoNotice key={instance.key} notice={notice} />;-}--function SwipeableUndoNotice(props: {- readonly notice: NonNullable<ReturnType<typeof useThreadUndoNotice>>;-}) {- const { notice } = props;- const insets = useSafeAreaInsets();- const translation = useSharedValue(0);- const width = useSharedValue(0);-- useLayoutEffect(- () => () => {- cancelAnimation(translation);- },- [translation],- );-- const dismiss = () => {- // A newer action can replace the notice while the swipe is animating out.- if (readThreadUndoNotice() === notice) dismissThreadUndoNotice();- };- 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(dismiss)();- }),- );- } else {- translation.set(withTiming(0, SWIPE_TIMING));- }- },- });- const animatedStyle = useAnimatedStyle(() => ({- transform: [{ translateX: translation.value }],- }));-- // Clip the entrance above navigation; the notice intentionally covers the anchored FAB.- return (- <Animated.View- className="absolute inset-x-3 z-[100] overflow-hidden"- style={{ bottom: insets.bottom + 12 }}- pointerEvents="box-none"- exiting={NOTICE_EXITING}- onLayout={(event) => {- width.set(event.nativeEvent.layout.width);- }}- >- <GestureDetector gesture={gesture}>- <Animated.View collapsable={false} entering={noticeEntering} style={animatedStyle}>- {/* Keep the dismiss target separate so TalkBack can also focus Undo. */}- <View- accessible- accessibilityRole="alert"- accessibilityLiveRegion="assertive"- accessibilityLabel={`${notice.action} thread`}- accessibilityActions={[{ name: "dismiss", label: "Dismiss message" }]}- onAccessibilityAction={({ nativeEvent }) => {- if (nativeEvent.actionName === "dismiss") dismiss();- }}- pointerEvents="none"- style={StyleSheet.absoluteFill}- />- <Toast- message={`${notice.action} thread`}- action={{ label: "Undo", onPress: () => void notice.undo() }}- />- </Animated.View>- </GestureDetector>- </Animated.View>- );-}diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsxindex 578dc356e6e..ec7c630d29e 100644--- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx+++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx@@ -1,17 +1,76 @@-import { View } from "react-native";+import { useState } from "react";+import { useKeyboardState } from "react-native-keyboard-controller";+import { Platform, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { Toast } from "../../components/ui/Toast";-import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";-import { dismissThreadUndoNotice, useThreadUndoNotice } from "./thread-undo-notice";+import {+ useDeviceType,+ useDuoBottomBarInset,+ useNativeLayoutMetrics,+ useNativeColumnLayoutMetrics,+} from "../../native/native-layout-metrics";+import { workspaceSearchBottomClearance } from "../workspace/workspace-tabs-state";+import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";+import {+ dismissThreadUndoNotice,+ readThreadUndoNotice,+ useThreadUndoNotice,+} from "./thread-undo-notice";export function ThreadUndoNotice(props: { readonly visible: boolean }) {const notice = useThreadUndoNotice();const insets = useSafeAreaInsets();+ const columnMetrics = useNativeColumnLayoutMetrics();+ const rootMetrics = useNativeLayoutMetrics();+ const workspace = useWorkspaceTabs();+ const deviceType = useDeviceType();+ const keyboardHeight = useKeyboardState((keyboard) => keyboard.height);+ const horizontalInsets =+ Platform.OS === "ios"+ ? deviceType === "phone"+ ? { left: 29, right: 23 }+ : { left: 20, right: 20 }+ : { left: 12, right: 12 };+ // The Duo's native tab pill extends above the 48-point toolbar reservation.+ const workspacePadding =+ useDuoBottomBarInset() === undefined+ ? deviceType === "phone" && keyboardHeight === 0+ ? 32+ : 16+ : 8;+ // Replacing a notice must also cancel the native gesture tracking the old one.+ const [instance, setInstance] = useState({ notice, key: 0 });+ if (instance.notice !== notice) setInstance({ notice, key: instance.key + 1 });if (!props.visible || notice === null) return null;+ const foldedResting =+ rootMetrics?.hasHinge &&+ rootMetrics.horizontalSizeClass === "compact" &&+ workspace?.state.tabs.threads.searchMode === "resting";+ const bottom =+ Platform.OS === "ios"+ ? foldedResting+ ? Math.max(rootMetrics.safeArea.bottom, keyboardHeight) + 8+ : rootMetrics?.hasHinge && rootMetrics.verticalBarEdge !== "none"+ ? // The column's safe area already includes UIKit's search toolbar in this posture.+ workspaceSearchBottomClearance({+ bottomInset: rootMetrics.safeArea.bottom,+ bottomBarInset: rootMetrics.bottomBarInset,+ keyboardHeight,+ }) -+ 16 ++ 8+ : Math.max(+ insets.bottom,+ columnMetrics?.safeArea.bottom ?? 0,+ (workspace?.bottomClearance ?? 0) - workspacePadding,+ ) + 8+ : insets.bottom + 12;return (<View- className="absolute inset-x-3 z-[100]"- style={{ top: insets.top + APP_BAR_HEIGHT + 8 }}+ key={instance.key}+ collapsable={false}+ className="absolute z-[100]"+ style={{ bottom, ...horizontalInsets }}pointerEvents="box-none"><Toast@@ -22,7 +81,11 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) {void notice.undo();},}}- onDismiss={dismissThreadUndoNotice}+ dismissMode="swipe"+ onDismiss={() => {+ // A newer action can replace the notice while the swipe is animating out.+ if (readThreadUndoNotice() === notice) dismissThreadUndoNotice();+ }}/></View>);diff --git a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsxindex 46721018998..cf472442f46 100644--- a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx+++ b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx@@ -1,10 +1,13 @@import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { tryOpenExternalUrl } from "../../lib/openExternalUrl";import * as Haptics from "expo-haptics";-import { useEffect, useRef } from "react";+import { HeaderHeightContext } from "@react-navigation/elements";+import { useContext, useEffect, useRef } from "react";+import { Platform } from "react-native";import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";import { useSafeAreaInsets } from "react-native-safe-area-context";import { Toast } from "../../components/ui/Toast";+import { useToolbarLayout } from "../../components/ui/useToolbarLayout";import { MOBILE_MOTION } from "../../lib/designTokens";import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";import type { GitActionProgress } from "../../state/use-vcs-action-state";@@ -17,6 +20,13 @@ export function GitActionProgressOverlay(props: {const { progress, onDismiss } = props;const openPullRequest = props.onOpenPullRequest;const insets = useSafeAreaInsets();+ // Keyboard-copy feedback sits outside the screen's native header context.+ const headerHeight = useContext(HeaderHeightContext) ?? insets.top + APP_BAR_HEIGHT;+ const toolbar = useToolbarLayout();+ const top =+ Platform.OS === "android"+ ? toolbar.paddingTop + toolbar.height + toolbar.paddingBottom + 8+ : headerHeight + 8;const prevPhaseRef = useRef(progress.phase);useEffect(() => {@@ -37,9 +47,6 @@ export function GitActionProgressOverlay(props: {: tryOpenExternalUrl(progress.prUrl, "pull-request"));return;}- if (progress.phase === "success" || progress.phase === "error") {- onDismiss();- }};if (progress.phase === "idle") {@@ -56,10 +63,12 @@ export function GitActionProgressOverlay(props: {entering={FadeIn.duration(MOBILE_MOTION.enter).reduceMotion(ReduceMotion.System)}exiting={FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System)}className="absolute inset-x-3 z-[100]"- style={{ top: insets.top + APP_BAR_HEIGHT + 8 }}+ style={{ top }}pointerEvents="box-none"+ onAccessibilityEscape={onDismiss}><Toast+ singleLinemessage={progress.label ?? "Source control"}description={progress.description ?? undefined}tone={@@ -71,7 +80,6 @@ export function GitActionProgressOverlay(props: {}busy={progress.phase === "running"}action={openLabel ? { label: openLabel, onPress: handlePress } : undefined}- onDismiss={progress.phase === "running" ? undefined : onDismiss}/></Animated.View>);