Skip to content

Commit b913e89

Browse files
fix(mobile): each workspace tab keeps its own header options
The four native tab slots render the same root routes, so screen options written with navigation.setOptions were shared: switching tabs showed the slot's stale header, then crossfaded to another slot's title and toolbar. Options written inside a slot now live in that slot and merge over the route's own. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4226935 commit b913e89

7 files changed

Lines changed: 112 additions & 39 deletions

File tree

‎apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ import {
5858
NativePrimaryColumnContext,
5959
NativeWorkspaceInspectorContext,
6060
NativeWorkspaceModeContext,
61+
WorkspaceSlotOptionsContext,
62+
slotScreenOptions,
6163
} from "../../native/v5-workspace-context";
6264

6365
type ViewProps = ComponentProps<typeof NativeStackView>;
@@ -93,10 +95,14 @@ function ColumnScreen(props: {
9395
readonly navigation: ViewProps["navigation"];
9496
}) {
9597
const { descriptor } = props;
98+
// Options a screen set inside this workspace tab slot, over its route's.
99+
const options = slotScreenOptions(
100+
use(WorkspaceSlotOptionsContext),
101+
descriptor.route.key,
102+
descriptor.options,
103+
);
96104
const Header =
97-
props.sidebarToggle && !descriptor.options.unstable_headerLeftItems
98-
? SidebarToggleHeader
99-
: V5StackHeader;
105+
props.sidebarToggle && !options.unstable_headerLeftItems ? SidebarToggleHeader : V5StackHeader;
100106
const [presented, setPresented] = useState(false);
101107
const primaryColumn = useMemo(
102108
() =>
@@ -138,7 +144,7 @@ function ColumnScreen(props: {
138144
<NavigationContext value={descriptor.navigation}>
139145
<NavigationRouteContext value={descriptor.route}>
140146
<Header
141-
options={descriptor.options}
147+
options={options}
142148
canGoBack={!props.primary}
143149
column={props.primary ? "primary" : "detail"}
144150
onCompose={
@@ -152,7 +158,7 @@ function ColumnScreen(props: {
152158
<ColumnContent
153159
primary={props.primary}
154160
insetHorizontally={
155-
(descriptor.options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
161+
(options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
156162
}
157163
>
158164
<NativePrimaryColumnContext value={primaryColumn}>

‎apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
NAVIGATION_TAB_ICONS,
44
useEnabledNavigationTabs,
55
} from "./navigation-tabs";
6-
import { useCallback, useMemo, useState, type ReactNode } from "react";
6+
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
77
import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native";
88
import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens";
99

@@ -14,7 +14,10 @@ import {
1414
workspaceUsesColumns,
1515
type WorkspaceTab,
1616
} from "./workspace-tabs-state";
17-
import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context";
17+
import {
18+
NativeWorkspaceTabActivityContext,
19+
WorkspaceSlotOptionsContext,
20+
} from "../../native/v5-workspace-context";
1821
import { useCompactWorkspaceTabs, useSystemWorkspaceTabBar } from "./useSystemWorkspaceTabBar";
1922
import { useControlTheme } from "../../components/ui/useControlTheme";
2023
import { useDeviceType } from "../../native/native-layout-metrics";
@@ -31,23 +34,42 @@ function RetainedWorkspaceTab(props: {
3134
readonly children: ReactNode;
3235
}) {
3336
const workspace = useWorkspaceTabs()!;
34-
const { isTabActive } = workspace;
35-
const isActive = useCallback(() => isTabActive(props.tab), [isTabActive, props.tab]);
37+
// Whether this slot is the visible one, read by cleanups after the switch has committed.
38+
const activeRef = useRef(props.active);
39+
useLayoutEffect(() => {
40+
activeRef.current = props.active;
41+
}, [props.active]);
42+
const isActive = useCallback(() => activeRef.current, []);
3643
const activity = useMemo(
3744
() => ({
3845
active: props.active,
3946
isActive,
4047
}),
4148
[props.active, isActive],
4249
);
50+
const [optionsByRoute, setOptionsByRoute] = useState<ReadonlyMap<string, object>>(new Map());
51+
// Stable, so writers and the cleanups that depend on them don't re-run on every write.
52+
const setRouteOptions = useCallback(
53+
(routeKey: string, options: object) =>
54+
setOptionsByRoute((current) =>
55+
new Map(current).set(routeKey, { ...current.get(routeKey), ...options }),
56+
),
57+
[],
58+
);
59+
const slotOptions = useMemo(
60+
() => ({ byRoute: optionsByRoute, set: setRouteOptions }),
61+
[optionsByRoute, setRouteOptions],
62+
);
4363
const [content, setContent] = useState(
4464
props.active ? { workspace, children: props.children } : null,
4565
);
4666
if (props.active && (content?.workspace !== workspace || content?.children !== props.children))
4767
setContent({ workspace, children: props.children });
4868
return content ? (
4969
<NativeWorkspaceTabActivityContext value={activity}>
50-
<WorkspaceTabsContext value={content.workspace}>{content.children}</WorkspaceTabsContext>
70+
<WorkspaceSlotOptionsContext value={slotOptions}>
71+
<WorkspaceTabsContext value={content.workspace}>{content.children}</WorkspaceTabsContext>
72+
</WorkspaceSlotOptionsContext>
5173
</NativeWorkspaceTabActivityContext>
5274
) : null;
5375
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ const harness = vi.hoisted(() => ({
1919

2020
// Native headers retain the actions materialized when navigation applies options. Like React
2121
// Navigation, the header renders again only when the options are no longer shallowly equal.
22-
vi.mock("@react-navigation/native", () => {
22+
vi.mock("@react-navigation/native", async () => {
23+
// vi.mock factories run before the file's imports.
24+
const { createContext } = await vi.importActual<typeof import("react")>("react");
2325
const navigation = {
2426
setOptions(options: HeaderOptions) {
2527
harness.setOptionsCalls += 1;
@@ -39,6 +41,8 @@ vi.mock("@react-navigation/native", () => {
3941
},
4042
};
4143
return {
44+
// Outside a workspace tab slot the header writes to the route's navigation.
45+
NavigationRouteContext: createContext(undefined),
4246
useNavigation: () => navigation,
4347
useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
4448
};

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

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import { useNavigation, useRoute, type ParamListBase } from "@react-navigation/native";
1+
import { useRoute } from "@react-navigation/native";
22
import type {
33
NativeStackHeaderItem,
44
NativeStackHeaderItemMenu,
55
NativeStackNavigationOptions,
6-
NativeStackNavigationProp,
76
} from "@react-navigation/native-stack";
87
import {
98
Children,
@@ -17,11 +16,7 @@ import {
1716
import type { ColorValue } from "react-native";
1817
import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";
1918
import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
20-
import { NativeStackScreenOptions } from "./StackHeader";
21-
22-
function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
23-
return useNavigation<NativeStackNavigationProp<ParamListBase>>();
24-
}
19+
import { NativeStackScreenOptions, useScreenOptionsWriter } from "./StackHeader";
2520

2621
function labelFromChildren(children: ReactNode): string {
2722
const parts: string[] = [];
@@ -230,7 +225,7 @@ function NativeHeaderToolbarRoot(props: {
230225
readonly placement?: "left" | "right" | "bottom";
231226
readonly children?: ReactNode;
232227
}) {
233-
const navigation = useNativeStackNavigation();
228+
const setOptions = useScreenOptionsWriter();
234229
const route = useRoute();
235230
const tabActivity = use(NativeWorkspaceTabActivityContext);
236231
const isTabActive = tabActivity?.isActive;
@@ -242,20 +237,20 @@ function NativeHeaderToolbarRoot(props: {
242237
);
243238

244239
useLayoutEffect(() => {
245-
if (!navigation) return;
240+
if (!setOptions) return;
246241
return () => {
247242
if (isTabActive && !isTabActive()) return;
248243
if (props.placement === "bottom") {
249-
navigation.setOptions({
244+
setOptions({
250245
unstable_headerToolbarItems: () => [],
251246
} as NativeStackOptionsWithToolbar);
252247
} else if (props.placement === "left") {
253-
navigation.setOptions({ unstable_headerLeftItems: () => [] });
248+
setOptions({ unstable_headerLeftItems: () => [] });
254249
} else {
255-
navigation.setOptions({ unstable_headerRightItems: () => [] });
250+
setOptions({ unstable_headerRightItems: () => [] });
256251
}
257252
};
258-
}, [navigation, props.placement, isTabActive]);
253+
}, [setOptions, props.placement, isTabActive]);
259254

260255
return (
261256
<NativeStackScreenOptions

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

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1-
import { useNavigation, type ParamListBase } from "@react-navigation/native";
1+
import {
2+
NavigationRouteContext,
3+
useNavigation,
4+
type ParamListBase,
5+
} from "@react-navigation/native";
26
import type {
37
NativeStackNavigationOptions,
48
NativeStackNavigationProp,
59
} from "@react-navigation/native-stack";
610
import { isValidElement, use, useEffect, useLayoutEffect, useMemo, useRef } from "react";
7-
import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
11+
import {
12+
NativeWorkspaceTabActivityContext,
13+
WorkspaceSlotOptionsContext,
14+
} from "./v5-workspace-context";
815
import type { ColorValue } from "react-native";
916

1017
export {
@@ -160,6 +167,23 @@ function stabilizeOptionFunctions(
160167
return value;
161168
}
162169

170+
/**
171+
* Sets the current screen's options. Inside a workspace tab slot they're kept for that slot, so
172+
* slots rendering the same route never overwrite each other's header.
173+
*/
174+
export function useScreenOptionsWriter() {
175+
const navigation = useNativeStackNavigation();
176+
const setSlotOptions = use(WorkspaceSlotOptionsContext)?.set;
177+
const routeKey = use(NavigationRouteContext)?.key;
178+
return useMemo(() => {
179+
if (setSlotOptions && routeKey !== undefined)
180+
return (options: NativeStackNavigationOptions) => setSlotOptions(routeKey, options);
181+
return navigation
182+
? (options: NativeStackNavigationOptions) => navigation.setOptions(options)
183+
: null;
184+
}, [navigation, routeKey, setSlotOptions]);
185+
}
186+
163187
export function NativeStackScreenOptions(props: {
164188
readonly options?: AppNativeStackNavigationOptions;
165189
/**
@@ -173,6 +197,7 @@ export function NativeStackScreenOptions(props: {
173197
readonly name?: string;
174198
}) {
175199
const navigation = useNativeStackNavigation();
200+
const setOptions = useScreenOptionsWriter();
176201
const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
177202
const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
178203
const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
@@ -192,7 +217,7 @@ export function NativeStackScreenOptions(props: {
192217
lastAppliedOptionsSignatureRef.current = undefined;
193218
return;
194219
}
195-
if (!navigation || !stableOptions) {
220+
if (!setOptions || !stableOptions) {
196221
return;
197222
}
198223
const signature = optionsSignature([stableOptions, props.optionsVersion]);
@@ -204,15 +229,15 @@ export function NativeStackScreenOptions(props: {
204229
// stabilized factories keep their identity, so one whose output changed needs a new wrapper
205230
// to reach the header.
206231
optionFunctionWrappersRef.current = new Map();
207-
navigation.setOptions(
232+
setOptions(
208233
stabilizeOptionFunctions(
209234
normalizedOptions,
210235
"options",
211236
latestOptionFunctionsRef.current,
212237
optionFunctionWrappersRef.current,
213238
) as NativeStackNavigationOptions,
214239
);
215-
}, [navigation, normalizedOptions, props.optionsVersion, stableOptions, tabActive]);
240+
}, [setOptions, normalizedOptions, props.optionsVersion, stableOptions, tabActive]);
216241

217242
useEffect(() => {
218243
if (!navigation || !props.listeners) {

‎apps/mobile/src/native/createV5StackNavigator.ios.tsx‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ import {
2020
type NativeStackNavigatorProps,
2121
type NativeStackTypeBag,
2222
} from "@react-navigation/native-stack";
23-
import { useCallback, useRef, useState, type ComponentProps } from "react";
23+
import { use, useCallback, useRef, useState, type ComponentProps } from "react";
24+
import { WorkspaceSlotOptionsContext, slotScreenOptions } from "./v5-workspace-context";
2425
import { StyleSheet, View } from "react-native";
2526
import { FormSheet, Stack } from "react-native-screens";
2627
import { NativeScrollEdgeEffectsContext } from "./NativeScrollViewMarker";
@@ -56,6 +57,8 @@ export function V5CardStackView(
5657
props: V5StackViewProps & { readonly onRootVisibilityChange?: (visible: boolean) => void },
5758
) {
5859
const { preventedRoutes } = usePreventRemoveContext();
60+
// Options a screen set inside this workspace tab slot, over its route's.
61+
const slot = use(WorkspaceSlotOptionsContext);
5962
const nativePopSource = useRef<string | null>(null);
6063
const [screens, setScreens] = useState({
6164
completedNativeDismissals: new Set<string>(),
@@ -148,6 +151,7 @@ export function V5CardStackView(
148151
{screens.routes.map((route, index) => {
149152
const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
150153
if (!descriptor) return null;
154+
const options = slotScreenOptions(slot, route.key, descriptor.options);
151155
const attached = props.state.routes.some((current) => current.key === route.key);
152156
return (
153157
<Stack.Screen
@@ -157,8 +161,7 @@ export function V5CardStackView(
157161
attached || screens.nativeCompletingPops.has(route.key) ? "attached" : "detached"
158162
}
159163
preventNativeDismiss={
160-
preventedRoutes[route.key]?.preventRemove ||
161-
descriptor.options.gestureEnabled === false
164+
preventedRoutes[route.key]?.preventRemove || options.gestureEnabled === false
162165
}
163166
onDismiss={removeDismissed}
164167
onNativeDismiss={nativeDismiss}
@@ -229,23 +232,20 @@ export function V5CardStackView(
229232
<NavigationContext value={descriptor.navigation}>
230233
<NavigationRouteContext value={descriptor.route}>
231234
<V5StackHeader
232-
options={descriptor.options}
235+
options={options}
233236
canGoBack={
234237
attached
235238
? props.state.routes.findIndex((current) => current.key === route.key) > 0
236239
: index > 0
237240
}
238241
/>
239242
<NativeColumnContent
240-
backgroundColor={
241-
StyleSheet.flatten(descriptor.options.contentStyle)?.backgroundColor
242-
}
243+
backgroundColor={StyleSheet.flatten(options.contentStyle)?.backgroundColor}
243244
insetHorizontally={
244-
(descriptor.options as AppNativeStackNavigationOptions)
245-
.nativeContentInsetHorizontally
245+
(options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
246246
}
247247
>
248-
<NativeScrollEdgeEffectsContext value={descriptor.options.scrollEdgeEffects}>
248+
<NativeScrollEdgeEffectsContext value={options.scrollEdgeEffects}>
249249
{descriptor.render()}
250250
</NativeScrollEdgeEffectsContext>
251251
</NativeColumnContent>

‎apps/mobile/src/native/v5-workspace-context.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
import { createContext, type ReactNode } from "react";
22

33
export const NativeWorkspaceModeContext = createContext(false);
4+
/**
5+
* Each workspace tab slot renders the same routes, so header options a screen sets are kept per
6+
* slot (by route key) instead of on the shared route: a slot's header then never shows options
7+
* another slot set, and switching tabs has nothing left to update.
8+
*/
9+
export interface WorkspaceSlotOptions {
10+
readonly byRoute: ReadonlyMap<string, object>;
11+
readonly set: (routeKey: string, options: object) => void;
12+
}
13+
export const WorkspaceSlotOptionsContext = createContext<WorkspaceSlotOptions | null>(null);
14+
15+
/** A route's options with whatever its screens set within this slot on top. */
16+
export function slotScreenOptions<Options extends object>(
17+
slot: WorkspaceSlotOptions | null,
18+
routeKey: string | undefined,
19+
options: Options,
20+
): Options {
21+
const own = routeKey === undefined ? undefined : slot?.byRoute.get(routeKey);
22+
return own ? { ...options, ...own } : options;
23+
}
24+
425
/** Retained tabs must not update another tab's navigation options. */
526
export const NativeWorkspaceTabActivityContext = createContext<{
627
readonly active: boolean;

0 commit comments

Comments
 (0)