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

AndroidAnchoredMenu.tsx

231 lines8.0 KB

1import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
2import type { ReactNode } from "react";
3import { 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 { OverlayPortal } from "./OverlayPortal";
10import { useAndroidControlSizing } from "./useAndroidControlSizing";
11import { MenuPopup } from "./MenuPopup";
12​
13const SCREEN_MARGIN = 12;
14const ANCHOR_GAP = 6;
15​
16// Both snapshots are taken at open time so later reflows (keyboard show/hide,
17// screen transitions) can't flip an opens-up menu to opens-down
18// mid-presentation.
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 menuWidth =
50 overlay === null
51 ? desiredMenuWidth
52 : Math.min(desiredMenuWidth, Math.max(0, overlay.width - 2 * SCREEN_MARGIN));
53 const anchorRef = useRef<ViewInstance>(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 = useCallback(() => {
59 setAnchor(null);
60 setPath([]);
61 setOverlay(null);
62 setRootHeight(null);
63 }, []);
64​
65 const open = useCallback(() => {
66 anchorRef.current?.measureInWindow((x, y, width, height) => {
67 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
68 });
69 }, [keyboardVisible]);
70​
71 const measureOverlay = useCallback(() => {
72 overlayRef.current?.measureInWindow((x, y, width, height) => {
73 setOverlay({ x, y, width, height });
74 setRootHeight(height);
75 });
76 }, []);
77​
78 const submenuDepth = path.length;
79 useEffect(() => {
80 if (anchor === null || !anchor.keyboardWasVisible) {
81 return;
82 }
83 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
84 if (submenuDepth > 0) {
85 setPath((current) => current.slice(0, -1));
86 } else {
87 close();
88 }
89 return true;
90 });
91 return () => subscription.remove();
92 }, [anchor, close, submenuDepth]);
93​
94 const parent = path[path.length - 1] ?? null;
95 const levelActions = (parent?.subactions ?? props.actions).filter(
96 (action) => !(action.attributes?.hidden ?? false),
97 );
98​
99 const local =
100 anchor === null || overlay === null
101 ? null
102 : {
103 x: anchor.x - overlay.x,
104 y: anchor.y - overlay.y,
105 width: anchor.width,
106 height: anchor.height,
107 };
108 const preferredLeft =
109 local === null || overlay === null
110 ? 0
111 : local.x + local.width / 2 <= overlay.width / 2
112 ? local.x
113 : local.x + local.width - menuWidth;
114 const left =
115 overlay === null
116 ? 0
117 : Math.min(Math.max(preferredLeft, SCREEN_MARGIN), overlay.width - menuWidth - SCREEN_MARGIN);
118 // The keyboard stays up while the menu is open (in-window overlay, no
119 // focus change), so the space it covers is not usable — without this the
120 // composer-pill menus "open down" into the IME and can't be tapped.
121 const usableBottom =
122 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
123 const spaceBelow =
124 local === null || overlay === null
125 ? 0
126 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
127 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
128 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
129 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
130 const placeable = local !== null && rootHeight !== null;
131​
132 const onPressItem = useCallback(
133 (action: MenuAction) => {
134 if ((action.subactions?.length ?? 0) > 0) {
135 setPath((current) => [...current, action]);
136 return;
137 }
138 close();
139 if (action.id !== undefined) {
140 props.onPressAction?.({
141 nativeEvent: { event: action.id },
142 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
143 }
144 },
145 [close, props.onPressAction],
146 );
147​
148 return (
149 <>
150 {typeof props.children === "function" ? (
151 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
152 {props.children(open)}
153 </View>
154 ) : (
155 <Pressable
156 ref={anchorRef}
157 accessibilityRole="button"
158 className={props.className}
159 collapsable={false}
160 style={props.style}
161 onPress={open}
162 >
163 <View pointerEvents="none">{props.children}</View>
164 </Pressable>
165 )}
166 {anchor === null ? null : (
167 <OverlayPortal>
168 <View
169 ref={overlayRef}
170 collapsable={false}
171 className="absolute inset-0"
172 onLayout={measureOverlay}
173 >
174 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
175 {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
176 <MenuPopup
177 anchor={local}
178 menuWidth={menuWidth}
179 actions={levelActions}
180 title={props.title}
181 parent={parent}
182 onPress={onPressItem}
183 onBack={() => setPath((current) => current.slice(0, -1))}
184 onClose={close}
185 />
186 ) : (
187 <Animated.View
188 entering={FadeIn.duration(120)}
189 className="absolute overflow-hidden bg-card-alt shadow-md"
190 style={{
191 left,
192 maxHeight,
193 width: menuWidth,
194 borderRadius: 4 * scale,
195 ...(opensDown
196 ? { top: local.y + local.height + ANCHOR_GAP }
197 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
198 }}
199 >
200 {/* Compose DropdownMenu takes popup focus in the pinned Expo UI version.
201 Keep editor menus in-window so opening one preserves the keyboard. */}
202​
203 {/* keyboardShouldPersistTaps: the menu often opens over an
204 active editor; the first item tap must act, not just
205 dismiss the keyboard. */}
206 <ScrollView
207 contentContainerStyle={{ paddingVertical: 7 * scale }}
208 bounces={false}
209 keyboardShouldPersistTaps="always"
210 showsVerticalScrollIndicator={false}
211 >
212 <MenuPopup
213 inline
214 anchor={local}
215 menuWidth={menuWidth}
216 actions={levelActions}
217 title={props.title}
218 parent={parent}
219 onPress={onPressItem}
220 onBack={() => setPath((current) => current.slice(0, -1))}
221 onClose={close}
222 />
223 </ScrollView>
224 </Animated.View>
225 )}
226 </View>
227 </OverlayPortal>
228 )}
229 </>
230 );