Skip to content

Commit cfdfc2a

Browse files
fix(mobile): dispatch native toolbar actions to current handlers (pingdotgg#24271)
1 parent f694a19 commit cfdfc2a

2 files changed

Lines changed: 163 additions & 55 deletions

File tree

‎apps/mobile/src/native/NativeHeaderToolbar.test.tsx‎

Lines changed: 125 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { NativeStackHeaderItem } from "@react-navigation/native-stack";
2-
import { act, createContext, type ReactElement } from "react";
2+
import { act, createContext, startTransition, Suspense, type ReactElement } from "react";
33
import { createRoot, type Root } from "react-dom/client";
44
import { afterEach, expect, it, vi } from "vite-plus/test";
55

@@ -14,7 +14,6 @@ const harness = vi.hoisted(() => ({
1414
appliedOptions: {} as HeaderOptions,
1515
renderedItems: [] as NativeStackHeaderItem[],
1616
setOptionsCalls: 0,
17-
openedDocuments: [] as string[],
1817
}));
1918

2019
// Native headers retain the actions materialized when navigation applies options. Like React
@@ -51,26 +50,6 @@ vi.mock("@react-navigation/native", async () => {
5150
import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
5251

5352
let root: Root | null = null;
54-
type Placement = "left" | "right" | "bottom";
55-
56-
function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {
57-
return (
58-
<NativeHeaderToolbar placement={props.placement}>
59-
<NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">
60-
<NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>
61-
Open PDF
62-
</NativeHeaderToolbar.MenuAction>
63-
</NativeHeaderToolbar.Menu>
64-
</NativeHeaderToolbar>
65-
);
66-
}
67-
68-
function renderDocument(path: string, placement: Placement) {
69-
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
70-
harness.params = { path: path.split("/") };
71-
root ??= createRoot(document.createElement("div"));
72-
act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));
73-
}
7453

7554
// Like React Navigation's NavigationStateContext, whose default value throws when
7655
// read. React restores a context's default outside render, so layout effects see it.
@@ -109,33 +88,76 @@ function renderedCustomLabel() {
10988
return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];
11089
}
11190

112-
function openRenderedDocument() {
113-
const menu = harness.renderedItems[0];
114-
if (menu?.type !== "menu") throw new Error("Expected the native file menu");
115-
const action = menu.menu.items[0];
116-
if (action?.type !== "action") throw new Error("Expected the native Open PDF action");
117-
action.onPress?.();
118-
}
119-
12091
afterEach(() => {
12192
act(() => root?.unmount());
12293
root = null;
12394
harness.appliedOptions = {};
12495
harness.renderedItems = [];
12596
harness.setOptionsCalls = 0;
126-
harness.openedDocuments = [];
12797
vi.unstubAllGlobals();
12898
});
12999

130100
it.each(["left", "right", "bottom"] as const)(
131-
"updates the %s header action when switching between documents with the same name",
101+
"dispatches retained %s actions to the latest committed handlers without registering again",
132102
(placement) => {
133-
renderDocument("first/guide.pdf", placement);
134-
openRenderedDocument();
135-
renderDocument("second/guide.pdf", placement);
136-
openRenderedDocument();
137-
138-
expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);
103+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
104+
root = createRoot(document.createElement("div"));
105+
const onPress = vi.fn();
106+
const render = (path: string) =>
107+
act(() =>
108+
root!.render(
109+
<NativeHeaderToolbar placement={placement}>
110+
<NativeHeaderToolbar.Button label="Open" onPress={() => onPress("button", path)} />
111+
<NativeHeaderToolbar.Menu title="File">
112+
<NativeHeaderToolbar.MenuAction onPress={() => onPress("menu", path)}>
113+
Open
114+
</NativeHeaderToolbar.MenuAction>
115+
<NativeHeaderToolbar.Menu title="More">
116+
<NativeHeaderToolbar.MenuAction onPress={() => onPress("nested", path)}>
117+
Open
118+
</NativeHeaderToolbar.MenuAction>
119+
</NativeHeaderToolbar.Menu>
120+
</NativeHeaderToolbar.Menu>
121+
</NativeHeaderToolbar>,
122+
),
123+
);
124+
125+
render("first/guide.pdf");
126+
const [button, menu] = harness.renderedItems;
127+
if (button?.type !== "button" || menu?.type !== "menu") {
128+
throw new Error("Expected the native button and menu");
129+
}
130+
const [action, submenu] = menu.menu.items;
131+
if (action?.type !== "action" || submenu?.type !== "submenu") {
132+
throw new Error("Expected the direct action and submenu");
133+
}
134+
const nested = submenu.items[0];
135+
if (nested?.type !== "action") throw new Error("Expected the nested action");
136+
const press = () => {
137+
button.onPress?.();
138+
action.onPress?.();
139+
nested.onPress?.();
140+
};
141+
press();
142+
expect(onPress.mock.calls).toEqual([
143+
["button", "first/guide.pdf"],
144+
["menu", "first/guide.pdf"],
145+
["nested", "first/guide.pdf"],
146+
]);
147+
onPress.mockClear();
148+
const registrations = harness.setOptionsCalls;
149+
expect(registrations).toBeGreaterThan(0);
150+
151+
render("second/guide.pdf");
152+
153+
expect(harness.setOptionsCalls).toBe(registrations);
154+
expect(harness.renderedItems).toEqual([button, menu]);
155+
press();
156+
expect(onPress.mock.calls).toEqual([
157+
["button", "second/guide.pdf"],
158+
["menu", "second/guide.pdf"],
159+
["nested", "second/guide.pdf"],
160+
]);
139161
},
140162
);
141163

