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