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

AppSidebarLayout.tsx

446 lines16.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import * as Schema from "effect/Schema";
3import {
4 useEffect,
5 useRef,
6 useState,
7 useSyncExternalStore,
8 type CSSProperties,
9 type ReactNode,
10} from "react";
11import { useLocation, useNavigate } from "@tanstack/react-router";
12​
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, useLegacySidebarEnabled } from "../hooks/useSettings";
35import {
36 PanelAnimationSuppressionProvider,
37 usePanelAnimationSettings,
38 usePanelNavigationSuppression,
39} from "../panelAnimations";
40import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
41import LegacyThreadSidebar from "./LegacySidebar";
42import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
43import ThreadSidebar from "./Sidebar";
44import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
45import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
46import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
47import type { SidebarRouteReveal } from "./sidebar/routeReveal";
48import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
49import { useProjects } from "../state/entities";
50import {
51 clampThreadSidebarWidth,
52 resolveInitialThreadSidebarWidth,
53 resolveThreadSidebarMaximumWidth,
54 resolveThreadSidebarMinimumWidth,
55 THREAD_MAIN_CONTENT_MIN_WIDTH,
56 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
57} from "./threadSidebarWidth";
58import {
59 Sidebar,
60 SidebarProvider,
61 SidebarRail,
62 SidebarTrigger,
63 useSidebar,
64 useSidebarVisibility,
65} from "./ui/sidebar";
66import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
67import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
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);
75​
76function readViewportWidth(): number {
77 return window.innerWidth;
79​
80// getWindowFullscreenState is a synchronous IPC round trip, so the snapshot is cached
81// and only re-read when a subscription starts.
82let windowFullscreenSnapshot: boolean | null = null;
83​
84function macosDesktopBridge() {
85 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
86 return window.desktopBridge ?? null;
88​
89function subscribeToWindowFullscreen(onChange: () => void): () => void {
90 const bridge = macosDesktopBridge();
91 if (
92 typeof bridge?.getWindowFullscreenState !== "function" ||
93 typeof bridge.onWindowFullscreenStateChange !== "function"
94 ) {
95 return () => {};
96 }
97 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
98 windowFullscreenSnapshot = fullscreen;
99 onChange();
100 });
101 // The window may have changed state between the first render and this subscription.
102 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
103 return () => {
104 unsubscribe();
105 windowFullscreenSnapshot = null;
106 };
108​
109function readWindowFullscreen(): boolean {
110 if (windowFullscreenSnapshot === null) {
111 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
112 windowFullscreenSnapshot =
113 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
114 }
115 return windowFullscreenSnapshot;
117​
118function readInitialThreadSidebarWidth(): number {
119 try {
120 return resolveInitialThreadSidebarWidth(
121 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
122 window.innerWidth,
123 );
124 } catch (error) {
125 console.error("Could not read persisted thread sidebar width.", error);
126 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
127 }
129​
130function SidebarControl() {
131 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
132 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
133 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
134 const isSidebarVisible = useSidebarVisibility();
135 const environmentIdentificationMode = useEnvironmentIdentificationMode();
136 const stageBackdropVariant = useSidebarStageBackdropVariant(
137 environmentIdentificationMode === "artwork",
138 );
139 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
140 context: { usagePageOpen },
141 });
142​
143 useEffect(() => {
144 const onKeyDown = (event: KeyboardEvent) => {
145 if (event.defaultPrevented) return;
146 if (
147 event.target instanceof HTMLElement &&
148 event.target.closest("[data-keybinding-capture]")
149 ) {
150 return;
151 }
152 if (
153 isRichTextBoldShortcut(event, window.getSelection()) &&
154 event.target instanceof HTMLElement &&
155 event.target.closest('[data-composer-rich-text="true"]')
156 ) {
157 // The rich-text composer claims Mod+B only to bold selected text;
158 // the toggle stays available everywhere else.
159 return;
160 }
161 if (
162 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
163 "sidebar.toggle"
164 )
165 return;
166​
167 event.preventDefault();
168 event.stopPropagation();
169 toggleSidebar();
170 };
171​
172 window.addEventListener("keydown", onKeyDown, true);
173 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
174 if (action === "sidebar.toggle") toggleSidebar();
175 });
176 return () => {
177 window.removeEventListener("keydown", onKeyDown, true);
178 unsubscribe?.();
179 };
180 }, [keybindings, toggleSidebar, usagePageOpen]);
181​
182 return (
183 <div
184 className={cn(
185 "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",
186 isMobile && mobileSheetMounted && "hidden",
187 )}
188 data-sidebar-control=""
189 >
190 <Tooltip>
191 <TooltipTrigger
192 render={
193 <SidebarTrigger
194 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
195 className={cn(
196 "pointer-events-auto",
197 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
198 )}
199 aria-label="Toggle main sidebar"
200 />
201 }
202 />
203 <TooltipPopup side="bottom">
204 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
205 </TooltipPopup>
206 </Tooltip>
207 </div>
208 );
210​
211function routePanelsOpen(routeThreadRef: ReturnType<typeof useThreadRouteRef>) {
212 if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
213 return {
214 terminalOpen: selectThreadTerminalUiState(
215 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
216 routeThreadRef,
217 ).terminalOpen,
218 previewOpen:
219 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
220 "preview",
221 };
223​
224export function NavigationHistoryShortcuts() {
225 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
226 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
227 const routeThreadRef = useThreadRouteRef();
228​
229 useEffect(() => {
230 const onKeyDown = (event: KeyboardEvent) => {
231 if (event.defaultPrevented) return;
232 if (
233 event.target instanceof HTMLElement &&
234 event.target.closest("[data-keybinding-capture]")
235 ) {
236 return;
237 }
238 const command = resolveShortcutCommand(event, keybindings, {
239 context: {
240 terminalFocus: isTerminalFocused(),
241 previewFocus: isPreviewFocused(),
242 ...routePanelsOpen(routeThreadRef),
243 editableFocus: isEditableFocused(event.target),
244 modelPickerOpen: isModelPickerOpen(),
245 usagePageOpen,
246 },
247 });
248 if (command !== "navigation.back" && command !== "navigation.forward") return;
249​
250 event.preventDefault();
251 event.stopPropagation();
252 if (command === "navigation.back") window.history.back();
253 else window.history.forward();
254 };
255​
256 window.addEventListener("keydown", onKeyDown);
257 return () => window.removeEventListener("keydown", onKeyDown);
258 }, [keybindings, routeThreadRef, usagePageOpen]);
259​
260 return null;
262​
263const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
264​
265// Undoes the thread actions in the sidebar's notice. Mounted wherever the
266// thread sidebar can show; Settings replaces it. Listens in the capture phase
267// so mod+z reaches it before the composer's own undo handler consumes the key.
268function ThreadUndoShortcut() {
269 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
270 const routeThreadRef = useThreadRouteRef();
271 // A collapsed sidebar hides the notice, so text fields keep their own undo.
272 const noticeVisible = useSidebarVisibility();
273 // Outlives the effect: undoing an archive navigates, which re-runs it mid-hold.
274 const heldUndoKey = useRef<string | null>(null);
275​
276 useEffect(() => {
277 const onKeyDown = (event: KeyboardEvent) => {
278 // A held key undoes once. Cancel its repeats so they cannot fall through
279 // to the editor's own undo, even after the last notice is gone.
280 if (event.repeat) {
281 if (event.code === heldUndoKey.current) {
282 event.preventDefault();
283 event.stopPropagation();
284 }
285 return;
286 }
287 // A modifier tapped mid-hold leaves the held key repeating.
288 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey.current = null;
289 const command = resolveShortcutCommand(event, keybindings, {
290 context: {
291 terminalFocus: isTerminalFocused(),
292 previewFocus: isPreviewFocused(),
293 ...routePanelsOpen(routeThreadRef),
294 editableFocus:
295 isEditableFocused(event.target) && !(noticeVisible && threadUndoClaimsShortcut()),
296 modelPickerOpen: isModelPickerOpen(),
297 },
298 });
299 if (command !== "thread.undo") {
300 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
301 return;
302 }
303 if (isCommandPaletteOpen() || isModelPickerOpen()) return;
304 if (undoLatestThreadAction()) {
305 heldUndoKey.current = event.code;
306 event.preventDefault();
307 event.stopPropagation();
308 }
309 };
310 // Pastes from a menu, dictation and drops edit text without a keypress.
311 const onInput = () => releaseThreadUndoShortcut();
312​
313 window.addEventListener("keydown", onKeyDown, true);
314 window.addEventListener("input", onInput, true);
315 return () => {
316 window.removeEventListener("keydown", onKeyDown, true);
317 window.removeEventListener("input", onInput, true);
318 };
319 }, [keybindings, noticeVisible, routeThreadRef]);
320​
321 return null;
323​
324// Settings swaps the thread sidebar out of the tree. Keep the lightweight
325// project projection subscribed so returning to a draft never renders the
326// zero-project state while the environment snapshot reconnects.
327function ProjectProjectionRetention() {
328 useProjects();
329 return null;
331​
332export function AppSidebarLayout({ children }: { children: ReactNode }) {
333 const navigate = useNavigate();
334 const legacySidebarEnabled = useLegacySidebarEnabled();
335 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
336 observedKey: null,
337 pendingKey: null,
338 }));
339 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
340 usePanelAnimationSettings();
341 useThreadVisitedMigration();
342 const pathname = useLocation({ select: (location) => location.pathname });
343 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
344 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
345 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
346 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
347 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
348 // Subscribed rather than read once: the clamp must track live window size,
349 // and a clamped drag ends with an unchanged width, which skips the re-render
350 // that would otherwise refresh a render-time snapshot.
351 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
352 const [brandWidth, setBrandWidth] = useState(0);
353 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
354 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
355 const resetSidebarWidth = () => {
356 try {
357 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
358 } catch (error) {
359 console.error("Could not clear persisted thread sidebar width.", error);
360 }
361 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
362 };
363 const isWindowFullscreen = useSyncExternalStore(
364 subscribeToWindowFullscreen,
365 readWindowFullscreen,
366 );
367 const windowControlsInsetStyle = (
368 isMacosDesktop && !isWindowFullscreen
369 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
370 : {}
371 ) as CSSProperties;
372 const sidebarProviderStyle = {
373 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
374 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
375 ...windowControlsInsetStyle,
376 } as CSSProperties;
377​
378 useEffect(() => {
379 const onMenuAction = window.desktopBridge?.onMenuAction;
380 if (typeof onMenuAction !== "function") {
381 return;
382 }
383​
384 const unsubscribe = onMenuAction((action) => {
385 if (action === "open-settings") {
386 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
387 if (!isSettingsRoute) {
388 void navigate({ to: "/settings" });
389 }
390 }
391 });
392​
393 return () => {
394 unsubscribe?.();
395 };
396 }, [navigate, pathname]);
397​
398 return (
399 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
400 <SidebarProvider
401 className="h-dvh! min-h-0!"
402 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
403 defaultOpen
404 style={sidebarProviderStyle}
405 >
406 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
407 <ProjectProjectionRetention />
408 <Sidebar
409 side="left"
410 collapsible="offcanvas"
411 data-app-sidebar=""
412 role="navigation"
413 aria-label={isOnSettings ? "Settings" : "Threads"}
414 resizable={{
415 maxWidth: sidebarMaximumWidth,
416 minWidth: sidebarMinimumWidth,
417 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
418 nextWidth <= currentWidth ||
419 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
420 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
421 onResize: setSidebarWidth,
422 }}
423 style={windowControlsInsetStyle}
424 >
425 {isOnSettings ? (
426 <>
427 <SidebarChromeHeader isElectron={isElectron} />
428 <SettingsSidebarNav pathname={pathname} />
429 </>
430 ) : legacySidebarEnabled ? (
431 <LegacyThreadSidebar routeReveal={sidebarRouteReveal} />
432 ) : (
433 <ThreadSidebar routeReveal={sidebarRouteReveal} />
434 )}
435 <SidebarRail onDoubleClick={resetSidebarWidth} />
436 </Sidebar>
437 {children}
438 <BackgroundThreadAnnouncer />
439 <SidebarControl />
440 <NavigationHistoryShortcuts />
441 {isOnSettings ? null : <ThreadUndoShortcut />}
442 <MainAppLocationTracker />
443 </SidebarProvider>
444 </PanelAnimationSuppressionProvider>
445 );