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

createV5StackNavigator.ios.tsx

422 lines14.5 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, 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 nativeWorkspacePopAction,
30 nativeWorkspacePopCount,
31 partitionStackPresentations,
32 reconcileStackScreens,
33} from "./workspace-stack-projection";
34​
35export type V5StackViewProps = ComponentProps<typeof NativeStackView>;
36​
37/** The presentation envelope must not mount a second search bar or header. */
38export function modalEnvelopeOptions(options: NativeStackNavigationOptions) {
39 return {
40 ...Object.fromEntries(
41 Object.entries(options).filter(
42 ([key]) =>
43 !key.startsWith("header") &&
44 !key.startsWith("unstable_header") &&
45 key !== "unstable_navigationItemStyle",
46 ),
47 ),
48 headerShown: false,
49 };
51​
52/** Keep outgoing screens until UIKit completes its pop, as required by v5. */
53export function V5CardStackView(props: V5StackViewProps) {
54 const { preventedRoutes } = usePreventRemoveContext();
55 const [screens, setScreens] = useState({
56 completedNativeDismissals: new Set<string>(),
57 routes: props.state.routes,
58 descriptors: props.descriptors,
59 observedRoutes: props.state.routes,
60 observedDescriptors: props.descriptors,
61 });
62 if (
63 screens.observedRoutes !== props.state.routes ||
64 screens.observedDescriptors !== props.descriptors
65 ) {
66 const routes = reconcileStackScreens(
67 screens.routes,
68 props.state.routes,
69 screens.completedNativeDismissals,
70 );
71 const active = new Set(props.state.routes.map((route) => route.key));
72 const retainedKeys = new Set(routes.map((route) => route.key));
73 setScreens({
74 completedNativeDismissals: new Set(
75 [...screens.completedNativeDismissals].filter((key) => active.has(key)),
76 ),
77 routes,
78 descriptors: Object.fromEntries(
79 Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>
80 retainedKeys.has(key),
81 ),
82 ),
83 observedRoutes: props.state.routes,
84 observedDescriptors: props.descriptors,
85 });
86 }
87 // Keep the real descriptor through dismissal. describe(route, true) creates
88 // a placeholder whose navigation rejects setOptions and dispatches.
89 const nativeDismiss = useCallback(
90 (key: string) => {
91 const state = props.navigation.getState();
92 const attached = state.routes.some((route) => route.key === key);
93 setScreens((current) => {
94 const completedNativeDismissals = new Set(current.completedNativeDismissals);
95 if (attached) {
96 completedNativeDismissals.add(key);
97 return { ...current, completedNativeDismissals };
98 }
99 // A delayed callback needs immediate cleanup: the router already
100 // removed the route, so no further router update will follow.
101 completedNativeDismissals.delete(key);
102 const descriptors = { ...current.descriptors };
103 delete descriptors[key];
104 return {
105 ...current,
106 completedNativeDismissals,
107 routes: current.routes.filter((route) => route.key !== key),
108 descriptors,
109 };
110 });
111 const action = nativeWorkspacePopAction(state, key);
112 if (action) props.navigation.dispatch(action);
113 },
114 [props.navigation, setScreens],
115 );
116 const removeDismissed = useCallback(
117 (key: string) => {
118 if (!props.navigation.getState().routes.some((route) => route.key === key)) {
119 setScreens((current) => {
120 const descriptors = { ...current.descriptors };
121 delete descriptors[key];
122 return {
123 ...current,
124 routes: current.routes.filter((route) => route.key !== key),
125 descriptors,
126 };
127 });
128 }
129 },
130 [props.navigation, setScreens],
131 );
132 return (
133 <View className="flex-1 bg-screen">
134 <Stack.Host>
135 {screens.routes.map((route, index) => {
136 const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
137 if (!descriptor) return null;
138 const attached = props.state.routes.some((current) => current.key === route.key);
139 return (
140 <Stack.Screen
141 key={route.key}
142 screenKey={route.key}
143 activityMode={attached ? "attached" : "detached"}
144 preventNativeDismiss={
145 preventedRoutes[route.key]?.preventRemove ||
146 descriptor.options.gestureEnabled === false
147 }
148 onDismiss={removeDismissed}
149 onNativeDismiss={nativeDismiss}
150 onNativeDismissPrevented={() => {
151 if (preventedRoutes[route.key]?.preventRemove) descriptor.navigation.goBack();
152 }}
153 onWillAppear={() =>
154 props.navigation.emit({
155 type: "transitionStart",
156 target: route.key,
157 data: { closing: false },
158 })
159 }
160 onDidAppear={() =>
161 props.navigation.emit({
162 type: "transitionEnd",
163 target: route.key,
164 data: { closing: false },
165 })
166 }
167 onWillDisappear={() =>
168 props.navigation.emit({
169 type: "transitionStart",
170 target: route.key,
171 data: { closing: true },
172 })
173 }
174 onDidDisappear={() =>
175 props.navigation.emit({
176 type: "transitionEnd",
177 target: route.key,
178 data: { closing: true },
179 })
180 }
181 >
182 <NavigationContext value={descriptor.navigation}>
183 <NavigationRouteContext value={descriptor.route}>
184 <V5StackHeader options={descriptor.options} canGoBack={index > 0} />
185 <NativeColumnContent>{descriptor.render()}</NativeColumnContent>
186 </NavigationRouteContext>
187 </NavigationContext>
188 </Stack.Screen>
189 );
190 })}
191 </Stack.Host>
192 </View>
193 );
195​
196/** v5 owns pushes and headers; the legacy renderer only presents modal groups. */
197export function V5StackView(props: V5StackViewProps) {
198 const groups = partitionStackPresentations(props.state.routes, (route) => {
199 const presentation = props.descriptors[route.key]?.options.presentation;
200 return (
201 ["SettingsSheet", "NewTaskSheet"].includes(route.name) ||
202 (presentation !== undefined && presentation !== "card")
203 );
204 });
205 const routes = groups.map((group) => group[0]!);
206 const descriptors = Object.fromEntries(
207 groups.map((group) => {
208 const first = group[0]!;
209 const descriptor = props.descriptors[first.key]!;
210 return [
211 first.key,
212 {
213 ...descriptor,
214 options: modalEnvelopeOptions(descriptor.options),
215 render: () => (
216 <V5CardStackView
217 {...props}
218 state={{
219 ...props.state,
220 routes: group,
221 index: group.length - 1,
222 preloadedRoutes: [],
223 }}
224 />
225 ),
226 },
227 ];
228 }),
229 );
230 return (
231 <NativeStackView
232 {...props}
233 descriptors={descriptors}
234 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
235 />
236 );
238​
239/** Keep a direct card host mounted while v5 form sheets present above it. */
240export function V5SheetStackView(props: V5StackViewProps) {
241 const { preventedRoutes } = usePreventRemoveContext();
242 const groups = partitionStackPresentations(
243 props.state.routes,
244 (route) => props.descriptors[route.key]?.options.presentation === "formSheet",
245 );
246 const [retained, setRetained] = useState({
247 groups: groups.slice(1),
248 descriptors: props.descriptors,
249 observedRoutes: props.state.routes,
250 observedDescriptors: props.descriptors,
251 });
252 if (
253 retained.observedRoutes !== props.state.routes ||
254 retained.observedDescriptors !== props.descriptors
255 ) {
256 const active = new Set(groups.slice(1).map((group) => group[0]!.key));
257 const sheets = [
258 ...groups.slice(1),
259 ...retained.groups.filter((group) => !active.has(group[0]!.key)),
260 ];
261 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
262 setRetained({
263 groups: sheets,
264 descriptors: Object.fromEntries(
265 Object.entries({ ...retained.descriptors, ...props.descriptors }).filter(([key]) =>
266 sheetKeys.has(key),
267 ),
268 ),
269 observedRoutes: props.state.routes,
270 observedDescriptors: props.descriptors,
271 });
272 }
273 const removeSheet = (key: string) => {
274 setRetained((current) => {
275 const sheets = current.groups.filter((group) => group[0]!.key !== key);
276 const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
277 return {
278 ...current,
279 groups: sheets,
280 descriptors: Object.fromEntries(
281 Object.entries(current.descriptors).filter(([routeKey]) => sheetKeys.has(routeKey)),
282 ),
283 };
284 });
285 };
286 const base = groups[0] ?? [];
287 return (
288 <View className="flex-1 bg-screen">
289 <V5CardStackView
290 {...props}
291 state={{ ...props.state, routes: base, index: base.length - 1, preloadedRoutes: [] }}
292 />
293 {retained.groups.map((group) => {
294 const first = group[0]!;
295 const descriptor = props.descriptors[first.key] ?? retained.descriptors[first.key];
296 if (!descriptor) return null;
297 const options = descriptor.options;
298 const attached = nativeWorkspacePopCount(props.state, first.key) > 0;
299 return (
300 <FormSheet
301 key={first.key}
302 isOpen={attached}
303 detents={options.sheetAllowedDetents}
304 initialDetentIndex={options.sheetInitialDetentIndex}
305 largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex}
306 prefersGrabberVisible={options.sheetGrabberVisible}
307 preferredCornerRadius={options.sheetCornerRadius}
308 prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge}
309 nativeContainerStyle={{
310 backgroundColor: StyleSheet.flatten(options.contentStyle)?.backgroundColor,
311 }}
312 preventNativeDismiss={
313 group.some((route) => preventedRoutes[route.key]?.preventRemove) ||
314 options.gestureEnabled === false
315 }
316 onNativeDismissPrevented={() => {
317 const guarded = group.findLast((route) => preventedRoutes[route.key]?.preventRemove);
318 if (guarded) {
319 const state = props.navigation.getState();
320 const action = nativeWorkspacePopAction(state, first.key);
321 if (action) props.navigation.dispatch(action);
322 }
323 }}
324 onDismiss={() => removeSheet(first.key)}
325 onNativeDismiss={() => {
326 const state = props.navigation.getState();
327 const action = nativeWorkspacePopAction(state, first.key);
328 if (action) props.navigation.dispatch(action);
329 removeSheet(first.key);
330 }}
331 >
332 <V5CardStackView
333 {...props}
334 descriptors={{ ...retained.descriptors, ...props.descriptors }}
335 state={{
336 ...props.state,
337 routes: group,
338 index: group.length - 1,
339 preloadedRoutes: [],
340 }}
341 />
342 </FormSheet>
343 );
344 })}
345 </View>
346 );
348​
349function V5Navigator({
350 nativeSheets,
351 id,
352 initialRouteName,
353 UNSTABLE_routeNamesChangeBehavior,
354 children,
355 layout,
356 screenListeners,
357 screenOptions,
358 screenLayout,
359 UNSTABLE_router,
360 ...rest
361}: NativeStackNavigatorProps & { readonly nativeSheets?: boolean }) {
362 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
363 StackNavigationState<ParamListBase>,
364 StackRouterOptions,
365 StackActionHelpers<ParamListBase>,
366 NativeStackNavigationOptions,
367 NativeStackNavigationEventMap
368 >(StackRouter, {
369 id,
370 initialRouteName,
371 UNSTABLE_routeNamesChangeBehavior,
372 children,
373 layout,
374 screenListeners,
375 screenOptions,
376 screenLayout,
377 UNSTABLE_router,
378 });
379 const StackView = nativeSheets ? V5SheetStackView : V5StackView;
380 return (
381 <NavigationContent>
382 <StackView
383 {...rest}
384 state={state}
385 describe={describe}
386 descriptors={descriptors}
387 navigation={navigation}
388 />
389 </NavigationContent>
390 );
392​
393function V5StackNavigator(props: NativeStackNavigatorProps) {
394 return <V5Navigator {...props} />;
396​
397function V5SheetStackNavigator(props: NativeStackNavigatorProps) {
398 return <V5Navigator {...props} nativeSheets />;
400​
401type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
402 NativeStackTypeBag<ParamList, NavigatorID>,
403 "Navigator"
404> & { Navigator: typeof V5StackNavigator };
405export function createV5StackNavigator<
406 const ParamList extends ParamListBase,
407 const NavigatorID extends string | undefined = string | undefined,
408 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
409 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
410>(config?: Config): TypedNavigator<TypeBag, Config> {
411 return createNavigatorFactory(V5StackNavigator)(config);
413​
414/** For navigators whose presentations are cards and form sheets only. */
415export function createV5SheetStackNavigator<
416 const ParamList extends ParamListBase,
417 const NavigatorID extends string | undefined = string | undefined,
418 const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
419 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
420>(config?: Config): TypedNavigator<TypeBag, Config> {
421 return createNavigatorFactory(V5SheetStackNavigator)(config);