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