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

AppSidebarLayout.tsx

367 lines13.1 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, useNavigate, useParams } from "@tanstack/react-router";
11​
12import { isElectron } from "../env";
13import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
14import {
15 isRichTextBoldShortcut,
16 resolveShortcutCommand,
17 shortcutLabelForCommand,
18} from "../keybindings";
19import { isEditableFocused } from "../lib/editableFocus";
20import { isPreviewFocused } from "../lib/previewFocus";
21import { isTerminalFocused } from "../lib/terminalFocus";
22import { isModelPickerOpen } from "../modelPickerVisibility";
23import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
24import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
25import { resolveThreadRouteRef } from "../threadRoutes";
26import { cn, isMacPlatform } from "../lib/utils";
27import { primaryServerKeybindingsAtom } from "../state/server";
28import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
29import {
30 PanelAnimationSuppressionProvider,
31 usePanelAnimationSettings,
32 usePanelNavigationSuppression,
33} from "../panelAnimations";
34import LegacyThreadSidebar from "./LegacySidebar";
35import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
36import ThreadSidebar from "./Sidebar";
37import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
38import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
39import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
40import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
41import { useProjects } from "../state/entities";
42import {
43 clampThreadSidebarWidth,
44 resolveInitialThreadSidebarWidth,
45 resolveThreadSidebarMaximumWidth,
46 resolveThreadSidebarMinimumWidth,
47 THREAD_MAIN_CONTENT_MIN_WIDTH,
48 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
49} from "./threadSidebarWidth";
50import {
51 Sidebar,
52 SidebarProvider,
53 SidebarRail,
54 SidebarTrigger,
55 useSidebar,
56 useSidebarVisibility,
57} from "./ui/sidebar";
58import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
59​
60const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
61​
62function subscribeToViewportWidth(onChange: () => void): () => void {
63 window.addEventListener("resize", onChange);
64 return () => window.removeEventListener("resize", onChange);
66​
67function readViewportWidth(): number {
68 return window.innerWidth;
70​
71// getWindowFullscreenState is a synchronous IPC round trip, so the snapshot is cached
72// and only re-read when a subscription starts.
73let windowFullscreenSnapshot: boolean | null = null;
74​
75function macosDesktopBridge() {
76 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
77 return window.desktopBridge ?? null;
79​
80function subscribeToWindowFullscreen(onChange: () => void): () => void {
81 const bridge = macosDesktopBridge();
82 if (
83 typeof bridge?.getWindowFullscreenState !== "function" ||
84 typeof bridge.onWindowFullscreenStateChange !== "function"
85 ) {
86 return () => {};
87 }
88 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
89 windowFullscreenSnapshot = fullscreen;
90 onChange();
91 });
92 // The window may have changed state between the first render and this subscription.
93 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
94 return () => {
95 unsubscribe();
96 windowFullscreenSnapshot = null;
97 };
99​
100function readWindowFullscreen(): boolean {
101 if (windowFullscreenSnapshot === null) {
102 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
103 windowFullscreenSnapshot =
104 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
105 }
106 return windowFullscreenSnapshot;
108​
109function readInitialThreadSidebarWidth(): number {
110 try {
111 return resolveInitialThreadSidebarWidth(
112 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
113 window.innerWidth,
114 );
115 } catch (error) {
116 console.error("Could not read persisted thread sidebar width.", error);
117 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
118 }
120​
121function SidebarControl() {
122 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
123 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
124 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
125 const isSidebarVisible = useSidebarVisibility();
126 const environmentIdentificationMode = useEnvironmentIdentificationMode();
127 const stageBackdropVariant = useSidebarStageBackdropVariant(
128 environmentIdentificationMode === "artwork",
129 );
130 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
131 context: { usagePageOpen },
132 });
133​
134 useEffect(() => {
135 const onKeyDown = (event: KeyboardEvent) => {
136 if (event.defaultPrevented) return;
137 if (
138 event.target instanceof HTMLElement &&
139 event.target.closest("[data-keybinding-capture]")
140 ) {
141 return;
142 }
143 if (
144 isRichTextBoldShortcut(event) &&
145 event.target instanceof HTMLElement &&
146 event.target.closest('[data-composer-rich-text="true"]')
147 ) {
148 // The rich-text composer claims Mod+B for bold; the toggle stays
149 // available everywhere else, including the plain-text composer.
150 return;
151 }
152 if (
153 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
154 "sidebar.toggle"
155 )
156 return;
157​
158 event.preventDefault();
159 event.stopPropagation();
160 toggleSidebar();
161 };
162​
163 window.addEventListener("keydown", onKeyDown, true);
164 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
165 if (action === "sidebar.toggle") toggleSidebar();
166 });
167 return () => {
168 window.removeEventListener("keydown", onKeyDown, true);
169 unsubscribe?.();
170 };
171 }, [keybindings, toggleSidebar, usagePageOpen]);
172​
173 return (
174 <div
175 className={cn(
176 "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",
177 isMobile && mobileSheetMounted && "hidden",
178 )}
179 data-sidebar-control=""
180 >
181 <Tooltip>
182 <TooltipTrigger
183 render={
184 <SidebarTrigger
185 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
186 className={cn(
187 "pointer-events-auto",
188 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
189 )}
190 aria-label="Toggle main sidebar"
191 />
192 }
193 />
194 <TooltipPopup side="bottom">
195 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
196 </TooltipPopup>
197 </Tooltip>
198 </div>
199 );
201​
202function NavigationHistoryShortcuts() {
203 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
204 const routeThreadRef = useParams({
205 strict: false,
206 select: (params) => resolveThreadRouteRef(params),
207 });
208​
209 useEffect(() => {
210 const onKeyDown = (event: KeyboardEvent) => {
211 if (event.defaultPrevented) return;
212 if (
213 event.target instanceof HTMLElement &&
214 event.target.closest("[data-keybinding-capture]")
215 ) {
216 return;
217 }
218 const command = resolveShortcutCommand(event, keybindings, {
219 context: {
220 terminalFocus: isTerminalFocused(),
221 terminalOpen: routeThreadRef
222 ? selectThreadTerminalUiState(
223 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
224 routeThreadRef,
225 ).terminalOpen
226 : false,
227 previewFocus: isPreviewFocused(),
228 previewOpen: routeThreadRef
229 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
230 "preview"
231 : false,
232 editableFocus: isEditableFocused(event.target),
233 modelPickerOpen: isModelPickerOpen(),
234 },
235 });
236 if (command !== "navigation.back" && command !== "navigation.forward") return;
237​
238 event.preventDefault();
239 event.stopPropagation();
240 if (command === "navigation.back") window.history.back();
241 else window.history.forward();
242 };
243​
244 window.addEventListener("keydown", onKeyDown);
245 return () => window.removeEventListener("keydown", onKeyDown);
246 }, [keybindings, routeThreadRef]);
247​
248 return null;
250​
251// Settings swaps the thread sidebar out of the tree. Keep the lightweight
252// project projection subscribed so returning to a draft never renders the
253// zero-project state while the environment snapshot reconnects.
254function ProjectProjectionRetention() {
255 useProjects();
256 return null;
258​
259export function AppSidebarLayout({ children }: { children: ReactNode }) {
260 const navigate = useNavigate();
261 const legacySidebarEnabled = useLegacySidebarEnabled();
262 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
263 usePanelAnimationSettings();
264 useThreadVisitedMigration();
265 const pathname = useLocation({ select: (location) => location.pathname });
266 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
267 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
268 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
269 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
270 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
271 // Subscribed rather than read once: the clamp must track live window size,
272 // and a clamped drag ends with an unchanged width, which skips the re-render
273 // that would otherwise refresh a render-time snapshot.
274 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
275 const [brandWidth, setBrandWidth] = useState(0);
276 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
277 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
278 const resetSidebarWidth = () => {
279 try {
280 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
281 } catch (error) {
282 console.error("Could not clear persisted thread sidebar width.", error);
283 }
284 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
285 };
286 const isWindowFullscreen = useSyncExternalStore(
287 subscribeToWindowFullscreen,
288 readWindowFullscreen,
289 );
290 const windowControlsInsetStyle = (
291 isMacosDesktop && !isWindowFullscreen
292 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
293 : {}
294 ) as CSSProperties;
295 const sidebarProviderStyle = {
296 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
297 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
298 ...windowControlsInsetStyle,
299 } as CSSProperties;
300​
301 useEffect(() => {
302 const onMenuAction = window.desktopBridge?.onMenuAction;
303 if (typeof onMenuAction !== "function") {
304 return;
305 }
306​
307 const unsubscribe = onMenuAction((action) => {
308 if (action === "open-settings") {
309 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
310 if (!isSettingsRoute) {
311 void navigate({ to: "/settings" });
312 }
313 }
314 });
315​
316 return () => {
317 unsubscribe?.();
318 };
319 }, [navigate, pathname]);
320​
321 return (
322 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
323 <SidebarProvider
324 className="h-dvh! min-h-0!"
325 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
326 defaultOpen
327 style={sidebarProviderStyle}
328 >
329 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
330 <ProjectProjectionRetention />
331 <Sidebar
332 side="left"
333 collapsible="offcanvas"
334 data-app-sidebar=""
335 role="navigation"
336 aria-label={isOnSettings ? "Settings" : "Threads"}
337 resizable={{
338 maxWidth: sidebarMaximumWidth,
339 minWidth: sidebarMinimumWidth,
340 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
341 nextWidth <= currentWidth ||
342 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
343 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
344 onResize: setSidebarWidth,
345 }}
346 style={windowControlsInsetStyle}
347 >
348 {isOnSettings ? (
349 <>
350 <SidebarChromeHeader isElectron={isElectron} />
351 <SettingsSidebarNav pathname={pathname} />
352 </>
353 ) : legacySidebarEnabled ? (
354 <LegacyThreadSidebar />
355 ) : (
356 <ThreadSidebar />
357 )}
358 <SidebarRail onDoubleClick={resetSidebarWidth} />
359 </Sidebar>
360 {children}
361 <SidebarControl />
362 <NavigationHistoryShortcuts />
363 <MainAppLocationTracker />
364 </SidebarProvider>
365 </PanelAnimationSuppressionProvider>
366 );