Open History to see the last commit
1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import { cloneElement, isValidElement, type ReactElement, type ReactNode } from "react";
3import { use, useRef, useState } from "react";
4import type {
5 AccessibilityProps,
6 PressableProps,
7 StyleProp,
8 ViewInstance,
9 ViewStyle,
10} from "react-native";
11import { Pressable, ScrollView, View } from "react-native";
12import { useKeyboardState } from "react-native-keyboard-controller";
13
14import { useHardwareBack } from "../../lib/backHandler";
15import {
16 deriveMenuHorizontalPlacement,
17 deriveMenuVerticalPlacement,
18} from "../../lib/menu-placement";
19import { WindowHingeContext } from "../../native/window-hinge-context";
20import { OverlayPortal } from "./OverlayPortal";
21import { useAndroidControlSizing } from "./useAndroidControlSizing";
22import { MenuPopup } from "./MenuPopup";
23
24const SCREEN_MARGIN = 12;
25const ANCHOR_GAP = 6;
26
27// Freeze both snapshots at opening so keyboard and screen reflows cannot flip menu direction.
28type AnchorSnapshot = {
29 readonly x: number;
30 readonly y: number;
31 readonly width: number;
32 readonly height: number;
33 readonly keyboardWasVisible: boolean;
34};
35
36type OverlayFrame = {
37 readonly x: number;
38 readonly y: number;
39 readonly width: number;
40 readonly height: number;
41};
42
43export type AndroidAnchoredMenuProps = {
44 readonly actions: readonly MenuAction[];
45 readonly title?: string;
46 readonly onPressAction?: MenuComponentProps["onPressAction"];
47 readonly accessibilityLabel?: AccessibilityProps["accessibilityLabel"];
48 readonly accessibilityHint?: AccessibilityProps["accessibilityHint"];
49 readonly accessibilityState?: AccessibilityProps["accessibilityState"];
50 readonly hitSlop?: PressableProps["hitSlop"];
51 readonly className?: string;
52 readonly style?: StyleProp<ViewStyle>;
53 readonly children: ReactNode | ((open: () => void) => ReactNode);
54};
55
56type TriggerAccessibilityProps = {
57 readonly accessible?: boolean;
58 readonly accessibilityRole?: AccessibilityProps["accessibilityRole"];
59 readonly accessibilityLabel?: AccessibilityProps["accessibilityLabel"];
60 readonly accessibilityHint?: AccessibilityProps["accessibilityHint"];
61 readonly accessibilityState?: AccessibilityProps["accessibilityState"];
62 readonly importantForAccessibility?: AccessibilityProps["importantForAccessibility"];
63 readonly hitSlop?: PressableProps["hitSlop"];
64 readonly disabled?: boolean;
65 readonly children?: ReactNode;
66};
67
68function stripTriggerAccessibility(node: ReactNode, depth = 0): ReactNode {
69 if (depth >= 3) return node;
70 if (Array.isArray(node)) {
71 let changed = false;
72 const next = node.map((child) => {
73 const stripped = stripTriggerAccessibility(child, depth);
74 if (stripped !== child) changed = true;
75 return stripped;
76 });
77 return changed ? next : node;
78 }
79 if (!isValidElement(node)) return node;
80 const element = node as ReactElement<TriggerAccessibilityProps>;
81 const { accessibilityRole, accessibilityLabel, accessibilityHint, accessibilityState } =
82 element.props;
83 if (
84 accessibilityRole !== undefined ||
85 accessibilityLabel !== undefined ||
86 accessibilityHint !== undefined ||
87 accessibilityState !== undefined
88 ) {
89 return cloneElement(element, {
90 accessible: false,
91 accessibilityRole: undefined,
92 accessibilityLabel: undefined,
93 accessibilityHint: undefined,
94 accessibilityState: undefined,
95 importantForAccessibility: "no-hide-descendants",
96 });
97 }
98 if (element.props.children !== undefined) {
99 const nextChild = stripTriggerAccessibility(element.props.children, depth + 1);
100 if (nextChild !== element.props.children) {
101 return cloneElement(element, undefined, nextChild);
102 }
103 }
104 return node;
105}
106
107function extractTriggerAccessibility(
108 node: ReactNode,
109 depth = 0,
110 acc: {
111 accessibilityLabel?: AccessibilityProps["accessibilityLabel"];
112 accessibilityHint?: AccessibilityProps["accessibilityHint"];
113 accessibilityState?: AccessibilityProps["accessibilityState"];
114 hitSlop?: PressableProps["hitSlop"];
115 } = {},
116): TriggerAccessibilityProps {
117 if (depth >= 3) return acc;
118 if (Array.isArray(node)) {
119 for (const child of node) {
120 extractTriggerAccessibility(child, depth, acc);
121 }
122 return acc;
123 }
124 if (!isValidElement(node)) return acc;
125 const element = node as ReactElement<TriggerAccessibilityProps>;
126 const { accessibilityLabel, accessibilityHint, accessibilityState, hitSlop, disabled } =
127 element.props;
128 if (acc.accessibilityLabel === undefined && accessibilityLabel !== undefined) {
129 acc.accessibilityLabel = accessibilityLabel;
130 }
131 if (acc.accessibilityHint === undefined && accessibilityHint !== undefined) {
132 acc.accessibilityHint = accessibilityHint;
133 }
134 if (acc.accessibilityState === undefined) {
135 const nextState = accessibilityState ?? (disabled !== undefined ? { disabled } : undefined);
136 if (nextState !== undefined) acc.accessibilityState = nextState;
137 }
138 if (acc.hitSlop === undefined && hitSlop !== undefined) {
139 acc.hitSlop = hitSlop;
140 }
141 if (
142 acc.accessibilityLabel !== undefined &&
143 acc.accessibilityHint !== undefined &&
144 acc.accessibilityState !== undefined &&
145 acc.hitSlop !== undefined
146 ) {
147 return acc;
148 }
149 if (element.props.children !== undefined) {
150 extractTriggerAccessibility(element.props.children, depth + 1, acc);
151 }
152 return acc;
153}
154
155export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
156 const { scale, menuWidth: desiredMenuWidth, menuItemHeight } = useAndroidControlSizing();
157 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
158 const [path, setPath] = useState<readonly MenuAction[]>([]);
159 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
160 const windowHinge = use(WindowHingeContext);
161 // State, not a ref: `open` reaches render-prop children, and the compiler
162 // bails out of the whole component when a ref might be read during render.
163 const [anchorNode, setAnchorNode] = useState<ViewInstance | null>(null);
164 const overlayRef = useRef<ViewInstance>(null);
165
166 const keyboardVisible = useKeyboardState((state) => state.isVisible);
167 const keyboardHeight = useKeyboardState((state) => state.height);
168 const close = () => {
169 setAnchor(null);
170 setPath([]);
171 setOverlay(null);
172 };
173 // The in-window menu is pinned to the trigger's spot above the keyboard, which is stale once it hides.
174 if (anchor?.keyboardWasVisible === true && !keyboardVisible) {
175 close();
176 }
177
178 const open = () => {
179 anchorNode?.measureInWindow((x, y, width, height) => {
180 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
181 });
182 };
183
184 const measureOverlay = () => {
185 overlayRef.current?.measureInWindow((x, y, width, height) => {
186 setOverlay({ x, y, width, height });
187 });
188 };
189
190 // Only the in-window (keyboard) presentation needs this; the native popup
191 // handles back itself.
192 useHardwareBack(anchor?.keyboardWasVisible === true, () => {
193 if (path.length > 0) {
194 setPath((current) => current.slice(0, -1));
195 } else {
196 close();
197 }
198 return true;
199 });
200
201 const parent = path[path.length - 1] ?? null;
202 const levelActions = (parent?.subactions ?? props.actions).filter(
203 (action) => !(action.attributes?.hidden ?? false),
204 );
205
206 const local =
207 anchor === null || overlay === null
208 ? null
209 : {
210 x: anchor.x - overlay.x,
211 y: anchor.y - overlay.y,
212 width: anchor.width,
213 height: anchor.height,
214 };
215 const { left, width: menuWidth } =
216 local === null || overlay === null
217 ? { left: 0, width: desiredMenuWidth }
218 : deriveMenuHorizontalPlacement({
219 anchorX: local.x,
220 anchorWidth: local.width,
221 overlayWidth: overlay.width,
222 desiredWidth: desiredMenuWidth,
223 margin: SCREEN_MARGIN,
224 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
225 });
226 const verticalPlacement =
227 local === null || overlay === null
228 ? null
229 : deriveMenuVerticalPlacement({
230 anchorY: local.y,
231 anchorHeight: local.height,
232 overlayHeight: overlay.height,
233 // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
234 keyboardInset: keyboardVisible ? keyboardHeight : 0,
235 gap: ANCHOR_GAP,
236 margin: SCREEN_MARGIN,
237 minHeight: 2 * menuItemHeight + 14 * scale,
238 });
239
240 const onPressItem = (action: MenuAction) => {
241 if ((action.subactions?.length ?? 0) > 0) {
242 setPath((current) => [...current, action]);
243 return;
244 }
245 close();
246 if (action.id !== undefined) {
247 props.onPressAction?.({
248 nativeEvent: { event: action.id },
249 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
250 }
251 };
252
253 const triggerAccessibility =
254 typeof props.children === "function" ? {} : extractTriggerAccessibility(props.children);
255 const triggerLabel =
256 props.accessibilityLabel ?? triggerAccessibility.accessibilityLabel ?? props.title;
257 const triggerHint = props.accessibilityHint ?? triggerAccessibility.accessibilityHint;
258 const triggerState = props.accessibilityState ?? triggerAccessibility.accessibilityState;
259 const triggerHitSlop = props.hitSlop ?? triggerAccessibility.hitSlop;
260
261 return (
262 <>
263 {typeof props.children === "function" ? (
264 <View
265 ref={setAnchorNode}
266 collapsable={false}
267 className={props.className}
268 style={props.style}
269 >
270 {props.children(open)}
271 </View>
272 ) : (
273 <Pressable
274 ref={setAnchorNode}
275 accessibilityRole="button"
276 accessibilityLabel={triggerLabel}
277 accessibilityHint={triggerHint}
278 accessibilityState={triggerState}
279 hitSlop={triggerHitSlop}
280 className={props.className}
281 collapsable={false}
282 style={props.style}
283 onPress={open}
284 >
285 <View
286 pointerEvents="none"
287 accessible={false}
288 importantForAccessibility="no-hide-descendants"
289 accessibilityElementsHidden
290 >
291 {stripTriggerAccessibility(props.children)}
292 </View>
293 </Pressable>
294 )}
295 {anchor === null ? null : (
296 <OverlayPortal>
297 <View
298 ref={overlayRef}
299 collapsable={false}
300 className="absolute inset-0"
301 onLayout={measureOverlay}
302 >
303 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
304 {local === null ? null : !anchor.keyboardWasVisible ? (
305 <MenuPopup
306 // Compose aligns to the trigger's start if it fits; hinge-safe triggers keep menus on their side.
307 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
308 menuWidth={menuWidth}
309 actions={levelActions}
310 title={props.title}
311 parent={parent}
312 onPress={onPressItem}
313 onBack={() => setPath((current) => current.slice(0, -1))}
314 onClose={close}
315 />
316 ) : (
317 <View
318 // No entering animation: it freezes this frame before the Compose host reports its size.
319 className="absolute overflow-hidden bg-card-alt shadow-md"
320 style={{
321 left,
322 width: menuWidth,
323 borderRadius: 4 * scale,
324 ...verticalPlacement,
325 }}
326 >
327 {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */}
328
329 {/* The first item tap must act while the keyboard is open. */}
330 <ScrollView
331 contentContainerStyle={{ paddingVertical: 7 * scale }}
332 bounces={false}
333 keyboardShouldPersistTaps="always"
334 showsVerticalScrollIndicator={false}
335 >
336 <MenuPopup
337 inline
338 anchor={local}
339 menuWidth={menuWidth}
340 actions={levelActions}
341 title={props.title}
342 parent={parent}
343 onPress={onPressItem}
344 onBack={() => setPath((current) => current.slice(0, -1))}
345 onClose={close}
346 />
347 </ScrollView>
348 </View>
349 )}
350 </View>
351 </OverlayPortal>
352 )}
353 </>
354 );
355}