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