Open History to see the last commit
1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import type { ReactNode } from "react";
3import { use, useCallback, useEffect, useRef, useState } from "react";
4import type { StyleProp, ViewInstance, 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 { deriveMenuHorizontalPlacement } from "../../lib/menu-placement";
10import { WindowHingeContext } from "../../native/window-hinge-context";
11import { OverlayPortal } from "./OverlayPortal";
12import { useAndroidControlSizing } from "./useAndroidControlSizing";
13import { MenuPopup } from "./MenuPopup";
14
15const SCREEN_MARGIN = 12;
16const ANCHOR_GAP = 6;
17
18// Freeze both snapshots at opening so keyboard and screen reflows cannot flip menu direction.
19type AnchorSnapshot = {
20 readonly x: number;
21 readonly y: number;
22 readonly width: number;
23 readonly height: number;
24 readonly keyboardWasVisible: boolean;
25};
26
27type OverlayFrame = {
28 readonly x: number;
29 readonly y: number;
30 readonly width: number;
31 readonly height: number;
32};
33
34export type AndroidAnchoredMenuProps = {
35 readonly actions: readonly MenuAction[];
36 readonly title?: string;
37 readonly onPressAction?: MenuComponentProps["onPressAction"];
38 readonly className?: string;
39 readonly style?: StyleProp<ViewStyle>;
40 readonly children: ReactNode | ((open: () => void) => ReactNode);
41};
42
43export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
44 const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing();
45 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
46 const [path, setPath] = useState<readonly MenuAction[]>([]);
47 const [rootHeight, setRootHeight] = useState<number | null>(null);
48 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
49 const windowHinge = use(WindowHingeContext);
50 const anchorRef = useRef<ViewInstance>(null);
51 const overlayRef = useRef<ViewInstance>(null);
52
53 const keyboardVisible = useKeyboardState((state) => state.isVisible);
54 const keyboardHeight = useKeyboardState((state) => state.height);
55 const close = useCallback(() => {
56 setAnchor(null);
57 setPath([]);
58 setOverlay(null);
59 setRootHeight(null);
60 }, []);
61
62 const open = useCallback(() => {
63 anchorRef.current?.measureInWindow((x, y, width, height) => {
64 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
65 });
66 }, [keyboardVisible]);
67
68 const measureOverlay = useCallback(() => {
69 overlayRef.current?.measureInWindow((x, y, width, height) => {
70 setOverlay({ x, y, width, height });
71 setRootHeight(height);
72 });
73 }, []);
74
75 const submenuDepth = path.length;
76 useEffect(() => {
77 if (anchor === null || !anchor.keyboardWasVisible) {
78 return;
79 }
80 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
81 if (submenuDepth > 0) {
82 setPath((current) => current.slice(0, -1));
83 } else {
84 close();
85 }
86 return true;
87 });
88 return () => subscription.remove();
89 }, [anchor, close, submenuDepth]);
90
91 const parent = path[path.length - 1] ?? null;
92 const levelActions = (parent?.subactions ?? props.actions).filter(
93 (action) => !(action.attributes?.hidden ?? false),
94 );
95
96 const local =
97 anchor === null || overlay === null
98 ? null
99 : {
100 x: anchor.x - overlay.x,
101 y: anchor.y - overlay.y,
102 width: anchor.width,
103 height: anchor.height,
104 };
105 const { left, width: menuWidth } =
106 local === null || overlay === null
107 ? { left: 0, width: desiredMenuWidth }
108 : deriveMenuHorizontalPlacement({
109 anchorX: local.x,
110 anchorWidth: local.width,
111 overlayWidth: overlay.width,
112 desiredWidth: desiredMenuWidth,
113 margin: SCREEN_MARGIN,
114 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
115 });
116 // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
117 const usableBottom =
118 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
119 const spaceBelow =
120 local === null || overlay === null
121 ? 0
122 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
123 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
124 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
125 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
126 const placeable = local !== null && rootHeight !== null;
127
128 const onPressItem = useCallback(
129 (action: MenuAction) => {
130 if ((action.subactions?.length ?? 0) > 0) {
131 setPath((current) => [...current, action]);
132 return;
133 }
134 close();
135 if (action.id !== undefined) {
136 props.onPressAction?.({
137 nativeEvent: { event: action.id },
138 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
139 }
140 },
141 [close, props.onPressAction],
142 );
143
144 return (
145 <>
146 {typeof props.children === "function" ? (
147 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
148 {props.children(open)}
149 </View>
150 ) : (
151 <Pressable
152 ref={anchorRef}
153 accessibilityRole="button"
154 className={props.className}
155 collapsable={false}
156 style={props.style}
157 onPress={open}
158 >
159 <View pointerEvents="none">{props.children}</View>
160 </Pressable>
161 )}
162 {anchor === null ? null : (
163 <OverlayPortal>
164 <View
165 ref={overlayRef}
166 collapsable={false}
167 className="absolute inset-0"
168 onLayout={measureOverlay}
169 >
170 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
171 {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
172 <MenuPopup
173 // Compose aligns to the trigger's start if it fits; hinge-safe triggers keep menus on their side.
174 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
175 menuWidth={menuWidth}
176 actions={levelActions}
177 title={props.title}
178 parent={parent}
179 onPress={onPressItem}
180 onBack={() => setPath((current) => current.slice(0, -1))}
181 onClose={close}
182 />
183 ) : (
184 <Animated.View
185 entering={FadeIn.duration(120)}
186 className="absolute overflow-hidden bg-card-alt shadow-md"
187 style={{
188 left,
189 maxHeight,
190 width: menuWidth,
191 borderRadius: 4 * scale,
192 ...(opensDown
193 ? { top: local.y + local.height + ANCHOR_GAP }
194 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
195 }}
196 >
197 {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */}
198
199 {/* The first item tap must act while the keyboard is open. */}
200 <ScrollView
201 contentContainerStyle={{ paddingVertical: 7 * scale }}
202 bounces={false}
203 keyboardShouldPersistTaps="always"
204 showsVerticalScrollIndicator={false}
205 >
206 <MenuPopup
207 inline
208 anchor={local}
209 menuWidth={menuWidth}
210 actions={levelActions}
211 title={props.title}
212 parent={parent}
213 onPress={onPressItem}
214 onBack={() => setPath((current) => current.slice(0, -1))}
215 onClose={close}
216 />
217 </ScrollView>
218 </Animated.View>
219 )}
220 </View>
221 </OverlayPortal>
222 )}
223 </>
224 );
225}