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

AppSidebarLayout.tsx

516 lines18.8 KB

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