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 window.addEventListener("keydown", onKeyDown, true);
126 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
127 if (action === "sidebar.toggle") toggleSidebar();
128 });
129 return () => {
130 window.removeEventListener("keydown", onKeyDown, true);
131 unsubscribe?.();
132 };
133 }, [keybindings, toggleSidebar, usagePageOpen]);
134
135 return (
136 <div
137 className={cn(
138 "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",
139 isMobile && mobileSheetMounted && "hidden",
140 )}
141 data-sidebar-control=""
142 >
143 <Tooltip>
144 <TooltipTrigger
145 render={
146 <SidebarTrigger
147 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
148 className={cn(
149 "pointer-events-auto",
150 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
151 )}
152 aria-label="Toggle main sidebar"
153 />
154 }
155 />
156 <TooltipPopup side="bottom">
157 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
158 </TooltipPopup>
159 </Tooltip>
160 </div>
161 );
162}
163
164function NavigationHistoryShortcuts() {
165 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
166 const routeThreadRef = useParams({
167 strict: false,
168 select: (params) => resolveThreadRouteRef(params),
169 });
170
171 useEffect(() => {
172 const onKeyDown = (event: KeyboardEvent) => {
173 if (event.defaultPrevented) return;
174 if (
175 event.target instanceof HTMLElement &&
176 event.target.closest("[data-keybinding-capture]")
177 ) {
178 return;
179 }
180 const command = resolveShortcutCommand(event, keybindings, {
181 context: {
182 terminalFocus: isTerminalFocused(),
183 terminalOpen: routeThreadRef
184 ? selectThreadTerminalUiState(
185 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
186 routeThreadRef,
187 ).terminalOpen
188 : false,
189 previewFocus: isPreviewFocused(),
190 previewOpen: routeThreadRef
191 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
192 "preview"
193 : false,
194 editableFocus: isEditableFocused(event.target),
195 modelPickerOpen: isModelPickerOpen(),
196 },
197 });
198 if (command !== "navigation.back" && command !== "navigation.forward") return;
199
200 event.preventDefault();
201 event.stopPropagation();
202 if (command === "navigation.back") window.history.back();
203 else window.history.forward();
204 };
205
206 window.addEventListener("keydown", onKeyDown);
207 return () => window.removeEventListener("keydown", onKeyDown);
208 }, [keybindings, routeThreadRef]);
209
210 return null;
211}
212
213// Settings swaps the thread sidebar out of the tree. Keep the lightweight
214// project projection subscribed so returning to a draft never renders the
215// zero-project state while the environment snapshot reconnects.
216function ProjectProjectionRetention() {
217 useProjects();
218 return null;
219}
220
221export function AppSidebarLayout({ children }: { children: ReactNode }) {
222 const navigate = useNavigate();
223 const legacySidebarEnabled = useLegacySidebarEnabled();
224 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
225 usePanelAnimationSettings();
226 useThreadVisitedMigration();
227 const pathname = useLocation({ select: (location) => location.pathname });
228 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
229 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
230 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
231 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
232 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
233 // Subscribed rather than read once: the clamp must track live window size,
234 // and a clamped drag ends with an unchanged width, which skips the re-render
235 // that would otherwise refresh a render-time snapshot.
236 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
237 const [brandWidth, setBrandWidth] = useState(0);
238 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
239 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
240 const resetSidebarWidth = () => {
241 try {
242 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
243 } catch (error) {
244 console.error("Could not clear persisted thread sidebar width.", error);
245 }
246 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
247 };
248 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
249 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
250 return isMacosDesktop && typeof getWindowFullscreenState === "function"
251 ? getWindowFullscreenState()
252 : false;
253 });
254 const windowControlsInsetStyle = (
255 isMacosDesktop && !isWindowFullscreen
256 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
257 : {}
258 ) as CSSProperties;
259 const sidebarProviderStyle = {
260 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
261 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
262 ...windowControlsInsetStyle,
263 } as CSSProperties;
264
265 useEffect(() => {
266 if (!isMacosDesktop) return;
267 const bridge = window.desktopBridge;
268 if (!bridge) return;
269 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
270 if (
271 typeof getWindowFullscreenState !== "function" ||
272 typeof onWindowFullscreenStateChange !== "function"
273 ) {
274 return;
275 }
276
277 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
278 setIsWindowFullscreen(getWindowFullscreenState());
279 return unsubscribe;
280 }, [isMacosDesktop]);
281
282 useEffect(() => {
283 const onMenuAction = window.desktopBridge?.onMenuAction;
284 if (typeof onMenuAction !== "function") {
285 return;
286 }
287
288 const unsubscribe = onMenuAction((action) => {
289 if (action === "open-settings") {
290 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
291 if (!isSettingsRoute) {
292 void navigate({ to: "/settings" });
293 }
294 }
295 });
296
297 return () => {
298 unsubscribe?.();
299 };
300 }, [navigate, pathname]);
301
302 return (
303 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
304 <SidebarProvider
305 className="h-dvh! min-h-0!"
306 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
307 defaultOpen
308 style={sidebarProviderStyle}
309 >
310 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
311 <ProjectProjectionRetention />
312 <Sidebar
313 side="left"
314 collapsible="offcanvas"
315 data-app-sidebar=""
316 role="navigation"
317 aria-label={isOnSettings ? "Settings" : "Threads"}
318 resizable={{
319 maxWidth: sidebarMaximumWidth,
320 minWidth: sidebarMinimumWidth,
321 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
322 nextWidth <= currentWidth ||
323 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
324 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
325 onResize: setSidebarWidth,
326 }}
327 style={windowControlsInsetStyle}
328 >
329 {isOnSettings ? (
330 <>
331 <SidebarChromeHeader isElectron={isElectron} />
332 <SettingsSidebarNav pathname={pathname} />
333 </>
334 ) : legacySidebarEnabled ? (
335 <LegacyThreadSidebar />
336 ) : (
337 <ThreadSidebar />
338 )}
339 <SidebarRail onDoubleClick={resetSidebarWidth} />
340 </Sidebar>
341 {children}
342 <SidebarControl />
343 <NavigationHistoryShortcuts />
344 <MainAppLocationTracker />
345 </SidebarProvider>
346 </PanelAnimationSuppressionProvider>
347 );
348}