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

AppSidebarLayout.tsx

437 lines15.7 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​
222function NavigationHistoryShortcuts() {
223 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
224 const routeThreadRef = useThreadRouteRef();
225​
226 useEffect(() => {
227 const onKeyDown = (event: KeyboardEvent) => {
228 if (event.defaultPrevented) return;
229 if (
230 event.target instanceof HTMLElement &&
231 event.target.closest("[data-keybinding-capture]")
232 ) {
233 return;
234 }
235 const command = resolveShortcutCommand(event, keybindings, {
236 context: {
237 terminalFocus: isTerminalFocused(),
238 previewFocus: isPreviewFocused(),
239 ...routePanelsOpen(routeThreadRef),
240 editableFocus: isEditableFocused(event.target),
241 modelPickerOpen: isModelPickerOpen(),
242 },
243 });
244 if (command !== "navigation.back" && command !== "navigation.forward") return;
245​
246 event.preventDefault();
247 event.stopPropagation();
248 if (command === "navigation.back") window.history.back();
249 else window.history.forward();
250 };
251​
252 window.addEventListener("keydown", onKeyDown);
253 return () => window.removeEventListener("keydown", onKeyDown);
254 }, [keybindings, routeThreadRef]);
255​
256 return null;
258​
259const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
260​
261// Undoes the thread actions in the sidebar's notice. Mounted wherever the
262// thread sidebar can show; Settings replaces it. Listens in the capture phase
263// so mod+z reaches it before the composer's own undo handler consumes the key.
264function ThreadUndoShortcut() {
265 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
266 const routeThreadRef = useThreadRouteRef();
267 // A collapsed sidebar hides the notice, so text fields keep their own undo.
268 const noticeVisible = useSidebarVisibility();
269 // Outlives the effect: undoing an archive navigates, which re-runs it mid-hold.
270 const heldUndoKey = useRef<string | null>(null);
271​
272 useEffect(() => {
273 const onKeyDown = (event: KeyboardEvent) => {
274 // A held key undoes once. Cancel its repeats so they cannot fall through
275 // to the editor's own undo, even after the last notice is gone.
276 if (event.repeat) {
277 if (event.code === heldUndoKey.current) {
278 event.preventDefault();
279 event.stopPropagation();
280 }
281 return;
282 }
283 // A modifier tapped mid-hold leaves the held key repeating.
284 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey.current = null;
285 const command = resolveShortcutCommand(event, keybindings, {
286 context: {
287 terminalFocus: isTerminalFocused(),
288 previewFocus: isPreviewFocused(),
289 ...routePanelsOpen(routeThreadRef),
290 editableFocus:
291 isEditableFocused(event.target) && !(noticeVisible && threadUndoClaimsShortcut()),
292 modelPickerOpen: isModelPickerOpen(),
293 },
294 });
295 if (command !== "thread.undo") {
296 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
297 return;
298 }
299 if (isCommandPaletteOpen() || isModelPickerOpen()) return;
300 if (undoLatestThreadAction()) {
301 heldUndoKey.current = event.code;
302 event.preventDefault();
303 event.stopPropagation();
304 }
305 };
306 // Pastes from a menu, dictation and drops edit text without a keypress.
307 const onInput = () => releaseThreadUndoShortcut();
308​
309 window.addEventListener("keydown", onKeyDown, true);
310 window.addEventListener("input", onInput, true);
311 return () => {
312 window.removeEventListener("keydown", onKeyDown, true);
313 window.removeEventListener("input", onInput, true);
314 };
315 }, [keybindings, noticeVisible, routeThreadRef]);
316​
317 return null;
319​
320// Settings swaps the thread sidebar out of the tree. Keep the lightweight
321// project projection subscribed so returning to a draft never renders the
322// zero-project state while the environment snapshot reconnects.
323function ProjectProjectionRetention() {
324 useProjects();
325 return null;
327​
328export function AppSidebarLayout({ children }: { children: ReactNode }) {
329 const navigate = useNavigate();
330 const legacySidebarEnabled = useLegacySidebarEnabled();
331 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
332 usePanelAnimationSettings();
333 useThreadVisitedMigration();
334 const pathname = useLocation({ select: (location) => location.pathname });
335 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
336 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
337 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
338 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
339 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
340 // Subscribed rather than read once: the clamp must track live window size,
341 // and a clamped drag ends with an unchanged width, which skips the re-render
342 // that would otherwise refresh a render-time snapshot.
343 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
344 const [brandWidth, setBrandWidth] = useState(0);
345 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
346 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
347 const resetSidebarWidth = () => {
348 try {
349 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
350 } catch (error) {
351 console.error("Could not clear persisted thread sidebar width.", error);
352 }
353 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
354 };
355 const isWindowFullscreen = useSyncExternalStore(
356 subscribeToWindowFullscreen,
357 readWindowFullscreen,
358 );
359 const windowControlsInsetStyle = (
360 isMacosDesktop && !isWindowFullscreen
361 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
362 : {}
363 ) as CSSProperties;
364 const sidebarProviderStyle = {
365 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
366 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
367 ...windowControlsInsetStyle,
368 } as CSSProperties;
369​
370 useEffect(() => {
371 const onMenuAction = window.desktopBridge?.onMenuAction;
372 if (typeof onMenuAction !== "function") {
373 return;
374 }
375​
376 const unsubscribe = onMenuAction((action) => {
377 if (action === "open-settings") {
378 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
379 if (!isSettingsRoute) {
380 void navigate({ to: "/settings" });
381 }
382 }
383 });
384​
385 return () => {
386 unsubscribe?.();
387 };
388 }, [navigate, pathname]);
389​
390 return (
391 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
392 <SidebarProvider
393 className="h-dvh! min-h-0!"
394 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
395 defaultOpen
396 style={sidebarProviderStyle}
397 >
398 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
399 <ProjectProjectionRetention />
400 <Sidebar
401 side="left"
402 collapsible="offcanvas"
403 data-app-sidebar=""
404 role="navigation"
405 aria-label={isOnSettings ? "Settings" : "Threads"}
406 resizable={{
407 maxWidth: sidebarMaximumWidth,
408 minWidth: sidebarMinimumWidth,
409 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
410 nextWidth <= currentWidth ||
411 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
412 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
413 onResize: setSidebarWidth,
414 }}
415 style={windowControlsInsetStyle}
416 >
417 {isOnSettings ? (
418 <>
419 <SidebarChromeHeader isElectron={isElectron} />
420 <SettingsSidebarNav pathname={pathname} />
421 </>
422 ) : legacySidebarEnabled ? (
423 <LegacyThreadSidebar />
424 ) : (
425 <ThreadSidebar />
426 )}
427 <SidebarRail onDoubleClick={resetSidebarWidth} />
428 </Sidebar>
429 {children}
430 <SidebarControl />
431 <NavigationHistoryShortcuts />
432 {isOnSettings ? null : <ThreadUndoShortcut />}
433 <MainAppLocationTracker />
434 </SidebarProvider>
435 </PanelAnimationSuppressionProvider>
436 );