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

AppSidebarLayout.tsx

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