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 { useCallback, useRef, useState, type ComponentProps } from "react";
24import { StyleSheet, View } from "react-native";
25import { FormSheet, Stack } from "react-native-screens";
26import { NativeScrollEdgeEffectsContext } from "./NativeScrollViewMarker";
27import { V5StackHeader } from "./V5StackHeader.ios";
28import type { AppNativeStackNavigationOptions } from "./StackHeader";
29import { NativeColumnContent } from "./NativeColumnContent.ios";
30import {
31 nativeStackPopAction,
32 nativeWorkspacePopAction,
33 nativeWorkspacePopCount,
34 partitionStackPresentations,
35 reconcileStackScreens,
36} from "./workspace-stack-projection";
37
38export type V5StackViewProps = ComponentProps<typeof NativeStackView>;
39
40export function modalEnvelopeOptions(options: NativeStackNavigationOptions) {
41 return {
42 ...Object.fromEntries(
43 Object.entries(options).filter(
44 ([key]) =>
45 !key.startsWith("header") &&
46 !key.startsWith("unstable_header") &&
47 key !== "unstable_navigationItemStyle",
48 ),
49 ),
50 headerShown: false,
51 };
52}
53
54/** Keep outgoing screens until UIKit completes its pop, as required by v5. */
55export function V5CardStackView(
56 props: V5StackViewProps & { readonly onRootVisibilityChange?: (visible: boolean) => void },
57) {
58 const { preventedRoutes } = usePreventRemoveContext();
59 const nativePopSource = useRef<string | null>(null);
60 const [screens, setScreens] = useState({
61 completedNativeDismissals: new Set<string>(),
62 nativeCompletingPops: new Set<string>(),
63 routes: props.state.routes,
64 descriptors: props.descriptors,
65 observedRoutes: props.state.routes,
66 observedDescriptors: props.descriptors,
67 });
68 if (
69 screens.observedRoutes !== props.state.routes ||
70 screens.observedDescriptors !== props.descriptors
71 ) {
72 const routes = reconcileStackScreens(
73 screens.routes,
74 props.state.routes,
75 screens.completedNativeDismissals,
76 );
77 const active = new Set(props.state.routes.map((route) => route.key));
78 const retainedKeys = new Set(routes.map((route) => route.key));
79 setScreens({
80 nativeCompletingPops: new Set(
81 [...screens.nativeCompletingPops].filter((key) => retainedKeys.has(key)),
82 ),
83 completedNativeDismissals: new Set(
84 [...screens.completedNativeDismissals].filter((key) => active.has(key)),
85 ),
86 routes,
87 descriptors: Object.fromEntries(
88 Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>
89 retainedKeys.has(key),
90 ),
91 ),
92 observedRoutes: props.state.routes,
93 observedDescriptors: props.descriptors,
94 });
95 }
96 // Keep the real descriptor through dismissal. describe(route, true) creates
97 // a placeholder whose navigation rejects setOptions and dispatches.
98 const nativeDismiss = useCallback(
99 (key: string) => {
100 const state = props.navigation.getState();
101 const attached = state.routes.some((route) => route.key === key);
102 setScreens((current) => {
103 const completedNativeDismissals = new Set(current.completedNativeDismissals);
104 const nativeCompletingPops = new Set(current.nativeCompletingPops);
105 nativeCompletingPops.delete(key);
106 if (attached) {
107 completedNativeDismissals.add(key);
108 return { ...current, completedNativeDismissals, nativeCompletingPops };
109 }
110 // A delayed callback needs immediate cleanup: the router already
111 // removed the route, so no further router update will follow.
112 completedNativeDismissals.delete(key);
113 const descriptors = { ...current.descriptors };
114 delete descriptors[key];
115 return {
116 ...current,
117 completedNativeDismissals,
118 nativeCompletingPops,
119 routes: current.routes.filter((route) => route.key !== key),
120 descriptors,
121 };
122 });
123 if (nativePopSource.current === key) nativePopSource.current = null;
124 const action = nativeStackPopAction(state, key);
125 if (action) props.navigation.dispatch(action);
126 },
127 [props.navigation, setScreens],
128 );
129 const removeDismissed = useCallback(
130 (key: string) => {
131 if (!props.navigation.getState().routes.some((route) => route.key === key)) {
132 setScreens((current) => {
133 const descriptors = { ...current.descriptors };
134 delete descriptors[key];
135 return {
136 ...current,
137 routes: current.routes.filter((route) => route.key !== key),
138 descriptors,
139 };
140 });
141 }
142 },
143 [props.navigation, setScreens],
144 );
145 return (
146 <View className="flex-1 bg-screen">
147 <Stack.Host>
148 {screens.routes.map((route, index) => {
149 const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
150 if (!descriptor) return null;
151 const attached = props.state.routes.some((current) => current.key === route.key);
152 return (
153 <Stack.Screen
154 key={route.key}
155 screenKey={route.key}
156 activityMode={
157 attached || screens.nativeCompletingPops.has(route.key) ? "attached" : "detached"
158 }
159 preventNativeDismiss={
160 preventedRoutes[route.key]?.preventRemove ||
161 descriptor.options.gestureEnabled === false
162 }
163 onDismiss={removeDismissed}
164 onNativeDismiss={nativeDismiss}
165 onNativeDismissPrevented={() => {
166 if (preventedRoutes[route.key]?.preventRemove) descriptor.navigation.goBack();
167 }}
168 onWillAppear={() => {
169 if (index === 0) props.onRootVisibilityChange?.(true);
170 props.navigation.emit({
171 type: "transitionStart",
172 target: route.key,
173 data: { closing: false },
174 });
175 }}
176 onDidAppear={() => {
177 const source = nativePopSource.current;
178 if (source === route.key) {
179 nativePopSource.current = null;
180 } else if (source) {
181 const state = props.navigation.getState();
182 const action = nativeStackPopAction(state, source, route.key);
183 if (action) {
184 const sourceIndex = state.routes.findIndex((current) => current.key === source);
185 // UIKit owns this pop. Keep these children attached until its
186 // dismissal callback, so the early router update cannot enqueue a second pop.
187 const poppedKeys = state.routes
188 .slice(sourceIndex - action.payload.count + 1, sourceIndex + 1)
189 .map((popped) => popped.key);
190 setScreens((current) => ({
191 ...current,
192 nativeCompletingPops: new Set([
193 ...current.nativeCompletingPops,
194 ...poppedKeys,
195 ]),
196 }));
197 nativePopSource.current = null;
198 props.navigation.dispatch(action);
199 }
200 }
201 props.navigation.emit({
202 type: "transitionEnd",
203 target: route.key,
204 data: { closing: false },
205 });
206 }}
207 onWillDisappear={() => {
208 if (index === 0) props.onRootVisibilityChange?.(false);
209 const state = props.navigation.getState();
210 // JS pushes/pops already changed history. Only native Back leaves
211 // the disappearing card at the router's active index.
212 if (state.index > 0 && state.routes[state.index]?.key === route.key) {
213 nativePopSource.current = route.key;
214 }
215 props.navigation.emit({
216 type: "transitionStart",
217 target: route.key,
218 data: { closing: true },
219 });
220 }}
221 onDidDisappear={() =>
222 props.navigation.emit({
223 type: "transitionEnd",
224 target: route.key,
225 data: { closing: true },
226 })
227 }
228 >
229 <NavigationContext value={descriptor.navigation}>
230 <NavigationRouteContext value={descriptor.route}>
231 <V5StackHeader
232 options={descriptor.options}
233 canGoBack={
234 attached
235 ? props.state.routes.findIndex((current) => current.key === route.key) > 0
236 : index > 0
237 }
238 />
239 <NativeColumnContent
240 insetHorizontally={
241 (descriptor.options as AppNativeStackNavigationOptions)
242 .nativeContentInsetHorizontally
243 }
244 >
245 <NativeScrollEdgeEffectsContext value={descriptor.options.scrollEdgeEffects}>
246 {descriptor.render()}
247 </NativeScrollEdgeEffectsContext>
248 </NativeColumnContent>
249 </NavigationRouteContext>
250 </NavigationContext>
251 </Stack.Screen>
252 );
253 })}
254 </Stack.Host>
255 </View>
256 );
257}
258
259export function V5StackView(props: V5StackViewProps) {
260 const groups = partitionStackPresentations(props.state.routes, (route) => {
261 const presentation = props.descriptors[route.key]?.options.presentation;
262 return (
263 ["SettingsSheet", "NewTaskSheet"].includes(route.name) ||
264 (presentation !== undefined && presentation !== "card")
265 );
266 });
267 const routes = groups.map((group) => group[0]!);
268 const descriptors = Object.fromEntries(
269 groups.map((group) => {
270 const first = group[0]!;
271 const descriptor = props.descriptors[first.key]!;
272 const visibleRoute = group.at(-1)!;
273 return [
274 first.key,
275 {
276 ...descriptor,
277 navigation: props.descriptors[visibleRoute.key]!.navigation,
278 route: visibleRoute,
279 options: modalEnvelopeOptions(descriptor.options),
280 render: () => (
281 <V5CardStackView
282 {...props}
283 state={{
284 ...props.state,
285 routes: group,
286 index: group.length - 1,
287 preloadedRoutes: [],
288 }}
289 />
290 ),
291 },
292 ];
293 }),
294 );
295 return (
296 <NativeStackView
297 presentationEnvelope
298 {...props}
299 descriptors={descriptors}
300 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
301 />
302 );
303}
304
305export function V5SheetStackView(props: V5StackViewProps) {
306 const { preventedRoutes } = usePreventRemoveContext();
307 const groups = partitionStackPresentations(
308 props.state.routes,
309 (route) => props.descriptors[route.key]?.options.presentation === "formSheet",
310 );
311 const [retained, setRetained] = useState({
312 groups: groups.slice(1),
313 descriptors: props.descriptors,
314 observedRoutes: props.state.routes,
315 observedDescriptors: props.descriptors,
316 });
317 if (
318 retained.observedRoutes !== props.state.routes ||
319 retained.observedDescriptors !== props.descriptors
320 ) {
321 const active = new Set(groups.slice(1).map((group) => group[0]!.key));
322 const sheets = [
323 ...groups.slice(1),
324 ...retained.groups.filter((group) => !active.has(group[0]!.key)),
325 ];
326 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
327 setRetained({
328 groups: sheets,
329 descriptors: Object.fromEntries(
330 Object.entries({ ...retained.descriptors, ...props.descriptors }).filter(([key]) =>
331 sheetKeys.has(key),
332 ),
333 ),
334 observedRoutes: props.state.routes,
335 observedDescriptors: props.descriptors,
336 });
337 }
338 const removeSheet = (key: string) => {
339 setRetained((current) => {
340 const sheets = current.groups.filter((group) => group[0]!.key !== key);
341 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
342 return {
343 ...current,
344 groups: sheets,
345 descriptors: Object.fromEntries(
346 Object.entries(current.descriptors).filter(([routeKey]) => sheetKeys.has(routeKey)),
347 ),
348 };
349 });
350 };
351 const base = groups[0] ?? [];
352 return (
353 <View className="flex-1 bg-screen">
354 <V5CardStackView
355 {...props}
356 state={{ ...props.state, routes: base, index: base.length - 1, preloadedRoutes: [] }}
357 />
358 {retained.groups.map((group) => {
359 const first = group[0]!;
360 const descriptor = props.descriptors[first.key] ?? retained.descriptors[first.key];
361 if (!descriptor) return null;
362 const options = descriptor.options;
363 const attached = nativeWorkspacePopCount(props.state, first.key) > 0;
364 return (
365 <FormSheet
366 key={first.key}
367 isOpen={attached}
368 detents={options.sheetAllowedDetents}
369 initialDetentIndex={options.sheetInitialDetentIndex}
370 largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex}
371 prefersGrabberVisible={options.sheetGrabberVisible}
372 preferredCornerRadius={options.sheetCornerRadius}
373 prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge}
374 nativeContainerStyle={{
375 backgroundColor: StyleSheet.flatten(options.contentStyle)?.backgroundColor,
376 }}
377 preventNativeDismiss={
378 group.some((route) => preventedRoutes[route.key]?.preventRemove) ||
379 options.gestureEnabled === false
380 }
381 onNativeDismissPrevented={() => {
382 const guarded = group.findLast((route) => preventedRoutes[route.key]?.preventRemove);
383 if (guarded) {
384 const state = props.navigation.getState();
385 const action = nativeWorkspacePopAction(state, first.key);
386 if (action) props.navigation.dispatch(action);
387 }
388 }}
389 onDismiss={() => removeSheet(first.key)}
390 onNativeDismiss={() => {
391 const state = props.navigation.getState();
392 const action = nativeWorkspacePopAction(state, first.key);
393 if (action) props.navigation.dispatch(action);
394 removeSheet(first.key);
395 }}
396 >
397 <V5CardStackView
398 {...props}
399 descriptors={{ ...retained.descriptors, ...props.descriptors }}
400 state={{
401 ...props.state,
402 routes: group,
403 index: group.length - 1,
404 preloadedRoutes: [],
405 }}
406 />
407 </FormSheet>
408 );
409 })}
410 </View>
411 );
412}
413
414function V5Navigator({
415 nativeSheets,
416 id,
417 initialRouteName,
418 UNSTABLE_routeNamesChangeBehavior,
419 children,
420 layout,
421 screenListeners,
422 screenOptions,
423 screenLayout,
424 UNSTABLE_router,
425 ...rest
426}: NativeStackNavigatorProps & { readonly nativeSheets?: boolean }) {
427 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
428 StackNavigationState<ParamListBase>,
429 StackRouterOptions,
430 StackActionHelpers<ParamListBase>,
431 NativeStackNavigationOptions,
432 NativeStackNavigationEventMap
433 >(StackRouter, {
434 id,
435 initialRouteName,
436 UNSTABLE_routeNamesChangeBehavior,
437 children,
438 layout,
439 screenListeners,
440 screenOptions,
441 screenLayout,
442 UNSTABLE_router,
443 });
444 const StackView = nativeSheets ? V5SheetStackView : V5StackView;
445 return (
446 <NavigationContent>
447 <StackView
448 {...rest}
449 state={state}
450 describe={describe}
451 descriptors={descriptors}
452 navigation={navigation}
453 />
454 </NavigationContent>
455 );
456}
457
458function V5StackNavigator(props: NativeStackNavigatorProps) {
459 return <V5Navigator {...props} />;
460}
461
462function V5SheetStackNavigator(props: NativeStackNavigatorProps) {
463 return <V5Navigator {...props} nativeSheets />;
464}
465
466type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
467 NativeStackTypeBag<ParamList, NavigatorID>,
468 "Navigator"
469> & { Navigator: typeof V5StackNavigator };
470export function createV5StackNavigator<
471 const ParamList extends ParamListBase,
472 const NavigatorID extends string | undefined = string | undefined,
473 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
474 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
475>(config?: Config): TypedNavigator<TypeBag, Config> {
476 return createNavigatorFactory(V5StackNavigator)(config);
477}
478
479export function createV5SheetStackNavigator<
480 const ParamList extends ParamListBase,
481 const NavigatorID extends string | undefined = string | undefined,
482 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
483 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
484>(config?: Config): TypedNavigator<TypeBag, Config> {
485 return createNavigatorFactory(V5SheetStackNavigator)(config);
486}