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

AdaptiveWorkspaceLayout.tsx

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