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, useRouter, type AnyRouter } from "@tanstack/react-router";
11
12import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus";
13import { isCommandPaletteOpen } from "../commandPaletteBus";
14import { isElectron } from "../env";
15import {
16 releaseThreadUndoShortcut,
17 threadUndoClaimsShortcut,
18 undoLatestThreadAction,
19} from "../hooks/showThreadUndoNotice";
20import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
21import {
22 isRichTextBoldShortcut,
23 resolveShortcutCommand,
24 shortcutLabelForCommand,
25} from "../keybindings";
26import { isEditableFocused } from "../lib/editableFocus";
27import { isPreviewFocused } from "../lib/previewFocus";
28import { isTerminalFocused } from "../lib/terminalFocus";
29import { isModelPickerOpen } from "../modelPickerVisibility";
30import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
31import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
32import { cn, isMacPlatform } from "../lib/utils";
33import { primaryServerKeybindingsAtom } from "../state/server";
34import { useEnvironmentIdentificationMode } from "../hooks/useSettings";
35import {
36 PanelAnimationSuppressionProvider,
37 usePanelAnimationSettings,
38 usePanelNavigationSuppression,
39} from "../panelAnimations";
40import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
41import ThreadSidebar from "./Sidebar";
42import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
43import { isAppModalPage } from "./sidebar/mainAppLocation";
44import type { SidebarRouteReveal } from "./sidebar/routeReveal";
45import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
46import {
47 clampThreadSidebarWidth,
48 resolveInitialThreadSidebarWidth,
49 resolveThreadSidebarMaximumWidth,
50 resolveThreadSidebarMinimumWidth,
51 THREAD_MAIN_CONTENT_MIN_WIDTH,
52 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
53} from "./threadSidebarWidth";
54import {
55 Sidebar,
56 SidebarProvider,
57 SidebarRail,
58 SidebarTrigger,
59 useSidebar,
60 useSidebarVisibility,
61} from "./ui/sidebar";
62import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
63import { appAtomRegistry } from "../rpc/atomRegistry";
64import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher";
65import { resolveThreadRouteRef } from "../threadRoutes";
66
67const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
68
69function subscribeToViewportWidth(onChange: () => void): () => void {
70 window.addEventListener("resize", onChange);
71 return () => window.removeEventListener("resize", onChange);
72}
73
74function readViewportWidth(): number {
75 return window.innerWidth;
76}
77
78// Cache the synchronous fullscreen IPC read until subscription.
79let windowFullscreenSnapshot: boolean | null = null;
80
81function macosDesktopBridge() {
82 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
83 return window.desktopBridge ?? null;
84}
85
86function subscribeToWindowFullscreen(onChange: () => void): () => void {
87 const bridge = macosDesktopBridge();
88 if (
89 typeof bridge?.getWindowFullscreenState !== "function" ||
90 typeof bridge.onWindowFullscreenStateChange !== "function"
91 ) {
92 return () => {};
93 }
94 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
95 windowFullscreenSnapshot = fullscreen;
96 onChange();
97 });
98 // The window may have changed state between the first render and this subscription.
99 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
100 return () => {
101 unsubscribe();
102 windowFullscreenSnapshot = null;
103 };
104}
105
106function readWindowFullscreen(): boolean {
107 if (windowFullscreenSnapshot === null) {
108 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
109 windowFullscreenSnapshot =
110 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
111 }
112 return windowFullscreenSnapshot;
113}
114
115function readInitialThreadSidebarWidth(): number {
116 try {
117 return resolveInitialThreadSidebarWidth(
118 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
119 window.innerWidth,
120 );
121 } catch (error) {
122 console.error("Could not read persisted thread sidebar width.", error);
123 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
124 }
125}
126
127function readUsagePageOpen(router: AnyRouter) {
128 return router.state.location.pathname === "/usage";
129}
130
131function isKeybindingCaptureTarget(event: KeyboardEvent) {
132 return event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]");
133}
134
135function readRoutePanelsOpen(router: AnyRouter) {
136 const routeThreadRef = resolveThreadRouteRef(router.state.matches.at(-1)?.params ?? {});
137 if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
138 return {
139 terminalOpen: selectThreadTerminalUiState(
140 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
141 routeThreadRef,
142 ).terminalOpen,
143 previewOpen:
144 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
145 "preview",
146 };
147}
148
149export function registerNavigationHistoryCommands(router: AnyRouter): () => void {
150 return registerCommands(
151 {
152 "navigation.back": (event) => {
153 event.preventDefault();
154 event.stopPropagation();
155 window.history.back();
156 },
157 "navigation.forward": (event) => {
158 event.preventDefault();
159 event.stopPropagation();
160 window.history.forward();
161 },
162 },
163 {
164 when: (event) => !isKeybindingCaptureTarget(event),
165 context: () => ({
166 ...readRoutePanelsOpen(router),
167 usagePageOpen: readUsagePageOpen(router),
168 }),
169 },
170 );
171}
172
173// Capture phase, so F6 also leaves widgets that swallow keys, such as the terminal.
174function registerWorkspaceFocusCommands(router: AnyRouter): () => void {
175 const move = (direction: 1 | -1) => (event: KeyboardEvent) => {
176 if (event.isComposing) return false;
177 // Inside a dialog the move is refused, but the key is still consumed.
178 event.preventDefault();
179 event.stopPropagation();
180 moveWorkspaceFocus(direction);
181 };
182 const disposers = [
183 registerCommands(
184 { "workspace.focusNext": move(1), "workspace.focusPrevious": move(-1) },
185 {
186 capture: true,
187 when: (event) => !isKeybindingCaptureTarget(event),
188 context: () => readRoutePanelsOpen(router),
189 },
190 ),
191 // A focused desktop browser forwards the keys; its renderer focus is stale.
192 registerMenuAction("workspace.focusNext", () => moveWorkspaceFocus(1, "panel")),
193 registerMenuAction("workspace.focusPrevious", () => moveWorkspaceFocus(-1, "panel")),
194 ];
195 return () => {
196 for (const dispose of disposers) dispose();
197 };
198}
199
200// Escape leaves the pull requests page when no scope (a selection, a dialog,
201// a drag) claimed it, so it observes after every other scope.
202function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {
203 return registerCommands(
204 {},
205 {
206 observe: (event, consumed) => {
207 if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return;
208 if (router.state.location.pathname !== "/pull-requests") return;
209 event.preventDefault();
210 const activeElement = document.activeElement;
211 if (activeElement instanceof HTMLElement) activeElement.blur();
212 if (router.state.location.state.__TSR_index !== 0) {
213 window.history.back();
214 return;
215 }
216 void router.navigate({ to: "/" });
217 },
218 },
219 );
220}
221
222const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
223
224// A held key undoes once. Module state: undoing an archive navigates, and the
225// hold must survive whatever that re-renders.
226let heldUndoKey: string | null = null;
227
228// Undoes the thread actions in the sidebar's notice. Settings and Usage own
229// mod+z while open. Captured so mod+z reaches it before the composer's own
230// undo handler consumes the key.
231function registerThreadUndoCommands(
232 router: AnyRouter,
233 readSidebarVisible: () => boolean,
234): () => void {
235 const threadSidebarShown = () => !isAppModalPage(router.state.location.pathname);
236 const unregister = registerCommands(
237 {},
238 {
239 capture: true,
240 when: threadSidebarShown,
241 onKeyDown: (event) => {
242 // Cancel a held key's repeats so they cannot fall through to the
243 // editor's own undo, even after the last notice is gone.
244 if (event.repeat) {
245 if (event.code !== heldUndoKey) return false;
246 event.preventDefault();
247 event.stopPropagation();
248 return true;
249 }
250 // A modifier tapped mid-hold leaves the held key repeating.
251 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey = null;
252 const command = resolveShortcutCommand(
253 event,
254 appAtomRegistry.get(primaryServerKeybindingsAtom),
255 {
256 context: {
257 terminalFocus: isTerminalFocused(),
258 previewFocus: isPreviewFocused(),
259 ...readRoutePanelsOpen(router),
260 // A collapsed sidebar hides the notice, so text fields keep their own undo.
261 editableFocus:
262 isEditableFocused(event.target) &&
263 !(readSidebarVisible() && threadUndoClaimsShortcut()),
264 modelPickerOpen: isModelPickerOpen(),
265 },
266 },
267 );
268 if (command !== "thread.undo") {
269 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
270 return false;
271 }
272 if (isCommandPaletteOpen() || isModelPickerOpen()) return false;
273 if (!undoLatestThreadAction()) return false;
274 heldUndoKey = event.code;
275 event.preventDefault();
276 event.stopPropagation();
277 return true;
278 },
279 },
280 );
281 // Pastes from a menu, dictation and drops edit text without a keypress.
282 const onInput = () => {
283 if (threadSidebarShown()) releaseThreadUndoShortcut();
284 };
285 window.addEventListener("input", onInput, true);
286 return () => {
287 unregister();
288 window.removeEventListener("input", onInput, true);
289 };
290}
291
292/** Keyboard and menu commands that live as long as the app shell. */
293function registerAppShellCommands(router: AnyRouter, shellElement: Element): () => void {
294 // The provider mirrors the visibility it renders onto its wrapper, so the
295 // committed state is readable when a key arrives.
296 const readSidebarVisible = () =>
297 shellElement.closest('[data-slot="sidebar-wrapper"]')?.getAttribute("data-sidebar-state") ===
298 "expanded";
299 const disposers = [
300 registerThreadUndoCommands(router, readSidebarVisible),
301 registerNavigationHistoryCommands(router),
302 registerWorkspaceFocusCommands(router),
303 registerPullRequestsEscapeCommand(router),
304 registerMenuAction("open-settings", () => {
305 if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
306 void router.navigate({ to: "/settings" });
307 }),
308 ];
309 return () => {
310 for (const dispose of disposers) dispose();
311 };
312}
313
314function SidebarControl() {
315 const router = useRouter();
316 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
317 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
318 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
319 const isSidebarVisible = useSidebarVisibility();
320 const environmentIdentificationMode = useEnvironmentIdentificationMode();
321 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
322 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
323 context: { usagePageOpen },
324 });
325
326 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener that toggles the sidebar on its shortcut
327 useEffect(() => {
328 const onKeyDown = (event: KeyboardEvent) => {
329 if (event.defaultPrevented) return;
330 if (
331 event.target instanceof HTMLElement &&
332 event.target.closest("[data-keybinding-capture]")
333 ) {
334 return;
335 }
336 if (
337 isRichTextBoldShortcut(event, window.getSelection()) &&
338 event.target instanceof HTMLElement &&
339 event.target.closest('[data-composer-rich-text="true"]')
340 ) {
341 // The rich-text composer claims Mod+B only to bold selected text;
342 // the toggle stays available everywhere else.
343 return;
344 }
345 if (
346 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
347 "sidebar.toggle"
348 )
349 return;
350
351 event.preventDefault();
352 event.stopPropagation();
353 toggleSidebar();
354 };
355
356 window.addEventListener("keydown", onKeyDown, true);
357 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
358 if (action === "sidebar.toggle") toggleSidebar();
359 });
360 return () => {
361 window.removeEventListener("keydown", onKeyDown, true);
362 unsubscribe?.();
363 };
364 }, [keybindings, toggleSidebar, usagePageOpen]);
365
366 // The control lives as long as the shell, so it carries the shell's commands. Created
367 // once so re-renders never re-register them.
368 const [appShellCommandsRef] = useState(
369 () => (node: HTMLDivElement | null) =>
370 node === null ? undefined : registerAppShellCommands(router, node),
371 );
372
373 return (
374 <div
375 ref={appShellCommandsRef}
376 className={cn(
377 "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",
378 isMobile && mobileSheetMounted && "hidden",
379 )}
380 data-sidebar-control=""
381 >
382 <Tooltip>
383 <TooltipTrigger
384 render={
385 <SidebarTrigger
386 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
387 className={cn(
388 "pointer-events-auto",
389 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
390 )}
391 aria-label="Toggle main sidebar"
392 />
393 }
394 />
395 <TooltipPopup side="bottom">
396 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
397 </TooltipPopup>
398 </Tooltip>
399 </div>
400 );
401}
402
403export function AppSidebarLayout({ children }: { children: ReactNode }) {
404 const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads");
405 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
406 observedKey: null,
407 pendingKey: null,
408 }));
409 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
410 usePanelAnimationSettings();
411 const pathname = useLocation({ select: (location) => location.pathname });
412 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
413 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
414 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
415 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
416 // A clamped drag may not change width, so viewport changes need a separate subscription.
417 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
418 const [brandWidth, setBrandWidth] = useState(0);
419 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
420 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
421 const resetSidebarWidth = () => {
422 try {
423 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
424 } catch (error) {
425 console.error("Could not clear persisted thread sidebar width.", error);
426 }
427 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
428 };
429 const isWindowFullscreen = useSyncExternalStore(
430 subscribeToWindowFullscreen,
431 readWindowFullscreen,
432 );
433 const windowControlsInsetStyle = (
434 isMacosDesktop && !isWindowFullscreen
435 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
436 : {}
437 ) as CSSProperties;
438 const sidebarProviderStyle = {
439 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
440 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
441 ...windowControlsInsetStyle,
442 } as CSSProperties;
443
444 return (
445 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
446 <SidebarProvider
447 className="h-dvh! min-h-0!"
448 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
449 defaultOpen
450 style={sidebarProviderStyle}
451 >
452 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
453 <Sidebar
454 side="left"
455 collapsible="offcanvas"
456 data-app-sidebar=""
457 {...sidebarArea}
458 role="navigation"
459 aria-label="Threads"
460 resizable={{
461 maxWidth: sidebarMaximumWidth,
462 minWidth: sidebarMinimumWidth,
463 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
464 nextWidth <= currentWidth ||
465 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
466 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
467 onResize: setSidebarWidth,
468 }}
469 style={windowControlsInsetStyle}
470 >
471 <ThreadSidebar routeReveal={sidebarRouteReveal} />
472 <SidebarRail onDoubleClick={resetSidebarWidth} />
473 </Sidebar>
474 {children}
475 <BackgroundThreadAnnouncer />
476 <SidebarControl />
477 </SidebarProvider>
478 </PanelAnimationSuppressionProvider>
479 );
480}