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

createV5StackNavigator.ios.tsx

473 lines17.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 { 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 };
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 );
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 presentationEnvelope
283 {...props}
284 descriptors={descriptors}
285 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
286 />
287 );
289​
290/** Keep a direct card host mounted while v5 form sheets present above it. */
291export function V5SheetStackView(props: V5StackViewProps) {
292 const { preventedRoutes } = usePreventRemoveContext();
293 const groups = partitionStackPresentations(
294 props.state.routes,
295 (route) => props.descriptors[route.key]?.options.presentation === "formSheet",
296 );
297 const [retained, setRetained] = useState({
298 groups: groups.slice(1),
299 descriptors: props.descriptors,
300 observedRoutes: props.state.routes,
301 observedDescriptors: props.descriptors,
302 });
303 if (
304 retained.observedRoutes !== props.state.routes ||
305 retained.observedDescriptors !== props.descriptors
306 ) {
307 const active = new Set(groups.slice(1).map((group) => group[0]!.key));
308 const sheets = [
309 ...groups.slice(1),
310 ...retained.groups.filter((group) => !active.has(group[0]!.key)),
311 ];
312 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
313 setRetained({
314 groups: sheets,
315 descriptors: Object.fromEntries(
316 Object.entries({ ...retained.descriptors, ...props.descriptors }).filter(([key]) =>
317 sheetKeys.has(key),
318 ),
319 ),
320 observedRoutes: props.state.routes,
321 observedDescriptors: props.descriptors,
322 });
323 }
324 const removeSheet = (key: string) => {
325 setRetained((current) => {
326 const sheets = current.groups.filter((group) => group[0]!.key !== key);
327 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
328 return {
329 ...current,
330 groups: sheets,
331 descriptors: Object.fromEntries(
332 Object.entries(current.descriptors).filter(([routeKey]) => sheetKeys.has(routeKey)),
333 ),
334 };
335 });
336 };
337 const base = groups[0] ?? [];
338 return (
339 <View className="flex-1 bg-screen">
340 <V5CardStackView
341 {...props}
342 state={{ ...props.state, routes: base, index: base.length - 1, preloadedRoutes: [] }}
343 />
344 {retained.groups.map((group) => {
345 const first = group[0]!;
346 const descriptor = props.descriptors[first.key] ?? retained.descriptors[first.key];
347 if (!descriptor) return null;
348 const options = descriptor.options;
349 const attached = nativeWorkspacePopCount(props.state, first.key) > 0;
350 return (
351 <FormSheet
352 key={first.key}
353 isOpen={attached}
354 detents={options.sheetAllowedDetents}
355 initialDetentIndex={options.sheetInitialDetentIndex}
356 largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex}
357 prefersGrabberVisible={options.sheetGrabberVisible}
358 preferredCornerRadius={options.sheetCornerRadius}
359 prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge}
360 nativeContainerStyle={{
361 backgroundColor: StyleSheet.flatten(options.contentStyle)?.backgroundColor,
362 }}
363 preventNativeDismiss={
364 group.some((route) => preventedRoutes[route.key]?.preventRemove) ||
365 options.gestureEnabled === false
366 }
367 onNativeDismissPrevented={() => {
368 const guarded = group.findLast((route) => preventedRoutes[route.key]?.preventRemove);
369 if (guarded) {
370 const state = props.navigation.getState();
371 const action = nativeWorkspacePopAction(state, first.key);
372 if (action) props.navigation.dispatch(action);
373 }
374 }}
375 onDismiss={() => removeSheet(first.key)}
376 onNativeDismiss={() => {
377 const state = props.navigation.getState();
378 const action = nativeWorkspacePopAction(state, first.key);
379 if (action) props.navigation.dispatch(action);
380 removeSheet(first.key);
381 }}
382 >
383 <V5CardStackView
384 {...props}
385 descriptors={{ ...retained.descriptors, ...props.descriptors }}
386 state={{
387 ...props.state,
388 routes: group,
389 index: group.length - 1,
390 preloadedRoutes: [],
391 }}
392 />
393 </FormSheet>
394 );
395 })}
396 </View>
397 );
399​
400function V5Navigator({
401 nativeSheets,
402 id,
403 initialRouteName,
404 UNSTABLE_routeNamesChangeBehavior,
405 children,
406 layout,
407 screenListeners,
408 screenOptions,
409 screenLayout,
410 UNSTABLE_router,
411 ...rest
412}: NativeStackNavigatorProps & { readonly nativeSheets?: boolean }) {
413 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
414 StackNavigationState<ParamListBase>,
415 StackRouterOptions,
416 StackActionHelpers<ParamListBase>,
417 NativeStackNavigationOptions,
418 NativeStackNavigationEventMap
419 >(StackRouter, {
420 id,
421 initialRouteName,
422 UNSTABLE_routeNamesChangeBehavior,
423 children,
424 layout,
425 screenListeners,
426 screenOptions,
427 screenLayout,
428 UNSTABLE_router,
429 });
430 const StackView = nativeSheets ? V5SheetStackView : V5StackView;
431 return (
432 <NavigationContent>
433 <StackView
434 {...rest}
435 state={state}
436 describe={describe}
437 descriptors={descriptors}
438 navigation={navigation}
439 />
440 </NavigationContent>
441 );
443​
444function V5StackNavigator(props: NativeStackNavigatorProps) {
445 return <V5Navigator {...props} />;
447​
448function V5SheetStackNavigator(props: NativeStackNavigatorProps) {
449 return <V5Navigator {...props} nativeSheets />;
451​
452type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
453 NativeStackTypeBag<ParamList, NavigatorID>,
454 "Navigator"
455> & { Navigator: typeof V5StackNavigator };
456export function createV5StackNavigator<
457 const ParamList extends ParamListBase,
458 const NavigatorID extends string | undefined = string | undefined,
459 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
460 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
461>(config?: Config): TypedNavigator<TypeBag, Config> {
462 return createNavigatorFactory(V5StackNavigator)(config);
464​
465/** For navigators whose presentations are cards and form sheets only. */
466export function createV5SheetStackNavigator<
467 const ParamList extends ParamListBase,
468 const NavigatorID extends string | undefined = string | undefined,
469 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
470 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
471>(config?: Config): TypedNavigator<TypeBag, Config> {
472 return createNavigatorFactory(V5SheetStackNavigator)(config);