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

AdaptiveWorkspaceLayout.tsx

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