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

createV5StackNavigator.ios.tsx

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