Open History to see the last commit
1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import type { ReactNode } from "react";
3import { use, useRef, useState } from "react";
4import type { StyleProp, ViewInstance, ViewStyle } from "react-native";
5import { Pressable, ScrollView, View } from "react-native";
6import { useKeyboardState } from "react-native-keyboard-controller";
7import Animated, { FadeIn } from "react-native-reanimated";
8
9import { useHardwareBack } from "../../lib/backHandler";
10import { deriveMenuHorizontalPlacement } from "../../lib/menu-placement";
11import { WindowHingeContext } from "../../native/window-hinge-context";
12import { OverlayPortal } from "./OverlayPortal";
13import { useAndroidControlSizing } from "./useAndroidControlSizing";
14import { MenuPopup } from "./MenuPopup";
15
16const SCREEN_MARGIN = 12;
17const ANCHOR_GAP = 6;
18
19// Freeze both snapshots at opening so keyboard and screen reflows cannot flip menu direction.
20type AnchorSnapshot = {
21 readonly x: number;
22 readonly y: number;
23 readonly width: number;
24 readonly height: number;
25 readonly keyboardWasVisible: boolean;
26};
27
28type OverlayFrame = {
29 readonly x: number;
30 readonly y: number;
31 readonly width: number;
32 readonly height: number;
33};
34
35export type AndroidAnchoredMenuProps = {
36 readonly actions: readonly MenuAction[];
37 readonly title?: string;
38 readonly onPressAction?: MenuComponentProps["onPressAction"];
39 readonly className?: string;
40 readonly style?: StyleProp<ViewStyle>;
41 readonly children: ReactNode | ((open: () => void) => ReactNode);
42};
43
44export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
45 const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing();
46 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
47 const [path, setPath] = useState<readonly MenuAction[]>([]);
48 const [rootHeight, setRootHeight] = useState<number | null>(null);
49 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
50 const windowHinge = use(WindowHingeContext);
51 // State, not a ref: `open` reaches render-prop children, and the compiler
52 // bails out of the whole component when a ref might be read during render.
53 const [anchorNode, setAnchorNode] = useState<ViewInstance | null>(null);
54 const overlayRef = useRef<ViewInstance>(null);
55
56 const keyboardVisible = useKeyboardState((state) => state.isVisible);
57 const keyboardHeight = useKeyboardState((state) => state.height);
58 const close = () => {
59 setAnchor(null);
60 setPath([]);
61 setOverlay(null);
62 setRootHeight(null);
63 };
64
65 const open = () => {
66 anchorNode?.measureInWindow((x, y, width, height) => {
67 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
68 });
69 };
70
71 const measureOverlay = () => {
72 overlayRef.current?.measureInWindow((x, y, width, height) => {
73 setOverlay({ x, y, width, height });
74 setRootHeight(height);
75 });
76 };
77
78 // Only the in-window (keyboard) presentation needs this; the native popup
79 // handles back itself.
80 useHardwareBack(anchor?.keyboardWasVisible === true, () => {
81 if (path.length > 0) {
82 setPath((current) => current.slice(0, -1));
83 } else {
84 close();
85 }
86 return true;
87 });
88
89 const parent = path[path.length - 1] ?? null;
90 const levelActions = (parent?.subactions ?? props.actions).filter(
91 (action) => !(action.attributes?.hidden ?? false),
92 );
93
94 const local =
95 anchor === null || overlay === null
96 ? null
97 : {
98 x: anchor.x - overlay.x,
99 y: anchor.y - overlay.y,
100 width: anchor.width,
101 height: anchor.height,
102 };
103 const { left, width: menuWidth } =
104 local === null || overlay === null
105 ? { left: 0, width: desiredMenuWidth }
106 : deriveMenuHorizontalPlacement({
107 anchorX: local.x,
108 anchorWidth: local.width,
109 overlayWidth: overlay.width,
110 desiredWidth: desiredMenuWidth,
111 margin: SCREEN_MARGIN,
112 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
113 });
114 // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
115 const usableBottom =
116 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
117 const spaceBelow =
118 local === null || overlay === null
119 ? 0
120 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
121 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
122 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
123 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
124 const placeable = local !== null && rootHeight !== null;
125
126 const onPressItem = (action: MenuAction) => {
127 if ((action.subactions?.length ?? 0) > 0) {
128 setPath((current) => [...current, action]);
129 return;
130 }
131 close();
132 if (action.id !== undefined) {
133 props.onPressAction?.({
134 nativeEvent: { event: action.id },
135 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
136 }
137 };
138
139 return (
140 <>
141 {typeof props.children === "function" ? (
142 <View
143 ref={setAnchorNode}
144 collapsable={false}
145 className={props.className}
146 style={props.style}
147 >
148 {props.children(open)}
149 </View>
150 ) : (
151 <Pressable
152 ref={setAnchorNode}
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}