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

AndroidAnchoredMenu.tsx

336 lines13.8 KB

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