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

ControlPill.tsx

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