Open History to see the last commit
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 NavigationContext,
10 NavigationRouteContext,
11 StackActions,
12 useNavigation,
13} from "@react-navigation/native";
14import {
15 createContext,
16 use,
17 useCallback,
18 useEffect,
19 useMemo,
20 useRef,
21 useState,
22 type ReactNode,
23} from "react";
24import { useWindowDimensions, View } from "react-native";
25import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
26import { AsyncResult } from "effect/unstable/reactivity";
27
28import {
29 deriveFileInspectorPaneLayout,
30 deriveLayout,
31 deriveWorkspacePaneLayout,
32 type FileInspectorPaneLayout,
33 type Layout,
34 type WorkspaceAuxiliaryPaneRole,
35 type WorkspacePaneLayout,
36} from "../../lib/layout";
37import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
38import { scopedThreadKey } from "../../lib/scopedEntities";
39import { mobilePreferencesAtom } from "../../state/preferences";
40import {
41 DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
42 resolveMobileProjectGroupingSettings,
43} from "../../state/project-grouping";
44import {
45 parseActiveThreadPath,
46 useHardwareKeyboardCommand,
47} from "../keyboard/hardwareKeyboardCommands";
48import { AndroidHomeFabLayout } from "../home/AndroidHomeFab";
49import { HomeListOptionsProvider } from "../home/home-list-options";
50import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
51import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
52import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
53import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
54
55interface AdaptiveWorkspaceContextValue {
56 readonly layout: Layout;
57 readonly panes: WorkspacePaneLayout;
58 readonly fileInspector: FileInspectorPaneLayout;
59 readonly primarySidebarSearchQuery: string;
60 readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
61 /**
62 * Route screens hand their inspector pane content to the workspace so it
63 * renders BESIDE the navigator (outside the native stack header) instead of
64 * inside the route. Returns a deactivate callback: the pane animates closed
65 * (content kept mounted for the exit transition) unless a newer
66 * registration already took over — stale deactivates never clobber it.
67 * Prefer useRegisterWorkspaceInspector over calling this directly.
68 */
69 readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;
70 readonly setPrimarySidebarSearchQuery: (query: string) => void;
71 readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void;
72 readonly toggleAuxiliaryPane: () => void;
73 readonly togglePrimarySidebar: () => void;
74 readonly setAuxiliaryPaneWidth: (width: number) => void;
75}
76
77const compactLayout = deriveLayout({ width: 0, height: 0 });
78const compactPanes = deriveWorkspacePaneLayout({
79 layout: compactLayout,
80 viewportWidth: 0,
81 primarySidebarPreferredVisible: true,
82 auxiliaryPanePreferredVisible: true,
83});
84const compactFileInspector = deriveFileInspectorPaneLayout({
85 layout: compactLayout,
86 viewportWidth: 0,
87});
88const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
89 layout: compactLayout,
90 panes: compactPanes,
91 fileInspector: compactFileInspector,
92 primarySidebarSearchQuery: "",
93 activateAuxiliaryPaneRole: () => () => undefined,
94 registerWorkspaceInspector: () => () => undefined,
95 setPrimarySidebarSearchQuery: () => undefined,
96 showAuxiliaryPane: () => undefined,
97 toggleAuxiliaryPane: () => undefined,
98 togglePrimarySidebar: () => undefined,
99 setAuxiliaryPaneWidth: () => undefined,
100});
101
102export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {
103 return use(AdaptiveWorkspaceContext);
104}
105
106export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
107 const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();
108
109 useFocusEffect(
110 useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]),
111 );
112}
113
114/**
115 * Register this screen's inspector pane content with the workspace column.
116 *
117 * The column renders BESIDE the navigator — outside any screen — so the
118 * registering screen's navigation and route contexts are captured here and
119 * re-provided around the portal content. Without them, useNavigation/useRoute
120 * inside the pane (e.g. GitOverviewSheet via useThreadSelection) throw
121 * "Couldn't find a route object".
122 *
123 * Registration is FOCUS-scoped, driven by navigation events rather than the
124 * screen's own render cycle: react-native-screens freezes blurred screens, so
125 * a cleanup that depends on the blurred subtree re-rendering never runs and
126 * would leak the pane into the next route. Blur deactivates the pane (it
127 * animates closed, or is replaced seamlessly when the next route registers in
128 * the same commit); focus re-registers it.
129 */
130export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefined) {
131 const { registerWorkspaceInspector } = useAdaptiveWorkspaceLayout();
132 // Raw context values (not the useNavigation/useRoute wrappers) so the
133 // portal re-provides exactly what this screen sees.
134 const navigation = use(NavigationContext);
135 const route = use(NavigationRouteContext);
136
137 const wrappedRender = useMemo(() => {
138 if (render === undefined) {
139 return undefined;
140 }
141 return () => (
142 <NavigationContext.Provider value={navigation}>
143 <NavigationRouteContext.Provider value={route}>{render()}</NavigationRouteContext.Provider>
144 </NavigationContext.Provider>
145 );
146 }, [navigation, render, route]);
147
148 const wrappedRenderRef = useRef(wrappedRender);
149 wrappedRenderRef.current = wrappedRender;
150 const focusedRef = useRef(false);
151 const deactivateRef = useRef<(() => void) | null>(null);
152
153 const syncRegistration = useCallback(() => {
154 if (!focusedRef.current || wrappedRenderRef.current === undefined) {
155 deactivateRef.current?.();
156 return;
157 }
158 deactivateRef.current = registerWorkspaceInspector(wrappedRenderRef.current);
159 }, [registerWorkspaceInspector]);
160
161 // Focus lifecycle. Blur/focus events fire even when the blurred subtree is
162 // frozen (events are navigation-driven, renders are not).
163 useFocusEffect(
164 useCallback(() => {
165 focusedRef.current = true;
166 syncRegistration();
167 return () => {
168 focusedRef.current = false;
169 syncRegistration();
170 };
171 }, [syncRegistration]),
172 );
173
174 // Content changes while focused re-register in place.
175 useEffect(() => {
176 if (focusedRef.current) {
177 syncRegistration();
178 }
179 }, [syncRegistration, wrappedRender]);
180
181 // Unmount: hand the pane back (owner-guarded, so a route that already
182 // took over is unaffected).
183 useEffect(
184 () => () => {
185 deactivateRef.current?.();
186 deactivateRef.current = null;
187 },
188 [],
189 );
190}
191
192export function AdaptiveWorkspaceLayout(props: {
193 readonly children: ReactNode;
194 readonly pathname: string;
195}) {
196 const preferencesResult = useAtomValue(mobilePreferencesAtom);
197 if (!AsyncResult.isSuccess(preferencesResult)) {
198 return AsyncResult.isFailure(preferencesResult) ? (
199 <AdaptiveWorkspaceLayoutContent
200 {...props}
201 projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
202 />
203 ) : null;
204 }
205 const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
206 return (
207 <AdaptiveWorkspaceLayoutContent
208 {...props}
209 projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
210 />
211 );
212}
213
214function AdaptiveWorkspaceLayoutContent(
215 props: {
216 readonly children: ReactNode;
217 readonly pathname: string;
218 } & {
219 readonly projectGroupingMode: SidebarProjectGroupingMode;
220 },
221) {
222 const projectGroupingMode = props.projectGroupingMode;
223 const { materialYouStyleLayoutActive } = useAppearancePreferences();
224 const { width, height } = useWindowDimensions();
225 const pathname = props.pathname;
226 const navigation = useNavigation();
227 const activeRoleOwner = useRef<symbol | null>(null);
228 const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
229 const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
230 const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
231 number | null
232 >(null);
233 const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);
234 const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
235 null,
236 );
237 const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
238 const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
239 useState<WorkspaceAuxiliaryPaneRole | null>(null);
240 const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]);
241 const layout = baseLayout;
242 // In split layouts the sidebar IS the thread list — it renders on every
243 // route, including Home (which shows an empty-detail pane instead of the
244 // compact list).
245 const shouldRenderPrimarySidebar = layout.usesSplitView;
246 const fileInspector = useMemo(
247 () =>
248 deriveFileInspectorPaneLayout({
249 layout,
250 viewportWidth: width,
251 preferredWidth: fileInspectorPreferredWidth ?? undefined,
252 reservedLeadingWidth:
253 shouldRenderPrimarySidebar && primarySidebarPreferredVisible
254 ? (layout.listPaneWidth ?? 0)
255 : 0,
256 }),
257 [
258 fileInspectorPreferredWidth,
259 layout,
260 primarySidebarPreferredVisible,
261 shouldRenderPrimarySidebar,
262 width,
263 ],
264 );
265 const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
266 focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
267 const auxiliaryPanePreferredVisible =
268 auxiliaryPaneRole === "inspector"
269 ? fileInspectorPreferredVisible
270 : supplementaryPanePreferredVisible;
271 const auxiliaryPanePreferredWidth =
272 auxiliaryPaneRole === "inspector"
273 ? fileInspectorPreferredWidth
274 : supplementaryPanePreferredWidth;
275 const panes = useMemo(
276 () =>
277 deriveWorkspacePaneLayout({
278 layout,
279 viewportWidth: width,
280 primarySidebarPreferredVisible,
281 auxiliaryPanePreferredVisible,
282 auxiliaryPaneRole,
283 auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
284 }),
285 [
286 auxiliaryPanePreferredVisible,
287 auxiliaryPaneRole,
288 auxiliaryPanePreferredWidth,
289 layout,
290 primarySidebarPreferredVisible,
291 width,
292 ],
293 );
294 const activeThread = parseActiveThreadPath(pathname);
295 const environmentId = activeThread?.environmentId ?? null;
296 const threadId = activeThread?.threadId ?? null;
297 const selectedThreadKey = useMemo(() => {
298 if (environmentId === null || threadId === null) {
299 return null;
300 }
301 try {
302 return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
303 } catch {
304 return null;
305 }
306 }, [environmentId, threadId]);
307 // Wrapped in an object: bare functions in useState would be treated as
308 // lazy initializers/updaters. `active: false` keeps the outgoing route's
309 // content mounted so the pane can animate closed (or be replaced
310 // seamlessly by the next route's registration in the same commit).
311 const [workspaceInspector, setWorkspaceInspector] = useState<{
312 readonly render: () => ReactNode;
313 readonly active: boolean;
314 } | null>(null);
315 const workspaceInspectorOwner = useRef<symbol | null>(null);
316 const registerWorkspaceInspector = useCallback((render: () => ReactNode) => {
317 const owner = Symbol("workspace-inspector");
318 workspaceInspectorOwner.current = owner;
319 setWorkspaceInspector({ render, active: true });
320
321 return () => {
322 // During a push/replace the outgoing screen deactivates AFTER the
323 // incoming screen registered — only the current owner may deactivate.
324 if (workspaceInspectorOwner.current !== owner) {
325 return;
326 }
327 setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
328 };
329 }, []);
330 // Once the close animation settles, drop the stale content entirely.
331 const handleWorkspaceInspectorClosed = useCallback(() => {
332 setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
333 }, []);
334 const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
335 const owner = Symbol(role);
336 activeRoleOwner.current = owner;
337 setFocusedAuxiliaryPaneRole(role);
338
339 return () => {
340 if (activeRoleOwner.current !== owner) {
341 return;
342 }
343 activeRoleOwner.current = null;
344 setFocusedAuxiliaryPaneRole(null);
345 };
346 }, []);
347 const togglePrimarySidebar = useCallback(() => {
348 if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
349 setFileInspectorPreferredVisible(false);
350 setPrimarySidebarPreferredVisible(true);
351 return;
352 }
353 setPrimarySidebarPreferredVisible((current) => !current);
354 }, [panes.primarySidebarSuppressedByAuxiliary, panes.primarySidebarVisible]);
355 const revealPrimarySidebar = useCallback(() => {
356 if (panes.primarySidebarSuppressedByAuxiliary) {
357 setFileInspectorPreferredVisible(false);
358 }
359 setPrimarySidebarPreferredVisible(true);
360 }, [panes.primarySidebarSuppressedByAuxiliary]);
361 const handleToggleSidebarCommand = useCallback(() => {
362 togglePrimarySidebar();
363 return true;
364 }, [togglePrimarySidebar]);
365 useHardwareKeyboardCommand("toggleSidebar", handleToggleSidebarCommand);
366 const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
367 if (role === "inspector") {
368 setFocusedAuxiliaryPaneRole("inspector");
369 setFileInspectorPreferredVisible(true);
370 return;
371 }
372 setFocusedAuxiliaryPaneRole("supplementary");
373 setSupplementaryPanePreferredVisible(true);
374 }, []);
375 const handleOpenFilesCommand = useCallback(() => {
376 const activeThread = parseActiveThreadPath(pathname);
377 if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
378 return false;
379 }
380 showAuxiliaryPane("inspector");
381 if (/\/files(?:\/|$)/.test(pathname)) {
382 return true;
383 }
384 navigation.navigate("ThreadFiles", activeThread);
385 return true;
386 }, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);
387 useHardwareKeyboardCommand("files", handleOpenFilesCommand);
388 const toggleAuxiliaryPane = useCallback(() => {
389 if (auxiliaryPaneRole === "inspector") {
390 setFileInspectorPreferredVisible((current) => !current);
391 return;
392 }
393 setSupplementaryPanePreferredVisible((current) => !current);
394 }, [auxiliaryPaneRole]);
395 const setAuxiliaryPaneWidth = useCallback(
396 (nextWidth: number) => {
397 if (auxiliaryPaneRole === "inspector") {
398 setFileInspectorPreferredWidth(nextWidth);
399 return;
400 }
401 setSupplementaryPanePreferredWidth(nextWidth);
402 },
403 [auxiliaryPaneRole],
404 );
405 const contextValue = useMemo(
406 () => ({
407 layout,
408 panes,
409 fileInspector,
410 primarySidebarSearchQuery,
411 activateAuxiliaryPaneRole,
412 registerWorkspaceInspector,
413 setPrimarySidebarSearchQuery,
414 showAuxiliaryPane,
415 toggleAuxiliaryPane,
416 togglePrimarySidebar,
417 setAuxiliaryPaneWidth,
418 }),
419 [
420 activateAuxiliaryPaneRole,
421 fileInspector,
422 layout,
423 panes,
424 primarySidebarSearchQuery,
425 registerWorkspaceInspector,
426 showAuxiliaryPane,
427 setPrimarySidebarSearchQuery,
428 setAuxiliaryPaneWidth,
429 toggleAuxiliaryPane,
430 togglePrimarySidebar,
431 ],
432 );
433
434 const handleOpenSettings = useCallback(() => {
435 navigation.navigate("SettingsSheet", {
436 screen: "SettingsContent",
437 params: { screen: "Settings" },
438 });
439 }, [navigation]);
440
441 const handleStartNewTask = useCallback(() => {
442 navigation.navigate("NewTaskSheet", { screen: "NewTask" });
443 }, [navigation]);
444
445 // Minted here (root stack navigation) so the sidebar pane stays free of
446 // navigation hooks — on iOS it renders inside an independent nav tree.
447 const handleOpenEnvironmentSettings = useCallback(() => {
448 navigation.navigate("SettingsSheet", {
449 screen: "SettingsContent",
450 params: { screen: "SettingsEnvironments" },
451 });
452 }, [navigation]);
453
454 const handleNewThreadOnBranch = useCallback(
455 (thread: EnvironmentThreadShell) => {
456 navigation.navigate("NewTaskSheet", {
457 screen: "NewTaskDraft",
458 params: {
459 environmentId: String(thread.environmentId),
460 projectId: String(thread.projectId),
461 branch: thread.branch,
462 worktreePath: thread.worktreePath,
463 },
464 });
465 },
466 [navigation],
467 );
468
469 const handleNewThreadInProject = useCallback(
470 (project: EnvironmentProject) => {
471 navigation.navigate("NewTaskSheet", {
472 screen: "NewTaskDraft",
473 params: {
474 environmentId: String(project.environmentId),
475 projectId: String(project.id),
476 title: project.title,
477 },
478 });
479 },
480 [navigation],
481 );
482
483 const renderedSidebarWidth = useSharedValue(
484 panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
485 );
486 useEffect(() => {
487 const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0;
488 renderedSidebarWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING);
489 }, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]);
490 const sidebarAnimatedStyle = useAnimatedStyle(() => ({
491 opacity: Math.min(1, renderedSidebarWidth.value / 80),
492 width: renderedSidebarWidth.value,
493 }));
494
495 // Freeze the content pane at its SETTLED width while the side panes
496 // animate. The navigator (native header + markdown feed) lays out ONCE per
497 // pane toggle instead of re-measuring on every animation frame — the
498 // animating columns merely clip/reveal it over a matching background.
499 // Continuously re-wrapping the chat feed was the main source of dropped
500 // frames during sidebar/inspector transitions.
501 const inspectorColumnTargetWidth =
502 workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
503 ? (panes.auxiliaryPaneWidth ?? 0)
504 : 0;
505 const contentSettledWidth = layout.usesSplitView
506 ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth)
507 : null;
508
509 const handleSelectThread = useCallback(
510 (thread: EnvironmentThreadShell) => {
511 const params = {
512 environmentId: String(thread.environmentId),
513 threadId: String(thread.id),
514 };
515 const navigationAction = resolveThreadSelectionNavigationAction({
516 usesSplitView: layout.usesSplitView,
517 pathname,
518 });
519 if (navigationAction === "set-params") {
520 const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
521 if (nextThreadKey === selectedThreadKey) {
522 return;
523 }
524 setFileInspectorPreferredVisible(false);
525 navigation.navigate("Thread", params);
526 return;
527 }
528 if (navigationAction === "replace") {
529 setFileInspectorPreferredVisible(false);
530 navigation.dispatch(StackActions.replace("Thread", params));
531 return;
532 }
533 navigation.navigate("Thread", params);
534 },
535 [layout.usesSplitView, pathname, navigation, selectedThreadKey],
536 );
537
538 return (
539 <HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
540 <AdaptiveWorkspaceContext.Provider value={contextValue}>
541 <View testID="adaptive-workspace-layout" className="flex-1 flex-row">
542 {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
543 <Animated.View
544 className="self-stretch overflow-hidden"
545 accessibilityElementsHidden={!panes.primarySidebarVisible}
546 collapsable={false}
547 importantForAccessibility={
548 panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
549 }
550 pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
551 style={sidebarAnimatedStyle}
552 >
553 <View className="flex-1" style={{ width: layout.listPaneWidth }}>
554 <AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
555 <ThreadNavigationSidebar
556 width={layout.listPaneWidth}
557 visible={panes.primarySidebarVisible}
558 onRequestVisibility={revealPrimarySidebar}
559 selectedThreadKey={selectedThreadKey}
560 onOpenSettings={handleOpenSettings}
561 onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
562 onNewThreadInProject={handleNewThreadInProject}
563 onNewThreadOnBranch={handleNewThreadOnBranch}
564 onSelectThread={handleSelectThread}
565 onSearchQueryChange={setPrimarySidebarSearchQuery}
566 searchQuery={primarySidebarSearchQuery}
567 />
568 </AndroidHomeFabLayout>
569 </View>
570 </Animated.View>
571 ) : null}
572 <View
573 className={
574 materialYouStyleLayoutActive
575 ? "flex-1 overflow-hidden bg-header"
576 : "flex-1 overflow-hidden bg-screen"
577 }
578 collapsable={false}
579 >
580 <View
581 collapsable={false}
582 style={
583 contentSettledWidth !== null ? { flex: 1, width: contentSettledWidth } : { flex: 1 }
584 }
585 >
586 {props.children}
587 </View>
588 </View>
589 <WorkspaceInspectorPane
590 active={workspaceInspector?.active ?? false}
591 panes={panes}
592 renderInspector={workspaceInspector?.render}
593 setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
594 onClosed={handleWorkspaceInspectorClosed}
595 />
596 </View>
597 </AdaptiveWorkspaceContext.Provider>
598 </HomeListOptionsProvider>
599 );
600}