Open History to see the last commit
1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import type { ReactNode } from "react";
3import { useCallback, useEffect, useRef, useState } from "react";
4import type { StyleProp, ViewStyle } from "react-native";
5import { BackHandler, Pressable, ScrollView, View } from "react-native";
6import { useKeyboardState } from "react-native-keyboard-controller";
7import Animated, { FadeIn } from "react-native-reanimated";
8
9import { OverlayPortal } from "./OverlayPortal";
10import { MaterialMenuPopup } from "./MaterialMenuPopup";
11
12const MENU_WIDTH = 250;
13const SCREEN_MARGIN = 12;
14const ANCHOR_GAP = 6;
15
16// Anchor position is snapshotted in window coordinates when the menu opens;
17// the overlay root measures itself the same way, and the menu is placed from
18// the delta. Both snapshots are taken at open time so later reflows (keyboard
19// show/hide, screen transitions) can't flip an opens-up menu to opens-down
20// mid-presentation.
21type AnchorSnapshot = {
22 readonly x: number;
23 readonly y: number;
24 readonly width: number;
25 readonly height: number;
26 readonly keyboardWasVisible: boolean;
27};
28
29type OverlayFrame = {
30 readonly x: number;
31 readonly y: number;
32 readonly width: number;
33 readonly height: number;
34};
35
36export type AndroidAnchoredMenuProps = {
37 readonly actions: readonly MenuAction[];
38 readonly title?: string;
39 readonly onPressAction?: MenuComponentProps["onPressAction"];
40 /** Applied to the anchor wrapper — call sites flex these to fill toolbars. */
41 readonly className?: string;
42 readonly style?: StyleProp<ViewStyle>;
43 /**
44 * Plain children open the menu on tap (the wrapper owns the press). A
45 * render function keeps the children interactive and hands them `open` to
46 * call from their own gesture — e.g. a row that selects on tap and opens
47 * this menu on long-press.
48 */
49 readonly children: ReactNode | ((open: () => void) => ReactNode);
50};
51
52/**
53 * Adapts the app's MenuView actions to Material dropdowns on Android. Editor
54 * menus render native Material rows in-window to retain keyboard focus; other
55 * menus use the native popup for placement, animation and dismissal.
56 */
57export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
58 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
59 const [path, setPath] = useState<readonly MenuAction[]>([]);
60 // Height of the modal's root view, in the modal's own coordinate space.
61 // Menus that flip above their anchor are pinned by their BOTTOM edge
62 // (bottom = rootHeight - anchorTop), so drill-in height changes grow
63 // upward without any re-measurement — positioning them via `top` from the
64 // menu's measured height made every submenu transition settle over two
65 // frames and jitter.
66 const [rootHeight, setRootHeight] = useState<number | null>(null);
67 // Window frame of the overlay root, measured on layout. Anchor coordinates
68 // are converted into this frame, so the menu lands correctly no matter
69 // where the portal host sits (status bar, keyboard resize, etc.).
70 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
71 const anchorRef = useRef<View>(null);
72 const overlayRef = useRef<View>(null);
73
74 const keyboardVisible = useKeyboardState((state) => state.isVisible);
75 const keyboardHeight = useKeyboardState((state) => state.height);
76 const close = useCallback(() => {
77 setAnchor(null);
78 setPath([]);
79 setOverlay(null);
80 setRootHeight(null);
81 }, []);
82
83 const open = useCallback(() => {
84 anchorRef.current?.measureInWindow((x, y, width, height) => {
85 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
86 });
87 }, [keyboardVisible]);
88
89 const measureOverlay = useCallback(() => {
90 overlayRef.current?.measureInWindow((x, y, width, height) => {
91 setOverlay({ x, y, width, height });
92 setRootHeight(height);
93 });
94 }, []);
95
96 // The native popup owns back dismissal. In-window menus need a handler;
97 // back returns to the parent submenu before closing the overlay.
98 const submenuDepth = path.length;
99 useEffect(() => {
100 if (anchor === null || !anchor.keyboardWasVisible) {
101 return;
102 }
103 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
104 if (submenuDepth > 0) {
105 setPath((current) => current.slice(0, -1));
106 } else {
107 close();
108 }
109 return true;
110 });
111 return () => subscription.remove();
112 }, [anchor, close, submenuDepth]);
113
114 const parent = path[path.length - 1] ?? null;
115 const levelActions = (parent?.subactions ?? props.actions).filter(
116 (action) => !(action.attributes?.hidden ?? false),
117 );
118
119 // Anchor in overlay-local coordinates (both measured in window space).
120 const local =
121 anchor === null || overlay === null
122 ? null
123 : {
124 x: anchor.x - overlay.x,
125 y: anchor.y - overlay.y,
126 width: anchor.width,
127 height: anchor.height,
128 };
129 const preferredLeft =
130 local === null || overlay === null
131 ? 0
132 : local.x + local.width / 2 <= overlay.width / 2
133 ? local.x
134 : local.x + local.width - MENU_WIDTH;
135 const left =
136 overlay === null
137 ? 0
138 : Math.min(
139 Math.max(preferredLeft, SCREEN_MARGIN),
140 overlay.width - MENU_WIDTH - SCREEN_MARGIN,
141 );
142 // The keyboard stays up while the menu is open (in-window overlay, no
143 // focus change), so the space it covers is not usable — without this the
144 // composer-pill menus "open down" into the IME and can't be tapped.
145 const usableBottom =
146 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
147 const spaceBelow =
148 local === null || overlay === null
149 ? 0
150 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
151 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
152 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
153 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
154 // The menu needs the overlay frame before it can be placed; it stays
155 // unmounted for that first frame so the fade-in plays at the final position.
156 const placeable = local !== null && rootHeight !== null;
157
158 const onPressItem = useCallback(
159 (action: MenuAction) => {
160 if ((action.subactions?.length ?? 0) > 0) {
161 setPath((current) => [...current, action]);
162 return;
163 }
164 close();
165 if (action.id !== undefined) {
166 props.onPressAction?.({
167 nativeEvent: { event: action.id },
168 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
169 }
170 },
171 [close, props.onPressAction],
172 );
173
174 return (
175 <>
176 {typeof props.children === "function" ? (
177 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
178 {props.children(open)}
179 </View>
180 ) : (
181 <Pressable
182 ref={anchorRef}
183 accessibilityRole="button"
184 className={props.className}
185 collapsable={false}
186 style={props.style}
187 onPress={open}
188 >
189 <View pointerEvents="none">{props.children}</View>
190 </Pressable>
191 )}
192 {anchor === null ? null : (
193 <OverlayPortal>
194 <View
195 ref={overlayRef}
196 collapsable={false}
197 className="absolute inset-0"
198 onLayout={measureOverlay}
199 >
200 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
201 {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
202 <MaterialMenuPopup
203 anchor={local}
204 actions={levelActions}
205 title={props.title}
206 parent={parent}
207 onPress={onPressItem}
208 onBack={() => setPath((current) => current.slice(0, -1))}
209 onClose={close}
210 />
211 ) : (
212 <Animated.View
213 entering={FadeIn.duration(120)}
214 className="absolute w-[250px] overflow-hidden rounded-[4px] bg-card-alt shadow-md"
215 style={{
216 left,
217 maxHeight,
218 ...(opensDown
219 ? { top: local.y + local.height + ANCHOR_GAP }
220 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
221 }}
222 >
223 {/* Compose DropdownMenu takes popup focus in the pinned Expo UI version.
224 Keep editor menus in-window so opening one preserves the keyboard. */}
225
226 {/* keyboardShouldPersistTaps: the menu often opens over an
227 active editor; the first item tap must act, not just
228 dismiss the keyboard. */}
229 <ScrollView
230 contentContainerClassName="py-2"
231 bounces={false}
232 keyboardShouldPersistTaps="always"
233 showsVerticalScrollIndicator={false}
234 >
235 <MaterialMenuPopup
236 inline
237 anchor={local}
238 actions={levelActions}
239 title={props.title}
240 parent={parent}
241 onPress={onPressItem}
242 onBack={() => setPath((current) => current.slice(0, -1))}
243 onClose={close}
244 />
245 </ScrollView>
246 </Animated.View>
247 )}
248 </View>
249 </OverlayPortal>
250 )}
251 </>
252 );
253}