Open History to see the last commit
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, useParams } 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 { resolveThreadRouteRef } from "../threadRoutes";
26import { cn, isMacPlatform } from "../lib/utils";
27import { primaryServerKeybindingsAtom } from "../state/server";
28import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
29import {
30 PanelAnimationSuppressionProvider,
31 usePanelAnimationSettings,
32 usePanelNavigationSuppression,
33} from "../panelAnimations";
34import LegacyThreadSidebar from "./LegacySidebar";
35import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
36import ThreadSidebar from "./Sidebar";
37import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
38import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
39import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
40import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
41import { useProjects } from "../state/entities";
42import {
43 clampThreadSidebarWidth,
44 resolveInitialThreadSidebarWidth,
45 resolveThreadSidebarMaximumWidth,
46 resolveThreadSidebarMinimumWidth,
47 THREAD_MAIN_CONTENT_MIN_WIDTH,
48 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
49} from "./threadSidebarWidth";
50import {
51 Sidebar,
52 SidebarProvider,
53 SidebarRail,
54 SidebarTrigger,
55 useSidebar,
56 useSidebarVisibility,
57} from "./ui/sidebar";
58import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
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);
65}
66
67function readViewportWidth(): number {
68 return window.innerWidth;
69}
70
71function readInitialThreadSidebarWidth(): number {
72 try {
73 return resolveInitialThreadSidebarWidth(
74 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
75 window.innerWidth,
76 );
77 } catch (error) {
78 console.error("Could not read persisted thread sidebar width.", error);
79 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
80 }
81}
82
83function SidebarControl() {
84 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
85 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
86 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
87 const isSidebarVisible = useSidebarVisibility();
88 const environmentIdentificationMode = useEnvironmentIdentificationMode();
89 const stageBackdropVariant = useSidebarStageBackdropVariant(
90 environmentIdentificationMode === "artwork",
91 );
92 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
93 context: { usagePageOpen },
94 });
95
96 useEffect(() => {
97 const onKeyDown = (event: KeyboardEvent) => {
98 if (event.defaultPrevented) return;
99 if (
100 event.target instanceof HTMLElement &&
101 event.target.closest("[data-keybinding-capture]")
102 ) {
103 return;
104 }
105 if (
106 isRichTextBoldShortcut(event) &&
107 event.target instanceof HTMLElement &&
108 event.target.closest('[data-composer-rich-text="true"]')
109 ) {
110 // The rich-text composer claims Mod+B for bold; the toggle stays
111 // available everywhere else, including the plain-text composer.
112 return;
113 }
114 if (
115 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
116 "sidebar.toggle"
117 )
118 return;
119
120 event.preventDefault();
121 event.stopPropagation();
122 toggleSidebar();
123 };
124
125 // Capture before focused editors consume commands such as Mod+B for rich-text formatting.
126 window.addEventListener("keydown", onKeyDown, true);
127 // A focused desktop browser page forwards the chord as a menu action.
128 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
129 if (action === "sidebar.toggle") toggleSidebar();
130 });
131 return () => {
132 window.removeEventListener("keydown", onKeyDown, true);
133 unsubscribe?.();
134 };
135 }, [keybindings, toggleSidebar, usagePageOpen]);
136
137 return (
138 // The right-side layout controls carry mr-px (border compensation inside
139 // the panel), so the trigger mirrors it: both clusters sit one extra pixel
140 // off their edge and the titlebar reads symmetric.
141 // The sheet owns its trigger until its closing transition unmounts it.
142 <div
143 className={cn(
144 "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",
145 isMobile && mobileSheetMounted && "hidden",
146 )}
147 data-sidebar-control=""
148 >
149 <Tooltip>
150 <TooltipTrigger
151 render={
152 <SidebarTrigger
153 // Over the stage artwork the trigger is a control on imagery, like the media
154 // viewer's arrows; that variant positions itself, so the layout is reset here.
155 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
156 className={cn(
157 "pointer-events-auto",
158 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
159 )}
160 aria-label="Toggle main sidebar"
161 />
162 }
163 />
164 <TooltipPopup side="bottom">
165 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
166 </TooltipPopup>
167 </Tooltip>
168 </div>
169 );
170}
171
172// Moves through the app's route history like a browser's back/forward buttons.
173function NavigationHistoryShortcuts() {
174 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
175 const routeThreadRef = useParams({
176 strict: false,
177 select: (params) => resolveThreadRouteRef(params),
178 });
179
180 useEffect(() => {
181 const onKeyDown = (event: KeyboardEvent) => {
182 if (event.defaultPrevented) return;
183 if (
184 event.target instanceof HTMLElement &&
185 event.target.closest("[data-keybinding-capture]")
186 ) {
187 return;
188 }
189 const command = resolveShortcutCommand(event, keybindings, {
190 context: {
191 terminalFocus: isTerminalFocused(),
192 terminalOpen: routeThreadRef
193 ? selectThreadTerminalUiState(
194 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
195 routeThreadRef,
196 ).terminalOpen
197 : false,
198 previewFocus: isPreviewFocused(),
199 previewOpen: routeThreadRef
200 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
201 "preview"
202 : false,
203 editableFocus: isEditableFocused(event.target),
204 modelPickerOpen: isModelPickerOpen(),
205 },
206 });
207 if (command !== "navigation.back" && command !== "navigation.forward") return;
208
209 event.preventDefault();
210 event.stopPropagation();
211 if (command === "navigation.back") window.history.back();
212 else window.history.forward();
213 };
214
215 window.addEventListener("keydown", onKeyDown);
216 return () => window.removeEventListener("keydown", onKeyDown);
217 }, [keybindings, routeThreadRef]);
218
219 return null;
220}
221
222// Settings swaps the thread sidebar out of the tree. Keep the lightweight
223// project projection subscribed so returning to a draft never renders the
224// zero-project state while the environment snapshot reconnects.
225function ProjectProjectionRetention() {
226 useProjects();
227 return null;
228}
229
230export function AppSidebarLayout({ children }: { children: ReactNode }) {
231 const navigate = useNavigate();
232 const legacySidebarEnabled = useLegacySidebarEnabled();
233 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
234 usePanelAnimationSettings();
235 // Settings routes show the settings nav in place of whichever thread
236 // sidebar is active.
237 // Seeds server-side visited tracking from this browser's localStorage the
238 useThreadVisitedMigration();
239 const pathname = useLocation({ select: (location) => location.pathname });
240 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
241 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
242 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
243 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
244 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
245 // Subscribed rather than read once: the clamp must track live window size,
246 // and a clamped drag ends with an unchanged width, which skips the re-render
247 // that would otherwise refresh a render-time snapshot.
248 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
249 const [brandWidth, setBrandWidth] = useState(0);
250 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
251 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
252 const resetSidebarWidth = () => {
253 try {
254 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
255 } catch (error) {
256 console.error("Could not clear persisted thread sidebar width.", error);
257 }
258 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
259 };
260 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
261 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
262 return isMacosDesktop && typeof getWindowFullscreenState === "function"
263 ? getWindowFullscreenState()
264 : false;
265 });
266 const windowControlsInsetStyle = (
267 isMacosDesktop && !isWindowFullscreen
268 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
269 : {}
270 ) as CSSProperties;
271 const sidebarProviderStyle = {
272 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
273 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
274 ...windowControlsInsetStyle,
275 } as CSSProperties;
276
277 useEffect(() => {
278 if (!isMacosDesktop) return;
279 const bridge = window.desktopBridge;
280 if (!bridge) return;
281 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
282 if (
283 typeof getWindowFullscreenState !== "function" ||
284 typeof onWindowFullscreenStateChange !== "function"
285 ) {
286 return;
287 }
288
289 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
290 setIsWindowFullscreen(getWindowFullscreenState());
291 return unsubscribe;
292 }, [isMacosDesktop]);
293
294 useEffect(() => {
295 const onMenuAction = window.desktopBridge?.onMenuAction;
296 if (typeof onMenuAction !== "function") {
297 return;
298 }
299
300 const unsubscribe = onMenuAction((action) => {
301 if (action === "open-settings") {
302 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
303 if (!isSettingsRoute) {
304 void navigate({ to: "/settings" });
305 }
306 }
307 });
308
309 return () => {
310 unsubscribe?.();
311 };
312 }, [navigate, pathname]);
313
314 return (
315 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
316 <SidebarProvider
317 className="h-dvh! min-h-0!"
318 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
319 defaultOpen
320 style={sidebarProviderStyle}
321 >
322 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
323 <ProjectProjectionRetention />
324 <Sidebar
325 side="left"
326 collapsible="offcanvas"
327 data-app-sidebar=""
328 role="navigation"
329 aria-label={isOnSettings ? "Settings" : "Threads"}
330 resizable={{
331 maxWidth: sidebarMaximumWidth,
332 minWidth: sidebarMinimumWidth,
333 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
334 nextWidth <= currentWidth ||
335 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
336 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
337 onResize: setSidebarWidth,
338 }}
339 // The narrow-window sidebar is a sheet, portaled outside the provider's styles.
340 style={windowControlsInsetStyle}
341 >
342 {isOnSettings ? (
343 <>
344 <SidebarChromeHeader isElectron={isElectron} />
345 <SettingsSidebarNav pathname={pathname} />
346 </>
347 ) : legacySidebarEnabled ? (
348 <LegacyThreadSidebar />
349 ) : (
350 <ThreadSidebar />
351 )}
352 <SidebarRail onDoubleClick={resetSidebarWidth} />
353 </Sidebar>
354 {children}
355 <SidebarControl />
356 <NavigationHistoryShortcuts />
357 <MainAppLocationTracker />
358 </SidebarProvider>
359 </PanelAnimationSuppressionProvider>
360 );
361}