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

AdaptiveWorkspaceLayout.tsx

554 lines20.4 KB

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