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