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 { useCallback, useEffect, useRef, useState } 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
36let presentRequest: ((request: DialogRequest) => void) | null = null;
37
38export function alert(...[title, message, buttons, options]: Parameters<typeof Alert.alert>): void {
39 const actions = buttons?.length ? buttons.slice(0, 3) : [{ text: "OK" }];
40 const normalized = actions.map((action, index) =>
41 index === actions.length - 1 ? { ...action, text: action.text || "OK" } : action,
42 );
43 presentRequest?.({
44 kind: "alert",
45 request: { title, message, buttons: normalized, options },
46 });
47}
48
49export function confirm(request: ConfirmDialogRequest): void {
50 presentRequest?.({ kind: "confirm", request });
51}
52
53export function prompt(request: TextInputDialogRequest): void {
54 presentRequest?.({ kind: "text-input", request });
55}
56
57/** Android presenter for Dialog.alert, Dialog.confirm and Dialog.prompt; mounted once at the app root. */
58export function Host() {
59 const [presented, setPresented] = useState<(DialogRequest & { readonly id: number }) | null>(
60 null,
61 );
62 const [inputValue, setInputValue] = useState("");
63 const nextPresentationId = useRef(0);
64 useEffect(() => {
65 presentRequest = (request) => {
66 setInputValue(request.kind === "text-input" ? request.request.initialValue : "");
67 setPresented({ ...request, id: ++nextPresentationId.current });
68 };
69 return () => {
70 presentRequest = null;
71 };
72 }, []);
73
74 const handleCancel = useCallback(() => {
75 setPresented(null);
76 if (presented?.kind === "alert") presented.request.options?.onDismiss?.();
77 else presented?.request.onCancel?.();
78 }, [presented]);
79
80 const handleConfirm = useCallback(
81 (nativeInputValue?: string) => {
82 setPresented(null);
83 if (presented?.kind === "confirm") {
84 presented.request.onConfirm();
85 } else if (presented?.kind === "text-input") {
86 presented.request.onConfirm(nativeInputValue ?? inputValue);
87 }
88 },
89 [inputValue, presented],
90 );
91
92 if (presented?.kind === "alert") {
93 return (
94 <DialogPresentation
95 key={presented.id}
96 request={{
97 title: presented.request.title ?? "",
98 message: presented.request.message ?? undefined,
99 confirmText: "",
100 }}
101 alertActions={presented.request.buttons ?? [{ text: "OK" }]}
102 dismissable={presented.request.options?.cancelable ?? false}
103 onAlertAction={(action) => {
104 setPresented(null);
105 action.onPress?.();
106 }}
107 onCancel={handleCancel}
108 onConfirm={handleConfirm}
109 />
110 );
111 }
112
113 return presented ? (
114 <DialogPresentation
115 key={presented.id}
116 request={presented.request}
117 inputInitialValue={
118 presented.kind === "text-input" ? presented.request.initialValue : undefined
119 }
120 onInputChange={setInputValue}
121 onCancel={handleCancel}
122 onConfirm={handleConfirm}
123 />
124 ) : null;
125}
126
127function DialogPresentation(props: DialogPresentationProps) {
128 const { themeVariables: colors } = useAppearancePreferences();
129 const titleTypography = useScaledTextRole("title");
130 const bodyTypography = useScaledTextRole("footnote");
131 const inputTypography = useScaledTextRole("body");
132 const inputState = useNativeState(props.inputInitialValue ?? "");
133 const inputSelection = useNativeState({ start: 0, end: props.inputInitialValue?.length ?? 0 });
134 const confirm = () => {
135 const value = props.inputInitialValue === undefined ? undefined : inputState.get();
136 props.onConfirm(value);
137 };
138 const actions = props.alertActions ?? [
139 { text: props.request.cancelText ?? "Cancel", onPress: props.onCancel },
140 {
141 text: props.request.confirmText,
142 style: props.request.destructive ? ("destructive" as const) : ("default" as const),
143 onPress: confirm,
144 },
145 ];
146 const destructive = actions.some((action) => action.style === "destructive");
147 // Error text colors can be pastel in dark themes. Filled actions need a white-label contrast pair.
148 const destructiveFill = themeColorWithContrast(colors["--color-danger-foreground"], "#ffffff");
149 const renderAction = (action: AlertButton, index: number) => {
150 const isDestructive = action.style === "destructive";
151 const isPrimary = isDestructive || index === actions.length - 1;
152 const Component = isPrimary ? Button : OutlinedButton;
153 return (
154 <Component
155 key={index}
156 onClick={() => (props.alertActions ? props.onAlertAction?.(action) : action.onPress?.())}
157 colors={{
158 containerColor: isDestructive
159 ? destructiveFill
160 : isPrimary
161 ? colors["--color-prominent-action"]
162 : "#00000000",
163 contentColor: isDestructive
164 ? "#ffffff"
165 : isPrimary
166 ? colors["--color-prominent-action-foreground"]
167 : colors["--color-foreground"],
168 }}
169 >
170 <Text style={bodyTypography}>{action.text ?? ""}</Text>
171 </Component>
172 );
173 };
174 return (
175 <NativeThemeHost ignoreSafeAreaKeyboardInsets style={{ height: 0, width: 0 }}>
176 <AlertDialog
177 onDismissRequest={props.onCancel}
178 properties={{
179 dismissOnBackPress: props.dismissable ?? true,
180 dismissOnClickOutside: props.dismissable ?? true,
181 }}
182 tonalElevation={0}
183 colors={{
184 containerColor: colors["--color-card"],
185 titleContentColor: colors["--color-foreground"],
186 textContentColor: colors["--color-foreground-secondary"],
187 }}
188 >
189 <AlertDialog.Title>
190 <Column verticalArrangement={{ spacedBy: 16 }}>
191 {destructive ? (
192 <Icon
193 source={require("../../../assets/icons/delete.xml")}
194 tint={colors["--color-danger-foreground"]}
195 size={24}
196 />
197 ) : null}
198 <Text style={titleTypography}>{props.request.title}</Text>
199 </Column>
200 </AlertDialog.Title>
201 {props.inputInitialValue !== undefined ? (
202 <AlertDialog.Text>
203 <OutlinedTextField
204 autoFocus
205 singleLine
206 value={inputState}
207 selection={inputSelection}
208 onValueChange={props.onInputChange}
209 textStyle={inputTypography}
210 keyboardOptions={{ imeAction: "done" }}
211 keyboardActions={{
212 onDone: confirm,
213 }}
214 colors={{
215 focusedTextColor: colors["--color-foreground"],
216 unfocusedTextColor: colors["--color-foreground"],
217 focusedIndicatorColor: colors["--color-focus"],
218 unfocusedIndicatorColor: colors["--color-border"],
219 cursorColor: colors["--color-focus"],
220 }}
221 >
222 <OutlinedTextField.Label>
223 <Text style={bodyTypography}>{props.request.title}</Text>
224 </OutlinedTextField.Label>
225 </OutlinedTextField>
226 </AlertDialog.Text>
227 ) : props.request.message ? (
228 <AlertDialog.Text>
229 <Text style={bodyTypography}>{props.request.message}</Text>
230 </AlertDialog.Text>
231 ) : null}
232 {actions.length > 1 ? (
233 <AlertDialog.DismissButton>
234 <FlowRow>{actions.slice(0, -1).map(renderAction)}</FlowRow>
235 </AlertDialog.DismissButton>
236 ) : null}
237 {actions.length > 0 ? (
238 <AlertDialog.ConfirmButton>
239 {renderAction(actions[actions.length - 1]!, actions.length - 1)}
240 </AlertDialog.ConfirmButton>
241 ) : null}
242 </AlertDialog>
243 </NativeThemeHost>
244 );
245}
246
247interface DialogPresentationProps {
248 readonly alertActions?: readonly AlertButton[];
249 readonly onAlertAction?: (action: AlertButton) => void;
250 readonly dismissable?: boolean;
251 readonly request: Pick<
252 ConfirmDialogRequest,
253 "title" | "message" | "cancelText" | "confirmText" | "destructive"
254 >;
255 readonly inputInitialValue?: string;
256 readonly onInputChange?: (value: string) => void;
257 readonly onCancel: () => void;
258 readonly onConfirm: (inputValue?: string) => void;
259}