Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AppSidebarLayout.tsx

456 lines16.4 KB

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 { isCommandPaletteOpen } from "../commandPaletteBus";
13import { isElectron } from "../env";
14import {
15 releaseThreadUndoShortcut,
16 threadUndoClaimsShortcut,
17 undoLatestThreadAction,
18} from "../hooks/showThreadUndoNotice";
19import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
20import {
21 isRichTextBoldShortcut,
22 resolveShortcutCommand,
23 shortcutLabelForCommand,
24} from "../keybindings";
25import { isEditableFocused } from "../lib/editableFocus";
26import { isPreviewFocused } from "../lib/previewFocus";
27import { isTerminalFocused } from "../lib/terminalFocus";
28import { isModelPickerOpen } from "../modelPickerVisibility";
29import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
30import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
31import { cn, isMacPlatform } from "../lib/utils";
32import { primaryServerKeybindingsAtom } from "../state/server";
33import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
34import {
35 PanelAnimationSuppressionProvider,
36 usePanelAnimationSettings,
37 usePanelNavigationSuppression,
38} from "../panelAnimations";
39import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
40import LegacyThreadSidebar from "./LegacySidebar";
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);
73​
74function readViewportWidth(): number {
75 return window.innerWidth;
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;
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 };
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;
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 }
126​
127function readUsagePageOpen(router: AnyRouter) {
128 return router.state.location.pathname === "/usage";
130​
131function isKeybindingCaptureTarget(event: KeyboardEvent) {
132 return event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]");
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 };
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 );
172​
173// Escape leaves the pull requests page when no scope (a selection, a dialog,
174// a drag) claimed it, so it observes after every other scope.
175function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {
176 return registerCommands(
177 {},
178 {
179 observe: (event, consumed) => {
180 if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return;
181 if (router.state.location.pathname !== "/pull-requests") return;
182 event.preventDefault();
183 const activeElement = document.activeElement;
184 if (activeElement instanceof HTMLElement) activeElement.blur();
185 if (router.state.location.state.__TSR_index !== 0) {
186 window.history.back();
187 return;
188 }
189 void router.navigate({ to: "/" });
190 },
191 },
192 );
194​
195const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
196​
197// A held key undoes once. Module state: undoing an archive navigates, and the
198// hold must survive whatever that re-renders.
199let heldUndoKey: string | null = null;
200​
201// Undoes the thread actions in the sidebar's notice. Settings and Usage own
202// mod+z while open. Captured so mod+z reaches it before the composer's own
203// undo handler consumes the key.
204function registerThreadUndoCommands(
205 router: AnyRouter,
206 readSidebarVisible: () => boolean,
207): () => void {
208 const threadSidebarShown = () => !isAppModalPage(router.state.location.pathname);
209 const unregister = registerCommands(
210 {},
211 {
212 capture: true,
213 when: threadSidebarShown,
214 onKeyDown: (event) => {
215 // Cancel a held key's repeats so they cannot fall through to the
216 // editor's own undo, even after the last notice is gone.
217 if (event.repeat) {
218 if (event.code !== heldUndoKey) return false;
219 event.preventDefault();
220 event.stopPropagation();
221 return true;
222 }
223 // A modifier tapped mid-hold leaves the held key repeating.
224 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey = null;
225 const command = resolveShortcutCommand(
226 event,
227 appAtomRegistry.get(primaryServerKeybindingsAtom),
228 {
229 context: {
230 terminalFocus: isTerminalFocused(),
231 previewFocus: isPreviewFocused(),
232 ...readRoutePanelsOpen(router),
233 // A collapsed sidebar hides the notice, so text fields keep their own undo.
234 editableFocus:
235 isEditableFocused(event.target) &&
236 !(readSidebarVisible() && threadUndoClaimsShortcut()),
237 modelPickerOpen: isModelPickerOpen(),
238 },
239 },
240 );
241 if (command !== "thread.undo") {
242 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
243 return false;
244 }
245 if (isCommandPaletteOpen() || isModelPickerOpen()) return false;
246 if (!undoLatestThreadAction()) return false;
247 heldUndoKey = event.code;
248 event.preventDefault();
249 event.stopPropagation();
250 return true;
251 },
252 },
253 );
254 // Pastes from a menu, dictation and drops edit text without a keypress.
255 const onInput = () => {
256 if (threadSidebarShown()) releaseThreadUndoShortcut();
257 };
258 window.addEventListener("input", onInput, true);
259 return () => {
260 unregister();
261 window.removeEventListener("input", onInput, true);
262 };
264​
265/** Keyboard and menu commands that live as long as the app shell. */
266function registerAppShellCommands(router: AnyRouter, shellElement: Element): () => void {
267 // The provider mirrors the visibility it renders onto its wrapper, so the
268 // committed state is readable when a key arrives.
269 const readSidebarVisible = () =>
270 shellElement.closest('[data-slot="sidebar-wrapper"]')?.getAttribute("data-sidebar-state") ===
271 "expanded";
272 const disposers = [
273 registerThreadUndoCommands(router, readSidebarVisible),
274 registerNavigationHistoryCommands(router),
275 registerPullRequestsEscapeCommand(router),
276 registerMenuAction("open-settings", () => {
277 if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
278 void router.navigate({ to: "/settings" });
279 }),
280 ];
281 return () => {
282 for (const dispose of disposers) dispose();
283 };
285​
286function SidebarControl() {
287 const router = useRouter();
288 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
289 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
290 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
291 const isSidebarVisible = useSidebarVisibility();
292 const environmentIdentificationMode = useEnvironmentIdentificationMode();
293 const stageBackdropVariant = useSidebarStageBackdropVariant(
294 environmentIdentificationMode === "artwork",
295 );
296 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
297 context: { usagePageOpen },
298 });
299​
300 useEffect(() => {
301 const onKeyDown = (event: KeyboardEvent) => {
302 if (event.defaultPrevented) return;
303 if (
304 event.target instanceof HTMLElement &&
305 event.target.closest("[data-keybinding-capture]")
306 ) {
307 return;
308 }
309 if (
310 isRichTextBoldShortcut(event, window.getSelection()) &&
311 event.target instanceof HTMLElement &&
312 event.target.closest('[data-composer-rich-text="true"]')
313 ) {
314 // The rich-text composer claims Mod+B only to bold selected text;
315 // the toggle stays available everywhere else.
316 return;
317 }
318 if (
319 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
320 "sidebar.toggle"
321 )
322 return;
323​
324 event.preventDefault();
325 event.stopPropagation();
326 toggleSidebar();
327 };
328​
329 window.addEventListener("keydown", onKeyDown, true);
330 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
331 if (action === "sidebar.toggle") toggleSidebar();
332 });
333 return () => {
334 window.removeEventListener("keydown", onKeyDown, true);
335 unsubscribe?.();
336 };
337 }, [keybindings, toggleSidebar, usagePageOpen]);
338​
339 // The control lives as long as the shell, so it carries the shell's commands. Created
340 // once so re-renders never re-register them.
341 const [appShellCommandsRef] = useState(
342 () => (node: HTMLDivElement | null) =>
343 node === null ? undefined : registerAppShellCommands(router, node),
344 );
345​
346 return (
347 <div
348 ref={appShellCommandsRef}
349 className={cn(
350 "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",
351 isMobile && mobileSheetMounted && "hidden",
352 )}
353 data-sidebar-control=""
354 >
355 <Tooltip>
356 <TooltipTrigger
357 render={
358 <SidebarTrigger
359 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
360 className={cn(
361 "pointer-events-auto",
362 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
363 )}
364 aria-label="Toggle main sidebar"
365 />
366 }
367 />
368 <TooltipPopup side="bottom">
369 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
370 </TooltipPopup>
371 </Tooltip>
372 </div>
373 );
375​
376export function AppSidebarLayout({ children }: { children: ReactNode }) {
377 const legacySidebarEnabled = useLegacySidebarEnabled();
378 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
379 observedKey: null,
380 pendingKey: null,
381 }));
382 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
383 usePanelAnimationSettings();
384 const pathname = useLocation({ select: (location) => location.pathname });
385 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
386 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
387 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
388 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
389 // A clamped drag may not change width, so viewport changes need a separate subscription.
390 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
391 const [brandWidth, setBrandWidth] = useState(0);
392 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
393 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
394 const resetSidebarWidth = () => {
395 try {
396 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
397 } catch (error) {
398 console.error("Could not clear persisted thread sidebar width.", error);
399 }
400 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
401 };
402 const isWindowFullscreen = useSyncExternalStore(
403 subscribeToWindowFullscreen,
404 readWindowFullscreen,
405 );
406 const windowControlsInsetStyle = (
407 isMacosDesktop && !isWindowFullscreen
408 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
409 : {}
410 ) as CSSProperties;
411 const sidebarProviderStyle = {
412 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
413 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
414 ...windowControlsInsetStyle,
415 } as CSSProperties;
416​
417 return (
418 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
419 <SidebarProvider
420 className="h-dvh! min-h-0!"
421 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
422 defaultOpen
423 style={sidebarProviderStyle}
424 >
425 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
426 <Sidebar
427 side="left"
428 collapsible="offcanvas"
429 data-app-sidebar=""
430 role="navigation"
431 aria-label="Threads"
432 resizable={{
433 maxWidth: sidebarMaximumWidth,
434 minWidth: sidebarMinimumWidth,
435 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
436 nextWidth <= currentWidth ||
437 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
438 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
439 onResize: setSidebarWidth,
440 }}
441 style={windowControlsInsetStyle}
442 >
443 {legacySidebarEnabled ? (
444 <LegacyThreadSidebar routeReveal={sidebarRouteReveal} />
445 ) : (
446 <ThreadSidebar routeReveal={sidebarRouteReveal} />
447 )}
448 <SidebarRail onDoubleClick={resetSidebarWidth} />
449 </Sidebar>
450 {children}
451 <BackgroundThreadAnnouncer />
452 <SidebarControl />
453 </SidebarProvider>
454 </PanelAnimationSuppressionProvider>
455 );