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