The best way to control Claude Code, Codex and more from any computer or phone

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