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

AndroidAnchoredMenu.tsx

226 lines8.0 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// 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 { onPressAction } = props;
129 const onPressItem = useCallback(
130 (action: MenuAction) => {
131 if ((action.subactions?.length ?? 0) > 0) {
132 setPath((current) => [...current, action]);
133 return;
134 }
135 close();
136 if (action.id !== undefined) {
137 onPressAction?.({
138 nativeEvent: { event: action.id },
139 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
140 }
141 },
142 [close, onPressAction],
143 );
144​
145 return (
146 <>
147 {typeof props.children === "function" ? (
148 <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
149 {props.children(open)}
150 </View>
151 ) : (
152 <Pressable
153 ref={anchorRef}
154 accessibilityRole="button"
155 className={props.className}
156 collapsable={false}
157 style={props.style}
158 onPress={open}
159 >
160 <View pointerEvents="none">{props.children}</View>
161 </Pressable>
162 )}
163 {anchor === null ? null : (
164 <OverlayPortal>
165 <View
166 ref={overlayRef}
167 collapsable={false}
168 className="absolute inset-0"
169 onLayout={measureOverlay}
170 >
171 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
172 {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
173 <MenuPopup
174 // Compose aligns to the trigger's start if it fits; hinge-safe triggers keep menus on their side.
175 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
176 menuWidth={menuWidth}
177 actions={levelActions}
178 title={props.title}
179 parent={parent}
180 onPress={onPressItem}
181 onBack={() => setPath((current) => current.slice(0, -1))}
182 onClose={close}
183 />
184 ) : (
185 <Animated.View
186 entering={FadeIn.duration(120)}
187 className="absolute overflow-hidden bg-card-alt shadow-md"
188 style={{
189 left,
190 maxHeight,
191 width: menuWidth,
192 borderRadius: 4 * scale,
193 ...(opensDown
194 ? { top: local.y + local.height + ANCHOR_GAP }
195 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
196 }}
197 >
198 {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */}
199​
200 {/* The first item tap must act while the keyboard is open. */}
201 <ScrollView
202 contentContainerStyle={{ paddingVertical: 7 * scale }}
203 bounces={false}
204 keyboardShouldPersistTaps="always"
205 showsVerticalScrollIndicator={false}
206 >
207 <MenuPopup
208 inline
209 anchor={local}
210 menuWidth={menuWidth}
211 actions={levelActions}
212 title={props.title}
213 parent={parent}
214 onPress={onPressItem}
215 onBack={() => setPath((current) => current.slice(0, -1))}
216 onClose={close}
217 />
218 </ScrollView>
219 </Animated.View>
220 )}
221 </View>
222 </OverlayPortal>
223 )}
224 </>
225 );