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