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

AndroidAnchoredMenu.android.tsx

224 lines7.9 KB

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";
7​
8import { useHardwareBack } from "../../lib/backHandler";
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 // State, not a ref: `open` reaches render-prop children, and the compiler
51 // bails out of the whole component when a ref might be read during render.
52 const [anchorNode, setAnchorNode] = useState<ViewInstance | null>(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 = () => {
58 setAnchor(null);
59 setPath([]);
60 setOverlay(null);
61 setRootHeight(null);
62 };
63​
64 const open = () => {
65 anchorNode?.measureInWindow((x, y, width, height) => {
66 setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
67 });
68 };
69​
70 const measureOverlay = () => {
71 overlayRef.current?.measureInWindow((x, y, width, height) => {
72 setOverlay({ x, y, width, height });
73 setRootHeight(height);
74 });
75 };
76​
77 // Only the in-window (keyboard) presentation needs this; the native popup
78 // handles back itself.
79 useHardwareBack(anchor?.keyboardWasVisible === true, () => {
80 if (path.length > 0) {
81 setPath((current) => current.slice(0, -1));
82 } else {
83 close();
84 }
85 return true;
86 });
87​
88 const parent = path[path.length - 1] ?? null;
89 const levelActions = (parent?.subactions ?? props.actions).filter(
90 (action) => !(action.attributes?.hidden ?? false),
91 );
92​
93 const local =
94 anchor === null || overlay === null
95 ? null
96 : {
97 x: anchor.x - overlay.x,
98 y: anchor.y - overlay.y,
99 width: anchor.width,
100 height: anchor.height,
101 };
102 const { left, width: menuWidth } =
103 local === null || overlay === null
104 ? { left: 0, width: desiredMenuWidth }
105 : deriveMenuHorizontalPlacement({
106 anchorX: local.x,
107 anchorWidth: local.width,
108 overlayWidth: overlay.width,
109 desiredWidth: desiredMenuWidth,
110 margin: SCREEN_MARGIN,
111 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
112 });
113 // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
114 const usableBottom =
115 overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
116 const spaceBelow =
117 local === null || overlay === null
118 ? 0
119 : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
120 const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
121 const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
122 const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
123 const placeable = local !== null && rootHeight !== null;
124​
125 const onPressItem = (action: MenuAction) => {
126 if ((action.subactions?.length ?? 0) > 0) {
127 setPath((current) => [...current, action]);
128 return;
129 }
130 close();
131 if (action.id !== undefined) {
132 props.onPressAction?.({
133 nativeEvent: { event: action.id },
134 } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
135 }
136 };
137​
138 return (
139 <>
140 {typeof props.children === "function" ? (
141 <View
142 ref={setAnchorNode}
143 collapsable={false}
144 className={props.className}
145 style={props.style}
146 >
147 {props.children(open)}
148 </View>
149 ) : (
150 <Pressable
151 ref={setAnchorNode}
152 accessibilityRole="button"
153 className={props.className}
154 collapsable={false}
155 style={props.style}
156 onPress={open}
157 >
158 <View pointerEvents="none">{props.children}</View>
159 </Pressable>
160 )}
161 {anchor === null ? null : (
162 <OverlayPortal>
163 <View
164 ref={overlayRef}
165 collapsable={false}
166 className="absolute inset-0"
167 onLayout={measureOverlay}
168 >
169 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
170 {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
171 <MenuPopup
172 // Compose aligns to the trigger's start if it fits; hinge-safe triggers keep menus on their side.
173 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
174 menuWidth={menuWidth}
175 actions={levelActions}
176 title={props.title}
177 parent={parent}
178 onPress={onPressItem}
179 onBack={() => setPath((current) => current.slice(0, -1))}
180 onClose={close}
181 />
182 ) : (
183 <View
184 // No entering animation: it freezes this frame before the Compose host reports its size.
185 className="absolute overflow-hidden bg-card-alt shadow-md"
186 style={{
187 left,
188 maxHeight,
189 width: menuWidth,
190 borderRadius: 4 * scale,
191 ...(opensDown
192 ? { top: local.y + local.height + ANCHOR_GAP }
193 : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
194 }}
195 >
196 {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */}
197​
198 {/* The first item tap must act while the keyboard is open. */}
199 <ScrollView
200 contentContainerStyle={{ paddingVertical: 7 * scale }}
201 bounces={false}
202 keyboardShouldPersistTaps="always"
203 showsVerticalScrollIndicator={false}
204 >
205 <MenuPopup
206 inline
207 anchor={local}
208 menuWidth={menuWidth}
209 actions={levelActions}
210 title={props.title}
211 parent={parent}
212 onPress={onPressItem}
213 onBack={() => setPath((current) => current.slice(0, -1))}
214 onClose={close}
215 />
216 </ScrollView>
217 </View>
218 )}
219 </View>
220 </OverlayPortal>
221 )}
222 </>
223 );