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 primarySidebarPreferredVisible: showPrimarySidebar,
328 auxiliaryPanePreferredVisible,
329 auxiliaryPaneRole,
330 auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
331 }),
332 [
333 auxiliaryPanePreferredVisible,
334 auxiliaryPaneRole,
335 auxiliaryPanePreferredWidth,
336 layout,
337 showPrimarySidebar,
338 width,
339 ],
340 );
341 const activeThread = parseActiveThreadPath(pathname);
342 const environmentId = activeThread?.environmentId ?? null;
343 const threadId = activeThread?.threadId ?? null;
344 const selectedThreadKey = (() => {
345 if (environmentId === null || threadId === null) {
346 return null;
347 }
348 try {
349 return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
350 } catch {
351 return null;
352 }
353 })();
354 const [workspaceInspector, setWorkspaceInspector] = useState<{
355 readonly render: () => ReactNode;
356 readonly active: boolean;
357 } | null>(null);
358 const workspaceInspectorOwner = useRef<symbol | null>(null);
359 const registerWorkspaceInspector = (render: () => ReactNode) => {
360 const owner = Symbol("workspace-inspector");
361 workspaceInspectorOwner.current = owner;
362 setWorkspaceInspector({ render, active: true });
363
364 return () => {
365 // Outgoing screens deactivate after incoming registration; only the current owner may deactivate.
366 if (workspaceInspectorOwner.current !== owner) {
367 return;
368 }
369 setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
370 };
371 };
372 const handleWorkspaceInspectorClosed = () => {
373 setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
374 };
375 const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => {
376 const owner = Symbol(role);
377 activeRoleOwner.current = owner;
378 setFocusedAuxiliaryPaneRole(role);
379
380 return () => {
381 if (activeRoleOwner.current !== owner) {
382 return;
383 }
384 activeRoleOwner.current = null;
385 setFocusedAuxiliaryPaneRole(null);
386 };
387 };
388 const setPrimarySidebarVisible = (visible: boolean) => {
389 if (layout.primarySidebarOverlaysContent) {
390 setOverlaySidebar((current) => ({ ...current, visible }));
391 } else {
392 setPrimarySidebarPreferredVisible(visible);
393 }
394 };
395 const togglePrimarySidebar = () => {
396 if (primarySidebarPinned) {
397 return;
398 }
399 // A sidebar the keyboard set aside returns with the keyboard; the user's preference stays
400 // intact. One the user had hidden still opens.
401 if (composerKeyboardActive) {
402 void KeyboardController.dismiss();
403 if (primarySidebarPreferredVisible) return;
404 }
405 if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
406 setFileInspectorPreferredVisible(false);
407 setPrimarySidebarPreferredVisible(true);
408 return;
409 }
410 setPrimarySidebarVisible(!preferredSidebarVisible);
411 };
412 const revealPrimarySidebar = () => {
413 if (composerKeyboardActive) void KeyboardController.dismiss();
414 if (panes.primarySidebarSuppressedByAuxiliary) {
415 setFileInspectorPreferredVisible(false);
416 }
417 setPrimarySidebarVisible(true);
418 };
419 const handleToggleSidebarCommand = () => {
420 togglePrimarySidebar();
421 return true;
422 };
423 const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);
424 useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);
425 const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => {
426 if (role === "inspector") {
427 setFocusedAuxiliaryPaneRole("inspector");
428 setFileInspectorPreferredVisible(true);
429 return;
430 }
431 setFocusedAuxiliaryPaneRole("supplementary");
432 setSupplementaryPanePreferredVisible(true);
433 };
434 const handleOpenFilesCommand = () => {
435 const activeThread = parseActiveThreadPath(pathname);
436 if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
437 return false;
438 }
439 showAuxiliaryPane("inspector");
440 if (/\/files(?:\/|$)/.test(pathname)) {
441 return true;
442 }
443 navigation.navigate("ThreadFiles", activeThread);
444 return true;
445 };
446 useHardwareKeyboardCommand("files", handleOpenFilesCommand);
447 const toggleAuxiliaryPane = () => {
448 if (auxiliaryPaneRole === "inspector") {
449 setFileInspectorPreferredVisible((current) => !current);
450 return;
451 }
452 setSupplementaryPanePreferredVisible((current) => !current);
453 };
454 const setAuxiliaryPaneWidth = (nextWidth: number) => {
455 if (auxiliaryPaneRole === "inspector") {
456 setFileInspectorPreferredWidth(nextWidth);
457 return;
458 }
459 setSupplementaryPanePreferredWidth(nextWidth);
460 };
461 /**
462 * The one way to open a workspace tab: replaces the workspace with the tab's list and, when the
463 * window has columns, the page it last showed, keeping any sheet on top. An overlay sidebar
464 * stays open over that page.
465 */
466 const openWorkspaceTab = (
467 tab: WorkspaceTab | "settings",
468 options?: { readonly columns?: boolean },
469 ) => {
470 const state = rootStackState(navigation);
471 if (!state) return;
472 const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
473 const next = workspaceTabNavigationState(
474 { ...state, routes: workspace },
475 tab,
476 currentWorkspaceSelections(),
477 {
478 columns: Platform.OS === "ios" && (options?.columns ?? layout.usesSplitView),
479 check: workspaceSelectionCheck,
480 overlays,
481 },
482 );
483 if (layout.primarySidebarOverlaysContent) {
484 const opened = next.routes.at(-1 - overlays.length)?.key ?? null;
485 setOverlaySidebar((current) => ({ ...current, visible: true, keepOpenFor: opened }));
486 }
487 dispatchRootStackReset(navigation, state, next);
488 };
489 const handleOpenSettings = () => openWorkspaceTab("settings");
490
491 const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
492 /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
493 function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
494 deferredThreadSelection.run(() => {
495 if (Platform.OS === "android") Keyboard.dismiss();
496 setFileInspectorPreferredVisible(false);
497 if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
498 workspace?.dispatch({
499 type: "select",
500 tab: detail.name === "Thread" ? "threads" : "pullRequests",
501 });
502 startOpeningDetail(detail);
503 navigation.dispatch(selectWorkspaceDetail(detail, sheet));
504 });
505 }
506 const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) =>
507 handleSelectDetail({ name: "Thread", params });
508
509 const projects = useProjects();
510 const compactAndroidSettings =
511 Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;
512 // Reads the open page when pressed, so the layout context doesn't change on every navigation.
513 const handleStartNewTask = () => {
514 const state = rootStackState(navigation);
515 const currentRoute = workspaceRoutesOf(
516 state?.routes.slice(0, state.index + 1) ?? [],
517 ).workspace.at(-1);
518 const params =
519 currentRoute?.name === "Thread"
520 ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])
521 : undefined;
522 const first = (value: string | string[] | undefined) =>
523 Array.isArray(value) ? value[0] : value;
524 const thread = appAtomRegistry
525 .get(environmentThreadShells.navigationThreadShellsAtom)
526 .find(
527 (candidate) =>
528 candidate.environmentId === first(params?.environmentId) &&
529 candidate.id === first(params?.threadId),
530 );
531 const draft = params?.draft;
532 const draftEnvironmentId = first(draft?.environmentId);
533 const draftProjectId = first(draft?.projectId);
534 const currentProject = thread
535 ? { environmentId: thread.environmentId, id: thread.projectId }
536 : projects.find(
537 (project) =>
538 project.environmentId === draftEnvironmentId && project.id === draftProjectId,
539 );
540 handleSelectThreadRoute(
541 newTaskDestination(layout.usesSplitView, projects, currentProject, uuidv4()),
542 );
543 };
544
545 useHardwareKeyboardCommand("newTask", () => {
546 handleStartNewTask();
547 return true;
548 });
549
550 // Create at root: the iOS sidebar renders in an independent navigation tree.
551 const handleOpenEnvironmentSettings = () => {
552 openSettings(navigation, "SettingsEnvironments");
553 };
554
555 const handleOpenThreadPullRequests = useOpenThreadPullRequests();
556 const { openPendingTask: handleOpenPendingTask } =
557 usePendingTaskListActions(handleSelectThreadRoute);
558
559 const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {
560 handleSelectThreadRoute({
561 draft: {
562 requestId: uuidv4(),
563 environmentId: String(thread.environmentId),
564 projectId: String(thread.projectId),
565 branch: thread.branch,
566 worktreePath: thread.worktreePath,
567 },
568 });
569 };
570
571 const handleNewThreadInProject = (project: EnvironmentProject) => {
572 handleSelectThreadRoute({
573 draft: {
574 requestId: uuidv4(),
575 environmentId: String(project.environmentId),
576 projectId: String(project.id),
577 title: project.title,
578 },
579 });
580 };
581
582 const inspectorColumnTargetWidth =
583 workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
584 ? (panes.auxiliaryPaneWidth ?? 0)
585 : 0;
586 const contentTargetWidth = layout.usesSplitView
587 ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth)
588 : null;
589 const [listPaneSizing, setListPaneSizing] = useState({
590 viewportWidth,
591 workspacePage,
592 sidebarVisible: panes.primarySidebarVisible,
593 listPaneTarget: layout.listPaneWidth,
594 listPaneFloor: layout.listPaneWidth,
595 listPaneCeiling: layout.listPaneWidth,
596 revision: 0,
597 });
598 if (
599 Platform.OS === "android" &&
600 (listPaneSizing.viewportWidth !== viewportWidth ||
601 listPaneSizing.workspacePage !== workspacePage ||
602 listPaneSizing.sidebarVisible !== panes.primarySidebarVisible ||
603 listPaneSizing.listPaneTarget !== layout.listPaneWidth)
604 ) {
605 // A book-posture hinge resizes the visible list pane instead of revealing it.
606 const resizingSidebar =
607 listPaneSizing.viewportWidth === viewportWidth &&
608 listPaneSizing.workspacePage === workspacePage &&
609 listPaneSizing.sidebarVisible &&
610 panes.primarySidebarVisible &&
611 listPaneSizing.listPaneTarget !== layout.listPaneWidth;
612 setListPaneSizing({
613 viewportWidth,
614 workspacePage,
615 sidebarVisible: panes.primarySidebarVisible,
616 listPaneTarget: layout.listPaneWidth,
617 // Retargets widen the list-width span because the animated hinge edge may still be inside it.
618 listPaneFloor: resizingSidebar
619 ? Math.min(listPaneSizing.listPaneFloor ?? 0, layout.listPaneWidth ?? 0)
620 : layout.listPaneWidth,
621 listPaneCeiling: resizingSidebar
622 ? Math.max(listPaneSizing.listPaneCeiling ?? 0, layout.listPaneWidth ?? 0)
623 : layout.listPaneWidth,
624 revision: listPaneSizing.revision + 1,
625 });
626 }
627 const settleListPane = (revision: number) => {
628 setListPaneSizing((current) =>
629 current.revision !== revision ||
630 (current.listPaneFloor === current.listPaneTarget &&
631 current.listPaneCeiling === current.listPaneTarget)
632 ? current
633 : {
634 ...current,
635 listPaneFloor: current.listPaneTarget,
636 listPaneCeiling: current.listPaneTarget,
637 },
638 );
639 };
640 const listPaneFloor = listPaneSizing.listPaneFloor ?? 0;
641 const listPaneCeiling = listPaneSizing.listPaneCeiling ?? 0;
642 const listPaneRevision = listPaneSizing.revision;
643 // Android lays the content out at its new width as soon as a pane toggles, then holds it
644 // against the edge that stays put while the other one slides, so nothing reflows after the
645 // panes land. A sliding sidebar uncovers the strip it is about to fill, or covers the content
646 // until it is gone.
647 const contentLeftTarget =
648 navigationRailWidth +
649 (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible
650 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
651 : 0);
652 const [contentAnchor, setContentAnchor] = useState({
653 viewportWidth,
654 left: contentLeftTarget,
655 inspector: inspectorColumnTargetWidth,
656 end: false,
657 });
658 if (
659 Platform.OS === "android" &&
660 (contentAnchor.viewportWidth !== viewportWidth ||
661 contentAnchor.left !== contentLeftTarget ||
662 contentAnchor.inspector !== inspectorColumnTargetWidth)
663 ) {
664 setContentAnchor({
665 viewportWidth,
666 left: contentLeftTarget,
667 inspector: inspectorColumnTargetWidth,
668 end:
669 contentAnchor.viewportWidth === viewportWidth &&
670 contentAnchor.inspector === inspectorColumnTargetWidth,
671 });
672 }
673
674 const renderedSidebarWidth = useSharedValue(
675 panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0,
676 );
677 const renderedRailWidth = useSharedValue(navigationRailWidth);
678 const leavingWorkspacePage = useRef(false);
679 useEffect(() => {
680 if (nativeWorkspace) return;
681 renderedRailWidth.set(withTiming(navigationRailWidth, WORKSPACE_PANE_TIMING));
682 // A workspace page hides the sidebar through React instead, in the same commit that mounts
683 // the page. Animating it here would hide it a few frames before the page appears.
684 if (workspacePage) {
685 leavingWorkspacePage.current = true;
686 return;
687 }
688 const snap = leavingWorkspacePage.current;
689 leavingWorkspacePage.current = false;
690 const targetWidth = panes.primarySidebarVisible
691 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
692 : 0;
693 // The content beside it already took its final width when the page closed.
694 renderedSidebarWidth.set(
695 withTiming(targetWidth, snap ? { duration: 0 } : WORKSPACE_PANE_TIMING, (finished) => {
696 if (finished && Platform.OS === "android") runOnJS(settleListPane)(listPaneRevision);
697 }),
698 );
699 }, [
700 nativeWorkspace,
701 navigationRailWidth,
702 layout.listPaneWidth,
703 layout.listPaneGap,
704 panes.primarySidebarVisible,
705 renderedSidebarWidth,
706 renderedRailWidth,
707 settleListPane,
708 listPaneRevision,
709 workspacePage,
710 ]);
711 const railAnimatedStyle = useAnimatedStyle(() => ({ width: renderedRailWidth.value }));
712 // Showing or hiding the sidebar clips a fixed-width list. A hinge resize instead tracks the
713 // animated edge, so the header actions slide with it rather than jumping or being covered.
714 const listPaneGap = layout.listPaneGap ?? 0;
715 const listPaneAnimatedStyle = useAnimatedStyle(() => ({
716 width: Math.min(
717 listPaneCeiling,
718 Math.max(listPaneFloor, renderedSidebarWidth.value - listPaneGap),
719 ),
720 }));
721 const sidebarAnimatedStyle = useAnimatedStyle(() => ({
722 // Fading a UIKit glass ancestor can leave remounted header effects missing.
723 opacity: Platform.OS === "ios" ? 1 : Math.min(1, renderedSidebarWidth.value / 80),
724 width: renderedSidebarWidth.value,
725 }));
726
727 // Clip the navigator at its settled width so native headers and markdown reflow only once per pane toggle.
728 const renderedInspectorWidth = useSharedValue(inspectorColumnTargetWidth);
729 const renderedContentWidth = useDerivedValue(() =>
730 Math.max(
731 0,
732 viewportWidth -
733 renderedRailWidth.value -
734 renderedSidebarWidth.value -
735 renderedInspectorWidth.value,
736 ),
737 );
738
739 const handleSelectThread = (thread: EnvironmentThreadShell) => {
740 handleSelectThreadRoute({
741 environmentId: String(thread.environmentId),
742 threadId: String(thread.id),
743 });
744 };
745
746 const contextValue = {
747 layout,
748 panes,
749 fileInspector,
750 primarySidebarSearchQuery,
751 startNewTask: handleStartNewTask,
752 deferThreadSelectionUntil: deferredThreadSelection.waitFor,
753 selectDetail: handleSelectDetail,
754 activateAuxiliaryPaneRole,
755 registerWorkspaceInspector,
756 setPrimarySidebarSearchQuery,
757 showAuxiliaryPane,
758 toggleAuxiliaryPane,
759 togglePrimarySidebar,
760 setPrimarySidebarVisible,
761 openWorkspaceTab,
762 setAuxiliaryPaneWidth,
763 composerKeyboardActive,
764 setComposerEditing,
765 };
766
767 if (nativeWorkspace) {
768 return (
769 <HomeListOptionsProvider
770 projectGroupingMode={projectGroupingMode}
771 savedFilters={props.savedThreadListFilters}
772 >
773 <AdaptiveWorkspaceContext value={contextValue}>
774 <NativeWorkspaceInspectorContext
775 value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}
776 >
777 {props.children}
778 </NativeWorkspaceInspectorContext>
779 </AdaptiveWorkspaceContext>
780 </HomeListOptionsProvider>
781 );
782 }
783 return (
784 <HomeListOptionsProvider
785 projectGroupingMode={projectGroupingMode}
786 savedFilters={props.savedThreadListFilters}
787 >
788 <AdaptiveWorkspaceContext.Provider value={contextValue}>
789 <WindowHingeContext value={windowHinge}>
790 <View
791 testID="adaptive-workspace-layout"
792 className={Platform.OS === "android" ? "flex-1 flex-row bg-header" : "flex-1 flex-row"}
793 >
794 <AndroidHingeObserver onChange={handleHingeChange} />
795 {shouldRenderNavigationRail ? (
796 <Animated.View className="self-stretch" style={railAnimatedStyle} />
797 ) : null}
798 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
799 <Animated.View
800 className="self-stretch overflow-hidden"
801 accessibilityElementsHidden={!panes.primarySidebarVisible}
802 collapsable={false}
803 importantForAccessibility={
804 panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
805 }
806 pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
807 // Under a workspace page the sidebar leaves the row but keeps its size, so its
808 // lists never lay out at zero size and are ready, unchanged, on the way back. The
809 // content pane, laid out after it, covers it, in the same mount as the page.
810 style={[
811 workspacePage ? { position: "absolute", top: 0, bottom: 0, left: 0 } : null,
812 sidebarAnimatedStyle,
813 ]}
814 >
815 <Animated.View className="flex-1" style={listPaneAnimatedStyle}>
816 <RenderErrorBoundary
817 renderFallback={(fallback) => (
818 <RenderFailureView
819 {...fallback}
820 title="The sidebar couldn't be displayed"
821 exit={{ label: "Open settings", onPress: handleOpenSettings }}
822 />
823 )}
824 >
825 <AndroidWorkspaceSidebar
826 onRequestVisibility={revealPrimarySidebar}
827 selectedPullRequestKey={props.selectedPullRequestKey ?? null}
828 >
829 <AndroidHomeFabLayout sidebar onStartNewTask={handleStartNewTask}>
830 <ThreadNavigationSidebar
831 width={layout.listPaneWidth}
832 visible={panes.primarySidebarVisible}
833 onRequestVisibility={revealPrimarySidebar}
834 selectedThreadKey={selectedThreadKey}
835 onOpenSettings={handleOpenSettings}
836 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
837 onNewThreadInProject={handleNewThreadInProject}
838 onNewThreadOnBranch={handleNewThreadOnBranch}
839 onOpenPendingTask={handleOpenPendingTask}
840 onSelectThread={handleSelectThread}
841 onOpenThreadPullRequests={handleOpenThreadPullRequests}
842 onSearchQueryChange={setPrimarySidebarSearchQuery}
843 searchQuery={primarySidebarSearchQuery}
844 />
845 </AndroidHomeFabLayout>
846 </AndroidWorkspaceSidebar>
847 </RenderErrorBoundary>
848 </Animated.View>
849 </Animated.View>
850 ) : null}
851 <View
852 className={
853 Platform.OS === "android"
854 ? "flex-1 overflow-hidden bg-header"
855 : "flex-1 overflow-hidden bg-screen"
856 }
857 collapsable={false}
858 >
859 <View
860 collapsable={false}
861 style={
862 contentTargetWidth !== null
863 ? {
864 flex: 1,
865 width: contentTargetWidth,
866 alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
867 }
868 : { flex: 1 }
869 }
870 >
871 {/* Android holds the content still, so its floating controls keep its width. */}
872 <WorkspaceContentWidthContext
873 value={
874 layout.usesSplitView && Platform.OS !== "android" ? renderedContentWidth : null
875 }
876 >
877 <WorkspaceSettledContentWidthContext
878 value={
879 Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null
880 }
881 >
882 {/* Compact Settings keeps the bottom navigation under all of its pages. */}
883 <SafeAreaInsetsContext
884 value={
885 compactAndroidSettings ? { ...safeAreaInsets, bottom: 0 } : safeAreaInsets
886 }
887 >
888 <View className="flex-1">{props.children}</View>
889 </SafeAreaInsetsContext>
890 {compactAndroidSettings ? (
891 <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
892 ) : null}
893 </WorkspaceSettledContentWidthContext>
894 </WorkspaceContentWidthContext>
895 </View>
896 </View>
897 <WorkspaceInspectorPane
898 pathname={props.pathname}
899 renderedInspectorWidth={renderedInspectorWidth}
900 active={workspaceInspector?.active ?? false}
901 panes={panes}
902 renderInspector={workspaceInspector?.render}
903 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
904 onClosed={handleWorkspaceInspectorClosed}
905 />
906 {shouldRenderNavigationRail && navigationRailWidth > 0 ? (
907 // The rail reserves its slot above and draws over the panes, so it can widen over
908 // the list in place. It takes the whole workspace only while it is open.
909 <View
910 className="absolute inset-y-0 left-0"
911 style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
912 >
913 <AndroidWorkspaceNavigation
914 onNewThread={handleStartNewTask}
915 rail
916 onSelect={revealPrimarySidebar}
917 onOverlayChange={setRailOverlay}
918 />
919 </View>
920 ) : null}
921 </View>
922 </WindowHingeContext>
923 </AdaptiveWorkspaceContext.Provider>
924 </HomeListOptionsProvider>
925 );
926}