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