Open History to see the last commit
1import {
2 createNavigatorFactory,
3 NavigationContext,
4 NavigationRouteContext,
5 StackRouter,
6 useNavigationBuilder,
7 type NavigatorTypeBagBase,
8 type ParamListBase,
9 type StackActionHelpers,
10 type StackNavigationState,
11 type StackRouterOptions,
12 type StaticConfig,
13 type TypedNavigator,
14} from "@react-navigation/native";
15import {
16 NativeStackView,
17 type NativeStackNavigationEventMap,
18 type NativeStackNavigationOptions,
19 type NativeStackNavigatorProps,
20 type NativeStackTypeBag,
21} from "@react-navigation/native-stack";
22import {
23 Fragment,
24 use,
25 useCallback,
26 useEffect,
27 useMemo,
28 useRef,
29 useState,
30 type ComponentProps,
31} from "react";
32import { View } from "react-native";
33import { Split, type SplitHostCommands } from "react-native-screens";
34import { EnvironmentId, ThreadId } from "@t3tools/contracts";
35import { scopedThreadKey } from "../../lib/scopedEntities";
36import { WorkspaceTabsProvider, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
37import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios";
38import { workspaceUsesColumns } from "../workspace/workspace-tabs-state";
39import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation";
40import { workspaceRoutesOf } from "./workspace-overlay-routes";
41import { setNativelyPoppingWorkspaceRoute } from "../workspace/workspace-detail-selection";
42import { useWorkspaceSidebarHeaderItem } from "./useWorkspaceSidebarHeaderItem";
43import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics";
44
45import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
46import { WorkspaceEmptyDetail } from "./WorkspaceEmptyDetail";
47import { NativeColumnContent as ColumnContent } from "../../native/NativeColumnContent.ios";
48import {
49 modalEnvelopeOptions,
50 V5CardStackView,
51 V5StackView,
52} from "../../native/createV5StackNavigator.ios";
53import {
54 useNativeWorkspaceColumnsReady,
55 useNativeWorkspaceColumnsSupported,
56} from "../../native/NativeWorkspaceColumns";
57import { V5StackHeader } from "../../native/V5StackHeader.ios";
58import type { AppNativeStackNavigationOptions } from "../../native/StackHeader";
59import {
60 collapsedSplitTransition,
61 nativeWorkspacePopAction,
62 projectWorkspaceStack,
63 partitionStackPresentations,
64 reconcileStackScreens,
65 type CollapsedSplitColumn,
66} from "../../native/workspace-stack-projection";
67import {
68 NativePrimaryColumnContext,
69 NativeWorkspaceInspectorContext,
70 NativeWorkspaceModeContext,
71 WorkspaceSlotOptionsContext,
72 slotScreenOptions,
73} from "../../native/v5-workspace-context";
74
75type ViewProps = ComponentProps<typeof NativeStackView>;
76type Descriptor = ViewProps["descriptors"][string];
77type Route = ViewProps["state"]["routes"][number];
78
79const isPullRequestRoute = (route: Route) =>
80 route.name === "PullRequest" ||
81 route.name === "PullRequestFile" ||
82 route.name === "PullRequestFiles";
83
84/** Beside the list, the first Settings page shows on one native screen that swaps its content. */
85const SETTINGS_DETAIL_SCREEN = "settings-detail";
86
87function ColumnScreen(props: {
88 readonly descriptor: Descriptor;
89 readonly screenKey?: string;
90 readonly primary?: boolean;
91 readonly attached?: boolean;
92 readonly selectedThreadKey?: string | null;
93 readonly selectedPullRequestKey?: string | null;
94 readonly onDismiss: (routeKey: string, native: boolean) => void;
95 readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;
96 readonly onCompose?: () => void;
97 /** Settings pages don't draw their own sidebar toggle, unlike threads and pull requests. */
98 readonly sidebarToggle?: boolean;
99 readonly navigation: ViewProps["navigation"];
100}) {
101 const { descriptor } = props;
102 // Options a screen set inside this workspace tab slot, over its route's.
103 const slotOptions = slotScreenOptions(
104 use(WorkspaceSlotOptionsContext),
105 descriptor.route.key,
106 descriptor.options,
107 );
108 const sidebarItem = useWorkspaceSidebarHeaderItem();
109 // Swapping header components would unmount the native header config, which hides the bar.
110 const options =
111 props.sidebarToggle && !slotOptions.unstable_headerLeftItems
112 ? ({
113 ...slotOptions,
114 unstable_headerLeftItems: () => [sidebarItem],
115 } as AppNativeStackNavigationOptions as typeof slotOptions)
116 : slotOptions;
117 const [presented, setPresented] = useState(false);
118 const primaryColumn = useMemo(
119 () =>
120 props.primary
121 ? {
122 presented,
123 selectedThreadKey: props.selectedThreadKey ?? null,
124 selectedPullRequestKey: props.selectedPullRequestKey ?? null,
125 }
126 : null,
127 [props.primary, props.selectedThreadKey, props.selectedPullRequestKey, presented],
128 );
129 const key = descriptor.route.key;
130 return (
131 <Split.Screen
132 screenKey={props.screenKey ?? key}
133 activityMode={props.attached === false ? "detached" : "attached"}
134 onDismiss={(event) => {
135 props.onDismiss(key, event.nativeEvent.isNativeDismiss);
136 }}
137 onWillAppear={() => {
138 props.onAppearance("willAppear", key);
139 props.navigation.emit({ type: "transitionStart", target: key, data: { closing: false } });
140 }}
141 onDidAppear={() => {
142 setPresented(true);
143 props.onAppearance("didAppear", key);
144 props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: false } });
145 }}
146 onWillDisappear={() => {
147 setPresented(false);
148 props.onAppearance("willDisappear", key);
149 props.navigation.emit({ type: "transitionStart", target: key, data: { closing: true } });
150 }}
151 onDidDisappear={() =>
152 props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } })
153 }
154 >
155 <NavigationContext value={descriptor.navigation}>
156 <NavigationRouteContext value={descriptor.route}>
157 <V5StackHeader
158 options={options}
159 canGoBack={!props.primary}
160 column={props.primary ? "primary" : "detail"}
161 onCompose={
162 descriptor.route.params &&
163 "draft" in descriptor.route.params &&
164 descriptor.route.params.draft
165 ? undefined
166 : props.onCompose
167 }
168 />
169 <ColumnContent
170 primary={props.primary}
171 insetHorizontally={
172 (options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
173 }
174 >
175 <NativePrimaryColumnContext value={primaryColumn}>
176 {/* The Settings slot swaps pages here; its column keeps its measured insets. */}
177 <Fragment key={key}>{descriptor.render()}</Fragment>
178 </NativePrimaryColumnContext>
179 </ColumnContent>
180 </NavigationRouteContext>
181 </NavigationContext>
182 </Split.Screen>
183 );
184}
185
186function WorkspaceColumns(
187 props: ViewProps & { readonly primary: Route; readonly detail: Route[] },
188) {
189 const {
190 layout,
191 panes,
192 togglePrimarySidebar,
193 setPrimarySidebarVisible,
194 toggleAuxiliaryPane,
195 startNewTask,
196 openWorkspaceTab,
197 } = useAdaptiveWorkspaceLayout();
198 const deviceType = useDeviceType();
199 const settingsDetailIn = (detail: readonly Route[]) =>
200 layout.usesSplitView && detail[0] && isSettingsRoute(detail[0].name) ? detail[0] : undefined;
201 // Split screens must remain mounted while UIKit animates a detached route away.
202 const [screens, setScreens] = useState({
203 routes: props.detail,
204 descriptors: props.descriptors,
205 observedRoutes: props.detail,
206 observedDescriptors: props.descriptors,
207 completed: new Set<string>(),
208 });
209 if (
210 screens.observedRoutes !== props.detail ||
211 screens.observedDescriptors !== props.descriptors
212 ) {
213 const active = new Set(props.detail.map((route) => route.key));
214 const settingsSlot = settingsDetailIn(props.detail);
215 const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed).filter(
216 // The slot's native screen stays; the pages it showed, and any above them, just go.
217 (route) => !settingsSlot || active.has(route.key) || !isSettingsRoute(route.name),
218 );
219 const retained = new Set(routes.map((route) => route.key));
220 setScreens({
221 routes,
222 descriptors: Object.fromEntries(
223 Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>
224 retained.has(key),
225 ),
226 ),
227 observedRoutes: props.detail,
228 observedDescriptors: props.descriptors,
229 completed: new Set([...screens.completed].filter((key) => active.has(key))),
230 });
231 }
232
233 const workspaceTabs = useWorkspaceTabs();
234 const selectedTab = workspaceTabs?.state.selectedTab;
235 const settingsOpen = workspaceTabs?.settingsOpen ?? false;
236 const openNewTask = startNewTask;
237 // The cover detail rail needs room for thread tools above the fixed tabs.
238 // The unfolded Duo keeps compose in its detail bar.
239 const detailCompose =
240 deviceType === "duo-unfolded" && selectedTab !== "pullRequests" && !settingsOpen
241 ? openNewTask
242 : undefined;
243 const inspector = use(NativeWorkspaceInspectorContext);
244 const hostRef = useRef<SplitHostCommands>(null);
245 const activeDetailKey = props.detail.at(-1)?.key;
246 const compactColumn = activeDetailKey ? "secondary" : "primary";
247 const collapsed = useRef(!layout.usesSplitView);
248 const collapsedColumn = useRef<CollapsedSplitColumn>({ visible: compactColumn, leaving: null });
249 const threadParams = props.detail.findLast((route) => route.name === "Thread")?.params;
250 const pullRequestParams = props.detail.findLast(isPullRequestRoute)?.params;
251 const selectedPullRequestKey =
252 pullRequestParams &&
253 "environmentId" in pullRequestParams &&
254 "host" in pullRequestParams &&
255 "repository" in pullRequestParams &&
256 "number" in pullRequestParams &&
257 typeof pullRequestParams.environmentId === "string" &&
258 typeof pullRequestParams.host === "string" &&
259 typeof pullRequestParams.repository === "string" &&
260 typeof pullRequestParams.number === "number"
261 ? `${pullRequestParams.environmentId}:${pullRequestParams.host}:${pullRequestParams.repository}:${pullRequestParams.number}`
262 : null;
263 const selectedThreadKey =
264 threadParams &&
265 "environmentId" in threadParams &&
266 "threadId" in threadParams &&
267 typeof threadParams.environmentId === "string" &&
268 typeof threadParams.threadId === "string"
269 ? scopedThreadKey(
270 EnvironmentId.make(threadParams.environmentId),
271 ThreadId.make(threadParams.threadId),
272 )
273 : null;
274 const handleNativeDismiss = useCallback(
275 (key: string, native: boolean) => {
276 setScreens((current) => ({
277 ...current,
278 routes: current.routes.filter((route) => route.key !== key),
279 completed: new Set([...current.completed, key]),
280 }));
281 if (native) {
282 const state = props.navigation.getState();
283 const action = nativeWorkspacePopAction(state, key);
284 if (action) props.navigation.dispatch(action);
285 }
286 },
287 [props.navigation],
288 );
289 const followCollapsedSplit = (
290 type: "willAppear" | "didAppear" | "willDisappear",
291 key: string,
292 ) => {
293 if (!collapsed.current || layout.usesSplitView) return;
294 const transition = collapsedSplitTransition(
295 collapsedColumn.current,
296 { type, key },
297 props.navigation.getState(),
298 props.primary.key,
299 );
300 collapsedColumn.current = transition.column;
301 setNativelyPoppingWorkspaceRoute(transition.column.leaving);
302 if (transition.pop) props.navigation.dispatch(transition.pop);
303 };
304
305 useEffect(() => {
306 if (layout.usesSplitView || collapsedColumn.current.visible === compactColumn) return;
307 collapsedColumn.current = { ...collapsedColumn.current, visible: compactColumn };
308 hostRef.current?.show(compactColumn);
309 }, [compactColumn, layout.usesSplitView]);
310
311 const primary = props.descriptors[props.primary.key];
312 if (!primary) return null;
313 return (
314 <Split.Host
315 ref={hostRef}
316 testID="adaptive-workspace-layout"
317 preferredSplitBehavior={layout.primarySidebarOverlaysContent ? "overlay" : "tile"}
318 primaryBackgroundStyle={deviceType === "pad" ? "none" : "default"}
319 topColumnForCollapsing={compactColumn}
320 onCollapse={() => {
321 collapsed.current = true;
322 collapsedColumn.current = { visible: compactColumn, leaving: null };
323 setNativelyPoppingWorkspaceRoute(null);
324 }}
325 onExpand={() => {
326 collapsed.current = false;
327 setNativelyPoppingWorkspaceRoute(null);
328 // Native callbacks can outlive the render that created them, so decide from the live
329 // router state. An expanded split has columns, so its tab gets a page beside the list.
330 const live = props.navigation.getState();
331 const { workspace } = workspaceRoutesOf(live.routes.slice(0, live.index + 1));
332 if (workspace.some((route) => route.name !== "Home" && route.name !== "Settings")) return;
333 const tab = workspace.some((route) => route.name === "Settings")
334 ? "settings"
335 : (["threads", "pullRequests", "usage"] as const).find((candidate) =>
336 workspaceTabs?.isTabActive(candidate),
337 );
338 openWorkspaceTab(tab ?? "threads", { columns: true });
339 }}
340 preferredDisplayMode={
341 // UIKit applies the mode as a collapsed split expands, before the new width reaches JS, so a
342 // collapsed split already carries the sidebar the expanded one will show.
343 (layout.usesSplitView ? panes.primarySidebarVisible : panes.primarySidebarWhenExpanded) ||
344 (!layout.usesSplitView && !activeDetailKey)
345 ? layout.primarySidebarOverlaysContent
346 ? "oneOverSecondary"
347 : "oneBesideSecondary"
348 : "secondaryOnly"
349 }
350 onDisplayModeWillChange={({ nativeEvent }) => {
351 if (!layout.primarySidebarOverlaysContent) return;
352 if (nativeEvent.nextDisplayMode === "oneOverSecondary") setPrimarySidebarVisible(true);
353 else if (nativeEvent.nextDisplayMode === "secondaryOnly") setPrimarySidebarVisible(false);
354 }}
355 displayModeButtonVisibility="never"
356 presentsWithGesture
357 showInspector={inspector.visible}
358 onInspectorHide={() => {
359 if (inspector.visible) toggleAuxiliaryPane();
360 }}
361 columnMetrics={{
362 minimumPrimaryColumnWidth: 280,
363 maximumPrimaryColumnWidth: Math.max(380, layout.listPaneWidth ?? 0),
364 preferredPrimaryColumnWidthOrFraction: layout.listPaneWidth ?? 320,
365 minimumSecondaryColumnWidth: 320,
366 }}
367 >
368 <Split.Column>
369 <Split.Stack>
370 <ColumnScreen
371 descriptor={primary}
372 primary
373 selectedThreadKey={selectedThreadKey}
374 selectedPullRequestKey={selectedPullRequestKey}
375 onDismiss={handleNativeDismiss}
376 onAppearance={followCollapsedSplit}
377 navigation={props.navigation}
378 />
379 </Split.Stack>
380 </Split.Column>
381 <Split.Column>
382 <Split.Stack>
383 <Split.Screen
384 screenKey="workspace-empty"
385 activityMode={layout.usesSplitView && !activeDetailKey ? "attached" : "detached"}
386 >
387 <V5StackHeader
388 options={{
389 headerShown: true,
390 title: "",
391 unstable_headerLeftItems: () => [
392 {
393 type: "button",
394 label: "",
395 icon: { type: "sfSymbol", name: "sidebar.left" },
396 onPress: togglePrimarySidebar,
397 },
398 ],
399 }}
400 canGoBack={false}
401 column="detail"
402 onCompose={detailCompose}
403 />
404 <ColumnContent>
405 <WorkspaceEmptyDetail
406 tab={settingsOpen ? "settings" : selectedTab}
407 onStartNewTask={
408 // Duo provides compose in the detail bar; iPad uses the empty-state action.
409 detailCompose ? undefined : openNewTask
410 }
411 />
412 </ColumnContent>
413 </Split.Screen>
414 {screens.routes.map((route) => {
415 const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
416 const inSettingsSlot = settingsDetailIn(props.detail)?.key === route.key;
417 const screenKey = inSettingsSlot ? SETTINGS_DETAIL_SCREEN : route.key;
418 return descriptor ? (
419 <ColumnScreen
420 key={screenKey}
421 screenKey={screenKey}
422 descriptor={descriptor}
423 sidebarToggle={inSettingsSlot}
424 attached={props.detail.some((current) => current.key === route.key)}
425 onDismiss={handleNativeDismiss}
426 onAppearance={followCollapsedSplit}
427 onCompose={isPullRequestRoute(route) ? undefined : detailCompose}
428 navigation={props.navigation}
429 />
430 ) : null;
431 })}
432 </Split.Stack>
433 </Split.Column>
434 <Split.Inspector>
435 <Split.HeaderConfig hidden />
436 {/* Inspector panes host their own native stacks, which UIKit insets for the Duo's
437 vertical bar wherever they sit, so each pane insets its own content instead. */}
438 <ColumnContent insetHorizontally={false}>
439 <View className="flex-1 bg-screen">{inspector.render?.()}</View>
440 </ColumnContent>
441 </Split.Inspector>
442 </Split.Host>
443 );
444}
445
446function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean }) {
447 const { layout } = useAdaptiveWorkspaceLayout();
448 const workspace = useWorkspaceTabs()!;
449 // Native dismiss commits the route pop after the transition. Restore the dock
450 // when the primary screen starts appearing, including interactive back gestures.
451 const [primaryVisible, setPrimaryVisible] = useState(false);
452 const metrics = useNativeLayoutMetrics();
453 const projection = projectWorkspaceStack(props.state, (route) => {
454 const presentation = props.descriptors[route.key]?.options.presentation;
455 return presentation !== undefined && presentation !== "card";
456 });
457 // Detail-only histories must stay single-stack: placeholder descriptors cannot own sidebar actions or setOptions.
458 const primaryRoute = projection.primary;
459 if (!primaryRoute) return <V5StackView {...props} />;
460 const primaryDescriptor = props.descriptors[primaryRoute.key]!;
461 const descriptors = props.descriptors;
462 const baseRoute = { key: `${props.state.key}:workspace`, name: "Workspace" };
463 const visibleRoute = projection.detail.at(-1) ?? primaryRoute;
464 const workspacePage = !workspaceUsesColumns(workspace.state.selectedTab, workspace.settingsOpen);
465 const baseDescriptor: Descriptor = {
466 ...primaryDescriptor,
467 navigation: props.descriptors[visibleRoute.key]!.navigation,
468 // Identify the real visible route under the stable envelope key, or useIsFocused closes media viewers.
469 route: visibleRoute,
470 options: { headerShown: false },
471 render: () => (
472 <WorkspaceNativeTabs
473 hidden={
474 !workspacePage &&
475 projection.detail.length > 0 &&
476 !primaryVisible &&
477 !layout.usesSplitView &&
478 (metrics?.verticalBarEdge ?? "none") === "none"
479 }
480 >
481 {props.nativeColumns && !workspacePage ? (
482 <WorkspaceColumns
483 {...props}
484 descriptors={descriptors}
485 primary={primaryRoute}
486 detail={projection.detail}
487 />
488 ) : (
489 <V5CardStackView
490 {...props}
491 onRootVisibilityChange={setPrimaryVisible}
492 onNativePopChange={setNativelyPoppingWorkspaceRoute}
493 descriptors={descriptors}
494 state={{
495 ...props.state,
496 routes: [primaryRoute, ...projection.detail],
497 index: projection.detail.length,
498 preloadedRoutes: [],
499 }}
500 />
501 )}
502 </WorkspaceNativeTabs>
503 ),
504 };
505 const overlays = partitionStackPresentations(projection.overlays, (route) => {
506 const presentation = props.descriptors[route.key]?.options.presentation;
507 return presentation !== undefined && presentation !== "card";
508 });
509 const routes = [baseRoute, ...overlays.map((group) => group[0]!)];
510 return (
511 <NativeStackView
512 presentationEnvelope
513 {...props}
514 state={{ ...props.state, routes, index: routes.length - 1, preloadedRoutes: [] }}
515 descriptors={{
516 ...Object.fromEntries(
517 overlays.map((group) => {
518 const route = group[0]!;
519 const descriptor = props.descriptors[route.key]!;
520 const visibleRoute = group.at(-1)!;
521 return [
522 route.key,
523 {
524 ...descriptor,
525 navigation: props.descriptors[visibleRoute.key]!.navigation,
526 route: visibleRoute,
527 options: modalEnvelopeOptions(descriptor.options),
528 render: () => (
529 <V5CardStackView
530 {...props}
531 state={{
532 ...props.state,
533 routes: group,
534 index: group.length - 1,
535 preloadedRoutes: [],
536 }}
537 />
538 ),
539 },
540 ];
541 }),
542 ),
543 [baseRoute.key]: baseDescriptor,
544 }}
545 />
546 );
547}
548
549function WorkspaceStackNavigator({
550 id,
551 initialRouteName,
552 UNSTABLE_routeNamesChangeBehavior,
553 children,
554 layout,
555 screenListeners,
556 screenOptions,
557 screenLayout,
558 UNSTABLE_router,
559 ...rest
560}: NativeStackNavigatorProps) {
561 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
562 const nativeWorkspaceColumnsReady = useNativeWorkspaceColumnsReady();
563 const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
564 StackNavigationState<ParamListBase>,
565 StackRouterOptions,
566 StackActionHelpers<ParamListBase>,
567 NativeStackNavigationOptions,
568 NativeStackNavigationEventMap
569 >(StackRouter, {
570 id,
571 initialRouteName,
572 UNSTABLE_routeNamesChangeBehavior,
573 children,
574 layout,
575 screenListeners,
576 screenOptions,
577 screenLayout,
578 UNSTABLE_router,
579 });
580 if (!nativeWorkspaceColumnsReady) return null;
581 const settingsOpen = settingsOpenIn(
582 state.routes.slice(0, state.index + 1).filter((route) => {
583 const presentation = descriptors[route.key]?.options.presentation;
584 return presentation === undefined || presentation === "card";
585 }),
586 );
587 return (
588 <NativeWorkspaceModeContext value={usesNativeWorkspaceColumns}>
589 <NavigationContent>
590 <WorkspaceTabsProvider settingsOpen={settingsOpen}>
591 <WorkspaceStackView
592 nativeColumns={usesNativeWorkspaceColumns}
593 {...rest}
594 state={state}
595 describe={describe}
596 descriptors={descriptors}
597 navigation={navigation}
598 />
599 </WorkspaceTabsProvider>
600 </NavigationContent>
601 </NativeWorkspaceModeContext>
602 );
603}
604
605type WorkspaceTypeBag<
606 ParamList extends ParamListBase,
607 NavigatorID extends string | undefined,
608> = Omit<NativeStackTypeBag<ParamList, NavigatorID>, "Navigator"> & {
609 Navigator: typeof WorkspaceStackNavigator;
610};
611
612export function createWorkspaceStackNavigator<
613 const ParamList extends ParamListBase,
614 const NavigatorID extends string | undefined = string | undefined,
615 const TypeBag extends NavigatorTypeBagBase = WorkspaceTypeBag<ParamList, NavigatorID>,
616 const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
617>(config?: Config): TypedNavigator<TypeBag, Config> {
618 return createNavigatorFactory(WorkspaceStackNavigator)(config);
619}