Open History to see the last commit
1import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
2import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";
3import { createDeferredNavigation } 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 }, [wrappedRender]);
152
153 useEffect(
154 () => () => {
155 deactivateRef.current?.();
156 deactivateRef.current = null;
157 },
158 [],
159 );
160}
161
162export function AdaptiveWorkspaceLayout(props: {
163 readonly children: ReactNode;
164 readonly pathname: string;
165 readonly workspaceRouteKey: string | undefined;
166 readonly selectedPullRequestKey?: string | null;
167}) {
168 const preferencesResult = useAtomValue(mobilePreferencesAtom);
169 if (!AsyncResult.isSuccess(preferencesResult)) {
170 return AsyncResult.isFailure(preferencesResult) ? (
171 <AdaptiveWorkspaceLayoutContent
172 {...props}
173 projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
174 />
175 ) : null;
176 }
177 const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
178 return (
179 <AdaptiveWorkspaceLayoutContent
180 {...props}
181 projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
182 savedThreadListFilters={preferencesResult.value.threadListFilters}
183 />
184 );
185}
186
187function AdaptiveWorkspaceLayoutContent(
188 props: {
189 readonly children: ReactNode;
190 readonly pathname: string;
191 readonly workspaceRouteKey: string | undefined;
192 readonly selectedPullRequestKey?: string | null;
193 } & {
194 readonly projectGroupingMode: SidebarProjectGroupingMode;
195 readonly savedThreadListFilters?: ThreadListFilters | undefined;
196 },
197) {
198 const projectGroupingMode = props.projectGroupingMode;
199 const nativeWorkspace = use(NativeWorkspaceModeContext);
200 const windowDimensions = useWindowDimensions();
201 const nativeMetrics = useNativeLayoutMetrics();
202 const { width: viewportWidth, height } = nativeMetrics ?? windowDimensions;
203 const pathname = props.pathname;
204 const workspace = useWorkspaceTabs();
205 // Settings and Usage occupy the workspace rather than a list/detail pair.
206 const androidSettingsOpen = useAndroidWorkspaceRoot()?.settingsOpen ?? false;
207 const safeAreaInsets = useSafeAreaInsets();
208 const workspacePage =
209 Platform.OS === "android" && (androidSettingsOpen || workspace?.state.selectedTab === "usage");
210 const navigation = useNavigation();
211 const activeRoleOwner = useRef<symbol | null>(null);
212 const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
213 const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
214 const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
215 number | null
216 >(null);
217 const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);
218 const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
219 null,
220 );
221 const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
222 const [railOverlay, setRailOverlay] = useState(false);
223 const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
224 useState<WorkspaceAuxiliaryPaneRole | null>(null);
225 // The compiler can't memoize these derivations: they stay live across later hook calls. Fresh
226 // objects here change the workspace context on every render, so every workspace screen
227 // re-renders on any layout state change, and the inspector registration then loops: each
228 // re-register re-renders its screen, which hands over a new inspector renderer.
229 const baseLayout = useMemo(
230 () => deriveLayout({ width: viewportWidth, height, nativeMetrics, nativeWorkspace }),
231 [height, viewportWidth, nativeMetrics, nativeWorkspace],
232 );
233 // The overlay sidebar closes when a page opens from it, and stays open on a list or on the
234 // page a tab switch opened (`keepOpenFor`, set by that switch).
235 const [overlaySidebar, setOverlaySidebar] = useState({
236 active: baseLayout.primarySidebarOverlaysContent,
237 pathname,
238 visible: isWorkspaceListPath(pathname),
239 keepOpenFor: null as string | null,
240 });
241 if (
242 overlaySidebar.active !== baseLayout.primarySidebarOverlaysContent ||
243 (overlaySidebar.active && overlaySidebar.pathname !== pathname)
244 ) {
245 setOverlaySidebar({
246 active: baseLayout.primarySidebarOverlaysContent,
247 pathname,
248 visible:
249 isWorkspaceListPath(pathname) ||
250 (overlaySidebar.keepOpenFor !== null &&
251 overlaySidebar.keepOpenFor === props.workspaceRouteKey),
252 keepOpenFor: null,
253 });
254 }
255 const preferredSidebarVisible = baseLayout.primarySidebarOverlaysContent
256 ? overlaySidebar.visible
257 : primarySidebarPreferredVisible;
258 const primarySidebarPinned = isPrimarySidebarPinned({
259 pathname,
260 nativeWorkspace,
261 usesSplitView: baseLayout.usesSplitView,
262 });
263 const [composerEditing, setComposerEditing] = useState(false);
264 const softKeyboardVisible = useKeyboardState((state) => state.isVisible);
265 // Keyed on the soft keyboard, not focus: a hardware keyboard leaves room for the sidebar, and
266 // Back closes the keyboard while the editor keeps focus. Deferred so the composer commits its
267 // keyboard render first; relaying out in the same commit held it behind the keyboard.
268 const composerKeyboardActive = useDeferredValue(
269 Platform.OS === "android" && baseLayout.usesSplitView && composerEditing && softKeyboardVisible,
270 );
271 const showPrimarySidebar =
272 !workspacePage &&
273 (primarySidebarPinned || (preferredSidebarVisible && !composerKeyboardActive));
274 const shouldRenderNavigationRail = Platform.OS === "android" && baseLayout.usesSplitView;
275 const navigationRailWidth =
276 shouldRenderNavigationRail && (showPrimarySidebar || workspacePage)
277 ? ANDROID_WORKSPACE_RAIL_WIDTH
278 : 0;
279 const [hinge, setHinge] = useState<VerticalHinge | null>(null);
280 const [windowHinge, setWindowHinge] = useState<VerticalHinge | null>(null);
281 const handleHingeChange = (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {
282 setHinge(next);
283 setWindowHinge(nextWindow);
284 };
285 const layout = useMemo(
286 () =>
287 alignListPaneToHinge({
288 layout: baseLayout,
289 hinge,
290 viewportWidth,
291 leadingWidth: navigationRailWidth,
292 }),
293 [baseLayout, hinge, navigationRailWidth, viewportWidth],
294 );
295 const width = viewportWidth - navigationRailWidth;
296 // The sidebar stays mounted under a workspace page, so its list is ready on the way back.
297 const shouldRenderPrimarySidebar = layout.usesSplitView;
298 const fileInspector = useMemo(
299 () =>
300 deriveFileInspectorPaneLayout({
301 layout,
302 viewportWidth: width,
303 preferredWidth: fileInspectorPreferredWidth ?? undefined,
304 reservedLeadingWidth:
305 shouldRenderPrimarySidebar && showPrimarySidebar && !layout.primarySidebarOverlaysContent
306 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
307 : 0,
308 }),
309 [fileInspectorPreferredWidth, layout, showPrimarySidebar, shouldRenderPrimarySidebar, width],
310 );
311 const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
312 focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
313 const auxiliaryPanePreferredVisible =
314 !workspacePage &&
315 (auxiliaryPaneRole === "inspector"
316 ? fileInspectorPreferredVisible
317 : supplementaryPanePreferredVisible);
318 const auxiliaryPanePreferredWidth =
319 auxiliaryPaneRole === "inspector"
320 ? fileInspectorPreferredWidth
321 : supplementaryPanePreferredWidth;
322 const panes = useMemo(
323 () =>
324 deriveWorkspacePaneLayout({
325 layout,
326 viewportWidth: width,
327 nativeWorkspace,
328 primarySidebarPreferredVisible: showPrimarySidebar,
329 auxiliaryPanePreferredVisible,
330 auxiliaryPaneRole,
331 auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
332 }),
333 [
334 auxiliaryPanePreferredVisible,
335 auxiliaryPaneRole,
336 auxiliaryPanePreferredWidth,
337 layout,
338 nativeWorkspace,
339 showPrimarySidebar,
340 width,
341 ],
342 );
343 const activeThread = parseActiveThreadPath(pathname);
344 const environmentId = activeThread?.environmentId ?? null;
345 const threadId = activeThread?.threadId ?? null;
346 const selectedThreadKey = (() => {
347 if (environmentId === null || threadId === null) {
348 return null;
349 }
350 try {
351 return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
352 } catch {
353 return null;
354 }
355 })();
356 const [workspaceInspector, setWorkspaceInspector] = useState<{
357 readonly render: () => ReactNode;
358 readonly active: boolean;
359 } | null>(null);
360 const workspaceInspectorOwner = useRef<symbol | null>(null);
361 const registerWorkspaceInspector = (render: () => ReactNode) => {
362 const owner = Symbol("workspace-inspector");
363 workspaceInspectorOwner.current = owner;
364 setWorkspaceInspector({ render, active: true });
365
366 return () => {
367 // Outgoing screens deactivate after incoming registration; only the current owner may deactivate.
368 if (workspaceInspectorOwner.current !== owner) {
369 return;
370 }
371 setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
372 };
373 };
374 const handleWorkspaceInspectorClosed = () => {
375 setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
376 };
377 const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => {
378 const owner = Symbol(role);
379 activeRoleOwner.current = owner;
380 setFocusedAuxiliaryPaneRole(role);
381
382 return () => {
383 if (activeRoleOwner.current !== owner) {
384 return;
385 }
386 activeRoleOwner.current = null;
387 setFocusedAuxiliaryPaneRole(null);
388 };
389 };
390 const setPrimarySidebarVisible = (visible: boolean) => {
391 if (layout.primarySidebarOverlaysContent) {
392 setOverlaySidebar((current) => ({ ...current, visible }));
393 } else {
394 setPrimarySidebarPreferredVisible(visible);
395 }
396 };
397 const togglePrimarySidebar = () => {
398 if (primarySidebarPinned) {
399 return;
400 }
401 // A sidebar the keyboard set aside returns with the keyboard; the user's preference stays
402 // intact. One the user had hidden still opens.
403 if (composerKeyboardActive) {
404 void KeyboardController.dismiss();
405 if (primarySidebarPreferredVisible) return;
406 }
407 if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
408 setFileInspectorPreferredVisible(false);
409 setPrimarySidebarPreferredVisible(true);
410 return;
411 }
412 setPrimarySidebarVisible(!preferredSidebarVisible);
413 };
414 const revealPrimarySidebar = () => {
415 if (composerKeyboardActive) void KeyboardController.dismiss();
416 if (panes.primarySidebarSuppressedByAuxiliary) {
417 setFileInspectorPreferredVisible(false);
418 }
419 setPrimarySidebarVisible(true);
420 };
421 const handleToggleSidebarCommand = () => {
422 togglePrimarySidebar();
423 return true;
424 };
425 const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);
426 useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);
427 const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => {
428 if (role === "inspector") {
429 setFocusedAuxiliaryPaneRole("inspector");
430 setFileInspectorPreferredVisible(true);
431 return;
432 }
433 setFocusedAuxiliaryPaneRole("supplementary");
434 setSupplementaryPanePreferredVisible(true);
435 };
436 const handleOpenFilesCommand = () => {
437 const activeThread = parseActiveThreadPath(pathname);
438 if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
439 return false;
440 }
441 showAuxiliaryPane("inspector");
442 if (/\/files(?:\/|$)/.test(pathname)) {
443 return true;
444 }
445 navigation.navigate("ThreadFiles", activeThread);
446 return true;
447 };
448 useHardwareKeyboardCommand("files", handleOpenFilesCommand);
449 const toggleAuxiliaryPane = () => {
450 if (auxiliaryPaneRole === "inspector") {
451 setFileInspectorPreferredVisible((current) => !current);
452 return;
453 }
454 setSupplementaryPanePreferredVisible((current) => !current);
455 };
456 const setAuxiliaryPaneWidth = (nextWidth: number) => {
457 if (auxiliaryPaneRole === "inspector") {
458 setFileInspectorPreferredWidth(nextWidth);
459 return;
460 }
461 setSupplementaryPanePreferredWidth(nextWidth);
462 };
463 /**
464 * The one way to open a workspace tab: replaces the workspace with the tab's list and, when the
465 * window has columns, the page it last showed, keeping any sheet on top. An overlay sidebar
466 * stays open over that page.
467 */
468 const openWorkspaceTab = (
469 tab: WorkspaceTab | "settings",
470 options?: { readonly columns?: boolean },
471 ) => {
472 const state = rootStackState(navigation);
473 if (!state) return;
474 const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
475 const next = workspaceTabNavigationState(
476 { ...state, routes: workspace },
477 tab,
478 currentWorkspaceSelections(),
479 {
480 columns: Platform.OS === "ios" && (options?.columns ?? layout.usesSplitView),
481 check: workspaceSelectionCheck,
482 overlays,
483 },
484 );
485 if (layout.primarySidebarOverlaysContent) {
486 const opened = next.routes.at(-1 - overlays.length)?.key ?? null;
487 setOverlaySidebar((current) => ({ ...current, visible: true, keepOpenFor: opened }));
488 }
489 dispatchRootStackReset(navigation, state, next);
490 };
491 const handleOpenSettings = () => openWorkspaceTab("settings");
492
493 const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
494 /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
495 function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
496 deferredThreadSelection.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 deferThreadSelectionUntil: deferredThreadSelection.waitFor,
773 selectDetail: handleSelectDetail,
774 activateAuxiliaryPaneRole,
775 registerWorkspaceInspector,
776 setPrimarySidebarSearchQuery,
777 showAuxiliaryPane,
778 toggleAuxiliaryPane,
779 togglePrimarySidebar,
780 setPrimarySidebarVisible,
781 openWorkspaceTab,
782 setAuxiliaryPaneWidth,
783 composerKeyboardActive,
784 setComposerEditing,
785 sidebarByOrientation,
786 };
787
788 if (nativeWorkspace) {
789 return (
790 <HomeListOptionsProvider
791 projectGroupingMode={projectGroupingMode}
792 savedFilters={props.savedThreadListFilters}
793 >
794 <AdaptiveWorkspaceContext value={contextValue}>
795 <NativeWorkspaceInspectorContext
796 value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}
797 >
798 {props.children}
799 </NativeWorkspaceInspectorContext>
800 </AdaptiveWorkspaceContext>
801 </HomeListOptionsProvider>
802 );
803 }
804 return (
805 <HomeListOptionsProvider
806 projectGroupingMode={projectGroupingMode}
807 savedFilters={props.savedThreadListFilters}
808 >
809 <AdaptiveWorkspaceContext.Provider value={contextValue}>
810 <WindowHingeContext value={windowHinge}>
811 <View
812 testID="adaptive-workspace-layout"
813 className={Platform.OS === "android" ? "flex-1 flex-row bg-header" : "flex-1 flex-row"}
814 >
815 <AndroidHingeObserver onChange={handleHingeChange} />
816 {shouldRenderNavigationRail ? (
817 <Animated.View className="self-stretch" style={railAnimatedStyle} />
818 ) : null}
819 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
820 <Animated.View
821 className="self-stretch overflow-hidden"
822 accessibilityElementsHidden={!panes.primarySidebarVisible}
823 collapsable={false}
824 importantForAccessibility={
825 panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
826 }
827 pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
828 // Under a workspace page the sidebar leaves the row but keeps its size, so its
829 // lists never lay out at zero size and are ready, unchanged, on the way back. The
830 // content pane, laid out after it, covers it, in the same mount as the page.
831 style={[
832 workspacePage ? { position: "absolute", top: 0, bottom: 0, left: 0 } : null,
833 sidebarAnimatedStyle,
834 ]}
835 >
836 <Animated.View className="flex-1" style={listPaneAnimatedStyle}>
837 <RenderErrorBoundary
838 renderFallback={(fallback) => (
839 <RenderFailureView
840 {...fallback}
841 title="The sidebar couldn't be displayed"
842 exit={{ label: "Open settings", onPress: handleOpenSettings }}
843 />
844 )}
845 >
846 <AndroidWorkspaceSidebar
847 onRequestVisibility={revealPrimarySidebar}
848 selectedPullRequestKey={props.selectedPullRequestKey ?? null}
849 >
850 <AndroidHomeFabLayout sidebar onStartNewTask={handleStartNewTask}>
851 <ThreadNavigationSidebar
852 width={layout.listPaneWidth}
853 visible={panes.primarySidebarVisible}
854 onRequestVisibility={revealPrimarySidebar}
855 selectedThreadKey={selectedThreadKey}
856 onOpenSettings={handleOpenSettings}
857 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
858 onNewThreadInProject={handleNewThreadInProject}
859 onNewThreadOnBranch={handleNewThreadOnBranch}
860 onOpenPendingTask={handleOpenPendingTask}
861 onSelectThread={handleSelectThread}
862 onOpenThreadPullRequests={handleOpenThreadPullRequests}
863 onSearchQueryChange={setPrimarySidebarSearchQuery}
864 searchQuery={primarySidebarSearchQuery}
865 />
866 </AndroidHomeFabLayout>
867 </AndroidWorkspaceSidebar>
868 </RenderErrorBoundary>
869 </Animated.View>
870 </Animated.View>
871 ) : null}
872 <View
873 className={
874 Platform.OS === "android"
875 ? "flex-1 overflow-hidden bg-header"
876 : "flex-1 overflow-hidden bg-screen"
877 }
878 collapsable={false}
879 >
880 <View
881 collapsable={false}
882 style={
883 contentTargetWidth !== null
884 ? {
885 flex: 1,
886 width: contentTargetWidth,
887 alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
888 }
889 : { flex: 1 }
890 }
891 >
892 {/* Android holds the content still, so its floating controls keep its width. */}
893 <WorkspaceContentWidthContext
894 value={
895 layout.usesSplitView && Platform.OS !== "android" ? renderedContentWidth : null
896 }
897 >
898 <WorkspaceSettledContentWidthContext
899 value={
900 Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null
901 }
902 >
903 {/* Compact Settings keeps the bottom navigation under all of its pages. */}
904 <SafeAreaInsetsContext
905 value={
906 compactAndroidSettings ? { ...safeAreaInsets, bottom: 0 } : safeAreaInsets
907 }
908 >
909 <View className="flex-1">{props.children}</View>
910 </SafeAreaInsetsContext>
911 {compactAndroidSettings ? (
912 <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
913 ) : null}
914 </WorkspaceSettledContentWidthContext>
915 </WorkspaceContentWidthContext>
916 </View>
917 </View>
918 <WorkspaceInspectorPane
919 pathname={props.pathname}
920 renderedInspectorWidth={renderedInspectorWidth}
921 active={workspaceInspector?.active ?? false}
922 panes={panes}
923 renderInspector={workspaceInspector?.render}
924 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
925 onClosed={handleWorkspaceInspectorClosed}
926 />
927 {shouldRenderNavigationRail && navigationRailWidth > 0 ? (
928 // The rail reserves its slot above and draws over the panes, so it can widen over
929 // the list in place. It takes the whole workspace only while it is open.
930 <View
931 className="absolute inset-y-0 left-0"
932 style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
933 >
934 <AndroidWorkspaceNavigation
935 onNewThread={handleStartNewTask}
936 rail
937 onSelect={revealPrimarySidebar}
938 onOverlayChange={setRailOverlay}
939 />
940 </View>
941 ) : null}
942 </View>
943 </WindowHingeContext>
944 </AdaptiveWorkspaceContext.Provider>
945 </HomeListOptionsProvider>
946 );
947}