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

AdaptiveWorkspaceLayout.tsx

963 lines37.1 KB

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