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