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