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 { 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 { themeAppearance } = useAppearancePreferences();
83 const isDarkMode = themeAppearance === "dark";
84 const keyboardVisible = useKeyboardState((state) => state.isVisible);
85 const keyboardHeight = useKeyboardState((state) => state.height);
86 const close = useCallback(() => {
87 setAnchor(null);
88 setPath([]);
89 setOverlay(null);
90 setRootHeight(null);
91 }, []);
92
93 const open = useCallback(() => {
94 anchorRef.current?.measureInWindow((x, y, width, height) => {
95 setAnchor({ x, y, width, height });
96 });
97 }, []);
98
99 const measureOverlay = useCallback(() => {
100 overlayRef.current?.measureInWindow((x, y, width, height) => {
101 setOverlay({ x, y, width, height });
102 setRootHeight(height);
103 });
104 }, []);
105
106 // The dropdown renders in-window (no Modal takes focus), so the hardware
107 // back gesture needs explicit handling while it is open. Back steps out of
108 // a drilled-in submenu one level at a time (mirroring the tappable parent
109 // header) before closing the menu. Under predictive back
110 // (enableOnBackInvokedCallback) this stays correct: back reaches JS
111 // through always-registered OnBackPressedDispatcher callbacks (react-native
112 // core on Android 16+, withAndroidPredictiveBackCompat on 13-15), which
113 // also keeps the system from playing a "leave app" preview while the menu
114 // merely closes.
115 const submenuDepth = path.length;
116 useEffect(() => {
117 if (anchor === null) {
118 return;
119 }
120 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
121 if (submenuDepth > 0) {
122 setPath((current) => current.slice(0, -1));
123 } else {
124 close();
125 }
126 return true;
127 });
128 return () => subscription.remove();
129 }, [anchor, close, submenuDepth]);
130
131 const parent = path.length > 0 ? path[path.length - 1] : null;
132 const levelActions = (parent?.subactions ?? props.actions).filter(
133 (action) => !(action.attributes?.hidden ?? false),
134 );
135
136 // Anchor in overlay-local coordinates (both measured in window space).
137 const local =
138 anchor === null || overlay === null
139 ? null
140 : {
141 x: anchor.x - overlay.x,
142 y: anchor.y - overlay.y,
143 width: anchor.width,
144 height: anchor.height,
145 };
146 const preferredLeft =
147 local === null || overlay === null
148 ? 0
149 : local.x + local.width / 2 <= overlay.width / 2
150 ? local.x
151 : local.x + local.width - MENU_WIDTH;
152 const left =
153 overlay === null
154 ? 0
155 : Math.min(
156 Math.max(preferredLeft, SCREEN_MARGIN),
157 overlay.width - MENU_WIDTH - SCREEN_MARGIN,
158 );
159 // The keyboard stays up while the menu is open (in-window overlay, no
160 // focus change), so the space it covers is not usable — without this the
161 // composer-pill menus "open down" into the IME and can't be tapped.
162 const usableBottom =
163 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
164 const spaceBelow =
165 local === null || overlay === null
166 ? 0
167 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
168 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
169 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
170 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
171 // The menu needs the overlay frame before it can be placed; it stays
172 // unmounted for that first frame so the fade-in plays at the final position.
173 const placeable = local !== null && rootHeight !== null;
174
175 const onPressItem = useCallback(
176 (action: MenuAction) => {
177 if ((action.subactions?.length ?? 0) > 0) {
178 setPath((current) => [...current, action]);
179 return;
180 }
181 close();
182 if (action.id !== undefined) {
183 props.onPressAction?.({
184 nativeEvent: { event: action.id },
185 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
186 }
187 },
188 [close, props.onPressAction],
189 );
190
191 return (
192 <>
193 {typeof props.children === "function" ? (
194 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
195 {props.children(open)}
196 </View>
197 ) : (
198 <Pressable
199 ref={anchorRef}
200 accessibilityRole="button"
201 className={props.className}
202 collapsable={false}
203 style={props.style}
204 onPress={open}
205 >
206 <View pointerEvents="none">{props.children}</View>
207 </Pressable>
208 )}
209 {anchor === null ? null : (
210 <OverlayPortal>
211 <View
212 ref={overlayRef}
213 collapsable={false}
214 className="absolute inset-0"
215 onLayout={measureOverlay}
216 >
217 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
218 {!placeable || local === null ? null : (
219 <Animated.View
220 entering={FadeIn.duration(120)}
221 className="absolute w-[250px] overflow-hidden rounded-[12px] border border-border shadow-2xl"
222 style={{
223 left,
224 maxHeight,
225 ...(opensDown
226 ? { top: local.y + local.height + ANCHOR_GAP }
227 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
228 }}
229 >
230 {/* Frosted backdrop: blur of the app content behind the menu,
231 washed with the translucent card tone so rows keep contrast. */}
232 <BlurView
233 blurMethod="dimezisBlurView"
234 blurTarget={appBlurTargetRef}
235 intensity={40}
236 tint={isDarkMode ? "dark" : "light"}
237 className="absolute inset-0"
238 />
239 <View className="absolute inset-0 bg-card-translucent" />
240 {/* keyboardShouldPersistTaps: the menu often opens over an
241 active editor; the first item tap must act, not just
242 dismiss the keyboard. */}
243 <ScrollView
244 bounces={false}
245 keyboardShouldPersistTaps="always"
246 showsVerticalScrollIndicator={false}
247 >
248 {parent !== null ? (
249 // Muted parent title as the submenu header; tapping it
250 // steps back, but it reads as a label, not a button.
251 <Pressable
252 className="px-3.5 pb-1 pt-2.5"
253 onPress={() => setPath((current) => current.slice(0, -1))}
254 >
255 <Text className="text-xs font-t3-bold text-foreground-muted">
256 {parent.title}
257 </Text>
258 </Pressable>
259 ) : props.title ? (
260 <>
261 <View className="px-3.5 py-2">
262 <Text className="text-center text-xs text-foreground-muted">
263 {props.title}
264 </Text>
265 </View>
266 <View className="h-px bg-border" />
267 </>
268 ) : null}
269 {levelActions.map((action, index) => {
270 const destructive = action.attributes?.destructive ?? false;
271 const disabled = action.attributes?.disabled ?? false;
272 const hasSubmenu = (action.subactions?.length ?? 0) > 0;
273 return (
274 <Pressable
275 key={action.id ?? `${index}-${action.title}`}
276 disabled={disabled}
277 className={cn(
278 "min-h-11 flex-row items-center gap-2.5 px-3.5 py-2.5 active:bg-subtle",
279 disabled && "opacity-45",
280 )}
281 onPress={() => onPressItem(action)}
282 >
283 <View className="flex-1 gap-0.5">
284 <Text
285 className={cn(
286 // Same face as the pill labels that open these menus.
287 "text-sm font-t3-bold",
288 destructive && "text-danger-foreground",
289 )}
290 >
291 {action.title}
292 </Text>
293 {action.subtitle ? (
294 <Text className="text-xs leading-snug text-foreground-muted">
295 {action.subtitle}
296 </Text>
297 ) : null}
298 </View>
299 {hasSubmenu ? (
300 <SymbolView
301 name="chevron.right"
302 size={13}
303 tintColorClassName={"accent-icon-subtle"}
304 type="monochrome"
305 />
306 ) : action.state === "on" ? (
307 <SymbolView
308 name="checkmark"
309 size={15}
310 tintColorClassName={"accent-icon"}
311 type="monochrome"
312 />
313 ) : action.image ? (
314 <SymbolView
315 name={action.image as AppSymbolName}
316 size={15}
317 tintColorClassName={
318 destructive ? "accent-danger-foreground" : "accent-icon"
319 }
320 type="monochrome"
321 />
322 ) : null}
323 </Pressable>
324 );
325 })}
326 </ScrollView>
327 </Animated.View>
328 )}
329 </View>
330 </OverlayPortal>
331 )}
332 </>
333 );
334}