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

AdaptiveWorkspaceLayout.tsx

1,034 lines41.2 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 // Android's split content is a rounded card: keep it off the screen edge like the list card.
630 const contentEndGap = Platform.OS === "android" && layout.usesSplitView ? 4 : 0;
631 const contentTargetWidth = layout.usesSplitView
632 ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth - contentEndGap)
633 : null;
634 const [listPaneSizing, setListPaneSizing] = useState({
635 viewportWidth,
636 workspacePage,
637 sidebarVisible: panes.primarySidebarVisible,
638 listPaneTarget: layout.listPaneWidth,
639 listPaneFloor: layout.listPaneWidth,
640 listPaneCeiling: layout.listPaneWidth,
641 revision: 0,
642 });
643 if (
644 Platform.OS === "android" &&
645 (listPaneSizing.viewportWidth !== viewportWidth ||
646 listPaneSizing.workspacePage !== workspacePage ||
647 listPaneSizing.sidebarVisible !== panes.primarySidebarVisible ||
648 listPaneSizing.listPaneTarget !== layout.listPaneWidth)
649 ) {
650 // A book-posture hinge resizes the visible list pane instead of revealing it.
651 const resizingSidebar =
652 listPaneSizing.viewportWidth === viewportWidth &&
653 listPaneSizing.workspacePage === workspacePage &&
654 listPaneSizing.sidebarVisible &&
655 panes.primarySidebarVisible &&
656 listPaneSizing.listPaneTarget !== layout.listPaneWidth;
657 setListPaneSizing({
658 viewportWidth,
659 workspacePage,
660 sidebarVisible: panes.primarySidebarVisible,
661 listPaneTarget: layout.listPaneWidth,
662 // Retargets widen the list-width span because the animated hinge edge may still be inside it.
663 listPaneFloor: resizingSidebar
664 ? Math.min(listPaneSizing.listPaneFloor ?? 0, layout.listPaneWidth ?? 0)
665 : layout.listPaneWidth,
666 listPaneCeiling: resizingSidebar
667 ? Math.max(listPaneSizing.listPaneCeiling ?? 0, layout.listPaneWidth ?? 0)
668 : layout.listPaneWidth,
669 revision: listPaneSizing.revision + 1,
670 });
671 }
672 const settleListPane = (revision: number) => {
673 setListPaneSizing((current) =>
674 current.revision !== revision ||
675 (current.listPaneFloor === current.listPaneTarget &&
676 current.listPaneCeiling === current.listPaneTarget)
677 ? current
678 : {
679 ...current,
680 listPaneFloor: current.listPaneTarget,
681 listPaneCeiling: current.listPaneTarget,
682 },
683 );
684 };
685 const listPaneFloor = listPaneSizing.listPaneFloor ?? 0;
686 const listPaneCeiling = listPaneSizing.listPaneCeiling ?? 0;
687 const listPaneRevision = listPaneSizing.revision;
688 // Android lays the content out at its new width as soon as a pane toggles, then holds it
689 // against the edge that stays put while the other one slides, so nothing reflows after the
690 // panes land. A sliding sidebar uncovers the strip it is about to fill, or covers the content
691 // until it is gone.
692 const contentLeftTarget =
693 navigationRailWidth +
694 (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible
695 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
696 : 0);
697 const [contentAnchor, setContentAnchor] = useState({
698 viewportWidth,
699 left: contentLeftTarget,
700 inspector: inspectorColumnTargetWidth,
701 end: false,
702 });
703 if (
704 Platform.OS === "android" &&
705 (contentAnchor.viewportWidth !== viewportWidth ||
706 contentAnchor.left !== contentLeftTarget ||
707 contentAnchor.inspector !== inspectorColumnTargetWidth)
708 ) {
709 setContentAnchor({
710 viewportWidth,
711 left: contentLeftTarget,
712 inspector: inspectorColumnTargetWidth,
713 end:
714 contentAnchor.viewportWidth === viewportWidth &&
715 contentAnchor.inspector === inspectorColumnTargetWidth,
716 });
717 }
718​
719 const renderedSidebarWidth = useSharedValue(
720 panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0,
721 );
722 const renderedRailWidth = useSharedValue(navigationRailWidth);
723 const leavingWorkspacePage = useRef(false);
724 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- animates the Reanimated rail and sidebar width shared values toward the layout's targets
725 useEffect(() => {
726 if (nativeWorkspace) return;
727 renderedRailWidth.set(withTiming(navigationRailWidth, WORKSPACE_PANE_TIMING));
728 // A workspace page hides the sidebar through React instead, in the same commit that mounts
729 // the page. Animating it here would hide it a few frames before the page appears.
730 if (workspacePage) {
731 leavingWorkspacePage.current = true;
732 return;
733 }
734 const snap = leavingWorkspacePage.current;
735 leavingWorkspacePage.current = false;
736 const targetWidth = panes.primarySidebarVisible
737 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
738 : 0;
739 // The content beside it already took its final width when the page closed.
740 renderedSidebarWidth.set(
741 withTiming(targetWidth, snap ? { duration: 0 } : WORKSPACE_PANE_TIMING, (finished) => {
742 if (finished && Platform.OS === "android") runOnJS(settleListPane)(listPaneRevision);
743 }),
744 );
745 }, [
746 nativeWorkspace,
747 navigationRailWidth,
748 layout.listPaneWidth,
749 layout.listPaneGap,
750 panes.primarySidebarVisible,
751 renderedSidebarWidth,
752 renderedRailWidth,
753 settleListPane,
754 listPaneRevision,
755 workspacePage,
756 ]);
757 const railAnimatedStyle = useAnimatedStyle(() => ({ width: renderedRailWidth.value }));
758 // Showing or hiding the sidebar clips a fixed-width list. A hinge resize instead tracks the
759 // animated edge, so the header actions slide with it rather than jumping or being covered.
760 const listPaneGap = layout.listPaneGap ?? 0;
761 const listPaneAnimatedStyle = useAnimatedStyle(() => ({
762 width: Math.min(
763 listPaneCeiling,
764 Math.max(listPaneFloor, renderedSidebarWidth.value - listPaneGap),
765 ),
766 }));
767 const sidebarAnimatedStyle = useAnimatedStyle(() => ({
768 // Fading a UIKit glass ancestor can leave remounted header effects missing.
769 opacity:
770 Platform.OS === "ios" || floatingTabsEnabled
771 ? 1
772 : Math.min(1, renderedSidebarWidth.value / 80),
773 width: renderedSidebarWidth.value,
774 }));
775​
776 // Clip the navigator at its settled width so native headers and markdown reflow only once per pane toggle.
777 const renderedInspectorWidth = useSharedValue(inspectorColumnTargetWidth);
778 const renderedContentWidth = useDerivedValue(() =>
779 Math.max(
780 0,
781 viewportWidth -
782 renderedRailWidth.value -
783 renderedSidebarWidth.value -
784 renderedInspectorWidth.value,
785 ),
786 );
787​
788 const handleSelectThread = (thread: EnvironmentThreadShell) => {
789 handleSelectThreadRoute({
790 environmentId: String(thread.environmentId),
791 threadId: String(thread.id),
792 });
793 };
794​
795 // Rotating flips the overlay; until the new size reaches JS, predict the reset above.
796 const sidebarOverRotates =
797 nativeWorkspace && nativeMetrics?.hasHinge === true && layout.usesSplitView;
798 // The current orientation's panes already account for an inspector that needs the sidebar's room.
799 const sidebarInLandscape = baseLayout.primarySidebarOverlaysContent
800 ? primarySidebarPinned || primarySidebarPreferredVisible
801 : panes.primarySidebarVisible;
802 const sidebarInPortrait =
803 primarySidebarPinned ||
804 (baseLayout.primarySidebarOverlaysContent
805 ? overlaySidebar.visible
806 : isWorkspaceListPath(pathname));
807 const sidebarByOrientation = useMemo(
808 () =>
809 sidebarOverRotates ? { landscape: sidebarInLandscape, portrait: sidebarInPortrait } : null,
810 [sidebarInLandscape, sidebarInPortrait, sidebarOverRotates],
811 );
812​
813 const contextValue = {
814 layout,
815 panes,
816 fileInspector,
817 primarySidebarSearchQuery,
818 startNewTask: handleStartNewTask,
819 selectDetail: handleSelectDetail,
820 activateAuxiliaryPaneRole,
821 registerWorkspaceInspector,
822 setPrimarySidebarSearchQuery,
823 showAuxiliaryPane,
824 toggleAuxiliaryPane,
825 togglePrimarySidebar,
826 setPrimarySidebarVisible,
827 openWorkspaceTab,
828 setAuxiliaryPaneWidth,
829 composerKeyboardActive,
830 setComposerEditing,
831 sidebarByOrientation,
832 };
833​
834 if (nativeWorkspace) {
835 return (
836 <HomeListOptionsProvider
837 projectGroupingMode={projectGroupingMode}
838 savedFilters={props.savedThreadListFilters}
839 >
840 <AdaptiveWorkspaceContext value={contextValue}>
841 <NativeWorkspaceInspectorContext
842 value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}
843 >
844 {props.children}
845 </NativeWorkspaceInspectorContext>
846 </AdaptiveWorkspaceContext>
847 </HomeListOptionsProvider>
848 );
849 }
850 const renderColumns = (children: ReactNode) => (
851 <View
852 testID="adaptive-workspace-layout"
853 className={Platform.OS === "android" ? "flex-1 flex-row bg-header" : "flex-1 flex-row"}
854 >
855 <AndroidHingeObserver onChange={handleHingeChange} />
856 {shouldRenderNavigationRail ? (
857 <Animated.View className="self-stretch" style={railAnimatedStyle} />
858 ) : null}
859 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
860 <Animated.View
861 className="self-stretch overflow-hidden"
862 accessibilityElementsHidden={workspacePage || !panes.primarySidebarVisible}
863 collapsable={false}
864 importantForAccessibility={
865 !workspacePage && panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
866 }
867 pointerEvents={!workspacePage && panes.primarySidebarVisible ? "auto" : "none"}
868 // Under a workspace page the sidebar leaves the row but keeps its size, so its
869 // lists never lay out at zero size and are ready, unchanged, on the way back. The
870 // content pane, laid out after it, covers it, in the same mount as the page.
871 style={[
872 workspacePage ? { position: "absolute", top: 0, bottom: 0, left: 0 } : null,
873 sidebarAnimatedStyle,
874 ]}
875 >
876 <Animated.View className="flex-1" style={listPaneAnimatedStyle}>
877 <RenderErrorBoundary
878 renderFallback={(fallback) => (
879 <RenderFailureView
880 {...fallback}
881 title="The sidebar couldn't be displayed"
882 exit={{ label: "Open settings", onPress: handleOpenSettings }}
883 />
884 )}
885 >
886 <AndroidWorkspaceSidebar
887 onRequestVisibility={revealPrimarySidebar}
888 selectedPullRequestKey={props.selectedPullRequestKey ?? null}
889 >
890 <AndroidHomeFabLayout
891 sidebar
892 disabled={workspacePage}
893 paneWidth={layout.listPaneWidth}
894 onStartNewTask={handleStartNewTask}
895 >
896 <ThreadNavigationSidebar
897 width={layout.listPaneWidth}
898 visible={panes.primarySidebarVisible}
899 onRequestVisibility={revealPrimarySidebar}
900 selectedThreadKey={selectedThreadKey}
901 onOpenSettings={handleOpenSettings}
902 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
903 onNewThreadInProject={handleNewThreadInProject}
904 onNewThreadOnBranch={handleNewThreadOnBranch}
905 onOpenPendingTask={handleOpenPendingTask}
906 onSelectThread={handleSelectThread}
907 onOpenThreadPullRequests={handleOpenThreadPullRequests}
908 onSearchQueryChange={setPrimarySidebarSearchQuery}
909 searchQuery={primarySidebarSearchQuery}
910 />
911 </AndroidHomeFabLayout>
912 </AndroidWorkspaceSidebar>
913 </RenderErrorBoundary>
914 {/* Keep the pill under the content throughout the sidebar's clipping animation. */}
915 {floatingTabsEnabled && !workspacePage ? (
916 <FloatingWorkspaceTabs
917 paneWidth={layout.listPaneWidth}
918 onNewThread={handleStartNewTask}
919 onSelect={revealPrimarySidebar}
920 />
921 ) : null}
922 </Animated.View>
923 </Animated.View>
924 ) : null}
925 <View
926 className={
927 Platform.OS === "android"
928 ? "flex-1 overflow-hidden bg-header"
929 : "flex-1 overflow-hidden bg-screen"
930 }
931 collapsable={false}
932 >
933 <View
934 collapsable={false}
935 style={
936 contentTargetWidth !== null
937 ? {
938 flex: 1,
939 width: contentTargetWidth,
940 alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
941 marginRight: contentAnchor.end ? contentEndGap : 0,
942 }
943 : { flex: 1 }
944 }
945 >
946 {/* Android holds the content still, so its floating controls keep its width. */}
947 <WorkspaceContentWidthContext
948 value={layout.usesSplitView && Platform.OS !== "android" ? renderedContentWidth : null}
949 >
950 <WorkspaceSettledContentWidthContext
951 value={Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null}
952 >
953 {/* Compact Settings keeps the bottom navigation under all of its pages. */}
954 <SafeAreaInsetsContext
955 value={
956 floatingTabsEnabled &&
957 (compactAndroidSettings || (layout.usesSplitView && workspacePage))
958 ? {
959 ...safeAreaInsets,
960 bottom:
961 safeAreaInsets.bottom +
962 FLOATING_TABS.bottom +
963 FLOATING_TABS.edge +
964 floatingTabs.height,
965 }
966 : compactAndroidSettings
967 ? { ...safeAreaInsets, bottom: 0 }
968 : safeAreaInsets
969 }
970 >
971 <View className="flex-1">
972 <SettingsWorkspaceLayout>{children}</SettingsWorkspaceLayout>
973 </View>
974 </SafeAreaInsetsContext>
975 {floatingTabsEnabled &&
976 (compactAndroidSettings || (layout.usesSplitView && workspacePage)) ? (
977 <FloatingWorkspaceTabs
978 paneWidth={layout.usesSplitView ? (layout.listPaneWidth ?? undefined) : undefined}
979 fillWidth={compactAndroidSettings}
980 onNewThread={handleStartNewTask}
981 />
982 ) : compactAndroidSettings ? (
983 <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
984 ) : null}
985 </WorkspaceSettledContentWidthContext>
986 </WorkspaceContentWidthContext>
987 </View>
988 </View>
989 <WorkspaceInspectorPane
990 pathname={props.pathname}
991 renderedInspectorWidth={renderedInspectorWidth}
992 active={workspaceInspector?.active ?? false}
993 panes={panes}
994 renderInspector={workspaceInspector?.render}
995 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
996 onClosed={handleWorkspaceInspectorClosed}
997 />
998 {shouldRenderNavigationRail && navigationRailWidth > 0 ? (
999 // The rail reserves its slot above and draws over the panes, so it can widen over
1000 // the list in place. It takes the whole workspace only while it is open.
1001 <View
1002 className="absolute inset-y-0 left-0"
1003 style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
1005 <AndroidWorkspaceNavigation
1006 onNewThread={handleStartNewTask}
1007 rail
1008 onSelect={revealPrimarySidebar}
1009 onOverlayChange={setRailOverlay}
1010 />
1011 </View>
1012 ) : null}
1013 </View>
1014 );
1015​
1016 return (
1017 <HomeListOptionsProvider
1018 projectGroupingMode={projectGroupingMode}
1019 savedFilters={props.savedThreadListFilters}
1021 <AdaptiveWorkspaceContext.Provider value={contextValue}>
1022 <WindowHingeContext value={windowHinge}>
1023 {usesPresentationHost ? (
1024 <WorkspaceColumnsRendererContext value={renderColumns}>
1025 {props.children}
1026 </WorkspaceColumnsRendererContext>
1027 ) : (
1028 renderColumns(props.children)
1029 )}
1030 </WindowHingeContext>
1031 </AdaptiveWorkspaceContext.Provider>
1032 </HomeListOptionsProvider>
1033 );