Skip to content

Commit 7510e5e

Browse files
fix(mobile): Android dialogs raised before or during activity replacement now show (#25229)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent a2589f2 commit 7510e5e

13 files changed

Lines changed: 244 additions & 169 deletions

‎apps/mobile/src/components/ui/AndroidAnchoredMenu.tsx‎

Lines changed: 41 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
22
import type { ReactNode } from "react";
3-
import { use, useCallback, useEffect, useRef, useState } from "react";
3+
import { use, useRef, useState } from "react";
44
import type { StyleProp, ViewInstance, ViewStyle } from "react-native";
5-
import { BackHandler, Pressable, ScrollView, View } from "react-native";
5+
import { Pressable, ScrollView, View } from "react-native";
66
import { useKeyboardState } from "react-native-keyboard-controller";
77
import Animated, { FadeIn } from "react-native-reanimated";
88

9+
import { useHardwareBack } from "../../lib/backHandler";
910
import { deriveMenuHorizontalPlacement } from "../../lib/menu-placement";
1011
import { WindowHingeContext } from "../../native/window-hinge-context";
1112
import { OverlayPortal } from "./OverlayPortal";
@@ -47,46 +48,43 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
4748
const [rootHeight, setRootHeight] = useState<number | null>(null);
4849
const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
4950
const windowHinge = use(WindowHingeContext);
50-
const anchorRef = useRef<ViewInstance>(null);
51+
// State, not a ref: `open` reaches render-prop children, and the compiler
52+
// bails out of the whole component when a ref might be read during render.
53+
const [anchorNode, setAnchorNode] = useState<ViewInstance | null>(null);
5154
const overlayRef = useRef<ViewInstance>(null);
5255

5356
const keyboardVisible = useKeyboardState((state) => state.isVisible);
5457
const keyboardHeight = useKeyboardState((state) => state.height);
55-
const close = useCallback(() => {
58+
const close = () => {
5659
setAnchor(null);
5760
setPath([]);
5861
setOverlay(null);
5962
setRootHeight(null);
60-
}, []);
63+
};
6164

62-
const open = useCallback(() => {
63-
anchorRef.current?.measureInWindow((x, y, width, height) => {
65+
const open = () => {
66+
anchorNode?.measureInWindow((x, y, width, height) => {
6467
setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });
6568
});
66-
}, [keyboardVisible]);
69+
};
6770

68-
const measureOverlay = useCallback(() => {
71+
const measureOverlay = () => {
6972
overlayRef.current?.measureInWindow((x, y, width, height) => {
7073
setOverlay({ x, y, width, height });
7174
setRootHeight(height);
7275
});
73-
}, []);
76+
};
7477

75-
const submenuDepth = path.length;
76-
useEffect(() => {
77-
if (anchor === null || !anchor.keyboardWasVisible) {
78-
return;
78+
// Only the in-window (keyboard) presentation needs this; the native popup
79+
// handles back itself.
80+
useHardwareBack(anchor?.keyboardWasVisible === true, () => {
81+
if (path.length > 0) {
82+
setPath((current) => current.slice(0, -1));
83+
} else {
84+
close();
7985
}
80-
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
81-
if (submenuDepth > 0) {
82-
setPath((current) => current.slice(0, -1));
83-
} else {
84-
close();
85-
}
86-
return true;
87-
});
88-
return () => subscription.remove();
89-
}, [anchor, close, submenuDepth]);
86+
return true;
87+
});
9088

