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