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