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

AdaptiveWorkspaceLayout.tsx

928 lines35.3 KB

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