Open History to see the last commit
1import {
2 createNavigatorFactory,
3 NavigationContext,
4 NavigationRouteContext,
5 StackRouter,
6 useNavigationBuilder,
7 usePreventRemoveContext,
8 type NavigatorTypeBagBase,
9 type ParamListBase,
10 type StackActionHelpers,
11 type StackNavigationState,
12 type StackRouterOptions,
13 type StaticConfig,
14 type TypedNavigator,
15} from "@react-navigation/native";
16import {
17 NativeStackView,
18 type NativeStackNavigationEventMap,
19 type NativeStackNavigationOptions,
20 type NativeStackNavigatorProps,
21 type NativeStackTypeBag,
22} from "@react-navigation/native-stack";
23import { use, useCallback, useRef, useState, type ComponentProps } from "react";
24import {
25 NativeWorkspaceTabActivityContext,
26 WorkspaceSlotOptionsContext,
27 slotScreenOptions,
28} from "./v5-workspace-context";
29import { StyleSheet, View } from "react-native";
30import { Stack } from "react-native-screens";
31import { NativeScrollEdgeEffectsContext } from "./NativeScrollViewMarker";
32import { V5StackHeader } from "./V5StackHeader.ios";
33import type { AppNativeStackNavigationOptions } from "./StackHeader";
34import { NativeColumnContent } from "./NativeColumnContent.ios";
35import {
36 isPresentedRoute,
37 nativeStackPopAction,
38 partitionStackPresentations,
39 reconcileStackScreens,
40} from "./workspace-stack-projection";
41
42export type V5StackViewProps = ComponentProps<typeof NativeStackView>;
43
44export function modalEnvelopeOptions(options: NativeStackNavigationOptions) {
45 return {
46 ...Object.fromEntries(
47 Object.entries(options).filter(
48 ([key]) =>
49 !key.startsWith("header") &&
50 !key.startsWith("unstable_header") &&
51 key !== "unstable_navigationItemStyle",
52 ),
53 ),
54 headerShown: false,
55 };
56}
57
58/** Keep outgoing screens until UIKit completes its pop, as required by v5. */
59export function V5CardStackView(
60 props: V5StackViewProps & {
61 readonly onRootVisibilityChange?: (visible: boolean) => void;
62 /** The card native Back is popping, which the router still shows until the pop finishes. */
63 readonly onNativePopChange?: (key: string | null) => void;
64 },
65) {
66 const { preventedRoutes } = usePreventRemoveContext();
67 // Options a screen set inside this workspace tab slot, over its route's.
68 const slot = use(WorkspaceSlotOptionsContext);
69 const tabActivity = use(NativeWorkspaceTabActivityContext);
70 const isActiveTabSlot = () =>
71 tabActivity === null || (tabActivity.isActive() && !tabActivity.headerOnly);
72 const nativePopSource = useRef<string | null>(null);
73 // Back reveals the card beneath; a full-screen presentation covers the card without revealing one.
74 const cardRevealed = useRef(false);
75 const { onNativePopChange } = props;
76 const setNativePopSource = useCallback(
77 (key: string | null) => {
78 nativePopSource.current = key;
79 onNativePopChange?.(key);
80 },
81 [onNativePopChange],
82 );
83 const [screens, setScreens] = useState({
84 completedNativeDismissals: new Set<string>(),
85 nativeCompletingPops: new Set<string>(),
86 routes: props.state.routes,
87 descriptors: props.descriptors,
88 observedRoutes: props.state.routes,
89 observedDescriptors: props.descriptors,
90 });
91 if (
92 screens.observedRoutes !== props.state.routes ||
93 screens.observedDescriptors !== props.descriptors
94 ) {
95 const routes = reconcileStackScreens(
96 screens.routes,
97 props.state.routes,
98 screens.completedNativeDismissals,
99 );
100 const active = new Set(props.state.routes.map((route) => route.key));
101 const retainedKeys = new Set(routes.map((route) => route.key));
102 setScreens({
103 nativeCompletingPops: new Set(
104 [...screens.nativeCompletingPops].filter((key) => retainedKeys.has(key)),
105 ),
106 completedNativeDismissals: new Set(
107 [...screens.completedNativeDismissals].filter((key) => active.has(key)),
108 ),
109 routes,
110 descriptors: Object.fromEntries(
111 Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>
112 retainedKeys.has(key),
113 ),
114 ),
115 observedRoutes: props.state.routes,
116 observedDescriptors: props.descriptors,
117 });
118 }
119 // Retain the real descriptor through dismissal; placeholders reject setOptions and dispatch.
120 const nativeDismiss = useCallback(
121 (key: string) => {
122 const state = props.navigation.getState();
123 const attached = state.routes.some((route) => route.key === key);
124 setScreens((current) => {
125 const completedNativeDismissals = new Set(current.completedNativeDismissals);
126 const nativeCompletingPops = new Set(current.nativeCompletingPops);
127 nativeCompletingPops.delete(key);
128 if (attached) {
129 completedNativeDismissals.add(key);
130 return { ...current, completedNativeDismissals, nativeCompletingPops };
131 }
132 // Clean delayed callbacks immediately; the router already removed this route and will not update again.
133 completedNativeDismissals.delete(key);
134 const descriptors = { ...current.descriptors };
135 delete descriptors[key];
136 return {
137 ...current,
138 completedNativeDismissals,
139 nativeCompletingPops,
140 routes: current.routes.filter((route) => route.key !== key),
141 descriptors,
142 };
143 });
144 if (nativePopSource.current === key) setNativePopSource(null);
145 const action = nativeStackPopAction(state, key);
146 if (action) props.navigation.dispatch(action);
147 },
148 [props.navigation, setNativePopSource, setScreens],
149 );
150 const removeDismissed = (key: string) => {
151 if (!props.navigation.getState().routes.some((route) => route.key === key)) {
152 setScreens((current) => {
153 const descriptors = { ...current.descriptors };
154 delete descriptors[key];
155 return {
156 ...current,
157 routes: current.routes.filter((route) => route.key !== key),
158 descriptors,
159 };
160 });
161 }
162 };
163 return (
164 <View className="flex-1 bg-screen">
165 <Stack.Host>
166 {screens.routes.map((route, index) => {
167 const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
168 if (!descriptor) return null;
169 const options = slotScreenOptions(slot, route.key, descriptor.options);
170 const attached = props.state.routes.some((current) => current.key === route.key);
171 return (
172 <Stack.Screen
173 key={route.key}
174 screenKey={route.key}
175 activityMode={
176 attached || screens.nativeCompletingPops.has(route.key) ? "attached" : "detached"
177 }
178 preventNativeDismiss={
179 preventedRoutes[route.key]?.preventRemove || options.gestureEnabled === false
180 }
181 onDismiss={removeDismissed}
182 onNativeDismiss={nativeDismiss}
183 onNativeDismissPrevented={() => {
184 if (preventedRoutes[route.key]?.preventRemove) descriptor.navigation.goBack();
185 }}
186 onWillAppear={() => {
187 cardRevealed.current = true;
188 if (isActiveTabSlot()) props.onRootVisibilityChange?.(index === 0);
189 props.navigation.emit({
190 type: "transitionStart",
191 target: route.key,
192 data: { closing: false },
193 });
194 }}
195 onDidAppear={() => {
196 if (index > 0 && isActiveTabSlot()) props.onRootVisibilityChange?.(false);
197 const source = nativePopSource.current;
198 if (source === route.key) {
199 setNativePopSource(null);
200 } else if (source) {
201 const state = props.navigation.getState();
202 const action = nativeStackPopAction(state, source, route.key);
203 if (action) {
204 const sourceIndex = state.routes.findIndex((current) => current.key === source);
205 // Keep children until UIKit's dismissal callback; early router removal would enqueue a second pop.
206 const poppedKeys = state.routes
207 .slice(sourceIndex - action.payload.count + 1, sourceIndex + 1)
208 .map((popped) => popped.key);
209 setScreens((current) => ({
210 ...current,
211 nativeCompletingPops: new Set([
212 ...current.nativeCompletingPops,
213 ...poppedKeys,
214 ]),
215 }));
216 setNativePopSource(null);
217 props.navigation.dispatch(action);
218 }
219 }
220 props.navigation.emit({
221 type: "transitionEnd",
222 target: route.key,
223 data: { closing: false },
224 });
225 }}
226 onWillDisappear={() => {
227 if (index === 0 && isActiveTabSlot()) props.onRootVisibilityChange?.(false);
228 const state = props.navigation.getState();
229 // Only native Back leaves the disappearing card active; JS navigation already changed history.
230 if (
231 isActiveTabSlot() &&
232 state.index > 0 &&
233 state.routes[state.index]?.key === route.key
234 ) {
235 cardRevealed.current = false;
236 setNativePopSource(route.key);
237 }
238 props.navigation.emit({
239 type: "transitionStart",
240 target: route.key,
241 data: { closing: true },
242 });
243 }}
244 onDidDisappear={() => {
245 if (nativePopSource.current === route.key && !cardRevealed.current) {
246 setNativePopSource(null);
247 }
248 props.navigation.emit({
249 type: "transitionEnd",
250 target: route.key,
251 data: { closing: true },
252 });
253 }}
254 >
255 <NavigationContext value={descriptor.navigation}>
256 <NavigationRouteContext value={descriptor.route}>
257 <V5StackHeader
258 options={options}
259 canGoBack={
260 attached
261 ? props.state.routes.findIndex((current) => current.key === route.key) > 0
262 : index > 0
263 }
264 />
265 <NativeColumnContent
266 backgroundColor={StyleSheet.flatten(options.contentStyle)?.backgroundColor}
267 insetHorizontally={
268 (options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
269 }
270 >
271 <NativeScrollEdgeEffectsContext value={options.scrollEdgeEffects}>
272 {descriptor.render()}
273 </NativeScrollEdgeEffectsContext>
274 </NativeColumnContent>
275 </NavigationRouteContext>
276 </NavigationContext>
277 </Stack.Screen>
278 );
279 })}
280 </Stack.Host>
281 </View>
282 );
283}
284
285export function V5StackView(props: V5StackViewProps) {
286 const groups = partitionStackPresentations(props.state.routes, (route) => {
287 return isPresentedRoute(props.descriptors[route.key]?.options);
288 });
289 const routes = groups.map((group) => group[0]!);
290 const descriptors = Object.fromEntries(
291 groups.map((group) => {
292 const first = group[0]!;
293 const descriptor = props.descriptors[first.key]!;
294 const visibleRoute = group.at(-1)!;
295 return [
296 first.key,
297 {
298 ...descriptor,
299 navigation: props.descriptors[visibleRoute.key]!.navigation,
300 route: visibleRoute,
301 options: modalEnvelopeOptions(descriptor.options),
302 render: () => (
303 <V5CardStackView
304 {...props}
305 state={{
306 ...props.state,
307 routes: group,
308 index: group.length - 1,
309 preloadedRoutes: [],
310 }}
311 />
312 ),
313 },
314 ];
315 }),
316 );
317 return (
318 <NativeStackView
319 presentationEnvelope
320 {...props}
321 descriptors={descriptors}
322 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
323 />
324 );
325}
326
327function V5Navigator({
328 id,
329 initialRouteName,
330 UNSTABLE_routeNamesChangeBehavior,
331 children,
332 layout,
333 screenListeners,
334 screenOptions,
335 screenLayout,
336 UNSTABLE_router,
337 ...rest
338}: NativeStackNavigatorProps) {
339 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
340 StackNavigationState<ParamListBase>,
341 StackRouterOptions,
342 StackActionHelpers<ParamListBase>,
343 NativeStackNavigationOptions,
344 NativeStackNavigationEventMap
345 >(StackRouter, {
346 id,
347 initialRouteName,
348 UNSTABLE_routeNamesChangeBehavior,
349 children,
350 layout,
351 screenListeners,
352 screenOptions,
353 screenLayout,
354 UNSTABLE_router,
355 });
356 const StackView = V5StackView;
357 return (
358 <NavigationContent>
359 <StackView
360 {...rest}
361 state={state}
362 describe={describe}
363 descriptors={descriptors}
364 navigation={navigation}
365 />
366 </NavigationContent>
367 );
368}
369
370function V5StackNavigator(props: NativeStackNavigatorProps) {
371 return <V5Navigator {...props} />;
372}
373
374type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
375 NativeStackTypeBag<ParamList, NavigatorID>,
376 "Navigator"
377> & { Navigator: typeof V5StackNavigator };
378export function createV5StackNavigator<
379 const ParamList extends ParamListBase,
380 const NavigatorID extends string | undefined = string | undefined,
381 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
382 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
383>(config?: Config): TypedNavigator<TypeBag, Config> {
384 return createNavigatorFactory(V5StackNavigator)(config);
385}