Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

createV5StackNavigator.ios.tsx

489 lines17.7 KB

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 };
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 backgroundColor={
241 StyleSheet.flatten(descriptor.options.contentStyle)?.backgroundColor
242 }
243 insetHorizontally={
244 (descriptor.options as AppNativeStackNavigationOptions)
245 .nativeContentInsetHorizontally
246 }
247 >
248 <NativeScrollEdgeEffectsContext value={descriptor.options.scrollEdgeEffects}>
249 {descriptor.render()}
250 </NativeScrollEdgeEffectsContext>
251 </NativeColumnContent>
252 </NavigationRouteContext>
253 </NavigationContext>
254 </Stack.Screen>
255 );
256 })}
257 </Stack.Host>
258 </View>
259 );
261​
262export function V5StackView(props: V5StackViewProps) {
263 const groups = partitionStackPresentations(props.state.routes, (route) => {
264 const presentation = props.descriptors[route.key]?.options.presentation;
265 return (
266 route.name === "SettingsSheet" || (presentation !== undefined && presentation !== "card")
267 );
268 });
269 const routes = groups.map((group) => group[0]!);
270 const descriptors = Object.fromEntries(
271 groups.map((group) => {
272 const first = group[0]!;
273 const descriptor = props.descriptors[first.key]!;
274 const visibleRoute = group.at(-1)!;
275 return [
276 first.key,
277 {
278 ...descriptor,
279 navigation: props.descriptors[visibleRoute.key]!.navigation,
280 route: visibleRoute,
281 options: modalEnvelopeOptions(descriptor.options),
282 render: () => (
283 <V5CardStackView
284 {...props}
285 state={{
286 ...props.state,
287 routes: group,
288 index: group.length - 1,
289 preloadedRoutes: [],
290 }}
291 />
292 ),
293 },
294 ];
295 }),
296 );
297 return (
298 <NativeStackView
299 presentationEnvelope
300 {...props}
301 descriptors={descriptors}
302 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
303 />
304 );
306​
307export function V5SheetStackView(props: V5StackViewProps) {
308 const { preventedRoutes } = usePreventRemoveContext();
309 const groups = partitionStackPresentations(
310 props.state.routes,
311 (route) => props.descriptors[route.key]?.options.presentation === "formSheet",
312 );
313 const [retained, setRetained] = useState({
314 groups: groups.slice(1),
315 descriptors: props.descriptors,
316 observedRoutes: props.state.routes,
317 observedDescriptors: props.descriptors,
318 });
319 if (
320 retained.observedRoutes !== props.state.routes ||
321 retained.observedDescriptors !== props.descriptors
322 ) {
323 const active = new Set(groups.slice(1).map((group) => group[0]!.key));
324 const sheets = [
325 ...groups.slice(1),
326 ...retained.groups.filter((group) => !active.has(group[0]!.key)),
327 ];
328 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
329 setRetained({
330 groups: sheets,
331 descriptors: Object.fromEntries(
332 Object.entries({ ...retained.descriptors, ...props.descriptors }).filter(([key]) =>
333 sheetKeys.has(key),
334 ),
335 ),
336 observedRoutes: props.state.routes,
337 observedDescriptors: props.descriptors,
338 });
339 }
340 const removeSheet = (key: string) => {
341 setRetained((current) => {
342 const sheets = current.groups.filter((group) => group[0]!.key !== key);
343 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
344 return {
345 ...current,
346 groups: sheets,
347 descriptors: Object.fromEntries(
348 Object.entries(current.descriptors).filter(([routeKey]) => sheetKeys.has(routeKey)),
349 ),
350 };
351 });
352 };
353 const base = groups[0] ?? [];
354 return (
355 <View className="flex-1 bg-screen">
356 <V5CardStackView
357 {...props}
358 state={{ ...props.state, routes: base, index: base.length - 1, preloadedRoutes: [] }}
359 />
360 {retained.groups.map((group) => {
361 const first = group[0]!;
362 const descriptor = props.descriptors[first.key] ?? retained.descriptors[first.key];
363 if (!descriptor) return null;
364 const options = descriptor.options;
365 const attached = nativeWorkspacePopCount(props.state, first.key) > 0;
366 return (
367 <FormSheet
368 key={first.key}
369 isOpen={attached}
370 detents={options.sheetAllowedDetents}
371 initialDetentIndex={options.sheetInitialDetentIndex}
372 largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex}
373 prefersGrabberVisible={options.sheetGrabberVisible}
374 prefersHorizontalBars={options.sheetPrefersHorizontalBars}
375 preferredCornerRadius={options.sheetCornerRadius}
376 prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge}
377 nativeContainerStyle={{
378 backgroundColor: StyleSheet.flatten(options.contentStyle)?.backgroundColor,
379 }}
380 preventNativeDismiss={
381 group.some((route) => preventedRoutes[route.key]?.preventRemove) ||
382 options.gestureEnabled === false
383 }
384 onNativeDismissPrevented={() => {
385 const guarded = group.findLast((route) => preventedRoutes[route.key]?.preventRemove);
386 if (guarded) {
387 const state = props.navigation.getState();
388 const action = nativeWorkspacePopAction(state, first.key);
389 if (action) props.navigation.dispatch(action);
390 }
391 }}
392 onDismiss={() => removeSheet(first.key)}
393 onNativeDismiss={() => {
394 const state = props.navigation.getState();
395 const action = nativeWorkspacePopAction(state, first.key);
396 if (action) props.navigation.dispatch(action);
397 removeSheet(first.key);
398 }}
399 >
400 <V5CardStackView
401 {...props}
402 descriptors={{ ...retained.descriptors, ...props.descriptors }}
403 state={{
404 ...props.state,
405 routes: group,
406 index: group.length - 1,
407 preloadedRoutes: [],
408 }}
409 />
410 </FormSheet>
411 );
412 })}
413 </View>
414 );
416​
417function V5Navigator({
418 nativeSheets,
419 id,
420 initialRouteName,
421 UNSTABLE_routeNamesChangeBehavior,
422 children,
423 layout,
424 screenListeners,
425 screenOptions,
426 screenLayout,
427 UNSTABLE_router,
428 ...rest
429}: NativeStackNavigatorProps & { readonly nativeSheets?: boolean }) {
430 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
431 StackNavigationState<ParamListBase>,
432 StackRouterOptions,
433 StackActionHelpers<ParamListBase>,
434 NativeStackNavigationOptions,
435 NativeStackNavigationEventMap
436 >(StackRouter, {
437 id,
438 initialRouteName,
439 UNSTABLE_routeNamesChangeBehavior,
440 children,
441 layout,
442 screenListeners,
443 screenOptions,
444 screenLayout,
445 UNSTABLE_router,
446 });
447 const StackView = nativeSheets ? V5SheetStackView : V5StackView;
448 return (
449 <NavigationContent>
450 <StackView
451 {...rest}
452 state={state}
453 describe={describe}
454 descriptors={descriptors}
455 navigation={navigation}
456 />
457 </NavigationContent>
458 );
460​
461function V5StackNavigator(props: NativeStackNavigatorProps) {
462 return <V5Navigator {...props} />;
464​
465function V5SheetStackNavigator(props: NativeStackNavigatorProps) {
466 return <V5Navigator {...props} nativeSheets />;
468​
469type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
470 NativeStackTypeBag<ParamList, NavigatorID>,
471 "Navigator"
472> & { Navigator: typeof V5StackNavigator };
473export function createV5StackNavigator<
474 const ParamList extends ParamListBase,
475 const NavigatorID extends string | undefined = string | undefined,
476 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
477 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
478>(config?: Config): TypedNavigator<TypeBag, Config> {
479 return createNavigatorFactory(V5StackNavigator)(config);
481​
482export function createV5SheetStackNavigator<
483 const ParamList extends ParamListBase,
484 const NavigatorID extends string | undefined = string | undefined,
485 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
486 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
487>(config?: Config): TypedNavigator<TypeBag, Config> {
488 return createNavigatorFactory(V5SheetStackNavigator)(config);