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