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

ControlPill.tsx

260 lines8.6 KB

1import { MenuView } from "@react-native-menu/menu";
2import * as Haptics from "expo-haptics";
3import {
4 cloneElement,
5 isValidElement,
6 type ComponentProps,
7 type ReactElement,
8 type ReactNode,
9 useMemo,
10 useRef,
11} from "react";
12import { Platform, Pressable, View, type ColorValue, type PressableProps } from "react-native";
13import { withUniwind } from "uniwind";
14import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
15​
16import { cn } from "../lib/cn";
17import { withMenuActionIconColors } from "../lib/menu-action-colors";
18import { AndroidAnchoredMenu } from "./AndroidAnchoredMenu";
19import { SymbolView } from "./AppSymbol";
20import { AppText as Text } from "./AppText";
21​
22const ThemedMenuView = withUniwind(
23 function NativeMenuView({
24 iconColor,
25 destructiveIconColor,
26 ...props
27 }: ComponentProps<typeof MenuView> & {
28 readonly iconColor?: ColorValue;
29 readonly destructiveIconColor?: ColorValue;
30 }) {
31 const actions = useMemo(
32 () =>
33 withMenuActionIconColors(props.actions, {
34 icon: iconColor,
35 destructiveIcon: destructiveIconColor,
36 }),
37 [props.actions, iconColor, destructiveIconColor],
38 );
39 return <MenuView {...props} actions={actions} />;
40 },
41 {
42 iconColor: { fromClassName: "iconColorClassName", styleProperty: "accentColor" },
43 destructiveIconColor: {
44 fromClassName: "destructiveIconColorClassName",
45 styleProperty: "accentColor",
46 },
47 },
48);
49​
50export function ControlPill(props: {
51 readonly icon?: ComponentProps<typeof SymbolView>["name"];
52 readonly iconNode?: ReactNode;
53 readonly label?: string;
54 readonly accessibilityLabel?: string;
55 readonly onPress?: () => void;
56 readonly activateOnPressIn?: boolean;
57 readonly variant?: "circle" | "pill" | "primary" | "danger";
58 readonly disabled?: boolean;
59 readonly className?: string;
60}) {
61 const variant = props.variant ?? "circle";
62 const activatedOnPressInRef = useRef(false);
63​
64 const handlePressIn = () => {
65 activatedOnPressInRef.current = true;
66 props.onPress?.();
67 };
68 const handlePressOut = () => {
69 // Pressability invokes onPressOut immediately before onPress on release.
70 // Defer the reset so onPress can identify the same physical gesture.
71 setTimeout(() => {
72 activatedOnPressInRef.current = false;
73 }, 0);
74 };
75 const handlePress = () => {
76 if (activatedOnPressInRef.current) {
77 return;
78 }
79 props.onPress?.();
80 };
81​
82 const iconTintClassName =
83 variant === "primary"
84 ? props.disabled
85 ? "accent-icon-subtle"
86 : "accent-primary-foreground"
87 : variant === "danger"
88 ? "accent-danger-foreground"
89 : "accent-icon";
90​
91 const isCircle =
92 variant === "circle" || variant === "danger" || (variant === "primary" && !props.label);
93 const containerClassName = cn(
94 isCircle
95 ? "h-11 w-11 items-center justify-center rounded-full"
96 : variant === "primary"
97 ? "h-11 flex-row items-center justify-center gap-2 rounded-full px-5"
98 : "h-11 flex-row items-center justify-center gap-2 rounded-full px-3.5",
99 variant === "primary"
100 ? props.disabled
101 ? "bg-subtle-strong"
102 : "bg-primary"
103 : variant === "danger"
104 ? "bg-danger"
105 : "bg-subtle",
106 props.className,
107 );
108 const labelClassName = cn(
109 "text-center text-xs font-t3-bold",
110 variant === "primary"
111 ? props.disabled
112 ? "text-foreground-muted"
113 : "text-primary-foreground"
114 : "",
115 );
116​
117 return (
118 <Pressable
119 accessibilityLabel={props.accessibilityLabel ?? props.label}
120 accessibilityRole="button"
121 onPress={props.activateOnPressIn ? handlePress : props.onPress}
122 onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
123 onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
124 disabled={props.disabled}
125 className={containerClassName}
126 >
127 {props.iconNode ? (
128 <View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
129 ) : props.icon ? (
130 <SymbolView
131 name={props.icon}
132 size={16}
133 tintColorClassName={iconTintClassName}
134 type="monochrome"
135 />
136 ) : null}
137 {props.label ? <Text className={labelClassName}>{props.label}</Text> : null}
138 </Pressable>
139 );
141​
142// iOS renders the native UIMenu (standard checkmark for `state: "on"`);
143// Android renders the token-styled AndroidAnchoredMenu, since the native
144// AppCompat popup can't be themed past its stock animation, metrics, and
145// submenu chrome.
146export function ControlPillMenu(
147 props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
148 readonly children: ReactNode;
149 readonly className?: string;
150 },
151) {
152 const { themeAppearance } = useAppearancePreferences();
153 const isDarkMode = themeAppearance === "dark";
154 const menuPress = useRef({ isPreparing: false, isOpen: false, suppressPress: false });
155 const pendingPress = useRef<(() => void) | null>(null);
156​
157 if (Platform.OS === "android") {
158 // Long-press menus keep their child interactive: the child element gets
159 // an injected onLongPress (mirroring the iOS context-menu interaction)
160 // so its own tap handling still works.
161 if (props.shouldOpenOnLongPress && isValidElement(props.children)) {
162 const child = props.children as ReactElement<{ onLongPress?: () => void }>;
163 return (
164 <AndroidAnchoredMenu
165 actions={props.actions}
166 className={props.className}
167 title={props.title}
168 style={props.style}
169 onPressAction={props.onPressAction}
170 >
171 {(open) =>
172 cloneElement(child, {
173 onLongPress: () => {
174 void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
175 open();
176 },
177 })
178 }
179 </AndroidAnchoredMenu>
180 );
181 }
182 return (
183 <AndroidAnchoredMenu
184 actions={props.actions}
185 className={props.className}
186 title={props.title}
187 style={props.style}
188 onPressAction={props.onPressAction}
189 >
190 {props.children}
191 </AndroidAnchoredMenu>
192 );
193 }
194​
195 const { className: _className, ...menuProps } = props;
196 let children = menuProps.children;
197 if (props.shouldOpenOnLongPress && isValidElement(children)) {
198 const child = children as ReactElement<Pick<PressableProps, "onTouchStart" | "onPress">>;
199 children = cloneElement(child, {
200 onTouchStart: (event) => {
201 // Reset for a new touch, not onPressIn, which also fires when a
202 // finger moves out of the row and back during the same gesture.
203 menuPress.current.isPreparing = false;
204 menuPress.current.suppressPress = menuPress.current.isOpen;
205 pendingPress.current = null;
206 child.props.onTouchStart?.(event);
207 },
208 onPress: (event) => {
209 // Accessibility clicks have no touch identifier and must not inherit
210 // cancellation from a previous physical gesture.
211 const isTouch = typeof event.nativeEvent.identifier === "number";
212 if (isTouch ? menuPress.current.suppressPress : menuPress.current.isOpen) {
213 return;
214 }
215 if (isTouch && menuPress.current.isPreparing) {
216 // A release can arrive between native menu preparation and display.
217 // Let UIKit's display/cancel callback decide this press's outcome.
218 event.persist();
219 pendingPress.current = () => child.props.onPress?.(event);
220 return;
221 }
222 child.props.onPress?.(event);
223 },
224 });
225 menuProps.onMenuInteractionStart = () => {
226 menuPress.current.isPreparing = true;
227 props.onMenuInteractionStart?.();
228 };
229 menuProps.onOpenMenu = () => {
230 menuPress.current.isPreparing = false;
231 menuPress.current.isOpen = true;
232 menuPress.current.suppressPress = true;
233 pendingPress.current = null;
234 props.onOpenMenu?.();
235 };
236 menuProps.onCloseMenu = () => {
237 menuPress.current.isPreparing = false;
238 menuPress.current.isOpen = false;
239 // Keep this gesture cancelled even if dismissal precedes finger-up.
240 // A separate JS long-press timer would also swallow holds that never
241 // open the native menu.
242 const press = pendingPress.current;
243 pendingPress.current = null;
244 props.onCloseMenu?.();
245 if (!menuPress.current.suppressPress) {
246 press?.();
247 }
248 };
249 }
250 return (
251 <ThemedMenuView
252 {...menuProps}
253 iconColorClassName="accent-icon"
254 destructiveIconColorClassName="accent-danger-foreground"
255 themeVariant={isDarkMode ? "dark" : "light"}
256 >
257 {children}
258 </ThemedMenuView>
259 );