Open History to see the last commit
1import {
2 WorkspaceColumnsRendererContext,
3 WorkspacePresentationHostContext,
4} from "./workspace-presentation-context";
5import { useAndroidFloatingTabs } from "../settings/appearance/AppearancePreferencesProvider";
6import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
7import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";
8import { threadSelectionDeferral } from "./deferred-navigation";
9import { uuidv4 } from "../../lib/uuid";
10import type {
11 EnvironmentProject,
12 EnvironmentThreadShell,
13} from "@t3tools/client-runtime/state/shell";
14import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
15import { useAtomValue } from "@effect/atom-react";
16import { useFocusEffect } from "@react-navigation/native";
17import { NavigationContext, NavigationRouteContext, useNavigation } from "@react-navigation/native";
18import {
19 use,
20 useDeferredValue,
21 useEffect,
22 useEffectEvent,
23 useMemo,
24 useRef,
25 useState,
26 type ReactNode,
27} from "react";
28import { Keyboard, Platform, useWindowDimensions, View } from "react-native";
29import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller";
30import Animated, {
31 runOnJS,
32 useAnimatedStyle,
33 useDerivedValue,
34 useSharedValue,
35 withTiming,
36} from "react-native-reanimated";
37import { AsyncResult } from "effect/reactivity";
38
39import {
40 deriveFileInspectorPaneLayout,
41 alignListPaneToHinge,
42 deriveLayout,
43 type VerticalHinge,
44 deriveWorkspacePaneLayout,
45 isPrimarySidebarPinned,
46 isWorkspaceListPath,
47 type WorkspaceAuxiliaryPaneRole,
48} from "../../lib/layout";
49import { scopedThreadKey } from "../../lib/scopedEntities";
50import type { ThreadListFilters } from "../../persistence/mobile-preferences";
51import { appAtomRegistry } from "../../state/atom-registry";
52import { useProjects } from "../../state/entities";
53import { useThreadCwd } from "../../state/use-selected-thread-worktree";
54import { environmentThreadShells } from "../../state/threads";
55import { mobilePreferencesAtom } from "../../state/preferences";
56import {
57 DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
58 resolveMobileProjectGroupingSettings,
59} from "../../state/project-grouping";
60import {
61 parseActiveThreadPath,
62 useHardwareKeyboardCommand,
63} from "../keyboard/hardwareKeyboardCommands";
64import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
65import { useEnabledNavigationTabs } from "../workspace/navigation-tabs";
66import { FLOATING_TABS, floatingTabsMetrics } from "../workspace/floating-workspace-tabs";
67import { AndroidHomeFabLayout } from "../home/AndroidHomeFab";
68import {
69 AndroidWorkspaceNavigation,
70 FloatingWorkspaceTabs,
71 ANDROID_WORKSPACE_RAIL_WIDTH,
72} from "../workspace/AndroidWorkspaceNavigation";
73import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar";
74import {
75 selectWorkspaceDetail,
76 type WorkspaceDetail,
77 type WorkspaceDetailSheet,
78} from "../workspace/workspace-detail-selection";
79import { startOpeningDetail } from "../workspace/useSelectWorkspaceDetail";
80import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
81import { HomeListOptionsProvider } from "../home/home-list-options";
82import { newTaskDestination } from "../threads/new-task-project-selection";
83import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
84import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
85import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests";
86import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
87import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
88import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
89import {
90 WorkspaceContentWidthContext,
91 WorkspaceSettledContentWidthContext,
92} from "./workspace-content-width";
93import {
94 NativeWorkspaceModeContext,
95 NativeWorkspaceInspectorContext,
96} from "../../native/v5-workspace-context";
97
98import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
99import { AndroidHingeObserver } from "../../native/AndroidHingeObserver";
100import { WindowHingeContext } from "../../native/window-hinge-context";
101import { useAndroidWorkspaceRoot } from "../workspace/AndroidWorkspaceTabsProvider";
102import { openSettings } from "../settings/settings-navigation";
103import { dispatchRootStackReset, rootStackState } from "../../lib/root-stack-reset";
104import {
105 currentWorkspaceSelections,
106 workspaceSelectionCheck,
107} from "../workspace/workspace-selection-store";
108import {
109 workspaceTabColumns,
110 workspaceTabNavigationState,
111} from "../workspace/workspace-tab-navigation";
112import type { WorkspaceTab } from "../workspace/workspace-tabs-state";
113import { workspaceRoutesOf } from "./workspace-overlay-routes";
114import { SettingsWorkspaceLayout } from "../settings/SettingsWorkspaceLayout";
115
116export { useAdaptiveWorkspaceLayout };
117
118export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
119 const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();
120
121 useFocusEffect(() => activateAuxiliaryPaneRole(role));
122}
123
124/** Capture inspector navigation contexts. Register on focus events because frozen blurred screens may never clean up. */
125export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefined) {
126 const { registerWorkspaceInspector } = useAdaptiveWorkspaceLayout();
127 const navigation = use(NavigationContext);
128 const route = use(NavigationRouteContext);
129
130 const wrappedRender = (() => {
131 if (render === undefined) {
132 return undefined;
133 }
134 return () => (
135 <NavigationContext.Provider value={navigation}>
136 <NavigationRouteContext.Provider value={route}>{render()}</NavigationRouteContext.Provider>
137 </NavigationContext.Provider>
138 );
139 })();
140
141 const focusedRef = useRef(false);
142 const deactivateRef = useRef<(() => void) | null>(null);
143
144 const syncRegistration = useEffectEvent(() => {
145 if (!focusedRef.current || wrappedRender === undefined) {
146 deactivateRef.current?.();
147 return;
148 }
149 deactivateRef.current = registerWorkspaceInspector(wrappedRender);
150 });
151
152 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus events own the inspector registration lifetime.
153 useEffect(() => {
154 if (navigation === undefined) return;
155 const focus = () => {
156 if (focusedRef.current) return;
157 focusedRef.current = true;
158 syncRegistration();
159 };
160 const blur = () => {
161 focusedRef.current = false;
162 syncRegistration();
163 };
164 if (navigation.isFocused()) focus();
165 const unsubscribeFocus = navigation.addListener("focus", focus);
166 const unsubscribeBlur = navigation.addListener("blur", blur);
167 return () => {
168 unsubscribeFocus();
169 unsubscribeBlur();
170 focusedRef.current = false;
171 deactivateRef.current?.();
172 deactivateRef.current = null;
173 };
174 }, [navigation]);
175
176 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Changed pane content replaces the focused inspector registration.
177 useEffect(() => {
178 if (focusedRef.current) {
179 syncRegistration();
180 }
181 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Changed pane content replaces its existing native workspace registration.
182 }, [wrappedRender]);
183}
184
185export function AdaptiveWorkspaceLayout(props: {
186 readonly children: ReactNode;
187 readonly pathname: string;
188 readonly workspaceRouteKey: string | undefined;
189 readonly workspaceRouteName: string | undefined;
190 readonly workspaceRouteKeys: ReadonlyArray<string>;
191 readonly selectedPullRequestKey?: string | null;
192}) {
193 const preferencesResult = useAtomValue(mobilePreferencesAtom);
194 if (!AsyncResult.isSuccess(preferencesResult)) {
195 return AsyncResult.isFailure(preferencesResult) ? (
196 <AdaptiveWorkspaceLayoutContent
197 {...props}
198 projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
199 />
200 ) : null;
201 }
202 const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
203 return (
204 <AdaptiveWorkspaceLayoutContent
205 {...props}
206 projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
207 savedThreadListFilters={preferencesResult.value.threadListFilters}
208 />
209 );
210}
211
212function AdaptiveWorkspaceLayoutContent(
213 props: {
214 readonly children: ReactNode;
215 readonly pathname: string;
216 readonly workspaceRouteKey: string | undefined;
217 readonly workspaceRouteName: string | undefined;
218 readonly workspaceRouteKeys: ReadonlyArray<string>;
219 readonly selectedPullRequestKey?: string | null;
220 } & {
221 readonly projectGroupingMode: SidebarProjectGroupingMode;
222 readonly savedThreadListFilters?: ThreadListFilters | undefined;
223 },
224) {
225 const floatingTabsEnabled = useAndroidFloatingTabs();
226 const projectGroupingMode = props.projectGroupingMode;
227 const nativeWorkspace = use(NativeWorkspaceModeContext);
228 const usesPresentationHost = use(WorkspacePresentationHostContext);
229 const windowDimensions = useWindowDimensions();
230 const nativeMetrics = useNativeLayoutMetrics();
231 const { width: viewportWidth, height } = nativeMetrics ?? windowDimensions;
232 const pathname = props.pathname;
233 const workspace = useWorkspaceTabs();
234 // Settings and Usage occupy the workspace rather than a list/detail pair.
235 const androidSettingsOpen = useAndroidWorkspaceRoot()?.settingsOpen ?? false;
236 const safeAreaInsets = useSafeAreaInsets();
237 const workspacePage =
238 Platform.OS === "android" && (androidSettingsOpen || workspace?.state.selectedTab === "usage");
239 const navigation = useNavigation();
240 const activeRoleOwner = useRef<symbol | null>(null);
241 const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
242 const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
243 const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
244 number | null
245 >(null);
246 const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);
247 const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
248 null,
249 );
250 const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
251 const [railOverlay, setRailOverlay] = useState(false);
252 const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
253 useState<WorkspaceAuxiliaryPaneRole | null>(null);
254 // The compiler can't memoize these derivations: they stay live across later hook calls. Fresh
255 // objects here change the workspace context on every render, so every workspace screen
256 // re-renders on any layout state change, and the inspector registration then loops: each
257 // re-register re-renders its screen, which hands over a new inspector renderer.
258 const baseLayout = useMemo(
259 () => deriveLayout({ width: viewportWidth, height, nativeMetrics, nativeWorkspace }),
260 [height, viewportWidth, nativeMetrics, nativeWorkspace],
261 );
262 // The overlay sidebar closes when a page opens from it, and stays open on a list or on the
263 // page a tab switch opened (`keepOpenFor`, set by that switch).
264 const [overlaySidebar, setOverlaySidebar] = useState({
265 active: baseLayout.primarySidebarOverlaysContent,
266 pathname,
267 visible: isWorkspaceListPath(pathname),
268 keepOpenFor: null as string | null,
269 });
270 if (
271 overlaySidebar.active !== baseLayout.primarySidebarOverlaysContent ||
272 (overlaySidebar.active && overlaySidebar.pathname !== pathname)
273 ) {
274 setOverlaySidebar({
275 active: baseLayout.primarySidebarOverlaysContent,
276 pathname,
277 visible:
278 isWorkspaceListPath(pathname) ||
279 (overlaySidebar.keepOpenFor !== null &&
280 overlaySidebar.keepOpenFor === props.workspaceRouteKey),
281 keepOpenFor: null,
282 });
283 }
284 const preferredSidebarVisible = baseLayout.primarySidebarOverlaysContent
285 ? overlaySidebar.visible
286 : primarySidebarPreferredVisible;
287 const primarySidebarPinned = isPrimarySidebarPinned({
288 pathname,
289 nativeWorkspace,
290 usesSplitView: baseLayout.usesSplitView,
291 });
292 const [composerEditing, setComposerEditing] = useState(false);
293 const softKeyboardVisible = useKeyboardState((state) => state.isVisible);
294 // Keyed on the soft keyboard, not focus: a hardware keyboard leaves room for the sidebar, and
295 // Back closes the keyboard while the editor keeps focus. Deferred so the composer commits its
296 // keyboard render first; relaying out in the same commit held it behind the keyboard.
297 const composerKeyboardActive = useDeferredValue(
298 Platform.OS === "android" && baseLayout.usesSplitView && composerEditing && softKeyboardVisible,
299 );
300 const showPrimarySidebar =
301 !workspacePage &&
302 (primarySidebarPinned || (preferredSidebarVisible && !composerKeyboardActive));
303 const shouldRenderNavigationRail =
304 Platform.OS === "android" && baseLayout.usesSplitView && !floatingTabsEnabled;
305 const enabledTabs = useEnabledNavigationTabs();
306 const { scale, fabSize } = useAndroidControlSizing();
307 const floatingTabs = floatingTabsMetrics(enabledTabs.length + 1, scale, fabSize);
308 const navigationRailWidth =
309 shouldRenderNavigationRail && (showPrimarySidebar || workspacePage)
310 ? ANDROID_WORKSPACE_RAIL_WIDTH
311 : 0;
312 const [hinge, setHinge] = useState<VerticalHinge | null>(null);
313 const [windowHinge, setWindowHinge] = useState<VerticalHinge | null>(null);
314 const handleHingeChange = (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {
315 setHinge(next);
316 setWindowHinge(nextWindow);
317 };
318 const layout = useMemo(() => {
319 const aligned = alignListPaneToHinge({
320 layout: baseLayout,
321 hinge,
322 viewportWidth,
323 leadingWidth: navigationRailWidth,
324 });
325 if (
326 !floatingTabsEnabled ||
327 !aligned.usesSplitView ||
328 aligned.listPaneGap !== undefined ||
329 aligned.listPaneWidth === null ||
330 aligned.listPaneWidth >= floatingTabs.row ||
331 viewportWidth - floatingTabs.row < 320
332 )
333 return aligned;
334 return { ...aligned, listPaneWidth: floatingTabs.row };
335 }, [
336 baseLayout,
337 hinge,
338 navigationRailWidth,
339 viewportWidth,
340 floatingTabs.row,
341 floatingTabsEnabled,
342 ]);
343 const width = viewportWidth - navigationRailWidth;
344 // The sidebar stays mounted under a workspace page, so its list is ready on the way back.
345 const shouldRenderPrimarySidebar = layout.usesSplitView;
346 const fileInspector = useMemo(
347 () =>
348 deriveFileInspectorPaneLayout({
349 layout,
350 viewportWidth: width,
351 preferredWidth: fileInspectorPreferredWidth ?? undefined,
352 reservedLeadingWidth:
353 shouldRenderPrimarySidebar && showPrimarySidebar && !layout.primarySidebarOverlaysContent
354 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
355 : 0,
356 }),
357 [fileInspectorPreferredWidth, layout, showPrimarySidebar, shouldRenderPrimarySidebar, width],
358 );
359 const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
360 focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
361 const auxiliaryPanePreferredVisible =
362 !workspacePage &&
363 (auxiliaryPaneRole === "inspector"
364 ? fileInspectorPreferredVisible
365 : supplementaryPanePreferredVisible);
366 const auxiliaryPanePreferredWidth =
367 auxiliaryPaneRole === "inspector"
368 ? fileInspectorPreferredWidth
369 : supplementaryPanePreferredWidth;
370 const panes = useMemo(
371 () =>
372 deriveWorkspacePaneLayout({
373 layout,
374 viewportWidth: width,
375 nativeWorkspace,
376 primarySidebarPreferredVisible: showPrimarySidebar,
377 auxiliaryPanePreferredVisible,
378 auxiliaryPaneRole,
379 auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
380 }),
381 [
382 auxiliaryPanePreferredVisible,
383 auxiliaryPaneRole,
384 auxiliaryPanePreferredWidth,
385 layout,
386 nativeWorkspace,
387 showPrimarySidebar,
388 width,
389 ],
390 );
391 const activeThread = parseActiveThreadPath(pathname);
392 const environmentId = activeThread?.environmentId ?? null;
393 const threadId = activeThread?.threadId ?? null;
394 const selectedThreadRef = (() => {
395 if (environmentId === null || threadId === null) {
396 return null;
397 }
398 try {
399 return {
400 environmentId: EnvironmentId.make(environmentId),
401 threadId: ThreadId.make(threadId),
402 };
403 } catch {
404 return null;
405 }
406 })();
407 const selectedThreadKey =
408 selectedThreadRef === null
409 ? null
410 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
411 const isFilesRoute = props.workspaceRouteName === "ThreadFiles";
412 // Same resolution the Files screen uses: without a cwd it shows "Files unavailable" and
413 // registers no inspector, so revealing would only hide the sidebar beside that screen.
414 const filesCwd = useThreadCwd(isFilesRoute && fileInspector.supported ? selectedThreadRef : null);
415 // Opening a review or the files route reveals its inspector once per route and thread.
416 // Routes still on the stack remember their reveal, so going back to one keeps the user's choice.
417 const revealsInspector =
418 props.workspaceRouteName === "ThreadReview" || (isFilesRoute && filesCwd !== null);
419 const [revealedInspectors, setRevealedInspectors] = useState<ReadonlyMap<string, string>>(
420 () => new Map(),
421 );
422 if (
423 revealsInspector &&
424 props.workspaceRouteKey !== undefined &&
425 selectedThreadKey !== null &&
426 revealedInspectors.get(props.workspaceRouteKey) !== selectedThreadKey
427 ) {
428 const next = new Map<string, string>();
429 for (const routeKey of props.workspaceRouteKeys) {
430 const revealedThreadKey = revealedInspectors.get(routeKey);
431 if (revealedThreadKey !== undefined) {
432 next.set(routeKey, revealedThreadKey);
433 }
434 }
435 next.set(props.workspaceRouteKey, selectedThreadKey);
436 setRevealedInspectors(next);
437 setFocusedAuxiliaryPaneRole("inspector");
438 setFileInspectorPreferredVisible(true);
439 }
440 const [workspaceInspector, setWorkspaceInspector] = useState<{
441 readonly render: () => ReactNode;
442 readonly active: boolean;
443 } | null>(null);
444 const workspaceInspectorOwner = useRef<symbol | null>(null);
445 const registerWorkspaceInspector = (render: () => ReactNode) => {
446 const owner = Symbol("workspace-inspector");
447 workspaceInspectorOwner.current = owner;
448 setWorkspaceInspector({ render, active: true });
449
450 return () => {
451 // Outgoing screens deactivate after incoming registration; only the current owner may deactivate.
452 if (workspaceInspectorOwner.current !== owner) {
453 return;
454 }
455 setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
456 };
457 };
458 const handleWorkspaceInspectorClosed = () => {
459 setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
460 };
461 const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => {
462 const owner = Symbol(role);
463 activeRoleOwner.current = owner;
464 setFocusedAuxiliaryPaneRole(role);
465
466 return () => {
467 if (activeRoleOwner.current !== owner) {
468 return;
469 }
470 activeRoleOwner.current = null;
471 setFocusedAuxiliaryPaneRole(null);
472 };
473 };
474 const setPrimarySidebarVisible = (visible: boolean) => {
475 if (layout.primarySidebarOverlaysContent) {
476 setOverlaySidebar((current) => ({ ...current, visible }));
477 } else {
478 setPrimarySidebarPreferredVisible(visible);
479 }
480 };
481 const togglePrimarySidebar = () => {
482 if (primarySidebarPinned) {
483 return;
484 }
485 // A sidebar the keyboard set aside returns with the keyboard; the user's preference stays
486 // intact. One the user had hidden still opens.
487 if (composerKeyboardActive) {
488 void KeyboardController.dismiss();
489 if (primarySidebarPreferredVisible) return;
490 }
491 if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
492 setFileInspectorPreferredVisible(false);
493 setPrimarySidebarPreferredVisible(true);
494 return;
495 }
496 setPrimarySidebarVisible(!preferredSidebarVisible);
497 };
498 const revealPrimarySidebar = () => {
499 if (composerKeyboardActive) void KeyboardController.dismiss();
500 if (panes.primarySidebarSuppressedByAuxiliary) {
501 setFileInspectorPreferredVisible(false);
502 }
503 setPrimarySidebarVisible(true);
504 };
505 const handleToggleSidebarCommand = () => {
506 togglePrimarySidebar();
507 return true;
508 };
509 const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);
510 useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);
511 const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => {
512 if (role === "inspector") {
513 setFocusedAuxiliaryPaneRole("inspector");
514 setFileInspectorPreferredVisible(true);
515 return;
516 }
517 setFocusedAuxiliaryPaneRole("supplementary");
518 setSupplementaryPanePreferredVisible(true);
519 };
520 const handleOpenFilesCommand = () => {
521 const activeThread = parseActiveThreadPath(pathname);
522 if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
523 return false;
524 }
525 showAuxiliaryPane("inspector");
526 if (/\/files(?:\/|$)/.test(pathname)) {
527 return true;
528 }
529 navigation.navigate("ThreadFiles", activeThread);
530 return true;
531 };
532 useHardwareKeyboardCommand("files", handleOpenFilesCommand);
533 const toggleAuxiliaryPane = () => {
534 if (auxiliaryPaneRole === "inspector") {
535 setFileInspectorPreferredVisible((current) => !current);
536 return;
537 }
538 setSupplementaryPanePreferredVisible((current) => !current);
539 };
540 const setAuxiliaryPaneWidth = (nextWidth: number) => {
541 if (auxiliaryPaneRole === "inspector") {
542 setFileInspectorPreferredWidth(nextWidth);
543 return;
544 }
545 setSupplementaryPanePreferredWidth(nextWidth);
546 };
547 /**
548 * The one way to open a workspace tab: replaces the workspace with the tab's list and, when the
549 * window has columns, the page it last showed, keeping any sheet on top. An overlay sidebar
550 * stays open over that page.
551 */
552 const openWorkspaceTab = (
553 tab: WorkspaceTab | "settings",
554 options?: { readonly columns?: boolean },
555 ) => {
556 const state = rootStackState(navigation);
557 if (!state) return;
558 const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
559 const next = workspaceTabNavigationState(
560 { ...state, routes: workspace },
561 tab,
562 currentWorkspaceSelections(),
563 {
564 columns: workspaceTabColumns(Platform.OS, tab, options?.columns ?? layout.usesSplitView),
565 check: workspaceSelectionCheck,
566 overlays,
567 },
568 );
569 if (layout.primarySidebarOverlaysContent) {
570 const opened = next.routes.at(-1 - overlays.length)?.key ?? null;
571 setOverlaySidebar((current) => ({ ...current, visible: true, keepOpenFor: opened }));
572 }
573 dispatchRootStackReset(navigation, state, next);
574 };
575 const handleOpenSettings = () => openWorkspaceTab("settings");
576
577 /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
578 function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
579 threadSelectionDeferral.run(() => {
580 if (Platform.OS === "android") Keyboard.dismiss();
581 setFileInspectorPreferredVisible(false);
582 if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
583 workspace?.dispatch({
584 type: "select",
585 tab: detail.name === "Thread" ? "threads" : "pullRequests",
586 });
587 startOpeningDetail(detail);
588 navigation.dispatch(selectWorkspaceDetail(detail, sheet));
589 });
590 }
591 const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) =>
592 handleSelectDetail({ name: "Thread", params });
593
594 const projects = useProjects();
595 const compactAndroidSettings =
596 Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;
597 // Reads the open page when pressed, so the layout context doesn't change on every navigation.
598 const handleStartNewTask = () => {
599 const state = rootStackState(navigation);
600 const currentRoute = workspaceRoutesOf(
601 state?.routes.slice(0, state.index + 1) ?? [],
602 ).workspace.at(-1);
603 const params =
604 currentRoute?.name === "Thread"
605 ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])
606 : undefined;
607 const first = (value: string | string[] | undefined) =>
608 Array.isArray(value) ? value[0] : value;
609 const environmentId = first(params?.environmentId);
610 const threadId = first(params?.threadId);
611 // The full index, not the sidebar list: subagent and archived threads are current threads too.
612 const projectId =
613 environmentId && threadId
614 ? appAtomRegistry
615 .get(
616 environmentThreadShells.environmentThreadIndexAtom(EnvironmentId.make(environmentId)),
617 )
618 .get(ThreadId.make(threadId))?.projectId
619 : undefined;
620 const preferences = appAtomRegistry.get(mobilePreferencesAtom);
621 const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
622 handleSelectThreadRoute(
623 newTaskDestination({
624 projects,
625 requestId: uuidv4(),
626 useLastProject: saved?.useLastProjectForNewThreads,
627 currentProject: environmentId && projectId ? { environmentId, projectId } : undefined,
628 lastProject: saved?.lastThreadProject,
629 }),
630 );
631 };
632
633 useHardwareKeyboardCommand("newTask", () => {
634 handleStartNewTask();
635 return true;
636 });
637
638 // Create at root: the iOS sidebar renders in an independent navigation tree.
639 const handleOpenEnvironmentSettings = () => {
640 openSettings(navigation, "SettingsEnvironments");
641 };
642
643 const handleOpenThreadPullRequests = useOpenThreadPullRequests();
644 const { openPendingTask: handleOpenPendingTask } =
645 usePendingTaskListActions(handleSelectThreadRoute);
646
647 const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {
648 handleSelectThreadRoute({
649 draft: {
650 requestId: uuidv4(),
651 environmentId: String(thread.environmentId),
652 projectId: String(thread.projectId),
653 branch: thread.branch,
654 worktreePath: thread.worktreePath,
655 },
656 });
657 };
658
659 const handleNewThreadInProject = (project: EnvironmentProject) => {
660 handleSelectThreadRoute({
661 draft: {
662 requestId: uuidv4(),
663 environmentId: String(project.environmentId),
664 projectId: String(project.id),
665 title: project.title,
666 },
667 });
668 };
669
670 const inspectorColumnTargetWidth =
671 workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
672 ? (panes.auxiliaryPaneWidth ?? 0)
673 : 0;
674 // Android's split content is a rounded card: keep it off the screen edge like the list card.
675 const contentEndGap = Platform.OS === "android" && layout.usesSplitView ? 4 : 0;
676 const contentTargetWidth = layout.usesSplitView
677 ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth - contentEndGap)
678 : null;
679 const [listPaneSizing, setListPaneSizing] = useState({
680 viewportWidth,
681 workspacePage,
682 sidebarVisible: panes.primarySidebarVisible,
683 listPaneTarget: layout.listPaneWidth,
684 listPaneFloor: layout.listPaneWidth,
685 listPaneCeiling: layout.listPaneWidth,
686 revision: 0,
687 });
688 if (
689 Platform.OS === "android" &&
690 (listPaneSizing.viewportWidth !== viewportWidth ||
691 listPaneSizing.workspacePage !== workspacePage ||
692 listPaneSizing.sidebarVisible !== panes.primarySidebarVisible ||
693 listPaneSizing.listPaneTarget !== layout.listPaneWidth)
694 ) {
695 // A book-posture hinge resizes the visible list pane instead of revealing it.
696 const resizingSidebar =
697 listPaneSizing.viewportWidth === viewportWidth &&
698 listPaneSizing.workspacePage === workspacePage &&
699 listPaneSizing.sidebarVisible &&
700 panes.primarySidebarVisible &&
701 listPaneSizing.listPaneTarget !== layout.listPaneWidth;
702 setListPaneSizing({
703 viewportWidth,
704 workspacePage,
705 sidebarVisible: panes.primarySidebarVisible,
706 listPaneTarget: layout.listPaneWidth,
707 // Retargets widen the list-width span because the animated hinge edge may still be inside it.
708 listPaneFloor: resizingSidebar
709 ? Math.min(listPaneSizing.listPaneFloor ?? 0, layout.listPaneWidth ?? 0)
710 : layout.listPaneWidth,
711 listPaneCeiling: resizingSidebar
712 ? Math.max(listPaneSizing.listPaneCeiling ?? 0, layout.listPaneWidth ?? 0)
713 : layout.listPaneWidth,
714 revision: listPaneSizing.revision + 1,
715 });
716 }
717 const settleListPane = (revision: number) => {
718 setListPaneSizing((current) =>
719 current.revision !== revision ||
720 (current.listPaneFloor === current.listPaneTarget &&
721 current.listPaneCeiling === current.listPaneTarget)
722 ? current
723 : {
724 ...current,
725 listPaneFloor: current.listPaneTarget,
726 listPaneCeiling: current.listPaneTarget,
727 },
728 );
729 };
730 const listPaneFloor = listPaneSizing.listPaneFloor ?? 0;
731 const listPaneCeiling = listPaneSizing.listPaneCeiling ?? 0;
732 const listPaneRevision = listPaneSizing.revision;
733 // Android lays the content out at its new width as soon as a pane toggles, then holds it
734 // against the edge that stays put while the other one slides, so nothing reflows after the
735 // panes land. A sliding sidebar uncovers the strip it is about to fill, or covers the content
736 // until it is gone.
737 const contentLeftTarget =
738 navigationRailWidth +
739 (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible
740 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
741 : 0);
742 const [contentAnchor, setContentAnchor] = useState({
743 viewportWidth,
744 left: contentLeftTarget,
745 inspector: inspectorColumnTargetWidth,
746 end: false,
747 });
748 if (
749 Platform.OS === "android" &&
750 (contentAnchor.viewportWidth !== viewportWidth ||
751 contentAnchor.left !== contentLeftTarget ||
752 contentAnchor.inspector !== inspectorColumnTargetWidth)
753 ) {
754 setContentAnchor({
755 viewportWidth,
756 left: contentLeftTarget,
757 inspector: inspectorColumnTargetWidth,
758 end:
759 contentAnchor.viewportWidth === viewportWidth &&
760 contentAnchor.inspector === inspectorColumnTargetWidth,
761 });
762 }
763
764 const renderedSidebarWidth = useSharedValue(
765 panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0,
766 );
767 const renderedRailWidth = useSharedValue(navigationRailWidth);
768 const leavingWorkspacePage = useRef(false);
769 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- animates the Reanimated rail and sidebar width shared values toward the layout's targets
770 useEffect(() => {
771 if (nativeWorkspace) return;
772 renderedRailWidth.set(withTiming(navigationRailWidth, WORKSPACE_PANE_TIMING));
773 // A workspace page hides the sidebar through React instead, in the same commit that mounts
774 // the page. Animating it here would hide it a few frames before the page appears.
775 if (workspacePage) {
776 leavingWorkspacePage.current = true;
777 return;
778 }
779 const snap = leavingWorkspacePage.current;
780 leavingWorkspacePage.current = false;
781 const targetWidth = panes.primarySidebarVisible
782 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
783 : 0;
784 // The content beside it already took its final width when the page closed.
785 renderedSidebarWidth.set(
786 withTiming(targetWidth, snap ? { duration: 0 } : WORKSPACE_PANE_TIMING, (finished) => {
787 if (finished && Platform.OS === "android") runOnJS(settleListPane)(listPaneRevision);
788 }),
789 );
790 }, [
791 nativeWorkspace,
792 navigationRailWidth,
793 layout.listPaneWidth,
794 layout.listPaneGap,
795 panes.primarySidebarVisible,
796 renderedSidebarWidth,
797 renderedRailWidth,
798 settleListPane,
799 listPaneRevision,
800 workspacePage,
801 ]);
802 const railAnimatedStyle = useAnimatedStyle(() => ({ width: renderedRailWidth.value }));
803 // Showing or hiding the sidebar clips a fixed-width list. A hinge resize instead tracks the
804 // animated edge, so the header actions slide with it rather than jumping or being covered.
805 const listPaneGap = layout.listPaneGap ?? 0;
806 const listPaneAnimatedStyle = useAnimatedStyle(() => ({
807 width: Math.min(
808 listPaneCeiling,
809 Math.max(listPaneFloor, renderedSidebarWidth.value - listPaneGap),
810 ),
811 }));
812 const sidebarAnimatedStyle = useAnimatedStyle(() => ({
813 // Fading a UIKit glass ancestor can leave remounted header effects missing.
814 opacity:
815 Platform.OS === "ios" || floatingTabsEnabled
816 ? 1
817 : Math.min(1, renderedSidebarWidth.value / 80),
818 width: renderedSidebarWidth.value,
819 }));
820
821 // Clip the navigator at its settled width so native headers and markdown reflow only once per pane toggle.
822 const renderedInspectorWidth = useSharedValue(inspectorColumnTargetWidth);
823 const renderedContentWidth = useDerivedValue(() =>
824 Math.max(
825 0,
826 viewportWidth -
827 renderedRailWidth.value -
828 (workspacePage ? 0 : renderedSidebarWidth.value) -
829 renderedInspectorWidth.value,
830 ),
831 );
832 // Android can resize the native row before React removes its split panes on a fold.
833 const androidSplit = Platform.OS === "android" && layout.usesSplitView;
834 const androidContentSlotStyle = useAnimatedStyle(() => ({
835 width: androidSplit ? renderedContentWidth.value : ("100%" as const),
836 }));
837 // While the sidebar animates, clip the settled navigator instead of reflowing its text every frame.
838 const androidNavigatorLimit = useAnimatedStyle(() => ({
839 maxWidth:
840 androidSplit && contentTargetWidth !== null && renderedContentWidth.value < contentTargetWidth
841 ? contentTargetWidth
842 : ("100%" as const),
843 }));
844
845 const handleSelectThread = (thread: EnvironmentThreadShell) => {
846 handleSelectThreadRoute({
847 environmentId: String(thread.environmentId),
848 threadId: String(thread.id),
849 });
850 };
851
852 // Rotating flips the overlay; until the new size reaches JS, predict the reset above.
853 const sidebarOverRotates =
854 nativeWorkspace && nativeMetrics?.hasHinge === true && layout.usesSplitView;
855 // The current orientation's panes already account for an inspector that needs the sidebar's room.
856 const sidebarInLandscape = baseLayout.primarySidebarOverlaysContent
857 ? primarySidebarPinned || primarySidebarPreferredVisible
858 : panes.primarySidebarVisible;
859 const sidebarInPortrait =
860 primarySidebarPinned ||
861 (baseLayout.primarySidebarOverlaysContent
862 ? overlaySidebar.visible
863 : isWorkspaceListPath(pathname));
864 const sidebarByOrientation = useMemo(
865 () =>
866 sidebarOverRotates ? { landscape: sidebarInLandscape, portrait: sidebarInPortrait } : null,
867 [sidebarInLandscape, sidebarInPortrait, sidebarOverRotates],
868 );
869
870 const contextValue = {
871 layout,
872 panes,
873 fileInspector,
874 primarySidebarSearchQuery,
875 startNewTask: handleStartNewTask,
876 selectDetail: handleSelectDetail,
877 activateAuxiliaryPaneRole,
878 registerWorkspaceInspector,
879 setPrimarySidebarSearchQuery,
880 showAuxiliaryPane,
881 toggleAuxiliaryPane,
882 togglePrimarySidebar,
883 setPrimarySidebarVisible,
884 openWorkspaceTab,
885 setAuxiliaryPaneWidth,
886 composerKeyboardActive,
887 setComposerEditing,
888 sidebarByOrientation,
889 };
890
891 if (nativeWorkspace) {
892 return (
893 <HomeListOptionsProvider
894 projectGroupingMode={projectGroupingMode}
895 savedFilters={props.savedThreadListFilters}
896 >
897 <AdaptiveWorkspaceContext value={contextValue}>
898 <NativeWorkspaceInspectorContext
899 value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}
900 >
901 {props.children}
902 </NativeWorkspaceInspectorContext>
903 </AdaptiveWorkspaceContext>
904 </HomeListOptionsProvider>
905 );
906 }
907 const renderColumns = (children: ReactNode) => (
908 <View
909 testID="adaptive-workspace-layout"
910 className={Platform.OS === "android" ? "flex-1 flex-row bg-header" : "flex-1 flex-row"}
911 >
912 <AndroidHingeObserver onChange={handleHingeChange} />
913 {shouldRenderNavigationRail ? (
914 <Animated.View className="shrink self-stretch" style={railAnimatedStyle} />
915 ) : null}
916 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
917 <Animated.View
918 className="self-stretch overflow-hidden android:shrink"
919 accessibilityElementsHidden={workspacePage || !panes.primarySidebarVisible}
920 collapsable={false}
921 importantForAccessibility={
922 !workspacePage && panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
923 }
924 pointerEvents={!workspacePage && panes.primarySidebarVisible ? "auto" : "none"}
925 // Under a workspace page the sidebar leaves the row but keeps its size, so its
926 // lists never lay out at zero size and are ready, unchanged, on the way back. The
927 // content pane, laid out after it, covers it, in the same mount as the page.
928 style={[
929 workspacePage ? { position: "absolute", top: 0, bottom: 0, left: 0 } : null,
930 sidebarAnimatedStyle,
931 ]}
932 >
933 <Animated.View className="flex-1" style={listPaneAnimatedStyle}>
934 <RenderErrorBoundary
935 renderFallback={(fallback) => (
936 <RenderFailureView
937 {...fallback}
938 title="The sidebar couldn't be displayed"
939 exit={{ label: "Open settings", onPress: handleOpenSettings }}
940 />
941 )}
942 >
943 <AndroidWorkspaceSidebar
944 onRequestVisibility={revealPrimarySidebar}
945 selectedPullRequestKey={props.selectedPullRequestKey ?? null}
946 >
947 <AndroidHomeFabLayout
948 sidebar
949 disabled={workspacePage}
950 onStartNewTask={handleStartNewTask}
951 >
952 <ThreadNavigationSidebar
953 width={layout.listPaneWidth}
954 visible={panes.primarySidebarVisible}
955 onRequestVisibility={revealPrimarySidebar}
956 selectedThreadKey={selectedThreadKey}
957 onOpenSettings={handleOpenSettings}
958 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
959 onNewThreadInProject={handleNewThreadInProject}
960 onNewThreadOnBranch={handleNewThreadOnBranch}
961 onOpenPendingTask={handleOpenPendingTask}
962 onSelectThread={handleSelectThread}
963 onOpenThreadPullRequests={handleOpenThreadPullRequests}
964 onSearchQueryChange={setPrimarySidebarSearchQuery}
965 searchQuery={primarySidebarSearchQuery}
966 />
967 </AndroidHomeFabLayout>
968 </AndroidWorkspaceSidebar>
969 </RenderErrorBoundary>
970 {/* Keep the pill under the content throughout the sidebar's clipping animation. */}
971 {floatingTabsEnabled && !workspacePage ? (
972 <FloatingWorkspaceTabs
973 paneWidth={layout.listPaneWidth}
974 onNewThread={handleStartNewTask}
975 onSelect={revealPrimarySidebar}
976 />
977 ) : null}
978 </Animated.View>
979 </Animated.View>
980 ) : null}
981 <Animated.View
982 className={
983 Platform.OS === "android"
984 ? "max-w-full shrink-0 overflow-hidden bg-header"
985 : "flex-1 overflow-hidden bg-screen"
986 }
987 style={Platform.OS === "android" ? androidContentSlotStyle : undefined}
988 collapsable={false}
989 >
990 <Animated.View
991 collapsable={false}
992 style={[
993 contentTargetWidth !== null
994 ? {
995 flex: 1,
996 width: contentTargetWidth,
997 alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
998 marginRight: contentAnchor.end ? contentEndGap : 0,
999 }
1000 : { flex: 1 },
1001 Platform.OS === "android" ? androidNavigatorLimit : undefined,
1002 ]}
1003 >
1004 {/* Android holds the content still, so its floating controls keep its width. */}
1005 <WorkspaceContentWidthContext
1006 value={layout.usesSplitView && Platform.OS !== "android" ? renderedContentWidth : null}
1007 >
1008 <WorkspaceSettledContentWidthContext
1009 value={Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null}
1010 >
1011 {/* Compact Settings keeps the bottom navigation under all of its pages. */}
1012 <SafeAreaInsetsContext
1013 value={
1014 floatingTabsEnabled &&
1015 (compactAndroidSettings || (layout.usesSplitView && workspacePage))
1016 ? {
1017 ...safeAreaInsets,
1018 bottom:
1019 safeAreaInsets.bottom +
1020 FLOATING_TABS.bottom +
1021 FLOATING_TABS.edge +
1022 floatingTabs.height,
1023 }
1024 : compactAndroidSettings
1025 ? { ...safeAreaInsets, bottom: 0 }
1026 : safeAreaInsets
1027 }
1028 >
1029 <View className="flex-1">
1030 <SettingsWorkspaceLayout>{children}</SettingsWorkspaceLayout>
1031 </View>
1032 </SafeAreaInsetsContext>
1033 {floatingTabsEnabled &&
1034 (compactAndroidSettings || (layout.usesSplitView && workspacePage)) ? (
1035 <FloatingWorkspaceTabs
1036 paneWidth={layout.usesSplitView ? (layout.listPaneWidth ?? undefined) : undefined}
1037 fillWidth={compactAndroidSettings}
1038 onNewThread={handleStartNewTask}
1039 />
1040 ) : compactAndroidSettings ? (
1041 <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
1042 ) : null}
1043 </WorkspaceSettledContentWidthContext>
1044 </WorkspaceContentWidthContext>
1045 </Animated.View>
1046 </Animated.View>
1047 <WorkspaceInspectorPane
1048 pathname={props.pathname}
1049 renderedInspectorWidth={renderedInspectorWidth}
1050 active={workspaceInspector?.active ?? false}
1051 panes={panes}
1052 renderInspector={workspaceInspector?.render}
1053 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
1054 onClosed={handleWorkspaceInspectorClosed}
1055 />
1056 {shouldRenderNavigationRail && navigationRailWidth > 0 ? (
1057 // Its trailing inset clips the old rail as soon as Android fits the workspace to a cover display.
1058 <View
1059 className="absolute inset-y-0 left-0 overflow-hidden"
1060 style={
1061 railOverlay
1062 ? { right: 0 }
1063 : { right: viewportWidth - navigationRailWidth, maxWidth: navigationRailWidth }
1064 }
1065 >
1066 <AndroidWorkspaceNavigation
1067 onNewThread={handleStartNewTask}
1068 rail
1069 onSelect={revealPrimarySidebar}
1070 onOverlayChange={setRailOverlay}
1071 />
1072 </View>
1073 ) : null}
1074 </View>
1075 );
1076
1077 return (
1078 <HomeListOptionsProvider
1079 projectGroupingMode={projectGroupingMode}
1080 savedFilters={props.savedThreadListFilters}
1081 >
1082 <AdaptiveWorkspaceContext.Provider value={contextValue}>
1083 <WindowHingeContext value={windowHinge}>
1084 {usesPresentationHost ? (
1085 <WorkspaceColumnsRendererContext value={renderColumns}>
1086 {props.children}
1087 </WorkspaceColumnsRendererContext>
1088 ) : (
1089 renderColumns(props.children)
1090 )}
1091 </WindowHingeContext>
1092 </AdaptiveWorkspaceContext.Provider>
1093 </HomeListOptionsProvider>
1094 );
1095}