import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu"; import type { ReactNode } from "react"; import { useCallback, useEffect, useRef, useState } from "react"; import type { StyleProp, ViewInstance, ViewStyle } from "react-native"; import { BackHandler, Pressable, ScrollView, View } from "react-native"; import { useKeyboardState } from "react-native-keyboard-controller"; import Animated, { FadeIn } from "react-native-reanimated"; import { OverlayPortal } from "./OverlayPortal"; import { useAndroidControlSizing } from "./useAndroidControlSizing"; import { MaterialMenuPopup } from "./MaterialMenuPopup"; const SCREEN_MARGIN = 12; const ANCHOR_GAP = 6; // Anchor position is snapshotted in window coordinates when the menu opens; // the overlay root measures itself the same way, and the menu is placed from // the delta. Both snapshots are taken at open time so later reflows (keyboard // show/hide, screen transitions) can't flip an opens-up menu to opens-down // mid-presentation. type AnchorSnapshot = { readonly x: number; readonly y: number; readonly width: number; readonly height: number; readonly keyboardWasVisible: boolean; }; type OverlayFrame = { readonly x: number; readonly y: number; readonly width: number; readonly height: number; }; export type AndroidAnchoredMenuProps = { readonly actions: readonly MenuAction[]; readonly title?: string; readonly onPressAction?: MenuComponentProps["onPressAction"]; /** Applied to the anchor wrapper — call sites flex these to fill toolbars. */ readonly className?: string; readonly style?: StyleProp; /** * Plain children open the menu on tap (the wrapper owns the press). A * render function keeps the children interactive and hands them `open` to * call from their own gesture — e.g. a row that selects on tap and opens * this menu on long-press. */ readonly children: ReactNode | ((open: () => void) => ReactNode); }; /** * Adapts the app's MenuView actions to Material dropdowns on Android. Editor * menus render native Material rows in-window to retain keyboard focus; other * menus use the native popup for placement, animation and dismissal. */ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing(); const [anchor, setAnchor] = useState(null); const [path, setPath] = useState([]); // Height of the modal's root view, in the modal's own coordinate space. // Menus that flip above their anchor are pinned by their BOTTOM edge // (bottom = rootHeight - anchorTop), so drill-in height changes grow // upward without any re-measurement — positioning them via `top` from the // menu's measured height made every submenu transition settle over two // frames and jitter. const [rootHeight, setRootHeight] = useState(null); // Window frame of the overlay root, measured on layout. Anchor coordinates // are converted into this frame, so the menu lands correctly no matter // where the portal host sits (status bar, keyboard resize, etc.). const [overlay, setOverlay] = useState(null); const menuWidth = overlay === null ? desiredMenuWidth : Math.min(desiredMenuWidth, Math.max(0, overlay.width - 2 * SCREEN_MARGIN)); const anchorRef = useRef(null); const overlayRef = useRef(null); const keyboardVisible = useKeyboardState((state) => state.isVisible); const keyboardHeight = useKeyboardState((state) => state.height); const close = useCallback(() => { setAnchor(null); setPath([]); setOverlay(null); setRootHeight(null); }, []); const open = useCallback(() => { anchorRef.current?.measureInWindow((x, y, width, height) => { setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible }); }); }, [keyboardVisible]); const measureOverlay = useCallback(() => { overlayRef.current?.measureInWindow((x, y, width, height) => { setOverlay({ x, y, width, height }); setRootHeight(height); }); }, []); // The native popup owns back dismissal. In-window menus need a handler; // back returns to the parent submenu before closing the overlay. const submenuDepth = path.length; useEffect(() => { if (anchor === null || !anchor.keyboardWasVisible) { return; } const subscription = BackHandler.addEventListener("hardwareBackPress", () => { if (submenuDepth > 0) { setPath((current) => current.slice(0, -1)); } else { close(); } return true; }); return () => subscription.remove(); }, [anchor, close, submenuDepth]); const parent = path[path.length - 1] ?? null; const levelActions = (parent?.subactions ?? props.actions).filter( (action) => !(action.attributes?.hidden ?? false), ); // Anchor in overlay-local coordinates (both measured in window space). const local = anchor === null || overlay === null ? null : { x: anchor.x - overlay.x, y: anchor.y - overlay.y, width: anchor.width, height: anchor.height, }; const preferredLeft = local === null || overlay === null ? 0 : local.x + local.width / 2 <= overlay.width / 2 ? local.x : local.x + local.width - menuWidth; const left = overlay === null ? 0 : Math.min(Math.max(preferredLeft, SCREEN_MARGIN), overlay.width - menuWidth - SCREEN_MARGIN); // The keyboard stays up while the menu is open (in-window overlay, no // focus change), so the space it covers is not usable — without this the // composer-pill menus "open down" into the IME and can't be tapped. const usableBottom = overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0); const spaceBelow = local === null || overlay === null ? 0 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN; const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN; const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove; const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480); // The menu needs the overlay frame before it can be placed; it stays // unmounted for that first frame so the fade-in plays at the final position. const placeable = local !== null && rootHeight !== null; const onPressItem = useCallback( (action: MenuAction) => { if ((action.subactions?.length ?? 0) > 0) { setPath((current) => [...current, action]); return; } close(); if (action.id !== undefined) { props.onPressAction?.({ nativeEvent: { event: action.id }, } as Parameters>[0]); } }, [close, props.onPressAction], ); return ( <> {typeof props.children === "function" ? ( {props.children(open)} ) : ( {props.children} )} {anchor === null ? null : ( {!placeable || local === null ? null : !anchor.keyboardWasVisible ? ( setPath((current) => current.slice(0, -1))} onClose={close} /> ) : ( {/* Compose DropdownMenu takes popup focus in the pinned Expo UI version. Keep editor menus in-window so opening one preserves the keyboard. */} {/* keyboardShouldPersistTaps: the menu often opens over an active editor; the first item tap must act, not just dismiss the keyboard. */} setPath((current) => current.slice(0, -1))} onClose={close} /> )} )} ); }