@@ -150,3 +172,68 @@ it("applies a custom header element rendered inside a navigation container", ()
150172
renderConnecting("Reconnecting");
151173
expect(renderedCustomLabel()).toBe("Reconnecting");
152174
});
175+
176+
it("keeps committed handlers while a replacement render suspends", () => {
177+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
178+
root = createRoot(document.createElement("div"));
179+
const onPress = vi.fn();
180+
const pending = new Promise<never>(() => {});
181+
function Suspend(): never {
182+
throw pending;
183+
}
184+
const toolbar = (value: string, suspend = false) => (
185+
<Suspense fallback={null}>
186+
<NativeHeaderToolbar>
187+
<NativeHeaderToolbar.Button label="Open" onPress={() => onPress(value)} />
188+
</NativeHeaderToolbar>
189+
{suspend && <Suspend />}
190+
</Suspense>
191+
);
192+
act(() => root!.render(toolbar("committed")));
193+
const button = harness.renderedItems[0];
194+
if (button?.type !== "button") throw new Error("Expected the native button");
195+
196+
act(() => startTransition(() => root!.render(toolbar("pending", true))));
197+
button.onPress?.();
198+
expect(onPress.mock.calls).toEqual([["committed"]]);
199+
200+
act(() => root!.render(toolbar("replacement")));
201+
button.onPress?.();
202+
expect(onPress.mock.calls).toEqual([["committed"], ["replacement"]]);
203+
});
204+
205+
it("isolates toolbar handlers and ignores retained actions after their toolbar unmounts", () => {
206+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
207+
root = createRoot(document.createElement("div"));
208+
const onPress = vi.fn();
209+
const toolbar = (id: string, value: string) => (
210+
<NativeHeaderToolbar key={id}>
211+
<NativeHeaderToolbar.Button label={id} onPress={() => onPress(id, value)} />
212+
</NativeHeaderToolbar>
213+
);
214+
act(() => root!.render([toolbar("first", "initial")]));
215+
const first = harness.renderedItems[0];
216+
if (first?.type !== "button") throw new Error("Expected the first native button");
217+
act(() => root!.render([toolbar("first", "initial"), toolbar("second", "initial")]));
218+
const second = harness.renderedItems[0];
219+
if (second?.type !== "button") throw new Error("Expected the second native button");
220+
221+
act(() => root!.render([toolbar("first", "updated"), toolbar("second", "updated")]));
222+
first.onPress?.();
223+
second.onPress?.();
224+
expect(onPress.mock.calls).toEqual([
225+
["first", "updated"],
226+
["second", "updated"],
227+
]);
228+
229+
onPress.mockClear();
230+
act(() => root!.render([toolbar("second", "remaining")]));
231+
first.onPress?.();
232+
second.onPress?.();
233+
expect(onPress.mock.calls).toEqual([["second", "remaining"]]);
234+
235+
onPress.mockClear();
236+
act(() => root!.render(null));
237+
second.onPress?.();
238+
expect(onPress).not.toHaveBeenCalled();
239+
});

‎apps/mobile/src/native/NativeHeaderToolbar.tsx‎

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isValidElement,
1010
useLayoutEffect,
1111
useMemo,
12+
useRef,
1213
use,
1314
type ReactElement,
1415
type ReactNode,
@@ -60,6 +61,8 @@ function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
6061
return undefined;
6162
}
6263

64+
type RegisterHandler = (handler: unknown) => () => void;
65+
6366
type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
6467

