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