9189
const parent = path[path.length - 1] ?? null;
9290
const levelActions = (parent?.subactions ?? props.actions).filter(
@@ -125,32 +123,33 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
125123
const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
126124
const placeable = local !== null && rootHeight !== null;
127125

128-
const { onPressAction } = props;
129-
const onPressItem = useCallback(
130-
(action: MenuAction) => {
131-
if ((action.subactions?.length ?? 0) > 0) {
132-
setPath((current) => [...current, action]);
133-
return;
134-
}
135-
close();
136-
if (action.id !== undefined) {
137-
onPressAction?.({
138-
nativeEvent: { event: action.id },
139-
} as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
140-
}
141-
},
142-
[close, onPressAction],
143-
);
126+
const onPressItem = (action: MenuAction) => {
127+
if ((action.subactions?.length ?? 0) > 0) {
128+
setPath((current) => [...current, action]);
129+
return;
130+
}
131+
close();
132+
if (action.id !== undefined) {
133+
props.onPressAction?.({
134+
nativeEvent: { event: action.id },
135+
} as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
136+
}
137+
};
144138

145139
return (
146140
<>
147141
{typeof props.children === "function" ? (
148-
<View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
142+
<View
143+
ref={setAnchorNode}
144+
collapsable={false}
145+
className={props.className}
146+
style={props.style}
147+
>
149148
{props.children(open)}
150149
</View>
151150
) : (
152151
<Pressable
153-
ref={anchorRef}
152+
ref={setAnchorNode}
154153
accessibilityRole="button"
155154
className={props.className}
156155
collapsable={false}

‎apps/mobile/src/components/ui/Dialog.android.test.tsx‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,16 @@ import { act, type ReactNode } from "react";
22
import { createRoot, type Root } from "react-dom/client";
33
import { afterEach, expect, it, vi } from "vite-plus/test";
44

5+
// Every click handler a button was rendered with, so a test can deliver a
6+
// native event that was dispatched against an older render.
7+
const renderedClicks = vi.hoisted(() => [] as Array<() => void>);
8+
59
vi.mock("@expo/ui/jetpack-compose", () => {
610
const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;
7-
const Button = (props: { readonly children?: ReactNode; readonly onClick?: () => void }) => (
8-
<button onClick={props.onClick}>{props.children}</button>
9-
);
11+
const Button = (props: { readonly children?: ReactNode; readonly onClick?: () => void }) => {
12+
if (props.onClick) renderedClicks.push(props.onClick);
13+
return <button onClick={props.onClick}>{props.children}</button>;
14+
};
1015
return {
1116
AlertDialog: Object.assign(Slot, {
1217
Title: Slot,
@@ -51,6 +56,7 @@ function mountHost() {
5156

5257
afterEach(() => {
5358
for (const root of roots.splice(0)) act(() => root.unmount());
59+
renderedClicks.length = 0;
5460
document.body.innerHTML = "";
5561
});
5662

@@ -65,3 +71,34 @@ it("keeps presenting dialogs after an older root's Host unmounts", () => {
6571

6672
expect(current.container.textContent).toContain("Saved");
6773
});
74+
75+
it("presents a dialog requested before any Host mounted", () => {
76+
Dialog.alert("Could not import shared content", undefined, [{ text: "Dismiss" }]);
77+
78+
const { container } = mountHost();
79+
80+
expect(container.textContent).toContain("Could not import shared content");
81+
});
82+
83+
it("keeps a dialog raised while the activity is replaced", () => {
84+
const previous = mountHost();
85+
act(() => Dialog.alert("Shared content imported", undefined, [{ text: "OK" }]));
86+
const current = mountHost();
87+
roots.splice(roots.indexOf(previous.root), 1);
88+
act(() => previous.root.unmount());
89+
90+
expect(current.container.textContent).toContain("Shared content imported");
91+
});
92+
93+
it("ignores a late action from a dialog that a newer one replaced", () => {
94+
const { container } = mountHost();
95+
const olderAction = vi.fn();
96+
act(() => Dialog.alert("Older", undefined, [{ text: "OK", onPress: olderAction }]));
97+
const olderClick = renderedClicks.at(-1)!;
98+
act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }]));
99+
100+
act(() => olderClick());
101+
102+
expect(olderAction).toHaveBeenCalledOnce();
103+
expect(container.textContent).toContain("Newer");
104+
});

‎apps/mobile/src/components/ui/Dialog.android.tsx‎

Lines changed: 54 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
1515
import { useScaledTextRole } from "../../features/settings/appearance/useScaledTextRole";
1616

17-
import { useCallback, useEffect, useRef, useState } from "react";
17+
import { useSyncExternalStore } from "react";
1818
import { themeColorWithContrast } from "../../lib/mobileTheme";
1919
import type { Alert, AlertButton } from "react-native";
2020
import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types";
@@ -33,63 +33,78 @@ type DialogRequest =
3333
| { readonly kind: "confirm"; readonly request: ConfirmDialogRequest }
3434
| { readonly kind: "text-input"; readonly request: TextInputDialogRequest };
3535

36-
let presentRequest: ((request: DialogRequest) => void) | null = null;
36+
type 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.
41+
let presented: PresentedDialog | null = null;
42+
let nextPresentationId = 0;
43+
const listeners = new Set<() => void>();
44+
45+
function setPresented(next: PresentedDialog | null) {
46+
presented = next;
47+
for (const listener of listeners) listener();
48+
}
49+
50+
function 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. */
55+
function dismiss(id: number) {
56+
if (presented?.id === id) setPresented(null);
57+
}
58+
59+
function subscribe(listener: () => void) {
60+
listeners.add(listener);
61+
return () => {
62+
listeners.delete(listener);
63+
};
64+
}
65+
66+
function getPresented() {
67+
return presented;
68+
}
3769

3870
export function alert(...[title, message, buttons, options]: Parameters<typeof Alert.alert>): void {
3971
const actions = buttons?.length ? buttons.slice(0, 3) : [{ text: "OK" }];
4072
const normalized = actions.map((action, index) =>
4173
index === actions.length - 1 ? { ...action, text: action.text || "OK" } : action,
4274
);
43-
presentRequest?.({
75+
submitRequest({
4476
kind: "alert",
4577
request: { title, message, buttons: normalized, options },
4678
});
4779
}
4880

4981
export function confirm(request: ConfirmDialogRequest): void {
50-
presentRequest?.({ kind: "confirm", request });
82+
submitRequest({ kind: "confirm", request });
5183
}
5284

5385
export function prompt(request: TextInputDialogRequest): void {
54-
presentRequest?.({ kind: "text-input", request });
86+
submitRequest({ kind: "text-input", request });
5587
}
5688

5789
export function Host() {
58-
const [presented, setPresented] = useState<(DialogRequest & { readonly id: number }) | null>(
59-
null,
60-
);
61-
const [inputValue, setInputValue] = useState("");
62-
const nextPresentationId = useRef(0);
63-
useEffect(() => {
64-
const present = (request: DialogRequest) => {
65-
setInputValue(request.kind === "text-input" ? request.request.initialValue : "");
66-
setPresented({ ...request, id: ++nextPresentationId.current });
67-
};
68-
presentRequest = present;
69-
return () => {
70-
// When Android replaces the activity, the new root's Host registers before the old root
71-
// unmounts. Clearing unconditionally would leave the live Host without dialogs.
72-
if (presentRequest === present) presentRequest = null;
73-
};
74-
}, []);
90+
const presented = useSyncExternalStore(subscribe, getPresented, getPresented);
7591

76-
const handleCancel = useCallback(() => {
77-
setPresented(null);
78-
if (presented?.kind === "alert") presented.request.options?.onDismiss?.();
79-
else presented?.request.onCancel?.();
80-
}, [presented]);
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+
};
8198

82-
const handleConfirm = useCallback(
83-
(nativeInputValue?: string) => {
84-
setPresented(null);
85-
if (presented?.kind === "confirm") {
86-
presented.request.onConfirm();
87-
} else if (presented?.kind === "text-input") {
88-
presented.request.onConfirm(nativeInputValue ?? inputValue);
89-
}
90-
},
91-
[inputValue, presented],
92-
);
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+
};
93108

94109
if (presented?.kind === "alert") {
95110
return (
@@ -103,7 +118,7 @@ export function Host() {
103118
alertActions={presented.request.buttons ?? [{ text: "OK" }]}
104119
dismissable={presented.request.options?.cancelable ?? false}
105120
onAlertAction={(action) => {
106-
setPresented(null);
121+
dismiss(presented.id);
107122
action.onPress?.();
108123
}}
109124
onCancel={handleCancel}
@@ -120,7 +135,6 @@ export function Host() {
120135
presented.kind === "text-input" ? presented.request.initialValue : undefined
121136
}
122137
inputPlaceholder={presented.kind === "text-input" ? presented.request.placeholder : undefined}
123-
onInputChange={setInputValue}
124138
onCancel={handleCancel}
125139
onConfirm={handleConfirm}
126140
/>
@@ -212,7 +226,6 @@ function DialogPresentation(props: DialogPresentationProps) {
212226
singleLine
213227
value={inputState}
214228
selection={inputSelection}
215-
onValueChange={props.onInputChange}
216229
textStyle={inputTypography}
217230
keyboardOptions={{ imeAction: "done" }}
218231
keyboardActions={{
@@ -267,7 +280,6 @@ interface DialogPresentationProps {
267280
>;
268281
readonly inputInitialValue?: string;
269282
readonly inputPlaceholder?: string;
270-
readonly onInputChange?: (value: string) => void;
271283
readonly onCancel: () => void;
272284
readonly onConfirm: (inputValue?: string) => void;
273285
}

0 commit comments

Comments
 (0)