Open History to see the last commit
1import { NativeThemeHost } from "./NativeThemeHost.android";
2import {
3 AlertDialog,
4 Button,
5 OutlinedButton,
6 Icon,
7 FlowRow,
8 Column,
9 OutlinedTextField,
10 Text,
11 useNativeState,
12} from "@expo/ui/jetpack-compose";
13
14import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
15import { useScaledTextRole } from "../../features/settings/appearance/useScaledTextRole";
16
17import { useSyncExternalStore } from "react";
18import { themeColorWithContrast } from "../../lib/mobileTheme";
19import type { Alert, AlertButton } from "react-native";
20import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types";
21
22export type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types";
23
24type AlertRequest = {
25 readonly title: Parameters<typeof Alert.alert>[0];
26 readonly message: Parameters<typeof Alert.alert>[1];
27 readonly buttons: Parameters<typeof Alert.alert>[2];
28 readonly options: Parameters<typeof Alert.alert>[3];
29};
30
31type DialogRequest =
32 | { readonly kind: "alert"; readonly request: AlertRequest }
33 | { readonly kind: "confirm"; readonly request: ConfirmDialogRequest }
34 | { readonly kind: "text-input"; readonly request: TextInputDialogRequest };
35
36type PresentedDialog = DialogRequest & { readonly id: number };
37
38// App services raise dialogs before the root mounts, so the request lives in
39// the module and the Host renders whatever is current. One dialog shows at a
40// time: a new request replaces the presented one.
41let presented: PresentedDialog | null = null;
42let nextPresentationId = 0;
43const listeners = new Set<() => void>();
44
45function setPresented(next: PresentedDialog | null) {
46 presented = next;
47 for (const listener of listeners) listener();
48}
49
50function submitRequest(dialog: DialogRequest) {
51 setPresented({ ...dialog, id: ++nextPresentationId });
52}
53
54/** Closes the dialog only if it is still the one the action came from. */
55function dismiss(id: number) {
56 if (presented?.id === id) setPresented(null);
57}
58
59function subscribe(listener: () => void) {
60 listeners.add(listener);
61 return () => {
62 listeners.delete(listener);
63 };
64}
65
66function getPresented() {
67 return presented;
68}
69
70export function alert(...[title, message, buttons, options]: Parameters<typeof Alert.alert>): void {
71 const actions = buttons?.length ? buttons.slice(0, 3) : [{ text: "OK" }];
72 const normalized = actions.map((action, index) =>
73 index === actions.length - 1 ? { ...action, text: action.text || "OK" } : action,
74 );
75 submitRequest({
76 kind: "alert",
77 request: { title, message, buttons: normalized, options },
78 });
79}
80
81export function confirm(request: ConfirmDialogRequest): void {
82 submitRequest({ kind: "confirm", request });
83}
84
85export function prompt(request: TextInputDialogRequest): void {
86 submitRequest({ kind: "text-input", request });
87}
88
89export function Host() {
90 const presented = useSyncExternalStore(subscribe, getPresented, getPresented);
91
92 const handleCancel = () => {
93 if (!presented) return;
94 dismiss(presented.id);
95 if (presented.kind === "alert") presented.request.options?.onDismiss?.();
96 else presented.request.onCancel?.();
97 };
98
99 const handleConfirm = (nativeInputValue?: string) => {
100 if (!presented) return;
101 dismiss(presented.id);
102 if (presented.kind === "confirm") {
103 presented.request.onConfirm();
104 } else if (presented.kind === "text-input") {
105 presented.request.onConfirm(nativeInputValue ?? presented.request.initialValue);
106 }
107 };
108
109 if (presented?.kind === "alert") {
110 return (
111 <DialogPresentation
112 key={presented.id}
113 request={{
114 title: presented.request.title ?? "",
115 message: presented.request.message ?? undefined,
116 confirmText: "",
117 }}
118 alertActions={presented.request.buttons ?? [{ text: "OK" }]}
119 dismissable={presented.request.options?.cancelable ?? false}
120 onAlertAction={(action) => {
121 dismiss(presented.id);
122 action.onPress?.();
123 }}
124 onCancel={handleCancel}
125 onConfirm={handleConfirm}
126 />
127 );
128 }
129
130 return presented ? (
131 <DialogPresentation
132 key={presented.id}
133 request={presented.request}
134 inputInitialValue={
135 presented.kind === "text-input" ? presented.request.initialValue : undefined
136 }
137 inputPlaceholder={presented.kind === "text-input" ? presented.request.placeholder : undefined}
138 onCancel={handleCancel}
139 onConfirm={handleConfirm}
140 />
141 ) : null;
142}
143
144function DialogPresentation(props: DialogPresentationProps) {
145 const { themeVariables: colors } = useAppearancePreferences();
146 const titleTypography = useScaledTextRole("title");
147 const bodyTypography = useScaledTextRole("footnote");
148 const inputTypography = useScaledTextRole("body");
149 const inputState = useNativeState(props.inputInitialValue ?? "");
150 const inputSelection = useNativeState({ start: 0, end: props.inputInitialValue?.length ?? 0 });
151 const confirm = () => {
152 const value = props.inputInitialValue === undefined ? undefined : inputState.get();
153 props.onConfirm(value);
154 };
155 const actions = props.alertActions ?? [
156 { text: props.request.cancelText ?? "Cancel", onPress: props.onCancel },
157 {
158 text: props.request.confirmText,
159 style: props.request.destructive ? ("destructive" as const) : ("default" as const),
160 onPress: confirm,
161 },
162 ];
163 const destructive = actions.some((action) => action.style === "destructive");
164 // Error text colors can be pastel in dark themes. Filled actions need a white-label contrast pair.
165 const destructiveFill = themeColorWithContrast(colors["--color-danger-foreground"], "#ffffff");
166 const renderAction = (action: AlertButton, index: number) => {
167 const isDestructive = action.style === "destructive";
168 const isPrimary = isDestructive || index === actions.length - 1;
169 const Component = isPrimary ? Button : OutlinedButton;
170 return (
171 <Component
172 key={index}
173 onClick={() => (props.alertActions ? props.onAlertAction?.(action) : action.onPress?.())}
174 colors={{
175 containerColor: isDestructive
176 ? destructiveFill
177 : isPrimary
178 ? colors["--color-prominent-action"]
179 : "#00000000",
180 contentColor: isDestructive
181 ? "#ffffff"
182 : isPrimary
183 ? colors["--color-prominent-action-foreground"]
184 : colors["--color-foreground"],
185 }}
186 >
187 <Text style={bodyTypography}>{action.text ?? ""}</Text>
188 </Component>
189 );
190 };
191 return (
192 <NativeThemeHost ignoreSafeAreaKeyboardInsets style={{ height: 0, width: 0 }}>
193 <AlertDialog
194 onDismissRequest={props.onCancel}
195 properties={{
196 dismissOnBackPress: props.dismissable ?? true,
197 dismissOnClickOutside: props.dismissable ?? true,
198 }}
199 tonalElevation={0}
200 colors={{
201 containerColor: colors["--color-card"],
202 titleContentColor: colors["--color-foreground"],
203 textContentColor: colors["--color-foreground-secondary"],
204 }}
205 >
206 <AlertDialog.Title>
207 <Column verticalArrangement={{ spacedBy: 16 }}>
208 {destructive ? (
209 <Icon
210 source={require("../../../assets/icons/delete.xml")}
211 tint={colors["--color-danger-foreground"]}
212 size={24}
213 />
214 ) : null}
215 <Text style={titleTypography}>{props.request.title}</Text>
216 </Column>
217 </AlertDialog.Title>
218 {props.inputInitialValue !== undefined ? (
219 <AlertDialog.Text>
220 <Column verticalArrangement={{ spacedBy: 16 }}>
221 {props.request.message ? (
222 <Text style={bodyTypography}>{props.request.message}</Text>
223 ) : null}
224 <OutlinedTextField
225 autoFocus
226 singleLine
227 value={inputState}
228 selection={inputSelection}
229 textStyle={inputTypography}
230 keyboardOptions={{ imeAction: "done" }}
231 keyboardActions={{
232 onDone: confirm,
233 }}
234 colors={{
235 focusedTextColor: colors["--color-foreground"],
236 unfocusedTextColor: colors["--color-foreground"],
237 focusedIndicatorColor: colors["--color-focus"],
238 unfocusedIndicatorColor: colors["--color-border"],
239 cursorColor: colors["--color-focus"],
240 }}
241 >
242 <OutlinedTextField.Label>
243 <Text style={bodyTypography}>{props.request.title}</Text>
244 </OutlinedTextField.Label>
245 {props.inputPlaceholder ? (
246 <OutlinedTextField.Placeholder>
247 <Text style={bodyTypography}>{props.inputPlaceholder}</Text>
248 </OutlinedTextField.Placeholder>
249 ) : null}
250 </OutlinedTextField>
251 </Column>
252 </AlertDialog.Text>
253 ) : props.request.message ? (
254 <AlertDialog.Text>
255 <Text style={bodyTypography}>{props.request.message}</Text>
256 </AlertDialog.Text>
257 ) : null}
258 {actions.length > 1 ? (
259 <AlertDialog.DismissButton>
260 <FlowRow>{actions.slice(0, -1).map(renderAction)}</FlowRow>
261 </AlertDialog.DismissButton>
262 ) : null}
263 {actions.length > 0 ? (
264 <AlertDialog.ConfirmButton>
265 {renderAction(actions[actions.length - 1]!, actions.length - 1)}
266 </AlertDialog.ConfirmButton>
267 ) : null}
268 </AlertDialog>
269 </NativeThemeHost>
270 );
271}
272
273interface DialogPresentationProps {
274 readonly alertActions?: readonly AlertButton[];
275 readonly onAlertAction?: (action: AlertButton) => void;
276 readonly dismissable?: boolean;
277 readonly request: Pick<
278 ConfirmDialogRequest,
279 "title" | "message" | "cancelText" | "confirmText" | "destructive"
280 >;
281 readonly inputInitialValue?: string;
282 readonly inputPlaceholder?: string;
283 readonly onCancel: () => void;
284 readonly onConfirm: (inputValue?: string) => void;
285}