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

AdaptiveWorkspaceLayout.tsx

948 lines37.1 KB

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));
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 );
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 );
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 const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
495 /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
496 function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
497 deferredThreadSelection.run(() => {
498 if (Platform.OS === "android") Keyboard.dismiss();
499 setFileInspectorPreferredVisible(false);
500 if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
501 workspace?.dispatch({
502 type: "select",
503 tab: detail.name === "Thread" ? "threads" : "pullRequests",
504 });
505 startOpeningDetail(detail);
506 navigation.dispatch(selectWorkspaceDetail(detail, sheet));
507 });
508 }
509 const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) =>
510 handleSelectDetail({ name: "Thread", params });
511​
512 const projects = useProjects();
513 const compactAndroidSettings =
514 Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;
515 // Reads the open page when pressed, so the layout context doesn't change on every navigation.
516 const handleStartNewTask = () => {
517 const state = rootStackState(navigation);
518 const currentRoute = workspaceRoutesOf(
519 state?.routes.slice(0, state.index + 1) ?? [],
520 ).workspace.at(-1);
521 const params =
522 currentRoute?.name === "Thread"
523 ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])
524 : undefined;
525 const first = (value: string | string[] | undefined) =>
526 Array.isArray(value) ? value[0] : value;
527 const thread = appAtomRegistry
528 .get(environmentThreadShells.navigationThreadShellsAtom)
529 .find(
530 (candidate) =>
531 candidate.environmentId === first(params?.environmentId) &&
532 candidate.id === first(params?.threadId),
533 );
534 const draft = params?.draft;
535 const draftEnvironmentId = first(draft?.environmentId);
536 const draftProjectId = first(draft?.projectId);
537 const currentProject = thread
538 ? { environmentId: thread.environmentId, id: thread.projectId }
539 : projects.find(
540 (project) =>
541 project.environmentId === draftEnvironmentId && project.id === draftProjectId,
542 );
543 handleSelectThreadRoute(
544 newTaskDestination(layout.usesSplitView, projects, currentProject, uuidv4()),
545 );
546 };
547​
548 useHardwareKeyboardCommand("newTask", () => {
549 handleStartNewTask();
550 return true;
551 });
552​
553 // Create at root: the iOS sidebar renders in an independent navigation tree.
554 const handleOpenEnvironmentSettings = () => {
555 openSettings(navigation, "SettingsEnvironments");
556 };
557​
558 const handleOpenThreadPullRequests = useOpenThreadPullRequests();
559 const { openPendingTask: handleOpenPendingTask } =
560 usePendingTaskListActions(handleSelectThreadRoute);
561​
562 const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {
563 handleSelectThreadRoute({
564 draft: {
565 requestId: uuidv4(),
566 environmentId: String(thread.environmentId),
567 projectId: String(thread.projectId),
568 branch: thread.branch,
569 worktreePath: thread.worktreePath,
570 },
571 });
572 };
573​
574 const handleNewThreadInProject = (project: EnvironmentProject) => {
575 handleSelectThreadRoute({
576 draft: {
577 requestId: uuidv4(),
578 environmentId: String(project.environmentId),
579 projectId: String(project.id),
580 title: project.title,
581 },
582 });
583 };
584​
585 const inspectorColumnTargetWidth =
586 workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
587 ? (panes.auxiliaryPaneWidth ?? 0)
588 : 0;
589 const contentTargetWidth = layout.usesSplitView
590 ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth)
591 : null;
592 const [listPaneSizing, setListPaneSizing] = useState({
593 viewportWidth,
594 workspacePage,
595 sidebarVisible: panes.primarySidebarVisible,
596 listPaneTarget: layout.listPaneWidth,
597 listPaneFloor: layout.listPaneWidth,
598 listPaneCeiling: layout.listPaneWidth,
599 revision: 0,
600 });
601 if (
602 Platform.OS === "android" &&
603 (listPaneSizing.viewportWidth !== viewportWidth ||
604 listPaneSizing.workspacePage !== workspacePage ||
605 listPaneSizing.sidebarVisible !== panes.primarySidebarVisible ||
606 listPaneSizing.listPaneTarget !== layout.listPaneWidth)
607 ) {
608 // A book-posture hinge resizes the visible list pane instead of revealing it.
609 const resizingSidebar =
610 listPaneSizing.viewportWidth === viewportWidth &&
611 listPaneSizing.workspacePage === workspacePage &&
612 listPaneSizing.sidebarVisible &&
613 panes.primarySidebarVisible &&
614 listPaneSizing.listPaneTarget !== layout.listPaneWidth;
615 setListPaneSizing({
616 viewportWidth,
617 workspacePage,
618 sidebarVisible: panes.primarySidebarVisible,
619 listPaneTarget: layout.listPaneWidth,
620 // Retargets widen the list-width span because the animated hinge edge may still be inside it.
621 listPaneFloor: resizingSidebar
622 ? Math.min(listPaneSizing.listPaneFloor ?? 0, layout.listPaneWidth ?? 0)
623 : layout.listPaneWidth,
624 listPaneCeiling: resizingSidebar
625 ? Math.max(listPaneSizing.listPaneCeiling ?? 0, layout.listPaneWidth ?? 0)
626 : layout.listPaneWidth,
627 revision: listPaneSizing.revision + 1,
628 });
629 }
630 const settleListPane = (revision: number) => {
631 setListPaneSizing((current) =>
632 current.revision !== revision ||
633 (current.listPaneFloor === current.listPaneTarget &&
634 current.listPaneCeiling === current.listPaneTarget)
635 ? current
636 : {
637 ...current,
638 listPaneFloor: current.listPaneTarget,
639 listPaneCeiling: current.listPaneTarget,
640 },
641 );
642 };
643 const listPaneFloor = listPaneSizing.listPaneFloor ?? 0;
644 const listPaneCeiling = listPaneSizing.listPaneCeiling ?? 0;
645 const listPaneRevision = listPaneSizing.revision;
646 // Android lays the content out at its new width as soon as a pane toggles, then holds it
647 // against the edge that stays put while the other one slides, so nothing reflows after the
648 // panes land. A sliding sidebar uncovers the strip it is about to fill, or covers the content
649 // until it is gone.
650 const contentLeftTarget =
651 navigationRailWidth +
652 (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible
653 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
654 : 0);
655 const [contentAnchor, setContentAnchor] = useState({
656 viewportWidth,
657 left: contentLeftTarget,
658 inspector: inspectorColumnTargetWidth,
659 end: false,
660 });
661 if (
662 Platform.OS === "android" &&
663 (contentAnchor.viewportWidth !== viewportWidth ||
664 contentAnchor.left !== contentLeftTarget ||
665 contentAnchor.inspector !== inspectorColumnTargetWidth)
666 ) {
667 setContentAnchor({
668 viewportWidth,
669 left: contentLeftTarget,
670 inspector: inspectorColumnTargetWidth,
671 end:
672 contentAnchor.viewportWidth === viewportWidth &&
673 contentAnchor.inspector === inspectorColumnTargetWidth,
674 });
675 }
676​
677 const renderedSidebarWidth = useSharedValue(
678 panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0,
679 );
680 const renderedRailWidth = useSharedValue(navigationRailWidth);
681 const leavingWorkspacePage = useRef(false);
682 useEffect(() => {
683 if (nativeWorkspace) return;
684 renderedRailWidth.set(withTiming(navigationRailWidth, WORKSPACE_PANE_TIMING));
685 // A workspace page hides the sidebar through React instead, in the same commit that mounts
686 // the page. Animating it here would hide it a few frames before the page appears.
687 if (workspacePage) {
688 leavingWorkspacePage.current = true;
689 return;
690 }
691 const snap = leavingWorkspacePage.current;
692 leavingWorkspacePage.current = false;
693 const targetWidth = panes.primarySidebarVisible
694 ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
695 : 0;
696 // The content beside it already took its final width when the page closed.
697 renderedSidebarWidth.set(
698 withTiming(targetWidth, snap ? { duration: 0 } : WORKSPACE_PANE_TIMING, (finished) => {
699 if (finished && Platform.OS === "android") runOnJS(settleListPane)(listPaneRevision);
700 }),
701 );
702 }, [
703 nativeWorkspace,
704 navigationRailWidth,
705 layout.listPaneWidth,
706 layout.listPaneGap,
707 panes.primarySidebarVisible,
708 renderedSidebarWidth,
709 renderedRailWidth,
710 settleListPane,
711 listPaneRevision,
712 workspacePage,
713 ]);
714 const railAnimatedStyle = useAnimatedStyle(() => ({ width: renderedRailWidth.value }));
715 // Showing or hiding the sidebar clips a fixed-width list. A hinge resize instead tracks the
716 // animated edge, so the header actions slide with it rather than jumping or being covered.
717 const listPaneGap = layout.listPaneGap ?? 0;
718 const listPaneAnimatedStyle = useAnimatedStyle(() => ({
719 width: Math.min(
720 listPaneCeiling,
721 Math.max(listPaneFloor, renderedSidebarWidth.value - listPaneGap),
722 ),
723 }));
724 const sidebarAnimatedStyle = useAnimatedStyle(() => ({
725 // Fading a UIKit glass ancestor can leave remounted header effects missing.
726 opacity: Platform.OS === "ios" ? 1 : Math.min(1, renderedSidebarWidth.value / 80),
727 width: renderedSidebarWidth.value,
728 }));
729​
730 // Clip the navigator at its settled width so native headers and markdown reflow only once per pane toggle.
731 const renderedInspectorWidth = useSharedValue(inspectorColumnTargetWidth);
732 const renderedContentWidth = useDerivedValue(() =>
733 Math.max(
734 0,
735 viewportWidth -
736 renderedRailWidth.value -
737 renderedSidebarWidth.value -
738 renderedInspectorWidth.value,
739 ),
740 );
741​
742 const handleSelectThread = (thread: EnvironmentThreadShell) => {
743 handleSelectThreadRoute({
744 environmentId: String(thread.environmentId),
745 threadId: String(thread.id),
746 });
747 };
748​
749 // Rotating flips the overlay; until the new size reaches JS, predict the reset above.
750 const sidebarOverRotates =
751 nativeWorkspace && nativeMetrics?.hasHinge === true && layout.usesSplitView;
752 // The current orientation's panes already account for an inspector that needs the sidebar's room.
753 const sidebarInLandscape = baseLayout.primarySidebarOverlaysContent
754 ? primarySidebarPinned || primarySidebarPreferredVisible
755 : panes.primarySidebarVisible;
756 const sidebarInPortrait =
757 primarySidebarPinned ||
758 (baseLayout.primarySidebarOverlaysContent
759 ? overlaySidebar.visible
760 : isWorkspaceListPath(pathname));
761 const sidebarByOrientation = useMemo(
762 () =>
763 sidebarOverRotates ? { landscape: sidebarInLandscape, portrait: sidebarInPortrait } : null,
764 [sidebarInLandscape, sidebarInPortrait, sidebarOverRotates],
765 );
766​
767 const contextValue = {
768 layout,
769 panes,
770 fileInspector,
771 primarySidebarSearchQuery,
772 startNewTask: handleStartNewTask,
773 deferThreadSelectionUntil: deferredThreadSelection.waitFor,
774 selectDetail: handleSelectDetail,
775 activateAuxiliaryPaneRole,
776 registerWorkspaceInspector,
777 setPrimarySidebarSearchQuery,
778 showAuxiliaryPane,
779 toggleAuxiliaryPane,
780 togglePrimarySidebar,
781 setPrimarySidebarVisible,
782 openWorkspaceTab,
783 setAuxiliaryPaneWidth,
784 composerKeyboardActive,
785 setComposerEditing,
786 sidebarByOrientation,
787 };
788​
789 if (nativeWorkspace) {
790 return (
791 <HomeListOptionsProvider
792 projectGroupingMode={projectGroupingMode}
793 savedFilters={props.savedThreadListFilters}
794 >
795 <AdaptiveWorkspaceContext value={contextValue}>
796 <NativeWorkspaceInspectorContext
797 value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}
798 >
799 {props.children}
800 </NativeWorkspaceInspectorContext>
801 </AdaptiveWorkspaceContext>
802 </HomeListOptionsProvider>
803 );
804 }
805 return (
806 <HomeListOptionsProvider
807 projectGroupingMode={projectGroupingMode}
808 savedFilters={props.savedThreadListFilters}
809 >
810 <AdaptiveWorkspaceContext.Provider value={contextValue}>
811 <WindowHingeContext value={windowHinge}>
812 <View
813 testID="adaptive-workspace-layout"
814 className={Platform.OS === "android" ? "flex-1 flex-row bg-header" : "flex-1 flex-row"}
815 >
816 <AndroidHingeObserver onChange={handleHingeChange} />
817 {shouldRenderNavigationRail ? (
818 <Animated.View className="self-stretch" style={railAnimatedStyle} />
819 ) : null}
820 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
821 <Animated.View
822 className="self-stretch overflow-hidden"
823 accessibilityElementsHidden={!panes.primarySidebarVisible}
824 collapsable={false}
825 importantForAccessibility={
826 panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
827 }
828 pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
829 // Under a workspace page the sidebar leaves the row but keeps its size, so its
830 // lists never lay out at zero size and are ready, unchanged, on the way back. The
831 // content pane, laid out after it, covers it, in the same mount as the page.
832 style={[
833 workspacePage ? { position: "absolute", top: 0, bottom: 0, left: 0 } : null,
834 sidebarAnimatedStyle,
835 ]}
836 >
837 <Animated.View className="flex-1" style={listPaneAnimatedStyle}>
838 <RenderErrorBoundary
839 renderFallback={(fallback) => (
840 <RenderFailureView
841 {...fallback}
842 title="The sidebar couldn't be displayed"
843 exit={{ label: "Open settings", onPress: handleOpenSettings }}
844 />
845 )}
846 >
847 <AndroidWorkspaceSidebar
848 onRequestVisibility={revealPrimarySidebar}
849 selectedPullRequestKey={props.selectedPullRequestKey ?? null}
850 >
851 <AndroidHomeFabLayout sidebar onStartNewTask={handleStartNewTask}>
852 <ThreadNavigationSidebar
853 width={layout.listPaneWidth}
854 visible={panes.primarySidebarVisible}
855 onRequestVisibility={revealPrimarySidebar}
856 selectedThreadKey={selectedThreadKey}
857 onOpenSettings={handleOpenSettings}
858 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
859 onNewThreadInProject={handleNewThreadInProject}
860 onNewThreadOnBranch={handleNewThreadOnBranch}
861 onOpenPendingTask={handleOpenPendingTask}
862 onSelectThread={handleSelectThread}
863 onOpenThreadPullRequests={handleOpenThreadPullRequests}
864 onSearchQueryChange={setPrimarySidebarSearchQuery}
865 searchQuery={primarySidebarSearchQuery}
866 />
867 </AndroidHomeFabLayout>
868 </AndroidWorkspaceSidebar>
869 </RenderErrorBoundary>
870 </Animated.View>
871 </Animated.View>
872 ) : null}
873 <View
874 className={
875 Platform.OS === "android"
876 ? "flex-1 overflow-hidden bg-header"
877 : "flex-1 overflow-hidden bg-screen"
878 }
879 collapsable={false}
880 >
881 <View
882 collapsable={false}
883 style={
884 contentTargetWidth !== null
885 ? {
886 flex: 1,
887 width: contentTargetWidth,
888 alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
889 }
890 : { flex: 1 }
891 }
892 >
893 {/* Android holds the content still, so its floating controls keep its width. */}
894 <WorkspaceContentWidthContext
895 value={
896 layout.usesSplitView && Platform.OS !== "android" ? renderedContentWidth : null
897 }
898 >
899 <WorkspaceSettledContentWidthContext
900 value={
901 Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null
902 }
903 >
904 {/* Compact Settings keeps the bottom navigation under all of its pages. */}
905 <SafeAreaInsetsContext
906 value={
907 compactAndroidSettings ? { ...safeAreaInsets, bottom: 0 } : safeAreaInsets
908 }
909 >
910 <View className="flex-1">{props.children}</View>
911 </SafeAreaInsetsContext>
912 {compactAndroidSettings ? (
913 <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
914 ) : null}
915 </WorkspaceSettledContentWidthContext>
916 </WorkspaceContentWidthContext>
917 </View>
918 </View>
919 <WorkspaceInspectorPane
920 pathname={props.pathname}
921 renderedInspectorWidth={renderedInspectorWidth}
922 active={workspaceInspector?.active ?? false}
923 panes={panes}
924 renderInspector={workspaceInspector?.render}
925 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
926 onClosed={handleWorkspaceInspectorClosed}
927 />
928 {shouldRenderNavigationRail && navigationRailWidth > 0 ? (
929 // The rail reserves its slot above and draws over the panes, so it can widen over
930 // the list in place. It takes the whole workspace only while it is open.
931 <View
932 className="absolute inset-y-0 left-0"
933 style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
934 >
935 <AndroidWorkspaceNavigation
936 onNewThread={handleStartNewTask}
937 rail
938 onSelect={revealPrimarySidebar}
939 onOverlayChange={setRailOverlay}
940 />
941 </View>
942 ) : null}
943 </View>
944 </WindowHingeContext>
945 </AdaptiveWorkspaceContext.Provider>
946 </HomeListOptionsProvider>
947 );