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

createV5StackNavigator.ios.tsx

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