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

createV5StackNavigator.ios.tsx

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