TypeScript
fix(mobile): Android dialogs raised before or during activity replacement now show (#25229)
Julius Marminge7510e5e43c6c
diff --git a/apps/mobile/src/components/ui/AndroidAnchoredMenu.tsx b/apps/mobile/src/components/ui/AndroidAnchoredMenu.tsxindex d4a7ab54041..a1f6a02cc32 100644--- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.tsx+++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.tsx@@ -1,11 +1,12 @@import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";import type { ReactNode } from "react";-import { use, useCallback, useEffect, useRef, useState } from "react";+import { use, useRef, useState } from "react";import type { StyleProp, ViewInstance, ViewStyle } from "react-native";-import { BackHandler, Pressable, ScrollView, View } from "react-native";+import { Pressable, ScrollView, View } from "react-native";import { useKeyboardState } from "react-native-keyboard-controller";import Animated, { FadeIn } from "react-native-reanimated";+import { useHardwareBack } from "../../lib/backHandler";import { deriveMenuHorizontalPlacement } from "../../lib/menu-placement";import { WindowHingeContext } from "../../native/window-hinge-context";import { OverlayPortal } from "./OverlayPortal";@@ -47,46 +48,43 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {const [rootHeight, setRootHeight] = useState<number | null>(null);const [overlay, setOverlay] = useState<OverlayFrame | null>(null);const windowHinge = use(WindowHingeContext);- const anchorRef = useRef<ViewInstance>(null);+ // State, not a ref: `open` reaches render-prop children, and the compiler+ // bails out of the whole component when a ref might be read during render.+ const [anchorNode, setAnchorNode] = useState<ViewInstance | null>(null);const overlayRef = useRef<ViewInstance>(null);const keyboardVisible = useKeyboardState((state) => state.isVisible);const keyboardHeight = useKeyboardState((state) => state.height);- const close = useCallback(() => {+ const close = () => {setAnchor(null);setPath([]);setOverlay(null);setRootHeight(null);- }, []);+ };- const open = useCallback(() => {- anchorRef.current?.measureInWindow((x, y, width, height) => {+ const open = () => {+ anchorNode?.measureInWindow((x, y, width, height) => {setAnchor({ x, y, width, height, keyboardWasVisible: keyboardVisible });});- }, [keyboardVisible]);+ };- const measureOverlay = useCallback(() => {+ const measureOverlay = () => {overlayRef.current?.measureInWindow((x, y, width, height) => {setOverlay({ x, y, width, height });setRootHeight(height);});- }, []);+ };- const submenuDepth = path.length;- useEffect(() => {- if (anchor === null || !anchor.keyboardWasVisible) {- return;+ // Only the in-window (keyboard) presentation needs this; the native popup+ // handles back itself.+ useHardwareBack(anchor?.keyboardWasVisible === true, () => {+ if (path.length > 0) {+ setPath((current) => current.slice(0, -1));+ } else {+ close();}- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {- if (submenuDepth > 0) {- setPath((current) => current.slice(0, -1));- } else {- close();- }- return true;- });- return () => subscription.remove();- }, [anchor, close, submenuDepth]);+ return true;+ });const parent = path[path.length - 1] ?? null;const levelActions = (parent?.subactions ?? props.actions).filter(@@ -125,32 +123,33 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);const placeable = local !== null && rootHeight !== null;- const { onPressAction } = props;- const onPressItem = useCallback(- (action: MenuAction) => {- if ((action.subactions?.length ?? 0) > 0) {- setPath((current) => [...current, action]);- return;- }- close();- if (action.id !== undefined) {- onPressAction?.({- nativeEvent: { event: action.id },- } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);- }- },- [close, onPressAction],- );+ const onPressItem = (action: MenuAction) => {+ if ((action.subactions?.length ?? 0) > 0) {+ setPath((current) => [...current, action]);+ return;+ }+ close();+ if (action.id !== undefined) {+ props.onPressAction?.({+ nativeEvent: { event: action.id },+ } as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);+ }+ };return (<>{typeof props.children === "function" ? (- <View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>+ <View+ ref={setAnchorNode}+ collapsable={false}+ className={props.className}+ style={props.style}+ >{props.children(open)}</View>) : (<Pressable- ref={anchorRef}+ ref={setAnchorNode}accessibilityRole="button"className={props.className}collapsable={false}diff --git a/apps/mobile/src/components/ui/Dialog.android.test.tsx b/apps/mobile/src/components/ui/Dialog.android.test.tsxindex 1d67caa7d86..d283cf004c2 100644--- a/apps/mobile/src/components/ui/Dialog.android.test.tsx+++ b/apps/mobile/src/components/ui/Dialog.android.test.tsx@@ -2,11 +2,16 @@ import { act, type ReactNode } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, expect, it, vi } from "vite-plus/test";+// Every click handler a button was rendered with, so a test can deliver a+// native event that was dispatched against an older render.+const renderedClicks = vi.hoisted(() => [] as Array<() => void>);+vi.mock("@expo/ui/jetpack-compose", () => {const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;- const Button = (props: { readonly children?: ReactNode; readonly onClick?: () => void }) => (- <button onClick={props.onClick}>{props.children}</button>- );+ const Button = (props: { readonly children?: ReactNode; readonly onClick?: () => void }) => {+ if (props.onClick) renderedClicks.push(props.onClick);+ return <button onClick={props.onClick}>{props.children}</button>;+ };return {AlertDialog: Object.assign(Slot, {Title: Slot,@@ -51,6 +56,7 @@ function mountHost() {afterEach(() => {for (const root of roots.splice(0)) act(() => root.unmount());+ renderedClicks.length = 0;document.body.innerHTML = "";});@@ -65,3 +71,34 @@ it("keeps presenting dialogs after an older root's Host unmounts", () => {expect(current.container.textContent).toContain("Saved");});++it("presents a dialog requested before any Host mounted", () => {+ Dialog.alert("Could not import shared content", undefined, [{ text: "Dismiss" }]);++ const { container } = mountHost();++ expect(container.textContent).toContain("Could not import shared content");+});++it("keeps a dialog raised while the activity is replaced", () => {+ const previous = mountHost();+ act(() => Dialog.alert("Shared content imported", undefined, [{ text: "OK" }]));+ const current = mountHost();+ roots.splice(roots.indexOf(previous.root), 1);+ act(() => previous.root.unmount());++ expect(current.container.textContent).toContain("Shared content imported");+});++it("ignores a late action from a dialog that a newer one replaced", () => {+ const { container } = mountHost();+ const olderAction = vi.fn();+ act(() => Dialog.alert("Older", undefined, [{ text: "OK", onPress: olderAction }]));+ const olderClick = renderedClicks.at(-1)!;+ act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }]));++ act(() => olderClick());++ expect(olderAction).toHaveBeenCalledOnce();+ expect(container.textContent).toContain("Newer");+});diff --git a/apps/mobile/src/components/ui/Dialog.android.tsx b/apps/mobile/src/components/ui/Dialog.android.tsxindex bc93254c0f3..af05275b7f2 100644--- a/apps/mobile/src/components/ui/Dialog.android.tsx+++ b/apps/mobile/src/components/ui/Dialog.android.tsx@@ -14,7 +14,7 @@ import {import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";import { useScaledTextRole } from "../../features/settings/appearance/useScaledTextRole";-import { useCallback, useEffect, useRef, useState } from "react";+import { useSyncExternalStore } from "react";import { themeColorWithContrast } from "../../lib/mobileTheme";import type { Alert, AlertButton } from "react-native";import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types";@@ -33,63 +33,78 @@ type DialogRequest =| { readonly kind: "confirm"; readonly request: ConfirmDialogRequest }| { readonly kind: "text-input"; readonly request: TextInputDialogRequest };-let presentRequest: ((request: DialogRequest) => void) | null = null;+type PresentedDialog = DialogRequest & { readonly id: number };++// App services raise dialogs before the root mounts, so the request lives in+// the module and the Host renders whatever is current. One dialog shows at a+// time: a new request replaces the presented one.+let presented: PresentedDialog | null = null;+let nextPresentationId = 0;+const listeners = new Set<() => void>();++function setPresented(next: PresentedDialog | null) {+ presented = next;+ for (const listener of listeners) listener();+}++function submitRequest(dialog: DialogRequest) {+ setPresented({ ...dialog, id: ++nextPresentationId });+}++/** Closes the dialog only if it is still the one the action came from. */+function dismiss(id: number) {+ if (presented?.id === id) setPresented(null);+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++function getPresented() {+ return presented;+}export function alert(...[title, message, buttons, options]: Parameters<typeof Alert.alert>): void {const actions = buttons?.length ? buttons.slice(0, 3) : [{ text: "OK" }];const normalized = actions.map((action, index) =>index === actions.length - 1 ? { ...action, text: action.text || "OK" } : action,);- presentRequest?.({+ submitRequest({kind: "alert",request: { title, message, buttons: normalized, options },});}export function confirm(request: ConfirmDialogRequest): void {- presentRequest?.({ kind: "confirm", request });+ submitRequest({ kind: "confirm", request });}export function prompt(request: TextInputDialogRequest): void {- presentRequest?.({ kind: "text-input", request });+ submitRequest({ kind: "text-input", request });}export function Host() {- const [presented, setPresented] = useState<(DialogRequest & { readonly id: number }) | null>(- null,- );- const [inputValue, setInputValue] = useState("");- const nextPresentationId = useRef(0);- useEffect(() => {- const present = (request: DialogRequest) => {- setInputValue(request.kind === "text-input" ? request.request.initialValue : "");- setPresented({ ...request, id: ++nextPresentationId.current });- };- presentRequest = present;- return () => {- // When Android replaces the activity, the new root's Host registers before the old root- // unmounts. Clearing unconditionally would leave the live Host without dialogs.- if (presentRequest === present) presentRequest = null;- };- }, []);+ const presented = useSyncExternalStore(subscribe, getPresented, getPresented);- const handleCancel = useCallback(() => {- setPresented(null);- if (presented?.kind === "alert") presented.request.options?.onDismiss?.();- else presented?.request.onCancel?.();- }, [presented]);+ const handleCancel = () => {+ if (!presented) return;+ dismiss(presented.id);+ if (presented.kind === "alert") presented.request.options?.onDismiss?.();+ else presented.request.onCancel?.();+ };- const handleConfirm = useCallback(- (nativeInputValue?: string) => {- setPresented(null);- if (presented?.kind === "confirm") {- presented.request.onConfirm();- } else if (presented?.kind === "text-input") {- presented.request.onConfirm(nativeInputValue ?? inputValue);- }- },- [inputValue, presented],- );+ const handleConfirm = (nativeInputValue?: string) => {+ if (!presented) return;+ dismiss(presented.id);+ if (presented.kind === "confirm") {+ presented.request.onConfirm();+ } else if (presented.kind === "text-input") {+ presented.request.onConfirm(nativeInputValue ?? presented.request.initialValue);+ }+ };if (presented?.kind === "alert") {return (@@ -103,7 +118,7 @@ export function Host() {alertActions={presented.request.buttons ?? [{ text: "OK" }]}dismissable={presented.request.options?.cancelable ?? false}onAlertAction={(action) => {- setPresented(null);+ dismiss(presented.id);action.onPress?.();}}onCancel={handleCancel}@@ -120,7 +135,6 @@ export function Host() {presented.kind === "text-input" ? presented.request.initialValue : undefined}inputPlaceholder={presented.kind === "text-input" ? presented.request.placeholder : undefined}- onInputChange={setInputValue}onCancel={handleCancel}onConfirm={handleConfirm}/>@@ -212,7 +226,6 @@ function DialogPresentation(props: DialogPresentationProps) {singleLinevalue={inputState}selection={inputSelection}- onValueChange={props.onInputChange}textStyle={inputTypography}keyboardOptions={{ imeAction: "done" }}keyboardActions={{@@ -267,7 +280,6 @@ interface DialogPresentationProps {>;readonly inputInitialValue?: string;readonly inputPlaceholder?: string;- readonly onInputChange?: (value: string) => void;readonly onCancel: () => void;readonly onConfirm: (inputValue?: string) => void;}diff --git a/apps/mobile/src/components/ui/OverlayPortal.tsx b/apps/mobile/src/components/ui/OverlayPortal.tsxindex a7939cfa307..a4f07f46024 100644--- a/apps/mobile/src/components/ui/OverlayPortal.tsx+++ b/apps/mobile/src/components/ui/OverlayPortal.tsx@@ -1,9 +1,8 @@-import { type ReactNode, useEffect, useState } from "react";+import { type ReactNode, useEffect, useState, useSyncExternalStore } from "react";import { View } from "react-native";// RN Modals move native window focus and close the keyboard. Keep composer menus in-window.type Entries = ReadonlyMap<number, ReactNode>;-type Listener = (entries: Entries) => void;let nextKey = 0;@@ -11,24 +10,41 @@ function allocateKey() {return nextKey++;}const entries = new Map<number, ReactNode>();-const listeners = new Set<Listener>();+const listeners = new Set<() => void>();+let snapshot: Entries = new Map();function emit() {- const snapshot = new Map(entries);+ snapshot = new Map(entries);for (const listener of listeners) {- listener(snapshot);+ listener();}}+function subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++function getSnapshot() {+ return snapshot;+}+export function OverlayPortal(props: { readonly children: ReactNode }) {const [key] = useState(allocateKey);- // Re-project every render so open menus reflect content and theme changes.+ // RN has no createPortal, so projecting into the out-of-tree host has to+ // happen after commit. No dependency array: re-project after every render so+ // the host always shows the current content (menus re-render while open —+ // drill-in, theme).useEffect(() => {entries.set(key, props.children);emit();});+ // Removal is unmount-only: deleting on every re-projection would move the+ // entry to the end of the map and restack it above overlays opened later.useEffect(() => () => {entries.delete(key);@@ -41,14 +57,7 @@ export function OverlayPortal(props: { readonly children: ReactNode }) {}export function OverlayPortalHost() {- const [current, setCurrent] = useState<Entries>(() => new Map());-- useEffect(() => {- listeners.add(setCurrent);- return () => {- listeners.delete(setCurrent);- };- }, []);+ const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);if (current.size === 0) {return null;diff --git a/apps/mobile/src/components/ui/SliderRow.android.tsx b/apps/mobile/src/components/ui/SliderRow.android.tsxindex ad774efa212..d9ab444f2cb 100644--- a/apps/mobile/src/components/ui/SliderRow.android.tsx+++ b/apps/mobile/src/components/ui/SliderRow.android.tsx@@ -1,7 +1,7 @@import { Slider } from "@expo/ui/jetpack-compose";import { fillMaxWidth } from "@expo/ui/jetpack-compose/modifiers";import * as Haptics from "expo-haptics";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { View } from "react-native";import { AppText as Text } from "./AppText";@@ -12,11 +12,8 @@ import type { SliderRowProps } from "./SliderRow.types";export function SliderRow(props: SliderRowProps) {const { colors } = useControlTheme();- const draft = useRef(props.value);- const dragging = useRef(false);- useEffect(() => {- if (!dragging.current) draft.current = props.value;- }, [props.value]);+ // The value of the drag in progress; null between drags.+ const draft = useRef<number | null>(null);const commit = (value: number) => {if (props.disabled) return;const next = Math.min(@@ -66,12 +63,12 @@ export function SliderRow(props: SliderRowProps) {inactiveTrackColor: colors["--color-secondary"],}}onValueChange={(value) => {- dragging.current = true;draft.current = value;}}onValueChangeFinished={() => {- dragging.current = false;- commit(draft.current);+ const value = draft.current;+ draft.current = null;+ if (value !== null) commit(value);}}/></NativeThemeHost>diff --git a/apps/mobile/src/components/ui/SliderRow.tsx b/apps/mobile/src/components/ui/SliderRow.tsxindex fcb837129da..4e993363df0 100644--- a/apps/mobile/src/components/ui/SliderRow.tsx+++ b/apps/mobile/src/components/ui/SliderRow.tsx@@ -6,7 +6,7 @@ import {tint,} from "@expo/ui/swift-ui/modifiers";import * as Haptics from "expo-haptics";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { View } from "react-native";import { AppText } from "./AppText";@@ -19,11 +19,9 @@ export type { SliderRowProps } from "./SliderRow.types";export function SliderRow(props: SliderRowProps) {const { colors } = useControlTheme();- const draft = useRef(props.value);+ // The value of the drag in progress; null until the drag moves.+ const draft = useRef<number | null>(null);const editing = useRef(false);- useEffect(() => {- if (!editing.current) draft.current = props.value;- }, [props.value]);const commit = (value: number) => {if (props.disabled) return;const next = Math.min(@@ -60,13 +58,15 @@ export function SliderRow(props: SliderRowProps) {accessibilityValue(props.valueLabel),]}onValueChange={(value) => {- draft.current = value;// Accessibility adjustments do not begin a touch editing session.- if (!editing.current) commit(value);+ if (editing.current) draft.current = value;+ else commit(value);}}onEditingChanged={(isEditing) => {editing.current = isEditing;- if (!isEditing) commit(draft.current);+ const value = draft.current;+ draft.current = null;+ if (!isEditing && value !== null) commit(value);}}/></NativeThemeHost>diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsxindex 615b931acbf..7e7fea4527b 100644--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx@@ -504,6 +504,9 @@ export function CommandPalette(props: {results.findIndex((item) => item.key === selection),);const selectedKey = results[selectedIndex]?.key;+ // The native list follows the highlighted row. Key presses move it, but so do+ // live thread updates and late message matches that reorder or drop the+ // selected row under a kept selection, so no single handler owns the scroll.useEffect(() => {if (selectedIndex === 0) {// Centering before the list measures its height scrolls half the first row out of view.@@ -514,26 +517,30 @@ export function CommandPalette(props: {}, [selectedIndex, selectedKey]);const dismissed = useRef(false);+ const dismissFallback = useRef<ReturnType<typeof setTimeout> | null>(null);const handleDismissed = useCallback(() => {+ if (dismissFallback.current !== null) clearTimeout(dismissFallback.current);+ dismissFallback.current = null;if (dismissed.current) return;dismissed.current = true;// Present navigation sheets only after UIKit has dismissed this modal.props.onClose();pendingAction.current?.();}, [props]);-- // iOS may drop onDismiss during presentation or competing sheets; a fallback clears stale palette state.- useEffect(() => {- if (visible) return;- const fallback = setTimeout(handleDismissed, 400);- return () => clearTimeout(fallback);- }, [visible, handleDismissed]);+ useEffect(+ () => () => {+ if (dismissFallback.current !== null) clearTimeout(dismissFallback.current);+ },+ [],+ );function close(run?: () => void) {if (closing.current) return;closing.current = true;pendingAction.current = run ?? null;setVisible(false);+ // iOS may drop onDismiss during presentation or competing sheets; a fallback clears stale palette state.+ dismissFallback.current = setTimeout(handleDismissed, 400);}function onCommand(command: HardwareKeyboardCommand) {@@ -603,6 +610,8 @@ export function CommandPalette(props: {onChangeText={(value) => {setQuery(value);setSelection(null);+ // The follow effect stays idle when the top row and its key are unchanged,+ // so a touch-scrolled list would otherwise keep its old offset.listRef.current?.scrollToOffset({ offset: 0, animated: false });}}returnKeyType="go"diff --git a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx b/apps/mobile/src/features/layout/workspace-inspector-pane.tsxindex fea0b3964f9..68a57a22980 100644--- a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx+++ b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx@@ -1,7 +1,9 @@import { useEffect, useRef, useState, type ReactNode } from "react";import Animated, {+ cubicBezier,runOnJS,useAnimatedStyle,+ useReducedMotion,useSharedValue,withTiming,type SharedValue,@@ -12,6 +14,9 @@ import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderEimport { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";import { WorkspacePaneDivider } from "./workspace-pane-divider";+// CSS form of WORKSPACE_PANE_TIMING's Easing.inOut(Easing.cubic).+const PANE_EASING = cubicBezier(0.65, 0, 0.35, 1);+/** Pass layout props to avoid an import cycle with AdaptiveWorkspaceLayout. */export function WorkspaceInspectorPane(props: {readonly pathname: string;@@ -32,7 +37,7 @@ export function WorkspaceInspectorPane(props: {const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0);const { renderedInspectorWidth } = props;- const renderedContentWidth = useSharedValue(inspectorWidth ?? 0);+ const reduceMotion = useReducedMotion();const onClosed = props.onClosed;useEffect(() => {@@ -56,15 +61,6 @@ export function WorkspaceInspectorPane(props: {resizing,]);- useEffect(() => {- const targetWidth = inspectorWidth ?? 0;- if (!inspectorVisible || resizing) {- renderedContentWidth.set(targetWidth);- return;- }- renderedContentWidth.set(withTiming(targetWidth, WORKSPACE_PANE_TIMING));- }, [inspectorVisible, inspectorWidth, renderedContentWidth, resizing]);-const inspectorStyle = useAnimatedStyle(() => ({opacity: inspectorProgress.value,@@ -73,7 +69,14 @@ export function WorkspaceInspectorPane(props: {}),[],);- const inspectorContentStyle = useAnimatedStyle(() => ({ width: renderedContentWidth.value }), []);+ // A hidden or resizing pane takes its width at once; a visible one eases with the column.+ const inspectorContentStyle = {+ width: inspectorWidth ?? 0,+ transitionProperty: "width",+ transitionDuration:+ !inspectorVisible || resizing || reduceMotion ? 0 : WORKSPACE_PANE_TIMING.duration,+ transitionTimingFunction: PANE_EASING,+ } as const;const beginResize = () => {resizeStartWidth.current = inspectorWidth ?? 0;setResizing(true);diff --git a/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx b/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsxindex f29d1677b72..de5d93b8cba 100644--- a/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx+++ b/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx@@ -1,8 +1,10 @@import { requireOptionalNativeModule } from "expo";-import { useEffect, useState } from "react";import { Platform } from "react-native";+import { useDeadlinePassed } from "../lib/clock";import type { NativeLayoutMetrics } from "../lib/reserved-regions";-import { useNativeLayoutMetrics } from "./native-layout-metrics";+import { useNativeLayoutMetrics, useNativeLayoutMetricsDeadline } from "./native-layout-metrics";++export { NATIVE_METRICS_TIMEOUT_MS } from "./native-layout-metrics";const nativeControls = requireOptionalNativeModule<{readonly supportsWorkspaceColumns?: boolean;@@ -19,24 +21,15 @@ export function nativeWorkspaceColumnsSupportedFor(metrics: NativeLayoutMetrics);}-// Binaries without the native no-hinge fallback never report metrics on ordinary-// iPhones running iOS 27.1 or later. Use the compact navigator rather than staying blank.-export const NATIVE_METRICS_TIMEOUT_MS = 1000;-export function useNativeWorkspaceColumnsReady() {const metrics = useNativeLayoutMetrics();- const [timedOut, setTimedOut] = useState(false);+ const metricsDeadline = useNativeLayoutMetricsDeadline();const waiting =!(Platform.OS === "ios" && Platform.isPad) &&!!nativeControls?.ViewPrototypes?.T3NativeControls_LayoutMetrics &&metrics === null;-- useEffect(() => {- if (!waiting) return;- const timeout = setTimeout(() => setTimedOut(true), NATIVE_METRICS_TIMEOUT_MS);- return () => clearTimeout(timeout);- }, [waiting]);-+ // Without metrics by the deadline, use the compact navigator rather than staying blank.+ const timedOut = useDeadlinePassed(waiting ? metricsDeadline : null);return !waiting || timedOut;}diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsxindex 67b77a8c6b4..e03e02d5e49 100644--- a/apps/mobile/src/native/StackHeader.tsx+++ b/apps/mobile/src/native/StackHeader.tsx@@ -194,22 +194,26 @@ export function NativeStackScreenOptions(props: {const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());- const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);- const stableOptions = normalizedOptions- ? (stabilizeOptionFunctions(- normalizedOptions,- "options",- latestOptionFunctionsRef.current,- optionFunctionWrappersRef.current,- ) as NativeStackNavigationOptions)- : undefined;+ // Stabilizing records each factory's latest closure, so it runs in the commit+ // phase: a render React discards must not leak its closures into the header.+ // It runs before the tab check so wrappers already installed in an inactive+ // tab's header still call the newest closures.useLayoutEffect(() => {+ const normalizedOptions = normalizeScreenOptions(props.options);+ const stableOptions = normalizedOptions+ ? stabilizeOptionFunctions(+ normalizedOptions,+ "options",+ latestOptionFunctionsRef.current,+ optionFunctionWrappersRef.current,+ )+ : undefined;if (!tabActive) {lastAppliedOptionsSignatureRef.current = undefined;return;}- if (!setOptions || !stableOptions) {+ if (!setOptions || !normalizedOptions) {return;}const signature = optionsSignature([stableOptions, props.optionsVersion]);@@ -229,7 +233,7 @@ export function NativeStackScreenOptions(props: {optionFunctionWrappersRef.current,) as NativeStackNavigationOptions,);- }, [setOptions, normalizedOptions, props.optionsVersion, stableOptions, tabActive]);+ }, [setOptions, props.options, props.optionsVersion, tabActive]);useEffect(() => {if (!navigation || !props.listeners) {diff --git a/apps/mobile/src/native/V5StackHeader.ios.tsx b/apps/mobile/src/native/V5StackHeader.ios.tsxindex 7fc128f52ec..969960b2c92 100644--- a/apps/mobile/src/native/V5StackHeader.ios.tsx+++ b/apps/mobile/src/native/V5StackHeader.ios.tsx@@ -268,6 +268,8 @@ export function V5StackHeader(props: {: undefined;const searchOptions = options.headerSearchBarOptions;const autofocusRef = searchOptions?.ref ?? searchRef;+ // iOS ignores the native autoFocus prop, and SearchBar's imperative handle changes every+ // commit, so a ref callback would refocus on each render; focus once after the header mounts.useEffect(() => {if (!searchOptions?.autoFocus) return;const frame = requestAnimationFrame(() => autofocusRef.current?.focus());diff --git a/apps/mobile/src/native/native-layout-metrics.tsx b/apps/mobile/src/native/native-layout-metrics.tsxindex 3ace671cbf5..cd254eabe99 100644--- a/apps/mobile/src/native/native-layout-metrics.tsx+++ b/apps/mobile/src/native/native-layout-metrics.tsx@@ -11,6 +11,10 @@ const NativeLayoutContext = createContext<NativeLayoutMetrics | null>(null);const DeviceTypeContext = createContext<DeviceType>(deriveDeviceType({ isPad: IS_PAD, metrics: null }),);+// Binaries without the native no-hinge fallback never report metrics on ordinary+// iPhones running iOS 27.1 or later; consumers stop waiting at this deadline.+export const NATIVE_METRICS_TIMEOUT_MS = 1000;+const NativeLayoutMetricsDeadlineContext = createContext<number>(0);// Column reservations come from UIKit's layout, outside the resizing navigator.export const NativeColumnLayoutMetricsContext = createContext<NativeLayoutMetrics | null>(null);@@ -38,6 +42,7 @@ export function currentNativeLayoutMetrics() {export function NativeLayoutMetricsProvider(props: { readonly children: ReactNode }) {const [metrics, setMetrics] = useState<NativeLayoutMetrics | null>(null);+ const [metricsDeadline] = useState(() => Date.now() + NATIVE_METRICS_TIMEOUT_MS);const publish = (next: NativeLayoutMetrics) => {latestMetrics = next;for (const settle of metricsWaiters) settle(next);@@ -45,12 +50,14 @@ export function NativeLayoutMetricsProvider(props: { readonly children: ReactNod};const deviceType = deriveDeviceType({ isPad: IS_PAD, metrics });return (- <NativeLayoutContext value={metrics}>- <DeviceTypeContext value={deviceType}>- <NativeLayoutObserver onChange={publish} />- {props.children}- </DeviceTypeContext>- </NativeLayoutContext>+ <NativeLayoutMetricsDeadlineContext value={metricsDeadline}>+ <NativeLayoutContext value={metrics}>+ <DeviceTypeContext value={deviceType}>+ <NativeLayoutObserver onChange={publish} />+ {props.children}+ </DeviceTypeContext>+ </NativeLayoutContext>+ </NativeLayoutMetricsDeadlineContext>);}@@ -58,6 +65,11 @@ export function useNativeLayoutMetrics() {return use(NativeLayoutContext);}+/** Epoch ms after which a consumer still waiting for the first metrics gives up. */+export function useNativeLayoutMetricsDeadline() {+ return use(NativeLayoutMetricsDeadlineContext);+}+export function useNativeColumnLayoutMetrics() {return use(NativeColumnLayoutMetricsContext);}diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex 7eb3b3c915a..c644fb09a4c 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -15,14 +15,12 @@ const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =// Remove bailout entries and manual memoization when compilation starts; this check rejects stale entries.const KNOWN_BAILOUTS: Record<string, string> = {"src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",- "src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render","src/components/ui/Menu.tsx": "ref read during render","src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render","src/features/home/thread-swipe-actions.tsx": "ref read during render","src/features/threads/ThreadArrangementSheet.tsx": "ref read during render","src/features/voice-input/VoiceInputProvider.tsx": "ref read during render","src/features/voice-input/useVoiceInputController.ts": "ref read during render",- "src/native/StackHeader.tsx": "ref read during render","src/native/T3ComposerEditor.ios.tsx": "ref read during render","src/native/T3ComposerEditor.native.tsx": "ref read during render",};