Open History to see the last commit
1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import { BlurView } from "expo-blur";
3import type { ReactNode } from "react";
4import { useCallback, useEffect, useRef, useState } from "react";
5import type { StyleProp, ViewStyle } from "react-native";
6import { BackHandler, Pressable, ScrollView, View } from "react-native";
7import { useKeyboardState } from "react-native-keyboard-controller";
8import Animated, { FadeIn } from "react-native-reanimated";
9
10import { appBlurTargetRef } from "../lib/appBlurTarget";
11import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
12import { useThemeColor } from "../lib/useThemeColor";
13import { cn } from "../lib/cn";
14import { type AppSymbolName, SymbolView } from "./AppSymbol";
15import { AppText as Text } from "./AppText";
16import { OverlayPortal } from "./OverlayPortal";
17
18const MENU_WIDTH = 250;
19const SCREEN_MARGIN = 12;
20const ANCHOR_GAP = 6;
21
22// Anchor position is snapshotted in window coordinates when the menu opens;
23// the overlay root measures itself the same way, and the menu is placed from
24// the delta. Both snapshots are taken at open time so later reflows (keyboard
25// show/hide, screen transitions) can't flip an opens-up menu to opens-down
26// mid-presentation.
27type AnchorSnapshot = {
28 readonly x: number;
29 readonly y: number;
30 readonly width: number;
31 readonly height: number;
32};
33
34type OverlayFrame = {
35 readonly x: number;
36 readonly y: number;
37 readonly width: number;
38 readonly height: number;
39};
40
41export type AndroidAnchoredMenuProps = {
42 readonly actions: readonly MenuAction[];
43 readonly title?: string;
44 readonly onPressAction?: MenuComponentProps["onPressAction"];
45 /** Applied to the anchor wrapper — call sites flex these to fill toolbars. */
46 readonly className?: string;
47 readonly style?: StyleProp<ViewStyle>;
48 /**
49 * Plain children open the menu on tap (the wrapper owns the press). A
50 * render function keeps the children interactive and hands them `open` to
51 * call from their own gesture — e.g. a row that selects on tap and opens
52 * this menu on long-press.
53 */
54 readonly children: ReactNode | ((open: () => void) => ReactNode);
55};
56
57/**
58 * Token-styled anchored dropdown for Android, drop-in for the subset of the
59 * MenuView contract the app uses (actions with state/subtitle/image/
60 * attributes, one level of subactions). The native AppCompat PopupMenu caps
61 * out on theming — stock animation, item metrics, and submenu chrome — so
62 * ControlPillMenu renders this instead on Android while iOS keeps the native
63 * UIMenu. Styling follows the themed native popup (12dp radius, plain rows,
64 * trailing check glyph); submenus drill in under a muted parent-title header.
65 */
66export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
67 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
68 const [path, setPath] = useState<readonly MenuAction[]>([]);
69 // Height of the modal's root view, in the modal's own coordinate space.
70 // Menus that flip above their anchor are pinned by their BOTTOM edge
71 // (bottom = rootHeight - anchorTop), so drill-in height changes grow
72 // upward without any re-measurement — positioning them via `top` from the
73 // menu's measured height made every submenu transition settle over two
74 // frames and jitter.
75 const [rootHeight, setRootHeight] = useState<number | null>(null);
76 // Window frame of the overlay root, measured on layout. Anchor coordinates
77 // are converted into this frame, so the menu lands correctly no matter
78 // where the portal host sits (status bar, keyboard resize, etc.).
79 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
80 const anchorRef = useRef<View>(null);
81 const overlayRef = useRef<View>(null);
82
83 const { themeAppearance } = useAppearancePreferences();
84 const isDarkMode = themeAppearance === "dark";
85 const keyboardVisible = useKeyboardState((state) => state.isVisible);
86 const keyboardHeight = useKeyboardState((state) => state.height);
87 const rippleColor = useThemeColor("--color-subtle");
88 const iconColor = useThemeColor("--color-icon");
89 const iconSubtleColor = useThemeColor("--color-icon-subtle");
90 const dangerColor = useThemeColor("--color-danger-foreground");
91
92 const close = useCallback(() => {
93 setAnchor(null);
94 setPath([]);
95 setOverlay(null);
96 setRootHeight(null);
97 }, []);
98
99 const open = useCallback(() => {
100 anchorRef.current?.measureInWindow((x, y, width, height) => {
101 setAnchor({ x, y, width, height });
102 });
103 }, []);
104
105 const measureOverlay = useCallback(() => {
106 overlayRef.current?.measureInWindow((x, y, width, height) => {
107 setOverlay({ x, y, width, height });
108 setRootHeight(height);
109 });
110 }, []);
111
112 // The dropdown renders in-window (no Modal takes focus), so the hardware
113 // back gesture needs explicit handling while it is open. Back steps out of
114 // a drilled-in submenu one level at a time (mirroring the tappable parent
115 // header) before closing the menu. Under predictive back
116 // (enableOnBackInvokedCallback) this stays correct: back reaches JS
117 // through always-registered OnBackPressedDispatcher callbacks (react-native
118 // core on Android 16+, withAndroidPredictiveBackCompat on 13-15), which
119 // also keeps the system from playing a "leave app" preview while the menu
120 // merely closes.
121 const submenuDepth = path.length;
122 useEffect(() => {
123 if (anchor === null) {
124 return;
125 }
126 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
127 if (submenuDepth > 0) {
128 setPath((current) => current.slice(0, -1));
129 } else {
130 close();
131 }
132 return true;
133 });
134 return () => subscription.remove();
135 }, [anchor, close, submenuDepth]);
136
137 const parent = path.length > 0 ? path[path.length - 1] : null;
138 const levelActions = (parent?.subactions ?? props.actions).filter(
139 (action) => !(action.attributes?.hidden ?? false),
140 );
141
142 // Anchor in overlay-local coordinates (both measured in window space).
143 const local =
144 anchor === null || overlay === null
145 ? null
146 : {
147 x: anchor.x - overlay.x,
148 y: anchor.y - overlay.y,
149 width: anchor.width,
150 height: anchor.height,
151 };
152 const preferredLeft =
153 local === null || overlay === null
154 ? 0
155 : local.x + local.width / 2 <= overlay.width / 2
156 ? local.x
157 : local.x + local.width - MENU_WIDTH;
158 const left =
159 overlay === null
160 ? 0
161 : Math.min(
162 Math.max(preferredLeft, SCREEN_MARGIN),
163 overlay.width - MENU_WIDTH - SCREEN_MARGIN,
164 );
165 // The keyboard stays up while the menu is open (in-window overlay, no
166 // focus change), so the space it covers is not usable — without this the
167 // composer-pill menus "open down" into the IME and can't be tapped.
168 const usableBottom =
169 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
170 const spaceBelow =
171 local === null || overlay === null
172 ? 0
173 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
174 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
175 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
176 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
177 // The menu needs the overlay frame before it can be placed; it stays
178 // unmounted for that first frame so the fade-in plays at the final position.
179 const placeable = local !== null && rootHeight !== null;
180
181 const onPressItem = useCallback(
182 (action: MenuAction) => {
183 if ((action.subactions?.length ?? 0) > 0) {
184 setPath((current) => [...current, action]);
185 return;
186 }
187 close();
188 if (action.id !== undefined) {
189 props.onPressAction?.({
190 nativeEvent: { event: action.id },
191 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
192 }
193 },
194 [close, props.onPressAction],
195 );
196
197 return (
198 <>
199 {typeof props.children === "function" ? (
200 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
201 {props.children(open)}
202 </View>
203 ) : (
204 <Pressable
205 ref={anchorRef}
206 accessibilityRole="button"
207 className={props.className}
208 collapsable={false}
209 style={props.style}
210 onPress={open}
211 >
212 <View pointerEvents="none">{props.children}</View>
213 </Pressable>
214 )}
215 {anchor === null ? null : (
216 <OverlayPortal>
217 <View
218 ref={overlayRef}
219 collapsable={false}
220 className="absolute inset-0"
221 onLayout={measureOverlay}
222 >
223 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
224 {!placeable || local === null ? null : (
225 <Animated.View
226 entering={FadeIn.duration(120)}
227 className="absolute w-[250px] overflow-hidden rounded-[12px] border border-border shadow-2xl"
228 style={{
229 left,
230 maxHeight,
231 ...(opensDown
232 ? { top: local.y + local.height + ANCHOR_GAP }
233 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
234 }}
235 >
236 {/* Frosted backdrop: blur of the app content behind the menu,
237 washed with the translucent card tone so rows keep contrast. */}
238 <BlurView
239 blurMethod="dimezisBlurView"
240 blurTarget={appBlurTargetRef}
241 intensity={40}
242 tint={isDarkMode ? "dark" : "light"}
243 className="absolute inset-0"
244 />
245 <View className="absolute inset-0 bg-card-translucent" />
246 {/* keyboardShouldPersistTaps: the menu often opens over an
247 active editor; the first item tap must act, not just
248 dismiss the keyboard. */}
249 <ScrollView
250 bounces={false}
251 keyboardShouldPersistTaps="always"
252 showsVerticalScrollIndicator={false}
253 >
254 {parent !== null ? (
255 // Muted parent title as the submenu header; tapping it
256 // steps back, but it reads as a label, not a button.
257 <Pressable
258 className="px-3.5 pb-1 pt-2.5"
259 onPress={() => setPath((current) => current.slice(0, -1))}
260 >
261 <Text className="text-xs font-t3-bold text-foreground-muted">
262 {parent.title}
263 </Text>
264 </Pressable>
265 ) : props.title ? (
266 <>
267 <View className="px-3.5 py-2">
268 <Text className="text-center text-xs text-foreground-muted">
269 {props.title}
270 </Text>
271 </View>
272 <View className="h-px bg-border" />
273 </>
274 ) : null}
275 {levelActions.map((action, index) => {
276 const destructive = action.attributes?.destructive ?? false;
277 const disabled = action.attributes?.disabled ?? false;
278 const hasSubmenu = (action.subactions?.length ?? 0) > 0;
279 return (
280 <Pressable
281 key={action.id ?? `${index}-${action.title}`}
282 android_ripple={{ color: rippleColor }}
283 disabled={disabled}
284 className={cn(
285 "min-h-11 flex-row items-center gap-2.5 px-3.5 py-2.5",
286 disabled && "opacity-45",
287 )}
288 onPress={() => onPressItem(action)}
289 >
290 <View className="flex-1 gap-0.5">
291 <Text
292 className={cn(
293 // Same face as the pill labels that open these menus.
294 "text-sm font-t3-bold",
295 destructive && "text-danger-foreground",
296 )}
297 >
298 {action.title}
299 </Text>
300 {action.subtitle ? (
301 <Text className="text-xs leading-snug text-foreground-muted">
302 {action.subtitle}
303 </Text>
304 ) : null}
305 </View>
306 {hasSubmenu ? (
307 <SymbolView
308 name="chevron.right"
309 size={13}
310 tintColor={iconSubtleColor}
311 type="monochrome"
312 />
313 ) : action.state === "on" ? (
314 <SymbolView
315 name="checkmark"
316 size={15}
317 tintColor={iconColor}
318 type="monochrome"
319 />
320 ) : action.image ? (
321 <SymbolView
322 name={action.image as AppSymbolName}
323 size={15}
324 tintColor={destructive ? dangerColor : iconColor}
325 type="monochrome"
326 />
327 ) : null}
328 </Pressable>
329 );
330 })}
331 </ScrollView>
332 </Animated.View>
333 )}
334 </View>
335 </OverlayPortal>
336 )}
337 </>
338 );
339}