Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AndroidAnchoredMenu.tsx

322 lines12.9 KB

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