6568
function elementTypeName(element: ReactElement): string | undefined {
@@ -72,6 +75,7 @@ function elementTypeName(element: ReactElement): string | undefined {
7275

7376
function convertMenuAction(
7477
element: ReactElement<ToolbarElementProps>,
78+
register: RegisterHandler,
7579
): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
7680
const typeName = elementTypeName(element);
7781
if (typeName === "NativeHeaderToolbarMenuAction") {
@@ -82,10 +86,7 @@ function convertMenuAction(
8286
description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
8387
disabled: Boolean(element.props.disabled),
8488
icon: iconFromProp(element.props.icon),
85-
onPress:
86-
typeof element.props.onPress === "function"
87-
? (element.props.onPress as () => void)
88-
: () => undefined,
89+
onPress: register(element.props.onPress),
8990
state: element.props.isOn === true ? "on" : undefined,
9091
destructive: Boolean(element.props.destructive),
9192
discoverabilityLabel:
@@ -104,30 +105,36 @@ function convertMenuAction(
104105
: labelFromChildren(element.props.children),
105106
icon: iconFromProp(element.props.icon),
106107
inline: Boolean(element.props.inline),
107-
items: collectMenuItems(element.props.children),
108+
items: collectMenuItems(element.props.children, register),
108109
};
109110
}
110111

111112
return null;
112113
}
113114

114-
function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
115+
function collectMenuItems(
116+
children: ReactNode,
117+
register: RegisterHandler,
118+
): NativeStackHeaderItemMenu["menu"]["items"] {
115119
const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
116120
Children.forEach(children, (child) => {
117121
if (!isValidElement<ToolbarElementProps>(child)) {
118122
return;
119123
}
120-
const item = convertMenuAction(child);
124+
const item = convertMenuAction(child, register);
121125
if (item) {
122126
items.push(item);
123127
return;
124128
}
125-
items.push(...collectMenuItems(child.props.children));
129+
items.push(...collectMenuItems(child.props.children, register));
126130
});
127131
return items;
128132
}
129133

130-
function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
134+
function convertToolbarChild(
135+
child: ReactNode,
136+
register: RegisterHandler,
137+
): NativeToolbarItem | null {
131138
if (!isValidElement<ToolbarElementProps>(child)) {
132139
return null;
133140
}
@@ -154,10 +161,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
154161
axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
155162
disabled: Boolean(child.props.disabled),
156163
icon: iconFromProp(child.props.icon),
157-
onPress:
158-
typeof child.props.onPress === "function"
159-
? (child.props.onPress as () => void)
160-
: () => undefined,
164+
onPress: register(child.props.onPress),
161165
sharesBackground: !child.props.separateBackground,
162166
tintColor: child.props.tintColor as ColorValue | undefined,
163167
variant:
@@ -182,7 +186,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
182186
icon: iconFromProp(child.props.icon),
183187
menu: {
184188
title: typeof child.props.title === "string" ? child.props.title : undefined,
185-
items: collectMenuItems(child.props.children),
189+
items: collectMenuItems(child.props.children, register),
186190
},
187191
sharesBackground: !child.props.separateBackground,
188192
tintColor: child.props.tintColor as ColorValue | undefined,
@@ -205,10 +209,10 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
205209
return null;
206210
}
207211

208-
function collectToolbarItems(children: ReactNode): NativeToolbarItem[] {
212+
function collectToolbarItems(children: ReactNode, register: RegisterHandler): NativeToolbarItem[] {
209213
const items: NativeToolbarItem[] = [];
210214
Children.forEach(children, (child) => {
211-
const item = convertToolbarChild(child);
215+
const item = convertToolbarChild(child, register);
212216
if (item) {
213217
if (item.type === "spacing") {
214218
// Native defaults missing spacing-item indices to zero, moving spacers before earlier siblings.
@@ -228,7 +232,24 @@ function NativeHeaderToolbarRoot(props: {
228232
const route = useRoute();
229233
const tabActivity = use(NativeWorkspaceTabActivityContext);
230234
const isTabActive = tabActivity?.isActive;
231-
const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
235+
const committedHandlers = useRef<(() => void)[]>([]);
236+
const { items, handlers } = useMemo(() => {
237+
const handlers: (() => void)[] = [];
238+
const register: RegisterHandler = (handler) => {
239+
const index = handlers.length;
240+
handlers.push(typeof handler === "function" ? (handler as () => void) : () => undefined);
241+
return () => committedHandlers.current[index]?.();
242+
};
243+
return { items: collectToolbarItems(props.children, register), handlers };
244+
}, [props.children, committedHandlers]);
245+
// Native retains actions when unchanged presentation skips re-registration.
246+
// Publish only committed handlers; abandoned renders must not replace them.
247+
useLayoutEffect(() => {
248+
committedHandlers.current = handlers;
249+
return () => {
250+
committedHandlers.current = [];
251+
};
252+
}, [handlers, committedHandlers]);
232253
// UIKit's search placement item belongs to the toolbar, never a header group.
233254
const headerItems = useMemo(
234255
() => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),

0 commit comments

Comments
 (0)