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