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

AdaptiveWorkspaceLayout.tsx

1,030 lines40.8 KB

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