@devries-cameron20 / t3code Mirror · read-only / commits / cfdfc2ab7c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 18:15 UTC

fix(mobile): dispatch native toolbar actions to current handlers (#24271)

Julius Marminge committed Oct 25, 2026 at 01:00 UTC cfdfc2ab7c7afbc90ab36d9443d7806675e2b4f0
2 files changed +163 -55
apps/mobile/src/native/NativeHeaderToolbar.test.tsx
+125 -38
@@ -1,5 +1,5 @@
1 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";
3 import { createRoot, type Root } from "react-dom/client";
4 import { afterEach, expect, it, vi } from "vite-plus/test";
5
@@ -14,7 +14,6 @@ const harness = vi.hoisted(() => ({
14 appliedOptions: {} as HeaderOptions,
15 renderedItems: [] as NativeStackHeaderItem[],
16 setOptionsCalls: 0,
17 - openedDocuments: [] as string[],
17 }));
18
19 // Native headers retain the actions materialized when navigation applies options. Like React
@@ -51,26 +50,6 @@ vi.mock("@react-navigation/native", async () => {
50 import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
51
52 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 -}
53
54 // Like React Navigation's NavigationStateContext, whose default value throws when
55 // read. React restores a context's default outside render, so layout effects see it.
@@ -109,33 +88,76 @@ function renderedCustomLabel() {
88 return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];
89 }
90
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 -
91 afterEach(() => {
92 act(() => root?.unmount());
93 root = null;
94 harness.appliedOptions = {};
95 harness.renderedItems = [];
96 harness.setOptionsCalls = 0;
126 - harness.openedDocuments = [];
97 vi.unstubAllGlobals();
98 });
99
100 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",
102 (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 + ]);
161 },
162 );
163
@@ -150,3 +172,68 @@ it("applies a custom header element rendered inside a navigation container", ()
172 renderConnecting("Reconnecting");
173 expect(renderedCustomLabel()).toBe("Reconnecting");
174 });
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
+38 -17
@@ -9,6 +9,7 @@ import {
9 isValidElement,
10 useLayoutEffect,
11 useMemo,
12 + useRef,
13 use,
14 type ReactElement,
15 type ReactNode,
@@ -60,6 +61,8 @@ function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
61 return undefined;
62 }
63
64 +type RegisterHandler = (handler: unknown) => () => void;
65 +
66 type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
67
68 function elementTypeName(element: ReactElement): string | undefined {
@@ -72,6 +75,7 @@ function elementTypeName(element: ReactElement): string | undefined {
75
76 function convertMenuAction(
77 element: ReactElement<ToolbarElementProps>,
78 + register: RegisterHandler,
79 ): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
80 const typeName = elementTypeName(element);
81 if (typeName === "NativeHeaderToolbarMenuAction") {
@@ -82,10 +86,7 @@ function convertMenuAction(
86 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
87 disabled: Boolean(element.props.disabled),
88 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),
90 state: element.props.isOn === true ? "on" : undefined,
91 destructive: Boolean(element.props.destructive),
92 discoverabilityLabel:
@@ -104,30 +105,36 @@ function convertMenuAction(
105 : labelFromChildren(element.props.children),
106 icon: iconFromProp(element.props.icon),
107 inline: Boolean(element.props.inline),
107 - items: collectMenuItems(element.props.children),
108 + items: collectMenuItems(element.props.children, register),
109 };
110 }
111
112 return null;
113 }
114
114 -function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
115 +function collectMenuItems(
116 + children: ReactNode,
117 + register: RegisterHandler,
118 +): NativeStackHeaderItemMenu["menu"]["items"] {
119 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
120 Children.forEach(children, (child) => {
121 if (!isValidElement<ToolbarElementProps>(child)) {
122 return;
123 }
120 - const item = convertMenuAction(child);
124 + const item = convertMenuAction(child, register);
125 if (item) {
126 items.push(item);
127 return;
128 }
125 - items.push(...collectMenuItems(child.props.children));
129 + items.push(...collectMenuItems(child.props.children, register));
130 });
131 return items;
132 }
133
130 -function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
134 +function convertToolbarChild(
135 + child: ReactNode,
136 + register: RegisterHandler,
137 +): NativeToolbarItem | null {
138 if (!isValidElement<ToolbarElementProps>(child)) {
139 return null;
140 }
@@ -154,10 +161,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
161 axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
162 disabled: Boolean(child.props.disabled),
163 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),
165 sharesBackground: !child.props.separateBackground,
166 tintColor: child.props.tintColor as ColorValue | undefined,
167 variant:
@@ -182,7 +186,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
186 icon: iconFromProp(child.props.icon),
187 menu: {
188 title: typeof child.props.title === "string" ? child.props.title : undefined,
185 - items: collectMenuItems(child.props.children),
189 + items: collectMenuItems(child.props.children, register),
190 },
191 sharesBackground: !child.props.separateBackground,
192 tintColor: child.props.tintColor as ColorValue | undefined,
@@ -205,10 +209,10 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
209 return null;
210 }
211
208 -function collectToolbarItems(children: ReactNode): NativeToolbarItem[] {
212 +function collectToolbarItems(children: ReactNode, register: RegisterHandler): NativeToolbarItem[] {
213 const items: NativeToolbarItem[] = [];
214 Children.forEach(children, (child) => {
211 - const item = convertToolbarChild(child);
215 + const item = convertToolbarChild(child, register);
216 if (item) {
217 if (item.type === "spacing") {
218 // Native defaults missing spacing-item indices to zero, moving spacers before earlier siblings.
@@ -228,7 +232,24 @@ function NativeHeaderToolbarRoot(props: {
232 const route = useRoute();
233 const tabActivity = use(NativeWorkspaceTabActivityContext);
234 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]);
253 // UIKit's search placement item belongs to the toolbar, never a header group.
254 const headerItems = useMemo(
255 () => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),