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

AdaptiveWorkspaceLayout.tsx

895 lines33.9 KB

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