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

AppSidebarLayout.tsx

365 lines13.1 KB

1import { useAtomValue } from "@effect/atom-react";
2import * as Schema from "effect/Schema";
3import {
4 useEffect,
5 useState,
6 useSyncExternalStore,
7 type CSSProperties,
8 type ReactNode,
9} from "react";
10import { useLocation, useNavigate } from "@tanstack/react-router";
11​
12import { isElectron } from "../env";
13import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
14import {
15 isRichTextBoldShortcut,
16 resolveShortcutCommand,
17 shortcutLabelForCommand,
18} from "../keybindings";
19import { isEditableFocused } from "../lib/editableFocus";
20import { isPreviewFocused } from "../lib/previewFocus";
21import { isTerminalFocused } from "../lib/terminalFocus";
22import { isModelPickerOpen } from "../modelPickerVisibility";
23import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
24import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
25import { cn, isMacPlatform } from "../lib/utils";
26import { primaryServerKeybindingsAtom } from "../state/server";
27import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
28import {
29 PanelAnimationSuppressionProvider,
30 usePanelAnimationSettings,
31 usePanelNavigationSuppression,
32} from "../panelAnimations";
33import LegacyThreadSidebar from "./LegacySidebar";
34import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
35import ThreadSidebar from "./Sidebar";
36import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
37import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
38import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
39import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
40import { useProjects } from "../state/entities";
41import {
42 clampThreadSidebarWidth,
43 resolveInitialThreadSidebarWidth,
44 resolveThreadSidebarMaximumWidth,
45 resolveThreadSidebarMinimumWidth,
46 THREAD_MAIN_CONTENT_MIN_WIDTH,
47 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
48} from "./threadSidebarWidth";
49import {
50 Sidebar,
51 SidebarProvider,
52 SidebarRail,
53 SidebarTrigger,
54 useSidebar,
55 useSidebarVisibility,
56} from "./ui/sidebar";
57import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
58import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
59​
60const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
61​
62function subscribeToViewportWidth(onChange: () => void): () => void {
63 window.addEventListener("resize", onChange);
64 return () => window.removeEventListener("resize", onChange);
66​
67function readViewportWidth(): number {
68 return window.innerWidth;
70​
71// getWindowFullscreenState is a synchronous IPC round trip, so the snapshot is cached
72// and only re-read when a subscription starts.
73let windowFullscreenSnapshot: boolean | null = null;
74​
75function macosDesktopBridge() {
76 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
77 return window.desktopBridge ?? null;
79​
80function subscribeToWindowFullscreen(onChange: () => void): () => void {
81 const bridge = macosDesktopBridge();
82 if (
83 typeof bridge?.getWindowFullscreenState !== "function" ||
84 typeof bridge.onWindowFullscreenStateChange !== "function"
85 ) {
86 return () => {};
87 }
88 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
89 windowFullscreenSnapshot = fullscreen;
90 onChange();
91 });
92 // The window may have changed state between the first render and this subscription.
93 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
94 return () => {
95 unsubscribe();
96 windowFullscreenSnapshot = null;
97 };
99​
100function readWindowFullscreen(): boolean {
101 if (windowFullscreenSnapshot === null) {
102 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
103 windowFullscreenSnapshot =
104 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
105 }
106 return windowFullscreenSnapshot;
108​
109function readInitialThreadSidebarWidth(): number {
110 try {
111 return resolveInitialThreadSidebarWidth(
112 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
113 window.innerWidth,
114 );
115 } catch (error) {
116 console.error("Could not read persisted thread sidebar width.", error);
117 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
118 }
120​
121function SidebarControl() {
122 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
123 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
124 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
125 const isSidebarVisible = useSidebarVisibility();
126 const environmentIdentificationMode = useEnvironmentIdentificationMode();
127 const stageBackdropVariant = useSidebarStageBackdropVariant(
128 environmentIdentificationMode === "artwork",
129 );
130 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
131 context: { usagePageOpen },
132 });
133​
134 useEffect(() => {
135 const onKeyDown = (event: KeyboardEvent) => {
136 if (event.defaultPrevented) return;
137 if (
138 event.target instanceof HTMLElement &&
139 event.target.closest("[data-keybinding-capture]")
140 ) {
141 return;
142 }
143 if (
144 isRichTextBoldShortcut(event) &&
145 event.target instanceof HTMLElement &&
146 event.target.closest('[data-composer-rich-text="true"]')
147 ) {
148 // The rich-text composer claims Mod+B for bold; the toggle stays
149 // available everywhere else, including the plain-text composer.
150 return;
151 }
152 if (
153 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
154 "sidebar.toggle"
155 )
156 return;
157​
158 event.preventDefault();
159 event.stopPropagation();
160 toggleSidebar();
161 };
162​
163 window.addEventListener("keydown", onKeyDown, true);
164 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
165 if (action === "sidebar.toggle") toggleSidebar();
166 });
167 return () => {
168 window.removeEventListener("keydown", onKeyDown, true);
169 unsubscribe?.();
170 };
171 }, [keybindings, toggleSidebar, usagePageOpen]);
172​
173 return (
174 <div
175 className={cn(
176 "pointer-events-none fixed left-[var(--workspace-controls-left)] top-[var(--workspace-controls-top)] z-50 ml-px flex h-[var(--workspace-topbar-height)] items-center",
177 isMobile && mobileSheetMounted && "hidden",
178 )}
179 data-sidebar-control=""
180 >
181 <Tooltip>
182 <TooltipTrigger
183 render={
184 <SidebarTrigger
185 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
186 className={cn(
187 "pointer-events-auto",
188 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
189 )}
190 aria-label="Toggle main sidebar"
191 />
192 }
193 />
194 <TooltipPopup side="bottom">
195 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
196 </TooltipPopup>
197 </Tooltip>
198 </div>
199 );
201​
202function NavigationHistoryShortcuts() {
203 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
204 const routeThreadRef = useThreadRouteRef();
205​
206 useEffect(() => {
207 const onKeyDown = (event: KeyboardEvent) => {
208 if (event.defaultPrevented) return;
209 if (
210 event.target instanceof HTMLElement &&
211 event.target.closest("[data-keybinding-capture]")
212 ) {
213 return;
214 }
215 const command = resolveShortcutCommand(event, keybindings, {
216 context: {
217 terminalFocus: isTerminalFocused(),
218 terminalOpen: routeThreadRef
219 ? selectThreadTerminalUiState(
220 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
221 routeThreadRef,
222 ).terminalOpen
223 : false,
224 previewFocus: isPreviewFocused(),
225 previewOpen: routeThreadRef
226 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
227 "preview"
228 : false,
229 editableFocus: isEditableFocused(event.target),
230 modelPickerOpen: isModelPickerOpen(),
231 },
232 });
233 if (command !== "navigation.back" && command !== "navigation.forward") return;
234​
235 event.preventDefault();
236 event.stopPropagation();
237 if (command === "navigation.back") window.history.back();
238 else window.history.forward();
239 };
240​
241 window.addEventListener("keydown", onKeyDown);
242 return () => window.removeEventListener("keydown", onKeyDown);
243 }, [keybindings, routeThreadRef]);
244​
245 return null;
247​
248// Settings swaps the thread sidebar out of the tree. Keep the lightweight
249// project projection subscribed so returning to a draft never renders the
250// zero-project state while the environment snapshot reconnects.
251function ProjectProjectionRetention() {
252 useProjects();
253 return null;
255​
256export function AppSidebarLayout({ children }: { children: ReactNode }) {
257 const navigate = useNavigate();
258 const legacySidebarEnabled = useLegacySidebarEnabled();
259 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
260 usePanelAnimationSettings();
261 useThreadVisitedMigration();
262 const pathname = useLocation({ select: (location) => location.pathname });
263 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
264 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
265 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
266 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
267 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
268 // Subscribed rather than read once: the clamp must track live window size,
269 // and a clamped drag ends with an unchanged width, which skips the re-render
270 // that would otherwise refresh a render-time snapshot.
271 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
272 const [brandWidth, setBrandWidth] = useState(0);
273 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
274 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
275 const resetSidebarWidth = () => {
276 try {
277 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
278 } catch (error) {
279 console.error("Could not clear persisted thread sidebar width.", error);
280 }
281 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
282 };
283 const isWindowFullscreen = useSyncExternalStore(
284 subscribeToWindowFullscreen,
285 readWindowFullscreen,
286 );
287 const windowControlsInsetStyle = (
288 isMacosDesktop && !isWindowFullscreen
289 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
290 : {}
291 ) as CSSProperties;
292 const sidebarProviderStyle = {
293 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
294 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
295 ...windowControlsInsetStyle,
296 } as CSSProperties;
297​
298 useEffect(() => {
299 const onMenuAction = window.desktopBridge?.onMenuAction;
300 if (typeof onMenuAction !== "function") {
301 return;
302 }
303​
304 const unsubscribe = onMenuAction((action) => {
305 if (action === "open-settings") {
306 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
307 if (!isSettingsRoute) {
308 void navigate({ to: "/settings" });
309 }
310 }
311 });
312​
313 return () => {
314 unsubscribe?.();
315 };
316 }, [navigate, pathname]);
317​
318 return (
319 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
320 <SidebarProvider
321 className="h-dvh! min-h-0!"
322 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
323 defaultOpen
324 mobileBreakpoint={sidebarMinimumWidth + THREAD_MAIN_CONTENT_MIN_WIDTH}
325 style={sidebarProviderStyle}
326 >
327 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
328 <ProjectProjectionRetention />
329 <Sidebar
330 side="left"
331 collapsible="offcanvas"
332 data-app-sidebar=""
333 role="navigation"
334 aria-label={isOnSettings ? "Settings" : "Threads"}
335 resizable={{
336 maxWidth: sidebarMaximumWidth,
337 minWidth: sidebarMinimumWidth,
338 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
339 nextWidth <= currentWidth ||
340 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
341 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
342 onResize: setSidebarWidth,
343 }}
344 style={windowControlsInsetStyle}
345 >
346 {isOnSettings ? (
347 <>
348 <SidebarChromeHeader isElectron={isElectron} />
349 <SettingsSidebarNav pathname={pathname} />
350 </>
351 ) : legacySidebarEnabled ? (
352 <LegacyThreadSidebar />
353 ) : (
354 <ThreadSidebar />
355 )}
356 <SidebarRail onDoubleClick={resetSidebarWidth} />
357 </Sidebar>
358 {children}
359 <SidebarControl />
360 <NavigationHistoryShortcuts />
361 <MainAppLocationTracker />
362 </SidebarProvider>
363 </PanelAnimationSuppressionProvider>
364 );