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

AndroidAnchoredMenu.tsx

233 lines8.4 KB

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// Both snapshots are taken at open time so later reflows (keyboard show/hide,
19// screen transitions) can't flip an opens-up menu to opens-down
20// mid-presentation.
21type AnchorSnapshot = {
22 readonly x: number;
23 readonly y: number;
24 readonly width: number;
25 readonly height: number;
26 readonly keyboardWasVisible: boolean;
27};
28​
29type OverlayFrame = {
30 readonly x: number;
31 readonly y: number;
32 readonly width: number;
33 readonly height: number;
34};
35​
36export type AndroidAnchoredMenuProps = {
37 readonly actions: readonly MenuAction[];
38 readonly title?: string;
39 readonly onPressAction?: MenuComponentProps["onPressAction"];
40 readonly className?: string;
41 readonly style?: StyleProp<ViewStyle>;
42 readonly children: ReactNode | ((open: () => void) => ReactNode);
43};
44​
45export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
46 const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing();
47 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
48 const [path, setPath] = useState<readonly MenuAction[]>([]);
49 const [rootHeight, setRootHeight] = useState<number | null>(null);
50 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
51 const windowHinge = use(WindowHingeContext);
52 const anchorRef = useRef<ViewInstance>(null);
53 const overlayRef = useRef<ViewInstance>(null);
54​
55 const keyboardVisible = useKeyboardState((state) => state.isVisible);
56 const keyboardHeight = useKeyboardState((state) => state.height);
57 const close = useCallback(() => {
58 setAnchor(null);
59 setPath([]);
60 setOverlay(null);
61 setRootHeight(null);
62 }, []);
63​
64 const open = useCallback(() => {
65 anchorRef.current?.measureInWindow((x, y, width, height) => {
66 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
67 });
68 }, [keyboardVisible]);
69​
70 const measureOverlay = useCallback(() => {
71 overlayRef.current?.measureInWindow((x, y, width, height) => {
72 setOverlay({ x, y, width, height });
73 setRootHeight(height);
74 });
75 }, []);
76​
77 const submenuDepth = path.length;
78 useEffect(() => {
79 if (anchor === null || !anchor.keyboardWasVisible) {
80 return;
81 }
82 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
83 if (submenuDepth > 0) {
84 setPath((current) => current.slice(0, -1));
85 } else {
86 close();
87 }
88 return true;
89 });
90 return () => subscription.remove();
91 }, [anchor, close, submenuDepth]);
92​
93 const parent = path[path.length - 1] ?? null;
94 const levelActions = (parent?.subactions ?? props.actions).filter(
95 (action) => !(action.attributes?.hidden ?? false),
96 );
97​
98 const local =
99 anchor === null || overlay === null
100 ? null
101 : {
102 x: anchor.x - overlay.x,
103 y: anchor.y - overlay.y,
104 width: anchor.width,
105 height: anchor.height,
106 };
107 const { left, width: menuWidth } =
108 local === null || overlay === null
109 ? { left: 0, width: desiredMenuWidth }
110 : deriveMenuHorizontalPlacement({
111 anchorX: local.x,
112 anchorWidth: local.width,
113 overlayWidth: overlay.width,
114 desiredWidth: desiredMenuWidth,
115 margin: SCREEN_MARGIN,
116 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
117 });
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 // Compose aligns its dropdown to the trigger's start whenever it fits, so a
178 // trigger at the hinge-safe position keeps the menu on the anchor's side.
179 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
180 menuWidth={menuWidth}
181 actions={levelActions}
182 title={props.title}
183 parent={parent}
184 onPress={onPressItem}
185 onBack={() => setPath((current) => current.slice(0, -1))}
186 onClose={close}
187 />
188 ) : (
189 <Animated.View
190 entering={FadeIn.duration(120)}
191 className="absolute overflow-hidden bg-card-alt shadow-md"
192 style={{
193 left,
194 maxHeight,
195 width: menuWidth,
196 borderRadius: 4 * scale,
197 ...(opensDown
198 ? { top: local.y + local.height + ANCHOR_GAP }
199 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
200 }}
201 >
202 {/* Compose DropdownMenu takes popup focus in the pinned Expo UI version.
203 Keep editor menus in-window so opening one preserves the keyboard. */}
204​
205 {/* keyboardShouldPersistTaps: the menu often opens over an
206 active editor; the first item tap must act, not just
207 dismiss the keyboard. */}
208 <ScrollView
209 contentContainerStyle={{ paddingVertical: 7 * scale }}
210 bounces={false}
211 keyboardShouldPersistTaps="always"
212 showsVerticalScrollIndicator={false}
213 >
214 <MenuPopup
215 inline
216 anchor={local}
217 menuWidth={menuWidth}
218 actions={levelActions}
219 title={props.title}
220 parent={parent}
221 onPress={onPressItem}
222 onBack={() => setPath((current) => current.slice(0, -1))}
223 onClose={close}
224 />
225 </ScrollView>
226 </Animated.View>
227 )}
228 </View>
229 </OverlayPortal>
230 )}
231 </>
232 );