TypeScript
fix(mobile): dispatch native toolbar actions to current handlers (#24271)
Julius Marmingecfdfc2ab7c7a
diff --git a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx b/apps/mobile/src/native/NativeHeaderToolbar.test.tsxindex 2b3275de637..b531e8f1a7a 100644--- a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx+++ b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx@@ -1,5 +1,5 @@import type { NativeStackHeaderItem } from "@react-navigation/native-stack";-import { act, createContext, type ReactElement } from "react";+import { act, createContext, startTransition, Suspense, type ReactElement } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, expect, it, vi } from "vite-plus/test";@@ -14,7 +14,6 @@ const harness = vi.hoisted(() => ({appliedOptions: {} as HeaderOptions,renderedItems: [] as NativeStackHeaderItem[],setOptionsCalls: 0,- openedDocuments: [] as string[],}));// Native headers retain the actions materialized when navigation applies options. Like React@@ -51,26 +50,6 @@ vi.mock("@react-navigation/native", async () => {import { NativeHeaderToolbar } from "./NativeHeaderToolbar";let root: Root | null = null;-type Placement = "left" | "right" | "bottom";--function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {- return (- <NativeHeaderToolbar placement={props.placement}>- <NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">- <NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>- Open PDF- </NativeHeaderToolbar.MenuAction>- </NativeHeaderToolbar.Menu>- </NativeHeaderToolbar>- );-}--function renderDocument(path: string, placement: Placement) {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- harness.params = { path: path.split("/") };- root ??= createRoot(document.createElement("div"));- act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));-}// Like React Navigation's NavigationStateContext, whose default value throws when// read. React restores a context's default outside render, so layout effects see it.@@ -109,33 +88,76 @@ function renderedCustomLabel() {return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];}-function openRenderedDocument() {- const menu = harness.renderedItems[0];- if (menu?.type !== "menu") throw new Error("Expected the native file menu");- const action = menu.menu.items[0];- if (action?.type !== "action") throw new Error("Expected the native Open PDF action");- action.onPress?.();-}-afterEach(() => {act(() => root?.unmount());root = null;harness.appliedOptions = {};harness.renderedItems = [];harness.setOptionsCalls = 0;- harness.openedDocuments = [];vi.unstubAllGlobals();});it.each(["left", "right", "bottom"] as const)(- "updates the %s header action when switching between documents with the same name",+ "dispatches retained %s actions to the latest committed handlers without registering again",(placement) => {- renderDocument("first/guide.pdf", placement);- openRenderedDocument();- renderDocument("second/guide.pdf", placement);- openRenderedDocument();-- expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));+ const onPress = vi.fn();+ const render = (path: string) =>+ act(() =>+ root!.render(+ <NativeHeaderToolbar placement={placement}>+ <NativeHeaderToolbar.Button label="Open" onPress={() => onPress("button", path)} />+ <NativeHeaderToolbar.Menu title="File">+ <NativeHeaderToolbar.MenuAction onPress={() => onPress("menu", path)}>+ Open+ </NativeHeaderToolbar.MenuAction>+ <NativeHeaderToolbar.Menu title="More">+ <NativeHeaderToolbar.MenuAction onPress={() => onPress("nested", path)}>+ Open+ </NativeHeaderToolbar.MenuAction>+ </NativeHeaderToolbar.Menu>+ </NativeHeaderToolbar.Menu>+ </NativeHeaderToolbar>,+ ),+ );++ render("first/guide.pdf");+ const [button, menu] = harness.renderedItems;+ if (button?.type !== "button" || menu?.type !== "menu") {+ throw new Error("Expected the native button and menu");+ }+ const [action, submenu] = menu.menu.items;+ if (action?.type !== "action" || submenu?.type !== "submenu") {+ throw new Error("Expected the direct action and submenu");+ }+ const nested = submenu.items[0];+ if (nested?.type !== "action") throw new Error("Expected the nested action");+ const press = () => {+ button.onPress?.();+ action.onPress?.();+ nested.onPress?.();+ };+ press();+ expect(onPress.mock.calls).toEqual([+ ["button", "first/guide.pdf"],+ ["menu", "first/guide.pdf"],+ ["nested", "first/guide.pdf"],+ ]);+ onPress.mockClear();+ const registrations = harness.setOptionsCalls;+ expect(registrations).toBeGreaterThan(0);++ render("second/guide.pdf");++ expect(harness.setOptionsCalls).toBe(registrations);+ expect(harness.renderedItems).toEqual([button, menu]);+ press();+ expect(onPress.mock.calls).toEqual([+ ["button", "second/guide.pdf"],+ ["menu", "second/guide.pdf"],+ ["nested", "second/guide.pdf"],+ ]);},);@@ -150,3 +172,68 @@ it("applies a custom header element rendered inside a navigation container", ()renderConnecting("Reconnecting");expect(renderedCustomLabel()).toBe("Reconnecting");});++it("keeps committed handlers while a replacement render suspends", () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));+ const onPress = vi.fn();+ const pending = new Promise<never>(() => {});+ function Suspend(): never {+ throw pending;+ }+ const toolbar = (value: string, suspend = false) => (+ <Suspense fallback={null}>+ <NativeHeaderToolbar>+ <NativeHeaderToolbar.Button label="Open" onPress={() => onPress(value)} />+ </NativeHeaderToolbar>+ {suspend && <Suspend />}+ </Suspense>+ );+ act(() => root!.render(toolbar("committed")));+ const button = harness.renderedItems[0];+ if (button?.type !== "button") throw new Error("Expected the native button");++ act(() => startTransition(() => root!.render(toolbar("pending", true))));+ button.onPress?.();+ expect(onPress.mock.calls).toEqual([["committed"]]);++ act(() => root!.render(toolbar("replacement")));+ button.onPress?.();+ expect(onPress.mock.calls).toEqual([["committed"], ["replacement"]]);+});++it("isolates toolbar handlers and ignores retained actions after their toolbar unmounts", () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));+ const onPress = vi.fn();+ const toolbar = (id: string, value: string) => (+ <NativeHeaderToolbar key={id}>+ <NativeHeaderToolbar.Button label={id} onPress={() => onPress(id, value)} />+ </NativeHeaderToolbar>+ );+ act(() => root!.render([toolbar("first", "initial")]));+ const first = harness.renderedItems[0];+ if (first?.type !== "button") throw new Error("Expected the first native button");+ act(() => root!.render([toolbar("first", "initial"), toolbar("second", "initial")]));+ const second = harness.renderedItems[0];+ if (second?.type !== "button") throw new Error("Expected the second native button");++ act(() => root!.render([toolbar("first", "updated"), toolbar("second", "updated")]));+ first.onPress?.();+ second.onPress?.();+ expect(onPress.mock.calls).toEqual([+ ["first", "updated"],+ ["second", "updated"],+ ]);++ onPress.mockClear();+ act(() => root!.render([toolbar("second", "remaining")]));+ first.onPress?.();+ second.onPress?.();+ expect(onPress.mock.calls).toEqual([["second", "remaining"]]);++ onPress.mockClear();+ act(() => root!.render(null));+ second.onPress?.();+ expect(onPress).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/native/NativeHeaderToolbar.tsx b/apps/mobile/src/native/NativeHeaderToolbar.tsxindex 47a2ecb0008..88b72e2335f 100644--- a/apps/mobile/src/native/NativeHeaderToolbar.tsx+++ b/apps/mobile/src/native/NativeHeaderToolbar.tsx@@ -9,6 +9,7 @@ import {isValidElement,useLayoutEffect,useMemo,+ useRef,use,type ReactElement,type ReactNode,@@ -60,6 +61,8 @@ function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {return undefined;}+type RegisterHandler = (handler: unknown) => () => void;+type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };function elementTypeName(element: ReactElement): string | undefined {@@ -72,6 +75,7 @@ function elementTypeName(element: ReactElement): string | undefined {function convertMenuAction(element: ReactElement<ToolbarElementProps>,+ register: RegisterHandler,): NativeStackHeaderItemMenu["menu"]["items"][number] | null {const typeName = elementTypeName(element);if (typeName === "NativeHeaderToolbarMenuAction") {@@ -82,10 +86,7 @@ function convertMenuAction(description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,disabled: Boolean(element.props.disabled),icon: iconFromProp(element.props.icon),- onPress:- typeof element.props.onPress === "function"- ? (element.props.onPress as () => void)- : () => undefined,+ onPress: register(element.props.onPress),state: element.props.isOn === true ? "on" : undefined,destructive: Boolean(element.props.destructive),discoverabilityLabel:@@ -104,30 +105,36 @@ function convertMenuAction(: labelFromChildren(element.props.children),icon: iconFromProp(element.props.icon),inline: Boolean(element.props.inline),- items: collectMenuItems(element.props.children),+ items: collectMenuItems(element.props.children, register),};}return null;}-function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {+function collectMenuItems(+ children: ReactNode,+ register: RegisterHandler,+): NativeStackHeaderItemMenu["menu"]["items"] {const items: NativeStackHeaderItemMenu["menu"]["items"] = [];Children.forEach(children, (child) => {if (!isValidElement<ToolbarElementProps>(child)) {return;}- const item = convertMenuAction(child);+ const item = convertMenuAction(child, register);if (item) {items.push(item);return;}- items.push(...collectMenuItems(child.props.children));+ items.push(...collectMenuItems(child.props.children, register));});return items;}-function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {+function convertToolbarChild(+ child: ReactNode,+ register: RegisterHandler,+): NativeToolbarItem | null {if (!isValidElement<ToolbarElementProps>(child)) {return null;}@@ -154,10 +161,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,disabled: Boolean(child.props.disabled),icon: iconFromProp(child.props.icon),- onPress:- typeof child.props.onPress === "function"- ? (child.props.onPress as () => void)- : () => undefined,+ onPress: register(child.props.onPress),sharesBackground: !child.props.separateBackground,tintColor: child.props.tintColor as ColorValue | undefined,variant:@@ -182,7 +186,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {icon: iconFromProp(child.props.icon),menu: {title: typeof child.props.title === "string" ? child.props.title : undefined,- items: collectMenuItems(child.props.children),+ items: collectMenuItems(child.props.children, register),},sharesBackground: !child.props.separateBackground,tintColor: child.props.tintColor as ColorValue | undefined,@@ -205,10 +209,10 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {return null;}-function collectToolbarItems(children: ReactNode): NativeToolbarItem[] {+function collectToolbarItems(children: ReactNode, register: RegisterHandler): NativeToolbarItem[] {const items: NativeToolbarItem[] = [];Children.forEach(children, (child) => {- const item = convertToolbarChild(child);+ const item = convertToolbarChild(child, register);if (item) {if (item.type === "spacing") {// Native defaults missing spacing-item indices to zero, moving spacers before earlier siblings.@@ -228,7 +232,24 @@ function NativeHeaderToolbarRoot(props: {const route = useRoute();const tabActivity = use(NativeWorkspaceTabActivityContext);const isTabActive = tabActivity?.isActive;- const items = useMemo(() => collectToolbarItems(props.children), [props.children]);+ const committedHandlers = useRef<(() => void)[]>([]);+ const { items, handlers } = useMemo(() => {+ const handlers: (() => void)[] = [];+ const register: RegisterHandler = (handler) => {+ const index = handlers.length;+ handlers.push(typeof handler === "function" ? (handler as () => void) : () => undefined);+ return () => committedHandlers.current[index]?.();+ };+ return { items: collectToolbarItems(props.children, register), handlers };+ }, [props.children, committedHandlers]);+ // Native retains actions when unchanged presentation skips re-registration.+ // Publish only committed handlers; abandoned renders must not replace them.+ useLayoutEffect(() => {+ committedHandlers.current = handlers;+ return () => {+ committedHandlers.current = [];+ };+ }, [handlers, committedHandlers]);// UIKit's search placement item belongs to the toolbar, never a header group.const headerItems = useMemo(() => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),